Skip to content

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

feat: motion menu update

CristianOlivera151c36744a7b4
diff --git a/app/components/ui/SidebarTool.tsx b/app/components/ui/SidebarTool.tsx
index 56ef698..e47e307 100644
--- a/app/components/ui/SidebarTool.tsx
+++ b/app/components/ui/SidebarTool.tsx
@@ -20,13 +20,14 @@ interface SidebarToolProps {
isActive?: boolean;
onClick?: () => void;
badge?: string;
+ badgeStyle?: "default" | "premium";
badgeCount?: number;
disabled?: boolean;
popover?: PopoverConfig;
}
export const SidebarTool = forwardRef<HTMLButtonElement, SidebarToolProps>(
- ({ icon, label, isActive, onClick, badge, badgeCount, disabled, popover }, ref) => {
+ ({ icon, label, isActive, onClick, badge, badgeStyle, badgeCount, disabled, popover }, ref) => {
const [isOpen, setIsOpen] = useState(false);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
@@ -61,8 +62,18 @@ export const SidebarTool = forwardRef<HTMLButtonElement, SidebarToolProps>(
</div>
)}
{badge && (
- <div className="absolute -top-1 -right-0.5 z-10 px-1.5 py-0.5 bg-linear-to-r from-gray-500 to-gray-500 rounded-full border border-white/20 shadow-lg pointer-events-none">
- <span className="text-[8px] font-bold text-white tracking-widest uppercase block drop-shadow-sm leading-none">
+ <div
+ className={`absolute -top-1 -right-0.5 z-10 pointer-events-none select-none flex items-center justify-center min-w-[42px] ${badgeStyle === "premium"
+ ? "px-1 py-[3px] rounded-full border border-rose-400/40 shadow-[0_0_20px_rgba(244,63,94,0.3)] bg-gradient-to-r from-violet-600 via-pink-600 to-amber-500"
+ : "px-1.5 py-0.5 rounded-full border border-white/20 shadow-lg bg-linear-to-r from-gray-500 to-gray-500"
+ }`}
+ >
+ <span
+ className={`block font-bold uppercase leading-none text-center ${badgeStyle === "premium"
+ ? "text-[8.5px] font-black text-white tracking-[0.2em] pl-[0.2em] drop-shadow-[0_1.5px_2px_rgba(0,0,0,0.6)]"
+ : "text-[8px] text-white tracking-[0.18em] pl-[0.18em] drop-shadow-sm"
+ }`}
+ >
{badge}
</span>
</div>
diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsx
index 63910a5..11befa4 100644
--- a/app/components/ui/editor/ControlPanel.tsx
+++ b/app/components/ui/editor/ControlPanel.tsx
@@ -284,7 +284,14 @@ export function ControlPanel({
{activeTool === "motion" && (
<Suspense fallback={<MockupMenuSkeleton />}>
- {mediaType === "image" ? <ImageMotionMenu /> : <MotionMenu />}
+ {mediaType === "image"
+ ? <ImageMotionMenu
+ backgroundColorCss={undefined}
+ backgroundTab={backgroundTab}
+ selectedWallpaper={selectedWallpaper}
+ selectedImageUrl={selectedImageUrl}
+ />
+ : <MotionMenu />}
</Suspense>
)}
diff --git a/app/components/ui/editor/EditorTopBar.tsx b/app/components/ui/editor/EditorTopBar.tsx
index 3de6913..8f0c3db 100644
--- a/app/components/ui/editor/EditorTopBar.tsx
+++ b/app/components/ui/editor/EditorTopBar.tsx
@@ -5,10 +5,11 @@ import { ExportDropdown } from "../ExportDropdown";
import { ExportImageDropdown } from "../ExportImageDropdown";
import type { ExportQuality, ExportProgress } from "@/types";
import type { EditorMode } from "@/types/editor-mode.types";
+import type { Tool } from "@/types/editor.types";
import type { ImageExportFormat } from "@/types/image-project.types";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { useEffect, useState } from "react";
-import { useAuth } from "@/hooks/useAuth";
+import { useAuth } from "@/app/contexts/useAuth";
import { useTranslations } from "next-intl";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import Image from "next/image";
@@ -35,6 +36,12 @@ interface EditorTopBarProps {
imageExportProgress?: ImageExportProgress;
canvasWidth?: number;
canvasHeight?: number;
+ // Motion-aware undo/redo: when activeTool is "motion", these take over.
+ activeTool?: Tool;
+ onUndoMotion?: () => boolean;
+ onRedoMotion?: () => boolean;
+ canUndoMotion?: boolean;
+ canRedoMotion?: boolean;
}
export function EditorTopBar({
@@ -50,8 +57,19 @@ export function EditorTopBar({
imageExportProgress,
canvasWidth = 1920,
canvasHeight = 1080,
+ activeTool,
+ onUndoMotion,
+ onRedoMotion,
+ canUndoMotion = false,
+ canRedoMotion = false,
}: EditorTopBarProps) {
const isPhotoMode = editorMode === "photo";
+ const isMotionActive = activeTool === "motion";
+ // Motion tool is the active one: route undo/redo through motion.
+ const effectiveOnUndo = isMotionActive ? onUndoMotion : onUndo;
+ const effectiveOnRedo = isMotionActive ? onRedoMotion : onRedo;
+ const effectiveCanUndo = isMotionActive ? canUndoMotion : canUndo;
+ const effectiveCanRedo = isMotionActive ? canRedoMotion : canRedo;
const t = useTranslations("editor.topBar");
const [showAlert, setShowAlert] = useState(false);
const [prevStatus, setPrevStatus] = useState<string>(exportProgress.status);
@@ -134,21 +152,33 @@ export function EditorTopBar({
<div className="flex items-center ml-auto">
<div className="flex items-center gap-2 border-r border-white/10 pr-3">
- <TooltipAction label={canUndo ? t("history.undo") : t("history.noUndo")}>
+ <TooltipAction label={effectiveCanUndo ? t("history.undo") : t("history.noUndo")}>
<button
- onClick={onUndo}
- disabled={!canUndo}
- className={`transition-colors ${canUndo ? "hover:text-white text-white/70" : "opacity-30 cursor-not-allowed text-white/30"
+ onClick={() => {
+ if (isMotionActive) {
+ onUndoMotion?.();
+ } else {
+ onUndo?.();
+ }
+ }}
+ disabled={!effectiveCanUndo}
+ className={`transition-colors ${effectiveCanUndo ? "hover:text-white text-white/70" : "opacity-30 cursor-not-allowed text-white/30"
}`}
>
<Icon icon="mdi:undo" width="20" />
</button>
</TooltipAction>
- <TooltipAction label={canRedo ? t("history.redo") : t("history.noRedo")}>
+ <TooltipAction label={effectiveCanRedo ? t("history.redo") : t("history.noRedo")}>
<button
- onClick={onRedo}
- disabled={!canRedo}
- className={`transition-colors ${canRedo ? "hover:text-white text-white/70" : "opacity-30 cursor-not-allowed text-white/60"
+ onClick={() => {
+ if (isMotionActive) {
+ onRedoMotion?.();
+ } else {
+ onRedo?.();
+ }
+ }}
+ disabled={!effectiveCanRedo}
+ className={`transition-colors ${effectiveCanRedo ? "hover:text-white text-white/70" : "opacity-30 cursor-not-allowed text-white/60"
}`}
>
<Icon icon="mdi:redo" width="20" />
diff --git a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
new file mode 100644
index 0000000..9fd97e3
--- /dev/null
+++ b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
@@ -0,0 +1,406 @@
+"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 {
+ createCoverScreenCanvas,
+ type ImageMaskConfigLike,
+} from "@/lib/phone3d.utils";
+
+export interface IPhone13ProMax3DApi {
+ 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: 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 ─────────────────────────────────────────────────────
+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;
+}
+
+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;
+}
+
+// ─── Escena 3D ──────────────────────────────────────────────────────────────
+function ModelScene({
+ imageUrl,
+ imageMaskConfig,
+ initialRotationX,
+ initialRotationY,
+ onRotationChange,
+ rootRef,
+ cameraRef,
+ zoom,
+ onApi,
+}: {
+ imageUrl: string | null;
+ imageMaskConfig: ImageMaskConfigLike | null;
+ initialRotationX: number;
+ initialRotationY: 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;
+}) {
+ const gltf = useGLTF("/models/apple_iphone_13_pro_max.glb") as unknown as {
+ nodes: GLTFNodes;
+ materials: GLTFMaterials;
+ };
+ const { nodes, materials } = gltf;
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const orbitRef = useRef<any>(null);
+ const lastLoadedImageUrlRef = useRef<string | null>(null);
+ const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | null>(null);
+
+ useEffect(() => {
+ const api: IPhone13ProMax3DApi = {
+ renderAt: (w, h) => { void w; void h; },
+ };
+ onApi?.(api);
+ return () => onApi?.(null);
+ }, [onApi]);
+
+ useEffect(() => {
+ if (materials.Wallpaper) {
+ wallpaperMatRef.current = materials.Wallpaper as THREE.MeshStandardMaterial;
+ }
+ }, [materials.Wallpaper]);
+
+ useEffect(() => {
+ const mat = wallpaperMatRef.current;
+ if (!mat) return;
+
+ if (!imageUrl) {
+ if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }
+ lastLoadedImageUrlRef.current = null;
+ return;
+ }
+ if (lastLoadedImageUrlRef.current === imageUrl) 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 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;
+ mat.map = tex;
+ mat.needsUpdate = true;
+ lastLoadedImageUrlRef.current = imageUrl;
+ };
+ img.src = imageUrl;
+ }, [imageUrl, imageMaskConfig]);
+
+ useEffect(() => {
+ // Microtask delay para asegurar que OrbitControls ya está montado
+ 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);
+ }, []);
+
+ 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>
+ </>
+ );
+}
+
+// ─── Componente público ──────────────────────────────────────────────────────
+export function IPhone13ProMax3DViewer({
+ imageUrl = null,
+ imageMaskConfig = null,
+ initialRotationX = -58.23,
+ initialRotationY = -29.82,
+ initialRotationZ: _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 parseShadowColor = (hex: string, opacity: number): string => {
+ const h = hex.replace("#", "");
+ const r = parseInt(h.length === 3 ? h[0] + h[0] : h.slice(0, 2), 16);
+ const g = parseInt(h.length === 3 ? h[1] + h[1] : h.slice(2, 4), 16);
+ const b = parseInt(h.length === 3 ? h[2] + h[2] : h.slice(4, 6), 16);
+ return `rgba(${r},${g},${b},${opacity.toFixed(3)})`;
+ };
+ const shadowRgba = shadowColor.startsWith("#")
+ ? parseShadowColor(shadowColor, computedOpacity)
+ : shadowColor;
+ const hasShadow = t > 0.01;
+
+ return (
+ <div
+ style={{
+ display: "inline-block",
+ transformOrigin: "top center",
+ transform: `scale(${scale})`,
+ width: 480,
+ height: 1000 + (hasShadow ? computedBlur * 0.8 : 0),
+
+ }}
+ >
+ <div style={{ position: "relative", width: 480, height: 1000 }}>
+ {/* Sombra de suelo: elipse difusa con curva t^2 */}
+ {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 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).
+ */}
+ <div
+ style={{
+ position: "absolute",
+ inset: "-200px",
+ 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",
+ pointerEvents: "auto",
+ }}
+ onPointerDown={() => setGrabbing(true)}
+ onPointerUp={() => setGrabbing(false)}
+ onPointerLeave={() => setGrabbing(false)}
+ >
+ <Canvas
+ style={{ width: "100%", height: "100%", overflow: "visible" }}
+ gl={{
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ powerPreference: "high-performance",
+ }}
+ dpr={4}
+ 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}
+ onRotationChange={onRotationChange}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ zoom={zoom}
+ onApi={onApi}
+ />
+ </Canvas>
+ </div>
+ </div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/ImageMaskEditor.tsx b/app/components/ui/editor/ImageMaskEditor.tsx
index b31435e..29d0d72 100644
--- a/app/components/ui/editor/ImageMaskEditor.tsx
+++ b/app/components/ui/editor/ImageMaskEditor.tsx
@@ -175,7 +175,7 @@ export function ImageMaskEditor({
</div>
{active && (
- <div className="absolute top-2 right-2 z-30 size-4 rounded-full bg-gradient-primary flex items-center justify-center shadow-xl">
+ <div className="absolute top-2 right-2 z-30 size-4 rounded-full bg-cyan-500 flex items-center justify-center shadow-xl">
<Icon icon="mdi:check" width="10" className="text-white" />
</div>
)}
diff --git a/app/components/ui/editor/ImageMotionMenu.tsx b/app/components/ui/editor/ImageMotionMenu.tsx
index afe3ecc..edbfb1a 100644
--- a/app/components/ui/editor/ImageMotionMenu.tsx
+++ b/app/components/ui/editor/ImageMotionMenu.tsx
@@ -4,6 +4,7 @@ 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;
@@ -11,11 +12,14 @@ const Y_HALF = 500;
const HANDLE_R = 9;
function PositionPad({
- x, y, onChangeX, onChangeY,
+ 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);
@@ -31,7 +35,7 @@ function PositionPad({
const fromEvent = (e: React.PointerEvent) => {
if (!padRef.current) return;
-
+
const rect = padRef.current.getBoundingClientRect();
const currentWidth = rect.width;
@@ -42,32 +46,57 @@ function PositionPad({
onChangeY(Math.round((ry / PAD_H) * Y_HALF * 2 - Y_HALF));
};
- const handleReset = (e: React.PointerEvent) => {
- e.stopPropagation();
- onChangeX(0);
- onChangeY(0);
- };
+ // 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 bg-zinc-950/80 border border-zinc-800/50 shadow-[inset_0_2px_8px_rgba(0,0,0,0.8)]"
+ 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;
+ 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%' }} />
@@ -75,32 +104,21 @@ function PositionPad({
<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" : "cursor-grab"
- }`}
+ 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 * 2,
- height: HANDLE_R * 2,
+ width: HANDLE_R * 3,
+ height: HANDLE_R * 3,
left: `calc(${pctX * 100}% - ${HANDLE_R}px)`,
top: hy - HANDLE_R,
}}
>
- <div className="w-1.5 h-1.5 bg-zinc-950 rounded-full" />
</div>
- <button
- onPointerDown={handleReset}
- className="absolute top-1.5 left-1.5 z-10 opacity-0 group-hover:opacity-100 transition-all duration-200 text-[9px] font-medium text-zinc-400 hover:text-white flex items-center gap-1 bg-zinc-900/95 hover:bg-zinc-800 px-2 py-0.5 rounded-md border border-white/5 shadow-lg active:scale-95 cursor-pointer"
- title="Restablecer posición al centro"
- >
- <Icon icon="lucide:rotate-ccw" className="w-2.5 h-2.5 text-zinc-500 group-hover:text-white" />
- <span>Reset</span>
- </button>
</div>
</div>
);
}
-
// ─── Device template definition ───────────────────────────────────────────────
const IMAGE_DEVICE_TEMPLATES = [
{
@@ -109,12 +127,19 @@ const IMAGE_DEVICE_TEMPLATES = [
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: undefined as string | undefined,
+ modelUrl: "/models/phone-gltf.glb",
},
{
id: "iphone",
@@ -130,12 +155,41 @@ const IMAGE_DEVICE_TEMPLATES = [
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() {
+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,
@@ -143,43 +197,64 @@ export function ImageMotionMenu() {
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 {
- setImagePhoneDevice(id);
+ 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);
- setImagePhoneX(0);
- setImagePhoneY(0);
- setImagePhoneScale(1);
- setImagePhoneRotX(0);
- setImagePhoneRotY(0);
}
};
const handleReset = () => {
setImagePhoneX(0);
setImagePhoneY(0);
- setImagePhoneScale(1);
+ 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/90 font-semibold text-sm tracking-wide">
- <Icon icon="ph:device-mobile-bold" width="16" className="text-blue-400" />
+ <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>
- <span className="text-[9px] uppercase tracking-widest text-white/25 font-bold bg-white/5 px-2 py-0.5 rounded-full border border-white/6">
- Imagen
- </span>
</div>
{/* Device template grid */}
@@ -226,12 +301,6 @@ export function ImageMotionMenu() {
<h3 className={`truncate text-xs font-semibold ${isActive ? "text-white" : "text-white/60"}`}>
{tpl.title}
</h3>
- {isActive && (
- <div
- className="size-1.5 rounded-full flex-shrink-0"
- style={{ background: tpl.accentColor }}
- />
- )}
</div>
</button>
@@ -267,38 +336,48 @@ export function ImageMotionMenu() {
label="Escala"
value={Math.round(imagePhoneScale * 100)}
min={30}
- max={200}
+ max={300}
step={1}
- onChange={(v) => setImagePhoneScale(v / 100)}
+ 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-[10px] text-white/40 font-medium">Posición</span>
+ <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 className="rounded-xl bg-white/3 border border-white/5 px-3 py-2.5 flex flex-col gap-1.5">
- <div className="flex items-center gap-1.5 text-white/50">
- <Icon icon="ph:cursor-click" width="11" />
- <span className="text-[10px] font-medium">Controles del canvas</span>
- </div>
- <ul className="space-y-1">
- <li className="flex items-start gap-1.5 text-[10px] text-white/35">
- <span className="text-white/25 mt-px">↔</span>
- <span>Arrastra el teléfono para girarlo en 3D</span>
- </li>
- <li className="flex items-start gap-1.5 text-[10px] text-white/35">
- <span className="text-white/25 mt-px">⊕</span>
- <span>Ctrl + scroll para hacer zoom</span>
- </li>
- </ul>
- </div>
</div>
)}
</div>
diff --git a/app/components/ui/editor/Laptop3DViewer.tsx b/app/components/ui/editor/Laptop3DViewer.tsx
new file mode 100644
index 0000000..2b87a99
--- /dev/null
+++ b/app/components/ui/editor/Laptop3DViewer.tsx
@@ -0,0 +1,582 @@
+"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,
+ type ImageMaskConfigLike,
+} from "@/lib/phone3d.utils";
+
+// ─── Dimensiones ──────────────────────────────────────────────────────────────
+const LAPTOP_W = 1500;
+const LAPTOP_H = 1035;
+const RENDER_MULTIPLIER = 2;
+const RENDER_W = LAPTOP_W * RENDER_MULTIPLIER;
+const RENDER_H = LAPTOP_H * RENDER_MULTIPLIER;
+
+const CAM_FOV = 40;
+const CAM_RADIUS = 75;
+
+const screenSize: [number, number] = [29.4, 20];
+const LID_CLOSED_X = Math.PI * 0.5;
+const LID_OPEN_X = -0.2 * Math.PI;
+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+
+const DAMPING_FACTOR = 0.08;
+
+const THETA_SPEED = (2 * Math.PI) / LAPTOP_W / 7;
+const PHI_SPEED = Math.PI / LAPTOP_H / 7;
+
+export interface Laptop3DApi {
+ renderAt: (width: number, height: number) => void;
+}
+
+interface Props {
+ imageUrl?: string | null;
+ openingProgress?: number;
+ imageMaskConfig?: ImageMaskConfigLike | null;
+ initialRotationX?: number;
+ initialRotationY?: number;
+ initialRotationZ?: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ onMount?: (canvas: HTMLCanvasElement) => void;
+ onApi?: (api: Laptop3DApi | null) => void;
+ scale?: number;
+ zoom?: number;
+ shadowIntensity?: number;
+ shadowColor?: string;
+}
+
+// ─── GLB cache ────────────────────────────────────────────────────────────────
+let gltfCachePromise: Promise<THREE.Group> | null = null;
+function loadLaptopGltf(): Promise<THREE.Group> {
+ if (!gltfCachePromise) {
+ gltfCachePromise = new Promise<THREE.Group>((resolve, reject) =>
+ new GLTFLoader().load(
+ "/models/mac-book.glb",
+ (gltf) => resolve(gltf.scene as THREE.Group),
+ undefined,
+ reject
+ )
+ );
+ }
+ return gltfCachePromise;
+}
+
+// ─── Angle helpers ────────────────────────────────────────────────────────────
+function anglesFromInitial(rx: number, ry: number, radius: number): THREE.Vector3 {
+ const DEG = Math.PI / 180;
+ const phi = Math.PI / 2 - rx * DEG;
+ const theta = ry * DEG;
+ return new THREE.Vector3().setFromSphericalCoords(radius, phi, theta);
+}
+
+function rxRyFromCamera(camPos: THREE.Vector3): { rx: number; ry: number } {
+ const sph = new THREE.Spherical().setFromVector3(camPos);
+ const rx = (Math.PI / 2 - sph.phi) * (180 / Math.PI);
+ const ry = sph.theta * (180 / Math.PI);
+ return { rx, ry };
+}
+
+// ─── Shadow color helper ──────────────────────────────────────────────────────
+function parseShadowColor(hex: string, opacity: number): string {
+ const h = hex.replace("#", "");
+ const r = parseInt(h.length === 3 ? h[0] + h[0] : h.slice(0, 2), 16);
+ const g = parseInt(h.length === 3 ? h[1] + h[1] : h.slice(2, 4), 16);
+ const b = parseInt(h.length === 3 ? h[2] + h[2] : h.slice(4, 6), 16);
+ return `rgba(${r},${g},${b},${opacity.toFixed(3)})`;
+}
+
+export function Laptop3DViewer({
+ imageUrl = null,
+ openingProgress = 1,
+ imageMaskConfig = null,
+ initialRotationX = 0,
+ initialRotationY = 0,
+ initialRotationZ = 0,
+ onRotationChange,
+ onMount,
+ onApi,
+ scale = 1,
+ zoom = 1,
+ shadowIntensity = 0,
+ shadowColor = "#000000",
+}: Props) {
+ const webglRef = useRef<HTMLDivElement>(null);
+ const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
+ const sceneRef = useRef<THREE.Scene | null>(null);
+ const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const macGroupRef = useRef<THREE.Group | null>(null);
+ const lidGroupRef = useRef<THREE.Group | null>(null);
+ const screenMaterialRef = useRef<THREE.MeshBasicMaterial | null>(null);
+ const lightHolderRef = useRef<THREE.Group | null>(null);
+ const imageUrlRef = useRef<string | null>(imageUrl);
+ const lastLoadedUrlRef = useRef<string | null>(null);
+ const imageMaskConfigRef = useRef<ImageMaskConfigLike | null>(imageMaskConfig);
+ const openingProgressRef = useRef<number>(openingProgress);
+ const onRotationChangeRef = useRef(onRotationChange);
+ const onMountRef = useRef(onMount);
+ const onApiRef = useRef(onApi);
+ const zoomRef = useRef(zoom);
+
+ const camPosRef = useRef<THREE.Vector3>(new THREE.Vector3(0, 0, CAM_RADIUS / zoom));
+ const camTargetRef = useRef<THREE.Vector3>(new THREE.Vector3(0, 0, CAM_RADIUS / zoom));
+ const velRef = useRef<{ dTheta: number; dPhi: number }>({ dTheta: 0, dPhi: 0 });
+ const lastPxRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
+ const isDraggingRef = useRef(false);
+ const [grabbing, setGrabbing] = useState(false);
+ const [loaded, setLoaded] = useState(false);
+
+ // Sync refs
+ useEffect(() => { onRotationChangeRef.current = onRotationChange; }, [onRotationChange]);
+ useEffect(() => { onMountRef.current = onMount; }, [onMount]);
+ useEffect(() => { onApiRef.current = onApi; }, [onApi]);
+ useEffect(() => { imageUrlRef.current = imageUrl; }, [imageUrl]);
+ useEffect(() => { openingProgressRef.current = openingProgress; }, [openingProgress]);
+ useEffect(() => {
+ imageMaskConfigRef.current = imageMaskConfig;
+ lastLoadedUrlRef.current = null;
+ }, [imageMaskConfig]);
+ useEffect(() => { zoomRef.current = zoom; }, [zoom]);
+
+ // ── Lid + screen opacity ──────────────────────────────────────────────────
+ const applyLid = useCallback(() => {
+ const lid = lidGroupRef.current;
+ const mat = screenMaterialRef.current;
+ if (!lid || !mat) return;
+ const t = Math.max(0, Math.min(1, openingProgressRef.current));
+ lid.rotation.x = lerp(LID_CLOSED_X, LID_OPEN_X, t);
+ mat.opacity = 0.96 * t;
+ }, []);
+
+ // ── Screen texture ────────────────────────────────────────────────────────
+ const loadScreenTexture = useCallback((
+ url: string,
+ mat: THREE.MeshBasicMaterial,
+ renderer: THREE.WebGLRenderer
+ ) => {
+ 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);
+ if (mat.map) mat.map.dispose();
+ const tex = new THREE.CanvasTexture(cover);
+ tex.flipY = false;
+ tex.wrapS = THREE.RepeatWrapping;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ if (cover.width && cover.height) {
+ tex.repeat.y = (cover.width / cover.height) / screenSize[0] * screenSize[1];
+ }
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.anisotropy = renderer.capabilities.getMaxAnisotropy();
+ mat.map = tex;
+ mat.needsUpdate = true;
+ lastLoadedUrlRef.current = url;
+ };
+ img.onerror = () => { lastLoadedUrlRef.current = url; };
+ img.src = url;
+ }, []);
+
+ // ── Main Three.js setup ───────────────────────────────────────────────────
+ useEffect(() => {
+ const container = webglRef.current;
+ if (!container) return;
+
+ const scene = new THREE.Scene();
+ sceneRef.current = scene;
+
+ const radius = CAM_RADIUS / zoom;
+ const initPos = anglesFromInitial(initialRotationX, initialRotationY, radius);
+ camPosRef.current.copy(initPos);
+ camTargetRef.current.copy(initPos);
+
+ const camera = new THREE.PerspectiveCamera(CAM_FOV, RENDER_W / RENDER_H, 10, 1000);
+ camera.position.copy(initPos);
+ camera.lookAt(0, 0, 0);
+ cameraRef.current = camera;
+
+ // ── Lighting ──────────────────────────────────────────────────────────────
+ scene.add(new THREE.AmbientLight(0xffffff, 3.2));
+
+ const lightHolder = new THREE.Group();
+ scene.add(lightHolder);
+ lightHolderRef.current = lightHolder;
+
+ const mainLight = new THREE.PointLight(0xfff5e1, 0.8);
+ mainLight.position.set(0, 5, 50);
+ lightHolder.add(mainLight);
+
+ const dl1 = new THREE.DirectionalLight(0xffffff, 2.6);
+ dl1.position.set(4, 8, 7);
+ scene.add(dl1);
+
+ const dl2 = new THREE.DirectionalLight(0xaabbff, 0.8);
+ dl2.position.set(-5, -2, 4);
+ scene.add(dl2);
+
+ const dl3 = new THREE.DirectionalLight(0xffffff, 1.3);
+ dl3.position.set(0, -6, 6);
+ scene.add(dl3);
+
+ // ── Materials ─────────────────────────────────────────────────────────────
+ const darkPlasticMaterial = new THREE.MeshStandardMaterial({
+ color: 0x000000, roughness: 0.9, metalness: 0.9,
+ });
+ const cameraMaterial = new THREE.MeshBasicMaterial({ color: 0x333333 });
+ const logoMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });
+ const baseMetalMaterial = new THREE.MeshStandardMaterial({
+ color: 0xcecfd3, roughness: 0.25, metalness: 0.85,
+ });
+ const screenMaterial = new THREE.MeshBasicMaterial({
+ map: null, transparent: true, opacity: 0, side: THREE.BackSide,
+ });
+ screenMaterialRef.current = screenMaterial;
+
+ const textLoader = new THREE.TextureLoader();
+ const keyboardMaterial = new THREE.MeshBasicMaterial({
+ color: 0xffffff, transparent: true,
+ });
+ textLoader.load("/images/pages/keyboard-overlay.png", (tex) => {
+ keyboardMaterial.alphaMap = tex;
+ keyboardMaterial.needsUpdate = true;
+ });
+
+ // ── Renderer ──────────────────────────────────────────────────────────────
+ const renderer = new THREE.WebGLRenderer({
+ antialias: true, alpha: true, preserveDrawingBuffer: true,
+ });
+ const DPR = Math.min(window.devicePixelRatio || 1, 3);
+ renderer.setPixelRatio(DPR);
+ renderer.setSize(RENDER_W, RENDER_H, false);
+ renderer.setClearColor(0x000000, 0);
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.5;
+ rendererRef.current = renderer;
+
+ const canvas = renderer.domElement;
+ // Simple absolute positioning — same as v2. The parent container uses
+ // overflow:visible so rotated geometry is never clipped.
+ canvas.style.cssText = `position:absolute;top:0;left:0;width:${LAPTOP_W}px;height:${LAPTOP_H}px;pointer-events:none`;
+ container.appendChild(canvas);
+ onMountRef.current?.(canvas);
+
+ // ── Load GLB ──────────────────────────────────────────────────────────────
+ loadLaptopGltf().then((gltf) => {
+ const root = gltf.clone(true);
+ root.position.z = -10;
+ root.rotation.set(0, 0, initialRotationZ * (Math.PI / 180));
+ scene.add(root);
+ macGroupRef.current = root;
+
+ const lidGroup = new THREE.Group();
+ const bottomGroup = new THREE.Group();
+
+ ;[...root.children].forEach((child) => {
+ if (child.name === "_top") {
+ lidGroup.add(child);
+ ;[...child.children].forEach((obj) => {
+ if (!(obj instanceof THREE.Mesh)) return;
+ const m = obj as THREE.Mesh;
+ if (m.name === "lid") m.material = baseMetalMaterial;
+ else if (m.name === "logo") m.material = logoMaterial;
+ else if (m.name === "screen-frame") m.material = darkPlasticMaterial;
+ else if (m.name === "camera") m.material = cameraMaterial;
+ });
+ } else if (child.name === "_bottom") {
+ bottomGroup.add(child);
+ ;[...child.children].forEach((obj) => {
+ if (!(obj instanceof THREE.Mesh)) return;
+ const m = obj as THREE.Mesh;
+ if (m.name === "base") m.material = baseMetalMaterial;
+ else if (["legs", "keyboard", "inner"].includes(m.name))
+ m.material = darkPlasticMaterial;
+ });
+ }
+ });
+
+ root.add(lidGroup);
+ root.add(bottomGroup);
+ lidGroupRef.current = lidGroup;
+
+ const screenMesh = new THREE.Mesh(
+ new THREE.PlaneGeometry(screenSize[0], screenSize[1]),
+ screenMaterial
+ );
+ screenMesh.position.set(0, 10.5, -0.11);
+ screenMesh.rotation.set(Math.PI, 0, 0);
+ lidGroup.add(screenMesh);
+
+ const darkScreen = new THREE.Mesh(
+ new THREE.PlaneGeometry(screenSize[0], screenSize[1]),
+ darkPlasticMaterial
+ );
+ darkScreen.position.set(0, 10.5, -0.111);
+ darkScreen.rotation.set(Math.PI, Math.PI, 0);
+ lidGroup.add(darkScreen);
+
+ const keyboardKeys = new THREE.Mesh(
+ new THREE.PlaneGeometry(27.7, 11.6),
+ keyboardMaterial
+ );
+ keyboardKeys.rotation.set(-0.5 * Math.PI, 0, 0);
+ keyboardKeys.position.set(0, 0.045, 7.21);
+ bottomGroup.add(keyboardKeys);
+
+ if (imageUrlRef.current) {
+ loadScreenTexture(imageUrlRef.current, screenMaterial, renderer);
+ }
+ applyLid();
+ setLoaded(true);
+ }).catch((err) => {
+ console.error("Error al cargar el GLB del laptop:", err);
+ });
+
+ // ── Render loop with inertia ──────────────────────────────────────────────
+ let raf = 0;
+ const EPS = 1e-6;
+ const tick = () => {
+ raf = requestAnimationFrame(tick);
+ const vel = velRef.current;
+
+ if (Math.abs(vel.dTheta) > EPS || Math.abs(vel.dPhi) > EPS) {
+ const sph = new THREE.Spherical().setFromVector3(camPosRef.current);
+ sph.theta += vel.dTheta;
+ sph.phi = Math.max(0.05, Math.min(Math.PI - 0.05, sph.phi + vel.dPhi));
+ sph.radius = CAM_RADIUS / zoomRef.current;
+
+ camPosRef.current.setFromSpherical(sph);
+ camera.position.copy(camPosRef.current);
+ camera.lookAt(0, 0, 0);
+
+ vel.dTheta *= (1 - DAMPING_FACTOR);
+ vel.dPhi *= (1 - DAMPING_FACTOR);
+
+ if (Math.abs(vel.dTheta) < EPS) vel.dTheta = 0;
+ if (Math.abs(vel.dPhi) < EPS) vel.dPhi = 0;
+ }
+
+ if (lightHolderRef.current) {
+ lightHolderRef.current.quaternion.copy(camera.quaternion);
+ }
+
+ renderer.render(scene, camera);
+ };
+ raf = requestAnimationFrame(tick);
+
+ return () => {
+ cancelAnimationFrame(raf);
+ onApiRef.current?.(null);
+ renderer.dispose();
+ if (container.contains(canvas)) container.removeChild(canvas);
+ rendererRef.current = null;
+ sceneRef.current = null;
+ cameraRef.current = null;
+ macGroupRef.current = null;
+ lidGroupRef.current = null;
+ screenMaterialRef.current = null;
+ lightHolderRef.current = null;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // ── Sync initialRotation props → camera ──────────────────────────────────
+ useEffect(() => {
+ const radius = CAM_RADIUS / zoom;
+ const newPos = anglesFromInitial(initialRotationX, initialRotationY, radius);
+ velRef.current = { dTheta: 0, dPhi: 0 };
+ camPosRef.current.copy(newPos);
+ camTargetRef.current.copy(newPos);
+ const cam = cameraRef.current;
+ if (cam) { cam.position.copy(newPos); cam.lookAt(0, 0, 0); }
+ }, [initialRotationX, initialRotationY, zoom]);
+
+ // ── Sync rotationZ → group ────────────────────────────────────────────────
+ useEffect(() => {
+ const group = macGroupRef.current;
+ if (group) group.rotation.z = initialRotationZ * (Math.PI / 180);
+ }, [initialRotationZ]);
+
+ // ── Sync openingProgress → lid ────────────────────────────────────────────
+ useEffect(() => {
+ openingProgressRef.current = openingProgress;
+ applyLid();
+ }, [openingProgress, applyLid]);
+
+ // ── Reload screen texture ─────────────────────────────────────────────────
+ useEffect(() => {
+ const mat = screenMaterialRef.current;
+ const renderer = rendererRef.current;
+ if (!mat || !renderer || !imageUrl) return;
+ if (lastLoadedUrlRef.current === imageUrl) return;
+ loadScreenTexture(imageUrl, mat, renderer);
+ }, [imageUrl, loadScreenTexture]);
+
+ // ── renderAt API ──────────────────────────────────────────────────────────
+ useEffect(() => {
+ const api: Laptop3DApi = {
+ renderAt: (w, h) => {
+ const renderer = rendererRef.current;
+ const camera = cameraRef.current;
+ const scene = sceneRef.current;
+ if (!renderer || !camera || !scene) return;
+ const oldAspect = camera.aspect;
+ camera.aspect = w / h;
+ camera.updateProjectionMatrix();
+ renderer.setSize(w, h, false);
+ renderer.render(scene, camera);
+ camera.aspect = oldAspect;
+ camera.updateProjectionMatrix();
+ renderer.setSize(RENDER_W, RENDER_H, false);
+ },
+ };
+ onApiRef.current?.(api);
+ return () => onApiRef.current?.(null);
+ }, []);
+
+ // ── Pointer drag ──────────────────────────────────────────────────────────
+ const onPointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
+ isDraggingRef.current = true;
+ setGrabbing(true);
+ lastPxRef.current = { x: e.clientX, y: e.clientY };
+ velRef.current = { dTheta: 0, dPhi: 0 };
+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ }, []);
+
+ const onPointerMove = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
+ if (!isDraggingRef.current) return;
+ const dx = e.clientX - lastPxRef.current.x;
+ const dy = e.clientY - lastPxRef.current.y;
+ lastPxRef.current = { x: e.clientX, y: e.clientY };
+ velRef.current.dTheta -= dx * THETA_SPEED;
+ velRef.current.dPhi -= dy * PHI_SPEED;
+ }, []);
+
+ const onPointerUp = useCallback(() => {
+ if (!isDraggingRef.current) return;
+ isDraggingRef.current = false;
+ setGrabbing(false);
+ const { rx, ry } = rxRyFromCamera(camPosRef.current);
+ onRotationChangeRef.current?.(rx, ry);
+ }, []);
+
+ // ── Shadow ────────────────────────────────────────────────────────────────
+ const t = Math.max(0, Math.min(1, shadowIntensity));
+ const tEased = t * t;
+ const computedBlur = tEased * 60;
+ const computedOpacity = tEased * 0.7;
+ const shadowRgba = shadowColor.startsWith("#")
+ ? parseShadowColor(shadowColor, computedOpacity)
+ : shadowColor;
+ const hasShadow = t > 0.01;
+
+ return (
+ <div
+ style={{
+ display: "inline-block",
+ transformOrigin: "top center",
+ transform: `scale(${scale})`,
+ width: LAPTOP_W,
+ height: LAPTOP_H + (hasShadow ? computedBlur * 0.8 : 0),
+ marginTop: "200px",
+ }}
+ >
+ {/*
+ * 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",
+ width: LAPTOP_W,
+ height: LAPTOP_H,
+ overflow: "visible",
+ willChange: "transform",
+ }}
+ >
+ {/* Ground shadow ellipse */}
+ {hasShadow && (
+ <div
+ aria-hidden
+ style={{
+ position: "absolute",
+ bottom: -(computedBlur * 0.5),
+ left: `${10 + tEased * 5}%`,
+ width: `${80 - 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",
+ }}
+ />
+ )}
+
+ {/* WebGL canvas container — overflow:visible lets model exceed bounds */}
+ <div
+ ref={webglRef}
+ style={{
+ position: "absolute",
+ left: 0,
+ top: 0,
+ width: LAPTOP_W,
+ height: LAPTOP_H,
+ overflow: "visible",
+ pointerEvents: "none",
+ zIndex: 2,
+ filter: hasShadow
+ ? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`
+ : "none",
+ transition: "filter 0.15s ease",
+ }}
+ />
+
+ {/* Drag interaction layer */}
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ zIndex: 3,
+ cursor: grabbing ? "grabbing" : "grab",
+ }}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerLeave={onPointerUp}
+ />
+
+ {!loaded && (
+ <div
+ className="absolute inset-0 flex items-center justify-center pointer-events-none"
+ style={{ zIndex: 4 }}
+ >
+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/Phone3DViewer.tsx b/app/components/ui/editor/Phone3DViewer.tsx
index 980894c..8dc8928 100644
--- a/app/components/ui/editor/Phone3DViewer.tsx
+++ b/app/components/ui/editor/Phone3DViewer.tsx
@@ -1,836 +1,598 @@
"use client";
/**
- * Phone3DViewer
+ * Phone3DViewer — R3F + drei + OrbitControls edition
*
- * Architecture: ONE master timeline per sequence.
- * Entry + snap + drift are all added to a single gsap.timeline() so there
- * are zero gaps, zero competing tweens, and zero onComplete chains.
+ * Key architectural fixes in this version:
*
- * Phase machine:
- * idle → entry → hold → exit → done
+ * 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.
*
- * The hold drift uses repeat:-1 yoyo on a sub-timeline added to the master.
- * The exit is scheduled with gsap.delayedCall (not onComplete) so killMotion
- * can cancel it cleanly without race conditions.
+ * 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 gsap from "gsap";
-import phoneGltfData from "@/public/models/phone-gltf.json";
-import { NRX, NRY, idleScript } from "@/lib/animation-core";
-import { TEMPLATES } from "@/lib/template-registry";
-import { AV, MotionStyle } from "@/types/motion.types";
-import { CAMERA_VARIANTS, DEFAULT_VARIANT_ID } from "./templates-motion/Phone";
-import type { AnimMode } from "@/types/motion.types";
-
-// ─── Canvas dimensions ────────────────────────────────────────────────────────
-const PHONE_W = 231;
-const PHONE_H = 469;
-const RENDER_W = 595;
-const RENDER_H = 765;
-const CAM_FOV = 20;
-const CAM_Z = 14;
-
-const RX = (PHONE_W - RENDER_W) / 2;
-const RY = (PHONE_H - RENDER_H) / 2;
-
-// ─── GLTF cache ───────────────────────────────────────────────────────────────
-const GLTF_STR = JSON.stringify(phoneGltfData);
-let gltfCachePromise: Promise<THREE.Group> | null = null;
-
-function loadGltfGroup(): Promise<THREE.Group> {
- if (!gltfCachePromise) {
- gltfCachePromise = new Promise((resolve, reject) =>
- new GLTFLoader().parse(GLTF_STR, "", (gltf) => resolve(gltf.scene as THREE.Group), reject)
- );
- }
- return gltfCachePromise;
-}
-
-// Per-URL GLTF cache for external GLB files
-const gltfUrlCache = new Map<string, Promise<THREE.Group>>();
-
-function loadGltfFromUrl(url: string): Promise<THREE.Group> {
- if (!gltfUrlCache.has(url)) {
- gltfUrlCache.set(url, new Promise((resolve, reject) =>
- new GLTFLoader().load(url, (gltf) => resolve(gltf.scene as THREE.Group), undefined, reject)
- ));
- }
- return gltfUrlCache.get(url)!;
-}
-
-function cloneGroup(src: THREE.Group): THREE.Group {
- const clone = src.clone(true);
- clone.traverse((child) => {
- if (child instanceof THREE.Mesh) {
- child.material = Array.isArray(child.material)
- ? (child.material as THREE.Material[]).map((m) => m.clone())
- : (child.material as THREE.Material).clone();
- }
- });
- return clone;
+import {
+ PHONE_W,
+ PHONE_H,
+ deviceConfigs,
+ getDeviceFromModelUrl,
+ createCoverScreenCanvas,
+ loadGltfGroup,
+ cloneGroup,
+ type ImageMaskConfigLike,
+} from "@/lib/phone3d.utils";
+
+export interface Phone3DApi {
+ renderAt: (width: number, height: number) => void;
}
-// ─── Props ────────────────────────────────────────────────────────────────────
interface Props {
- videoElement?: HTMLVideoElement | null;
- canvasElement?: HTMLCanvasElement | null;
imageUrl?: string | null;
- isPlaying?: boolean;
- animDuration?: number;
- intensity?: number;
- templateId?: string | null;
- motionStyle?: MotionStyle;
- variantId?: string | null;
- animMode?: AnimMode;
- /** If true, drag releases keep the final rotation (no spring-back). Default false */
- keepRotation?: boolean;
- /** Initial 3D rotation offset (degrees) to restore after remount */
+ imageMaskConfig?: ImageMaskConfigLike | null;
initialRotationX?: number;
initialRotationY?: number;
- /** Called on pointer-up with final rotation offsets */
+ initialRotationZ?: number;
onRotationChange?: (rx: number, ry: number) => void;
- /** Called once the WebGL canvas is ready — used by parent to capture a snapshot for export */
onMount?: (canvas: HTMLCanvasElement) => void;
- /** External GLB model URL (e.g. '/models/iphone-15-pro-max.glb'). When omitted, uses the default phone-gltf.json */
+ onApi?: (api: Phone3DApi | null) => void;
modelUrl?: string;
+ scale?: number;
+ zoom?: number;
+ shadowIntensity?: number;
+ shadowColor?: string;
}
-// ─── helpers ──────────────────────────────────────────────────────────────────
-/** Shortest arc in degrees from curRy to targetRy, result in [-180, 180] */
-function shortArc(curRy: number, targetRy: number): number {
- return ((targetRy - curRy) % 360 + 540) % 360 - 180;
-}
-
-// ─── Component ────────────────────────────────────────────────────────────────
-export function Phone3DViewer({
- videoElement = null,
- canvasElement = null,
- imageUrl = null,
- isPlaying = false,
- animDuration = 8000,
- intensity = 70,
- templateId = null,
- motionStyle = "normal",
- variantId = null,
- animMode = "entry+exit",
- keepRotation = false,
- initialRotationX = 0,
- initialRotationY = 0,
- onRotationChange,
- onMount,
- modelUrl,
-}: Props) {
- const webglRef = useRef<HTMLDivElement>(null);
- const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
- const phoneGroupRef = useRef<THREE.Group | null>(null);
- const screenMeshRef = useRef<THREE.Mesh | null>(null);
- const rootRef = useRef<HTMLDivElement>(null);
-
- // ── Animation state ──────────────────────────────────────────────────────────
- // Single master timeline — killed atomically by stopAll()
- const masterTlRef = useRef<gsap.core.Timeline | null>(null);
- // delayedCall for exit scheduling — killed atomically by stopAll()
- const exitTimerRef = useRef<gsap.core.Tween | null>(null);
- // Monotonically-increasing token; stale callbacks bail out immediately
- const tokenRef = useRef(0);
-
- type Phase = "idle" | "entry" | "hold" | "exit" | "done";
- const phaseRef = useRef<Phase>("idle");
- const holdEndEpochRef = useRef(0);
- const holdRemRef = useRef(0);
- // Captures the exit launcher so pause/resume can reschedule it
- const scheduleExitRef = useRef<((delayMs: number) => void) | null>(null);
-
- const [loaded, setLoaded] = useState(false);
- const [dragging, setDragging] = useState(false);
-
- const isDraggingRef = useRef(false);
- const hasEnteredRef = useRef(false);
-
- const imageUrlRef = useRef(imageUrl);
- const lastLoadedImageUrlRef = useRef<string | null>(null);
- const videoElementRef = useRef<HTMLVideoElement | null>(videoElement);
- const canvasElementRef = useRef<HTMLCanvasElement | null>(canvasElement);
- const textureCreatedRef = useRef(false);
- const animDurRef = useRef(animDuration);
- const intensityRef = useRef(intensity);
- const templateIdRef = useRef(templateId);
- const motionStyleRef = useRef<MotionStyle>(motionStyle);
- const variantIdRef = useRef(variantId);
- const animModeRef = useRef<AnimMode>(animMode);
- const isPlayingRef = useRef(isPlaying);
-
- const dragOrigin = useRef({ px: 0, py: 0, rx: 0, ry: 0 });
- const animIdRef = useRef(0);
- const userOffset = useRef<{ rx: number; ry: number }>({ rx: initialRotationX, ry: initialRotationY });
- const av = useRef<AV>({ rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.0 });
- const keepRotationRef = useRef(keepRotation);
- const onRotationChangeRef = useRef(onRotationChange);
- const onMountRef = useRef(onMount);
- const modelUrlRef = useRef(modelUrl);
- useEffect(() => { keepRotationRef.current = keepRotation; }, [keepRotation]);
- useEffect(() => { onRotationChangeRef.current = onRotationChange; }, [onRotationChange]);
- useEffect(() => { onMountRef.current = onMount; }, [onMount]);
- useEffect(() => { modelUrlRef.current = modelUrl; }, [modelUrl]);
-
- // Animate to new rotation when parent changes initialRotationX/Y (e.g. card click)
- useEffect(() => {
- if (isDraggingRef.current) return;
- gsap.to(userOffset.current, {
- rx: initialRotationX,
- ry: initialRotationY,
- duration: 0.55,
- ease: "power2.out",
- overwrite: "auto",
- onUpdate: updateDOM,
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [initialRotationX, initialRotationY]);
-
- useEffect(() => { imageUrlRef.current = imageUrl; }, [imageUrl]);
- useEffect(() => { videoElementRef.current = videoElement; }, [videoElement]);
- useEffect(() => { canvasElementRef.current = canvasElement; }, [canvasElement]);
- useEffect(() => { animDurRef.current = animDuration; }, [animDuration]);
- useEffect(() => { intensityRef.current = intensity; }, [intensity]);
- useEffect(() => { templateIdRef.current = templateId; }, [templateId]);
- useEffect(() => { motionStyleRef.current = motionStyle; }, [motionStyle]);
- useEffect(() => { variantIdRef.current = variantId; }, [variantId]);
- useEffect(() => { animModeRef.current = animMode; }, [animMode]);
- useEffect(() => { isPlayingRef.current = isPlaying; }, [isPlaying]);
-
- useEffect(() => { textureCreatedRef.current = false; }, [imageUrl, videoElement, canvasElement]);
-
- // ── updateDOM — applies av to Three.js group + root CSS ───────────────────
- const updateDOM = useCallback(() => {
- const r = rootRef.current;
- if (!r) return;
- const { rx, ry, tx, ty, sc } = av.current;
- const DEG = Math.PI / 180;
- const group = phoneGroupRef.current;
- if (group) group.rotation.set(
- (rx + userOffset.current.rx) * DEG,
- (ry + userOffset.current.ry) * DEG,
- 0, "YXZ"
- );
- r.style.transform = `translate(${tx}px, ${ty}px) scale(${sc})`;
- }, []);
-
- // ── stopAll — kills EVERYTHING, increments token ─────────────────────────
- const stopAll = useCallback(() => {
- tokenRef.current += 1;
- if (exitTimerRef.current) { exitTimerRef.current.kill(); exitTimerRef.current = null; }
- if (masterTlRef.current) { masterTlRef.current.kill(); masterTlRef.current = null; }
- gsap.killTweensOf(av.current);
- scheduleExitRef.current = null;
- }, []);
+const DEFAULT_CAM_Z = 1.5;
- // ── startMotion — the only entry point for launching an animation ─────────
- const startMotion = useCallback((durMs: number, once = false) => {
- // Static mode: no animation, just stay at rest pose
- if (animModeRef.current === "static") return;
-
- stopAll();
- phaseRef.current = "idle";
- holdRemRef.current = 0;
- holdEndEpochRef.current = 0;
-
- const id = templateIdRef.current;
- const style = motionStyleRef.current;
- const i = intensityRef.current / 100;
- const tpl = TEMPLATES.find((t) => t.id === id);
- const isPhone = id === "phone";
-
- const variant = CAMERA_VARIANTS.find(
- (v) => v.id === (variantIdRef.current ?? DEFAULT_VARIANT_ID)
- ) ?? CAMERA_VARIANTS[0];
-
- const mode: AnimMode = animModeRef.current;
-
- // Capture token for this invocation
- const myToken = tokenRef.current;
- const alive = () => tokenRef.current === myToken;
-
- // ── Non-phone: just run the template script unchanged ──────────────────
- if (!isPhone) {
- const script = tpl?.script ?? idleScript;
- const tl = script(av.current, i, durMs, style, updateDOM);
- masterTlRef.current = tl;
- phaseRef.current = "hold";
- return;
- }
-
- // ── Phone: compute durations ───────────────────────────────────────────
- const entryDur = (mode === "entry" || mode === "entry+exit") ? variant.entryDuration : 0;
- const exitDur = (mode === "exit" || mode === "entry+exit") ? variant.exitDuration : 0;
- const holdDur = Math.max(durMs - entryDur - exitDur, 0);
-
- // ── Compute snap arc from wherever av currently is to hero pose ───────
- // snapDur is proportional to arc magnitude so large rotations glide smoothly
- const curRy = av.current.ry;
- const arcDelta = shortArc(curRy, NRY);
- const arcDeg = Math.abs(arcDelta);
- const snapDur = 0.25 + (arcDeg / 180) * 0.45; // 0.25s – 0.70s
-
- // ── ONE master timeline for entry + snap ─────────────────────────────
- // Using GSAP's position parameter (">") so snap starts at the END of entry.
- // No separate onComplete chains — everything is one timeline.
- const master = gsap.timeline({ paused: true });
-
- if (mode === "entry" || mode === "entry+exit") {
- // Add entry sub-timeline at position 0
- const entryTl = variant.entryScript(av.current, i, entryDur, style, updateDOM);
- entryTl.repeat(0);
- master.add(entryTl, 0);
-
- // Snap tween appended right after entry ends (position ">")
- master.to(av.current, {
- rx: NRX,
- ry: curRy + arcDelta, // shortest-arc target
- tx: 0, ty: 0, sc: 1.0,
- duration: snapDur,
- ease: "power2.out",
- onUpdate: updateDOM,
- }, ">");
-
- } else if (mode === "exit" || mode === "none") {
- // No entry: just snap to hero pose first, then hold
- master.to(av.current, {
- rx: NRX, ry: curRy + arcDelta,
- tx: 0, ty: 0, sc: 1.0,
- duration: snapDur,
- ease: "power2.out",
- onUpdate: updateDOM,
- }, 0);
- }
-
- // When the master finishes (entry + snap), transition to hold
- master.eventCallback("onComplete", () => {
- if (!alive()) return;
-
- phaseRef.current = "hold";
-
- // ── Hold: smooth breathing drift, repeat:-1 yoyo ─────────────────
- // This is a NEW standalone timeline (not inside master) so it can
- // be killed independently from the exit.
- const driftTl = gsap.timeline({ repeat: -1, yoyo: true });
- driftTl.to(av.current, {
- rx: NRX - 2 * i,
- ry: NRY - 4 * i,
- tx: 2 * i,
- ty: -3 * i,
- sc: 1.0,
- duration: 2.8,
- ease: "sine.inOut",
- onUpdate: updateDOM,
- });
- masterTlRef.current = driftTl;
-
- // ── Schedule exit ────────────────────────────────────────────────
- // Build the schedule function here so pause/resume can reuse it
- const doScheduleExit = (delayMs: number) => {
- if (!alive()) return;
- const safe = Math.max(delayMs, 0);
- holdEndEpochRef.current = Date.now() + safe;
- exitTimerRef.current = gsap.delayedCall(safe / 1000, () => {
- exitTimerRef.current = null;
- if (!alive()) return;
- runExit();
- });
- };
- scheduleExitRef.current = doScheduleExit;
-
- if (mode === "entry+exit" || mode === "exit") {
- doScheduleExit(holdDur);
- }
- // mode "entry" or "none": drift runs indefinitely until video ends/pauses
- });
+function parseShadowColor(hex: string, opacity: number): string {
+ const h = hex.replace("#", "");
+ const r = parseInt(h.length === 3 ? h[0] + h[0] : h.slice(0, 2), 16);
+ const g = parseInt(h.length === 3 ? h[1] + h[1] : h.slice(2, 4), 16);
+ const b = parseInt(h.length === 3 ? h[2] + h[2] : h.slice(4, 6), 16);
+ return `rgba(${r},${g},${b},${opacity.toFixed(3)})`;
+}
- // ── runExit ─────────────────────────────────────────────────────────
- const runExit = () => {
- if (!alive()) return;
- phaseRef.current = "exit";
-
- // Kill the drift
- if (masterTlRef.current) { masterTlRef.current.kill(); masterTlRef.current = null; }
- gsap.killTweensOf(av.current);
-
- // Snap quickly to clean hero pose before starting the exit script
- // so the exit always starts from a known position
- const preExitArc = shortArc(av.current.ry, NRY);
- const preExitDur = Math.min(0.3, Math.abs(preExitArc) / 360);
-
- const exitMaster = gsap.timeline();
-
- if (preExitDur > 0.05) {
- exitMaster.to(av.current, {
- rx: NRX, ry: av.current.ry + preExitArc,
- tx: 0, ty: 0, sc: 1.0,
- duration: preExitDur,
- ease: "power2.out",
- onUpdate: updateDOM,
- });
- }
+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 exitTl = variant.exitScript(av.current, i, exitDur, style, updateDOM);
- exitTl.repeat(0);
- exitMaster.add(exitTl, ">");
+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; }
+}
- exitMaster.eventCallback("onComplete", () => {
- if (alive()) phaseRef.current = "done";
- });
+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;
+}
- masterTlRef.current = exitMaster;
+// ─── GltfModelScene — iphone 15 / samsung / iphone-13 ────────────────────────
+function GltfModelScene({
+ imageUrl,
+ imageMaskConfig,
+ initialRotationX,
+ initialRotationY,
+ initialRotationZ,
+ zoom,
+ onRotationChange,
+ onApi,
+ modelUrl,
+}: 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 = () => {
+ 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.src = url;
+ }, [deviceConfig, gl]);
- // ── preview (once=true): run the legacy `script` and spring back ─────
- if (once) {
- master.kill(); // don't need the master we built
- const previewDur = Math.min(durMs, 4000);
- const previewTl = variant.script(av.current, i, previewDur, style, updateDOM);
- previewTl.repeat(0);
- previewTl.eventCallback("onComplete", () => {
- if (!alive()) return;
- phaseRef.current = "done";
- const arc = shortArc(av.current.ry, NRY);
- gsap.to(av.current, {
- rx: NRX, ry: av.current.ry + arc,
- tx: 0, ty: 0, sc: 1.0,
- duration: 0.8 + Math.abs(arc) / 360,
- ease: "power3.out",
- onUpdate: updateDOM,
- });
- });
- masterTlRef.current = previewTl;
- phaseRef.current = "entry";
- return;
+ // 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);
}
- // Play the master (entry + snap → triggers onComplete → hold)
- phaseRef.current = "entry";
- masterTlRef.current = master;
- master.play();
-
- }, [stopAll, updateDOM]);
+ // 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
+ }, []);
- // ── isPlaying effect ──────────────────────────────────────────────────────
+ // Texture sync on prop change
useEffect(() => {
- if (!hasEnteredRef.current) return;
-
- if (isPlaying) {
- // Cancel any spring-to-REST from the pause transition
- gsap.killTweensOf(av.current);
-
- const phase = phaseRef.current;
-
- if (phase === "hold") {
- // Resume drift without replaying entry
- const i = intensityRef.current / 100;
- const mode = animModeRef.current;
-
- const driftTl = gsap.timeline({ repeat: -1, yoyo: true });
- driftTl.to(av.current, {
- rx: NRX - 2 * i, ry: NRY - 4 * i,
- tx: 2 * i, ty: -3 * i, sc: 1.0,
- duration: 2.8, ease: "sine.inOut", onUpdate: updateDOM,
- });
- masterTlRef.current = driftTl;
-
- // Reschedule exit if applicable
- if ((mode === "entry+exit" || mode === "exit") && scheduleExitRef.current) {
- const remaining = holdRemRef.current > 0
- ? holdRemRef.current
- : Math.max(holdEndEpochRef.current - Date.now(), 0);
- holdRemRef.current = 0;
- if (remaining > 0) {
- scheduleExitRef.current(remaining);
- }
- }
-
- } else if (phase === "exit") {
- // Mid-exit when paused — restart exit from clean hero pose
- startMotion(animDurRef.current, false);
-
- } else if (phase === "done") {
- // Video looped or restarted — launch full sequence again
- startMotion(animDurRef.current, false);
-
- } else {
- // idle or interrupted entry
- startMotion(animDurRef.current, false);
- }
-
- } else {
- // Pause — save hold remaining before stopping everything
- if (phaseRef.current === "hold") {
- holdRemRef.current = exitTimerRef.current
- ? Math.max(holdEndEpochRef.current - Date.now(), 0)
- : 0;
- }
- stopAll();
-
- // Gentle spring to hero pose on pause (shortest arc)
- const arc = shortArc(av.current.ry, NRY);
- gsap.to(av.current, {
- rx: NRX, ry: av.current.ry + arc,
- tx: 0, ty: 0, sc: 1.0,
- duration: 0.9, ease: "power3.out",
- onUpdate: updateDOM,
- });
+ 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;
}
- }, [isPlaying, startMotion, stopAll, updateDOM]);
+ if (lastLoadedUrlRef.current === imageUrl) return;
+ applyTexture(mat, imageUrl);
+ }, [imageUrl, imageMaskConfig, applyTexture]);
- // ── Variant / template change → smooth bridge transition ─────────────────
- const isFirstRender = useRef(true);
+ // Orbit sync on prop change
useEffect(() => {
- if (isFirstRender.current) { isFirstRender.current = false; return; }
- if (!hasEnteredRef.current) return;
- if (!templateId || templateId === "none") return;
-
- // Increment token manually (we manage the bridge ourselves)
- tokenRef.current += 1;
- const myToken = tokenRef.current;
-
- // Stop everything without going through stopAll (we want our own bridge)
- if (exitTimerRef.current) { exitTimerRef.current.kill(); exitTimerRef.current = null; }
- if (masterTlRef.current) { masterTlRef.current.kill(); masterTlRef.current = null; }
- gsap.killTweensOf(av.current);
- scheduleExitRef.current = null;
- phaseRef.current = "idle";
- holdRemRef.current = 0;
-
- // Bridge: smooth arc to hero pose, then launch new animation
- const arc = shortArc(av.current.ry, NRY);
- const arcDeg = Math.abs(arc);
- const bridgeDur = 0.4 + (arcDeg / 180) * 0.4;
-
- gsap.to(av.current, {
- rx: NRX, ry: av.current.ry + arc,
- tx: 0, ty: 0, sc: 1.0,
- duration: bridgeDur,
- ease: "power2.inOut",
- onUpdate: updateDOM,
- onComplete: () => {
- if (tokenRef.current !== myToken) return;
- // once=true if paused (preview), once=false if playing (full run)
- startMotion(animDurRef.current, !isPlayingRef.current);
- },
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [templateId, variantId]);
+ 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]);
- // ── Intensity/style/duration changes → restart if playing ────────────────
useEffect(() => {
- if (!hasEnteredRef.current) return;
- if (!isPlayingRef.current) return;
- startMotion(animDurRef.current, false);
- }, [animDuration, intensity, motionStyle, animMode, startMotion]);
+ const root = rootRef.current;
+ if (!root || root.children.length === 0) return;
+ (root.children[0] as THREE.Group).rotation.z = initialRotationZ * (Math.PI / 180);
+ }, [initialRotationZ]);
- // ── Cinema mount entrance ─────────────────────────────────────────────────
useEffect(() => {
- const i = intensity / 100;
-
- // Static mode: no entrance animation — snap to rest pose immediately
- if (animModeRef.current === "static") {
- Object.assign(av.current, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.0 });
- updateDOM();
- hasEnteredRef.current = true;
- return () => {
- stopAll();
- gsap.killTweensOf(av.current);
- };
- }
-
- Object.assign(av.current, {
- rx: NRX + 30 * i, ry: NRY + 50 * i,
- tx: 0, ty: -60 * i, sc: 0.7,
- });
- updateDOM();
-
- gsap.to(av.current, {
- rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.0,
- duration: 1.2, ease: "expo.out",
- onUpdate: updateDOM,
- onComplete: () => {
- hasEnteredRef.current = true;
- if (isPlayingRef.current) startMotion(animDurRef.current, false);
+ 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 () => {
- stopAll();
- gsap.killTweensOf(av.current);
+ 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} />
+ </>
+ );
+}
+
+// ─── DefaultPhoneModelScene — JSON phone ──────────────────────────────────────
+function DefaultPhoneModelScene({
+ imageUrl,
+ imageMaskConfig,
+ initialRotationX,
+ initialRotationY,
+ initialRotationZ,
+ zoom,
+ onRotationChange,
+ onApi,
+}: 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 = () => {
+ 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;
};
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ img.src = url;
+ }, [gl]);
- // ── Three.js setup + RAF texture loop ─────────────────────────────────────
useEffect(() => {
- const container = webglRef.current;
- if (!container) return;
-
- const scene = new THREE.Scene();
- const camera = new THREE.PerspectiveCamera(CAM_FOV, RENDER_W / RENDER_H, 0.1, 100);
- camera.position.set(0, 0, CAM_Z);
-
- scene.add(new THREE.AmbientLight(0xffffff, 3.2));
- const dl1 = new THREE.DirectionalLight(0xffffff, 2.6); dl1.position.set(4, 8, 7); scene.add(dl1);
- const dl2 = new THREE.DirectionalLight(0xaabbff, 0.8); dl2.position.set(-5,-2, 4); scene.add(dl2);
- const dl3 = new THREE.DirectionalLight(0xffffff, 1.3); dl3.position.set(0, -6, 6); scene.add(dl3);
-
- const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
- renderer.setSize(RENDER_W, RENDER_H);
- renderer.setClearColor(0x000000, 0);
- renderer.outputColorSpace = THREE.SRGBColorSpace;
- renderer.toneMapping = THREE.ACESFilmicToneMapping;
- renderer.toneMappingExposure = 1.5;
- rendererRef.current = renderer;
-
- const canvas = renderer.domElement;
- canvas.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none";
- container.appendChild(canvas);
- onMountRef.current?.(canvas);
-
- const loadPromise = modelUrlRef.current
- ? loadGltfFromUrl(modelUrlRef.current)
- : loadGltfGroup();
-
- loadPromise.then((cached) => {
+ 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 box = new THREE.Box3().setFromObject(group);
+ 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());
- group.position.sub(center);
- const halfH = CAM_Z * Math.tan((CAM_FOV / 2) * Math.PI / 180);
- const sf = (halfH * 2 * 0.80) / size.y;
+ 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.multiplyScalar(sf);
- scene.add(group);
- phoneGroupRef.current = group;
- group.updateMatrixWorld(true);
+ group.position.copy(center).negate().multiplyScalar(sf);
+ group.rotation.z = initialRotationZ * (Math.PI / 180);
group.traverse((child) => {
if (!(child instanceof THREE.Mesh)) return;
- const matName: string = Array.isArray(child.material)
- ? ((child.material[0] as THREE.Material)?.name ?? "")
- : ((child.material as THREE.Material)?.name ?? "");
-
- if (matName === "Screen.editable" || child.name === "Screen") {
- screenMeshRef.current = child;
- const mat = (Array.isArray(child.material)
- ? child.material[0] : child.material) as THREE.MeshStandardMaterial;
- mat.color.set(0xffffff);
- mat.roughness = 1.0;
- mat.metalness = 0.0;
- mat.needsUpdate = true;
- child.visible = true;
- return;
- }
-
- if (!Array.isArray(child.material)) {
- const mat = child.material as THREE.MeshStandardMaterial;
- if (!mat.isMeshStandardMaterial) return;
- if (matName.includes("Body")) mat.color.set(0x707070);
- if (matName.includes("Bezel")) mat.color.set(0x808080);
- if (matName.includes("Buttons")) mat.color.set(0x909090);
- if (matName.includes("Lenses")) {
- mat.color.set(0x060608);
- mat.roughness = 0.06;
- mat.metalness = 0.55;
- }
+ 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);
}
});
- setLoaded(true);
- });
-
- // RAF texture loop
- const tick = () => {
- animIdRef.current = requestAnimationFrame(tick);
- const mesh = screenMeshRef.current;
- if (!mesh) { renderer.render(scene, camera); return; }
-
- const mat = (Array.isArray(mesh.material)
- ? mesh.material[0] : mesh.material) as THREE.MeshStandardMaterial;
- const currentImageUrl = imageUrlRef.current;
-
- if (currentImageUrl) {
- if (lastLoadedImageUrlRef.current !== currentImageUrl) {
- new THREE.TextureLoader().load(
- currentImageUrl,
- (tex) => {
- if (mat.map) mat.map.dispose();
- tex.flipY = false;
- tex.colorSpace = THREE.SRGBColorSpace;
- tex.generateMipmaps = false;
- tex.minFilter = tex.magFilter = THREE.LinearFilter;
- tex.wrapS = tex.wrapT = THREE.ClampToEdgeWrapping;
- mat.map = tex;
- mat.needsUpdate = true;
- lastLoadedImageUrlRef.current = currentImageUrl;
- },
- undefined,
- () => { lastLoadedImageUrlRef.current = currentImageUrl; }
- );
- }
- } else {
- lastLoadedImageUrlRef.current = null;
- const vid = videoElementRef.current;
- const cvs = canvasElementRef.current;
-
- if (vid) {
- const ready = vid.videoWidth > 0 && vid.videoHeight > 0 && vid.readyState >= 2;
- if (ready) {
- if (!(mat.map instanceof THREE.VideoTexture)) {
- textureCreatedRef.current = true;
- if (mat.map) mat.map.dispose();
- const vt = new THREE.VideoTexture(vid);
- vt.flipY = false;
- vt.colorSpace = THREE.SRGBColorSpace;
- vt.generateMipmaps = false;
- vt.minFilter = vt.magFilter = THREE.LinearFilter;
- vt.wrapS = vt.wrapT = THREE.ClampToEdgeWrapping;
- mat.map = vt;
- mat.needsUpdate = true;
- }
- mat.map.needsUpdate = true;
- }
- } else if (cvs) {
- const ready = cvs.width > 0 && cvs.height > 0;
- if (ready) {
- if (!(mat.map instanceof THREE.CanvasTexture)) {
- textureCreatedRef.current = true;
- if (mat.map) mat.map.dispose();
- const ct = new THREE.CanvasTexture(cvs);
- ct.flipY = false;
- ct.colorSpace = THREE.SRGBColorSpace;
- ct.generateMipmaps = false;
- ct.minFilter = ct.magFilter = THREE.LinearFilter;
- ct.wrapS = ct.wrapT = THREE.ClampToEdgeWrapping;
- mat.map = ct;
- mat.needsUpdate = true;
- } else {
- (mat.map as THREE.CanvasTexture).needsUpdate = true;
- }
- }
- }
- }
+ root.add(group);
- renderer.render(scene, camera);
- };
- animIdRef.current = requestAnimationFrame(tick);
-
- return () => {
- cancelAnimationFrame(animIdRef.current);
- if (phoneGroupRef.current) {
- phoneGroupRef.current.traverse((child) => {
- if (child instanceof THREE.Mesh) {
- const mats = Array.isArray(child.material) ? child.material : [child.material];
- mats.forEach((m: THREE.Material) => {
- if ((m as THREE.MeshStandardMaterial).map) {
- (m as THREE.MeshStandardMaterial).map!.dispose();
- }
- m.dispose();
- });
- }
- });
+ if (imageUrlRef.current && screenMatRef.current) {
+ applyTexture(screenMatRef.current, imageUrlRef.current);
}
- renderer.dispose();
- if (container.contains(canvas)) container.removeChild(canvas);
- rendererRef.current = phoneGroupRef.current = screenMeshRef.current = null;
- };
- }, []);
- // ── Pointer drag ──────────────────────────────────────────────────────────
- const onPointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
- gsap.killTweensOf(userOffset.current);
- isDraggingRef.current = true;
- setDragging(true);
- dragOrigin.current = {
- px: e.clientX, py: e.clientY,
- rx: userOffset.current.rx, ry: userOffset.current.ry,
- };
- (e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);
+ 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
}, []);
- const onPointerMove = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
- if (!isDraggingRef.current) return;
- userOffset.current.rx = dragOrigin.current.rx - (e.clientY - dragOrigin.current.py) * 0.45;
- userOffset.current.ry = dragOrigin.current.ry + (e.clientX - dragOrigin.current.px) * 0.65;
- updateDOM();
- }, [updateDOM]);
-
- const onPointerUp = useCallback(() => {
- if (!isDraggingRef.current) return;
- isDraggingRef.current = false;
- setDragging(false);
- if (keepRotationRef.current) {
- // Keep final rotation — just notify parent
- onRotationChangeRef.current?.(userOffset.current.rx, userOffset.current.ry);
- } else {
- gsap.to(userOffset.current, {
- rx: 0, ry: 0, duration: 2.2, ease: "power3.out", onUpdate: updateDOM,
- });
+ 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;
}
- }, [updateDOM]);
+ if (lastLoadedUrlRef.current === imageUrl) return;
+ applyTexture(mat, imageUrl);
+ }, [imageUrl, imageMaskConfig, applyTexture]);
- return (
- <div
- ref={rootRef}
- className="select-none"
- style={{ position: "relative", width: PHONE_W, height: PHONE_H, willChange: "transform" }}
- >
- {/* Ambient glow */}
- <div
- aria-hidden
- style={{
- position: "absolute", width: 1400, height: 1400,
- left: "50%", top: "50%", transform: "translate(-50%,-50%)",
- background: "radial-gradient(circle,rgba(99,102,241,0.45) 0%,rgba(139,92,246,0.25) 30%,rgba(59,130,246,0.15) 55%,transparent 80%)",
- filter: "blur(140px)",
- }}
- />
+ 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]);
- {/* WebGL canvas */}
- <div
- ref={webglRef}
- style={{
- position: "absolute", left: RX, top: RY,
- width: RENDER_W, height: RENDER_H,
- pointerEvents: "none", zIndex: 2,
+ 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} />
+ </>
+ );
+}
- {/* Drag capture */}
- <div
- style={{ position: "absolute", inset: 0, zIndex: 3, cursor: dragging ? "grabbing" : "grab" }}
- onPointerDown={onPointerDown}
- onPointerMove={onPointerMove}
- onPointerUp={onPointerUp}
- onPointerLeave={onPointerUp}
- />
+// ─── Phone3DViewer (public) ───────────────────────────────────────────────────
+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,
+ onRotationChange,
+ onApi,
+ modelUrl,
+ };
- {/* Loading skeleton */}
- {!loaded && (
- <div style={{
- position: "absolute", inset: 0, zIndex: 10, borderRadius: "52px",
- background: "linear-gradient(148deg,#262640 0%,#18182e 45%,#0e0e1c 100%)",
- display: "flex", alignItems: "center", justifyContent: "center",
- pointerEvents: "none",
- }}>
- <div style={{
- width: "28px", height: "28px", borderRadius: "50%",
- border: "2px solid rgba(255,255,255,0.08)",
- borderTop: "2px solid rgba(99,102,241,0.75)",
- animation: "phoneSpin 0.8s linear infinite",
- }} />
- <style>{`@keyframes phoneSpin{to{transform:rotate(360deg)}}`}</style>
+ return (
+ <div
+ style={{
+ display: "inline-block",
+ transformOrigin: "top center",
+ transform: `scale(${scale})`,
+ width: PHONE_W,
+ height: PHONE_H + (hasShadow ? computedBlur * 0.8 : 0),
+ marginTop: "150px",
+ 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)}
+ >
+ <Canvas
+ key={modelUrl ?? "default"}
+ // ← Tamaño explícito: evita que R3F lea dimensiones del div con inset negativo
+ style={{
+ width: "100%",
+ height: "100%",
+ overflow: "visible",
+ display: "block", // ← elimina el inline-block gap
+ }}
+ gl={{
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ powerPreference: "high-performance",
+ }}
+ dpr={4}
+ 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} />
+ : <GltfModelScene {...sceneProps} />
+ }
+ </Canvas>
</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 4d4613d..0deb94c 100644
--- a/app/components/ui/editor/PhotoEditorPlaceholder.tsx
+++ b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
@@ -38,7 +38,7 @@ export function PhotoEditorPlaceholder({
}: PhotoEditorPlaceholderProps) {
const previewImageUrl = staticImageUrl ?? canvasImageUrl;
const t = useTranslations("editor");
- const { imagePhoneActive, setImagePhoneRotX, setImagePhoneRotY, setImagePhonePresetId } = useMotionContext();
+ const { imagePhoneActive, imagePhoneDevice, setImagePhoneRotX, setImagePhoneRotY, setImagePhoneRotZ, setImagePhonePerspective, setImagePhoneScale, setImagePhoneY, setImagePhonePresetId } = useMotionContext();
const [customConfig, setCustomConfig] = useState<Preview3DConfig>({
id: "custom",
label: "Custom",
@@ -175,20 +175,95 @@ export function PhotoEditorPlaceholder({
)}
{/* 3D preview: phone shape when phone active, CSS-transformed image otherwise */}
<div className="absolute inset-0 flex items-center justify-center z-10">
- {imagePhoneActive ? (
+ {imagePhoneActive ? (
+ imagePhoneDevice === "laptop" ? (
+ // ── Laptop thumbnail ──
+ // Uses config.rotateX/Y directly (same Euler convention as Laptop3DViewer)
+ <div style={{
+ perspective: `${Math.round((config.perspective || 600) * 0.5)}px`,
+ perspectiveOrigin: 'center center',
+ }}>
+ <div style={{
+ transform: `rotateX(${config.rotateX}deg) rotateY(${config.rotateY}deg)`,
+ transformStyle: 'preserve-3d',
+ transition: 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)',
+ width: 88,
+ height: 54,
+ position: 'relative',
+ filter: 'drop-shadow(0 4px 12px rgba(0,0,0,0.7))',
+ }}>
+ {/* Pantalla / Lid */}
+ <div style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '68%',
+ borderRadius: '3px 3px 0 0',
+ border: '1.5px solid rgba(255,255,255,0.22)',
+ background: 'linear-gradient(150deg, #1a1a2a 0%, #0d0d15 100%)',
+ overflow: 'hidden',
+ }}>
+ <div style={{
+ position: 'absolute',
+ inset: '2px',
+ borderRadius: '2px',
+ overflow: 'hidden',
+ ...(previewImageUrl
+ ? { backgroundImage: `url(${previewImageUrl})`, backgroundSize: 'cover', backgroundPosition: 'center' }
+ : { background: 'rgba(0,163,255,0.10)' }
+ ),
+ }} />
+ {/* Camara */}
+ <div style={{
+ position: 'absolute', top: 1, left: '50%',
+ transform: 'translateX(-50%)',
+ width: 3, height: 3, borderRadius: '50%',
+ background: 'rgba(255,255,255,0.15)',
+ }} />
+ </div>
+ {/* Base / Keyboard */}
+ <div style={{
+ position: 'absolute',
+ bottom: 0,
+ left: 0,
+ right: 0,
+ height: '34%',
+ borderRadius: '0 0 3px 3px',
+ background: 'linear-gradient(180deg, #cecfd3 0%, #b4b5bb 100%)',
+ border: '1px solid rgba(200,200,200,0.3)',
+ }}>
+ {/* Keyboard texture lines */}
+ <div style={{
+ position: 'absolute',
+ top: '30%', left: '8%', right: '8%', height: '40%',
+ background: 'repeating-linear-gradient(90deg, rgba(0,0,0,0.12) 0px, rgba(0,0,0,0.12) 1px, transparent 1px, transparent 5px)',
+ borderRadius: '1px',
+ }} />
+ {/* Trackpad */}
+ <div style={{
+ position: 'absolute',
+ bottom: '12%', left: '35%', right: '35%', height: '28%',
+ borderRadius: '1px',
+ background: 'rgba(0,0,0,0.10)',
+ border: '0.5px solid rgba(0,0,0,0.15)',
+ }} />
+ </div>
+ </div>
+ </div>
+ ) : (
(() => {
// Usar el offset de Three.js para que la thumbnail coincida con el canvas
const phoneOffset = PREVIEW_TO_PHONE_OFFSET[config.id];
const previewRx = (phoneOffset?.rx ?? 0) + NRX; // total = NRX + userOffset
- const previewRy = (phoneOffset?.ry ?? 0) + NRY;
- const cssRy = -previewRy; // invertir para CSS
+ const previewRy = (phoneOffset?.ry ?? 0) + NRY; // CSS y Three.js comparten convención (+Y = left forward)
return (
<div style={{
perspective: `${Math.round((config.perspective || 600) * 0.55)}px`,
perspectiveOrigin: 'center center',
}}>
<div style={{
- transform: `rotateX(${previewRx}deg) rotateY(${cssRy}deg)`,
+ transform: `rotateX(${previewRx}deg) rotateY(${previewRy}deg)`,
transformStyle: 'preserve-3d',
transition: 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)',
width: 53,
@@ -227,6 +302,7 @@ export function PhotoEditorPlaceholder({
</div>
);
})()
+ )
) : (
<div
style={{ perspective: `${config.perspective || 600}px`, perspectiveOrigin: 'center center' }}
@@ -290,16 +366,20 @@ export function PhotoEditorPlaceholder({
</PopoverHeader>
<div className="space-y-4">
- <SliderControl
- icon="mdi:cube-outline"
- label={t("photoPreview.custom.perspective")}
- value={customConfig.perspective || 600}
- min={200}
- max={1000}
- step={50}
- onChange={(value) => updateCustomConfig({ perspective: value })}
- suffix="px"
- />
+ {!imagePhoneActive && (
+ <SliderControl
+ icon="mdi:cube-outline"
+ label={t("photoPreview.custom.perspective")}
+ value={customConfig.perspective || 600}
+ min={200}
+ max={1000}
+ step={50}
+ onChange={(value) => {
+ updateCustomConfig({ perspective: value });
+ }}
+ suffix="px"
+ />
+ )}
<SliderControl
icon="mdi:resize"
@@ -308,7 +388,10 @@ export function PhotoEditorPlaceholder({
min={50}
max={150}
step={5}
- onChange={(value) => updateCustomConfig({ scale: value / 100 })}
+ onChange={(value) => {
+ updateCustomConfig({ scale: value / 100 });
+ if (imagePhoneActive) setImagePhoneScale(value / 100);
+ }}
suffix="%"
/>
@@ -328,7 +411,7 @@ export function PhotoEditorPlaceholder({
updateCustomConfig({ rotateY: rY, rotateX: rX });
if (imagePhoneActive) {
setImagePhoneRotX(rX);
- setImagePhoneRotY(-rY);
+ setImagePhoneRotY(rY);
}
}}
>
@@ -337,7 +420,7 @@ export function PhotoEditorPlaceholder({
<div className="h-full w-px bg-white/5 absolute" />
</div>
<div
- className={`absolute w-2.5 h-2.5 rounded-full bg-gradient-primary shadow-[0_0_10px_rgba(0,163,255,0.5)]`}
+ className={`absolute w-2.5 h-2.5 rounded-full bg-cyan-500 shadow-[0_0_10px_rgba(0,163,255,0.5)]`}
style={{
left: `${50 + (-customConfig.rotateY / 45) * 50}%`,
top: `${50 + (customConfig.rotateX / 45) * 50}%`,
@@ -355,7 +438,10 @@ export function PhotoEditorPlaceholder({
min={-45}
max={45}
step={5}
- onChange={(value) => updateCustomConfig({ rotateZ: value })}
+ onChange={(value) => {
+ updateCustomConfig({ rotateZ: value });
+ if (imagePhoneActive) setImagePhoneRotZ(value);
+ }}
suffix="°"
/>
@@ -364,9 +450,12 @@ export function PhotoEditorPlaceholder({
label={t("photoPreview.custom.vertical")}
value={customConfig.translateY}
min={-10}
- max={10}
+ max={100}
step={1}
- onChange={(value) => updateCustomConfig({ translateY: value })}
+ onChange={(value) => {
+ updateCustomConfig({ translateY: value });
+ if (imagePhoneActive) setImagePhoneY(value);
+ }}
suffix="%"
/>
</div>
@@ -385,6 +474,14 @@ export function PhotoEditorPlaceholder({
};
setCustomConfig(resetConfig);
if (selectedPreviewId === "custom") onSelectPreview?.(resetConfig);
+ if (imagePhoneActive) {
+ setImagePhoneRotX(0);
+ setImagePhoneRotY(0);
+ setImagePhoneRotZ(0);
+ setImagePhonePerspective(600);
+ setImagePhoneScale(0.9);
+ setImagePhoneY(0);
+ }
}}
className="w-full mt-4 px-3 py-2 rounded-lg bg-white/5 hover:bg-white/10 text-[11px] text-white/60 hover:text-white transition-all flex items-center justify-center gap-2 border border-white/5"
>
@@ -452,6 +549,14 @@ export function PhotoEditorPlaceholder({
perspective: 600
};
setCustomConfig(defaultCustom);
+ if (imagePhoneActive) {
+ setImagePhoneRotX(0);
+ setImagePhoneRotY(0);
+ setImagePhoneRotZ(0);
+ setImagePhonePerspective(600);
+ setImagePhoneScale(0.9);
+ setImagePhoneY(0);
+ }
onReset?.();
}}
>
diff --git a/app/components/ui/editor/ToolsSidebar.tsx b/app/components/ui/editor/ToolsSidebar.tsx
index fec40c6..28b88d4 100644
--- a/app/components/ui/editor/ToolsSidebar.tsx
+++ b/app/components/ui/editor/ToolsSidebar.tsx
@@ -7,7 +7,7 @@ import type { EditorMode } from "@/types/editor-mode.types";
import { useRef, useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import { TooltipAction } from "@/components/ui/tooltip-action";
-import { useRecording } from "@/hooks/RecordingContext";
+import { useRecording } from "@/app/contexts/RecordingContext";
import RecordingSetupDialog from "../RecordingSetupDialog";
interface ExtendedToolsSidebarProps extends ToolsSidebarProps {
@@ -260,19 +260,22 @@ export function ToolsSidebar({
videoSrc: "/videos/preview-mockup.mp4"
}}
/>
-
- <SidebarTool
- icon="mage:box-3d"
- label={t("tools.motion")}
- isActive={activeTool === "motion"}
- onClick={() => onToolChange("motion")}
- popover={{
- title: t("popovers.motion.title"),
- description: t("popovers.motion.description"),
- videoSrc: "/videos/preview-motion.mp4"
- }}
- />
-
+ {isPhotoMode && (
+ <SidebarTool
+ icon="mage:box-3d"
+ label={t("tools.motion")}
+ isActive={activeTool === "motion"}
+ onClick={() => onToolChange("motion")}
+ popover={{
+ title: t("popovers.motion.title"),
+ description: t("popovers.motion.description"),
+ videoSrc: "/videos/preview-motion.mp4"
+ }}
+ 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 0356b42..2707fdd 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -25,10 +25,7 @@ import DropImage from "@/components/ui/DropImage";
import { LayersPanel } from "./LayersPanel";
import { Icon } from "@iconify/react";
import { useMotionContext } from "@/app/contexts/MotionContext";
-
-// Phone3DViewer render canvas dimensions (must match Phone3DViewer.tsx RENDER_W/H)
-const PHONE_RENDER_W = 595;
-const PHONE_RENDER_H = 765;
+import { PHONE_H, PHONE_W } from "@/lib/phone3d.utils";
export type { VideoCanvasHandle, VideoCanvasProps };
@@ -37,6 +34,16 @@ const Phone3DViewer = dynamic(
{ ssr: false }
);
+const Laptop3DViewer = dynamic(
+ () => import("./Laptop3DViewer").then((m) => ({ default: m.Laptop3DViewer })),
+ { ssr: false }
+);
+
+const IPhone13ProMax3DViewer = dynamic(
+ () => import("./IPhone13ProMax3DViewer").then((m) => ({ default: m.IPhone13ProMax3DViewer })),
+ { ssr: false }
+);
+
export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({
activeTool: _activeTool,
isPlaying = false,
@@ -97,12 +104,14 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// Motion 3D phone overlay state (reads from shared MotionContext)
const {
- selectedTemplateId, motionDuration, motionImageUrl,
- motionIntensity, motionStyle, motionVariantId, motionAnimMode,
+ selectedTemplateId, motionImageUrl,
imagePhoneActive, imagePhoneX, imagePhoneY,
imagePhoneScale, setImagePhoneScale,
imagePhoneRotX, setImagePhoneRotX, imagePhoneRotY, setImagePhoneRotY,
- imagePhoneDevice, setImagePhoneDevice, imagePhonePresetId, setImagePhonePresetId
+ imagePhoneRotZ,
+ imagePhoneDevice, imagePhonePresetId,
+ imagePhoneOpening,
+ imagePhoneShadow, imagePhoneShadowColor
} = useMotionContext();
// Phone shows whenever a real template is selected AND we are in video mode
const motionActive = selectedTemplateId !== null && selectedTemplateId !== "none" && mediaType === "video";
@@ -110,14 +119,23 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// Ctrl+scroll zoom badge state for image phone overlay
const [imagePhoneZoomVisible, setImagePhoneZoomVisible] = useState(false);
const imagePhoneZoomTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Ref for the non-passive Ctrl+scroll wheel handler (React's onWheel is always passive).
+ // Updated each render so the closure always has the latest state values.
+ const ctrlScrollWheelRef = useRef<((e: WheelEvent) => void) | null>(null);
// WebGL canvas from image phone Phone3DViewer, captured via onMount prop for export
const imagePhoneCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ // Phone3DViewer API (e.g. renderAt) so we can re-render the WebGL canvas
+ // 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);
// Model URL for the active device
const PHONE_DEVICE_URLS: Record<string, string | undefined> = {
- phone: undefined,
+ phone: '/models/phone-gltf.glb',
iphone: '/models/iphone-15-pro-max.glb',
+ 'iphone-13-pro-max': '/models/apple_iphone_13_pro_max.glb',
samsung: '/models/samsung-galaxy-s25-ultra.glb',
+ laptop: '/models/mac-book.glb',
};
const imagePhoneModelUrl = PHONE_DEVICE_URLS[imagePhoneDevice];
@@ -275,6 +293,31 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const previewContainerRef = useRef<HTMLDivElement>(null);
const canvasWrapperRef = useRef<HTMLDivElement>(null);
+ // ── Non-passive Ctrl+scroll zoom for image phone overlay ──────────────
+ // React registers onWheel listeners as passive (React 17+), so calling
+ // e.preventDefault() inside onWheel silently fails and the browser logs:
+ // "Unable to preventDefault inside passive event listener invocation."
+ // Fix: update a ref each render (captures fresh state, no re-render cost)
+ // and attach a stable non-passive listener once via useEffect.
+ ctrlScrollWheelRef.current = (e: WheelEvent) => {
+ if (!e.ctrlKey || mediaType !== "image" || !imagePhoneActive) return;
+ e.preventDefault();
+ const next = Math.max(0.3, Math.min(3, imagePhoneScale * (e.deltaY < 0 ? 1.05 : 0.95)));
+ setImagePhoneScale(next);
+ setImagePhoneZoomVisible(true);
+ if (imagePhoneZoomTimerRef.current) clearTimeout(imagePhoneZoomTimerRef.current);
+ imagePhoneZoomTimerRef.current = setTimeout(() => setImagePhoneZoomVisible(false), 1200);
+ };
+ useEffect(() => {
+ const el = previewContainerRef.current;
+ if (!el) return;
+ // Stable wrapper delegates to the always-fresh ref
+ const handler = (e: WheelEvent) => ctrlScrollWheelRef.current?.(e);
+ el.addEventListener('wheel', handler, { passive: false });
+ return () => el.removeEventListener('wheel', handler);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []); // attach once — ctrlScrollWheelRef.current updated each render
+
// Compute canvas dimensions to fill available space while maintaining aspect ratio
const [canvasDimensions, setCanvasDimensions] = useState<{ width: number; height: number } | null>(null);
@@ -1134,8 +1177,13 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const pxScale = canvasWidth / domW;
const phoneCx = canvasWidth / 2 + imagePhoneX * pxScale;
const phoneCy = canvasHeight / 2 + imagePhoneY * pxScale;
- const drawW = PHONE_RENDER_W * imagePhoneScale * pxScale;
- const drawH = PHONE_RENDER_H * imagePhoneScale * pxScale;
+ const drawW = PHONE_W * imagePhoneScale * pxScale;
+ const drawH = PHONE_H * imagePhoneScale * pxScale;
+ // Re-render the WebGL canvas at the target export resolution
+ // to avoid the pixelation that comes from upscaling a 595×765
+ // buffer. The Phone3DViewer restores the buffer to preview size
+ // after this call so the on-screen preview is unaffected.
+ imagePhoneApiRef.current?.renderAt(drawW, drawH);
ctx.drawImage(phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH);
}
ctx.restore();
@@ -1651,7 +1699,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
<div ref={canvasWrapperRef} className="flex-1 flex items-center justify-center min-h-0 min-w-0 mx-4">
<div
ref={previewContainerRef}
- className={`relative shrink-0 transition-all duration-300 ${imagePhoneActive ? 'overflow-visible' : 'overflow-hidden'} ${mediaType === "image" && imageUrl
+ className={`relative shrink-0 transition-all duration-300 overflow-hidden ${mediaType === "image" && imageUrl
? ""
: "border border-white/20 rounded-xl"
}`}
@@ -1683,6 +1731,9 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
style={{
perspective: mediaType === "image" && imageTransform && apply3DToBackground ? `${imageTransform.perspective || 600}px` : 'none',
perspectiveOrigin: 'center center',
+ // Propagate overflow:visible so the 3D phone overlay in image mode
+ // is never clipped when the user rotates or drags it outside bounds.
+ overflow: 'hidden',
}}
>
{!(mediaType === "image" && apply3DToBackground) && (
@@ -1703,6 +1754,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
transition: mediaType === "image" && apply3DToBackground
? 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)'
: zoomTransform.isMoving ? `transform ${zoomTransform.transitionMs}ms linear` : `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
+ // Allow the 3D phone to overflow this layer when in image-phone mode
+ overflow: 'hidden',
}}
>
{/* FONDO 3D: Solo se renderiza aquí adentro cuando el modo imagen 3D está activo */}
@@ -1747,6 +1800,8 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
transformStyle: 'preserve-3d',
zIndex: isVideoSelected ? 101 : 2,
pointerEvents: 'none',
+ // Allow the 3D phone overlay to overflow when in image-phone mode
+ overflow: 'hidden',
}}
>
{/* Capa 2B: Video con padding, esquinas redondeadas y sombras */}
@@ -1764,7 +1819,9 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
...(mediaType === "image" && imageTransform && !apply3DToBackground ? {
perspective: `${imageTransform.perspective || 600}px`,
perspectiveOrigin: 'center center',
- } : {})
+ } : {}),
+ // Allow the 3D phone overlay to overflow this padding layer
+ overflow: imagePhoneActive ? 'visible' : 'hidden',
}}
>
<div
@@ -1960,7 +2017,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
setIsDraggingElement={setIsDraggingElement}
setIsDraggingElementRotation={setIsDraggingElementRotation}
elementDragStart={elementDragStart}
- layerZIndex={3}
+ layerZIndex={200}
elementCorners={elementCorners}
setElementCorners={setElementCorners}
editingTextId={editingTextId}
@@ -2031,38 +2088,15 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
}}
>
<Phone3DViewer
- videoElement={videoRef?.current ?? null}
- canvasElement={exportCanvasRef.current}
imageUrl={motionImageUrl}
- isPlaying={isPlaying}
- animDuration={motionDuration}
- intensity={motionIntensity}
- templateId={selectedTemplateId}
- motionStyle={motionStyle}
- variantId={motionVariantId}
- animMode={motionAnimMode}
+ initialRotationX={0}
+ initialRotationY={0}
+ initialRotationZ={0}
+ shadowIntensity={0}
+ shadowColor="#000000"
/>
</div>
- {/* Zoom level badge — appears briefly after scrolling */}
- <div
- className="absolute bottom-3 left-1/2 -translate-x-1/2 pointer-events-none select-none"
- style={{
- opacity: motionZoomVisible ? 1 : 0,
- transition: 'opacity 0.25s ease',
- zIndex: 10,
- }}
- >
- <div className="flex items-center gap-1.5 bg-black/70 backdrop-blur-sm text-white/90 text-[11px] font-medium px-2.5 py-1 rounded-full border border-white/10">
- <Icon
- icon="lucide:search"
- className="opacity-70"
- style={{ width: '10px', height: '10px' }}
- />
- {Math.round(motionZoomScale * 100)}%
- </div>
- </div>
-
{/* Ctrl+scroll hint — shown when zoom is at 100% */}
{motionZoomScale === 1 && !motionZoomVisible && (
<div className="absolute bottom-3 left-1/2 -translate-x-1/2 pointer-events-none select-none opacity-0 group-hover:opacity-100 transition-opacity">
@@ -2078,11 +2112,13 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
{mediaType === "image" && imagePhoneActive && (
<div
className="absolute inset-0 pointer-events-none"
- style={{ zIndex: 155 }}
+ style={{ zIndex: 155, overflow: "visible" }}
>
<div
- className="absolute"
+ 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%',
@@ -2090,50 +2126,73 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
transformOrigin: 'center center',
pointerEvents: 'auto',
userSelect: 'none',
- }}
- onWheel={(e) => {
- if (!e.ctrlKey) return;
- e.preventDefault();
- const next = Math.max(0.3, Math.min(3, imagePhoneScale * (e.deltaY < 0 ? 1.05 : 0.95)));
- setImagePhoneScale(next);
- setImagePhoneZoomVisible(true);
- if (imagePhoneZoomTimerRef.current) clearTimeout(imagePhoneZoomTimerRef.current);
- imagePhoneZoomTimerRef.current = setTimeout(() => setImagePhoneZoomVisible(false), 1200);
+ filter: imagePhoneShadow > 0 && imagePhoneDevice !== "laptop"
+ ? `drop-shadow(0px ${18 * imagePhoneShadow}px ${28 * imagePhoneShadow}px ${imagePhoneShadowColor})`
+ : "none",
}}
>
- <Phone3DViewer
- key={`${imagePhoneDevice}-${imagePhonePresetId}`}
- imageUrl={imageUrl}
- isPlaying={false}
- animDuration={0}
- intensity={0}
- templateId="phone"
- motionStyle="normal"
- animMode="static"
- keepRotation={true}
- initialRotationX={imagePhoneRotX}
- initialRotationY={imagePhoneRotY}
- modelUrl={imagePhoneModelUrl}
- onRotationChange={(rx, ry) => {
- setImagePhoneRotX(rx);
- setImagePhoneRotY(ry);
- }}
- onMount={(canvas) => { imagePhoneCanvasRef.current = canvas; }}
- />
- </div>
-
- {/* Zoom badge */}
- {imagePhoneZoomVisible && (
- <div className="absolute bottom-3 left-1/2 -translate-x-1/2 pointer-events-none select-none" style={{ zIndex: 10 }}>
- <div className="flex items-center gap-1.5 bg-black/70 backdrop-blur-sm text-white/90 text-[11px] font-medium px-2.5 py-1 rounded-full border border-white/10">
- <Icon icon="lucide:search" className="opacity-70" style={{ width: '10px', height: '10px' }} />
- {Math.round(imagePhoneScale * 100)}%
- </div>
+ <div style={{ position: "relative", zIndex: 50 }} className="top-50">
+ <EditorHoverTooltip show={isVideoHovered && mediaType === "image"} />
</div>
- )}
+
+ {imagePhoneDevice === "laptop" ? (
+ <Laptop3DViewer
+ key={`laptop-${imagePhonePresetId}`}
+ imageUrl={imageUrl}
+ openingProgress={imagePhoneOpening}
+ imageMaskConfig={imageMaskConfig}
+ initialRotationX={imagePhoneRotX}
+ initialRotationY={imagePhoneRotY}
+ initialRotationZ={imagePhoneRotZ}
+ onRotationChange={(rx, ry) => {
+ setImagePhoneRotX(rx);
+ setImagePhoneRotY(ry);
+ }}
+ onMount={(canvas) => { imagePhoneCanvasRef.current = canvas; }}
+ onApi={(api) => { imagePhoneApiRef.current = api; }}
+ scale={1}
+ zoom={1}
+ shadowIntensity={imagePhoneShadow}
+ shadowColor={imagePhoneShadowColor}
+ />
+ ) : imagePhoneDevice === "iphone-13-pro-max" ? (
+ <IPhone13ProMax3DViewer
+ imageUrl={imageUrl}
+ imageMaskConfig={imageMaskConfig}
+ initialRotationX={imagePhoneRotX}
+ initialRotationY={imagePhoneRotY}
+ onRotationChange={(rx, ry) => { setImagePhoneRotX(rx); setImagePhoneRotY(ry); }}
+ onMount={(canvas) => { imagePhoneCanvasRef.current = canvas; }}
+ onApi={(api) => { imagePhoneApiRef.current = api; }}
+ scale={1}
+ zoom={1}
+ shadowIntensity={imagePhoneShadow}
+ shadowColor={imagePhoneShadowColor}
+ />
+ ) : (
+ <Phone3DViewer
+ key={`${imagePhoneDevice}-${imagePhonePresetId}`}
+ imageUrl={imageUrl}
+ imageMaskConfig={imageMaskConfig}
+ initialRotationX={imagePhoneRotX}
+ initialRotationY={imagePhoneRotY}
+ initialRotationZ={imagePhoneRotZ}
+ modelUrl={imagePhoneModelUrl}
+ scale={1}
+ zoom={1}
+ shadowIntensity={imagePhoneShadow}
+ shadowColor={imagePhoneShadowColor}
+ onRotationChange={(rx, ry) => {
+ setImagePhoneRotX(rx);
+ setImagePhoneRotY(ry);
+ }}
+ onMount={(canvas) => { imagePhoneCanvasRef.current = canvas; }}
+ onApi={(api) => { imagePhoneApiRef.current = api; }}
+ />
+ )}
+ </div>
</div>
)}
-
</div>
{/* End perspective wrapper div */}
{(isDraggingElement && (alignmentGuides.vertical.length > 0 || alignmentGuides.horizontal.length > 0)) && (
diff --git a/app/components/ui/editor/templates-motion/Phone.tsx b/app/components/ui/editor/templates-motion/Phone.tsx
index 0d2c1fa..5cac091 100644
--- a/app/components/ui/editor/templates-motion/Phone.tsx
+++ b/app/components/ui/editor/templates-motion/Phone.tsx
@@ -1,402 +1,10 @@
"use client";
-import gsap from "gsap";
import { Icon } from "@iconify/react";
import { useMotionContext } from "@/app/contexts/MotionContext";
import { useState, useEffect } from "react";
-import { STYLE_CFG, NRX, NRY } from "@/lib/animation-core";
-import type { ScriptFn, EditorPanelProps, MotionTemplate, MotionStyle, AnimMode } from "@/types/motion.types";
-
-// ─── Internal variant type ────────────────────────────────────────────────────
-interface CameraVariant {
- id: string;
- label: string;
- description: string;
- icon: string;
- /** Suggested default animMode for this variant */
- defaultAnimMode: AnimMode;
- /** Duration in ms for the entry animation */
- entryDuration: number;
- /** Duration in ms for the exit animation */
- exitDuration: number;
- /** Entry: dramatic pose → REST (NRX/NRY). Must end at REST. */
- entryScript: ScriptFn;
- /** Exit: REST (NRX/NRY) → dramatic pose. */
- exitScript: ScriptFn;
- /** Kept for backwards compat with one-shot preview */
- script: ScriptFn;
-}
-// POSE DE REPOSO COMPARTIDA — todos terminan aquí (ligeramente más girado que showcase)
-// showcase usa: { rx: NRX + 15*a, ry: -35*a, tx: 30*a, ty: -10*a, sc: 0.92 }
-// todos los demás usan: { rx: NRX + 15*a, ry: -42*a, tx: 33*a, ty: -10*a, sc: 0.92 }
-
-// ─── LOOPS SCRIPTS ────────────────────────────────────────────────────────────
-
-const sweepScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp, e1, e2, e3 } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX + 18 * a, ry: -58 * a, tx: 36 * a, ty: -14 * a, sc: 0.95, duration: c * 0.12, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.04, duration: c * 0.22, ease: e2, onUpdate })
- .to(av, { rx: NRX + 14 * a, ry: NRY - 50 * a, tx: 36 * a, ty: -18 * a, sc: 0.98, duration: c * 0.20, ease: e3, onUpdate })
- .to(av, { rx: NRX + 6 * a, ry: NRY + 32 * a, tx: -24 * a, ty: 10 * a, sc: 1.02, duration: c * 0.20, ease: e3, onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.26, ease: "power3.in", onUpdate });
-};
-
-// 1. HERO REVEAL (Respeta tu pose personalizada: ry: 50*a)
-const heroRevealScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp, e1, e2 } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: 50 * a, tx: 33 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX + 18 * a, ry: -58 * a, tx: 36 * a, ty: -14 * a, sc: 0.90, duration: c * 0.10, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 10 * a, ry: -28 * a, tx: 14 * a, ty: 6 * a, sc: 0.94, duration: c * 0.16, ease: "power3.out", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.00, duration: c * 0.18, ease: e1, onUpdate })
- .to(av, { rx: NRX - 4 * a, ry: NRY + 8 * a, tx: -3 * a, ty: -5 * a, sc: 1.00, duration: c * 0.18, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 6 * a, ry: NRY - 30 * a, tx: 18 * a, ty: -10 * a, sc: 0.97, duration: c * 0.16, ease: e2, onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: 50 * a, tx: 33 * a, ty: 4 * a, sc: 1.00, duration: c * 0.22, ease: "power3.in", onUpdate });
-};
-
-// 2. ORBIT (Ajustado para no achicarse tanto)
-const orbitScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp, e1, e2 } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 4 * a, ry: NRY + 10 * a, tx: -5 * a, ty: -4 * a, sc: 1.00, duration: c * 0.16, ease: e1, onUpdate })
- .to(av, { rx: NRX + 8 * a, ry: 62 * a, tx: -12 * a, ty: 6 * a, sc: 0.95, duration: c * 0.20, ease: e2, onUpdate })
- .to(av, { rx: NRX + 10 * a, ry: 66 * a, tx: -14 * a, ty: 8 * a, sc: 0.94, duration: c * 0.08, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.00, duration: c * 0.12, ease: e1, onUpdate })
- .to(av, { rx: NRX + 8 * a, ry: -62 * a, tx: 12 * a, ty: 6 * a, sc: 0.95, duration: c * 0.20, ease: e2, onUpdate })
- .to(av, { rx: NRX + 10 * a, ry: -66 * a, tx: 14 * a, ty: 8 * a, sc: 0.94, duration: c * 0.08, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.16, ease: "expo.out", onUpdate });
-};
-
-// 3. SHOWCASE
-const showcaseScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp, e1, e2 } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX + 18 * a, ry: -55 * a, tx: 35 * a, ty: -14 * a, sc: 0.90, duration: c * 0.12, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX, ry: 0, tx: 0, ty: 0, sc: 1.08, duration: c * 0.22, ease: e2, onUpdate })
- .to(av, { rx: NRX - 6 * a, ry: 6 * a, tx: -4 * a, ty: -8 * a, sc: 1.00, duration: c * 0.18, ease: "expo.out", onUpdate })
- .to(av, { rx: NRX - 4 * a, ry: 10 * a, tx: -6 * a, ty: -4 * a, sc: 1.00, duration: c * 0.15, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX - 20 * a, ry: 58 * a, tx: -38 * a, ty: 12 * a, sc: 0.88, duration: c * 0.18, ease: e1, onUpdate })
- .to(av, { rx: NRX - 22 * a, ry: 62 * a, tx: -40 * a, ty: 14 * a, sc: 0.87, duration: c * 0.08, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.07, ease: "power3.inOut", onUpdate });
-};
-
-// 4. STAGE ENTRY (Corregido zoom-out excesivo al entrar/rebotar)
-const stageEntryScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX + 18 * a, ry: -58 * a, tx: 36 * a, ty: -14 * a, sc: 0.90, duration: c * 0.08, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 6 * a, ry: NRY - 18 * a, tx: 0, ty: 50 * a, sc: 0.90, duration: c * 0.10, ease: "power2.in", onUpdate })
- .to(av, { rx: NRX + 3 * a, ry: NRY - 6 * a, tx: 0, ty: 16 * a, sc: 0.95, duration: c * 0.20, ease: "expo.out", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: -8 * a, sc: 1.05, duration: c * 0.12, ease: "back.out(1.8)", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.00, duration: c * 0.08, ease: "power2.out", onUpdate })
- .to(av, { rx: NRX - 5 * a, ry: NRY - 16 * a, tx: 8 * a, ty: -5 * a, sc: 1.00, duration: c * 0.18, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 4 * a, ry: NRY + 12 * a, tx: -6 * a, ty: 4 * a, sc: 1.00, duration: c * 0.14, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.10, ease: "power4.in", onUpdate });
-};
-
-// 5. TILT SHIFT
-const tiltShiftScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp, e1, e3 } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX + 20 * a, ry: -66 * a, tx: 40 * a, ty: -14 * a, sc: 0.93, duration: c * 0.16, ease: e3, onUpdate })
- .to(av, { rx: NRX, ry: 0, tx: 0, ty: 0, sc: 1.06, duration: c * 0.18, ease: e1, onUpdate })
- .to(av, { rx: NRX - 3 * a, ry: 5 * a, tx: 0, ty: -4 * a, sc: 1.00, duration: c * 0.10, ease: "expo.out", onUpdate })
- .to(av, { rx: NRX - 18 * a, ry: 62 * a, tx: -36 * a, ty: 10 * a, sc: 0.91, duration: c * 0.20, ease: e3, onUpdate })
- .to(av, { rx: NRX - 20 * a, ry: 66 * a, tx: -38 * a, ty: 12 * a, sc: 0.91, duration: c * 0.08, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.00, duration: c * 0.12, ease: e1, onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.16, ease: "power2.in", onUpdate });
-};
-
-// 6. GRAVITY DROP (Minimizado el salto hacia atrás)
-const gravityDropScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 4 * a, ry: NRY - 20 * a, tx: 0, ty: -100 * a, sc: 0.88, duration: c * 0.08, ease: "power2.in", onUpdate })
- .to(av, { rx: NRX + 4 * a, ry: NRY, tx: 0, ty: 16 * a, sc: 1.05, duration: c * 0.20, ease: "power3.in", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: -14 * a, sc: 1.00, duration: c * 0.10, ease: "power2.out", onUpdate })
- .to(av, { rx: NRX + 2 * a, ry: NRY, tx: 0, ty: 4 * a, sc: 1.00, duration: c * 0.06, ease: "power2.in", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: -2 * a, sc: 1.00, duration: c * 0.04, ease: "power2.out", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.00, duration: c * 0.06, ease: "power2.inOut", onUpdate })
- .to(av, { rx: NRX - 5 * a, ry: NRY - 16 * a, tx: 10 * a, ty: -6 * a, sc: 1.00, duration: c * 0.20, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 4 * a, ry: NRY + 12 * a, tx: -7 * a, ty: 5 * a, sc: 1.00, duration: c * 0.16, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.10, ease: "power4.in", onUpdate });
-};
-
-// 7. SIGNATURE (Respeta tu pose personalizada: ry: -45*a)
-const signatureScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp, e1, e2 } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -45 * a, tx: 12 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 4 * a, ry: NRY - 10 * a, tx: 5 * a, ty: -5 * a, sc: 1.00, duration: c * 0.16, ease: e1, onUpdate })
- .to(av, { rx: NRX - 4 * a, ry: NRY - 12 * a, tx: 6 * a, ty: -5 * a, sc: 1.00, duration: c * 0.16, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 4 * a, ry: NRY + 10 * a, tx: -5 * a, ty: 4 * a, sc: 1.00, duration: c * 0.16, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 10 * a, ry: 58 * a, tx: -14 * a, ty: 6 * a, sc: 0.88, duration: c * 0.16, ease: e2, onUpdate })
- .to(av, { rx: NRX + 12 * a, ry: 62 * a, tx: -16 * a, ty: 8 * a, sc: 0.87, duration: c * 0.10, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 4 * a, ry: 18 * a, tx: -4 * a, ty: 2 * a, sc: 0.96, duration: c * 0.12, ease: e1, onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -45 * a, tx: 12 * a, ty: 4 * a, sc: 1.00, duration: c * 0.14, ease: "expo.out", onUpdate });
-};
-
-// 8. CINEMATIC IN (Corregido achicamiento masivo sc:0.78 -> 0.92)
-const cinematicInScript: ScriptFn = (av, intensity, durMs, _style, onUpdate) => {
- const c = Math.min(durMs / 1000, 4.0);
- const a = intensity;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX + 8 * a, ry: -28 * a, tx: -18 * a, ty: -20 * a, sc: 0.92, duration: c * 0.40, ease: "power4.out", onUpdate })
- .to(av, { rx: NRX + 2 * a, ry: 0, tx: 0, ty: 0, sc: 1.06, duration: c * 0.30, ease: "expo.out", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: -3 * a, sc: 1.00, duration: c * 0.18, ease: "back.out(1.3)", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.12, ease: "sine.inOut", onUpdate });
-};
-
-// 9. CINEMATIC OUT (Corregido achicamiento masivo sc:0.58 -> 0.85)
-const cinematicOutScript: ScriptFn = (av, intensity, durMs, _style, onUpdate) => {
- const c = Math.min(durMs / 1000, 3.5);
- const a = intensity;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.00, duration: c * 0.18, ease: "power2.out", onUpdate })
- .to(av, { rx: NRX - 3 * a, ry: NRY - 6 * a, tx: 3 * a, ty: -4 * a, sc: 1.02, duration: c * 0.14, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX + 14 * a, ry: -52 * a, tx: -26 * a, ty: -72 * a, sc: 0.85, duration: c * 0.68, ease: "power3.in", onUpdate });
-};
-
-// ─── ENTRY / EXIT scripts ─────────────────────────────────────────────────────
-
-const heroRevealEntry: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000, { amp, e1 } = STYLE_CFG[style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -58 * a, tx: 36 * a, ty: 12 * a, sc: 1.00 })
- .to(av, { rx: NRX - 35 * a, ry: -28 * a, tx: 14 * a, ty: 6 * a, sc: 1.00, duration: c * 0.35, ease: "power3.out", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.00, duration: c * 0.35, ease: e1, onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: 50 * a, tx: 33 * a, ty: 4 * a, sc: 1.00, duration: c * 0.30, ease: "sine.out", onUpdate });
-};
-
-const heroRevealExit: ScriptFn = (av, intensity, durMs, _style, onUpdate) => {
- const c = durMs / 1000, { amp, e2 } = STYLE_CFG[_style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: 50 * a, tx: 33 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 30 * a, ry: -30 * a, tx: 18 * a, ty: -10 * a, sc: 1.00, duration: c * 0.45, ease: e2, onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -58 * a, tx: 36 * a, ty: 12 * a, sc: 1.00, duration: c * 0.55, ease: "power3.in", onUpdate });
-};
-const orbitEntry: ScriptFn = (av, intensity, durMs, _style, onUpdate) => {
- const c = durMs / 1000, { amp } = STYLE_CFG[_style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 30 * a, ry: -64 * a, tx: 14 * a, ty: 6 * a, sc: 1.00 })
- .to(av, { rx: NRX - 30 * a, ry: -28 * a, tx: 6 * a, ty: -4 * a, sc: 1.00, duration: c * 0.50, ease: "power2.out", onUpdate })
- .to(av, { rx: NRX, ry: -35 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.50, ease: "expo.out", onUpdate });
-};
-
-const orbitExit: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000, { amp } = STYLE_CFG[style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX, ry: -35 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 30 * a, ry: -40 * a, tx: -12 * a, ty: 5 * a, sc: 1.00, duration: c * 0.50, ease: "power2.in", onUpdate })
- .to(av, { rx: NRX - 30 * a, ry: 40 * a, tx: -18 * a, ty: 9 * a, sc: 0.95, duration: c * 0.50, ease: "power4.in", onUpdate });
-};
-
-
-const showcaseEntry: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000, { amp, e2 } = STYLE_CFG[style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 55 * a, ry: -55 * a, tx: 35 * a, ty: 12 * a, sc: 1.00 })
- .to(av, { rx: NRX, ry: 0, tx: 0, ty: 0, sc: 1.00, duration: c * 0.55, ease: e2, onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.45, ease: "expo.out", onUpdate });
-};
-
-const showcaseExit: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000, { amp, e1 } = STYLE_CFG[style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 30 * a, ry: -20 * a, tx: -36 * a, ty: 6 * a, sc: 1.00, duration: c * 0.55, ease: e1, onUpdate })
- .to(av, { rx: NRX - 20 * a, ry: 40 * a, tx: -44 * a, ty: 15 * a, sc: 0.95, duration: c * 0.45, ease: "power4.in", onUpdate });
-};
-const stageEntryEntry: ScriptFn = (av, intensity, durMs, _style, onUpdate) => {
- const c = durMs / 1000, { amp } = STYLE_CFG[_style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 55 * a, ry: -55 * a, tx: 35 * a, ty: 12 * a, sc: 1.00 })
- .to(av, { rx: NRX, ry: 0, tx: 0, ty: 0, sc: 1.00, duration: c * 0.55, ease: "power2.out", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.45, ease: "expo.out", onUpdate });
-};
-
-const stageEntryExit: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000, { amp } = STYLE_CFG[style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 30 * a, ry: -20 * a, tx: -36 * a, ty: 6 * a, sc: 1.00, duration: c * 0.55, ease: "power3.in", onUpdate })
- .to(av, { rx: NRX - 20 * a, ry: 40 * a, tx: -44 * a, ty: 15 * a, sc: 0.95, duration: c * 0.45, ease: "power4.in", onUpdate });
-};
-
-const tiltShiftEntry: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp, e1 } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX + 20 * a, ry: -66 * a, tx: 40 * a, ty: -14 * a, sc: 0.93 })
- .to(av, { rx: NRX, ry: 0, tx: 0, ty: 0, sc: 1.06, duration: c * 0.55, ease: e1, onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.45, ease: "expo.out", onUpdate });
-};
-
-const tiltShiftExit: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000;
- const { amp, e3 } = STYLE_CFG[style];
- const a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 18 * a, ry: 62 * a, tx: -36 * a, ty: 10 * a, sc: 0.91, duration: c * 0.55, ease: e3, onUpdate })
- .to(av, { rx: NRX - 20 * a, ry: 76 * a, tx: -46 * a, ty: 14 * a, sc: 0.88, duration: c * 0.45, ease: "power4.in", onUpdate });
-};
-
-const gravityDropEntry: ScriptFn = (av, intensity, durMs, _style, onUpdate) => {
- const c = durMs / 1000, { amp } = STYLE_CFG[_style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 45 * a, ry: NRY - 20 * a, tx: 0, ty: -100 * a, sc: 1.00 })
- .to(av, { rx: NRX - 30 * a, ry: NRY, tx: 0, ty: 16 * a, sc: 1.00, duration: c * 0.45, ease: "power3.in", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: -35 * a, sc: 1.00, duration: c * 0.55, ease: "expo.out", onUpdate });
-};
-
-const gravityDropExit: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000, { amp } = STYLE_CFG[style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: -35 * a, sc: 1.00 })
- .to(av, { rx: NRX - 30 * a, ry: NRY - 12 * a, tx: 0, ty: -36 * a, sc: 0.92, duration: c * 0.40, ease: "power2.in", onUpdate })
- .to(av, { rx: NRX - 45 * a, ry: NRY - 20 * a, tx: 0, ty: -100 * a, sc: 0.85, duration: c * 0.60, ease: "power4.in", onUpdate });
-};
-
-const signatureEntry: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000, { amp, e1 } = STYLE_CFG[style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 55 * a, ry: -60 * a, tx: 16 * a, ty: 12 * a, sc: 1.00 })
- .to(av, { rx: NRX - 40 * a, ry: -35 * a, tx: 8 * a, ty: 6 * a, sc: 1.00, duration: c * 0.45, ease: "power2.out", onUpdate })
- .to(av, { rx: NRX, ry: NRY, tx: 0, ty: 0, sc: 1.00, duration: c * 0.35, ease: "back.out(1.2)", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -45 * a, tx: 12 * a, ty: 4 * a, sc: 1.00, duration: c * 0.20, ease: "power3.out", onUpdate });
-};
-
-const signatureExit: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- const c = durMs / 1000, { amp, e2 } = STYLE_CFG[style], a = intensity * amp;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -45 * a, tx: 12 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 30 * a, ry: -20 * a, tx: -14 * a, ty: 6 * a, sc: 1.00, duration: c * 0.50, ease: e2, onUpdate })
- .to(av, { rx: NRX - 20 * a, ry: 40 * a, tx: -30 * a, ty: 15 * a, sc: 0.95, duration: c * 0.50, ease: "power4.in", onUpdate });
-};
-const cinematicInEntry: ScriptFn = (av, intensity, durMs, _style, onUpdate) => {
- const c = Math.min(durMs / 1000, 4.0), a = intensity;
- return gsap.timeline()
- .set(av, { rx: NRX - 55 * a, ry: -55 * a, tx: 35 * a, ty: 12 * a, sc: 1.00 })
- .to(av, { rx: NRX - 35 * a, ry: -28 * a, tx: 14 * a, ty: 6 * a, sc: 1.00, duration: c * 0.40, ease: "power4.out", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: 0, tx: 0, ty: 0, sc: 1.06, duration: c * 0.30, ease: "expo.out", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: NRY, tx: 0, ty: -3 * a, sc: 1.00, duration: c * 0.18, ease: "back.out(1.3)", onUpdate })
- .to(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00, duration: c * 0.12, ease: "sine.inOut", onUpdate });
-};
-
-const cinematicOutExit: ScriptFn = (av, intensity, durMs, _style, onUpdate) => {
- const c = Math.min(durMs / 1000, 3.5), a = intensity;
- return gsap.timeline()
- .set(av, { rx: NRX - 38 * a, ry: -50 * a, tx: 30 * a, ty: 4 * a, sc: 1.00 })
- .to(av, { rx: NRX - 35 * a, ry: NRY - 6 * a, tx: 3 * a, ty: -4 * a, sc: 1.02, duration: c * 0.18, ease: "sine.inOut", onUpdate })
- .to(av, { rx: NRX - 20 * a, ry: 40 * a, tx: -44 * a, ty: 15 * a, sc: 0.95, duration: c * 0.82, ease: "power3.in", onUpdate });
-};
-
-// ─── Variant registry ─────────────────────────────────────────────────────────
-
-export const DEFAULT_VARIANT_ID = "heroReveal";
-
-export const CAMERA_VARIANTS: CameraVariant[] = [
- {
- id: "heroReveal", label: "Hero Reveal", description: "Entrada lateral, pausa al frente, loop suave",
- icon: "ph:sparkle-bold", defaultAnimMode: "entry+exit",
- entryDuration: 2800, exitDuration: 1800,
- entryScript: heroRevealEntry, exitScript: heroRevealExit, script: heroRevealScript,
- },
- {
- id: "orbit", label: "Orbit", description: "Gira de cara a cara por ambos laterales",
- icon: "ph:arrows-clockwise-bold", defaultAnimMode: "entry+exit",
- entryDuration: 2400, exitDuration: 1600,
- entryScript: orbitEntry, exitScript: orbitExit, script: orbitScript,
- },
- {
- id: "showcase", label: "Showcase", description: "Dos poses con giro entre ellas — look Stripe",
- icon: "ph:intersect-bold", defaultAnimMode: "entry+exit",
- entryDuration: 2200, exitDuration: 1800,
- entryScript: showcaseEntry, exitScript: showcaseExit, script: showcaseScript,
- },
- {
- id: "stageEntry", label: "Stage Entry", description: "Aparece desde abajo con bounce, de cara siempre",
- icon: "ph:rocket-launch-bold", defaultAnimMode: "entry",
- entryDuration: 2500, exitDuration: 1500,
- entryScript: stageEntryEntry, exitScript: stageEntryExit, script: stageEntryScript,
- },
- {
- id: "tiltShift", label: "Tilt Shift", description: "Inclinaciones profundas — muestra los laterales",
- icon: "ph:arrows-left-right-bold", defaultAnimMode: "entry+exit",
- entryDuration: 2000, exitDuration: 1600,
- entryScript: tiltShiftEntry, exitScript: tiltShiftExit, script: tiltShiftScript,
- },
- {
- id: "gravityDrop", label: "Gravity Drop", description: "Caída física con rebote natural",
- icon: "ph:arrow-fat-down-bold", defaultAnimMode: "entry",
- entryDuration: 2200, exitDuration: 1400,
- entryScript: gravityDropEntry, exitScript: gravityDropExit, script: gravityDropScript,
- },
- {
- id: "signature", label: "Signature", description: "Drift suave + lateral lento, look brand",
- icon: "ph:seal-bold", defaultAnimMode: "entry+exit",
- entryDuration: 3200, exitDuration: 2200,
- entryScript: signatureEntry, exitScript: signatureExit, script: signatureScript,
- },
- {
- id: "cinematicIn", label: "Cinematic In", description: "Entrada cinematográfica desde arriba lateral",
- icon: "ph:film-slate-bold", defaultAnimMode: "entry",
- entryDuration: 3500, exitDuration: 1800,
- entryScript: cinematicInEntry, exitScript: cinematicOutExit, script: cinematicInScript,
- },
- {
- id: "cinematicOut", label: "Cinematic Out", description: "Pausa al frente y sale hacia arriba lateral",
- icon: "ph:arrow-fat-line-right-bold", defaultAnimMode: "exit",
- entryDuration: 2500, exitDuration: 2800,
- entryScript: cinematicInEntry, exitScript: cinematicOutExit, script: cinematicOutScript,
- },
-];
-
-// ─── Resolve the active script from a variant ID ──────────────────────────────
-export function resolvePhoneScript(variantId: string): ScriptFn {
- return CAMERA_VARIANTS.find((v) => v.id === variantId)?.script ?? sweepScript;
-}
-
-// The exported ScriptFn used by Phone3DViewer — reads variant from context
-// via a closure: the context value is passed in at call-site in PhoneTemplate.
-export const phoneScript: ScriptFn = (av, intensity, durMs, style, onUpdate) => {
- // Default — Phone3DViewer calls this; the variant-aware version is built below.
- return sweepScript(av, intensity, durMs, style, onUpdate);
-};
-
-// ─── Easing picker ────────────────────────────────────────────────────────────
-const EASING_OPTIONS: { id: MotionStyle; label: string; path: string }[] = [
- { id: "smooth", label: "Suave", path: "M 0 48 C 16 44 32 4 48 0" },
- { id: "normal", label: "Normal", path: "M 0 48 C 12 36 36 12 48 0" },
- { id: "cinematic", label: "Cine", path: "M 0 48 C 2 46 6 2 48 0" },
-];
+import type { EditorPanelProps, MotionTemplate, AnimMode } from "@/types/motion.types";
+import { CAMERA_VARIANTS, DEFAULT_VARIANT_ID, EASING_OPTIONS, phoneScript } from "@/lib/motion.utils";
function EasingPicker() {
const { motionStyle, setMotionStyle } = useMotionContext();
@@ -598,8 +206,8 @@ export function PhoneEditorPanel({ template }: EditorPanelProps) {
<SectionHeader label="Animación" />
<div className="grid grid-cols-4 gap-1">
{(["entry", "exit", "entry+exit", "none"] as AnimMode[]).map((m) => {
- const labels: Record<AnimMode, string> = { "entry": "Entrada", "exit": "Salida", "entry+exit": "Ambas", "none": "Ninguna" };
- const icons: Record<AnimMode, string> = { "entry": "ph:arrow-line-down-bold", "exit": "ph:arrow-line-up-bold", "entry+exit": "ph:arrows-vertical-bold", "none": "ph:minus-bold" };
+ const labels: Record<AnimMode, string> = { "entry": "Entrada", "exit": "Salida", "entry+exit": "Ambas", "none": "Ninguna", "static": "Estática" };
+ const icons: Record<AnimMode, string> = { "entry": "ph:arrow-line-down-bold", "exit": "ph:arrow-line-up-bold", "entry+exit": "ph:arrows-vertical-bold", "none": "ph:minus-bold", "static": "ph:pause-bold" };
const active = motionAnimMode === m;
return (
<button
diff --git a/app/components/ui/home/RecordingSteps.tsx b/app/components/ui/home/RecordingSteps.tsx
index d204df1..e1da618 100644
--- a/app/components/ui/home/RecordingSteps.tsx
+++ b/app/components/ui/home/RecordingSteps.tsx
@@ -3,7 +3,7 @@ import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Icon } from "@iconify/react";
import StepRow from "./StepRow";
-import { useRecording } from "@/hooks/RecordingContext";
+import { useRecording } from "@/app/contexts/RecordingContext";
import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
import RecordingSetupDialog from "../RecordingSetupDialog";
import { useTranslations } from "next-intl";
diff --git a/app/contexts/MotionContext.tsx b/app/contexts/MotionContext.tsx
index 1108b7a..2b23539 100644
--- a/app/contexts/MotionContext.tsx
+++ b/app/contexts/MotionContext.tsx
@@ -1,6 +1,6 @@
"use client";
-import { createContext, useContext, useState, type ReactNode } from "react";
+import { createContext, useCallback, useContext, useRef, useState, type ReactNode } from "react";
import type { MotionStyle, AnimMode } from "@/types/motion.types";
interface MotionState {
@@ -45,11 +45,36 @@ interface MotionState {
setImagePhoneRotX: (v: number) => void;
imagePhoneRotY: number;
setImagePhoneRotY: (v: number) => void;
- /** Which 3D device model is active: the default phone JSON, iPhone 15 Pro Max or Samsung S25 Ultra */
- imagePhoneDevice: 'phone' | 'iphone' | 'samsung';
- setImagePhoneDevice: (d: 'phone' | 'iphone' | 'samsung') => void;
+ /** Z-axis rotation (degrees) for the phone mockup */
+ imagePhoneRotZ: number;
+ setImagePhoneRotZ: (v: number) => void;
+ /** Perspective (px) for the 3D transform on the phone mockup */
+ imagePhonePerspective: number;
+ setImagePhonePerspective: (v: number) => void;
+ /** Which 3D device model is active: the default phone JSON, iPhone 15 Pro Max, Samsung S25 Ultra, or single macOS laptop */
+ imagePhoneDevice: 'phone' | 'iphone' | 'iphone-13-pro-max' | 'samsung' | 'laptop';
+ setImagePhoneDevice: (d: 'phone' | 'iphone' | 'iphone-13-pro-max' | 'samsung' | 'laptop') => void;
imagePhonePresetId: string;
setImagePhonePresetId: (id: string) => void;
+ /** Laptop opening animation progress (0 = closed, 1 = fully open) */
+ imagePhoneOpening: number;
+ setImagePhoneOpening: (v: number) => void;
+ /** Drop-shadow intensity for the active device mockup (0 = no shadow, 1 = full) */
+ imagePhoneShadow: number;
+ setImagePhoneShadow: (v: number) => void;
+ /** Drop-shadow color (CSS color string) */
+ imagePhoneShadowColor: string;
+ setImagePhoneShadowColor: (v: string) => void;
+ /** Undo the last motion transform change. Returns true if there was something to undo. */
+ undoMotion: () => boolean;
+ /** Redo a previously-undone motion transform change. Returns true if there was something to redo. */
+ redoMotion: () => boolean;
+ /** Push the current motion transform state to the undo history. */
+ pushHistory: () => void;
+ /** True when there is at least one entry in the motion undo stack. */
+ canUndoMotion: boolean;
+ /** True when there is at least one entry in the motion redo stack. */
+ canRedoMotion: boolean;
}
const MotionContext = createContext<MotionState | null>(null);
@@ -70,8 +95,83 @@ export function MotionProvider({ children }: { children: ReactNode }) {
const [imagePhoneScale, setImagePhoneScale] = useState(1);
const [imagePhoneRotX, setImagePhoneRotX] = useState(0);
const [imagePhoneRotY, setImagePhoneRotY] = useState(0);
- const [imagePhoneDevice, setImagePhoneDevice] = useState<'phone' | 'iphone' | 'samsung'>('phone');
-const [imagePhonePresetId, setImagePhonePresetId] = useState('front');
+ const [imagePhoneRotZ, setImagePhoneRotZ] = useState(0);
+ const [imagePhonePerspective, setImagePhonePerspective] = useState(600);
+ const [imagePhoneDevice, setImagePhoneDevice] = useState<'phone' | 'iphone' | 'iphone-13-pro-max' | 'samsung' | 'laptop'>('phone');
+ const [imagePhonePresetId, setImagePhonePresetId] = useState('front');
+ const [imagePhoneOpening, setImagePhoneOpening] = useState(1);
+ const [imagePhoneShadow, setImagePhoneShadow] = useState(0.6);
+ 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;
+ rx: number; ry: number; rz: number;
+ opening: number; shadow: number; shadowColor: string;
+ }>;
+ future: Array<{
+ x: number; y: number; scale: number;
+ rx: number; ry: number; rz: number;
+ opening: number; shadow: number; shadowColor: string;
+ }>;
+ }>({ 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);
+
+ const refreshCanFlags = () => {
+ setCanUndoMotion(historyRef.current.past.length > 0);
+ setCanRedoMotion(historyRef.current.future.length > 0);
+ };
+
+ const pushHistory = () => {
+ historyRef.current.past.push({
+ x: imagePhoneX, y: imagePhoneY, scale: imagePhoneScale,
+ rx: imagePhoneRotX, ry: imagePhoneRotY, rz: imagePhoneRotZ,
+ opening: imagePhoneOpening, shadow: imagePhoneShadow, shadowColor: imagePhoneShadowColor,
+ });
+ if (historyRef.current.past.length > MAX_HISTORY) historyRef.current.past.shift();
+ historyRef.current.future = [];
+ refreshCanFlags();
+ };
+
+ const undoMotion = useCallback(() => {
+ const past = historyRef.current.past;
+ if (past.length === 0) return false;
+ historyRef.current.future.push({
+ x: imagePhoneX, y: imagePhoneY, scale: imagePhoneScale,
+ rx: imagePhoneRotX, ry: imagePhoneRotY, rz: imagePhoneRotZ,
+ opening: imagePhoneOpening, shadow: imagePhoneShadow, shadowColor: imagePhoneShadowColor,
+ });
+ const snap = past.pop()!;
+ setImagePhoneX(snap.x); setImagePhoneY(snap.y); setImagePhoneScale(snap.scale);
+ setImagePhoneRotX(snap.rx); setImagePhoneRotY(snap.ry); setImagePhoneRotZ(snap.rz);
+ setImagePhoneOpening(snap.opening); setImagePhoneShadow(snap.shadow); setImagePhoneShadowColor(snap.shadowColor);
+ refreshCanFlags();
+ return true;
+ }, [imagePhoneX, imagePhoneY, imagePhoneScale, imagePhoneRotX, imagePhoneRotY, imagePhoneRotZ, imagePhoneOpening, imagePhoneShadow, imagePhoneShadowColor]);
+
+ const redoMotion = useCallback(() => {
+ const future = historyRef.current.future;
+ if (future.length === 0) return false;
+ historyRef.current.past.push({
+ x: imagePhoneX, y: imagePhoneY, scale: imagePhoneScale,
+ rx: imagePhoneRotX, ry: imagePhoneRotY, rz: imagePhoneRotZ,
+ opening: imagePhoneOpening, shadow: imagePhoneShadow, shadowColor: imagePhoneShadowColor,
+ });
+ const snap = future.pop()!;
+ setImagePhoneX(snap.x); setImagePhoneY(snap.y); setImagePhoneScale(snap.scale);
+ setImagePhoneRotX(snap.rx); setImagePhoneRotY(snap.ry); setImagePhoneRotZ(snap.rz);
+ setImagePhoneOpening(snap.opening); setImagePhoneShadow(snap.shadow); setImagePhoneShadowColor(snap.shadowColor);
+ refreshCanFlags();
+ return true;
+ }, [imagePhoneX, imagePhoneY, imagePhoneScale, imagePhoneRotX, imagePhoneRotY, imagePhoneRotZ, imagePhoneOpening, imagePhoneShadow, imagePhoneShadowColor]);
+
return (
<MotionContext.Provider value={{
selectedTemplateId, setSelectedTemplateId,
@@ -87,8 +187,16 @@ const [imagePhonePresetId, setImagePhonePresetId] = useState('front');
imagePhoneScale, setImagePhoneScale,
imagePhoneRotX, setImagePhoneRotX,
imagePhoneRotY, setImagePhoneRotY,
+ imagePhoneRotZ, setImagePhoneRotZ,
+ imagePhonePerspective, setImagePhonePerspective,
imagePhoneDevice, setImagePhoneDevice,
- imagePhonePresetId, setImagePhonePresetId
+ imagePhonePresetId, setImagePhonePresetId,
+ imagePhoneOpening, setImagePhoneOpening,
+ imagePhoneShadow, setImagePhoneShadow,
+ imagePhoneShadowColor, setImagePhoneShadowColor,
+ undoMotion, redoMotion, pushHistory,
+ canUndoMotion,
+ canRedoMotion,
}}>
{children}
</MotionContext.Provider>