Create professional demos and 3D mockups in seconds, directly in your browser
feat: enhance MockupMenu with mediaType support and improve device scrolling
CristianOlivera14cbaa7826e59
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsxindex 90f7c0d..bee588a 100644--- a/app/[locale]/(editor)/editor/page.tsx+++ b/app/[locale]/(editor)/editor/page.tsx@@ -458,7 +458,6 @@ export default function Editor() {height: currentProject.imageHeight,});- // ── Restore motion / 3D device mockup state ────────────────────────if (currentProject.imagePhoneActive !== undefined) {setImagePhoneActive(currentProject.imagePhoneActive);}@@ -865,7 +864,6 @@ export default function Editor() {setTimeout(() => setImageExportProgress({ status: "idle", progress: 0, message: "" }), 4000);}}, [imageUrl, imageDimensions, selectedWallpaper, aspectRatio, customDimensions, selectedElementId, selectCanvasElement]);- // Generate canvas snapshot for photo mode previewsuseEffect(() => {if (!isPhotoMode || !imageUrl || !canvasRef.current) {setCanvasImageUrl(null);@@ -874,7 +872,7 @@ export default function Editor() {const generateSnapshot = async () => {try {- await canvasRef.current?.drawFrame();+ await canvasRef.current?.drawFrame(false);const exportCanvas = canvasRef.current?.getExportCanvas();if (exportCanvas) {const dataUrl = exportCanvas.toDataURL("image/png", 0.8);@@ -988,7 +986,10 @@ export default function Editor() {}}}, [audioTracks, masterVolume]);-+ const selectedCanvasElement = useMemo(+ () => canvasElements.find(el => el.id === selectedElementId) ?? null,+ [canvasElements, selectedElementId]+ );// Sync audio playback with video current timeconst syncAudioPlayback = useCallback((videoTime: number, playing: boolean) => {if (isExportingRef.current) return;@@ -3047,7 +3048,7 @@ export default function Editor() {initialMockupMenuPage={initialMockupMenuPage}mockupMenuNavigationToken={mockupMenuNavigationToken}onAddCanvasElement={addCanvasElement}- selectedCanvasElement={canvasElements.find(el => el.id === selectedElementId) || null}+ selectedCanvasElement={selectedCanvasElement}onUpdateCanvasElement={updateCanvasElement}onDeleteCanvasElement={deleteCanvasElement}onBringToFront={bringToFront}@@ -3336,7 +3337,7 @@ export default function Editor() {onMockupChange={handleMockupChange}onMockupConfigChange={handleMockupConfigChange}onAddCanvasElement={addCanvasElement}- selectedCanvasElement={canvasElements.find(el => el.id === selectedElementId) || null}+ selectedCanvasElement={selectedCanvasElement}onUpdateCanvasElement={updateCanvasElement}onDeleteCanvasElement={deleteCanvasElement}onBringToFront={bringToFront}diff --git a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx b/app/components/ui/editor/IPhone13ProMax3DViewer.tsxindex 31ef412..873efe1 100644--- a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx+++ b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx@@ -2,7 +2,7 @@import { Canvas, useThree, useFrame } from "@react-three/fiber";import { PerspectiveCamera, useGLTF, Environment, OrbitControls, ContactShadows } from "@react-three/drei";-import { useEffect, useRef, useState, Suspense } from "react";+import { useEffect, useRef, useState, Suspense, useLayoutEffect } from "react";import * as THREE from "three";import {createCoverScreenCanvas,@@ -40,6 +40,7 @@ interface Props {const TEX_W = 1284 * 2;const TEX_H = 2778 * 2;+const PLACEHOLDER_PHONE_URL = "/images/mockups-3d/placeholder-phone.avif";useGLTF.preload("/models/apple_iphone_13_pro_max.glb");@@ -145,6 +146,8 @@ function ModelScene({const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | null>(null);const videoTextureRef = useRef<THREE.VideoTexture | null>(null);const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D();+ const onApiRef = useRef(onApi);+ useLayoutEffect(() => { onApiRef.current = onApi; });useFrame(() => {if (videoElement && videoTextureRef.current) {@@ -153,35 +156,40 @@ function ModelScene({});useEffect(() => {- const previewW = gl.domElement.clientWidth;- const previewH = gl.domElement.clientHeight;+ const capturedOnApi = onApiRef.current;+ const RENDER_PIXEL_RATIO = 2;const api: IPhone13ProMax3DApi = {renderAt: (w, h) => {const cam = cameraRef.current ?? camera;if (!cam) return;- (cam as THREE.PerspectiveCamera).aspect = w / h;++ const maxTexSize = gl.capabilities.maxTextureSize || 4096;+ const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;+ const safeW = Math.max(1, Math.min(Math.round(w), maxDim));+ const safeH = Math.max(1, Math.min(Math.round(h), maxDim));++ (cam as THREE.PerspectiveCamera).aspect = safeW / safeH;(cam as THREE.PerspectiveCamera).updateProjectionMatrix();- gl.setPixelRatio(2);- gl.setSize(w, h, false);- if (videoTextureRef.current) {- videoTextureRef.current.needsUpdate = true;- }+ gl.setPixelRatio(RENDER_PIXEL_RATIO);+ gl.setSize(safeW, safeH, false);+ if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;gl.render(scene, cam);},restorePreview: () => {const cam = cameraRef.current ?? camera;if (!cam) return;- const previewAspect = previewW / previewH;- (cam as THREE.PerspectiveCamera).aspect = previewAspect;+ const freshW = gl.domElement.clientWidth;+ const freshH = gl.domElement.clientHeight;+ (cam as THREE.PerspectiveCamera).aspect = freshW / freshH;(cam as THREE.PerspectiveCamera).updateProjectionMatrix();gl.setPixelRatio(3);- gl.setSize(previewW, previewH, false);+ gl.setSize(freshW, freshH, false);},hasBuiltInShadow: true,};- onApi?.(api);- return () => onApi?.(null);- }, [gl, scene, camera, cameraRef, onApi]);+ capturedOnApi?.(api);+ return () => capturedOnApi?.(null);+ }, [gl, scene, camera, cameraRef]);useEffect(() => {onLoaded?.();@@ -244,14 +252,45 @@ function ModelScene({const cropKey = cropArea ? JSON.stringify(cropArea) : null;if (!imageUrl) {- if (mat.map) {- mat.map.dispose();- mat.map = null;+ const placeholderKey = `__placeholder__:${PLACEHOLDER_PHONE_URL}`;+ if (lastLoadedImageUrlRef.current === placeholderKey) return;++ const img = new Image();+ img.crossOrigin = "anonymous";+ img.onload = () => {+ const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, null);++ if (mat.map) {+ mat.map.dispose();+ mat.map = null;+ }++ const tex = new THREE.CanvasTexture(cover);+ tex.flipY = true;+ tex.colorSpace = THREE.SRGBColorSpace;+ tex.generateMipmaps = true;+ tex.minFilter = THREE.LinearMipmapLinearFilter;+ tex.magFilter = THREE.LinearFilter;+ tex.wrapS = THREE.ClampToEdgeWrapping;+ tex.wrapT = THREE.ClampToEdgeWrapping;+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();+ mat.map = tex;mat.needsUpdate = true;- }- lastLoadedImageUrlRef.current = null;- lastLoadedMaskKeyRef.current = null;- lastLoadedCropKeyRef.current = null;++ lastLoadedImageUrlRef.current = placeholderKey;+ lastLoadedMaskKeyRef.current = null;+ lastLoadedCropKeyRef.current = null;+ };+ img.onerror = () => {+ if (mat.map) {+ mat.map.dispose();+ mat.map = null;+ }+ mat.color.set(0x1a1a1a);+ mat.needsUpdate = true;+ lastLoadedImageUrlRef.current = placeholderKey;+ };+ img.src = PLACEHOLDER_PHONE_URL;return;}@@ -355,7 +394,6 @@ function ModelScene({<directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" /><directionalLight position={[0, -5, 5]} intensity={0.35} />- {/* Contact shadow rendered inside the WebGL scene for export fidelity */}{showContactShadow && (<ContactShadowsposition={[0, -0.55, 0]}diff --git a/app/components/ui/editor/Laptop3DViewer.tsx b/app/components/ui/editor/Laptop3DViewer.tsxindex 9bf3be1..4e5b593 100644--- a/app/components/ui/editor/Laptop3DViewer.tsx+++ b/app/components/ui/editor/Laptop3DViewer.tsx@@ -2,7 +2,7 @@import { Canvas, useThree, useFrame } from "@react-three/fiber";import { PerspectiveCamera, Environment, OrbitControls } from "@react-three/drei";-import { useEffect, useRef, useState, Suspense, useCallback } from "react";+import { useEffect, useRef, useState, Suspense, useCallback, useLayoutEffect } from "react";import * as THREE from "three";import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";import {@@ -30,6 +30,7 @@ const screenSize: [number, number] = [29.4, 20];const LID_CLOSED_X = Math.PI * 0.5;const LID_OPEN_X = -0.2 * Math.PI;const DEG = Math.PI / 180;+const PLACEHOLDER_LAPTOP_URL = "/images/mockups-3d/placeholder-laptop.avif";const lerp = (a: number, b: number, t: number) => a + (b - a) * t;@@ -101,6 +102,8 @@ function ModelScene({const videoTextureRef = useRef<THREE.VideoTexture | null>(null);const lastLoadedUrlRef = useRef<string | null>(null);const lastLoadedCropKeyRef = useRef<string | null>(null);+ const onApiRef = useRef(onApi);+ useLayoutEffect(() => { onApiRef.current = onApi; });const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D({defaultEnvironment: "forest"@@ -113,33 +116,33 @@ function ModelScene({});useEffect(() => {- const previewW = RENDER_W;- const previewH = RENDER_H;+ const capturedOnApi = onApiRef.current;const api: Laptop3DApi = {renderAt: (w, h) => {- if (!cameraRef.current) return;- cameraRef.current.aspect = w / h;- cameraRef.current.updateProjectionMatrix();-+ const cam = cameraRef.current ?? camera;+ if (!cam) return;+ (cam as THREE.PerspectiveCamera).aspect = w / h;+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();gl.setPixelRatio(2);gl.setSize(w, h, false);- if (videoTextureRef.current) {- videoTextureRef.current.needsUpdate = true;- }- gl.render(scene, cameraRef.current);+ if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;+ gl.render(scene, cam);},restorePreview: () => {- if (!cameraRef.current) return;- cameraRef.current.aspect = RENDER_W / RENDER_H;- cameraRef.current.updateProjectionMatrix();- gl.setPixelRatio(RENDER_MULTIPLIER);- gl.setSize(RENDER_W, RENDER_H, false);+ const cam = cameraRef.current ?? camera;+ if (!cam) return;+ const freshW = gl.domElement.clientWidth;+ const freshH = gl.domElement.clientHeight;+ (cam as THREE.PerspectiveCamera).aspect = freshW / freshH;+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();+ gl.setPixelRatio(3);+ gl.setSize(freshW, freshH, false);},- hasBuiltInShadow: false,+ hasBuiltInShadow: true,};- onApi?.(api);- return () => onApi?.(null);- }, [onApi, gl, scene, cameraRef]);+ capturedOnApi?.(api);+ return () => capturedOnApi?.(null);+ }, [gl, scene, camera, cameraRef]);const applyTexture = useCallback(() => {if (videoElement) return;@@ -148,6 +151,53 @@ function ModelScene({const cropKey = cropArea ? JSON.stringify(cropArea) : null;+ if (!imageUrl) {+ const placeholderKey = `__placeholder__:${PLACEHOLDER_LAPTOP_URL}`;+ if (lastLoadedUrlRef.current === placeholderKey) return;++ const img = new Image();+ img.crossOrigin = "anonymous";+ img.onload = () => {+ const currentMat = screenMatRef.current;+ if (!currentMat) return;++ const TEX_W = RENDER_W;+ const TEX_H = RENDER_H;++ const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, null);++ if (currentMat.map) {+ currentMat.map.dispose();+ }++ const tex = new THREE.CanvasTexture(cover);+ tex.flipY = false;+ tex.wrapS = THREE.RepeatWrapping;+ tex.colorSpace = THREE.SRGBColorSpace;++ if (cover.width && cover.height) {+ tex.repeat.y = ((cover.width / cover.height) / screenSize[0]) * screenSize[1];+ }++ tex.generateMipmaps = true;+ tex.minFilter = THREE.LinearMipmapLinearFilter;+ tex.magFilter = THREE.LinearFilter;+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();++ currentMat.map = tex;+ currentMat.color.set(0xffffff);+ currentMat.needsUpdate = true;++ lastLoadedUrlRef.current = placeholderKey;+ lastLoadedCropKeyRef.current = null;+ };+ img.onerror = () => {+ lastLoadedUrlRef.current = placeholderKey;+ };+ img.src = PLACEHOLDER_LAPTOP_URL;+ return;+ }+if (!imageUrl) {if (mat.map) {mat.map.dispose();diff --git a/app/components/ui/editor/Mockup3dMenu.tsx b/app/components/ui/editor/Mockup3dMenu.tsxindex ad27f4d..83c13af 100644--- a/app/components/ui/editor/Mockup3dMenu.tsx+++ b/app/components/ui/editor/Mockup3dMenu.tsx@@ -1,6 +1,6 @@"use client";-import { useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";import { useTranslations } from "next-intl";import { Icon } from "@iconify/react";import { SliderControl } from "../../../../components/ui/SliderControl";@@ -46,29 +46,30 @@ function PositionPad({const bgLayerStyle: React.CSSProperties = backgroundUrl? {- backgroundImage: `url('${backgroundUrl}')`,- backgroundSize: "cover",- backgroundPosition: "center",- backgroundRepeat: "no-repeat",- }+ backgroundImage: `url('${backgroundUrl}')`,+ backgroundSize: "cover",+ backgroundPosition: "center",+ backgroundRepeat: "no-repeat",+ }: backgroundColorCss? backgroundColorCss.startsWith("#") || backgroundColorCss.startsWith("rgb")? { backgroundColor: backgroundColorCss }: {- backgroundImage: backgroundColorCss,- backgroundSize: "cover",- backgroundPosition: "center",- }+ backgroundImage: backgroundColorCss,+ backgroundSize: "cover",+ backgroundPosition: "center",+ }: {};return (<div className="relative group w-full cursor-default"><divref={padRef}- className={`relative w-full rounded-[14px] overflow-hidden select-none border shadow-[inset_0_2px_8px_rgba(0,0,0,0.8)] transition-all duration-200 ${isDraggingState- ? "border-cyan-500/40 ring-1 ring-cyan-500/20"- : "border-zinc-800/50"- }`}+ className={`relative w-full rounded-[14px] overflow-hidden select-none border shadow-[inset_0_2px_8px_rgba(0,0,0,0.8)] transition-all duration-200 ${+ isDraggingState+ ? "border-cyan-500/40 ring-1 ring-cyan-500/20"+ : "border-zinc-800/50"+ }`}style={{ height: PAD_H }}onPointerDown={(e) => {dragging.current = true;@@ -77,7 +78,9 @@ function PositionPad({onDragStart?.();fromEvent(e);}}- onPointerMove={(e) => { if (dragging.current) fromEvent(e); }}+ onPointerMove={(e) => {+ if (dragging.current) fromEvent(e);+ }}onPointerUp={() => {dragging.current = false;setIsDraggingState(false);@@ -90,17 +93,23 @@ function PositionPad({)}<div className="absolute inset-0 pointer-events-none opacity-10 bg-[radial-gradient(#a1a1aa_1px,transparent_1px)] bg-size-[14px_14px]" />- <div className="absolute top-0 bottom-0 w-px bg-linear-to-b from-transparent via-white/10 to-transparent -translate-x-1/2" style={{ left: "50%" }} />- <div className="absolute left-0 right-0 h-px bg-linear-to-r from-transparent via-white/10 to-transparent -translate-y-1/2" style={{ top: "50%" }} />+ <div+ className="absolute top-0 bottom-0 w-px bg-linear-to-b from-transparent via-white/10 to-transparent -translate-x-1/2"+ style={{ left: "50%" }}+ />+ <div+ className="absolute left-0 right-0 h-px bg-linear-to-r from-transparent via-white/10 to-transparent -translate-y-1/2"+ style={{ top: "50%" }}+ /><divclassName="absolute pointer-events-none bg-white/10 transition-opacity -translate-x-1/2"- style={{ left: `${pctX * 100}%`, top: 0, bottom: 0, width: '1px' }}+ style={{ left: `${pctX * 100}%`, top: 0, bottom: 0, width: "1px" }}/><divclassName="absolute pointer-events-none bg-white/10 transition-opacity -translate-y-1/2"- style={{ top: hy, left: 0, right: 0, height: '1px' }}+ style={{ top: hy, left: 0, right: 0, height: "1px" }}/><div@@ -116,7 +125,110 @@ function PositionPad({/></div></div>+ );+}++function ActiveDevicePreview({+ tpl,+}: {+ tpl: ActiveDeviceTpl;+}) {+ const videoRef = useRef<HTMLVideoElement | null>(null);+ const [isHovering, setIsHovering] = useState(false);+ const [videoReady, setVideoReady] = useState(false);++ useEffect(() => {+ const video = videoRef.current;+ if (!video) return;++ if (isHovering) {+ const play = async () => {+ try {+ await video.play();+ } catch {+ }+ };+ play();+ } else {+ video.pause();+ video.currentTime = 0;+ }+ }, [isHovering]);++ return (+ <div+ className="relative w-full h-86 overflow-hidden squircle-element-camera border"+ style={{ borderColor: `${tpl.accentColor}44` }}+ onMouseEnter={() => setIsHovering(true)}+ onMouseLeave={() => setIsHovering(false)}+ >+ <div className="absolute inset-0 bg-[#0d0d10]" />++ <div+ className="absolute inset-0 z-10 pointer-events-none"+ style={{+ background: `linear-gradient(135deg, ${tpl.accentColor}22 0%, transparent 70%)`,+ }}+ />+ {tpl.posterUrl ? (+ <img+ src={tpl.posterUrl}+ alt={tpl.title}+ draggable={false}+ className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${+ isHovering ? "scale-105 opacity-0" : "scale-100 opacity-100"+ }`}+ />+ ) : (+ <div className="absolute inset-0 flex items-center justify-center">+ <Icon+ icon={tpl.icon}+ width="48"+ style={{ color: `${tpl.accentColor}cc` }}+ />+ </div>+ )}++ {tpl.videoUrl && (+ <video+ ref={videoRef}+ src={tpl.videoUrl}+ poster={tpl.posterUrl}+ muted+ loop+ playsInline+ preload="metadata"+ onLoadedData={() => setVideoReady(true)}+ className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${+ isHovering && videoReady ? "scale-105 opacity-100" : "scale-100 opacity-0"+ }`}+ />+ )}++ <div+ className={`absolute inset-0 z-20 bg-black/20 transition-opacity duration-300 ${+ isHovering ? "opacity-100" : "opacity-0"+ }`}+ />++ <div className=" flex items-center gap-2 absolute bottom-0 left-0 right-0 px-3 py-2 bg-gradient-to-t from-black/80 to-transparent z-30">+ <Icon+ icon={tpl.icon}+ width={14}+ />+ <span className="text-[11px] font-bold text-white/90 tracking-wide">+ {tpl.title}+ </span>+ </div>++ <div+ className="absolute top-2 right-2 size-5 rounded-full flex items-center justify-center z-30"+ style={{ background: tpl.accentColor }}+ >+ <Icon icon="mdi:check-bold" width={11} className="text-white" />+ </div>+ </div>);}@@ -126,6 +238,8 @@ export interface ActiveDeviceTpl {accentColor: string;icon: string;modelUrl: string;+ posterUrl?: string;+ videoUrl?: string;}export interface Mockup3dMenuProps {@@ -202,50 +316,19 @@ export function Mockup3dMenu({<><div className="flex items-center gap-2 p-3 border-b border-white/6 shrink-0"><DetailPageHeader- label="Dispositivo 3D"+ label={t("device3DTitle")}icon="mage:box-3d"onBack={onBack}/></div><div className="flex-1 overflow-y-auto custom-scrollbar px-4 py-4 space-y-5">- {activeDeviceTpl && (- <div- className="relative w-full h-70 overflow-hidden rounded-2xl border"- style={{ borderColor: `${activeDeviceTpl.accentColor}44` }}- >- <div- className="absolute inset-0"- style={{- background: `linear-gradient(135deg, ${activeDeviceTpl.accentColor}22 0%, transparent 70%)`,- }}- />- <div className="absolute inset-0 bg-[#0d0d10]" style={{ zIndex: -1 }} />- <div className="absolute inset-0 flex items-center justify-center">- <Icon- icon={activeDeviceTpl.icon}- width="48"- style={{ color: `${activeDeviceTpl.accentColor}cc` }}- />- </div>- <div className="absolute bottom-0 left-0 right-0 px-3 py-2 bg-gradient-to-t from-black/80 to-transparent">- <span className="text-[11px] font-bold text-white/90 tracking-wide">- {activeDeviceTpl.title}- </span>- </div>- <div- className="absolute top-2 right-2 size-5 rounded-full flex items-center justify-center"- style={{ background: activeDeviceTpl.accentColor }}- >- <Icon icon="mdi:check-bold" width={11} className="text-white" />- </div>- </div>- )}+ {activeDeviceTpl && <ActiveDevicePreview tpl={activeDeviceTpl} />}<div className="flex flex-col gap-4"><div className="flex items-center justify-between"><span className="text-[10px] font-semibold text-white/50 uppercase tracking-wider">- Configuración+ {t("configuration")}</span><buttontype="button"@@ -253,12 +336,12 @@ export function Mockup3dMenu({className="flex items-center gap-1 text-[11px] text-white/40 hover:text-white/80 transition-colors"><Icon icon="lucide:rotate-ccw" width="11" />- Resetear+ {t("reset")}</button></div><SliderControl- label="Escala"+ label={t("scale")}value={Math.round(imagePhoneScale * 100)}min={30}max={300}@@ -270,7 +353,7 @@ export function Mockup3dMenu({{isLaptop && (<SliderControlicon="material-symbols:laptop-chromebook-outline"- label="Apertura de laptop"+ label={t("laptopOpening")}value={Math.round(imagePhoneOpening * 100)}min={0}max={100}@@ -282,7 +365,7 @@ export function Mockup3dMenu({<SliderControlicon="mdi:blur"- label="Sombra"+ label={t("shadow")}value={Math.round(imagePhoneShadow * 100)}min={0}max={100}@@ -292,7 +375,7 @@ export function Mockup3dMenu({/><div className="flex flex-col gap-2">- <span className="text-xs text-white/60 font-medium">Posición</span>+ <span className="text-xs text-white/60 font-medium">{t("position")}</span><PositionPadx={imagePhoneX}y={imagePhoneY}@@ -310,9 +393,9 @@ export function Mockup3dMenu({className="w-full text-xs mt-2"><Icon icon="ph:trash-bold" width="13" aria-hidden="true" />- Quitar marco+ {t("removeFrame")}</Button></div></>);-}+}\ No newline at end of filediff --git a/app/components/ui/editor/MockupMenu.tsx b/app/components/ui/editor/MockupMenu.tsxindex de7e755..b21bc42 100644--- a/app/components/ui/editor/MockupMenu.tsx+++ b/app/components/ui/editor/MockupMenu.tsx@@ -17,14 +17,13 @@ export interface MockupMenuProps {mockupId?: string;mockupConfig?: MockupConfig;onMockupChange?: (mockupId: string) => void;- onMockupConfigChange?: (config: Partial<MockupConfig>) => void;- // Background props forwarded from parent (needed for PositionPad in 3D menu)- backgroundUrl?: string | null;+ onMockupConfigChange?: (config: Partial<MockupConfig>) => void; backgroundUrl?: string | null;backgroundColorCss?: string | null;backgroundTab?: "wallpaper" | "image" | "color" | "unsplash";selectedWallpaper?: number;selectedImageUrl?: string;initialPage?: MenuPage;+ mediaType?: "video" | "image";}export function MockupMenu({@@ -38,6 +37,7 @@ export function MockupMenu({selectedWallpaper,selectedImageUrl,initialPage = "home",+ mediaType = "image",}: MockupMenuProps) {const t = useTranslations("mockupMenu");@@ -48,12 +48,9 @@ export function MockupMenu({setPage(initialPage);}}, [initialPage]);-- // ── 2D popover state ──const [selectedCategory, setSelectedCategory] = useState<MockupCategory>("all");const [gridLoaded, setGridLoaded] = useState(false);const devicesScrollRef = useRef<HTMLDivElement>(null);- const [isDevicesHover, setIsDevicesHover] = useState(false);const [canScrollLeft, setCanScrollLeft] = useState(false);const [canScrollRight, setCanScrollRight] = useState(false);@@ -107,8 +104,6 @@ export function MockupMenu({const onWheel = (e: WheelEvent) => {if (el.scrollWidth <= el.clientWidth) return;-- // Si ya es scroll horizontal, lo dejamos pasarif (Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;e.preventDefault();@@ -120,8 +115,6 @@ export function MockupMenu({el.addEventListener("wheel", onWheel, { passive: false });el.addEventListener("scroll", onScroll, { passive: true });window.addEventListener("resize", updateDevicesScrollState);-- // estado inicial correcto al volver a homeupdateDevicesScrollState();return () => {@@ -132,8 +125,6 @@ export function MockupMenu({return () => cancelAnimationFrame(id);}, [page, restoreDevicesScroll, updateDevicesScrollState]);-- // ── 3D context ──const {imagePhoneActive,setImagePhoneActive,@@ -156,7 +147,6 @@ export function MockupMenu({setImagePhoneShadowColor,} = useMockup3dContext();- // ── Derived ──const filteredMockups =selectedCategory === "all"? MOCKUPS@@ -167,6 +157,7 @@ export function MockupMenu({const activeDeviceId: ImageDeviceId | null = imagePhoneActive? (imagePhoneDevice as ImageDeviceId): null;+const activeDeviceTpl: ActiveDeviceTpl | null = (() => {if (!imagePhoneActive) return null;const tpl = IMAGE_DEVICE_TEMPLATES.find((t) => t.id === activeDeviceId);@@ -177,8 +168,11 @@ export function MockupMenu({accentColor: tpl.accentColor,icon: tpl.icon,modelUrl: tpl.modelUrl,+ posterUrl: tpl.posterUrl,+ videoUrl: tpl.videoUrl,};})();+const isLaptop = imagePhoneActive && imagePhoneDevice === "laptop";const resolvedBackgroundUrl = (() => {@@ -194,9 +188,7 @@ export function MockupMenu({return null;})();- const hasActiveFrame = mockupId !== "none" || imagePhoneActive;-- // ── Handlers: 2D ──+ const hasActiveFrame = mockupId !== "none" || (mediaType === "image" && imagePhoneActive);const handleMockupSelect = (id: string) => {onMockupChange?.(id);@@ -210,14 +202,7 @@ export function MockupMenu({setTimeout(() => setGridLoaded(true), 250);};- // ── Handlers: 3D ──-const handleDeviceClick = (id: ImageDeviceId) => {- // Only reset the pose when switching to a *different* device.- // If the user clicks the already-active device card, keep the current- // position/rotation/scale so they don't lose their edits.- // (Special case: if the device's rotation is still at the context default- // of 0/0 — i.e. has never been posed — apply the canonical pose once.)const isSameDevice = imagePhoneDevice === id;const isUnposed = imagePhoneRotX === 0 && imagePhoneRotY === 0;@@ -244,16 +229,12 @@ export function MockupMenu({setPage("detail-3d");};- // ── Handlers: shared ──-const handleRemoveAll = () => {onMockupChange?.("none");setImagePhoneActive(false);setPage("home");};- // PAGE: DETAIL 2D-if (page === "detail-2d") {return (<Mockup2dMenu@@ -266,8 +247,6 @@ export function MockupMenu({);}- // PAGE: DETAIL 3D-if (page === "detail-3d") {return (<Mockup3dMenu@@ -295,23 +274,18 @@ export function MockupMenu({);}- // PAGE: HOME-return (<div className="p-4 flex flex-col gap-6">- {/* Header */}<div className="flex items-center gap-2 text-white font-medium"><Icon icon="hugeicons:ai-browser" width="20" aria-hidden="true" /><span>{t("title")}</span></div>- {/* ── 2D Section ── */}<div className="flex flex-col gap-3"><p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">- Marcos 2D+ {t("frames2D")}</p>- {/* 2D selector trigger */}<PopoveronOpenChange={(open) => {if (open && !gridLoaded) {@@ -324,7 +298,7 @@ export function MockupMenu({type="button"className={`group relative flex items-center gap-3 p-2 squircle-element border transition-all w-full h-35 ${mockupId !== "none"? "bg-blue-500/10 border-blue-500/40 text-blue-300"- : "bg-white/[0.03] border-white/[0.07] text-white/40 hover:border-white/20"+ : "bg-white/3 border-white/[0.07] text-white/40 hover:border-white/20"}`}aria-label={t("windowType")}aria-haspopup="dialog"@@ -502,72 +476,68 @@ export function MockupMenu({</div></div>- {/* Divider */}- <div className="h-px bg-white/[0.06]" />+ {mediaType === "image" && (+ <>+ <div className="h-px bg-white/6" />- <div className="flex flex-col gap-3">- <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">- Dispositivos 3D- </p>+ <div className="flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">+ {t("devices3D")}+ </p>- <div- className="relative group"- onMouseEnter={() => setIsDevicesHover(true)}- onMouseLeave={() => setIsDevicesHover(false)}- >- <div- className={`pointer-events-none absolute inset-y-0 right-0 z-20 w-8 bg-gradient-to-l from-[#141417] to-transparent transition-opacity duration-200 ${canScrollRight ? "opacity-100" : "opacity-0"- }`}- />-- <button- type="button"- onClick={() => scrollDevices("left")}- disabled={!canScrollLeft}- className={`absolute left-1 top-1/2 -translate-y-1/2 z-30 flex items-center justify-center size-8 rounded-full border backdrop-blur-md transition-all duration-200 ${isDevicesHover && canScrollLeft- ? "opacity-100 translate-x-0 bg-black/45 border-white/10 text-white/80 hover:bg-black/70 hover:text-white"- : "opacity-0 -translate-x-2 pointer-events-none"- }`}- aria-label="Scroll left"- >- <Icon icon="ph:caret-left-bold" width="14" />- </button>-- <button- type="button"- onClick={() => scrollDevices("right")}- disabled={!canScrollRight}- className={`absolute right-1 top-1/2 -translate-y-1/2 z-30 flex items-center justify-center size-8 rounded-full border backdrop-blur-md transition-all duration-200 ${isDevicesHover && canScrollRight- ? "opacity-100 translate-x-0 bg-black/45 border-white/10 text-white/80 hover:bg-black/70 hover:text-white"- : "opacity-0 translate-x-2 pointer-events-none"- }`}- aria-label="Scroll right"- >- <Icon icon="ph:caret-right-bold" width="14" />- </button>-- <div- ref={devicesScrollRef}- className="flex gap-2 overflow-x-auto overflow-y-hidden snap-x snap-mandatory scroll-smooth pb-2 pl-1 pr-12 custom-scrollbar"- style={{- scrollbarWidth: "none",- msOverflowStyle: "none",- }}- onScroll={handleDevicesScroll}- >- {IMAGE_DEVICE_TEMPLATES.map((tpl) => (- <DeviceCard- key={tpl.id}- tpl={tpl}- isActive={activeDeviceId === tpl.id}- onClick={() => handleDeviceClick(tpl.id)}+ <div className="flex items-center gap-2">+ <div className="flex items-center squircle-element border border-white/8 bg-white/3 p-0.5">+ <button+ type="button"+ onClick={() => scrollDevices("left")}+ disabled={!canScrollLeft}+ className="flex size-7 items-center justify-center squircle-element text-white/70 transition-all hover:bg-white/6 hover:text-white disabled:pointer-events-none disabled:opacity-30"+ >+ <Icon icon="ph:caret-left-bold" width="12" />+ </button>++ <button+ type="button"+ onClick={() => scrollDevices("right")}+ disabled={!canScrollRight}+ className="flex size-7 items-center justify-center rounded-full text-white/70 transition-all hover:bg-white/6 hover:text-white disabled:pointer-events-none disabled:opacity-30"+ >+ <Icon icon="ph:caret-right-bold" width="12" />+ </button>+ </div>+ </div>+ </div>++ <div className="relative">+ <div+ className={`pointer-events-none absolute inset-y-0 right-0 z-20 w-12 bg-gradient-to-l from-[#141417] to-transparent transition-opacity duration-200 ${canScrollRight ? "opacity-100" : "opacity-0"+ }`}/>- ))}++ <div+ ref={devicesScrollRef}+ className="flex gap-2 overflow-x-auto overflow-y-hidden snap-x snap-mandatory scroll-smooth pb-2 pl-1 pr-12 custom-scrollbar"+ style={{+ scrollbarWidth: "none",+ msOverflowStyle: "none",+ }}+ onScroll={handleDevicesScroll}+ >+ {IMAGE_DEVICE_TEMPLATES.map((tpl) => (+ <DeviceCard+ key={tpl.id}+ tpl={tpl}+ isActive={activeDeviceId === tpl.id}+ onClick={() => handleDeviceClick(tpl.id)}+ />+ ))}+ </div>+ </div></div>- </div>- </div>+ </>+ )}- {/* ── Remove button (unified) ── */}{hasActiveFrame && (<ButtononClick={handleRemoveAll}@@ -581,4 +551,4 @@ export function MockupMenu({)}</div>);-}+}\ No newline at end of filediff --git a/app/components/ui/editor/Phone3DViewer.tsx b/app/components/ui/editor/Phone3DViewer.tsxindex 63af038..72ca8af 100644--- a/app/components/ui/editor/Phone3DViewer.tsx+++ b/app/components/ui/editor/Phone3DViewer.tsx@@ -2,7 +2,7 @@import { Canvas, useThree, useFrame } from "@react-three/fiber";import { PerspectiveCamera, Environment, OrbitControls } from "@react-three/drei";-import { useEffect, useRef, useState, Suspense, useCallback } from "react";+import { useEffect, useRef, useState, Suspense, useCallback, useLayoutEffect } from "react";import * as THREE from "three";import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";import {@@ -48,6 +48,7 @@ interface Props {const DEG = Math.PI / 180;const specificGltfCache = new Map<string, Promise<THREE.Group>>();+const PLACEHOLDER_PHONE_URL = "/images/mockups-3d/placeholder-phone.avif";function loadSpecificGltf(url: string): Promise<THREE.Group> {if (!specificGltfCache.has(url)) {@@ -106,6 +107,8 @@ function ModelScene({const lastLoadedCropKeyRef = useRef<string | null>(null);const screenAspectRef = useRef<number>(0.459);const flipYRef = useRef<boolean>(false);+ const onApiRef = useRef(onApi);+ useLayoutEffect(() => { onApiRef.current = onApi; });const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D();@@ -116,49 +119,112 @@ function ModelScene({});useEffect(() => {- const previewW = gl.domElement.clientWidth || PHONE_W;- const previewH = gl.domElement.clientHeight || PHONE_H;+ const capturedOnApi = onApiRef.current;+ const RENDER_PIXEL_RATIO = 2;const api: Phone3DApi = {renderAt: (w, h) => {- if (!cameraRef.current) return;- const oldAspect = cameraRef.current.aspect;- cameraRef.current.aspect = w / h;- cameraRef.current.updateProjectionMatrix();- gl.setPixelRatio(2);- gl.setSize(w, h, false);- if (videoTextureRef.current) {- videoTextureRef.current.needsUpdate = true;- }- gl.render(scene, cameraRef.current);+ const cam = cameraRef.current ?? camera;+ if (!cam) return;++ const maxTexSize = gl.capabilities.maxTextureSize || 4096;+ const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;+ const safeW = Math.max(1, Math.min(Math.round(w), maxDim));+ const safeH = Math.max(1, Math.min(Math.round(h), maxDim));++ (cam as THREE.PerspectiveCamera).aspect = safeW / safeH;+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();+ gl.setPixelRatio(RENDER_PIXEL_RATIO);+ gl.setSize(safeW, safeH, false);+ if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;+ gl.render(scene, cam);},restorePreview: () => {- if (!cameraRef.current) return;- cameraRef.current.aspect = previewW / previewH;- cameraRef.current.updateProjectionMatrix();+ const cam = cameraRef.current ?? camera;+ if (!cam) return;+ const freshW = gl.domElement.clientWidth;+ const freshH = gl.domElement.clientHeight;+ (cam as THREE.PerspectiveCamera).aspect = freshW / freshH;+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();gl.setPixelRatio(3);- gl.setSize(previewW, previewH, false);+ gl.setSize(freshW, freshH, false);},- hasBuiltInShadow: false,+ hasBuiltInShadow: true,};- onApi?.(api);- return () => onApi?.(null);- }, [onApi, gl, scene, cameraRef]);+ capturedOnApi?.(api);+ return () => capturedOnApi?.(null);+ }, [gl, scene, camera, cameraRef]);const applyTexture = useCallback(() => {if (videoElement) return;const mat = screenMatRef.current;if (!mat) return;const cropKey = cropArea ? JSON.stringify(cropArea) : null;+if (!imageUrl) {- if (mat.map) {- mat.map.dispose();- mat.map = null;- mat.needsUpdate = true;- }- lastLoadedUrlRef.current = null;- lastLoadedCropKeyRef.current = null;+ const placeholderKey = `__placeholder__:${PLACEHOLDER_PHONE_URL}`;+ if (lastLoadedUrlRef.current === placeholderKey) return;++ const device = getDeviceFromModelUrl(modelUrl);+ const deviceConfig = deviceConfigs[device];+ const isDefaultPhone = device === "phone";++ const img = new Image();+ img.crossOrigin = "anonymous";+ img.onload = () => {+ const currentMat = screenMatRef.current;+ if (!currentMat) return;++ let TARGET_W = 2048;+ let TARGET_H = 0;+ let cornerRadius = 0;+ if (isDefaultPhone) {+ TARGET_W = PHONE_W * 4;+ TARGET_H = Math.round(TARGET_W / screenAspectRef.current);+ } else {+ TARGET_H = Math.round(TARGET_W / deviceConfig.aspectRatio);+ cornerRadius = Math.round(TARGET_W * deviceConfig.cornerRadiusFactor);+ }++ // El placeholder no tiene cropArea ni mask — se cubre "cover" a pantalla completa+ const cover = createCoverScreenCanvas(img, TARGET_W, TARGET_H, cornerRadius, null);++ if (currentMat.map) {+ currentMat.map.dispose();+ currentMat.map = null;+ }+ const tex = new THREE.CanvasTexture(cover);+ tex.flipY = flipYRef.current;+ tex.colorSpace = THREE.SRGBColorSpace;+ tex.generateMipmaps = true;+ tex.minFilter = THREE.LinearMipmapLinearFilter;+ tex.magFilter = THREE.LinearFilter;+ tex.wrapS = THREE.ClampToEdgeWrapping;+ tex.wrapT = THREE.ClampToEdgeWrapping;+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();+ currentMat.map = tex;+ currentMat.color.set(0xffffff);+ currentMat.needsUpdate = true;++ lastLoadedUrlRef.current = placeholderKey;+ lastLoadedCropKeyRef.current = null;+ };+ img.onerror = () => {+ // Si el placeholder falla en cargar, al menos deja la pantalla+ // en un gris neutro en vez de quedar sin textura.+ const currentMat = screenMatRef.current;+ if (!currentMat) return;+ if (currentMat.map) {+ currentMat.map.dispose();+ currentMat.map = null;+ }+ currentMat.color.set(0x1a1a1a);+ currentMat.needsUpdate = true;+ lastLoadedUrlRef.current = placeholderKey;+ };+ img.src = PLACEHOLDER_PHONE_URL;return;}+if (lastLoadedUrlRef.current === imageUrl &&lastLoadedCropKeyRef.current === cropKey &&diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsxindex d50af67..a7c36fc 100644--- a/app/components/ui/editor/VideoCanvas.tsx+++ b/app/components/ui/editor/VideoCanvas.tsx@@ -1,6 +1,6 @@"use client";-import { useRef, useEffect, useImperativeHandle, forwardRef, useMemo, useState } from "react";+import { useRef, useEffect, useImperativeHandle, forwardRef, useMemo, useState, useCallback, memo } from "react";import dynamic from "next/dynamic";import type { VideoCanvasHandle, VideoCanvasProps, VideoThumbnail } from "@/types";import type { ImageElement, SvgElement } from "@/types/canvas-elements.types";@@ -44,7 +44,7 @@ const IPhone13ProMax3DViewer = dynamic({ ssr: false });-export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({+const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({activeTool: _activeTool,mediaType = "video",imageUrl = null,@@ -113,7 +113,19 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functimagePhoneShadow, imagePhoneShadowColor} = useMockup3dContext();// 3D phone overlay is active in both video and image mode+ // Añadir FUERA del JSX de VideoCanvas, junto a los otros useCallback:+ const handlePhoneMount = useCallback((canvas: HTMLCanvasElement) => {+ imagePhoneCanvasRef.current = canvas;+ }, []);++ const handlePhoneApi = useCallback((api: typeof imagePhoneApiRef.current) => {+ imagePhoneApiRef.current = api;+ }, []);+ const handlePhoneRotationChange = useCallback((rx: number, ry: number) => {+ setImagePhoneRotX(rx);+ setImagePhoneRotY(ry);+ }, [setImagePhoneRotX, setImagePhoneRotY]);// Ctrl+scroll zoom badge state for image phone overlayconst [imagePhoneZoomVisible, setImagePhoneZoomVisible] = useState(false);const imagePhoneZoomTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -125,6 +137,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functconst imagePhoneApiRef = useRef<{ renderAt: (w: number, h: number) => void; restorePreview: () => void; hasBuiltInShadow?: boolean } | null>(null);const [activePhoneDevice, setActivePhoneDevice] = useState<string | null>(null);const [phoneTransitioning, setPhoneTransitioning] = useState(false);+ const rafDragRef = useRef<number | null>(null);+ const pendingUpdateRef = useRef<{ id: string; x: number; y: number } | null>(null);// Model URL for the active deviceconst PHONE_DEVICE_URLS: Record<string, string | undefined> = {@@ -340,6 +354,26 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functreturn () => observer.disconnect();}, [aspectRatio, customAspectRatio]);++ const phoneCalibrationWidthRef = useRef<number>(canvasDimensions?.width ?? 0);+ useEffect(() => {+ if (canvasDimensions?.width) {+ phoneCalibrationWidthRef.current = canvasDimensions.width;+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [imagePhoneX, imagePhoneY, imagePhoneScale]);++ const phoneCanvasScaleFactor = (canvasDimensions?.width && phoneCalibrationWidthRef.current)+ ? canvasDimensions.width / phoneCalibrationWidthRef.current+ : 1;++ // Usar SIEMPRE estos valores para posicionar/dimensionar el mockup 3D —+ // nunca imagePhoneX/Y/Scale crudos, excepto dentro del cálculo que llama+ // a setImagePhoneScale() (ese debe leer el valor real almacenado).+ const effectiveImagePhoneX = imagePhoneX * phoneCanvasScaleFactor;+ const effectiveImagePhoneY = imagePhoneY * phoneCanvasScaleFactor;+ const effectiveImagePhoneScale = imagePhoneScale * phoneCanvasScaleFactor;+const cameraDragRef = useRef<{pointerId: number;startX: number;@@ -404,7 +438,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functreturn () => window.removeEventListener("pointerdown", close);}, [!!canvasCtxMenu]); // eslint-disable-line react-hooks/exhaustive-deps- // Calculate mask styles — selects video or image mask based on mediaTypeconst maskStyles = useMemo(() => {const config = mediaType === "video" ? videoMaskConfig : imageMaskConfig;if (!config || !config.enabled) return {};@@ -442,7 +475,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functconst elementImagesRef = useRef<Map<string, HTMLImageElement>>(new Map());const svgImageCacheRef = useRef<Map<string, HTMLImageElement>>(new Map());- // Actualizar canvas dimensions cuando cambia el aspect ratiouseEffect(() => {const canvas = exportCanvasRef.current;if (canvas) {@@ -451,7 +483,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct}}, [exportDimensions]);- // Precargar imagen de wallpaper para el canvasuseEffect(() => {if (shouldShowWallpaper && wallpaperUrl) {const img = new Image();@@ -487,21 +518,17 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct}if (imagePhoneDevice === activePhoneDevice) return;- // 1. Desmonta el viewer actual (libera contexto WebGL)setPhoneTransitioning(true);setActivePhoneDevice(null);- // 2. Espera un frame para que el GC libere el contexto viejo- // antes de crear el nuevoconst id = setTimeout(() => {setActivePhoneDevice(imagePhoneDevice);setPhoneTransitioning(false);- }, 50); // 50ms es suficiente para que el contexto anterior se libere+ }, 50);return () => clearTimeout(id);}, [imagePhoneDevice, imagePhoneActive]);- // Preload canvas element images (only for image elements, not SVGs)useEffect(() => {const cache = elementImagesRef.current;const loadedPaths = new Set(cache.keys());@@ -584,7 +611,13 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functguides.horizontal.push(50);}- setMockupAlignmentGuides(guides);+ if (+ guides.vertical.length !== alignmentGuides.vertical.length ||+ guides.horizontal.length !== alignmentGuides.horizontal.length+ ) {+ setMockupAlignmentGuides(guides);++ }onVideoTransformChange({...videoTransform,@@ -745,24 +778,46 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functguides.horizontal.push(centerY);}- setAlignmentGuides(guides);+ if (+ guides.vertical.length !== alignmentGuides.vertical.length ||+ guides.horizontal.length !== alignmentGuides.horizontal.length+ ) {+ setAlignmentGuides(guides);+ }- onElementUpdate(selectedElementId, {- x: newX,- y: newY,- });+ pendingUpdateRef.current = { id: selectedElementId, x: newX, y: newY };+ if (!rafDragRef.current) {+ rafDragRef.current = requestAnimationFrame(() => {+ const pending = pendingUpdateRef.current;+ if (pending && onElementUpdate) {+ onElementUpdate(pending.id, { x: pending.x, y: pending.y });+ }+ rafDragRef.current = null;+ });+ }}}};const handleMouseUp = () => {- // If the mouse barely moved: treat as a click → collapse multi-selection to the clicked elementif (pendingCollapseRef.current && !wasDragRef.current) {const id = pendingCollapseRef.current;setCanvasSelectedIds([id]);}pendingCollapseRef.current = null;wasDragRef.current = false;++ // Flush any pending RAF update antes de limpiar estado+ if (rafDragRef.current) {+ cancelAnimationFrame(rafDragRef.current);+ rafDragRef.current = null;+ if (pendingUpdateRef.current && onElementUpdate) {+ const { id, x, y } = pendingUpdateRef.current;+ onElementUpdate(id, { x, y });+ }+ pendingUpdateRef.current = null;+ }+setIsDraggingElement(false);setIsDraggingElementRotation(false);setAlignmentGuides({ vertical: [], horizontal: [] });@@ -960,7 +1015,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct};// Function to draw a frame on the export canvas- const drawFrame = async () => {+ const drawFrame = async (highQuality: boolean = true) => {const canvas = exportCanvasRef.current;const canvasCtxOptions: CanvasRenderingContext2DSettings = { alpha: true, colorSpace: 'srgb', desynchronized: false, willReadFrequently: false };const ctx = canvas?.getContext('2d', canvasCtxOptions);@@ -1163,12 +1218,12 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functconst phoneGL = imagePhoneCanvasRef.current;const domW = canvasDimensions?.width ?? canvasWidth;const pxScale = canvasWidth / domW;- const phoneCx = canvasWidth / 2 + imagePhoneX * pxScale;- const phoneCy = canvasHeight / 2 + imagePhoneY * pxScale;+ const phoneCx = canvasWidth / 2 + effectiveImagePhoneX * pxScale;+ const phoneCy = canvasHeight / 2 + effectiveImagePhoneY * pxScale;// Use device-specific dimensions instead of generic PHONE_W/Hconst deviceDims = DEVICE_3D_DIMENSIONS[imagePhoneDevice] ?? { width: PHONE_W, height: PHONE_H };- const drawW = deviceDims.width * imagePhoneScale * pxScale;- const drawH = deviceDims.height * imagePhoneScale * pxScale;+ const drawW = deviceDims.width * effectiveImagePhoneScale * pxScale;+ const drawH = deviceDims.height * effectiveImagePhoneScale * pxScale;// Paint CSS-shadow replica as a 2D radial gradient underneath the model,// but only for devices whose 3D viewer doesn't already render ContactShadows.const hasBuiltInShadow = imagePhoneApiRef.current?.hasBuiltInShadow ?? false;@@ -1188,10 +1243,17 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functctx.fill();ctx.restore();}- // Re-render the WebGL canvas at the target export resolution- imagePhoneApiRef.current?.renderAt(drawW, drawH);- ctx.drawImage(phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH);- imagePhoneApiRef.current?.restorePreview();+ if (highQuality) {+ // Solo para exportación real — redimensionar el canvas WebGL EN VIVO+ // causa una carrera con el compositor del navegador.+ imagePhoneApiRef.current?.renderAt(drawW, drawH);+ ctx.drawImage(phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH);+ imagePhoneApiRef.current?.restorePreview();+ } else {+ // Liviano: escala lo que ya está renderizado en el canvas en vivo.+ // Nunca toca la resolución del canvas visible.+ ctx.drawImage(phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH);+ }}ctx.restore();return;@@ -1278,9 +1340,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functif (!imagePhoneActive) {drawMockupAndMedia(fgCtx, containerX, containerY, containerWidth, containerHeight, video!, false);}- // ── Phone 3D encima del video, con zoom aplicado ──if (imagePhoneActive && imagePhoneCanvasRef.current) {- drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState);+ drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality);}fgCtx.restore();@@ -1366,9 +1427,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functctx.drawImage(videoLayer, 0, 0);ctx.restore();}- // ── Mockup 3D FUERA del zoom — overlay independiente ──if (imagePhoneActive && imagePhoneCanvasRef.current) {- drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState);+ drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality);}@@ -1380,10 +1440,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct}ctx.restore();- // ── Dibuja el mockup 3D SIN zoom del fragmento (es un overlay independiente) ──if (imagePhoneActive && imagePhoneCanvasRef.current) {- // SIN ctx.save/applyVideoZoom — posición absoluta en el canvas- drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState);+ drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality);}}@@ -1402,34 +1460,29 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functcanvasWidth: number,canvasHeight: number,_frameTime: number,- zs: { scale: number; focusX: number; focusY: number }, // ← nuevo parámetro+ zs: { scale: number; focusX: number; focusY: number },+ highQuality: boolean,) => {const phoneGL = imagePhoneCanvasRef.current!;const domW = canvasDimensions?.width ?? canvasWidth;const pxScale = canvasWidth / domW;- // Zoom del fragmento activo — recibido como parámetro, no del closureconst zScale = zs.scale;const focusPxX = (zs.focusX / 100) * canvasWidth;const focusPxY = (zs.focusY / 100) * canvasHeight;const centerX = canvasWidth / 2;const centerY = canvasHeight / 2;- // Posición base del mockup (sin zoom)- const baseCx = centerX + imagePhoneX * pxScale;- const baseCy = centerY + imagePhoneY * pxScale;+ const baseCx = centerX + effectiveImagePhoneX * pxScale;+ const baseCy = centerY + effectiveImagePhoneY * pxScale;- // Aplicar la misma transformación que applyVideoZoom:- // newPos = (base - focusPx) * scale + centerconst phoneCx = (baseCx - focusPxX) * zScale + centerX;const phoneCy = (baseCy - focusPxY) * zScale + centerY;- // Tamaño también escala con el zoomconst deviceDims = DEVICE_3D_DIMENSIONS[imagePhoneDevice] ?? { width: PHONE_W, height: PHONE_H };- const drawW = deviceDims.width * imagePhoneScale * pxScale * zScale;- const drawH = deviceDims.height * imagePhoneScale * pxScale * zScale;+ const drawW = deviceDims.width * effectiveImagePhoneScale * pxScale * zScale;+ const drawH = deviceDims.height * effectiveImagePhoneScale * pxScale * zScale;- // Sombra de sueloconst hasBuiltInShadow = imagePhoneApiRef.current?.hasBuiltInShadow ?? false;if (imagePhoneShadow > 0.01 && !hasBuiltInShadow) {const sT = imagePhoneShadow * imagePhoneShadow;@@ -1451,12 +1504,15 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functc.restore();}- // Renderizar WebGL- imagePhoneApiRef.current?.renderAt(drawW, drawH);- c.drawImage(phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH);- imagePhoneApiRef.current?.restorePreview();+ if (highQuality) {+ imagePhoneApiRef.current?.renderAt(drawW, drawH);+ c.drawImage(phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH);+ imagePhoneApiRef.current?.restorePreview();+ } else {+ c.drawImage(phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH);+ }};-+const drawCameraOverlay = async (ctx: CanvasRenderingContext2D,canvasWidth: number,@@ -2106,7 +2162,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functstyle={{left: "50%",top: "50%",- transform: `translate(calc(-50% + ${imagePhoneX}px), calc(-50% + ${imagePhoneY}px))`,+ transform: `translate(calc(-50% + ${effectiveImagePhoneX}px), calc(-50% + ${effectiveImagePhoneY}px))`,+transformOrigin: "center center",pointerEvents: "none",userSelect: "none",@@ -2151,7 +2208,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functstyle={{left: "50%",top: "50%",- transform: `translate(calc(-50% + ${imagePhoneX}px), calc(-50% + ${imagePhoneY}px)) scale(${imagePhoneScale})`,+ transform: `translate(calc(-50% + ${effectiveImagePhoneX}px), calc(-50% + ${effectiveImagePhoneY}px)) scale(${effectiveImagePhoneScale})`,+transformOrigin: "center center",pointerEvents: "auto",userSelect: "none",@@ -2179,16 +2237,9 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functinitialRotationX={imagePhoneRotX}initialRotationY={imagePhoneRotY}initialRotationZ={imagePhoneRotZ}- onRotationChange={(rx, ry) => {- setImagePhoneRotX(rx);- setImagePhoneRotY(ry);- }}- onMount={(canvas) => {- imagePhoneCanvasRef.current = canvas;- }}- onApi={(api) => {- imagePhoneApiRef.current = api;- }}+ onRotationChange={handlePhoneRotationChange}+ onMount={handlePhoneMount}+ onApi={handlePhoneApi}scale={1}zoom={1}shadowIntensity={imagePhoneShadow}@@ -2204,16 +2255,9 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functinitialRotationX={imagePhoneRotX}initialRotationY={imagePhoneRotY}initialRotationZ={imagePhoneRotZ}- onRotationChange={(rx, ry) => {- setImagePhoneRotX(rx);- setImagePhoneRotY(ry);- }}- onMount={(canvas) => {- imagePhoneCanvasRef.current = canvas;- }}- onApi={(api) => {- imagePhoneApiRef.current = api;- }}+ onRotationChange={handlePhoneRotationChange}+ onMount={handlePhoneMount}+ onApi={handlePhoneApi}scale={1}zoom={1}shadowIntensity={imagePhoneShadow}@@ -2234,16 +2278,9 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functzoom={1}shadowIntensity={imagePhoneShadow}shadowColor={imagePhoneShadowColor}- onRotationChange={(rx, ry) => {- setImagePhoneRotX(rx);- setImagePhoneRotY(ry);- }}- onMount={(canvas) => {- imagePhoneCanvasRef.current = canvas;- }}- onApi={(api) => {- imagePhoneApiRef.current = api;- }}+ onRotationChange={handlePhoneRotationChange}+ onMount={handlePhoneMount}+ onApi={handlePhoneApi}/>)}</div>@@ -2475,3 +2512,4 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct</div>);});+export const VideoCanvas = memo(VideoCanvasInner);\ No newline at end of filediff --git a/components/ui/DeviceCard.tsx b/components/ui/DeviceCard.tsxindex 3f13b7d..7faaf70 100644--- a/components/ui/DeviceCard.tsx+++ b/components/ui/DeviceCard.tsx@@ -1,5 +1,6 @@-import { IMAGE_DEVICE_TEMPLATES } from "@/types";+import { useEffect, useRef, useState } from "react";import { Icon } from "@iconify/react";+import { IMAGE_DEVICE_TEMPLATES } from "@/types";export function DeviceCard({tpl,@@ -10,59 +11,119 @@ export function DeviceCard({isActive: boolean;onClick: () => void;}) {+ const videoRef = useRef<HTMLVideoElement | null>(null);+ const [isHovering, setIsHovering] = useState(false);+ const [videoReady, setVideoReady] = useState(false);++ useEffect(() => {+ const video = videoRef.current;+ if (!video) return;++ if (isHovering) {+ const play = async () => {+ try {+ await video.play();+ } catch {+ }+ };+ play();+ } else {+ video.pause();+ video.currentTime = 0;+ }+ }, [isHovering]);return (<div className="relative w-40 shrink-0 snap-start mt-0.5"><buttontype="button"onClick={onClick}- className={`group flex h-full w-full flex-col overflow-hidden rounded-2xl border text-left transition-all duration-300 active:scale-[0.98] ${isActive+ onMouseEnter={() => setIsHovering(true)}+ onMouseLeave={() => setIsHovering(false)}+ className={`group flex h-full w-full overflow-hidden rounded-2xl border text-left transition-all duration-300 active:scale-[0.98] ${isActive? "border-white/20 bg-[#1a1a1e]": "border-white/6 bg-[#17171a] hover:border-white/20"}`}>- <div className="relative aspect-3/4 w-full shrink-0 bg-[#0d0d10]">+ <div className="relative aspect-3/4 w-full overflow-hidden bg-[#0d0d10]"><div- className="absolute inset-0"+ className="absolute inset-0 z-10"style={{background: isActive? `linear-gradient(135deg, ${tpl.accentColor}22 0%, transparent 70%)`: `linear-gradient(135deg, ${tpl.accentColor}10 0%, transparent 70%)`,}}/>- <div className="absolute inset-0 flex items-center justify-center">- <Icon- icon={tpl.icon}- width="22"- style={{- color: isActive ? `${tpl.accentColor}cc` : `${tpl.accentColor}55`,- }}- />++ <img+ src={tpl.posterUrl}+ alt={tpl.title}+ draggable={false}+ className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${isHovering ? "scale-105 opacity-0" : "scale-100 opacity-100"+ }`}+ />++ <video+ ref={videoRef}+ src={tpl.videoUrl}+ poster={tpl.posterUrl}+ muted+ loop+ playsInline+ preload="metadata"+ onLoadedData={() => setVideoReady(true)}+ className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${isHovering && videoReady+ ? "scale-105 opacity-100"+ : "scale-100 opacity-0"+ }`}+ />++ <div+ className={`absolute inset-0 z-20 bg-black/20 transition-opacity duration-300 ${isHovering ? "opacity-100" : "opacity-0"+ }`}+ />++ <div+ className={`absolute inset-x-0 bottom-0 z-30 transition-all duration-300 ${isHovering+ ? "translate-y-0 opacity-100"+ : "translate-y-3 opacity-0"+ }`}+ >+ <div className="absolute inset-0 h-24 bg-gradient-to-t from-black via-black/70 to-transparent" />++ <div className="relative flex items-center gap-2 p-3">+ <Icon+ icon={tpl.icon}+ width={10}+ />+ <span className="truncate text-[10px] font-medium text-white">+ {tpl.title}+ </span>+ </div></div>{isActive && (<div- className="absolute top-1.5 right-1.5 size-4 rounded-full flex items-center justify-center"- style={{ background: tpl.accentColor }}+ className="absolute top-2 right-2 z-40 flex size-4 items-center justify-center rounded-full"+ style={{+ background: tpl.accentColor,+ }}>- <Icon icon="mdi:check-bold" width={9} className="text-white" />+ <Icon+ icon="mdi:check-bold"+ width={8}+ className="text-white"+ /></div>)}</div>-- <div className="border-t border-white/5 bg-[#111113] px-3 py-2.5">- <h3- className={`truncate text-xs font-semibold ${isActive ? "text-white" : "text-white/60"- }`}- >- {tpl.title}- </h3>- </div></button>{isActive && (<divclassName="pointer-events-none absolute inset-0 rounded-2xl"- style={{ boxShadow: `inset 0 0 0 1.5px ${tpl.accentColor}88` }}+ style={{+ boxShadow: `inset 0 0 0 1.5px ${tpl.accentColor}88`,+ }}/>)}</div>