Skip to content

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

fix: Render 3D native

CristianOlivera1d22fc4dd8be4
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsx
index 2d2f036..d5de10f 100644
--- a/app/[locale]/(editor)/editor/page.tsx
+++ b/app/[locale]/(editor)/editor/page.tsx
@@ -10,6 +10,7 @@ import { useImageProjects } from "@/hooks/useImageProjects";
import { getUploadedVideo, deleteUploadedVideo } from "@/lib/video-upload-cache";
import { getUploadedImage, deleteUploadedImage } from "@/lib/image-upload-cache";
import { useEditorMode } from "@/hooks/useEditorMode";
+import { useActiveTool } from "@/hooks/useActiveTool";
import { useScreenCapture } from "@/hooks/useScreenCapture";
import { useVideoExport } from "@/hooks/useVideoExport";
import { useVideoThumbnails, type VideoThumbnail } from "@/hooks/useVideoThumbnails";
@@ -40,7 +41,7 @@ import { LoadingSpinner } from "@/components/ui/LoadingSpinner";
import { TimelineSkeleton } from "@/app/components/ui/Skeleton";
import { AudioTrimModal } from "@/app/components/ui/editor/AudioTrimModal";
import { useAuth } from "@/app/contexts/useAuth";
-import { useMotionContext } from "@/app/contexts/MotionContext";
+import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";
import { VIDEO_Z_INDEX } from "@/lib/constants";
import { getWallpaperUrl } from "@/lib/wallpaper.utils";
import Image from "next/image";
@@ -75,7 +76,7 @@ export default function Editor() {
imagePhoneOpening, setImagePhoneOpening,
imagePhoneShadow, setImagePhoneShadow,
imagePhoneShadowColor, setImagePhoneShadowColor,
- } = useMotionContext();
+ } = useMockup3dContext();
// Undo/Redo system - centralized state management
const {
@@ -134,7 +135,9 @@ export default function Editor() {
const [imageMaskConfig, setImageMaskConfig] = useState<ImageMaskConfig>(DEFAULT_MASK_CONFIG);
const [videoMaskConfig, setVideoMaskConfig] = useState<ImageMaskConfig>(DEFAULT_MASK_CONFIG);
- const [activeTool, setActiveTool] = useState<Tool>("screenshot");
+ // Active tool: lee `?m=<tool>` de la URL en mount. setActiveTool
+ // actualiza la URL con replaceState (preserva mode y otros params).
+ const [activeTool, setActiveTool] = useActiveTool();
const [elementsTextTabTrigger, setElementsTextTabTrigger] = useState(0);
const [backgroundTab, setBackgroundTab] = useState<BackgroundTab>("wallpaper");
const [selectedWallpaper, setSelectedWallpaper] = useState(0);
diff --git a/app/[locale]/(editor)/layout.tsx b/app/[locale]/(editor)/layout.tsx
index 658ca7d..8b3cca7 100644
--- a/app/[locale]/(editor)/layout.tsx
+++ b/app/[locale]/(editor)/layout.tsx
@@ -2,18 +2,18 @@
import { AuthProvider } from "@/app/contexts/useAuth";
import RecordingOverlay from "../../components/ui/RecordingOverlay";
-import { MotionProvider } from "@/app/contexts/MotionContext";
+import { Mockup3dProvider } from "@/app/contexts/Mockup3dContext";
import { RecordingProvider } from "@/app/contexts/RecordingContext";
export default function EditorLayout({ children }: { children: React.ReactNode }) {
return (
<AuthProvider>
<RecordingProvider>
- <MotionProvider>
+ <Mockup3dProvider>
<div className="min-h-screen bg-neutral-950">
{children}
</div>
- </MotionProvider>
+ </Mockup3dProvider>
<RecordingOverlay />
</RecordingProvider>
</AuthProvider>
diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsx
index 11befa4..fd48059 100644
--- a/app/components/ui/editor/ControlPanel.tsx
+++ b/app/components/ui/editor/ControlPanel.tsx
@@ -29,7 +29,6 @@ import CursorMenu from "./CursorMenu";
import { DEFAULT_CURSOR_CONFIG } from "@/types/cursor.types";
import { CameraMenu } from "./CameraMenu";
-// Lazy loads (se mantienen igual)
const ImageRecentBackgroundGrid = lazy(() => import("../ImageRecentBackgroundGrid").then(mod => ({ default: mod.ImageRecentBackgroundGrid })));
const BackgroundColorEditor = lazy(() => import("../BackgroundColorEditor").then(mod => ({ default: mod.BackgroundColorEditor })));
const ZoomFragmentEditor = lazy(() => import("./ZoomFragmentEditor").then(mod => ({ default: mod.ZoomFragmentEditor })));
@@ -40,8 +39,6 @@ const MockupMenu = lazy(() => import("./MockupMenu").then(mod => ({ default: mod
const AudioMenu = lazy(() => import("./AudioMenu").then(mod => ({ default: mod.AudioMenu })));
const VideosMenu = lazy(() => import("./VideosMenu").then(mod => ({ default: mod.VideosMenu })));
const HistoryMenu = lazy(() => import("./HistoryMenu").then(mod => ({ default: mod.HistoryMenu })));
-const MotionMenu = lazy(() => import("./MotionMenu").then(mod => ({ default: mod.MotionMenu })));
-const ImageMotionMenu = lazy(() => import("./ImageMotionMenu").then(mod => ({ default: mod.ImageMotionMenu })));
interface ExtendedControlPanelProps extends ControlPanelProps {
onTogglePanel?: () => void;
@@ -278,22 +275,30 @@ export function ControlPanel({
{activeTool === "mockup" && (
<Suspense fallback={<MockupMenuSkeleton />}>
- <MockupMenu mockupId={mockupId} mockupConfig={mockupConfig} onMockupChange={onMockupChange} onMockupConfigChange={onMockupConfigChange} />
+ <MockupMenu
+ mockupId={mockupId}
+ mockupConfig={mockupConfig}
+ onMockupChange={onMockupChange}
+ onMockupConfigChange={onMockupConfigChange}
+ backgroundTab={backgroundTab}
+ selectedWallpaper={selectedWallpaper}
+ selectedImageUrl={selectedImageUrl}
+ />
</Suspense>
)}
-
+ {/*
{activeTool === "motion" && (
- <Suspense fallback={<MockupMenuSkeleton />}>
+ <Suspense >
{mediaType === "image"
? <ImageMotionMenu
backgroundColorCss={undefined}
backgroundTab={backgroundTab}
selectedWallpaper={selectedWallpaper}
selectedImageUrl={selectedImageUrl}
- />
+ />
: <MotionMenu />}
</Suspense>
- )}
+ )} */}
{activeTool === "videos" && (
<Suspense fallback={<VideosMenuSkeleton />}>
diff --git a/app/components/ui/editor/HistoryMenu.tsx b/app/components/ui/editor/HistoryMenu.tsx
index e1a9bed..7c55fe6 100644
--- a/app/components/ui/editor/HistoryMenu.tsx
+++ b/app/components/ui/editor/HistoryMenu.tsx
@@ -174,18 +174,6 @@ export function HistoryMenu({
<div className="absolute inset-0 bg-linear-to-t from-[#0A0A0A]/95 via-[#0A0A0A]/50 to-black/20 opacity-0 group-hover:opacity-100 transition-all duration-300 flex flex-col justify-between p-2.5">
<div className="flex justify-end gap-1.5 -translate-y-2.5 group-hover:translate-y-0 transition-transform duration-300">
- <TooltipAction label={t("actions.addToCanvas")}>
- <button
- onClick={(e) => {
- e.stopPropagation();
- onAddToCanvas(project.id);
- }}
- className="size-6 flex items-center justify-center squircle-element bg-[#0A0A0A]/80 backdrop-blur-md border border-white/20 text-white/70 hover:text-white hover:bg-gray-500 hover:border-gray-500 transition-all"
- >
- <Icon icon="material-symbols:add-rounded" width="16" />
- </button>
- </TooltipAction>
-
<TooltipAction label={t("actions.delete")}>
<button
onClick={(e) => {
diff --git a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
index dbf9c1b..1828731 100644
--- a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
+++ b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
@@ -1,27 +1,17 @@
"use client";
-/**
- * IPhone13ProMax3DViewer (R3F + drei — OrbitControls edition)
- *
- * Sombra: mismo sistema que Laptop3DViewer
- * - Una sola prop `shadowIntensity` (0–1)
- * - Curva cuadratica interna (t^2): arranque suave, maximo dramatico
- * - Elipse de suelo + drop-shadow en contorno del modelo
- */
-
-import { Canvas } from "@react-three/fiber";
-import {
- PerspectiveCamera,
- useGLTF,
- Environment,
- OrbitControls,
-} from "@react-three/drei";
import { useEffect, useRef, useState } 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 {
@@ -31,6 +21,7 @@ export interface IPhone13ProMax3DApi {
interface Props {
imageUrl?: string | null;
imageMaskConfig?: ImageMaskConfigLike | null;
+ cropArea?: { x: number; y: number; width: number; height: number } | null;
initialRotationX?: number;
initialRotationY?: number;
initialRotationZ?: number;
@@ -39,400 +30,384 @@ interface Props {
onApi?: (api: IPhone13ProMax3DApi | null) => void;
scale?: number;
zoom?: number;
- /**
- * Intensidad de la sombra de 0 a 1.
- * 0 = sin sombra, 1 = sombra maxima.
- * Curva cuadratica interna (t^2) para crecimiento gradual en todo el rango.
- * Default: 0 (sin sombra)
- */
shadowIntensity?: number;
- /**
- * Color base de la sombra en hex o rgb. Default: "#000000"
- * La opacidad se controla automaticamente con shadowIntensity.
- */
shadowColor?: string;
}
-// ─── Textura de pantalla ─────────────────────────────────────────────────────
+// ─── Dimensiones de textura ───────────────────────────────────────────────────
const TEX_W = 1284 * 2;
const TEX_H = 2778 * 2;
-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;
+// ─── 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;
}
-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;
+// ─── 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();
}
-// ─── Escena 3D ──────────────────────────────────────────────────────────────
-function ModelScene({
- imageUrl,
- imageMaskConfig,
- initialRotationX,
- initialRotationY,
- initialRotationZ,
+export function IPhone13ProMax3DViewer({
+ imageUrl = null,
+ imageMaskConfig = null,
+ cropArea = null,
+ initialRotationX = -58.23,
+ initialRotationY = -29.82,
+ initialRotationZ = 0,
onRotationChange,
- rootRef,
- cameraRef,
- zoom,
+ onMount,
onApi,
- onLoaded,
-}: {
- imageUrl: string | null;
- imageMaskConfig: ImageMaskConfigLike | 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 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);
+ 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
const lastLoadedImageUrlRef = useRef<string | null>(null);
const lastLoadedMaskKeyRef = useRef<string | null>(null);
- const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | 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 ───────────────────────────────────────────
useEffect(() => {
+ if (!onApi) return;
const api: IPhone13ProMax3DApi = {
- renderAt: (w, h) => { void w; void h; },
+ 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);
+ },
};
- onApi?.(api);
- return () => onApi?.(null);
+ onApi(api);
+ return () => onApi(null);
}, [onApi]);
useEffect(() => {
- if (materials.Wallpaper) {
- wallpaperMatRef.current = materials.Wallpaper as THREE.MeshStandardMaterial;
+ if (cameraRef.current && controlsRef.current) {
+ applyCameraPosition(cameraRef.current, controlsRef.current, initialRotationX, initialRotationY, zoom);
}
- }, [materials.Wallpaper]);
+ }, [initialRotationX, initialRotationY, zoom]);
+
+ useEffect(() => {
+ if (modelRootRef.current) {
+ modelRootRef.current.rotation.z = initialRotationZ * DEG;
+ }
+ }, [initialRotationZ]);
+ // ─── Actualización de Textura de Pantalla ───────────────────────────────────
useEffect(() => {
const mat = wallpaperMatRef.current;
if (!mat) return;
- // Serializa el mask para detectar cambios. Si el mask cambia,
- // la textura debe regenerarse aunque la imagen no cambie.
const maskKey = imageMaskConfig ? JSON.stringify(imageMaskConfig) : null;
+ 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;
return;
}
- // Skip solo si la imagen Y el mask no cambiaron
+
if (
lastLoadedImageUrlRef.current === imageUrl &&
- lastLoadedMaskKeyRef.current === maskKey
- ) return;
+ lastLoadedMaskKeyRef.current === maskKey &&
+ lastLoadedCropKeyRef.current === cropKey
+ ) {
+ return;
+ }
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
- const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, imageMaskConfig);
- if (mat.map) { mat.map.dispose(); mat.map = null; }
+ const cropped = applyCropToImage(img, cropArea);
+ const cover = createCoverScreenCanvas(cropped, TEX_W, TEX_H, 0, imageMaskConfig);
+
+ if (mat.map) {
+ mat.map.dispose();
+ mat.map = null;
+ }
const tex = new THREE.CanvasTexture(cover);
- tex.flipY = true;
+ tex.flipY = true; // Se mantiene la inversión Y originaria del R3F
tex.colorSpace = THREE.SRGBColorSpace;
tex.generateMipmaps = true;
tex.minFilter = THREE.LinearMipmapLinearFilter;
tex.magFilter = THREE.LinearFilter;
tex.wrapS = THREE.ClampToEdgeWrapping;
tex.wrapT = THREE.ClampToEdgeWrapping;
+
mat.map = tex;
mat.needsUpdate = true;
+
lastLoadedImageUrlRef.current = imageUrl;
lastLoadedMaskKeyRef.current = maskKey;
- onLoaded?.();
- };
- img.onerror = () => {
- // Even on error, hide the loader so the user sees the device
- // (with the original iOS wallpaper) instead of a permanent spinner.
- onLoaded?.();
+ lastLoadedCropKeyRef.current = cropKey;
};
img.src = imageUrl;
- }, [imageUrl, imageMaskConfig, onLoaded]);
-
- useEffect(() => {
- // Reposiciona OrbitControls cuando cambian initialRotationX/Y.
- // Permite que el crosshair "Rotation XY" del popup Custom del
- // PhotoEditorPlaceholder mueva la cámara en tiempo real.
- // NO interfiere con el drag del usuario porque:
- // - El drag llama onEnd al TERMINAR, no en cada frame
- // - El setFromSphericalCoords es determinístico: la posición
- // calculada desde los props ES la misma que el drag dejó
- // (mismo phi/theta/radius), así que no hay "salto"
- 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]);
-
- // Sync initialRotationZ → group rotation.z (mismo patrón que Laptop3DViewer).
- // Permite que el slider "Rotation Z" del popup Custom del
- // PhotoEditorPlaceholder se refleje en el modelo. NO interfiere
- // con el drag de OrbitControls (que solo afecta X/Y vía la cámara),
- // así que es seguro ejecutar este useEffect en cada cambio de prop.
- useEffect(() => {
- const root = rootRef.current;
- if (root) {
- root.rotation.z = initialRotationZ * (Math.PI / 180);
- }
- }, [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, 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 ────────────────────────────────────────────────────────
-// Owns its own `loaded` state. Remounting via `key={imageUrl}` is the
-// idiomatic React way to reset state when the image changes — no
-// cascading setState in useEffect.
-function CanvasWithLoader({
- imageUrl,
- imageMaskConfig,
- initialRotationX,
- initialRotationY,
- initialRotationZ,
- onRotationChange,
- rootRef,
- cameraRef,
- zoom,
- onApi,
- onMount,
-}: {
- imageUrl: string | null;
- imageMaskConfig: ImageMaskConfigLike | 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);
+ }, [imageUrl, imageMaskConfig, cropArea, loaded]);
- return (
- <>
- <Canvas
- style={{ width: "100%", height: "100%", overflow: "visible" }}
- gl={{
- antialias: true,
- alpha: true,
- preserveDrawingBuffer: true,
- powerPreference: "high-performance",
- // Permite software rendering si la GPU no soporta WebGL2 —
- // evita "Context Lost" en hardware limitado.
- failIfMajorPerformanceCaveat: false,
- }}
- // dpr=2: balance entre nitidez y consumo de VRAM. dpr=4
- // saturaba la GPU junto con el GLB pesado del iPhone 13
- // Pro Max + Environment HDR y causaba "Context Lost".
- dpr={2}
- onCreated={({ gl, scene }) => {
- gl.outputColorSpace = THREE.SRGBColorSpace;
- gl.toneMapping = THREE.NeutralToneMapping;
- gl.toneMappingExposure = 1.0;
- scene.environmentIntensity = 1.6;
- onMount?.(gl.domElement);
- }}
- >
- <ModelScene
- imageUrl={imageUrl}
- imageMaskConfig={imageMaskConfig}
- initialRotationX={initialRotationX}
- initialRotationY={initialRotationY}
- initialRotationZ={initialRotationZ}
- onRotationChange={onRotationChange}
- rootRef={rootRef}
- cameraRef={cameraRef}
- zoom={zoom}
- onApi={onApi}
- onLoaded={() => setLoaded(true)}
- />
- </Canvas>
-
- {/* Loader — covers the white wallpaper texture while the
- user's image is being decoded. */}
- {!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>
- )}
- </>
- );
-}
+ // ─── Sombras y Renderizado HTML ─────────────────────────────────────────────
-// ─── Componente público ──────────────────────────────────────────────────────
-export function IPhone13ProMax3DViewer({
- imageUrl = null,
- imageMaskConfig = 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);
-
- // ── Curva cuadratica: mismo sistema que Laptop3DViewer ───────────────────
- // t^2 da arranque suave (0→0.04 al 20%) y maximo dramatico (1→1 al 100%)
const t = Math.max(0, Math.min(1, shadowIntensity));
const tEased = t * t;
- const computedBlur = tEased * 60; // 0–60 px
- const computedOpacity = tEased * 0.7; // 0–0.7
+ const computedBlur = tEased * 60;
+ const computedOpacity = tEased * 0.7;
const shadowRgba = shadowColor.startsWith("#")
? parseShadowColor(shadowColor, computedOpacity)
: shadowColor;
- const hasShadow = t > 0.01;
+
+ const hasShadow = t > 0.01 && loaded;
return (
<div
@@ -442,12 +417,11 @@ export function IPhone13ProMax3DViewer({
transform: `scale(${scale})`,
width: 480,
height: 1000 + (hasShadow ? computedBlur * 0.8 : 0),
- marginTop: "200px"
-
+ marginTop: "20px",
}}
>
<div style={{ position: "relative", width: 480, height: 1000 }}>
- {/* Sombra de suelo: elipse difusa con curva t^2 */}
+ {/* Sombra de suelo - Aparece sólo tras la carga */}
{hasShadow && (
<div
aria-hidden
@@ -466,44 +440,48 @@ export function IPhone13ProMax3DViewer({
/>
)}
- {/*
- Canvas wrapper con inset negativo para que OrbitControls
- no clipee el modelo cuando se rota al maximo.
- drop-shadow sigue el contorno real del iPhone (igual que Laptop3DViewer).
- */}
+ {/* Capa de interacción y WebGL */}
<div
style={{
position: "absolute",
- inset: "-200px",
+ inset: "-200px", // Aumenta el área del WebGL y la zona de drag (880x1400 px)
zIndex: 2,
overflow: "visible",
cursor: grabbing ? "grabbing" : "grab",
- // drop-shadow en contorno del modelo con curva t^2
filter: hasShadow
? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`
: "none",
- transition: "filter 0.15s ease",
+ transition: loaded ? "filter 0.15s ease" : "none",
pointerEvents: "auto",
}}
onPointerDown={() => setGrabbing(true)}
onPointerUp={() => setGrabbing(false)}
onPointerLeave={() => setGrabbing(false)}
>
- <CanvasWithLoader
- key={imageUrl ?? "no-image"}
- imageUrl={imageUrl}
- imageMaskConfig={imageMaskConfig}
- initialRotationX={initialRotationX}
- initialRotationY={initialRotationY}
- initialRotationZ={initialRotationZ}
- onRotationChange={onRotationChange}
- rootRef={rootRef}
- cameraRef={cameraRef}
- zoom={zoom}
- onApi={onApi}
- onMount={onMount}
+ {/* Contenedor Vanilla Three.js */}
+ <div
+ ref={containerRef}
+ style={{
+ width: "100%",
+ height: "100%",
+ opacity: loaded && !contextLost ? 1 : 0,
+ transition: "opacity 0.25s ease",
+ }}
/>
</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/ImageMotionMenu.tsx b/app/components/ui/editor/ImageMotionMenu.tsx
deleted file mode 100644
index edbfb1a..0000000
--- a/app/components/ui/editor/ImageMotionMenu.tsx
+++ /dev/null
@@ -1,385 +0,0 @@
-"use client";
-
-import { useRef, useState } from "react";
-import { Icon } from "@iconify/react";
-import { useMotionContext } from "@/app/contexts/MotionContext";
-import { SliderControl } from "../SliderControl";
-import { getWallpaperUrl } from "@/lib/wallpaper.utils";
-
-const PAD_H = 130;
-const X_HALF = 500;
-const Y_HALF = 500;
-const HANDLE_R = 9;
-
-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);
-
- // Forzamos límites matemáticos para los valores de X e Y
- const cx = Math.max(-X_HALF, Math.min(X_HALF, x));
- const cy = Math.max(-Y_HALF, Math.min(Y_HALF, y));
-
- // Calculamos las posiciones en porcentaje para que responda al ancho fluido de CSS
- 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));
- };
-
- // Build the background layer style: prefer the image URL, fall back to a CSS color/gradient
- 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);
- }}
- >
- {/* Background layer (canvas background) */}
- <div className="absolute inset-0 pointer-events-none" style={bgLayerStyle} />
-
- {/* Dark overlay so the grid/handles remain readable on bright backgrounds */}
- <div className="absolute inset-0 pointer-events-none bg-black/40" />
-
- {/* Active highlight ring while dragging */}
- {isDraggingState && (
- <div className="absolute inset-0 pointer-events-none rounded-[14px] ring-2 ring-cyan-400/30 animate-pulse" />
- )}
-
- {/* Grid */}
- <div className="absolute inset-0 pointer-events-none opacity-10 bg-[radial-gradient(#a1a1aa_1px,transparent_1px)] bg-size-[14px_14px]" />
-
- {/* Crosshairs */}
- <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>
- </div>
- );
-}
-
-// ─── Device template definition ───────────────────────────────────────────────
-const IMAGE_DEVICE_TEMPLATES = [
- {
- id: "none",
- title: "None",
- accentColor: "#555",
- icon: "ph:prohibit",
- },
- {
- id: "iphone-13-pro-max",
- title: "iPhone 13 Pro",
- accentColor: "#7C7C85",
- icon: "simple-icons:apple",
- modelUrl: "/models/apple_iphone_13_pro_max.glb",
- },
- {
- id: "phone",
- title: "Phone",
- accentColor: "#00A3FF",
- icon: "ph:device-mobile-bold",
- modelUrl: "/models/phone-gltf.glb",
- },
- {
- id: "iphone",
- title: "iPhone 15 Pro",
- accentColor: "#A8A8B0",
- icon: "simple-icons:apple",
- modelUrl: "/models/iphone-15-pro-max.glb",
- },
- {
- id: "samsung",
- title: "Samsung S25",
- accentColor: "#1428A0",
- icon: "simple-icons:samsung",
- modelUrl: "/models/samsung-galaxy-s25-ultra.glb",
- },
- {
- id: "laptop",
- title: "macOS Laptop",
- accentColor: "#CECFD3",
- icon: "ph:laptop-bold",
- modelUrl: "/models/mac-book.glb",
- }
-] as const;
-
-type ImageDeviceId = typeof IMAGE_DEVICE_TEMPLATES[number]["id"];
-
-// ─── ImageMotionMenu ──────────────────────────────────────────────────────────
-export function ImageMotionMenu({
- backgroundUrl,
- backgroundColorCss,
- backgroundTab,
- selectedWallpaper,
- selectedImageUrl,
-}: {
- backgroundUrl?: string | null;
- backgroundColorCss?: string | null;
- backgroundTab?: "wallpaper" | "image" | "color" | "unsplash";
- selectedWallpaper?: number;
- selectedImageUrl?: string;
-}) {
- // Compute the current canvas background URL based on the active tab
- const resolvedBackgroundUrl = (() => {
- if (backgroundUrl) return backgroundUrl;
- if (backgroundTab === "image" && selectedImageUrl) return selectedImageUrl;
- if (backgroundTab === "wallpaper" && typeof selectedWallpaper === "number" && selectedWallpaper >= 0) {
- return getWallpaperUrl(selectedWallpaper);
- }
- return null;
- })();
-
- const {
- imagePhoneActive, setImagePhoneActive,
- imagePhoneX, setImagePhoneX,
- imagePhoneY, setImagePhoneY,
- imagePhoneScale, setImagePhoneScale,
- setImagePhoneRotX, setImagePhoneRotY,
- imagePhoneDevice, setImagePhoneDevice,
- imagePhoneOpening, setImagePhoneOpening,
- imagePhoneShadow, setImagePhoneShadow,
- imagePhoneShadowColor, setImagePhoneShadowColor,
- pushHistory,
- } = useMotionContext();
-
- const activeDeviceId: ImageDeviceId = imagePhoneActive ? imagePhoneDevice : "none";
- const isLaptop = imagePhoneActive && imagePhoneDevice === "laptop";
-
- const handleDeviceClick = (id: ImageDeviceId) => {
- if (id === "none") {
- setImagePhoneActive(false);
- } else {
- if (id !== imagePhoneDevice) {
- setImagePhoneDevice(id);
- setImagePhoneX(0);
- setImagePhoneY(0);
- setImagePhoneScale(0.8);
- // ← Inicializar rotación con los defaults correctos según el device
- if (id === "iphone-13-pro-max") {
- setImagePhoneRotX(-58.23);
- setImagePhoneRotY(-29.82);
- } else {
- setImagePhoneRotX(0);
- setImagePhoneRotY(0);
- }
- if (id === "laptop") {
- setImagePhoneOpening(1);
- setImagePhoneScale(1);
- }
- }
- setImagePhoneActive(true);
- }
- };
-
- 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="p-4 flex flex-col gap-5 w-full bg-[#111113] min-h-screen">
- {/* Header */}
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2 text-white font-medium">
- <Icon icon="mage:box-3d" width="20" aria-hidden="true" />
- <span>Motion</span>
- </div>
- </div>
-
- {/* Device template grid */}
- <div className="grid grid-cols-2 gap-3 items-start">
- {IMAGE_DEVICE_TEMPLATES.map((tpl) => {
- const isActive = activeDeviceId === tpl.id;
- const isNone = tpl.id === "none";
- return (
- <div key={tpl.id} className="relative">
- <button
- type="button"
- onClick={() => handleDeviceClick(tpl.id)}
- className={`group flex h-full w-full flex-col overflow-hidden rounded-2xl border text-left transition-all duration-300 active:scale-[0.98] ${isActive
- ? "border-white/20 bg-[#1a1a1e]"
- : "border-white/6 bg-[#17171a] hover:border-white/20"
- }`}
- >
- <div className="relative aspect-video w-full shrink-0 bg-[#0d0d10]">
- <div
- className="absolute inset-0"
- style={{
- background: isActive
- ? `linear-gradient(135deg, ${tpl.accentColor}22 0%, transparent 70%)`
- : `linear-gradient(135deg, ${tpl.accentColor}10 0%, transparent 70%)`,
- }}
- />
- <div className="absolute inset-0 flex items-center justify-center">
- <Icon
- icon={tpl.icon}
- width="20"
- style={{ color: isActive ? `${tpl.accentColor}cc` : `${tpl.accentColor}55` }}
- />
- </div>
- {isActive && !isNone && (
- <div
- className="absolute top-1.5 right-1.5 size-4 rounded-full flex items-center justify-center"
- style={{ background: tpl.accentColor }}
- >
- <Icon icon="mdi:check-bold" width={9} className="text-white" />
- </div>
- )}
- </div>
- <div className="border-t border-white/5 bg-[#111113] px-3 py-2.5 flex items-center justify-between">
- <h3 className={`truncate text-xs font-semibold ${isActive ? "text-white" : "text-white/60"}`}>
- {tpl.title}
- </h3>
- </div>
- </button>
-
- {isActive && (
- <div
- className="pointer-events-none absolute inset-0 rounded-2xl"
- style={{
- boxShadow: `0 0 0 1.5px ${tpl.accentColor}88`,
- }}
- />
- )}
- </div>
- );
- })}
- </div>
-
- {/* Config panel — shown when phone is active */}
- {imagePhoneActive && (
- <div className="flex flex-col gap-4 pt-2 border-t border-white/6">
- <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={resolvedBackgroundUrl}
- backgroundColorCss={backgroundColorCss}
- />
- </div>
- </div>
- )}
- </div>
- );
-}
diff --git a/app/components/ui/editor/Laptop3DViewer.tsx b/app/components/ui/editor/Laptop3DViewer.tsx
index 94e538c..ba20c68 100644
--- a/app/components/ui/editor/Laptop3DViewer.tsx
+++ b/app/components/ui/editor/Laptop3DViewer.tsx
@@ -1,30 +1,15 @@
"use client";
-/**
- * Laptop3DViewer
- *
- * Drag system: mirrors IPhone13ProMax3DViewer / OrbitControls exactly.
- * - Spherical-coordinate camera (radius, phi, theta) instead of direct
- * rotation on the group → same feel as OrbitControls.
- * - Inertial damping via requestAnimationFrame loop (dampingFactor 0.08).
- * - onRotationChange fires at pointer-up (same as onEnd in OrbitControls).
- * - initialRotationX / initialRotationY map to phi / theta identically.
- *
- * Canvas: simple absolute positioning (top:0, left:0) like the v2 viewer —
- * no BLEED system. The parent container uses overflow:visible so geometry
- * rotated outside the nominal 600×410 bounds is never clipped.
- */
-
import { useCallback, useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import {
createCoverScreenCanvas,
+ applyCropToImage,
parseShadowColor,
type ImageMaskConfigLike,
} from "@/lib/phone3d.utils";
-// ─── Dimensiones ──────────────────────────────────────────────────────────────
const LAPTOP_W = 1500;
const LAPTOP_H = 1035;
const RENDER_MULTIPLIER = 2;
@@ -50,8 +35,9 @@ export interface Laptop3DApi {
interface Props {
imageUrl?: string | null;
- openingProgress?: number;
imageMaskConfig?: ImageMaskConfigLike | null;
+ cropArea?: { x: number; y: number; width: number; height: number } | null;
+ openingProgress?: number;
initialRotationX?: number;
initialRotationY?: number;
initialRotationZ?: number;
@@ -99,6 +85,7 @@ export function Laptop3DViewer({
imageUrl = null,
openingProgress = 1,
imageMaskConfig = null,
+ cropArea = null,
initialRotationX = 0,
initialRotationY = 0,
initialRotationZ = 0,
@@ -120,6 +107,8 @@ export function Laptop3DViewer({
const lightHolderRef = useRef<THREE.Group | null>(null);
const imageUrlRef = useRef<string | null>(imageUrl);
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);
@@ -146,6 +135,7 @@ export function Laptop3DViewer({
lastLoadedUrlRef.current = null;
}, [imageMaskConfig]);
useEffect(() => { zoomRef.current = zoom; }, [zoom]);
+ useEffect(() => { cropAreaRef.current = cropArea ?? null; }, [cropArea]);
// ── Lid + screen opacity ──────────────────────────────────────────────────
const applyLid = useCallback(() => {
@@ -163,12 +153,20 @@ export function Laptop3DViewer({
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 img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
const TEX_W = RENDER_W * 2;
const TEX_H = RENDER_H * 2;
- const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, imageMaskConfigRef.current);
+ // 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 tex = new THREE.CanvasTexture(cover);
tex.flipY = false;
@@ -472,7 +470,6 @@ export function Laptop3DViewer({
onRotationChangeRef.current?.(rx, ry);
}, []);
- // ── Shadow ────────────────────────────────────────────────────────────────
const t = Math.max(0, Math.min(1, shadowIntensity));
const tEased = t * t;
const computedBlur = tEased * 60;
@@ -490,15 +487,9 @@ export function Laptop3DViewer({
transform: `scale(${scale})`,
width: LAPTOP_W,
height: LAPTOP_H + (hasShadow ? computedBlur * 0.8 : 0),
- marginTop: "200px",
+ marginTop: "250px",
}}
>
- {/*
- * overflow:visible is the key fix — the canvas renders at LAPTOP_W×LAPTOP_H
- * but geometry rotated beyond those bounds is no longer clipped.
- * This mirrors how IPhone13ProMax3DViewer uses inset:"-200px" to achieve
- * the same result, but without needing an oversized canvas or BLEED math.
- */}
<div
style={{
position: "relative",
diff --git a/app/components/ui/editor/MockupMenu.tsx b/app/components/ui/editor/MockupMenu.tsx
index 425c620..780ea97 100644
--- a/app/components/ui/editor/MockupMenu.tsx
+++ b/app/components/ui/editor/MockupMenu.tsx
@@ -1,44 +1,361 @@
"use client";
-import { useState } from "react";
+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 type { MockupCategory, MockupConfig, MockupFeatures } from "@/types/mockup.types";
-import { getMockupFeatures } from "@/types/mockup.types";
+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 { 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";
-const FRAME_COLORS_DARK = ["#1e1e1e", "#181818", "#252526", "#0d1117", "#1a1b26", "#282a36"];
-const FRAME_COLORS_LIGHT = ["#ffffff", "#f3f3f3", "#f6f8fa", "#fafafa", "#e8e8e8"];
-const FRAME_COLORS = [...FRAME_COLORS_DARK, ...FRAME_COLORS_LIGHT];
+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>
+ );
+}
+
+function DeviceCard({
+ tpl,
+ isActive,
+ onClick,
+}: {
+ tpl: (typeof IMAGE_DEVICE_TEMPLATES)[number];
+ isActive: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <div className="relative w-40 shrink-0 snap-start mt-0.5">
+ <button
+ type="button"
+ onClick={onClick}
+ className={`group flex h-full w-full flex-col overflow-hidden rounded-2xl border text-left transition-all duration-300 active:scale-[0.98] ${isActive
+ ? "border-white/20 bg-[#1a1a1e]"
+ : "border-white/6 bg-[#17171a] hover:border-white/20"
+ }`}
+ >
+ <div className="relative aspect-3/4 w-full shrink-0 bg-[#0d0d10]">
+ <div
+ className="absolute inset-0"
+ style={{
+ background: isActive
+ ? `linear-gradient(135deg, ${tpl.accentColor}22 0%, transparent 70%)`
+ : `linear-gradient(135deg, ${tpl.accentColor}10 0%, transparent 70%)`,
+ }}
+ />
+ <div className="absolute inset-0 flex items-center justify-center">
+ <Icon
+ icon={tpl.icon}
+ width="22"
+ style={{
+ color: isActive ? `${tpl.accentColor}cc` : `${tpl.accentColor}55`,
+ }}
+ />
+ </div>
+
+ {isActive && (
+ <div
+ className="absolute top-1.5 right-1.5 size-4 rounded-full flex items-center justify-center"
+ style={{ background: tpl.accentColor }}
+ >
+ <Icon icon="mdi:check-bold" width={9} className="text-white" />
+ </div>
+ )}
+ </div>
+
+ <div className="border-t border-white/5 bg-[#111113] px-3 py-2.5">
+ <h3
+ className={`truncate text-xs font-semibold ${isActive ? "text-white" : "text-white/60"
+ }`}
+ >
+ {tpl.title}
+ </h3>
+ </div>
+ </button>
+
+ {isActive && (
+ <div
+ className="pointer-events-none absolute inset-0 rounded-2xl"
+ style={{ boxShadow: `0 0 0 1.5px ${tpl.accentColor}88` }}
+ />
+ )}
+ </div>
+ );
+}
+
+// ─── Props ────────────────────────────────────────────────────────────────────
interface MockupMenuProps {
mockupId?: string;
mockupConfig?: MockupConfig;
onMockupChange?: (mockupId: string) => void;
onMockupConfigChange?: (config: Partial<MockupConfig>) => void;
+ // Background props forwarded from parent (needed for PositionPad)
+ backgroundUrl?: string | null;
+ backgroundColorCss?: string | null;
+ backgroundTab?: "wallpaper" | "image" | "color" | "unsplash";
+ selectedWallpaper?: number;
+ selectedImageUrl?: string;
}
+// ─── MockupMenu ───────────────────────────────────────────────────────────────
+
export function MockupMenu({
mockupId = "none",
mockupConfig,
onMockupChange,
onMockupConfigChange,
+ backgroundUrl,
+ backgroundColorCss,
+ backgroundTab,
+ selectedWallpaper,
+ selectedImageUrl,
}: MockupMenuProps) {
const t = useTranslations("mockupMenu");
+
+ // ── Navigation state ──
+ const [page, setPage] = useState<MenuPage>("home");
+
+ // ── 2D popover state ──
const [selectedCategory, setSelectedCategory] = useState<MockupCategory>("all");
- const [popoverOpen, setPopoverOpen] = useState(false);
const [gridLoaded, setGridLoaded] = useState(false);
+ const devicesScrollRef = useRef<HTMLDivElement>(null);
+ const [isDevicesHover, setIsDevicesHover] = useState(false);
+ const [canScrollLeft, setCanScrollLeft] = useState(false);
+ const [canScrollRight, setCanScrollRight] = useState(false);
+
+ const updateDevicesScrollState = useCallback(() => {
+ const el = devicesScrollRef.current;
+ if (!el) return;
+
+ const maxScrollLeft = el.scrollWidth - el.clientWidth;
+ setCanScrollLeft(el.scrollLeft > 8);
+ setCanScrollRight(el.scrollLeft < maxScrollLeft - 8);
+ }, []);
+
+ const devicesScrollLeftRef = useRef(0);
+
+ const handleDevicesScroll = useCallback(() => {
+ const el = devicesScrollRef.current;
+ if (!el) return;
+
+ devicesScrollLeftRef.current = el.scrollLeft;
+ updateDevicesScrollState();
+ }, [updateDevicesScrollState]);
+
+ const restoreDevicesScroll = useCallback(() => {
+ const el = devicesScrollRef.current;
+ if (!el) return;
+
+ el.scrollLeft = devicesScrollLeftRef.current;
+ updateDevicesScrollState();
+ }, [updateDevicesScrollState]);
+
+ const scrollDevices = useCallback((direction: "left" | "right") => {
+ const el = devicesScrollRef.current;
+ if (!el) return;
+
+ const amount = Math.max(220, Math.round(el.clientWidth * 0.78));
+ el.scrollBy({
+ left: direction === "left" ? -amount : amount,
+ behavior: "smooth",
+ });
+ }, []);
+
+ useEffect(() => {
+ if (page !== "home") return;
+
+ const id = requestAnimationFrame(() => {
+ restoreDevicesScroll();
+ });
+
+ const el = devicesScrollRef.current;
+ if (!el) return;
+
+ const onWheel = (e: WheelEvent) => {
+ if (el.scrollWidth <= el.clientWidth) return;
+
+ // Si ya es scroll horizontal, lo dejamos pasar
+ if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
+
+ e.preventDefault();
+ el.scrollLeft += e.deltaY;
+ };
+
+ const onScroll = () => updateDevicesScrollState();
+
+ el.addEventListener("wheel", onWheel, { passive: false });
+ el.addEventListener("scroll", onScroll, { passive: true });
+ window.addEventListener("resize", updateDevicesScrollState);
+
+ // estado inicial correcto al volver a home
+ updateDevicesScrollState();
- const filteredMockups = selectedCategory === "all" ? MOCKUPS : MOCKUPS.filter(m => m.category === selectedCategory);
+ return () => {
+ el.removeEventListener("wheel", onWheel);
+ el.removeEventListener("scroll", onScroll);
+ window.removeEventListener("resize", updateDevicesScrollState);
+ };
- // Obtener el mockup actual y sus features
- const currentMockup = MOCKUPS.find(m => m.id === mockupId);
+ return () => cancelAnimationFrame(id);
+ }, [page, restoreDevicesScroll, updateDevicesScrollState]);
+
+ // ── 3D context ──
+ const {
+ imagePhoneActive,
+ setImagePhoneActive,
+ imagePhoneX,
+ setImagePhoneX,
+ imagePhoneY,
+ setImagePhoneY,
+ imagePhoneScale,
+ setImagePhoneScale,
+ setImagePhoneRotX,
+ setImagePhoneRotY,
+ imagePhoneDevice,
+ setImagePhoneDevice,
+ imagePhoneOpening,
+ setImagePhoneOpening,
+ imagePhoneShadow,
+ setImagePhoneShadow,
+ setImagePhoneShadowColor,
+ pushHistory,
+ } = useMockup3dContext();
+
+ // ── Derived ──
+ const filteredMockups =
+ selectedCategory === "all"
+ ? MOCKUPS
+ : 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 isLaptop = imagePhoneActive && imagePhoneDevice === "laptop";
+
+ const resolvedBackgroundUrl = (() => {
+ if (backgroundUrl) return backgroundUrl;
+ if (backgroundTab === "image" && selectedImageUrl) return selectedImageUrl;
+ if (
+ backgroundTab === "wallpaper" &&
+ typeof selectedWallpaper === "number" &&
+ selectedWallpaper >= 0
+ ) {
+ return getWallpaperUrl(selectedWallpaper);
+ }
+ return null;
+ })();
+
+ const hasActiveFrame = mockupId !== "none" || imagePhoneActive;
+
+ // ── Handlers: 2D ──
+
const handleMockupSelect = (id: string) => {
onMockupChange?.(id);
+ if (imagePhoneActive) setImagePhoneActive(false);
+ if (id !== "none") setPage("detail-2d");
};
const handleCategoryChange = (cat: MockupCategory) => {
@@ -51,293 +368,654 @@ export function MockupMenu({
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";
- }
+ if (isDark && !isCurrentColorDark) newFrameColor = "#1e1e1e";
+ else if (!isDark && isCurrentColorDark) newFrameColor = "#f6f6f6";
onMockupConfigChange?.({ darkMode: isDark, frameColor: newFrameColor });
};
- const handleFrameColorChange = (color: string) => {
+ const handleFrameColorChange = (color: string) =>
onMockupConfigChange?.({ frameColor: color.toLowerCase() });
- };
- const handleUrlChange = (url: string) => {
- onMockupConfigChange?.({ url });
+ const handleUrlChange = (url: string) => onMockupConfigChange?.({ url });
+ const handleHeaderScaleChange = (headerScale: number) => onMockupConfigChange?.({ headerScale });
+ const handleHeaderOpacityChange = (headerOpacity: number) => onMockupConfigChange?.({ headerOpacity });
+
+ // ── Handlers: 3D ──
+
+ const handleDeviceClick = (id: ImageDeviceId) => {
+ if (id !== imagePhoneDevice) {
+ setImagePhoneDevice(id);
+ setImagePhoneX(0);
+ setImagePhoneY(0);
+ setImagePhoneScale(0.8);
+ if (id === "iphone-13-pro-max") {
+ setImagePhoneRotX(-58.23);
+ setImagePhoneRotY(-29.82);
+ } 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 handleHeaderScaleChange = (headerScale: number) => {
- onMockupConfigChange?.({ headerScale });
+ 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");
};
- const handleHeaderOpacityChange = (headerOpacity: number) => {
- onMockupConfigChange?.({ headerOpacity });
+ // ── Handlers: shared ──
+
+ const handleRemoveAll = () => {
+ onMockupChange?.("none");
+ setImagePhoneActive(false);
+ setPage("home");
};
- return (
- <div className="p-4 flex flex-col gap-6">
- <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>
+ // ─────────────────────────────────────────────────────────────────────────
+ // PAGE: HOME
+ // ─────────────────────────────────────────────────────────────────────────
- <div className="space-y-2">
- <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">{t("windowType")}</p>
- <Popover
- onOpenChange={(open) => {
- setPopoverOpen(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 bg-blue-500/10 border-blue-500/40 text-blue-300"
- 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}
+ if (page === "home") {
+ return (
+ <div className="p-4 flex flex-col gap-6">
+ {/* Header */}
+ <div className="flex items-center gap-2 text-white font-medium">
+ <Icon icon="hugeicons:ai-browser" width="20" aria-hidden="true" />
+ <span>{t("title")}</span>
+ </div>
+
+ {/* ── 2D Section ── */}
+ <div className="flex flex-col gap-3">
+ <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">
+ Marcos 2D
+ </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 gap-1.5">
- <span className="text-[10px] font-bold tracking-wider">{currentMockup?.name || t("none")}</span>
+ <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>
- </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
+ </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"
}`}
>
- <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"}')`,
- }}
+ <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 flex items-center justify-center pointer-events-none">
- {mockup.preview}
+ <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>
- <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 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>
- )}
- </button>
- );
- })}
+ {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>
- </div>
- </PopoverContent>
- </Popover>
- </div>
+ </PopoverContent>
+ </Popover>
- {mockupId === "none" && (
- <div className="space-y-2.5">
- <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">{t("suggested")}</p>
- <div className="grid grid-cols-3 gap-2">
- {["glass-ui-container","macos", "chrome", "macos-glass", "brave", "chrome-glass", "macos-dark-ide", "glass-curve", "macos-ghost"].map((id) => {
- const mockup = MOCKUPS.find((m) => m.id === id);
- if (!mockup) return null;
- const categoryConfig = MOCKUP_CATEGORIES.find((c) => c.id === mockup.category);
- return (
- <button
- key={id}
- onClick={() => handleMockupSelect(id)}
- className="group relative w-full h-20 squircle-element border border-white/[0.07] hover:border-white/20 overflow-hidden transition-all active:scale-95"
- >
- <div
- className="absolute inset-0 bg-cover bg-center transition-transform duration-500 group-hover:scale-105"
- style={{ backgroundImage: `url('${categoryConfig?.bgUrl || ""}')` }}
+ <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 flex items-center justify-center pointer-events-none scale-90">
- {mockup.preview}
+ <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>
- <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>
- </button>
- );
- })}
+ <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>
- )}
- {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>
+ {/* Divider */}
+ <div className="h-px bg-white/[0.06]" />
+
+ <div className="flex flex-col gap-3">
+ <p className="text-[10px] uppercase tracking-widest text-white/40 font-bold">
+ Dispositivos 3D
+ </p>
+
+ <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"
+ }`}
+ />
- <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"
+ 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-pressed={mockupConfig?.darkMode}
- aria-label={t("darkMode.dark")}
+ aria-label="Scroll left"
>
- <Icon icon="ph:moon-bold" width="10" aria-hidden="true" /> {t("darkMode.dark")}
+ <Icon icon="ph:caret-left-bold" width="14" />
</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"
+ 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-pressed={!mockupConfig?.darkMode}
- aria-label={t("darkMode.light")}
+ aria-label="Scroll right"
>
- <Icon icon="ph:sun-bold" width="10" aria-hidden="true" /> {t("darkMode.light")}
+ <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>
- </fieldset>
+ </div>
- )}
+ {/* ── 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>
+ );
+ }
- {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>
+ // ─────────────────────────────────────────────────────────────────────────
+ // 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>
- )}
- {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 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>
+ )}
+
+ {/* 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"
+ }`}
+ 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={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>
- )}
+ </>
+ );
+ }
- {(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}
- />
+ 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" />
+ </div>
+ </div>
)}
- {features.hasHeaderOpacity && (
- <SliderControl
- icon="mdi:opacity"
- label={t("sliders.headerOpacity")}
- value={mockupConfig?.headerOpacity ?? 100}
- min={0}
- max={100}
- onChange={handleHeaderOpacityChange}
- />
+
+ {/* 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>
+ <button
+ type="button"
+ onClick={handle3DReset}
+ 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={resolvedBackgroundUrl}
+ backgroundColorCss={backgroundColorCss}
+ />
+ </div>
+ </div>
)}
+
+ <Button
+ onClick={handleRemoveAll}
+ variant="outline"
+ className="w-full text-xs mt-2"
+ >
+ <Icon icon="ph:trash-bold" width="13" aria-hidden="true" />
+ Quitar marco
+ </Button>
</div>
- )}
+ </>
- {mockupId !== "none" && (
- <button
- onClick={() => handleMockupSelect("none")}
- className="w-full flex items-center justify-center gap-2 py-2 rounded-lg border border-white/7 bg-white/4 hover:bg-red-500/10 hover:border-red-500/30 text-white/40 hover:text-red-400 text-[11px] transition-all"
- aria-label={t("remove")}
- >
- <Icon icon="ph:trash-bold" width="13" aria-hidden="true" />
- {t("remove")}
- </button>
- )}
- </div>
- );
+ );
+ }
+
+ return null;
}
\ No newline at end of file
diff --git a/app/components/ui/editor/MotionMenu.tsx b/app/components/ui/editor/MotionMenu.tsx
index 85e07c1..20aa240 100644
--- a/app/components/ui/editor/MotionMenu.tsx
+++ b/app/components/ui/editor/MotionMenu.tsx
@@ -1,25 +1,8 @@
"use client";
-import { useState } from "react";
import { Icon } from "@iconify/react";
-import { useMotionContext } from "@/app/contexts/MotionContext";
-import { MotionTemplate } from "@/types/motion.types";
-// ─── MotionMenu ───────────────────────────────────────────────────────────────
export function MotionMenu() {
- const { selectedTemplateId, setSelectedTemplateId, setMotionDuration } = useMotionContext();
- const [openTemplate, setOpenTemplate] = useState<MotionTemplate | null>(null);
-
- const handleClick = (template: MotionTemplate) => {
- if (!template.showPhone) {
- // "Solo video" — deactivate immediately, no editor
- setSelectedTemplateId("none");
- setMotionDuration(0);
- return;
- }
- // Templates with phone open their own editor
- setOpenTemplate(template);
- };
return (
<div className="p-4 flex flex-col gap-5 w-full bg-[#111113] min-h-screen">
diff --git a/app/components/ui/editor/Phone3DViewer.tsx b/app/components/ui/editor/Phone3DViewer.tsx
index e2fb340..6051510 100644
--- a/app/components/ui/editor/Phone3DViewer.tsx
+++ b/app/components/ui/editor/Phone3DViewer.tsx
@@ -1,662 +1,596 @@
"use client";
-/**
- * Phone3DViewer — R3F + drei + OrbitControls edition
- *
- * Key architectural fixes in this version:
- *
- * A. rootRef / cameraRef are now created INSIDE each scene component
- * (not passed down from Phone3DViewer). This means every Canvas remount
- * gets completely fresh refs — no stale WebGL objects from a previous
- * context leak through.
- *
- * B. Canvas key=modelUrl forces a full remount on device switch, which is
- * the cleanest way to get a fresh WebGL context. Combined with (A), this
- * eliminates the white-flash-then-disappear bug on first load.
- *
- * C. Scale factor calculation uses the camera frustum correctly.
- *
- * D. Orbit initial position is applied via Promise.resolve() microtask
- * after root.add(group) — OrbitControls is mounted by R3F by then.
- */
-
-import { Canvas, useThree } from "@react-three/fiber";
-import {
- PerspectiveCamera,
- useGLTF,
- Environment,
- OrbitControls,
-} from "@react-three/drei";
import { useCallback, useEffect, useRef, useState } 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,
- 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;
- 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;
-
-function SharedLights() {
- return (
- <>
- <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} />
- </>
- );
+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)!;
}
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; }
}
-interface SceneProps {
- imageUrl: string | null;
- imageMaskConfig: ImageMaskConfigLike | null;
- initialRotationX: number;
- initialRotationY: number;
- initialRotationZ: number;
- zoom: number;
- onRotationChange?: (rx: number, ry: number) => void;
- onApi?: (api: Phone3DApi | null) => void;
- modelUrl?: string;
- onLoaded?: () => void;
+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();
}
-// ─── GltfModelScene — iphone 15 / samsung / iphone-13 ────────────────────────
-function GltfModelScene({
- imageUrl,
- imageMaskConfig,
- initialRotationX,
- initialRotationY,
- initialRotationZ,
- zoom,
- onRotationChange,
- onApi,
- modelUrl,
- onLoaded,
-}: SceneProps) {
- const rootRef = useRef<THREE.Group>(null);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const orbitRef = useRef<any>(null);
- const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);
- const lastLoadedUrlRef = useRef<string | null>(null);
- const setupDoneRef = useRef(false);
-
- const { gl, scene, camera } = useThree();
- const device = getDeviceFromModelUrl(modelUrl);
- const deviceConfig = deviceConfigs[device];
- const gltf = useGLTF(modelUrl!) as { scene: THREE.Group };
-
- // Stable refs so callbacks always see current values
- const imageUrlRef = useRef(imageUrl);
- const imageMaskConfigRef = useRef(imageMaskConfig);
- useEffect(() => { imageUrlRef.current = imageUrl; }, [imageUrl]);
- useEffect(() => { imageMaskConfigRef.current = imageMaskConfig; }, [imageMaskConfig]);
-
- const applyTexture = useCallback((mat: THREE.MeshBasicMaterial, url: string) => {
- const img = new Image();
- img.crossOrigin = "anonymous";
- img.onload = () => {
- // requestAnimationFrame difiere la creación del CanvasTexture
- // al próximo frame para no bloquear el render actual ni
- // forzar una subida síncrona de píxeles a la GPU.
- requestAnimationFrame(() => {
- const TARGET_W = 2048;
- const TARGET_H = Math.round(TARGET_W / deviceConfig.aspectRatio);
- const cornerRadius = Math.round(TARGET_W * deviceConfig.cornerRadiusFactor);
- const cover = createCoverScreenCanvas(img, TARGET_W, TARGET_H, cornerRadius, imageMaskConfigRef.current);
- if (mat.map) { mat.map.dispose(); mat.map = null; }
- const tex = new THREE.CanvasTexture(cover);
- tex.flipY = true;
- tex.colorSpace = THREE.SRGBColorSpace;
- tex.generateMipmaps = true;
- tex.minFilter = THREE.LinearMipmapLinearFilter;
- tex.magFilter = THREE.LinearFilter;
- tex.wrapS = THREE.ClampToEdgeWrapping;
- tex.wrapT = THREE.ClampToEdgeWrapping;
- tex.anisotropy = gl.capabilities.getMaxAnisotropy();
- mat.map = tex;
- mat.color.set(0xffffff);
- mat.needsUpdate = true;
- lastLoadedUrlRef.current = url;
- });
- };
- img.onerror = () => {
- // Imagen inválida: libera cualquier textura previa y deja el
- // material con su color base (gris oscuro) en lugar del quad
- // blanco del navegador.
- if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }
- mat.color.set(0x111111);
- lastLoadedUrlRef.current = url; // evita reintento
- };
- img.src = url;
- }, [deviceConfig, gl]);
-
- // One-time setup per Canvas mount
- useEffect(() => {
- if (setupDoneRef.current) return;
- setupDoneRef.current = true;
-
- const root = rootRef.current;
- if (!root) return;
-
- const group = gltf.scene.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) * (Math.PI / 180));
- const sf = (halfH * 2 * 0.8) / size.y;
- group.scale.setScalar(sf);
- group.position.copy(center).negate().multiplyScalar(sf);
- group.rotation.z = initialRotationZ * (Math.PI / 180);
-
- const planeH = 4.3 * deviceConfig.screenHeightFactor;
- const planeW = planeH * deviceConfig.aspectRatio;
- const mat = new THREE.MeshBasicMaterial({
- color: 0x111111, side: THREE.FrontSide,
- transparent: true, depthTest: false, depthWrite: false,
- });
- const plane = new THREE.Mesh(new THREE.PlaneGeometry(planeW, planeH), mat);
- plane.position.set(deviceConfig.screenOffset.x, deviceConfig.screenOffset.y, deviceConfig.screenOffset.z);
- plane.renderOrder = 10;
- group.add(plane);
- screenMatRef.current = mat;
- root.add(group);
-
- if (imageUrlRef.current) {
- applyTexture(mat, imageUrlRef.current);
- }
-
- onLoaded?.();
-
- // Microtask: OrbitControls is guaranteed mounted by R3F before this runs
- Promise.resolve().then(() => {
- const orbit = orbitRef.current;
- if (!orbit) return;
- orbit.object.position.setFromSphericalCoords(
- DEFAULT_CAM_Z / zoom,
- Math.PI / 2 - initialRotationX * (Math.PI / 180),
- initialRotationY * (Math.PI / 180),
- );
- orbit.update();
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // Texture sync on prop change
- useEffect(() => {
- const mat = screenMatRef.current;
- if (!mat) return;
- if (!imageUrl) {
- if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }
- lastLoadedUrlRef.current = null;
- return;
- }
- if (lastLoadedUrlRef.current === imageUrl) return;
- applyTexture(mat, imageUrl);
- }, [imageUrl, imageMaskConfig, applyTexture]);
-
- // Orbit sync on prop change
- useEffect(() => {
- const orbit = orbitRef.current;
- if (!orbit) return;
- orbit.object.position.setFromSphericalCoords(
- DEFAULT_CAM_Z / zoom,
- Math.PI / 2 - initialRotationX * (Math.PI / 180),
- initialRotationY * (Math.PI / 180),
- );
- orbit.update();
- }, [initialRotationX, initialRotationY, zoom]);
-
- useEffect(() => {
- const root = rootRef.current;
- if (!root || root.children.length === 0) return;
- (root.children[0] as THREE.Group).rotation.z = initialRotationZ * (Math.PI / 180);
- }, [initialRotationZ]);
-
- useEffect(() => {
- const api: Phone3DApi = {
- renderAt: (width, height) => {
- const cam = camera as THREE.PerspectiveCamera;
- const oldAspect = cam.aspect;
- gl.setSize(width, height, false);
- cam.aspect = width / height;
- cam.updateProjectionMatrix();
- gl.clear();
- gl.render(scene, cam);
- gl.setPixelRatio(Math.min(window.devicePixelRatio || 1, 3));
- gl.setSize(PHONE_W, PHONE_H, false);
- cam.aspect = oldAspect;
- cam.updateProjectionMatrix();
- },
- };
- onApi?.(api);
- return () => onApi?.(null);
- }, [onApi, gl, scene, camera]);
-
- return (
- <>
- <PerspectiveCamera makeDefault fov={40} near={0.01} far={100} position={[0, 0, DEFAULT_CAM_Z / zoom]} />
- <OrbitControls
- ref={orbitRef}
- enableZoom={false}
- enablePan={false}
- enableDamping
- dampingFactor={0.08}
- onEnd={() => {
- const orbit = orbitRef.current;
- if (!orbit || !onRotationChange) return;
- onRotationChange(
- (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI),
- orbit.getAzimuthalAngle() * (180 / Math.PI),
- );
- }}
- />
- <SharedLights />
- <group ref={rootRef} dispose={null} />
- </>
- );
+// ─── Renderizador Interno Vanilla Three.js ────────────────────────────────────
+interface VanillaRendererProps extends Omit<Props, "scale" | "shadowIntensity" | "shadowColor"> {
+ onLoaded: () => void;
+ onContextLost: () => void;
}
-// ─── DefaultPhoneModelScene — JSON phone ──────────────────────────────────────
-function DefaultPhoneModelScene({
- imageUrl,
- imageMaskConfig,
- initialRotationX,
- initialRotationY,
- initialRotationZ,
- zoom,
- onRotationChange,
- onApi,
- onLoaded,
-}: Omit<SceneProps, "modelUrl">) {
- const rootRef = useRef<THREE.Group>(null);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const orbitRef = useRef<any>(null);
- const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);
- const screenAspectRef = useRef<number>(0.459);
- const lastLoadedUrlRef = useRef<string | null>(null);
- const setupDoneRef = useRef(false);
-
- const { gl, scene, camera } = useThree();
-
- const imageUrlRef = useRef(imageUrl);
- const imageMaskConfigRef = useRef(imageMaskConfig);
- useEffect(() => { imageUrlRef.current = imageUrl; }, [imageUrl]);
- useEffect(() => { imageMaskConfigRef.current = imageMaskConfig; }, [imageMaskConfig]);
-
- const applyTexture = useCallback((mat: THREE.MeshBasicMaterial, url: string) => {
- const aspect = screenAspectRef.current;
- const TARGET_W = PHONE_W * 4;
- const TARGET_H = Math.round(TARGET_W / aspect);
- const img = new Image();
- img.crossOrigin = "anonymous";
- img.onload = () => {
- // requestAnimationFrame difiere la creación del CanvasTexture
- // al próximo frame para no saturar la GPU.
- requestAnimationFrame(() => {
- const cover = createCoverScreenCanvas(img, TARGET_W, TARGET_H, 0, imageMaskConfigRef.current);
- if (mat.map) { mat.map.dispose(); mat.map = null; }
- const tex = new THREE.CanvasTexture(cover);
- tex.flipY = false;
- tex.colorSpace = THREE.SRGBColorSpace;
- tex.generateMipmaps = true;
- tex.minFilter = THREE.LinearMipmapLinearFilter;
- tex.magFilter = THREE.LinearFilter;
- tex.wrapS = THREE.ClampToEdgeWrapping;
- tex.wrapT = THREE.ClampToEdgeWrapping;
- tex.anisotropy = gl.capabilities.getMaxAnisotropy();
- mat.map = tex;
- mat.color.set(0xffffff);
- mat.needsUpdate = true;
- lastLoadedUrlRef.current = url;
- });
- };
- img.onerror = () => {
- if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }
- mat.color.set(0x111111);
- lastLoadedUrlRef.current = url;
- };
- img.src = url;
- }, [gl]);
-
- useEffect(() => {
- if (setupDoneRef.current) return;
- setupDoneRef.current = true;
-
- loadGltfGroup().then((cached) => {
- const root = rootRef.current;
- if (!root || root.children.length > 0) return;
-
- 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) * (Math.PI / 180));
- const sf = (halfH * 2 * 0.8) / size.y;
- group.scale.setScalar(sf);
- group.position.copy(center).negate().multiplyScalar(sf);
- group.rotation.z = initialRotationZ * (Math.PI / 180);
-
- 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 (!Array.isArray(child.material)) {
- const m = child.material as THREE.MeshStandardMaterial;
- if (m.isMeshStandardMaterial) applyMetalMaterial(m, matName);
+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;
}
- });
- root.add(group);
+ if (lastLoadedUrlRef.current === imageUrl && lastLoadedCropKeyRef.current === cropKey) {
+ return;
+ }
- if (imageUrlRef.current && screenMatRef.current) {
- applyTexture(screenMatRef.current, imageUrlRef.current);
- }
+ 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();
+ });
+ } 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();
+ });
+ }
- onLoaded?.();
+ // 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);
+ });
+ 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]);
- Promise.resolve().then(() => {
- const orbit = orbitRef.current;
- if (!orbit) return;
- orbit.object.position.setFromSphericalCoords(
- DEFAULT_CAM_Z / zoom,
- Math.PI / 2 - initialRotationX * (Math.PI / 180),
- initialRotationY * (Math.PI / 180),
- );
- orbit.update();
- });
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- useEffect(() => {
- const mat = screenMatRef.current;
- if (!mat) return;
- if (!imageUrl) {
- if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }
- lastLoadedUrlRef.current = null;
- return;
- }
- if (lastLoadedUrlRef.current === imageUrl) return;
- applyTexture(mat, imageUrl);
- }, [imageUrl, imageMaskConfig, applyTexture]);
-
- useEffect(() => {
- const orbit = orbitRef.current;
- if (!orbit) return;
- orbit.object.position.setFromSphericalCoords(
- DEFAULT_CAM_Z / zoom,
- Math.PI / 2 - initialRotationX * (Math.PI / 180),
- initialRotationY * (Math.PI / 180),
- );
- orbit.update();
- }, [initialRotationX, initialRotationY, zoom]);
-
- useEffect(() => {
- const root = rootRef.current;
- if (!root || root.children.length === 0) return;
- (root.children[0] as THREE.Group).rotation.z = initialRotationZ * (Math.PI / 180);
- }, [initialRotationZ]);
-
- useEffect(() => {
- const api: Phone3DApi = {
- renderAt: (width, height) => {
- const cam = camera as THREE.PerspectiveCamera;
- const oldAspect = cam.aspect;
- gl.setSize(width, height, false);
- cam.aspect = width / height;
- cam.updateProjectionMatrix();
- gl.clear();
- gl.render(scene, cam);
- gl.setPixelRatio(Math.min(window.devicePixelRatio || 1, 3));
- gl.setSize(PHONE_W, PHONE_H, false);
- cam.aspect = oldAspect;
- cam.updateProjectionMatrix();
- },
- };
- onApi?.(api);
- return () => onApi?.(null);
- }, [onApi, gl, scene, camera]);
-
- return (
- <>
- <PerspectiveCamera makeDefault fov={40} near={0.01} far={100} position={[0, 0, DEFAULT_CAM_Z / zoom]} />
- <OrbitControls
- ref={orbitRef}
- enableZoom={false}
- enablePan={false}
- enableDamping
- dampingFactor={0.08}
- onEnd={() => {
- const orbit = orbitRef.current;
- if (!orbit || !onRotationChange) return;
- onRotationChange(
- (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI),
- orbit.getAzimuthalAngle() * (180 / Math.PI),
- );
- }}
- />
- <SharedLights />
- <group ref={rootRef} dispose={null} />
- </>
- );
+ 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%" }} />;
}
-// ─── Phone3DViewer (public) ───────────────────────────────────────────────────
+// ─── Componente Principal Público ─────────────────────────────────────────────
export function Phone3DViewer({
- imageUrl = null,
- imageMaskConfig = null,
- initialRotationX = 0,
- initialRotationY = 0,
- initialRotationZ = 0,
- onRotationChange,
- onMount,
- onApi,
- modelUrl,
- scale = 1,
- zoom = 1,
- shadowIntensity = 0,
- shadowColor = "#000000",
-}: Props) {
- const [grabbing, setGrabbing] = useState(false);
-
- const device = getDeviceFromModelUrl(modelUrl);
- const isDefaultPhone = device === "phone";
-
- 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;
-
- const sceneProps: SceneProps = {
- imageUrl,
- imageMaskConfig,
- initialRotationX,
- initialRotationY,
- initialRotationZ,
- zoom,
+ imageUrl = null,
+ imageMaskConfig = null,
+ cropArea = null,
+ initialRotationX = 0,
+ initialRotationY = 0,
+ initialRotationZ = 0,
onRotationChange,
+ onMount,
onApi,
modelUrl,
- };
-
- 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: "150px"
- }}
- >
- <div style={{ position: "relative", width: PHONE_W, height: PHONE_H }}>
-
- {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",
- }}
- />
- )}
-
- {/* Canvas wrapper — inset negativo para que OrbitControls no clipee */}
- <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)}
- >
- <CanvasWithLoader
- key={modelUrl ?? "default"}
- isDefaultPhone={isDefaultPhone}
- sceneProps={sceneProps}
- onMount={onMount}
- />
- </div>
- </div>
- </div>
- );
-}
-
-// ─── CanvasWithLoader ────────────────────────────────────────────────────────
-// Each instance owns its own `loaded` state. Remounting via `key` is the
-// idiomatic React way to reset state when modelUrl changes — no
-// cascading setState in useEffect.
-function CanvasWithLoader({
- isDefaultPhone,
- sceneProps,
- onMount,
-}: {
- isDefaultPhone: boolean;
- sceneProps: SceneProps;
- onMount?: (canvas: HTMLCanvasElement) => void;
-}) {
- const [loaded, setLoaded] = useState(false);
+ 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 (
- <>
- <Canvas
- style={{
- width: "100%",
- height: "100%",
- overflow: "visible",
- display: "block",
- }}
- gl={{
- antialias: true,
- alpha: true,
- preserveDrawingBuffer: true,
- powerPreference: "high-performance",
- // Permite software rendering si la GPU no soporta WebGL2 —
- // reduce probabilidad de "Context Lost" en hardware limitado.
- failIfMajorPerformanceCaveat: false,
- }}
- // dpr=2: balance entre nitidez y consumo de VRAM. dpr=4
- // saturaba la GPU junto con los GLB pesados (iPhone 15, S25)
- // y causaba "WebGLRenderer: Context Lost".
- dpr={2}
- onCreated={({ gl, scene: s }) => {
- gl.outputColorSpace = THREE.SRGBColorSpace;
- gl.toneMapping = THREE.NeutralToneMapping;
- gl.toneMappingExposure = 1.0;
- s.environmentIntensity = 1.6;
- onMount?.(gl.domElement);
- }}
- >
- {isDefaultPhone
- ? <DefaultPhoneModelScene {...sceneProps} onLoaded={() => setLoaded(true)} />
- : <GltfModelScene {...sceneProps} onLoaded={() => setLoaded(true)} />
- }
- </Canvas>
-
- {/* Loader — covers the white screen plane while the GLB
- and the user's image texture are loading on first mount.
- Removed automatically via key remount on device switch. */}
- {!loaded && (
<div
- className="absolute inset-0 flex items-center justify-center pointer-events-none"
- style={{ zIndex: 4 }}
+ style={{
+ display: "inline-block",
+ transformOrigin: "top center",
+ transform: `scale(${scale})`,
+ width: PHONE_W,
+ height: PHONE_H + (hasShadow ? computedBlur * 0.8 : 0),
+ marginTop: "220px",
+ }}
>
- <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
+ <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>
</div>
- )}
- </>
- );
+ );
}
\ No newline at end of file
diff --git a/app/components/ui/editor/PhotoEditorPlaceholder.tsx b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
index 1d2f675..9d897ab 100644
--- a/app/components/ui/editor/PhotoEditorPlaceholder.tsx
+++ b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
@@ -17,7 +17,7 @@ import {
PopoverTitle,
} from "@/components/ui/popover";
import { PhotoEditorPlaceholderProps, Preview3DConfig, PREVIEW_CONFIGS, PREVIEW_TO_PHONE_OFFSET } from "@/types/photo.types";
-import { useMotionContext } from "@/app/contexts/MotionContext";
+import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";
export function PhotoEditorPlaceholder({
className = "",
@@ -38,7 +38,7 @@ export function PhotoEditorPlaceholder({
}: PhotoEditorPlaceholderProps) {
const previewImageUrl = staticImageUrl ?? canvasImageUrl;
const t = useTranslations("editor");
- const { imagePhoneActive, imagePhoneDevice, setImagePhoneRotX, setImagePhoneRotY, setImagePhoneRotZ, setImagePhonePerspective, setImagePhoneScale, setImagePhoneY, setImagePhonePresetId } = useMotionContext();
+ const { imagePhoneActive, imagePhoneDevice, setImagePhoneRotX, setImagePhoneRotY, setImagePhoneRotZ, setImagePhonePerspective, setImagePhoneScale, setImagePhoneY, setImagePhonePresetId } = useMockup3dContext();
const [customConfig, setCustomConfig] = useState<Preview3DConfig>({
id: "custom",
label: "Custom",
diff --git a/app/components/ui/editor/ToolsSidebar.tsx b/app/components/ui/editor/ToolsSidebar.tsx
index 28b88d4..c2fdf7b 100644
--- a/app/components/ui/editor/ToolsSidebar.tsx
+++ b/app/components/ui/editor/ToolsSidebar.tsx
@@ -259,8 +259,11 @@ export function ToolsSidebar({
description: t("popovers.mockup.description"),
videoSrc: "/videos/preview-mockup.mp4"
}}
+ badge={t("tools.newTool")}
+ badgeStyle="premium"
/>
- {isPhotoMode && (
+
+ {/* {isPhotoMode && (
<SidebarTool
icon="mage:box-3d"
label={t("tools.motion")}
@@ -274,8 +277,8 @@ export function ToolsSidebar({
badge={t("tools.newTool")}
badgeStyle="premium"
/>
- )}
-
+ )} */}
+
{/* Video-specific tools - hidden in photo mode */}
{!isPhotoMode && (
<SidebarTool
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index a2119e5..7be1c21 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -24,7 +24,7 @@ import { EditorHoverTooltip } from "./EditorHoverTooltip";
import DropImage from "@/components/ui/DropImage";
import { LayersPanel } from "./LayersPanel";
import { Icon } from "@iconify/react";
-import { useMotionContext } from "@/app/contexts/MotionContext";
+import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";
import { PHONE_H, PHONE_W } from "@/lib/phone3d.utils";
export type { VideoCanvasHandle, VideoCanvasProps };
@@ -46,7 +46,6 @@ const IPhone13ProMax3DViewer = dynamic(
export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({
activeTool: _activeTool,
- isPlaying = false,
mediaType = "video",
imageUrl = null,
imageRef,
@@ -112,7 +111,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
imagePhoneDevice, imagePhonePresetId,
imagePhoneOpening,
imagePhoneShadow, imagePhoneShadowColor
- } = useMotionContext();
+ } = useMockup3dContext();
// Phone shows whenever a real template is selected AND we are in video mode
const motionActive = selectedTemplateId !== null && selectedTemplateId !== "none" && mediaType === "video";
@@ -128,6 +127,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// at the export resolution right before capturing (fixes the pixelation
// caused by upscaling a 595×765 canvas to 4K).
const imagePhoneApiRef = useRef<{ renderAt: (w: number, h: number) => void } | null>(null);
+ const [activePhoneDevice, setActivePhoneDevice] = useState<string | null>(null);
+ const [phoneTransitioning, setPhoneTransitioning] = useState(false);
// Model URL for the active device
const PHONE_DEVICE_URLS: Record<string, string | undefined> = {
@@ -488,6 +489,28 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
}
}, [imageUrlToLoad]);
+
+ useEffect(() => {
+ if (!imagePhoneActive) {
+ setActivePhoneDevice(null);
+ return;
+ }
+ if (imagePhoneDevice === activePhoneDevice) return;
+
+ // 1. Desmonta el viewer actual (libera contexto WebGL)
+ setPhoneTransitioning(true);
+ setActivePhoneDevice(null);
+
+ // 2. Espera un frame para que el GC libere el contexto viejo
+ // antes de crear el nuevo
+ const id = setTimeout(() => {
+ setActivePhoneDevice(imagePhoneDevice);
+ setPhoneTransitioning(false);
+ }, 50); // 50ms es suficiente para que el contexto anterior se libere
+
+ return () => clearTimeout(id);
+ }, [imagePhoneDevice, imagePhoneActive]);
+
// Preload canvas element images (only for image elements, not SVGs)
useEffect(() => {
const cache = elementImagesRef.current;
@@ -2070,7 +2093,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
}}
/>
- {/* ── Motion 3D Phone Overlay — INSIDE zoom layer so fragment-zoom applies ── */}
{motionActive && (
<div
ref={phoneOverlayRef}
@@ -2082,9 +2104,9 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
<div
style={{
transform: `scale(${motionZoomScale})`,
- transformOrigin: 'center center',
- transition: 'transform 0.08s ease-out',
- willChange: 'transform',
+ transformOrigin: "center center",
+ transition: "transform 0.08s ease-out",
+ willChange: "transform",
}}
>
<Phone3DViewer
@@ -2108,39 +2130,69 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
</div>
)}
- {/* ── Image-mode phone overlay — inside zoom layer for correct z-index stacking ── */}
+ {/* ── Image-mode phone overlay ── */}
{mediaType === "image" && imagePhoneActive && (
<div
className="absolute inset-0 pointer-events-none"
style={{ zIndex: 155, overflow: "visible" }}
>
+ <div
+ className="absolute animate-in fade-in zoom-in-95 duration-300"
+ style={{
+ left: "50%",
+ top: "50%",
+ transform: `translate(calc(-50% + ${imagePhoneX}px), calc(-50% + ${imagePhoneY}px))`,
+ transformOrigin: "center center",
+ pointerEvents: "none",
+ userSelect: "none",
+ zIndex: 9999,
+ }}
+ >
+ <div
+ style={{
+ position: "absolute",
+ left: "50%",
+ transform: "translateX(-50%)",
+ pointerEvents: "none",
+ }}
+ >
+ <EditorHoverTooltip show={isVideoHovered && mediaType === "image"} />
+ </div>
+ </div>
+
+ {/* Mockup layer: SÍ se escala */}
<div
className="absolute animate-in fade-in zoom-in-95 duration-300"
data-image-phone-overlay
onMouseEnter={() => setIsVideoHovered(true)}
onMouseLeave={() => setIsVideoHovered(false)}
style={{
- left: '50%',
- top: '50%',
+ left: "50%",
+ top: "50%",
transform: `translate(calc(-50% + ${imagePhoneX}px), calc(-50% + ${imagePhoneY}px)) scale(${imagePhoneScale})`,
- transformOrigin: 'center center',
- pointerEvents: 'auto',
- userSelect: 'none',
- filter: imagePhoneShadow > 0 && imagePhoneDevice !== "laptop"
- ? `drop-shadow(0px ${18 * imagePhoneShadow}px ${28 * imagePhoneShadow}px ${imagePhoneShadowColor})`
- : "none",
+ transformOrigin: "center center",
+ pointerEvents: "auto",
+ userSelect: "none",
+ filter:
+ imagePhoneShadow > 0 && imagePhoneDevice !== "laptop"
+ ? `drop-shadow(0px ${18 * imagePhoneShadow}px ${28 * imagePhoneShadow}px ${imagePhoneShadowColor})`
+ : "none",
}}
>
- <div style={{ position: "relative", zIndex: 50 }} className="top-120">
- <EditorHoverTooltip show={isVideoHovered && mediaType === "image"} />
- </div>
-
- {imagePhoneDevice === "laptop" ? (
+ {phoneTransitioning || !activePhoneDevice ? (
+ <div
+ style={{ width: PHONE_W, height: PHONE_H }}
+ className="flex items-center justify-center"
+ >
+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
+ </div>
+ ) : activePhoneDevice === "laptop" ? (
<Laptop3DViewer
- key={`laptop-${imagePhonePresetId}`}
+ key="laptop"
imageUrl={imageUrl}
openingProgress={imagePhoneOpening}
imageMaskConfig={imageMaskConfig}
+ cropArea={cropArea}
initialRotationX={imagePhoneRotX}
initialRotationY={imagePhoneRotY}
initialRotationZ={imagePhoneRotZ}
@@ -2148,24 +2200,36 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
setImagePhoneRotX(rx);
setImagePhoneRotY(ry);
}}
- onMount={(canvas) => { imagePhoneCanvasRef.current = canvas; }}
- onApi={(api) => { imagePhoneApiRef.current = api; }}
+ onMount={(canvas) => {
+ imagePhoneCanvasRef.current = canvas;
+ }}
+ onApi={(api) => {
+ imagePhoneApiRef.current = api;
+ }}
scale={1}
zoom={1}
shadowIntensity={imagePhoneShadow}
shadowColor={imagePhoneShadowColor}
/>
- ) : imagePhoneDevice === "iphone-13-pro-max" ? (
+ ) : activePhoneDevice === "iphone-13-pro-max" ? (
<IPhone13ProMax3DViewer
- key={`iphone-13-pro-max-${imagePhonePresetId}`}
+ key="iphone-13-pro-max"
imageUrl={imageUrl}
imageMaskConfig={imageMaskConfig}
+ cropArea={cropArea}
initialRotationX={imagePhoneRotX}
initialRotationY={imagePhoneRotY}
initialRotationZ={imagePhoneRotZ}
- onRotationChange={(rx, ry) => { setImagePhoneRotX(rx); setImagePhoneRotY(ry); }}
- onMount={(canvas) => { imagePhoneCanvasRef.current = canvas; }}
- onApi={(api) => { imagePhoneApiRef.current = api; }}
+ onRotationChange={(rx, ry) => {
+ setImagePhoneRotX(rx);
+ setImagePhoneRotY(ry);
+ }}
+ onMount={(canvas) => {
+ imagePhoneCanvasRef.current = canvas;
+ }}
+ onApi={(api) => {
+ imagePhoneApiRef.current = api;
+ }}
scale={1}
zoom={1}
shadowIntensity={imagePhoneShadow}
@@ -2173,9 +2237,10 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
/>
) : (
<Phone3DViewer
- key={`${imagePhoneDevice}-${imagePhonePresetId}`}
+ key={imagePhoneDevice}
imageUrl={imageUrl}
imageMaskConfig={imageMaskConfig}
+ cropArea={cropArea}
initialRotationX={imagePhoneRotX}
initialRotationY={imagePhoneRotY}
initialRotationZ={imagePhoneRotZ}
@@ -2188,8 +2253,12 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
setImagePhoneRotX(rx);
setImagePhoneRotY(ry);
}}
- onMount={(canvas) => { imagePhoneCanvasRef.current = canvas; }}
- onApi={(api) => { imagePhoneApiRef.current = api; }}
+ onMount={(canvas) => {
+ imagePhoneCanvasRef.current = canvas;
+ }}
+ onApi={(api) => {
+ imagePhoneApiRef.current = api;
+ }}
/>
)}
</div>
diff --git a/app/components/ui/editor/ZoomFragmentEditor.tsx b/app/components/ui/editor/ZoomFragmentEditor.tsx
index 3ead8be..568327e 100644
--- a/app/components/ui/editor/ZoomFragmentEditor.tsx
+++ b/app/components/ui/editor/ZoomFragmentEditor.tsx
@@ -7,6 +7,7 @@ import { SliderControl } from "../SliderControl";
import type { ZoomFragmentEditorProps } from "@/types/zoom.types";
import { formatZoomTime, zoomLevelToFactor, speedToTransitionMs, calculateHoldDuration } from "@/types/zoom.types";
import { TooltipAction } from "@/components/ui/tooltip-action";
+import { DetailPageHeader } from "@/components/ui/DetailHeaderMenu";
export function ZoomFragmentEditor({
fragment, videoUrl, videoThumbnail, currentTime = 0,
@@ -77,12 +78,11 @@ export function ZoomFragmentEditor({
<div className="flex flex-col h-full text-white">
{/* Header */}
<div className="flex items-center gap-2 p-3 border-b border-white/6 shrink-0">
- <button onClick={onBack} className="flex items-center justify-center size-7 rounded-md hover:bg-white/6 text-white/50 transition-colors">
- <Icon icon="ph:arrow-left-bold" width="14" />
- </button>
- <div className="flex items-center gap-2 min-w-0">
- <span className="text-md font-medium text-white truncate">{t("title")}</span>
- </div>
+ <DetailPageHeader
+ label={t("title")}
+ icon="ph:arrow-left-bold"
+ onBack={onBack}
+ />
<TooltipAction label={t("deleteTooltip")}>
<button onClick={onDelete} className="ml-auto flex items-center gap-1.5 text-[10px] text-red-400/70 hover:text-red-400 px-2 py-1 rounded-md transition-colors shrink-0">
<Icon icon="ph:trash-bold" width="12" />
diff --git a/app/contexts/MotionContext.tsx b/app/contexts/Mockup3dContext.tsx
similarity index 81%
rename from app/contexts/MotionContext.tsx
rename to app/contexts/Mockup3dContext.tsx
index 2b23539..95c643e 100644
--- a/app/contexts/MotionContext.tsx
+++ b/app/contexts/Mockup3dContext.tsx
@@ -1,33 +1,16 @@
"use client";
import { createContext, useCallback, useContext, useRef, useState, type ReactNode } from "react";
-import type { MotionStyle, AnimMode } from "@/types/motion.types";
-interface MotionState {
+interface Mockup3dState {
selectedTemplateId: string | null;
setSelectedTemplateId: (id: string | null) => void;
- motionDuration: number;
- setMotionDuration: (d: number) => void;
-
motionImageUrl: string | null;
setMotionImageUrl: (url: string | null) => void;
motionIntensity: number;
setMotionIntensity: (i: number) => void;
-
- motionStyle: MotionStyle;
- setMotionStyle: (s: MotionStyle) => void;
-
- /** ID of the active camera-path variant within the current template */
- motionVariantId: string | null;
- setMotionVariantId: (id: string) => void;
-
- /** Which finite animations play: entry, exit, both, or none */
- motionAnimMode: AnimMode;
- setMotionAnimMode: (m: AnimMode) => void;
-
- // ── Image mode phone mockup state ──────────────────────────────────────────
/** Whether the phone mockup is active in image mode */
imagePhoneActive: boolean;
setImagePhoneActive: (v: boolean) => void;
@@ -77,16 +60,13 @@ interface MotionState {
canRedoMotion: boolean;
}
-const MotionContext = createContext<MotionState | null>(null);
+const Mockup3dContext = createContext<Mockup3dState | null>(null);
-export function MotionProvider({ children }: { children: ReactNode }) {
+export function Mockup3dProvider({ children }: { children: ReactNode }) {
const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null);
- const [motionDuration, setMotionDuration] = useState(8000); // era 4000
const [motionImageUrl, setMotionImageUrl] = useState<string | null>(null);
const [motionIntensity, setMotionIntensity] = useState(70);
- const [motionStyle, setMotionStyle] = useState<MotionStyle>("normal");
- const [motionVariantId, setMotionVariantId] = useState<string | null>(null);
- const [motionAnimMode, setMotionAnimMode] = useState<AnimMode>("entry+exit");
+ // Add this with your other useState hooks inside Mockup3dProvider
// Image mode phone mockup
const [imagePhoneActive, setImagePhoneActive] = useState(false);
@@ -104,8 +84,6 @@ export function MotionProvider({ children }: { children: ReactNode }) {
const [imagePhoneShadowColor, setImagePhoneShadowColor] = useState("#000000");
// ── Undo/redo stack for motion transforms (max 50 entries) ────────────────
- // Each entry is a snapshot of the transform-related state. When the user
- // presses Ctrl+Z / Ctrl+Shift+Z, we pop/push from the stacks.
const historyRef = useRef<{
past: Array<{
x: number; y: number; scale: number;
@@ -119,8 +97,6 @@ export function MotionProvider({ children }: { children: ReactNode }) {
}>;
}>({ past: [], future: [] });
const MAX_HISTORY = 50;
- // Tracked via useState so consumers re-render when the stacks change.
- // (Mutating historyRef.current alone wouldn't trigger a re-render.)
const [canUndoMotion, setCanUndoMotion] = useState(false);
const [canRedoMotion, setCanRedoMotion] = useState(false);
@@ -173,14 +149,10 @@ export function MotionProvider({ children }: { children: ReactNode }) {
}, [imagePhoneX, imagePhoneY, imagePhoneScale, imagePhoneRotX, imagePhoneRotY, imagePhoneRotZ, imagePhoneOpening, imagePhoneShadow, imagePhoneShadowColor]);
return (
- <MotionContext.Provider value={{
+ <Mockup3dContext.Provider value={{
selectedTemplateId, setSelectedTemplateId,
- motionDuration, setMotionDuration,
motionImageUrl, setMotionImageUrl,
motionIntensity, setMotionIntensity,
- motionStyle, setMotionStyle,
- motionVariantId, setMotionVariantId,
- motionAnimMode, setMotionAnimMode,
imagePhoneActive, setImagePhoneActive,
imagePhoneX, setImagePhoneX,
imagePhoneY, setImagePhoneY,
@@ -199,12 +171,12 @@ export function MotionProvider({ children }: { children: ReactNode }) {
canRedoMotion,
}}>
{children}
- </MotionContext.Provider>
+ </Mockup3dContext.Provider>
);
}
-export function useMotionContext() {
- const ctx = useContext(MotionContext);
- if (!ctx) throw new Error("useMotionContext must be used inside MotionProvider");
+export function useMockup3dContext() {
+ const ctx = useContext(Mockup3dContext);
+ if (!ctx) throw new Error("useMockup3dContext must be used inside Mockup3dProvider");
return ctx;
}
\ No newline at end of file
diff --git a/claude.md b/claude.md
index 456dac9..f47045e 100644
--- a/claude.md
+++ b/claude.md
@@ -31,18 +31,21 @@ El **editor funciona sin backend**: todo se procesa con FFmpeg.wasm / MediaBunny
- `VIDEO_MODE_CONFIG` y `PHOTO_MODE_CONFIG` (`types/editor-mode.types.ts`) activan/desactivan features: timeline, playerControls, videoClips, audioTracks, zoomFragments, camera, cursor, mockups, background, elements, export.
- **Photo mode**: sube/edita imágenes con mockups, 3D previews, image masking, export como PNG/WEBP/JPG/AVIF.
-### Mockups (15+ componentes)
-Definidos en `lib/mockup-data.tsx` con catálogo `MOCKUPS: Mockup[]` y renderer en `MockupWrapper.tsx`:
-- **macOS** (light/dark, glass, ghost, ghost-glass, container-glass, dark-ide, ghost-ide)
-- **iPhone** (slim)
-- **S24 Ultra** (Samsung)
-- **Chrome** / **Brave** / **Browser tab glass**
-- **VSCode** (editor oscuro)
-- **Glass variants** (curve, full, ui-container, hard-shell)
-- **Mockup config**: `darkMode`, `frameColor`, `url`, `headerScale`, `headerOpacity`, `cornerRadius` — cada mockup declara qué features soporta (`MockupFeatures`).
-- **Smart radius**: `BOTTOM_ONLY_RADIUS_MOCKUPS` y `SELF_SHADOWING_MOCKUPS` en `lib/constants.ts` controlan cómo se renderiza el `border-radius` y la sombra por mockup.
-- **Perspectiva 3D** del frame vía CSS 3D transforms o canvas (`lib/perspective3d.ts` con Three.js `WebGLRenderer` offscreen).
-- **Duplicación deliberada**: cada mockup vive en `app/components/ui/editor/mockups/*.tsx` (preview React) y en `lib/mockup-canvas/*.ts` (renderer canvas para export) — **NO tocar uno sin tocar el otro**.
+### Mockups 3D (consolidados en `MockupMenu`)
+La lógica de motion/mockup 3D se consolidó en el menú `MockupMenu` (`app/components/ui/editor/MockupMenu.tsx`). Dispositivos soportados definidos en `IMAGE_DEVICE_TEMPLATES` (`types/mockup.types.ts`):
+- **`Mockup3dContext`** (`app/contexts/Mockup3dContext.tsx`) — estado global del mockup 3D: `imagePhoneActive/X/Y/Scale/RotX/RotY/RotZ/Perspective/Device/PresetId/Opening/Shadow/ShadowColor`. Hook `useMockup3dContext()`. Reemplaza al antiguo `MotionContext` (eliminado). Incluye undo/redo (`pushHistory`/`undoMotion`/`redoMotion`/`canUndoMotion`/`canRedoMotion`).
+- **3 viewers 3D** (todos reescritos a vanilla Three.js + `OrbitControls` + `RoomEnvironment` para el PBR):
+ - **`Phone3DViewer.tsx`** (~600 líneas) — vanilla Three.js. Renderiza el phone default JSON (`/models/phone-gltf.glb`) o los GLB específicos según `modelUrl`. Soporta iPhone 15 Pro Max, Samsung S25 Ultra, iPhone 13 Pro Max.
+ - **`IPhone13ProMax3DViewer.tsx`** (~464 líneas) — vanilla Three.js con `OrbitControls`. Carga `/models/apple_iphone_13_pro_max.glb` con `RoomEnvironment`. Inyecta la imagen del usuario en `Body_Wallpaper_0` (los UVs del mesh están listos, no requiere plane overlay). Maneja `webglcontextlost`/`webglcontextrestored` para evitar crash. Sync de `initialRotationX/Y` via spherical coords, `initialRotationZ` aplicado al `rootGroup.rotation.z`.
+ - **`Laptop3DViewer.tsx`** (~574 líneas) — vanilla Three.js. Carga `/models/mac-book.glb` con su sistema propio de drag (no OrbitControls) + inertia/damping via RAF loop. Pantalla customizable con `screenMaterial` y `darkPlasticMaterial`. `lid` rotación animada por `openingProgress`. **Mantener drag fluido y sync con popup Custom funcionando** (es el viewer de referencia — copia el patrón cuando crees viewers nuevos).
+- **Devices soportados**: `'phone' | 'iphone' | 'iphone-13-pro-max' | 'samsung' | 'laptop'`
+- **Sync crop**: `cropArea` (de `ImageCropperModal`) se aplica vía `applyCropToImage()` (`lib/phone3d.utils.ts`) ANTES del cover-fit. Los 3 viewers lo soportan.
+- **Sync mask**: `imageMaskConfig` (de `ImageMaskEditor`) se aplica vía `createCoverScreenCanvas()` con `globalCompositeOperation = "destination-out"` y gradientes lineales.
+- **PRESETS thumbnails** (`PREVIEW_CONFIGS` en `types/photo.types.ts`): front / top-left-angle / top-right-angle / bottom-left-angle / bottom-right-angle / isometric / tilt-up / tilt-down + custom (crosshair + sliders del popup). Cada preset mapea a `PREVIEW_TO_PHONE_OFFSET` que setea `imagePhoneRotX/Y` y remonta el viewer (vía `key={imagePhonePresetId}` en `VideoCanvas`).
+- **Popup Custom** (`PhotoEditorPlaceholder.tsx`): sliders de Scale, Rotation X/Y (crosshair), Rotation Z, Vertical translateY, Perspective. Todos se sincronizan al state global y al viewer.
+- **Posición por defecto iPhone 13 Pro Max**: `RotX=-58.23, RotY=-29.82` (seteada en `handleDeviceClick` de `MockupMenu.tsx:421-423` cuando se selecciona el dispositivo).
+- **Ctrl+scroll zoom** en phone overlay con badge indicador.
+- **`MockupMenu` lazy-loaded** en `ControlPanel.tsx` con `MockupMenuSkeleton`.
### Fondos
- **100+ presets** categorizados en `lib/wallpaper.catalog.ts` (desktop, gradient, minimal, pattern).
@@ -72,15 +75,6 @@ Definidos en `lib/mockup-data.tsx` con catálogo `MOCKUPS: Mockup[]` y renderer
- **3D perspective** vía `lib/perspective3d.ts` (offscreen WebGL + CanvasTexture) — aplicado SOLO al foreground (mockup), no al background.
- **GlobalConfig** (`ZoomGlobalConfig.tsx`) lista fragmentos, **TrackItem** los muestra en la timeline, **Editor** edita focus points + toggle movement/3D.
-### Motion / 3D Phone
-- **`MotionContext`** (`app/contexts/MotionContext.tsx`) — estado global: `selectedTemplateId`, `motionDuration/Intensity/Style/VariantId/AnimMode/ImageUrl` + `imagePhoneActive/X/Y/Scale/RotX/RotY/Device/PresetId`.
-- **`MotionTemplate`** con `ScriptFn` que devuelve un `gsap.core.Timeline` (`types/motion.types.ts`).
-- **`Phone3DViewer.tsx`** — única master timeline (idle → entry → hold → exit → done) con `gsap.timeline()` + `gsap.delayedCall`. Carga GLTF (phone default, iPhone 15 Pro Max, Samsung S25 Ultra) desde `public/models/`.
-- **Templates registrados** en `lib/template-registry.ts` (`soloVideoTemplate`, `phoneTemplate`; otros comentados para futuro).
-- **Style presets** (`STYLE_CFG` en `lib/animation-core.ts`): `smooth` / `normal` / `cinematic` con amplitudes y easings distintos.
-- **`ImageMotionMenu.tsx`** para modo foto: position pad (X/Y), device picker, presets, image upload.
-- **Ctrl+scroll zoom** en phone overlay con badge indicador.
-
### Audio
- **Multi-track** (hasta `MAX_AUDIO_TRACKS = 5`).
- **Cada track** (`types/audio.types.ts`): id, audioId, name, startTime, duration, volume, loop, trimStart.
@@ -148,7 +142,7 @@ Definidos en `lib/mockup-data.tsx` con catálogo `MOCKUPS: Mockup[]` y renderer
- **Estilos**: Tailwind CSS 4 (`@tailwindcss/postcss`), `tw-animate-css`, `class-variance-authority`, `tailwind-merge`, `clsx`
- **UI primitives**: Radix UI (`@radix-ui/react-dialog`, `react-dropdown-menu`), `radix-ui`, shadcn (`components.json`), iconos `lucide-react` y `@iconify/react`
- **Animaciones**: Framer Motion 12, GSAP 3.15 + ScrollTrigger, Atropos (parallax), Swapy (drag-reorder)
-- **3D / gráficos**: Three.js 0.184 + `@types/three` (WebGL renderer offscreen para perspective 3D y motion phone)
+- **3D / gráficos**: Three.js 0.184 + `@types/three` (vanilla Three.js para los 3 viewers 3D: `Phone3DViewer`, `IPhone13ProMax3DViewer`, `Laptop3DViewer`). Usa `OrbitControls` y `RoomEnvironment` directamente desde `three/examples/jsm/...`. **No usa** `@react-three/fiber` ni `@react-three/drei` (esos paquetes siguen instalados pero no se importan en el editor).
- **Video / media**:
- `@ffmpeg/ffmpeg` + `@ffmpeg/core` + `@ffmpeg/util` (servidos desde `public/ffmpeg/`)
- `mediabunny` (pipeline de video optimizado MP4/WebM)
@@ -183,14 +177,13 @@ openvidshot/
│ │ ├── seo/ # StructuredData (JSON-LD: WebApp + Organization)
│ │ └── ui/
│ │ ├── editor/ # Núcleo del editor (ver §5)
-│ │ │ ├── mockups/ # 18+ componentes React de mockups
-│ │ │ └── templates-motion/ # Plantillas de animación (Phone)
+│ │ │ └── mockups/ # 18+ componentes React de mockups
│ │ ├── home/ # Landing (Hero, Demo, BannerCTA, RecordingSteps, ...)
│ │ ├── floating/ # FloatingCameraPreview, RecordingOverlay, ExportOverlay
│ │ └── ... # AspectRatioSelect, BackgroundColorEditor, ExportDropdown, PhotoPicker, RecordingSetup, SidebarTool, Skeleton, SliderControl, TabButton, TemplateEditorShell, WalpaperSections
│ ├── config/env.ts # ENV tipado (unsplash, pexels, pixabay keys)
│ ├── contexts/
-│ │ ├── MotionContext.tsx # Estado global de motion/3D phone
+│ │ ├── Mockup3dContext.tsx # Estado global del mockup 3D (reemplaza MotionContext)
│ │ ├── RecordingContext.tsx # Provider de grabación + Alt+S/Alt+D shortcuts
│ │ ├── useAuth.tsx # Sesión Supabase + AuthProvider
│ ├── [locale]/
@@ -218,11 +211,11 @@ openvidshot/
│ ├── useVideoUpload.ts / useVideoThumbnails.ts / useVideoExport.ts
│ ├── useImageExport.ts / useImageProjects.ts
│ ├── useEditorMode.ts # Lee `?mode=` de URL
+│ ├── useActiveTool.ts # Lee `?m=<tool>` de URL (sincroniza sidebar/ControlPanel con query params)
│ ├── useUndoRedo.ts # History stack (max 50)
│ ├── useDebounce.ts
│
├── lib/ # Lógica pura, utils y catálogos
-│ ├── animation-core.ts # NRX/NRY neutral pose, STYLE_CFG, idleScript
│ ├── canvas-elements.config.ts # SVG_CATEGORIES, IMAGE_CATEGORIES, pinned items
│ ├── canvas.utils.ts # drawRoundedRect, calculateScaledPadding, applyCanvasBackground,
│ │ # getAspectRatioStyle/Number/MaxWidth, calculateSmoothZoom
@@ -238,7 +231,7 @@ openvidshot/
│ ├── mockup-previews.tsx # React preview components (None/Macos/Brave/Chrome/...)
│ ├── perspective3d.ts # Three.js offscreen WebGL renderer (singleton)
│ ├── photo-providers.ts # Unsplash/Pexels/Pixabay config
-│ ├── template-registry.ts # TEMPLATES: soloVideoTemplate + phoneTemplate
+│ ├── template-registry.ts # ELIMINADO — los motion templates se consolidaron en MockupMenu
│ ├── thumbnail-cache.ts # Video thumbnails persistence
│ ├── video-cache-utils.ts # Helpers
│ ├── image-projects-cache.ts # IndexedDB wrapper para ImageProject (modo photo)
@@ -267,7 +260,7 @@ openvidshot/
│ ├── layers.types.ts # LayersPanelProps, ContextMenuProps
│ ├── mockup.types.ts # MockupConfig (darkMode/frameColor/url/headerScale/...),
│ │ # MockupFeatures, MockupCategory, DEFAULT_MOCKUP_CONFIG
-│ ├── motion.types.ts # MotionTemplate, ScriptFn, AnimMode, MotionStyle, AV
+│ ├── motion.types.ts # ELIMINADO — la lógica de motion se consolidó en MockupMenu/Mockup3dContext
│ ├── photo.types.ts # Preview3DConfig, ImageMaskConfig, PREVIEW_CONFIGS,
│ │ # PREVIEW_TO_PHONE_OFFSET (front/top-left-angle/...)
│ ├── player-control.types.ts # PlayerControlsProps, MIN_ZOOM, MAX_ZOOM, ZOOM_STEP
@@ -295,7 +288,7 @@ openvidshot/
│ │ ├── mockups/ (bg-browser, bg-ide, bg-mobile)
│ │ ├── pages/ (hero, demos, login, qr, posters, openvid)
│ │ └── scroll/ (logos sponsors/decoradores)
-│ ├── models/ # glTF/GLB: iphone-15-pro-max.glb, samsung-galaxy-s25-ultra.glb, phone-gltf.json
+│ ├── models/ # glTF/GLB: iphone-15-pro-max.glb, samsung-galaxy-s25-ultra.glb, apple_iphone_13_pro_max.glb, phone-gltf.json
│ ├── svg/ # logo, mockups, cursores, openvid
│ ├── videos/ # Previews de features (audio, mockup, zoom, ...)
│ ├── elements/images/ # assets, overlays, stickers
@@ -327,32 +320,34 @@ openvidshot/
| Componente | Rol |
|---|---|
-| `VideoCanvas.tsx` (~2400 líneas) | **Canvas principal**. Maneja `<video>` + `<canvas>` de export + `CanvasElementsLayer` + `MockupWrapper` + `Phone3DViewer` (dynamic, ssr:false). Expone `VideoCanvasHandle` (getExportCanvas/drawFrame/getPreviewContainer/clearAllSelection/restoreSelectionState) vía `forwardRef`. Lee `MotionContext` para phone overlay. Implementa `drawFrame` que renderiza a canvas con zoom 3D, mockup frame, video mask, canvas elements, camera overlay, motion phone bezel. Drag/rotate handles para video transform. |
+| `VideoCanvas.tsx` (~2400 líneas) | **Canvas principal**. Maneja `<video>` + `<canvas>` de export + `CanvasElementsLayer` + `MockupWrapper` + `Phone3DViewer` (dynamic, ssr:false). Expone `VideoCanvasHandle` (getExportCanvas/drawFrame/getPreviewContainer/clearAllSelection/restoreSelectionState) vía `forwardRef`. Lee `Mockup3dContext` para phone overlay. Implementa `drawFrame` que renderiza a canvas con zoom 3D, mockup frame, video mask, canvas elements, camera overlay, motion phone bezel. Drag/rotate handles para video transform. Pasa `cropArea` a los 3 viewers 3D para sincronizar el crop con el `ImageCropperModal`. |
| `CanvasElementsLayer.tsx` | Capa de elementos (shapes, text, SVG, imágenes) sobre el canvas; inline text editor Figma-style. |
| `Timeline.tsx` | Timeline con trim, video clips, zoom fragments, audio tracks. Pan via framer-motion, ghosts en drag. |
| `PlayerControls.tsx` | Transport: play/pause, skip ±5s, aspect ratio, crop, zoom level, fullscreen, video mask editor. |
| `EditorTopBar.tsx` | Logo, undo/redo, export dropdown (video/image), user menu, alert de export error. |
-| `ToolsSidebar.tsx` | Sidebar vertical con tools: screenshot, mockup, motion, zoom, audio, videos, camera, cursor, elements, history. |
-| `MobileToolsMenu.tsx` | Menú de tools en mobile (Dialog bottom sheet). |
+| `ToolsSidebar.tsx` | Sidebar vertical con tools: screenshot, mockup, zoom, audio, videos, camera, cursor, elements, history. (Motion tool removido/consolidado en `MockupMenu`.) |
+| `MobileToolsMenu.tsx` | Menú de tools en mobile (Dialog bottom sheet). Consume `activeTool` del editor (sincronizado con `?m=` via `useActiveTool`). |
| `MobileControlPanel.tsx` | ControlPanel en mobile via Dialog bottom sheet. |
-| `ControlPanel.tsx` | Panel reactivo principal (lazy-loaded, muchos sub-skeletons). Cambia contenido según `activeTool`. |
+| `ControlPanel.tsx` | Panel reactivo principal (lazy-loaded, muchos sub-skeletons). Cambia contenido según `activeTool`. El bloque `motion` está comentado — su lógica se movió a `MockupMenu`. |
| `LabelSidebar.tsx` | Etiquetas laterales (Video/Zoom/Audio) en el timeline. |
-| `MockupMenu.tsx` + `mockups/*` | Selector de mockups por categoría + renderers. |
-| `MotionMenu.tsx` + `ImageMotionMenu.tsx` + `templates-motion/Phone.tsx` | Plantillas motion (phone) para video e image mode. |
+| `MockupMenu.tsx` + `mockups/*` | **Consolida** device picker (phone/iphone/iphone-13-pro-max/samsung/laptop), presets thumbnails (front/top-left/etc), popup Custom (scale/rotX/Y/Z/translateY/perspective), crop sync. Lee `Mockup3dContext` y `useActiveTool`. Lazy-loaded con `MockupMenuSkeleton`. |
+| `MotionMenu.tsx` | Casi vacío (placeholder). `ImageMotionMenu.tsx` eliminado. Toda la lógica se movió a `MockupMenu`. |
| `CameraMenu.tsx` | Configuración de camera overlay (shape, corner, size, mirror). |
-| `Phone3DViewer.tsx` (~836 líneas) | Three.js viewer para el phone overlay con GSAP master timeline. |
+| `Phone3DViewer.tsx` | **Vanilla Three.js + OrbitControls + RoomEnvironment**. Carga GLTF (`/models/iphone-15-pro-max.glb`, `/models/samsung-galaxy-s25-ultra.glb`, etc) según `modelUrl`. Inyecta imagen del usuario en el screen plane vía `createCoverScreenCanvas` con `applyCropToImage` + `imageMaskConfig`. Soporta `onRotationChange` desde el `end` de OrbitControls. Maneja `webglcontextlost`/`webglcontextrestored`. |
+| `IPhone13ProMax3DViewer.tsx` | **Vanilla Three.js** para el iPhone 13 Pro Max. Carga `/models/apple_iphone_13_pro_max.glb`. Inyecta la imagen directamente en `Body_Wallpaper_0` (los UVs del mesh están listos, no requiere plane overlay). Mismos OrbitControls + RoomEnvironment + manejo de context lost. |
+| `Laptop3DViewer.tsx` | **Vanilla Three.js** con su propio sistema de drag (NO usa OrbitControls) + inertia/damping via RAF loop. Carga `/models/mac-book.glb`. Pantalla customizable con `screenMaterial`. `lid` rotación animada por `openingProgress`. **Viewer de referencia** — copiar este patrón al crear viewers nuevos. |
| `FloatingCameraPreview.tsx` | Preview flotante arrastrable de la cámara (sidebar). |
| `ZoomFragmentEditor.tsx` / `ZoomFragmentTrackItem.tsx` / `ZoomGlobalConfig.tsx` | Editor de focus point + track item + lista global. |
| `AudioMenu.tsx` / `AudioFragmentTrackItem.tsx` / `AudioTrimModal.tsx` | Multi-track de audio (max 5). |
| `VideoClipTrackItem.tsx` / `VideoCropperModal.tsx` / `VideosMenu.tsx` | Clips de video (multi-clip) + cropper + library. |
-| `ImageCropperModal.tsx` / `ImageMaskEditor.tsx` / `GetMediaMaskStyles.tsx` | Crop + mask + helpers. |
+| `ImageCropperModal.tsx` / `ImageMaskEditor.tsx` / `GetMediaMaskStyles.tsx` | Crop + mask + helpers. `cropArea` se pasa a `VideoCanvas` y luego a los 3 viewers 3D. |
| `ElementsMenu.tsx` (3 tabs: text/elements/uploads) | Shapes, SVG, imágenes, texto. |
| `CursorMenu.tsx` | Configuración del cursor (style, color, size, click effect). |
| `LayersPanel.tsx` (~927 líneas) | Panel de capas con drag-reorder, lock, hide, group/ungroup, multi-select. |
| `HistoryMenu.tsx` | Lista de proyectos de imagen (modo photo). |
| `ContextMenu.tsx` | Menú contextual de las capas (bring to front, send to back, group, delete). |
| `EditorHoverTooltip.tsx` | Tooltip on-canvas con shortcuts (Ctrl+Scroll zoom, Ctrl+V paste). |
-| `PhotoEditorPlaceholder.tsx` | Placeholder del editor de foto (debajo del canvas en photo mode). |
+| `PhotoEditorPlaceholder.tsx` | Placeholder del editor de foto (debajo del canvas en photo mode). Usa `useMockup3dContext` y contiene el `ImageMaskEditor` + el popup Custom del `MockupMenu`. |
| `PlaceholderEditor.tsx` | Placeholder inicial antes de subir archivo. |
| `Skeleton.tsx` | Skeletons de carga para cada menu. |
| `CanvasElementsLayer.tsx` | Capa DOM de elementos con text editor inline. |
@@ -363,13 +358,14 @@ El componente `Editor` raíz coordina todo el estado y los hooks del editor:
**Estados principales** (todos como `useState`):
- Editor mode: `useEditorMode` lee `?mode=` de URL
+- Active tool: `useActiveTool` lee `?m=<tool>` de URL (deep links, mobile share)
- Auth: `useAuth`
- Undo/Redo: `useUndoRedo<EditorState>` (centralizado, sincroniza con `editorState` en `useEffect`)
- Image state: `imageUrl`, `imageRef`, `imageExportProgress`
- Capture: `useScreenCapture`
- Image projects: `useImageProjects` (IndexedDB)
- 3D preview: `imageTransform`, `apply3DToBackground`
-- **UI state**: `activeTool`, `backgroundTab`, `selectedWallpaper`, `backgroundBlur`, `padding`, `roundedCorners`, `shadows`, `isControlPanelOpen`
+- **UI state**: `activeTool` (sincronizado con URL via `useActiveTool`), `backgroundTab`, `selectedWallpaper`, `backgroundBlur`, `padding`, `roundedCorners`, `shadows`, `isControlPanelOpen`
- **Video transform**: `videoTransform` (rotation, translateX, translateY)
- **Uploaded images**: array + LocalStorage sync
- **Background color/gradient**: `backgroundColorConfig`
@@ -438,7 +434,7 @@ El componente `Editor` raíz coordina todo el estado y los hooks del editor:
### 5.3 Contexts y providers
-- **`MotionContext`** (`app/contexts/MotionContext.tsx`) — state global de motion templates, intensity, style, animMode, image phone X/Y/scale/rotation, device. Hook `useMotionContext`.
+- **`Mockup3dContext`** (`app/contexts/Mockup3dContext.tsx`) — state global del mockup 3D: `imagePhoneActive/X/Y/Scale/RotX/RotY/RotZ/Perspective/Device/PresetId/Opening/Shadow/ShadowColor` + undo/redo (`pushHistory`/`undoMotion`/`redoMotion`/`canUndoMotion`/`canRedoMotion`). Hook `useMockup3dContext()`. Reemplaza al antiguo `MotionContext` (eliminado).
- **`AuthProvider`** (`app/contexts/useAuth.tsx`) — sesión Supabase + user profile.
- **`RecordingProvider`** (`app/contexts/RecordingContext.tsx`) — wrapper de `useScreenRecording` con shortcuts Alt+S/Alt+D.
- **`TooltipProvider`** (`components/ui/tooltip.tsx`) — Radix tooltip con `delayDuration={200}`.
@@ -448,9 +444,9 @@ Orden de providers en `app/[locale]/(editor)/layout.tsx`:
```jsx
<AuthProvider>
<RecordingProvider>
- <MotionProvider>
+ <Mockup3dProvider>
<div>{children}</div>
- </MotionProvider>
+ </Mockup3dProvider>
<RecordingOverlay />
</RecordingProvider>
</AuthProvider>
@@ -460,6 +456,7 @@ Orden de providers en `app/[locale]/(editor)/layout.tsx`:
- **`useUndoRedo<T>(initialState)`** — history stack (past/present/future) con `MAX_HISTORY_SIZE=50`. `setState` con `skipHistory` flag.
- **`useEditorMode`** — lee `?mode=` de URL, expone `isVideoMode`/`isPhotoMode`/`setMode`.
+- **`useActiveTool`** (`hooks/useActiveTool.ts`) — lee `?m=<tool>` de la URL y expone `[activeTool, setActiveTool]`. Usa `useSearchParams` + `useRouter` (Next.js) para que el state se mantenga sincronizado con la URL en AMBAS direcciones. Permite deep links tipo `/es/editor?mode=video&m=mockup` que cargan el menú activo directamente. Hook estilo `useState` para drop-in replacement.
- **`useVideoExport(videoRef, canvasRef)`** — pipeline de export con MediaBunny + FFmpeg.wasm. Maneja cancellation token.
- **`useVideoThumbnails(url, duration, options)`** — genera thumbnails cada 0.1s, calidad "low"/"high".
- **`useImageProjects`** — CRUD de proyectos de imagen en IndexedDB (auto-save 3s).
@@ -524,7 +521,7 @@ pnpm lint / format
- **Idioma por defecto**: `es` (ver `i18n.ts`). Todos los textos visibles usan `useTranslations("namespace")` de `next-intl`.
- **Refs vs State**: el editor usa muchos `useRef` para evitar stale closures en `requestAnimationFrame`, drag handlers, y event listeners globales.
- **i18n keys**: están en `messages/{es,en,ru}.json` — agregar clave en los 3 al añadir un texto nuevo.
-- **Animaciones GSAP**: se registran plugins (`ScrollTrigger` en home, `GLTFLoader` en Phone3DViewer) — limpiar con `gsap.matchMedia()` o `killTweensOf`.
+- **Animaciones GSAP**: se registran plugins (`ScrollTrigger` en home) — limpiar con `gsap.matchMedia()` o `killTweensOf`. Los viewers 3D NO usan GSAP (todo es vanilla Three.js con `OrbitControls` o drag custom).
- **Three.js singleton**: `lib/perspective3d.ts` mantiene un único `WebGLRenderer`/`Scene`/`Camera` reutilizado entre renders; llamar `disposePerspective3D()` en cleanup.
- **Framer Motion**: usado para AnimatePresence (panel open/close, export overlay, hover).
- **Atropos**: solo en `EditorPreview.tsx` (home) para parallax 3D.
@@ -538,11 +535,6 @@ pnpm lint / format
5. Agregar a `BOTTOM_ONLY_RADIUS_MOCKUPS` o `SELF_SHADOWING_MOCKUPS` en `lib/constants.ts` si necesita tratamiento especial de border-radius/shadow.
6. Verificar que `MockupWrapper.tsx` lo importe.
-### Estructura de un motion template nuevo
-1. Definir `MotionTemplate` en `app/components/ui/editor/templates-motion/{name}.tsx` con `script: ScriptFn` (función que devuelve `gsap.core.Timeline`).
-2. Registrar en `lib/template-registry.ts` (descomentar línea correspondiente).
-3. Si tiene panel de edición, exponer `EditorPanel` en el template.
-
### Estructura de un nuevo tool en el sidebar
1. Agregar el tool al union type `Tool` en `types/editor.types.ts`.
2. Agregar la entrada en `ToolsSidebar.tsx` (icono + handler + scroll ref).
diff --git a/components/ui/DetailHeaderMenu.tsx b/components/ui/DetailHeaderMenu.tsx
new file mode 100644
index 0000000..09fcdc3
--- /dev/null
+++ b/components/ui/DetailHeaderMenu.tsx
@@ -0,0 +1,29 @@
+import { Icon } from "@iconify/react";
+
+export function DetailPageHeader({
+ label,
+ icon,
+ onBack,
+}: {
+ label: string;
+ icon: string;
+ onBack: () => void;
+}) {
+ return (
+ <>
+ <button
+ type="button"
+ onClick={onBack}
+ className="flex items-center justify-center size-7 rounded-md hover:bg-white/6 text-white/50 transition-colors"
+ aria-label="Volver al inicio"
+ >
+ <Icon icon="ph:arrow-left-bold" width="13" />
+ </button>
+ <div className="flex items-center gap-1.5 text-white/60">
+ <span className="text-md font-mediumtruncate">
+ {label}
+ </span>
+ </div>
+ </>
+ );
+}
\ No newline at end of file
diff --git a/hooks/useActiveTool.ts b/hooks/useActiveTool.ts
new file mode 100644
index 0000000..4a16666
--- /dev/null
+++ b/hooks/useActiveTool.ts
@@ -0,0 +1,69 @@
+"use client";
+
+/**
+ * useActiveTool
+ *
+ * Sincroniza la herramienta activa del editor (sidebar/ControlPanel) con
+ * el query param `?m=<tool>` de la URL.
+ *
+ * /es/editor?mode=video&m=mockup → mockup menu
+ * /es/editor?mode=photo&m=elements → elements menu
+ *
+ * Usa `useSearchParams` de Next.js + `useRouter` para que el state se
+ * mantenga sincronizado con la URL en AMBAS direcciones:
+ * - Al hacer click en un tool → URL cambia → state se actualiza
+ * (porque useSearchParams es reactivo a router.replace)
+ * - Al navegar a una URL con `?m=X` (pegar URL, back/forward) → el
+ * state lee el valor de la URL en mount/vía re-render.
+ *
+ * El setter usa `router.replace` en lugar de `window.history.replaceState`
+ * para que Next.js se entere del cambio y `useSearchParams` se actualice.
+ */
+
+import { useCallback, useEffect } from "react";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
+import type { Tool } from "@/types/editor.types";
+
+const VALID_TOOLS: ReadonlySet<Tool> = new Set<Tool>([
+ "screenshot",
+ "elements",
+ "audio",
+ "zoom",
+ "mockup",
+ "cursor",
+ "videos",
+ "camera",
+ "history",
+ "motion",
+]);
+
+function parseTool(value: string | null): Tool {
+ if (value && VALID_TOOLS.has(value as Tool)) {
+ return value as Tool;
+ }
+ return "screenshot";
+}
+
+/**
+ * Hook estilo `useState`: retorna [value, setter]. Lee `m` de la URL y
+ * actualiza la URL al cambiar.
+ */
+export function useActiveTool(): [Tool, (next: Tool) => void] {
+ const router = useRouter();
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+
+ // `useSearchParams` es reactivo a router.replace (no a replaceState).
+ // En mount, ya tiene el valor de la URL; no necesita useEffect extra.
+ const tool = parseTool(searchParams.get("m"));
+
+ const setTool = useCallback((next: Tool) => {
+ // Construye los nuevos params preservando todos los existentes
+ // (mode, preset, etc.) y actualizando solo `m`
+ const params = new URLSearchParams(searchParams.toString());
+ params.set("m", next);
+ router.replace(`${pathname}?${params.toString()}`);
+ }, [router, pathname, searchParams]);
+
+ return [tool, setTool];
+}
diff --git a/lib/animation-core.ts b/lib/animation-core.ts
index 0e62d22..58c5cfe 100644
--- a/lib/animation-core.ts
+++ b/lib/animation-core.ts
@@ -1,4 +1,13 @@
-import { MotionStyle, ScriptFn } from "@/types/motion.types";
+// ─── Local types (motion.types.ts fue eliminado al consolidar MockupMenu) ─────
+type MotionStyle = "smooth" | "normal" | "cinematic";
+type ScriptFn = (
+ av: { rx: number; ry: number; tx: number; ty: number; sc: number },
+ intensity: number,
+ duration: number,
+ style: MotionStyle,
+ onUpdate?: () => void
+) => gsap.core.Timeline;
+
import gsap from "gsap";
// ─── Neutral resting position (slight 3-D tilt for depth) ────────────────────
diff --git a/lib/phone3d.utils.ts b/lib/phone3d.utils.ts
index 4db150f..53f4b98 100644
--- a/lib/phone3d.utils.ts
+++ b/lib/phone3d.utils.ts
@@ -216,3 +216,63 @@ export function parseShadowColor(hex: string, opacity: number): string {
const b = parseInt(h.length === 3 ? h[2] + h[2] : h.slice(4, 6), 16);
return `rgba(${r},${g},${b},${opacity.toFixed(3)})`;
}
+
+// ─── Crop helper ─────────────────────────────────────────────────────────────
+// Aplica un crop a una imagen y devuelve un HTMLCanvasElement con la región
+// recortada. El crop está en porcentajes (0-100). Si el crop cubre el 100%
+// o es null/undefined, devuelve la imagen original sin modificar.
+export interface CropAreaLike {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export function applyCropToImage(
+ source: HTMLImageElement | HTMLVideoElement | HTMLCanvasElement,
+ cropArea: CropAreaLike | null | undefined
+): HTMLCanvasElement {
+ let srcW: number, srcH: number;
+ if (source instanceof HTMLImageElement) {
+ srcW = source.naturalWidth || source.width || 1;
+ srcH = source.naturalHeight || source.height || 1;
+ } else if (source instanceof HTMLVideoElement) {
+ srcW = source.videoWidth || 1;
+ srcH = source.videoHeight || 1;
+ } else {
+ srcW = source.width || 1;
+ srcH = source.height || 1;
+ }
+
+ // Si el crop está vacío o cubre el 100%, no hace nada
+ const isFullCrop = !cropArea
+ || (cropArea.x <= 0 && cropArea.y <= 0
+ && cropArea.width >= 100 && cropArea.height >= 100);
+ if (isFullCrop) {
+ const out = document.createElement("canvas");
+ out.width = srcW;
+ out.height = srcH;
+ out.getContext("2d")!.drawImage(source, 0, 0, srcW, srcH);
+ return out;
+ }
+
+ // Calcular región en píxeles. Clamp para no salirnos de la imagen.
+ const x = Math.max(0, Math.min(100, cropArea.x));
+ const y = Math.max(0, Math.min(100, cropArea.y));
+ const width = Math.max(1, Math.min(100 - x, cropArea.width));
+ const height = Math.max(1, Math.min(100 - y, cropArea.height));
+
+ const sx = (x / 100) * srcW;
+ const sy = (y / 100) * srcH;
+ const sw = (width / 100) * srcW;
+ const sh = (height / 100) * srcH;
+
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.round(sw);
+ canvas.height = Math.round(sh);
+ const ctx = canvas.getContext("2d")!;
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(source, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);
+ return canvas;
+}
diff --git a/messages/en.json b/messages/en.json
index c678024..8f1824c 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -550,7 +550,6 @@
"daysAgo": "{days, plural, =1 {1 day ago} other {# days ago}}"
},
"actions": {
- "addToCanvas": "Add to canvas",
"delete": "Delete from history"
}
},
diff --git a/messages/es.json b/messages/es.json
index 01a1def..db2ece5 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -975,7 +975,6 @@
"daysAgo": "{days, plural, =1 {Hace 1 día} other {Hace # días}}"
},
"actions": {
- "addToCanvas": "Añadir al canvas",
"delete": "Eliminar del historial"
}
},
diff --git a/messages/ru.json b/messages/ru.json
index 5bd1c77..7657535 100644
--- a/messages/ru.json
+++ b/messages/ru.json
@@ -518,7 +518,6 @@
"daysAgo": "{days, plural, one {# день назад} few {# дня назад} many {# дней назад} other {# дней назад}}"
},
"actions": {
- "addToCanvas": "Добавить на холст",
"delete": "Удалить из истории"
}
},
diff --git a/types/mockup.types.ts b/types/mockup.types.ts
index 5fac8e7..6d2a887 100644
--- a/types/mockup.types.ts
+++ b/types/mockup.types.ts
@@ -1,4 +1,7 @@
export type MockupCategory = "browser" | "mobile" | "ide" | "all";
+export const FRAME_COLORS_DARK = ["#1e1e1e", "#181818", "#252526", "#0d1117", "#1a1b26", "#282a36"];
+export const FRAME_COLORS_LIGHT = ["#ffffff", "#f3f3f3", "#f6f8fa", "#fafafa", "#e8e8e8"];
+export const FRAME_COLORS = [...FRAME_COLORS_DARK, ...FRAME_COLORS_LIGHT];
// Available configurations for each mockup
export interface MockupFeatures {
@@ -76,3 +79,57 @@ export function getMockupDefaultConfig(mockup: Mockup | undefined): MockupConfig
...(mockup?.defaultConfig ?? {}),
};
}
+
+export type ImageDeviceId = (typeof IMAGE_DEVICE_TEMPLATES)[number]["id"];
+
+// ─── PositionPad ─────────────────────────────────────────────────────────────
+
+export const PAD_H = 130;
+export const X_HALF = 500;
+export const Y_HALF = 500;
+export const HANDLE_R = 9;
+
+// ─── Types ────────────────────────────────────────────────────────────────────
+
+export type MenuPage = "home" | "detail-2d" | "detail-3d";
+
+// ─── 3D Device definitions ────────────────────────────────────────────────────
+
+export const IMAGE_DEVICE_TEMPLATES = [
+ {
+ id: "iphone-13-pro-max",
+ title: "iPhone 13 Pro",
+ accentColor: "#7C7C85",
+ icon: "simple-icons:apple",
+ modelUrl: "/models/apple_iphone_13_pro_max.glb",
+ },
+ {
+ id: "phone",
+ title: "Phone",
+ accentColor: "#00A3FF",
+ icon: "ph:device-mobile-bold",
+ modelUrl: "/models/phone-gltf.glb",
+ },
+ {
+ id: "iphone",
+ title: "iPhone 15 Pro",
+ accentColor: "#A8A8B0",
+ icon: "simple-icons:apple",
+ modelUrl: "/models/iphone-15-pro-max.glb",
+ },
+ {
+ id: "samsung",
+ title: "Samsung S25",
+ accentColor: "#1428A0",
+ icon: "simple-icons:samsung",
+ modelUrl: "/models/samsung-galaxy-s25-ultra.glb",
+ },
+ {
+ id: "laptop",
+ title: "macOS Laptop",
+ accentColor: "#CECFD3",
+ icon: "ph:laptop-bold",
+ modelUrl: "/models/mac-book.glb",
+ },
+] as const;
+
diff --git a/types/motion.types.ts b/types/motion.types.ts
index 6a75732..78c6519 100644
--- a/types/motion.types.ts
+++ b/types/motion.types.ts
@@ -1,10 +1,3 @@
-// ─── Shared motion types ──────────────────────────────────────────────────────
-
-export type MotionStyle = "smooth" | "normal" | "cinematic";
-
-/** Controls which finite animations play during a video clip */
-export type AnimMode = "entry" | "exit" | "entry+exit" | "none" | "static";
-
/** Animation vector — GSAP tweens this object, Three.js reads it */
export interface AV {
rx: number;
@@ -14,12 +7,15 @@ export interface AV {
sc: number;
}
+// ─── Tipos restaurados (motion.types.ts fue modificado pero aún los usa CameraVariant) ─────
+export type MotionStyle = "smooth" | "normal" | "cinematic";
+export type AnimMode = "entry" | "exit" | "entry+exit" | "none" | "static";
+
/** A cinematic script function — returns a repeating GSAP timeline */
export type ScriptFn = (
av: AV,
intensity: number, // 0–1
durMs: number,
- style: MotionStyle,
onUpdate: () => void,
) => gsap.core.Timeline;