Skip to content

Create professional demos and 3D mockups in seconds, directly in your browser

feat(ui): add VideoClipTrackItem and VideosMenu components for enhanced video editing experience feat(lib): implement video library functions for managing uploaded videos and metadata feat(types): define VideoTrackClip interface and related utility functions for clip management

CristianOlivera1dc75fcd9ee14
diff --git a/app/components/ui/editor/VideoClipTrackItem.tsx b/app/components/ui/editor/VideoClipTrackItem.tsx
new file mode 100644
index 0000000..332f938
--- /dev/null
+++ b/app/components/ui/editor/VideoClipTrackItem.tsx
@@ -0,0 +1,312 @@
+"use client";
+
+import { useState, useRef, useCallback, useMemo, useEffect } from "react";
+import { motion, useMotionValue, useTransform } from "framer-motion";
+import type { VideoTrackClip } from "@/types/video-track.types";
+import { Icon } from "@iconify/react";
+import type { MotionValue } from "framer-motion";
+
+const MIN_CLIP_DURATION = 0.1;
+
+interface VideoClipTrackItemProps {
+ clip: VideoTrackClip;
+ isSelected: boolean;
+ contentWidth: number;
+ totalDuration: number;
+ otherClips: VideoTrackClip[];
+ currentTime?: number;
+ onSelect: () => void;
+ onUpdate: (updates: Partial<VideoTrackClip>) => void;
+ onDelete?: () => void;
+ onDragStateChange?: (isDragging: boolean) => void;
+ zoomLevel: number;
+ playheadX: MotionValue<number>;
+}
+
+export function VideoClipTrackItem({
+ clip,
+ isSelected,
+ contentWidth,
+ totalDuration,
+ otherClips,
+ currentTime = 0,
+ onSelect,
+ onUpdate,
+ onDelete,
+ onDragStateChange,
+ zoomLevel,
+ playheadX,
+}: VideoClipTrackItemProps) {
+ const [isDragging, setIsDragging] = useState(false);
+ const [isResizing, setIsResizing] = useState<'start' | 'end' | null>(null);
+ const [isHovered, setIsHovered] = useState(false);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ const clipX = useMotionValue(0);
+ const clipWidth = useMotionValue(0);
+
+ const timeToPixels = useCallback((time: number) => {
+ if (totalDuration === 0) return 0;
+ return (time / totalDuration) * contentWidth;
+ }, [totalDuration, contentWidth]);
+
+ const clipDuration = clip.trimEnd - clip.trimStart;
+
+ const pixelsToTime = useCallback((pixels: number) => {
+ if (contentWidth === 0) return 0;
+ return (pixels / contentWidth) * totalDuration;
+ }, [contentWidth, totalDuration]);
+
+ const initialLeft = timeToPixels(clip.startTime);
+ const initialWidth = timeToPixels(clipDuration);
+
+ const clipEndTime = clip.startTime + clipDuration;
+
+ // Calculate progress within this clip (0 to clipWidth)
+ const progressWidth = useTransform(
+ playheadX,
+ (px) => {
+ const clipStartPx = timeToPixels(clip.startTime);
+ const clipEndPx = timeToPixels(clip.startTime + clipDuration);
+ if (px <= clipStartPx) return 0;
+ if (px >= clipEndPx) return timeToPixels(clipDuration);
+ return px - clipStartPx;
+ }
+ );
+
+ useEffect(() => {
+ if (!isDragging && !isResizing) {
+ clipX.set(initialLeft);
+ clipWidth.set(initialWidth);
+ }
+ }, [initialLeft, initialWidth, isDragging, isResizing, clipX, clipWidth]);
+
+ // Calculate boundaries based on other clips
+ const boundaries = useMemo(() => {
+ const sorted = [...otherClips]
+ .filter(c => c.id !== clip.id)
+ .sort((a, b) => a.startTime - b.startTime);
+
+ let minStart = 0;
+ // Don't limit maxEnd by totalDuration - allow clip to expand up to its full duration
+ // The actual limit will be the next clip's start time OR unlimited (for the last clip)
+ let maxEnd = Infinity;
+
+ for (const other of sorted) {
+ const otherEnd = other.startTime + (other.trimEnd - other.trimStart);
+ const clipEnd = clip.startTime + clipDuration;
+
+ if (otherEnd <= clip.startTime) {
+ minStart = Math.max(minStart, otherEnd);
+ }
+ if (other.startTime >= clipEnd) {
+ maxEnd = Math.min(maxEnd, other.startTime);
+ break;
+ }
+ }
+
+ return { minStart, maxEnd };
+ }, [otherClips, clip.id, clip.startTime, clipDuration]);
+
+ // Drag handler
+ const handleDrag = useCallback((_e: MouseEvent | TouchEvent | PointerEvent, info: { delta: { x: number } }) => {
+ if (contentWidth === 0 || totalDuration === 0) return;
+
+ const currentX = clipX.get();
+ let newX = currentX + info.delta.x;
+
+ const minX = timeToPixels(boundaries.minStart);
+ const maxX = timeToPixels(boundaries.maxEnd - clipDuration);
+ newX = Math.max(minX, Math.min(maxX, newX));
+
+ clipX.set(newX);
+ }, [contentWidth, totalDuration, clipX, clipDuration, boundaries, timeToPixels]);
+
+ const handleDragStart = useCallback(() => {
+ setIsDragging(true);
+ onDragStateChange?.(true);
+ }, [onDragStateChange]);
+
+ const handleDragEnd = useCallback(() => {
+ setIsDragging(false);
+ onDragStateChange?.(false);
+
+ const newStartTime = pixelsToTime(clipX.get());
+ onUpdate({
+ startTime: Math.max(0, newStartTime),
+ });
+ }, [clipX, pixelsToTime, onUpdate, onDragStateChange]);
+
+ // Resize handlers
+ const handleResizeStartDrag = useCallback((_e: MouseEvent | TouchEvent | PointerEvent, info: { delta: { x: number } }) => {
+ if (contentWidth === 0 || totalDuration === 0) return;
+
+ const currentX = clipX.get();
+ const currentWidth = clipWidth.get();
+
+ let newX = currentX + info.delta.x;
+ let newWidth = currentWidth - info.delta.x;
+
+ const minWidth = timeToPixels(MIN_CLIP_DURATION);
+ if (newWidth < minWidth) {
+ newWidth = minWidth;
+ newX = currentX + currentWidth - minWidth;
+ }
+
+ const minX = timeToPixels(boundaries.minStart);
+ if (newX < minX) {
+ newWidth = newWidth - (minX - newX);
+ newX = minX;
+ }
+
+ clipX.set(newX);
+ clipWidth.set(newWidth);
+ }, [contentWidth, totalDuration, clipX, clipWidth, boundaries, timeToPixels]);
+
+ const handleResizeEndDrag = useCallback((_e: MouseEvent | TouchEvent | PointerEvent, info: { delta: { x: number } }) => {
+ if (contentWidth === 0 || totalDuration === 0) return;
+
+ const currentX = clipX.get();
+ const currentWidth = clipWidth.get();
+ let newWidth = currentWidth + info.delta.x;
+
+ const minWidth = timeToPixels(MIN_CLIP_DURATION);
+ newWidth = Math.max(minWidth, newWidth);
+
+ // Limit by boundary with other clips (if there's a next clip)
+ if (Number.isFinite(boundaries.maxEnd)) {
+ const maxWidthByBoundary = timeToPixels(boundaries.maxEnd) - currentX;
+ newWidth = Math.min(newWidth, maxWidthByBoundary);
+ }
+
+ const maxAvailableDuration = clip.duration - clip.trimStart;
+ const maxWidthBySource = timeToPixels(maxAvailableDuration);
+ newWidth = Math.min(newWidth, maxWidthBySource);
+
+ clipWidth.set(newWidth);
+ }, [contentWidth, totalDuration, clipWidth, clipX, boundaries, timeToPixels, clip.duration, clip.trimStart]);
+
+ const handleResizeStart = useCallback((handle: 'start' | 'end') => {
+ setIsResizing(handle);
+ onDragStateChange?.(true);
+ }, [onDragStateChange]);
+
+ const handleResizeEnd = useCallback(() => {
+ setIsResizing(null);
+ onDragStateChange?.(false);
+
+ const newStartTime = pixelsToTime(clipX.get());
+ const newDuration = pixelsToTime(clipWidth.get());
+
+ // Calculate new trim values
+ const trimDelta = newStartTime - clip.startTime;
+ const newTrimStart = Math.max(0, clip.trimStart + trimDelta);
+ const newTrimEnd = Math.min(clip.duration, newTrimStart + newDuration);
+
+ onUpdate({
+ startTime: Math.max(0, newStartTime),
+ trimStart: newTrimStart,
+ trimEnd: newTrimEnd,
+ });
+ }, [clipX, clipWidth, pixelsToTime, clip, onUpdate, onDragStateChange]);
+
+ const isInteracting = isDragging || isResizing !== null;
+
+ // Format duration for display
+ const formatDuration = (seconds: number): string => {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ return mins > 0 ? `${mins}:${secs.toString().padStart(2, '0')}` : `${secs}s`;
+ };
+
+ return (
+ <motion.div
+ ref={containerRef}
+ className={`absolute top-0 bottom-0 rounded-md cursor-grab active:cursor-grabbing overflow-hidden group ${isSelected
+ ? 'ring-[1.5px] ring-[#4ade80] shadow-[0_0_12px_rgba(74,222,128,0.3)] z-10'
+ : ''
+ } ${isInteracting ? 'z-10' : 'z-0'}`}
+ style={{
+ x: clipX,
+ width: clipWidth,
+ border: '1px solid rgba(52, 168, 83, 0.4)',
+ background: '#182e20',
+ }}
+ drag="x"
+ dragConstraints={{ left: 0, right: contentWidth }}
+ dragElastic={0}
+ dragMomentum={false}
+ onDrag={handleDrag}
+ onDragStart={handleDragStart}
+ onDragEnd={handleDragEnd}
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelect();
+ }}
+ onMouseEnter={() => setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ >
+ <div className="absolute inset-0 flex items-center overflow-hidden">
+ <div className="flex h-full w-full">
+ {Array.from({ length: Math.max(1, Math.ceil(zoomLevel * 3)) }).map((_, i) => (
+ <div
+ key={i}
+ className="h-full flex-1 border-r border-[#34A853]/10 last:border-r-0"
+ style={{
+ background: 'linear-gradient(to top, rgba(0, 0, 0, 0) 0%, rgba(20, 80, 40, 0.1) 50%, rgba(52, 168, 83, 0.1) 100%)',
+ boxShadow: 'inset 0px 1px 0px rgba(255, 255, 255, 0.05)'
+ }}
+ />
+ ))}
+ </div>
+ </div>
+
+ <motion.div
+ className="absolute top-0 bottom-0 left-0 border-r-2 border-[#4ade80] pointer-events-none z-5"
+ style={{
+ width: progressWidth,
+ background: `linear-gradient(to bottom, rgba(52, 168, 83, 0.9) 0%, rgba(34, 139, 34, 1) 50%, rgba(20, 80, 40, 1) 100%)`,
+ boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.2)'
+ }}
+ />
+
+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none z-10">
+ <span className="flex items-center gap-2 text-emerald-400 text-[11px] font-medium drop-shadow-sm">
+ <Icon icon="solar:videocamera-record-bold" width="12" className="opacity-70" />
+ <span className="truncate max-w-30">{clip.name}</span>
+ <span className="text-emerald-400/60 font-mono text-[10px]">
+ {formatDuration(clipDuration)}
+ </span>
+ </span>
+ </div>
+
+ <motion.div
+ className="absolute left-0 top-0 bottom-0 w-3 cursor-ew-resize z-20 group/trim flex items-center justify-center"
+ drag="x"
+ dragConstraints={{ left: 0, right: 0 }}
+ dragElastic={0}
+ dragMomentum={false}
+ onDrag={handleResizeStartDrag}
+ onDragStart={() => handleResizeStart('start')}
+ onDragEnd={handleResizeEnd}
+ >
+ <div className={`w-1.5 h-8 rounded-full transition-all ${isResizing === 'start' ? 'bg-[#4ade80] scale-110' : 'bg-[#34A853] group-hover/trim:bg-[#4ade80]'
+ }`} />
+ </motion.div>
+
+ <motion.div
+ className="absolute right-0 top-0 bottom-0 w-3 cursor-ew-resize z-20 group/trim flex items-center justify-end"
+ drag="x"
+ dragConstraints={{ left: 0, right: 0 }}
+ dragElastic={0}
+ dragMomentum={false}
+ onDrag={handleResizeEndDrag}
+ onDragStart={() => handleResizeStart('end')}
+ onDragEnd={handleResizeEnd}
+ >
+ <div className={`w-1.5 h-8 rounded-full transition-all ${isResizing === 'end' ? 'bg-[#4ade80] scale-110' : 'bg-[#34A853] group-hover/trim:bg-[#4ade80]'
+ }`} />
+ </motion.div>
+ </motion.div>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/VideosMenu.tsx b/app/components/ui/editor/VideosMenu.tsx
new file mode 100644
index 0000000..c9d3f0e
--- /dev/null
+++ b/app/components/ui/editor/VideosMenu.tsx
@@ -0,0 +1,355 @@
+"use client";
+
+import { Icon } from "@iconify/react";
+import { useEffect, useState, useCallback, useRef } from "react";
+import { motion, AnimatePresence } from "framer-motion";
+import { Button } from "@/components/ui/button";
+import { TooltipAction } from "@/components/ui/tooltip-action";
+import {
+ type LibraryVideoInfo,
+ getLibraryVideoInfoList,
+ deleteLibraryVideo,
+ getLibraryVideo,
+ updateVideoAudioState,
+ formatFileSize,
+ formatVideoDuration,
+} from "@/lib/videos-library";
+
+interface VideosMenuProps {
+ onAddToTrack?: (videoId: string, blob: Blob, duration: number) => void;
+ onRemoveFromTrack?: (videoId: string) => void;
+ onVideoUpload?: (file: File) => void;
+ onVideoDeleteFromTrack?: (videoId: string) => void;
+ videosInTrackIds?: string[];
+ refreshTrigger?: number;
+ isUploading?: boolean;
+ onVideoAudioToggle?: (videoId: string, hasAudio: boolean) => void;
+}
+
+export function VideosMenu({
+ onAddToTrack,
+ onRemoveFromTrack,
+ onVideoUpload,
+ onVideoDeleteFromTrack,
+ videosInTrackIds = [],
+ refreshTrigger,
+ isUploading = false,
+ onVideoAudioToggle
+}: VideosMenuProps) {
+ const [videos, setVideos] = useState<LibraryVideoInfo[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [deletingId, setDeletingId] = useState<string | null>(null);
+ const [addingId, setAddingId] = useState<string | null>(null);
+ const [isDragging, setIsDragging] = useState(false);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const loadVideos = useCallback(async () => {
+ try {
+ const videoList = await getLibraryVideoInfoList();
+ setVideos(videoList);
+ } catch (error) {
+ console.error("Error loading videos:", error);
+ } finally {
+ setIsLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ loadVideos();
+ }, [loadVideos, refreshTrigger]);
+
+ const handleDelete = async (id: string) => {
+ if (deletingId) return;
+ setDeletingId(id);
+
+ try {
+ await deleteLibraryVideo(id);
+ setVideos((prev) => prev.filter((v) => v.id !== id));
+ onVideoDeleteFromTrack?.(id);
+ } catch (error) {
+ console.error("Error deleting video:", error);
+ } finally {
+ setDeletingId(null);
+ }
+ };
+
+ const handleAddToTrack = async (id: string) => {
+ if (addingId || !onAddToTrack) return;
+ setAddingId(id);
+
+ try {
+ const video = await getLibraryVideo(id);
+ if (video) {
+ onAddToTrack(video.id, video.blob, video.duration);
+ }
+ } catch (error) {
+ console.error("Error adding video to track:", error);
+ } finally {
+ setAddingId(null);
+ }
+ };
+
+ const handleToggleAudio = async (id: string, currentHasAudio: boolean | undefined) => {
+ try {
+ const newHasAudio = !(currentHasAudio ?? true);
+ await updateVideoAudioState(id, newHasAudio);
+ setVideos(prev => prev.map(v => v.id === id ? { ...v, hasAudio: newHasAudio } : v));
+ onVideoAudioToggle?.(id, newHasAudio);
+ } catch (error) {
+ console.error("Error toggling audio state:", error);
+ }
+ };
+
+ const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (file && onVideoUpload) {
+ onVideoUpload(file);
+ }
+ if (fileInputRef.current) {
+ fileInputRef.current.value = "";
+ }
+ }, [onVideoUpload]);
+
+ const triggerFileUpload = () => {
+ fileInputRef.current?.click();
+ };
+
+ const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (!isUploading) setIsDragging(true);
+ };
+
+ const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragging(false);
+ };
+
+ const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ };
+
+ const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragging(false);
+
+ if (isUploading) return;
+
+ const file = e.dataTransfer.files?.[0];
+ if (file && file.type.startsWith("video/") && onVideoUpload) {
+ onVideoUpload(file);
+ }
+ };
+
+ return (
+ <div
+ className="p-4 flex flex-col gap-5 h-full relative"
+ onDragEnter={handleDragEnter}
+ onDragOver={handleDragOver}
+ onDrop={handleDrop}
+ >
+ <AnimatePresence>
+ {isDragging && (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-[#09090B]/90 backdrop-blur-sm border-2 border-blue-500 border-dashed rounded-xl m-2"
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ >
+ <div className="w-14 h-14 rounded-full bg-blue-500/20 border flex items-center justify-center border-blue-500/50 text-blue-400 mb-4 scale-110">
+ <Icon icon="solar:upload-minimalistic-bold" className="text-2xl" />
+ </div>
+ <p className="text-blue-400 font-medium text-sm">¡Suelta tu video aquí!</p>
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="video/*"
+ onChange={handleFileSelect}
+ className="hidden"
+ />
+
+ <div className="flex items-center gap-2 text-white font-medium">
+ <Icon icon="solar:video-library-outline" width="20" />
+ <span>Videos</span>
+ </div>
+
+ <div className="flex-1 overflow-y-auto custom-scrollbar -mx-1 px-1">
+ {isLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <Icon icon="svg-spinners:ring-resize" width="24" className="text-white/40" />
+ </div>
+ ) : videos.length === 0 ? (
+ <div
+ onClick={triggerFileUpload}
+ className="group bg-[#09090B] border border-dashed border-white/10 hover:border-white/30 hover:bg-white/3 squircle-element p-8 text-center cursor-pointer transition-colors"
+ >
+ <div className="w-12 h-12 rounded-full bg-white/5 border border-white/10 flex items-center justify-center mx-auto mb-4 group-hover:scale-105 transition-transform">
+ <Icon icon="solar:upload-minimalistic-outline" width="24" className="text-white/40 group-hover:text-white/70 transition-colors" />
+ </div>
+ <p className="text-sm font-medium text-white/70 mb-1">Subir video</p>
+ <p className="text-xs text-white/40 mb-5">Haz clic o arrastra un archivo aquí</p>
+
+ <Button
+ disabled={isUploading}
+ variant="outline"
+ className="w-full text-xs"
+ >
+ {isUploading ? (
+ <>
+ <Icon icon="svg-spinners:ring-resize" width="16" />
+ <span>Subiendo...</span>
+ </>
+ ) : (
+ <span>Seleccionar archivo</span>
+ )}
+ </Button>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ <Button
+ onClick={triggerFileUpload}
+ disabled={isUploading}
+ variant="outline"
+ className="w-full text-xs mb-4 group"
+ >
+ {isUploading ? (
+ <>
+ <Icon icon="svg-spinners:ring-resize" width="16" />
+ <span className="text-sm">Subiendo...</span>
+ </>
+ ) : (
+ <>
+ <Icon icon="solar:upload-minimalistic-outline" width="16" className="group-hover:-translate-y-0.5 transition-transform" />
+ <span className="text-sm">Subir video</span>
+ </>
+ )}
+ </Button>
+
+ <AnimatePresence mode="popLayout">
+ {videos.map((video) => (
+ <motion.div
+ key={video.id}
+ layout
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, x: -20, scale: 0.95 }}
+ className={`group bg-[#09090B] border squircle-element overflow-hidden transition-colors ${videosInTrackIds.includes(video.id)
+ ? "border-blue-500/50 bg-blue-500/5"
+ : "border-white/5 hover:border-white/10"
+ }`}
+ >
+ <div className="flex gap-3 p-2.5 items-center">
+ <div
+ className="relative w-20 h-12 rounded-md overflow-hidden bg-black/50 shrink-0 cursor-pointer"
+ onClick={() => {
+ if (!addingId) {
+ videosInTrackIds.includes(video.id) ? onRemoveFromTrack?.(video.id) : handleAddToTrack(video.id);
+ }
+ }}
+ >
+ {video.thumbnailUrl ? (
+ <img src={video.thumbnailUrl} alt={video.fileName} className="w-full h-full object-cover" />
+ ) : (
+ <div className="w-full h-full flex items-center justify-center">
+ <Icon icon="solar:play-bold" width="20" className="text-white/30" />
+ </div>
+ )}
+
+ <div className="absolute bottom-0.5 right-0.5 px-1 py-0.5 bg-black/70 rounded text-[9px] font-mono text-white/80">
+ {formatVideoDuration(video.duration)}
+ </div>
+
+ <div className={`absolute inset-0 flex items-center justify-center transition-all ${videosInTrackIds.includes(video.id)
+ ? "bg-blue-500/10 opacity-100"
+ : "bg-black/60 opacity-0 group-hover:opacity-100"
+ }`}>
+ {addingId === video.id ? (
+ <Icon icon="svg-spinners:ring-resize" width="20" className="text-white" />
+ ) : videosInTrackIds.includes(video.id) ? (
+ <Icon icon="solar:check-circle-bold" width="20" className="text-blue-400" />
+ ) : (
+ <div className="absolute inset-0 flex items-center justify-center">
+ <div className={`
+ flex items-center gap-0.5 px-2 py-1
+ bg-white/10 backdrop-blur-md border border-white/20 rounded-full
+ shadow-2xl transition-all duration-300
+ group-hover:bg-white/20 group-hover:scale-105
+ `}>
+ <Icon
+ icon="material-symbols:add-rounded"
+ width="16"
+ className="text-white drop-shadow-md"
+ />
+ <span className="text-[9px] font-bold text-white tracking-wider">
+ Añadir
+ </span>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <div className="flex-1 min-w-0 flex flex-col justify-center">
+ <p className="text-xs text-white/80 truncate" title={video.fileName}>
+ {video.fileName}
+ </p>
+ <div className="flex items-center gap-2 mt-0.5">
+ <span className="text-[10px] text-white/40">{formatFileSize(video.fileSize)}</span>
+ <span className="text-[10px] text-white/30">•</span>
+ <span className="text-[10px] text-white/40">{video.width}×{video.height}</span>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
+ <TooltipAction label={video.hasAudio === false ? "Activar audio" : "Silenciar"}>
+ <button
+ onClick={() => handleToggleAudio(video.id, video.hasAudio)}
+ disabled={video.originalHasAudio === false}
+ className={`p-1.5 rounded-md transition-colors ${video.originalHasAudio === false
+ ? "text-white/10 cursor-not-allowed"
+ : video.hasAudio === false
+ ? "text-red-400 bg-red-500/10"
+ : "text-white/40 hover:text-white hover:bg-white/5"
+ }`}
+ >
+ <Icon icon={video.hasAudio === false ? "solar:volume-cross-outline" : "solar:volume-loud-outline"} width="16" />
+ </button>
+ </TooltipAction>
+
+ <TooltipAction label="Eliminar video">
+ <button
+ onClick={() => handleDelete(video.id)}
+ disabled={deletingId === video.id}
+ className="p-1.5 rounded-md text-white/40 hover:text-red-400 hover:bg-red-500/10 transition-colors disabled:opacity-50"
+ >
+ {deletingId === video.id ? (
+ <Icon icon="svg-spinners:ring-resize" width="16" />
+ ) : (
+ <Icon icon="solar:trash-bin-trash-outline" width="16" />
+ )}
+ </button>
+ </TooltipAction>
+ </div>
+ </div>
+ </motion.div>
+ ))}
+ </AnimatePresence>
+ </div>
+ )}
+ </div>
+
+ <div className="text-[10px] text-white/25 text-center pt-2 border-t border-white/5 shrink-0">
+ Los videos se almacenan localmente en tu navegador
+ </div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/lib/videos-library.ts b/lib/videos-library.ts
new file mode 100644
index 0000000..524f49a
--- /dev/null
+++ b/lib/videos-library.ts
@@ -0,0 +1,410 @@
+const DB_NAME = "openvid-videos-library";
+const DB_VERSION = 3;
+const STORE_NAME = "uploaded-videos";
+
+export interface LibraryVideo {
+ id: string;
+ blob: Blob;
+ fileName: string;
+ fileSize: number;
+ duration: number;
+ width: number;
+ height: number;
+ aspectRatio: string;
+ uploadedAt: number;
+ thumbnailUrl?: string;
+ hasAudio?: boolean;
+ originalHasAudio?: boolean;
+}
+
+export interface LibraryVideoInfo {
+ id: string;
+ fileName: string;
+ fileSize: number;
+ duration: number;
+ width: number;
+ height: number;
+ aspectRatio: string;
+ uploadedAt: number;
+ thumbnailUrl?: string;
+ hasAudio?: boolean;
+ originalHasAudio?: boolean;
+}
+
+interface ExtendedVideoElement extends HTMLVideoElement {
+ audioTracks?: { length: number };
+ mozHasAudio?: boolean;
+}
+
+let dbInstance: IDBDatabase | null = null;
+
+function generateVideoId(): string {
+ return `uploaded_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
+}
+
+async function openDB(): Promise<IDBDatabase> {
+ if (dbInstance) return dbInstance;
+
+ return new Promise((resolve, reject) => {
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => {
+ dbInstance = request.result;
+ resolve(request.result);
+ };
+
+ request.onupgradeneeded = (event) => {
+ const db = (event.target as IDBOpenDBRequest).result;
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
+ const store = db.createObjectStore(STORE_NAME, { keyPath: "id" });
+ store.createIndex("uploadedAt", "uploadedAt", { unique: false });
+ }
+ };
+ });
+}
+
+export async function findExistingVideo(fileName: string, fileSize: number): Promise<LibraryVideo | null> {
+ const db = await openDB();
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readonly");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.openCursor();
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = (event) => {
+ const cursor = (event.target as IDBRequest<IDBCursorWithValue>).result;
+ if (cursor) {
+ const video = cursor.value as LibraryVideo;
+ if (video.fileName === fileName && video.fileSize === fileSize) {
+ resolve(video);
+ return;
+ }
+ cursor.continue();
+ } else {
+ resolve(null);
+ }
+ };
+ });
+}
+
+async function getVideoMetadata(file: File): Promise<{
+ duration: number;
+ width: number;
+ height: number;
+ aspectRatio: string;
+}> {
+ return new Promise((resolve, reject) => {
+ const video = document.createElement("video");
+ video.preload = "metadata";
+
+ video.onloadedmetadata = () => {
+ const metadata = {
+ duration: video.duration,
+ width: video.videoWidth,
+ height: video.videoHeight,
+ aspectRatio: "auto",
+ };
+ URL.revokeObjectURL(video.src);
+ resolve(metadata);
+ };
+
+ video.onerror = () => {
+ URL.revokeObjectURL(video.src);
+ reject(new Error("Failed to load video metadata"));
+ };
+
+ video.src = URL.createObjectURL(file);
+ });
+}
+
+async function detectVideoHasAudio(blob: Blob): Promise<boolean> {
+ return new Promise((resolve) => {
+ const video = document.createElement("video");
+ video.preload = "metadata";
+
+ video.onloadedmetadata = () => {
+ let hasAudio = false;
+
+ const extVideo = video as ExtendedVideoElement;
+
+ if (extVideo.audioTracks !== undefined && extVideo.audioTracks.length > 0) {
+ hasAudio = true;
+ }
+ else if (extVideo.mozHasAudio !== undefined) {
+ hasAudio = extVideo.mozHasAudio;
+ }
+ else {
+ hasAudio = true;
+ }
+
+ URL.revokeObjectURL(video.src);
+ resolve(hasAudio);
+ };
+
+ video.onerror = () => {
+ URL.revokeObjectURL(video.src);
+ resolve(true);
+ };
+
+ video.src = URL.createObjectURL(blob);
+ });
+}
+
+async function generateThumbnail(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const video = document.createElement("video");
+ video.preload = "metadata";
+ video.muted = true;
+
+ video.onloadeddata = () => {
+ const seekTime = video.duration * 0.1;
+ if (!isFinite(seekTime) || seekTime < 0) {
+ video.currentTime = 0;
+ } else {
+ video.currentTime = seekTime;
+ }
+ };
+
+ video.onseeked = () => {
+ const canvas = document.createElement("canvas");
+ const aspectRatio = video.videoWidth / video.videoHeight;
+ canvas.width = 160;
+ canvas.height = Math.round(160 / aspectRatio);
+
+ const ctx = canvas.getContext("2d");
+ if (ctx) {
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
+ const thumbnailUrl = canvas.toDataURL("image/jpeg", 0.7);
+ URL.revokeObjectURL(video.src);
+ resolve(thumbnailUrl);
+ } else {
+ URL.revokeObjectURL(video.src);
+ reject(new Error("Failed to get canvas context"));
+ }
+ };
+
+ video.onerror = () => {
+ URL.revokeObjectURL(video.src);
+ reject(new Error("Failed to load video for thumbnail"));
+ };
+
+ video.src = URL.createObjectURL(blob);
+ });
+}
+
+export async function addVideoToLibrary(file: File): Promise<LibraryVideo> {
+ const db = await openDB();
+ const metadata = await getVideoMetadata(file);
+
+ let thumbnailUrl: string | undefined;
+ try {
+ thumbnailUrl = await generateThumbnail(file);
+ } catch (e) {
+ console.warn("Failed to generate thumbnail:", e);
+ }
+
+ let hasAudio = true;
+ try {
+ hasAudio = await detectVideoHasAudio(file);
+ } catch (e) {
+ console.warn("Failed to detect audio:", e);
+ }
+
+ const video: LibraryVideo = {
+ id: generateVideoId(),
+ blob: file,
+ fileName: file.name,
+ fileSize: file.size,
+ duration: metadata.duration,
+ width: metadata.width,
+ height: metadata.height,
+ aspectRatio: metadata.aspectRatio,
+ uploadedAt: Date.now(),
+ thumbnailUrl,
+ hasAudio,
+ originalHasAudio: hasAudio,
+ };
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.add(video);
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve(video);
+ });
+}
+
+export interface AddVideoWithMetadataOptions {
+ blob: Blob;
+ fileName: string;
+ duration: number;
+ width: number;
+ height: number;
+ hasAudio?: boolean;
+}
+
+export async function addVideoToLibraryWithMetadata(options: AddVideoWithMetadataOptions): Promise<LibraryVideo> {
+ const db = await openDB();
+
+ let thumbnailUrl: string | undefined;
+ try {
+ thumbnailUrl = await generateThumbnail(options.blob);
+ } catch (e) {
+ console.warn("Failed to generate thumbnail:", e);
+ }
+
+ let hasAudio = options.hasAudio;
+ if (hasAudio === undefined) {
+ try {
+ hasAudio = await detectVideoHasAudio(options.blob);
+ } catch (e) {
+ console.warn("Failed to detect audio:", e);
+ hasAudio = true;
+ }
+ }
+
+ const video: LibraryVideo = {
+ id: generateVideoId(),
+ blob: options.blob,
+ fileName: options.fileName,
+ fileSize: options.blob.size,
+ duration: options.duration,
+ width: options.width,
+ height: options.height,
+ aspectRatio: "auto",
+ uploadedAt: Date.now(),
+ thumbnailUrl,
+ hasAudio,
+ originalHasAudio: hasAudio,
+ };
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.add(video);
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve(video);
+ });
+}
+
+export async function getAllLibraryVideos(): Promise<LibraryVideo[]> {
+ const db = await openDB();
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readonly");
+ const store = transaction.objectStore(STORE_NAME);
+ const index = store.index("uploadedAt");
+ const request = index.openCursor(null, "prev");
+
+ const videos: LibraryVideo[] = [];
+
+ request.onsuccess = (event) => {
+ const cursor = (event.target as IDBRequest<IDBCursorWithValue>).result;
+ if (cursor) {
+ videos.push(cursor.value);
+ cursor.continue();
+ } else {
+ resolve(videos);
+ }
+ };
+
+ request.onerror = () => reject(request.error);
+ });
+}
+
+export async function getLibraryVideoInfoList(): Promise<LibraryVideoInfo[]> {
+ const videos = await getAllLibraryVideos();
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ return videos.map(({ blob: _blob, ...info }) => info);
+}
+
+export async function getLibraryVideo(id: string): Promise<LibraryVideo | null> {
+ const db = await openDB();
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readonly");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.get(id);
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve(request.result || null);
+ });
+}
+
+export async function deleteLibraryVideo(id: string): Promise<void> {
+ const db = await openDB();
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.delete(id);
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve();
+ });
+}
+
+export async function updateVideoAudioState(id: string, hasAudio: boolean): Promise<void> {
+ const db = await openDB();
+ const video = await getLibraryVideo(id);
+
+ if (!video) {
+ throw new Error(`Video with id ${id} not found`);
+ }
+
+ const updatedVideo: LibraryVideo = {
+ ...video,
+ hasAudio,
+ };
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.put(updatedVideo);
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve();
+ });
+}
+
+export async function clearLibrary(): Promise<void> {
+ const db = await openDB();
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.clear();
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve();
+ });
+}
+
+export async function getLibraryVideoCount(): Promise<number> {
+ const db = await openDB();
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readonly");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.count();
+
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve(request.result);
+ });
+}
+
+export function formatFileSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+export function formatVideoDuration(seconds: number): string {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
+}
diff --git a/types/video-track.types.ts b/types/video-track.types.ts
new file mode 100644
index 0000000..6f52eb0
--- /dev/null
+++ b/types/video-track.types.ts
@@ -0,0 +1,54 @@
+export interface VideoTrackClip {
+ id: string;
+ libraryVideoId: string;
+ name: string;
+ startTime: number;
+ duration: number;
+ trimStart: number;
+ trimEnd: number;
+ thumbnailUrl?: string;
+}
+
+export function calculateTotalDuration(clips: VideoTrackClip[]): number {
+ if (clips.length === 0) return 0;
+ const sorted = [...clips].sort((a, b) => a.startTime - b.startTime);
+ const lastClip = sorted[sorted.length - 1];
+ return lastClip.startTime + (lastClip.trimEnd - lastClip.trimStart);
+}
+
+export function findNextClipPosition(clips: VideoTrackClip[]): number {
+ if (clips.length === 0) return 0;
+ const sorted = [...clips].sort((a, b) => a.startTime - b.startTime);
+ const lastClip = sorted[sorted.length - 1];
+ return lastClip.startTime + (lastClip.trimEnd - lastClip.trimStart);
+}
+
+export function doClipsOverlap(clip1: VideoTrackClip, clip2: VideoTrackClip): boolean {
+ const clip1End = clip1.startTime + (clip1.trimEnd - clip1.trimStart);
+ const clip2End = clip2.startTime + (clip2.trimEnd - clip2.trimStart);
+ return clip1.startTime < clip2End && clip2.startTime < clip1End;
+}
+
+export function getClipAtTime(clips: VideoTrackClip[], time: number): VideoTrackClip | null {
+ return clips.find(clip => {
+ const clipEnd = clip.startTime + (clip.trimEnd - clip.trimStart);
+ return time >= clip.startTime && time < clipEnd;
+ }) || null;
+}
+
+export function getActiveClipAtTime(
+ clips: VideoTrackClip[],
+ time: number
+): { clip: VideoTrackClip; localTime: number } | null {
+ const clip = getClipAtTime(clips, time);
+ if (!clip) return null;
+
+ const timeInClip = time - clip.startTime;
+ const localTime = clip.trimStart + timeInClip;
+
+ return { clip, localTime };
+}
+
+export function sortClipsByTime(clips: VideoTrackClip[]): VideoTrackClip[] {
+ return [...clips].sort((a, b) => a.startTime - b.startTime);
+}
diff --git a/types/video.types.ts b/types/video.types.ts
index 2f70fe7..cf59ba0 100644
--- a/types/video.types.ts
+++ b/types/video.types.ts
@@ -1,3 +1,5 @@
+import type { VideoTrackClip } from "./video-track.types";
+
export type ExportQuality = "4k" | "2k" | "1080p" | "720p" | "480p" | "gif" | "webm-alpha";
export interface TrimSettings {
@@ -22,6 +24,10 @@ export interface ExportSettings {
}>;
masterVolume?: number;
videoBlob?: Blob;
+ // Multi-video clips (for concatenated videos)
+ videoClips?: VideoTrackClip[];
+ // Video blobs map for multi-clip export (libraryVideoId -> Blob)
+ videoClipBlobs?: Map<string, Blob>;
}
export interface ExportProgress {