Skip to content

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

fix: update motion menu

CristianOlivera1a3bddb844ed2
diff --git a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
index 9fd97e3..dbf9c1b 100644
--- a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
+++ b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
@@ -20,6 +20,7 @@ import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import {
createCoverScreenCanvas,
+ parseShadowColor,
type ImageMaskConfigLike,
} from "@/lib/phone3d.utils";
@@ -120,21 +121,25 @@ function ModelScene({
imageMaskConfig,
initialRotationX,
initialRotationY,
+ initialRotationZ,
onRotationChange,
rootRef,
cameraRef,
zoom,
onApi,
+ onLoaded,
}: {
imageUrl: string | null;
imageMaskConfig: ImageMaskConfigLike | null;
initialRotationX: number;
initialRotationY: number;
+ initialRotationZ: number;
onRotationChange?: (rx: number, ry: number) => void;
rootRef: React.MutableRefObject<THREE.Group | null>;
cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
zoom: number;
onApi?: (api: IPhone13ProMax3DApi | null) => void;
+ onLoaded?: () => void;
}) {
const gltf = useGLTF("/models/apple_iphone_13_pro_max.glb") as unknown as {
nodes: GLTFNodes;
@@ -145,6 +150,7 @@ function ModelScene({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const orbitRef = useRef<any>(null);
const lastLoadedImageUrlRef = useRef<string | null>(null);
+ const lastLoadedMaskKeyRef = useRef<string | null>(null);
const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | null>(null);
useEffect(() => {
@@ -165,12 +171,21 @@ function ModelScene({
const mat = wallpaperMatRef.current;
if (!mat) return;
+ // Serializa el mask para detectar cambios. Si el mask cambia,
+ // la textura debe regenerarse aunque la imagen no cambie.
+ const maskKey = imageMaskConfig ? JSON.stringify(imageMaskConfig) : null;
+
if (!imageUrl) {
if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }
lastLoadedImageUrlRef.current = null;
+ lastLoadedMaskKeyRef.current = null;
return;
}
- if (lastLoadedImageUrlRef.current === imageUrl) return;
+ // Skip solo si la imagen Y el mask no cambiaron
+ if (
+ lastLoadedImageUrlRef.current === imageUrl &&
+ lastLoadedMaskKeyRef.current === maskKey
+ ) return;
const img = new Image();
img.crossOrigin = "anonymous";
@@ -189,12 +204,26 @@ function ModelScene({
mat.map = tex;
mat.needsUpdate = true;
lastLoadedImageUrlRef.current = imageUrl;
+ lastLoadedMaskKeyRef.current = maskKey;
+ onLoaded?.();
+ };
+ img.onerror = () => {
+ // Even on error, hide the loader so the user sees the device
+ // (with the original iOS wallpaper) instead of a permanent spinner.
+ onLoaded?.();
};
img.src = imageUrl;
- }, [imageUrl, imageMaskConfig]);
+ }, [imageUrl, imageMaskConfig, onLoaded]);
useEffect(() => {
- // Microtask delay para asegurar que OrbitControls ya está montado
+ // Reposiciona OrbitControls cuando cambian initialRotationX/Y.
+ // Permite que el crosshair "Rotation XY" del popup Custom del
+ // PhotoEditorPlaceholder mueva la cámara en tiempo real.
+ // NO interfiere con el drag del usuario porque:
+ // - El drag llama onEnd al TERMINAR, no en cada frame
+ // - El setFromSphericalCoords es determinístico: la posición
+ // calculada desde los props ES la misma que el drag dejó
+ // (mismo phi/theta/radius), así que no hay "salto"
const id = setTimeout(() => {
const orbit = orbitRef.current;
if (!orbit) return;
@@ -206,7 +235,19 @@ function ModelScene({
orbit.update();
}, 0);
return () => clearTimeout(id);
- }, []);
+ }, [initialRotationX, initialRotationY, zoom]);
+
+ // Sync initialRotationZ → group rotation.z (mismo patrón que Laptop3DViewer).
+ // Permite que el slider "Rotation Z" del popup Custom del
+ // PhotoEditorPlaceholder se refleje en el modelo. NO interfiere
+ // con el drag de OrbitControls (que solo afecta X/Y vía la cámara),
+ // así que es seguro ejecutar este useEffect en cada cambio de prop.
+ useEffect(() => {
+ const root = rootRef.current;
+ if (root) {
+ root.rotation.z = initialRotationZ * (Math.PI / 180);
+ }
+ }, [initialRotationZ]);
return (
<>
@@ -235,7 +276,6 @@ function ModelScene({
/>
<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" />
@@ -278,13 +318,98 @@ function ModelScene({
);
}
+// ─── CanvasWithLoader ────────────────────────────────────────────────────────
+// Owns its own `loaded` state. Remounting via `key={imageUrl}` is the
+// idiomatic React way to reset state when the image changes — no
+// cascading setState in useEffect.
+function CanvasWithLoader({
+ imageUrl,
+ imageMaskConfig,
+ initialRotationX,
+ initialRotationY,
+ initialRotationZ,
+ onRotationChange,
+ rootRef,
+ cameraRef,
+ zoom,
+ onApi,
+ onMount,
+}: {
+ imageUrl: string | null;
+ imageMaskConfig: ImageMaskConfigLike | null;
+ initialRotationX: number;
+ initialRotationY: number;
+ initialRotationZ: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ rootRef: React.MutableRefObject<THREE.Group | null>;
+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
+ zoom: number;
+ onApi?: (api: IPhone13ProMax3DApi | null) => void;
+ onMount?: (canvas: HTMLCanvasElement) => void;
+}) {
+ const [loaded, setLoaded] = useState(false);
+
+ return (
+ <>
+ <Canvas
+ style={{ width: "100%", height: "100%", overflow: "visible" }}
+ gl={{
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ powerPreference: "high-performance",
+ // Permite software rendering si la GPU no soporta WebGL2 —
+ // evita "Context Lost" en hardware limitado.
+ failIfMajorPerformanceCaveat: false,
+ }}
+ // dpr=2: balance entre nitidez y consumo de VRAM. dpr=4
+ // saturaba la GPU junto con el GLB pesado del iPhone 13
+ // Pro Max + Environment HDR y causaba "Context Lost".
+ dpr={2}
+ onCreated={({ gl, scene }) => {
+ gl.outputColorSpace = THREE.SRGBColorSpace;
+ gl.toneMapping = THREE.NeutralToneMapping;
+ gl.toneMappingExposure = 1.0;
+ scene.environmentIntensity = 1.6;
+ onMount?.(gl.domElement);
+ }}
+ >
+ <ModelScene
+ imageUrl={imageUrl}
+ imageMaskConfig={imageMaskConfig}
+ initialRotationX={initialRotationX}
+ initialRotationY={initialRotationY}
+ initialRotationZ={initialRotationZ}
+ onRotationChange={onRotationChange}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ zoom={zoom}
+ onApi={onApi}
+ onLoaded={() => setLoaded(true)}
+ />
+ </Canvas>
+
+ {/* Loader — covers the white wallpaper texture while the
+ user's image is being decoded. */}
+ {!loaded && (
+ <div
+ className="absolute inset-0 flex items-center justify-center pointer-events-none"
+ style={{ zIndex: 4 }}
+ >
+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
+ </div>
+ )}
+ </>
+ );
+}
+
// ─── Componente público ──────────────────────────────────────────────────────
export function IPhone13ProMax3DViewer({
imageUrl = null,
imageMaskConfig = null,
initialRotationX = -58.23,
initialRotationY = -29.82,
- initialRotationZ: _initialRotationZ = 0,
+ initialRotationZ = 0,
onRotationChange,
onMount,
onApi,
@@ -304,13 +429,6 @@ export function IPhone13ProMax3DViewer({
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;
@@ -324,6 +442,7 @@ export function IPhone13ProMax3DViewer({
transform: `scale(${scale})`,
width: 480,
height: 1000 + (hasShadow ? computedBlur * 0.8 : 0),
+ marginTop: "200px"
}}
>
@@ -370,35 +489,20 @@ export function IPhone13ProMax3DViewer({
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>
+ <CanvasWithLoader
+ key={imageUrl ?? "no-image"}
+ imageUrl={imageUrl}
+ imageMaskConfig={imageMaskConfig}
+ initialRotationX={initialRotationX}
+ initialRotationY={initialRotationY}
+ initialRotationZ={initialRotationZ}
+ onRotationChange={onRotationChange}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ zoom={zoom}
+ onApi={onApi}
+ onMount={onMount}
+ />
</div>
</div>
</div>
diff --git a/app/components/ui/editor/Laptop3DViewer.tsx b/app/components/ui/editor/Laptop3DViewer.tsx
index 2b87a99..94e538c 100644
--- a/app/components/ui/editor/Laptop3DViewer.tsx
+++ b/app/components/ui/editor/Laptop3DViewer.tsx
@@ -20,6 +20,7 @@ import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import {
createCoverScreenCanvas,
+ parseShadowColor,
type ImageMaskConfigLike,
} from "@/lib/phone3d.utils";
@@ -94,15 +95,6 @@ function rxRyFromCamera(camPos: THREE.Vector3): { rx: number; ry: number } {
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,
diff --git a/app/components/ui/editor/MotionMenu.tsx b/app/components/ui/editor/MotionMenu.tsx
index 9bc898f..85e07c1 100644
--- a/app/components/ui/editor/MotionMenu.tsx
+++ b/app/components/ui/editor/MotionMenu.tsx
@@ -4,73 +4,12 @@ import { useState } from "react";
import { Icon } from "@iconify/react";
import { useMotionContext } from "@/app/contexts/MotionContext";
import { MotionTemplate } from "@/types/motion.types";
-import { TemplateEditorShell } from "../TemplateEditorShell";
-import { TEMPLATES } from "@/lib/template-registry";
-
-// ─── Template card (thumbnail + title) ───────────────────────────────────────
-function TemplateCard({
- template,
- isActive,
- onClick,
-}: {
- template: MotionTemplate;
- isActive: boolean;
- onClick: () => void;
-}) {
- return (
- <div className="relative">
- <button
- type="button"
- onClick={onClick}
- className="group flex h-full w-full flex-col overflow-hidden rounded-2xl border border-white/[0.06] bg-[#17171a] text-left transition-all duration-300 hover:border-white/20 active:scale-[0.98]"
- >
- {/* Thumbnail placeholder */}
- <div className="relative aspect-video w-full shrink-0 bg-[#0d0d10]">
- <div
- className="absolute inset-0"
- style={{
- background: `linear-gradient(135deg, ${template.accentColor}18 0%, transparent 70%)`,
- }}
- />
- <div className="absolute inset-0 flex items-center justify-center">
- <Icon icon={template.icon} width="20" style={{ color: `${template.accentColor}60` }} />
- </div>
- </div>
-
- <div className="border-t border-white/[0.05] bg-[#111113] px-4 py-3">
- <h3 className="truncate text-sm font-medium text-white">{template.title}</h3>
- </div>
- </button>
-
- {/* Active ring */}
- {isActive && (
- <div
- className="pointer-events-none absolute inset-0 rounded-2xl"
- style={{
- boxShadow: `0 0 0 2px ${template.accentColor}`,
- border: `1px solid ${template.accentColor}55`,
- }}
- />
- )}
- </div>
- );
-}
// ─── MotionMenu ───────────────────────────────────────────────────────────────
export function MotionMenu() {
const { selectedTemplateId, setSelectedTemplateId, setMotionDuration } = useMotionContext();
const [openTemplate, setOpenTemplate] = useState<MotionTemplate | null>(null);
- // If a template with an editor is open, render the editor shell
- if (openTemplate) {
- return (
- <TemplateEditorShell
- template={openTemplate}
- onBack={() => setOpenTemplate(null)}
- />
- );
- }
-
const handleClick = (template: MotionTemplate) => {
if (!template.showPhone) {
// "Solo video" — deactivate immediately, no editor
@@ -91,20 +30,13 @@ export function MotionMenu() {
<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/[0.06]">
- Templates
+ Animaciones
</span>
</div>
{/* Grid */}
<div className="grid grid-cols-2 gap-4 items-start">
- {TEMPLATES.map((t) => (
- <TemplateCard
- key={t.id}
- template={t}
- isActive={selectedTemplateId === t.id}
- onClick={() => handleClick(t)}
- />
- ))}
+
</div>
</div>
);
diff --git a/app/components/ui/editor/Phone3DViewer.tsx b/app/components/ui/editor/Phone3DViewer.tsx
index 8dc8928..e2fb340 100644
--- a/app/components/ui/editor/Phone3DViewer.tsx
+++ b/app/components/ui/editor/Phone3DViewer.tsx
@@ -38,6 +38,7 @@ import {
loadGltfGroup,
cloneGroup,
type ImageMaskConfigLike,
+ parseShadowColor,
} from "@/lib/phone3d.utils";
export interface Phone3DApi {
@@ -62,14 +63,6 @@ interface Props {
const DEFAULT_CAM_Z = 1.5;
-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)})`;
-}
-
function SharedLights() {
return (
<>
@@ -99,6 +92,7 @@ interface SceneProps {
onRotationChange?: (rx: number, ry: number) => void;
onApi?: (api: Phone3DApi | null) => void;
modelUrl?: string;
+ onLoaded?: () => void;
}
// ─── GltfModelScene — iphone 15 / samsung / iphone-13 ────────────────────────
@@ -112,6 +106,7 @@ function GltfModelScene({
onRotationChange,
onApi,
modelUrl,
+ onLoaded,
}: SceneProps) {
const rootRef = useRef<THREE.Group>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -135,24 +130,37 @@ function GltfModelScene({
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;
+ // requestAnimationFrame difiere la creación del CanvasTexture
+ // al próximo frame para no bloquear el render actual ni
+ // forzar una subida síncrona de píxeles a la GPU.
+ requestAnimationFrame(() => {
+ const TARGET_W = 2048;
+ const TARGET_H = Math.round(TARGET_W / deviceConfig.aspectRatio);
+ const cornerRadius = Math.round(TARGET_W * deviceConfig.cornerRadiusFactor);
+ const cover = createCoverScreenCanvas(img, TARGET_W, TARGET_H, cornerRadius, imageMaskConfigRef.current);
+ if (mat.map) { mat.map.dispose(); mat.map = null; }
+ const tex = new THREE.CanvasTexture(cover);
+ tex.flipY = true;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.wrapS = THREE.ClampToEdgeWrapping;
+ tex.wrapT = THREE.ClampToEdgeWrapping;
+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();
+ mat.map = tex;
+ mat.color.set(0xffffff);
+ mat.needsUpdate = true;
+ lastLoadedUrlRef.current = url;
+ });
+ };
+ img.onerror = () => {
+ // Imagen inválida: libera cualquier textura previa y deja el
+ // material con su color base (gris oscuro) en lugar del quad
+ // blanco del navegador.
+ if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }
+ mat.color.set(0x111111);
+ lastLoadedUrlRef.current = url; // evita reintento
};
img.src = url;
}, [deviceConfig, gl]);
@@ -193,6 +201,8 @@ function GltfModelScene({
applyTexture(mat, imageUrlRef.current);
}
+ onLoaded?.();
+
// Microtask: OrbitControls is guaranteed mounted by R3F before this runs
Promise.resolve().then(() => {
const orbit = orbitRef.current;
@@ -292,6 +302,7 @@ function DefaultPhoneModelScene({
zoom,
onRotationChange,
onApi,
+ onLoaded,
}: Omit<SceneProps, "modelUrl">) {
const rootRef = useRef<THREE.Group>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -315,20 +326,29 @@ function DefaultPhoneModelScene({
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;
+ // requestAnimationFrame difiere la creación del CanvasTexture
+ // al próximo frame para no saturar la GPU.
+ requestAnimationFrame(() => {
+ const cover = createCoverScreenCanvas(img, TARGET_W, TARGET_H, 0, imageMaskConfigRef.current);
+ if (mat.map) { mat.map.dispose(); mat.map = null; }
+ const tex = new THREE.CanvasTexture(cover);
+ tex.flipY = false;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.wrapS = THREE.ClampToEdgeWrapping;
+ tex.wrapT = THREE.ClampToEdgeWrapping;
+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();
+ mat.map = tex;
+ mat.color.set(0xffffff);
+ mat.needsUpdate = true;
+ lastLoadedUrlRef.current = url;
+ });
+ };
+ img.onerror = () => {
+ if (mat.map) { mat.map.dispose(); mat.map = null; mat.needsUpdate = true; }
+ mat.color.set(0x111111);
lastLoadedUrlRef.current = url;
};
img.src = url;
@@ -382,6 +402,8 @@ function DefaultPhoneModelScene({
applyTexture(screenMatRef.current, imageUrlRef.current);
}
+ onLoaded?.();
+
Promise.resolve().then(() => {
const orbit = orbitRef.current;
if (!orbit) return;
@@ -519,7 +541,7 @@ export function Phone3DViewer({
transform: `scale(${scale})`,
width: PHONE_W,
height: PHONE_H + (hasShadow ? computedBlur * 0.8 : 0),
- marginTop: "150px",
+ marginTop: "220px",
marginLeft: "150px"
}}
>
@@ -561,38 +583,80 @@ export function Phone3DViewer({
onPointerUp={() => setGrabbing(false)}
onPointerLeave={() => setGrabbing(false)}
>
- <Canvas
+ <CanvasWithLoader
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>
+ isDefaultPhone={isDefaultPhone}
+ sceneProps={sceneProps}
+ onMount={onMount}
+ />
</div>
-
</div>
</div>
);
+}
+
+// ─── CanvasWithLoader ────────────────────────────────────────────────────────
+// Each instance owns its own `loaded` state. Remounting via `key` is the
+// idiomatic React way to reset state when modelUrl changes — no
+// cascading setState in useEffect.
+function CanvasWithLoader({
+ isDefaultPhone,
+ sceneProps,
+ onMount,
+}: {
+ isDefaultPhone: boolean;
+ sceneProps: SceneProps;
+ onMount?: (canvas: HTMLCanvasElement) => void;
+}) {
+ const [loaded, setLoaded] = useState(false);
+
+ return (
+ <>
+ <Canvas
+ style={{
+ width: "100%",
+ height: "100%",
+ overflow: "visible",
+ display: "block",
+ }}
+ gl={{
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ powerPreference: "high-performance",
+ // Permite software rendering si la GPU no soporta WebGL2 —
+ // reduce probabilidad de "Context Lost" en hardware limitado.
+ failIfMajorPerformanceCaveat: false,
+ }}
+ // dpr=2: balance entre nitidez y consumo de VRAM. dpr=4
+ // saturaba la GPU junto con los GLB pesados (iPhone 15, S25)
+ // y causaba "WebGLRenderer: Context Lost".
+ dpr={2}
+ onCreated={({ gl, scene: s }) => {
+ gl.outputColorSpace = THREE.SRGBColorSpace;
+ gl.toneMapping = THREE.NeutralToneMapping;
+ gl.toneMappingExposure = 1.0;
+ s.environmentIntensity = 1.6;
+ onMount?.(gl.domElement);
+ }}
+ >
+ {isDefaultPhone
+ ? <DefaultPhoneModelScene {...sceneProps} onLoaded={() => setLoaded(true)} />
+ : <GltfModelScene {...sceneProps} onLoaded={() => setLoaded(true)} />
+ }
+ </Canvas>
+
+ {/* Loader — covers the white screen plane while the GLB
+ and the user's image texture are loading on first mount.
+ Removed automatically via key remount on device switch. */}
+ {!loaded && (
+ <div
+ className="absolute inset-0 flex items-center justify-center pointer-events-none"
+ style={{ zIndex: 4 }}
+ >
+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
+ </div>
+ )}
+ </>
+ );
}
\ No newline at end of file
diff --git a/app/components/ui/editor/PhotoEditorPlaceholder.tsx b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
index 0deb94c..1d2f675 100644
--- a/app/components/ui/editor/PhotoEditorPlaceholder.tsx
+++ b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
@@ -306,7 +306,7 @@ export function PhotoEditorPlaceholder({
) : (
<div
style={{ perspective: `${config.perspective || 600}px`, perspectiveOrigin: 'center center' }}
- className="w-full h-full flex items-center justify-center p-3" /* Padding sutil */
+ className="w-full h-full flex items-center justify-center p-3"
>
<div
className="relative w-full h-full max-w-[92%] max-h-[92%] rounded-lg overflow-hidden border border-white/5 shadow-2xl"
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 2707fdd..a2119e5 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -2131,7 +2131,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
: "none",
}}
>
- <div style={{ position: "relative", zIndex: 50 }} className="top-50">
+ <div style={{ position: "relative", zIndex: 50 }} className="top-120">
<EditorHoverTooltip show={isVideoHovered && mediaType === "image"} />
</div>
@@ -2157,10 +2157,12 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
/>
) : imagePhoneDevice === "iphone-13-pro-max" ? (
<IPhone13ProMax3DViewer
+ key={`iphone-13-pro-max-${imagePhonePresetId}`}
imageUrl={imageUrl}
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; }}
diff --git a/lib/phone3d.utils.ts b/lib/phone3d.utils.ts
index 7c7641c..4db150f 100644
--- a/lib/phone3d.utils.ts
+++ b/lib/phone3d.utils.ts
@@ -207,4 +207,12 @@ export function cloneGroup(src: THREE.Group): THREE.Group {
/** Shortest arc in degrees from curRy to targetRy, result in [-180, 180] */
export function shortArc(curRy: number, targetRy: number): number {
return ((targetRy - curRy) % 360 + 540) % 360 - 180;
-}
\ No newline at end of file
+}
+
+export 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)})`;
+}