Skip to content

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

Refactor: Remove legacy donation and legal pages, introduce new layout structure

CristianOlivera103251ced261d
diff --git a/app/(auth)/login/page.tsx b/app/(auth)/login/page.tsx
deleted file mode 100644
index d6e4d59..0000000
--- a/app/(auth)/login/page.tsx
+++ /dev/null
@@ -1,186 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { createClient } from "@/utils/supabase/client";
-import { Button } from "@/components/ui/button";
-import { Icon } from "@iconify/react";
-import Image from "next/image";
-import Link from "next/link";
-import "../../globals.css";
-
-type OAuthProvider = "google" | "github" | "twitch";
-
-interface ProviderConfig {
- name: string;
- icon: string;
- provider: OAuthProvider;
- bgClass: string;
- iconColor?: string;
-}
-
-const providers: ProviderConfig[] = [
- {
- name: "Google",
- icon: "material-icon-theme:google",
- provider: "google",
- bgClass: "border-white/10 bg-transparent hover:bg-white/5",
- },
- {
- name: "GitHub",
- icon: "mdi:github",
- provider: "github",
- bgClass: "border-white/10 bg-transparent hover:bg-white/5",
- },
- {
- name: "Twitch",
- icon: "mdi:twitch",
- provider: "twitch",
- bgClass: "border-white/10 bg-transparent hover:bg-white/5",
- iconColor: "text-[#9146FF]"
- },
-];
-
-export default function Login() {
- const [loading, setLoading] = useState<OAuthProvider | null>(null);
- const [error, setError] = useState<string | null>(null);
- const supabase = createClient();
-
- const handleOAuthSignIn = async (provider: OAuthProvider) => {
- try {
- setLoading(provider);
- setError(null);
-
- const redirectUrl = `${window.location.origin}/auth/callback`;
-
- const { error: signInError } = await supabase.auth.signInWithOAuth({
- provider,
- options: {
- redirectTo: redirectUrl,
- queryParams: {
- access_type: "offline",
- prompt: "consent",
- },
- },
- });
-
- if (signInError) {
- throw signInError;
- }
- } catch (err) {
- console.error(`Error signing in with ${provider}:`, err);
- setError(
- err instanceof Error
- ? err.message
- : "Error al iniciar sesión. Por favor, intenta de nuevo."
- );
- setLoading(null);
- }
- };
-
- return (
- <div className="min-h-screen w-full bg-[#030303] grid lg:grid-cols-2 text-white selection:bg-white/30">
- <div className="relative flex flex-col justify-center px-8 sm:px-16 lg:px-24 xl:px-32">
-
- <div className="absolute top-8 left-8 sm:left-12 lg:left-16">
- <Button
- variant="ghost"
- size="sm"
- className="text-neutral-500 hover:text-white hover:bg-white/5 tracking-wide text-xs uppercase"
- asChild
- >
- <Link href="/">
- <Icon icon="solar:arrow-left-linear" className="mr-2" width="16" />
- Volver
- </Link>
- </Button>
- </div>
-
- <div className="w-full max-w-sm mx-auto mt-16 lg:mt-0">
- <div className="mb-10">
- <Image src="/svg/logo-openvid.svg" alt="Logo" width={60} height={60} className="mb-4" />
- <h1 className="text-3xl sm:text-4xl font-light tracking-tighter text-white mb-3">
- Bienvenido
- </h1>
- <p className="text-neutral-300 text-md font-light tracking-wide">
- Inicia sesión o regístrate para empezar a crear tomas cinemáticas.
- </p>
- </div>
-
- <div className="space-y-4">
- {providers.map((providerConfig) => (
- <Button
- key={providerConfig.provider}
- onClick={() => handleOAuthSignIn(providerConfig.provider)}
- disabled={loading !== null}
- variant="outline"
- size="lg"
- className={`w-full h-12 gap-3 text-white transition-all font-light rounded-none ${providerConfig.bgClass} disabled:opacity-50 disabled:cursor-not-allowed`}
- >
- {loading === providerConfig.provider ? (
- <>
- <Icon
- icon="svg-spinners:ring-resize"
- className="w-5 h-5"
- />
- <span>Conectando...</span>
- </>
- ) : (
- <>
- <Icon
- icon={providerConfig.icon}
- className={`${providerConfig.iconColor || 'text-white'} size-5`}
- />
- <span>Continuar con {providerConfig.name}</span>
- </>
- )}
- </Button>
- ))}
- </div>
-
- {error && (
- <div className="mt-4 p-3 bg-red-500/10 border border-red-500/20 rounded">
- <p className="text-red-400 text-sm">{error}</p>
- </div>
- )}
-
- <p className="mt-12 text-md text-neutral-300 leading-relaxed font-light">
- Al continuar, aceptas nuestros: <br />
- <Link href="/terms" target="_blank" className="text-neutral-300 hover:text-white underline decoration-white/30 underline-offset-4 transition-colors">Términos de Servicio</Link> y{" "}
- <Link href="/privacy" target="_blank" className="text-neutral-300 hover:text-white underline decoration-white/30 underline-offset-4 transition-colors">Política de Privacidad</Link>.
- </p>
- </div>
- </div>
- <div className="hidden lg:block relative w-full h-full border-l border-white/10 bg-[#020203] overflow-hidden group">
- <div className="absolute -top-[10%] -left-[10%] w-[70%] h-[70%] bg-cyan-600/20 rounded-full blur-[80px] pointer-events-none group-hover:bg-cyan-500/30 transition-colors duration-1000"></div>
- <div className="absolute -bottom-[10%] -right-[10%] w-[60%] h-[60%] bg-purple-900/10 rounded-full blur-[80px] pointer-events-none group-hover:bg-purple-700/50 transition-colors duration-1000"></div>
- <div className="absolute inset-0 bg-[radial-gradient(white_0.5px,transparent_0.5px)] bg-size-[40px_40px] opacity-[0.4] pointer-events-none"></div>
- <div className="absolute inset-0 transition-transform duration-1000 ease-in-out scale-110 group-hover:scale-125">
- <img
- src="/images/pages/openvid-login.webp"
- alt="Cinematic Shot BW"
- className="absolute inset-0 w-full h-full object-contain mix-blend-luminosity opacity-70 transition-all duration-1000 ease-in-out [clip-path:inset(0_0_0_50%)] group-hover:opacity-0"
- />
- <img
- src="/images/pages/openvid-login.webp"
- alt="Cinematic Shot Color"
- className="absolute inset-0 w-full h-full object-contain transition-all duration-1000 ease-in-out [clip-path:inset(0_50%_0_0)] group-hover:[clip-path:inset(0_0_0_0%)]"
- />
- <div
- className="absolute inset-0 pointer-events-none mix-blend-screen opacity-40 transition-opacity duration-1000"
- style={{
- background: 'linear-gradient(130deg, rgba(0, 210, 255, 0.4), rgba(58, 123, 213, 0.4) 41.07%, rgba(106, 17, 203, 0.4) 76.05%)',
- maskImage: 'url(/images/pages/openvid-login.webp)',
- maskSize: 'contain',
- maskRepeat: 'no-repeat',
- maskPosition: 'center'
- }}
- />
- </div>
- <div className="absolute inset-0 bg-[radial-gradient(#ffffff22_1px,transparent_1px)] bg-size-[24px_24px] opacity-20 pointer-events-none z-10"></div>
- <div className="absolute inset-0 bg-linear-to-t from-black via-transparent to-black/60 pointer-events-none z-10"></div>
- <div className="absolute top-0 left-1/2 w-px h-full bg-white/20 group-hover:bg-transparent transition-colors duration-1000 pointer-events-none z-20"></div>
- </div>
-
- </div>
- );
-}
\ No newline at end of file
diff --git a/app/(editor)/editor/page.tsx b/app/(editor)/editor/page.tsx
deleted file mode 100644
index 4acaf7d..0000000
--- a/app/(editor)/editor/page.tsx
+++ /dev/null
@@ -1,2394 +0,0 @@
-"use client";
-
-import { useState, useRef, useEffect, useCallback, lazy, Suspense, useMemo } from "react";
-import { Icon } from "@iconify/react";
-import { motion, AnimatePresence } from "framer-motion";
-import { loadVideoFromIndexedDB, deleteRecordedVideo } from "@/hooks/useScreenRecording";
-import { useVideoUpload } from "@/hooks/useVideoUpload";
-import { getUploadedVideo, deleteUploadedVideo } from "@/lib/video-upload-cache";
-import { useVideoExport } from "@/hooks/useVideoExport";
-import { useVideoThumbnails, type VideoThumbnail } from "@/hooks/useVideoThumbnails";
-import { useUndoRedo } from "@/hooks/useUndoRedo";
-import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";
-import { addVideoToLibrary, addVideoToLibraryWithMetadata, getLibraryVideoCount, getLibraryVideo, findExistingVideo } from "@/lib/videos-library";
-import { calculateTotalDuration, findNextClipPosition, getClipAtTime, type VideoTrackClip } from "@/types/video-track.types";
-import type { ExportQuality, Tool, BackgroundTab, VideoCanvasHandle, BackgroundColorConfig, AspectRatio, CropArea, ZoomFragment, AudioTrack } from "@/types";
-import type { TrimRange } from "@/types/timeline.types";
-import type { MockupConfig } from "@/types/mockup.types";
-import type { EditorState } from "@/types/editor-state.types";
-import { createInitialEditorState } from "@/types/editor-state.types";
-import { DEFAULT_MOCKUP_CONFIG, getMockupDefaultConfig } from "@/types/mockup.types";
-import type { CanvasElement } from "@/types/canvas-elements.types";
-import type { CameraConfig } from "@/types/camera.types";
-import { MOCKUPS } from "@/lib/mockup-data";
-import { gradientToCss, generateDefaultZoomFragments, createZoomFragment, detectVideoHasAudio } from "@/types";
-import "../../globals.css";
-import { ToolsSidebar } from "@/app/components/ui/editor/ToolsSidebar";
-import { MobileToolsMenu } from "@/app/components/ui/editor/MobileToolsMenu";
-import { MobileControlPanel } from "@/app/components/ui/editor/MobileControlPanel";
-import { EditorTopBar } from "@/app/components/ui/editor/EditorTopBar";
-import { VideoCanvas } from "@/app/components/ui/editor/VideoCanvas";
-import { PlayerControls } from "@/app/components/ui/editor/PlayerControls";
-import { findValidFragmentPosition } from "@/app/components/ui/editor/ZoomFragmentTrackItem";
-import { LoadingSpinner } from "@/app/components/ui/LoadingSpinner";
-import { TimelineSkeleton } from "@/app/components/ui/Skeleton";
-import { AudioTrimModal } from "@/app/components/ui/editor/AudioTrimModal";
-import { VIDEO_Z_INDEX } from "@/lib/constants";
-import Image from "next/image";
-import Link from "next/link";
-import { TooltipAction } from "@/components/ui/tooltip-action";
-
-// Lazy load heavy components
-const ControlPanel = lazy(() => import("@/app/components/ui/editor/ControlPanel").then(mod => ({ default: mod.ControlPanel })));
-const Timeline = lazy(() => import("@/app/components/ui/editor/Timeline").then(mod => ({ default: mod.Timeline })));
-const ExportOverlay = lazy(() => import("@/app/components/ui/ExportOverlay").then(mod => ({ default: mod.ExportOverlay })));
-const VideoCropperModal = lazy(() => import("@/app/components/ui/editor/VideoCropperModal").then(mod => ({ default: mod.VideoCropperModal })));
-
-export default function Editor() {
- // Undo/Redo system - centralized state management
- const {
- state: editorState,
- setState: setEditorState,
- undo,
- redo,
- canUndo,
- canRedo,
- clearHistory,
- } = useUndoRedo<EditorState>(createInitialEditorState());
-
- const [activeTool, setActiveTool] = useState<Tool>("screenshot");
- const [backgroundTab, setBackgroundTab] = useState<BackgroundTab>("wallpaper");
- const [selectedWallpaper, setSelectedWallpaper] = useState(0);
- const [backgroundBlur, setBackgroundBlur] = useState(0);
- const [padding, setPadding] = useState(10);
- const [roundedCorners, setRoundedCorners] = useState(10);
- const [shadows, setShadows] = useState(10);
- const [isControlPanelOpen, setIsControlPanelOpen] = useState(true);
- const [isMobileControlPanelOpen, setIsMobileControlPanelOpen] = useState(false);
-
- // Video transform state (rotation and position)
- const [videoTransform, setVideoTransform] = useState<{ rotation: number; translateX: number; translateY: number }>({
- rotation: 0,
- translateX: 0,
- translateY: 0,
- });
-
- // Custom background images
- const [uploadedImages, setUploadedImages] = useState<string[]>(() => {
- if (typeof window !== 'undefined') {
- const stored = localStorage.getItem("openvid-uploaded-images");
- if (stored) {
- try {
- const parsed = JSON.parse(stored);
- if (Array.isArray(parsed)) {
- return parsed;
- }
- } catch (error) {
- console.error("Error loading uploaded images:", error);
- }
- }
- }
- return [];
- });
- const [selectedImageUrl, setSelectedImageUrl] = useState<string>("");
- const [unsplashBgUrl, setUnsplashBgUrl] = useState<string>("");
-
- // Background color/gradient state
- const [backgroundColorConfig, setBackgroundColorConfig] = useState<BackgroundColorConfig | null>(null);
-
- // Aspect ratio, fullscreen, and cropper state
- const [aspectRatio, setAspectRatio] = useState<AspectRatio>("auto");
- const [videoDimensions, setVideoDimensions] = useState<{ width: number; height: number } | null>(null);
- const [customDimensions, setCustomDimensions] = useState<{ width: number; height: number } | null>(null);
- const [isFullscreen, setIsFullscreen] = useState(false);
- const [isCropperOpen, setIsCropperOpen] = useState(false);
- const [cropArea, setCropArea] = useState<CropArea | undefined>(undefined);
-
- // Computed: which dimensions to use for the canvas
- const customAspectRatio = aspectRatio === "auto" ? videoDimensions : (aspectRatio === "custom" ? customDimensions : null);
-
- // Refs for fullscreen
- const editorAreaRef = useRef<HTMLDivElement>(null);
- const clipSwitchTimeRef = useRef<number | null>(null);
- const isSeekingToClipRef = useRef<boolean>(false);
-
- // Video state
- const [videoUrl, setVideoUrl] = useState<string | null>(null);
- const [videoId, setVideoId] = useState<string | null>(null);
- const [videoDuration, setVideoDuration] = useState<number>(0);
- const [currentTime, setCurrentTime] = useState<number>(0);
- const [isPlaying, setIsPlaying] = useState<boolean>(false);
- const videoRef = useRef<HTMLVideoElement>(null);
- const canvasRef = useRef<VideoCanvasHandle>(null);
- const isSwitchingClipRef = useRef<boolean>(false);
-
- // Timeline state
- const [timelineZoom, setTimelineZoom] = useState<number>(1);
- const [isDraggingPlayhead, setIsDraggingPlayhead] = useState<boolean>(false);
- const [trimRange, setTrimRange] = useState<TrimRange>({ start: 0, end: 0 });
- const animationFrameRef = useRef<number | null>(null);
- const justEndedRef = useRef<boolean>(false);
- const wasPlayingBeforeDragRef = useRef<boolean>(false);
- const isExportingRef = useRef(false);
- const [scrubTime, setScrubTime] = useState<number>(0);
- // Ref that is always in sync with scrubTime — avoids stale closure in handlePlayheadDragEnd
- const scrubTimeRef = useRef<number>(0);
-
- // Zoom fragments state
- const [zoomFragments, setZoomFragments] = useState<ZoomFragment[]>([]);
- const [selectedZoomFragmentId, setSelectedZoomFragmentId] = useState<string | null>(null);
-
- // Ref to always have the latest zoomFragments value (prevents stale closures)
- const zoomFragmentsRef = useRef<ZoomFragment[]>([]);
- useEffect(() => {
- zoomFragmentsRef.current = zoomFragments;
- }, [zoomFragments]);
-
- // Mockup state
- const [mockupId, setMockupId] = useState<string>("none");
- const [mockupConfig, setMockupConfig] = useState<MockupConfig>(DEFAULT_MOCKUP_CONFIG);
-
- // Canvas elements state
- const [canvasElements, setCanvasElements] = useState<CanvasElement[]>([]);
- const [selectedElementId, setSelectedElementId] = useState<string | null>(null);
-
- // Audio state
- const [uploadedAudios, setUploadedAudios] = useState<import("@/types/audio.types").UploadedAudio[]>([]);
- const [audioTracks, setAudioTracks] = useState<import("@/types/audio.types").AudioTrack[]>([]);
- const [muteOriginalAudio, setMuteOriginalAudio] = useState<boolean>(false);
- const [masterVolume, setMasterVolume] = useState<number>(1);
- const [selectedAudioTrackId, setSelectedAudioTrackId] = useState<string | null>(null);
- // Whether the currently loaded source video file contains an audio stream
- const [videoHasAudioTrack, setVideoHasAudioTrack] = useState<boolean>(true);
-
- const [isRecordedVideo, setIsRecordedVideo] = useState<boolean>(false);
-
- // Camera overlay state (from recorded video's camera track, or post-record adjustments)
- const [cameraConfig, setCameraConfig] = useState<CameraConfig | null>(null);
- const [cameraUrl, setCameraUrl] = useState<string | null>(null);
-
- const handleCameraConfigChange = useCallback((partial: Partial<CameraConfig>) => {
- setCameraConfig((prev) => (prev ? { ...prev, ...partial } : prev));
- }, []);
-
- const handleCameraClick = useCallback(() => {
- setActiveTool("camera");
- }, []);
-
- // Videos library state
- const [newVideosCount, setNewVideosCount] = useState<number>(0);
- const [videosLibraryRefresh, setVideosLibraryRefresh] = useState<number>(0);
-
- // Video track clips state (multi-video support)
- const [videoClips, setVideoClips] = useState<VideoTrackClip[]>([]);
- // Computed from videoClips - array of library video IDs currently in track
- const videosInTrackIds = useMemo(() =>
- videoClips.map(clip => clip.libraryVideoId),
- [videoClips]);
- // Ref para acceder al valor actual de videoClips en callbacks (evitar closure stale)
- const videoClipsRef = useRef<VideoTrackClip[]>([]);
- useEffect(() => {
- videoClipsRef.current = videoClips;
- }, [videoClips]);
- const [selectedVideoClipId, setSelectedVideoClipId] = useState<string | null>(null);
-
- // Multi-video playback: store video blobs and URLs indexed by libraryVideoId
- const videoBlobsRef = useRef<Map<string, Blob>>(new Map());
- const videoUrlsRef = useRef<Map<string, string>>(new Map());
- const activeClipIdRef = useRef<string | null>(null);
- const activeClipDataRef = useRef<VideoTrackClip | null>(null);
- // Per-clip audio state cache: libraryVideoId → hasAudio (avoids async reads during playback)
- const clipAudioStateRef = useRef<Map<string, boolean>>(new Map());
- // Ref to always have the latest muteOriginalAudio value (prevents stale closures inside RAF callbacks)
- const muteOriginalAudioRef = useRef<boolean>(false);
- useEffect(() => {
- muteOriginalAudioRef.current = muteOriginalAudio;
- }, [muteOriginalAudio]);
- // Audio trim modal state
- const [autoTrimModalOpen, setAutoTrimModalOpen] = useState(false);
- const [pendingAudioUpload, setPendingAudioUpload] = useState<{
- audio: import("@/types/audio.types").UploadedAudio;
- trackId: string;
- } | null>(null);
-
- // Audio playback refs - store HTML Audio elements for each track
- const audioElementsRef = useRef<Map<string, HTMLAudioElement>>(new Map());
-
- // Initialize audio elements when tracks change
- useEffect(() => {
- const currentElements = audioElementsRef.current;
- const currentTrackIds = new Set(audioTracks.map(t => t.id));
-
- // Remove audio elements for deleted tracks
- for (const [trackId, audioEl] of currentElements.entries()) {
- if (!currentTrackIds.has(trackId)) {
- audioEl.pause();
- audioEl.src = '';
- currentElements.delete(trackId);
- }
- }
-
- // Create audio elements for new tracks
- for (const track of audioTracks) {
- if (!currentElements.has(track.id)) {
- const audio = uploadedAudios.find(a => a.id === track.audioId);
- if (audio) {
- const audioEl = new Audio(audio.url);
- audioEl.preload = 'auto';
- audioEl.volume = track.volume * masterVolume;
- currentElements.set(track.id, audioEl);
- }
- }
- }
- }, [audioTracks, uploadedAudios, masterVolume]);
-
- // Update audio volumes when master volume or track volumes change
- useEffect(() => {
- const currentElements = audioElementsRef.current;
- for (const track of audioTracks) {
- const audioEl = currentElements.get(track.id);
- if (audioEl) {
- audioEl.volume = track.volume * masterVolume;
- }
- }
- }, [audioTracks, masterVolume]);
-
- // Sync audio playback with video current time
- const syncAudioPlayback = useCallback((videoTime: number, playing: boolean) => {
- if (isExportingRef.current) return;
- const currentElements = audioElementsRef.current;
-
- for (const track of audioTracks) {
- const audioEl = currentElements.get(track.id);
- if (!audioEl) continue;
-
- const trackStart = track.startTime;
- const trackEnd = track.startTime + track.duration;
- const trimStart = track.trimStart ?? 0;
-
- if (videoTime >= trackStart && videoTime < trackEnd) {
- const audioTime = trimStart + (videoTime - trackStart);
-
- if (Math.abs(audioEl.currentTime - audioTime) > 0.1) {
- audioEl.currentTime = audioTime;
- }
-
- if (playing && audioEl.paused) {
- audioEl.play().catch(() => { });
- } else if (!playing && !audioEl.paused) {
- audioEl.pause();
- }
- } else {
- if (!audioEl.paused) {
- audioEl.pause();
- }
- }
- }
- }, [audioTracks]);
-
- useEffect(() => {
- const elementsRef = audioElementsRef.current;
- return () => {
- for (const audioEl of elementsRef.values()) {
- audioEl.pause();
- audioEl.src = '';
- }
- elementsRef.clear();
- };
- }, []);
-
- const updateEditorStateDebounced = useRef<NodeJS.Timeout | null>(null);
- useEffect(() => {
- if (updateEditorStateDebounced.current) {
- clearTimeout(updateEditorStateDebounced.current);
- }
- updateEditorStateDebounced.current = setTimeout(() => {
- setEditorState({
- backgroundTab,
- selectedWallpaper,
- backgroundBlur,
- padding,
- roundedCorners,
- shadows,
- selectedImageUrl,
- backgroundColorConfig,
- aspectRatio,
- customDimensions,
- cropArea,
- trimRange,
- zoomFragments,
- mockupId,
- mockupConfig,
- canvasElements,
- audioTracks,
- muteOriginalAudio,
- masterVolume,
- cameraConfig,
- });
- }, 300);
- return () => {
- if (updateEditorStateDebounced.current) {
- clearTimeout(updateEditorStateDebounced.current);
- }
- };
- }, [
- backgroundTab, selectedWallpaper, backgroundBlur, padding,
- roundedCorners, shadows, selectedImageUrl, backgroundColorConfig,
- aspectRatio, customDimensions, cropArea, trimRange,
- zoomFragments, mockupId, mockupConfig, canvasElements,
- audioTracks, muteOriginalAudio, masterVolume, cameraConfig,
- setEditorState
- ]);
-
- // Sync editorState → individual states (from undo/redo)
- useEffect(() => {
- setBackgroundTab(editorState.backgroundTab);
- setSelectedWallpaper(editorState.selectedWallpaper);
- setBackgroundBlur(editorState.backgroundBlur);
- setPadding(editorState.padding);
- setRoundedCorners(editorState.roundedCorners);
- setShadows(editorState.shadows);
- setSelectedImageUrl(editorState.selectedImageUrl);
- setBackgroundColorConfig(editorState.backgroundColorConfig);
- setAspectRatio(editorState.aspectRatio);
- setCustomDimensions(editorState.customDimensions);
- setCropArea(editorState.cropArea);
- setTrimRange(editorState.trimRange);
- setZoomFragments(editorState.zoomFragments);
- setMockupId(editorState.mockupId);
- setMockupConfig(editorState.mockupConfig);
- setCanvasElements(editorState.canvasElements);
- setAudioTracks(editorState.audioTracks);
- setMuteOriginalAudio(editorState.muteOriginalAudio);
- setMasterVolume(editorState.masterVolume);
- setCameraConfig(editorState.cameraConfig);
- }, [editorState]);
-
- // Handler para cambiar el mockup
- const handleMockupChange = useCallback((newMockupId: string) => {
- setMockupId(newMockupId);
- // Establecer la config por defecto del nuevo mockup
- const newMockup = MOCKUPS.find(m => m.id === newMockupId);
- setMockupConfig(getMockupDefaultConfig(newMockup));
- }, []);
-
- // Handler para cambiar la configuración del mockup
- const handleMockupConfigChange = useCallback((updates: Partial<MockupConfig>) => {
- setMockupConfig(prev => ({ ...prev, ...updates }));
- }, []);
-
- // Handler para cambiar las esquinas redondeadas (sincroniza ambos valores)
- const handleRoundedCornersChange = useCallback((value: number) => {
- setRoundedCorners(value); // Para NoneMockup y canvas general
- setMockupConfig(prev => ({ ...prev, cornerRadius: value })); // Para mockups que usan config
- }, []);
-
- // Canvas elements handlers
- const addCanvasElement = useCallback((element: CanvasElement) => {
- setCanvasElements(prev => [...prev, element]);
- setSelectedElementId(element.id);
- }, []);
-
- const updateCanvasElement = useCallback((id: string, updates: Partial<CanvasElement>) => {
- setCanvasElements(prev => prev.map(el =>
- el.id === id ? { ...el, ...updates } as CanvasElement : el
- ));
- }, []);
-
- const deleteCanvasElement = useCallback((id: string) => {
- setCanvasElements(prev => prev.filter(el => el.id !== id));
- setSelectedElementId(prev => prev === id ? null : prev);
- }, []);
-
- const selectCanvasElement = useCallback((id: string | null) => {
- setSelectedElementId(id);
- // Auto-open elements menu when selecting an element
- if (id) {
- setActiveTool("elements");
- }
- }, []);
-
-
- // Copy/paste handlers
- const [copiedElement, setCopiedElement] = useState<CanvasElement | null>(null);
-
- const copySelectedElement = useCallback(() => {
- if (!selectedElementId) return;
- const element = canvasElements.find(el => el.id === selectedElementId);
- if (element) {
- setCopiedElement(element);
- }
- }, [selectedElementId, canvasElements]);
-
- const pasteElement = useCallback(() => {
- if (!copiedElement) return;
-
- const newElement = {
- ...copiedElement,
- id: `${copiedElement.type}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
- x: copiedElement.x + 5, // Offset slightly from original
- y: copiedElement.y + 5,
- zIndex: Date.now(),
- } as CanvasElement;
-
- setCanvasElements(prev => [...prev, newElement]);
- setSelectedElementId(newElement.id);
- setActiveTool("elements");
- }, [copiedElement]);
-
- const bringToFront = useCallback((id: string) => {
- // Get elements that are above the video (zIndex >= VIDEO_Z_INDEX)
- const aboveVideoElements = canvasElements.filter(el => el.zIndex >= VIDEO_Z_INDEX);
- const maxAboveVideo = aboveVideoElements.length > 0
- ? Math.max(...aboveVideoElements.map(el => el.zIndex))
- : VIDEO_Z_INDEX - 1;
- // Ensure the element goes above video and all other above-video elements
- updateCanvasElement(id, { zIndex: Math.max(maxAboveVideo + 1, VIDEO_Z_INDEX) });
- }, [canvasElements, updateCanvasElement]);
-
- const sendToBack = useCallback((id: string) => {
- const element = canvasElements.find(el => el.id === id);
- if (!element) return;
-
- // If element is above video (zIndex >= VIDEO_Z_INDEX), send it just behind video
- if (element.zIndex >= VIDEO_Z_INDEX) {
- const behindVideoElements = canvasElements.filter(el => el.zIndex < VIDEO_Z_INDEX);
- const minBehindVideo = behindVideoElements.length > 0
- ? Math.min(...behindVideoElements.map(el => el.zIndex))
- : VIDEO_Z_INDEX - 100;
- updateCanvasElement(id, { zIndex: Math.min(minBehindVideo - 1, VIDEO_Z_INDEX - 1) });
- } else {
- const behindVideoElements = canvasElements.filter(el => el.zIndex < VIDEO_Z_INDEX && el.id !== id);
- const minBehindVideo = behindVideoElements.length > 0
- ? Math.min(...behindVideoElements.map(el => el.zIndex))
- : element.zIndex;
- updateCanvasElement(id, { zIndex: minBehindVideo - 1 });
- }
- }, [canvasElements, updateCanvasElement]);
-
- // Audio handlers
- const handleAudioUpload = useCallback(async (file: File) => {
- try {
- const MAX_AUDIO_TRACKS = 5;
- if (audioTracks.length >= MAX_AUDIO_TRACKS) {
- alert(`Máximo ${MAX_AUDIO_TRACKS} pistas de audio permitidas.`);
- return;
- }
-
- const url = URL.createObjectURL(file);
-
- const audio = new Audio(url);
- await new Promise<void>((resolve, reject) => {
- audio.addEventListener('loadedmetadata', () => resolve());
- audio.addEventListener('error', () => reject(new Error('Failed to load audio')));
- });
-
- const newAudio: import("@/types/audio.types").UploadedAudio = {
- id: `audio-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
- name: file.name,
- url,
- duration: audio.duration,
- fileSize: file.size,
- mimeType: file.type,
- };
-
- setUploadedAudios(prev => [...prev, newAudio]);
-
- const lastTrackEnd = audioTracks.reduce((max, track) =>
- Math.max(max, track.startTime + track.duration), 0);
-
- const trackId = `track-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
-
- if (audio.duration > videoDuration) {
- setPendingAudioUpload({ audio: newAudio, trackId });
- setAutoTrimModalOpen(true);
- } else {
- const newTrack: import("@/types/audio.types").AudioTrack = {
- id: trackId,
- audioId: newAudio.id,
- name: newAudio.name,
- startTime: lastTrackEnd,
- duration: newAudio.duration,
- volume: 1,
- loop: false,
- };
-
- setAudioTracks(prev => [...prev, newTrack]);
-
- if (audioTracks.length === 0) {
- setMuteOriginalAudio(true);
- }
- }
- } catch (error) {
- console.error('Error uploading audio:', error);
- alert('Error al subir el audio. Por favor intenta de nuevo.');
- }
- }, [audioTracks, videoDuration]);
-
- const handleAudioDelete = useCallback((audioId: string) => {
- setUploadedAudios(prev => {
- const audio = prev.find(a => a.id === audioId);
- if (audio) {
- URL.revokeObjectURL(audio.url);
- }
- return prev.filter(a => a.id !== audioId);
- });
-
- setAudioTracks(prev => prev.filter(track => track.audioId !== audioId));
- }, []);
-
- const handleAddAudioTrack = useCallback((audioId: string) => {
- const audio = uploadedAudios.find(a => a.id === audioId);
- if (!audio) return;
-
- const MAX_AUDIO_TRACKS = 5;
- if (audioTracks.length >= MAX_AUDIO_TRACKS) {
- alert(`Máximo ${MAX_AUDIO_TRACKS} pistas de audio permitidas.`);
- return;
- }
-
- if (audioTracks.some(track => track.audioId === audioId)) {
- return;
- }
-
- // Calculate startTime as end of last track to prevent overlapping
- const lastTrackEnd = audioTracks.reduce((max, track) =>
- Math.max(max, track.startTime + track.duration), 0);
-
- const newTrack: import("@/types/audio.types").AudioTrack = {
- id: `track-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
- audioId,
- name: audio.name,
- startTime: lastTrackEnd,
- duration: audio.duration,
- volume: 1,
- loop: false,
- };
-
- setAudioTracks(prev => [...prev, newTrack]);
- if (audioTracks.length === 0) {
- setMuteOriginalAudio(true);
- }
- }, [uploadedAudios, audioTracks]);
-
- const handleUpdateAudioTrack = useCallback((trackId: string, updates: Partial<import("@/types/audio.types").AudioTrack>) => {
- setAudioTracks(prev => prev.map(track =>
- track.id === trackId ? { ...track, ...updates } : track
- ));
- }, []);
-
- const handleDeleteAudioTrack = useCallback((trackId: string) => {
- setAudioTracks(prev => {
- const remaining = prev.filter(track => track.id !== trackId);
- if (remaining.length === 0) {
- setMuteOriginalAudio(false);
- }
- return remaining;
- });
- }, []);
-
- const handleToggleMuteOriginalAudio = useCallback(() => {
- setMuteOriginalAudio(prev => !prev);
- }, []);
-
- const handleMasterVolumeChange = useCallback((volume: number) => {
- setMasterVolume(volume);
- }, []);
-
- const handleSelectAudioTrack = useCallback((trackId: string | null) => {
- setSelectedAudioTrackId(trackId);
- if (trackId) {
- setSelectedZoomFragmentId(null);
- setSelectedVideoClipId(null);
- setSelectedElementId(null);
- setActiveTool("audio");
- }
- }, []);
-
- const [thumbnailClipId, setThumbnailClipId] = useState<string | null>(null);
-
- const thumbnailsCacheRef = useRef<Map<string, VideoThumbnail[]>>(new Map());
-
- const currentDisplayTime = isDraggingPlayhead ? scrubTime : currentTime;
- useEffect(() => {
- if (videoClips.length <= 1) {
- setThumbnailClipId(null);
- return;
- }
- const clipAtTime = getClipAtTime(videoClips, currentDisplayTime);
- if (clipAtTime) {
- setThumbnailClipId(prev => {
- if (prev !== clipAtTime.libraryVideoId) {
- return clipAtTime.libraryVideoId;
- }
- return prev;
- });
- }
- }, [currentDisplayTime, videoClips]);
-
- const thumbnailUrl = useMemo(() => {
- if (videoClips.length <= 1 || !thumbnailClipId) return videoUrl;
- return videoUrlsRef.current.get(thumbnailClipId) || videoUrl;
- }, [videoUrl, videoClips.length, thumbnailClipId]);
-
- const thumbnailVideoId = useMemo(() => {
- if (videoClips.length <= 1 || !thumbnailClipId) return videoId;
- return thumbnailClipId;
- }, [videoId, videoClips.length, thumbnailClipId]);
-
- const thumbnailDuration = useMemo(() => {
- if (videoClips.length <= 1 || !thumbnailClipId) return videoDuration;
- const clip = videoClips.find(c => c.libraryVideoId === thumbnailClipId);
- return clip?.duration || videoDuration;
- }, [videoDuration, videoClips, thumbnailClipId]);
-
- const { getThumbnailForTime: getRawThumbnailForTime, thumbnails: currentThumbnails } = useVideoThumbnails(
- thumbnailUrl,
- thumbnailDuration,
- {
- interval: 0.1,
- quality: "high",
- videoId: thumbnailVideoId || undefined,
- }
- );
-
- useEffect(() => {
- if (thumbnailVideoId && currentThumbnails.length > 0) {
- thumbnailsCacheRef.current.set(thumbnailVideoId, currentThumbnails);
- }
- }, [thumbnailVideoId, currentThumbnails]);
-
- const findNearestThumbnail = useCallback((thumbs: VideoThumbnail[], time: number): VideoThumbnail | null => {
- if (thumbs.length === 0) return null;
- let left = 0;
- let right = thumbs.length - 1;
- while (left < right) {
- const mid = Math.floor((left + right) / 2);
- if (thumbs[mid].time < time) left = mid + 1;
- else right = mid;
- }
- if (left > 0) {
- const prevDiff = Math.abs(thumbs[left - 1].time - time);
- const currDiff = Math.abs(thumbs[left].time - time);
- if (prevDiff < currDiff) return thumbs[left - 1];
- }
- return thumbs[left];
- }, []);
-
- // Clip-aware getThumbnailForTime: looks up any clip's thumbnails from cache
- const getThumbnailForTime = useCallback((timelineTime: number) => {
- const clips = videoClipsRef.current;
- if (clips.length <= 1) {
- return getRawThumbnailForTime(timelineTime);
- }
-
- const clipAtTime = getClipAtTime(clips, timelineTime);
- if (!clipAtTime) return null;
-
- const localTime = clipAtTime.trimStart + (timelineTime - clipAtTime.startTime);
-
- // If this is the currently generating clip, use the hook directly (most up-to-date)
- if (clipAtTime.libraryVideoId === thumbnailVideoId) {
- return getRawThumbnailForTime(localTime);
- }
-
- // Otherwise, check the persistent cache
- const cached = thumbnailsCacheRef.current.get(clipAtTime.libraryVideoId);
- if (cached && cached.length > 0) {
- return findNearestThumbnail(cached, localTime);
- }
-
- return null;
- }, [getRawThumbnailForTime, thumbnailVideoId, findNearestThumbnail]);
-
- // Find which clip is active at a given timeline time - using standardized function
- const findActiveClipAtTime = useCallback((timelineTime: number): VideoTrackClip | null => {
- const clips = videoClipsRef.current;
- return getClipAtTime(clips, timelineTime);
- }, []);
-
- // Convert timeline time to clip-local time
- const timelineToClipTime = useCallback((timelineTime: number, clip: VideoTrackClip): number => {
- const offsetInClip = timelineTime - clip.startTime;
- return clip.trimStart + offsetInClip;
- }, []);
-
- // Pre-load video blobs when clips change
- useEffect(() => {
- const loadClipBlobs = async () => {
- const currentBlobs = videoBlobsRef.current;
- const currentUrls = videoUrlsRef.current;
- const neededIds = new Set(videoClips.map(c => c.libraryVideoId));
-
- for (const [id, url] of currentUrls.entries()) {
- if (!neededIds.has(id)) {
- URL.revokeObjectURL(url);
- currentUrls.delete(id);
- currentBlobs.delete(id);
- }
- }
-
- for (const clip of videoClips) {
- if (!currentBlobs.has(clip.libraryVideoId)) {
- try {
- const libraryVideo = await getLibraryVideo(clip.libraryVideoId);
- if (libraryVideo) {
- currentBlobs.set(clip.libraryVideoId, libraryVideo.blob);
- const url = URL.createObjectURL(libraryVideo.blob);
- currentUrls.set(clip.libraryVideoId, url);
- }
- } catch (e) {
- console.warn("Failed to load video blob for clip:", clip.id, e);
- }
- }
- }
- };
-
- if (videoClips.length > 0) {
- loadClipBlobs();
- }
- }, [videoClips]);
-
- const { exportVideo, cancelExport, exportProgress } = useVideoExport(videoRef, canvasRef);
- const { uploadVideo, loadUploadedVideo, isUploading } = useVideoUpload();
- const [videoBlob, setVideoBlob] = useState<Blob | null>(null);
-
- const handleExport = (quality: ExportQuality) => {
- isExportingRef.current = true;
- for (const audioEl of audioElementsRef.current.values()) {
- audioEl.pause();
- }
-
- exportVideo({
- quality,
- videoBlob: videoBlob ?? undefined,
- transparentBackground: selectedWallpaper === -1,
- trim: trimRange.end > trimRange.start ? { start: trimRange.start, end: trimRange.end } : undefined,
- muteOriginalAudio,
- videoHasAudioTrack: videoHasAudioTrack,
- audioTracks: audioTracks.map(track => {
- const audio = uploadedAudios.find(a => a.id === track.audioId);
- return {
- audioUrl: audio?.url || '',
- startTime: track.startTime,
- duration: track.duration,
- trimStart: track.trimStart ?? 0,
- volume: track.volume,
- loop: track.loop,
- };
- }),
- masterVolume,
- videoClips: videoClips.length > 0 ? videoClips : undefined,
- videoClipBlobs: videoClips.length > 1 ? videoBlobsRef.current : undefined,
- }).finally(() => {
- });
- };
-
- // Handler para subir video (desde ToolsSidebar)
- const handleVideoUpload = useCallback(async (file: File) => {
- // Usar ref para obtener el valor actual de clips (evitar stale closure)
- const hasExistingClips = videoClipsRef.current.length > 0;
-
- // Add video to library first
- let libraryVideo: Awaited<ReturnType<typeof addVideoToLibrary>> | null = null;
- try {
- libraryVideo = await addVideoToLibrary(file);
- const count = await getLibraryVideoCount();
- setNewVideosCount(hasExistingClips ? count : 0);
- setVideosLibraryRefresh(prev => prev + 1);
- } catch (error) {
- console.warn("Failed to add video to library:", error);
- return;
- }
-
- // If there are already clips, just add to library (user will add to track manually)
- if (hasExistingClips) {
- setActiveTool("videos");
- return;
- }
-
- // First video - add to track
- // Clear any stale blob/URL refs from previous videos
- for (const [, url] of videoUrlsRef.current.entries()) {
- URL.revokeObjectURL(url);
- }
- videoBlobsRef.current.clear();
- videoUrlsRef.current.clear();
- activeClipIdRef.current = null;
- activeClipDataRef.current = null;
- setVideoBlob(file);
- detectVideoHasAudio(file).then(hasAudio => {
- setVideoHasAudioTrack(hasAudio);
- if (!hasAudio) setMuteOriginalAudio(true);
- if (libraryVideo) {
- clipAudioStateRef.current.set(libraryVideo.id, hasAudio);
- }
- });
-
- try {
- await clearAllThumbnailCache();
- } catch (error) {
- console.warn("Failed to clear thumbnails:", error);
- }
-
- const uploadedData = await uploadVideo(file);
- if (uploadedData && libraryVideo) {
- lastLoadedVideoIdRef.current = uploadedData.videoId;
-
- setVideoUrl(uploadedData.url);
- setVideoId(uploadedData.videoId);
- setVideoDuration(uploadedData.duration);
- setTrimRange({ start: 0, end: uploadedData.duration });
- setAspectRatio(uploadedData.aspectRatio);
- setVideoDimensions({ width: uploadedData.width, height: uploadedData.height });
-
- const newClip: VideoTrackClip = {
- id: crypto.randomUUID(),
- libraryVideoId: libraryVideo.id,
- name: file.name,
- startTime: 0,
- duration: uploadedData.duration,
- trimStart: 0,
- trimEnd: uploadedData.duration,
- thumbnailUrl: libraryVideo.thumbnailUrl,
- };
- clipAudioStateRef.current.set(libraryVideo.id, libraryVideo.hasAudio !== false);
- activeClipIdRef.current = newClip.id;
- activeClipDataRef.current = newClip;
- setVideoClips([newClip]);
- setSelectedVideoClipId(newClip.id);
-
- const defaultFragments = generateDefaultZoomFragments(uploadedData.duration);
- setZoomFragments(defaultFragments);
-
- setCurrentTime(0);
- setIsPlaying(false);
- setTimeout(() => clearHistory(), 200);
- }
- }, [uploadVideo, clearHistory]);
-
- // Handler para subir video solo a la librería (desde VideosMenu)
- const handleVideoUploadToLibrary = useCallback(async (file: File) => {
- try {
- await addVideoToLibrary(file);
- const count = await getLibraryVideoCount();
- setNewVideosCount(count);
- setVideosLibraryRefresh(prev => prev + 1);
- } catch (error) {
- console.warn("Failed to add video to library:", error);
- }
- }, []);
-
- // Handler para agregar video desde la librería al track (concatenar)
- const handleAddVideoToTrack = useCallback(async (videoId: string, blob: Blob, duration: number) => {
- // Get video info from library
- const libraryVideo = await import("@/lib/videos-library").then(m => m.getLibraryVideo(videoId));
- if (!libraryVideo) return;
-
- // Cache the per-clip audio state (hasAudio defaults to true if undefined)
- clipAudioStateRef.current.set(videoId, libraryVideo.hasAudio !== false);
-
- // Store blob in ref for multi-video playback
- if (!videoBlobsRef.current.has(videoId)) {
- videoBlobsRef.current.set(videoId, blob);
- const blobUrl = URL.createObjectURL(blob);
- videoUrlsRef.current.set(videoId, blobUrl);
- }
-
- // Usar functional update para tener siempre el estado más reciente
- setVideoClips(prevClips => {
- const startTime = findNextClipPosition(prevClips);
-
- const newClip: VideoTrackClip = {
- id: crypto.randomUUID(),
- libraryVideoId: videoId,
- name: libraryVideo.fileName,
- startTime,
- duration,
- trimStart: 0,
- trimEnd: duration,
- thumbnailUrl: libraryVideo.thumbnailUrl,
- };
-
- const updatedClips = [...prevClips, newClip];
-
- setTimeout(() => {
- const newTotalDuration = calculateTotalDuration(updatedClips);
- setVideoDuration(newTotalDuration);
- setTrimRange({ start: 0, end: newTotalDuration });
-
- if (prevClips.length === 0) {
- activeClipIdRef.current = newClip.id;
- activeClipDataRef.current = newClip;
- const url = videoUrlsRef.current.get(videoId) || URL.createObjectURL(blob);
- setVideoBlob(blob);
- setVideoUrl(url);
- setVideoId(videoId);
-
- detectVideoHasAudio(blob).then(hasAudio => {
- clipAudioStateRef.current.set(videoId, hasAudio);
- });
-
- const video = document.createElement('video');
- video.preload = 'metadata';
- const metadataUrl = URL.createObjectURL(blob);
- video.onloadedmetadata = () => {
- setVideoDimensions({ width: video.videoWidth, height: video.videoHeight });
- setAspectRatio("auto");
- URL.revokeObjectURL(metadataUrl);
- };
- video.src = metadataUrl;
-
- const defaultFragments = generateDefaultZoomFragments(duration);
- setZoomFragments(defaultFragments);
-
- setCurrentTime(0);
- setIsPlaying(false);
- }
-
- setNewVideosCount(0);
- clearHistory();
- }, 0);
-
- return updatedClips;
- });
- }, [clearHistory]);
-
- // Handlers for video clip management
- const handleSelectVideoClip = useCallback((clipId: string | null) => {
- setSelectedVideoClipId(clipId);
- // Clear other selections when selecting video clip (mutual exclusivity)
- if (clipId) {
- setSelectedZoomFragmentId(null);
- setSelectedAudioTrackId(null);
- setSelectedElementId(null);
- setActiveTool("videos");
- }
- }, []);
-
- const handleUpdateVideoClip = useCallback((clipId: string, updates: Partial<VideoTrackClip>) => {
- setVideoClips(prev => {
- const newClips = prev.map(clip =>
- clip.id === clipId ? { ...clip, ...updates } : clip
- );
- if (updates.startTime !== undefined || updates.trimEnd !== undefined || updates.trimStart !== undefined) {
- const newDuration = calculateTotalDuration(newClips);
- setVideoDuration(newDuration);
- setTrimRange({ start: 0, end: newDuration });
- }
- return newClips;
- });
- }, []);
-
- const handleDeleteVideoClip = useCallback((clipId: string) => {
- setVideoClips(prev => {
- const newClips = prev.filter(clip => clip.id !== clipId);
- if (newClips.length > 0) {
- const newDuration = calculateTotalDuration(newClips);
- setVideoDuration(newDuration);
- setTrimRange({ start: 0, end: newDuration });
-
- if (activeClipIdRef.current === clipId) {
- const firstClip = [...newClips].sort((a, b) => a.startTime - b.startTime)[0];
- activeClipIdRef.current = firstClip.id;
- activeClipDataRef.current = firstClip;
- const url = videoUrlsRef.current.get(firstClip.libraryVideoId);
- if (url && videoRef.current) {
- videoRef.current.src = url;
- videoRef.current.currentTime = firstClip.trimStart;
- }
- setCurrentTime(firstClip.startTime);
- }
- } else {
- setVideoUrl(null);
- setVideoId(null);
- setVideoDuration(0);
- setTrimRange({ start: 0, end: 0 });
- activeClipIdRef.current = null;
- activeClipDataRef.current = null;
- if (videoRef.current) {
- videoRef.current.removeAttribute('src');
- }
- }
- return newClips;
- });
- if (selectedVideoClipId === clipId) {
- setSelectedVideoClipId(null);
- }
- }, [selectedVideoClipId]);
-
- // Handler para eliminar video de track cuando se elimina de la librería (cascade delete)
- const handleDeleteVideoFromLibrary = useCallback((libraryVideoId: string) => {
- setVideoClips(prev => {
- const newClips = prev.filter(clip => clip.libraryVideoId !== libraryVideoId);
- if (newClips.length > 0) {
- const newDuration = calculateTotalDuration(newClips);
- setVideoDuration(newDuration);
- setTrimRange({ start: 0, end: newDuration });
- } else {
- setVideoUrl(null);
- setVideoId(null);
- setVideoDuration(0);
- setTrimRange({ start: 0, end: 0 });
- activeClipIdRef.current = null;
- activeClipDataRef.current = null;
- if (videoRef.current) {
- videoRef.current.removeAttribute('src');
- videoRef.current.load();
- }
- lastLoadedVideoIdRef.current = null;
- deleteRecordedVideo().catch(() => { });
- deleteUploadedVideo().catch(() => { });
- }
- return newClips;
- });
- // Clean up blob/URL refs
- if (videoBlobsRef.current.has(libraryVideoId)) {
- videoBlobsRef.current.delete(libraryVideoId);
- }
- if (videoUrlsRef.current.has(libraryVideoId)) {
- const url = videoUrlsRef.current.get(libraryVideoId);
- if (url) URL.revokeObjectURL(url);
- videoUrlsRef.current.delete(libraryVideoId);
- }
- }, []);
-
- // Handler for per-clip audio toggle from VideosMenu
- const handleVideoAudioToggle = useCallback((videoId: string, hasAudio: boolean) => {
- clipAudioStateRef.current.set(videoId, hasAudio);
-
- if (muteOriginalAudio) return;
-
- const activeClip = activeClipDataRef.current;
- if (activeClip && activeClip.libraryVideoId === videoId && videoRef.current) {
- videoRef.current.muted = !hasAudio;
- }
- }, [muteOriginalAudio]);
-
- // Handler para quitar video del track (toggle) - solo remueve el clip, no la librería
- const handleRemoveVideoFromTrack = useCallback((libraryVideoId: string) => {
- setVideoClips(prev => {
- const newClips = prev.filter(clip => clip.libraryVideoId !== libraryVideoId);
- if (newClips.length > 0) {
- const newDuration = calculateTotalDuration(newClips);
- setVideoDuration(newDuration);
- setTrimRange({ start: 0, end: newDuration });
- const currentActiveId = activeClipIdRef.current;
- if (currentActiveId && !newClips.find(c => c.id === currentActiveId)) {
- activeClipIdRef.current = newClips[0].id;
- }
- } else {
- setVideoUrl(null);
- setVideoId(null);
- setVideoDuration(0);
- setTrimRange({ start: 0, end: 0 });
- activeClipIdRef.current = null;
- activeClipDataRef.current = null;
- }
- return newClips;
- });
- }, []);
-
- useEffect(() => {
- if (activeTool === "videos") {
- setNewVideosCount(0);
- }
- }, [activeTool]);
-
- const lastLoadedVideoIdRef = useRef<string | null>(null);
-
- useEffect(() => {
- const loadVideo = async () => {
- try {
- const [uploadedData, recordedData, cachedUpload] = await Promise.all([
- loadUploadedVideo(),
- loadVideoFromIndexedDB(),
- getUploadedVideo(),
- ]);
-
- let videoToLoad: typeof uploadedData | typeof recordedData = null;
- let videoBlob: Blob | null = null;
-
- if (uploadedData && recordedData) {
- videoToLoad = uploadedData.timestamp > recordedData.timestamp ? uploadedData : recordedData;
- if (uploadedData.timestamp > recordedData.timestamp && cachedUpload) {
- videoBlob = cachedUpload.blob;
- } else if ('blob' in recordedData && recordedData.blob) {
- videoBlob = recordedData.blob;
- }
- } else if (uploadedData) {
- videoToLoad = uploadedData;
- if (cachedUpload) {
- videoBlob = cachedUpload.blob;
- }
- } else if (recordedData) {
- videoToLoad = recordedData;
- if ('blob' in recordedData && recordedData.blob) {
- videoBlob = recordedData.blob;
- }
- }
-
- if (videoToLoad) {
- if (lastLoadedVideoIdRef.current !== videoToLoad.videoId && videoClipsRef.current.length === 0) {
- lastLoadedVideoIdRef.current = videoToLoad.videoId;
-
- setVideoUrl(videoToLoad.url);
- setVideoId(videoToLoad.videoId);
- if (videoRef.current) {
- videoRef.current.src = videoToLoad.url;
- }
- setVideoDuration(videoToLoad.duration);
- setTrimRange({ start: 0, end: videoToLoad.duration });
- const defaultFragments = generateDefaultZoomFragments(videoToLoad.duration);
- setZoomFragments(defaultFragments);
-
- if ('aspectRatio' in videoToLoad) {
- setAspectRatio(videoToLoad.aspectRatio || "auto");
- if (videoToLoad.width && videoToLoad.height) {
- setVideoDimensions({ width: videoToLoad.width, height: videoToLoad.height });
- }
- }
-
- if (videoBlob && videoBlob.size > 0) {
- setVideoBlob(videoBlob);
-
- const fileName = 'fileName' in videoToLoad
- ? (videoToLoad.fileName as string)
- : `Recording-${videoToLoad.videoId}.webm`;
- const width = 'width' in videoToLoad ? (videoToLoad.width as number) : 1920;
- const height = 'height' in videoToLoad ? (videoToLoad.height as number) : 1080;
-
- try {
- let libraryVideo = await findExistingVideo(fileName, videoBlob.size);
-
- if (!libraryVideo) {
- libraryVideo = await addVideoToLibraryWithMetadata({
- blob: videoBlob,
- fileName,
- duration: videoToLoad.duration,
- width,
- height,
- });
- }
-
- videoBlobsRef.current.set(libraryVideo.id, videoBlob);
- videoUrlsRef.current.set(libraryVideo.id, videoToLoad.url);
- // Cache per-clip audio state + update global videoHasAudioTrack state
- const hasAudio = libraryVideo.hasAudio !== false;
- clipAudioStateRef.current.set(libraryVideo.id, hasAudio);
- setVideoHasAudioTrack(hasAudio);
- if (!hasAudio) setMuteOriginalAudio(true);
-
- const newClip: VideoTrackClip = {
- id: crypto.randomUUID(),
- libraryVideoId: libraryVideo.id,
- name: libraryVideo.fileName,
- startTime: 0,
- duration: libraryVideo.duration,
- trimStart: 0,
- trimEnd: libraryVideo.duration,
- thumbnailUrl: libraryVideo.thumbnailUrl,
- hasCamera: 'cameraUrl' in videoToLoad && !!videoToLoad.cameraUrl,
- };
-
- activeClipIdRef.current = newClip.id;
- activeClipDataRef.current = newClip;
-
- setVideoClips([newClip]);
- setVideosLibraryRefresh(prev => prev + 1);
- } catch (e) {
- console.warn("Failed to add video to library:", e);
- }
- }
-
- if ('isRecordedVideo' in videoToLoad && videoToLoad.isRecordedVideo) {
- setIsRecordedVideo(true);
- } else {
- setIsRecordedVideo(false);
- }
-
- // Pick up camera track + config saved at record-time.
- // Only the recorded-video branch carries these fields.
- if ('cameraUrl' in videoToLoad && videoToLoad.cameraUrl) {
- setCameraUrl(videoToLoad.cameraUrl);
- } else {
- setCameraUrl(null);
- }
- if ('cameraConfig' in videoToLoad && videoToLoad.cameraConfig) {
- setCameraConfig(videoToLoad.cameraConfig);
- } else {
- setCameraConfig(null);
- }
-
- setTimeout(() => {
- clearHistory();
- }, 200);
- }
- }
-
- } catch (error) {
- console.error("Error loading video:", error);
- }
- };
-
- loadVideo();
-
- // Re-check when page becomes visible (user navigates back or uploads new video)
- const handleVisibilityChange = () => {
- if (!document.hidden) {
- loadVideo();
- }
- };
-
- document.addEventListener("visibilitychange", handleVisibilityChange);
- return () => document.removeEventListener("visibilitychange", handleVisibilityChange);
- }, [loadUploadedVideo, clearHistory]);
-
- useEffect(() => {
- if (uploadedImages.length > 0) {
- localStorage.setItem("openvid-uploaded-images", JSON.stringify(uploadedImages));
- }
- }, [uploadedImages]);
-
- useEffect(() => {
- if (videoRef.current) {
- videoRef.current.muted = muteOriginalAudio;
- }
- }, [muteOriginalAudio]);
-
- // Keyboard shortcuts for undo/redo
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- const target = e.target as HTMLElement;
- const isInputFocused = target.tagName === 'INPUT' ||
- target.tagName === 'TEXTAREA' ||
- target.isContentEditable;
-
- if (isInputFocused) return;
-
- if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
- e.preventDefault();
- if (canUndo) {
- undo();
- }
- }
-
- if (((e.ctrlKey || e.metaKey) && e.key === 'y') ||
- ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'z')) {
- e.preventDefault();
- if (canRedo) {
- redo();
- }
- }
- };
-
- window.addEventListener('keydown', handleKeyDown);
- return () => window.removeEventListener('keydown', handleKeyDown);
- }, [undo, redo, canUndo, canRedo]);
-
- const togglePlayPause = useCallback(() => {
- if (videoRef.current) {
- if (isPlaying) {
- videoRef.current.pause();
- const clips = videoClipsRef.current;
- if (clips.length > 0 && activeClipDataRef.current) {
- const activeClip = activeClipDataRef.current;
- const offsetInClip = videoRef.current.currentTime - activeClip.trimStart;
- const timelineTime = activeClip.startTime + offsetInClip;
- setCurrentTime(timelineTime);
- syncAudioPlayback(timelineTime, false);
- } else {
- syncAudioPlayback(currentTime, false);
- }
- } else {
- const clips = videoClipsRef.current;
- let startTime = currentTime;
-
- if (trimRange.end > 0) {
- if (startTime < trimRange.start || startTime >= trimRange.end) {
- startTime = trimRange.start;
- setCurrentTime(startTime);
- }
- }
-
- if (clips.length > 0) {
- const clipAtTime = findActiveClipAtTime(startTime);
- if (clipAtTime) {
- if (clipAtTime.id !== activeClipIdRef.current) {
- const url = videoUrlsRef.current.get(clipAtTime.libraryVideoId);
- if (url && videoRef.current) {
- activeClipIdRef.current = clipAtTime.id;
- activeClipDataRef.current = clipAtTime;
- videoRef.current.src = url;
-
- const clipTime = timelineToClipTime(startTime, clipAtTime);
- const onCanPlay = () => {
- if (videoRef.current) {
- videoRef.current.playbackRate = 1.0;
- videoRef.current.currentTime = clipTime;
- const clipHasAudio = clipAudioStateRef.current.get(clipAtTime.libraryVideoId);
- videoRef.current.muted = muteOriginalAudioRef.current || clipHasAudio === false;
- videoRef.current.play().catch(() => { });
- syncAudioPlayback(startTime, true);
- }
- videoRef.current?.removeEventListener('canplay', onCanPlay);
- };
- videoRef.current.addEventListener('canplay', onCanPlay);
- setIsPlaying(true);
- return;
- }
- } else {
- activeClipIdRef.current = clipAtTime.id;
- activeClipDataRef.current = clipAtTime; // Keep data ref in sync (clip may have moved positions)
- const clipTime = timelineToClipTime(startTime, clipAtTime);
- videoRef.current.currentTime = clipTime;
- }
- } else if (clips.length === 1) {
- const clip = clips[0];
- activeClipIdRef.current = clip.id;
- activeClipDataRef.current = clip;
- videoRef.current.currentTime = clip.trimStart;
- setCurrentTime(clip.startTime);
- }
- } else {
- videoRef.current.currentTime = startTime;
- }
-
- const playPromise = videoRef.current.play();
- if (playPromise !== undefined) {
- playPromise.catch(error => {
- if (error.name !== 'AbortError') {
- console.warn('Play interrupted:', error);
- }
- });
- }
- syncAudioPlayback(startTime, true);
- }
- setIsPlaying(!isPlaying);
- }
- }, [isPlaying, currentTime, trimRange.start, trimRange.end, syncAudioPlayback, findActiveClipAtTime, timelineToClipTime]);
-
- // Smooth time update using requestAnimationFrame
- const updateTimeSmoothRef = useRef<() => void>(() => { });
-
- useEffect(() => {
- updateTimeSmoothRef.current = () => {
- if (justEndedRef.current) return;
- if (isSwitchingClipRef.current) {
- if (isPlaying && !isDraggingPlayhead) {
- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);
- }
- return;
- }
-
- if (videoRef.current && !isDraggingPlayhead) {
- const clips = videoClipsRef.current;
-
- if (clips.length > 0) {
- const currentVideoTime = videoRef.current.currentTime;
-
- let activeClip: VideoTrackClip | null = null;
-
- if (activeClipDataRef.current && activeClipDataRef.current.id === activeClipIdRef.current) {
- activeClip = activeClipDataRef.current;
- } else {
- const foundByIdActiveClip = clips.find(c => c.id === activeClipIdRef.current);
-
- if (foundByIdActiveClip) {
- activeClip = foundByIdActiveClip;
- } else if (clips.length === 1) {
- activeClip = clips[0];
- } else {
- activeClip = clips[0];
- }
- }
-
- if (!activeClip) {
- if (isPlaying && !isDraggingPlayhead) {
- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);
- }
- return;
- }
-
- if (!isSwitchingClipRef.current && activeClipIdRef.current !== activeClip.id) {
- activeClipIdRef.current = activeClip.id;
- activeClipDataRef.current = activeClip;
- }
-
- if (clipSwitchTimeRef.current !== null) {
- setCurrentTime(clipSwitchTimeRef.current);
- if (isPlaying && !isDraggingPlayhead) {
- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);
- }
- return;
- }
-
- if (activeClip) {
- const offsetInClip = currentVideoTime - activeClip.trimStart;
- const timelineTime = activeClip.startTime + offsetInClip;
- const clipDuration = activeClip.trimEnd - activeClip.trimStart;
- const clipEndOnTimeline = activeClip.startTime + clipDuration;
-
- const reachedEndByTime = currentVideoTime >= activeClip.trimEnd;
- const reachedEndByTimeline = timelineTime >= clipEndOnTimeline;
-
- if (reachedEndByTime || reachedEndByTimeline) {
- const sortedClips = [...clips].sort((a, b) => a.startTime - b.startTime);
- const currentIndex = sortedClips.findIndex(c => c.id === activeClip!.id);
- const nextClip = sortedClips[currentIndex + 1];
-
- if (nextClip) {
- const nextUrl = videoUrlsRef.current.get(nextClip.libraryVideoId);
- const nextBlob = videoBlobsRef.current.get(nextClip.libraryVideoId);
-
- if (nextUrl && videoRef.current) {
- const nextClipSnapshot = { ...nextClip }; // copia inmutable
-
- activeClipIdRef.current = nextClipSnapshot.id;
- activeClipDataRef.current = nextClipSnapshot;
- clipSwitchTimeRef.current = nextClipSnapshot.startTime;
- isSwitchingClipRef.current = true;
-
- const currentVideo = videoRef.current;
- currentVideo.pause();
- currentVideo.src = nextUrl;
-
- const startPlayback = () => {
- clipSwitchTimeRef.current = null;
- isSwitchingClipRef.current = false;
- justEndedRef.current = false;
- currentVideo.playbackRate = 1.0;
- const nextClipHasAudio = clipAudioStateRef.current.get(nextClipSnapshot.libraryVideoId);
- currentVideo.muted = muteOriginalAudioRef.current || nextClipHasAudio === false;
- currentVideo.play().catch(e => {
- if (e.name !== 'AbortError') console.warn('Play interrupted:', e);
- });
- setIsPlaying(true);
- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);
- };
-
- const onCanPlay = () => {
- if (currentVideo) {
- const targetTime = nextClipSnapshot.trimStart;
- if (targetTime < 0.01) {
- currentVideo.currentTime = 0;
- startPlayback();
- } else {
- const onSeeked = () => {
- startPlayback();
- currentVideo.removeEventListener('seeked', onSeeked);
- };
- currentVideo.addEventListener('seeked', onSeeked);
- currentVideo.currentTime = targetTime;
- }
- }
- currentVideo?.removeEventListener('canplay', onCanPlay);
- };
- currentVideo.addEventListener('canplay', onCanPlay);
-
- setCurrentTime(nextClipSnapshot.startTime);
- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);
- return;
- }
- } else {
- videoRef.current.pause();
- syncAudioPlayback(clipEndOnTimeline, false);
- setIsPlaying(false);
- justEndedRef.current = true;
- setCurrentTime(clipEndOnTimeline);
- setTimeout(() => { justEndedRef.current = false; }, 300);
- return;
- }
- }
-
- if (trimRange.end > 0 && timelineTime >= trimRange.end) {
- videoRef.current.pause();
- syncAudioPlayback(timelineTime, false);
- setIsPlaying(false);
- justEndedRef.current = true;
- setCurrentTime(trimRange.end);
- setTimeout(() => { justEndedRef.current = false; }, 300);
- return;
- }
-
- setCurrentTime(timelineTime);
- syncAudioPlayback(timelineTime, true);
- }
- } else {
- const currentVideoTime = videoRef.current.currentTime;
-
- if (trimRange.end > 0 && currentVideoTime >= trimRange.end) {
- videoRef.current.pause();
- syncAudioPlayback(currentVideoTime, false);
- setIsPlaying(false);
- justEndedRef.current = true;
- setCurrentTime(trimRange.end);
- setTimeout(() => { justEndedRef.current = false; }, 300);
- return;
- }
-
- setCurrentTime(currentVideoTime);
- syncAudioPlayback(currentVideoTime, true);
- }
- }
- if (isPlaying && !isDraggingPlayhead) {
- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);
- }
- };
- }, [isPlaying, isDraggingPlayhead, trimRange.end, syncAudioPlayback]);
-
- // Start/stop animation frame loop based on playing state
- useEffect(() => {
- if (isPlaying && !isDraggingPlayhead) {
- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);
- } else {
- if (animationFrameRef.current) {
- cancelAnimationFrame(animationFrameRef.current);
- animationFrameRef.current = null;
- }
- }
-
- return () => {
- if (animationFrameRef.current) {
- cancelAnimationFrame(animationFrameRef.current);
- }
- };
- }, [isPlaying, isDraggingPlayhead]);
-
- const handleTimeUpdate = () => {
- if (videoRef.current && !isPlaying && !justEndedRef.current && !isSeekingToClipRef.current) {
- const clips = videoClipsRef.current;
- if (clips.length > 0 && activeClipDataRef.current) {
- const activeClip = activeClipDataRef.current;
- const offsetInClip = videoRef.current.currentTime - activeClip.trimStart;
- const timelineTime = activeClip.startTime + offsetInClip;
- setCurrentTime(timelineTime);
- } else {
- setCurrentTime(videoRef.current.currentTime);
- }
- }
- };
-
- const handlePlayheadDragStart = useCallback(() => {
- setIsDraggingPlayhead(true);
- // Pause video during scrubbing for smoother experience
- if (videoRef.current && !videoRef.current.paused) {
- wasPlayingBeforeDragRef.current = true;
- videoRef.current.pause();
- } else {
- wasPlayingBeforeDragRef.current = false;
- }
- }, []);
-
- const handlePlayheadDragEnd = useCallback(() => {
- setIsDraggingPlayhead(false);
-
- // Always read from ref — scrubTime state may still be stale at this point
- const finalTime = scrubTimeRef.current;
-
- // Set playhead position immediately (prevents visual jump)
- setCurrentTime(finalTime);
-
- if (videoRef.current) {
- const clips = videoClipsRef.current;
-
- if (clips.length > 0) {
- const clipAtTime = findActiveClipAtTime(finalTime);
-
- if (clipAtTime) {
- const clipTime = timelineToClipTime(finalTime, clipAtTime);
-
- if (clipAtTime.id !== activeClipIdRef.current) {
- const url = videoUrlsRef.current.get(clipAtTime.libraryVideoId);
- if (url) {
- activeClipIdRef.current = clipAtTime.id;
- activeClipDataRef.current = clipAtTime;
- isSeekingToClipRef.current = true;
- const currentVideo = videoRef.current;
- currentVideo.src = url;
-
- const shouldPlay = wasPlayingBeforeDragRef.current;
- const onCanPlay = () => {
- if (currentVideo) {
- currentVideo.playbackRate = 1.0;
- currentVideo.currentTime = clipTime;
- const clipHasAudio = clipAudioStateRef.current.get(clipAtTime.libraryVideoId);
- currentVideo.muted = muteOriginalAudioRef.current || clipHasAudio === false;
- isSeekingToClipRef.current = false;
- if (shouldPlay) {
- currentVideo.play().catch(e => {
- if (e.name !== 'AbortError') console.warn('Play interrupted:', e);
- });
- setIsPlaying(true);
- syncAudioPlayback(finalTime, true);
- } else {
- syncAudioPlayback(finalTime, false);
- }
- }
- currentVideo?.removeEventListener('canplay', onCanPlay);
- };
- currentVideo.addEventListener('canplay', onCanPlay);
- return;
- }
- } else {
- videoRef.current.currentTime = clipTime;
- }
- }
- } else {
- videoRef.current.currentTime = finalTime;
- }
- }
-
- if (wasPlayingBeforeDragRef.current && videoRef.current) {
- const playPromise = videoRef.current.play();
- if (playPromise !== undefined) {
- playPromise.catch(error => {
- if (error.name !== 'AbortError') {
- console.warn('Play interrupted:', error);
- }
- });
- }
- setIsPlaying(true);
- syncAudioPlayback(finalTime, true);
- } else {
- syncAudioPlayback(finalTime, false);
- }
- }, [syncAudioPlayback, findActiveClipAtTime, timelineToClipTime]);
-
- const handleZoomChange = useCallback((zoom: number) => {
- setTimelineZoom(zoom);
- }, []);
-
- const handleLoadedMetadata = useCallback(() => {
- if (videoRef.current) {
- videoRef.current.playbackRate = 1.0;
-
- const duration = videoRef.current.duration;
- if (isFinite(duration) && duration > 0) {
- const currentClips = videoClipsRef.current;
- if (currentClips.length <= 1) {
- setVideoDuration(duration);
- setTrimRange(prev => prev.end === 0 ? { start: 0, end: duration } : prev);
- }
- }
- }
- }, []);
-
- const skipBackward = useCallback(() => {
- if (videoRef.current) {
- const newTime = Math.max(trimRange.start, videoRef.current.currentTime - 5);
- videoRef.current.currentTime = newTime;
- setCurrentTime(newTime);
- syncAudioPlayback(newTime, isPlaying);
- }
- }, [trimRange.start, isPlaying, syncAudioPlayback]);
-
- const skipForward = useCallback(() => {
- if (videoRef.current) {
- const newTime = Math.min(trimRange.end, videoRef.current.currentTime + 5);
- videoRef.current.currentTime = newTime;
- setCurrentTime(newTime);
- syncAudioPlayback(newTime, isPlaying);
-
- if (newTime >= trimRange.end) {
- videoRef.current.pause();
- setIsPlaying(false);
- syncAudioPlayback(newTime, false);
- }
- }
- }, [trimRange.end, isPlaying, syncAudioPlayback]);
-
- const handleSeek = useCallback((time: number) => {
- scrubTimeRef.current = time;
- setScrubTime(time);
- setCurrentTime(time);
-
- if (videoRef.current && !isDraggingPlayhead) {
- const clips = videoClipsRef.current;
-
- if (clips.length > 0) {
- const clipAtTime = findActiveClipAtTime(time);
-
- if (clipAtTime) {
- const clipTime = timelineToClipTime(time, clipAtTime);
- const currentUrl = videoRef.current.src;
- const targetUrl = videoUrlsRef.current.get(clipAtTime.libraryVideoId);
- const needsClipSwitch = clipAtTime.id !== activeClipIdRef.current
- || (targetUrl && currentUrl !== targetUrl);
-
- if (needsClipSwitch && targetUrl) {
- const wasPlaying = isPlaying;
-
- if (videoRef.current && !videoRef.current.paused) {
- videoRef.current.pause();
- }
- if (animationFrameRef.current) {
- cancelAnimationFrame(animationFrameRef.current);
- animationFrameRef.current = null;
- }
-
- activeClipIdRef.current = clipAtTime.id;
- activeClipDataRef.current = clipAtTime;
- isSeekingToClipRef.current = true;
- isSwitchingClipRef.current = true; // ← también marcar como switching
-
- const currentVideo = videoRef.current;
- currentVideo.src = targetUrl;
-
- const onCanPlay = () => {
- if (currentVideo) {
- currentVideo.playbackRate = 1.0;
- currentVideo.currentTime = clipTime;
- const clipHasAudio = clipAudioStateRef.current.get(clipAtTime.libraryVideoId);
- currentVideo.muted = muteOriginalAudioRef.current || clipHasAudio === false;
- isSeekingToClipRef.current = false;
- isSwitchingClipRef.current = false; // ← limpiar flag
- clipSwitchTimeRef.current = null;
-
- if (wasPlaying) {
- currentVideo.play().catch(e => {
- if (e.name !== 'AbortError') console.warn('Play interrupted:', e);
- });
- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);
- }
- }
- currentVideo?.removeEventListener('canplay', onCanPlay);
- };
- currentVideo.addEventListener('canplay', onCanPlay);
- syncAudioPlayback(time, false);
- return;
- } else {
- if ('fastSeek' in videoRef.current && typeof videoRef.current.fastSeek === 'function') {
- videoRef.current.fastSeek(clipTime);
- } else {
- videoRef.current.currentTime = clipTime;
- }
- }
- }
- } else {
- if ('fastSeek' in videoRef.current && typeof videoRef.current.fastSeek === 'function') {
- videoRef.current.fastSeek(time);
- } else {
- videoRef.current.currentTime = time;
- }
- }
- syncAudioPlayback(time, isPlaying);
- }
- }, [isDraggingPlayhead, isPlaying, syncAudioPlayback, findActiveClipAtTime, timelineToClipTime]);
-
- const handleImageUpload = (file: File) => {
- const reader = new FileReader();
- reader.onload = (e) => {
- const dataUrl = e.target?.result as string;
- if (dataUrl) {
- setUploadedImages(prev => [dataUrl, ...prev]);
- setSelectedImageUrl(dataUrl);
- }
- };
- reader.readAsDataURL(file);
- };
-
- const handleImageSelect = (url: string) => {
- if (backgroundTab === "wallpaper") {
- setUnsplashBgUrl(url);
- } else {
- setSelectedImageUrl(url);
- }
- };
-
- const handleWallpaperSelect = (index: number) => {
- setSelectedWallpaper(index);
- setUnsplashBgUrl("");
- };
-
- const handleImageRemove = (url: string) => {
- setUploadedImages(prev => prev.filter(img => img !== url));
- if (selectedImageUrl === url) {
- setSelectedImageUrl("");
- }
- };
-
- // Background tab change handler
- const handleBackgroundTabChange = (tab: BackgroundTab) => {
- setBackgroundTab(tab);
- };
-
- // Handler para cambio de color/gradiente
- const handleBackgroundColorChange = (config: BackgroundColorConfig) => {
- setBackgroundColorConfig(config);
- };
-
- // Zoom fragment handlers
- const handleSelectZoomFragment = useCallback((fragmentId: string | null) => {
- setSelectedZoomFragmentId(fragmentId);
- // Clear other selections when selecting zoom fragment (mutual exclusivity)
- if (fragmentId) {
- setSelectedAudioTrackId(null);
- setSelectedVideoClipId(null);
- setSelectedElementId(null);
- }
- }, []);
-
- const handleActivateZoomTool = useCallback(() => {
- setActiveTool("zoom");
- }, []);
-
- // Default duration for new zoom fragments
- const DEFAULT_ZOOM_FRAGMENT_DURATION = 2;
-
- const handleAddZoomFragment = useCallback((startTime: number) => {
- // Find valid position avoiding overlaps - use ref to get latest fragments
- const validPosition = findValidFragmentPosition(
- startTime,
- DEFAULT_ZOOM_FRAGMENT_DURATION,
- zoomFragmentsRef.current,
- videoDuration
- );
-
- if (!validPosition) {
- return;
- }
-
- const newFragment = createZoomFragment(validPosition.startTime, validPosition.endTime);
- setZoomFragments(prev => [...prev, newFragment].sort((a, b) => a.startTime - b.startTime));
- setSelectedZoomFragmentId(newFragment.id);
- setActiveTool("zoom"); // Switch to zoom tool when adding
- }, [videoDuration]);
-
- const handleUpdateZoomFragment = useCallback((fragmentId: string, updates: Partial<ZoomFragment>) => {
- setZoomFragments(prev => prev.map(f =>
- f.id === fragmentId ? { ...f, ...updates } : f
- ).sort((a, b) => a.startTime - b.startTime));
- }, []);
-
- const handleDeleteZoomFragment = useCallback((fragmentId: string) => {
- setZoomFragments(prev => prev.filter(f => f.id !== fragmentId));
- if (selectedZoomFragmentId === fragmentId) {
- setSelectedZoomFragmentId(null);
- }
- }, [selectedZoomFragmentId]);
-
- // Get currently selected zoom fragment - memoized
- const selectedZoomFragment = useMemo(() =>
- zoomFragments.find(f => f.id === selectedZoomFragmentId) || null,
- [zoomFragments, selectedZoomFragmentId]
- );
-
- // Calcular el CSS del background actual - memoized
- const backgroundColorCss = useMemo((): string | undefined => {
- if (backgroundTab === "color" && backgroundColorConfig) {
- if (backgroundColorConfig.type === "solid") {
- return backgroundColorConfig.config.color;
- } else {
- return gradientToCss(backgroundColorConfig.config);
- }
- }
- return undefined;
- }, [backgroundTab, backgroundColorConfig]);
-
- // Fullscreen toggle handler
- const toggleFullscreen = useCallback(async () => {
- if (!editorAreaRef.current) return;
-
- try {
- if (!document.fullscreenElement) {
- await editorAreaRef.current.requestFullscreen();
- setIsFullscreen(true);
- } else {
- await document.exitFullscreen();
- setIsFullscreen(false);
- }
- } catch (error) {
- console.error("Error toggling fullscreen:", error);
- }
- }, []);
-
- // Listen for fullscreen changes (e.g., pressing Escape)
- useEffect(() => {
- const handleFullscreenChange = () => {
- setIsFullscreen(!!document.fullscreenElement);
- };
-
- document.addEventListener("fullscreenchange", handleFullscreenChange);
- return () => document.removeEventListener("fullscreenchange", handleFullscreenChange);
- }, []);
-
- // Keyboard shortcuts for zoom fragments
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
- return;
- }
-
- if ((e.ctrlKey || e.metaKey) && e.key === 'c' && selectedElementId) {
- e.preventDefault();
- copySelectedElement();
- return;
- }
-
- if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
- e.preventDefault();
- pasteElement();
- return;
- }
-
- if ((e.key === "Delete" || e.key === "Backspace") && selectedElementId) {
- e.preventDefault();
- deleteCanvasElement(selectedElementId);
- return; // Prevent zoom fragment deletion if element is selected
- }
-
- if ((e.key === "Delete" || e.key === "Backspace") && selectedVideoClipId) {
- e.preventDefault();
- handleDeleteVideoClip(selectedVideoClipId);
- return;
- }
-
- if ((e.key === "Delete" || e.key === "Backspace") && selectedAudioTrackId) {
- e.preventDefault();
- handleDeleteAudioTrack(selectedAudioTrackId);
- setSelectedAudioTrackId(null);
- return;
- }
-
- if ((e.key === "Delete" || e.key === "Backspace") && selectedZoomFragmentId) {
- e.preventDefault();
- handleDeleteZoomFragment(selectedZoomFragmentId);
- }
-
- if (e.key === "Escape") {
- e.preventDefault();
- if (selectedElementId) {
- setSelectedElementId(null);
- } else if (selectedVideoClipId) {
- setSelectedVideoClipId(null);
- } else if (selectedAudioTrackId) {
- setSelectedAudioTrackId(null);
- } else if (selectedZoomFragmentId) {
- setSelectedZoomFragmentId(null);
- }
- }
-
- };
-
- document.addEventListener("keydown", handleKeyDown);
- return () => document.removeEventListener("keydown", handleKeyDown);
- }, [selectedElementId, selectedZoomFragmentId, selectedAudioTrackId, selectedVideoClipId, deleteCanvasElement, handleDeleteZoomFragment, handleDeleteAudioTrack, handleDeleteVideoClip, copySelectedElement, pasteElement]);
-
- useEffect(() => {
- const checkMobile = () => {
- if (window.innerWidth < 768) {
- setIsControlPanelOpen(false);
- }
- };
- checkMobile();
- window.addEventListener("resize", checkMobile);
- return () => window.removeEventListener("resize", checkMobile);
- }, []);
-
- const handleAspectRatioChange = useCallback((ratio: AspectRatio) => {
- setAspectRatio(ratio);
- }, []);
-
- const handleCustomDimensionsChange = useCallback((dimensions: { width: number; height: number }) => {
- setCustomDimensions(dimensions);
- }, []);
-
- const handleOpenCropper = useCallback(() => {
- setIsCropperOpen(true);
- }, []);
-
- const handleCloseCropper = useCallback(() => {
- setIsCropperOpen(false);
- }, []);
-
- const handleCropApply = useCallback((crop: CropArea) => {
- setCropArea(crop);
- }, []);
-
- // Only show camera if the active clip has camera support
- const activeClip = findActiveClipAtTime(currentTime);
- const shouldShowCamera = activeClip?.hasCamera === true;
- const effectiveCameraUrl = shouldShowCamera ? cameraUrl : null;
-
- return (
- <div className="flex flex-col h-screen w-full bg-[#0E0E12] text-white/60 font-sans overflow-hidden select-none">
- <div className="flex flex-1 overflow-hidden">
- <div className="hidden lg:flex">
- <ToolsSidebar
- activeTool={activeTool}
- onToolChange={setActiveTool}
- onVideoUpload={handleVideoUpload}
- isUploading={isUploading}
- selectedZoomFragmentId={selectedZoomFragmentId}
- selectedAudioTrackId={selectedAudioTrackId}
- selectedVideoClipId={selectedVideoClipId}
- selectedElementId={selectedElementId}
- newVideosCount={newVideosCount}
- />
- </div>
-
- <div className="hidden lg:block">
- <AnimatePresence mode="wait">
- {isControlPanelOpen && (
- <motion.div
- key="control-panel"
- initial={{ x: -320, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- exit={{ x: -320, opacity: 0 }}
- transition={{ duration: 0.3, ease: "easeInOut" }}
- >
- <Suspense fallback={
- <div className="w-[320px] h-screen bg-[#141417] border-r border-white/10 flex items-center justify-center">
- <LoadingSpinner message="Cargando panel..." />
- </div>
- }>
- <ControlPanel
- activeTool={activeTool}
- backgroundTab={backgroundTab}
- onVideoAudioToggle={handleVideoAudioToggle}
- onBackgroundTabChange={handleBackgroundTabChange}
- selectedWallpaper={selectedWallpaper}
- onWallpaperSelect={handleWallpaperSelect}
- backgroundBlur={backgroundBlur}
- onBackgroundBlurChange={setBackgroundBlur}
- padding={padding}
- onPaddingChange={setPadding}
- roundedCorners={roundedCorners}
- onRoundedCornersChange={handleRoundedCornersChange}
- shadows={shadows}
- onShadowsChange={setShadows}
- uploadedImages={uploadedImages}
- selectedImageUrl={selectedImageUrl}
- onImageUpload={handleImageUpload}
- onImageSelect={handleImageSelect}
- onImageRemove={handleImageRemove}
- backgroundColorConfig={backgroundColorConfig}
- onBackgroundColorChange={handleBackgroundColorChange}
- onTogglePanel={() => setIsControlPanelOpen(!isControlPanelOpen)}
- isOpen={isControlPanelOpen}
- zoomFragments={zoomFragments}
- selectedZoomFragment={selectedZoomFragment}
- onSelectZoomFragment={handleSelectZoomFragment}
- onAddZoomFragment={() => handleAddZoomFragment(currentTime)}
- onUpdateZoomFragment={handleUpdateZoomFragment}
- onDeleteZoomFragment={handleDeleteZoomFragment}
- videoUrl={videoUrl}
- videoThumbnail={selectedZoomFragment ? getThumbnailForTime(selectedZoomFragment.startTime)?.dataUrl ?? null : null}
- currentTime={currentTime}
- getThumbnailForTime={getThumbnailForTime}
- videoDimensions={customAspectRatio}
- mockupId={mockupId}
- mockupConfig={mockupConfig}
- onMockupChange={handleMockupChange}
- onMockupConfigChange={handleMockupConfigChange}
- onAddCanvasElement={addCanvasElement}
- selectedCanvasElement={canvasElements.find(el => el.id === selectedElementId) || null}
- onUpdateCanvasElement={updateCanvasElement}
- onDeleteCanvasElement={deleteCanvasElement}
- onBringToFront={bringToFront}
- onSendToBack={sendToBack}
- uploadedAudios={uploadedAudios}
- audioTracks={audioTracks}
- muteOriginalAudio={muteOriginalAudio}
- masterVolume={masterVolume}
- onAudioUpload={handleAudioUpload}
- onAudioDelete={handleAudioDelete}
- onAddAudioTrack={handleAddAudioTrack}
- onUpdateAudioTrack={handleUpdateAudioTrack}
- onDeleteAudioTrack={handleDeleteAudioTrack}
- onToggleMuteOriginalAudio={handleToggleMuteOriginalAudio}
- onMasterVolumeChange={handleMasterVolumeChange}
- videoDuration={videoDuration}
- onAddVideoToTrack={handleAddVideoToTrack}
- onRemoveVideoFromTrack={handleRemoveVideoFromTrack}
- onVideoUploadToLibrary={handleVideoUploadToLibrary}
- onVideoDeleteFromTrack={handleDeleteVideoFromLibrary}
- videosInTrackIds={videosInTrackIds}
- videosLibraryRefresh={videosLibraryRefresh}
- isVideoUploading={isUploading}
- cameraUrl={cameraUrl}
- cameraConfig={cameraConfig}
- onCameraConfigChange={handleCameraConfigChange}
- />
- </Suspense>
- </motion.div>
- )}
- </AnimatePresence>
- </div>
-
- <div
- ref={editorAreaRef}
- className="flex-1 bg-[#09090B] flex flex-col relative overflow-hidden min-w-0"
- >
- <AnimatePresence>
- {!isControlPanelOpen && (
- <TooltipAction label="Abrir panel de control" side="right">
- <motion.button
- initial={{ x: -100, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- exit={{ x: -100, opacity: 0 }}
- transition={{ duration: 0.3, ease: "easeInOut", delay: 0.15 }}
- whileHover={{ scale: 1.1 }}
- whileTap={{ scale: 0.9 }}
- onClick={() => setIsControlPanelOpen(true)}
- className="absolute top-2 left-4 z-50 p-2 flex items-center gap-2 squircle-element bg-[#18181b] border border-white/10 text-white hover:bg-[#252529] transition-all duration-200 shadow-lg"
- >
- <Link href="/" className="block sm:hidden"><Image src="/svg/logo-openvid.svg" alt="Logo" width={24} height={24} className="hover:opacity-80 transition-opacity" /></Link>
- <Icon icon="lucide:sidebar-open" width="20" className="hidden sm:block"
- />
- </motion.button>
- </TooltipAction>
- )}
- </AnimatePresence>
-
- <EditorTopBar
- onExport={handleExport}
- exportProgress={exportProgress}
- hasTransparentBackground={selectedWallpaper === -1}
- onUndo={undo}
- onRedo={redo}
- canUndo={canUndo}
- canRedo={canRedo}
- />
-
- <VideoCanvas
- ref={canvasRef}
- videoUrl={videoUrl}
- videoRef={videoRef}
- padding={padding}
- roundedCorners={roundedCorners}
- shadows={shadows}
- aspectRatio={aspectRatio}
- customAspectRatio={customAspectRatio}
- cropArea={cropArea}
- backgroundTab={backgroundTab}
- selectedWallpaper={selectedWallpaper}
- backgroundBlur={backgroundBlur}
- selectedImageUrl={selectedImageUrl}
- unsplashOverrideUrl={unsplashBgUrl}
- backgroundColorCss={backgroundColorCss}
- onTimeUpdate={handleTimeUpdate}
- onLoadedMetadata={handleLoadedMetadata}
- isScrubbing={isDraggingPlayhead}
- scrubTime={scrubTime}
- getThumbnailForTime={getThumbnailForTime}
- zoomFragments={zoomFragments}
- currentTime={currentTime}
- mockupId={mockupId}
- mockupConfig={mockupConfig ?? DEFAULT_MOCKUP_CONFIG}
- onVideoUpload={handleVideoUpload}
- isUploading={isUploading}
- videoTransform={videoTransform}
- onVideoTransformChange={setVideoTransform}
- canvasElements={canvasElements}
- selectedElementId={selectedElementId}
- onElementUpdate={updateCanvasElement}
- onElementSelect={selectCanvasElement}
- cameraUrl={effectiveCameraUrl}
- cameraConfig={cameraConfig}
- onCameraConfigChange={handleCameraConfigChange}
- onCameraClick={handleCameraClick}
- onEnded={() => {
- const clips = videoClipsRef.current;
- if (clips.length > 1) {
- const sortedClips = [...clips].sort((a, b) => a.startTime - b.startTime);
- const currentIndex = sortedClips.findIndex(c => c.id === activeClipIdRef.current);
- if (currentIndex >= 0 && currentIndex < sortedClips.length - 1) {
- return;
- }
- }
-
- setIsPlaying(false);
- justEndedRef.current = true;
- const endTime = trimRange.end > 0 ? trimRange.end : videoDuration;
- setCurrentTime(endTime);
- setTimeout(() => {
- justEndedRef.current = false;
- }, 300);
- }}
- />
-
- <PlayerControls
- isPlaying={isPlaying}
- currentTime={currentTime}
- videoDuration={videoDuration}
- aspectRatio={aspectRatio}
- customAspectRatio={aspectRatio === "custom" ? customDimensions : videoDimensions}
- isFullscreen={isFullscreen}
- zoomLevel={timelineZoom}
- onTogglePlayPause={togglePlayPause}
- onSkipBackward={skipBackward}
- onSkipForward={skipForward}
- onToggleFullscreen={toggleFullscreen}
- onAspectRatioChange={handleAspectRatioChange}
- onCustomAspectRatioChange={handleCustomDimensionsChange}
- onOpenCropper={handleOpenCropper}
- onZoomChange={handleZoomChange}
- />
-
- <Suspense fallback={<TimelineSkeleton />}>
- <Timeline
- videoDuration={videoDuration}
- currentTime={currentTime}
- onSeek={handleSeek}
- videoUrl={videoUrl}
- zoomLevel={timelineZoom}
- isDraggingPlayhead={isDraggingPlayhead}
- onDragStart={handlePlayheadDragStart}
- onDragEnd={handlePlayheadDragEnd}
- trimRange={trimRange}
- onTrimChange={setTrimRange}
- videoClips={videoClips}
- selectedVideoClipId={selectedVideoClipId}
- onSelectVideoClip={handleSelectVideoClip}
- onUpdateVideoClip={handleUpdateVideoClip}
- onDeleteVideoClip={handleDeleteVideoClip}
- zoomFragments={zoomFragments}
- selectedZoomFragmentId={selectedZoomFragmentId}
- onSelectZoomFragment={handleSelectZoomFragment}
- onAddZoomFragment={handleAddZoomFragment}
- onUpdateZoomFragment={handleUpdateZoomFragment}
- onActivateZoomTool={handleActivateZoomTool}
- audioTracks={audioTracks}
- uploadedAudios={uploadedAudios}
- selectedAudioTrackId={selectedAudioTrackId}
- onSelectAudioTrack={handleSelectAudioTrack}
- onUpdateAudioTrack={handleUpdateAudioTrack}
- />
- </Suspense>
-
- </div>
-
- </div>
-
- <MobileToolsMenu
- activeTool={activeTool}
- onToolChange={setActiveTool}
- onVideoUpload={handleVideoUpload}
- isUploading={isUploading}
- onOpenToolPanel={() => setIsMobileControlPanelOpen(true)}
- />
-
- <MobileControlPanel
- isOpen={isMobileControlPanelOpen}
- onClose={() => setIsMobileControlPanelOpen(false)}
- activeTool={activeTool}
- backgroundTab={backgroundTab}
- onBackgroundTabChange={handleBackgroundTabChange}
- selectedWallpaper={selectedWallpaper}
- onWallpaperSelect={handleWallpaperSelect}
- backgroundBlur={backgroundBlur}
- onBackgroundBlurChange={setBackgroundBlur}
- padding={padding}
- onPaddingChange={setPadding}
- roundedCorners={roundedCorners}
- onRoundedCornersChange={handleRoundedCornersChange}
- shadows={shadows}
- onShadowsChange={setShadows}
- uploadedImages={uploadedImages}
- selectedImageUrl={selectedImageUrl}
- onImageUpload={handleImageUpload}
- onImageSelect={handleImageSelect}
- onImageRemove={handleImageRemove}
- backgroundColorConfig={backgroundColorConfig}
- onBackgroundColorChange={handleBackgroundColorChange}
- zoomFragments={zoomFragments}
- selectedZoomFragment={selectedZoomFragment}
- onSelectZoomFragment={handleSelectZoomFragment}
- onAddZoomFragment={() => handleAddZoomFragment(currentTime)}
- onUpdateZoomFragment={handleUpdateZoomFragment}
- onDeleteZoomFragment={handleDeleteZoomFragment}
- videoUrl={videoUrl}
- videoThumbnail={selectedZoomFragment ? getThumbnailForTime(selectedZoomFragment.startTime)?.dataUrl ?? null : null}
- currentTime={currentTime}
- getThumbnailForTime={getThumbnailForTime}
- videoDimensions={videoDimensions}
- mockupId={mockupId}
- mockupConfig={mockupConfig}
- onMockupChange={handleMockupChange}
- onMockupConfigChange={handleMockupConfigChange}
- onAddCanvasElement={addCanvasElement}
- selectedCanvasElement={canvasElements.find(el => el.id === selectedElementId) || null}
- onUpdateCanvasElement={updateCanvasElement}
- onDeleteCanvasElement={deleteCanvasElement}
- onBringToFront={bringToFront}
- onSendToBack={sendToBack}
- uploadedAudios={uploadedAudios}
- audioTracks={audioTracks}
- muteOriginalAudio={muteOriginalAudio}
- masterVolume={masterVolume}
- onAudioUpload={handleAudioUpload}
- onAudioDelete={handleAudioDelete}
- onAddAudioTrack={handleAddAudioTrack}
- onUpdateAudioTrack={handleUpdateAudioTrack}
- onDeleteAudioTrack={handleDeleteAudioTrack}
- onToggleMuteOriginalAudio={handleToggleMuteOriginalAudio}
- onMasterVolumeChange={handleMasterVolumeChange}
- videoDuration={videoDuration}
- />
-
- <Suspense fallback={null}>
- <ExportOverlay
- exportProgress={exportProgress}
- onCancel={cancelExport}
- isTransparentExport={selectedWallpaper === -1}
- />
- </Suspense>
- <Suspense fallback={null}>
- <VideoCropperModal
- isOpen={isCropperOpen}
- onClose={handleCloseCropper}
- videoUrl={videoUrl}
- onCropApply={handleCropApply}
- initialCrop={cropArea}
- />
- </Suspense>
-
- {autoTrimModalOpen && pendingAudioUpload && (
- <AudioTrimModal
- key={pendingAudioUpload.audio.id}
- isOpen={autoTrimModalOpen}
- audioName={pendingAudioUpload.audio.name}
- audioUrl={pendingAudioUpload.audio.url}
- audioDuration={pendingAudioUpload.audio.duration}
- initialTrimStart={0}
- initialTrimEnd={Math.min(pendingAudioUpload.audio.duration, videoDuration)}
- onConfirm={(trimStart, trimEnd) => {
- if (pendingAudioUpload) {
- const lastTrackEnd = audioTracks.reduce((max, track) =>
- Math.max(max, track.startTime + track.duration), 0);
-
- const newTrack: AudioTrack = {
- id: pendingAudioUpload.trackId,
- audioId: pendingAudioUpload.audio.id,
- name: pendingAudioUpload.audio.name,
- startTime: lastTrackEnd,
- duration: trimEnd - trimStart,
- trimStart: trimStart,
- volume: 1,
- loop: false,
- };
-
- setAudioTracks(prev => [...prev, newTrack]);
-
- if (audioTracks.length === 0) {
- setMuteOriginalAudio(true);
- }
- }
- setAutoTrimModalOpen(false);
- setPendingAudioUpload(null);
- }}
- onCancel={() => {
- if (pendingAudioUpload) {
- setUploadedAudios(prev => prev.filter(a => a.id !== pendingAudioUpload.audio.id));
- URL.revokeObjectURL(pendingAudioUpload.audio.url);
- }
- setAutoTrimModalOpen(false);
- setPendingAudioUpload(null);
- }}
- />
- )}
- </div>
- );
-}
\ No newline at end of file
diff --git a/app/(editor)/layout.tsx b/app/(editor)/layout.tsx
deleted file mode 100644
index e8b63d0..0000000
--- a/app/(editor)/layout.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-"use client";
-
-import { AuthProvider } from "@/hooks/useAuth";
-import { RecordingProvider } from "@/hooks/RecordingContext";
-import RecordingOverlay from "../components/ui/RecordingOverlay";
-
-export default function EditorLayout({ children }: { children: React.ReactNode }) {
- return (
- <AuthProvider>
- <RecordingProvider>
- <div className="min-h-screen bg-neutral-950">
- {children}
- </div>
- <RecordingOverlay />
- </RecordingProvider>
- </AuthProvider>
- );
-}
diff --git a/app/(home)/donate/DonateClient.tsx b/app/(home)/donate/DonateClient.tsx
deleted file mode 100644
index fab2354..0000000
--- a/app/(home)/donate/DonateClient.tsx
+++ /dev/null
@@ -1,201 +0,0 @@
-"use client";
-
-import { Icon } from "@iconify/react";
-import Link from "next/link";
-import { useState } from "react";
-import { type DONATION_METHODS } from "./page";
-
-type Method = typeof DONATION_METHODS[number];
-
-export default function DonateClient({
- methods,
- defaultMethod
-}: {
- methods: Method[];
- defaultMethod: string;
-}) {
- const [selected, setSelected] = useState<string | null>(defaultMethod);
- const [copied, setCopied] = useState<string | null>(null);
- const [qrModalSrc, setQrModalSrc] = useState<string | null>(null);
-
- const handleCopy = (text: string, key: string) => {
- const cleanText = text.replace(/\s/g, '');
- navigator.clipboard.writeText(cleanText);
- setCopied(key);
- setTimeout(() => setCopied(null), 2000);
- };
-
- return (
- <div className="min-h-screen bg-black text-white overflow-hidden pt-24 pb-16 relative">
- <div className="max-w-2xl mx-auto px-4">
-
- <Link
- href="/"
- className="inline-flex items-center gap-2 text-sm text-white/40 hover:text-white mb-12 transition-colors group font-medium"
- >
- <Icon icon="lucide:arrow-left" width="16" className="group-hover:-translate-x-1 transition-transform" />
- Volver al inicio
- </Link>
-
- <div className="mb-10">
- <h1 className="text-2xl font-semibold text-white mb-2 tracking-tight">
- Apoya el desarrollo
- </h1>
- <p className="text-white/50 text-sm leading-relaxed max-w-lg">
- openvid es una herramienta de código abierto. Tu contribución nos permite mantener los servidores activos y continuar el desarrollo de nuevas características.
- </p>
- </div>
-
- <div className="flex flex-col bg-[#0A0A0A] border border-white/10 rounded-xl overflow-hidden shadow-2xl">
- <div className="px-5 py-3 border-b border-white/10 bg-white/5 flex items-center justify-between">
- <span className="text-[10px] font-semibold uppercase tracking-[0.15em] text-white/50">
- Métodos
- </span>
- <Icon icon="lucide:shield-check" width="14" className="text-white/30" />
- </div>
-
- <div className="flex flex-col">
- {methods.map((method) => (
- <div key={method.id} className="border-b border-white/5 last:border-0">
- <button
- onClick={() => setSelected(selected === method.id ? null : method.id)}
- className="w-full flex items-center justify-between p-5 text-left transition-colors hover:bg-white/5 group"
- >
- <div className="flex items-center gap-4">
- <div className="w-9 h-9 rounded bg-[#1C1C1F] border border-white/10 flex items-center justify-center shrink-0 overflow-hidden group-hover:border-white/20 transition-colors">
- {method.image ? (
- <img src={method.image} alt={method.name} className="w-full h-full object-cover opacity-80 group-hover:opacity-100 transition-opacity" />
- ) : (
- <Icon icon={method.icon!} width="18" style={{ color: method.color }} className="opacity-80 group-hover:opacity-100 transition-opacity" />
- )}
- </div>
- <div>
- <div className="flex items-center gap-2 mb-0.5">
- <span className="text-sm font-medium text-white/90 group-hover:text-white transition-colors">{method.name}</span>
- <span className="text-[9px] uppercase tracking-wider text-white/40 border border-white/10 px-1.5 py-0.5 rounded font-medium">
- {method.tagline}
- </span>
- </div>
- <p className="text-[11px] text-white/40">{method.detail}</p>
- </div>
- </div>
- <Icon
- icon="lucide:chevron-down"
- width="16"
- className={`text-white/30 shrink-0 transition-transform duration-300 ${selected === method.id ? "rotate-180 text-white/70" : ""}`}
- />
- </button>
-
- {selected === method.id && (
- <div className="bg-[#131315] border-t border-white/5 px-5 py-6 animate-in fade-in slide-in-from-top-2 duration-200">
-
- {method.id === "yape" && (
- <div className="space-y-4 max-w-md">
- <div className="flex flex-col items-center p-5 bg-black border border-white/10 rounded-lg">
- <button
- onClick={() => setQrModalSrc(method.qrImage!)}
- className="relative w-32 h-32 bg-white rounded flex items-center justify-center overflow-hidden cursor-pointer group hover:ring-2 hover:ring-white/20 transition-all"
- >
- <img src={method.qrImage} alt="Código QR Yape" className="w-full h-full object-contain transition-transform group-hover:scale-105" />
- <div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors flex items-center justify-center">
- <Icon icon="lucide:zoom-in" width="24" className="text-black opacity-0 group-hover:opacity-60 transition-opacity" />
- </div>
- </button>
- </div>
-
- <CopyRow label="Número celular" value={method.phone!} copyKey="yape-phone" copied={copied} onCopy={handleCopy} />
- </div>
- )}
-
- {method.id === "visa" && (
- <div className="space-y-3 max-w-md">
- <CopyRow label="Cuenta BCP (Soles)" value={method.account!} copyKey="visa-account" copied={copied} onCopy={handleCopy} />
- <CopyRow label="Código de Cuenta Interbancario (CCI)" value={method.cci!} copyKey="visa-cci" copied={copied} onCopy={handleCopy} />
- </div>
- )}
-
- {method.id === "paypal" && (
- <div className="space-y-4 max-w-md">
- <CopyRow label="Correo electrónico de PayPal" value={method.email!} copyKey="paypal-email" copied={copied} onCopy={handleCopy} />
- <div className="flex items-center gap-3">
- <div className="h-px bg-white/10 flex-1"></div>
- <span className="text-[10px] uppercase tracking-widest text-white/30 font-medium">o alternativamente</span>
- <div className="h-px bg-white/10 flex-1"></div>
- </div>
- <a
- href={method.link}
- target="_blank"
- rel="noopener noreferrer"
- className="flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-lg border border-white/10 bg-white/5 hover:bg-white/10 text-sm font-medium text-white transition-colors"
- >
- <Icon icon="lucide:external-link" width="16" className="text-white/50" />
- Abrir enlace de pago directo
- </a>
- </div>
- )}
-
- </div>
- )}
- </div>
- ))}
- </div>
- </div>
- </div>
-
- {qrModalSrc && (
- <div
- className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-in fade-in duration-200"
- onClick={() => setQrModalSrc(null)}
- >
- <div
- className="relative w-full max-w-sm bg-[#131315] border border-white/10 rounded-2xl p-6 shadow-2xl flex flex-col items-center animate-in zoom-in-95 duration-200"
- onClick={(e) => e.stopPropagation()}
- >
- <div className="w-full flex justify-between items-center mb-6">
- <span className="text-sm font-semibold text-white/90 tracking-wide">Escanear código QR</span>
- <button
- onClick={() => setQrModalSrc(null)}
- className="text-white/40 hover:text-white bg-white/5 hover:bg-white/10 rounded-full p-1.5 transition-colors"
- >
- <Icon icon="lucide:x" width="18" />
- </button>
- </div>
-
- <div className="w-full aspect-square bg-white rounded-xl overflow-hidden flex items-center justify-center p-2">
- <img src={qrModalSrc} alt="QR Ampliado" className="w-full h-full object-contain" />
- </div>
-
- <button
- onClick={() => setQrModalSrc(null)}
- className="mt-6 w-full py-2.5 rounded-lg border border-white/10 bg-white/5 hover:bg-white/10 text-sm font-medium text-white transition-colors"
- >
- Cerrar
- </button>
- </div>
- </div>
- )}
- </div>
- );
-}
-
-function CopyRow({ label, value, copyKey, copied, onCopy }: { label: string, value: string, copyKey: string, copied: string | null, onCopy: (val: string, key: string) => void }) {
- return (
- <div className="flex items-center justify-between bg-black border border-white/10 rounded-lg p-3 group">
- <div>
- <p className="text-[10px] uppercase tracking-wider text-white/40 mb-1 font-medium">{label}</p>
- <p className="font-mono text-sm text-white/90 tracking-wide">{value}</p>
- </div>
- <button
- onClick={() => onCopy(value, copyKey)}
- className={`flex items-center gap-1.5 px-3 py-1.5 rounded border transition-all text-xs font-medium ${
- copied === copyKey
- ? "border-green-500/30 bg-green-500/10 text-green-400"
- : "border-white/10 bg-white/5 text-white/60 hover:text-white hover:bg-white/10"
- }`}
- >
- <Icon icon={copied === copyKey ? "lucide:check" : "lucide:copy"} width="14" />
- {copied === copyKey ? "Copiado" : "Copiar"}
- </button>
- </div>
- );
-}
\ No newline at end of file
diff --git a/app/(home)/donate/page.tsx b/app/(home)/donate/page.tsx
deleted file mode 100644
index 10f3fca..0000000
--- a/app/(home)/donate/page.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { headers } from "next/headers";
-import DonateClient from "./DonateClient";
-
-export const DONATION_METHODS = [
- {
- id: "yape",
- name: "Yape",
- tagline: "Transferencia local",
- icon: "simple-icons:yape",
- image: "/images/pages/yape.avif",
- color: "#6C3EB8",
- detail: "Escanea el QR o usa el número de teléfono",
- phone: "+51 954 306 632",
- qrImage: "/images/pages/qr.avif",
- },
- {
- id: "visa",
- name: "Transferencia Bancaria",
- tagline: "Red nacional",
- icon: "mdi:bank-outline",
- image: "/images/pages/visa.avif",
- color: "#F5A623",
- detail: "Depósito directo a cuenta BCP (Soles)",
- account: "200-12083829-0-69",
- cci: "002-20011208382906945",
- },
- {
- id: "paypal",
- name: "PayPal",
- tagline: "Transferencia internacional",
- icon: "logos:paypal",
- color: "#009CDE",
- detail: "Envío mediante correo electrónico o enlace directo",
- email: "[email protected]",
- link: "https://www.paypal.com/ncp/payment/AZ3LS98LJ9SM2",
- },
-];
-
-export default async function DonatePage() {
- const headersList = await headers();
- const country = headersList.get("x-user-country") || "UNKNOWN";
-
- const isPeru = country === "PE" || country === "UNKNOWN";
-
- const availableMethods = isPeru
- ? DONATION_METHODS
- : DONATION_METHODS.filter(m => m.id !== "yape");
-
- const defaultMethod = isPeru ? "yape" : "paypal";
-
- return <DonateClient methods={availableMethods} defaultMethod={defaultMethod} />;
-}
\ No newline at end of file
diff --git a/app/(home)/layout.tsx b/app/(home)/layout.tsx
deleted file mode 100644
index 40f949a..0000000
--- a/app/(home)/layout.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-"use client";
-
-import "../globals.css";
-import Header from "../components/common/Header";
-import Footer from "../components/common/Footer";
-import { RecordingProvider } from "@/hooks/RecordingContext";
-import { AuthProvider } from "@/hooks/useAuth";
-import RecordingOverlay from "../components/ui/RecordingOverlay";
-
-export default function HomeLayout({ children }: { children: React.ReactNode }) {
- return (
- <AuthProvider>
- <RecordingProvider>
- <div className="flex min-h-screen flex-col text-neutral-300 bg-neutral-950">
- <Header />
- <main className="flex-1 w-full">
- {children}
- </main>
- <Footer />
- </div>
- <RecordingOverlay />
- </RecordingProvider>
- </AuthProvider>
- );
-}
diff --git a/app/(home)/page.tsx b/app/(home)/page.tsx
deleted file mode 100644
index 68e0401..0000000
--- a/app/(home)/page.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import DemoVideo from "../components/ui/DemoVideo";
-import DonationCard from "../components/ui/DonationCard";
-import EditorPreview from "../components/ui/EditorPreview";
-import Hero from "../components/ui/Hero";
-import InteractiveRecordingSteps from "../components/ui/RecordingSteps";
-export default function Home() {
- return (
- <div className="flex flex-col">
- <section className="relative pt-32 pb-20 overflow-hidden bg-gradient-radial-primary w-full">
- <div className="absolute top-0 left-1/2 -translate-x-1/2 w-250 h-125 rounded-[100%] blur-3xl pointer-events-none -z-10"></div>
-
- <div className="max-w-6xl mx-auto px-6 text-center relative z-10">
- <Hero />
- <EditorPreview />
- </div>
- </section>
-
- <section className="w-full py-16">
- <div className="max-w-6xl mx-auto px-6">
- <InteractiveRecordingSteps />
- </div>
- </section>
-
- <section className="py-16 w-full mb-20">
- <div className="max-w-xl mx-auto px-6">
- <DonationCard />
- </div>
- </section>
-
- <section className="w-full py-16">
- <div className="max-w-6xl mx-auto px-6">
- <DemoVideo/>
- </div>
- </section>
- </div>
- );
-}
\ No newline at end of file
diff --git a/app/(legal)/layout.tsx b/app/(legal)/layout.tsx
deleted file mode 100644
index 9badd7f..0000000
--- a/app/(legal)/layout.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { AuthProvider } from "@/hooks/useAuth";
-import Footer from "../components/common/Footer";
-import Header from "../components/common/Header";
-
-export default function LegalLayout({ children }: { children: React.ReactNode }) {
- return (
- <AuthProvider>
- <div className="min-h-screen flex flex-col bg-[#09090B]">
- <Header />
- <div className="grow pt-24 pb-16">
- {children}
- </div>
- <Footer />
- </div>
- </AuthProvider>
- );
-}
diff --git a/app/(legal)/privacy/page.tsx b/app/(legal)/privacy/page.tsx
deleted file mode 100644
index e28f45a..0000000
--- a/app/(legal)/privacy/page.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-"use client";
-
-import { Icon } from "@iconify/react";
-import Link from "next/link";
-
-export default function PrivacyPage() {
- return (
- <div className="min-h-screen bg-[#09090B] py-16 px-4 sm:px-6 lg:px-8">
- <div className="max-w-3xl mx-auto">
- <div className="mb-12">
- <Link
- href="/"
- className="inline-flex items-center text-sm text-white/50 hover:text-white mb-8 transition-colors"
- >
- <Icon icon="lucide:arrow-left" width="16" className="mr-2" />
- Volver al inicio
- </Link>
-
- <h1 className="text-3xl md:text-4xl font-semibold text-white mb-3">
- Política de Privacidad
- </h1>
- <p className="text-white/50 text-sm">
- Última actualización: {new Date().toLocaleDateString('es-ES', { day: 'numeric', month: 'long', year: 'numeric' })}
- </p>
- </div>
-
- <div className="space-y-10 text-white/70 leading-relaxed">
- <section>
- <h2 className="text-xl font-medium text-white mb-4">1. Introducción</h2>
- <p>
- En openvid, respetamos tu privacidad y nos comprometemos a proteger tu información personal.
- Esta política describe cómo recopilamos, usamos y protegemos tus datos cuando utilizas nuestra plataforma.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">2. Información que Recopilamos</h2>
- <p className="mb-3">
- Recopilamos la siguiente información cuando usas openvid:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2">
- <li><strong className="text-white/80">Información de cuenta:</strong> Nombre, correo electrónico y foto de perfil (cuando usas OAuth)</li>
- <li><strong className="text-white/80">Datos de uso:</strong> Información sobre cómo usas la aplicación y sus funciones</li>
- <li><strong className="text-white/80">Información técnica:</strong> Tipo de navegador, dispositivo, dirección IP y cookies</li>
- <li><strong className="text-white/80">Contenido temporal:</strong> Videos que subes para editar (procesados localmente en tu navegador)</li>
- </ul>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">3. Cómo Usamos tu Información</h2>
- <p className="mb-3">
- Utilizamos tu información para:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2">
- <li>Proporcionar y mejorar los servicios de openvid</li>
- <li>Personalizar tu experiencia de usuario</li>
- <li>Comunicarnos contigo sobre actualizaciones y nuevas funciones</li>
- <li>Analizar el uso de la plataforma para optimizar el rendimiento</li>
- <li>Prevenir fraudes y proteger la seguridad de la plataforma</li>
- </ul>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">4. Procesamiento de Videos</h2>
- <div className="flex items-start gap-3 p-4 bg-green-500/5 border border-green-500/20 rounded-xl mt-4">
- <Icon icon="lucide:shield-check" className="text-green-400 shrink-0 mt-0.5" width="18" />
- <div>
- <p className="text-white/80 font-semibold mb-1">Privacidad Garantizada</p>
- <p className="text-green-400/80 text-sm leading-relaxed">
- Tus videos se procesan <span className="font-semibold text-green-300">completamente en tu navegador</span>.
- No subimos tus videos a nuestros servidores. Todo el procesamiento ocurre localmente en tu dispositivo,
- garantizando que tu contenido permanezca privado y seguro.
- </p>
- </div>
- </div>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">5. Cookies y Tecnologías Similares</h2>
- <p className="mb-3">
- Utilizamos cookies y tecnologías similares para:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2 mb-3">
- <li>Mantener tu sesión activa</li>
- <li>Recordar tus preferencias de edición</li>
- <li>Analizar el rendimiento de la aplicación</li>
- <li>Proporcionar funciones de autenticación</li>
- </ul>
- <p>
- Puedes configurar tu navegador para rechazar cookies, pero esto puede afectar la funcionalidad de la aplicación.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">6. Compartir Información</h2>
- <p className="mb-3">
- No vendemos ni compartimos tu información personal con terceros, excepto en los siguientes casos:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2">
- <li><strong className="text-white/80">Proveedores de servicios:</strong> Como servicios de autenticación (Google OAuth)</li>
- <li><strong className="text-white/80">Cumplimiento legal:</strong> Cuando sea requerido por ley o autoridades competentes</li>
- <li><strong className="text-white/80">Protección de derechos:</strong> Para proteger nuestros derechos legales o los de otros usuarios</li>
- </ul>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">7. Seguridad de Datos</h2>
- <p className="mb-3">
- Implementamos medidas de seguridad técnicas y organizativas para proteger tu información contra:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2 mb-3">
- <li>Acceso no autorizado</li>
- <li>Divulgación accidental</li>
- <li>Alteración o destrucción de datos</li>
- </ul>
- <p>
- Sin embargo, ningún método de transmisión por Internet es 100% seguro, y no podemos garantizar la seguridad absoluta.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">8. Tus Derechos</h2>
- <p className="mb-3">
- Tienes derecho a:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2">
- <li><strong className="text-white/80">Acceso:</strong> Solicitar una copia de tu información personal</li>
- <li><strong className="text-white/80">Rectificación:</strong> Corregir información inexacta o incompleta</li>
- <li><strong className="text-white/80">Eliminación:</strong> Solicitar la eliminación de tu cuenta y datos</li>
- <li><strong className="text-white/80">Portabilidad:</strong> Recibir tus datos en un formato estructurado</li>
- <li><strong className="text-white/80">Oposición:</strong> Oponerte a ciertos procesamientos de tus datos</li>
- </ul>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">9. Retención de Datos</h2>
- <p>
- Conservamos tu información personal solo durante el tiempo necesario para los propósitos descritos en esta política.
- Los videos procesados en tu navegador no se almacenan en nuestros servidores y se eliminan automáticamente al cerrar la sesión.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">10. Menores de Edad</h2>
- <p>
- openvid no está dirigido a menores de 13 años. No recopilamos intencionalmente información de menores.
- Si descubrimos que hemos recopilado datos de un menor sin consentimiento parental, los eliminaremos de inmediato.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">11. Cambios a esta Política</h2>
- <p>
- Podemos actualizar esta política de privacidad periódicamente. Te notificaremos sobre cambios significativos
- mediante un aviso en la aplicación o por correo electrónico. Te recomendamos revisar esta página regularmente.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">12. Contacto</h2>
- <p>
- Si tienes preguntas o inquietudes sobre esta política de privacidad, o deseas ejercer tus derechos,
- puedes contactarnos a través de los canales disponibles en la aplicación.
- </p>
- </section>
- </div>
-
- <div className="mt-16 pt-8 border-t border-white/10">
- <p className="text-sm text-white/50">
- Al usar openvid, también aceptas nuestros{" "}
- <Link href="/terms" className="text-white hover:underline transition-colors">
- Términos de Servicio
- </Link>
- .
- </p>
- </div>
- </div>
- </div>
- );
-}
\ No newline at end of file
diff --git a/app/(legal)/terms/page.tsx b/app/(legal)/terms/page.tsx
deleted file mode 100644
index 175c144..0000000
--- a/app/(legal)/terms/page.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-"use client";
-
-import { Icon } from "@iconify/react";
-import Link from "next/link";
-
-export default function TermsPage() {
- return (
- <div className="min-h-screen bg-[#09090B] py-16 px-4 sm:px-6 lg:px-8">
- <div className="max-w-3xl mx-auto">
- <div className="mb-12">
- <Link
- href="/"
- className="inline-flex items-center text-sm text-white/50 hover:text-white mb-8 transition-colors"
- >
- <Icon icon="lucide:arrow-left" width="16" className="mr-2" />
- Volver al inicio
- </Link>
-
- <h1 className="text-3xl md:text-4xl font-semibold text-white mb-3">
- Términos de Servicio
- </h1>
- <p className="text-white/50 text-sm">
- Última actualización: {new Date().toLocaleDateString('es-ES', { day: 'numeric', month: 'long', year: 'numeric' })}
- </p>
- </div>
-
- <div className="space-y-10 text-white/70 leading-relaxed">
- <section>
- <h2 className="text-xl font-medium text-white mb-4">1. Aceptación de los Términos</h2>
- <p>
- Al acceder y utilizar openvid, aceptas estar legalmente vinculado por estos términos de servicio.
- Si no estás de acuerdo con alguna parte de estos términos, no debes utilizar nuestra plataforma.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">2. Descripción del Servicio</h2>
- <p className="mb-3">
- openvid es una aplicación web de edición de video que permite a los usuarios:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2">
- <li>Subir y editar videos en el navegador.</li>
- <li>Aplicar efectos visuales, fondos y elementos personalizados.</li>
- <li>Exportar videos con o sin fondo transparente.</li>
- <li>Utilizar herramientas de zoom, recorte y ajustes de audio.</li>
- </ul>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">3. Cuenta de Usuario</h2>
- <p className="mb-3">
- Para acceder a ciertas funciones, es posible que necesites crear una cuenta mediante:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2 mb-3">
- <li>Autenticación con Google OAuth.</li>
- <li>Otros métodos de autenticación disponibles.</li>
- </ul>
- <p>
- Eres responsable de mantener la confidencialidad de tu cuenta.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">4. Uso Aceptable</h2>
- <p className="mb-3">
- Al utilizar openvid, te comprometes a:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2">
- <li>No subir contenido ilegal, ofensivo o que viole derechos de terceros.</li>
- <li>No utilizar el servicio para propósitos maliciosos o fraudulentos.</li>
- <li>No intentar acceder a sistemas o datos sin autorización.</li>
- <li>Respetar los límites de uso y recursos del servicio.</li>
- </ul>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">5. Propiedad Intelectual</h2>
- <p>
- Tú mantienes todos los derechos sobre el contenido que subes a openvid.
- Nosotros solo procesamos tus videos temporalmente para proporcionar el servicio de edición.
- No almacenamos ni compartimos tu contenido sin tu consentimiento explícito.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">6. Limitación de Responsabilidad</h2>
- <p className="text-white/60">
- openvid se proporciona &quot;tal cual&quot; sin garantías de ningún tipo. No nos hacemos responsables de:
- </p>
- <ul className="list-disc list-inside space-y-2 ml-2">
- <li>Pérdida de datos o contenido.</li>
- <li>Interrupciones del servicio.</li>
- <li>Errores en la exportación de videos.</li>
- <li>Incompatibilidades con navegadores o dispositivos.</li>
- </ul>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">7. Modificaciones del Servicio</h2>
- <p>
- Nos reservamos el derecho de modificar, suspender o discontinuar el servicio en cualquier momento
- sin previo aviso. También podemos actualizar estos términos periódicamente.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">8. Ley Aplicable</h2>
- <p>
- Estos términos se rigen por las leyes aplicables en tu jurisdicción.
- Cualquier disputa se resolverá mediante arbitraje vinculante.
- </p>
- </section>
-
- <section>
- <h2 className="text-xl font-medium text-white mb-4">9. Contacto</h2>
- <p>
- Si tienes preguntas sobre estos términos, puedes contactarnos a través de los canales disponibles en la aplicación.
- </p>
- </section>
- </div>
-
- <div className="mt-16 pt-8 border-t border-white/10">
- <p className="text-sm text-white/50">
- Al usar openvid, también aceptas nuestra{" "}
- <Link href="/privacy" className="text-white hover:underline transition-colors">
- Política de Privacidad
- </Link>
- .
- </p>
- </div>
- </div>
- </div>
- );
-}
\ No newline at end of file
diff --git a/app/(auth)/layout.tsx b/app/[locale]/(auth)/layout.tsx
similarity index 100%
rename from app/(auth)/layout.tsx
rename to app/[locale]/(auth)/layout.tsx
diff --git a/app/[locale]/layout.tsx b/app/[locale]/layout.tsx
new file mode 100644
index 0000000..261d20e
--- /dev/null
+++ b/app/[locale]/layout.tsx
@@ -0,0 +1,47 @@
+import { NextIntlClientProvider } from 'next-intl';
+import { getMessages, setRequestLocale } from 'next-intl/server';
+import { notFound } from 'next/navigation';
+import { locales, type Locale } from '@/i18n';
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { Inter, Roboto, Poppins, Montserrat, DM_Sans } from "next/font/google";
+import "../globals.css";
+
+const inter = Inter({ subsets: ["latin"], variable: "--font-inter", display: "swap" });
+const roboto = Roboto({ subsets: ["latin"], weight: ["400", "500", "700"], variable: "--font-roboto", display: "swap" });
+const poppins = Poppins({ subsets: ["latin"], weight: ["400", "500", "700"], variable: "--font-poppins", display: "swap" });
+const montserrat = Montserrat({ subsets: ["latin"], weight: ["400", "500", "700"], variable: "--font-montserrat", display: "swap" });
+const dmSans = DM_Sans({ subsets: ["latin"], weight: ["400", "500", "700"], variable: "--font-dm-sans", display: "swap" });
+
+export default async function LocaleLayout({
+ children,
+ params
+}: {
+ children: React.ReactNode;
+ params: Promise<{ locale: string }>;
+}) {
+ const { locale } = await params;
+
+ if (!locales.includes(locale as Locale)) {
+ notFound();
+ }
+
+ setRequestLocale(locale);
+
+ const messages = await getMessages();
+
+ return (
+ <html lang={locale}>
+ <body className={`
+ ${inter.variable} ${roboto.variable} ${poppins.variable}
+ ${montserrat.variable} ${dmSans.variable} ${inter.className}
+ antialiased dark
+ `}>
+ <NextIntlClientProvider key={locale} messages={messages} locale={locale}>
+ <TooltipProvider delayDuration={200}>
+ {children}
+ </TooltipProvider>
+ </NextIntlClientProvider>
+ </body>
+ </html>
+ );
+}
\ No newline at end of file
diff --git a/app/[locale]/not-found.tsx b/app/[locale]/not-found.tsx
new file mode 100644
index 0000000..326cf0f
--- /dev/null
+++ b/app/[locale]/not-found.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import { AuthProvider } from "@/hooks/useAuth";
+import { Link } from "@/navigation";
+import Footer from "../components/common/Footer";
+import Header from "../components/common/Header";
+import Image from "next/image";
+
+export default function NotFound() {
+ const t = useTranslations('notFound');
+
+ return (
+ <AuthProvider>
+ <Header />
+
+ <div className="flex flex-col items-center justify-center min-h-dvh bg-[#050505] text-center px-6 relative overflow-hidden">
+
+ <h1 className="text-8xl md:text-[12rem] font-black tracking-tighter animate-reveal opacity-0 [animation-delay:150ms] bg-linear-to-b from-white/20 to-transparent bg-clip-text text-transparent select-none">
+ 404
+ </h1>
+
+ <div className="-mt-8 space-y-3 animate-reveal opacity-0 [animation-delay:300ms] relative z-10">
+ <div className="flex justify-center mb-4 opacity-50">
+ <Image src="/svg/openvid.svg" alt="Openvid" width={120} height={30} />
+ </div>
+
+ <h2 className="text-2xl md:text-4xl font-bold text-white tracking-tight">
+ {t('title')}
+ </h2>
+ <p className="text-neutral-500 max-w-sm mx-auto leading-relaxed text-sm md:text-base font-medium">
+ {t('description')}
+ </p>
+ </div>
+
+ <Link
+ href="/"
+ className="mt-12 px-10 py-4 bg-gradient-primary text-white font-bold rounded-full hover:scale-105 active:scale-95 transition-all animate-reveal opacity-0"
+ >
+ {t('backHome')}
+ </Link>
+
+ <div className="absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(0,163,255,0.08)_0%,transparent_60%)] pointer-events-none" />
+
+ </div>
+ <Footer/>
+ </AuthProvider>
+ );
+}
diff --git a/app/layout.tsx b/app/layout.tsx
index 6871384..bfbb66e 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -1,41 +1,4 @@
import type { Metadata } from "next";
-import { Inter, Roboto, Poppins, Montserrat, DM_Sans } from "next/font/google";
-import { TooltipProvider } from "@/components/ui/tooltip"
-import "./globals.css";
-
-const inter = Inter({
- subsets: ["latin"],
- display: "swap",
- variable: "--font-inter",
-});
-
-const roboto = Roboto({
- subsets: ["latin"],
- weight: ["400", "500", "700"],
- display: "swap",
- variable: "--font-roboto",
-});
-
-const poppins = Poppins({
- subsets: ["latin"],
- weight: ["400", "500", "700"],
- display: "swap",
- variable: "--font-poppins",
-});
-
-const montserrat = Montserrat({
- subsets: ["latin"],
- weight: ["400", "500", "700"],
- display: "swap",
- variable: "--font-montserrat",
-});
-
-const dmSans = DM_Sans({
- subsets: ["latin"],
- weight: ["400", "500", "700"],
- display: "swap",
- variable: "--font-dm-sans",
-});
export const metadata: Metadata = {
title: "openvid - Crea demos profesionales",
@@ -107,18 +70,6 @@ export const viewport = {
themeColor: "#050505",
};
-export default function RootLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
- return (
- <html lang="es">
- <body className={`${inter.variable} ${roboto.variable} ${poppins.variable} ${montserrat.variable} ${dmSans.variable} ${inter.className} antialiased dark`}>
- <TooltipProvider delayDuration={200}>
- {children}
- </TooltipProvider>
- </body>
- </html>
- );
+export default function RootLayout({ children }: { children: React.ReactNode }) {
+ return children;
}
\ No newline at end of file
diff --git a/app/not-found.tsx b/app/not-found.tsx
index 7f28cc7..2bef4be 100644
--- a/app/not-found.tsx
+++ b/app/not-found.tsx
@@ -1,46 +1,5 @@
-"use client";
-
-import Link from 'next/link';
-import Image from 'next/image';
-import Header from './components/common/Header';
-import { AuthProvider } from '@/hooks/useAuth';
-import Footer from './components/common/Footer';
+import { redirect } from 'next/navigation';
export default function NotFound() {
- return (
- <AuthProvider>
- <Header />
-
- <div className="flex flex-col items-center justify-center min-h-dvh bg-[#050505] text-center px-6 relative overflow-hidden">
-
- <h1 className="text-8xl md:text-[12rem] font-black tracking-tighter animate-reveal opacity-0 [animation-delay:150ms] bg-linear-to-b from-white/20 to-transparent bg-clip-text text-transparent select-none">
- 404
- </h1>
-
- <div className="-mt-8 space-y-3 animate-reveal opacity-0 [animation-delay:300ms] relative z-10">
- <div className="flex justify-center mb-4 opacity-50">
- <Image src="/svg/openvid.svg" alt="Openvid" width={120} height={30} />
- </div>
-
- <h2 className="text-2xl md:text-4xl font-bold text-white tracking-tight">
- Página no encontrada
- </h2>
- <p className="text-neutral-500 max-w-sm mx-auto leading-relaxed text-sm md:text-base font-medium">
- La ruta que buscas no existe en nuestro editor.
- </p>
- </div>
-
- <Link
- href="/"
- className="mt-12 px-10 py-4 bg-gradient-primary text-white font-bold rounded-full hover:scale-105 active:scale-95 transition-all animate-reveal opacity-0"
- >
- Volver al Inicio
- </Link>
-
- <div className="absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(0,163,255,0.08)_0%,transparent_60%)] pointer-events-none" />
-
- </div>
- <Footer/>
- </AuthProvider>
- );
+ redirect('/es');
}