Skip to content

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

feat: add ImageMaskEditor and PhotoEditorPlaceholder components for enhanced image masking and editing capabilities

CristianOlivera13b489d71ec35
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsx
index 5383f07..41cea62 100644
--- a/app/[locale]/(editor)/editor/page.tsx
+++ b/app/[locale]/(editor)/editor/page.tsx
@@ -1,18 +1,23 @@
"use client";
import { useState, useRef, useEffect, useCallback, lazy, Suspense, useMemo } from "react";
+import { toBlob } from 'html-to-image';
import { Icon } from "@iconify/react";
import { motion, AnimatePresence } from "framer-motion";
import { loadVideoFromIndexedDB, deleteRecordedVideo } from "@/hooks/useScreenRecording";
import { useVideoUpload } from "@/hooks/useVideoUpload";
+import { useImageProjects } from "@/hooks/useImageProjects";
import { getUploadedVideo, deleteUploadedVideo } from "@/lib/video-upload-cache";
+import { getUploadedImage, deleteUploadedImage } from "@/lib/image-upload-cache";
+import { useEditorMode } from "@/hooks/useEditorMode";
+import { useScreenCapture } from "@/hooks/useScreenCapture";
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 { ExportQuality, Tool, BackgroundTab, VideoCanvasHandle, BackgroundColorConfig, AspectRatio, CropArea, ZoomFragment, AudioTrack, ImageExportFormat } from "@/types";
import type { TrimRange } from "@/types/timeline.types";
import type { MockupConfig } from "@/types/mockup.types";
import type { EditorState } from "@/types/editor-state.types";
@@ -20,8 +25,10 @@ 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 type { Preview3DConfig, ImageMaskConfig } from "@/types/photo.types";
+import { DEFAULT_MASK_CONFIG, PREVIEW_CONFIGS } from "@/types/photo.types";
import { MOCKUPS } from "@/lib/mockup-data";
-import { gradientToCss, generateDefaultZoomFragments, createZoomFragment, detectVideoHasAudio } from "@/types";
+import { gradientToCss, generateDefaultZoomFragments, createZoomFragment, detectVideoHasAudio, ASPECT_RATIO_DIMENSIONS } from "@/types";
import { ToolsSidebar } from "@/app/components/ui/editor/ToolsSidebar";
import { MobileToolsMenu } from "@/app/components/ui/editor/MobileToolsMenu";
import { MobileControlPanel } from "@/app/components/ui/editor/MobileControlPanel";
@@ -37,13 +44,17 @@ 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 })));
+const ImageCropperModal = lazy(() => import("@/app/components/ui/editor/ImageCropperModal").then(mod => ({ default: mod.ImageCropperModal })));
+const PhotoEditorPlaceholder = lazy(() => import("@/app/components/ui/editor/PhotoEditorPlaceholder").then(mod => ({ default: mod.PhotoEditorPlaceholder })));
export default function Editor() {
+ // Editor mode (video/photo) from URL params
+ const { mode: editorMode, isVideoMode, isPhotoMode } = useEditorMode();
+
// Undo/Redo system - centralized state management
const {
state: editorState,
@@ -55,6 +66,51 @@ export default function Editor() {
clearHistory,
} = useUndoRedo<EditorState>(createInitialEditorState());
+ // Image state for photo mode
+ const [imageUrl, setImageUrl] = useState<string | null>(null);
+ const imageRef = useRef<HTMLImageElement>(null);
+ const [imageExportProgress, setImageExportProgress] = useState<{
+ status: "idle" | "preparing" | "rendering" | "complete" | "error";
+ progress: number;
+ message: string;
+ }>({
+ status: "idle",
+ progress: 0,
+ message: "",
+ });
+
+ // Screen capture hook
+ const { captureScreen, isCapturing } = useScreenCapture();
+
+ // Image projects system (IndexedDB persistence for photo mode)
+ const {
+ projects: imageProjects,
+ currentProject,
+ isLoading: isLoadingProjects,
+ isSaving: isSavingProject,
+ createProject,
+ saveCurrentProject,
+ switchToProject,
+ removeProject,
+ } = useImageProjects();
+
+ // Photo mode 3D preview state
+ const [selectedPreviewId, setSelectedPreviewId] = useState<string>("front");
+ const [canvasImageUrl, setCanvasImageUrl] = useState<string | null>(null);
+ const [imageTransform, setImageTransform] = useState<Preview3DConfig>({
+ id: "front",
+ label: "Front",
+ rotateX: 0,
+ rotateY: 0,
+ rotateZ: 0,
+ translateY: 0,
+ scale: 0.9,
+ perspective: 600,
+ });
+ const [apply3DToBackground, setApply3DToBackground] = useState(false);
+ const [imageDimensions, setImageDimensions] = useState<{ width: number; height: number } | null>(null);
+ const [imageMaskConfig, setImageMaskConfig] = useState<ImageMaskConfig>(DEFAULT_MASK_CONFIG);
+
const [activeTool, setActiveTool] = useState<Tool>("screenshot");
const [backgroundTab, setBackgroundTab] = useState<BackgroundTab>("wallpaper");
const [selectedWallpaper, setSelectedWallpaper] = useState(0);
@@ -104,7 +160,9 @@ export default function Editor() {
const [cropArea, setCropArea] = useState<CropArea | undefined>(undefined);
// Computed: which dimensions to use for the canvas
- const customAspectRatio = aspectRatio === "auto" ? videoDimensions : (aspectRatio === "custom" ? customDimensions : null);
+ const customAspectRatio = aspectRatio === "auto"
+ ? (isPhotoMode ? imageDimensions : videoDimensions)
+ : (aspectRatio === "custom" ? customDimensions : null);
// Refs for fullscreen
const editorAreaRef = useRef<HTMLDivElement>(null);
@@ -174,6 +232,493 @@ export default function Editor() {
setActiveTool("camera");
}, []);
+ // Auto-save current image project when configurations change
+ const autoSaveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const isRestoringProjectRef = useRef(false);
+ const isLoadingFromCacheRef = useRef(false);
+ const lastRestoredProjectIdRef = useRef<string | null>(null);
+
+ const autoSaveCurrentProject = useCallback(async () => {
+ if (!isPhotoMode || !imageUrl || !currentProject) return;
+
+ // Don't auto-save during project restoration
+ if (isRestoringProjectRef.current) return;
+
+ // Debounce saves to avoid excessive writes
+ if (autoSaveTimeoutRef.current) {
+ clearTimeout(autoSaveTimeoutRef.current);
+ }
+
+ autoSaveTimeoutRef.current = setTimeout(async () => {
+ try {
+ await saveCurrentProject({
+ backgroundTab,
+ selectedWallpaper,
+ backgroundBlur,
+ selectedImageUrl,
+ backgroundColorConfig,
+ padding,
+ roundedCorners,
+ shadows,
+ aspectRatio,
+ customDimensions,
+ cropArea,
+ mockupId,
+ mockupConfig,
+ canvasElements,
+ imageTransform: {
+ rotation: videoTransform.rotation,
+ translateX: videoTransform.translateX,
+ translateY: videoTransform.translateY,
+ },
+ imagePreview3D: imageTransform,
+ apply3DToBackground,
+ imageMaskConfig,
+ });
+ } catch (error) {
+ console.error("Auto-save failed:", error);
+ }
+ }, 3000); // 3 second debounce
+ }, [
+ isPhotoMode,
+ imageUrl,
+ currentProject,
+ saveCurrentProject,
+ backgroundTab,
+ selectedWallpaper,
+ backgroundBlur,
+ selectedImageUrl,
+ backgroundColorConfig,
+ padding,
+ roundedCorners,
+ shadows,
+ aspectRatio,
+ customDimensions,
+ cropArea,
+ mockupId,
+ mockupConfig,
+ canvasElements,
+ videoTransform,
+ imageTransform,
+ apply3DToBackground,
+ imageMaskConfig,
+ ]);
+
+ useEffect(() => {
+ if (currentProject && isPhotoMode && !isRestoringProjectRef.current) {
+ autoSaveCurrentProject();
+ }
+ }, [
+ backgroundTab,
+ selectedWallpaper,
+ backgroundBlur,
+ selectedImageUrl,
+ backgroundColorConfig,
+ padding,
+ roundedCorners,
+ shadows,
+ aspectRatio,
+ customDimensions,
+ cropArea,
+ mockupId,
+ mockupConfig,
+ canvasElements,
+ videoTransform,
+ imageTransform,
+ apply3DToBackground,
+ imageMaskConfig,
+ currentProject,
+ isPhotoMode,
+ autoSaveCurrentProject,
+ ]);
+
+ // Restore current project when project ID changes (not on every currentProject update)
+ useEffect(() => {
+ if (!isPhotoMode || !currentProject) return;
+
+ if (lastRestoredProjectIdRef.current === currentProject.id) return;
+
+ isRestoringProjectRef.current = true;
+ lastRestoredProjectIdRef.current = currentProject.id;
+
+ const imageDataUrl = currentProject.imageDataUrl;
+
+ if (!imageDataUrl) {
+ console.error("Project missing imageDataUrl");
+ isRestoringProjectRef.current = false;
+ return;
+ }
+
+ // Directly restore all states using the data URL
+ setImageUrl(imageDataUrl);
+ setBackgroundTab(currentProject.backgroundTab);
+ setSelectedWallpaper(currentProject.selectedWallpaper);
+ setBackgroundBlur(currentProject.backgroundBlur);
+ setSelectedImageUrl(currentProject.selectedImageUrl);
+ setBackgroundColorConfig(currentProject.backgroundColorConfig);
+ setPadding(currentProject.padding);
+ setRoundedCorners(currentProject.roundedCorners);
+ setShadows(currentProject.shadows);
+ setAspectRatio(currentProject.aspectRatio);
+ setCustomDimensions(currentProject.customDimensions);
+ setCropArea(currentProject.cropArea);
+ setMockupId(currentProject.mockupId);
+ setMockupConfig(currentProject.mockupConfig);
+ setCanvasElements(currentProject.canvasElements);
+ setVideoTransform(currentProject.imageTransform);
+ setImageTransform(currentProject.imagePreview3D);
+ setApply3DToBackground(currentProject.apply3DToBackground);
+ setImageMaskConfig(currentProject.imageMaskConfig);
+ setImageDimensions({
+ width: currentProject.imageWidth,
+ height: currentProject.imageHeight,
+ });
+
+ setTimeout(() => {
+ isRestoringProjectRef.current = false;
+ }, 500); //
+ }, [currentProject, isPhotoMode]);
+
+ // Image project handlers
+ const handleSelectImageProject = useCallback(async (projectId: string) => {
+ if (!isPhotoMode) return;
+
+ // Save current project before switching
+ if (currentProject && imageUrl) {
+ await autoSaveCurrentProject();
+ }
+
+ // Load the selected project
+ await switchToProject(projectId);
+ }, [isPhotoMode, currentProject, imageUrl, autoSaveCurrentProject, switchToProject]);
+
+ const handleAddImageToCanvas = useCallback(async (projectId: string) => {
+ await handleSelectImageProject(projectId);
+ }, [handleSelectImageProject]);
+
+ const handleDeleteImageProject = useCallback(async (projectId: string) => {
+ // If deleting the current project, cancel auto-save and clear state immediately
+ const isDeletingCurrent = currentProject?.id === projectId;
+
+ if (isDeletingCurrent) {
+ // Cancel any pending auto-save to prevent race condition
+ if (autoSaveTimeoutRef.current) {
+ clearTimeout(autoSaveTimeoutRef.current);
+ autoSaveTimeoutRef.current = null;
+ }
+ }
+
+ await removeProject(projectId);
+
+ // Clear canvas if we deleted the current project
+ if (isDeletingCurrent) {
+ setImageUrl(null);
+ setCanvasImageUrl(null);
+ setImageDimensions(null);
+ // Reset to default state
+ setBackgroundTab("wallpaper");
+ setSelectedWallpaper(0);
+ setBackgroundBlur(0);
+ setPadding(10);
+ setRoundedCorners(10);
+ setShadows(10);
+ setAspectRatio("auto");
+ setCustomDimensions(null);
+ setCropArea(undefined);
+ setMockupId("none");
+ setMockupConfig(DEFAULT_MOCKUP_CONFIG);
+ setCanvasElements([]);
+ setImageTransform({ id: "front", label: "Front", rotateX: 0, rotateY: 0, rotateZ: 0, translateY: 0, scale: 0.9, perspective: 600 });
+ setApply3DToBackground(false);
+ setImageMaskConfig(DEFAULT_MASK_CONFIG);
+ }
+ }, [currentProject, removeProject]);
+
+ const handleUploadImageToHistory = useCallback(async (file: File) => {
+ // This will create a new project when user uploads from history menu
+ try {
+ const img = await createImageBitmap(file);
+ const project = await createProject(
+ file,
+ file.name,
+ img.width,
+ img.height,
+ {
+ backgroundTab,
+ selectedWallpaper,
+ backgroundBlur,
+ selectedImageUrl,
+ backgroundColorConfig,
+ padding,
+ roundedCorners,
+ shadows,
+ aspectRatio,
+ customDimensions,
+ cropArea,
+ mockupId,
+ mockupConfig,
+ canvasElements,
+ imageTransform: {
+ rotation: videoTransform.rotation,
+ translateX: videoTransform.translateX,
+ translateY: videoTransform.translateY,
+ },
+ imagePreview3D: imageTransform,
+ apply3DToBackground,
+ imageMaskConfig,
+ }
+ );
+
+ if (project) {
+ setImageUrl(project.imageDataUrl);
+ setImageDimensions({ width: img.width, height: img.height });
+ }
+ } catch (error) {
+ console.error("Failed to upload image to history:", error);
+ }
+ }, [
+ createProject,
+ backgroundTab,
+ selectedWallpaper,
+ backgroundBlur,
+ selectedImageUrl,
+ backgroundColorConfig,
+ padding,
+ roundedCorners,
+ shadows,
+ aspectRatio,
+ customDimensions,
+ cropArea,
+ mockupId,
+ mockupConfig,
+ canvasElements,
+ videoTransform,
+ imageTransform,
+ apply3DToBackground,
+ imageMaskConfig,
+ ]);
+
+ // Screen capture handler - now creates a project
+ const handleScreenCapture = useCallback(async () => {
+ const blob = await captureScreen();
+ if (blob) {
+ try {
+ const file = new File([blob], `Screenshot ${new Date().toLocaleString()}.png`, { type: "image/png" });
+ const img = await createImageBitmap(blob);
+
+ const project = await createProject(
+ file,
+ file.name,
+ img.width,
+ img.height
+ );
+
+ if (project) {
+ setImageUrl(project.imageDataUrl);
+ setImageDimensions({ width: img.width, height: img.height });
+ }
+ } catch (error) {
+ console.error("Failed to create project from screenshot:", error);
+ }
+ }
+ }, [captureScreen, createProject]);
+
+ // Unified image upload handler - updates current project if exists, otherwise creates new
+ const handleImageUploadToCanvas = useCallback(async (file: File) => {
+ try {
+ const img = await createImageBitmap(file);
+
+ // If there's a current project, update it instead of creating a new one
+ if (currentProject && isPhotoMode) {
+ const updated = await saveCurrentProject({
+ imageBlob: file,
+ imageName: file.name,
+ imageWidth: img.width,
+ imageHeight: img.height,
+ });
+
+ if (updated) {
+ setImageUrl(updated.imageDataUrl);
+ setImageDimensions({ width: img.width, height: img.height });
+ }
+ } else {
+ // No current project, create a new one
+ const project = await createProject(
+ file,
+ file.name,
+ img.width,
+ img.height
+ );
+
+ if (project) {
+ setImageUrl(project.imageDataUrl);
+ setImageDimensions({ width: img.width, height: img.height });
+ }
+ }
+ } catch (error) {
+ console.error("Failed to upload image:", error);
+ }
+ }, [createProject, currentProject, isPhotoMode, saveCurrentProject]);
+
+ // Handler for drag & drop images on canvas (photo mode only)
+ const handleImageDrop = useCallback(async (files: FileList | File[]) => {
+ if (!isPhotoMode) return;
+
+ const fileArray = Array.from(files);
+ const imageFile = fileArray.find(f => f.type.startsWith('image/'));
+
+ if (imageFile) {
+ await handleImageUploadToCanvas(imageFile);
+ }
+ }, [isPhotoMode, handleImageUploadToCanvas]);
+
+ // Image export handler - using html-to-image with fixed dimensions
+ const handleImageExport = useCallback(async (
+ format: ImageExportFormat,
+ quality: number,
+ scale: number
+ ) => {
+ if (!canvasRef.current) return;
+
+ try {
+ setImageExportProgress({ status: "preparing", progress: 0, message: "Preparing export..." });
+
+ const previewContainer = canvasRef.current.getPreviewContainer();
+ if (!previewContainer || !imageUrl) {
+ throw new Error("Preview container or image not available");
+ }
+
+ const imageElements = previewContainer.querySelectorAll('img');
+ const originalSrcs = new Map<HTMLImageElement, string>();
+
+ await Promise.all(Array.from(imageElements).map(async (img) => {
+ const src = img.src;
+ if (!src.startsWith('blob:') && !src.startsWith('data:')) return;
+
+ try {
+ const response = await fetch(src);
+ const blob = await response.blob();
+ const base64 = await new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.onerror = reject;
+ reader.readAsDataURL(blob);
+ });
+ originalSrcs.set(img, src);
+ img.src = base64;
+ if (!img.complete) {
+ await new Promise<void>((resolve) => { img.onload = () => resolve(); });
+ }
+ } catch (e) {
+ console.warn("Could not convert image src to base64:", src, e);
+ }
+ }));
+
+ setImageExportProgress({ status: "rendering", progress: 50, message: "Rendering image..." });
+
+ let exportWidth = 1920;
+ let exportHeight = 1080;
+
+ if ((aspectRatio === "auto" || aspectRatio === "custom") && customDimensions) {
+ exportWidth = customDimensions.width;
+ exportHeight = customDimensions.height;
+ } else if (aspectRatio === "auto") {
+ if (imageDimensions) {
+ exportWidth = imageDimensions.width;
+ exportHeight = imageDimensions.height;
+ }
+ } else {
+ const dims = ASPECT_RATIO_DIMENSIONS[aspectRatio];
+ if (dims) { exportWidth = dims.width; exportHeight = dims.height; }
+ }
+
+ exportWidth = Math.round(exportWidth * scale);
+ exportHeight = Math.round(exportHeight * scale);
+
+ const hasTransparentBackground = selectedWallpaper === -1;
+
+ await new Promise(resolve => setTimeout(resolve, 50));
+
+ const blob = await toBlob(previewContainer, {
+ quality,
+ cacheBust: false,
+ ...(hasTransparentBackground ? {} : { backgroundColor: '#09090B' }),
+ type: `image/${format}`,
+ canvasWidth: exportWidth,
+ canvasHeight: exportHeight,
+ pixelRatio: 1,
+ });
+
+ originalSrcs.forEach((originalSrc, img) => {
+ img.src = originalSrc;
+ });
+
+ if (!blob) throw new Error("Failed to generate image blob");
+
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.download = `openvidshot-${Date.now()}.${format}`;
+ link.href = url;
+ link.click();
+ URL.revokeObjectURL(url);
+
+ setImageExportProgress({ status: "complete", progress: 100, message: "Export complete!" });
+ setTimeout(() => setImageExportProgress({ status: "idle", progress: 0, message: "" }), 2000);
+
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
+ setImageExportProgress({ status: "error", progress: 0, message: `Export failed: ${errorMessage}` });
+ setTimeout(() => setImageExportProgress({ status: "idle", progress: 0, message: "" }), 4000);
+ }
+ }, [imageUrl, imageDimensions, selectedWallpaper, aspectRatio, customDimensions]);
+ // Generate canvas snapshot for photo mode previews
+ useEffect(() => {
+ if (!isPhotoMode || !imageUrl || !canvasRef.current) {
+ setCanvasImageUrl(null);
+ return;
+ }
+
+ const generateSnapshot = async () => {
+ try {
+ await canvasRef.current?.drawFrame();
+ const exportCanvas = canvasRef.current?.getExportCanvas();
+ if (exportCanvas) {
+ const dataUrl = exportCanvas.toDataURL("image/png", 0.8);
+ setCanvasImageUrl(dataUrl);
+ }
+ } catch (error) {
+ console.error("Error generating canvas snapshot:", error);
+ }
+ };
+
+ const initialTimeout = setTimeout(generateSnapshot, 300);
+
+ return () => {
+ clearTimeout(initialTimeout);
+ };
+ }, [isPhotoMode, imageUrl, backgroundTab, selectedWallpaper, backgroundBlur, padding, roundedCorners, shadows, selectedImageUrl, backgroundColorConfig]);
+
+ // Handle 3D preview selection
+ const handleSelectPreview = useCallback((config: Preview3DConfig) => {
+ setSelectedPreviewId(config.id);
+ setImageTransform(config);
+ }, []);
+
+ // Handle 3D background toggle
+ const handleToggle3DBackground = useCallback((value: boolean) => {
+ setApply3DToBackground(value);
+ }, [setApply3DToBackground]);
+
+ // Reset all photo editor visual settings to defaults
+ const handleResetPhotoEditor = useCallback(() => {
+ const frontConfig = PREVIEW_CONFIGS[0];
+ setSelectedPreviewId(frontConfig.id);
+ setImageTransform(frontConfig);
+ setApply3DToBackground(false);
+ setImageMaskConfig(DEFAULT_MASK_CONFIG);
+ setVideoTransform({ rotation: 0, translateX: 0, translateY: 0 });
+ }, []);
+
// Videos library state
const [newVideosCount, setNewVideosCount] = useState<number>(0);
const [videosLibraryRefresh, setVideosLibraryRefresh] = useState<number>(0);
@@ -196,9 +741,7 @@ export default function Editor() {
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;
@@ -323,6 +866,10 @@ export default function Editor() {
muteOriginalAudio,
masterVolume,
cameraConfig,
+ videoTransform,
+ imageTransform,
+ apply3DToBackground,
+ imageMaskConfig,
});
}, 300);
return () => {
@@ -336,6 +883,7 @@ export default function Editor() {
aspectRatio, customDimensions, cropArea, trimRange,
zoomFragments, mockupId, mockupConfig, canvasElements,
audioTracks, muteOriginalAudio, masterVolume, cameraConfig,
+ videoTransform, imageTransform, apply3DToBackground, imageMaskConfig,
setEditorState
]);
@@ -361,12 +909,15 @@ export default function Editor() {
setMuteOriginalAudio(editorState.muteOriginalAudio);
setMasterVolume(editorState.masterVolume);
setCameraConfig(editorState.cameraConfig);
+ setVideoTransform(editorState.videoTransform);
+ setImageTransform(editorState.imageTransform);
+ setApply3DToBackground(editorState.apply3DToBackground);
+ setImageMaskConfig(editorState.imageMaskConfig);
}, [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));
}, []);
@@ -379,7 +930,7 @@ export default function Editor() {
// 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
+ setMockupConfig(prev => ({ ...prev, cornerRadius: value }));
}, []);
// Canvas elements handlers
@@ -401,14 +952,11 @@ export default function Editor() {
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(() => {
@@ -425,9 +973,9 @@ export default function Editor() {
const newElement = {
...copiedElement,
id: `${copiedElement.type}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
- x: copiedElement.x + 5, // Offset slightly from original
+ x: copiedElement.x + 5,
y: copiedElement.y + 5,
- zIndex: Date.now(),
+ zIndex: VIDEO_Z_INDEX + 1,
} as CanvasElement;
setCanvasElements(prev => [...prev, newElement]);
@@ -785,7 +1333,6 @@ export default function Editor() {
// 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
@@ -800,14 +1347,12 @@ export default function Editor() {
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);
}
@@ -1096,6 +1641,44 @@ export default function Editor() {
const lastLoadedVideoIdRef = useRef<string | null>(null);
+ // Load image from cache when in photo mode and create project if not exists
+ useEffect(() => {
+ if (!isPhotoMode) return;
+ if (currentProject) return;
+ if (isLoadingFromCacheRef.current) return;
+ isLoadingFromCacheRef.current = true;
+
+ const loadImage = async () => {
+ try {
+ const cachedImage = await getUploadedImage();
+ if (cachedImage) {
+ await deleteUploadedImage();
+
+ const blob = cachedImage.blob;
+ const img = await createImageBitmap(blob);
+
+ const project = await createProject(
+ blob,
+ cachedImage.fileName || "Uploaded Image",
+ img.width,
+ img.height
+ );
+
+ if (project) {
+ setImageUrl(project.imageDataUrl);
+ setImageDimensions({ width: img.width, height: img.height });
+ }
+ }
+ } catch (error) {
+ console.error("Error loading image from cache:", error);
+ } finally {
+ isLoadingFromCacheRef.current = false;
+ }
+ };
+
+ loadImage();
+ }, [isPhotoMode, currentProject, createProject]);
+
useEffect(() => {
const loadVideo = async () => {
try {
@@ -1172,7 +1755,6 @@ export default function Editor() {
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);
@@ -1206,8 +1788,6 @@ export default function Editor() {
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 {
@@ -1285,6 +1865,30 @@ export default function Editor() {
return () => window.removeEventListener('keydown', handleKeyDown);
}, [undo, redo, canUndo, canRedo]);
+ // Keyboard listener for Ctrl+V image paste (photo mode only)
+ useEffect(() => {
+ if (!isPhotoMode) return;
+
+ const handlePaste = async (e: ClipboardEvent) => {
+ const items = e.clipboardData?.items;
+ if (!items) return;
+
+ for (const item of Array.from(items)) {
+ if (item.type.startsWith('image/')) {
+ e.preventDefault();
+ const file = item.getAsFile();
+ if (file) {
+ handleImageUploadToCanvas(file);
+ }
+ break;
+ }
+ }
+ };
+
+ window.addEventListener('paste', handlePaste);
+ return () => window.removeEventListener('paste', handlePaste);
+ }, [isPhotoMode, handleImageUploadToCanvas]);
+
const togglePlayPause = useCallback(() => {
if (videoRef.current) {
if (isPlaying) {
@@ -1338,7 +1942,7 @@ export default function Editor() {
}
} else {
activeClipIdRef.current = clipAtTime.id;
- activeClipDataRef.current = clipAtTime; // Keep data ref in sync (clip may have moved positions)
+ activeClipDataRef.current = clipAtTime;
const clipTime = timelineToClipTime(startTime, clipAtTime);
videoRef.current.currentTime = clipTime;
}
@@ -1367,7 +1971,6 @@ export default function Editor() {
}
}, [isPlaying, currentTime, trimRange.start, trimRange.end, syncAudioPlayback, findActiveClipAtTime, timelineToClipTime]);
- // Smooth time update using requestAnimationFrame
const updateTimeSmoothRef = useRef<() => void>(() => { });
useEffect(() => {
@@ -1441,7 +2044,7 @@ export default function Editor() {
const nextBlob = videoBlobsRef.current.get(nextClip.libraryVideoId);
if (nextUrl && videoRef.current) {
- const nextClipSnapshot = { ...nextClip }; // copia inmutable
+ const nextClipSnapshot = { ...nextClip };
activeClipIdRef.current = nextClipSnapshot.id;
activeClipDataRef.current = nextClipSnapshot;
@@ -1775,7 +2378,8 @@ export default function Editor() {
}
}, [isDraggingPlayhead, isPlaying, syncAudioPlayback, findActiveClipAtTime, timelineToClipTime]);
- const handleImageUpload = (file: File) => {
+ // Handler for background image upload (for ControlPanel)
+ const handleImageUpload = useCallback(async (file: File) => {
const reader = new FileReader();
reader.onload = (e) => {
const dataUrl = e.target?.result as string;
@@ -1785,7 +2389,7 @@ export default function Editor() {
}
};
reader.readAsDataURL(file);
- };
+ }, []);
const handleImageSelect = (url: string) => {
if (backgroundTab === "wallpaper") {
@@ -1820,7 +2424,6 @@ export default function Editor() {
// 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);
@@ -1851,7 +2454,7 @@ export default function Editor() {
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
+ setActiveTool("zoom");
}, [videoDuration]);
const handleUpdateZoomFragment = useCallback((fragmentId: string, updates: Partial<ZoomFragment>) => {
@@ -1902,7 +2505,6 @@ export default function Editor() {
}
}, []);
- // Listen for fullscreen changes (e.g., pressing Escape)
useEffect(() => {
const handleFullscreenChange = () => {
setIsFullscreen(!!document.fullscreenElement);
@@ -1912,7 +2514,6 @@ export default function Editor() {
return () => document.removeEventListener("fullscreenchange", handleFullscreenChange);
}, []);
- // Keyboard shortcuts for zoom fragments
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
@@ -1926,6 +2527,9 @@ export default function Editor() {
}
if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
+ if (isPhotoMode && !copiedElement) {
+ return;
+ }
e.preventDefault();
pasteElement();
return;
@@ -1934,7 +2538,7 @@ export default function Editor() {
if ((e.key === "Delete" || e.key === "Backspace") && selectedElementId) {
e.preventDefault();
deleteCanvasElement(selectedElementId);
- return; // Prevent zoom fragment deletion if element is selected
+ return;
}
if ((e.key === "Delete" || e.key === "Backspace") && selectedVideoClipId) {
@@ -1972,7 +2576,7 @@ export default function Editor() {
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
- }, [selectedElementId, selectedZoomFragmentId, selectedAudioTrackId, selectedVideoClipId, deleteCanvasElement, handleDeleteZoomFragment, handleDeleteAudioTrack, handleDeleteVideoClip, copySelectedElement, pasteElement]);
+ }, [selectedElementId, selectedZoomFragmentId, selectedAudioTrackId, selectedVideoClipId, deleteCanvasElement, handleDeleteZoomFragment, handleDeleteAudioTrack, handleDeleteVideoClip, copySelectedElement, pasteElement, isPhotoMode, copiedElement]);
useEffect(() => {
const checkMobile = () => {
@@ -2024,6 +2628,10 @@ export default function Editor() {
selectedVideoClipId={selectedVideoClipId}
selectedElementId={selectedElementId}
newVideosCount={newVideosCount}
+ editorMode={editorMode}
+ onImageUpload={handleImageUploadToCanvas}
+ onScreenCapture={handleScreenCapture}
+ isCapturing={isCapturing}
/>
</div>
@@ -2109,6 +2717,13 @@ export default function Editor() {
cameraUrl={cameraUrl}
cameraConfig={cameraConfig}
onCameraConfigChange={handleCameraConfigChange}
+ imageProjects={imageProjects}
+ currentImageProjectId={currentProject?.id || null}
+ isLoadingProjects={isLoadingProjects}
+ onSelectImageProject={handleSelectImageProject}
+ onAddImageToCanvas={handleAddImageToCanvas}
+ onDeleteImageProject={handleDeleteImageProject}
+ onUploadImageToHistory={handleUploadImageToHistory}
/>
</Suspense>
</motion.div>
@@ -2149,12 +2764,23 @@ export default function Editor() {
onRedo={redo}
canUndo={canUndo}
canRedo={canRedo}
+ editorMode={editorMode}
+ onImageExport={handleImageExport}
+ imageExportProgress={imageExportProgress}
+ canvasWidth={customAspectRatio?.width || 1920}
+ canvasHeight={customAspectRatio?.height || 1080}
/>
<VideoCanvas
ref={canvasRef}
videoUrl={videoUrl}
videoRef={videoRef}
+ mediaType={isPhotoMode ? "image" : "video"}
+ imageUrl={imageUrl}
+ imageRef={imageRef}
+ imageTransform={imageTransform}
+ apply3DToBackground={apply3DToBackground}
+ imageMaskConfig={imageMaskConfig}
padding={padding}
roundedCorners={roundedCorners}
shadows={shadows}
@@ -2177,6 +2803,8 @@ export default function Editor() {
mockupId={mockupId}
mockupConfig={mockupConfig ?? DEFAULT_MOCKUP_CONFIG}
onVideoUpload={handleVideoUpload}
+ onImageUpload={handleImageUploadToCanvas}
+ onImageDrop={handleImageDrop}
isUploading={isUploading}
videoTransform={videoTransform}
onVideoTransformChange={setVideoTransform}
@@ -2208,54 +2836,82 @@ export default function Editor() {
}}
/>
- <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>
+ {/* Video mode: Show player controls and timeline */}
+ {isVideoMode && (
+ <>
+ <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>
+ </>
+ )}
+
+ {/* Photo mode: Show placeholder instead of timeline */}
+ {isPhotoMode && (
+ <Suspense fallback={<TimelineSkeleton />}>
+ <PhotoEditorPlaceholder
+ canvasImageUrl={canvasImageUrl}
+ staticImageUrl={imageUrl}
+ onSelectPreview={handleSelectPreview}
+ selectedPreviewId={selectedPreviewId}
+ aspectRatio={aspectRatio}
+ onAspectRatioChange={handleAspectRatioChange}
+ customAspectRatio={customAspectRatio}
+ onCustomAspectRatioChange={handleCustomDimensionsChange}
+ onOpenCropper={handleOpenCropper}
+ apply3DToBackground={apply3DToBackground}
+ onToggle3DBackground={handleToggle3DBackground}
+ imageMaskConfig={imageMaskConfig}
+ onImageMaskConfigChange={setImageMaskConfig}
+ imageTransform={imageTransform}
+ onReset={handleResetPhotoEditor}
+ />
+ </Suspense>
+ )}
</div>
@@ -2335,13 +2991,23 @@ export default function Editor() {
/>
</Suspense>
<Suspense fallback={null}>
- <VideoCropperModal
- isOpen={isCropperOpen}
- onClose={handleCloseCropper}
- videoUrl={videoUrl}
- onCropApply={handleCropApply}
- initialCrop={cropArea}
- />
+ {isVideoMode ? (
+ <VideoCropperModal
+ isOpen={isCropperOpen}
+ onClose={handleCloseCropper}
+ videoUrl={videoUrl}
+ onCropApply={handleCropApply}
+ initialCrop={cropArea}
+ />
+ ) : (
+ <ImageCropperModal
+ isOpen={isCropperOpen}
+ onClose={handleCloseCropper}
+ imageUrl={imageUrl}
+ onCropApply={handleCropApply}
+ initialCrop={cropArea}
+ />
+ )}
</Suspense>
{autoTrimModalOpen && pendingAudioUpload && (
diff --git a/app/[locale]/(home)/page.tsx b/app/[locale]/(home)/page.tsx
index 1007341..6e16230 100644
--- a/app/[locale]/(home)/page.tsx
+++ b/app/[locale]/(home)/page.tsx
@@ -1,38 +1,49 @@
-import DemoVideo from "@/app/components/ui/DemoVideo";
+import { BentoDemos } from "@/app/components/ui/BentoDemos";
import DonationCard from "@/app/components/ui/DonationCard";
import EditorPreview from "@/app/components/ui/EditorPreview";
import Hero from "@/app/components/ui/Hero";
+import { HeroScrollMask } from "@/app/components/ui/HeroScrollMask";
import InteractiveRecordingSteps from "@/app/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="relative overflow-hidden bg-gradient-radial-primary w-full">
- <div className="max-w-6xl mx-auto px-6 text-center relative z-10">
- <Hero />
- <EditorPreview />
- </div>
- </section>
+ <div className="absolute top-0 left-1/2 -translate-x-1/2 w-250 h-[150%] rounded-[100%] blur-3xl pointer-events-none -z-10"></div>
+ <section className="pt-32 pb-6 sm:pb-14 bg-gradient-radial-primary">
+ <div className="max-w-6xl mx-auto px-6 text-center relative z-10">
+ <Hero />
+ </div>
+ </section>
+
+ <section className="w-full">
+ <div className="absolute top-0 left-1/2 -translate-x-1/2 w-250 h-[150%] rounded-[100%] blur-3xl pointer-events-none -z-10"></div>
+ <HeroScrollMask />
+ </section>
+ </div>
<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">
+ <section className="pt-8 pb-0 sm:py-2 w-full mb-0 sm:mb-42">
<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 className="relative overflow-hidden bg-gradient-radial-primary w-full py-20 pb-40">
+ <div className="absolute top-0 left-1/2 -translate-x-1/2 w-250 h-[150%] rounded-[100%] blur-xl pointer-events-none "></div>
+ <section className="w-full">
+ <div className="max-w-6xl mx-auto px-6 mb-14">
+ <EditorPreview />
+ </div>
+ {/* <BentoDemos /> */}
+ </section>
+ </div>
</div>
);
}
\ No newline at end of file
diff --git a/app/components/common/Header.tsx b/app/components/common/Header.tsx
index 24917ea..fcf3382 100644
--- a/app/components/common/Header.tsx
+++ b/app/components/common/Header.tsx
@@ -1,22 +1,29 @@
"use client";
-
import { useState, useEffect } from "react";
import Image from "next/image";
import { cn } from "@/lib/utils";
import { Link } from "@/navigation";
-import { hasAnyVideo } from "@/lib/video-cache-utils";
import { UserMenu } from "./UserMenu";
import { MobileMenu } from "./MobileMenu";
import { LanguageSwitcher } from "./LanguageSwitcher";
import { useTranslations } from "next-intl";
+import { Icon } from "@iconify/react";
+import { Button } from "@/components/ui/button";
+import { useRecording } from "@/hooks/RecordingContext";
+import RecordingSetupDialog from "../ui/RecordingSetupDialog";
+import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
export default function Header() {
+ const t = useTranslations('header');
+ const tRecording = useTranslations('recording.steps');
-const t = useTranslations('header');
const [isScrolled, setIsScrolled] = useState(false);
- const [hasCachedVideo, setHasCachedVideo] = useState(false);
const [isMounted, setIsMounted] = useState(false);
+ const { startCountdown, stopRecording, isIdle, isRecording, isCountdown, isProcessing } = useRecording();
+ const [setupDialogOpen, setSetupDialogOpen] = useState(false);
+ const [showMobileAlert, setShowMobileAlert] = useState(false);
+
useEffect(() => {
const timer = setTimeout(() => {
setIsMounted(true);
@@ -28,78 +35,119 @@ const t = useTranslations('header');
const handleScroll = () => {
setIsScrolled(window.scrollY > 20);
};
-
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
- useEffect(() => {
- const checkVideo = () => {
- hasAnyVideo().then(setHasCachedVideo).catch(() => {});
- };
-
- checkVideo();
+ const handleHeaderAction = () => {
+ if (isRecording) {
+ stopRecording();
+ return;
+ }
- const handleVisibilityChange = () => {
- if (!document.hidden) {
- checkVideo();
- }
- };
+ const isMobile = typeof window !== "undefined" &&
+ (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth < 768);
+
+ if (isMobile) {
+ setShowMobileAlert(true);
+ setTimeout(() => setShowMobileAlert(false), 5000);
+ } else {
+ setSetupDialogOpen(true);
+ }
+ };
- document.addEventListener("visibilitychange", handleVisibilityChange);
- return () => document.removeEventListener("visibilitychange", handleVisibilityChange);
- }, []);
+ const getButtonContent = () => {
+ if (isCountdown || isProcessing) {
+ return <Icon icon="eos-icons:loading" className="w-4 h-4 animate-spin" />;
+ }
+ if (isRecording) {
+ return <div className="w-2.5 h-2.5 bg-red-500 rounded-full animate-pulse" />;
+ }
+ return <Icon icon="material-symbols:cast-outline-rounded" className="w-4 h-4" />;
+ };
return (
- <header
- className={cn(
+ <>
+ <header className={cn(
"fixed top-0 w-full z-50 transition-all duration-300",
- isScrolled
- ? "border-b border-white/10 bg-[#050505]/80 backdrop-blur-xl py-0"
- : "bg-transparent border-transparent py-2"
+ isScrolled ? "border-b border-white/10 bg-[#050505]/80 backdrop-blur-xl py-0" : "bg-transparent border-transparent py-2"
)}
- >
- <div className="max-w-6xl mx-auto px-3 sm:px-6 h-16 flex items-center justify-between">
- <Link href="/" className="flex items-center gap-2 group">
- <Image src="/svg/logo-openvid.svg" alt="Logo" width={50} height={50} style={{ height: "auto" }} />
- <Image src="/svg/openvid.svg" alt="Logo" width={100} height={50} className="hidden sm:flex" style={{ height: "auto" }} />
- </Link>
+ >
+ <div className="max-w-6xl mx-auto px-3 sm:px-6 h-16 flex items-center justify-between">
+ <Link href="/" className="flex items-center gap-2 group">
+ <Image src="/svg/logo-openvid.svg" alt="Logo" width={50} height={50} style={{ height: "auto" }} />
+ <Image src="/svg/openvid.svg" alt="Logo" width={100} height={50} className="hidden sm:flex" style={{ height: "auto" }} />
+ </Link>
- <div className="hidden md:flex items-center gap-8 text-md font-medium text-neutral-400">
- <a href="#docs" className="hover:text-white transition-colors">{t('docs')}</a>
- <a href="https://github.com/CristianOlivera1/openvid" target="_blank" rel="noopener noreferrer" className="hover:text-white transition-colors">{t('github')}</a>
- {hasCachedVideo && (
- <Link href="/editor" className="hover:text-white transition-colors">
- {t('editor')}
- </Link>
- )}
- <Link href="/donate" target="_blank" className="hover:text-white transition-colors">{t('donate')}</Link>
- </div>
+ <div className="hidden md:flex items-center gap-8 text-md font-medium text-neutral-400">
+ <a href="#docs" className="hover:text-white transition-colors">{t('docs')}</a>
+ <a href="https://github.com/CristianOlivera1/openvid" target="_blank" rel="noopener noreferrer" className="hover:text-white transition-colors">{t('github')}</a>
+ <Link href="/donate" target="_blank" className="hover:text-white transition-colors">{t('donate')}</Link>
+ </div>
- <div className="flex items-center gap-2">
- {!isMounted ? (
- <div className="w-25 h-9 rounded-md bg-white/10 animate-pulse border border-white/5"></div>
- ) : (
- <LanguageSwitcher />
- )}
-
- <div className="block">
- {!isMounted ? (
- <div className="flex items-center gap-2 px-2 py-1">
- <div className="w-8 h-8 rounded-full bg-white/10 animate-pulse border border-white/5"></div>
- <div className="w-24 h-4 rounded-md bg-white/10 animate-pulse"></div>
+ <div className="flex items-center gap-3 sm:gap-6">
+ <Button
+ variant="outline"
+ onClick={handleHeaderAction}
+ disabled={isCountdown || isProcessing}
+ className={cn(
+ "transition-all hidden sm:flex",
+ isRecording && "border-red-500/50 text-red-400 hover:bg-red-500/5"
+ )}
+ >
+ {getButtonContent()}
+ <span className="text-xs font-bold tracking-tight">
+ {isRecording ? tRecording('step4.visual.stop') : t('screen')}
+ </span>
+ {!isRecording && (
+ <kbd className="hidden lg:flex items-center ml-1 px-1.5 py-0.5 rounded bg-black/20 border border-white/20 text-[9px] font-black text-white/80 uppercase">
+ Alt + S
+ </kbd>
+ )}
+ </Button>
+
+ <div className="flex items-center gap-2">
+ {!isMounted ? (
+ <div className="w-25 h-9 rounded-md bg-white/10 animate-pulse border border-white/5"></div>
+ ) : (
+ <LanguageSwitcher />
+ )}
+ <div className="block">
+ {!isMounted ? (
+ <div className="flex items-center gap-2 px-2 py-1">
+ <div className="w-8 h-8 rounded-full bg-white/10 animate-pulse border border-white/5"></div>
+ <div className="w-24 h-4 rounded-md bg-white/10 animate-pulse"></div>
+ </div>
+ ) : (
+ <UserMenu />
+ )}
</div>
- ) : (
- <UserMenu />
- )}
+
+ {!isMounted ? (
+ <div className="w-9 h-9 rounded-md bg-white/10 animate-pulse border border-white/5"></div>
+ ) : (
+ <MobileMenu />
+ )}
+ </div>
</div>
- {!isMounted ? (
- <div className="w-9 h-9 rounded-md bg-white/10 animate-pulse border border-white/5"></div>
- ) : (
- <MobileMenu />
- )}
</div>
- </div>
- </header>
+
+ {showMobileAlert && (
+ <div className="absolute top-20 left-1/2 -translate-x-1/2 w-full max-w-xs px-4">
+ <Alert variant="warning" className="bg-[#0A0A0A] border-yellow-500/50">
+ <Icon icon="solar:laptop-minimalistic-broken" className="text-xl" />
+ <AlertTitle>{tRecording('step1.permissionRequired')}</AlertTitle>
+ <AlertDescription>{tRecording('step1.mobileAlert')}</AlertDescription>
+ </Alert>
+ </div>
+ )}
+ </header>
+
+ <RecordingSetupDialog
+ open={setupDialogOpen}
+ onClose={() => setSetupDialogOpen(false)}
+ onStart={(config) => startCountdown(config)}
+ />
+ </>
);
}
\ No newline at end of file
diff --git a/app/components/common/LanguageSwitcher.tsx b/app/components/common/LanguageSwitcher.tsx
index 48baf0e..d3c1126 100644
--- a/app/components/common/LanguageSwitcher.tsx
+++ b/app/components/common/LanguageSwitcher.tsx
@@ -5,6 +5,7 @@ import { usePathname, useRouter } from '@/navigation';
import { useState, useTransition } from 'react';
import { Icon } from '@iconify/react';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
+import { Button } from '@/components/ui/button';
const languages = [
{ code: 'en', name: 'English', icon: 'circle-flags:us' },
@@ -33,9 +34,8 @@ export function LanguageSwitcher() {
return (
<DropdownMenu.Root open={isOpen} onOpenChange={setIsOpen}>
<DropdownMenu.Trigger asChild>
- <button
+ <Button variant="outline"
disabled={isPending}
- className="flex items-center gap-2 px-3 py-2 text-sm text-white/70 hover:text-white hover:bg-white/5 squircle-element transition-colors border border-white/10 disabled:opacity-50"
>
<Icon icon={currentLanguage.icon} width="18" height="18" />
<span className="hidden sm:inline font-medium">{currentLanguage.code.toUpperCase()}</span>
@@ -44,7 +44,7 @@ export function LanguageSwitcher() {
width="14"
className={`transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
/>
- </button>
+ </Button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
diff --git a/app/components/common/MobileMenu.tsx b/app/components/common/MobileMenu.tsx
index 7a677a9..cc2a2ff 100644
--- a/app/components/common/MobileMenu.tsx
+++ b/app/components/common/MobileMenu.tsx
@@ -126,38 +126,39 @@ export function MobileMenu() {
<Icon icon="solar:external-link-linear" className="w-4 h-4 ml-auto opacity-50" />
</a>
- {hasCachedVideo && (
- <Link
- href="/editor"
- onClick={closeMenu}
- className="flex items-center gap-3 px-4 py-3 text-blue-400 hover:text-blue-300 hover:bg-blue-500/10 rounded-lg transition-colors"
- >
- <Icon icon="solar:video-frame-cut-2-linear" className="w-5 h-5" />
- <span>{t('editor')}</span>
- </Link>
- )}
+ <a
+ href="/donate"
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={closeMenu}
+ className="flex items-center gap-3 px-4 py-3 text-neutral-300 hover:text-white hover:bg-white/5 rounded-lg transition-colors"
+ >
+ <Icon icon="mdi:donate" className="w-5 h-5" />
+ <span>{t('donate')}</span>
+ <Icon icon="solar:external-link-linear" className="w-4 h-4 ml-auto opacity-50" />
+ </a>
</div>
</nav>
<div className="p-4 border-t border-white/5">
{user ? (
- <button
- onClick={handleSignOut}
- disabled={isLoggingOut}
- className="w-full flex items-center justify-center gap-3 px-4 py-2 bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white rounded-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed border border-red-500/20 text-sm"
- >
- {isLoggingOut ? (
- <>
- <Icon icon="svg-spinners:ring-resize" className="w-5 h-5 animate-spin" />
- <span className="font-medium">{t('loggingOut')}</span>
- </>
- ) : (
- <>
- <Icon icon="solar:logout-2-linear" className="w-5 h-5" />
- <span className="font-medium">{t('logout')}</span>
- </>
- )}
- </button>
+ <button
+ onClick={handleSignOut}
+ disabled={isLoggingOut}
+ className="w-full flex items-center justify-center gap-3 px-4 py-2 bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white rounded-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed border border-red-500/20 text-sm"
+ >
+ {isLoggingOut ? (
+ <>
+ <Icon icon="svg-spinners:ring-resize" className="w-5 h-5 animate-spin" />
+ <span className="font-medium">{t('loggingOut')}</span>
+ </>
+ ) : (
+ <>
+ <Icon icon="solar:logout-2-linear" className="w-5 h-5" />
+ <span className="font-medium">{t('logout')}</span>
+ </>
+ )}
+ </button>
) : (
<Button variant="primary" asChild className="w-full">
<Link
diff --git a/app/components/ui/AspectRatioSelect.tsx b/app/components/ui/AspectRatioSelect.tsx
index b042d95..c6c9357 100644
--- a/app/components/ui/AspectRatioSelect.tsx
+++ b/app/components/ui/AspectRatioSelect.tsx
@@ -1,10 +1,9 @@
+"use client";
+
import { useState } from "react";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Icon } from "@iconify/react";
+import { useTranslations } from "next-intl";
import type { AspectRatio } from "@/types";
import { TooltipAction } from "@/components/ui/tooltip-action";
@@ -15,21 +14,26 @@ interface AspectRatioSelectProps {
onCustomDimensionsChange?: (dimensions: { width: number; height: number }) => void;
}
-const STANDARD_RATIOS: Partial<Record<AspectRatio, string>> = {
- "auto": "Auto",
- "16:9": "16:9 YouTube",
- "9:16": "9:16 TikTok",
- "1:1": "1:1 Instagram",
- "4:3": "4:3",
- "3:4": "3:4",
-};
-
-export function AspectRatioSelect({ value, onChange, customDimensions, onCustomDimensionsChange }: AspectRatioSelectProps) {
+export function AspectRatioSelect({
+ value,
+ onChange,
+ customDimensions,
+ onCustomDimensionsChange,
+}: AspectRatioSelectProps) {
+ const t = useTranslations("aspectRatioSelect");
const [isOpen, setIsOpen] = useState(false);
-
const [tempWidth, setTempWidth] = useState("");
const [tempHeight, setTempHeight] = useState("");
+ const STANDARD_RATIOS: Array<{ id: AspectRatio; label: string; subLabel?: string }> = [
+ { id: "auto", label: t("labels.auto") },
+ { id: "16:9", label: t("labels.youtube"), subLabel: "16:9" },
+ { id: "9:16", label: t("labels.tiktok"), subLabel: "9:16" },
+ { id: "1:1", label: t("labels.instagram"), subLabel: "1:1" },
+ { id: "4:3", label: "Estándar", subLabel: "4:3" },
+ { id: "3:4", label: "Retrato", subLabel: "3:4" },
+ ];
+
const handleOpenChange = (open: boolean) => {
if (open) {
setTempWidth(customDimensions?.width?.toString() || "1920");
@@ -46,7 +50,6 @@ export function AspectRatioSelect({ value, onChange, customDimensions, onCustomD
const handleCustomApply = () => {
const width = parseInt(tempWidth);
const height = parseInt(tempHeight);
-
if (width > 0 && height > 0 && onCustomDimensionsChange) {
onCustomDimensionsChange({ width, height });
onChange("custom");
@@ -58,19 +61,37 @@ export function AspectRatioSelect({ value, onChange, customDimensions, onCustomD
if (value === "custom" && customDimensions) {
return `${customDimensions.width}x${customDimensions.height}`;
}
- if (value === "auto") {
- return "Auto";
- }
- return STANDARD_RATIOS[value as keyof typeof STANDARD_RATIOS] || "Personalizado";
+ const standard = STANDARD_RATIOS.find((r) => r.id === value);
+ return standard ? standard.label : t("labels.custom");
})();
+ // Componente interno para dibujar las figuritas de los rectángulos/cuadrados
+ const RatioShape = ({ ratio, isSelected }: { ratio: AspectRatio; isSelected: boolean }) => {
+ if (ratio === "auto") {
+ return <Icon icon="lucide:maximize" width="24" className={isSelected ? "text-primary" : "opacity-60"} />;
+ }
+
+ const aspectClasses: Record<string, string> = {
+ "16:9": "aspect-video w-9",
+ "9:16": "aspect-[9/16] h-9",
+ "1:1": "aspect-square h-8",
+ "4:3": "aspect-[4/3] w-9",
+ "3:4": "aspect-[3/4] h-9",
+ };
+
+ return (
+ <div
+ className={`border-2 squircle-element transition-colors ${aspectClasses[ratio] || "aspect-square w-6"} ${isSelected ? "border-primary" : "border-foreground/40 group-hover:border-foreground/70"
+ }`}
+ />
+ );
+ };
+
return (
<Popover open={isOpen} onOpenChange={handleOpenChange}>
- <TooltipAction label="Seleccionar proporción de aspecto">
+ <TooltipAction label={t("tooltip")}>
<PopoverTrigger asChild>
- <button
- className="flex items-center gap-2 h-8 px-3 text-xs font-medium border border-input bg-background rounded-md hover:bg-accent hover:text-accent-foreground transition-colors w-full sm:w-auto"
- >
+ <button className="flex items-center gap-2 h-8 px-3 text-xs font-medium border border-white/20 bg-black squircle-element hover:bg-accent hover:text-accent-foreground transition-colors w-full sm:w-auto">
<Icon icon="mynaui:layout" width="16" className="shrink-0" />
<span className="truncate">{displayLabel}</span>
<Icon icon="lucide:chevron-down" width="14" className="ml-auto opacity-50 shrink-0" />
@@ -78,73 +99,90 @@ export function AspectRatioSelect({ value, onChange, customDimensions, onCustomD
</PopoverTrigger>
</TooltipAction>
- <PopoverContent className="w-64 p-2" align="start">
- <div className="flex flex-col gap-1">
-
- <div className="flex flex-col">
- {(Object.keys(STANDARD_RATIOS) as AspectRatio[]).map((ratio) => (
- <button
- key={ratio}
- onClick={() => handleStandardRatioClick(ratio)}
- className={`flex items-center w-full px-2 py-1.5 text-sm rounded-sm transition-colors
- ${value === ratio
- ? "bg-accent text-accent-foreground font-medium"
- : "hover:bg-accent hover:text-accent-foreground text-muted-foreground"
- }
- `}
- >
- <span className="flex-1 text-left">{STANDARD_RATIOS[ratio]}</span>
- {value === ratio && (
- <Icon icon="lucide:check" width="16" className="shrink-0" />
- )}
- </button>
- ))}
+ <PopoverContent className="w-72 p-3" align="start">
+ <div className="flex flex-col gap-4">
+
+ <div className="grid grid-cols-3 gap-2">
+ {STANDARD_RATIOS.map((item) => {
+ const isSelected = value === item.id;
+ return (
+ <button
+ key={item.id}
+ onClick={() => handleStandardRatioClick(item.id)}
+ className={`group flex flex-col items-center justify-center gap-2 p-2.5 squircle-element border transition-all ${isSelected
+ ? "border-primary bg-gradient-radial-primary text-primary"
+ : "border-white/20 bg-transparent hover:border-border hover:bg-accent text-muted-foreground"
+ }`}
+ >
+ <div className="h-10 flex items-center justify-center">
+ <RatioShape ratio={item.id} isSelected={isSelected} />
+ </div>
+ <div className="text-[10px] font-medium text-center leading-tight">
+ <span className={`block ${isSelected ? "text-primary font-semibold" : "text-foreground"}`}>
+ {item.label}
+ </span>
+ {item.subLabel && (
+ <span className="block opacity-70 mt-0.5 tracking-wider font-mono text-[10px]">
+ {item.subLabel}
+ </span>
+ )}
+ </div>
+ </button>
+ );
+ })}
</div>
- <div className="h-px bg-border my-2 mx-1" />
+ <div className="h-px bg-border/60 mx-1" />
- <div className="px-2 pb-1">
- <div className="flex items-center justify-between mb-2">
- <span className="text-xs font-medium text-foreground">Personalizado</span>
+ <div className="px-1 pb-1">
+ <div className="flex items-center justify-between mb-3">
+ <span className="text-xs font-medium text-foreground">
+ {t("customSection.title")}
+ </span>
{value === "custom" && (
- <Icon icon="lucide:check" width="14" className="text-accent-foreground" />
+ <span className="text-[10px] font-medium bg-primary/20 text-primary px-2 py-0.5 rounded-full">
+ Activo
+ </span>
)}
</div>
<div className="flex items-center gap-2 mb-3">
- <div className="flex-1">
+ <div className="relative flex-1">
+ <span className="absolute left-2.5 top-1/2 -translate-y-1/2 text-[10px] font-medium text-muted-foreground">
+ W
+ </span>
<input
type="number"
min="1"
max="7680"
value={tempWidth}
onChange={(e) => setTempWidth(e.target.value)}
- placeholder="Ancho"
- className="w-full h-8 px-2 text-xs border border-input bg-background rounded-md focus:outline-none focus:ring-1 focus:ring-ring"
+ className="w-full h-8 pl-7 pr-2 text-xs border border-input bg-background squircle-element focus:outline-none focus:ring-1 focus:ring-primary font-mono transition-shadow"
/>
</div>
- <span className="text-muted-foreground text-xs">x</span>
- <div className="flex-1">
+ <Icon icon="lucide:x" width="12" className="text-muted-foreground" />
+ <div className="relative flex-1">
+ <span className="absolute left-2.5 top-1/2 -translate-y-1/2 text-[10px] font-medium text-muted-foreground">
+ H
+ </span>
<input
type="number"
min="1"
max="4320"
value={tempHeight}
onChange={(e) => setTempHeight(e.target.value)}
- placeholder="Alto"
- className="w-full h-8 px-2 text-xs border border-input bg-background rounded-md focus:outline-none focus:ring-1 focus:ring-ring"
+ className="w-full h-8 pl-7 pr-2 text-xs border border-input bg-background squircle-element focus:outline-none focus:ring-1 focus:ring-primary font-mono transition-shadow"
/>
</div>
</div>
<button
onClick={handleCustomApply}
- className="w-full h-8 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 rounded-md transition-colors"
+ className="w-full h-8 text-xs font-medium bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-border squircle-element transition-colors"
>
- Aplicar medidas
+ {t("customSection.apply")}
</button>
</div>
-
</div>
</PopoverContent>
</Popover>
diff --git a/app/components/ui/BentoDemos.tsx b/app/components/ui/BentoDemos.tsx
new file mode 100644
index 0000000..d97f6cf
--- /dev/null
+++ b/app/components/ui/BentoDemos.tsx
@@ -0,0 +1,102 @@
+"use client";
+import React, { useEffect, useRef } from "react";
+import gsap from "gsap";
+import { ScrollTrigger } from "gsap/ScrollTrigger";
+
+gsap.registerPlugin(ScrollTrigger);
+const bentoVideos = [
+ {
+ id: 1,
+ src: "https://domare.hernandack.com/uploads/19bf07ca35f55af46ea6396865198c5c.mp4",
+ className: "",
+ },
+ {
+ id: 2,
+ src: "https://www.w3schools.com/html/mov_bbb.mp4",
+ className: "min-[690px]:col-[2/3] min-[690px]:row-span-2",
+ },
+ {
+ id: 3,
+ src: "https://domare.hernandack.com/uploads/19bf07ca35f55af46ea6396865198c5c.mp4",
+ className:
+ "min-[690px]:col-span-2 max-[690px]:col-[2/4] max-[690px]:row-[1/2] max-[470px]:col-auto max-[470px]:row-auto",
+ },
+ {
+ id: 4,
+ src: "https://www.w3schools.com/html/mov_bbb.mp4",
+ className: "",
+ },
+ {
+ id: 5,
+ src: "/images/pages/demo.mp4",
+ className: "min-[690px]:col-[3/5] min-[690px]:row-[2/3] max-[470px]:col-span-2",
+ },
+];
+
+
+export function BentoDemos() {
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const ctx = gsap.context(() => {
+ gsap.fromTo(
+ ".bento-card",
+ {
+ y: 80,
+ opacity: 0,
+ scale: 0.85,
+ rotateX: -15,
+ filter: "blur(12px)",
+ transformOrigin: "center bottom",
+ },
+ {
+ y: 0,
+ opacity: 1,
+ scale: 1,
+ rotateX: 0,
+ filter: "blur(0px)",
+ duration: 1.4,
+ stagger: {
+ amount: 0.5,
+ from: "start",
+ },
+ ease: "expo.out",
+ scrollTrigger: {
+ trigger: containerRef.current,
+ start: "top 80%",
+ toggleActions: "play none none none",
+ },
+ }
+ );
+ }, containerRef);
+
+ return () => ctx.revert();
+ }, []);
+
+ return (
+ <section
+ ref={containerRef}
+ className="grid place-content-center gap-[15px] p-[max(2vh,1.5rem)] w-full h-[80vh] min-h-[460px] grid-cols-[25%_30%_15%_25%] grid-rows-2 max-[690px]:h-[65vh] max-[470px]:grid-cols-2 max-[470px]:grid-rows-3 perspective-[1200px]"
+ >
+ {bentoVideos.map((item) => (
+ <div
+ key={item.id}
+ className={`bento-card group relative rounded-[25px] overflow-hidden bg-zinc-900 border border-white/10 shadow-lg transition-all duration-500 ease-out hover:-translate-y-2 hover:shadow-[0_20px_40px_rgba(0,0,0,0.5)] hover:border-white/30 z-0 hover:z-10 ${item.className}`}
+ >
+ <div className="absolute inset-0 bg-black/20 z-10 transition-opacity duration-700 group-hover:opacity-0 pointer-events-none" />
+
+ <video
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full h-full object-cover transition-transform duration-700 ease-out group-hover:scale-110"
+ >
+ <source src={item.src} type="video/mp4" />
+ Tu navegador no soporta el tag de video.
+ </video>
+ </div>
+ ))}
+ </section>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/DemoVideo.tsx b/app/components/ui/DemoVideo.tsx
index 77185be..0595452 100644
--- a/app/components/ui/DemoVideo.tsx
+++ b/app/components/ui/DemoVideo.tsx
@@ -40,7 +40,7 @@ export default function DemoVideo() {
}, [features.length]);
return (
- <div className="w-full flex flex-col items-center mb-30">
+ <div className="w-full flex flex-col items-center pb-30">
<h2 className="text-4xl md:text-6xl text-center font-bold tracking-tighter text-white mb-10 leading-tight drop-shadow-[1.2px_1.2px_100.2px_rgba(183,203,248,1)]">
{t('title')} <br />
<span className="bg-linear-to-r from-[#003780] to-white bg-clip-text text-transparent">
diff --git a/app/components/ui/EditorPreview.tsx b/app/components/ui/EditorPreview.tsx
index ade28b2..7589bca 100644
--- a/app/components/ui/EditorPreview.tsx
+++ b/app/components/ui/EditorPreview.tsx
@@ -1,8 +1,11 @@
'use client';
import { useEffect, useRef } from 'react';
import Atropos from 'atropos';
+import { useTranslations } from 'next-intl';
export default function EditorPreview() {
+ const t = useTranslations('demo');
+
const atroposRef = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -22,22 +25,27 @@ export default function EditorPreview() {
return (
<div className="relative max-w-6xl mx-auto mt-30 sm:mt-0 hero-perspective-container">
-
+ <h2 className="text-4xl md:text-6xl text-center font-bold tracking-tighter text-white mb-10 leading-tight drop-shadow-[1.2px_1.2px_100.2px_rgba(183,203,248,1)]">
+ {t('title')} <br />
+ <span className="bg-linear-to-r from-[#003780] to-white bg-clip-text text-transparent">
+ {t('subtitle')}
+ </span>
+ </h2>
<div className="hero-3d-wrapper relative w-full">
-
+
<div ref={atroposRef} className="atropos w-full rounded-2xl">
<div className="atropos-scale">
<div className="atropos-rotate">
<div className="atropos-inner rounded-2xl">
-
- <div
+
+ <div
className="absolute -inset-1 bg-linear-to-b from-neutral-700/10 to-transparent rounded-2xl blur-md -z-10"
data-atropos-offset="-5"
></div>
-
- <img
+
+ <img
src="/images/pages/openvid2.webp"
- alt="openvid Editor Preview"
+ alt="openvid Editor Preview"
className="w-full h-auto object-cover rounded-xl"
loading="lazy"
data-atropos-offset="3"
diff --git a/app/components/ui/ExportImageDropdown.tsx b/app/components/ui/ExportImageDropdown.tsx
new file mode 100644
index 0000000..45c706f
--- /dev/null
+++ b/app/components/ui/ExportImageDropdown.tsx
@@ -0,0 +1,296 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Icon } from "@iconify/react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { useState, useCallback, useMemo } from "react";
+import { useTranslations } from "next-intl";
+import type { ImageExportFormat } from "@/types/image-project.types";
+
+interface ImageExportProgress {
+ status: "idle" | "preparing" | "rendering" | "complete" | "error";
+ progress: number;
+ message: string;
+}
+
+interface ExportImageDropdownProps {
+ onExport: (format: ImageExportFormat, quality: number, scale: number) => void;
+ exportProgress: ImageExportProgress;
+ hasTransparentBackground?: boolean;
+ canvasWidth?: number;
+ canvasHeight?: number;
+}
+
+interface FormatOption {
+ format: ImageExportFormat;
+ label: string;
+ description: string;
+ icon: string;
+ supportsTransparency: boolean;
+}
+
+interface ExportPreset {
+ scale: number;
+ quality: number;
+ label: string;
+ description: string;
+ icon: string;
+ recommended?: boolean;
+}
+
+const FORMAT_OPTIONS: FormatOption[] = [
+ {
+ format: "png",
+ label: "PNG",
+ description: "Sin pérdida, soporta transparencia",
+ icon: "mdi:file-png-box",
+ supportsTransparency: true,
+ },
+ {
+ format: "avif",
+ label: "AVIF",
+ description: "Mejor compresión moderna",
+ icon: "mdi:image-multiple",
+ supportsTransparency: true,
+ },
+ {
+ format: "webp",
+ label: "WebP",
+ description: "Compresión eficiente",
+ icon: "mdi:web",
+ supportsTransparency: true,
+ },
+ {
+ format: "jpeg",
+ label: "JPEG",
+ description: "Compatible universal",
+ icon: "mdi:file-jpg-box",
+ supportsTransparency: false,
+ },
+];
+
+export function ExportImageDropdown({
+ onExport,
+ exportProgress,
+ hasTransparentBackground,
+ canvasWidth = 1920,
+ canvasHeight = 1080,
+}: ExportImageDropdownProps) {
+ const t = useTranslations("editor.exportImage");
+ const [isOpen, setIsOpen] = useState(false);
+ const [selectedFormat, setSelectedFormat] = useState<ImageExportFormat>("png");
+
+ const isExporting =
+ exportProgress.status !== "idle" &&
+ exportProgress.status !== "complete" &&
+ exportProgress.status !== "error";
+
+ const isTransparent = !!hasTransparentBackground;
+
+ const qualityPresets = useMemo((): ExportPreset[] => {
+ const isPng = selectedFormat === "png";
+ const isLossy = selectedFormat === "jpeg" || selectedFormat === "webp" || selectedFormat === "avif";
+
+ if (isPng) {
+ return [
+ {
+ scale: 4,
+ quality: 1,
+ label: "4K Ultra (4x)",
+ description: `${canvasWidth * 4} × ${canvasHeight * 4}`,
+ icon: "mdi:image-size-select-large",
+ },
+ {
+ scale: 2,
+ quality: 1,
+ label: "HD Retina (2x)",
+ description: `${canvasWidth * 2} × ${canvasHeight * 2}`,
+ icon: "mdi:image-multiple-outline",
+ recommended: true,
+ },
+ {
+ scale: 1,
+ quality: 1,
+ label: "Original (1x)",
+ description: `${canvasWidth} × ${canvasHeight}`,
+ icon: "mdi:image-outline",
+ },
+ ];
+ }
+
+ if (isLossy) {
+ return [
+ {
+ scale: 4,
+ quality: 0.95,
+ label: "4K Alta Calidad (4x)",
+ description: `${canvasWidth * 4} × ${canvasHeight * 4} · 95%`,
+ icon: "mdi:image-size-select-large",
+ },
+ {
+ scale: 2,
+ quality: 0.95,
+ label: "HD Alta Calidad (2x)",
+ description: `${canvasWidth * 2} × ${canvasHeight * 2} · 95%`,
+ icon: "mdi:image-multiple-outline",
+ recommended: true,
+ },
+ {
+ scale: 1,
+ quality: 0.95,
+ label: "Original Alta (1x)",
+ description: `${canvasWidth} × ${canvasHeight} · 95%`,
+ icon: "mdi:image-outline",
+ },
+ {
+ scale: 1,
+ quality: 0.8,
+ label: "Original Media (1x)",
+ description: `${canvasWidth} × ${canvasHeight} · 80%`,
+ icon: "mdi:image-outline",
+ },
+ {
+ scale: 1,
+ quality: 0.6,
+ label: "Original Comprimida (1x)",
+ description: `${canvasWidth} × ${canvasHeight} · 60%`,
+ icon: "mdi:image-outline",
+ },
+ ];
+ }
+
+ return [];
+ }, [selectedFormat, canvasWidth, canvasHeight]);
+
+ const handleExport = useCallback(
+ (preset: ExportPreset) => {
+ setIsOpen(false);
+ onExport(selectedFormat, preset.quality, preset.scale);
+ },
+ [onExport, selectedFormat]
+ );
+
+ const showTransparencyWarning = isTransparent && selectedFormat === "jpeg";
+
+ return (
+ <Popover open={isOpen} onOpenChange={setIsOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="primary"
+ className="px-3 py-2 text-sm gap-2 min-w-27.5"
+ size="sm"
+ disabled={isExporting}
+ >
+ <Icon icon="icon-park-outline:export" width="18" />
+ {t("button")}
+ <Icon icon="icon-park-outline:chevron-down" width="16" className="opacity-50" />
+ </Button>
+ </PopoverTrigger>
+
+ <PopoverContent
+ align="end"
+ className="w-80 bg-black border-white/15 text-white shadow-2xl p-0 rounded-xl overflow-hidden"
+ >
+ <div className="px-6 py-4 border-b border-white/10 flex justify-between items-center bg-white/3">
+ <span className="text-[10px] font-medium uppercase tracking-[0.15em] text-white/50">
+ {t("title") || "Formato"}
+ </span>
+ {isTransparent && (
+ <div className="flex items-center gap-2 px-2 py-0.5 rounded-full bg-cyan-500/10 border border-cyan-500/20 backdrop-blur-md">
+ <div className="size-1 bg-cyan-400 rounded-full animate-pulse shadow-[0_0_8px_rgba(34,211,238,0.8)]" />
+
+ <span className="text-[9px] font-bold uppercase tracking-wider text-cyan-400/90">
+ Transparente
+ </span>
+ </div>
+ )}
+ </div>
+
+ <div className="p-4 grid grid-cols-4 gap-3">
+ {FORMAT_OPTIONS.map((opt) => {
+ const isSelected = selectedFormat === opt.format;
+ const disabled = isTransparent && !opt.supportsTransparency;
+
+ return (
+ <button
+ key={opt.format}
+ onClick={() => !disabled && setSelectedFormat(opt.format)}
+ disabled={disabled}
+ className={`relative flex flex-col items-center gap-2 transition-all duration-300 group ${disabled ? "opacity-20 cursor-not-allowed" : "cursor-pointer"
+ }`}
+ >
+ <div
+ className={`relative size-12 rounded-2xl flex items-center justify-center transition-all duration-300 border ${isSelected
+ ? "border-white/30 scale-105"
+ : "border-white/10 hover:border-white/20"
+ }`}
+ style={{
+ background: isSelected
+ ? "radial-gradient(circle at 50% 0%, rgb(85, 85, 85) 0%, rgb(40, 40, 40) 80%)"
+ : "transparent",
+ boxShadow: isSelected
+ ? "rgb(255, 255, 255) 0px 0.5rem 0.2rem -0.5rem inset, rgba(255, 255, 255, 0.1) 0px 0px 0px 1px"
+ : "none",
+ }}
+ >
+ <Icon
+ icon={opt.icon}
+ width="22"
+ className={`${isSelected ? "text-white" : "text-white/40 group-hover:text-white/60"}`}
+ />
+
+ {isSelected && (
+ <div className="absolute left-1.5 top-1.5 size-4 bg-white rounded-full blur-[6px] opacity-30 rotate-45" />
+ )}
+ </div>
+ <span
+ className={`text-[9px] font-bold tracking-tighter ${isSelected ? "text-white" : "text-white/40"
+ }`}
+ >
+ {opt.label}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="px-2 pb-2">
+ <div className="bg-white/3 rounded-2xl border border-white/10 overflow-hidden max-h-64 overflow-y-auto custom-scrollbar">
+ {qualityPresets.map((preset, i) => (
+ <button
+ key={i}
+ onClick={() => handleExport(preset)}
+ className="w-full flex items-center justify-between p-4 hover:bg-white/5 transition-colors border-b border-white/10 last:border-0 group"
+ >
+ <div className="flex flex-col items-start gap-1">
+ <div className="flex items-center gap-2">
+ <span className="text-[13px] font-medium text-white/90 group-hover:text-white">
+ {preset.label}
+ </span>
+ {preset.recommended && (
+ <span className="border border-blue-500/30 text-blue-400 text-[9px] px-2 py-0.5 rounded-full font-bold tracking- ">
+ {t("recommended") || "Rec"}
+ </span>
+ )}
+ </div>
+ <span className="text-[10px] font-mono text-white/30">
+ {preset.description}
+ </span>
+ </div>
+
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {showTransparencyWarning && (
+ <div className="p-3 bg-red-500/10 text-center">
+ <p className="text-[9px] uppercase tracking-widest text-red-400 font-bold">
+ {t("noTransparency") || "Sin Transparencia"}
+ </p>
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/ExportOverlay.tsx b/app/components/ui/ExportOverlay.tsx
index 462ff46..d9783f9 100644
--- a/app/components/ui/ExportOverlay.tsx
+++ b/app/components/ui/ExportOverlay.tsx
@@ -2,6 +2,7 @@
import { Button } from "@/components/ui/button";
import { Icon } from "@iconify/react";
+import { useTranslations } from "next-intl";
interface ExportProgress {
status: "idle" | "preparing" | "encoding" | "finalizing" | "complete" | "error";
@@ -16,15 +17,35 @@ interface ExportOverlayProps {
}
export function ExportOverlay({ exportProgress, onCancel, isTransparentExport }: ExportOverlayProps) {
+ const t = useTranslations("exportOverlay");
+
const isExporting = exportProgress.status !== "idle" &&
exportProgress.status !== "complete" &&
exportProgress.status !== "error";
if (!isExporting) return null;
+ const getStatusMessage = () => {
+ switch (exportProgress.status) {
+ case "preparing":
+ return t("status.preparing");
+ case "encoding":
+ return exportProgress.message.startsWith("[Paso 1/2]")
+ ? t("status.capturing")
+ : t("status.encoding");
+ case "finalizing":
+ return exportProgress.message.startsWith("[Paso 2/2]")
+ ? t("status.encodingWebM")
+ : t("status.finalizing");
+ default:
+ return "";
+ }
+ };
+
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-md transition-all duration-500">
<div className="p-10 bg-black border border-white/10 rounded-2xl shadow-[0_0_80px_-15px_rgba(0,0,0,1)] w-full max-w-lg mx-4">
+
<div className="flex justify-center mb-8">
<div className="flex items-center gap-2.5 px-3 py-1 bg-white/3 border border-white/10 rounded-full">
<div className="relative flex h-2 w-2">
@@ -32,7 +53,7 @@ export function ExportOverlay({ exportProgress, onCancel, isTransparentExport }:
<span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500"></span>
</div>
<span className="text-[10px] font-bold uppercase tracking-[0.3em] text-white/50">
- Procesando Video
+ {t("processing")}
</span>
</div>
</div>
@@ -53,19 +74,8 @@ export function ExportOverlay({ exportProgress, onCancel, isTransparentExport }:
<div className="space-y-4 mb-10">
<div className="flex flex-col gap-2 border-l-2 border-white/10 pl-5 py-1">
<p className="text-lg font-medium tracking-tight leading-none shimmer-text">
- {exportProgress.status === "preparing" && "Preparando entorno de renderizado"}
- {exportProgress.status === "encoding" && (
- exportProgress.message.startsWith("[Paso 1/2]")
- ? "Capturando frames PNG (Paso 1 de 2)"
- : "Codificando secuencia de video"
- )}
- {exportProgress.status === "finalizing" && (
- exportProgress.message.startsWith("[Paso 2/2]")
- ? "Codificando video WebM (Paso 2 de 2)"
- : "Empaquetando archivos finales"
- )}
+ {getStatusMessage()}
</p>
-
<p className="text-sm text-white/40 font-mono italic mt-0.5 tracking-wide">
{exportProgress.message.replace(/^\[Paso \d\/\d\] /, "")}
</p>
@@ -74,14 +84,16 @@ export function ExportOverlay({ exportProgress, onCancel, isTransparentExport }:
<div className="flex items-start gap-3 p-4 bg-white/5 border border-white/10 rounded-xl">
<Icon icon="lucide:alert-circle" className="text-blue-500 shrink-0 mt-0.5" width="18" />
<p className="text-md text-white/60 leading-relaxed">
- Para optimizar los recursos de la GPU y CPU,{" "}
- <span className="relative font-bold text-white px-1">
- evita minimizar esta ventana
- <svg className="absolute -bottom-1 left-0 w-full h-2 text-blue-500/90" viewBox="0 0 100 10" preserveAspectRatio="none">
- <path d="M0 5 Q 25 0, 50 5 T 100 5" stroke="currentColor" strokeWidth="2" fill="transparent" strokeLinecap="round" />
- </svg>
- </span>
- . El proceso es intensivo y requiere prioridad del sistema.
+ {t.rich("warnings.performance", {
+ highlight: (chunks) => (
+ <span className="relative font-bold text-white px-1">
+ {chunks}
+ <svg className="absolute -bottom-1 left-0 w-full h-2 text-blue-500/90" viewBox="0 0 100 10" preserveAspectRatio="none">
+ <path d="M0 5 Q 25 0, 50 5 T 100 5" stroke="currentColor" strokeWidth="2" fill="transparent" strokeLinecap="round" />
+ </svg>
+ </span>
+ )
+ })}
</p>
</div>
@@ -89,13 +101,12 @@ export function ExportOverlay({ exportProgress, onCancel, isTransparentExport }:
<div className="flex items-start gap-3 p-4 bg-cyan-500/5 border border-cyan-500/20 rounded-xl">
<Icon icon="lucide:clock" className="text-cyan-400 shrink-0 mt-0.5" width="18" />
<p className="text-md text-cyan-400/80 leading-relaxed">
- Este proceso puede tardar más de lo habitual. La exportación{" "}
- <span className="font-semibold text-cyan-300">WebM con transparencia</span>{" "}
- requiere procesamiento adicional por CPU.
+ {t.rich("warnings.transparency", {
+ highlight: (chunks) => <span className="font-semibold text-cyan-300">{chunks}</span>
+ })}
</p>
</div>
)}
-
</div>
<Button
@@ -104,9 +115,9 @@ export function ExportOverlay({ exportProgress, onCancel, isTransparentExport }:
className="w-full h-12 bg-transparent hover:bg-red-500/5 border border-white/10 hover:border-red-500/20 text-white/60 hover:text-red-400 text-sm font-medium transition-all duration-300 rounded-xl"
>
<Icon icon="iconoir:cancel" width="16" className="mr-2" />
- Detener exportación
+ {t("actions.cancel")}
</Button>
</div>
</div>
);
-}
+}
\ No newline at end of file
diff --git a/app/components/ui/Hero.tsx b/app/components/ui/Hero.tsx
index a836de8..6bba424 100644
--- a/app/components/ui/Hero.tsx
+++ b/app/components/ui/Hero.tsx
@@ -1,158 +1,277 @@
"use client";
-
-import { Button } from "@/components/ui/button";
import { Icon } from "@iconify/react";
import { useRef, useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { saveUploadedVideo } from "@/lib/video-upload-cache";
+import { saveUploadedImage } from "@/lib/image-upload-cache";
import { useLocale, useTranslations } from "next-intl";
+import Link from "next/link";
interface HeroProps {
onVideoUpload?: (file: File) => void;
+ onPhotoUpload?: (file: File) => void;
}
-export default function Hero({ onVideoUpload }: HeroProps) {
- const t = useTranslations('hero');
- const fileInputRef = useRef<HTMLInputElement>(null);
- const [isDragging, setIsDragging] = useState(false);
- const [isUploading, setIsUploading] = useState(false);
+export default function Hero({ onVideoUpload, onPhotoUpload }: HeroProps) {
+ const t = useTranslations("hero");
const router = useRouter();
+ const locale = useLocale();
- const handleFile = useCallback(async (file: File) => {
- if (!file.type.startsWith("video/")) return;
- setIsUploading(true);
- try {
- await saveUploadedVideo(file);
+ const videoInputRef = useRef<HTMLInputElement>(null);
+ const [isDraggingVideo, setIsDraggingVideo] = useState(false);
+ const [isUploadingVideo, setIsUploadingVideo] = useState(false);
- if (onVideoUpload) {
- onVideoUpload(file);
+ const handleVideoFile = useCallback(
+ async (file: File) => {
+ if (!file.type.startsWith("video/")) return;
+ setIsUploadingVideo(true);
+ try {
+ await saveUploadedVideo(file);
+ if (onVideoUpload) {
+ onVideoUpload(file);
+ }
+ router.push("/editor?mode=video");
+ } catch (error) {
+ console.error("Error uploading video:", error);
+ setIsUploadingVideo(false);
}
+ },
+ [onVideoUpload, router]
+ );
- router.push("/editor");
- } catch (error) {
- console.error("Error uploading video:", error);
- setIsUploading(false);
- }
- }, [onVideoUpload, router]);
-
- const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const handleVideoFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
- if (file) handleFile(file);
+ if (file) handleVideoFile(file);
e.target.value = "";
};
- const handleDragOver = (e: React.DragEvent) => {
+ const handleVideoDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
- setIsDragging(true);
+ setIsDraggingVideo(true);
};
- const handleDragLeave = (e: React.DragEvent) => {
+ const handleVideoDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
- setIsDragging(false);
+ setIsDraggingVideo(false);
};
- const handleDrop = (e: React.DragEvent) => {
+ const handleVideoDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
- setIsDragging(false);
+ setIsDraggingVideo(false);
const file = e.dataTransfer.files?.[0];
- if (file) handleFile(file);
+ if (file) handleVideoFile(file);
+ };
+
+ const photoInputRef = useRef<HTMLInputElement>(null);
+ const [isDraggingPhoto, setIsDraggingPhoto] = useState(false);
+ const [isUploadingPhoto, setIsUploadingPhoto] = useState(false);
+
+ const handlePhotoFile = useCallback(
+ async (file: File) => {
+ if (!file.type.startsWith("image/")) return;
+ setIsUploadingPhoto(true);
+ try {
+ await saveUploadedImage(file);
+ if (onPhotoUpload) {
+ onPhotoUpload(file);
+ }
+ router.push("/editor?mode=photo");
+ } catch (error) {
+ console.error("Error uploading photo:", error);
+ setIsUploadingPhoto(false);
+ }
+ },
+ [onPhotoUpload, router]
+ );
+
+ const handlePhotoFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (file) handlePhotoFile(file);
+ e.target.value = "";
+ };
+
+ const handlePhotoDragOver = (e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDraggingPhoto(true);
+ };
+
+ const handlePhotoDragLeave = (e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDraggingPhoto(false);
};
- const locale = useLocale();
- const pantallaImg = locale === 'en' ? '/svg/screen.svg' : '/svg/pantalla.svg';
+ const handlePhotoDrop = (e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDraggingPhoto(false);
+ const file = e.dataTransfer.files?.[0];
+ if (file) handlePhotoFile(file);
+ };
return (
<>
<h1 className="animate-reveal text-5xl md:text-7xl font-semibold text-white tracking-tight mb-6 leading-[1.1] drop-shadow-[1.2px_1.2px_100.2px_rgba(183,203,248,1)]">
- {t.rich('title', {
+ <img
+ src="/svg/version.svg"
+ alt="Version"
+ aria-hidden="true"
+ className={`absolute h-auto shadow-2xl transition-all ${locale === 'es' ? "-top-8 sm:-top-4 lg:top-0 xl:top-4 left-0 -rotate-10 sm:left-26" : "-top-8 sm:top-0 xl:top-4 sm:left-10 -rotate-10" } w-16 sm:w-18`}
+ />
+ {t.rich("title", {
screen: (chunks) => (
<span className="relative inline-flex items-center">
<span className="sr-only">{chunks}</span>
<img
- src={pantallaImg}
- alt=""
+ src="/svg/mockups.svg"
+ alt="Screen icon"
aria-hidden="true"
className="inline-block h-[1.6em] w-auto align-middle translate-y-[0.1em] sm:translate-y-[0.3em]"
/>
-
<img
src="/svg/cursor-animate.svg"
className="absolute -top-18 sm:-top-25 -right-28 sm:-right-30 h-[4em] w-auto"
- alt=""
+ alt="Cursor animation"
aria-hidden="true"
/>
</span>
- )
+ ),
})}
<br />
- <span className="text-transparent bg-clip-text bg-linear-to-r from-neutral-200 via-neutral-400 to-[#003780]">
- {t('titleHighlight')}
+ <span className="text-transparent bg-clip-text bg-linear-to-r from-neutral-200 via-neutral-400 to-[#009CF2]">
+ {t("titleHighlight")}
</span>
</h1>
-
<p className="animate-reveal [animation-delay:150ms] text-lg md:text-xl text-neutral-400 max-w-2xl mx-auto mb-10 font-light leading-relaxed">
- {t('description')}
+ {t("description")}
</p>
- <div className="animate-reveal [animation-delay:300ms] flex flex-col sm:flex-row items-center justify-center gap-3">
- <div
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- onClick={() => !isUploading && fileInputRef.current?.click()}
- className={`relative flex items-center justify-center px-5 squircle-element border-2 border-dashed cursor-pointer transition-all duration-200 text-sm font-medium w-full sm:w-72 h-13
- ${isDragging
+ <div className="animate-reveal [animation-delay:300ms] flex flex-col sm:flex-row items-center justify-center gap-3 mb-2">
+ <div className="flex flex-col items-center gap-2 w-full sm:w-72">
+ <div
+ onDragOver={handleVideoDragOver}
+ onDragLeave={handleVideoDragLeave}
+ onDrop={handleVideoDrop}
+ onClick={() => !isUploadingVideo && videoInputRef.current?.click()}
+ className={`relative flex items-center justify-center px-5 squircle-element border-2 border-dashed cursor-pointer transition-all duration-200 text-sm font-medium w-full h-13 ${isDraggingVideo
? "border-blue-400/70 bg-blue-500/10 text-blue-300 scale-[1.02]"
- : isUploading
+ : isUploadingVideo
? "border-white/20 bg-white/5 text-white/40 cursor-not-allowed"
: "border-white/20 bg-white/5 text-white/90 hover:border-white/40 hover:bg-white/10 hover:text-white/80"
- }
- `}
- >
- <div className="flex items-center justify-center gap-3 pointer-events-none w-full">
- {isUploading ? (
- <>
- <Icon icon="svg-spinners:ring-resize" width="18" className="text-blue-400 shrink-0" />
- <span>{t('uploadButtonUploading')}</span>
- </>
- ) : isDragging ? (
- <>
- <Icon icon="ph:arrow-fat-down-bold" width="18" className="text-blue-400 shrink-0" />
- <span>{t('uploadButtonDragging')}</span>
- </>
- ) : (
- <>
- <Icon icon="mage:video-upload" width="20" className="shrink-0" />
- <span>{t('uploadButton')}</span>
- <span className="text-white/40 text-xs">MP4, WebM, MOV</span>
- </>
+ }`}
+ >
+ <div className="flex items-su justify-center gap-3 pointer-events-none w-full">
+ {isUploadingVideo ? (
+ <>
+ <Icon
+ icon="svg-spinners:ring-resize"
+ width="18"
+ className="text-blue-400 shrink-0"
+ />
+ <span>{t("uploadButtonUploading")}</span>
+ </>
+ ) : isDraggingVideo ? (
+ <>
+ <Icon
+ icon="ph:arrow-fat-down-bold"
+ width="18"
+ className="text-blue-400 shrink-0"
+ />
+ <span>{t("uploadButtonDragging")}</span>
+ </>
+ ) : (
+ <>
+ <Icon icon="mage:video-upload" width="22" className="shrink-0" />
+ <span>{t("uploadButton")}</span>
+ <span className="text-white/40 text-xs">MP4, WebM, MOV</span>
+ </>
+ )}
+ </div>
+ {isDraggingVideo && (
+ <div className="absolute inset-0 rounded-2xl bg-blue-500/5 blur-sm pointer-events-none" />
)}
</div>
-
- {isDragging && (
- <div className="absolute inset-0 rounded-2xl bg-blue-500/5 blur-sm pointer-events-none" />
- )}
+ <Link
+ href="/editor?mode=video"
+ className="text-sm text-white/60 hover:text-white/80 transition-colors underline decoration-white/30 underline-offset-4"
+ >
+ {t("goToVideoEditor")}
+ </Link>
+ <input
+ ref={videoInputRef}
+ type="file"
+ accept="video/mp4,video/webm,video/quicktime,video/x-matroska"
+ className="hidden"
+ onChange={handleVideoFileChange}
+ />
</div>
- <Button asChild variant="primary" size="lg" className="text-[14px] p-6 w-full sm:w-70 h-13">
- <a href="#docs">
- <div className="size-7 rounded-full bg-white flex items-center justify-center shrink-0">
- <Icon icon="fluent:screenshot-record-16-regular" className="size-5 text-red-500" />
+ <div className="flex flex-col items-center gap-2 w-full sm:w-72">
+ <div
+ onDragOver={handlePhotoDragOver}
+ onDragLeave={handlePhotoDragLeave}
+ onDrop={handlePhotoDrop}
+ onClick={() => !isUploadingPhoto && photoInputRef.current?.click()}
+ className={`relative flex items-center justify-center px-5 squircle-element border-2 border-dashed cursor-pointer transition-all duration-200 text-sm font-medium w-full h-13 ${isDraggingPhoto
+ ? "border-red-400/70 bg-red-500/10 text-red-300 scale-[1.02]"
+ : isUploadingPhoto
+ ? "border-white/20 bg-white/5 text-white/40 cursor-not-allowed"
+ : "border-white/20 bg-white/5 text-white/90 hover:border-white/40 hover:bg-white/10 hover:text-white/80"
+ }`}
+ >
+ <div className="flex items-center justify-center gap-3 pointer-events-none w-full">
+ {isUploadingPhoto ? (
+ <>
+ <Icon
+ icon="svg-spinners:ring-resize"
+ width="18"
+ className="text-red-400 shrink-0"
+ />
+ <span>{t("uploadPhotoUploading")}</span>
+ </>
+ ) : isDraggingPhoto ? (
+ <>
+ <Icon
+ icon="ph:arrow-fat-down-bold"
+ width="18"
+ className="text-red-400 shrink-0"
+ />
+ <span>{t("uploadPhotoDragging")}</span>
+ </>
+ ) : (
+ <>
+ <Icon
+ icon="solar:gallery-wide-linear"
+ width="20"
+ className="shrink-0"
+ />
+ <span>{t("uploadPhotoButton")}</span>
+ <span className="text-white/40 text-xs">JPG, PNG, WEBP</span>
+ </>
+ )}
</div>
- {t('recordButton')}
- </a>
- </Button>
-
- <input
- ref={fileInputRef}
- type="file"
- accept="video/mp4,video/webm,video/quicktime,video/x-matroska"
- className="hidden"
- onChange={handleFileChange}
- />
+ {isDraggingPhoto && (
+ <div className="absolute inset-0 rounded-2xl bg-red-500/5 blur-sm pointer-events-none" />
+ )}
+ </div>
+ <Link
+ href="/editor?mode=photo"
+ className="text-sm text-white/60 hover:text-white/80 transition-colors underline decoration-white/30 underline-offset-4"
+ >
+ {t("goToPhotoEditor")}
+ </Link>
+ <input
+ ref={photoInputRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/gif"
+ className="hidden"
+ onChange={handlePhotoFileChange}
+ />
+ </div>
</div>
</>
);
diff --git a/app/components/ui/HeroScrollMask.tsx b/app/components/ui/HeroScrollMask.tsx
new file mode 100644
index 0000000..f9f4536
--- /dev/null
+++ b/app/components/ui/HeroScrollMask.tsx
@@ -0,0 +1,223 @@
+"use client";
+
+import React, { useEffect, useRef, useState } from "react";
+import gsap from "gsap";
+import { ScrollTrigger } from "gsap/ScrollTrigger";
+import { Icon } from "@iconify/react";
+import { AnimatePresence, motion } from "framer-motion";
+import { useTranslations } from "next-intl";
+
+gsap.registerPlugin(ScrollTrigger);
+
+const floatImages = [
+ { src: "/images/scroll/magic.avif", pos: "top-[5%] left-[2%] md:left-[10%]", size: "w-[24vw] min-w-[180px]" },
+ { src: "/images/scroll/sould.avif", pos: "top-[40%] left-[2%] md:left-[4%]", size: "w-[15vw] min-w-[120px]" },
+ { src: "/images/scroll/hapyrobot.avif", pos: "bottom-[10%] sm:bottom-[1%] sm:left-[2%] md:left-[20%]", size: "w-[15vw] min-w-[120px]" },
+ { src: "/images/scroll/shadcn.avif", pos: "top-[20%] left-1/2 -translate-x-1/2 sm:top-[1%] sm:left-1/2 sm:-translate-x-1/2", size: "w-[24vw] min-w-[180px]" },
+ {
+ src: "/images/scroll/godly.avif", pos: "bottom-[30%] left-1/2 -translate-x-1/2 sm:bottom-[5%] sm:left-[40%] sm:-translate-x-1/2",
+ size: "w-[35vw] min-w-[150px] sm:w-[22vw] shadow-[0_0_100px_rgba(0,156,242,0.1)]"
+ },
+ { src: "/images/scroll/powered.avif", pos: "top-[5%] right-[2%] md:right-[5%]", size: "w-[15vw] min-w-[120px]" },
+ { src: "/images/scroll/vscode.avif", pos: "top-[40%] right-[2%] md:right-[2%]", size: "w-[24vw] min-w-[180px]" },
+ { src: "/images/scroll/daily.avif", pos: "bottom-[15%] sm:bottom-[8%] right-[2%] md:right-[15%]", size: "w-[19vw] min-w-[150px]" },
+ { src: "/images/scroll/lumina.avif", pos: "top-[18%] left-[10%] -translate-x-1/2 -translate-y-1/2 sm:top-[15%] sm:left-[30%] sm:-translate-x-[0vw] sm:translate-y-0 md:-translate-x-[0vw]", size: "w-[30vw] min-w-[120px] sm:w-[12vw]" },
+ { src: "/images/scroll/onyx.avif", pos: "top-[15%] left-1/2 -translate-x-1/2 sm:left-[60%] sm:translate-x-[20vw] md:translate-x-[15vw]", size: "w-[25vw] min-w-[100px] sm:w-[13vw]" },
+];
+
+export function HeroScrollMask() {
+ const t = useTranslations('demo');
+ const pinContainerRef = useRef<HTMLDivElement>(null);
+ const brandRef = useRef<HTMLSpanElement>(null);
+ const videoRef = useRef<HTMLVideoElement>(null);
+
+ const textContainerRef = useRef<HTMLDivElement>(null);
+
+ const [featureIndex, setFeatureIndex] = useState(0);
+ const features = t.raw('features') as string[];
+
+ useEffect(() => {
+ const featureInterval = setInterval(() => {
+ setFeatureIndex((prevIndex) => (prevIndex + 1) % features.length);
+ }, 3000);
+ return () => clearInterval(featureInterval);
+ }, [features?.length]);
+
+ useEffect(() => {
+ const mm = gsap.matchMedia();
+ mm.add({
+ isDesktop: "(min-width: 768px)",
+ isMobile: "(max-width: 767px)"
+ }, (context) => {
+ const conditions = context.conditions as { isMobile: boolean; isDesktop: boolean } | undefined;
+ const isMobile = !!conditions?.isMobile;
+ const timeline = gsap.timeline({ defaults: { ease: "none" } });
+
+ timeline.to(
+ ".floating-image",
+ {
+ x: (i) => (i % 2 === 0 ? "-120vw" : "120vw"),
+ y: (i) => (i < floatImages.length / 2 ? "-120vh" : "120vh"),
+ scale: 2.5,
+ opacity: 0,
+ stagger: {
+ each: 0.15,
+ from: "center",
+ },
+ duration: 3,
+ ease: "power3.inOut",
+ },
+ 0
+ );
+
+ timeline.fromTo(
+ brandRef.current,
+ { scale: 1, yPercent: -60 },
+ {
+ yPercent: -50,
+ xPercent: isMobile ? 50 : 150,
+ scale: isMobile ? 2500 : 1100,
+ duration: 5,
+ ease: "power2.inOut",
+ },
+ 2
+ )
+ .to(brandRef.current, {
+ backgroundColor: "black",
+ color: "white",
+ mixBlendMode: "multiply",
+ duration: 0
+ }, 2.5);
+
+ timeline.fromTo(
+ videoRef.current,
+ { opacity: 0, scale: 1.1 },
+ { opacity: 1, duration: 0.2, scale: 1.1, ease: "power3.inOut" },
+ 2.5
+ );
+
+ timeline.fromTo(
+ textContainerRef.current,
+ { opacity: 0, y: 20 },
+ { opacity: 1, y: 0, duration: 0.2, ease: "power3.out" },
+ 2.5
+ );
+
+ ScrollTrigger.create({
+ trigger: pinContainerRef.current,
+ pin: true,
+ start: "top top",
+ end: "+=300%",
+ scrub: 1,
+ animation: timeline,
+ });
+ });
+
+ return () => mm.revert();
+ }, []);
+
+ return (
+ <section ref={pinContainerRef} className="relative z-0 h-svh overflow-hidden bg-gradient-radial-primary transparent">
+ <div className="relative w-full h-svh overflow-hidden z-0 bg-transparent">
+
+ {floatImages.map((img, id) => (
+ <div
+ key={id}
+ className={`floating-image absolute squircle-element-camera overflow-hidden z-10
+ shadow-[-15px_-25px_60px_-30px_rgba(0,163,255,0.35)]
+ border border-white/10 backdrop-blur-md ${img.pos} ${img.size}
+ transition-all duration-700`}
+ >
+ <div className="relative w-full h-full bg-[#0a0a0a]">
+ <div className="absolute inset-0 bg-linear-to-tr from-white/5 to-transparent z-0" />
+
+ <img
+ src={img.src}
+ alt={`demo-${id}`}
+ className="w-full h-full block object-cover z-10 contrast-[1.1] brightness-[0.9] saturate-[1.2]"
+ />
+
+ <div
+ className="pointer-events-none absolute inset-0 z-20"
+ style={{
+ background: 'radial-gradient(circle at center, transparent 30%, rgba(0,0,0,0.4) 100%)',
+ mixBlendMode: 'overlay',
+ }}
+ />
+
+ <div className="pointer-events-none absolute inset-0 z-30 border-t border-white/20" />
+ </div>
+ </div>
+ ))}
+
+ <div className="absolute inset-0 z-10 flex flex-col justify-center items-center text-center gap-6">
+
+ <div
+ ref={textContainerRef}
+ className="absolute top-2 right-2 sm:top-6 sm:right-6 md:top-22 md:right-8 z-40 pointer-events-none select-none opacity-0"
+ >
+ <div className="bg-black/40 backdrop-blur-xl border border-white/20 rounded-xl md:rounded-2xl px-1 py-1 md:px-6 md:py-4 shadow-[0_20px_50px_rgba(0,0,0,0.5)] flex flex-col items-end min-w-45 sm:min-w-65 md:min-w-[320px]">
+ <div className="h-2 md:h-6 w-full flex items-center justify-end overflow-hidden px-1">
+ <AnimatePresence mode="wait">
+ <motion.h2
+ key={featureIndex}
+ initial={{ y: 30, opacity: 0, skewY: 10 }}
+ animate={{ y: 0, opacity: 1, skewY: 0 }}
+ exit={{ y: -30, opacity: 0, skewY: -10 }}
+ transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }}
+ className="text-[10px] sm:text-xl md:text-2xl font-black text-white italic tracking-tighter drop-shadow-[0_8px_8px_rgba(0,0,0,0.5)] uppercase whitespace-nowrap"
+ >
+ {features[featureIndex]}
+ </motion.h2>
+ </AnimatePresence>
+ </div>
+ <motion.div
+ key={`line-${featureIndex}`}
+ initial={{ width: 0 }}
+ animate={{ width: '100%' }}
+ transition={{ duration: 0.8, ease: "easeOut" }}
+ className="h-px md:h-1 bg-linear-to-r from-transparent via-blue-500 to-blue-400 rounded-full shadow-[0_0_10px_rgba(59,130,246,0.5)]"
+ />
+ </div>
+ </div>
+
+ <h2 className="relative w-full h-full flex justify-center items-center pointer-events-none">
+ <span
+ ref={brandRef}
+ className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-20 w-full h-full flex justify-center items-center text-center bg-transparent mix-blend-screen pointer-events-none text-white"
+ >
+ <svg className="w-[80vw] max-w-150 h-auto mask-b-from-30% mask-b-to-99%" viewBox="0 0 633 194" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
+ <path d="M103.134 107.981C105.925 92.1435 108.265 76.576 119.01 64.0971C133.912 46.7914 152.731 40.9116 174.689 46.2879C189.665 49.9545 197.837 60.7065 200.746 75.4457C205.842 101.264 189.119 130.568 164.479 139.231C149.37 144.542 135.044 144.252 122.367 132.11C119.577 137.387 119.396 142.908 118.307 148.111C115.621 160.949 113.22 173.851 110.987 186.776C110.202 191.321 108.429 193.524 103.5 192.916C98.2726 192.272 92.937 193.678 86.6763 192.498C92.1625 164.281 97.5956 136.338 103.134 107.981ZM142.28 120.621C151.263 122.549 159.131 120.209 165.869 114.153C173.693 107.121 177.764 98.0974 178.261 87.727C179.029 71.718 166.749 62.241 151.289 66.5312C138.427 70.1006 127.944 85.102 127.981 99.8879C128.006 110.294 132.318 116.812 142.28 120.621Z" />
+ <path d="M603.442 121.106C589.992 136.993 573.365 144.444 552.834 141.813C532.672 139.229 519.379 123.784 519.725 103.273C520.039 84.7037 526.768 68.7806 541.11 56.6562C553.84 45.8935 568.43 41.9106 584.879 46.1438C590.462 47.5807 594.936 51.038 599.799 54.8294C602.823 44.2583 604.179 33.907 606.33 23.7337C607.669 17.3979 608.913 11.0394 610.048 4.66424C610.512 2.05885 611.768 0.988612 614.419 1.05772C619.081 1.17922 623.754 1.20797 628.414 1.04402C632.234 0.909572 633.365 2.29144 632.608 6.1293C628.845 25.2024 625.303 44.3191 621.628 63.41C619.525 74.3398 617.297 85.2455 615.163 96.1696C613.371 105.347 609.338 113.465 603.442 121.106ZM550.928 77.1706C547.366 81.8927 545.046 87.1389 543.802 92.9448C541.439 103.974 544.721 113.728 552.614 118.494C560.989 123.551 572.465 121.925 580.814 114.526C588.136 108.037 592.156 99.8021 593.249 90.2027C595.111 73.843 584.489 63.2459 568.875 65.8489C561.657 67.0522 556.055 71.1476 550.928 77.1706Z" />
+ <path d="M228.253 138.133C210.379 127.671 203.62 110.332 208.637 88.4852C214.419 63.3067 235.448 45.2571 261.264 44.4367C281.948 43.7793 299.766 54.0981 302.52 77.6562C303.049 82.176 301.757 83.8384 297.588 85.0055C277.094 90.7435 256.676 96.7522 236.235 102.677C234.35 103.223 232.32 103.429 230.765 104.749C231.68 116.809 244.023 124.821 256.799 121.579C264.75 119.561 271.07 115.091 274.861 107.726C276.475 104.589 278.596 103.37 281.934 103.424C287.531 103.514 293.131 103.449 298.812 103.449C295.886 126.521 262.283 152.852 228.253 138.133ZM233.818 85.323C238.546 85.2204 242.833 83.2546 247.287 82.0462C257.147 79.3711 266.942 76.4543 276.785 73.6299C274.596 67.3805 267.363 63.4057 259.706 63.8475C246.96 64.5829 235.604 73.669 233.818 85.323Z" />
+ <path d="M62.9133 44.9725C83.2609 47.0505 95.977 61.4009 97.1926 81.6589C98.8676 109.571 78.8816 135.646 52.1363 141.311C28.9054 146.232 7.52747 135.802 1.92562 115.654C-1.57551 103.061 -0.216118 90.561 5.30131 78.6889C15.0362 57.7419 31.2952 45.9557 54.5433 44.3729C57.1627 44.1946 59.8303 44.7245 62.9133 44.9725ZM24.2117 91.5522C24.0202 93.0374 23.8785 94.531 23.6295 96.0065C20.6802 113.486 35.0865 125.939 51.6519 119.787C64.7376 114.928 71.5567 104.595 73.3941 91.104C74.6452 81.917 73.2727 73.0755 64.2051 68.098C55.2604 63.1881 46.4518 65.1663 38.3144 70.6049C31.0535 75.4577 27.0109 82.6288 24.2117 91.5522Z" />
+ <path d="M335.391 84.071C332.048 101.28 328.725 118.07 325.66 134.907C324.943 138.846 323.127 140.167 319.271 139.889C315.293 139.601 311.271 139.675 307.281 139.864C303.293 140.053 301.862 138.633 302.689 134.557C306.224 117.137 309.616 99.6873 313.046 82.2455C315.065 71.9775 317.197 61.7285 318.987 51.4203C319.624 47.748 321.253 46.3022 324.925 46.33C336.896 46.4204 341.7 44.9258 360.758 44.5892C376.868 42.6816 390.857 55.3259 393.147 71.4636C394.693 82.357 391.643 92.5918 389.88 103.021C388.109 113.503 385.813 123.895 383.928 134.36C383.238 138.191 381.793 140.295 377.42 139.885C373.29 139.499 369.093 139.674 364.933 139.811C361.092 139.937 360.058 138.534 360.841 134.685C363.984 119.217 366.855 103.694 369.818 88.1902C370.036 87.0503 370.266 85.9032 370.353 84.7491C371.211 73.3971 367.41 67.104 358.888 65.7084C347.953 63.9178 338.952 69.4989 336.284 79.7527C335.949 81.0385 335.761 82.3624 335.391 84.071Z" />
+ <path d="M441.004 95.832C448.408 81.2445 455.87 67.0978 462.733 52.6656C465.114 47.6574 468.082 45.759 473.486 46.2176C478.703 46.6603 483.987 46.3134 488.814 46.3134C489.909 48.7025 489.014 49.8276 488.408 50.9564C473.376 78.9826 458.257 106.963 443.358 135.06C441.426 138.704 439.11 140.139 435.113 139.863C431.134 139.588 427.096 139.527 423.129 139.879C418.929 140.251 417.175 138.537 416.451 134.539C413.192 116.556 409.725 98.6108 406.376 80.6442C404.549 70.8436 402.967 60.9941 400.946 51.2346C400.159 47.4332 401.592 46.3747 404.936 46.3824C409.434 46.3929 413.938 46.504 418.427 46.2943C422.779 46.0909 424.518 47.8597 425.12 52.2637C427.634 70.683 430.517 89.0518 433.29 107.436C433.358 107.89 433.703 108.303 434.086 109.069C437.179 105.003 438.676 100.404 441.004 95.832Z" />
+ <path d="M516.097 66.6983C511.66 89.9209 507.258 112.717 502.903 135.521C502.311 138.623 500.775 140.029 497.462 139.855C492.983 139.62 488.48 139.672 483.994 139.813C480.202 139.932 479.081 138.649 479.881 134.739C484.069 114.271 488.027 93.7566 492.049 73.2551C493.518 65.7675 495.019 58.2849 496.345 50.7716C496.858 47.8645 498.119 46.2925 501.233 46.3436C506.055 46.4228 510.879 46.378 515.702 46.3325C518.738 46.3038 519.886 47.4955 519.183 50.6448C518.027 55.8226 517.144 61.0612 516.097 66.6983Z" />
+ <path d="M503.501 20.1523C500.655 10.8349 505.164 2.46105 513.757 0.411426C522.202 -1.60279 528.731 3.9868 528.028 12.6294C527.577 18.1794 523.214 23.1626 517.215 24.9798C511.545 26.6973 507.717 25.4373 503.501 20.1523Z" />
+ </svg>
+ </span>
+ <div className="absolute inset-0 w-full h-full z-10 overflow-hidden">
+ <div className="absolute inset-0 z-20 bg-linear-to-b from-transparent from-70% to-[#0C0C0D] pointer-events-none" />
+
+ <video
+ ref={videoRef}
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full h-full object-cover"
+ >
+ <source src="/images/pages/demo.mp4" type="video/mp4" />
+ </video>
+ </div>
+
+ </h2>
+ <p className="absolute bottom-10 z-30 text-white/80 font-semibold text-4xl">
+ <Icon icon="iconoir:mouse-scroll-wheel" />
+ </p>
+ </div>
+ </div>
+ </section>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/PhotoPickerPopover.tsx b/app/components/ui/PhotoPickerPopover.tsx
index 209c1e0..49d0e2d 100644
--- a/app/components/ui/PhotoPickerPopover.tsx
+++ b/app/components/ui/PhotoPickerPopover.tsx
@@ -5,10 +5,16 @@ import { Icon } from "@iconify/react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { fetchPhotosWithCache, fetchDiscoveryPhotos, type UnifiedPhoto } from "@/lib/photo-providers";
import { TooltipAction } from "@/components/ui/tooltip-action";
+import { useTranslations } from "next-intl";
const SUGGESTION_BADGES = [
- "blur gradient", "dark wallpaper", "minimal abstract", "neon city",
- "nature landscape", "aurora borealis", "gradient wallpaper"
+ { id: "blur gradient", key: "blur_gradient" },
+ { id: "dark wallpaper", key: "dark_wallpaper" },
+ { id: "minimal abstract", key: "minimal_abstract" },
+ { id: "neon city", key: "neon_city" },
+ { id: "nature landscape", key: "nature_landscape" },
+ { id: "aurora borealis", key: "aurora_borealis" },
+ { id: "gradient wallpaper", key: "gradient_wallpaper" }
];
interface PhotoPickerPopoverProps {
@@ -17,7 +23,6 @@ interface PhotoPickerPopoverProps {
function ProgressiveImage({ photo }: { photo: UnifiedPhoto }) {
const [isLoaded, setIsLoaded] = useState(false);
-
return (
<div
className="w-full relative overflow-hidden squircle-element group"
@@ -49,10 +54,12 @@ function MasonryGrid({
photos,
onSelect,
loading,
+ emptyText,
}: {
photos: UnifiedPhoto[];
onSelect: (url: string) => void;
loading: boolean;
+ emptyText: string;
}) {
function toColumns<T>(items: T[], n: number): T[][] {
const cols: T[][] = Array.from({ length: n }, () => []);
@@ -83,7 +90,7 @@ function MasonryGrid({
return (
<div className="flex flex-col items-center justify-center py-20 text-white/30 gap-3">
<Icon icon="ph:image-broken-duotone" width="48" className="opacity-50" />
- <span className="text-xs font-medium tracking-wide">Sin resultados</span>
+ <span className="text-xs font-medium tracking-wide">{emptyText}</span>
</div>
);
}
@@ -108,6 +115,7 @@ function MasonryGrid({
}
export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
+ const t = useTranslations("photoPicker");
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
const [activeQuery, setActiveQuery] = useState("");
@@ -116,6 +124,7 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [isSearchMode, setIsSearchMode] = useState(false);
+
const scrollRef = useRef<HTMLDivElement>(null);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const prevOpenRef = useRef(false);
@@ -132,11 +141,13 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
setPage(1);
setHasMore(true);
setLoading(true);
+
fetchDiscoveryPhotos().then((results) => {
setPhotos(results);
setLoading(false);
});
}, 0);
+
return () => clearTimeout(t);
}, [open]);
@@ -147,22 +158,26 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
setIsSearchMode(true);
setPage(1);
setLoading(true);
+
fetchPhotosWithCache(activeQuery, 1, 20).then((results) => {
setPhotos(results);
setHasMore(results.length === 20);
setLoading(false);
});
}, 0);
+
return () => clearTimeout(t);
}, [activeQuery]);
const handleScroll = useCallback(() => {
const el = scrollRef.current;
if (!el || !hasMore || loading || !isSearchMode) return;
+
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 80) {
const nextPage = page + 1;
setPage(nextPage);
setLoading(true);
+
fetchPhotosWithCache(activeQuery, nextPage, 20).then((results) => {
setPhotos((prev) => {
const seen = new Set(prev.map((p) => p.id));
@@ -182,7 +197,9 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val = e.target.value;
setInputValue(val);
+
if (debounceRef.current) clearTimeout(debounceRef.current);
+
if (val.trim().length >= 2) {
debounceRef.current = setTimeout(() => setActiveQuery(val.trim()), 600);
}
@@ -197,6 +214,7 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
setActiveQuery("");
setIsSearchMode(false);
setLoading(true);
+
fetchDiscoveryPhotos().then((results) => {
setPhotos(results);
setLoading(false);
@@ -209,30 +227,24 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
return (
<Popover open={open} onOpenChange={setOpen}>
- <TooltipAction label="Buscar fondos (Unsplash + Pexels + Pixabay)">
+ <TooltipAction label={t("tooltip")}>
<PopoverTrigger asChild>
- <button
- className="aspect-square squircle-element bg-gray-100 border border-white/10 bg-linear-to-br from-indigo-500 via-purple-500 to-pink-500 bg-[url('/svg/ppu.svg')] bg-cover bg-center flex items-center justify-center hover:opacity-80 transition group relative overflow-hidden"
- >
- </button>
+ <button className="aspect-square squircle-element bg-gray-100 border border-white/10 bg-linear-to-br from-indigo-500 via-purple-500 to-pink-500 bg-[url('/svg/ppu.svg')] bg-cover bg-center flex items-center justify-center hover:opacity-80 transition group relative overflow-hidden" />
</PopoverTrigger>
</TooltipAction>
-
<PopoverContent side="right" align="start" sideOffset={12} className="w-115 p-0 border-0 shadow-2xl">
<div className="flex flex-col bg-black border border-white/10 rounded-xl overflow-hidden shadow-2xl max-h-150">
-
<div className="px-4 py-3 border-b border-white/10 bg-white/5 shrink-0">
<div className="flex items-center gap-2">
<Icon icon="ph:images-bold" width="13" className="text-white/50" />
<span className="text-[10px] font-medium uppercase tracking-[0.15em] text-white/50">
- Fondos
+ {t("title")}
</span>
<span className="ml-auto text-[10px] text-white/30">
- {isSearchMode ? `"${activeQuery}"` : "Descubriendo"}
+ {isSearchMode ? `"${activeQuery}"` : t("statusDiscovering")}
</span>
</div>
</div>
-
<div className="px-4 pt-3 pb-2 shrink-0">
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-white/6 border border-white/10 focus-within:border-white/20 transition-colors">
<Icon icon="ph:magnifying-glass-bold" width="13" className="text-white/30 shrink-0" />
@@ -241,7 +253,7 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
value={inputValue}
onChange={handleInputChange}
onKeyDown={handleInputKeyDown}
- placeholder="Buscar fondos..."
+ placeholder={t("searchPlaceholder")}
className="flex-1 bg-transparent text-[12px] text-white/80 placeholder:text-white/30 outline-none"
/>
{inputValue && (
@@ -251,47 +263,39 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
)}
</div>
</div>
-
<div className="px-4 pb-3 shrink-0">
<div className="flex flex-wrap gap-1.5">
{SUGGESTION_BADGES.map((badge) => (
<button
- key={badge}
- onClick={() => handleBadgeClick(badge)}
- className={`px-2.5 py-0.5 rounded-full text-[11px] transition-all border ${activeQuery === badge
- ? "bg-white/15 border-white/30 text-white/90"
- : "bg-white/5 border-white/10 text-white/50 hover:text-white/70 hover:border-white/20"
+ key={badge.id}
+ onClick={() => handleBadgeClick(badge.id)}
+ className={`px-2.5 py-0.5 rounded-full text-[11px] transition-all border ${activeQuery === badge.id
+ ? "bg-white/15 border-white/30 text-white/90"
+ : "bg-white/5 border-white/10 text-white/50 hover:text-white/70 hover:border-white/20"
}`}
>
- {badge}
+ {t(`badges.${badge.key}`)}
</button>
))}
</div>
</div>
-
<div className="h-px bg-white/10 shrink-0" />
-
<div
ref={scrollRef}
onScroll={handleScroll}
className="overflow-y-auto custom-scrollbar flex-1"
style={{ minHeight: 0 }}
>
- <MasonryGrid
- photos={photos}
- onSelect={handleSelect}
- loading={loading && photos.length === 0}
- />
+ <MasonryGrid photos={photos} onSelect={handleSelect} loading={loading && photos.length === 0} emptyText={t("noResults")} />
{loading && photos.length > 0 && (
<div className="flex justify-center py-3">
<Icon icon="mdi:loading" className="text-white/30 animate-spin" width="20" />
</div>
)}
</div>
-
<div className="px-4 py-2.5 border-t border-white/10 bg-white/5 shrink-0">
<span className="text-[10px] text-white/30">
- Fotos de{" "}
+ {t("footerPhotosBy")}{" "}
<a
href="https://unsplash.com"
target="_blank"
@@ -309,7 +313,7 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
>
Pexels
</a>
- {" y "}
+ {t("footerAnd")}
<a
href="https://pixabay.com"
target="_blank"
diff --git a/app/components/ui/PlaceholderEditor.tsx b/app/components/ui/PlaceholderEditor.tsx
index 996a3a6..7151bbe 100644
--- a/app/components/ui/PlaceholderEditor.tsx
+++ b/app/components/ui/PlaceholderEditor.tsx
@@ -2,17 +2,21 @@ import { Button } from "@/components/ui/button";
import { Icon } from "@iconify/react";
import { useRef, useState } from "react";
import { useTranslations } from "next-intl";
+import type { MediaType } from "@/types/editor.types";
interface PlaceholderEditorProps {
onVideoUpload?: (file: File) => void;
isUploading?: boolean;
+ mediaType?: MediaType;
}
-export default function PlaceholderEditor({ onVideoUpload, isUploading = false }: PlaceholderEditorProps) {
+export default function PlaceholderEditor({ onVideoUpload, isUploading = false, mediaType = "video" }: PlaceholderEditorProps) {
const t = useTranslations('placeholder');
const fileInputRef = useRef<HTMLInputElement>(null);
const [isDragging, setIsDragging] = useState(false);
+ const isImageMode = mediaType === "image";
+
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file && onVideoUpload) {
@@ -48,11 +52,19 @@ export default function PlaceholderEditor({ onVideoUpload, isUploading = false }
setIsDragging(false);
const file = e.dataTransfer.files?.[0];
- if (file && file.type.startsWith("video/") && onVideoUpload) {
+ const isValidFile = isImageMode
+ ? file?.type.startsWith("image/")
+ : file?.type.startsWith("video/");
+
+ if (file && isValidFile && onVideoUpload) {
onVideoUpload(file);
}
};
+ const acceptedFormats = isImageMode
+ ? "image/jpeg,image/png,image/webp,image/gif"
+ : "video/mp4,video/webm,video/quicktime,video/x-matroska";
+
return (
<>
<div className="bg-[#2D2D2D] flex flex-col justify-center items-center px-6 shrink-0 w-3xl h-9 rounded-t-2xl border-b border-white/5">
@@ -150,13 +162,15 @@ export default function PlaceholderEditor({ onVideoUpload, isUploading = false }
</div>
<div className="space-y-1 mb-6 pointer-events-none">
<p className="text-base font-medium text-zinc-200">
- {isDragging ? t('upload.dragging') : t('upload.title')}
+ {isDragging
+ ? (isImageMode ? t('upload.draggingImage') : t('upload.dragging'))
+ : (isImageMode ? t('upload.titleImage') : t('upload.title'))}
<span className="font-normal text-zinc-400">
- {!isDragging && ` ${t('upload.subtitle')}`}
+ {!isDragging && ` ${isImageMode ? t('upload.subtitleImage') : t('upload.subtitle')}`}
</span>
</p>
<p className="text-sm text-zinc-500">
- {t('upload.formats')}
+ {isImageMode ? t('upload.formatsImage') : t('upload.formats')}
</p>
</div>
<div className="relative z-10">
@@ -183,7 +197,7 @@ export default function PlaceholderEditor({ onVideoUpload, isUploading = false }
<input
ref={fileInputRef}
type="file"
- accept="video/mp4,video/webm,video/quicktime,video/x-matroska"
+ accept={acceptedFormats}
className="hidden"
onChange={handleFileChange}
/>
diff --git a/app/components/ui/RecordingSteps.tsx b/app/components/ui/RecordingSteps.tsx
index 3f8999c..253fe2a 100644
--- a/app/components/ui/RecordingSteps.tsx
+++ b/app/components/ui/RecordingSteps.tsx
@@ -295,7 +295,7 @@ export default function InteractiveRecordingSteps() {
];
return (
- <div id="docs" className="w-full max-w-7xl mx-auto px-0 sm:px-6 py-24 text-left">
+ <div id="docs" className="w-full max-w-7xl mx-auto px-0 sm:px-6 py-6 sm:py-24 text-left">
<div className="max-w-3xl mx-auto text-center mb-32">
<h2 className="text-4xl md:text-6xl font-bold tracking-tighter text-white mb-6 leading-tight drop-shadow-[1.2px_1.2px_100.2px_rgba(183,203,248,1)]">
{t('title')} <br />
diff --git a/app/components/ui/Skeleton.tsx b/app/components/ui/Skeleton.tsx
index 642ad2c..bfbf0f3 100644
--- a/app/components/ui/Skeleton.tsx
+++ b/app/components/ui/Skeleton.tsx
@@ -509,4 +509,39 @@ export function VideosMenuSkeleton() {
</div>
);
+}
+
+export function HistoryMenuSkeleton() {
+ return (
+ <div className="p-4 flex flex-col gap-5">
+ {/* Título del menú */}
+ <Skeleton height={20} width={120} />
+
+ {/* Botón principal de "Subir / Nuevo" */}
+ <Skeleton height={36} variant="square" />
+
+ {/* Sección de la cuadrícula de historial */}
+ <div className="space-y-4">
+ <Skeleton height={10} width={80} /> {/* Subtítulo (ej. "Recientes") */}
+
+ <div className="grid grid-cols-2 gap-3">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <div key={i} className="flex flex-col gap-2 p-2 rounded-lg bg-white/3 border border-white/5">
+ {/* Miniatura del proyecto/imagen */}
+ <Skeleton
+ variant="square"
+ className="w-full rounded-md"
+ style={{ aspectRatio: "16/9" } as React.CSSProperties}
+ />
+ {/* Textos simulados (Nombre y fecha) */}
+ <div className="space-y-1.5 mt-1">
+ <Skeleton height={10} width="80%" />
+ <Skeleton height={8} width="50%" />
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
}
\ No newline at end of file
diff --git a/app/components/ui/StepRow.tsx b/app/components/ui/StepRow.tsx
index 0d49197..a082d20 100644
--- a/app/components/ui/StepRow.tsx
+++ b/app/components/ui/StepRow.tsx
@@ -34,12 +34,12 @@ export default function StepRow({
}}
/>
- <div className="absolute inset-0 rounded-full bg-gradient-to-tr from-white/5 to-transparent pointer-events-none" />
+ <div className="absolute inset-0 rounded-full bg-linear-to-tr from-white/5 to-transparent pointer-events-none" />
<span className="relative z-10">{number}</span>
</span>
- <h3 className="text-3xl md:text-4xl font-light tracking-tight text-white drop-shadow-[1.2px_1.2px_100.2px_rgba(183,203,248,1)]">
+ <h3 className="text-3xl md:text-4xl font-light tracking-tight text-white [text-shadow:0_0_60px_rgba(183,203,248,0.8),0_0_100px_rgba(183,203,248,0.7),0_0_200px_rgba(183,203,248,0.5),0_0_350px_rgba(183,203,248,0.3)]">
{title}
</h3>
</div>
diff --git a/app/components/ui/editor/AudioFragmentTrackItem.tsx b/app/components/ui/editor/AudioFragmentTrackItem.tsx
index e6df777..f1aab88 100644
--- a/app/components/ui/editor/AudioFragmentTrackItem.tsx
+++ b/app/components/ui/editor/AudioFragmentTrackItem.tsx
@@ -2,24 +2,7 @@
import { useState, useRef, useCallback, useMemo, useEffect } from "react";
import { motion, useMotionValue } from "framer-motion";
-import type { AudioTrack, UploadedAudio } from "@/types/audio.types";
-
-const MIN_FRAGMENT_DURATION = 0.1;
-const MIN_VISUAL_WIDTH_PX = 50;
-
-interface AudioFragmentTrackItemProps {
- track: AudioTrack;
- audio: UploadedAudio | undefined;
- isSelected: boolean;
- contentWidth: number;
- videoDuration: number;
- otherTracks: AudioTrack[];
- onSelect: () => void;
- onUpdate: (updates: Partial<AudioTrack>) => void;
- onDragStateChange?: (isDragging: boolean) => void;
- onMouseEnter?: () => void;
- onMouseLeave?: () => void;
-}
+import { AudioFragmentTrackItemProps, MIN_FRAGMENT_DURATION, MIN_VISUAL_WIDTH_PX } from "@/types/audio.types";
export function AudioFragmentTrackItem({
track,
diff --git a/app/components/ui/editor/AudioMenu.tsx b/app/components/ui/editor/AudioMenu.tsx
index 2217695..5b11924 100644
--- a/app/components/ui/editor/AudioMenu.tsx
+++ b/app/components/ui/editor/AudioMenu.tsx
@@ -2,53 +2,13 @@
import { Icon } from "@iconify/react";
import { useCallback, useRef, useState, useEffect } from "react";
-import type { AudioTrack, UploadedAudio } from "@/types/audio.types";
+import type { AudioMenuProps, AudioTrack } from "@/types/audio.types";
import { SliderControl } from "../SliderControl";
import { AudioTrimModal } from "./AudioTrimModal";
import { Button } from "@/components/ui/button";
import { TooltipAction } from "@/components/ui/tooltip-action";
-
-interface AudioMenuProps {
- audioTracks: AudioTrack[];
- uploadedAudios: UploadedAudio[];
- muteOriginalAudio: boolean;
- masterVolume: number;
- videoDuration: number;
- onAudioUpload: (file: File) => void;
- onUpdateAudioTrack: (trackId: string, updates: Partial<AudioTrack>) => void;
- onDeleteAudioTrack: (trackId: string) => void;
- onToggleMuteOriginalAudio: () => void;
- onMasterVolumeChange: (volume: number) => void;
-}
-
-function TrackVolumeSlider({ track, onUpdateAudioTrack }: {
- track: AudioTrack;
- onUpdateAudioTrack: (id: string, updates: Partial<AudioTrack>) => void;
-}) {
- const [internalVolume, setInternalVolume] = useState(track.volume * 100);
-
- useEffect(() => {
- const externalValue = track.volume * 100;
- if (Math.abs(internalVolume - externalValue) > 1) {
- setInternalVolume(externalValue);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [track.volume]);
-
- return (
- <SliderControl
- icon="mdi:volume-medium"
- label="Volumen"
- value={internalVolume}
- min={0}
- max={100}
- onChange={(value: number) => {
- setInternalVolume(value);
- onUpdateAudioTrack(track.id, { volume: value / 100 });
- }}
- />
- );
-}
+import { TrackVolumeSlider } from "@/components/ui/TrackVolumeSlider";
+import { useTranslations } from "next-intl";
export function AudioMenu({
audioTracks,
@@ -62,6 +22,7 @@ export function AudioMenu({
onToggleMuteOriginalAudio,
onMasterVolumeChange,
}: AudioMenuProps) {
+ const t = useTranslations("audioMenu");
const fileInputRef = useRef<HTMLInputElement>(null);
const [selectedTrackId, setSelectedTrackId] = useState<string | null>(null);
const [trimModalOpen, setTrimModalOpen] = useState(false);
@@ -149,7 +110,7 @@ export function AudioMenu({
<div className="p-4 flex flex-col gap-5">
<div className="flex items-center gap-2 text-white font-medium">
<Icon icon="mdi:volume-high" width="20" />
- <span>Audio</span>
+ <span>{t("title")}</span>
</div>
<div className="bg-[#09090B] border border-white/5 squircle-element p-3">
@@ -162,20 +123,20 @@ export function AudioMenu({
width="18"
className={muteOriginalAudio ? "text-red-400" : "text-blue-400"}
/>
- <span>Audio original</span>
+ <span>{t("originalAudio")}</span>
</div>
<div className={`px-2 py-0.5 rounded text-xs font-medium ${muteOriginalAudio
? "bg-red-500/20 text-red-400"
: "bg-blue-500/20 text-blue-400"
}`}>
- {muteOriginalAudio ? "Silenciado" : "Activo"}
+ {muteOriginalAudio ? t("muted") : t("active")}
</div>
</button>
</div>
<SliderControl
icon="mdi:volume-medium"
- label="Volumen maestro"
+ label={t("masterVolume")}
value={internalMasterVolume}
min={0}
max={100}
@@ -205,10 +166,10 @@ export function AudioMenu({
onClick={() => fileInputRef.current?.click()}
>
<Icon icon="mdi:upload" width="14" />
- <span>Subir audio</span>
+ <span>{t("uploadButton")}</span>
</Button>
<p className="text-xs text-white/40 mt-2 text-center">
- MP3, WAV, OGG, AAC, M4A (max 10MB)
+ {t("uploadHint")}
</p>
</div>
@@ -216,7 +177,7 @@ export function AudioMenu({
<div className="flex flex-col gap-2">
<div className="text-xs font-medium text-white/60 flex items-center gap-2">
<Icon icon="mdi:timeline-clock" width="14" />
- <span>PISTAS EN LÍNEA DE TIEMPO ({audioTracks.length})</span>
+ <span>{t("timelineTracks", { count: audioTracks.length })}</span>
</div>
<div className="flex flex-col gap-2">
{audioTracks.map((track) => {
@@ -238,17 +199,17 @@ export function AudioMenu({
{track.name}
</div>
<div className="text-xs text-white/40 mt-0.5">
- Inicio: {formatDuration(track.startTime)} • Duración: {formatDuration(track.duration)}
+ {t("start")}: {formatDuration(track.startTime)} • {t("duration")}: {formatDuration(track.duration)}
</div>
{exceedsVideoDuration && (
<div className="text-xs text-orange-400 mt-1 flex items-center gap-1">
<Icon icon="mdi:alert" width="12" />
- Excede duración del video
+ {t("exceedsDuration")}
</div>
)}
</div>
<div className="flex items-center gap-1">
- <TooltipAction label="Recortar audio">
+ <TooltipAction label={t("trimAction")}>
<button
onClick={(e) => {
e.stopPropagation();
@@ -260,7 +221,7 @@ export function AudioMenu({
<Icon icon="mdi:content-cut" width="16" />
</button>
</TooltipAction>
- <TooltipAction label="Eliminar audio">
+ <TooltipAction label={t("deleteAction")}>
<button
onClick={(e) => {
e.stopPropagation();
@@ -295,10 +256,11 @@ export function AudioMenu({
{audioTracks.length === 0 && (
<div className="text-center py-8 px-4 text-white/40">
<Icon icon="mdi:music-note-off" width="48" className="mx-auto mb-3 opacity-30" />
- <p className="text-sm">No hay pistas de audio</p>
- <p className="text-xs mt-1">Sube un archivo de audio para añadirlo automáticamente a la línea de tiempo</p>
+ <p className="text-sm">{t("noTracks")}</p>
+ <p className="text-xs mt-1">{t("noTracksHint")}</p>
</div>
)}
+
{trimModalOpen && trimModalTrack && (() => {
const originalAudio = uploadedAudios.find(a => a.id === trimModalTrack.audioId);
if (!originalAudio) return null;
diff --git a/app/components/ui/editor/CanvasElementsLayer.tsx b/app/components/ui/editor/CanvasElementsLayer.tsx
index d4f915e..cfa5330 100644
--- a/app/components/ui/editor/CanvasElementsLayer.tsx
+++ b/app/components/ui/editor/CanvasElementsLayer.tsx
@@ -4,7 +4,6 @@ import { Corner, VIDEO_Z_INDEX, getNearestCorner, getCornerStyle } from "@/lib";
import { CanvasElement, SvgElement, ImageElement } from "@/types/canvas-elements.types";
import { useRef, useState, useEffect, useCallback } from "react";
-{/* Canvas Elements Layer Component - renders elements either behind or above video */ }
export function CanvasElementsLayer({
canvasContainerRef,
canvasElements,
@@ -19,6 +18,7 @@ export function CanvasElementsLayer({
setIsDraggingElementRotation,
elementDragStart,
layerZIndex,
+ hitTestOnly = false,
}: {
canvasContainerRef?: React.RefObject<HTMLDivElement | null>;
canvasElements: CanvasElement[];
@@ -33,11 +33,11 @@ export function CanvasElementsLayer({
setIsDraggingElementRotation: (dragging: boolean) => void;
elementDragStart: React.MutableRefObject<{ x: number; y: number; initialX: number; initialY: number; initialRotation: number }>;
layerZIndex: number;
+ hitTestOnly?: boolean;
}) {
const layerRef = useRef<HTMLDivElement>(null);
const [refSize, setRefSize] = useState(0);
- // Per-element corner tracking: elementId → Corner
const [elementCorners, setElementCorners] = useState<Record<string, Corner>>({});
useEffect(() => {
@@ -63,9 +63,11 @@ export function CanvasElementsLayer({
}
}, [canvasContainerRef]);
- const filteredElements = canvasElements.filter(element =>
+const filteredElements = hitTestOnly
+ ? canvasElements // todos los elementos cuando es hit layer
+ : canvasElements.filter(element =>
behindVideo ? element.zIndex < VIDEO_Z_INDEX : element.zIndex >= VIDEO_Z_INDEX
- );
+ );
if (filteredElements.length === 0) {
return (
@@ -101,8 +103,10 @@ export function CanvasElementsLayer({
width: wPx > 0 ? `${wPx}px` : `${element.width}%`,
height: hPx > 0 ? `${hPx}px` : `${element.height}%`,
transform: `translate(-50%, -50%) rotate(${element.rotation}deg)`,
- zIndex: element.zIndex,
+ zIndex: hitTestOnly ? element.zIndex : element.zIndex,
transition: isDraggingElement ? 'none' : 'transform 0.1s ease-out',
+ // Cuando es hitTestOnly: invisible pero interactivo
+ ...(hitTestOnly ? { opacity: 0, pointerEvents: 'auto' } : {}),
};
const handleMouseEnter = () => setHoveredElementId(element.id);
@@ -127,6 +131,21 @@ export function CanvasElementsLayer({
};
};
+ if (hitTestOnly) {
+ return (
+ <div
+ key={element.id}
+ data-canvas-element
+ className="pointer-events-auto cursor-move"
+ style={commonStyle}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ onMouseMove={handleMouseMove}
+ onMouseDown={handleMouseDown}
+ />
+ );
+ }
+
const rotationHandle = isSelected && onElementUpdate ? (
<div
data-element-rotation
diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsx
index a304e2d..eda92d4 100644
--- a/app/components/ui/editor/ControlPanel.tsx
+++ b/app/components/ui/editor/ControlPanel.tsx
@@ -19,7 +19,8 @@ import {
ImageBackgroundSkeleton,
ZoomFragmentEditorSkeleton,
AudioMenuSkeleton,
- VideosMenuSkeleton
+ VideosMenuSkeleton,
+ HistoryMenuSkeleton
} from "../Skeleton";
import { ElementsMenu } from "./ElementsMenu";
@@ -38,6 +39,7 @@ const WallpaperCatalogGrid = lazy(() => import("../WalpaperSections").then(mod =
const MockupMenu = lazy(() => import("./MockupMenu").then(mod => ({ default: mod.MockupMenu })));
const AudioMenu = lazy(() => import("./AudioMenu").then(mod => ({ default: mod.AudioMenu })));
const VideosMenu = lazy(() => import("./VideosMenu").then(mod => ({ default: mod.VideosMenu })));
+const HistoryMenu = lazy(() => import("./HistoryMenu").then(mod => ({ default: mod.HistoryMenu })));
interface ExtendedControlPanelProps extends ControlPanelProps {
onTogglePanel?: () => void;
@@ -122,6 +124,14 @@ export function ControlPanel({
cameraUrl = null,
cameraConfig = null,
onCameraConfigChange,
+ // History/Image projects props
+ imageProjects = [],
+ currentImageProjectId = null,
+ isLoadingProjects = false,
+ onSelectImageProject,
+ onAddImageToCanvas,
+ onDeleteImageProject,
+ onUploadImageToHistory,
}: ExtendedControlPanelProps) {
const t = useTranslations("controlPanel");
@@ -362,6 +372,20 @@ export function ControlPanel({
onCameraConfigChange={onCameraConfigChange || (() => { })}
/>
)}
+
+ {activeTool === "history" && (
+ <Suspense fallback={<HistoryMenuSkeleton />}>
+ <HistoryMenu
+ projects={imageProjects || []}
+ currentProjectId={currentImageProjectId}
+ isLoading={isLoadingProjects}
+ onSelectProject={onSelectImageProject || (() => { })}
+ onAddToCanvas={onAddImageToCanvas || (() => { })}
+ onDeleteProject={onDeleteImageProject || (() => { })}
+ onUploadToHistory={onUploadImageToHistory || (() => { })}
+ />
+ </Suspense>
+ )}
</div>
</div>
);
diff --git a/app/components/ui/editor/EditorHoverTooltip.tsx b/app/components/ui/editor/EditorHoverTooltip.tsx
new file mode 100644
index 0000000..07ca506
--- /dev/null
+++ b/app/components/ui/editor/EditorHoverTooltip.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+interface EditorHoverTooltipProps {
+ show: boolean;
+}
+
+export function EditorHoverTooltip({ show }: EditorHoverTooltipProps) {
+ if (!show) return null;
+
+ return (
+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none animate-in fade-in zoom-in-95 duration-200">
+ <div className="flex items-center gap-4 px-4 py-2 bg-[#0A0A0A]/90 backdrop-blur-md rounded-full border border-white/30 shadow-2xl">
+ <div className="flex items-center gap-3">
+ <span className="text-[11px] text-white/70 font-medium tracking-tight">Zoom</span>
+ <div className="flex items-center gap-1">
+ <kbd className="h-5 px-1.5 flex items-center justify-center bg-[#171717] rounded border border-white/30 text-[9px] text-white font-mono">
+ Ctrl
+ </kbd>
+ <span className="text-white/70 text-[10px]">+</span>
+ <kbd className="h-5 px-1.5 flex items-center justify-center bg-[#171717] rounded border border-white/30 text-[9px] text-white font-mono">
+ Scroll
+ </kbd>
+ </div>
+ </div>
+
+ <div className="w-px h-4 bg-white/30" />
+
+ <div className="flex items-center gap-3">
+ <span className="text-[11px] text-white/70 font-medium tracking-tight">Pegar</span>
+ <div className="flex items-center gap-1">
+ <kbd className="h-5 px-1.5 flex items-center justify-center bg-[#171717] rounded border border-white/30 text-[9px] text-white font-mono">
+ Ctrl
+ </kbd>
+ <span className="text-white/70 text-[10px]">+</span>
+ <kbd className="w-5 h-5 flex items-center justify-center bg-[#171717] rounded border border-white/30 text-[9px] text-white font-mono">
+ V
+ </kbd>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/app/components/ui/editor/EditorTopBar.tsx b/app/components/ui/editor/EditorTopBar.tsx
index eb56c30..89c5732 100644
--- a/app/components/ui/editor/EditorTopBar.tsx
+++ b/app/components/ui/editor/EditorTopBar.tsx
@@ -2,7 +2,10 @@
import { Icon } from "@iconify/react";
import { ExportDropdown } from "../ExportDropdown";
+import { ExportImageDropdown } from "../ExportImageDropdown";
import type { ExportQuality, ExportProgress } from "@/types";
+import type { EditorMode } from "@/types/editor-mode.types";
+import type { ImageExportFormat } from "@/types/image-project.types";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
@@ -12,6 +15,12 @@ import Image from "next/image";
import Link from "next/link";
import { TooltipAction } from "@/components/ui/tooltip-action";
+interface ImageExportProgress {
+ status: "idle" | "preparing" | "rendering" | "complete" | "error";
+ progress: number;
+ message: string;
+}
+
interface EditorTopBarProps {
onExport: (quality: ExportQuality) => void;
exportProgress: ExportProgress;
@@ -20,6 +29,12 @@ interface EditorTopBarProps {
onRedo?: () => void;
canUndo?: boolean;
canRedo?: boolean;
+ // Photo mode props
+ editorMode?: EditorMode;
+ onImageExport?: (format: ImageExportFormat, quality: number, scale: number) => void;
+ imageExportProgress?: ImageExportProgress;
+ canvasWidth?: number;
+ canvasHeight?: number;
}
export function EditorTopBar({
@@ -30,7 +45,13 @@ export function EditorTopBar({
onRedo,
canUndo = false,
canRedo = false,
+ editorMode = "video",
+ onImageExport,
+ imageExportProgress,
+ canvasWidth = 1920,
+ canvasHeight = 1080,
}: EditorTopBarProps) {
+ const isPhotoMode = editorMode === "photo";
const t = useTranslations("editor.topBar");
const [showAlert, setShowAlert] = useState(false);
const [prevStatus, setPrevStatus] = useState<string>(exportProgress.status);
@@ -135,11 +156,21 @@ export function EditorTopBar({
</TooltipAction>
</div>
- <ExportDropdown
- onExport={onExport}
- exportProgress={exportProgress}
- hasTransparentBackground={hasTransparentBackground}
- />
+ {isPhotoMode && onImageExport && imageExportProgress ? (
+ <ExportImageDropdown
+ onExport={onImageExport}
+ exportProgress={imageExportProgress}
+ hasTransparentBackground={hasTransparentBackground}
+ canvasWidth={canvasWidth}
+ canvasHeight={canvasHeight}
+ />
+ ) : (
+ <ExportDropdown
+ onExport={onExport}
+ exportProgress={exportProgress}
+ hasTransparentBackground={hasTransparentBackground}
+ />
+ )}
{loading ? (
<div className="flex items-center gap-2 pl-3 border-l border-white/10 ml-1">
diff --git a/app/components/ui/editor/ElementsMenu.tsx b/app/components/ui/editor/ElementsMenu.tsx
index e2bd2ba..e39e50e 100644
--- a/app/components/ui/editor/ElementsMenu.tsx
+++ b/app/components/ui/editor/ElementsMenu.tsx
@@ -371,7 +371,7 @@ export function ElementsMenu({
)}
<div className="space-y-3">
- <SliderControl icon="mdi:resize" label={t("properties.size")} value={selectedElement.type === "svg" ? shapeSize : imageSize} onChange={selectedElement.type === "svg" ? setShapeSize : setImageSize} min={5} max={100} />
+ <SliderControl icon="mdi:resize" label={t("properties.size")} value={selectedElement.type === "svg" ? shapeSize : imageSize} onChange={selectedElement.type === "svg" ? setShapeSize : setImageSize} min={5} max={200} />
<SliderControl icon="mdi:opacity" label={t("properties.opacity")} value={selectedElement.type === "svg" ? shapeOpacity : imageOpacity} onChange={selectedElement.type === "svg" ? setShapeOpacity : setImageOpacity} />
</div>
diff --git a/app/components/ui/editor/HistoryMenu.tsx b/app/components/ui/editor/HistoryMenu.tsx
new file mode 100644
index 0000000..3202b5f
--- /dev/null
+++ b/app/components/ui/editor/HistoryMenu.tsx
@@ -0,0 +1,216 @@
+"use client";
+
+import { Icon } from "@iconify/react";
+import { useRef, useState, useCallback } from "react";
+import { useTranslations } from "next-intl";
+import type { ImageProjectPreview } from "@/types/image-project.types";
+import { TooltipAction } from "@/components/ui/tooltip-action";
+
+interface HistoryMenuProps {
+ projects: ImageProjectPreview[];
+ currentProjectId?: string | null;
+ isLoading?: boolean;
+ onSelectProject: (projectId: string) => void;
+ onAddToCanvas: (projectId: string) => void;
+ onDeleteProject: (projectId: string) => void;
+ onUploadToHistory: (file: File) => void;
+}
+
+export function HistoryMenu({
+ projects,
+ currentProjectId,
+ isLoading = false,
+ onSelectProject,
+ onAddToCanvas,
+ onDeleteProject,
+ onUploadToHistory,
+}: HistoryMenuProps) {
+ const t = useTranslations("historyMenu");
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [isDragging, setIsDragging] = useState(false);
+ const [deletingId, setDeletingId] = useState<string | null>(null);
+
+ const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (file && file.type.startsWith("image/")) {
+ onUploadToHistory(file);
+ }
+ e.target.value = "";
+ }, [onUploadToHistory]);
+
+ const handleDragOver = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragging(true);
+ }, []);
+
+ const handleDragLeave = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragging(false);
+ }, []);
+
+ const handleDrop = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragging(false);
+
+ const file = e.dataTransfer.files[0];
+ if (file && file.type.startsWith("image/")) {
+ onUploadToHistory(file);
+ }
+ }, [onUploadToHistory]);
+
+ const handleDelete = useCallback((projectId: string) => {
+ setDeletingId(projectId);
+ setTimeout(() => {
+ onDeleteProject(projectId);
+ setDeletingId(null);
+ }, 150);
+ }, [onDeleteProject]);
+
+ return (
+ <div className="p-4 flex flex-col gap-4 h-full">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-white font-medium">
+ <Icon icon="material-symbols:history" width="20" />
+ <span>{t("title")}</span>
+ </div>
+ <span className="text-xs text-white/40">
+ {projects.length} {t("items")}
+ </span>
+ </div>
+
+ <div
+ className={`relative squircle-element border-2 border-dashed transition-all cursor-pointer ${isDragging
+ ? "border-gray-500 bg-gray-500/10"
+ : "border-white/20 hover:border-gray-500/50 hover:bg-gray-500/5"
+ }`}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ className="hidden"
+ onChange={handleFileSelect}
+ />
+ <div className="p-4 flex flex-col items-center gap-2 text-center">
+ <div className={`p-2 rounded-full transition-colors ${isDragging ? "bg-gray-500/20 text-gray-400" : "bg-white/5 text-white/60"
+ }`}>
+ <Icon icon="solar:upload-minimalistic-outline" width="24" className="text-white/40 group-hover:text-white/70 transition-colors" />
+ </div>
+ <div>
+ <p className="text-sm text-white/70">
+ {isDragging ? t("upload.drop") : t("upload.dragOrClick")}
+ </p>
+ <p className="text-xs text-white/40 mt-1">
+ PNG, JPG ...
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex-1 overflow-y-auto custom-scrollbar px-2 pb-4 pt-2">
+ {isLoading ? (
+ <div className="grid grid-cols-2 gap-3 animate-pulse">
+ {[...Array(2)].map((_, i) => (
+ <div
+ key={i}
+ className="relative aspect-video squircle-element bg-white/5 border border-white/10 overflow-hidden"
+ >
+ <div className="absolute inset-0 bg-linear-to-t from-white/5 to-transparent" />
+
+ <div className="absolute inset-0 flex items-center justify-center">
+ <Icon icon="solar:image-linear" width="24" className="text-white/10" />
+ </div>
+
+ <div className="absolute inset-x-0 bottom-0 p-2.5">
+ <div className="h-2 w-2/3 bg-white/10 rounded-full" />
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : projects.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-12 text-white/40 animate-in fade-in">
+ <div className="w-16 h-16 squircle-element bg-white/5 flex items-center justify-center mb-4 border border-white/10">
+ <Icon icon="solar:gallery-linear" width="32" className="opacity-50" />
+ </div>
+ <p className="text-sm font-medium text-white/70">{t("empty.title")}</p>
+ <p className="text-xs mt-1 text-center max-w-50 leading-relaxed">{t("empty.description")}</p>
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 gap-3 animate-in fade-in duration-300">
+ {projects.map((project) => (
+ <div
+ key={project.id}
+ onClick={() => onSelectProject(project.id)}
+ className={`group relative aspect-video squircle-element overflow-hidden cursor-pointer transition-all duration-300 ${currentProjectId === project.id
+ ? "ring-2 ring-gray-400 ring-offset-2 ring-offset-[#0A0A0A] shadow-[0_0_15px_rgba(168,85,247,0.4)]"
+ : "border border-white/10 hover:border-white/30 hover:shadow-xl"
+ } ${deletingId === project.id ? "opacity-50 scale-95" : "scale-100"}`}
+ >
+ {project.thumbnailDataUrl ? (
+ <img
+ src={project.thumbnailDataUrl}
+ alt={project.imageName}
+ className="absolute inset-0 w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
+ />
+ ) : (
+ <div className="absolute inset-0 flex items-center justify-center bg-[#171717]">
+ <Icon icon="solar:image-linear" width="24" className="text-white/20" />
+ </div>
+ )}
+
+ {currentProjectId === project.id && (
+ <div className="absolute top-2 left-2 z-10 bg-black border border-white/30 rounded-full p-0.5 shadow-lg animate-in zoom-in">
+ <Icon icon="mdi:check" width="14" className="text-white" />
+ </div>
+ )}
+
+ <div className="absolute inset-0 bg-linear-to-t from-[#0A0A0A]/95 via-[#0A0A0A]/50 to-black/20 opacity-0 group-hover:opacity-100 transition-all duration-300 flex flex-col justify-between p-2.5">
+
+ <div className="flex justify-end gap-1.5 -translate-y-2.5 group-hover:translate-y-0 transition-transform duration-300">
+ <TooltipAction label={t("actions.addToCanvas")}>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onAddToCanvas(project.id);
+ }}
+ className="size-6 flex items-center justify-center squircle-element bg-[#0A0A0A]/80 backdrop-blur-md border border-white/20 text-white/70 hover:text-white hover:bg-gray-500 hover:border-gray-500 transition-all"
+ >
+ <Icon icon="material-symbols:add-rounded" width="16" />
+ </button>
+ </TooltipAction>
+
+ <TooltipAction label={t("actions.delete")}>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDelete(project.id);
+ }}
+ className="size-6 flex items-center justify-center squircle-element bg-[#0A0A0A]/80 backdrop-blur-md border border-white/20 text-white/70 hover:text-white hover:bg-red-500 hover:border-red-500 transition-all"
+ >
+ <Icon icon="solar:trash-bin-trash-linear" width="16" />
+ </button>
+ </TooltipAction>
+ </div>
+
+ <div className="translate-y-2.5 group-hover:translate-y-0 transition-transform duration-300">
+ <p className="text-[9px] text-white font-medium truncate drop-shadow-md tracking-tight">
+ {project.imageName}
+ </p>
+ </div>
+
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/ImageCropperModal.tsx b/app/components/ui/editor/ImageCropperModal.tsx
new file mode 100644
index 0000000..7362525
--- /dev/null
+++ b/app/components/ui/editor/ImageCropperModal.tsx
@@ -0,0 +1,413 @@
+"use client";
+
+import { useState, useRef, useEffect, useCallback } from "react";
+import { motion, AnimatePresence } from "framer-motion";
+import { Icon } from "@iconify/react";
+import { useTranslations } from "next-intl";
+import { Button } from "@/components/ui/button";
+import { CROP_ASPECT_RATIOS, type CropArea } from "@/types";
+
+interface ImageCropperModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ imageUrl: string | null;
+ onCropApply: (cropArea: CropArea) => void;
+ initialCrop?: CropArea | null;
+}
+
+export function ImageCropperModal({
+ isOpen,
+ onClose,
+ imageUrl,
+ onCropApply,
+ initialCrop,
+}: ImageCropperModalProps) {
+ const t = useTranslations("videoCropper");
+ const containerRef = useRef<HTMLDivElement>(null);
+ const imageRef = useRef<HTMLImageElement>(null);
+ const [cropArea, setCropArea] = useState<CropArea>(initialCrop ?? { x: 0, y: 0, width: 100, height: 100 });
+ const [selectedAspectRatio, setSelectedAspectRatio] = useState<number | null>(null);
+ const [isDragging, setIsDragging] = useState(false);
+ const [dragType, setDragType] = useState<"move" | "resize" | null>(null);
+ const [dragHandle, setDragHandle] = useState<string | null>(null);
+ const [imageDimensions, setImageDimensions] = useState({ width: 0, height: 0 });
+ const [wasOpen, setWasOpen] = useState(false);
+ const dragStartPos = useRef({ x: 0, y: 0 });
+ const initialCropRef = useRef<CropArea>({ x: 0, y: 0, width: 100, height: 100 });
+
+ if (isOpen && !wasOpen) {
+ setCropArea(initialCrop ?? { x: 0, y: 0, width: 100, height: 100 });
+ setSelectedAspectRatio(null);
+ setWasOpen(true);
+ } else if (!isOpen && wasOpen) {
+ setWasOpen(false);
+ }
+
+ const handleImageLoad = useCallback(() => {
+ if (imageRef.current) {
+ setImageDimensions({
+ width: imageRef.current.naturalWidth,
+ height: imageRef.current.naturalHeight,
+ });
+ }
+ }, []);
+
+ const handleAspectRatioSelect = useCallback((ratio: number | null) => {
+ setSelectedAspectRatio(ratio);
+ if (ratio === null || imageDimensions.width === 0) return;
+
+ const imageAspect = imageDimensions.width / imageDimensions.height;
+ const targetAspect = ratio;
+
+ let newWidth: number;
+ let newHeight: number;
+
+ if (targetAspect > imageAspect) {
+ newWidth = 100;
+ newHeight = (100 * imageAspect) / targetAspect;
+ } else {
+ newHeight = 100;
+ newWidth = (100 * targetAspect) / imageAspect;
+ }
+
+ const newX = (100 - newWidth) / 2;
+ const newY = (100 - newHeight) / 2;
+
+ setCropArea({
+ x: Math.max(0, newX),
+ y: Math.max(0, newY),
+ width: Math.min(100, newWidth),
+ height: Math.min(100, newHeight),
+ });
+ }, [imageDimensions]);
+
+ const handleMouseDown = (e: React.MouseEvent, type: "move" | "resize", handle?: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragging(true);
+ setDragType(type);
+ setDragHandle(handle ?? null);
+ dragStartPos.current = { x: e.clientX, y: e.clientY };
+ initialCropRef.current = { ...cropArea };
+ };
+
+ useEffect(() => {
+ if (!isDragging || !containerRef.current) return;
+
+ const handleMouseMove = (e: MouseEvent) => {
+ const container = containerRef.current;
+ if (!container) return;
+ const rect = container.getBoundingClientRect();
+ const deltaX = ((e.clientX - dragStartPos.current.x) / rect.width) * 100;
+ const deltaY = ((e.clientY - dragStartPos.current.y) / rect.height) * 100;
+
+ if (dragType === "move") {
+ const newX = Math.max(0, Math.min(100 - cropArea.width, initialCropRef.current.x + deltaX));
+ const newY = Math.max(0, Math.min(100 - cropArea.height, initialCropRef.current.y + deltaY));
+ setCropArea(prev => ({ ...prev, x: newX, y: newY }));
+ } else if (dragType === "resize" && dragHandle) {
+ const newCrop = { ...initialCropRef.current };
+ const minSize = 10;
+
+ switch (dragHandle) {
+ case "nw": {
+ const maxDx = initialCropRef.current.width - minSize;
+ const maxDy = initialCropRef.current.height - minSize;
+ const clampedDx = Math.max(-initialCropRef.current.x, Math.min(maxDx, deltaX));
+ const clampedDy = Math.max(-initialCropRef.current.y, Math.min(maxDy, deltaY));
+ newCrop.x = initialCropRef.current.x + clampedDx;
+ newCrop.y = initialCropRef.current.y + clampedDy;
+ newCrop.width = initialCropRef.current.width - clampedDx;
+ newCrop.height = initialCropRef.current.height - clampedDy;
+ break;
+ }
+ case "ne": {
+ const maxDx = 100 - initialCropRef.current.x - initialCropRef.current.width;
+ const maxDy = initialCropRef.current.height - minSize;
+ const clampedDx = Math.max(-(initialCropRef.current.width - minSize), Math.min(maxDx, deltaX));
+ const clampedDy = Math.max(-initialCropRef.current.y, Math.min(maxDy, deltaY));
+ newCrop.y = initialCropRef.current.y + clampedDy;
+ newCrop.width = initialCropRef.current.width + clampedDx;
+ newCrop.height = initialCropRef.current.height - clampedDy;
+ break;
+ }
+ case "sw": {
+ const maxDx = initialCropRef.current.width - minSize;
+ const maxDy = 100 - initialCropRef.current.y - initialCropRef.current.height;
+ const clampedDx = Math.max(-initialCropRef.current.x, Math.min(maxDx, deltaX));
+ const clampedDy = Math.max(-(initialCropRef.current.height - minSize), Math.min(maxDy, deltaY));
+ newCrop.x = initialCropRef.current.x + clampedDx;
+ newCrop.width = initialCropRef.current.width - clampedDx;
+ newCrop.height = initialCropRef.current.height + clampedDy;
+ break;
+ }
+ case "se": {
+ const maxDx = 100 - initialCropRef.current.x - initialCropRef.current.width;
+ const maxDy = 100 - initialCropRef.current.y - initialCropRef.current.height;
+ const clampedDx = Math.max(-(initialCropRef.current.width - minSize), Math.min(maxDx, deltaX));
+ const clampedDy = Math.max(-(initialCropRef.current.height - minSize), Math.min(maxDy, deltaY));
+ newCrop.width = initialCropRef.current.width + clampedDx;
+ newCrop.height = initialCropRef.current.height + clampedDy;
+ break;
+ }
+ case "n": {
+ const maxDy = initialCropRef.current.height - minSize;
+ const clampedDy = Math.max(-initialCropRef.current.y, Math.min(maxDy, deltaY));
+ newCrop.y = initialCropRef.current.y + clampedDy;
+ newCrop.height = initialCropRef.current.height - clampedDy;
+ break;
+ }
+ case "s": {
+ const maxDy = 100 - initialCropRef.current.y - initialCropRef.current.height;
+ const clampedDy = Math.max(-(initialCropRef.current.height - minSize), Math.min(maxDy, deltaY));
+ newCrop.height = initialCropRef.current.height + clampedDy;
+ break;
+ }
+ case "w": {
+ const maxDx = initialCropRef.current.width - minSize;
+ const clampedDx = Math.max(-initialCropRef.current.x, Math.min(maxDx, deltaX));
+ newCrop.x = initialCropRef.current.x + clampedDx;
+ newCrop.width = initialCropRef.current.width - clampedDx;
+ break;
+ }
+ case "e": {
+ const maxDx = 100 - initialCropRef.current.x - initialCropRef.current.width;
+ const clampedDx = Math.max(-(initialCropRef.current.width - minSize), Math.min(maxDx, deltaX));
+ newCrop.width = initialCropRef.current.width + clampedDx;
+ break;
+ }
+ }
+
+ newCrop.x = Math.max(0, Math.min(100 - minSize, newCrop.x));
+ newCrop.y = Math.max(0, Math.min(100 - minSize, newCrop.y));
+ newCrop.width = Math.max(minSize, Math.min(100 - newCrop.x, newCrop.width));
+ newCrop.height = Math.max(minSize, Math.min(100 - newCrop.y, newCrop.height));
+ setCropArea(newCrop);
+ }
+ };
+
+ const handleMouseUp = () => {
+ setIsDragging(false);
+ setDragType(null);
+ setDragHandle(null);
+ };
+
+ window.addEventListener("mousemove", handleMouseMove);
+ window.addEventListener("mouseup", handleMouseUp);
+ return () => {
+ window.removeEventListener("mousemove", handleMouseMove);
+ window.removeEventListener("mouseup", handleMouseUp);
+ };
+ }, [isDragging, dragType, dragHandle, cropArea.width, cropArea.height]);
+
+ const handleReset = () => {
+ setCropArea({ x: 0, y: 0, width: 100, height: 100 });
+ setSelectedAspectRatio(null);
+ };
+
+ const handleApply = () => {
+ onCropApply(cropArea);
+ onClose();
+ };
+
+ if (!isOpen) return null;
+
+ return (
+ <AnimatePresence>
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center"
+ >
+ <motion.div
+ initial={{ scale: 0.96, opacity: 0, y: 8 }}
+ animate={{ scale: 1, opacity: 1, y: 0 }}
+ exit={{ scale: 0.96, opacity: 0, y: 8 }}
+ transition={{ duration: 0.18, ease: [0.16, 1, 0.3, 1] }}
+ className="bg-[#0a0a0b] rounded-2xl border border-white/10 w-[92vw] max-w-5xl max-h-[88vh] flex flex-col overflow-hidden shadow-2xl"
+ >
+ {/* Header */}
+ <div className="flex items-center justify-between px-5 py-3.5 border-b border-white/10">
+ <div className="flex items-center gap-2.5">
+ <div className="w-6 h-6 rounded-md bg-white/10 flex items-center justify-center">
+ <Icon icon="mdi:crop" className="text-sm text-white/70" />
+ </div>
+ <span className="text-sm font-medium text-white">Recortar Imagen</span>
+ {imageDimensions.width > 0 && (
+ <span className="text-[11px] font-mono text-white/60 bg-white/4 px-2 py-0.5 rounded-md border border-white/10">
+ {imageDimensions.width} × {imageDimensions.height}
+ </span>
+ )}
+ </div>
+ <button
+ onClick={onClose}
+ className="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-white/10 transition-colors text-white/40 hover:text-white/70"
+ >
+ <Icon icon="mdi:close" className="text-base" />
+ </button>
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 flex overflow-hidden min-h-0">
+ {/* Preview Area */}
+ <div className="flex-1 p-6 flex items-center justify-center bg-black/50 overflow-hidden">
+ <div
+ ref={containerRef}
+ className="relative w-full h-full max-w-full max-h-full flex items-center justify-center"
+ >
+ <div
+ className="relative"
+ style={{
+ width: imageDimensions.width > imageDimensions.height ? '100%' : 'auto',
+ height: imageDimensions.width > imageDimensions.height ? 'auto' : '100%',
+ aspectRatio: `${imageDimensions.width}/${imageDimensions.height}`,
+ maxWidth: '100%',
+ maxHeight: '100%',
+ }}
+ >
+ {/* Imagen */}
+ <img
+ ref={imageRef}
+ src={imageUrl || ''}
+ alt="Crop preview"
+ onLoad={handleImageLoad}
+ className="w-full h-full object-contain select-none pointer-events-none"
+ draggable={false}
+ />
+
+ {/* Overlay oscuro fuera del área de recorte */}
+ <div className="absolute inset-0 pointer-events-none">
+ <svg width="100%" height="100%" className="absolute inset-0">
+ <defs>
+ <mask id="cropMask">
+ <rect width="100%" height="100%" fill="white" />
+ <rect
+ x={`${cropArea.x}%`}
+ y={`${cropArea.y}%`}
+ width={`${cropArea.width}%`}
+ height={`${cropArea.height}%`}
+ fill="black"
+ />
+ </mask>
+ </defs>
+ <rect width="100%" height="100%" fill="black" fillOpacity="0.5" mask="url(#cropMask)" />
+ </svg>
+ </div>
+
+ {/* Área de recorte */}
+ <div
+ className="absolute border-2 border-white shadow-lg cursor-move"
+ style={{
+ left: `${cropArea.x}%`,
+ top: `${cropArea.y}%`,
+ width: `${cropArea.width}%`,
+ height: `${cropArea.height}%`,
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "move")}
+ >
+ {/* Regla de tercios */}
+ <div className="absolute inset-0 grid grid-cols-3 grid-rows-3 pointer-events-none">
+ {[...Array(9)].map((_, i) => (
+ <div key={i} className="border border-white/20" />
+ ))}
+ </div>
+
+ {/* Handles de resize */}
+ {["nw", "ne", "sw", "se", "n", "s", "w", "e"].map((handle) => (
+ <div
+ key={handle}
+ className={`absolute w-3 h-3 bg-white border border-gray-800 rounded-sm cursor-${
+ handle.includes("n") || handle.includes("s") ? "ns" : handle.includes("w") || handle.includes("e") ? "ew" : "nwse"
+ }-resize hover:scale-125 transition-transform`}
+ style={{
+ ...(handle.includes("n") && { top: -1.5 }),
+ ...(handle.includes("s") && { bottom: -1.5 }),
+ ...(handle.includes("w") && { left: -1.5 }),
+ ...(handle.includes("e") && { right: -1.5 }),
+ ...(!handle.includes("n") && !handle.includes("s") && { top: "50%", transform: "translateY(-50%)" }),
+ ...(!handle.includes("w") && !handle.includes("e") && { left: "50%", transform: "translateX(-50%)" }),
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "resize", handle)}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Sidebar */}
+ <div className="w-64 bg-[#0a0a0b] border-l border-white/10 flex flex-col">
+ {/* Aspect Ratios */}
+ <div className="p-4 border-b border-white/10">
+ <p className="text-[10px] uppercase tracking-widest font-semibold text-white/60 mb-3">
+ {t("sections.ratio")}
+ </p>
+ <div className="grid grid-cols-3 gap-1">
+ {CROP_ASPECT_RATIOS.map((ratio) => (
+ <div key={ratio.label} className="relative">
+ <button
+ onClick={() => handleAspectRatioSelect(ratio.value)}
+ className={`w-full py-1.5 text-[11px] font-medium rounded-lg transition-all ${
+ selectedAspectRatio === ratio.value
+ ? "text-white border-transparent"
+ : "bg-white/4 text-white/40 hover:bg-white/8 hover:text-white/70 border border-white/10"
+ }`}
+ style={
+ selectedAspectRatio === ratio.value
+ ? {
+ background: "radial-gradient(circle at 50% 0%, #555555 0%, #252525 64%)",
+ boxShadow: "0 0 0 1px #fff3, 0 4px 4px 0 #0004, 0 0 0 1px #333",
+ }
+ : {}
+ }
+ >
+ {ratio.label}
+ </button>
+ {selectedAspectRatio === ratio.value && (
+ <div className="absolute left-1 top-1/5 -translate-y-1/2 size-3 bg-white rounded-full blur-[5px]" />
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Crop Area Info */}
+ <div className="p-4 border-b border-white/10">
+ <p className="text-[10px] uppercase tracking-widest font-semibold text-white/60 mb-3">
+ {t("sections.area")}
+ </p>
+ <div className="space-y-2">
+ {[
+ { label: t("labels.x"), value: cropArea.x },
+ { label: t("labels.y"), value: cropArea.y },
+ { label: t("labels.width"), value: cropArea.width },
+ { label: t("labels.height"), value: cropArea.height },
+ ].map(({ label, value }) => (
+ <div key={label} className="flex items-center justify-between">
+ <span className="text-[11px] text-white/25 font-mono w-4">{label}</span>
+ <div className="flex-1 mx-3 h-px bg-white/4" />
+ <span className="text-[11px] font-mono text-white/50">{value.toFixed(1)}%</span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex-1" />
+
+ {/* Actions */}
+ <div className="p-4 flex flex-col gap-2">
+ <Button variant="outline" onClick={handleReset}>
+ {t("buttons.reset")}
+ </Button>
+ <Button variant="primary" onClick={handleApply}>
+ {t("buttons.apply")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </motion.div>
+ </motion.div>
+ </AnimatePresence>
+ );
+}
diff --git a/app/components/ui/editor/ImageMaskEditor.tsx b/app/components/ui/editor/ImageMaskEditor.tsx
new file mode 100644
index 0000000..efa063e
--- /dev/null
+++ b/app/components/ui/editor/ImageMaskEditor.tsx
@@ -0,0 +1,336 @@
+"use client";
+
+import { Icon } from "@iconify/react";
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { SliderControl } from "../SliderControl";
+import {
+ Popover,
+ PopoverTrigger,
+ PopoverContent,
+ PopoverHeader,
+ PopoverTitle,
+} from "@/components/ui/popover";
+import type { ImageMaskConfig } from "@/types/photo.types";
+import { getMediaMaskStyles } from "./getMediaMaskStyles";
+import { ImageMaskEditorProps, MaskPreset, MASK_PRESETS } from "@/types/ImageMask.types";
+
+export function ImageMaskEditor({
+ maskConfig,
+ onMaskConfigChange,
+ canvasImageUrl
+}: ImageMaskEditorProps) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [activeTab, setActiveTab] = useState<"presets" | "custom">("presets");
+
+ const isPresetActive = (preset: MaskPreset) => {
+ if (preset.id === "none") {
+ return !maskConfig.enabled || (!maskConfig.top && !maskConfig.bottom && !maskConfig.left && !maskConfig.right && !maskConfig.angle);
+ }
+
+ if (!maskConfig.enabled) return false;
+
+ const isEqual = (a: unknown, b: unknown) => JSON.stringify(a || null) === JSON.stringify(b || null);
+
+ return (
+ isEqual(maskConfig.top, preset.config.top) &&
+ isEqual(maskConfig.bottom, preset.config.bottom) &&
+ isEqual(maskConfig.left, preset.config.left) &&
+ isEqual(maskConfig.right, preset.config.right) &&
+ maskConfig.angle === preset.config.angle
+ );
+ };
+
+ const handlePresetClick = (preset: MaskPreset) => {
+ if (preset.id === "none") {
+ onMaskConfigChange({ enabled: false });
+ return;
+ }
+
+ onMaskConfigChange({
+ enabled: preset.config.enabled ?? true,
+ top: undefined,
+ bottom: undefined,
+ left: undefined,
+ right: undefined,
+ angle: undefined,
+ angleFrom: undefined,
+ angleTo: undefined,
+ ...preset.config,
+ });
+ };
+
+ const getPreviewMaskStyles = (presetConfig: Partial<ImageMaskConfig>) => {
+ if (!presetConfig.enabled) return {};
+ return getMediaMaskStyles({
+ enabled: true,
+ top: presetConfig.top,
+ bottom: presetConfig.bottom,
+ left: presetConfig.left,
+ right: presetConfig.right,
+ angle: presetConfig.angle,
+ angleFrom: presetConfig.angleFrom,
+ angleTo: presetConfig.angleTo,
+ });
+ };
+
+ return (
+ <Popover open={isOpen} onOpenChange={setIsOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ className={`gap-2 text-xs transition-all duration-200 ${maskConfig.enabled
+ ? "bg-gradient-radial-primary text-cyan-500 border border-cyan-500/50!"
+ : ""
+ }`}
+ size="sm"
+ >
+ <Icon icon="material-symbols:gradient-outline" width="16" />
+ Mask
+ </Button>
+
+ </PopoverTrigger>
+
+ <PopoverContent align="end" className="w-100 bg-[#0A0A0A] border-white/10 shadow-2xl p-0 rounded-xl overflow-hidden">
+ <div className="flex flex-col">
+ <PopoverHeader className="px-4 py-3 border-b border-white/10 bg-white/5">
+ <div className="flex items-center justify-between">
+ <PopoverTitle className="text-xs font-semibold text-white/80 tracking-wide uppercase flex items-center gap-2">
+ <Icon icon="material-symbols:gradient-outline" width="14" className="text-blue-400" />
+ Efectos de Máscara
+ </PopoverTitle>
+ </div>
+ </PopoverHeader>
+
+ <div className="flex border-b border-white/10 bg-black/20">
+ <button
+ onClick={() => setActiveTab("presets")}
+ className={`flex-1 px-4 py-2.5 text-xs font-medium transition-all ${activeTab === "presets"
+ ? "text-blue-400 border-b-2 border-blue-400 bg-blue-500/5"
+ : "text-white/50 hover:text-white/80 hover:bg-white/5"
+ }`}
+ >
+ <Icon icon="mdi:palette-outline" width="14" className="inline mr-1.5" />
+ Preestablecido
+ </button>
+ <button
+ onClick={() => setActiveTab("custom")}
+ className={`flex-1 px-4 py-2.5 text-xs font-medium transition-all ${activeTab === "custom"
+ ? "text-blue-400 border-b-2 border-blue-400 bg-blue-500/5"
+ : "text-white/50 hover:text-white/80 hover:bg-white/5"
+ }`}
+ >
+ <Icon icon="mdi:tune" width="14" className="inline mr-1.5" />
+ Personalizado
+ </button>
+ </div>
+
+ <div className="p-4 max-h-96 overflow-y-auto custom-scrollbar">
+ {activeTab === "presets" ? (
+ <div className="grid grid-cols-2 gap-3 w-full">
+ {MASK_PRESETS.map((preset) => {
+ const active = isPresetActive(preset);
+ const previewStyles = getPreviewMaskStyles(preset.config);
+
+ return (
+ <button
+ key={preset.id}
+ onClick={() => handlePresetClick(preset)}
+ className={`group relative flex flex-col rounded-lg border transition-all overflow-hidden ${
+ active
+ ? "border-blue-500 bg-blue-500/10"
+ : "border-white/10 hover:border-white/30 bg-white/5 hover:bg-white/10"
+ }`}
+ >
+ <div className="relative w-full aspect-video bg-zinc-900">
+ {canvasImageUrl ? (
+ <div className="absolute inset-0 flex items-center justify-center p-1">
+ <img
+ src={canvasImageUrl}
+ alt={preset.label}
+ className="w-full h-full object-cover"
+ style={previewStyles}
+ />
+ </div>
+ ) : (
+ <div className="absolute inset-0 flex items-center justify-center">
+ <Icon
+ icon={preset.icon}
+ width="28"
+ className={`transition-colors ${active ? "text-blue-400" : "text-white/40 group-hover:text-blue-400"}`}
+ />
+ </div>
+ )}
+
+ <div className="absolute inset-x-0 bottom-0 h-full flex items-end p-2 pointer-events-none">
+ <span className={`text-[10px] font-bold text-shadow-lg transition-colors leading-tight ${active ? "text-blue-400" : "text-white/90"}`}>
+ {preset.label}
+ </span>
+ </div>
+
+ {active && (
+ <div className="absolute top-2 right-2 z-30 size-4 rounded-full bg-gradient-primary flex items-center justify-center shadow-xl">
+ <Icon icon="mdi:check" width="10" className="text-white" />
+ </div>
+ )}
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <label className="text-xs font-medium text-white/70">Top</label>
+ <button
+ onClick={() => onMaskConfigChange({
+ ...maskConfig,
+ top: maskConfig.top ? undefined : { from: 0, to: 30 },
+ })}
+ className="text-[10px] text-blue-400 hover:text-blue-300"
+ >
+ {maskConfig.top ? "Quitar" : "Añadir"}
+ </button>
+ </div>
+ {maskConfig.top && (
+ <>
+ <SliderControl
+ label="From"
+ value={maskConfig.top.from}
+ onChange={(value) => onMaskConfigChange({
+ ...maskConfig,
+ top: { ...maskConfig.top!, from: value },
+ })}
+ min={0}
+ max={100}
+ step={1}
+ suffix="%"
+ />
+ <SliderControl
+ label="To"
+ value={maskConfig.top.to ?? 100}
+ onChange={(value) => onMaskConfigChange({
+ ...maskConfig,
+ top: { ...maskConfig.top!, to: value },
+ })}
+ min={0}
+ max={100}
+ step={1}
+ suffix="%"
+ />
+ </>
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <hr />
+ <div className="flex items-center justify-between">
+ <label className="text-xs font-medium text-white/70">Bottom</label>
+ <button
+ onClick={() => onMaskConfigChange({
+ ...maskConfig,
+ bottom: maskConfig.bottom ? undefined : { from: 0, to: 30 },
+ })}
+ className="text-[10px] text-blue-400 hover:text-blue-300"
+ >
+ {maskConfig.bottom ? "Quitar" : "Añadir"}
+ </button>
+ </div>
+ {maskConfig.bottom && (
+ <>
+ <SliderControl
+ label="From"
+ value={maskConfig.bottom.from}
+ onChange={(value) => onMaskConfigChange({
+ ...maskConfig,
+ bottom: { ...maskConfig.bottom!, from: value },
+ })}
+ min={0}
+ max={100}
+ step={1}
+ suffix="%"
+ />
+ <SliderControl
+ label="To"
+ value={maskConfig.bottom.to ?? 100}
+ onChange={(value) => onMaskConfigChange({
+ ...maskConfig,
+ bottom: { ...maskConfig.bottom!, to: value },
+ })}
+ min={0}
+ max={100}
+ step={1}
+ suffix="%"
+ />
+ </>
+ )}
+ </div>
+ <hr />
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <label className="text-xs font-medium text-white/70">Left</label>
+ <button
+ onClick={() => onMaskConfigChange({
+ ...maskConfig,
+ left: maskConfig.left ? undefined : { from: 0, to: 20 },
+ })}
+ className="text-sm text-blue-400 hover:text-blue-300"
+ >
+ {maskConfig.left ? "x" : "+"}
+ </button>
+ </div>
+ {maskConfig.left && (
+ <SliderControl
+ label="From"
+ value={maskConfig.left.from}
+ onChange={(value) => onMaskConfigChange({
+ ...maskConfig,
+ left: { ...maskConfig.left!, from: value },
+ })}
+ min={0}
+ max={100}
+ step={1}
+ suffix="%"
+ />
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <label className="text-xs font-medium text-white/70">Right</label>
+ <button
+ onClick={() => onMaskConfigChange({
+ ...maskConfig,
+ right: maskConfig.right ? undefined : { from: 0, to: 20 },
+ })}
+ className="text-sm text-blue-400 hover:text-blue-300"
+ >
+ {maskConfig.right ? "x" : "+"}
+ </button>
+ </div>
+ {maskConfig.right && (
+ <SliderControl
+ label="From"
+ value={maskConfig.right.from}
+ onChange={(value) => onMaskConfigChange({
+ ...maskConfig,
+ right: { ...maskConfig.right!, from: value },
+ })}
+ min={0}
+ max={100}
+ step={1}
+ suffix="%"
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/MobileToolsMenu.tsx b/app/components/ui/editor/MobileToolsMenu.tsx
index 44045f0..157a35d 100644
--- a/app/components/ui/editor/MobileToolsMenu.tsx
+++ b/app/components/ui/editor/MobileToolsMenu.tsx
@@ -43,10 +43,10 @@ export function MobileToolsMenu({
<Dialog.Root open={isOpen} onOpenChange={setIsOpen}>
<Dialog.Trigger asChild>
<button
- className="fixed bottom-4 left-4 z-50 h-14 w-14 rounded-full shadow-lg shadow-blue-500/50 bg-gradient-primary flex items-center justify-center hover:scale-105 transition-transform active:scale-95 lg:hidden"
+ className="fixed bottom-4 left-4 z-50 size-10 rounded-full shadow-lg shadow-blue-500/50 bg-gradient-primary flex items-center justify-center hover:scale-105 transition-transform active:scale-95 lg:hidden"
aria-label="Abrir menú de herramientas"
>
- <Icon icon="solar:widget-2-bold-duotone" width="24" className="text-white" />
+ <Icon icon="solar:widget-2-bold-duotone" width="20" className="text-white" />
</button>
</Dialog.Trigger>
diff --git a/app/components/ui/editor/PhotoEditorPlaceholder.tsx b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
new file mode 100644
index 0000000..b36f193
--- /dev/null
+++ b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
@@ -0,0 +1,343 @@
+"use client";
+
+import { Icon } from "@iconify/react";
+import { useTranslations } from "next-intl";
+import { useState, useCallback } from "react";
+import { SliderControl } from "../SliderControl";
+import { Button } from "@/components/ui/button";
+import { AspectRatioSelect } from "@/app/components/ui/AspectRatioSelect";
+import { TooltipAction } from "@/components/ui/tooltip-action";
+import { ImageMaskEditor } from "./ImageMaskEditor";
+import {
+ Popover,
+ PopoverTrigger,
+ PopoverContent,
+ PopoverHeader,
+ PopoverTitle,
+} from "@/components/ui/popover";
+import { PhotoEditorPlaceholderProps, Preview3DConfig, PREVIEW_CONFIGS } from "@/types/photo.types";
+
+export function PhotoEditorPlaceholder({
+ className = "",
+ canvasImageUrl,
+ staticImageUrl,
+ onSelectPreview,
+ selectedPreviewId = "front",
+ aspectRatio = "auto",
+ onAspectRatioChange,
+ customAspectRatio = null,
+ onCustomAspectRatioChange,
+ onOpenCropper,
+ apply3DToBackground = false,
+ onToggle3DBackground,
+ imageMaskConfig,
+ onImageMaskConfigChange,
+ imageTransform,
+ onReset,
+}: PhotoEditorPlaceholderProps) {
+ const previewImageUrl = staticImageUrl ?? canvasImageUrl;
+ const t = useTranslations("editor");
+
+ const [customConfig, setCustomConfig] = useState<Preview3DConfig>({
+ id: "custom",
+ label: "Custom",
+ rotateX: 0,
+ rotateY: 0,
+ rotateZ: 0,
+ translateY: 0,
+ scale: 0.9,
+ perspective: 600,
+ });
+
+ const [isCustomPopoverOpen, setIsCustomPopoverOpen] = useState(false);
+
+ const isCustomUntouched =
+ customConfig.rotateX === 0 &&
+ customConfig.rotateY === 0 &&
+ customConfig.rotateZ === 0 &&
+ customConfig.translateY === 0 &&
+ customConfig.scale === 0.9 &&
+ customConfig.perspective === 600;
+
+ const updateCustomConfig = useCallback(
+ (updates: Partial<Preview3DConfig>) => {
+ const newConfig = { ...customConfig, ...updates };
+ setCustomConfig(newConfig);
+ if (selectedPreviewId === "custom") {
+ onSelectPreview?.(newConfig);
+ }
+ },
+ [customConfig, onSelectPreview, selectedPreviewId]
+ );
+
+ const allPreviews: Preview3DConfig[] = [
+ ...PREVIEW_CONFIGS.map(config => ({ ...config })),
+ customConfig,
+ ];
+
+ if (!previewImageUrl) {
+ return (
+ <div
+ className={`flex flex-col items-center justify-center bg-black border-t border-white/10 ${className}`}
+ style={{ height: "180px" }}
+ >
+ <div className="flex flex-col items-center gap-3 text-white/40">
+ <div className="p-3 rounded-xl bg-white/5 border border-white/10">
+ <Icon icon="lucide:image" width={28} height={28} />
+ </div>
+ <div className="text-center">
+ <p className="text-sm font-medium text-white/60">
+ {t("photoMode.title") || "No Image"}
+ </p>
+ <p className="text-xs text-white/40 mt-1 max-w-xs">
+ {t("photoMode.description") || "Upload or capture an image to get started"}
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const renderPreviewCard = (config: Preview3DConfig) => {
+ const isSelected = selectedPreviewId === config.id;
+ const isCustom = config.id === "custom";
+
+ const ButtonCard = (
+ <button
+ onClick={() => {
+ onSelectPreview?.(config);
+ if (isCustom) setIsCustomPopoverOpen(true);
+ }}
+ className={`group relative flex-1 min-w-25 aspect-video squircle-element p-px transition-all duration-300 ease-out outline-none ${isSelected
+ ? `bg-gradient-radial-primary shadow-[0_0_20px_rgba(0,163,255,0.15)]`
+ : isCustom && isCustomUntouched
+ ? "bg-transparent border border-dashed border-white/20 hover:border-white/40"
+ : "bg-white/10 hover:bg-white/20"
+ }`}
+ >
+ <div
+ className={`relative w-full h-full rounded-[10px] overflow-hidden transition-colors ${isCustom && isCustomUntouched ? "bg-transparent" : "bg-black/90"
+ }`}
+ >
+ {(!isCustom || !isCustomUntouched) && (
+ <div
+ className="absolute inset-0 opacity-[0.17] pointer-events-none group-hover:opacity-[0.3] transition-opacity duration-300"
+ style={{
+ backgroundImage: `radial-gradient(circle, #ffffff 0.8px, transparent 0.8px)`,
+ backgroundSize: '10px 10px',
+ }}
+ />
+ )}
+ {isCustom && isCustomUntouched ? (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-1.5 bg-white/3 group-hover:bg-white/5 border border-white/10 transition-colors">
+ <div className="w-7 h-7 rounded-full bg-white/5 border border-white/5 flex items-center justify-center">
+ <Icon icon="mdi:tune-variant" width={14} className="text-white/60 group-hover:text-[#00A3EE] transition-colors" />
+ </div>
+ <span className="text-[10px] font-medium text-white/50 group-hover:text-white/80 transition-colors">
+ Personalizar
+ </span>
+ </div>
+ ) : (
+ <>
+ <div className="absolute inset-0 bg-linear-to-br from-white/3 to-transparent" />
+
+ {isCustom && (
+ <div className="absolute top-2 left-2 z-20 flex items-center gap-1 bg-black/60 backdrop-blur-md border border-white/10 px-1.5 py-0.5 rounded text-[9px] font-bold text-white/90 uppercase tracking-wider pointer-events-none shadow-lg">
+ <Icon icon="mdi:tune" width={10} className="text-[#00A3EE]" />
+ Custom
+ </div>
+ )}
+
+ <div className="absolute inset-0 flex items-center justify-center p-2 z-10">
+ <div
+ style={{ perspective: `${config.perspective || 600}px`, perspectiveOrigin: 'center center' }}
+ className="w-full h-full flex items-center justify-center"
+ >
+ <div
+ className="relative w-full h-full rounded-md overflow-hidden border border-white/5 shadow-2xl"
+ style={{
+ transform: `rotateX(${config.rotateX}deg) rotateY(${config.rotateY}deg) rotateZ(${config.rotateZ}deg) scale(${config.scale}) translateY(${config.translateY}%)`,
+ transformStyle: "preserve-3d",
+ transition: "transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)",
+ }}
+ >
+ <img src={previewImageUrl!} alt={config.label} className="w-full h-full object-cover" draggable={false} />
+ </div>
+ </div>
+ </div>
+
+ <div className="absolute inset-0 bg-linear-to-t from-black/80 via-black/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none z-20" />
+ <div className="absolute bottom-2 left-2 opacity-0 group-hover:opacity-100 transition-all duration-300 translate-y-1 group-hover:translate-y-0 pointer-events-none flex items-center gap-1.5 z-20">
+ {!isCustom && <Icon icon="mdi:eye-outline" width={12} className="text-white/70" />}
+ <span className="text-[11px] font-medium text-white/90 tracking-wide">
+ {config.label}
+ </span>
+ </div>
+ </>
+ )}
+
+ {isSelected && (
+ <div className={`absolute top-2 right-2 z-30 size-5 rounded-full bg-gradient-primary flex items-center justify-center shadow-xl`}>
+ <Icon icon="mdi:check-bold" width={12} className="text-white" />
+ </div>
+ )}
+ </div>
+ </button>
+ );
+
+ if (isCustom) {
+ return (
+ <Popover open={isCustomPopoverOpen} onOpenChange={setIsCustomPopoverOpen} key={config.id}>
+ <PopoverTrigger asChild>
+ {ButtonCard}
+ </PopoverTrigger>
+ <PopoverContent align="end" sideOffset={12} className="w-64 bg-[#0A0A0A] border-white/10 shadow-2xl p-4 space-y-4 rounded-xl z-50">
+ <PopoverHeader className="mb-2">
+ <PopoverTitle className="text-xs font-semibold text-white/80 tracking-wide uppercase flex items-center gap-2">
+ <Icon icon="mdi:tune" width={14} className="text-[#00A3EE]" />
+ Ajustes 3D
+ </PopoverTitle>
+ </PopoverHeader>
+
+ <div className="space-y-4">
+ <SliderControl icon="mdi:cube-outline" label="Perspectiva" value={customConfig.perspective || 600} min={200} max={1000} step={50} onChange={(value) => updateCustomConfig({ perspective: value })} suffix="px" />
+ <SliderControl icon="mdi:resize" label="Escala" value={Math.round(customConfig.scale * 100)} min={50} max={150} step={5} onChange={(value) => updateCustomConfig({ scale: value / 100 })} suffix="%" />
+
+ {/* Pad de Rotación 2D minimalista */}
+ <div className="space-y-2">
+ <div className="flex items-center gap-1.5 text-[11px] text-white/50">
+ <Icon icon="mdi:rotate-3d-variant" width={12} />
+ <span>Rotación (X/Y)</span>
+ </div>
+ <div
+ className="relative w-full aspect-square bg-white/3 rounded-lg border border-white/10 cursor-crosshair overflow-hidden hover:bg-white/4 transition-colors"
+ onClick={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
+ const y = ((e.clientY - rect.top) / rect.height) * 2 - 1;
+ updateCustomConfig({ rotateY: Math.round(-x * 45), rotateX: Math.round(y * 45) });
+ }}
+ >
+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
+ <div className="w-full h-px bg-white/5" />
+ <div className="h-full w-px bg-white/5 absolute" />
+ </div>
+ <div
+ className={`absolute w-2.5 h-2.5 rounded-full bg-gradient-primary shadow-[0_0_10px_rgba(0,163,255,0.5)]`}
+ style={{ left: `${50 + (-customConfig.rotateY / 45) * 50}%`, top: `${50 + (customConfig.rotateX / 45) * 50}%`, transform: "translate(-50%, -50%)", transition: "all 0.1s ease-out" }}
+ />
+ </div>
+ </div>
+
+ <SliderControl icon="mdi:axis-z-rotate-clockwise" label="Rotación Z" value={customConfig.rotateZ} min={-45} max={45} step={5} onChange={(value) => updateCustomConfig({ rotateZ: value })} suffix="°" />
+ <SliderControl icon="mdi:arrow-up-down" label="Vertical" value={customConfig.translateY} min={-10} max={10} step={1} onChange={(value) => updateCustomConfig({ translateY: value })} suffix="%" />
+ </div>
+
+ <button
+ onClick={() => {
+ const resetConfig: Preview3DConfig = { id: "custom", label: "Custom", rotateX: 0, rotateY: 0, rotateZ: 0, translateY: 0, scale: 0.9, perspective: 600 };
+ setCustomConfig(resetConfig);
+ if (selectedPreviewId === "custom") onSelectPreview?.(resetConfig);
+ }}
+ className="w-full mt-4 px-3 py-2 rounded-lg bg-white/5 hover:bg-white/10 text-[11px] text-white/60 hover:text-white transition-all flex items-center justify-center gap-2 border border-white/5"
+ >
+ <Icon icon="mdi:restore" width={14} />
+ Restablecer
+ </button>
+ </PopoverContent>
+ </Popover>
+ );
+ }
+
+ return <div key={config.id} className="contents">{ButtonCard}</div>;
+ };
+
+ return (
+ <div className={`flex flex-col bg-black border-t border-white/10 ${className}`}>
+
+ <div className="flex flex-wrap items-center justify-between gap-3 px-5 py-3 border-b border-white/5">
+ <div className="flex items-center gap-2 text-white/60 whitespace-nowrap">
+ <Icon icon="mdi:tune-vertical" width={16} />
+ <span className="text-xs font-semibold tracking-wide uppercase">Ajustes</span>
+ {imageMaskConfig && onImageMaskConfigChange && (
+ <ImageMaskEditor
+ maskConfig={imageMaskConfig}
+ onMaskConfigChange={onImageMaskConfigChange}
+ canvasImageUrl={staticImageUrl ?? canvasImageUrl}
+ />
+ )}
+
+ {onToggle3DBackground && (
+ <TooltipAction label="Aplicar efecto 3D">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => onToggle3DBackground(!apply3DToBackground)}
+ className={`px-2.5 py-2 text-xs font-medium squircle-element transition-all ${apply3DToBackground
+ ? "bg-gradient-radial-primary text-cyan-500 border border-cyan-500/50!"
+ : "bg-white/5 text-white/50 border border-white/10 hover:bg-white/10"
+ }`}
+ aria-label="Aplicar efecto 3D"
+ >
+ <Icon icon="mdi:layers" width={12} className="inline" />
+ 3D: Mockup
+ </Button>
+ </TooltipAction>
+ )}
+
+ <TooltipAction label="Restablecer valores predeterminados">
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs"
+ onClick={() => {
+ const defaultCustom: Preview3DConfig = { id: "custom", label: "Custom", rotateX: 0, rotateY: 0, rotateZ: 0, translateY: 0, scale: 0.9, perspective: 600 };
+ setCustomConfig(defaultCustom);
+ onReset?.();
+ }}
+ >
+ <Icon
+ icon="material-symbols:refresh-rounded"
+ width={12}
+ />
+ Resetear
+ </Button>
+ </TooltipAction>
+
+ </div>
+
+ <div className="flex flex-wrap items-center justify-end gap-2">
+
+ {onOpenCropper && (
+ <TooltipAction label={t("cropper.tooltip")}>
+ <Button
+ variant="outline"
+ size="sm"
+ className="gap-1.5 px-3 py-1.5 text-xs bg-transparent border-white/10 hover:bg-white/5"
+ onClick={onOpenCropper}
+ aria-label={t("cropper.tooltip")}
+ >
+ <Icon icon="mdi:crop" width={14} />
+ {t("cropper.button")}
+ </Button>
+ </TooltipAction>
+ )}
+
+ {onAspectRatioChange && (
+ <AspectRatioSelect
+ value={aspectRatio}
+ onChange={onAspectRatioChange}
+ customDimensions={customAspectRatio}
+ onCustomDimensionsChange={onCustomAspectRatioChange}
+ />
+ )}
+ </div>
+ </div>
+
+ <div className="flex w-full gap-3 px-5 py-4 overflow-x-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:'none'] [scrollbar-width:'none']">
+ {allPreviews.map(renderPreviewCard)}
+ </div>
+
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/PlayerControls.tsx b/app/components/ui/editor/PlayerControls.tsx
index cd3bc0d..7f63516 100644
--- a/app/components/ui/editor/PlayerControls.tsx
+++ b/app/components/ui/editor/PlayerControls.tsx
@@ -2,16 +2,13 @@
import { useCallback, useMemo, useEffect } from "react";
import { Icon } from "@iconify/react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { AspectRatioSelect } from "../AspectRatioSelect";
import { formatTime } from "@/lib/video.utils";
-import type { PlayerControlsProps } from "@/types/player-control.types";
+import { MAX_ZOOM, MIN_ZOOM, ZOOM_STEP, type PlayerControlsProps } from "@/types/player-control.types";
import { TooltipAction } from "@/components/ui/tooltip-action";
-const MIN_ZOOM = 1;
-const MAX_ZOOM = 10;
-const ZOOM_STEP = 1;
-
export function PlayerControls({
isPlaying,
currentTime,
@@ -29,6 +26,7 @@ export function PlayerControls({
onOpenCropper,
onZoomChange,
}: PlayerControlsProps) {
+ const t = useTranslations("playerControls");
const zoomPercentage = useMemo(() => {
return ((zoomLevel - MIN_ZOOM) / (MAX_ZOOM - MIN_ZOOM)) * 100;
@@ -73,11 +71,11 @@ export function PlayerControls({
break;
case "ArrowUp":
e.preventDefault();
- onZoomChange(Math.min(MAX_ZOOM, Math.round(zoomLevel) + ZOOM_STEP));
+ handleZoomIn();
break;
case "ArrowDown":
e.preventDefault();
- onZoomChange(Math.max(MIN_ZOOM, Math.round(zoomLevel) - ZOOM_STEP));
+ handleZoomOut();
break;
case "f":
case "F":
@@ -89,20 +87,24 @@ export function PlayerControls({
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
- }, [onTogglePlayPause, onSkipBackward, onSkipForward, onToggleFullscreen, onZoomChange, zoomLevel]);
+ }, [onTogglePlayPause, onSkipBackward, onSkipForward, onToggleFullscreen, handleZoomIn, handleZoomOut]);
+
+ const fullscreenLabel = isFullscreen ? t("fullscreen.exit") : t("fullscreen.enter");
+ const playPauseLabel = isPlaying ? t("transport.pause") : t("transport.play");
return (
<div
className="h-13 shrink-0 border-t border-white/10 flex items-center justify-between px-5 bg-[#0D0D11]"
role="toolbar"
- aria-label="Controles de reproducción"
+ aria-label={t("toolbar")}
>
+ {/* Left Section: Fullscreen & Zoom */}
<div className="flex items-center gap-3 text-xs">
- <TooltipAction label={`${isFullscreen ? "Salir de pantalla completa" : "Pantalla completa"} (F)`}>
+ <TooltipAction label={fullscreenLabel}>
<button
onClick={onToggleFullscreen}
className="text-zinc-500 hover:text-white transition-colors"
- aria-label={isFullscreen ? "Salir de pantalla completa" : "Pantalla completa"}
+ aria-label={fullscreenLabel}
aria-pressed={isFullscreen}
>
<Icon icon={isFullscreen ? "typcn:arrow-minimise" : "typcn:arrow-maximise"} width="17" />
@@ -111,13 +113,13 @@ export function PlayerControls({
<div className="h-4 w-px bg-white/10" />
- <div className="flex items-center gap-2" role="group" aria-label="Zoom del timeline">
- <TooltipAction label="Alejar timeline (↓)">
+ <div className="flex items-center gap-2" role="group" aria-label={t("zoom.group")}>
+ <TooltipAction label={t("zoom.out")}>
<button
onClick={handleZoomOut}
disabled={zoomLevel <= MIN_ZOOM}
className="text-zinc-500 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
- aria-label="Reducir zoom del timeline"
+ aria-label={t("zoom.out")}
>
<Icon icon="mdi:magnify-minus-outline" width="16" />
</button>
@@ -140,86 +142,91 @@ export function PlayerControls({
value={Math.round(zoomLevel)}
onChange={handleSliderChange}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer appearance-none"
- aria-label={`Zoom del timeline: ${Math.round(zoomLevel)}×`}
+ aria-label={t("zoom.label", { level: Math.round(zoomLevel) })}
aria-valuemin={MIN_ZOOM}
aria-valuemax={MAX_ZOOM}
aria-valuenow={Math.round(zoomLevel)}
/>
</div>
- <TooltipAction label="Acercar timeline (↑)">
+
+ <TooltipAction label={t("zoom.in")}>
<button
onClick={handleZoomIn}
disabled={zoomLevel >= MAX_ZOOM}
className="text-zinc-500 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
- aria-label="Aumentar zoom del timeline"
+ aria-label={t("zoom.in")}
>
<Icon icon="mdi:magnify-plus-outline" width="16" />
</button>
</TooltipAction>
+
<span className="text-[10px] font-mono text-zinc-500 min-w-5" aria-live="polite" aria-atomic="true">
{Math.round(zoomLevel)}×
</span>
</div>
</div>
- <div className="flex items-center gap-4" role="group" aria-label="Controles de transporte">
+ {/* Middle Section: Transport Controls */}
+ <div className="flex items-center gap-4" role="group" aria-label={t("transport.group")}>
<span
className="text-[11px] font-mono text-zinc-500"
- aria-label={`Tiempo actual: ${formatTime(currentTime)}`}
+ aria-label={t("transport.currentTime", { time: formatTime(currentTime) })}
>
{formatTime(currentTime)}
</span>
<div className="flex items-center gap-2.5">
- <TooltipAction label="Retroceder 5s (← o J)">
+ <TooltipAction label={t("transport.backward")}>
<button
className="text-zinc-500 hover:text-white transition-colors"
onClick={onSkipBackward}
- aria-label="Retroceder 5 segundos"
+ aria-label={t("transport.backward")}
>
<Icon icon="mdi:rewind-5" width="20" />
</button>
</TooltipAction>
- <TooltipAction label={`${isPlaying ? "Pausar" : "Reproducir"} (Espacio o K)`}>
+
+ <TooltipAction label={playPauseLabel}>
<button
onClick={onTogglePlayPause}
className="w-9 h-9 flex items-center justify-center rounded-full bg-white/10 hover:bg-white/10 text-white transition border border-white/10"
- aria-label={isPlaying ? "Pausar" : "Reproducir"}
+ aria-label={playPauseLabel}
aria-pressed={isPlaying}
>
<Icon icon={isPlaying ? "mdi:pause" : "mdi:play"} width="20" />
</button>
</TooltipAction>
- <TooltipAction label="Avanzar 5s (→ o L)">
+
+ <TooltipAction label={t("transport.forward")}>
<button
className="text-zinc-500 hover:text-white transition-colors"
onClick={onSkipForward}
- aria-label="Avanzar 5 segundos"
+ aria-label={t("transport.forward")}
>
<Icon icon="mdi:fast-forward-5" width="20" />
</button>
</TooltipAction>
-
</div>
<span
className="text-[11px] font-mono text-zinc-500"
- aria-label={`Duración total: ${formatTime(videoDuration)}`}
+ aria-label={t("transport.totalTime", { time: formatTime(videoDuration) })}
>
{formatTime(videoDuration)}
</span>
</div>
<div className="flex items-center gap-2">
- <TooltipAction label="Abrir recortador de video">
+ <TooltipAction label={t("cropper.tooltip")}>
<Button
variant="outline"
size="sm"
className="gap-1.5 px-3 py-1.5 text-xs"
onClick={onOpenCropper}
- aria-label="Abrir recortador de video"
+ aria-label={t("cropper.tooltip")}
>
- <Icon icon="mdi:crop" width="14" /> Recortar
+ <Icon icon="mdi:crop" width="14" />
+ {t("cropper.button")}
</Button>
</TooltipAction>
diff --git a/app/components/ui/editor/Timeline.tsx b/app/components/ui/editor/Timeline.tsx
index 82c03ac..28b0ec0 100644
--- a/app/components/ui/editor/Timeline.tsx
+++ b/app/components/ui/editor/Timeline.tsx
@@ -10,8 +10,8 @@ import { ZoomFragmentTrackItem, findValidFragmentPosition } from "./ZoomFragment
import { AudioFragmentTrackItem } from "./AudioFragmentTrackItem";
import { VideoClipTrackItem } from "./VideoClipTrackItem";
import { Icon } from "@iconify/react";
+import { useTranslations } from "next-intl";
-// Default duration for new zoom fragments (in seconds)
const DEFAULT_ZOOM_FRAGMENT_DURATION = 2;
export function Timeline({
@@ -45,6 +45,8 @@ export function Timeline({
onSelectAudioTrack,
onUpdateAudioTrack,
}: TimelineProps) {
+ const t = useTranslations("timeline");
+
const trackRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [trackWidth, setTrackWidth] = useState(0);
@@ -346,7 +348,7 @@ export function Timeline({
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
- <div className={`w-2.5 h-2.5 bg-blue-400 rotate-45 rounded-[2px] mt-[3px] shrink-0 shadow-[0_0_8px_rgba(96,165,250,0.6)] transition-colors ${isDragging ? 'bg-blue-300 scale-110' : 'group-hover:bg-blue-300'}`} />
+ <div className={`w-2.5 h-2.5 bg-blue-400 rotate-45 rounded-[2px] mt-0.75 shrink-0 shadow-[0_0_8px_rgba(96,165,250,0.6)] transition-colors ${isDragging ? 'bg-blue-300 scale-110' : 'group-hover:bg-blue-300'}`} />
<div className={`w-px flex-1 transition-colors ${isDragging ? 'bg-blue-300 w-0.5' : 'bg-blue-400 group-hover:bg-blue-300'}`} />
</motion.div>
@@ -553,7 +555,6 @@ export function Timeline({
/>
))}
- {/* Ghost fragment — follows cursor on hover (shows nearest valid position) */}
{isHoveringZoomRow && !isDraggingZoomFragment && !isOverFragment && (() => {
const hoverTime = (ghostX / contentWidth) * validDuration;
const validPosition = findValidFragmentPosition(
@@ -564,14 +565,13 @@ export function Timeline({
);
if (!validPosition) {
- // No space available at all
return (
<div
className="absolute top-[10%] h-[80%] w-32 pointer-events-none"
style={{ left: ghostX - 64 }}
>
<div className="w-full h-full rounded border border-dashed border-red-400/50 bg-red-500/10 flex flex-col items-center justify-center gap-0.5">
- <span className="text-[8px] font-mono text-red-400/60">No espacio</span>
+ <span className="text-[8px] font-mono text-red-400/60"> {t("noSpace")}</span>
</div>
</div>
);
diff --git a/app/components/ui/editor/ToolsSidebar.tsx b/app/components/ui/editor/ToolsSidebar.tsx
index 6bab282..3bbb773 100644
--- a/app/components/ui/editor/ToolsSidebar.tsx
+++ b/app/components/ui/editor/ToolsSidebar.tsx
@@ -3,7 +3,8 @@
import { Icon } from "@iconify/react";
import { SidebarTool } from "../SidebarTool";
import type { ToolsSidebarProps } from "@/types/tool-sidebar.types";
-import { useRef, useState, useEffect } from "react";
+import type { EditorMode } from "@/types/editor-mode.types";
+import { useRef, useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import { TooltipAction } from "@/components/ui/tooltip-action";
import { useRecording } from "@/hooks/RecordingContext";
@@ -18,6 +19,11 @@ interface ExtendedToolsSidebarProps extends ToolsSidebarProps {
selectedVideoClipId?: string | null;
selectedElementId?: string | null;
newVideosCount?: number;
+ editorMode?: EditorMode;
+ // Photo mode props
+ onImageUpload?: (file: File) => void;
+ onScreenCapture?: () => void;
+ isCapturing?: boolean;
}
export function ToolsSidebar({
@@ -31,19 +37,29 @@ export function ToolsSidebar({
selectedVideoClipId,
selectedElementId,
newVideosCount = 0,
+ editorMode = "video",
+ // Photo mode props
+ onImageUpload,
+ onScreenCapture,
+ isCapturing = false,
}: ExtendedToolsSidebarProps) {
const t = useTranslations("toolsSidebar");
const fileInputRef = useRef<HTMLInputElement>(null);
+ const imageInputRef = useRef<HTMLInputElement>(null);
const zoomToolRef = useRef<HTMLButtonElement>(null);
const audioToolRef = useRef<HTMLButtonElement>(null);
const videosToolRef = useRef<HTMLButtonElement>(null);
const cameraToolRef = useRef<HTMLButtonElement>(null);
const elementsToolRef = useRef<HTMLButtonElement>(null);
const [isDragging, setIsDragging] = useState(false);
+ const [isImageDragging, setIsImageDragging] = useState(false);
const { startCountdown, isIdle, isRecording, isCountdown, isProcessing } = useRecording();
const [showMobileAlert, setShowMobileAlert] = useState(false);
const [setupDialogOpen, setSetupDialogOpen] = useState(false);
+ // Determine if we're in photo mode to hide video-specific tools
+ const isPhotoMode = editorMode === "photo";
+
useEffect(() => {
if (newVideosCount > 0 && videosToolRef.current && activeTool !== "videos") {
videosToolRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
@@ -92,6 +108,41 @@ export function ToolsSidebar({
fileInputRef.current?.click();
};
+ // Photo mode handlers
+ const handleImageFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (file && onImageUpload) {
+ onImageUpload(file);
+ e.target.value = '';
+ }
+ }, [onImageUpload]);
+
+ const handleImageUploadClick = useCallback(() => {
+ imageInputRef.current?.click();
+ }, []);
+
+ const handleImageDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (!isImageDragging) setIsImageDragging(true);
+ }, [isImageDragging]);
+
+ const handleImageDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsImageDragging(false);
+ }, []);
+
+ const handleImageDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsImageDragging(false);
+ const file = e.dataTransfer.files?.[0];
+ if (file && file.type.startsWith("image/") && onImageUpload) {
+ onImageUpload(file);
+ }
+ }, [onImageUpload]);
+
const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
@@ -178,19 +229,22 @@ export function ToolsSidebar({
}}
/>
- <SidebarTool
- icon="solar:video-library-outline"
- label={t("tools.videos")}
- isActive={activeTool === "videos"}
- onClick={() => onToolChange("videos")}
- ref={videosToolRef}
- badgeCount={activeTool !== "videos" ? newVideosCount : undefined}
- popover={{
- title: t("popovers.videos.title"),
- description: t("popovers.videos.description"),
- videoSrc: "/videos/preview-videos.mp4"
- }}
- />
+ {/* Video-specific tools - hidden in photo mode */}
+ {!isPhotoMode && (
+ <SidebarTool
+ icon="solar:video-library-outline"
+ label={t("tools.videos")}
+ isActive={activeTool === "videos"}
+ onClick={() => onToolChange("videos")}
+ ref={videosToolRef}
+ badgeCount={activeTool !== "videos" ? newVideosCount : undefined}
+ popover={{
+ title: t("popovers.videos.title"),
+ description: t("popovers.videos.description"),
+ videoSrc: "/videos/preview-videos.mp4"
+ }}
+ />
+ )}
<SidebarTool
label={t("tools.elements")}
@@ -209,122 +263,202 @@ export function ToolsSidebar({
</svg>
}
/>
+ {isPhotoMode && (
+
+ <SidebarTool
+ icon="material-symbols:history"
+ label={t("photo.library")}
+ isActive={activeTool === "history"}
+ onClick={() => onToolChange("history")}
+ popover={{
+ title: t("popovers.history.title"),
+ description: t("popovers.history.description"),
+ videoSrc: "/videos/preview-history.mp4"
+ }}
+ />
+ )}
- <SidebarTool
- icon="mdi:volume-high"
- label={t("tools.audio")}
- isActive={activeTool === "audio"}
- onClick={() => onToolChange("audio")}
- ref={audioToolRef}
- popover={{
- title: t("popovers.audio.title"),
- description: t("popovers.audio.description"),
- videoSrc: "/videos/preview-audio.mp4"
- }}
- />
-
- <SidebarTool
- icon="iconamoon:zoom-in-bold"
- label={t("tools.zoom")}
- isActive={activeTool === "zoom"}
- onClick={() => onToolChange("zoom")}
- ref={zoomToolRef}
- popover={{
- title: t("popovers.zoom.title"),
- description: t("popovers.zoom.description"),
- videoSrc: "/videos/preview-zoom.mp4"
- }}
- />
-
- <SidebarTool
- icon="solar:videocamera-record-bold-duotone"
- label={t("tools.camera")}
- isActive={activeTool === "camera"}
- onClick={() => onToolChange("camera")}
- ref={cameraToolRef}
- popover={{
- title: t("popovers.camera.title"),
- description: t("popovers.camera.description"),
- videoSrc: "/videos/preview-camera.mp4"
- }}
- />
-
- <SidebarTool
- icon="solar:cursor-bold-duotone"
- label={t("tools.cursor")}
- isActive={activeTool === "cursor"}
- onClick={() => onToolChange("cursor")}
- badge={!isCursorEnabled ? t("tools.soon") : undefined}
- disabled={!isCursorEnabled}
- />
+ {!isPhotoMode && (
+ <>
+ <SidebarTool
+ icon="mdi:volume-high"
+ label={t("tools.audio")}
+ isActive={activeTool === "audio"}
+ onClick={() => onToolChange("audio")}
+ ref={audioToolRef}
+ popover={{
+ title: t("popovers.audio.title"),
+ description: t("popovers.audio.description"),
+ videoSrc: "/videos/preview-audio.mp4"
+ }}
+ />
+
+ <SidebarTool
+ icon="iconamoon:zoom-in-bold"
+ label={t("tools.zoom")}
+ isActive={activeTool === "zoom"}
+ onClick={() => onToolChange("zoom")}
+ ref={zoomToolRef}
+ popover={{
+ title: t("popovers.zoom.title"),
+ description: t("popovers.zoom.description"),
+ videoSrc: "/videos/preview-zoom.mp4"
+ }}
+ />
+
+ <SidebarTool
+ icon="solar:videocamera-record-bold-duotone"
+ label={t("tools.camera")}
+ isActive={activeTool === "camera"}
+ onClick={() => onToolChange("camera")}
+ ref={cameraToolRef}
+ popover={{
+ title: t("popovers.camera.title"),
+ description: t("popovers.camera.description"),
+ videoSrc: "/videos/preview-camera.mp4"
+ }}
+ />
+
+ <SidebarTool
+ icon="solar:cursor-bold-duotone"
+ label={t("tools.cursor")}
+ isActive={activeTool === "cursor"}
+ onClick={() => onToolChange("cursor")}
+ badge={!isCursorEnabled ? t("tools.soon") : undefined}
+ disabled={!isCursorEnabled}
+ />
+ </>
+ )}
<div className="shrink-0 h-12" aria-hidden="true" />
</div>
- <div
- className="w-full p-2 relative flex flex-col items-center gap-1 shrink-0"
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- >
- <div className="absolute -top-0.5 left-0 w-full border-t border-white/10" />
-
- {showMobileAlert && (
- <div className="absolute bottom-full mb-2 left-1/2 -translate-x-1/2 w-64 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-300 z-50">
- {t("alerts.mobile")}
- </div>
- )}
-
- <TooltipAction label={isIdle ? t("recording.idle") : t("recording.inProgress")}>
- <button
- onClick={handleStartRecording}
- disabled={!isIdle}
- className={`w-full flex flex-col items-center text-center justify-center gap-1.5 p-2 rounded-xl cursor-pointer transition-all group border-2 border-transparent disabled:cursor-not-allowed ${!isIdle ? "opacity-70" : "hover:bg-red-500/10"}`}
- >
- <Icon icon={recordButtonContent.icon} width="24" height="24" className={`transition-colors ${recordButtonContent.className}`} />
- <span className={`text-xs font-medium transition-colors ${!isIdle ? recordButtonContent.className : "text-white/60 group-hover:text-red-400"}`}>
- {recordButtonContent.text}
- </span>
- </button>
- </TooltipAction>
-
- <TooltipAction label={isUploading ? t("upload.tooltipUploading") : t("upload.tooltip")}>
- <button
- onClick={handleUploadClick}
- disabled={isUploading}
- className={`w-full flex flex-col items-center text-center justify-center gap-1.5 p-2 rounded-xl cursor-pointer transition-all group disabled:opacity-50 disabled:cursor-not-allowed border-2 ${isDragging ? "bg-blue-500/20 text-blue-400 border-dashed border-blue-400/50 scale-105" : "border-transparent text-white/60 hover:bg-blue-500/20 hover:text-blue-400"}
- `}
- >
- {isUploading ? (
- <>
- <Icon icon="svg-spinners:ring-resize" className="transition-transform duration-300" width="24" height="24" />
- <span className="text-xs font-medium">{t("upload.buttonUploading")}</span>
- </>
- ) : (
- <>
- <Icon icon="mage:video-upload" className={`transition-transform duration-300 ${!isDragging && "group-hover:scale-105"}`} width="24" height="24" />
- <span className="text-xs font-medium">
- {isDragging ? t("upload.dropHere") : t("upload.button")}
- </span>
- </>
- )}
- </button>
- </TooltipAction>
-
- <input
- ref={fileInputRef}
- type="file"
- accept="video/mp4,video/webm,video/quicktime,video/x-matroska"
- className="hidden"
- onChange={handleFileChange}
- />
- </div>
+ {!isPhotoMode && (
+ <div
+ className="w-full p-2 relative flex flex-col items-center gap-1 shrink-0"
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ >
+ <div className="absolute -top-0.5 left-0 w-full border-t border-white/10" />
+
+ {showMobileAlert && (
+ <div className="absolute bottom-full mb-2 left-1/2 -translate-x-1/2 w-64 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-300 z-50">
+ {t("alerts.mobile")}
+ </div>
+ )}
+
+ <TooltipAction label={isIdle ? t("recording.idle") : t("recording.inProgress")}>
+ <button
+ onClick={handleStartRecording}
+ disabled={!isIdle}
+ className={`w-full flex flex-col items-center text-center justify-center gap-1.5 p-2 rounded-xl cursor-pointer transition-all group border-2 border-transparent disabled:cursor-not-allowed ${!isIdle ? "opacity-70" : "hover:bg-red-500/10"}`}
+ >
+ <Icon icon={recordButtonContent.icon} width="24" height="24" className={`transition-colors ${recordButtonContent.className}`} />
+ <span className={`text-xs font-medium transition-colors ${!isIdle ? recordButtonContent.className : "text-white/60 group-hover:text-red-400"}`}>
+ {recordButtonContent.text}
+ </span>
+ </button>
+ </TooltipAction>
+
+ <TooltipAction label={isUploading ? t("upload.tooltipUploading") : t("upload.tooltip")}>
+ <button
+ onClick={handleUploadClick}
+ disabled={isUploading}
+ className={`w-full flex flex-col items-center text-center justify-center gap-1.5 p-2 rounded-xl cursor-pointer transition-all group disabled:opacity-50 disabled:cursor-not-allowed border-2 ${isDragging ? "bg-blue-500/20 text-blue-400 border-dashed border-blue-400/50 scale-105" : "border-transparent text-white/60 hover:bg-blue-500/20 hover:text-blue-400"}`}
+ >
+ {isUploading ? (
+ <>
+ <Icon icon="svg-spinners:ring-resize" className="transition-transform duration-300" width="24" height="24" />
+ <span className="text-xs font-medium">{t("upload.buttonUploading")}</span>
+ </>
+ ) : (
+ <>
+ <Icon icon="mage:video-upload" className={`transition-transform duration-300 ${!isDragging && "group-hover:scale-105"}`} width="24" height="24" />
+ <span className="text-xs font-medium">
+ {isDragging ? t("upload.dropHere") : t("upload.button")}
+ </span>
+ </>
+ )}
+ </button>
+ </TooltipAction>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="video/mp4,video/webm,video/quicktime,video/x-matroska"
+ className="hidden"
+ onChange={handleFileChange}
+ />
+ </div>
+ )}
+
+ {isPhotoMode && (
+ <div
+ className="w-full p-2 relative flex flex-col items-center gap-1 shrink-0"
+ onDragOver={handleImageDragOver}
+ onDragLeave={handleImageDragLeave}
+ onDrop={handleImageDrop}
+ >
+ <div className="absolute -top-0.5 left-0 w-full border-t border-white/10" />
+
+ <TooltipAction label={t("photo.captureTooltip")}>
+ <button
+ onClick={onScreenCapture}
+ disabled={isCapturing}
+ className={`w-full flex flex-col items-center text-center justify-center gap-1.5 p-2 rounded-xl cursor-pointer transition-all group border-2 border-transparent disabled:cursor-not-allowed ${isCapturing ? "opacity-70" : "hover:bg-cyan-500/10"}`}
+ >
+ <Icon
+ icon={isCapturing ? "svg-spinners:ring-resize" : "fluent:screenshot-20-regular"}
+ width="24"
+ height="24"
+ className={`transition-colors ${isCapturing ? "text-cyan-400" : "text-white/60 group-hover:text-cyan-400"}`}
+ />
+ <span className={`text-xs font-medium transition-colors ${isCapturing ? "text-cyan-400" : "text-white/60 group-hover:text-cyan-400"}`}>
+ {isCapturing ? t("photo.capturing") : t("photo.capture")}
+ </span>
+ </button>
+ </TooltipAction>
+
+ <TooltipAction label={t("photo.uploadTooltip")}>
+ <button
+ onClick={handleImageUploadClick}
+ disabled={isUploading}
+ className={`w-full flex flex-col items-center text-center justify-center gap-1.5 p-2 rounded-xl cursor-pointer transition-all group disabled:opacity-50 disabled:cursor-not-allowed border-2 ${isImageDragging ? "bg-blue-500/20 text-blue-400 border-dashed border-blue-400/50 scale-105" : "border-transparent text-white/60 hover:bg-blue-500/20 hover:text-blue-400"}`}
+ >
+ {isUploading ? (
+ <>
+ <Icon icon="svg-spinners:ring-resize" className="transition-transform duration-300" width="24" height="24" />
+ <span className="text-xs font-medium">{t("photo.uploading")}</span>
+ </>
+ ) : (
+ <>
+ <Icon icon="mage:image-upload" className={`transition-transform duration-300 ${!isImageDragging && "group-hover:scale-105"}`} width="24" height="24" />
+ <span className="text-xs font-medium">
+ {isImageDragging ? t("photo.dropHere") : t("photo.upload")}
+ </span>
+ </>
+ )}
+ </button>
+ </TooltipAction>
+
+ <input
+ ref={imageInputRef}
+ type="file"
+ accept="image/png,image/jpeg,image/webp,image/gif"
+ className="hidden"
+ onChange={handleImageFileChange}
+ />
+ </div>
+ )}
</aside>
- <RecordingSetupDialog
- open={setupDialogOpen}
- onClose={() => setSetupDialogOpen(false)}
- onStart={(config) => startCountdown(config)}
- />
+ {!isPhotoMode && (
+ <RecordingSetupDialog
+ open={setupDialogOpen}
+ onClose={() => setSetupDialogOpen(false)}
+ onStart={(config) => startCountdown(config)}
+ />
+ )}
</div>
);
}
\ No newline at end of file
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 67620ad..957a5c1 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -16,11 +16,20 @@ import { DEFAULT_MOCKUP_CONFIG } from "@/types/mockup.types";
import { calculateSmoothZoom } from "@/lib/canvas.utils";
import { getSvgDataUrl } from "@/components/canvas-svg";
import { VIDEO_Z_INDEX, BOTTOM_ONLY_RADIUS_MOCKUPS, SELF_SHADOWING_MOCKUPS } from "@/lib/constants";
+import { applyPerspective3D, disposePerspective3D } from "@/lib/perspective3d";
import { RotationHandleIcon } from "@/components/ui/RotationHandleIcon";
import { CanvasElementsLayer } from "./CanvasElementsLayer";
+import { EditorHoverTooltip } from "./EditorHoverTooltip";
+import { Icon } from "@iconify/react";
export type { VideoCanvasHandle, VideoCanvasProps };
export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({
+ mediaType = "video",
+ imageUrl = null,
+ imageRef,
+ imageTransform,
+ apply3DToBackground = false,
+ imageMaskConfig,
videoRef,
videoUrl,
padding,
@@ -46,6 +55,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
mockupId = "none",
mockupConfig,
onVideoUpload,
+ onImageUpload,
+ onImageDrop,
isUploading = false,
videoTransform = { rotation: 0, translateX: 0, translateY: 0 },
onVideoTransformChange,
@@ -60,6 +71,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
}, ref) {
const wallpaperUrl = getWallpaperUrl(selectedWallpaper);
+ const hasMedia = mediaType === "video" ? !!videoUrl : !!imageUrl;
+
// Get current thumbnail for scrubbing preview
const currentThumbnail = useMemo<VideoThumbnail | null>(() => {
if (!isScrubbing || !getThumbnailForTime) return null;
@@ -115,18 +128,18 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
};
}, [activeZoomFragment, zoomFragments, currentTime]);
- // Determinar qué background mostrar basado en el tab activo
const shouldShowUnsplashOverride = backgroundTab === "wallpaper" && unsplashOverrideUrl !== "";
const shouldShowWallpaper = backgroundTab === "wallpaper" && selectedWallpaper >= 0 && !shouldShowUnsplashOverride;
const shouldShowCustomImage = backgroundTab === "image" && selectedImageUrl !== "";
const shouldShowCustomColor = backgroundTab === "color" && !!backgroundColorCss;
- // Canvas para exportación (no visible, solo para renderizado)
const exportCanvasRef = useRef<HTMLCanvasElement>(null);
+ // Foreground canvas — used to render the mockup in isolation so that the
+ // WebGL 3D perspective is applied only to the mockup, not to the background.
+ const foregroundCanvasRef = useRef<HTMLCanvasElement | null>(null);
const wallpaperImageRef = useRef<HTMLImageElement | null>(null);
const customImageRef = useRef<HTMLImageElement | null>(null);
- // Calcular dimensiones de exportación según aspect ratio
const exportDimensions = useMemo(() => {
if ((aspectRatio === "auto" || aspectRatio === "custom") && customAspectRatio) {
return { width: customAspectRatio.width, height: customAspectRatio.height };
@@ -139,6 +152,9 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// On-canvas controls state
const [isVideoHovered, setIsVideoHovered] = useState(false);
+ // Image zoom state (for photo mode)
+ const [imageZoomScale, setImageZoomScale] = useState(1);
+
// Set initial video src when videoUrl changes (initial load only — transitions manage src imperatively)
const lastSetVideoUrlRef = useRef<string | null>(null);
const preservedVideoStateRef = useRef<{ time: number; playing: boolean } | null>(null);
@@ -159,7 +175,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
videoRef.current.src = videoUrl;
lastSetVideoUrlRef.current = videoUrl;
- // Restore preserved state after src is set
if (preservedVideoStateRef.current) {
const { time, playing } = preservedVideoStateRef.current;
videoRef.current.currentTime = time;
@@ -180,7 +195,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// Preserve video state when mockup changes (detect unmount via cleanup)
useEffect(() => {
return () => {
- // On unmount, save video state to restore on remount
if (videoRef.current && videoUrl) {
preservedVideoStateRef.current = {
time: videoRef.current.currentTime,
@@ -189,6 +203,13 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
}
};
}, [mockupId, videoUrl, videoRef]);
+
+ // Dispose Three.js WebGL resources when component unmounts
+ useEffect(() => {
+ return () => {
+ disposePerspective3D();
+ };
+ }, []);
const [isDraggingVideo, setIsDraggingVideo] = useState(false);
const [isDraggingRotation, setIsDraggingRotation] = useState(false);
const [videoHoverCorner, setVideoHoverCorner] = useState<Corner>("top-right");
@@ -214,11 +235,58 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const [isDraggingElement, setIsDraggingElement] = useState(false);
const [isDraggingElementRotation, setIsDraggingElementRotation] = useState(false);
const elementDragStart = useRef({ x: 0, y: 0, initialX: 0, initialY: 0, initialRotation: 0 });
+
+ // Smart guides state for element alignment
+ const [alignmentGuides, setAlignmentGuides] = useState<{
+ vertical: number[];
+ horizontal: number[];
+ }>({ vertical: [], horizontal: [] });
+
+ // Smart guides state for mockup/video alignment
+ const [mockupAlignmentGuides, setMockupAlignmentGuides] = useState<{
+ vertical: number[];
+ horizontal: number[];
+ }>({ vertical: [], horizontal: [] });
+
+ // Drag & drop state for images (photo mode only)
+ const [isDraggingOver, setIsDraggingOver] = useState(false);
const canvasContainerRef = useRef<HTMLDivElement>(null);
- // Canvas element images cache (only for actual images, not SVGs)
+ // Calculate mask styles - will be applied to mockup wrapper when mockup exists, or to image directly
+ const maskStyles = useMemo(() => {
+ if (!imageMaskConfig || !imageMaskConfig.enabled) return {};
+
+ const masks = [];
+ if (imageMaskConfig.top) {
+ masks.push(`linear-gradient(180deg, transparent ${imageMaskConfig.top.from}%, black ${imageMaskConfig.top.to ?? 100}%)`);
+ }
+ if (imageMaskConfig.bottom) {
+ masks.push(`linear-gradient(0deg, transparent ${imageMaskConfig.bottom.from}%, black ${imageMaskConfig.bottom.to ?? 100}%)`);
+ }
+ if (imageMaskConfig.left) {
+ masks.push(`linear-gradient(90deg, transparent ${imageMaskConfig.left.from}%, black ${imageMaskConfig.left.to ?? 100}%)`);
+ }
+ if (imageMaskConfig.right) {
+ masks.push(`linear-gradient(270deg, transparent ${imageMaskConfig.right.from}%, black ${imageMaskConfig.right.to ?? 100}%)`);
+ }
+ if (imageMaskConfig.angle !== undefined) {
+ masks.push(`linear-gradient(${imageMaskConfig.angle}deg, transparent ${imageMaskConfig.angleFrom ?? 0}%, black ${imageMaskConfig.angleTo ?? 100}%)`);
+ }
+
+ if (masks.length === 0) return {};
+
+ return {
+ WebkitMaskImage: masks.join(', '),
+ WebkitMaskComposite: 'source-in',
+ maskImage: masks.join(', '),
+ maskComposite: 'intersect'
+ };
+ }, [imageMaskConfig]);
+
+ const hasMask = Object.keys(maskStyles).length > 0;
+ const hasMockup = mockupId && mockupId !== "none";
+
const elementImagesRef = useRef<Map<string, HTMLImageElement>>(new Map());
- // SVG element image cache keyed by "svgId-color" — avoids new Image() per frame
const svgImageCacheRef = useRef<Map<string, HTMLImageElement>>(new Map());
// Actualizar canvas dimensions cuando cambia el aspect ratio
@@ -322,10 +390,31 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const rect = container.getBoundingClientRect();
const percentX = (deltaX / rect.width) * 100;
const percentY = (deltaY / rect.height) * 100;
+
+ let newTranslateX = dragStartPos.current.initialTranslateX + percentX;
+ let newTranslateY = dragStartPos.current.initialTranslateY + percentY;
+
+ const SNAP_THRESHOLD = 2;
+ const centerX = 0;
+ const centerY = 0;
+ const guides: { vertical: number[]; horizontal: number[] } = { vertical: [], horizontal: [] };
+
+ if (Math.abs(newTranslateX - centerX) < SNAP_THRESHOLD) {
+ newTranslateX = centerX;
+ guides.vertical.push(50);
+ }
+
+ if (Math.abs(newTranslateY - centerY) < SNAP_THRESHOLD) {
+ newTranslateY = centerY;
+ guides.horizontal.push(50);
+ }
+
+ setMockupAlignmentGuides(guides);
+
onVideoTransformChange({
...videoTransform,
- translateX: dragStartPos.current.initialTranslateX + percentX,
- translateY: dragStartPos.current.initialTranslateY + percentY,
+ translateX: newTranslateX,
+ translateY: newTranslateY,
});
}
};
@@ -333,6 +422,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const handleMouseUp = () => {
setIsDraggingVideo(false);
setIsDraggingRotation(false);
+ setMockupAlignmentGuides({ vertical: [], horizontal: [] });
lastAngleRef.current = null;
};
@@ -429,9 +519,33 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const deltaY = e.clientY - elementDragStart.current.y;
const percentX = (deltaX / rect.width) * 100;
const percentY = (deltaY / rect.height) * 100;
+
+ let newX = Math.max(0, Math.min(100, elementDragStart.current.initialX + percentX));
+ let newY = Math.max(0, Math.min(100, elementDragStart.current.initialY + percentY));
+
+ // Smart guides: snap to center (horizontal and vertical)
+ const SNAP_THRESHOLD = 2;
+ const centerX = 50;
+ const centerY = 50;
+ const guides: { vertical: number[]; horizontal: number[] } = { vertical: [], horizontal: [] };
+
+ // Check horizontal center alignment
+ if (Math.abs(newX - centerX) < SNAP_THRESHOLD) {
+ newX = centerX;
+ guides.vertical.push(centerX);
+ }
+
+ // Check vertical center alignment
+ if (Math.abs(newY - centerY) < SNAP_THRESHOLD) {
+ newY = centerY;
+ guides.horizontal.push(centerY);
+ }
+
+ setAlignmentGuides(guides);
+
onElementUpdate(selectedElementId, {
- x: Math.max(0, Math.min(100, elementDragStart.current.initialX + percentX)),
- y: Math.max(0, Math.min(100, elementDragStart.current.initialY + percentY)),
+ x: newX,
+ y: newY,
});
}
};
@@ -439,6 +553,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const handleMouseUp = () => {
setIsDraggingElement(false);
setIsDraggingElementRotation(false);
+ setAlignmentGuides({ vertical: [], horizontal: [] });
};
window.addEventListener("mousemove", handleMouseMove);
@@ -449,9 +564,65 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
};
}, [isDraggingElement, isDraggingElementRotation, selectedElementId, canvasElements, onElementUpdate]);
+ // Image zoom with mouse wheel (photo mode only)
+ useEffect(() => {
+ if (mediaType !== "image" || !imageUrl) return;
+
+ const handleWheel = (e: WheelEvent) => {
+ // Only zoom if Ctrl/Cmd key is held (standard zoom gesture)
+ if (!e.ctrlKey && !e.metaKey) return;
+
+ e.preventDefault();
+
+ const delta = -e.deltaY;
+ const zoomFactor = delta > 0 ? 1.1 : 0.9;
+
+ setImageZoomScale(prev => {
+ const newScale = Math.max(0.5, Math.min(3, prev * zoomFactor));
+ return newScale;
+ });
+ };
+
+ const container = previewContainerRef.current;
+ if (!container) return;
+
+ container.addEventListener("wheel", handleWheel, { passive: false });
+ return () => {
+ container.removeEventListener("wheel", handleWheel);
+ };
+ }, [mediaType, imageUrl]);
+
+ // Drag & drop handlers for images
+ const handleDragOver = (e: React.DragEvent) => {
+ if (mediaType !== "image" || !onImageDrop) return;
+
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDraggingOver(true);
+ };
+
+ const handleDragLeave = (e: React.DragEvent) => {
+ if (mediaType !== "image") return;
+
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDraggingOver(false);
+ };
+
+ const handleDrop = (e: React.DragEvent) => {
+ if (mediaType !== "image" || !onImageDrop) return;
+
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDraggingOver(false);
+
+ const files = e.dataTransfer.files;
+ if (files && files.length > 0) {
+ onImageDrop(files);
+ }
+ };
+
// Helper function to render canvas elements (SVG, images, text)
- // If behindVideo is true, only render elements with zIndex < VIDEO_Z_INDEX
- // If behindVideo is false, only render elements with zIndex >= VIDEO_Z_INDEX
const renderCanvasElements = async (
ctx: CanvasRenderingContext2D,
elements: typeof canvasElements,
@@ -495,7 +666,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const elemX = (svgElement.x / 100) * canvasWidth;
const elemY = (svgElement.y / 100) * canvasHeight;
- // Use reference size for both width and height to maintain square aspect ratio for SVGs
const elemWidth = (svgElement.width / 100) * referenceSize;
const elemHeight = (svgElement.height / 100) * referenceSize;
@@ -531,13 +701,10 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
let finalWidth = elemWidth;
let finalHeight = elemHeight;
- // Apply object-contain logic: scale to fit within element bounds while maintaining aspect ratio
const elementAspectRatio = elemWidth / elemHeight;
if (imgAspectRatio > elementAspectRatio) {
- // Image is wider - fit to width
finalHeight = elemWidth / imgAspectRatio;
} else {
- // Image is taller - fit to height
finalWidth = elemHeight * imgAspectRatio;
}
@@ -564,8 +731,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
ctx.rotate((element.rotation * Math.PI) / 180);
ctx.globalAlpha = element.opacity;
- // Scale font size proportionally to canvas size using reference dimension
- // Base reference is 1080px (typical preview height)
const scaledFontSize = element.fontSize * (referenceSize / 1080);
const fontWeight = element.fontWeight === 'normal' ? '400' : element.fontWeight === 'medium' ? '500' : '700';
ctx.font = `${fontWeight} ${scaledFontSize}px ${element.fontFamily}`;
@@ -583,236 +748,289 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// Función para dibujar un frame en el canvas de exportación
const drawFrame = async () => {
const canvas = exportCanvasRef.current;
- const ctx = canvas?.getContext('2d', {
- alpha: true,
- desynchronized: false,
- willReadFrequently: false
- });
+ const canvasCtxOptions: CanvasRenderingContext2DSettings = { alpha: true, colorSpace: 'srgb', desynchronized: false, willReadFrequently: false };
+ const ctx = canvas?.getContext('2d', canvasCtxOptions);
const video = videoRef.current;
+ const image = imageRef?.current;
+ const mediaSource = mediaType === "image" ? image : video;
+
+ if (!canvas || !ctx || !mediaSource) return;
- if (!canvas || !ctx || !video) return;
+ const sourceWidth = mediaType === "image" ? (image?.naturalWidth ?? 0) : (video?.videoWidth ?? 0);
+ const sourceHeight = mediaType === "image" ? (image?.naturalHeight ?? 0) : (video?.videoHeight ?? 0);
+ if (sourceWidth === 0 || sourceHeight === 0) return;
- // Enable high-quality rendering
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
-
- // Calcular propiedades escaladas
const paddingPercent = padding * 0.5 / 100;
+
const scaledPaddingX = calculateScaledPadding(canvasWidth, paddingPercent);
const scaledPaddingY = calculateScaledPadding(canvasHeight, paddingPercent);
const scaledRadius = roundedCorners * (canvasWidth / 896);
const scaledShadowBlur = shadows * (canvasWidth / 896) * 0.8;
- // Reset canvas transformation matrix and clear
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
- const frameTime = video.currentTime;
+ const frameTime = mediaType === "video" && video ? video.currentTime : 0;
const zoomState = calculateSmoothZoom(frameTime, zoomFragments);
-
- ctx.save();
-
- // Apply zoom transform to entire canvas (affects everything including background)
const zoomCenterX = canvasWidth / 2;
const zoomCenterY = canvasHeight / 2;
+ const backgroundImage = (shouldShowCustomImage || shouldShowUnsplashOverride) ? customImageRef.current : (shouldShowWallpaper ? wallpaperImageRef.current : null);
- if (zoomState.scale !== 1 || zoomState.rotateX !== 0 || zoomState.rotateY !== 0) {
-
- // Punto de enfoque en píxeles
- const focusPxX = (zoomState.focusX / 100) * canvasWidth;
- const focusPxY = (zoomState.focusY / 100) * canvasHeight;
-
- // 1. Trasladar al punto de enfoque (centro de toda la transformación)
- ctx.translate(focusPxX, focusPxY);
-
- // 2. Aplicar 3D centrado en el punto de enfoque
- if (zoomState.perspective > 0 && (zoomState.rotateX !== 0 || zoomState.rotateY !== 0)) {
- const rotateXRad = (zoomState.rotateX * Math.PI) / 180;
- const rotateYRad = (zoomState.rotateY * Math.PI) / 180;
+ // Shared helper: draw background into any 2D context
+ const drawBg = (c: CanvasRenderingContext2D) => {
+ if (shouldShowCustomColor && backgroundColorCss) {
+ applyCanvasBackground(c, backgroundColorCss, canvasWidth, canvasHeight);
+ } else if (backgroundImage) {
+ c.save();
+ if (backgroundBlur > 0) {
+ c.filter = `blur(${backgroundBlur * 0.8}px)`;
+ const overflow = backgroundBlur * 2;
+ c.drawImage(backgroundImage, -overflow, -overflow, canvasWidth + overflow * 2, canvasHeight + overflow * 2);
+ } else {
+ c.drawImage(backgroundImage, 0, 0, canvasWidth, canvasHeight);
+ }
+ c.restore();
+ }
+ };
- const tanY = Math.tan(rotateYRad);
- const tanX = Math.tan(rotateXRad);
- const scaleX = 1 / Math.sqrt(1 + tanY * tanY);
- const scaleY = 1 / Math.sqrt(1 + tanX * tanX);
- const skewX = tanY * scaleX;
- const skewY = tanX * scaleY;
+ // Shared helper: compute container dimensions
+ const computeContainer = () => {
+ const availableWidth = canvasWidth - scaledPaddingX * 2;
+ const availableHeight = canvasHeight - scaledPaddingY * 2;
+ let mSrcW = sourceWidth;
+ let mSrcH = sourceHeight;
- ctx.transform(scaleX, skewY, skewX, scaleY, 0, 0);
+ if (cropArea && (cropArea.width < 100 || cropArea.height < 100)) {
+ mSrcW = (cropArea.width / 100) * sourceWidth;
+ mSrcH = (cropArea.height / 100) * sourceHeight;
+ }
+ const mAR = mSrcW / mSrcH;
+ const aAR = availableWidth / availableHeight;
+ let cW: number, cH: number;
+ if (mAR > aAR) {
+ cW = availableWidth;
+ cH = availableWidth / mAR;
+ } else {
+ cH = availableHeight;
+ cW = availableHeight * mAR;
}
+ const cX = scaledPaddingX + (availableWidth - cW) / 2;
+ const cY = scaledPaddingY + (availableHeight - cH) / 2;
+ return { containerX: cX, containerY: cY, containerWidth: cW, containerHeight: cH };
+ };
- // 3. Aplicar zoom: escalar desde el punto de enfoque
- // El offset mueve el contenido para que focusX/Y quede centrado en pantalla
- const offsetX = (zoomCenterX - focusPxX) * (zoomState.scale - 1);
- const offsetY = (zoomCenterY - focusPxY) * (zoomState.scale - 1);
- ctx.scale(zoomState.scale, zoomState.scale);
+ // Shared helper: draw shadow + mockup + video into a 2D context
+ const DEG_TO_RAD = Math.PI / 180;
+ const drawMockupAndMedia = (
+ c: CanvasRenderingContext2D,
+ containerX: number, containerY: number, containerWidth: number, containerHeight: number,
+ source: HTMLVideoElement | HTMLImageElement, applyImageXform: boolean
+ ) => {
+ const vCX = containerX + containerWidth / 2;
+ const vCY = containerY + containerHeight / 2;
+ const txPx = (videoTransform.translateX / 100) * containerWidth;
+ const tyPx = (videoTransform.translateY / 100) * containerHeight;
+
+ c.save();
+ c.translate(vCX + txPx, vCY + tyPx);
+ c.rotate(videoTransform.rotation * DEG_TO_RAD);
+
+ if (applyImageXform && imageTransform && !apply3DToBackground) {
+ if (imageTransform.perspective && imageTransform.perspective > 0 && (imageTransform.rotateX !== 0 || imageTransform.rotateY !== 0)) {
+ const rotXR = imageTransform.rotateX * DEG_TO_RAD;
+ const rotYR = imageTransform.rotateY * DEG_TO_RAD;
+ const tanY2 = Math.tan(rotYR);
+ const tanX2 = Math.tan(rotXR);
+ const sX2 = 1 / Math.sqrt(1 + tanY2 * tanY2);
+ const sY2 = 1 / Math.sqrt(1 + tanX2 * tanX2);
+ c.transform(sX2, tanX2 * sY2, tanY2 * sX2, sY2, 0, 0);
+ }
+ c.rotate(imageTransform.rotateZ * DEG_TO_RAD);
+ c.scale(imageTransform.scale * imageZoomScale, imageTransform.scale * imageZoomScale);
+ const iTY = (imageTransform.translateY / 100) * containerHeight;
+ c.translate(0, iTY / (imageTransform.scale * imageZoomScale));
+ }
+ c.translate(-vCX, -vCY);
+
+ // Shadow
+ if (shadows > 0 && !SELF_SHADOWING_MOCKUPS.includes(mockupId)) {
+ c.save();
+ c.shadowColor = 'rgba(0, 0, 0, 0.5)';
+ c.shadowBlur = scaledShadowBlur;
+ c.shadowOffsetY = scaledShadowBlur * 0.3;
+ c.fillStyle = 'black';
+ drawRoundedRect(c, containerX, containerY, containerWidth, containerHeight, scaledRadius);
+ c.fill();
+ c.restore();
+ }
- // 4. Volver al sistema de coordenadas del canvas, ajustando por zoom y offset de enfoque
- ctx.translate(
- -focusPxX + offsetX / zoomState.scale,
- -focusPxY + offsetY / zoomState.scale
- );
- }
+ // Mockup frame
+ const hasMockupLocal = mockupId && mockupId !== "none";
+ const mockupCfg = mockupConfig || DEFAULT_MOCKUP_CONFIG;
+ let vX = containerX, vY = containerY, vW = containerWidth, vH = containerHeight, vR = scaledRadius;
+
+ if (hasMockupLocal) {
+ const mBlur = SELF_SHADOWING_MOCKUPS.includes(mockupId) ? scaledShadowBlur : 0;
+ const mr = drawMockupToCanvas(c, mockupId, mockupCfg, containerX, containerY, containerWidth, containerHeight, scaledRadius, mBlur, canvasWidth);
+ vX = mr.contentX;
+ vY = mr.contentY;
+ vW = mr.contentWidth;
+ vH = mr.contentHeight;
+ vR = (mockupId === "iphone-slim" || mockupId === "glass-curve" || mockupId === "glass-full") ? scaledRadius * 6 : scaledRadius;
+ }
- const backgroundImage = (shouldShowCustomImage || shouldShowUnsplashOverride) ? customImageRef.current : (shouldShowWallpaper ? wallpaperImageRef.current : null);
+ c.save();
+ const bottomOnly = hasMockupLocal && BOTTOM_ONLY_RADIUS_MOCKUPS.includes(mockupId);
+ if (vR > 0) {
+ if (bottomOnly) {
+ drawRoundedRectBottomOnly(c, vX, vY, vW, vH, vR);
+ } else {
+ drawRoundedRect(c, vX, vY, vW, vH, vR);
+ }
+ c.clip();
+ } else {
+ c.beginPath();
+ c.rect(vX, vY, vW, vH);
+ c.clip();
+ }
- // 1. Dibujar fondo
- if (shouldShowCustomColor && backgroundColorCss) {
- applyCanvasBackground(ctx, backgroundColorCss, canvasWidth, canvasHeight);
- } else if (backgroundImage) {
- ctx.save();
+ if (mediaType === "video") {
+ c.filter = 'saturate(130%) contrast(104%) brightness(103%)';
+ }
- if (backgroundBlur > 0) {
- ctx.filter = `blur(${backgroundBlur * 0.8}px)`;
- const overflow = backgroundBlur * 2;
- ctx.drawImage(
- backgroundImage,
- -overflow,
- -overflow,
- canvasWidth + overflow * 2,
- canvasHeight + overflow * 2
- );
+ if (cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0)) {
+ const sX = (cropArea.x / 100) * sourceWidth;
+ const sY = (cropArea.y / 100) * sourceHeight;
+ const cW2 = (cropArea.width / 100) * sourceWidth;
+ const cH2 = (cropArea.height / 100) * sourceHeight;
+ c.drawImage(source, sX, sY, cW2, cH2, vX, vY, vW, vH);
} else {
- ctx.drawImage(backgroundImage, 0, 0, canvasWidth, canvasHeight);
+ c.drawImage(source, vX, vY, vW, vH);
}
+ c.restore();
+ c.restore();
+ };
+ if (mediaType === "image") {
+ ctx.save();
+ if (imageTransform && apply3DToBackground) {
+ ctx.translate(zoomCenterX, zoomCenterY);
+ if (imageTransform.perspective && imageTransform.perspective > 0 &&
+ (imageTransform.rotateX !== 0 || imageTransform.rotateY !== 0)) {
+ const rXR = (imageTransform.rotateX * Math.PI) / 180;
+ const rYR = (imageTransform.rotateY * Math.PI) / 180;
+ const tY2 = Math.tan(rYR);
+ const tX2 = Math.tan(rXR);
+ const sX2 = 1 / Math.sqrt(1 + tY2 * tY2);
+ const sY2 = 1 / Math.sqrt(1 + tX2 * tX2);
+ ctx.transform(sX2, tX2 * sY2, tY2 * sX2, sY2, 0, 0);
+ }
+ ctx.rotate((imageTransform.rotateZ * Math.PI) / 180);
+ ctx.scale(imageTransform.scale * imageZoomScale, imageTransform.scale * imageZoomScale);
+ const iTY = (imageTransform.translateY / 100) * canvasHeight;
+ ctx.translate(-zoomCenterX, -zoomCenterY + iTY);
+ }
+ drawBg(ctx);
+ await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, true);
+ const { containerX: cX, containerY: cY, containerWidth: cW, containerHeight: cH } = computeContainer();
+ drawMockupAndMedia(ctx, cX, cY, cW, cH, image!, true);
+ await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, false);
ctx.restore();
+ return;
}
- // 2. Render elements BEHIND video (zIndex < VIDEO_Z_INDEX) - before video transform
- await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, true);
+ const has3DEffect = zoomState.perspective > 0 && (zoomState.rotateX !== 0 || zoomState.rotateY !== 0);
+ const hasZoom = zoomState.scale !== 1;
- // 3. Calcular área disponible para el mockup/video
- const availableWidth = canvasWidth - scaledPaddingX * 2;
- const availableHeight = canvasHeight - scaledPaddingY * 2;
+ let focusPxX = 0, focusPxY = 0, fOffX = 0, fOffY = 0;
+ if (hasZoom) {
+ focusPxX = (zoomState.focusX / 100) * canvasWidth;
+ focusPxY = (zoomState.focusY / 100) * canvasHeight;
+ fOffX = (zoomCenterX - focusPxX) * (zoomState.scale - 1);
+ fOffY = (zoomCenterY - focusPxY) * (zoomState.scale - 1);
+ }
- // Obtener las dimensiones reales del video (considerando crop si existe)
- let videoSourceWidth = video.videoWidth;
- let videoSourceHeight = video.videoHeight;
+ const applyVideoZoom = (c: CanvasRenderingContext2D) => {
+ if (hasZoom) {
+ c.translate(focusPxX, focusPxY);
+ c.scale(zoomState.scale, zoomState.scale);
+ c.translate(-focusPxX + fOffX / zoomState.scale, -focusPxY + fOffY / zoomState.scale);
+ }
+ };
- if (cropArea && (cropArea.width < 100 || cropArea.height < 100)) {
- videoSourceWidth = (cropArea.width / 100) * video.videoWidth;
- videoSourceHeight = (cropArea.height / 100) * video.videoHeight;
- }
+ let fgCanvas: HTMLCanvasElement | null = null;
+ let fgCtx: CanvasRenderingContext2D | null = null;
- // Calcular aspect ratio del video fuente
- const videoAspectRatio = videoSourceWidth / videoSourceHeight;
- const availableAspectRatio = availableWidth / availableHeight;
+ // 1. ELIMINAMOS renderScale. Usamos solo un margen fijo del 50% para el giro 3D.
+ const BLEED_FACTOR = 1.5;
+ const fgWidth = canvasWidth * BLEED_FACTOR;
+ const fgHeight = canvasHeight * BLEED_FACTOR;
+ const fgOffsetX = (fgWidth - canvasWidth) / 2;
+ const fgOffsetY = (fgHeight - canvasHeight) / 2;
- // Calcular dimensiones del contenedor (mockup o video directo)
- let containerWidth: number;
- let containerHeight: number;
+ if (has3DEffect) {
+ if (!foregroundCanvasRef.current) {
+ foregroundCanvasRef.current = document.createElement('canvas');
+ }
+ fgCanvas = foregroundCanvasRef.current;
- if (videoAspectRatio > availableAspectRatio) {
- containerWidth = availableWidth;
- containerHeight = availableWidth / videoAspectRatio;
- } else {
- containerHeight = availableHeight;
- containerWidth = availableHeight * videoAspectRatio;
+ if (fgCanvas.width !== fgWidth || fgCanvas.height !== fgHeight) {
+ fgCanvas.width = fgWidth;
+ fgCanvas.height = fgHeight;
+ }
+
+ fgCtx = fgCanvas.getContext('2d', canvasCtxOptions);
+ if (fgCtx) {
+ fgCtx.setTransform(1, 0, 0, 1, 0, 0);
+ fgCtx.clearRect(0, 0, fgWidth, fgHeight);
+ fgCtx.imageSmoothingEnabled = true;
+ fgCtx.imageSmoothingQuality = 'high';
+ }
}
- // Centrar el contenedor en el área disponible
- const containerX = scaledPaddingX + (availableWidth - containerWidth) / 2;
- const containerY = scaledPaddingY + (availableHeight - containerHeight) / 2;
+ ctx.save();
+ drawBg(ctx);
+ ctx.restore();
- // 4. Aplicar transformaciones del video (rotación y traslación)
ctx.save();
+ applyVideoZoom(ctx);
+ await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, true);
+ ctx.restore();
- // Determinar el centro real del contenedor para rotar sobre su propio eje
- const videoCenterX = containerX + containerWidth / 2;
- const videoCenterY = containerY + containerHeight / 2;
+ const { containerX, containerY, containerWidth, containerHeight } = computeContainer();
- // Calcular traslación en píxeles basada en el tamaño del contenedor
- const translateXPx = (videoTransform.translateX / 100) * containerWidth;
- const translateYPx = (videoTransform.translateY / 100) * containerHeight;
+ if (has3DEffect && fgCanvas && fgCtx) {
+ fgCtx.save();
+ fgCtx.translate(fgOffsetX, fgOffsetY);
+ drawMockupAndMedia(fgCtx, containerX, containerY, containerWidth, containerHeight, video!, false);
+ fgCtx.restore();
- // Mover el origen al centro, trasladar, rotar, y devolver el origen a la esquina
- ctx.translate(videoCenterX + translateXPx, videoCenterY + translateYPx);
- ctx.rotate((videoTransform.rotation * Math.PI) / 180);
- ctx.translate(-videoCenterX, -videoCenterY);
+ applyPerspective3D(
+ fgCanvas,
+ zoomState.rotateX,
+ zoomState.rotateY,
+ zoomState.perspective * BLEED_FACTOR
+ );
- // 5. Dibujar sombra del contenedor (ahora rotará y se moverá con todo lo demás)
- if (shadows > 0 && !SELF_SHADOWING_MOCKUPS.includes(mockupId)) {
ctx.save();
- ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
- ctx.shadowBlur = scaledShadowBlur;
- ctx.shadowOffsetY = scaledShadowBlur * 0.3;
-
- ctx.fillStyle = 'black';
- drawRoundedRect(ctx, containerX, containerY, containerWidth, containerHeight, scaledRadius);
- ctx.fill();
+ applyVideoZoom(ctx);
+ ctx.drawImage(fgCanvas, -fgOffsetX, -fgOffsetY, fgWidth, fgHeight);
ctx.restore();
- }
-
- // 6. Determinar si hay mockup activo y dibujarlo
- const hasMockup = mockupId && mockupId !== "none";
- const currentMockupConfig = mockupConfig || DEFAULT_MOCKUP_CONFIG;
-
- let videoX = containerX;
- let videoY = containerY;
- let videoWidth = containerWidth;
- let videoHeight = containerHeight;
- let videoRadius = scaledRadius;
-
- if (hasMockup) {
- const mockupShadowBlur = SELF_SHADOWING_MOCKUPS.includes(mockupId) ? scaledShadowBlur : 0;
- const mockupResult = drawMockupToCanvas(
- ctx,
- mockupId,
- currentMockupConfig,
- containerX,
- containerY,
- containerWidth,
- containerHeight,
- scaledRadius,
- mockupShadowBlur,
- canvasWidth
- );
-
- videoX = mockupResult.contentX;
- videoY = mockupResult.contentY;
- videoWidth = mockupResult.contentWidth;
- videoHeight = mockupResult.contentHeight;
- videoRadius = mockupId === "iphone-slim" || mockupId === "glass-curve" || mockupId === "glass-full" ? scaledRadius * 6 : scaledRadius;
- }
-
- // 7. Dibujar video con esquinas redondeadas
- ctx.save();
- const needsBottomOnlyRadius = hasMockup && BOTTOM_ONLY_RADIUS_MOCKUPS.includes(mockupId);
-
- if (videoRadius > 0) {
- if (needsBottomOnlyRadius) {
- drawRoundedRectBottomOnly(ctx, videoX, videoY, videoWidth, videoHeight, videoRadius);
- } else {
- drawRoundedRect(ctx, videoX, videoY, videoWidth, videoHeight, videoRadius);
- }
- ctx.clip();
- } else {
- ctx.beginPath();
- ctx.rect(videoX, videoY, videoWidth, videoHeight);
- ctx.clip();
- }
-
- // Aplicar crop si existe
- if (cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0)) {
- const sourceX = (cropArea.x / 100) * video.videoWidth;
- const sourceY = (cropArea.y / 100) * video.videoHeight;
- const sourceWidth = (cropArea.width / 100) * video.videoWidth;
- const sourceHeight = (cropArea.height / 100) * video.videoHeight;
-
- ctx.drawImage(video, sourceX, sourceY, sourceWidth, sourceHeight, videoX, videoY, videoWidth, videoHeight);
} else {
- ctx.drawImage(video, videoX, videoY, videoWidth, videoHeight);
+ ctx.save();
+ applyVideoZoom(ctx);
+ drawMockupAndMedia(ctx, containerX, containerY, containerWidth, containerHeight, video!, false);
+ ctx.restore();
}
- ctx.restore();
- ctx.restore();
-
- // 8. Render elements ABOVE video (zIndex >= VIDEO_Z_INDEX)
+ ctx.save();
+ applyVideoZoom(ctx);
await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, false);
-
ctx.restore();
await drawCameraOverlay(ctx, canvasWidth, canvasHeight);
@@ -917,7 +1135,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
ctx.clip();
}
- try {
+ if (camVideo && camVideo.readyState >= 2) {
if (cameraConfig.mirror) {
ctx.translate(drawX + size, drawY);
ctx.scale(-1, 1);
@@ -925,20 +1143,39 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
} else {
ctx.drawImage(camVideo, sx, sy, srcShort, srcShort, drawX, drawY, size, size);
}
- } catch (e) {
}
-
ctx.restore();
+
};
useImperativeHandle(ref, () => ({
getExportCanvas: () => exportCanvasRef.current,
drawFrame,
+ getPreviewContainer: () => previewContainerRef.current,
}));
return (
- <div className="flex-1 flex items-center justify-center min-h-0 min-w-0 overflow-hidden bg-[#09090B] p-2 sm:p-4 lg:p-1">
- {/* Canvas oculto para exportación */}
+ <div
+ className="flex-1 flex items-center justify-center min-h-0 min-w-0 overflow-hidden bg-[#09090B] p-2 sm:p-4 lg:p-1 relative"
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ >
+ {mediaType === "image" && isDraggingOver && (
+ <div className="absolute inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm pointer-events-none">
+ <div className="flex flex-col items-center gap-4 text-white mask-[radial-gradient(circle,black_50%,transparent_95%)]">
+ <Icon icon="hugeicons:image-upload" width="120" />
+ <div className="text-xl font-semibold uppercase tracking-wider">
+ Suelta la imagen
+ </div>
+ </div>
+ </div>
+
+ )}
+
+ <div className="absolute inset-0 pointer-events-none z-0"
+ style={{ backgroundImage: 'radial-gradient(rgb(39, 39, 42) 1px, transparent 1px)', backgroundSize: '24px 24px' }}>
+ </div>
<canvas
ref={exportCanvasRef}
width={exportDimensions.width}
@@ -949,7 +1186,10 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
{/* Preview visual - contenedor con tamaño dinámico según aspect ratio */}
<div
ref={previewContainerRef}
- className="relative shrink-0 overflow-hidden border border-white/20 rounded-xl transition-all duration-300"
+ className={`relative shrink-0 overflow-hidden transition-all duration-300 ${mediaType === "image" && imageUrl
+ ? ""
+ : "border border-white/20 rounded-xl"
+ }`}
style={{
aspectRatio: getAspectRatioStyle(aspectRatio, customAspectRatio ?? undefined),
maxWidth: getMaxWidth(aspectRatio, customAspectRatio ?? undefined),
@@ -965,25 +1205,67 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
}}
>
{/* Zoom container - applies zoom to entire composition (background + video) */}
- <div
- className="absolute inset-0"
+ <div className="absolute inset-0"
style={{
- perspective: zoomTransform.perspective > 0 ? `${zoomTransform.perspective}px` : 'none',
+ perspective: mediaType === "image" && imageTransform && apply3DToBackground ? `${imageTransform.perspective || 600}px` : 'none',
perspectiveOrigin: 'center center',
}}
>
- {/* Zoom + translate layer */}
- <div
- className="absolute inset-0 origin-center"
+ <div className="absolute inset-0 overflow-hidden">
+ <div className="absolute transition-all duration-200" style={{
+ inset: backgroundBlur > 0 ? `-${backgroundBlur}px` : '0',
+ ...(shouldShowCustomColor && backgroundColorCss
+ ? backgroundColorCss.startsWith('#') || backgroundColorCss.startsWith('rgb')
+ ? { backgroundColor: backgroundColorCss }
+ : { backgroundImage: backgroundColorCss }
+ : (shouldShowCustomImage || shouldShowUnsplashOverride)
+ ? {
+ backgroundImage: `url('${shouldShowCustomImage ? selectedImageUrl : unsplashOverrideUrl}')`,
+ backgroundSize: 'cover',
+ backgroundPosition: 'center',
+ }
+ : shouldShowWallpaper
+ ? {
+ backgroundImage: `url('${wallpaperUrl}')`,
+ backgroundSize: 'cover',
+ backgroundPosition: 'center',
+ }
+ : { backgroundColor: 'transparent' }),
+ filter: backgroundBlur > 0 ? `blur(${backgroundBlur * 0.4}px)` : 'none',
+ }} />
+ </div>
+ {/* Zoom + translate layer (+ 3D transform for image mode when apply3DToBackground is true) */}
+ <div className="absolute inset-0 origin-center"
style={{
- transform: `scale(${zoomTransform.scale}) translate(${zoomTransform.translateX}%, ${zoomTransform.translateY}%)`,
- transition: zoomTransform.isMoving
- ? `transform ${zoomTransform.transitionMs}ms linear`
- : `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
- transformStyle: 'preserve-3d',
+ transform: mediaType === "image" && imageTransform && apply3DToBackground
+ ? `rotateX(${imageTransform.rotateX}deg) rotateY(${imageTransform.rotateY}deg) rotateZ(${imageTransform.rotateZ}deg) scale(${imageTransform.scale * imageZoomScale}) translateY(${imageTransform.translateY}%)`
+ : `scale(${zoomTransform.scale}) translate(${zoomTransform.translateX}%, ${zoomTransform.translateY}%)`,
+ perspective: !(mediaType === "image" && apply3DToBackground) && zoomTransform.perspective > 0
+ ? `${(zoomTransform.perspective / 10.8).toFixed(1)}cqh` : 'none',
+ transformStyle: mediaType === "image" && apply3DToBackground ? 'preserve-3d' : undefined,
+ transition: mediaType === "image" && apply3DToBackground
+ ? 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)'
+ : zoomTransform.isMoving ? `transform ${zoomTransform.transitionMs}ms linear` : `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
}}
>
- {/* 3D rotation layer */}
+ {/* Capa 2A: Canvas elements BEHIND video — sin rotación 3D */}
+ <CanvasElementsLayer
+ canvasContainerRef={canvasContainerRef}
+ canvasElements={canvasElements}
+ selectedElementId={selectedElementId}
+ hoveredElementId={hoveredElementId}
+ isDraggingElement={isDraggingElement}
+ behindVideo={true}
+ onElementSelect={onElementSelect}
+ onElementUpdate={onElementUpdate}
+ setHoveredElementId={setHoveredElementId}
+ setIsDraggingElement={setIsDraggingElement}
+ setIsDraggingElementRotation={setIsDraggingElementRotation}
+ elementDragStart={elementDragStart}
+ layerZIndex={1}
+ />
+
+ {/* 3D rotation layer — solo envuelve el mockup, el fondo queda plano */}
<div
className="absolute inset-0 origin-center"
style={{
@@ -991,78 +1273,50 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
? `rotateX(${zoomTransform.rotateX}deg) rotateY(${zoomTransform.rotateY}deg)`
: 'none',
transition: `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
+ willChange: zoomTransform.perspective > 0 ? 'transform' : 'auto',
+ transformStyle: 'preserve-3d',
+ zIndex: 2
}}
>
- {/* Capa 1: Fondo (siempre llena todo el contenedor) */}
- <div
- className="absolute inset-0 overflow-hidden"
- >
- <div
- className="absolute transition-all duration-200"
- style={{
- inset: backgroundBlur > 0 ? `-${backgroundBlur}px` : '0',
- ...(shouldShowCustomColor && backgroundColorCss
- ? // Color sólido o gradiente CSS
- backgroundColorCss.startsWith('#') || backgroundColorCss.startsWith('rgb')
- ? { backgroundColor: backgroundColorCss }
- : { backgroundImage: backgroundColorCss }
- : (shouldShowCustomImage || shouldShowUnsplashOverride)
- ? // Imagen personalizada o Unsplash override
- {
- backgroundImage: `url('${shouldShowCustomImage ? selectedImageUrl : unsplashOverrideUrl}')`,
- backgroundSize: 'cover',
- backgroundPosition: 'center',
- }
- : shouldShowWallpaper
- ? // Wallpaper
- {
- backgroundImage: `url('${wallpaperUrl}')`,
- backgroundSize: 'cover',
- backgroundPosition: 'center',
- }
- :
- { backgroundColor: 'transparent' }
- ),
- filter: backgroundBlur > 0 ? `blur(${backgroundBlur * 0.4}px)` : 'none',
- }}
- />
- </div>
-
- {/* Capa 2A: Canvas elements BEHIND video (zIndex < VIDEO_Z_INDEX) */}
- <CanvasElementsLayer
- canvasContainerRef={canvasContainerRef}
- canvasElements={canvasElements}
- selectedElementId={selectedElementId}
- hoveredElementId={hoveredElementId}
- isDraggingElement={isDraggingElement}
- behindVideo={true}
- onElementSelect={onElementSelect}
- onElementUpdate={onElementUpdate}
- setHoveredElementId={setHoveredElementId}
- setIsDraggingElement={setIsDraggingElement}
- setIsDraggingElementRotation={setIsDraggingElementRotation}
- elementDragStart={elementDragStart}
- layerZIndex={1}
- />
-
{/* Capa 2B: Video con padding, esquinas redondeadas y sombras */}
<div
className="absolute inset-0 flex items-center justify-center transition-all duration-200"
- style={{ padding: `${padding * 0.5}%`, zIndex: 2, pointerEvents: 'none' }}
+ style={{
+ padding: `${padding * 0.5}%`,
+ zIndex: 2,
+ pointerEvents: 'none',
+ ...(mediaType === "image" && imageTransform && !apply3DToBackground ? {
+ perspective: `${imageTransform.perspective || 600}px`,
+ perspectiveOrigin: 'center center',
+ } : {})
+ }}
>
<div
ref={videoContainerRef}
className="relative flex w-full h-full items-center justify-center max-w-full max-h-full"
style={{
- transform: `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg)`,
- cursor: isDraggingVideo ? 'move' : (isVideoHovered && videoUrl ? 'move' : 'default'),
- transition: isDraggingVideo || isDraggingRotation ? 'none' : 'transform 0.15s cubic-bezier(0.25, 0.46, 0.45, 0.94)',
+ transform: mediaType === "image" && imageTransform && !apply3DToBackground
+ ? `
+ translate(${videoTransform.translateX}%, ${videoTransform.translateY}%)
+ rotate(${videoTransform.rotation}deg)
+ rotateX(${imageTransform.rotateX}deg)
+ rotateY(${imageTransform.rotateY}deg)
+ rotateZ(${imageTransform.rotateZ}deg)
+ scale(${imageTransform.scale * imageZoomScale})
+ translateY(${imageTransform.translateY}%)
+ `
+ : `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg)`,
+ cursor: isDraggingVideo ? 'move' : (isVideoHovered && hasMedia ? 'move' : 'default'),
+ transition: (mediaType === "image" && imageTransform && !apply3DToBackground)
+ ? 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)'
+ : isDraggingVideo || isDraggingRotation ? 'none' : 'transform 0.15s cubic-bezier(0.25, 0.46, 0.45, 0.94)',
pointerEvents: 'auto',
+ transformStyle: mediaType === "image" && !apply3DToBackground ? 'preserve-3d' : undefined,
}}
- onMouseEnter={() => videoUrl && setIsVideoHovered(true)}
+ onMouseEnter={() => hasMedia && setIsVideoHovered(true)}
onMouseLeave={() => setIsVideoHovered(false)}
onMouseDown={(e) => {
- if (!videoUrl || !onVideoTransformChange) return;
+ if (!hasMedia || !onVideoTransformChange) return;
// Only start dragging if not clicking on rotation handle
if ((e.target as HTMLElement).closest('[data-rotation-handle]')) return;
@@ -1076,13 +1330,13 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
initialTranslateY: videoTransform.translateY,
};
}}
- onMouseMove={(e) => { if (videoUrl) setVideoHoverCorner(getNearestCorner(e, videoTransform.rotation)); }}
+ onMouseMove={(e) => { if (hasMedia) setVideoHoverCorner(getNearestCorner(e, videoTransform.rotation)); }}
>
<div className="relative">
- {/* Rotation handle */}
- {isVideoHovered && videoUrl && onVideoTransformChange && (
+ {isVideoHovered && hasMedia && onVideoTransformChange && (
<div
- data-rotation-handle style={getCornerStyle(videoHoverCorner, -14)}
+ data-rotation-handle
+ style={getCornerStyle(videoHoverCorner, -14)}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
@@ -1097,85 +1351,211 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
};
}}
>
- <RotationHandleIcon corner={videoHoverCorner} color="#e5e7eb" />
+ <div style={{
+ transform: `scale(${mediaType === "image" && imageTransform && !apply3DToBackground
+ ? 1 / (imageTransform.scale * imageZoomScale)
+ : 1
+ })`,
+ transformOrigin: "center center"
+ }}>
+ <RotationHandleIcon corner={videoHoverCorner} color="#e5e7eb" />
+ </div>
</div>
)}
- {isVideoHovered && videoUrl && !isDraggingVideo && !isDraggingRotation && (
+ {isVideoHovered && hasMedia && !isDraggingVideo && !isDraggingRotation && (
<div
className="absolute -inset-px border border-white pointer-events-none z-10 opacity-80"
style={{ borderRadius: `${roundedCorners + 1}px` }}
/>
)}
- <MockupWrapper
- mockupId={mockupId}
- config={mockupConfig ?? DEFAULT_MOCKUP_CONFIG}
- roundedCorners={roundedCorners}
- shadows={shadows}
+
+ {/* Wrapper for mask: applies to entire mockup if mockup exists */}
+ <div
+ className="w-full h-full"
+ style={hasMask && hasMockup ? maskStyles : {}}
>
- {videoUrl ? (
- <div className="relative flex items-center justify-center overflow-hidden w-full h-full rounded-[inherit]"
- > {/* Video element - src managed imperatively via videoRef, NOT as React prop */}
- <video
- key={videoUrl}
- ref={videoRef}
- preload="auto"
- playsInline
- className="w-full h-full object-contain"
- style={{
- // Aplicar crop usando object-view-box (CSS nativo)
- ...(cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0) ? {
- objectViewBox: `inset(${cropArea.y}% ${100 - cropArea.x - cropArea.width}% ${100 - cropArea.y - cropArea.height}% ${cropArea.x}%)`,
- } : {}),
- opacity: currentThumbnail ? 0 : 1,
- }}
- onTimeUpdate={onTimeUpdate}
- onLoadedMetadata={onLoadedMetadata}
- onEnded={onEnded}
- />
-
- {currentThumbnail && (
- <img
- src={currentThumbnail.dataUrl}
- alt="Preview"
- crossOrigin="anonymous"
- className="absolute inset-0 w-full h-full object-contain"
+ <MockupWrapper
+ mockupId={mockupId}
+ config={mockupConfig ?? DEFAULT_MOCKUP_CONFIG}
+ roundedCorners={roundedCorners}
+ shadows={shadows}
+ >
+ {hasMedia ? (
+ <div className="relative flex items-center justify-center overflow-hidden w-full h-full rounded-[inherit]">
+ {mediaType === "video" && videoUrl ? (
+ <>
+ <video
+ key={videoUrl}
+ ref={videoRef}
+ preload="auto"
+ playsInline
+ className="w-full h-full object-contain"
+ style={{
+ ...(cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0)
+ ? { objectViewBox: `inset(${cropArea.y}% ${100 - cropArea.x - cropArea.width}% ${100 - cropArea.y - cropArea.height}% ${cropArea.x}%)` }
+ : {}),
+ ...(hasMask && !hasMockup ? maskStyles : {}),
+ opacity: currentThumbnail ? 0 : 1,
+ }}
+ onTimeUpdate={onTimeUpdate}
+ onLoadedMetadata={onLoadedMetadata}
+ onEnded={onEnded}
+ />
+ {currentThumbnail && (
+ <img
+ src={currentThumbnail.dataUrl}
+ alt="Preview"
+ crossOrigin="anonymous"
+ className="absolute inset-0 w-full h-full object-contain"
+ style={hasMask && !hasMockup ? maskStyles : {}}
+ />
+ )}
+ </>
+ ) : mediaType === "image" && imageUrl ? (
+ <>
+ <img
+ ref={imageRef as React.RefObject<HTMLImageElement>}
+ src={imageUrl}
+ alt="Editing image"
+ crossOrigin="anonymous"
+ className="w-full h-full object-contain"
+ style={{
+ ...(cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0) ? {
+ objectViewBox: `inset(${cropArea.y}% ${100 - cropArea.x - cropArea.width}% ${100 - cropArea.y - cropArea.height}% ${cropArea.x}%)`
+ } : {}),
+ ...(hasMask && !hasMockup ? maskStyles : {}),
+ }}
+ onLoad={onLoadedMetadata}
+ />
+ <div
+ className="absolute inset-0 pointer-events-none transition-opacity duration-300"
+ style={{
+ background: "radial-gradient(circle at center, transparent 30%, rgba(0, 0, 0, 0.75) 100%)",
+ opacity: isVideoHovered ? 1 : 0,
+ zIndex: 10
+ }}
+ />
+ </>
+ ) : null}
+ </div>
+ ) : (
+ <div className="w-full h-full aspect-video min-w-75 bg-[#1E1E1E] border border-white/10 flex flex-col overflow-hidden">
+ <PlaceholderEditor
+ onVideoUpload={mediaType === "video" ? onVideoUpload : onImageUpload}
+ isUploading={isUploading}
+ mediaType={mediaType}
/>
- )}
- </div>
- ) : (
- <div className="w-full h-full aspect-video min-w-75 bg-[#1E1E1E] border border-white/10 flex flex-col overflow-hidden">
- <PlaceholderEditor
- onVideoUpload={onVideoUpload}
- isUploading={isUploading}
- />
- </div>
- )}
- </MockupWrapper>
+ </div>
+ )}
+ </MockupWrapper>
+ </div>
</div>
</div>
+ <div
+ className="absolute inset-0 flex items-center justify-center pointer-events-none z-50 transition-transform"
+ style={{
+ transform: mediaType === "image" && imageTransform && !apply3DToBackground
+ ? `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg) rotateX(${imageTransform.rotateX}deg) rotateY(${imageTransform.rotateY}deg) rotateZ(${imageTransform.rotateZ}deg) translateY(${imageTransform.translateY}%)`
+ : `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg)`,
+ transformStyle: mediaType === "image" && !apply3DToBackground ? 'preserve-3d' : undefined,
+ }}
+ >
+ <EditorHoverTooltip show={isVideoHovered && mediaType === "image"} />
+ </div>
</div>
- {/* End zoom transform div */}
</div>
+ {/* Capa 3: Canvas elements ABOVE video (zIndex >= VIDEO_Z_INDEX) */}
+ <CanvasElementsLayer
+ canvasContainerRef={undefined}
+ canvasElements={canvasElements}
+ selectedElementId={selectedElementId}
+ hoveredElementId={hoveredElementId}
+ isDraggingElement={isDraggingElement}
+ behindVideo={false}
+ onElementSelect={onElementSelect}
+ onElementUpdate={onElementUpdate}
+ setHoveredElementId={setHoveredElementId}
+ setIsDraggingElement={setIsDraggingElement}
+ setIsDraggingElementRotation={setIsDraggingElementRotation}
+ elementDragStart={elementDragStart}
+ layerZIndex={3}
+ />
+
+ {/* Capa HIT: invisible, todos los elementos, para recibir eventos */}
+ <CanvasElementsLayer
+ canvasContainerRef={undefined}
+ canvasElements={canvasElements}
+ selectedElementId={selectedElementId}
+ hoveredElementId={hoveredElementId}
+ isDraggingElement={isDraggingElement}
+ behindVideo={true}
+ onElementSelect={onElementSelect}
+ onElementUpdate={onElementUpdate}
+ setHoveredElementId={setHoveredElementId}
+ setIsDraggingElement={setIsDraggingElement}
+ setIsDraggingElementRotation={setIsDraggingElementRotation}
+ elementDragStart={elementDragStart}
+ layerZIndex={100}
+ hitTestOnly={true}
+ />
+
</div>
{/* End perspective wrapper div */}
- {/* Capa 3: Canvas elements ABOVE video (zIndex >= VIDEO_Z_INDEX) */}
- <CanvasElementsLayer
- canvasContainerRef={canvasContainerRef}
- canvasElements={canvasElements}
- selectedElementId={selectedElementId}
- hoveredElementId={hoveredElementId}
- isDraggingElement={isDraggingElement}
- behindVideo={false}
- onElementSelect={onElementSelect}
- onElementUpdate={onElementUpdate}
- setHoveredElementId={setHoveredElementId}
- setIsDraggingElement={setIsDraggingElement}
- setIsDraggingElementRotation={setIsDraggingElementRotation}
- elementDragStart={elementDragStart}
- layerZIndex={3}
- />
- {/* Capa 4: Camera overlay for preview — outside zoom transform, stays fixed */}
- {cameraUrl && cameraConfig?.enabled && (
+ {(isDraggingElement && (alignmentGuides.vertical.length > 0 || alignmentGuides.horizontal.length > 0)) && (
+ <>
+ {alignmentGuides.vertical.map((x, index) => (
+ <div
+ key={`v-${index}`}
+ className="absolute top-0 bottom-0 w-0.5 bg-white/30 pointer-events-none"
+ style={{
+ left: `${x}%`,
+ zIndex: VIDEO_Z_INDEX + 100,
+ }}
+ />
+ ))}
+ {alignmentGuides.horizontal.map((y, index) => (
+ <div
+ key={`h-${index}`}
+ className="absolute left-0 right-0 h-0.5 bg-white/30 pointer-events-none"
+ style={{
+ top: `${y}%`,
+ zIndex: VIDEO_Z_INDEX + 100,
+ }}
+ />
+ ))}
+ </>
+ )}
+
+ {/* Smart alignment guides for mockup (video/image) */}
+ {(isDraggingVideo && (mockupAlignmentGuides.vertical.length > 0 || mockupAlignmentGuides.horizontal.length > 0)) && (
+ <>
+ {/* Vertical guides */}
+ {mockupAlignmentGuides.vertical.map((x, index) => (
+ <div
+ key={`mockup-v-${index}`}
+ className="absolute top-0 bottom-0 w-0.5 bg-white/30 pointer-events-none"
+ style={{
+ left: `${x}%`,
+ zIndex: VIDEO_Z_INDEX + 100,
+ }}
+ />
+ ))}
+ {/* Horizontal guides */}
+ {mockupAlignmentGuides.horizontal.map((y, index) => (
+ <div
+ key={`mockup-h-${index}`}
+ className="absolute left-0 right-0 h-0.5 bg-white/30 pointer-events-none"
+ style={{
+ top: `${y}%`,
+ zIndex: VIDEO_Z_INDEX + 100,
+ }}
+ />
+ ))}
+ </>
+ )}
+
+ {/* Capa 4: Camera overlay for preview — only in video mode */}
+ {mediaType !== "image" && cameraUrl && cameraConfig?.enabled && (
<div data-camera-overlay className="absolute inset-0 pointer-events-none" style={{ zIndex: 4 }}>
<div
tabIndex={0}
diff --git a/app/components/ui/editor/VideoClipTrackItem.tsx b/app/components/ui/editor/VideoClipTrackItem.tsx
index 332f938..e73f2ec 100644
--- a/app/components/ui/editor/VideoClipTrackItem.tsx
+++ b/app/components/ui/editor/VideoClipTrackItem.tsx
@@ -88,8 +88,6 @@ export function VideoClipTrackItem({
.sort((a, b) => a.startTime - b.startTime);
let minStart = 0;
- // Don't limit maxEnd by totalDuration - allow clip to expand up to its full duration
- // The actual limit will be the next clip's start time OR unlimited (for the last clip)
let maxEnd = Infinity;
for (const other of sorted) {
diff --git a/app/components/ui/editor/VideoCropperModal.tsx b/app/components/ui/editor/VideoCropperModal.tsx
index ac2ae66..f5358a2 100644
--- a/app/components/ui/editor/VideoCropperModal.tsx
+++ b/app/components/ui/editor/VideoCropperModal.tsx
@@ -3,25 +3,9 @@
import { useState, useRef, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Icon } from "@iconify/react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
-import type { CropArea } from "@/types";
-
-interface VideoCropperModalProps {
- isOpen: boolean;
- onClose: () => void;
- videoUrl: string | null;
- onCropApply: (crop: CropArea) => void;
- initialCrop?: CropArea;
-}
-
-const CROP_ASPECT_RATIOS = [
- { label: "Libre", value: null },
- { label: "16:9", value: 16 / 9 },
- { label: "9:16", value: 9 / 16 },
- { label: "1:1", value: 1 },
- { label: "4:3", value: 4 / 3 },
- { label: "3:4", value: 3 / 4 },
-] as const;
+import { CROP_ASPECT_RATIOS, VideoCropperModalProps, type CropArea } from "@/types";
export function VideoCropperModal({
isOpen,
@@ -30,9 +14,9 @@ export function VideoCropperModal({
onCropApply,
initialCrop,
}: VideoCropperModalProps) {
+ const t = useTranslations("videoCropper");
const containerRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
-
const [cropArea, setCropArea] = useState<CropArea>(initialCrop ?? { x: 0, y: 0, width: 100, height: 100 });
const [selectedAspectRatio, setSelectedAspectRatio] = useState<number | null>(null);
const [isDragging, setIsDragging] = useState(false);
@@ -40,7 +24,6 @@ export function VideoCropperModal({
const [dragHandle, setDragHandle] = useState<string | null>(null);
const [videoDimensions, setVideoDimensions] = useState({ width: 0, height: 0 });
const [wasOpen, setWasOpen] = useState(false);
-
const dragStartPos = useRef({ x: 0, y: 0 });
const initialCropRef = useRef<CropArea>({ x: 0, y: 0, width: 100, height: 100 });
@@ -61,10 +44,8 @@ export function VideoCropperModal({
}
}, []);
- // Aplicar aspect ratio cuando se selecciona
const handleAspectRatioSelect = useCallback((ratio: number | null) => {
setSelectedAspectRatio(ratio);
-
if (ratio === null || videoDimensions.width === 0) return;
const videoAspect = videoDimensions.width / videoDimensions.height;
@@ -92,7 +73,6 @@ export function VideoCropperModal({
});
}, [videoDimensions]);
- // Manejo del inicio de arrastre
const handleMouseDown = (e: React.MouseEvent, type: "move" | "resize", handle?: string) => {
e.preventDefault();
e.stopPropagation();
@@ -103,14 +83,12 @@ export function VideoCropperModal({
initialCropRef.current = { ...cropArea };
};
- // Manejo del movimiento
useEffect(() => {
if (!isDragging || !containerRef.current) return;
const handleMouseMove = (e: MouseEvent) => {
const container = containerRef.current;
if (!container) return;
-
const rect = container.getBoundingClientRect();
const deltaX = ((e.clientX - dragStartPos.current.x) / rect.width) * 100;
const deltaY = ((e.clientY - dragStartPos.current.y) / rect.height) * 100;
@@ -196,7 +174,6 @@ export function VideoCropperModal({
newCrop.y = Math.max(0, Math.min(100 - minSize, newCrop.y));
newCrop.width = Math.max(minSize, Math.min(100 - newCrop.x, newCrop.width));
newCrop.height = Math.max(minSize, Math.min(100 - newCrop.y, newCrop.height));
-
setCropArea(newCrop);
}
};
@@ -209,7 +186,6 @@ export function VideoCropperModal({
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleMouseUp);
-
return () => {
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
@@ -248,7 +224,7 @@ export function VideoCropperModal({
<div className="w-6 h-6 rounded-md bg-white/10 flex items-center justify-center">
<Icon icon="mdi:crop" className="text-sm text-white/70" />
</div>
- <span className="text-sm font-medium text-white">Recortar video</span>
+ <span className="text-sm font-medium text-white">{t("title")}</span>
{videoDimensions.width > 0 && (
<span className="text-[11px] font-mono text-white/60 bg-white/4 px-2 py-0.5 rounded-md border border-white/10">
{videoDimensions.width} × {videoDimensions.height}
@@ -264,7 +240,6 @@ export function VideoCropperModal({
</div>
<div className="flex-1 flex overflow-hidden min-h-0">
-
<div className="flex-1 p-6 flex items-center justify-center bg-black/50 overflow-hidden">
<div
ref={containerRef}
@@ -277,9 +252,10 @@ export function VideoCropperModal({
height: "100%",
maxWidth: "100%",
maxHeight: "100%",
- aspectRatio: videoDimensions.width && videoDimensions.height
- ? `${videoDimensions.width}/${videoDimensions.height}`
- : "16/9",
+ aspectRatio:
+ videoDimensions.width && videoDimensions.height
+ ? `${videoDimensions.width}/${videoDimensions.height}`
+ : "16/9",
}}
>
{videoUrl ? (
@@ -288,11 +264,13 @@ export function VideoCropperModal({
src={videoUrl}
className="absolute inset-0 w-full h-full object-contain bg-black"
onLoadedMetadata={handleVideoLoad}
- muted loop autoPlay
+ muted
+ loop
+ autoPlay
/>
) : (
<div className="absolute inset-0 bg-white/3 rounded-lg flex items-center justify-center text-white/20 text-sm">
- Sin video
+ {t("noVideo")}
</div>
)}
@@ -321,40 +299,41 @@ export function VideoCropperModal({
{videoDimensions.width > 0 && (
<div className="absolute -top-6 left-1/2 -translate-x-1/2 bg-black/80 backdrop-blur-sm border border-white/12 text-white/60 text-[10px] font-mono px-2 py-0.5 rounded-md whitespace-nowrap pointer-events-none">
- {Math.round((videoDimensions.width * cropArea.width) / 100)} × {Math.round((videoDimensions.height * cropArea.height) / 100)}
+ {Math.round((videoDimensions.width * cropArea.width) / 100)} ×{" "}
+ {Math.round((videoDimensions.height * cropArea.height) / 100)}
</div>
)}
- {["nw", "ne", "sw", "se"].map((handle) => {
- const positions: Record<string, string> = {
- nw: "-top-1.5 -left-1.5 cursor-nwse-resize",
- ne: "-top-1.5 -right-1.5 cursor-nesw-resize",
- sw: "-bottom-1.5 -left-1.5 cursor-nesw-resize",
- se: "-bottom-1.5 -right-1.5 cursor-nwse-resize",
- };
- return (
- <div
- key={handle}
- className={`absolute w-3 h-3 bg-white rounded-sm shadow-lg ${positions[handle]}`}
- onMouseDown={(e) => { e.stopPropagation(); handleMouseDown(e, "resize", handle); }}
- />
- );
- })}
+ {["nw", "ne", "sw", "se"].map((handle) => (
+ <div
+ key={handle}
+ className={`absolute w-3 h-3 bg-white rounded-sm shadow-lg ${handle === "nw" ? "-top-1.5 -left-1.5 cursor-nwse-resize" :
+ handle === "ne" ? "-top-1.5 -right-1.5 cursor-nesw-resize" :
+ handle === "sw" ? "-bottom-1.5 -left-1.5 cursor-nesw-resize" :
+ "-bottom-1.5 -right-1.5 cursor-nwse-resize"
+ }`}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ handleMouseDown(e, "resize", handle);
+ }}
+ />
+ ))}
{["n", "s", "w", "e"].map((handle) => {
const isVertical = handle === "n" || handle === "s";
- const positions: Record<string, string> = {
- n: "left-1/2 -translate-x-1/2 -top-[3px] cursor-ns-resize",
- s: "left-1/2 -translate-x-1/2 -bottom-[3px] cursor-ns-resize",
- w: "top-1/2 -translate-y-1/2 -left-[3px] cursor-ew-resize",
- e: "top-1/2 -translate-y-1/2 -right-[3px] cursor-ew-resize",
- };
return (
<div
key={handle}
- className={`absolute bg-white rounded-sm ${positions[handle]}`}
+ className={`absolute bg-white rounded-sm ${handle === "n" ? "left-1/2 -translate-x-1/2 -top-0.75 cursor-ns-resize" :
+ handle === "s" ? "left-1/2 -translate-x-1/2 -bottom-0.75 cursor-ns-resize" :
+ handle === "w" ? "top-1/2 -translate-y-1/2 -left-0.75 cursor-ew-resize" :
+ "top-1/2 -translate-y-1/2 -right-0.75 cursor-ew-resize"
+ }`}
style={{ width: isVertical ? "28px" : "5px", height: isVertical ? "5px" : "28px" }}
- onMouseDown={(e) => { e.stopPropagation(); handleMouseDown(e, "resize", handle); }}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ handleMouseDown(e, "resize", handle);
+ }}
/>
);
})}
@@ -363,24 +342,26 @@ export function VideoCropperModal({
</div>
</div>
+ {/* Sidebar Controls */}
<div className="w-56 shrink-0 border-l border-white/10 flex flex-col bg-[#0d0d0f]">
-
<div className="p-4 border-b border-white/10">
- <p className="text-[10px] uppercase tracking-widest font-semibold text-white/60 mb-3">Proporción</p>
+ <p className="text-[10px] uppercase tracking-widest font-semibold text-white/60 mb-3">
+ {t("sections.ratio")}
+ </p>
<div className="grid grid-cols-3 gap-1">
{CROP_ASPECT_RATIOS.map((ratio) => (
<div key={ratio.label} className="relative">
<button
onClick={() => handleAspectRatioSelect(ratio.value)}
className={`w-full py-1.5 text-[11px] font-medium rounded-lg transition-all ${selectedAspectRatio === ratio.value
- ? "text-white border-transparent"
- : "bg-white/4 text-white/40 hover:bg-white/8 hover:text-white/70 border border-white/10"
+ ? "text-white border-transparent"
+ : "bg-white/4 text-white/40 hover:bg-white/8 hover:text-white/70 border border-white/10"
}`}
style={
selectedAspectRatio === ratio.value
? {
- background: 'radial-gradient(circle at 50% 0%, #555555 0%, #252525 64%)',
- boxShadow: 'inset 0 1.01rem 0.2rem -1rem #fff0, inset 0 -1.01rem 0.2rem -1rem #0000, 0 -1.02rem 0.2rem -1rem #fff0, 0 1rem 0.2rem -1rem #0000, 0 0 0 1px #fff3, 0 4px 4px 0 #0004, 0 0 0 1px #333',
+ background: "radial-gradient(circle at 50% 0%, #555555 0%, #252525 64%)",
+ boxShadow: "0 0 0 1px #fff3, 0 4px 4px 0 #0004, 0 0 0 1px #333",
}
: {}
}
@@ -396,13 +377,15 @@ export function VideoCropperModal({
</div>
<div className="p-4 border-b border-white/10">
- <p className="text-[10px] uppercase tracking-widest font-semibold text-white/60 mb-3">Área</p>
+ <p className="text-[10px] uppercase tracking-widest font-semibold text-white/60 mb-3">
+ {t("sections.area")}
+ </p>
<div className="space-y-2">
{[
- { label: "X", value: cropArea.x },
- { label: "Y", value: cropArea.y },
- { label: "W", value: cropArea.width },
- { label: "H", value: cropArea.height },
+ { label: t("labels.x"), value: cropArea.x },
+ { label: t("labels.y"), value: cropArea.y },
+ { label: t("labels.width"), value: cropArea.width },
+ { label: t("labels.height"), value: cropArea.height },
].map(({ label, value }) => (
<div key={label} className="flex items-center justify-between">
<span className="text-[11px] text-white/25 font-mono w-4">{label}</span>
@@ -416,23 +399,17 @@ export function VideoCropperModal({
<div className="flex-1" />
<div className="p-4 flex flex-col gap-2">
- <Button
- variant="outline"
- onClick={handleReset}
- >
- Restablecer
+ <Button variant="outline" onClick={handleReset}>
+ {t("buttons.reset")}
</Button>
- <Button
- variant="primary"
- onClick={handleApply}
- >
- Aplicar recorte
+ <Button variant="primary" onClick={handleApply}>
+ {t("buttons.apply")}
</Button>
</div>
</div>
</div>
</motion.div>
</motion.div>
- </AnimatePresence >
+ </AnimatePresence>
);
-}
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/ZoomFragmentEditor.tsx b/app/components/ui/editor/ZoomFragmentEditor.tsx
index 0cfbbc6..6cd8138 100644
--- a/app/components/ui/editor/ZoomFragmentEditor.tsx
+++ b/app/components/ui/editor/ZoomFragmentEditor.tsx
@@ -13,6 +13,7 @@ export function ZoomFragmentEditor({
getThumbnailForTime, videoDimensions, onBack, onDelete, onUpdate,
}: ZoomFragmentEditorProps) {
const t = useTranslations("zoomFragmentEditor");
+ const tCommon = useTranslations("editor");
const focusPreviewRef = useRef<HTMLDivElement>(null);
const [editingPoint, setEditingPoint] = useState<'start' | 'end'>('start');
@@ -310,8 +311,8 @@ export function ZoomFragmentEditor({
<div className="flex items-center gap-2">
<Icon icon="mdi:cube-outline" width="16" className="text-white/50" />
<div>
- <p className="text-xs font-medium text-white/80">{t("effect3d.title")}</p>
- <p className="text-[10px] text-white/40">{t("effect3d.subtitle")}</p>
+ <p className="text-xs font-medium text-white/80">{tCommon("effect3d.title")}</p>
+ <p className="text-[10px] text-white/40">{tCommon("effect3d.subtitle")}</p>
</div>
</div>
<button onClick={handleToggle3D} className={`relative w-11 h-6 rounded-full transition-colors ${fragment.enable3D ? 'bg-gray-400' : 'bg-white/15'}`}>
diff --git a/app/components/ui/editor/getMediaMaskStyles.tsx b/app/components/ui/editor/getMediaMaskStyles.tsx
new file mode 100644
index 0000000..46d09ca
--- /dev/null
+++ b/app/components/ui/editor/getMediaMaskStyles.tsx
@@ -0,0 +1,32 @@
+import type { ImageMaskConfig } from "@/types/photo.types";
+
+export function getMediaMaskStyles(maskConfig?: ImageMaskConfig | null): React.CSSProperties {
+ if (!maskConfig || !maskConfig.enabled) return {};
+
+ const masks: string[] = [];
+
+ if (maskConfig.top) {
+ masks.push(`linear-gradient(180deg, transparent ${maskConfig.top.from}%, black ${maskConfig.top.to ?? 100}%)`);
+ }
+ if (maskConfig.bottom) {
+ masks.push(`linear-gradient(0deg, transparent ${maskConfig.bottom.from}%, black ${maskConfig.bottom.to ?? 100}%)`);
+ }
+ if (maskConfig.left) {
+ masks.push(`linear-gradient(90deg, transparent ${maskConfig.left.from}%, black ${maskConfig.left.to ?? 100}%)`);
+ }
+ if (maskConfig.right) {
+ masks.push(`linear-gradient(270deg, transparent ${maskConfig.right.from}%, black ${maskConfig.right.to ?? 100}%)`);
+ }
+ if (maskConfig.angle !== undefined) {
+ masks.push(`linear-gradient(${maskConfig.angle}deg, transparent ${maskConfig.angleFrom ?? 0}%, black ${maskConfig.angleTo ?? 100}%)`);
+ }
+
+ if (masks.length === 0) return {};
+
+ return {
+ WebkitMaskImage: masks.join(', '),
+ WebkitMaskComposite: 'source-in',
+ maskImage: masks.join(', '),
+ maskComposite: 'intersect',
+ };
+}
\ No newline at end of file
diff --git a/components/ui/TrackVolumeSlider.tsx b/components/ui/TrackVolumeSlider.tsx
new file mode 100644
index 0000000..e3e655f
--- /dev/null
+++ b/components/ui/TrackVolumeSlider.tsx
@@ -0,0 +1,32 @@
+import { SliderControl } from "@/app/components/ui/SliderControl";
+import { AudioTrack } from "@/types/audio.types";
+import { useState, useEffect } from "react";
+
+export function TrackVolumeSlider({ track, onUpdateAudioTrack }: {
+ track: AudioTrack;
+ onUpdateAudioTrack: (id: string, updates: Partial<AudioTrack>) => void;
+}) {
+ const [internalVolume, setInternalVolume] = useState(track.volume * 100);
+
+ useEffect(() => {
+ const externalValue = track.volume * 100;
+ if (Math.abs(internalVolume - externalValue) > 1) {
+ setInternalVolume(externalValue);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [track.volume]);
+
+ return (
+ <SliderControl
+ icon="mdi:volume-medium"
+ label="Volumen"
+ value={internalVolume}
+ min={0}
+ max={100}
+ onChange={(value: number) => {
+ setInternalVolume(value);
+ onUpdateAudioTrack(track.id, { volume: value / 100 });
+ }}
+ />
+ );
+}
\ No newline at end of file
diff --git a/components/ui/dropdown-menu.tsx b/components/ui/dropdown-menu.tsx
index bffc327..637cc2e 100644
--- a/components/ui/dropdown-menu.tsx
+++ b/components/ui/dropdown-menu.tsx
@@ -42,7 +42,7 @@ function DropdownMenuContent({
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
+ "bg-black text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
@@ -230,7 +230,7 @@ function DropdownMenuSubContent({
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
+ "bg-black text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
diff --git a/components/ui/hover-card.tsx b/components/ui/hover-card.tsx
index 91e869c..6463246 100644
--- a/components/ui/hover-card.tsx
+++ b/components/ui/hover-card.tsx
@@ -32,7 +32,7 @@ function HoverCardContent({
align={align}
sideOffset={sideOffset}
className={cn(
- "z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
+ "z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border bg-black p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
diff --git a/components/ui/popover.tsx b/components/ui/popover.tsx
index 9519cc4..7dd8ce0 100644
--- a/components/ui/popover.tsx
+++ b/components/ui/popover.tsx
@@ -30,7 +30,7 @@ function PopoverContent({
align={align}
sideOffset={sideOffset}
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
+ "bg-black text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
diff --git a/components/ui/select.tsx b/components/ui/select.tsx
index fd01b74..dce1d0c 100644
--- a/components/ui/select.tsx
+++ b/components/ui/select.tsx
@@ -62,7 +62,7 @@ function SelectContent({
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
+ "bg-black text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className