Create professional demos and 3D mockups in seconds, directly in your browser
fix: update render drei quality mockups
CristianOlivera13fd4cb14186a
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsxindex d5de10f..add2e71 100644--- a/app/[locale]/(editor)/editor/page.tsx+++ b/app/[locale]/(editor)/editor/page.tsx@@ -20,7 +20,7 @@ import { addVideoToLibrary, addVideoToLibraryWithMetadata, getLibraryVideoCount,import { calculateTotalDuration, findNextClipPosition, getClipAtTime, type VideoTrackClip } from "@/types/video-track.types";import type { ExportQuality, Tool, BackgroundTab, VideoCanvasHandle, BackgroundColorConfig, AspectRatio, CropArea, ZoomFragment, AudioTrack, ImageExportFormat } from "@/types";import type { TrimRange } from "@/types/timeline.types";-import type { MockupConfig } from "@/types/mockup.types";+import type { MockupConfig, MenuPage } from "@/types/mockup.types";import type { EditorState } from "@/types/editor-state.types";import { createInitialEditorState } from "@/types/editor-state.types";import { DEFAULT_MOCKUP_CONFIG, getMockupDefaultConfig } from "@/types/mockup.types";@@ -147,6 +147,11 @@ export default function Editor() {const [shadows, setShadows] = useState(10);const [isControlPanelOpen, setIsControlPanelOpen] = useState(true);const [isMobileControlPanelOpen, setIsMobileControlPanelOpen] = useState(false);+ // Initial page for the MockupMenu when the user clicks a mockup already+ // applied on the canvas. Updated by handleMockupClick; consumed by the+ // MockupMenu via the `initialPage` prop (resets to "home" on remount when+ // the menu is collapsed/expanded).+ const [initialMockupMenuPage, setInitialMockupMenuPage] = useState<MenuPage>("home");// Video transform state (rotation and position)const [videoTransform, setVideoTransform] = useState<{ rotation: number; translateX: number; translateY: number }>({@@ -1102,6 +1107,15 @@ export default function Editor() {setMockupConfig(prev => ({ ...prev, ...updates }));}, []);+ // Click on a mockup that's already applied on the canvas: open the mockup+ // menu directly on the config page of that frame. Called by VideoCanvas+ // (see onMockupClick in VideoCanvasProps).+ const handleMockupClick = useCallback((kind: "2d" | "3d") => {+ setInitialMockupMenuPage(kind === "2d" ? "detail-2d" : "detail-3d");+ setActiveTool("mockup");+ setIsControlPanelOpen(true);+ }, [setActiveTool]);+// Handler para cambiar las esquinas redondeadas (sincroniza ambos valores)const handleRoundedCornersChange = useCallback((value: number) => {setRoundedCorners(value); // Para NoneMockup y canvas general@@ -2984,6 +2998,7 @@ export default function Editor() {mockupConfig={mockupConfig}onMockupChange={handleMockupChange}onMockupConfigChange={handleMockupConfigChange}+ initialMockupMenuPage={initialMockupMenuPage}onAddCanvasElement={addCanvasElement}selectedCanvasElement={canvasElements.find(el => el.id === selectedElementId) || null}onUpdateCanvasElement={updateCanvasElement}@@ -3056,6 +3071,7 @@ export default function Editor() {<VideoCanvasactiveTool={activeTool}isPlaying={isPlaying}+ onMockupClick={handleMockupClick}layersPanelToolbar={<EditorTopBaronExport={handleExport}diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsxindex fd48059..4e258dd 100644--- a/app/components/ui/editor/ControlPanel.tsx+++ b/app/components/ui/editor/ControlPanel.tsx@@ -87,6 +87,10 @@ export function ControlPanel({mockupConfig,onMockupChange,onMockupConfigChange,+ // Initial page for the MockupMenu (home | detail-2d | detail-3d). Set by+ // the parent when the user clicks a mockup already applied on the canvas,+ // so the menu opens directly on the config panel of that frame.+ initialMockupMenuPage,// Canvas elements propsonAddCanvasElement,selectedCanvasElement,@@ -283,6 +287,7 @@ export function ControlPanel({backgroundTab={backgroundTab}selectedWallpaper={selectedWallpaper}selectedImageUrl={selectedImageUrl}+ initialPage={initialMockupMenuPage}/></Suspense>)}diff --git a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx b/app/components/ui/editor/IPhone13ProMax3DViewer.tsxindex 1828731..83abcf2 100644--- a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx+++ b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx@@ -1,17 +1,19 @@"use client";-import { useEffect, useRef, useState } from "react";+import { Canvas, useThree } from "@react-three/fiber";+import {+ PerspectiveCamera,+ useGLTF,+ Environment,+ OrbitControls,+} from "@react-three/drei";+import { useEffect, useRef, useState, Suspense } from "react";import * as THREE from "three";-import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";-import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";-import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";import {createCoverScreenCanvas,applyCropToImage,parseShadowColor,type ImageMaskConfigLike,- PHONE_W,- PHONE_H,} from "@/lib/phone3d.utils";export interface IPhone13ProMax3DApi {@@ -34,312 +36,129 @@ interface Props {shadowColor?: string;}-// ─── Dimensiones de textura ───────────────────────────────────────────────────+// ─── Textura de pantalla ─────────────────────────────────────────────────────const TEX_W = 1284 * 2;const TEX_H = 2778 * 2;-// ─── Caché global del GLB ─────────────────────────────────────────────────────-let gltfCachePromise: Promise<THREE.Group> | null = null;-function loadIPhoneGltf(): Promise<THREE.Group> {- if (!gltfCachePromise) {- gltfCachePromise = new Promise<THREE.Group>((resolve, reject) =>- new GLTFLoader().load(- "/models/apple_iphone_13_pro_max.glb",- (gltf) => resolve(gltf.scene as THREE.Group),- undefined,- reject- )- );- }- return gltfCachePromise;+useGLTF.preload("/models/apple_iphone_13_pro_max.glb");++// ─── Tipos del GLB ──────────────────────────────────────────────────────────+interface GLTFNodes {+ Frame_Frame_0: THREE.Mesh;+ Frame_Frame2_0: THREE.Mesh;+ Frame_Port_0: THREE.Mesh;+ Frame_Antenna_0: THREE.Mesh;+ Frame_Mic_0: THREE.Mesh;+ Body_Mic_0: THREE.Mesh;+ Body_Bezel_0: THREE.Mesh;+ Body_Body_0: THREE.Mesh;+ Body_Wallpaper_0: THREE.Mesh;+ Body_Camera_Glass_0: THREE.Mesh;+ Body_Lens_0: THREE.Mesh;+ Body_Material_0: THREE.Mesh;+ Camera_Body_0: THREE.Mesh;+ Camera_Glass_0: THREE.Mesh;+ Camera_Camera_Frame001_0: THREE.Mesh;+ Camera_Mic_0: THREE.Mesh;+ Body001_Screen_Glass_0: THREE.Mesh;+ Button_Frame_0: THREE.Mesh;+ Circle003_Frame_0: THREE.Mesh;+ Apple_Logo_Logo_0: THREE.Mesh;+ Camera001_Body_0: THREE.Mesh;+ Camera001_Gray_Glass_0: THREE.Mesh;+ Camera001_Flash_0: THREE.Mesh;+ Camera001_Port_0: THREE.Mesh;+ Camera001_Camera_Frame_0: THREE.Mesh;+ Camera001_Camera_Glass_0: THREE.Mesh;+ Camera001_Lens_0: THREE.Mesh;+ Camera001_Black_Glass_0: THREE.Mesh;+ Camera003_Material002_0: THREE.Mesh;}-// ─── Helpers matemáticos ──────────────────────────────────────────────────────-const DEG = Math.PI / 180;-function applyCameraPosition(- camera: THREE.PerspectiveCamera,- controls: OrbitControls,- rx: number,- ry: number,- zoom: number-) {- const radius = 1.5 / zoom;- const phi = Math.PI / 2 - rx * DEG;- const theta = ry * DEG;- camera.position.setFromSphericalCoords(radius, phi, theta);- controls.update();+interface GLTFMaterials {+ Frame: THREE.Material;+ Frame2: THREE.Material;+ Port: THREE.Material;+ Antenna: THREE.Material;+ material: THREE.Material;+ Bezel: THREE.Material;+ Body: THREE.Material;+ Wallpaper: THREE.Material;+ Camera_Glass: THREE.Material;+ Lens: THREE.Material;+ Material: THREE.Material;+ Glass: THREE.Material;+ "Camera_Frame.001": THREE.Material;+ Screen_Glass: THREE.Material;+ Logo: THREE.Material;+ Gray_Glass: THREE.Material;+ Flash: THREE.Material;+ Camera_Frame: THREE.Material;+ Black_Glass: THREE.Material;+ "Material.002": THREE.Material;}-export function IPhone13ProMax3DViewer({- imageUrl = null,- imageMaskConfig = null,- cropArea = null,- initialRotationX = -58.23,- initialRotationY = -29.82,- initialRotationZ = 0,+// ─── Escena 3D ──────────────────────────────────────────────────────────────+function ModelScene({+ imageUrl,+ imageMaskConfig,+ cropArea,+ initialRotationX,+ initialRotationY,+ initialRotationZ,onRotationChange,- onMount,+ rootRef,+ cameraRef,+ zoom,onApi,- scale = 1,- zoom = 1,- shadowIntensity = 0,- shadowColor = "#000000",-}: Props) {- // Referencias DOM y Three.js- const containerRef = useRef<HTMLDivElement>(null);- const rendererRef = useRef<THREE.WebGLRenderer | null>(null);- const sceneRef = useRef<THREE.Scene | null>(null);- const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);- const controlsRef = useRef<OrbitControls | null>(null);- const modelRootRef = useRef<THREE.Group | null>(null);- const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | null>(null);-- // Referencias para evitar recargas innecesarias+ onLoaded,+}: {+ imageUrl: string | null;+ imageMaskConfig: ImageMaskConfigLike | null;+ cropArea: { x: number; y: number; width: number; height: number } | null;+ initialRotationX: number;+ initialRotationY: number;+ initialRotationZ: number;+ onRotationChange?: (rx: number, ry: number) => void;+ rootRef: React.MutableRefObject<THREE.Group | null>;+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;+ zoom: number;+ onApi?: (api: IPhone13ProMax3DApi | null) => void;+ onLoaded?: () => void;+}) {+ const { gl } = useThree(); // Usamos useThree para obtener el contexto de WebGL y sus capabilities+ const gltf = useGLTF("/models/apple_iphone_13_pro_max.glb") as unknown as {+ nodes: GLTFNodes;+ materials: GLTFMaterials;+ };+ const { nodes, materials } = gltf;++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const orbitRef = useRef<any>(null);const lastLoadedImageUrlRef = useRef<string | null>(null);const lastLoadedMaskKeyRef = useRef<string | null>(null);const lastLoadedCropKeyRef = useRef<string | null>(null);- const onRotationChangeRef = useRef(onRotationChange);-- // Estados de la UI- const [loaded, setLoaded] = useState(false);- const [contextLost, setContextLost] = useState(false);- const [grabbing, setGrabbing] = useState(false);-- // Sincronizar referencias inmutables- useEffect(() => {- onRotationChangeRef.current = onRotationChange;- }, [onRotationChange]);-- // ─── Inicialización principal de Three.js ───────────────────────────────────- useEffect(() => {- const container = containerRef.current;- if (!container) return;-- // Escena- const scene = new THREE.Scene();- sceneRef.current = scene;-- // Renderizador- const renderer = new THREE.WebGLRenderer({- antialias: true,- alpha: true,- preserveDrawingBuffer: true,- powerPreference: "high-performance",- });- renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 3));- renderer.setSize(container.clientWidth, container.clientHeight, false);- renderer.outputColorSpace = THREE.SRGBColorSpace;- renderer.toneMapping = THREE.NeutralToneMapping;- renderer.toneMappingExposure = 1.0;- container.appendChild(renderer.domElement);- rendererRef.current = renderer;- onMount?.(renderer.domElement);-- // Cámara- const camera = new THREE.PerspectiveCamera(- 40,- container.clientWidth / container.clientHeight,- 0.01,- 100- );- cameraRef.current = camera;-- // Controles Orbitales (Sustituto puro de @react-three/drei OrbitControls)- const controls = new OrbitControls(camera, renderer.domElement);- controls.enableZoom = false;- controls.enablePan = false;- controls.enableDamping = true;- controls.dampingFactor = 0.08; // Misma inercia fluida que R3F- controls.addEventListener("end", () => {- const ry = controls.getAzimuthalAngle() * (180 / Math.PI);- const rx = (Math.PI / 2 - controls.getPolarAngle()) * (180 / Math.PI);- onRotationChangeRef.current?.(rx, ry);- });- controlsRef.current = controls;-- // Posición inicial- applyCameraPosition(camera, controls, initialRotationX, initialRotationY, zoom);-- // Iluminación (Replicando `<Environment preset="apartment" />` + luces directas)- const pmremGenerator = new THREE.PMREMGenerator(renderer);- pmremGenerator.compileEquirectangularShader();- scene.environment = pmremGenerator.fromScene(new RoomEnvironment(), 0.04).texture;- scene.environmentIntensity = 1.3;- scene.add(new THREE.AmbientLight(0xffffff, 0.3));-- const dl1 = new THREE.DirectionalLight(0xffffff, 0.9);- dl1.position.set(3, 6, 5);- scene.add(dl1);-- const dl2 = new THREE.DirectionalLight(0xc8d8ff, 0.5);- dl2.position.set(-4, -2, 3);- scene.add(dl2);-- const dl3 = new THREE.DirectionalLight(0xffffff, 0.5);- dl3.position.set(0, -5, 5);- scene.add(dl3);-- // Jerarquía del modelo- const rootGroup = new THREE.Group();- rootGroup.rotation.z = initialRotationZ * DEG;- scene.add(rootGroup);- modelRootRef.current = rootGroup;-- // Cargar GLB- loadIPhoneGltf()- .then((gltfScene) => {- const phone = gltfScene.clone(true);- // El R3F tenía scale={0.01} -> inner scale={100} y rotation-y={Math.PI}- // Eso equivale netamente a rotarlo en Y 180 grados sin alterar escala- phone.rotation.y = Math.PI;-- phone.traverse((child) => {- if (!(child instanceof THREE.Mesh)) return;-- child.castShadow = true;- child.receiveShadow = true;-- const material = child.material;-- const mats = Array.isArray(material) ? material : [material];-- for (const mat of mats) {- if (!(mat instanceof THREE.MeshStandardMaterial)) continue;-- // Reduce reflejos globales- mat.envMapIntensity = 0.15;- }-- // Imagen de pantalla- if (child.name.includes("Wallpaper")) {- const mat = child.material as THREE.MeshStandardMaterial;- wallpaperMatRef.current = mat;-- mat.envMapIntensity = 0;- mat.roughness = 1;- mat.metalness = 0;- mat.needsUpdate = true;- }-- // Vidrio / capa superior de la pantalla- if (- child.name.includes("Screen_Glass") ||- child.name.includes("Glass") ||- child.name.includes("Display") ||- child.name.includes("FrontGlass")- ) {- const mat = child.material as THREE.MeshStandardMaterial;-- mat.envMapIntensity = 0;- mat.roughness = 1;- mat.metalness = 0;- mat.opacity = 1;- mat.transparent = false;- mat.needsUpdate = true;- }- });-- rootGroup.add(phone);-- // Simular un pequeño retardo para asegurar que los shaders compilaron- requestAnimationFrame(() => requestAnimationFrame(() => setLoaded(true)));- })- .catch(console.error);-- // Loop de renderizado- let raf = 0;- const tick = () => {- raf = requestAnimationFrame(tick);- controls.update(); // Necesario para el damping- renderer.render(scene, camera);- };- tick();-- // Eventos DOM (Resize y Context WebGL)- const resizeObserver = new ResizeObserver(() => {- if (!container || !camera || !renderer) return;- const w = container.clientWidth;- const h = container.clientHeight;- camera.aspect = w / h;- camera.updateProjectionMatrix();- renderer.setSize(w, h, false);- });- resizeObserver.observe(container);-- const handleContextLost = (e: Event) => {- e.preventDefault();- setContextLost(true);- setLoaded(false);- };- const handleContextRestored = () => setContextLost(false);-- renderer.domElement.addEventListener("webglcontextlost", handleContextLost);- renderer.domElement.addEventListener("webglcontextrestored", handleContextRestored);-- // Limpieza al desmontar- return () => {- cancelAnimationFrame(raf);- resizeObserver.disconnect();- renderer.domElement.removeEventListener("webglcontextlost", handleContextLost);- renderer.domElement.removeEventListener("webglcontextrestored", handleContextRestored);- pmremGenerator.dispose();-- scene.traverse((obj) => {- if (obj instanceof THREE.Mesh) {- obj.geometry.dispose();- if (Array.isArray(obj.material)) obj.material.forEach((m) => m.dispose());- else obj.material.dispose();- }- });-- renderer.dispose();- if (container.contains(renderer.domElement)) {- container.removeChild(renderer.domElement);- }- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- // ─── API y Sync de Props Externas ───────────────────────────────────────────+ const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | null>(null);useEffect(() => {- if (!onApi) return;const api: IPhone13ProMax3DApi = {- renderAt: (w, h) => {- const renderer = rendererRef.current;- const camera = cameraRef.current;- const scene = sceneRef.current;- if (!renderer || !camera || !scene) return;-- const oldAspect = camera.aspect;- camera.aspect = w / h;- camera.updateProjectionMatrix();- renderer.setSize(w, h, false);- renderer.render(scene, camera);-- // Restaurar estado- camera.aspect = oldAspect;- camera.updateProjectionMatrix();- renderer.setSize(containerRef.current?.clientWidth || PHONE_W, containerRef.current?.clientHeight || PHONE_H, false);- },+ renderAt: (w, h) => { void w; void h; },};- onApi(api);- return () => onApi(null);+ onApi?.(api);+ return () => onApi?.(null);}, [onApi]);+ // Notificar que el modelo base cargó (independiente de la imagen)useEffect(() => {- if (cameraRef.current && controlsRef.current) {- applyCameraPosition(cameraRef.current, controlsRef.current, initialRotationX, initialRotationY, zoom);- }- }, [initialRotationX, initialRotationY, zoom]);+ onLoaded?.();+ }, [onLoaded]);useEffect(() => {- if (modelRootRef.current) {- modelRootRef.current.rotation.z = initialRotationZ * DEG;+ if (materials.Wallpaper) {+ wallpaperMatRef.current = materials.Wallpaper as THREE.MeshStandardMaterial;}- }, [initialRotationZ]);+ }, [materials.Wallpaper]);- // ─── Actualización de Textura de Pantalla ───────────────────────────────────useEffect(() => {const mat = wallpaperMatRef.current;if (!mat) return;@@ -348,13 +167,10 @@ export function IPhone13ProMax3DViewer({const cropKey = cropArea ? JSON.stringify(cropArea) : null;if (!imageUrl) {- if (mat.map) {- mat.map.dispose();- mat.map = null;- mat.needsUpdate = true;- }+ if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }lastLoadedImageUrlRef.current = null;lastLoadedMaskKeyRef.current = null;+ lastLoadedCropKeyRef.current = null;return;}@@ -362,41 +178,228 @@ export function IPhone13ProMax3DViewer({lastLoadedImageUrlRef.current === imageUrl &&lastLoadedMaskKeyRef.current === maskKey &&lastLoadedCropKeyRef.current === cropKey- ) {- return;- }+ ) return;const img = new Image();img.crossOrigin = "anonymous";img.onload = () => {- const cropped = applyCropToImage(img, cropArea);- const cover = createCoverScreenCanvas(cropped, TEX_W, TEX_H, 0, imageMaskConfig);-- if (mat.map) {- mat.map.dispose();- mat.map = null;- }+ // Se aplica el recorte a la imagen si cropArea está presente+ const sourceImage = cropArea ? applyCropToImage(img, cropArea) : img;+ const cover = createCoverScreenCanvas(sourceImage, TEX_W, TEX_H, 0, imageMaskConfig);+ if (mat.map) { mat.map.dispose(); mat.map = null; }const tex = new THREE.CanvasTexture(cover);- tex.flipY = true; // Se mantiene la inversión Y originaria del R3F+ 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;-++ // EL SECRETO PARA LOS ÁNGULOS: Filtro Anisotrópico al máximo+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();+mat.map = tex;mat.needsUpdate = true;-+lastLoadedImageUrlRef.current = imageUrl;lastLoadedMaskKeyRef.current = maskKey;lastLoadedCropKeyRef.current = cropKey;};img.src = imageUrl;- }, [imageUrl, imageMaskConfig, cropArea, loaded]);+ }, [imageUrl, imageMaskConfig, cropArea, gl]);++ useEffect(() => {+ const id = setTimeout(() => {+ const orbit = orbitRef.current;+ if (!orbit) return;+ const DEG = Math.PI / 180;+ const radius = 1.5 / zoom;+ const phi = Math.PI / 2 - initialRotationX * DEG;+ const theta = initialRotationY * DEG;+ orbit.object.position.setFromSphericalCoords(radius, phi, theta);+ orbit.update();+ }, 0);+ return () => clearTimeout(id);+ }, [initialRotationX, initialRotationY, zoom]);++ useEffect(() => {+ const root = rootRef.current;+ if (root) {+ root.rotation.z = initialRotationZ * (Math.PI / 180);+ }+ }, [initialRotationZ]);- // ─── Sombras y Renderizado HTML ─────────────────────────────────────────────+ return (+ <>+ <PerspectiveCamera+ ref={cameraRef}+ makeDefault+ fov={40}+ near={0.01}+ far={100}+ position={[0, 0, 1.5 / zoom]}+ />++ <OrbitControls+ ref={orbitRef}+ enableZoom={false}+ enablePan={false}+ enableDamping+ dampingFactor={0.08}+ onEnd={() => {+ const orbit = orbitRef.current;+ if (!orbit || !onRotationChange) return;+ const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);+ const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);+ onRotationChange(rx, ry);+ }}+ />++ <Environment preset="city" background={false} />+ <ambientLight intensity={0.3} />+ <directionalLight position={[3, 6, 5]} intensity={0.6} />+ <directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />+ <directionalLight position={[0, -5, 5]} intensity={0.35} />++ <group ref={rootRef} rotation={[0, Math.PI, 0]} scale={0.01} dispose={null}>+ <group scale={100}>+ <mesh castShadow receiveShadow geometry={nodes.Frame_Frame_0.geometry} material={materials.Frame} />+ <mesh castShadow receiveShadow geometry={nodes.Frame_Frame2_0.geometry} material={materials.Frame2} />+ <mesh castShadow receiveShadow geometry={nodes.Frame_Port_0.geometry} material={materials.Port} />+ <mesh castShadow receiveShadow geometry={nodes.Frame_Antenna_0.geometry} material={materials.Antenna} />+ <mesh castShadow receiveShadow geometry={nodes.Frame_Mic_0.geometry} material={materials.material} />+ <mesh castShadow receiveShadow geometry={nodes.Body_Mic_0.geometry} material={materials.material} />+ <mesh castShadow receiveShadow geometry={nodes.Body_Bezel_0.geometry} material={materials.Bezel} />+ <mesh castShadow receiveShadow geometry={nodes.Body_Body_0.geometry} material={materials.Body} />+ <mesh castShadow receiveShadow geometry={nodes.Body_Wallpaper_0.geometry} material={materials.Wallpaper} />+ <mesh castShadow receiveShadow geometry={nodes.Body_Camera_Glass_0.geometry} material={materials.Camera_Glass} />+ <mesh castShadow receiveShadow geometry={nodes.Body_Lens_0.geometry} material={materials.Lens} />+ <mesh castShadow receiveShadow geometry={nodes.Body_Material_0.geometry} material={materials.Material} />+ <mesh castShadow receiveShadow geometry={nodes.Camera_Body_0.geometry} material={materials.Body} />+ <mesh castShadow receiveShadow geometry={nodes.Camera_Glass_0.geometry} material={materials.Glass} />+ <mesh castShadow receiveShadow geometry={nodes.Camera_Camera_Frame001_0.geometry} material={materials["Camera_Frame.001"]} />+ <mesh castShadow receiveShadow geometry={nodes.Camera_Mic_0.geometry} material={materials.material} />+ <mesh castShadow receiveShadow geometry={nodes.Body001_Screen_Glass_0.geometry} material={materials.Screen_Glass} />+ <mesh castShadow receiveShadow geometry={nodes.Button_Frame_0.geometry} material={materials.Frame} />+ <mesh castShadow receiveShadow geometry={nodes.Circle003_Frame_0.geometry} material={materials.Frame} />+ <mesh castShadow receiveShadow geometry={nodes.Apple_Logo_Logo_0.geometry} material={materials.Logo} />+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Body_0.geometry} material={materials.Body} />+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Gray_Glass_0.geometry} material={materials.Gray_Glass} />+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Flash_0.geometry} material={materials.Flash} />+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Port_0.geometry} material={materials.Port} />+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Camera_Frame_0.geometry} material={materials.Camera_Frame} />+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Camera_Glass_0.geometry} material={materials.Camera_Glass} />+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Lens_0.geometry} material={materials.Lens} />+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Black_Glass_0.geometry} material={materials.Black_Glass} />+ <mesh castShadow receiveShadow geometry={nodes.Camera003_Material002_0.geometry} material={materials["Material.002"]} />+ </group>+ </group>+ </>+ );+}++// ─── CanvasWithLoader ────────────────────────────────────────────────────────+function CanvasWithLoader({+ imageUrl,+ imageMaskConfig,+ cropArea,+ initialRotationX,+ initialRotationY,+ initialRotationZ,+ onRotationChange,+ rootRef,+ cameraRef,+ zoom,+ onApi,+ onMount,+}: {+ imageUrl: string | null;+ imageMaskConfig: ImageMaskConfigLike | null;+ cropArea: { x: number; y: number; width: number; height: number } | null;+ initialRotationX: number;+ initialRotationY: number;+ initialRotationZ: number;+ onRotationChange?: (rx: number, ry: number) => void;+ rootRef: React.MutableRefObject<THREE.Group | null>;+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;+ zoom: number;+ onApi?: (api: IPhone13ProMax3DApi | null) => void;+ onMount?: (canvas: HTMLCanvasElement) => void;+}) {+ const [loaded, setLoaded] = useState(false);++ return (+ <>+ <Canvas+ style={{ width: "100%", height: "100%", overflow: "visible" }}+ gl={{+ antialias: true,+ alpha: true,+ preserveDrawingBuffer: true,+ powerPreference: "high-performance",+ failIfMajorPerformanceCaveat: false,+ }}+ dpr={3}+ onCreated={({ gl, scene }) => {+ gl.outputColorSpace = THREE.SRGBColorSpace;+ gl.toneMapping = THREE.NeutralToneMapping;+ gl.toneMappingExposure = 1.0;+ scene.environmentIntensity = 1.6;+ onMount?.(gl.domElement);+ }}+ >+ {/* Suspense es OBLIGATORIO cuando se usa useGLTF para evitar crashes */}+ <Suspense fallback={null}>+ <ModelScene+ imageUrl={imageUrl}+ imageMaskConfig={imageMaskConfig}+ cropArea={cropArea}+ initialRotationX={initialRotationX}+ initialRotationY={initialRotationY}+ initialRotationZ={initialRotationZ}+ onRotationChange={onRotationChange}+ rootRef={rootRef}+ cameraRef={cameraRef}+ zoom={zoom}+ onApi={onApi}+ onLoaded={() => setLoaded(true)}+ />+ </Suspense>+ </Canvas>++ {!loaded && (+ <div+ className="absolute inset-0 flex items-center justify-center pointer-events-none"+ style={{ zIndex: 4 }}+ >+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />+ </div>+ )}+ </>+ );+}++// ─── Componente público ──────────────────────────────────────────────────────+export function IPhone13ProMax3DViewer({+ imageUrl = null,+ imageMaskConfig = null,+ cropArea = null,+ initialRotationX = -58.23,+ initialRotationY = -29.82,+ initialRotationZ = 0,+ onRotationChange,+ onMount,+ onApi,+ scale = 1,+ zoom = 1,+ shadowIntensity = 0,+ shadowColor = "#000000",+}: Props) {+ const rootRef = useRef<THREE.Group | null>(null);+ const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);+ const [grabbing, setGrabbing] = useState(false);const t = Math.max(0, Math.min(1, shadowIntensity));const tEased = t * t;@@ -406,8 +409,7 @@ export function IPhone13ProMax3DViewer({const shadowRgba = shadowColor.startsWith("#")? parseShadowColor(shadowColor, computedOpacity): shadowColor;-- const hasShadow = t > 0.01 && loaded;+ const hasShadow = t > 0.01;return (<div@@ -417,11 +419,11 @@ export function IPhone13ProMax3DViewer({transform: `scale(${scale})`,width: 480,height: 1000 + (hasShadow ? computedBlur * 0.8 : 0),- marginTop: "20px",+ marginTop: "200px",+ marginLeft: "170px"}}><div style={{ position: "relative", width: 480, height: 1000 }}>- {/* Sombra de suelo - Aparece sólo tras la carga */}{hasShadow && (<divaria-hidden@@ -440,48 +442,38 @@ export function IPhone13ProMax3DViewer({/>)}- {/* Capa de interacción y WebGL */}<divstyle={{position: "absolute",- inset: "-200px", // Aumenta el área del WebGL y la zona de drag (880x1400 px)+ inset: "-200px",zIndex: 2,overflow: "visible",cursor: grabbing ? "grabbing" : "grab",filter: hasShadow? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`: "none",- transition: loaded ? "filter 0.15s ease" : "none",+ transition: "filter 0.15s ease",pointerEvents: "auto",}}onPointerDown={() => setGrabbing(true)}onPointerUp={() => setGrabbing(false)}onPointerLeave={() => setGrabbing(false)}>- {/* Contenedor Vanilla Three.js */}- <div- ref={containerRef}- style={{- width: "100%",- height: "100%",- opacity: loaded && !contextLost ? 1 : 0,- transition: "opacity 0.25s ease",- }}+ <CanvasWithLoader+ imageUrl={imageUrl}+ imageMaskConfig={imageMaskConfig}+ cropArea={cropArea}+ initialRotationX={initialRotationX}+ initialRotationY={initialRotationY}+ initialRotationZ={initialRotationZ}+ onRotationChange={onRotationChange}+ rootRef={rootRef}+ cameraRef={cameraRef}+ zoom={zoom}+ onApi={onApi}+ onMount={onMount}/></div>-- {/* Pantallas de Carga y Context Lost */}- {contextLost && (- <div className="absolute inset-0 flex items-center justify-center bg-black/20" style={{ zIndex: 4 }}>- <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />- </div>- )}-- {!loaded && !contextLost && (- <div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ zIndex: 4 }}>- <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />- </div>- )}</div></div>);diff --git a/app/components/ui/editor/Laptop3DViewer.tsx b/app/components/ui/editor/Laptop3DViewer.tsxindex ba20c68..13f3aea 100644--- a/app/components/ui/editor/Laptop3DViewer.tsx+++ b/app/components/ui/editor/Laptop3DViewer.tsx@@ -1,6 +1,8 @@"use client";-import { useCallback, useEffect, useRef, useState } from "react";+import { Canvas, useThree } from "@react-three/fiber";+import { PerspectiveCamera, Environment, OrbitControls } from "@react-three/drei";+import { useEffect, useRef, useState, Suspense, useCallback } from "react";import * as THREE from "three";import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";import {@@ -12,22 +14,17 @@ import {const LAPTOP_W = 1500;const LAPTOP_H = 1035;-const RENDER_MULTIPLIER = 2;+const RENDER_MULTIPLIER = 3;const RENDER_W = LAPTOP_W * RENDER_MULTIPLIER;const RENDER_H = LAPTOP_H * RENDER_MULTIPLIER;-const CAM_FOV = 40;const CAM_RADIUS = 75;-const screenSize: [number, number] = [29.4, 20];const LID_CLOSED_X = Math.PI * 0.5;const LID_OPEN_X = -0.2 * Math.PI;-const lerp = (a: number, b: number, t: number) => a + (b - a) * t;--const DAMPING_FACTOR = 0.08;+const DEG = Math.PI / 180;-const THETA_SPEED = (2 * Math.PI) / LAPTOP_W / 7;-const PHI_SPEED = Math.PI / LAPTOP_H / 7;+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;export interface Laptop3DApi {renderAt: (width: number, height: number) => void;@@ -50,7 +47,6 @@ interface Props {shadowColor?: string;}-// ─── GLB cache ────────────────────────────────────────────────────────────────let gltfCachePromise: Promise<THREE.Group> | null = null;function loadLaptopGltf(): Promise<THREE.Group> {if (!gltfCachePromise) {@@ -66,218 +62,183 @@ function loadLaptopGltf(): Promise<THREE.Group> {return gltfCachePromise;}-// ─── Angle helpers ────────────────────────────────────────────────────────────-function anglesFromInitial(rx: number, ry: number, radius: number): THREE.Vector3 {- const DEG = Math.PI / 180;- const phi = Math.PI / 2 - rx * DEG;- const theta = ry * DEG;- return new THREE.Vector3().setFromSphericalCoords(radius, phi, theta);-}--function rxRyFromCamera(camPos: THREE.Vector3): { rx: number; ry: number } {- const sph = new THREE.Spherical().setFromVector3(camPos);- const rx = (Math.PI / 2 - sph.phi) * (180 / Math.PI);- const ry = sph.theta * (180 / Math.PI);- return { rx, ry };-}--export function Laptop3DViewer({- imageUrl = null,+function ModelScene({+ imageUrl,+ imageMaskConfig,+ cropArea,openingProgress = 1,- imageMaskConfig = null,- cropArea = null,- initialRotationX = 0,- initialRotationY = 0,+ initialRotationX = 43.23,+ initialRotationY = -37.82,initialRotationZ = 0,onRotationChange,- onMount,- onApi,- scale = 1,+ rootRef,+ cameraRef,zoom = 1,- shadowIntensity = 0,- shadowColor = "#000000",-}: Props) {- const webglRef = useRef<HTMLDivElement>(null);- const rendererRef = useRef<THREE.WebGLRenderer | null>(null);- const sceneRef = useRef<THREE.Scene | null>(null);- const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);- const macGroupRef = useRef<THREE.Group | null>(null);+ onApi,+ onLoaded,+}: Props & {+ rootRef: React.MutableRefObject<THREE.Group | null>;+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;+ onLoaded?: () => void;+}) {+ const { gl, scene, camera } = useThree();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const orbitRef = useRef<any>(null);++ const [modelGroup, setModelGroup] = useState<THREE.Group | null>(null);const lidGroupRef = useRef<THREE.Group | null>(null);- const screenMaterialRef = useRef<THREE.MeshBasicMaterial | null>(null);- const lightHolderRef = useRef<THREE.Group | null>(null);- const imageUrlRef = useRef<string | null>(imageUrl);+ const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);+const lastLoadedUrlRef = useRef<string | null>(null);const lastLoadedCropKeyRef = useRef<string | null>(null);- const cropAreaRef = useRef<{ x: number; y: number; width: number; height: number } | null>(null);- const imageMaskConfigRef = useRef<ImageMaskConfigLike | null>(imageMaskConfig);- const openingProgressRef = useRef<number>(openingProgress);- const onRotationChangeRef = useRef(onRotationChange);- const onMountRef = useRef(onMount);- const onApiRef = useRef(onApi);- const zoomRef = useRef(zoom);-- const camPosRef = useRef<THREE.Vector3>(new THREE.Vector3(0, 0, CAM_RADIUS / zoom));- const camTargetRef = useRef<THREE.Vector3>(new THREE.Vector3(0, 0, CAM_RADIUS / zoom));- const velRef = useRef<{ dTheta: number; dPhi: number }>({ dTheta: 0, dPhi: 0 });- const lastPxRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });- const isDraggingRef = useRef(false);- const [grabbing, setGrabbing] = useState(false);- const [loaded, setLoaded] = useState(false);- // Sync refs- useEffect(() => { onRotationChangeRef.current = onRotationChange; }, [onRotationChange]);- useEffect(() => { onMountRef.current = onMount; }, [onMount]);- useEffect(() => { onApiRef.current = onApi; }, [onApi]);- useEffect(() => { imageUrlRef.current = imageUrl; }, [imageUrl]);- useEffect(() => { openingProgressRef.current = openingProgress; }, [openingProgress]);+ // 1. API Render EstáticouseEffect(() => {- imageMaskConfigRef.current = imageMaskConfig;- lastLoadedUrlRef.current = null;- }, [imageMaskConfig]);- useEffect(() => { zoomRef.current = zoom; }, [zoom]);- useEffect(() => { cropAreaRef.current = cropArea ?? null; }, [cropArea]);-- // ── Lid + screen opacity ──────────────────────────────────────────────────- const applyLid = useCallback(() => {- const lid = lidGroupRef.current;- const mat = screenMaterialRef.current;- if (!lid || !mat) return;- const t = Math.max(0, Math.min(1, openingProgressRef.current));- lid.rotation.x = lerp(LID_CLOSED_X, LID_OPEN_X, t);- mat.opacity = 0.96 * t;- }, []);-- // ── Screen texture ────────────────────────────────────────────────────────- const loadScreenTexture = useCallback((- url: string,- mat: THREE.MeshBasicMaterial,- renderer: THREE.WebGLRenderer- ) => {- // Skip si ya cargamos esta URL con el mismo crop- const cropKey = cropAreaRef.current ? JSON.stringify(cropAreaRef.current) : null;- if (lastLoadedUrlRef.current === url && lastLoadedCropKeyRef.current === cropKey) return;- lastLoadedUrlRef.current = url;- lastLoadedCropKeyRef.current = cropKey;+ const api: Laptop3DApi = {+ renderAt: (w, h) => {+ if (!cameraRef.current) return;+ const oldAspect = cameraRef.current.aspect;+ cameraRef.current.aspect = w / h;+ cameraRef.current.updateProjectionMatrix();+ gl.setSize(w, h, false);+ gl.render(scene, cameraRef.current);+ cameraRef.current.aspect = oldAspect;+ cameraRef.current.updateProjectionMatrix();+ gl.setSize(RENDER_W, RENDER_H, false);+ },+ };+ onApi?.(api);+ return () => onApi?.(null);+ }, [onApi, gl, scene, cameraRef]);++ // 2. Lógica de Texturas Asegurada+ const applyTexture = useCallback(() => {+ 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;+ return;+ }++ if (+ lastLoadedUrlRef.current === imageUrl &&+ lastLoadedCropKeyRef.current === cropKey &&+ mat.map !== null+ ) {+ return;+ }const img = new Image();img.crossOrigin = "anonymous";img.onload = () => {- const TEX_W = RENDER_W * 2;- const TEX_H = RENDER_H * 2;- // Aplica el crop antes del cover-fit- const cropped = applyCropToImage(img, cropAreaRef.current);- const cover = createCoverScreenCanvas(cropped, TEX_W, TEX_H, 0, imageMaskConfigRef.current);- if (mat.map) mat.map.dispose();+ const currentMat = screenMatRef.current;+ if (!currentMat) return;++ // Usamos una resolución alta para evitar pixelación+ const TEX_W = RENDER_W;+ const TEX_H = RENDER_H;++ const cropped = applyCropToImage(img, cropArea);+ const cover = createCoverScreenCanvas(cropped, TEX_W, TEX_H, 0, imageMaskConfig);++ 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.repeat.y = ((cover.width / cover.height) / screenSize[0]) * screenSize[1];}++ // MEJORA DE CALIDAD: Filtrado anisotrópico al máximo soportado por la GPUtex.generateMipmaps = true;tex.minFilter = THREE.LinearMipmapLinearFilter;tex.magFilter = THREE.LinearFilter;- tex.anisotropy = renderer.capabilities.getMaxAnisotropy();- mat.map = tex;- mat.needsUpdate = true;- lastLoadedUrlRef.current = url;- };- img.onerror = () => { lastLoadedUrlRef.current = url; };- img.src = url;- }, []);-- // ── Main Three.js setup ───────────────────────────────────────────────────- useEffect(() => {- const container = webglRef.current;- if (!container) return;-- const scene = new THREE.Scene();- sceneRef.current = scene;+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();- const radius = CAM_RADIUS / zoom;- const initPos = anglesFromInitial(initialRotationX, initialRotationY, radius);- camPosRef.current.copy(initPos);- camTargetRef.current.copy(initPos);+ currentMat.map = tex;+ currentMat.color.set(0xffffff);+ currentMat.needsUpdate = true;- const camera = new THREE.PerspectiveCamera(CAM_FOV, RENDER_W / RENDER_H, 10, 1000);- camera.position.copy(initPos);- camera.lookAt(0, 0, 0);- cameraRef.current = camera;-- // ── Lighting ──────────────────────────────────────────────────────────────- scene.add(new THREE.AmbientLight(0xffffff, 3.2));+ lastLoadedUrlRef.current = imageUrl;+ lastLoadedCropKeyRef.current = cropKey;+ };- const lightHolder = new THREE.Group();- scene.add(lightHolder);- lightHolderRef.current = lightHolder;+ img.onerror = () => {+ lastLoadedUrlRef.current = imageUrl;+ lastLoadedCropKeyRef.current = cropKey;+ };- const mainLight = new THREE.PointLight(0xfff5e1, 0.8);- mainLight.position.set(0, 5, 50);- lightHolder.add(mainLight);+ img.src = imageUrl;+ }, [imageUrl, imageMaskConfig, cropArea, gl]);- const dl1 = new THREE.DirectionalLight(0xffffff, 2.6);- dl1.position.set(4, 8, 7);- scene.add(dl1);+ const applyTextureRef = useRef(applyTexture);+ useEffect(() => {+ applyTextureRef.current = applyTexture;+ }, [applyTexture]);- const dl2 = new THREE.DirectionalLight(0xaabbff, 0.8);- dl2.position.set(-5, -2, 4);- scene.add(dl2);+ useEffect(() => {+ applyTexture();+ }, [applyTexture]);- const dl3 = new THREE.DirectionalLight(0xffffff, 1.3);- dl3.position.set(0, -6, 6);- scene.add(dl3);+ // 3. Cargar GLB del Laptop y Ensamblar Materiales+ useEffect(() => {+ let isMounted = true;- // ── Materials ─────────────────────────────────────────────────────────────- const darkPlasticMaterial = new THREE.MeshStandardMaterial({- color: 0x000000, roughness: 0.9, metalness: 0.9,- });+ const darkPlasticMaterial = new THREE.MeshStandardMaterial({ color: 0x000000, roughness: 0.9, metalness: 0.9 });const cameraMaterial = new THREE.MeshBasicMaterial({ color: 0x333333 });const logoMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });- const baseMetalMaterial = new THREE.MeshStandardMaterial({- color: 0xcecfd3, roughness: 0.25, metalness: 0.85,- });- const screenMaterial = new THREE.MeshBasicMaterial({- map: null, transparent: true, opacity: 0, side: THREE.BackSide,+ const baseMetalMaterial = new THREE.MeshStandardMaterial({ color: 0xcecfd3, roughness: 0.25, metalness: 0.85 });++ const tStart = Math.max(0, Math.min(1, openingProgress));++ // MEJORA DE CALIDAD: toneMapped: false evita que los colores de la captura se vean grises/oscuros+ const screenMaterial = new THREE.MeshBasicMaterial({+ map: null,+ transparent: true,+ opacity: 0.96 * tStart,+ side: THREE.BackSide,+ color: 0xffffff,+ toneMapped: false});- screenMaterialRef.current = screenMaterial;+ screenMatRef.current = screenMaterial;const textLoader = new THREE.TextureLoader();- const keyboardMaterial = new THREE.MeshBasicMaterial({- color: 0xffffff, transparent: true,- });+ const keyboardMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, toneMapped: false });textLoader.load("/images/pages/keyboard-overlay.png", (tex) => {+ // Filtrado nítido para el teclado también+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();keyboardMaterial.alphaMap = tex;keyboardMaterial.needsUpdate = true;});- // ── Renderer ──────────────────────────────────────────────────────────────- const renderer = new THREE.WebGLRenderer({- antialias: true, alpha: true, preserveDrawingBuffer: true,- });- const DPR = Math.min(window.devicePixelRatio || 1, 3);- renderer.setPixelRatio(DPR);- renderer.setSize(RENDER_W, RENDER_H, false);- renderer.setClearColor(0x000000, 0);- renderer.outputColorSpace = THREE.SRGBColorSpace;- renderer.toneMapping = THREE.ACESFilmicToneMapping;- renderer.toneMappingExposure = 1.5;- rendererRef.current = renderer;-- const canvas = renderer.domElement;- // Simple absolute positioning — same as v2. The parent container uses- // overflow:visible so rotated geometry is never clipped.- canvas.style.cssText = `position:absolute;top:0;left:0;width:${LAPTOP_W}px;height:${LAPTOP_H}px;pointer-events:none`;- container.appendChild(canvas);- onMountRef.current?.(canvas);-- // ── Load GLB ──────────────────────────────────────────────────────────────- loadLaptopGltf().then((gltf) => {- const root = gltf.clone(true);+ const finalizeSetup = (group: THREE.Group) => {+ if (!isMounted) return;+ setModelGroup(group);++ setTimeout(() => {+ if (!isMounted) return;+ applyTextureRef.current();+ onLoaded?.();+ }, 50);+ };++ loadLaptopGltf().then((cachedGltf) => {+ const root = cachedGltf.clone(true);root.position.z = -10;- root.rotation.set(0, 0, initialRotationZ * (Math.PI / 180));- scene.add(root);- macGroupRef.current = root;const lidGroup = new THREE.Group();const bottomGroup = new THREE.Group();@@ -299,8 +260,7 @@ export function Laptop3DViewer({if (!(obj instanceof THREE.Mesh)) return;const m = obj as THREE.Mesh;if (m.name === "base") m.material = baseMetalMaterial;- else if (["legs", "keyboard", "inner"].includes(m.name))- m.material = darkPlasticMaterial;+ else if (["legs", "keyboard", "inner"].includes(m.name)) m.material = darkPlasticMaterial;});}});@@ -309,174 +269,154 @@ export function Laptop3DViewer({root.add(bottomGroup);lidGroupRef.current = lidGroup;- const screenMesh = new THREE.Mesh(- new THREE.PlaneGeometry(screenSize[0], screenSize[1]),- screenMaterial- );+ const screenMesh = new THREE.Mesh(new THREE.PlaneGeometry(screenSize[0], screenSize[1]), screenMaterial);screenMesh.position.set(0, 10.5, -0.11);screenMesh.rotation.set(Math.PI, 0, 0);lidGroup.add(screenMesh);- const darkScreen = new THREE.Mesh(- new THREE.PlaneGeometry(screenSize[0], screenSize[1]),- darkPlasticMaterial- );+ const darkScreen = new THREE.Mesh(new THREE.PlaneGeometry(screenSize[0], screenSize[1]), darkPlasticMaterial);darkScreen.position.set(0, 10.5, -0.111);darkScreen.rotation.set(Math.PI, Math.PI, 0);lidGroup.add(darkScreen);- const keyboardKeys = new THREE.Mesh(- new THREE.PlaneGeometry(27.7, 11.6),- keyboardMaterial- );+ const keyboardKeys = new THREE.Mesh(new THREE.PlaneGeometry(27.7, 11.6), keyboardMaterial);keyboardKeys.rotation.set(-0.5 * Math.PI, 0, 0);keyboardKeys.position.set(0, 0.045, 7.21);bottomGroup.add(keyboardKeys);- if (imageUrlRef.current) {- loadScreenTexture(imageUrlRef.current, screenMaterial, renderer);- }- applyLid();- setLoaded(true);+ finalizeSetup(root);}).catch((err) => {console.error("Error al cargar el GLB del laptop:", err);});- // ── Render loop with inertia ──────────────────────────────────────────────- let raf = 0;- const EPS = 1e-6;- const tick = () => {- raf = requestAnimationFrame(tick);- const vel = velRef.current;-- if (Math.abs(vel.dTheta) > EPS || Math.abs(vel.dPhi) > EPS) {- const sph = new THREE.Spherical().setFromVector3(camPosRef.current);- sph.theta += vel.dTheta;- sph.phi = Math.max(0.05, Math.min(Math.PI - 0.05, sph.phi + vel.dPhi));- sph.radius = CAM_RADIUS / zoomRef.current;-- camPosRef.current.setFromSpherical(sph);- camera.position.copy(camPosRef.current);- camera.lookAt(0, 0, 0);-- vel.dTheta *= (1 - DAMPING_FACTOR);- vel.dPhi *= (1 - DAMPING_FACTOR);-- if (Math.abs(vel.dTheta) < EPS) vel.dTheta = 0;- if (Math.abs(vel.dPhi) < EPS) vel.dPhi = 0;- }-- if (lightHolderRef.current) {- lightHolderRef.current.quaternion.copy(camera.quaternion);- }-- renderer.render(scene, camera);- };- raf = requestAnimationFrame(tick);-- return () => {- cancelAnimationFrame(raf);- onApiRef.current?.(null);- renderer.dispose();- if (container.contains(canvas)) container.removeChild(canvas);- rendererRef.current = null;- sceneRef.current = null;- cameraRef.current = null;- macGroupRef.current = null;- lidGroupRef.current = null;- screenMaterialRef.current = null;- lightHolderRef.current = null;- };- // eslint-disable-next-line react-hooks/exhaustive-deps+ return () => { isMounted = false; };+ // eslint-disable-next-line react-hooks/exhaustive-deps}, []);- // ── Sync initialRotation props → camera ──────────────────────────────────+ // 4. Actualizar posiciones de cámara dinámicasuseEffect(() => {+ const orbit = orbitRef.current;+ if (!orbit) return;const radius = CAM_RADIUS / zoom;- const newPos = anglesFromInitial(initialRotationX, initialRotationY, radius);- velRef.current = { dTheta: 0, dPhi: 0 };- camPosRef.current.copy(newPos);- camTargetRef.current.copy(newPos);- const cam = cameraRef.current;- if (cam) { cam.position.copy(newPos); cam.lookAt(0, 0, 0); }+ const phi = Math.PI / 2 - initialRotationX * DEG;+ const theta = initialRotationY * DEG;+ orbit.object.position.setFromSphericalCoords(radius, phi, theta);+ orbit.update();}, [initialRotationX, initialRotationY, zoom]);- // ── Sync rotationZ → group ────────────────────────────────────────────────+ // 5. Animación de Apertura de Tapa y Rotación BaseuseEffect(() => {- const group = macGroupRef.current;- if (group) group.rotation.z = initialRotationZ * (Math.PI / 180);- }, [initialRotationZ]);+ if (rootRef.current) rootRef.current.rotation.z = initialRotationZ * DEG;+ }, [initialRotationZ, modelGroup]);- // ── Sync openingProgress → lid ────────────────────────────────────────────useEffect(() => {- openingProgressRef.current = openingProgress;- applyLid();- }, [openingProgress, applyLid]);+ const lid = lidGroupRef.current;+ const mat = screenMatRef.current;+ if (!lid || !mat) return;- // ── Reload screen texture ─────────────────────────────────────────────────- useEffect(() => {- const mat = screenMaterialRef.current;- const renderer = rendererRef.current;- if (!mat || !renderer || !imageUrl) return;- if (lastLoadedUrlRef.current === imageUrl) return;- loadScreenTexture(imageUrl, mat, renderer);- }, [imageUrl, loadScreenTexture]);-- // ── renderAt API ──────────────────────────────────────────────────────────- useEffect(() => {- const api: Laptop3DApi = {- renderAt: (w, h) => {- const renderer = rendererRef.current;- const camera = cameraRef.current;- const scene = sceneRef.current;- if (!renderer || !camera || !scene) return;- const oldAspect = camera.aspect;- camera.aspect = w / h;- camera.updateProjectionMatrix();- renderer.setSize(w, h, false);- renderer.render(scene, camera);- camera.aspect = oldAspect;- camera.updateProjectionMatrix();- renderer.setSize(RENDER_W, RENDER_H, false);- },- };- onApiRef.current?.(api);- return () => onApiRef.current?.(null);- }, []);+ const t = Math.max(0, Math.min(1, openingProgress));+ lid.rotation.x = lerp(LID_CLOSED_X, LID_OPEN_X, t);+ mat.opacity = 0.96 * t;+ }, [openingProgress, modelGroup]);- // ── Pointer drag ──────────────────────────────────────────────────────────- const onPointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {- isDraggingRef.current = true;- setGrabbing(true);- lastPxRef.current = { x: e.clientX, y: e.clientY };- velRef.current = { dTheta: 0, dPhi: 0 };- (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);- }, []);+ return (+ <>+ <PerspectiveCamera ref={cameraRef} makeDefault fov={CAM_FOV} near={10} far={1000} position={[0, 0, CAM_RADIUS / zoom]} />++ <OrbitControls+ ref={orbitRef}+ enableZoom={false}+ enablePan={false}+ enableDamping+ dampingFactor={0.08}+ onEnd={() => {+ const orbit = orbitRef.current;+ if (!orbit || !onRotationChange) return;+ const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);+ const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);+ onRotationChange(rx, ry);+ }}+ />++ <Environment preset="city" background={false} />+ <ambientLight intensity={3.2} />++ <group>+ <pointLight position={[0, 5, 50]} intensity={0.8} color="#fff5e1" />+ </group>++ <directionalLight position={[4, 8, 7]} intensity={2.6} />+ <directionalLight position={[-5, -2, 4]} intensity={0.8} color="#aabbff" />+ <directionalLight position={[0, -6, 6]} intensity={1.3} />++ <group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>+ {modelGroup && <primitive object={modelGroup} />}+ </group>+ </>+ );+}- const onPointerMove = useCallback((e: React.PointerEvent<HTMLDivElement>) => {- if (!isDraggingRef.current) return;- const dx = e.clientX - lastPxRef.current.x;- const dy = e.clientY - lastPxRef.current.y;- lastPxRef.current = { x: e.clientX, y: e.clientY };- velRef.current.dTheta -= dx * THETA_SPEED;- velRef.current.dPhi -= dy * PHI_SPEED;- }, []);+function CanvasWithLoader(props: Props & {+ rootRef: React.MutableRefObject<THREE.Group | null>;+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;+}) {+ const [loaded, setLoaded] = useState(false);+ const handleLoaded = useCallback(() => setLoaded(true), []);- const onPointerUp = useCallback(() => {- if (!isDraggingRef.current) return;- isDraggingRef.current = false;- setGrabbing(false);- const { rx, ry } = rxRyFromCamera(camPosRef.current);- onRotationChangeRef.current?.(rx, ry);- }, []);+ return (+ <>+ <Canvas+ style={{ width: "100%", height: "100%", overflow: "visible" }}+ gl={{+ antialias: true,+ alpha: true,+ preserveDrawingBuffer: true,+ powerPreference: "high-performance" // <-- Prioriza la GPU dedicada+ }}+ // MEJORA DE CALIDAD: Recuperamos el supersampling (DPR * Multiplicador)+ dpr={Math.min((typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1) * RENDER_MULTIPLIER, 4)}+ onCreated={({ gl }) => {+ gl.setClearColor(0x000000, 0);+ gl.outputColorSpace = THREE.SRGBColorSpace;+ gl.toneMapping = THREE.ACESFilmicToneMapping;+ gl.toneMappingExposure = 1.5;+ props.onMount?.(gl.domElement);+ }}+ >+ <Suspense fallback={null}>+ <ModelScene {...props} onLoaded={handleLoaded} />+ </Suspense>+ </Canvas>++ {!loaded && (+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ zIndex: 4 }}>+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />+ </div>+ )}+ </>+ );+}++export function Laptop3DViewer(props: Props) {+ const {+ scale = 1,+ shadowIntensity = 0,+ shadowColor = "#000000",+ } = props;++ const rootRef = useRef<THREE.Group | null>(null);+ const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);+ const [grabbing, setGrabbing] = useState(false);const t = Math.max(0, Math.min(1, shadowIntensity));const tEased = t * t;const computedBlur = tEased * 60;const computedOpacity = tEased * 0.7;+const shadowRgba = shadowColor.startsWith("#")? parseShadowColor(shadowColor, computedOpacity): shadowColor;+const hasShadow = t > 0.01;return (@@ -499,7 +439,7 @@ export function Laptop3DViewer({willChange: "transform",}}>- {/* Ground shadow ellipse */}+ {/* Sombra proyectada */}{hasShadow && (<divaria-hidden@@ -518,9 +458,8 @@ export function Laptop3DViewer({/>)}- {/* WebGL canvas container — overflow:visible lets model exceed bounds */}+ {/* Canvas WebGL Container */}<div- ref={webglRef}style={{position: "absolute",left: 0,@@ -528,37 +467,19 @@ export function Laptop3DViewer({width: LAPTOP_W,height: LAPTOP_H,overflow: "visible",- pointerEvents: "none",zIndex: 2,+ cursor: grabbing ? "grabbing" : "grab",filter: hasShadow? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`: "none",transition: "filter 0.15s ease",}}- />-- {/* Drag interaction layer */}- <div- style={{- position: "absolute",- inset: 0,- zIndex: 3,- cursor: grabbing ? "grabbing" : "grab",- }}- onPointerDown={onPointerDown}- onPointerMove={onPointerMove}- onPointerUp={onPointerUp}- onPointerLeave={onPointerUp}- />-- {!loaded && (- <div- className="absolute inset-0 flex items-center justify-center pointer-events-none"- style={{ zIndex: 4 }}- >- <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />- </div>- )}+ onPointerDown={() => setGrabbing(true)}+ onPointerUp={() => setGrabbing(false)}+ onPointerLeave={() => setGrabbing(false)}+ >+ <CanvasWithLoader {...props} rootRef={rootRef} cameraRef={cameraRef} />+ </div></div></div>);diff --git a/app/components/ui/editor/Mockup2dMenu.tsx b/app/components/ui/editor/Mockup2dMenu.tsxnew file mode 100644index 0000000..82cf2cb--- /dev/null+++ b/app/components/ui/editor/Mockup2dMenu.tsx@@ -0,0 +1,213 @@+"use client";++import { useTranslations } from "next-intl";+import { Icon } from "@iconify/react";+import { SliderControl } from "../SliderControl";+import { FRAME_COLORS, FRAME_COLORS_DARK, MockupConfig, MockupFeatures, getMockupFeatures } from "@/types/mockup.types";+import { MOCKUPS, MOCKUP_CATEGORIES } from "@/lib/mockup-data";+import { Button } from "@/components/ui/button";+import { DetailPageHeader } from "@/components/ui/DetailHeaderMenu";++export interface Mockup2dMenuProps {+ mockupId: string;+ mockupConfig?: MockupConfig;+ onMockupChange?: (mockupId: string) => void;+ onMockupConfigChange?: (config: Partial<MockupConfig>) => void;+ onBack: () => void;+}++export function Mockup2dMenu({+ mockupId,+ mockupConfig,+ onMockupChange,+ onMockupConfigChange,+ onBack,+}: Mockup2dMenuProps) {+ const t = useTranslations("mockupMenu");++ const currentMockup = MOCKUPS.find((m) => m.id === mockupId);+ const features: MockupFeatures = getMockupFeatures(currentMockup);++ const handleDarkModeChange = (isDark: boolean) => {+ const currentFrameColor = (mockupConfig?.frameColor || "#f6f6f6").toLowerCase();+ const isCurrentColorDark = FRAME_COLORS_DARK.includes(currentFrameColor);+ let newFrameColor = currentFrameColor;+ if (isDark && !isCurrentColorDark) newFrameColor = "#1e1e1e";+ else if (!isDark && isCurrentColorDark) newFrameColor = "#f6f6f6";+ onMockupConfigChange?.({ darkMode: isDark, frameColor: newFrameColor });+ };++ const handleFrameColorChange = (color: string) =>+ onMockupConfigChange?.({ frameColor: color.toLowerCase() });++ const handleUrlChange = (url: string) => onMockupConfigChange?.({ url });+ const handleHeaderScaleChange = (headerScale: number) => onMockupConfigChange?.({ headerScale });+ const handleHeaderOpacityChange = (headerOpacity: number) => onMockupConfigChange?.({ headerOpacity });++ const handleRemove = () => onMockupChange?.("none");++ return (+ <>+ <div className="flex items-center gap-2 p-3 border-b border-white/6 shrink-0">+ <DetailPageHeader+ label="Marco 2D"+ icon="hugeicons:ai-browser"+ onBack={onBack}+ />+ </div>++ <div className="p-4 flex flex-col gap-5">+ {currentMockup && (+ <div className="relative w-full h-32 squircle-element overflow-hidden bg-neutral-900 border border-blue-500/30">+ {(() => {+ const categoryConfig = MOCKUP_CATEGORIES.find(+ (c) => c.id === currentMockup.category+ );+ const bgUrl =+ categoryConfig?.bgUrl ||+ "https://i.ibb.co/r2JQ3Gcy/minimal-02.jpg";+ return (+ <div+ className="absolute inset-0 bg-cover bg-center bg-no-repeat"+ style={{ backgroundImage: `url('${bgUrl}')` }}+ />+ );+ })()}+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none">+ {currentMockup.preview}+ </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">+ {currentMockup.name}+ </span>+ </div>+ </div>+ )}++ {features.hasDarkMode && (+ <fieldset className="flex items-center justify-between w-full gap-4">+ <legend className="float-left flex items-center gap-2 text-[11px] text-white/55 whitespace-nowrap">+ <Icon icon="ph:moon-bold" width="14" aria-hidden="true" />+ <span>{t("darkMode.label")}</span>+ </legend>+ <div+ className="flex items-center gap-1 p-0.5 rounded-lg bg-white/6 border border-white/[0.07]"+ role="group"+ aria-label={t("darkMode.label")}+ >+ <button+ onClick={() => handleDarkModeChange(true)}+ className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] transition-colors ${mockupConfig?.darkMode+ ? "bg-[#09090B] border border-white/10 text-white/70"+ : "text-white/30 hover:text-white/50"+ }`}+ aria-pressed={mockupConfig?.darkMode}+ aria-label={t("darkMode.dark")}+ >+ <Icon icon="ph:moon-bold" width="10" aria-hidden="true" />{" "}+ {t("darkMode.dark")}+ </button>+ <button+ onClick={() => handleDarkModeChange(false)}+ className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] transition-colors ${!mockupConfig?.darkMode+ ? "bg-[#09090B] border border-white/10 text-white/70"+ : "text-white/30 hover:text-white/50"+ }`}+ aria-pressed={!mockupConfig?.darkMode}+ aria-label={t("darkMode.light")}+ >+ <Icon icon="ph:sun-bold" width="10" aria-hidden="true" />{" "}+ {t("darkMode.light")}+ </button>+ </div>+ </fieldset>+ )}++ {features.hasFrameColor && (+ <div className="space-y-2.5">+ <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">+ {t("frameColor.label")}+ </p>+ <div className="grid grid-cols-6 gap-2">+ {FRAME_COLORS.map((color) => (+ <button+ key={color}+ onClick={() => handleFrameColorChange(color)}+ className={`aspect-square squircle-element cursor-pointer hover:ring-2 transition shadow-sm ring-white/60 border border-white/10 ${mockupConfig?.frameColor?.toLowerCase() === color.toLowerCase()+ ? "ring-2 ring-white/90 shadow-lg shadow-white"+ : "border-white/10 border-transparent hover:border-white/30"+ }`}+ style={{ backgroundColor: color }}+ aria-label={t("frameColor.ariaLabel", { color })}+ />+ ))}+ <label className="aspect-square squircle-element border border-dashed border-white/30 bg-white/5 flex items-center justify-center hover:bg-white/10 transition group cursor-pointer relative">+ <Icon icon="mingcute:color-picker-fill" width="20" className="text-white/30" aria-hidden="true" />+ <input+ type="color"+ className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"+ onChange={(e) => handleFrameColorChange(e.target.value)}+ value={mockupConfig?.frameColor || "#ffffff"}+ />+ </label>+ </div>+ </div>+ )}++ {features.hasUrl && (+ <div className="space-y-2">+ <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">+ {t("url.label")}+ </p>+ <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-[#09090B] border border-white/[0.07] focus-within:border-blue-500/40 transition-colors">+ <Icon icon="line-md:link" width="13" className="text-white/30 shrink-0" aria-hidden="true" />+ <input+ type="text"+ value={mockupConfig?.url || ""}+ onChange={(e) => handleUrlChange(e.target.value)}+ placeholder={t("url.placeholder")}+ className="flex-1 bg-transparent text-[11px] text-white/70 placeholder:text-white/20 outline-none font-mono"+ aria-label={t("url.label")}+ />+ </div>+ </div>+ )}++ {(features.hasHeaderScale || features.hasHeaderOpacity) && (+ <div className="space-y-3">+ {features.hasHeaderScale && (+ <SliderControl+ icon="mdi:resize"+ label={t("sliders.headerScale")}+ value={mockupConfig?.headerScale ?? 70}+ min={50}+ max={100}+ onChange={handleHeaderScaleChange}+ />+ )}+ {features.hasHeaderOpacity && (+ <SliderControl+ icon="mdi:opacity"+ label={t("sliders.headerOpacity")}+ value={mockupConfig?.headerOpacity ?? 100}+ min={0}+ max={100}+ onChange={handleHeaderOpacityChange}+ />+ )}+ </div>+ )}++ <Button+ onClick={handleRemove}+ variant="outline"+ className="w-full text-xs mt-auto"+ aria-label={t("remove")}+ >+ <Icon icon="ph:trash-bold" width="13" aria-hidden="true" />+ {t("remove")}+ </Button>+ </div>+ </>+ );+}diff --git a/app/components/ui/editor/Mockup3dMenu.tsx b/app/components/ui/editor/Mockup3dMenu.tsxnew file mode 100644index 0000000..4871e55--- /dev/null+++ b/app/components/ui/editor/Mockup3dMenu.tsx@@ -0,0 +1,309 @@+"use client";++import { useRef, useState } from "react";+import { useTranslations } from "next-intl";+import { Icon } from "@iconify/react";+import { SliderControl } from "../SliderControl";+import { HANDLE_R, ImageDeviceId, PAD_H, X_HALF, Y_HALF } from "@/types/mockup.types";+import { Button } from "@/components/ui/button";+import { DetailPageHeader } from "@/components/ui/DetailHeaderMenu";++function PositionPad({+ x,+ y,+ onChangeX,+ onChangeY,+ onDragStart,+ backgroundUrl,+ backgroundColorCss,+}: {+ x: number;+ y: number;+ onChangeX: (v: number) => void;+ onChangeY: (v: number) => void;+ onDragStart?: () => void;+ backgroundUrl?: string | null;+ backgroundColorCss?: string | null;+}) {+ const padRef = useRef<HTMLDivElement>(null);+ const dragging = useRef(false);+ const [isDraggingState, setIsDraggingState] = useState(false);++ const cx = Math.max(-X_HALF, Math.min(X_HALF, x));+ const cy = Math.max(-Y_HALF, Math.min(Y_HALF, y));+ const pctX = (cx + X_HALF) / (X_HALF * 2);+ const hy = ((cy + Y_HALF) / (Y_HALF * 2)) * PAD_H;++ const fromEvent = (e: React.PointerEvent) => {+ if (!padRef.current) return;+ const rect = padRef.current.getBoundingClientRect();+ const currentWidth = rect.width;+ const rx = Math.max(0, Math.min(currentWidth, e.clientX - rect.left));+ const ry = Math.max(0, Math.min(PAD_H, e.clientY - rect.top));+ onChangeX(Math.round((rx / currentWidth) * X_HALF * 2 - X_HALF));+ onChangeY(Math.round((ry / PAD_H) * Y_HALF * 2 - Y_HALF));+ };++ const bgLayerStyle: React.CSSProperties = backgroundUrl+ ? {+ backgroundImage: `url('${backgroundUrl}')`,+ backgroundSize: "cover",+ backgroundPosition: "center",+ backgroundRepeat: "no-repeat",+ }+ : backgroundColorCss+ ? backgroundColorCss.startsWith("#") || backgroundColorCss.startsWith("rgb")+ ? { backgroundColor: backgroundColorCss }+ : {+ backgroundImage: backgroundColorCss,+ backgroundSize: "cover",+ backgroundPosition: "center",+ }+ : {};++ return (+ <div className="relative group w-full cursor-default">+ <div+ ref={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"+ }`}+ style={{ height: PAD_H }}+ onPointerDown={(e) => {+ dragging.current = true;+ setIsDraggingState(true);+ (e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);+ onDragStart?.();+ fromEvent(e);+ }}+ onPointerMove={(e) => { if (dragging.current) fromEvent(e); }}+ onPointerUp={() => {+ dragging.current = false;+ setIsDraggingState(false);+ }}+ >+ <div className="absolute inset-0 pointer-events-none" style={bgLayerStyle} />+ <div className="absolute inset-0 pointer-events-none bg-black/40" />+ {isDraggingState && (+ <div className="absolute inset-0 pointer-events-none rounded-[14px] ring-2 ring-cyan-400/30 animate-pulse" />+ )}+ <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-gradient-to-b from-transparent via-white/10 to-transparent" style={{ left: "50%" }} />+ <div className="absolute left-0 right-0 h-px bg-gradient-to-r from-transparent via-white/10 to-transparent" style={{ top: "50%" }} />+ <div className="absolute pointer-events-none bg-white/5 transition-opacity" style={{ left: `calc(${pctX * 100}%)`, top: 0, bottom: 0, width: 1 }} />+ <div className="absolute pointer-events-none bg-white/5 transition-opacity" style={{ top: hy, left: 0, right: 0, height: 1 }} />+ <div+ className={`absolute bg-white border border-white/40 rounded-full shadow-[0_0_20px_4px_rgba(255,255,255,0.12),0_4px_12px_rgba(0,0,0,0.6)] mix-blend-screen flex items-center justify-center transition-all duration-75 pointer-events-auto ${isDraggingState ? "cursor-grabbing scale-125" : "cursor-grab"+ }`}+ style={{+ width: HANDLE_R * 3,+ height: HANDLE_R * 3,+ left: `calc(${pctX * 100}% - ${HANDLE_R}px)`,+ top: hy - HANDLE_R,+ }}+ />+ </div>+ </div>+ );+}++export interface ActiveDeviceTpl {+ id: ImageDeviceId;+ title: string;+ accentColor: string;+ icon: string;+ modelUrl: string;+}++export interface Mockup3dMenuProps {+ activeDeviceTpl: ActiveDeviceTpl | null;+ imagePhoneDevice: string;+ isLaptop: boolean;++ imagePhoneScale: number;+ setImagePhoneScale: (v: number) => void;+ imagePhoneOpening: number;+ setImagePhoneOpening: (v: number) => void;+ imagePhoneShadow: number;+ setImagePhoneShadow: (v: number) => void;+ setImagePhoneShadowColor: (v: string) => void;+ imagePhoneX: number;+ setImagePhoneX: (v: number) => void;+ imagePhoneY: number;+ setImagePhoneY: (v: number) => void;+ setImagePhoneRotX: (v: number) => void;+ setImagePhoneRotY: (v: number) => void;++ pushHistory: () => void;++ backgroundUrl?: string | null;+ backgroundColorCss?: string | null;++ onBack: () => void;+ onRemove: () => void;+}++export function Mockup3dMenu({+ activeDeviceTpl,+ imagePhoneDevice,+ isLaptop,++ imagePhoneScale,+ setImagePhoneScale,+ imagePhoneOpening,+ setImagePhoneOpening,+ imagePhoneShadow,+ setImagePhoneShadow,+ setImagePhoneShadowColor,+ imagePhoneX,+ setImagePhoneX,+ imagePhoneY,+ setImagePhoneY,+ setImagePhoneRotX,+ setImagePhoneRotY,++ pushHistory,++ backgroundUrl,+ backgroundColorCss,++ onBack,+ onRemove,+}: Mockup3dMenuProps) {+ const t = useTranslations("mockupMenu");++ const handleReset = () => {+ setImagePhoneX(0);+ setImagePhoneY(0);+ setImagePhoneScale(0.8);+ setImagePhoneRotX(0);+ setImagePhoneRotY(0);+ if (imagePhoneDevice === "laptop") {+ setImagePhoneOpening(1);+ setImagePhoneShadow(0.7);+ } else {+ setImagePhoneShadow(0.4);+ }+ setImagePhoneShadowColor("#000000");+ };++ return (+ <>+ <div className="flex items-center gap-2 p-3 border-b border-white/6 shrink-0">+ <DetailPageHeader+ label="Dispositivo 3D"+ 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>+ )}++ <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+ </span>+ <button+ type="button"+ onClick={handleReset}+ 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+ </button>+ </div>++ <SliderControl+ label="Escala"+ value={Math.round(imagePhoneScale * 100)}+ min={30}+ max={300}+ step={1}+ onChange={(v) => { pushHistory(); setImagePhoneScale(v / 100); }}+ suffix="%"+ />++ {isLaptop && (+ <SliderControl+ icon="material-symbols:laptop-chromebook-outline"+ label="Apertura de laptop"+ value={Math.round(imagePhoneOpening * 100)}+ min={0}+ max={100}+ step={1}+ onChange={(v) => { pushHistory(); setImagePhoneOpening(v / 100); }}+ suffix="%"+ />+ )}++ <SliderControl+ icon="mdi:blur"+ label="Sombra"+ value={Math.round(imagePhoneShadow * 100)}+ min={0}+ max={100}+ step={1}+ onChange={(v) => { pushHistory(); setImagePhoneShadow(v / 100); }}+ suffix="%"+ />++ <div className="flex flex-col gap-2">+ <span className="text-xs text-white/60 font-medium">Posición</span>+ <PositionPad+ x={imagePhoneX}+ y={imagePhoneY}+ onChangeX={setImagePhoneX}+ onChangeY={setImagePhoneY}+ onDragStart={pushHistory}+ backgroundUrl={backgroundUrl}+ backgroundColorCss={backgroundColorCss}+ />+ </div>+ </div>++ <Button+ onClick={onRemove}+ variant="outline"+ className="w-full text-xs mt-2"+ >+ <Icon icon="ph:trash-bold" width="13" aria-hidden="true" />+ Quitar marco+ </Button>+ </div>+ </>+ );+}diff --git a/app/components/ui/editor/MockupMenu.tsx b/app/components/ui/editor/MockupMenu.tsxindex 780ea97..992b895 100644--- a/app/components/ui/editor/MockupMenu.tsx+++ b/app/components/ui/editor/MockupMenu.tsx@@ -2,116 +2,15 @@import { useState, useRef, useCallback, useEffect } from "react";import { useTranslations } from "next-intl";import { Icon } from "@iconify/react";-import { SliderControl } from "../SliderControl";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { MOCKUPS, MOCKUP_CATEGORIES } from "@/lib/mockup-data";-import { IMAGE_DEVICE_TEMPLATES, ImageDeviceId, MenuPage, MockupCategory, MockupConfig, MockupFeatures } from "@/types/mockup.types";-import { FRAME_COLORS, FRAME_COLORS_DARK, getMockupFeatures, HANDLE_R, PAD_H, X_HALF, Y_HALF } from "@/types/mockup.types";+import { IMAGE_DEVICE_TEMPLATES, ImageDeviceId, MenuPage, MockupConfig, MockupCategory } from "@/types/mockup.types";import { MockupGridSkeleton } from "../Skeleton";import { Button } from "@/components/ui/button";import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";import { getWallpaperUrl } from "@/lib/wallpaper.utils";-import { DetailPageHeader } from "@/components/ui/DetailHeaderMenu";--function PositionPad({- x,- y,- onChangeX,- onChangeY,- onDragStart,- backgroundUrl,- backgroundColorCss,-}: {- x: number;- y: number;- onChangeX: (v: number) => void;- onChangeY: (v: number) => void;- onDragStart?: () => void;- backgroundUrl?: string | null;- backgroundColorCss?: string | null;-}) {- const padRef = useRef<HTMLDivElement>(null);- const dragging = useRef(false);- const [isDraggingState, setIsDraggingState] = useState(false);-- const cx = Math.max(-X_HALF, Math.min(X_HALF, x));- const cy = Math.max(-Y_HALF, Math.min(Y_HALF, y));- const pctX = (cx + X_HALF) / (X_HALF * 2);- const hy = ((cy + Y_HALF) / (Y_HALF * 2)) * PAD_H;-- const fromEvent = (e: React.PointerEvent) => {- if (!padRef.current) return;- const rect = padRef.current.getBoundingClientRect();- const currentWidth = rect.width;- const rx = Math.max(0, Math.min(currentWidth, e.clientX - rect.left));- const ry = Math.max(0, Math.min(PAD_H, e.clientY - rect.top));- onChangeX(Math.round((rx / currentWidth) * X_HALF * 2 - X_HALF));- onChangeY(Math.round((ry / PAD_H) * Y_HALF * 2 - Y_HALF));- };-- const bgLayerStyle: React.CSSProperties = backgroundUrl- ? {- backgroundImage: `url('${backgroundUrl}')`,- backgroundSize: "cover",- backgroundPosition: "center",- backgroundRepeat: "no-repeat",- }- : backgroundColorCss- ? backgroundColorCss.startsWith("#") || backgroundColorCss.startsWith("rgb")- ? { backgroundColor: backgroundColorCss }- : {- backgroundImage: backgroundColorCss,- backgroundSize: "cover",- backgroundPosition: "center",- }- : {};-- return (- <div className="relative group w-full cursor-default">- <div- ref={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"- }`}- style={{ height: PAD_H }}- onPointerDown={(e) => {- dragging.current = true;- setIsDraggingState(true);- (e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);- onDragStart?.();- fromEvent(e);- }}- onPointerMove={(e) => { if (dragging.current) fromEvent(e); }}- onPointerUp={() => {- dragging.current = false;- setIsDraggingState(false);- }}- >- <div className="absolute inset-0 pointer-events-none" style={bgLayerStyle} />- <div className="absolute inset-0 pointer-events-none bg-black/40" />- {isDraggingState && (- <div className="absolute inset-0 pointer-events-none rounded-[14px] ring-2 ring-cyan-400/30 animate-pulse" />- )}- <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-gradient-to-b from-transparent via-white/10 to-transparent" style={{ left: "50%" }} />- <div className="absolute left-0 right-0 h-px bg-gradient-to-r from-transparent via-white/10 to-transparent" style={{ top: "50%" }} />- <div className="absolute pointer-events-none bg-white/5 transition-opacity" style={{ left: `calc(${pctX * 100}%)`, top: 0, bottom: 0, width: 1 }} />- <div className="absolute pointer-events-none bg-white/5 transition-opacity" style={{ top: hy, left: 0, right: 0, height: 1 }} />- <div- className={`absolute bg-white border border-white/40 rounded-full shadow-[0_0_20px_4px_rgba(255,255,255,0.12),0_4px_12px_rgba(0,0,0,0.6)] mix-blend-screen flex items-center justify-center transition-all duration-75 pointer-events-auto ${isDraggingState ? "cursor-grabbing scale-125" : "cursor-grab"- }`}- style={{- width: HANDLE_R * 3,- height: HANDLE_R * 3,- left: `calc(${pctX * 100}% - ${HANDLE_R}px)`,- top: hy - HANDLE_R,- }}- />- </div>- </div>- );-}+import { Mockup2dMenu } from "./Mockup2dMenu";+import { Mockup3dMenu, type ActiveDeviceTpl } from "./Mockup3dMenu";function DeviceCard({tpl,@@ -183,17 +82,23 @@ function DeviceCard({// ─── Props ────────────────────────────────────────────────────────────────────-interface MockupMenuProps {+export interface MockupMenuProps {mockupId?: string;mockupConfig?: MockupConfig;onMockupChange?: (mockupId: string) => void;onMockupConfigChange?: (config: Partial<MockupConfig>) => void;- // Background props forwarded from parent (needed for PositionPad)+ // Background props forwarded from parent (needed for PositionPad in 3D menu)backgroundUrl?: string | null;backgroundColorCss?: string | null;backgroundTab?: "wallpaper" | "image" | "color" | "unsplash";selectedWallpaper?: number;selectedImageUrl?: string;+ /**+ * Initial page when the menu first mounts. When the canvas is clicked+ * while a mockup is already applied, the parent passes "detail-2d" or+ * "detail-3d" so the user lands directly on the config of the active frame.+ */+ initialPage?: MenuPage;}// ─── MockupMenu ───────────────────────────────────────────────────────────────@@ -208,11 +113,12 @@ export function MockupMenu({backgroundTab,selectedWallpaper,selectedImageUrl,+ initialPage = "home",}: MockupMenuProps) {const t = useTranslations("mockupMenu");// ── Navigation state ──- const [page, setPage] = useState<MenuPage>("home");+ const [page, setPage] = useState<MenuPage>(initialPage);// ── 2D popover state ──const [selectedCategory, setSelectedCategory] = useState<MockupCategory>("all");@@ -327,12 +233,22 @@ export function MockupMenu({: MOCKUPS.filter((m) => m.category === selectedCategory);const currentMockup = MOCKUPS.find((m) => m.id === mockupId);- const features: MockupFeatures = getMockupFeatures(currentMockup);const activeDeviceId: ImageDeviceId | null = imagePhoneActive? (imagePhoneDevice as ImageDeviceId): null;- const activeDeviceTpl = IMAGE_DEVICE_TEMPLATES.find((t) => t.id === activeDeviceId) ?? null;+ const activeDeviceTpl: ActiveDeviceTpl | null = (() => {+ if (!imagePhoneActive) return null;+ const tpl = IMAGE_DEVICE_TEMPLATES.find((t) => t.id === activeDeviceId);+ if (!tpl) return null;+ return {+ id: tpl.id,+ title: tpl.title,+ accentColor: tpl.accentColor,+ icon: tpl.icon,+ modelUrl: tpl.modelUrl,+ };+ })();const isLaptop = imagePhoneActive && imagePhoneDevice === "laptop";const resolvedBackgroundUrl = (() => {@@ -364,22 +280,6 @@ export function MockupMenu({setTimeout(() => setGridLoaded(true), 250);};- const handleDarkModeChange = (isDark: boolean) => {- const currentFrameColor = (mockupConfig?.frameColor || "#f6f6f6").toLowerCase();- const isCurrentColorDark = FRAME_COLORS_DARK.includes(currentFrameColor);- let newFrameColor = currentFrameColor;- if (isDark && !isCurrentColorDark) newFrameColor = "#1e1e1e";- else if (!isDark && isCurrentColorDark) newFrameColor = "#f6f6f6";- onMockupConfigChange?.({ darkMode: isDark, frameColor: newFrameColor });- };-- const handleFrameColorChange = (color: string) =>- onMockupConfigChange?.({ frameColor: color.toLowerCase() });-- const handleUrlChange = (url: string) => onMockupConfigChange?.({ url });- const handleHeaderScaleChange = (headerScale: number) => onMockupConfigChange?.({ headerScale });- const handleHeaderOpacityChange = (headerOpacity: number) => onMockupConfigChange?.({ headerOpacity });-// ── Handlers: 3D ──const handleDeviceClick = (id: ImageDeviceId) => {@@ -391,37 +291,22 @@ export function MockupMenu({if (id === "iphone-13-pro-max") {setImagePhoneRotX(-58.23);setImagePhoneRotY(-29.82);+ } else if (id === "laptop") {+ setImagePhoneRotX(43.23);+ setImagePhoneRotY(-37.82);+ setImagePhoneOpening(1);+ setImagePhoneScale(1);} else {setImagePhoneRotX(0);setImagePhoneRotY(0);}- if (id === "laptop") {- setImagePhoneOpening(1);- setImagePhoneScale(1);- setImagePhoneRotX(43.23);- setImagePhoneRotY(-37.82);- }+}setImagePhoneActive(true);if (mockupId !== "none") onMockupChange?.("none");setPage("detail-3d");};- const handle3DReset = () => {- setImagePhoneX(0);- setImagePhoneY(0);- setImagePhoneScale(0.8);- setImagePhoneRotX(0);- setImagePhoneRotY(0);- if (imagePhoneDevice === "laptop") {- setImagePhoneOpening(1);- setImagePhoneShadow(0.7);- } else {- setImagePhoneShadow(0.4);- }- setImagePhoneShadowColor("#000000");- };-// ── Handlers: shared ──const handleRemoveAll = () => {@@ -431,591 +316,337 @@ export function MockupMenu({};// ─────────────────────────────────────────────────────────────────────────- // PAGE: HOME+ // PAGE: DETAIL 2D// ─────────────────────────────────────────────────────────────────────────- if (page === "home") {+ if (page === "detail-2d") {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- </p>-- {/* 2D selector trigger */}- <Popover- onOpenChange={(open) => {- if (open && !gridLoaded) {- setTimeout(() => setGridLoaded(true), 300);- }- }}- >- <PopoverTrigger asChild>- <button- 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"- }`}- aria-label={t("windowType")}- aria-haspopup="dialog"- >- <div className="flex-1 flex flex-col gap-2 h-full justify-center overflow-hidden">- <div className="w-full squircle-element overflow-hidden bg-neutral-900 relative h-full">- {(() => {- const categoryConfig = MOCKUP_CATEGORIES.find(- (c) => c.id === currentMockup?.category- );- const bgUrl =- categoryConfig?.bgUrl ||- "https://i.ibb.co/r2JQ3Gcy/minimal-02.jpg";- return (- <div- className="absolute inset-0 bg-cover bg-center bg-no-repeat transition-transform duration-500 group-hover:scale-110"- style={{ backgroundImage: `url('${bgUrl}')` }}- />- );- })()}- <div className="absolute inset-0 flex items-center justify-center pointer-events-none scale-95">- {currentMockup?.preview}- </div>- </div>- <div className="flex items-center gap-1.5">- <span className="text-[10px] font-bold tracking-wider">- {currentMockup?.name || t("none")}- </span>- </div>- </div>- <div className="flex items-center justify-center px-2 border-l border-white/5 h-full group-hover:text-white transition-colors">- <Icon icon="uil:sort" aria-hidden="true" />- </div>- </button>- </PopoverTrigger>- <PopoverContent- side="right"- align="start"- sideOffset={12}- className="w-125 p-0 border-0 shadow-2xl"- >- <div className="flex flex-col bg-[#111113] border border-white/10 rounded-xl overflow-hidden shadow-2xl max-h-150">- <div className="flex items-center gap-2 px-4 py-3 border-b border-white/10 bg-white/2 flex-wrap">- {MOCKUP_CATEGORIES.map((cat) => (- <button- key={cat.id}- onClick={() => handleCategoryChange(cat.id)}- className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[10px] font-medium uppercase tracking-wider transition-all ${selectedCategory === cat.id- ? "bg-blue-500/20 text-blue-400 border border-blue-500/40"- : "bg-white/5 text-white/50 hover:text-white/70 border border-transparent hover:border-white/10"- }`}- >- <Icon icon={cat.icon} width="12" />- <span>{cat.label}</span>- </button>- ))}- <span className="ml-auto text-[10px] text-white/60">- {t("count", { count: filteredMockups.length })}- </span>- </div>- <div className="relative overflow-y-auto custom-scrollbar overflow-x-hidden min-h-62.5">- <div- className={`absolute inset-0 w-full transition-all duration-300 ease-out z-10 ${gridLoaded- ? "opacity-0 blur-md pointer-events-none scale-105"- : "opacity-100 blur-0 scale-100"- }`}- >- <MockupGridSkeleton />- </div>- <div- className={`p-3 grid grid-cols-3 gap-2 transition-all duration-300 ease-out ${!gridLoaded- ? "opacity-0 scale-95 pointer-events-none"- : "opacity-100 scale-100"- }`}- >- {filteredMockups.map((mockup) => {- const categoryConfig = MOCKUP_CATEGORIES.find(- (c) => c.id === mockup.category- );- const isActive = mockupId === mockup.id;- return (- <button- key={mockup.id}- onClick={() => handleMockupSelect(mockup.id)}- className={`group relative w-full h-28 squircle-element border-2 overflow-hidden shadow-lg transition-all active:scale-95 ${isActive- ? "border-blue-500 ring-2 ring-blue-500/50"- : "border-neutral-800 hover:border-white/20"- }`}- >- <div- className="absolute inset-0 bg-cover bg-center bg-no-repeat transition-transform duration-500 group-hover:scale-105"- style={{- backgroundImage: `url('${categoryConfig?.bgUrl ||- "https://i.ibb.co/r2JQ3Gcy/minimal-02.jpg"- }')`,- }}- >- <div className="absolute inset-0 flex items-center justify-center pointer-events-none">- {mockup.preview}- </div>- </div>- <div className="absolute inset-0 group-hover:bg-black/5 transition-colors pointer-events-none" />- <div className="absolute bottom-0 left-0 bg-black/60 border-t border-r border-white/10 px-2 py-1 text-[9px] text-white/80 font-bold tracking-tighter rounded-tr-md rounded-bl-lg z-30">- {mockup.name}- </div>- {isActive && (- <div className="absolute top-2 right-2 rounded-full shadow-[0_0_10px_rgba(96,165,250,0.8)] z-30">- <Icon- icon="icon-park-solid:check-one"- width="20"- className="text-blue-500"- />- </div>- )}- </button>- );- })}- </div>- </div>- </div>- </PopoverContent>- </Popover>-- <div className="space-y-2">- <div className="grid grid-cols-3 gap-2">- {[- "glass-ui-container",- "macos",- "macos-glass",- "brave",- "macos-dark-ide",- "glass-curve",- ].map((id) => {- const mockup = MOCKUPS.find((m) => m.id === id);- if (!mockup) return null;- const categoryConfig = MOCKUP_CATEGORIES.find(- (c) => c.id === mockup.category- );- const isActive = mockupId === mockup.id;- return (- <button- key={id}- onClick={() => handleMockupSelect(id)}- className={`group relative w-full h-20 squircle-element border overflow-hidden transition-all active:scale-95 ${isActive- ? "border-blue-500/60 ring-1 ring-blue-500/30"- : "border-white/[0.07] hover:border-white/20"- }`}- >- <div- className="absolute inset-0 bg-cover bg-center transition-transform duration-500 group-hover:scale-105"- style={{ backgroundImage: `url('${categoryConfig?.bgUrl || ""}')` }}- >- <div className="absolute inset-0 flex items-center justify-center pointer-events-none scale-90">- {mockup.preview}- </div>- </div>- <div className="absolute bottom-0 left-0 bg-black/60 border-t border-r border-white/10 px-2 py-0.5 text-[8px] text-white/80 font-bold tracking-tighter rounded-tr-md rounded-bl-lg z-30">- {mockup.name}- </div>- {isActive && (- <div className="absolute top-1.5 right-1.5 rounded-full shadow-[0_0_8px_rgba(96,165,250,0.7)] z-30">- <Icon icon="icon-park-solid:check-one" width="14" className="text-blue-500" />- </div>- )}- </button>- );- })}- </div>- </div>- </div>+ <Mockup2dMenu+ mockupId={mockupId}+ mockupConfig={mockupConfig}+ onMockupChange={onMockupChange}+ onMockupConfigChange={onMockupConfigChange}+ onBack={() => setPage("home")}+ />+ );+ }- {/* Divider */}- <div className="h-px bg-white/[0.06]" />+ // ─────────────────────────────────────────────────────────────────────────+ // PAGE: DETAIL 3D+ // ─────────────────────────────────────────────────────────────────────────- <div className="flex flex-col gap-3">- <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">- Dispositivos 3D- </p>+ if (page === "detail-3d") {+ return (+ <Mockup3dMenu+ activeDeviceTpl={activeDeviceTpl}+ imagePhoneDevice={imagePhoneDevice}+ isLaptop={isLaptop}+ imagePhoneScale={imagePhoneScale}+ setImagePhoneScale={setImagePhoneScale}+ imagePhoneOpening={imagePhoneOpening}+ setImagePhoneOpening={setImagePhoneOpening}+ imagePhoneShadow={imagePhoneShadow}+ setImagePhoneShadow={setImagePhoneShadow}+ setImagePhoneShadowColor={setImagePhoneShadowColor}+ imagePhoneX={imagePhoneX}+ setImagePhoneX={setImagePhoneX}+ imagePhoneY={imagePhoneY}+ setImagePhoneY={setImagePhoneY}+ setImagePhoneRotX={setImagePhoneRotX}+ setImagePhoneRotY={setImagePhoneRotY}+ pushHistory={pushHistory}+ backgroundUrl={resolvedBackgroundUrl}+ backgroundColorCss={backgroundColorCss}+ onBack={() => setPage("home")}+ onRemove={handleRemoveAll}+ />+ );+ }- <div- className="relative group"- onMouseEnter={() => setIsDevicesHover(true)}- onMouseLeave={() => setIsDevicesHover(false)}- >- <div- className={`pointer-events-none absolute inset-y-0 left-0 z-20 w-10 bg-gradient-to-r from-[#141417] to-transparent transition-opacity duration-200 ${isDevicesHover && canScrollLeft ? "opacity-100" : "opacity-0"- }`}- />- <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 ${isDevicesHover && canScrollRight ? "opacity-100" : "opacity-0"- }`}- />+ // ─────────────────────────────────────────────────────────────────────────+ // PAGE: HOME+ // ─────────────────────────────────────────────────────────────────────────- <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>+ 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+ </p>++ {/* 2D selector trigger */}+ <Popover+ onOpenChange={(open) => {+ if (open && !gridLoaded) {+ setTimeout(() => setGridLoaded(true), 300);+ }+ }}+ >+ <PopoverTrigger asChild><buttontype="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"+ 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"}`}- aria-label="Scroll right"+ aria-label={t("windowType")}+ aria-haspopup="dialog">- <Icon icon="ph:caret-right-bold" width="14" />+ <div className="flex-1 flex flex-col gap-2 h-full justify-center overflow-hidden">+ <div className="w-full squircle-element overflow-hidden bg-neutral-900 relative h-full">+ {(() => {+ const categoryConfig = MOCKUP_CATEGORIES.find(+ (c) => c.id === currentMockup?.category+ );+ const bgUrl =+ categoryConfig?.bgUrl ||+ "https://i.ibb.co/r2JQ3Gcy/minimal-02.jpg";+ return (+ <div+ className="absolute inset-0 bg-cover bg-center bg-no-repeat transition-transform duration-500 group-hover:scale-110"+ style={{ backgroundImage: `url('${bgUrl}')` }}+ />+ );+ })()}+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none scale-95">+ {currentMockup?.preview}+ </div>+ </div>+ <div className="flex items-center gap-1.5">+ <span className="text-[10px] font-bold tracking-wider">+ {currentMockup?.name || t("none")}+ </span>+ </div>+ </div>+ <div className="flex items-center justify-center px-2 border-l border-white/5 h-full group-hover:text-white transition-colors">+ <Icon icon="uil:sort" aria-hidden="true" />+ </div></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>- </div>- </div>-- {/* ── Remove button (unified) ── */}- {hasActiveFrame && (- <Button- onClick={handleRemoveAll}- variant="outline"- className="w-full text-xs"- aria-label={t("remove")}+ </PopoverTrigger>+ <PopoverContent+ side="right"+ align="start"+ sideOffset={12}+ className="w-125 p-0 border-0 shadow-2xl">- <Icon icon="ph:trash-bold" width="13" aria-hidden="true" />- {t("remove")}- </Button>- )}- </div>- );- }-- // ─────────────────────────────────────────────────────────────────────────- // PAGE: DETAIL 2D- // ─────────────────────────────────────────────────────────────────────────-- if (page === "detail-2d") {- return (- <>- <div className="flex items-center gap-2 p-3 border-b border-white/6 shrink-0">- <DetailPageHeader- label="Marco 2D"- icon="hugeicons:ai-browser"- onBack={() => setPage("home")}- />- </div>-- <div className="p-4 flex flex-col gap-5">-- {currentMockup && (- <div className="relative w-full h-32 squircle-element overflow-hidden bg-neutral-900 border border-blue-500/30">- {(() => {- const categoryConfig = MOCKUP_CATEGORIES.find(- (c) => c.id === currentMockup.category- );- const bgUrl =- categoryConfig?.bgUrl ||- "https://i.ibb.co/r2JQ3Gcy/minimal-02.jpg";- return (- <div- className="absolute inset-0 bg-cover bg-center bg-no-repeat"- style={{ backgroundImage: `url('${bgUrl}')` }}- />- );- })()}- <div className="absolute inset-0 flex items-center justify-center pointer-events-none">- {currentMockup.preview}- </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">- {currentMockup.name}+ <div className="flex flex-col bg-[#111113] border border-white/10 rounded-xl overflow-hidden shadow-2xl max-h-150">+ <div className="flex items-center gap-2 px-4 py-3 border-b border-white/10 bg-white/2 flex-wrap">+ {MOCKUP_CATEGORIES.map((cat) => (+ <button+ key={cat.id}+ onClick={() => handleCategoryChange(cat.id)}+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[10px] font-medium uppercase tracking-wider transition-all ${selectedCategory === cat.id+ ? "bg-blue-500/20 text-blue-400 border border-blue-500/40"+ : "bg-white/5 text-white/50 hover:text-white/70 border border-transparent hover:border-white/10"+ }`}+ >+ <Icon icon={cat.icon} width="12" />+ <span>{cat.label}</span>+ </button>+ ))}+ <span className="ml-auto text-[10px] text-white/60">+ {t("count", { count: filteredMockups.length })}</span></div>- </div>- )}-- {/* 2D config controls */}- {features.hasDarkMode && (- <fieldset className="flex items-center justify-between w-full gap-4">- <legend className="float-left flex items-center gap-2 text-[11px] text-white/55 whitespace-nowrap">- <Icon icon="ph:moon-bold" width="14" aria-hidden="true" />- <span>{t("darkMode.label")}</span>- </legend>- <div- className="flex items-center gap-1 p-0.5 rounded-lg bg-white/6 border border-white/[0.07]"- role="group"- aria-label={t("darkMode.label")}- >- <button- onClick={() => handleDarkModeChange(true)}- className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] transition-colors ${mockupConfig?.darkMode- ? "bg-[#09090B] border border-white/10 text-white/70"- : "text-white/30 hover:text-white/50"+ <div className="relative overflow-y-auto custom-scrollbar overflow-x-hidden min-h-62.5">+ <div+ className={`absolute inset-0 w-full transition-all duration-300 ease-out z-10 ${gridLoaded+ ? "opacity-0 blur-md pointer-events-none scale-105"+ : "opacity-100 blur-0 scale-100"}`}- aria-pressed={mockupConfig?.darkMode}- aria-label={t("darkMode.dark")}>- <Icon icon="ph:moon-bold" width="10" aria-hidden="true" />{" "}- {t("darkMode.dark")}- </button>- <button- onClick={() => handleDarkModeChange(false)}- className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] transition-colors ${!mockupConfig?.darkMode- ? "bg-[#09090B] border border-white/10 text-white/70"- : "text-white/30 hover:text-white/50"+ <MockupGridSkeleton />+ </div>+ <div+ className={`p-3 grid grid-cols-3 gap-2 transition-all duration-300 ease-out ${!gridLoaded+ ? "opacity-0 scale-95 pointer-events-none"+ : "opacity-100 scale-100"}`}- aria-pressed={!mockupConfig?.darkMode}- aria-label={t("darkMode.light")}>- <Icon icon="ph:sun-bold" width="10" aria-hidden="true" />{" "}- {t("darkMode.light")}- </button>- </div>- </fieldset>- )}-- {features.hasFrameColor && (- <div className="space-y-2.5">- <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">- {t("frameColor.label")}- </p>- <div className="grid grid-cols-6 gap-2">- {FRAME_COLORS.map((color) => (- <button- key={color}- onClick={() => handleFrameColorChange(color)}- className={`aspect-square squircle-element cursor-pointer hover:ring-2 transition shadow-sm ring-white/60 border border-white/10 ${mockupConfig?.frameColor?.toLowerCase() === color.toLowerCase()- ? "ring-2 ring-white/90 shadow-lg shadow-white"- : "border-white/10 border-transparent hover:border-white/30"- }`}- style={{ backgroundColor: color }}- aria-label={t("frameColor.ariaLabel", { color })}- />- ))}- <label className="aspect-square squircle-element border border-dashed border-white/30 bg-white/5 flex items-center justify-center hover:bg-white/10 transition group cursor-pointer relative">- <Icon icon="mingcute:color-picker-fill" width="20" className="text-white/30" aria-hidden="true" />- <input- type="color"- className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"- onChange={(e) => handleFrameColorChange(e.target.value)}- value={mockupConfig?.frameColor || "#ffffff"}- />- </label>- </div>- </div>- )}-- {features.hasUrl && (- <div className="space-y-2">- <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">- {t("url.label")}- </p>- <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-[#09090B] border border-white/[0.07] focus-within:border-blue-500/40 transition-colors">- <Icon icon="line-md:link" width="13" className="text-white/30 shrink-0" aria-hidden="true" />- <input- type="text"- value={mockupConfig?.url || ""}- onChange={(e) => handleUrlChange(e.target.value)}- placeholder={t("url.placeholder")}- className="flex-1 bg-transparent text-[11px] text-white/70 placeholder:text-white/20 outline-none font-mono"- aria-label={t("url.label")}- />- </div>- </div>- )}-- {(features.hasHeaderScale || features.hasHeaderOpacity) && (- <div className="space-y-3">- {features.hasHeaderScale && (- <SliderControl- icon="mdi:resize"- label={t("sliders.headerScale")}- value={mockupConfig?.headerScale ?? 70}- min={50}- max={100}- onChange={handleHeaderScaleChange}- />- )}- {features.hasHeaderOpacity && (- <SliderControl- icon="mdi:opacity"- label={t("sliders.headerOpacity")}- value={mockupConfig?.headerOpacity ?? 100}- min={0}- max={100}- onChange={handleHeaderOpacityChange}- />- )}- </div>- )}-- <Button- onClick={handleRemoveAll}- variant="outline"- className="w-full text-xs mt-auto"- aria-label={t("remove")}- >- <Icon icon="ph:trash-bold" width="13" aria-hidden="true" />- {t("remove")}- </Button>- </div>- </>- );- }-- if (page === "detail-3d") {- return (- <>- <div className="flex items-center gap-2 p-3 border-b border-white/6 shrink-0">- <DetailPageHeader- label="Dispositivo 3D"- icon="mage:box-3d"- onBack={() => setPage("home")}- />- </div>- <div className="flex-1 overflow-y-auto custom-scrollbar px-4 py-4 space-y-5">- {/* Active device preview — same card UI as 2D preview */}- {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" />+ {filteredMockups.map((mockup) => {+ const categoryConfig = MOCKUP_CATEGORIES.find(+ (c) => c.id === mockup.category+ );+ const isActive = mockupId === mockup.id;+ return (+ <button+ key={mockup.id}+ onClick={() => handleMockupSelect(mockup.id)}+ className={`group relative w-full h-28 squircle-element border-2 overflow-hidden shadow-lg transition-all active:scale-95 ${isActive+ ? "border-blue-500 ring-2 ring-blue-500/50"+ : "border-neutral-800 hover:border-white/20"+ }`}+ >+ <div+ className="absolute inset-0 bg-cover bg-center bg-no-repeat transition-transform duration-500 group-hover:scale-105"+ style={{+ backgroundImage: `url('${categoryConfig?.bgUrl ||+ "https://i.ibb.co/r2JQ3Gcy/minimal-02.jpg"+ }')`,+ }}+ >+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none">+ {mockup.preview}+ </div>+ </div>+ <div className="absolute inset-0 group-hover:bg-black/5 transition-colors pointer-events-none" />+ <div className="absolute bottom-0 left-0 bg-black/60 border-t border-r border-white/10 px-2 py-1 text-[9px] text-white/80 font-bold tracking-tighter rounded-tr-md rounded-bl-lg z-30">+ {mockup.name}+ </div>+ {isActive && (+ <div className="absolute top-2 right-2 rounded-full shadow-[0_0_10px_rgba(96,165,250,0.8)] z-30">+ <Icon+ icon="icon-park-solid:check-one"+ width="20"+ className="text-blue-500"+ />+ </div>+ )}+ </button>+ );+ })}+ </div></div></div>- )}-- {/* 3D config */}- {imagePhoneActive && (- <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- </span>+ </PopoverContent>+ </Popover>++ <div className="space-y-2">+ <div className="grid grid-cols-3 gap-2">+ {[+ "glass-ui-container",+ "macos",+ "macos-glass",+ "brave",+ "macos-dark-ide",+ "glass-curve",+ ].map((id) => {+ const mockup = MOCKUPS.find((m) => m.id === id);+ if (!mockup) return null;+ const categoryConfig = MOCKUP_CATEGORIES.find(+ (c) => c.id === mockup.category+ );+ const isActive = mockupId === mockup.id;+ return (<button- type="button"- onClick={handle3DReset}- className="flex items-center gap-1 text-[11px] text-white/40 hover:text-white/80 transition-colors"+ key={id}+ onClick={() => handleMockupSelect(id)}+ className={`group relative w-full h-20 squircle-element border overflow-hidden transition-all active:scale-95 ${isActive+ ? "border-blue-500/60 ring-1 ring-blue-500/30"+ : "border-white/[0.07] hover:border-white/20"+ }`}>- <Icon icon="lucide:rotate-ccw" width="11" />- Resetear+ <div+ className="absolute inset-0 bg-cover bg-center transition-transform duration-500 group-hover:scale-105"+ style={{ backgroundImage: `url('${categoryConfig?.bgUrl || ""}')` }}+ >+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none scale-90">+ {mockup.preview}+ </div>+ </div>+ <div className="absolute bottom-0 left-0 bg-black/60 border-t border-r border-white/10 px-2 py-0.5 text-[8px] text-white/80 font-bold tracking-tighter rounded-tr-md rounded-bl-lg z-30">+ {mockup.name}+ </div>+ {isActive && (+ <div className="absolute top-1.5 right-1.5 rounded-full shadow-[0_0_8px_rgba(96,165,250,0.7)] z-30">+ <Icon icon="icon-park-solid:check-one" width="14" className="text-blue-500" />+ </div>+ )}</button>- </div>+ );+ })}+ </div>+ </div>+ </div>- <SliderControl- label="Escala"- value={Math.round(imagePhoneScale * 100)}- min={30}- max={300}- step={1}- onChange={(v) => { pushHistory(); setImagePhoneScale(v / 100); }}- suffix="%"- />+ {/* Divider */}+ <div className="h-px bg-white/[0.06]" />- {isLaptop && (- <SliderControl- icon="material-symbols:laptop-chromebook-outline"- label="Apertura de laptop"- value={Math.round(imagePhoneOpening * 100)}- min={0}- max={100}- step={1}- onChange={(v) => { pushHistory(); setImagePhoneOpening(v / 100); }}- suffix="%"- />- )}-- <SliderControl- icon="mdi:blur"- label="Sombra"- value={Math.round(imagePhoneShadow * 100)}- min={0}- max={100}- step={1}- onChange={(v) => { pushHistory(); setImagePhoneShadow(v / 100); }}- suffix="%"- />+ <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-2">- <span className="text-xs text-white/60 font-medium">Posición</span>- <PositionPad- x={imagePhoneX}- y={imagePhoneY}- onChangeX={setImagePhoneX}- onChangeY={setImagePhoneY}- onDragStart={pushHistory}- backgroundUrl={resolvedBackgroundUrl}- backgroundColorCss={backgroundColorCss}- />- </div>- </div>- )}+ <div+ className="relative group"+ onMouseEnter={() => setIsDevicesHover(true)}+ onMouseLeave={() => setIsDevicesHover(false)}+ >+ <div+ className={`pointer-events-none absolute inset-y-0 left-0 z-20 w-10 bg-gradient-to-r from-[#141417] to-transparent transition-opacity duration-200 ${isDevicesHover && canScrollLeft ? "opacity-100" : "opacity-0"+ }`}+ />+ <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 ${isDevicesHover && canScrollRight ? "opacity-100" : "opacity-0"+ }`}+ />- <Button- onClick={handleRemoveAll}- variant="outline"- className="w-full text-xs mt-2"+ <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:trash-bold" width="13" aria-hidden="true" />- Quitar marco- </Button>- </div>- </>+ <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>+ </div>+ </div>- return null;-}\ No newline at end of file+ {/* ── Remove button (unified) ── */}+ {hasActiveFrame && (+ <Button+ onClick={handleRemoveAll}+ variant="outline"+ className="w-full text-xs"+ aria-label={t("remove")}+ >+ <Icon icon="ph:trash-bold" width="13" aria-hidden="true" />+ {t("remove")}+ </Button>+ )}+ </div>+ );+}diff --git a/app/components/ui/editor/Phone3DViewer.tsx b/app/components/ui/editor/Phone3DViewer.tsxindex 6051510..e039fd3 100644--- a/app/components/ui/editor/Phone3DViewer.tsx+++ b/app/components/ui/editor/Phone3DViewer.tsx@@ -1,596 +1,491 @@"use client";-import { useCallback, useEffect, useRef, useState } from "react";+import { Canvas, useThree } from "@react-three/fiber";+import { PerspectiveCamera, Environment, OrbitControls } from "@react-three/drei";+import { useEffect, useRef, useState, Suspense, useCallback } from "react";import * as THREE from "three";import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";-import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";-import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";import {- PHONE_W,- PHONE_H,- deviceConfigs,- getDeviceFromModelUrl,- createCoverScreenCanvas,- applyCropToImage,- loadGltfGroup,- cloneGroup,- type ImageMaskConfigLike,- parseShadowColor,+ PHONE_W,+ PHONE_H,+ deviceConfigs,+ getDeviceFromModelUrl,+ createCoverScreenCanvas,+ applyCropToImage,+ loadGltfGroup,+ cloneGroup,+ type ImageMaskConfigLike,+ parseShadowColor,} from "@/lib/phone3d.utils";export interface Phone3DApi {- renderAt: (width: number, height: number) => void;+ renderAt: (width: number, height: number) => void;}interface Props {- imageUrl?: string | null;- imageMaskConfig?: ImageMaskConfigLike | null;- cropArea?: { x: number; y: number; width: number; height: number } | null;- initialRotationX?: number;- initialRotationY?: number;- initialRotationZ?: number;- onRotationChange?: (rx: number, ry: number) => void;- onMount?: (canvas: HTMLCanvasElement) => void;- onApi?: (api: Phone3DApi | null) => void;- modelUrl?: string;- scale?: number;- zoom?: number;- shadowIntensity?: number;- shadowColor?: string;+ imageUrl?: string | null;+ imageMaskConfig?: ImageMaskConfigLike | null;+ cropArea?: { x: number; y: number; width: number; height: number } | null;+ initialRotationX?: number;+ initialRotationY?: number;+ initialRotationZ?: number;+ onRotationChange?: (rx: number, ry: number) => void;+ onMount?: (canvas: HTMLCanvasElement) => void;+ onApi?: (api: Phone3DApi | null) => void;+ modelUrl?: string;+ scale?: number;+ zoom?: number;+ shadowIntensity?: number;+ shadowColor?: string;}-// ─── Constantes y Helpers ─────────────────────────────────────────────────────-const DEFAULT_CAM_Z = 1.5;+// ─── Constantes y Helpers de Carga ──────────────────────────────────────────const DEG = Math.PI / 180;--// Caché global para modelos GLTF específicos (evita múltiples descargas)const specificGltfCache = new Map<string, Promise<THREE.Group>>();+function loadSpecificGltf(url: string): Promise<THREE.Group> {- if (!specificGltfCache.has(url)) {- specificGltfCache.set(- url,- new Promise((resolve, reject) => {- new GLTFLoader().load(- url,- (gltf) => resolve(gltf.scene),- undefined,- reject- );- })- );- }- return specificGltfCache.get(url)!;+ if (!specificGltfCache.has(url)) {+ specificGltfCache.set(+ url,+ new Promise((resolve, reject) => {+ new GLTFLoader().load(url, (gltf) => resolve(gltf.scene), undefined, reject);+ })+ );+ }+ return specificGltfCache.get(url)!;}function applyMetalMaterial(m: THREE.MeshStandardMaterial, matName: string): void {- if (matName.includes("Body")) { m.color.set(0x787878); m.roughness = 0.18; m.metalness = 0.85; m.envMapIntensity = 1.4; }- if (matName.includes("Bezel")) { m.color.set(0x909090); m.roughness = 0.12; m.metalness = 0.92; m.envMapIntensity = 1.6; }- if (matName.includes("Buttons")) { m.color.set(0x999999); m.roughness = 0.15; m.metalness = 0.88; m.envMapIntensity = 1.5; }- if (matName.includes("Lenses")) { m.color.set(0x060608); m.roughness = 0.04; m.metalness = 0.70; m.envMapIntensity = 2.0; }+ if (matName.includes("Body")) {+ m.color.set(0x787878); m.roughness = 0.18; m.metalness = 0.85; m.envMapIntensity = 1.4;+ }+ if (matName.includes("Bezel")) {+ m.color.set(0x909090); m.roughness = 0.12; m.metalness = 0.92; m.envMapIntensity = 1.6;+ }+ if (matName.includes("Buttons")) {+ m.color.set(0x999999); m.roughness = 0.15; m.metalness = 0.88; m.envMapIntensity = 1.5;+ }+ if (matName.includes("Lenses")) {+ m.color.set(0x060608); m.roughness = 0.04; m.metalness = 0.70; m.envMapIntensity = 2.0;+ }}-function applyCameraPosition(- camera: THREE.PerspectiveCamera,- controls: OrbitControls,- rx: number,- ry: number,- zoom: number-) {- const radius = DEFAULT_CAM_Z / zoom;- const phi = Math.PI / 2 - rx * DEG;- const theta = ry * DEG;- camera.position.setFromSphericalCoords(radius, phi, theta);- controls.update();-}+// ─── Escena 3D ──────────────────────────────────────────────────────────────+function ModelScene({+ imageUrl,+ imageMaskConfig,+ cropArea,+ initialRotationX = 0,+ initialRotationY = 0,+ initialRotationZ = 0,+ onRotationChange,+ rootRef,+ cameraRef,+ zoom = 1,+ modelUrl,+ onApi,+ onLoaded,+}: Props & {+ rootRef: React.MutableRefObject<THREE.Group | null>;+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;+ onLoaded?: () => void;+}) {+ const { gl, scene, camera } = useThree();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const orbitRef = useRef<any>(null);+ const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);+ const [modelGroup, setModelGroup] = useState<THREE.Group | null>(null);++ const lastLoadedUrlRef = useRef<string | null>(null);+ const lastLoadedCropKeyRef = useRef<string | null>(null);+ const screenAspectRef = useRef<number>(0.459);+ const flipYRef = useRef<boolean>(false);++ // 1. Configurar la API para renderizados estáticos+ useEffect(() => {+ const api: Phone3DApi = {+ renderAt: (w, h) => {+ if (!cameraRef.current) return;+ const oldAspect = cameraRef.current.aspect;+ cameraRef.current.aspect = w / h;+ cameraRef.current.updateProjectionMatrix();+ gl.setSize(w, h, false);+ gl.render(scene, cameraRef.current);+ cameraRef.current.aspect = oldAspect;+ cameraRef.current.updateProjectionMatrix();+ gl.setSize(gl.domElement.clientWidth || PHONE_W, gl.domElement.clientHeight || PHONE_H, false);+ },+ };+ onApi?.(api);+ return () => onApi?.(null);+ }, [onApi, gl, scene, cameraRef]);++ // 2. Lógica de Texturas+ const applyTexture = useCallback(() => {+ 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;+ return;+ }-// ─── Renderizador Interno Vanilla Three.js ────────────────────────────────────-interface VanillaRendererProps extends Omit<Props, "scale" | "shadowIntensity" | "shadowColor"> {- onLoaded: () => void;- onContextLost: () => void;-}+ // CLAVE DEL FIX: No solo validamos la caché, validamos que el material ACTUAL tenga la textura.+ if (+ lastLoadedUrlRef.current === imageUrl &&+ lastLoadedCropKeyRef.current === cropKey &&+ mat.map !== null+ ) {+ return;+ }-function VanillaPhoneRenderer({- imageUrl,- imageMaskConfig,- cropArea,- initialRotationX = 0,- initialRotationY = 0,- initialRotationZ = 0,- onRotationChange,- onMount,- onApi,- modelUrl,- zoom = 1,- onLoaded,- onContextLost,-}: VanillaRendererProps) {- const containerRef = useRef<HTMLDivElement>(null);- const rendererRef = useRef<THREE.WebGLRenderer | null>(null);- const sceneRef = useRef<THREE.Scene | null>(null);- const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);- const controlsRef = useRef<OrbitControls | null>(null);- const rootGroupRef = useRef<THREE.Group | null>(null);- const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);-- // Refs estables para evitar cargas innecesarias- const lastLoadedUrlRef = useRef<string | null>(null);- const lastLoadedCropKeyRef = useRef<string | null>(null);- const onRotationChangeRef = useRef(onRotationChange);- const screenAspectRef = useRef<number>(0.459); // Default fallback- const flipYRef = useRef<boolean>(false);-- useEffect(() => {- onRotationChangeRef.current = onRotationChange;- }, [onRotationChange]);-- // ─── Lógica de Texturas (Independiente de la carga del modelo) ────────────- const applyTexture = useCallback(() => {- const mat = screenMatRef.current;- const renderer = rendererRef.current;- if (!mat || !renderer) 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;- return;- }-- if (lastLoadedUrlRef.current === imageUrl && lastLoadedCropKeyRef.current === cropKey) {- return;- }-- const device = getDeviceFromModelUrl(modelUrl);- const deviceConfig = deviceConfigs[device];- const isDefaultPhone = device === "phone";-- const img = new Image();- img.crossOrigin = "anonymous";- img.onload = () => {- 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);- }-- const cropped = applyCropToImage(img, cropArea);- const cover = createCoverScreenCanvas(cropped, TARGET_W, TARGET_H, cornerRadius, imageMaskConfig);-- if (mat.map) {- mat.map.dispose();- mat.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 = renderer.capabilities.getMaxAnisotropy();-- mat.map = tex;- mat.color.set(0xffffff);- mat.needsUpdate = true;-- lastLoadedUrlRef.current = imageUrl;- lastLoadedCropKeyRef.current = cropKey;- };- img.onerror = () => {- if (mat.map) {- mat.map.dispose();- mat.map = null;- mat.needsUpdate = true;- }- mat.color.set(0x111111);- lastLoadedUrlRef.current = imageUrl;- lastLoadedCropKeyRef.current = cropKey;- };- img.src = imageUrl;- }, [imageUrl, imageMaskConfig, cropArea, modelUrl]);-- // Disparar textura al cambiar dependencias- useEffect(() => {- applyTexture();- }, [applyTexture]);-- // ─── Inicialización de la Escena ──────────────────────────────────────────- useEffect(() => {- const container = containerRef.current;- if (!container) return;-- // 1. Setup Base- const scene = new THREE.Scene();- sceneRef.current = scene;-- const renderer = new THREE.WebGLRenderer({- antialias: true,- alpha: true,- preserveDrawingBuffer: true,- powerPreference: "high-performance",- });- renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 3));- renderer.setSize(container.clientWidth, container.clientHeight, false);- renderer.outputColorSpace = THREE.SRGBColorSpace;- renderer.toneMapping = THREE.NeutralToneMapping;- renderer.toneMappingExposure = 1.0;- container.appendChild(renderer.domElement);- rendererRef.current = renderer;- onMount?.(renderer.domElement);-- const camera = new THREE.PerspectiveCamera(- 40,- container.clientWidth / container.clientHeight,- 0.01,- 100- );- cameraRef.current = camera;-- const controls = new OrbitControls(camera, renderer.domElement);- controls.enableZoom = false;- controls.enablePan = false;- controls.enableDamping = true;- controls.dampingFactor = 0.08;- controls.addEventListener("end", () => {- const ry = controls.getAzimuthalAngle() * (180 / Math.PI);- const rx = (Math.PI / 2 - controls.getPolarAngle()) * (180 / Math.PI);- onRotationChangeRef.current?.(rx, ry);- });- controlsRef.current = controls;-- applyCameraPosition(camera, controls, initialRotationX, initialRotationY, zoom);-- // 2. Luces (Equivalente exacto a SharedLights)- const pmremGenerator = new THREE.PMREMGenerator(renderer);- pmremGenerator.compileEquirectangularShader();- scene.environment = pmremGenerator.fromScene(new RoomEnvironment(), 0.04).texture;- scene.environmentIntensity = 1.6;-- scene.add(new THREE.AmbientLight(0xffffff, 0.3));-- const dl1 = new THREE.DirectionalLight(0xffffff, 0.6);- dl1.position.set(3, 6, 5);- scene.add(dl1);-- const dl2 = new THREE.DirectionalLight(0xc8d8ff, 0.25);- dl2.position.set(-4, -2, 3);- scene.add(dl2);-- const dl3 = new THREE.DirectionalLight(0xffffff, 0.35);- dl3.position.set(0, -5, 5);- scene.add(dl3);-- const rootGroup = new THREE.Group();- rootGroup.rotation.z = initialRotationZ * DEG;- scene.add(rootGroup);- rootGroupRef.current = rootGroup;-- // 3. Lógica de Carga de Modelo (Dependiente de modelUrl)- const device = getDeviceFromModelUrl(modelUrl);- const isDefaultPhone = device === "phone";-- const finalizeSetup = () => {- applyTexture();- // Asegurar que Three.js pintó el canvas antes de ocultar el spinner- requestAnimationFrame(() => {- requestAnimationFrame(() => {- onLoaded();- });- });- };-- if (isDefaultPhone) {- flipYRef.current = false;- loadGltfGroup().then((cached) => {- const group = cloneGroup(cached);- const camZ = DEFAULT_CAM_Z / zoom;- const box = new THREE.Box3().setFromObject(group);- const center = box.getCenter(new THREE.Vector3());- const size = box.getSize(new THREE.Vector3());- const halfH = camZ * Math.tan((40 / 2) * DEG);- const sf = (halfH * 2 * 0.8) / size.y;-- group.scale.setScalar(sf);- group.position.copy(center).negate().multiplyScalar(sf);-- group.traverse((child) => {- if (!(child instanceof THREE.Mesh)) return;- const mat = Array.isArray(child.material) ? child.material[0] : child.material;- const matName = (mat as THREE.Material)?.name ?? "";- const isScreen = matName === "Screen.editable" || child.name === "Screen";-- if (isScreen) {- const meshBox = new THREE.Box3().setFromObject(child);- const meshSize = meshBox.getSize(new THREE.Vector3());- if (meshSize.x > 0 && meshSize.y > 0) screenAspectRef.current = meshSize.x / meshSize.y;-- const basicMat = new THREE.MeshBasicMaterial({- color: 0x111111,- side: THREE.FrontSide,- transparent: true,- depthTest: false,- depthWrite: false,- });- child.material = basicMat;- child.renderOrder = 10;- screenMatRef.current = basicMat;- } else if (mat.isMeshStandardMaterial) {- applyMetalMaterial(mat, matName);- }- });-- rootGroup.add(group);- finalizeSetup();+ 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);+ }++ const cropped = applyCropToImage(img, cropArea);+ const cover = createCoverScreenCanvas(+ cropped,+ TARGET_W,+ TARGET_H,+ cornerRadius,+ imageMaskConfig+ );++ 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); // BLANCO PURO PARA REVELAR LA TEXTURA+ currentMat.needsUpdate = true;++ lastLoadedUrlRef.current = imageUrl;+ lastLoadedCropKeyRef.current = cropKey;+ };++ img.onerror = () => {+ const currentMat = screenMatRef.current;+ if (!currentMat) return;+ if (currentMat.map) {+ currentMat.map.dispose();+ currentMat.map = null;+ }+ currentMat.color.set(0x111111);+ currentMat.needsUpdate = true;+ lastLoadedUrlRef.current = imageUrl;+ lastLoadedCropKeyRef.current = cropKey;+ };++ img.src = imageUrl;+ }, [imageUrl, imageMaskConfig, cropArea, modelUrl, gl]);++ const applyTextureRef = useRef(applyTexture);+ useEffect(() => {+ applyTextureRef.current = applyTexture;+ }, [applyTexture]);++ useEffect(() => {+ applyTexture();+ }, [applyTexture]);++ // 3. Cargar el Modelo Dinámico+ useEffect(() => {+ let isMounted = true;+ const device = getDeviceFromModelUrl(modelUrl);+ const isDefaultPhone = device === "phone";++ const finalizeSetup = (group: THREE.Group) => {+ if (!isMounted) return;+ setModelGroup(group);++ // Retrasamos unos milisegundos para asegurar que Three ha inyectado el nodo+ setTimeout(() => {+ if (!isMounted) return;+ applyTextureRef.current();+ onLoaded?.();+ }, 50);+ };++ if (isDefaultPhone) {+ flipYRef.current = false;+ loadGltfGroup().then((cached) => {+ const group = cloneGroup(cached);+ // Usamos zoom default aquí para montar el tamaño base. El useEffect dinámico hará el resto.+ const camZ = 1.5;+ const box = new THREE.Box3().setFromObject(group);+ const center = box.getCenter(new THREE.Vector3());+ const size = box.getSize(new THREE.Vector3());+ const halfH = camZ * Math.tan((40 / 2) * DEG);+ const sf = (halfH * 2 * 0.8) / size.y;++ group.scale.setScalar(sf);+ group.position.copy(center).negate().multiplyScalar(sf);++ group.traverse((child) => {+ if (!(child instanceof THREE.Mesh)) return;+ const mat = Array.isArray(child.material) ? child.material[0] : child.material;+ const matName = (mat as THREE.Material)?.name ?? "";+ const isScreen = matName === "Screen.editable" || child.name === "Screen";++ if (isScreen) {+ const meshBox = new THREE.Box3().setFromObject(child);+ const meshSize = meshBox.getSize(new THREE.Vector3());+ if (meshSize.x > 0 && meshSize.y > 0) screenAspectRef.current = meshSize.x / meshSize.y;++ const basicMat = new THREE.MeshBasicMaterial({+ color: 0x111111, side: THREE.FrontSide, transparent: true, depthTest: false, depthWrite: false,});- } else {- flipYRef.current = true;- loadSpecificGltf(modelUrl!).then((loadedScene) => {- const group = loadedScene.clone(true);- const camZ = DEFAULT_CAM_Z / zoom;- const box = new THREE.Box3().setFromObject(group);- const center = box.getCenter(new THREE.Vector3());- const size = box.getSize(new THREE.Vector3());- const halfH = camZ * Math.tan((40 / 2) * DEG);- const sf = (halfH * 2 * 0.8) / size.y;-- group.scale.setScalar(sf);- group.position.copy(center).negate().multiplyScalar(sf);-- const deviceConfig = deviceConfigs[device];- const planeH = 4.3 * deviceConfig.screenHeightFactor;- const planeW = planeH * deviceConfig.aspectRatio;-- const basicMat = new THREE.MeshBasicMaterial({- color: 0x111111,- side: THREE.FrontSide,- transparent: true,- depthTest: false,- depthWrite: false,- });- screenMatRef.current = basicMat;-- const plane = new THREE.Mesh(new THREE.PlaneGeometry(planeW, planeH), basicMat);- plane.position.set(deviceConfig.screenOffset.x, deviceConfig.screenOffset.y, deviceConfig.screenOffset.z);- plane.renderOrder = 10;- group.add(plane);-- rootGroup.add(group);- finalizeSetup();- });- }-- // 4. Render Loop- let raf = 0;- const tick = () => {- raf = requestAnimationFrame(tick);- controls.update();- renderer.render(scene, camera);- };- tick();-- // 5. Eventos y Cleanup- const resizeObserver = new ResizeObserver(() => {- if (!container || !camera || !renderer) return;- const w = container.clientWidth;- const h = container.clientHeight;- camera.aspect = w / h;- camera.updateProjectionMatrix();- renderer.setSize(w, h, false);+ child.material = basicMat;+ child.renderOrder = 10;+ screenMatRef.current = basicMat;+ } else if (mat.isMeshStandardMaterial) {+ applyMetalMaterial(mat, matName);+ }});- resizeObserver.observe(container);-- const handleCtxLost = (e: Event) => {- e.preventDefault();- onContextLost();- };- renderer.domElement.addEventListener("webglcontextlost", handleCtxLost);-- return () => {- cancelAnimationFrame(raf);- resizeObserver.disconnect();- renderer.domElement.removeEventListener("webglcontextlost", handleCtxLost);- pmremGenerator.dispose();-- scene.traverse((obj) => {- if (obj instanceof THREE.Mesh) {- obj.geometry.dispose();- if (Array.isArray(obj.material)) obj.material.forEach((m) => m.dispose());- else obj.material.dispose();- }- });- renderer.dispose();- if (container.contains(renderer.domElement)) {- container.removeChild(renderer.domElement);- }- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []); // Se ejecuta una vez por montaje (controlado por el prop `key` del padre)-- // ─── Sync Dinámico (Zoom, Rotaciones y API) ─────────────────────────────────- useEffect(() => {- if (cameraRef.current && controlsRef.current) {- applyCameraPosition(cameraRef.current, controlsRef.current, initialRotationX, initialRotationY, zoom);- }- }, [initialRotationX, initialRotationY, zoom]);-- useEffect(() => {- if (rootGroupRef.current) {- rootGroupRef.current.rotation.z = initialRotationZ * DEG;- }- }, [initialRotationZ]);-- useEffect(() => {- if (!onApi) return;- const api: Phone3DApi = {- renderAt: (w, h) => {- const renderer = rendererRef.current;- const camera = cameraRef.current;- const scene = sceneRef.current;- if (!renderer || !camera || !scene) return;-- const oldAspect = camera.aspect;- camera.aspect = w / h;- camera.updateProjectionMatrix();- renderer.setSize(w, h, false);- renderer.render(scene, camera);-- camera.aspect = oldAspect;- camera.updateProjectionMatrix();- renderer.setSize(containerRef.current?.clientWidth || PHONE_W, containerRef.current?.clientHeight || PHONE_H, false);- },- };- onApi(api);- return () => onApi(null);- }, [onApi]);-- return <div ref={containerRef} style={{ width: "100%", height: "100%" }} />;+ finalizeSetup(group);+ });+ } else {+ flipYRef.current = true;+ loadSpecificGltf(modelUrl!).then((loadedScene) => {+ const group = loadedScene.clone(true);+ const camZ = 1.5;+ const box = new THREE.Box3().setFromObject(group);+ const center = box.getCenter(new THREE.Vector3());+ const size = box.getSize(new THREE.Vector3());+ const halfH = camZ * Math.tan((40 / 2) * DEG);+ const sf = (halfH * 2 * 0.8) / size.y;++ group.scale.setScalar(sf);+ group.position.copy(center).negate().multiplyScalar(sf);++ const deviceConfig = deviceConfigs[device];+ const planeH = 4.3 * deviceConfig.screenHeightFactor;+ const planeW = planeH * deviceConfig.aspectRatio;++ const basicMat = new THREE.MeshBasicMaterial({+ color: 0x111111, side: THREE.FrontSide, transparent: true, depthTest: false, depthWrite: false,+ });+ screenMatRef.current = basicMat;++ const plane = new THREE.Mesh(new THREE.PlaneGeometry(planeW, planeH), basicMat);+ plane.position.set(deviceConfig.screenOffset.x, deviceConfig.screenOffset.y, deviceConfig.screenOffset.z);+ plane.renderOrder = 10;+ group.add(plane);++ finalizeSetup(group);+ });+ }++ return () => { isMounted = false; };+ // Desactivamos exhaust-deps para que NUNCA se vuelva a ejecutar este setup al hacer zoom o cambiar onLoaded+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [modelUrl]);++ // 4. Actualizar posiciones de cámara dinámicas (Esto es seguro de ejecutar contínuamente)+ useEffect(() => {+ const orbit = orbitRef.current;+ if (!orbit) return;+ const radius = 1.5 / zoom;+ const phi = Math.PI / 2 - initialRotationX * DEG;+ const theta = initialRotationY * DEG;+ orbit.object.position.setFromSphericalCoords(radius, phi, theta);+ orbit.update();+ }, [initialRotationX, initialRotationY, zoom]);++ useEffect(() => {+ if (rootRef.current) rootRef.current.rotation.z = initialRotationZ * DEG;+ }, [initialRotationZ]);++ return (+ <>+ <PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={[0, 0, 1.5 / zoom]} />++ <OrbitControls+ ref={orbitRef}+ enableZoom={false}+ enablePan={false}+ enableDamping+ dampingFactor={0.08}+ onEnd={() => {+ const orbit = orbitRef.current;+ if (!orbit || !onRotationChange) return;+ const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);+ const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);+ onRotationChange(rx, ry);+ }}+ />++ <Environment preset="city" background={false} />+ <ambientLight intensity={0.3} />+ <directionalLight position={[3, 6, 5]} intensity={0.6} />+ <directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />+ <directionalLight position={[0, -5, 5]} intensity={0.35} />++ <group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>+ {modelGroup && <primitive object={modelGroup} />}+ </group>+ </>+ );}-// ─── Componente Principal Público ─────────────────────────────────────────────-export function Phone3DViewer({- imageUrl = null,- imageMaskConfig = null,- cropArea = null,- initialRotationX = 0,- initialRotationY = 0,- initialRotationZ = 0,- onRotationChange,- onMount,- onApi,- modelUrl,+// ─── CanvasWrapper con Loader ────────────────────────────────────────────────+function CanvasWithLoader(props: Props & {+ rootRef: React.MutableRefObject<THREE.Group | null>;+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;+}) {+ const [loaded, setLoaded] = useState(false);++ // CLAVE DEL FIX: onLoaded debe ser inmutable para no envenenar los hooks de la escena+ const handleLoaded = useCallback(() => setLoaded(true), []);++ return (+ <>+ <Canvas+ style={{ width: "100%", height: "100%", overflow: "visible" }}+ gl={{+ antialias: true,+ alpha: true,+ preserveDrawingBuffer: true,+ powerPreference: "high-performance",+ failIfMajorPerformanceCaveat: false,+ }}+ dpr={3}+ onCreated={({ gl, scene }) => {+ gl.outputColorSpace = THREE.SRGBColorSpace;+ gl.toneMapping = THREE.NeutralToneMapping;+ gl.toneMappingExposure = 1.0;+ scene.environmentIntensity = 1.6;+ props.onMount?.(gl.domElement);+ }}+ >+ <Suspense fallback={null}>+ <ModelScene {...props} onLoaded={handleLoaded} />+ </Suspense>+ </Canvas>++ {!loaded && (+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ zIndex: 4 }}>+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />+ </div>+ )}+ </>+ );+}++// ─── Componente Público Principal ───────────────────────────────────────────+export function Phone3DViewer(props: Props) {+ const {scale = 1,- zoom = 1,shadowIntensity = 0,shadowColor = "#000000",-}: Props) {- const [grabbing, setGrabbing] = useState(false);- const loadedRef = useRef(false);- const [showShadow, setShowShadow] = useState(false);- const [showSpinner, setShowSpinner] = useState(true);-- // Fuerza remounting (recreación del contexto WebGL) al perder contexto o cambiar dispositivo- const [mountKey, setMountKey] = useState(0);-- const t = Math.max(0, Math.min(1, shadowIntensity));- const tEased = t * t;- const computedBlur = tEased * 60;- const computedOpacity = tEased * 0.7;- const shadowRgba = shadowColor.startsWith("#")- ? parseShadowColor(shadowColor, computedOpacity)- : shadowColor;-- const hasShadow = t > 0.01 && showShadow;-- const handleLoaded = useCallback(() => {- if (loadedRef.current) return;- loadedRef.current = true;- setShowSpinner(false);- setShowShadow(true);- }, []);-- const handleContextLost = useCallback(() => {- setMountKey((prev) => prev + 1);- loadedRef.current = false;- setShowSpinner(true);- setShowShadow(false);- }, []);-- // El `key` final que asegura resetear todo el canvas cuando cambia el dispositivo- const finalMountKey = `${modelUrl ?? "default"}_${mountKey}`;-- return (- <div+ } = props;++ const rootRef = useRef<THREE.Group | null>(null);+ const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);+ const [grabbing, setGrabbing] = useState(false);++ const t = Math.max(0, Math.min(1, shadowIntensity));+ const tEased = t * t;+ const computedBlur = tEased * 60;+ const computedOpacity = tEased * 0.7;++ const shadowRgba = shadowColor.startsWith("#")+ ? parseShadowColor(shadowColor, computedOpacity)+ : shadowColor;++ const hasShadow = t > 0.01;++ return (+ <div+ style={{+ display: "inline-block",+ transformOrigin: "top center",+ transform: `scale(${scale})`,+ width: PHONE_W,+ height: PHONE_H + (hasShadow ? computedBlur * 0.8 : 0),+ marginTop: "220px",+ marginLeft: "140px",+ }}+ >+ <div style={{ position: "relative", width: PHONE_W, height: PHONE_H }}>++ {hasShadow && (+ <div+ aria-hiddenstyle={{- display: "inline-block",- transformOrigin: "top center",- transform: `scale(${scale})`,- width: PHONE_W,- height: PHONE_H + (hasShadow ? computedBlur * 0.8 : 0),- marginTop: "220px",+ position: "absolute",+ bottom: -(computedBlur * 0.5),+ left: `${20 + tEased * 5}%`,+ width: `${60 - tEased * 10}%`,+ height: Math.max(4, computedBlur * 0.55),+ borderRadius: "50%",+ background: shadowRgba,+ filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`,+ zIndex: 0,+ pointerEvents: "none",}}+ />+ )}++ <div+ style={{+ position: "absolute",+ inset: "-200px",+ zIndex: 2,+ overflow: "visible",+ cursor: grabbing ? "grabbing" : "grab",+ filter: hasShadow+ ? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`+ : "none",+ transition: "filter 0.15s ease",+ pointerEvents: "auto",+ }}+ onPointerDown={() => setGrabbing(true)}+ onPointerUp={() => setGrabbing(false)}+ onPointerLeave={() => setGrabbing(false)}>- <div style={{ position: "relative", width: PHONE_W, height: PHONE_H }}>-- {/* Sombra de Suelo (CSS Render) */}- {hasShadow && (- <div- aria-hidden- style={{- position: "absolute",- bottom: -(computedBlur * 0.5),- left: `${20 + tEased * 5}%`,- width: `${60 - tEased * 10}%`,- height: Math.max(4, computedBlur * 0.55),- borderRadius: "50%",- background: shadowRgba,- filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`,- zIndex: 0,- pointerEvents: "none",- }}- />- )}-- {/* Contenedor del Canvas con Hit-Area expandida para el Orbit */}- <div- style={{- position: "absolute",- inset: "-200px",- zIndex: 2,- overflow: "visible",- cursor: grabbing ? "grabbing" : "grab",- filter: hasShadow- ? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`- : "none",- transition: showShadow ? "filter 0.3s ease" : "none",- pointerEvents: "auto",- }}- onPointerDown={() => setGrabbing(true)}- onPointerUp={() => setGrabbing(false)}- onPointerLeave={() => setGrabbing(false)}- >- <VanillaPhoneRenderer- key={finalMountKey}- imageUrl={imageUrl}- imageMaskConfig={imageMaskConfig}- cropArea={cropArea}- initialRotationX={initialRotationX}- initialRotationY={initialRotationY}- initialRotationZ={initialRotationZ}- zoom={zoom}- modelUrl={modelUrl}- onRotationChange={onRotationChange}- onMount={onMount}- onApi={onApi}- onLoaded={handleLoaded}- onContextLost={handleContextLost}- />- </div>-- {/* Spinner de Carga Inicial */}- {showSpinner && (- <div- className="absolute inset-0 flex items-center justify-center pointer-events-none"- style={{ zIndex: 10 }}- >- <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />- </div>- )}- </div>+ <CanvasWithLoader {...props} rootRef={rootRef} cameraRef={cameraRef} /></div>- );+ </div>+ </div>+ );}\ No newline at end of filediff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsxindex 7be1c21..24d624d 100644--- a/app/components/ui/editor/VideoCanvas.tsx+++ b/app/components/ui/editor/VideoCanvas.tsx@@ -96,6 +96,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functtextToolActive = false,onTextToolDeactivate,onAddElement,+ onMockupClick,}, ref) {const wallpaperUrl = getWallpaperUrl(selectedWallpaper);@@ -287,6 +288,11 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functconst dragStartPos = useRef({ x: 0, y: 0, initialRotation: 0, initialTranslateX: 0, initialTranslateY: 0 });const lastAngleRef = useRef<number | null>(null);const videoContainerRef = useRef<HTMLDivElement>(null);+ // Click vs drag detection for the 2D mockup canvas: we record the+ // pointer-down position and only fire onMockupClick if the pointer+ // stayed within CLICK_THRESHOLD pixels (i.e. it was a click, not a drag).+ const clickStartPosRef = useRef<{ x: number; y: number } | null>(null);+ const CLICK_THRESHOLD = 5; // pxconst [elementCorners, setElementCorners] = useState<Record<string, Corner | null>>({});// Camera overlay refs / state@@ -1891,8 +1897,23 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functinitialTranslateX: videoTransform.translateX,initialTranslateY: videoTransform.translateY,};+ // Track click vs drag for onMockupClick dispatch+ clickStartPosRef.current = { x: e.clientX, y: e.clientY };}}onMouseMove={(e) => { if (hasMedia) setVideoHoverCorner(getNearestCorner(e, videoTransform.rotation)); }}+ onClick={(e) => {+ if ((e.target as HTMLElement).closest('[data-rotation-handle]')) return;+ if (!onMockupClick) return;+ if (mockupId === "none" || mockupId === undefined) return;+ // Only fire if pointer stayed within CLICK_THRESHOLD (i.e. a click, not a drag)+ const start = clickStartPosRef.current;+ clickStartPosRef.current = null;+ if (!start) return;+ const dx = e.clientX - start.x;+ const dy = e.clientY - start.y;+ if (dx * dx + dy * dy > CLICK_THRESHOLD * CLICK_THRESHOLD) return;+ onMockupClick("2d");+ }}><div className="relative">{isVideoSelected && videoHoverCorner && hasMedia && onVideoTransformChange && !isDraggingVideo && !isDraggingRotation && (@@ -2166,6 +2187,25 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functdata-image-phone-overlayonMouseEnter={() => setIsVideoHovered(true)}onMouseLeave={() => setIsVideoHovered(false)}+ onPointerDown={(e) => {+ if (!onMockupClick) return;+ if (mediaType !== "image" || !imagePhoneActive) return;+ // Track click vs drag so the viewers' OrbitControls / drag+ // system don't get mistaken for a click intent.+ clickStartPosRef.current = { x: e.clientX, y: e.clientY };+ }}+ onClick={(e) => {+ if (!onMockupClick) return;+ if (mediaType !== "image" || !imagePhoneActive) return;+ const start = clickStartPosRef.current;+ clickStartPosRef.current = null;+ if (!start) return;+ const dx = e.clientX - start.x;+ const dy = e.clientY - start.y;+ if (dx * dx + dy * dy > CLICK_THRESHOLD * CLICK_THRESHOLD) return;+ e.stopPropagation();+ onMockupClick("3d");+ }}style={{left: "50%",top: "50%",diff --git a/types/control-panel.types.ts b/types/control-panel.types.tsindex 5fc7467..35afaa3 100644--- a/types/control-panel.types.ts+++ b/types/control-panel.types.ts@@ -1,7 +1,7 @@import { BackgroundTab, Tool, VideoThumbnail } from "./editor.types";import { BackgroundColorConfig } from "./background.types";import { ZoomFragment } from "./zoom.types";-import { MockupConfig } from "./mockup.types";+import { MockupConfig, MenuPage } from "./mockup.types";import type { CanvasElement } from "./canvas-elements.types";import type { UploadedAudio, AudioTrack } from "./audio.types";import type { CursorConfig, CursorRecordingData } from "./cursor.types";@@ -44,6 +44,12 @@ export interface ControlPanelProps {mockupConfig?: MockupConfig;onMockupChange?: (mockupId: string) => void;onMockupConfigChange?: (config: Partial<MockupConfig>) => void;+ /**+ * Initial page for the MockupMenu (home | detail-2d | detail-3d). Set by+ * the parent when the user clicks a mockup already applied on the canvas,+ * so the menu opens directly on the config panel of that frame.+ */+ initialMockupMenuPage?: MenuPage;onAddCanvasElement?: (element: CanvasElement) => void;selectedCanvasElement?: CanvasElement | null;onUpdateCanvasElement?: (id: string, updates: Partial<CanvasElement>) => void;diff --git a/types/editor.types.ts b/types/editor.types.tsindex 88413b1..3e6c733 100644--- a/types/editor.types.ts+++ b/types/editor.types.ts@@ -122,4 +122,10 @@ export interface VideoCanvasProps {onTextToolDeactivate?: () => void;onAddElement?: (element: CanvasElement) => void;isPlaying?: boolean;+ /**+ * Called when the user clicks an active mockup on the canvas. The `kind`+ * discriminates between the 2D frame wrapper (e.g. MacOS browser) and+ * the 3D device phone overlay. Not fired when neither is active.+ */+ onMockupClick?: (kind: "2d" | "3d") => void;}\ No newline at end of file