Skip to content

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

feat: enhance SidebarTool with popover functionality and video previews

CristianOlivera1637f7209f115
diff --git a/app/components/ui/SidebarTool.tsx b/app/components/ui/SidebarTool.tsx
index adb8822..ba17efd 100644
--- a/app/components/ui/SidebarTool.tsx
+++ b/app/components/ui/SidebarTool.tsx
@@ -1,7 +1,18 @@
"use client";
import { Icon } from "@iconify/react";
-import { ReactNode, forwardRef } from "react";
+import { ReactNode, forwardRef, useState, useRef } from "react";
+import {
+ Popover,
+ PopoverTrigger,
+ PopoverContent,
+} from "@/components/ui/popover";
+
+interface PopoverConfig {
+ title: string;
+ description: string;
+ videoSrc?: string;
+}
interface SidebarToolProps {
icon: string | ReactNode;
@@ -11,71 +22,150 @@ interface SidebarToolProps {
badge?: string;
badgeCount?: number;
disabled?: boolean;
+ popover?: PopoverConfig;
}
export const SidebarTool = forwardRef<HTMLButtonElement, SidebarToolProps>(
- ({ icon, label, isActive, onClick, badge, badgeCount, disabled }, ref) => {
- return (
+ ({ icon, label, isActive, onClick, badge, badgeCount, disabled, popover }, ref) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+
+ const handleMouseEnter = () => {
+ if (disabled) return;
+ clearTimeout(timeoutRef.current);
+ setIsOpen(true);
+ };
+ const handleMouseLeave = () => {
+ timeoutRef.current = setTimeout(() => {
+ setIsOpen(false);
+ }, 150);
+ };
+
+ const ToolButton = (
<button
ref={ref}
onClick={disabled ? undefined : onClick}
disabled={disabled}
- className={`relative flex flex-col items-center gap-1.5 transition-all duration-200 group w-full
+ className={`relative flex flex-col items-center gap-1.5 transition-all duration-200 w-full
${disabled ? "opacity-40 cursor-not-allowed" : "cursor-pointer"}
- ${isActive ? "text-white" : "text-white/60 hover:text-white"}`
- }
- >
- {badgeCount !== undefined && badgeCount > 0 && (
- <div className="absolute -top-1 right-1 z-10 min-w-4 h-4 px-1 flex items-center justify-center bg-emerald-500 rounded-full border border-emerald-400 shadow-lg pointer-events-none animate-in zoom-in-50 duration-200">
- <span className="text-[9px] font-bold text-white leading-none">
- {badgeCount > 9 ? "9+" : badgeCount}
- </span>
- </div>
- )}
-
- {badge && (
- <div className="absolute -top-1 -right-0.5 z-10 px-1.5 py-0.5 bg-linear-to-r from-gray-500 to-gray-500 rounded-full border border-white/20 shadow-lg pointer-events-none">
- <span className="text-[8px] font-bold text-white tracking-widest uppercase block drop-shadow-sm leading-none">
- {badge}
- </span>
- </div>
- )}
-
- {isActive && !disabled && (
- <div className="absolute inset-x-0 top-0 h-px bg-linear-to-r from-transparent via-white/20 to-transparent mx-2" />
- )}
-
- <span
- className={`flex items-center justify-center p-3 squircle-element transition-all duration-200 group relative
- ${!disabled && isActive ? "" : "group-hover:bg-white/5"}
- `}
- style={isActive && !disabled ? {
- background: 'radial-gradient(circle at 50% 0%, #555555 0%, #454545 64%)',
- boxShadow: 'inset 0 1.01rem 0.2rem -1rem #fff, 0 0 0 1px #fff4, 0 4px 4px 0 #0004, 0 0 0 1px #333',
- } : {}}
+ ${isActive ? "text-white" : "text-white/60 hover:text-white"}`}
>
- <div className={`transition-transform duration-300 ${isActive && !disabled ? "scale-110" : !disabled ? "group-hover:scale-105" : ""}`}>
- {typeof icon === "string" ? (
- <Icon icon={icon} width="20" />
- ) : (
- <div className="w-5 h-5 flex items-center justify-center">
- {icon}
- </div>
- )}
- </div>
+ {badgeCount !== undefined && badgeCount > 0 && (
+ <div className="absolute -top-1 right-1 z-10 min-w-4 h-4 px-1 flex items-center justify-center bg-emerald-500 rounded-full border border-emerald-400 shadow-lg pointer-events-none animate-in zoom-in-50 duration-200">
+ <span className="text-[9px] font-bold text-white leading-none">
+ {badgeCount > 9 ? "9+" : badgeCount}
+ </span>
+ </div>
+ )}
+
+ {badge && (
+ <div className="absolute -top-1 -right-0.5 z-10 px-1.5 py-0.5 bg-linear-to-r from-gray-500 to-gray-500 rounded-full border border-white/20 shadow-lg pointer-events-none">
+ <span className="text-[8px] font-bold text-white tracking-widest uppercase block drop-shadow-sm leading-none">
+ {badge}
+ </span>
+ </div>
+ )}
{isActive && !disabled && (
- <div className="absolute left-1 w-8 h-2 top-1/5 -translate-y-1/2 size-3 bg-white rounded-full blur-[5px] rotate-45 opacity-50" />
+ <div className="absolute inset-x-0 top-0 h-px bg-linear-to-r from-transparent via-white/20 to-transparent mx-2" />
)}
- </span>
-
- {label && (
- <label className={`text-xs font-medium whitespace-nowrap overflow-hidden text-ellipsis max-w-full ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`}>
- {label}
- </label>
- )}
- </button>
- );
-});
+
+ <span
+ className={`flex items-center justify-center p-3 squircle-element transition-all duration-200 relative
+ ${!disabled && isActive ? "" : "hover:bg-white/5"}
+ `}
+ style={isActive && !disabled ? {
+ background: 'radial-gradient(circle at 50% 0%, #555555 0%, #454545 64%)',
+ boxShadow: 'inset 0 1.01rem 0.2rem -1rem #fff, 0 0 0 1px #fff4, 0 4px 4px 0 #0004, 0 0 0 1px #333',
+ } : {}}
+ >
+ <div className={`transition-transform duration-300 ${isActive && !disabled ? "scale-110" : !disabled ? "hover:scale-105" : ""}`}>
+ {typeof icon === "string" ? (
+ <Icon icon={icon} width="20" />
+ ) : (
+ <div className="w-5 h-5 flex items-center justify-center">
+ {icon}
+ </div>
+ )}
+ </div>
+
+ {isActive && !disabled && (
+ <div className="absolute left-1 w-8 h-2 top-1/5 -translate-y-1/2 size-3 bg-white rounded-full blur-[5px] rotate-45 opacity-50" />
+ )}
+ </span>
+
+ {label && (
+ <label className={`text-xs font-medium whitespace-nowrap overflow-hidden text-ellipsis max-w-full ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`}>
+ {label}
+ </label>
+ )}
+ </button>
+ );
+
+ if (!popover || disabled) {
+ return ToolButton;
+ }
+
+ return (
+ <Popover open={isOpen} onOpenChange={setIsOpen}>
+ <PopoverTrigger asChild>
+ <div
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ className="w-full flex justify-center"
+ >
+ {ToolButton}
+ </div>
+ </PopoverTrigger>
+
+ <PopoverContent
+ side="right"
+ sideOffset={16}
+ className="w-65 p-0 bg-[#09090B] border border-white/20 rounded-xl shadow-2xl overflow-hidden group/popover"
+ >
+ <div className="relative w-full aspect-3/4 flex flex-col justify-end overflow-hidden bg-[#0c0c0e]">
+
+ <div className="absolute inset-0 z-0">
+ <img
+ src="/images/pages/thumbnail-popover.avif"
+ className="w-full h-full object-cover blur-3xl opacity-40 scale-110"
+ alt="thumbnail-popover"
+ />
+ <div className="absolute inset-0 bg-[radial-gradient(circle_at_30%_30%,rgba(6,182,212,0.4)_0%,transparent_65%)] mix-blend-screen" />
+
+ <div className="absolute inset-0 bg-[radial-gradient(circle_at_70%_70%,rgba(147,51,234,0.15)_0%,transparent_60%)]" />
+ </div>
+
+ {isOpen && (
+ <video
+ src={popover.videoSrc}
+ poster="/images/pages/thumbnail-popover.avif"
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="absolute inset-0 w-full h-full object-cover mask-b-to-90% mask-b-from-90% z-10"
+ />
+ )}
+
+ <div className="absolute inset-0 z-20 bg-linear-to-t from-[#09090B] via-[#09090B]/60 to-transparent pointer-events-none" />
+
+ <div className="relative z-30 p-5">
+ <h3 className="text-sm font-bold text-white mb-1 drop-shadow-md">
+ {popover.title}
+ </h3>
+ <p className="text-[11px] text-cyan-50/50 leading-relaxed drop-shadow-md">
+ {popover.description}
+ </p>
+ </div>
+
+ <div className="absolute top-0 inset-x-0 h-px bg-linear-to-r from-transparent via-cyan-400/50 to-transparent z-40" />
+ </div>
+ </PopoverContent>
+
+ </Popover>
+ );
+ }
+);
SidebarTool.displayName = "SidebarTool";
\ No newline at end of file
diff --git a/app/components/ui/editor/ElementsMenu.tsx b/app/components/ui/editor/ElementsMenu.tsx
index a72ae1b..9a8e0d9 100644
--- a/app/components/ui/editor/ElementsMenu.tsx
+++ b/app/components/ui/editor/ElementsMenu.tsx
@@ -491,18 +491,17 @@ export function ElementsMenu({
</div>
<div className="grid grid-cols-6 gap-1.5">
{PINNED_IMAGE_ITEMS.map((item) => (
- <TooltipAction label={item.name} key={item.id}>
- <button
- onClick={() => handleAddImage(item)}
- className="aspect-square bg-white/3 hover:bg-white/8 border border-white/[0.07] hover:border-white/20 squircle-element flex items-center justify-center transition-all active:scale-90 overflow-hidden group"
- >
- <ProgressiveImg
- src={getImagePreviewPath(item)}
- alt={item.name}
- className="w-full h-full object-cover group-hover:scale-110"
- />
- </button>
- </TooltipAction>
+ <button
+ key={item.id}
+ onClick={() => handleAddImage(item)}
+ className="aspect-square bg-white/3 hover:bg-white/8 border border-white/[0.07] hover:border-white/20 squircle-element flex items-center justify-center transition-all active:scale-90 overflow-hidden group"
+ >
+ <ProgressiveImg
+ src={getImagePreviewPath(item)}
+ alt={item.name}
+ className="w-full h-full object-cover group-hover:scale-110"
+ />
+ </button>
))}
{Array.from({ length: Math.max(0, 11 - PINNED_IMAGE_ITEMS.length) }).map((_, i) => (
diff --git a/app/components/ui/editor/ToolsSidebar.tsx b/app/components/ui/editor/ToolsSidebar.tsx
index 38c6f42..8a86b77 100644
--- a/app/components/ui/editor/ToolsSidebar.tsx
+++ b/app/components/ui/editor/ToolsSidebar.tsx
@@ -180,12 +180,22 @@ export function ToolsSidebar({
label="Fondo"
isActive={activeTool === "screenshot"}
onClick={() => onToolChange("screenshot")}
+ popover={{
+ title: "Fondos y Lienzo",
+ description: "Añade gradientes, colores o imágenes",
+ videoSrc: "/videos/preview-background.mp4"
+ }}
/>
<SidebarTool
icon="hugeicons:ai-browser"
label="Mockup"
isActive={activeTool === "mockup"}
onClick={() => onToolChange("mockup")}
+ popover={{
+ title: "Generador de Mockups",
+ description: "Envuelve tus capturas en navegadores, dispositivos móviles o IDEs",
+ videoSrc: "/videos/preview-mockup.mp4"
+ }}
/>
<SidebarTool
icon="solar:video-library-outline"
@@ -194,12 +204,22 @@ export function ToolsSidebar({
onClick={() => onToolChange("videos")}
ref={videosToolRef}
badgeCount={activeTool !== "videos" ? newVideosCount : undefined}
+ popover={{
+ title: "Importar Videos",
+ description: "Sube tus grabaciones de pantalla o clips",
+ videoSrc: "/videos/preview-videos.mp4"
+ }}
/>
<SidebarTool
label="Elementos"
isActive={activeTool === "elements"}
onClick={() => onToolChange("elements")}
ref={elementsToolRef}
+ popover={{
+ title: "Elementos y Anotaciones",
+ description: "Añade flechas, formas geométricas, texto o resaltadores",
+ videoSrc: "/videos/preview-elements.mp4"
+ }}
icon={
<svg
width="24"
@@ -225,6 +245,11 @@ export function ToolsSidebar({
isActive={activeTool === "audio"}
onClick={() => onToolChange("audio")}
ref={audioToolRef}
+ // popover={{
+ // title: "Pistas y Efectos",
+ // description: "Sincroniza pistas de música de fondo o efectos de sonido (clics, notificaciones) para darle vida a tus videos.",
+ // videoSrc: "/videos/demo-audio.mp4"
+ // }}
/>
<SidebarTool
icon="iconamoon:zoom-in-bold"
@@ -232,6 +257,11 @@ export function ToolsSidebar({
isActive={activeTool === "zoom"}
onClick={() => onToolChange("zoom")}
ref={zoomToolRef}
+ // popover={{
+ // title: "Zoom Dinámico",
+ // description: "Crea acercamientos fluidos hacia partes específicas de la pantalla para guiar la atención del espectador.",
+ // videoSrc: "/videos/demo-zoom.mp4"
+ // }}
/>
<SidebarTool
icon="solar:videocamera-record-bold-duotone"
@@ -239,6 +269,11 @@ export function ToolsSidebar({
isActive={activeTool === "camera"}
onClick={() => onToolChange("camera")}
ref={cameraToolRef}
+ // popover={{
+ // title: "Cámara en pantalla",
+ // description: "Superpón la grabación de tu webcam con recortes circulares, marcos elegantes y fondos eliminados por IA.",
+ // videoSrc: "/videos/demo-camara.mp4"
+ // }}
/>
<SidebarTool
icon="solar:cursor-bold-duotone"
@@ -247,6 +282,11 @@ export function ToolsSidebar({
onClick={() => onToolChange("cursor")}
badge={!isCursorEnabled ? "Pronto" : undefined}
disabled={!isCursorEnabled}
+ // popover={!isCursorEnabled ? undefined : {
+ // title: "Cursores Inteligentes",
+ // description: "Suaviza el movimiento del ratón y añade efectos de clic estilo macOS para tutoriales más limpios.",
+ // videoSrc: "/videos/demo-cursor.mp4"
+ // }}
/>
<div className="shrink-0 h-12" aria-hidden="true" />
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 6bdb184..c75bc4c 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -1,10 +1,12 @@
"use client";
-import { useRef, useEffect, useImperativeHandle, forwardRef, useMemo, useState } from "react";
+import { useRef, useEffect, useImperativeHandle, forwardRef, useMemo, useState, useCallback } from "react";
import type { VideoCanvasHandle, VideoCanvasProps, VideoThumbnail } from "@/types";
import type { ImageElement, SvgElement, CanvasElement } from "@/types/canvas-elements.types";
import { getCameraLayout } from "@/types/camera.types";
import { ASPECT_RATIO_DIMENSIONS } from "@/types";
+// import { interpolateCursorPosition, DEFAULT_CURSOR_CONFIG, EMPTY_CURSOR_DATA } from "@/types/cursor.types";
+// import type { CursorKeyframe } from "@/types/cursor.types";
import { getWallpaperUrl } from "@/lib/wallpaper.utils";
import { drawRoundedRect, drawRoundedRectBottomOnly, calculateScaledPadding, applyCanvasBackground, getAspectRatioStyle, getMaxWidth, Corner, getCornerStyle, getNearestCorner } from "@/lib/canvas.utils";
import { drawMockupToCanvas } from "@/lib/mockup-canvas.utils";
@@ -14,7 +16,8 @@ import PlaceholderEditor from "../PlaceholderEditor";
import { MockupWrapper } from "./mockups/MockupWrapper";
import { DEFAULT_MOCKUP_CONFIG } from "@/types/mockup.types";
import { calculateSmoothZoom } from "@/lib/canvas.utils";
-import { getSvgDataUrl } from "@/components/canvas-svg";
+import { SVG_COMPONENTS, getSvgDataUrl } from "@/components/canvas-svg";
+// import { getCursorSvgDataUrl } from "@/components/cursor-svg";
import { VIDEO_Z_INDEX, BOTTOM_ONLY_RADIUS_MOCKUPS, SELF_SHADOWING_MOCKUPS } from "@/lib/constants";
import { RotationHandleIcon } from "@/components/ui/RotationHandleIcon";
import { CanvasElementsLayer } from "./CanvasElementsLayer";
@@ -53,6 +56,10 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
selectedElementId = null,
onElementUpdate,
onElementSelect,
+ // Cursor props
+ // cursorConfig = DEFAULT_CURSOR_CONFIG,
+ // cursorData = EMPTY_CURSOR_DATA,
+ // Camera overlay props
cameraUrl = null,
cameraConfig = null,
onCameraConfigChange,
@@ -75,6 +82,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// Calculate zoom transform for visual preview using 3-phase system
// Phase 1: Entry (zoom in), Phase 2: Hold with optional movement, Phase 3: Exit (zoom out)
const zoomTransform = useMemo(() => {
+ // No active fragment - smooth exit to base scale
if (!activeZoomFragment) {
const lastFragment = zoomFragments
.filter(f => f.endTime < currentTime)
@@ -100,6 +108,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const translateY = (50 - phaseState.focusY) * (phaseState.scale - 1) * 2;
// During hold phase with movement, reduce transition to avoid jarring
+ // CSS transitions should only apply to scale (entry/exit), not translate during movement
const isMoving = activeZoomFragment.movementEnabled && phaseState.phase === 'hold';
const transitionMs = isMoving ? 50 : speedToTransitionMs(activeZoomFragment.speed);
@@ -115,6 +124,34 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
};
}, [activeZoomFragment, zoomFragments, currentTime]);
+ // Calculate current cursor position from cursor data
+ /*const cursorPosition = useMemo<CursorKeyframe | null>(() => {
+ if (!cursorConfig.visible || cursorConfig.style === "none" || !cursorData.hasCursorData) {
+ return null;
+ }
+ return interpolateCursorPosition(cursorData.keyframes, currentTime, cursorConfig.smoothing);
+ }, [cursorConfig.visible, cursorConfig.style, cursorConfig.smoothing, cursorData.hasCursorData, cursorData.keyframes, currentTime]);*/
+
+ // Get cursor SVG data URL for rendering
+ /*const cursorSvgDataUrl = useMemo(() => {
+ if (!cursorPosition || cursorConfig.style === "none") return null;
+ return getCursorSvgDataUrl(cursorConfig.style, cursorPosition.state, cursorConfig.color, cursorConfig.size);
+ }, [cursorPosition, cursorConfig.style, cursorConfig.color, cursorConfig.size]);*/
+
+ // Preload cursor image for canvas rendering
+ /* const cursorImageRef = useRef<HTMLImageElement | null>(null);
+ useEffect(() => {
+ if (cursorSvgDataUrl) {
+ const img = new Image();
+ img.src = cursorSvgDataUrl;
+ img.onload = () => {
+ cursorImageRef.current = img;
+ };
+ } else {
+ cursorImageRef.current = null;
+ }
+ }, [cursorSvgDataUrl]);*/
+
// Determinar qué background mostrar basado en el tab activo
const shouldShowUnsplashOverride = backgroundTab === "wallpaper" && unsplashOverrideUrl !== "";
const shouldShowWallpaper = backgroundTab === "wallpaper" && selectedWallpaper >= 0 && !shouldShowUnsplashOverride;
@@ -137,21 +174,59 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
return dims || { width: 1920, height: 1080 };
}, [aspectRatio, customAspectRatio]);
+ // On-canvas controls state
const [isVideoHovered, setIsVideoHovered] = useState(false);
// 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);
+
+ // Reset lastSetVideoUrlRef when mockupId changes to force src re-assignment on remount
+ useEffect(() => {
+ lastSetVideoUrlRef.current = null;
+ }, [mockupId]);
+
useEffect(() => {
- if (videoRef.current && videoUrl && videoUrl !== lastSetVideoUrlRef.current) {
- if (!videoRef.current.src || videoRef.current.src === '' || videoRef.current.src === window.location.href) {
+ if (videoRef.current && videoUrl) {
+ // Always set src if video element has no src, src is empty, or we just changed mockup
+ const videoSrc = videoRef.current.src;
+ const needsSrc = !videoSrc || videoSrc === '' || videoSrc === window.location.href;
+ const isNewUrl = videoUrl !== lastSetVideoUrlRef.current;
+
+ if (needsSrc || isNewUrl) {
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;
+ if (playing) {
+ videoRef.current.play().catch(() => {
+ // Ignore play errors (may happen if video not ready)
+ });
+ }
+ preservedVideoStateRef.current = null;
+ }
}
}
if (!videoUrl) {
lastSetVideoUrlRef.current = null;
}
- }, [videoUrl, videoRef]);
+ }, [videoUrl, videoRef, mockupId]);
+
+ // 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,
+ playing: !videoRef.current.paused,
+ };
+ }
+ };
+ }, [mockupId, videoUrl, videoRef]);
const [isDraggingVideo, setIsDraggingVideo] = useState(false);
const [isDraggingRotation, setIsDraggingRotation] = useState(false);
const [videoHoverCorner, setVideoHoverCorner] = useState<Corner>("top-right");
@@ -183,6 +258,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
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());
+ // Cursor image cache keyed by data URL — avoids new Image() + decode per frame
+ // const cursorImageCacheRef = useRef<Map<string, HTMLImageElement>>(new Map());
// Actualizar canvas dimensions cuando cambia el aspect ratio
useEffect(() => {
@@ -624,6 +701,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const backgroundImage = (shouldShowCustomImage || shouldShowUnsplashOverride) ? customImageRef.current : (shouldShowWallpaper ? wallpaperImageRef.current : null);
+ // 1. Dibujar fondo
if (shouldShowCustomColor && backgroundColorCss) {
applyCanvasBackground(ctx, backgroundColorCss, canvasWidth, canvasHeight);
} else if (backgroundImage) {
@@ -646,8 +724,10 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
ctx.restore();
}
+ // 2. Render elements BEHIND video (zIndex < VIDEO_Z_INDEX) - before video transform
await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, true);
+ // 3. Calcular área disponible para el mockup/video
const availableWidth = canvasWidth - scaledPaddingX * 2;
const availableHeight = canvasHeight - scaledPaddingY * 2;
@@ -776,6 +856,85 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// 8. Render elements ABOVE video (zIndex >= VIDEO_Z_INDEX)
await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, false);
+ // 9. Render cursor overlay if enabled and data available
+ /* if (cursorConfig.visible && cursorConfig.style !== "none" && cursorData.hasCursorData) {
+ const frameTime = video.currentTime;
+ const cursorPos = interpolateCursorPosition(cursorData.keyframes, frameTime, cursorConfig.smoothing);
+
+ if (cursorPos) {
+ // Get cursor image from cache
+ const cursorDataUrl = getCursorSvgDataUrl(cursorConfig.style, cursorPos.state, cursorConfig.color, cursorConfig.size);
+ if (cursorDataUrl) {
+ let cursorImg = cursorImageCacheRef.current.get(cursorDataUrl);
+ if (!cursorImg) {
+ cursorImg = new Image();
+ cursorImageCacheRef.current.set(cursorDataUrl, cursorImg);
+ cursorImg.src = cursorDataUrl;
+ await new Promise<void>((resolve) => {
+ if (cursorImg!.complete) resolve();
+ else { cursorImg!.onload = () => resolve(); cursorImg!.onerror = () => resolve(); }
+ });
+ } else if (!cursorImg.complete) {
+ await new Promise<void>((resolve) => {
+ cursorImg!.onload = () => resolve();
+ cursorImg!.onerror = () => resolve();
+ setTimeout(resolve, 500);
+ });
+ }
+
+ // Calculate cursor position relative to the video area
+ // The cursor positions stored are percentages of the video dimensions
+ const cursorX = videoX + (cursorPos.x / 100) * videoWidth;
+ const cursorY = videoY + (cursorPos.y / 100) * videoHeight;
+
+ // Scale cursor size based on canvas dimensions
+ const cursorScale = canvasWidth / 1920; // Reference 1920px
+ const scaledCursorSize = cursorConfig.size * cursorScale;
+
+ ctx.save();
+ ctx.globalAlpha = 1;
+
+ // Draw click effect if clicking
+ if (cursorPos.clicking && cursorConfig.clickEffect !== "none") {
+ ctx.save();
+ const effectSize = scaledCursorSize * 2;
+
+ if (cursorConfig.clickEffect === "ripple") {
+ // Ripple effect - expanding circles
+ ctx.beginPath();
+ ctx.arc(cursorX, cursorY, effectSize, 0, Math.PI * 2);
+ ctx.strokeStyle = cursorConfig.clickEffectColor;
+ ctx.lineWidth = 3 * cursorScale;
+ ctx.globalAlpha = 0.5;
+ ctx.stroke();
+ } else if (cursorConfig.clickEffect === "ring") {
+ // Ring effect - solid ring
+ ctx.beginPath();
+ ctx.arc(cursorX, cursorY, effectSize * 0.8, 0, Math.PI * 2);
+ ctx.strokeStyle = cursorConfig.clickEffectColor;
+ ctx.lineWidth = 4 * cursorScale;
+ ctx.globalAlpha = 0.7;
+ ctx.stroke();
+ }
+
+ ctx.restore();
+ }
+
+ // Draw cursor image
+ // Cursor hotspot is typically at top-left for arrow cursors
+ ctx.drawImage(
+ cursorImg,
+ cursorX,
+ cursorY,
+ scaledCursorSize,
+ scaledCursorSize
+ );
+
+ ctx.restore();
+ }
+ }
+ }*/
+
ctx.restore();
// 10. Camera overlay — drawn in screen space AFTER zoom transform is unwound,
@@ -784,6 +943,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
};
// Draw the camera bubble in screen-space coordinates.
+ // Runs after the zoom ctx.restore() so position/size are unaffected by zoom.
const drawCameraOverlay = async (
ctx: CanvasRenderingContext2D,
canvasWidth: number,
@@ -791,51 +951,40 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
) => {
const camVideo = cameraVideoRef.current;
const mainVideo = videoRef.current;
-
if (!camVideo || !cameraConfig || !cameraConfig.enabled) return;
+ if (camVideo.readyState < 2 || !camVideo.videoWidth || !camVideo.videoHeight) return;
- if (!camVideo.videoWidth || !camVideo.videoHeight) return;
-
- if (mainVideo && camVideo.duration > 0 && mainVideo.currentTime > camVideo.duration - 0.1) return;
-
- if (mainVideo && camVideo.paused) {
- const diff = Math.abs(camVideo.currentTime - mainVideo.currentTime);
-
- if (diff > 0.05) {
- try {
- const targetTime = Math.min(
- mainVideo.currentTime,
- camVideo.duration - 0.05
- );
- camVideo.currentTime = targetTime;
+ // Guard against camera video being shorter than main video
+ if (mainVideo && camVideo.duration > 0 && mainVideo.currentTime > camVideo.duration - 0.1) {
+ return; // Skip drawing camera if we're beyond its duration
+ }
- // Esperar seeked + readyState
- await new Promise<void>((resolve) => {
- const fallbackTimeout = setTimeout(() => {
- camVideo.removeEventListener("seeked", onSeeked);
- resolve();
- }, 400);
-
- const onSeeked = () => {
- camVideo.removeEventListener("seeked", onSeeked);
-
- const checkReady = setInterval(() => {
- if (camVideo.readyState >= 3) {
- clearInterval(checkReady);
- clearTimeout(fallbackTimeout);
- resolve();
- }
- }, 10);
- };
-
- camVideo.addEventListener("seeked", onSeeked);
- });
- } catch {
- // continuar con el frame disponible
- }
+ // During export, main video seeks frame-by-frame; event-driven sync can leave the
+ // camera one frame behind. Nudge the camera to the main video's time and await
+ // the resulting seek so drawImage picks up the correct frame.
+ if (mainVideo && Math.abs(camVideo.currentTime - mainVideo.currentTime) > 0.05) {
+ try {
+ // Clamp camera seek to its actual duration
+ const targetTime = Math.min(mainVideo.currentTime, camVideo.duration - 0.05);
+ camVideo.currentTime = targetTime;
+ await new Promise<void>((resolve) => {
+ const done = () => {
+ camVideo.removeEventListener("seeked", done);
+ resolve();
+ };
+ camVideo.addEventListener("seeked", done);
+ // Guard against events that never fire (e.g., paused camera at end)
+ setTimeout(() => {
+ camVideo.removeEventListener("seeked", done);
+ resolve();
+ }, 100);
+ });
+ } catch {
+ // continue with whatever frame is available
}
}
+ // Double-check readyState after async seek
if (camVideo.readyState < 2) return;
const { size, left: drawX, top: drawY } = getCameraLayout(
@@ -843,22 +992,28 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
canvasWidth,
canvasHeight
);
-
if (size <= 0) return;
-
const shortSide = Math.min(canvasWidth, canvasHeight);
- const sizePercent = cameraConfig.size * 100;
+
+ // Escala el radio dinámicamente (igual que en preview)
+ const sizePercent = cameraConfig.size * 100; // 0.18 → 18
const sizeMultiplier = 0.5 + (sizePercent - 20) / 40;
+
+ // Center-crop the camera frame to a square
const srcShort = Math.min(camVideo.videoWidth, camVideo.videoHeight);
const sx = (camVideo.videoWidth - srcShort) / 2;
const sy = (camVideo.videoHeight - srcShort) / 2;
ctx.save();
+
+ // Drop shadow to match preview styling
ctx.shadowColor = "rgba(0, 0, 0, 0.55)";
ctx.shadowBlur = shortSide * 0.02;
ctx.shadowOffsetY = shortSide * 0.008;
+ // Create clipping path based on shape
if (cameraConfig.shape === "circle") {
+ // Perfect circle using arc
const centerX = drawX + size / 2;
const centerY = drawY + size / 2;
const radius = size / 2;
@@ -875,9 +1030,11 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
ctx.clip();
} else {
- const radius = cameraConfig.shape === "squircle"
- ? Math.round(80 * sizeMultiplier)
- : Math.round(6 * sizeMultiplier);
+ // Squircle or square with rounded corners
+ const radius =
+ cameraConfig.shape === "squircle"
+ ? Math.round(20 * sizeMultiplier)
+ : Math.round(6 * sizeMultiplier);
drawRoundedRect(ctx, drawX, drawY, size, size, radius);
ctx.fill();
@@ -901,6 +1058,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
ctx.restore();
};
+ // Exponer métodos para exportación
useImperativeHandle(ref, () => ({
getExportCanvas: () => exportCanvasRef.current,
drawFrame,
@@ -950,7 +1108,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
transition: zoomTransform.isMoving
? `transform ${zoomTransform.transitionMs}ms linear`
: `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
- transformStyle: 'preserve-3d',
+ transformStyle: 'preserve-3d', // ← mover aquí desde el div hijo
}}
>
{/* 3D rotation layer */}
@@ -961,6 +1119,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
? `rotateX(${zoomTransform.rotateX}deg) rotateY(${zoomTransform.rotateY}deg)`
: 'none',
transition: `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
+ // ← quitar transformStyle de aquí
}}
>
{/* Capa 1: Fondo (siempre llena todo el contenedor) */}
@@ -972,19 +1131,19 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
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',
@@ -1033,6 +1192,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
onMouseLeave={() => setIsVideoHovered(false)}
onMouseDown={(e) => {
if (!videoUrl || !onVideoTransformChange) return;
+ // Only start dragging if not clicking on rotation handle
if ((e.target as HTMLElement).closest('[data-rotation-handle]')) return;
e.preventDefault();
@@ -1048,6 +1208,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
onMouseMove={(e) => { if (videoUrl) setVideoHoverCorner(getNearestCorner(e, videoTransform.rotation)); }}
>
<div className="relative">
+ {/* Rotation handle */}
{isVideoHovered && videoUrl && onVideoTransformChange && (
<div
data-rotation-handle style={getCornerStyle(videoHoverCorner, -14)}
@@ -1081,14 +1242,16 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
shadows={shadows}
>
{videoUrl ? (
- <div className="relative flex items-center justify-center overflow-hidden max-w-full max-h-full rounded-[inherit]"
- >
+ <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="max-w-full max-h-full object-contain"
+ 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}%)`,
} : {}),
@@ -1119,8 +1282,10 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
</div>
</div>
</div>
+ {/* End zoom transform div */}
</div>
</div>
+ {/* End perspective wrapper div */}
{/* Capa 3: Canvas elements ABOVE video (zIndex >= VIDEO_Z_INDEX) */}
<CanvasElementsLayer
canvasContainerRef={canvasContainerRef}
@@ -1145,16 +1310,12 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
style={{ zIndex: 4 }}
>
<div
- tabIndex={0} // Permite que el elemento reciba foco (se seleccione)
onClick={() => {
if (onCameraClick) {
onCameraClick();
}
}}
onPointerDown={(e) => {
- // Al hacer click o empezar a arrastrar, le damos el foco instantáneo
- e.currentTarget.focus();
-
if (!onCameraConfigChange || !cameraConfig) return;
if (e.button !== 0) return;
const container = previewContainerRef.current;
@@ -1173,8 +1334,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
}}
onPointerMove={(e) => {
const drag = cameraDragRef.current;
- if (!drag || drag.pointerId !== e.pointerId || !onCameraConfigChange)
- return;
+ if (!drag || drag.pointerId !== e.pointerId || !onCameraConfigChange) return;
const dx = (e.clientX - drag.startX) / drag.rect.width;
const dy = (e.clientY - drag.startY) / drag.rect.height;
const nextX = Math.min(1, Math.max(0, drag.initialX + dx));
@@ -1198,33 +1358,15 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
cameraDragRef.current = null;
setIsDraggingCamera(false);
}}
- className={`absolute pointer-events-auto select-none group focus:outline-none ${onCameraConfigChange
- ? isDraggingCamera
- ? "cursor-grabbing"
- : "cursor-grab"
- : ""
+ className={`absolute pointer-events-auto select-none group ${onCameraConfigChange ? (isDraggingCamera ? "cursor-grabbing" : "cursor-grab") : ""
}`}
style={{
width: `${cameraConfig.size * 100}cqmin`,
aspectRatio: "1 / 1",
- left: `clamp(0px, calc(${cameraConfig.position.x * 100}% - ${cameraConfig.size * 50
- }cqmin), calc(100% - ${cameraConfig.size * 100}cqmin))`,
- top: `clamp(0px, calc(${cameraConfig.position.y * 100}% - ${cameraConfig.size * 50
- }cqmin), calc(100% - ${cameraConfig.size * 100}cqmin))`,
- transition: isDraggingCamera
- ? "none"
- : "left 120ms ease, top 120ms ease",
+ left: `clamp(0px, calc(${cameraConfig.position.x * 100}% - ${cameraConfig.size * 50}cqmin), calc(100% - ${cameraConfig.size * 100}cqmin))`,
+ top: `clamp(0px, calc(${cameraConfig.position.y * 100}% - ${cameraConfig.size * 50}cqmin), calc(100% - ${cameraConfig.size * 100}cqmin))`,
+ transition: isDraggingCamera ? "none" : "left 120ms ease, top 120ms ease",
touchAction: "none",
- borderRadius:
- cameraConfig.shape === "circle"
- ? "50%"
- : cameraConfig.shape === "squircle"
- ? `${Math.round(
- 20 * (0.5 + (cameraConfig.size * 100 - 20) / 40)
- )}px`
- : `${Math.round(
- 6 * (0.5 + (cameraConfig.size * 100 - 20) / 40)
- )}px`,
}}
>
<video
@@ -1232,16 +1374,62 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
muted
playsInline
preload="auto"
- className={`size-full object-cover shadow-[0_8px_30px_rgba(0,0,0,0.45)] transition-all duration-150 ring-1 ring-white/10 group-hover:ring-1 group-hover:ring-white group-focus:ring-2 group-focus:ring-[#0066FF] group-focus:shadow-[0_0_0_4px_rgba(0,102,255,0.15)] ${cameraConfig.shape === "squircle" ? "squircle-element-camera" : ""
+ className={`size-full object-cover shadow-[0_8px_30px_rgba(0,0,0,0.45)] ring-1 ring-white/15 ${cameraConfig.shape === "squircle" ? "squircle-element-camera" : ""
}`}
style={{
- borderRadius: "inherit",
+ borderRadius:
+ cameraConfig.shape === "circle"
+ ? "50%"
+ : cameraConfig.shape === "squircle"
+ ? `${Math.round(20 * (0.5 + (cameraConfig.size * 100 - 20) / 40))}px`
+ : `${Math.round(6 * (0.5 + (cameraConfig.size * 100 - 20) / 40))}px`,
transform: cameraConfig.mirror ? "scaleX(-1)" : undefined,
}}
/>
</div>
</div>
)}
+ {/* Capa 5: Cursor overlay for preview */}
+ {/* {cursorPosition && cursorSvgDataUrl && cursorConfig.visible && cursorConfig.style !== "none" && (
+ <div
+ className="absolute inset-0 pointer-events-none"
+ style={{
+ zIndex: 4,
+ padding: `${padding * 0.5}%`,
+ }}
+ >
+ <div className="relative w-full h-full">
+ {cursorPosition.clicking && cursorConfig.clickEffect !== "none" && (
+ <div
+ className="absolute rounded-full animate-ping"
+ style={{
+ left: `${cursorPosition.x}%`,
+ top: `${cursorPosition.y}%`,
+ width: cursorConfig.size * 2,
+ height: cursorConfig.size * 2,
+ transform: 'translate(-50%, -50%)',
+ backgroundColor: cursorConfig.clickEffectColor,
+ opacity: cursorConfig.clickEffect === "ripple" ? 0.3 : 0.5,
+ }}
+ />
+ )}
+ <img
+ src={cursorSvgDataUrl}
+ alt="cursor"
+ className="absolute pointer-events-none"
+ style={{
+ left: `${cursorPosition.x}%`,
+ top: `${cursorPosition.y}%`,
+ width: cursorConfig.size,
+ height: cursorConfig.size,
+ // Cursor hotspot at top-left for arrow cursors
+ transform: 'translate(0, 0)',
+ transition: cursorConfig.smoothing > 50 ? `all ${cursorConfig.smoothing}ms ease-out` : 'none',
+ }}
+ />
+ </div>
+ </div>
+ )} */}
</div>
</div>
</div>
diff --git a/public/images/pages/thumbnail-popover.avif b/public/images/pages/thumbnail-popover.avif
new file mode 100644
index 0000000..ac4af48
Binary files /dev/null and b/public/images/pages/thumbnail-popover.avif differ
diff --git a/public/videos/preview-background.mp4 b/public/videos/preview-background.mp4
new file mode 100644
index 0000000..b52e21f
Binary files /dev/null and b/public/videos/preview-background.mp4 differ
diff --git a/public/videos/preview-elements.mp4 b/public/videos/preview-elements.mp4
new file mode 100644
index 0000000..4afb7ca
Binary files /dev/null and b/public/videos/preview-elements.mp4 differ
diff --git a/public/videos/preview-mockup.mp4 b/public/videos/preview-mockup.mp4
new file mode 100644
index 0000000..c5a26ee
Binary files /dev/null and b/public/videos/preview-mockup.mp4 differ
diff --git a/public/videos/preview-videos.mp4 b/public/videos/preview-videos.mp4
new file mode 100644
index 0000000..282a72d
Binary files /dev/null and b/public/videos/preview-videos.mp4 differ