Create professional demos and 3D mockups in seconds, directly in your browser
feat: motion menu configurations and menu
CristianOlivera1e115a18e38f9
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsxindex 7a2957a..4a0c69a 100644--- a/app/[locale]/(editor)/editor/page.tsx+++ b/app/[locale]/(editor)/editor/page.tsx@@ -39,7 +39,9 @@ import { findValidFragmentPosition } from "@/app/components/ui/editor/ZoomFragmeimport { LoadingSpinner } from "@/components/ui/LoadingSpinner";import { TimelineSkeleton } from "@/app/components/ui/Skeleton";import { AudioTrimModal } from "@/app/components/ui/editor/AudioTrimModal";+import { useAuth } from "@/hooks/useAuth";import { VIDEO_Z_INDEX } from "@/lib/constants";+import { getWallpaperUrl } from "@/lib/wallpaper.utils";import Image from "next/image";import Link from "next/link";import { TooltipAction } from "@/components/ui/tooltip-action";@@ -55,6 +57,9 @@ export default function Editor() {// Editor mode (video/photo) from URL paramsconst { mode: editorMode, isVideoMode, isPhotoMode } = useEditorMode();+ // Auth — needed for building production-ready Recipe JSON+ const { user } = useAuth();+// Undo/Redo system - centralized state managementconst {state: editorState,@@ -1345,6 +1350,85 @@ export default function Editor() {const [videoBlob, setVideoBlob] = useState<Blob | null>(null);const handleExport = (quality: ExportQuality) => {+ // ── BACKEND TESTING: imprime el Recipe JSON completo en la consola ──+ // Para probar el backend: copia este JSON, reemplaza los campos+ // "storageKey" con el path real del video subido a Supabase Storage:+ // "source-videos/{tu-user-id}/{libraryVideoId}.mp4"+ console.log("=== RECIPE JSON PARA BACKEND (PRUEBAS) ===");+ const userId = user?.id ?? "USER-ID-NO-DISPONIBLE";+ const appOrigin = window.location.origin;+ console.log(JSON.stringify({+ quality,+ trim: trimRange.end > trimRange.start+ ? { start: trimRange.start, end: trimRange.end }+ : null,+ clips: videoClips.map(clip => ({+ id: clip.id,+ libraryVideoId: clip.libraryVideoId,+ storageKey: `source-videos/${userId}/${clip.libraryVideoId}.mp4`,+ name: clip.name,+ startTime: clip.startTime,+ trimStart: clip.trimStart,+ trimEnd: clip.trimEnd,+ duration: clip.trimEnd - clip.trimStart,+ hasAudio: clipAudioStateRef.current.get(clip.libraryVideoId) !== false,+ hasCamera: clip.hasCamera ?? false,+ })),+ muteOriginalAudio,+ masterVolume,+ videoHasAudioTrack,+ audioTracks: audioTracks.map(track => {+ const audio = uploadedAudios.find(a => a.id === track.audioId);+ return {+ audioId: track.audioId,+ audioStorageKey: `source-audios/${userId}/${track.audioId}`,+ name: audio?.name ?? track.name,+ startTime: track.startTime,+ duration: track.duration,+ trimStart: track.trimStart ?? 0,+ volume: track.volume,+ loop: track.loop,+ };+ }),+ backgroundTab,+ selectedWallpaper,+ // URL completa del wallpaper seleccionado (vacío si no se usa wallpaper)+ wallpaperUrl: backgroundTab === "wallpaper" && selectedWallpaper >= 0+ ? `${appOrigin}${getWallpaperUrl(selectedWallpaper)}`+ : null,+ backgroundBlur,+ // dataUrl si el usuario subió imagen propia | URL https si es Unsplash/Pexels | "" si no hay+ selectedImageUrl,+ backgroundColorConfig,+ aspectRatio,+ customDimensions,+ // Native video dimensions — used by the backend to compute output size when aspectRatio is 'auto'+ sourceDimensions: videoDimensions ?? null,+ cropArea,+ padding,+ roundedCorners,+ shadows,+ videoTransform,+ mockupId,+ mockupConfig,+ zoomFragments,+ canvasElements: canvasElements.map(el => {+ // Resolver imagePath de elementos built-in a URLs completas+ if (el.type === "image") {+ const imgEl = el as import("@/types/canvas-elements.types").ImageElement;+ if (imgEl.imagePath?.startsWith("/")) {+ return { ...el, imagePath: `${appOrigin}${imgEl.imagePath}` };+ }+ }+ return el;+ }),+ cameraConfig,+ cameraStorageKey: null,+ videoMaskConfig,+ }, null, 2));+ console.log("==========================================");+ // ── FIN BACKEND TESTING ──+isExportingRef.current = true;for (const audioEl of audioElementsRef.current.values()) {audioEl.pause();@@ -2797,6 +2881,7 @@ export default function Editor() {onDeleteImageProject={handleDeleteImageProject}onUploadImageToHistory={handleUploadImageToHistory}elementsTextTabTrigger={elementsTextTabTrigger}+ mediaType={isPhotoMode ? "image" : "video"}/></Suspense></motion.div>@@ -2830,6 +2915,8 @@ export default function Editor() {</AnimatePresence><VideoCanvas+ activeTool={activeTool}+ isPlaying={isPlaying}layersPanelToolbar={<EditorTopBaronExport={handleExport}diff --git a/app/[locale]/(editor)/layout.tsx b/app/[locale]/(editor)/layout.tsxindex b7d83db..30c0416 100644--- a/app/[locale]/(editor)/layout.tsx+++ b/app/[locale]/(editor)/layout.tsx@@ -3,14 +3,17 @@import { AuthProvider } from "@/hooks/useAuth";import { RecordingProvider } from "@/hooks/RecordingContext";import RecordingOverlay from "../../components/ui/RecordingOverlay";+import { MotionProvider } from "@/app/contexts/MotionContext";export default function EditorLayout({ children }: { children: React.ReactNode }) {return (<AuthProvider><RecordingProvider>- <div className="min-h-screen bg-neutral-950">- {children}- </div>+ <MotionProvider>+ <div className="min-h-screen bg-neutral-950">+ {children}+ </div>+ </MotionProvider><RecordingOverlay /></RecordingProvider></AuthProvider>diff --git a/app/components/ui/TemplateEditorShell.tsx b/app/components/ui/TemplateEditorShell.tsxnew file mode 100644index 0000000..9b94ee8--- /dev/null+++ b/app/components/ui/TemplateEditorShell.tsx@@ -0,0 +1,77 @@+"use client";++import { useEffect } from "react";+import { Icon } from "@iconify/react";+import { useMotionContext } from "@/app/contexts/MotionContext";+import { MotionTemplate } from "@/types/motion.types";++interface Props {+ template: MotionTemplate;+ onBack: () => void;+}++/**+ * Generic shell: header with back button + accent icon + scrollable body.+ * The template's own EditorPanel is rendered inside the body.+ * This component owns no editor state — it only activates the template+ * in context and delegates all controls to EditorPanel.+ */+export function TemplateEditorShell({ template, onBack }: Props) {+ const { setSelectedTemplateId, setMotionDuration, setMotionImageUrl } = useMotionContext();++ // Activate the template when the shell mounts+ useEffect(() => {+ setSelectedTemplateId(template.id);+ setMotionDuration(template.defaultDuration);+ setMotionImageUrl(null); // clear any previous image+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [template.id]);++ const EditorPanel = template.EditorPanel;++ return (+ <div className="flex flex-col h-full text-white">+ {/* ── Header ── */}+ <div className="flex items-center gap-2 px-3 py-2.5 border-b border-white/[0.06] shrink-0">+ <button+ onClick={onBack}+ className="flex items-center justify-center size-7 rounded-md hover:bg-white/6 text-white/50 hover:text-white/80 transition-colors"+ >+ <Icon icon="ph:arrow-left-bold" width="13" />+ </button>++ <div+ className="size-6 rounded-md flex items-center justify-center shrink-0"+ style={{+ backgroundColor: `${template.accentColor}20`,+ border: `1px solid ${template.accentColor}30`,+ }}+ >+ <Icon icon={template.icon} width="12" style={{ color: template.accentColor }} />+ </div>++ <div className="flex-1 min-w-0">+ <p className="text-xs font-semibold text-white/90 truncate leading-none">+ {template.title}+ </p>+ <p className="text-[9px] text-white/30 mt-0.5 truncate">+ {template.description}+ </p>+ </div>+ </div>++ {/* ── Body — template injects its own panel here ── */}+ <div className="flex-1 overflow-y-auto min-h-0 px-3 py-3 custom-scrollbar">+ {EditorPanel ? (+ <EditorPanel template={template} />+ ) : (+ // Fallback for templates that declare showPhone=true but have no EditorPanel yet+ <div className="flex items-center justify-center h-32 text-white/20 text-xs">+ Sin controles adicionales+ </div>+ )}+ <div className="h-4" />+ </div>+ </div>+ );+}\ No newline at end of filediff --git a/app/components/ui/editor/CanvasElementsLayer.tsx b/app/components/ui/editor/CanvasElementsLayer.tsxindex f70c2e3..d8ebf39 100644--- a/app/components/ui/editor/CanvasElementsLayer.tsx+++ b/app/components/ui/editor/CanvasElementsLayer.tsx@@ -7,7 +7,7 @@ import { useRef, useState, useEffect, useCallback } from "react";function InlineTextEditor({element,refSize,- onEnd,+ onEnd}: {element: TextElement;refSize: number;diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsxindex 6cf6e8a..63910a5 100644--- a/app/components/ui/editor/ControlPanel.tsx+++ b/app/components/ui/editor/ControlPanel.tsx@@ -40,6 +40,8 @@ const MockupMenu = lazy(() => import("./MockupMenu").then(mod => ({ default: modconst AudioMenu = lazy(() => import("./AudioMenu").then(mod => ({ default: mod.AudioMenu })));const VideosMenu = lazy(() => import("./VideosMenu").then(mod => ({ default: mod.VideosMenu })));const HistoryMenu = lazy(() => import("./HistoryMenu").then(mod => ({ default: mod.HistoryMenu })));+const MotionMenu = lazy(() => import("./MotionMenu").then(mod => ({ default: mod.MotionMenu })));+const ImageMotionMenu = lazy(() => import("./ImageMotionMenu").then(mod => ({ default: mod.ImageMotionMenu })));interface ExtendedControlPanelProps extends ControlPanelProps {onTogglePanel?: () => void;@@ -128,6 +130,7 @@ export function ControlPanel({onAddImageToCanvas,onDeleteImageProject,onUploadImageToHistory,+ mediaType = "video",}: ExtendedControlPanelProps) {const t = useTranslations("controlPanel");@@ -279,6 +282,12 @@ export function ControlPanel({</Suspense>)}+ {activeTool === "motion" && (+ <Suspense fallback={<MockupMenuSkeleton />}>+ {mediaType === "image" ? <ImageMotionMenu /> : <MotionMenu />}+ </Suspense>+ )}+{activeTool === "videos" && (<Suspense fallback={<VideosMenuSkeleton />}><VideosMenudiff --git a/app/components/ui/editor/ImageMotionMenu.tsx b/app/components/ui/editor/ImageMotionMenu.tsxnew file mode 100644index 0000000..afe3ecc--- /dev/null+++ b/app/components/ui/editor/ImageMotionMenu.tsx@@ -0,0 +1,306 @@+"use client";++import { useRef, useState } from "react";+import { Icon } from "@iconify/react";+import { useMotionContext } from "@/app/contexts/MotionContext";+import { SliderControl } from "../SliderControl";++const PAD_H = 130;+const X_HALF = 500;+const Y_HALF = 500;+const HANDLE_R = 9;++function PositionPad({+ x, y, onChangeX, onChangeY,+}: {+ x: number; y: number;+ onChangeX: (v: number) => void;+ onChangeY: (v: number) => void;+}) {+ const padRef = useRef<HTMLDivElement>(null);+ const dragging = useRef(false);+ const [isDraggingState, setIsDraggingState] = useState(false);++ // Forzamos límites matemáticos para los valores de X e Y+ const cx = Math.max(-X_HALF, Math.min(X_HALF, x));+ const cy = Math.max(-Y_HALF, Math.min(Y_HALF, y));++ // Calculamos las posiciones en porcentaje para que responda al ancho fluido de CSS+ const pctX = (cx + X_HALF) / (X_HALF * 2);+ const hy = ((cy + Y_HALF) / (Y_HALF * 2)) * PAD_H;++ const fromEvent = (e: React.PointerEvent) => {+ if (!padRef.current) return;++ const rect = padRef.current.getBoundingClientRect();+ const currentWidth = rect.width;++ const rx = Math.max(0, Math.min(currentWidth, e.clientX - rect.left));+ const ry = Math.max(0, Math.min(PAD_H, e.clientY - rect.top));++ onChangeX(Math.round((rx / currentWidth) * X_HALF * 2 - X_HALF));+ onChangeY(Math.round((ry / PAD_H) * Y_HALF * 2 - Y_HALF));+ };++ const handleReset = (e: React.PointerEvent) => {+ e.stopPropagation();+ onChangeX(0);+ onChangeY(0);+ };++ 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)]"+ style={{ height: PAD_H }}+ onPointerDown={(e) => {+ dragging.current = true;+ setIsDraggingState(true);+ (e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);+ fromEvent(e);+ }}+ onPointerMove={(e) => { if (dragging.current) fromEvent(e); }}+ onPointerUp={() => {+ dragging.current = false;+ setIsDraggingState(false);+ }}+ >+ <div className="absolute inset-0 pointer-events-none opacity-10 bg-[radial-gradient(#a1a1aa_1px,transparent_1px)] bg-size-[14px_14px]" />++ <div className="absolute top-0 bottom-0 w-px bg-gradient-to-b from-transparent via-white/10 to-transparent" style={{ left: '50%' }} />+ <div className="absolute left-0 right-0 h-px bg-gradient-to-r from-transparent via-white/10 to-transparent" style={{ top: '50%' }} />++ <div className="absolute pointer-events-none bg-white/5 transition-opacity" style={{ left: `calc(${pctX * 100}%)`, top: 0, bottom: 0, width: 1 }} />+ <div className="absolute pointer-events-none bg-white/5 transition-opacity" style={{ top: hy, left: 0, right: 0, height: 1 }} />++ <div+ className={`absolute bg-white border border-white/40 rounded-full shadow-[0_0_20px_4px_rgba(255,255,255,0.12),0_4px_12px_rgba(0,0,0,0.6)] mix-blend-screen flex items-center justify-center transition-all duration-75 pointer-events-auto ${+ isDraggingState ? "cursor-grabbing" : "cursor-grab"+ }`}+ style={{+ width: HANDLE_R * 2,+ height: HANDLE_R * 2,+ 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 = [+ {+ id: "none",+ title: "None",+ accentColor: "#555",+ icon: "ph:prohibit",+ },+ {+ id: "phone",+ title: "Phone",+ accentColor: "#00A3FF",+ icon: "ph:device-mobile-bold",+ modelUrl: undefined as string | undefined,+ },+ {+ id: "iphone",+ title: "iPhone 15 Pro",+ accentColor: "#A8A8B0",+ icon: "simple-icons:apple",+ modelUrl: "/models/iphone-15-pro-max.glb",+ },+ {+ id: "samsung",+ title: "Samsung S25",+ accentColor: "#1428A0",+ icon: "simple-icons:samsung",+ modelUrl: "/models/samsung-galaxy-s25-ultra.glb",+ },+] as const;++type ImageDeviceId = typeof IMAGE_DEVICE_TEMPLATES[number]["id"];++// ─── ImageMotionMenu ──────────────────────────────────────────────────────────+export function ImageMotionMenu() {+ const {+ imagePhoneActive, setImagePhoneActive,+ imagePhoneX, setImagePhoneX,+ imagePhoneY, setImagePhoneY,+ imagePhoneScale, setImagePhoneScale,+ setImagePhoneRotX, setImagePhoneRotY,+ imagePhoneDevice, setImagePhoneDevice,+ } = useMotionContext();++ const activeDeviceId: ImageDeviceId = imagePhoneActive ? imagePhoneDevice : "none";++ const handleDeviceClick = (id: ImageDeviceId) => {+ if (id === "none") {+ setImagePhoneActive(false);+ } else {+ setImagePhoneDevice(id);+ setImagePhoneActive(true);+ setImagePhoneX(0);+ setImagePhoneY(0);+ setImagePhoneScale(1);+ setImagePhoneRotX(0);+ setImagePhoneRotY(0);+ }+ };++ const handleReset = () => {+ setImagePhoneX(0);+ setImagePhoneY(0);+ setImagePhoneScale(1);+ setImagePhoneRotX(0);+ setImagePhoneRotY(0);+ };++ 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" />+ <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 */}+ <div className="grid grid-cols-2 gap-3 items-start">+ {IMAGE_DEVICE_TEMPLATES.map((tpl) => {+ const isActive = activeDeviceId === tpl.id;+ const isNone = tpl.id === "none";+ return (+ <div key={tpl.id} className="relative">+ <button+ type="button"+ onClick={() => handleDeviceClick(tpl.id)}+ className={`group flex h-full w-full flex-col overflow-hidden rounded-2xl border text-left transition-all duration-300 active:scale-[0.98] ${isActive+ ? "border-white/20 bg-[#1a1a1e]"+ : "border-white/6 bg-[#17171a] hover:border-white/20"+ }`}+ >+ <div className="relative aspect-video w-full shrink-0 bg-[#0d0d10]">+ <div+ className="absolute inset-0"+ style={{+ background: isActive+ ? `linear-gradient(135deg, ${tpl.accentColor}22 0%, transparent 70%)`+ : `linear-gradient(135deg, ${tpl.accentColor}10 0%, transparent 70%)`,+ }}+ />+ <div className="absolute inset-0 flex items-center justify-center">+ <Icon+ icon={tpl.icon}+ width="20"+ style={{ color: isActive ? `${tpl.accentColor}cc` : `${tpl.accentColor}55` }}+ />+ </div>+ {isActive && !isNone && (+ <div+ className="absolute top-1.5 right-1.5 size-4 rounded-full flex items-center justify-center"+ style={{ background: tpl.accentColor }}+ >+ <Icon icon="mdi:check-bold" width={9} className="text-white" />+ </div>+ )}+ </div>+ <div className="border-t border-white/5 bg-[#111113] px-3 py-2.5 flex items-center justify-between">+ <h3 className={`truncate text-xs font-semibold ${isActive ? "text-white" : "text-white/60"}`}>+ {tpl.title}+ </h3>+ {isActive && (+ <div+ className="size-1.5 rounded-full flex-shrink-0"+ style={{ background: tpl.accentColor }}+ />+ )}+ </div>+ </button>++ {isActive && (+ <div+ className="pointer-events-none absolute inset-0 rounded-2xl"+ style={{+ boxShadow: `0 0 0 1.5px ${tpl.accentColor}88`,+ }}+ />+ )}+ </div>+ );+ })}+ </div>++ {/* Config panel — shown when phone is active */}+ {imagePhoneActive && (+ <div className="flex flex-col gap-4 pt-2 border-t border-white/6">+ <div className="flex items-center justify-between">+ <span className="text-[10px] font-semibold text-white/50 uppercase tracking-wider">Configuración</span>+ <button+ type="button"+ onClick={handleReset}+ className="flex items-center gap-1 text-[11px] text-white/40 hover:text-white/80 transition-colors"+ >+ <Icon icon="lucide:rotate-ccw" width="11" />+ Resetear+ </button>+ </div>++ <SliderControl+ label="Escala"+ value={Math.round(imagePhoneScale * 100)}+ min={30}+ max={200}+ step={1}+ onChange={(v) => setImagePhoneScale(v / 100)}+ suffix="%"+ />++ <div className="flex flex-col gap-2">+ <span className="text-[10px] text-white/40 font-medium">Posición</span>+ <PositionPad+ x={imagePhoneX}+ y={imagePhoneY}+ onChangeX={setImagePhoneX}+ onChangeY={setImagePhoneY}+ />+ </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/LayersPanel.tsx b/app/components/ui/editor/LayersPanel.tsxindex fac59f6..866b485 100644--- a/app/components/ui/editor/LayersPanel.tsx+++ b/app/components/ui/editor/LayersPanel.tsx@@ -447,7 +447,7 @@ export function LayersPanel({}}data-layer-row="video-layer"className={[- "group relative flex items-center gap-1.5 h-7 px-2 rounded-md cursor-pointer select-none transition-all duration-100",+ "group relative flex items-center gap-1.5 h-7 px-2 rounded-md cursor-pointer select-none transition-all duration-100",isSelected? "bg-[#00A3FF]/15 text-white": "text-neutral-400 hover:bg-white/5 hover:text-neutral-200",diff --git a/app/components/ui/editor/MotionMenu.tsx b/app/components/ui/editor/MotionMenu.tsxnew file mode 100644index 0000000..9bc898f--- /dev/null+++ b/app/components/ui/editor/MotionMenu.tsx@@ -0,0 +1,111 @@+"use client";++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+ setSelectedTemplateId("none");+ setMotionDuration(0);+ return;+ }+ // Templates with phone open their own editor+ setOpenTemplate(template);+ };++ return (+ <div className="p-4 flex flex-col gap-5 w-full bg-[#111113] min-h-screen">+ {/* 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:film-strip-bold" width="16" className="text-blue-400" />+ <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+ </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>+ );+}\ No newline at end of filediff --git a/app/components/ui/editor/Phone3DViewer.tsx b/app/components/ui/editor/Phone3DViewer.tsxnew file mode 100644index 0000000..980894c--- /dev/null+++ b/app/components/ui/editor/Phone3DViewer.tsx@@ -0,0 +1,836 @@+"use client";++/**+ * Phone3DViewer+ *+ * 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.+ *+ * Phase machine:+ * idle → entry → hold → exit → done+ *+ * 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.+ */++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;+}++// ─── 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 */+ initialRotationX?: number;+ initialRotationY?: number;+ /** Called on pointer-up with final rotation offsets */+ 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 */+ modelUrl?: 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;+ }, []);++ // ── 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+ });++ // ── 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,+ });+ }++ const exitTl = variant.exitScript(av.current, i, exitDur, style, updateDOM);+ exitTl.repeat(0);+ exitMaster.add(exitTl, ">");++ exitMaster.eventCallback("onComplete", () => {+ if (alive()) phaseRef.current = "done";+ });++ masterTlRef.current = exitMaster;+ };++ // ── 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;+ }++ // Play the master (entry + snap → triggers onComplete → hold)+ phaseRef.current = "entry";+ masterTlRef.current = master;+ master.play();++ }, [stopAll, updateDOM]);++ // ── isPlaying effect ──────────────────────────────────────────────────────+ 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,+ });+ }+ }, [isPlaying, startMotion, stopAll, updateDOM]);++ // ── Variant / template change → smooth bridge transition ─────────────────+ const isFirstRender = useRef(true);+ 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]);++ // ── 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]);++ // ── 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);+ },+ });++ return () => {+ stopAll();+ gsap.killTweensOf(av.current);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ // ── 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) => {+ const group = cloneGroup(cached);+ 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;+ group.scale.setScalar(sf);+ group.position.multiplyScalar(sf);+ scene.add(group);+ phoneGroupRef.current = group;+ group.updateMatrixWorld(true);++ 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;+ }+ }+ });++ 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;+ }+ }+ }+ }++ 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();+ });+ }+ });+ }+ 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);+ }, []);++ 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,+ });+ }+ }, [updateDOM]);++ 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)",+ }}+ />++ {/* WebGL canvas */}+ <div+ ref={webglRef}+ style={{+ position: "absolute", left: RX, top: RY,+ width: RENDER_W, height: RENDER_H,+ pointerEvents: "none", zIndex: 2,+ }}+ />++ {/* Drag capture */}+ <div+ style={{ position: "absolute", inset: 0, zIndex: 3, cursor: dragging ? "grabbing" : "grab" }}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerLeave={onPointerUp}+ />++ {/* 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>+ </div>+ )}+ </div>+ );+}\ No newline at end of filediff --git a/app/components/ui/editor/PhotoEditorPlaceholder.tsx b/app/components/ui/editor/PhotoEditorPlaceholder.tsxindex 6b8daa5..4d4613d 100644--- a/app/components/ui/editor/PhotoEditorPlaceholder.tsx+++ b/app/components/ui/editor/PhotoEditorPlaceholder.tsx@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button";import { AspectRatioSelect } from "@/app/components/ui/AspectRatioSelect";import { TooltipAction } from "@/components/ui/tooltip-action";import { ImageMaskEditor } from "./ImageMaskEditor";+import { NRX, NRY } from "@/lib/animation-core";import {Popover,PopoverTrigger,@@ -15,7 +16,8 @@ import {PopoverHeader,PopoverTitle,} from "@/components/ui/popover";-import { PhotoEditorPlaceholderProps, Preview3DConfig, PREVIEW_CONFIGS } from "@/types/photo.types";+import { PhotoEditorPlaceholderProps, Preview3DConfig, PREVIEW_CONFIGS, PREVIEW_TO_PHONE_OFFSET } from "@/types/photo.types";+import { useMotionContext } from "@/app/contexts/MotionContext";export function PhotoEditorPlaceholder({className = "",@@ -32,11 +34,11 @@ export function PhotoEditorPlaceholder({onToggle3DBackground,imageMaskConfig,onImageMaskConfigChange,- imageTransform,onReset,}: PhotoEditorPlaceholderProps) {const previewImageUrl = staticImageUrl ?? canvasImageUrl;const t = useTranslations("editor");+ const { imagePhoneActive, setImagePhoneRotX, setImagePhoneRotY, setImagePhonePresetId } = useMotionContext();const [customConfig, setCustomConfig] = useState<Preview3DConfig>({id: "custom",label: "Custom",@@ -122,21 +124,27 @@ export function PhotoEditorPlaceholder({}onSelectPreview?.(config);if (isCustom) setIsCustomPopoverOpen(true);+ if (imagePhoneActive) {+ const offset = PREVIEW_TO_PHONE_OFFSET[config.id];+ if (offset) {+ setImagePhoneRotX(offset.rx);+ setImagePhoneRotY(offset.ry);+ setImagePhonePresetId(config.id);+ }+ }}}- className={`group relative shrink-0 w-32 sm:w-62 aspect-video squircle-element p-px transition-all duration-300 ease-out outline-none ${- isSelected- ? `shadow-[0_0_20px_rgba(0,163,255,0.15)]`- : isCustom && isCustomUntouched- ? "bg-gradient-radial-primary border border-dashed border-white/20 hover:border-white/40"- : "bg-white/10 hover:bg-white/20"- }`}+ className={`group relative shrink-0 w-32 sm:w-62 aspect-video squircle-element p-px transition-all duration-300 ease-out outline-none ${isSelected+ ? `shadow-[0_0_20px_rgba(0,163,255,0.15)]`+ : isCustom && isCustomUntouched+ ? "bg-gradient-radial-primary border border-dashed border-white/20 hover:border-white/40"+ : "bg-white/10 hover:bg-white/20"+ }`}aria-label={config.label}aria-pressed={isSelected}><div- className={`relative w-full h-full rounded-[10px] overflow-hidden transition-colors ${- isCustom && isCustomUntouched ? "bg-transparent" : "bg-black/90"- }`}+ className={`relative w-full h-full rounded-[10px] overflow-hidden transition-colors ${isCustom && isCustomUntouched ? "bg-transparent" : "bg-black/90"+ }`}>{(!isCustom || !isCustomUntouched) && (<div@@ -165,31 +173,86 @@ export function PhotoEditorPlaceholder({{t("photoPreview.custom.customize")}</div>)}- <div className="absolute inset-0 flex items-center justify-center p-2 z-10">- <div- style={{- perspective: `${config.perspective || 600}px`,- perspectiveOrigin: 'center center'- }}- className="w-full h-full flex items-center justify-center"- >+ {/* 3D preview: phone shape when phone active, CSS-transformed image otherwise */}+ <div className="absolute inset-0 flex items-center justify-center z-10">+ {imagePhoneActive ? (+ (() => {+ // 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+ return (+ <div style={{+ perspective: `${Math.round((config.perspective || 600) * 0.55)}px`,+ perspectiveOrigin: 'center center',+ }}>+ <div style={{+ transform: `rotateX(${previewRx}deg) rotateY(${cssRy}deg)`,+ transformStyle: 'preserve-3d',+ transition: 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)',+ width: 53,+ height: 106,+ borderRadius: '8px',+ border: '2px solid rgba(255,255,255,0.20)',+ background: 'linear-gradient(150deg, #151520 0%, #0d0d15 100%)',+ boxShadow: '0 8px 24px rgba(0,0,0,0.6)',+ position: 'relative',+ }}>+ {/* Pantalla */}+ <div style={{+ position: 'absolute', top: 5, left: 4, right: 4, bottom: 5,+ borderRadius: '5px',+ border: '0.5px solid rgba(255,255,255,0.06)',+ overflow: 'hidden',+ ...(previewImageUrl+ ? { backgroundImage: `url(${previewImageUrl})`, backgroundSize: 'cover', backgroundPosition: 'center' }+ : { background: 'rgba(0,163,255,0.10)' }+ ),+ }} />+ {/* Bocina */}+ <div style={{+ position: 'absolute', top: 2, left: '50%',+ transform: 'translateX(-50%)',+ width: 12, height: 1.5, borderRadius: '1px', background: '#000'+ }} />+ {/* Detalle inferior */}+ <div style={{+ position: 'absolute', bottom: 2, left: '50%',+ transform: 'translateX(-50%)',+ width: 16, height: 1.5, borderRadius: '1px',+ background: 'rgba(255,255,255,0.22)'+ }} />+ </div>+ </div>+ );+ })()+ ) : (<div- className="relative w-full h-full rounded-md overflow-hidden border border-white/5 shadow-2xl"- style={{- transform: `rotateX(${config.rotateX}deg) rotateY(${config.rotateY}deg) rotateZ(${config.rotateZ}deg) scale(${config.scale}) translateY(${config.translateY}%)`,- transformStyle: "preserve-3d",- transition: "transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)",- }}+ style={{ perspective: `${config.perspective || 600}px`, perspectiveOrigin: 'center center' }}+ className="w-full h-full flex items-center justify-center p-3" /* Padding sutil */>- <img- src={previewImageUrl!}- alt={config.label}- className="w-full h-full object-cover"- draggable={false}- />+ <div+ className="relative w-full h-full max-w-[92%] max-h-[92%] rounded-lg overflow-hidden border border-white/5 shadow-2xl"+ style={{+ transform: `rotateX(${config.rotateX}deg) rotateY(${config.rotateY}deg) rotateZ(${config.rotateZ}deg) scale(${config.scale}) translateY(${config.translateY}%)`,+ transformStyle: 'preserve-3d',+ transition: 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)',+ }}+ >+ {previewImageUrl && (+ <img+ src={previewImageUrl}+ alt={config.label}+ className="w-full h-full object-cover"+ draggable={false}+ />+ )}+ </div></div>- </div>+ )}</div>+<div className="absolute inset-0 bg-linear-to-t from-black/80 via-black/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none z-20" /><div className="absolute bottom-2 left-2 opacity-0 group-hover:opacity-100 transition-all duration-300 translate-y-1 group-hover:translate-y-0 pointer-events-none flex items-center gap-1.5 z-20">{!isCustom && <Icon icon="mdi:eye-outline" width={12} className="text-white/70" aria-hidden="true" />}@@ -215,7 +278,7 @@ export function PhotoEditorPlaceholder({{ButtonCard}</PopoverTrigger><PopoverContent- align="start"+ align="start"sideOffset={12}className="w-64 bg-[#0A0A0A] border-white/10 shadow-2xl p-4 space-y-4 rounded-xl z-50">@@ -260,11 +323,13 @@ export function PhotoEditorPlaceholder({const rect = e.currentTarget.getBoundingClientRect();const x = ((e.clientX - rect.left) / rect.width) * 2 - 1;const y = ((e.clientY - rect.top) / rect.height) * 2 - 1;-- updateCustomConfig({- rotateY: Math.round(-x * 45),- rotateX: Math.round(y * 45)- });+ const rY = Math.round(-x * 45);+ const rX = Math.round(y * 45);+ updateCustomConfig({ rotateY: rY, rotateX: rX });+ if (imagePhoneActive) {+ setImagePhoneRotX(rX);+ setImagePhoneRotY(-rY);+ }}}><div className="absolute inset-0 flex items-center justify-center pointer-events-none">@@ -357,11 +422,10 @@ export function PhotoEditorPlaceholder({variant="outline"size="sm"onClick={() => onToggle3DBackground(!apply3DToBackground)}- className={`px-2.5 py-2 text-xs font-medium squircle-element transition-all ${- apply3DToBackground- ? "bg-gradient-radial-primary text-cyan-500 border border-cyan-500/50!"- : "bg-white/5 text-white/50 border border-white/10 hover:bg-white/10"- }`}+ className={`px-2.5 py-2 text-xs font-medium squircle-element transition-all ${apply3DToBackground+ ? "bg-gradient-radial-primary text-cyan-500 border border-cyan-500/50!"+ : "bg-white/5 text-white/50 border border-white/10 hover:bg-white/10"+ }`}aria-label={t("photoPreview.apply3D")}aria-pressed={apply3DToBackground}>diff --git a/app/components/ui/editor/ToolsSidebar.tsx b/app/components/ui/editor/ToolsSidebar.tsxindex 08e34a5..fec40c6 100644--- a/app/components/ui/editor/ToolsSidebar.tsx+++ b/app/components/ui/editor/ToolsSidebar.tsx@@ -261,6 +261,18 @@ export function ToolsSidebar({}}/>+ <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"+ }}+ />+{/* Video-specific tools - hidden in photo mode */}{!isPhotoMode && (<SidebarTooldiff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsxindex 2f2aa33..0356b42 100644--- a/app/components/ui/editor/VideoCanvas.tsx+++ b/app/components/ui/editor/VideoCanvas.tsx@@ -1,6 +1,7 @@"use client";import { useRef, useEffect, useImperativeHandle, forwardRef, useMemo, useState } from "react";+import dynamic from "next/dynamic";import type { VideoCanvasHandle, VideoCanvasProps, VideoThumbnail } from "@/types";import type { ImageElement, SvgElement } from "@/types/canvas-elements.types";import { getCameraLayout } from "@/types/camera.types";@@ -23,9 +24,22 @@ import { EditorHoverTooltip } from "./EditorHoverTooltip";import DropImage from "@/components/ui/DropImage";import { LayersPanel } from "./LayersPanel";import { Icon } from "@iconify/react";+import { useMotionContext } from "@/app/contexts/MotionContext";++// Phone3DViewer render canvas dimensions (must match Phone3DViewer.tsx RENDER_W/H)+const PHONE_RENDER_W = 595;+const PHONE_RENDER_H = 765;+export type { VideoCanvasHandle, VideoCanvasProps };+const Phone3DViewer = dynamic(+ () => import("./Phone3DViewer").then((m) => ({ default: m.Phone3DViewer })),+ { ssr: false }+);+export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({+ activeTool: _activeTool,+ isPlaying = false,mediaType = "video",imageUrl = null,imageRef,@@ -81,6 +95,32 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functconst hasMedia = mediaType === "video" ? !!videoUrl : !!imageUrl;+ // Motion 3D phone overlay state (reads from shared MotionContext)+ const {+ selectedTemplateId, motionDuration, motionImageUrl,+ motionIntensity, motionStyle, motionVariantId, motionAnimMode,+ imagePhoneActive, imagePhoneX, imagePhoneY,+ imagePhoneScale, setImagePhoneScale,+ imagePhoneRotX, setImagePhoneRotX, imagePhoneRotY, setImagePhoneRotY,+ imagePhoneDevice, setImagePhoneDevice, imagePhonePresetId, setImagePhonePresetId+ } = useMotionContext();+ // Phone shows whenever a real template is selected AND we are in video mode+ const motionActive = selectedTemplateId !== null && selectedTemplateId !== "none" && mediaType === "video";++ // Ctrl+scroll zoom badge state for image phone overlay+ const [imagePhoneZoomVisible, setImagePhoneZoomVisible] = useState(false);+ const imagePhoneZoomTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ // WebGL canvas from image phone Phone3DViewer, captured via onMount prop for export+ const imagePhoneCanvasRef = useRef<HTMLCanvasElement | null>(null);++ // Model URL for the active device+ const PHONE_DEVICE_URLS: Record<string, string | undefined> = {+ phone: undefined,+ iphone: '/models/iphone-15-pro-max.glb',+ samsung: '/models/samsung-galaxy-s25-ultra.glb',+ };+ const imagePhoneModelUrl = PHONE_DEVICE_URLS[imagePhoneDevice];+// Get current thumbnail for scrubbing previewconst currentThumbnail = useMemo<VideoThumbnail | null>(() => {if (!isScrubbing || !getThumbnailForTime) return null;@@ -140,6 +180,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functconst shouldShowCustomColor = backgroundTab === "color" && !!backgroundColorCss;const exportCanvasRef = useRef<HTMLCanvasElement>(null);+ const phoneOverlayRef = useRef<HTMLDivElement>(null);// Foreground canvas — used to render the mockup in isolation so that the// WebGL 3D perspective is applied only to the mockup, not to the background.const foregroundCanvasRef = useRef<HTMLCanvasElement | null>(null);@@ -162,6 +203,11 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct// Image zoom state (for photo mode)const [imageZoomScale, setImageZoomScale] = useState(1);+ // Motion phone zoom state (Ctrl + scroll, mirrors image mode behaviour)+ const [motionZoomScale, setMotionZoomScale] = useState(1);+ const [motionZoomVisible, setMotionZoomVisible] = useState(false);+ const motionZoomTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+const lastSetVideoUrlRef = useRef<string | null>(null);const preservedVideoStateRef = useRef<{ time: number; playing: boolean } | null>(null);@@ -702,6 +748,35 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct};}, [mediaType, imageUrl]);+ // Motion phone zoom with mouse wheel (Ctrl + scroll) — mirrors image mode behaviour+ useEffect(() => {+ if (!motionActive) return;++ const handleWheel = (e: WheelEvent) => {+ if (!e.ctrlKey && !e.metaKey) return;+ e.preventDefault();+ const zoomFactor = e.deltaY < 0 ? 1.1 : 0.9;+ setMotionZoomScale(prev => Math.max(0.3, Math.min(3, prev * zoomFactor)));+ setMotionZoomVisible(true);+ if (motionZoomTimerRef.current) clearTimeout(motionZoomTimerRef.current);+ motionZoomTimerRef.current = setTimeout(() => setMotionZoomVisible(false), 1500);+ };++ const container = previewContainerRef.current;+ if (!container) return;++ container.addEventListener("wheel", handleWheel, { passive: false });+ return () => {+ container.removeEventListener("wheel", handleWheel);+ };+ }, [motionActive]);++ // Reset motion zoom when template selection changes+ useEffect(() => {+ setMotionZoomScale(1);+ setMotionZoomVisible(false);+ }, [selectedTemplateId]);+// Drag & drop handlers for imagesconst handleDragOver = (e: React.DragEvent) => {if (mediaType !== "image" || !onImageDrop) return;@@ -1052,6 +1127,17 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functconst { containerX: cX, containerY: cY, containerWidth: cW, containerHeight: cH } = computeContainer();drawMockupAndMedia(ctx, cX, cY, cW, cH, image!, true);await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, false);+ // ── Composite image phone mockup (WebGL snapshot) onto export canvas ──+ if (imagePhoneActive && imagePhoneCanvasRef.current) {+ const phoneGL = imagePhoneCanvasRef.current;+ const domW = canvasDimensions?.width ?? canvasWidth;+ const pxScale = canvasWidth / domW;+ const phoneCx = canvasWidth / 2 + imagePhoneX * pxScale;+ const phoneCy = canvasHeight / 2 + imagePhoneY * pxScale;+ const drawW = PHONE_RENDER_W * imagePhoneScale * pxScale;+ const drawH = PHONE_RENDER_H * imagePhoneScale * pxScale;+ ctx.drawImage(phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH);+ }ctx.restore();return;}@@ -1256,7 +1342,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functcamVideo.currentTime = targetTime;await new Promise<void>((resolve) => {-+const timeoutId = setTimeout(() => {camVideo.removeEventListener("seeked", onSeeked);resolve();@@ -1349,6 +1435,81 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct}ctx.restore();+ // ── Phone frame overlay for motion export ──+ // CSS 3D phone cannot be captured natively; draw a canvas phone bezel so the+ // export frame shows the phone outline with the video visible through the screen.+ if (motionActive) {+ const phoneH = canvasHeight * 0.65;+ const phoneW = phoneH * (272 / 552);+ const phoneX = (canvasWidth - phoneW) / 2;+ const phoneY = (canvasHeight - phoneH) / 2;+ const scale = phoneW / 272;+ const outerR = Math.round(44 * scale);+ const inset = Math.round(5 * scale);+ const screenR = Math.round(36 * scale);++ ctx.save();++ // Phone bezel — filled with dark color, screen area punched out (even-odd)+ ctx.beginPath();+ ctx.roundRect(phoneX, phoneY, phoneW, phoneH, outerR);+ ctx.roundRect(phoneX + inset, phoneY + inset, phoneW - inset * 2, phoneH - inset * 2, screenR);+ ctx.fillStyle = "rgba(14, 14, 26, 0.93)";+ ctx.fill("evenodd");++ // Outer phone border+ ctx.strokeStyle = "rgba(255,255,255,0.14)";+ ctx.lineWidth = Math.max(1, 1.5 * scale);+ ctx.beginPath();+ ctx.roundRect(phoneX, phoneY, phoneW, phoneH, outerR);+ ctx.stroke();++ // Screen inner border (subtle)+ ctx.strokeStyle = "rgba(255,255,255,0.05)";+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.roundRect(phoneX + inset, phoneY + inset, phoneW - inset * 2, phoneH - inset * 2, screenR);+ ctx.stroke();++ // Dynamic island+ const diW = phoneW * 0.22;+ const diH = Math.max(4, phoneH * 0.024);+ ctx.fillStyle = "#000";+ ctx.beginPath();+ ctx.roundRect(phoneX + (phoneW - diW) / 2, phoneY + phoneH * 0.018, diW, diH, diH / 2);+ ctx.fill();++ // Home indicator+ const homeW = phoneW * 0.28;+ const homeH = Math.max(3, 4 * scale);+ ctx.fillStyle = "rgba(255,255,255,0.28)";+ ctx.beginPath();+ ctx.roundRect(phoneX + (phoneW - homeW) / 2, phoneY + phoneH - homeH - inset * 1.5, homeW, homeH, homeH / 2);+ ctx.fill();++ // Side buttons (left: 2 volume, right: 1 power)+ const btnW = Math.max(2, 3 * scale);+ const btnH1 = phoneH * 0.08;+ const btnH2 = phoneH * 0.11;+ ctx.fillStyle = "rgba(14,14,26,0.93)";+ ctx.strokeStyle = "rgba(255,255,255,0.10)";+ ctx.lineWidth = 1;+ // volume up+ ctx.beginPath();+ ctx.roundRect(phoneX - btnW, phoneY + phoneH * 0.21, btnW, btnH1, btnW / 2);+ ctx.fill(); ctx.stroke();+ // volume down+ ctx.beginPath();+ ctx.roundRect(phoneX - btnW, phoneY + phoneH * 0.32, btnW, btnH2, btnW / 2);+ ctx.fill(); ctx.stroke();+ // power+ ctx.beginPath();+ ctx.roundRect(phoneX + phoneW, phoneY + phoneH * 0.27, btnW, btnH2, btnW / 2);+ ctx.fill(); ctx.stroke();++ ctx.restore();+ }+};useImperativeHandle(ref, () => ({@@ -1490,7 +1651,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"><divref={previewContainerRef}- className={`relative shrink-0 overflow-hidden transition-all duration-300 ${mediaType === "image" && imageUrl+ className={`relative shrink-0 transition-all duration-300 ${imagePhoneActive ? 'overflow-visible' : 'overflow-hidden'} ${mediaType === "image" && imageUrl? "": "border border-white/20 rounded-xl"}`}@@ -1501,12 +1662,15 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct: { width: '100%', height: 'auto', maxHeight: '100%' }),containerType: 'size',+}}onClick={(e) => {if (!(e.target as HTMLElement).closest('[data-canvas-element]') &&!(e.target as HTMLElement).closest('[data-camera-overlay]') &&- !(e.target as HTMLElement).closest('[data-video-container]')+ !(e.target as HTMLElement).closest('[data-video-container]') &&+ !(e.target as HTMLElement).closest('[data-phone-overlay]') &&+ !(e.target as HTMLElement).closest('[data-image-phone-overlay]')) {if (onElementSelect) onElementSelect(null);setIsVideoSelected(false);@@ -1592,6 +1756,11 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functpadding: `${padding * 0.5}%`,zIndex: isVideoSelected ? 101 : 2,pointerEvents: 'none',+ // Hide the video layer while a motion template is active;+ // the video element stays in the DOM so playback/timing continues.+ // In image mode, also hide when the phone overlay is active.+ opacity: (mediaType === "video" ? motionActive : imagePhoneActive) ? 0 : 1,+ transition: 'opacity 0.25s ease, padding 0.2s',...(mediaType === "image" && imageTransform && !apply3DToBackground ? {perspective: `${imageTransform.perspective || 600}px`,perspectiveOrigin: 'center center',@@ -1618,7 +1787,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functtransition: (mediaType === "image" && imageTransform && !apply3DToBackground)? 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)': isDraggingVideo || isDraggingRotation ? 'none' : 'transform 0.15s cubic-bezier(0.25, 0.46, 0.45, 0.94)',- pointerEvents: 'auto',+ pointerEvents: motionActive ? 'none' : 'auto',transformStyle: mediaType === "image" && !apply3DToBackground ? 'preserve-3d' : undefined,}}onMouseEnter={() => hasMedia && setIsVideoHovered(true)}@@ -1675,7 +1844,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct</div></div>)}- {(isVideoSelected || isVideoHovered) && hasMedia && !isDraggingRotation && (+ {(isVideoSelected || isVideoHovered) && hasMedia && !isDraggingRotation && !(mediaType === "image" && imagePhoneActive) && (<divclassName={`absolute -inset-px border pointer-events-none z-10 opacity-80 ${isVideoSelected ? 'border-blue-500' : 'border-white'}`}style={{ borderRadius: `${roundedCorners + 1}px` }}@@ -1831,7 +2000,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functsetIsDraggingElement={setIsDraggingElement}setIsDraggingElementRotation={setIsDraggingElementRotation}elementDragStart={elementDragStart}- layerZIndex={100}+ layerZIndex={200}hitTestOnly={true}elementCorners={elementCorners}setElementCorners={setElementCorners}@@ -1844,6 +2013,127 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct}}/>+ {/* ── Motion 3D Phone Overlay — INSIDE zoom layer so fragment-zoom applies ── */}+ {motionActive && (+ <div+ ref={phoneOverlayRef}+ data-phone-overlay+ className="absolute inset-0 flex items-center justify-center overflow-hidden"+ style={{ zIndex: 150, isolation: "isolate" }}+ >+ {/* Scale wrapper — controlled by Ctrl+scroll */}+ <div+ style={{+ transform: `scale(${motionZoomScale})`,+ transformOrigin: 'center center',+ transition: 'transform 0.08s ease-out',+ willChange: 'transform',+ }}+ >+ <Phone3DViewer+ videoElement={videoRef?.current ?? null}+ canvasElement={exportCanvasRef.current}+ imageUrl={motionImageUrl}+ isPlaying={isPlaying}+ animDuration={motionDuration}+ intensity={motionIntensity}+ templateId={selectedTemplateId}+ motionStyle={motionStyle}+ variantId={motionVariantId}+ animMode={motionAnimMode}+ />+ </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">+ <div className="text-white/30 text-[10px] font-normal whitespace-nowrap">+ Ctrl + scroll para zoom+ </div>+ </div>+ )}+ </div>+ )}++ {/* ── Image-mode phone overlay — inside zoom layer for correct z-index stacking ── */}+ {mediaType === "image" && imagePhoneActive && (+ <div+ className="absolute inset-0 pointer-events-none"+ style={{ zIndex: 155 }}+ >+ <div+ className="absolute"+ data-image-phone-overlay+ style={{+ left: '50%',+ top: '50%',+ transform: `translate(calc(-50% + ${imagePhoneX}px), calc(-50% + ${imagePhoneY}px)) scale(${imagePhoneScale})`,+ 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);+ }}+ >+ <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>+ )}+ </div>+ )}+</div>{/* End perspective wrapper div */}{(isDraggingElement && (alignmentGuides.vertical.length > 0 || alignmentGuides.horizontal.length > 0)) && (@@ -1996,10 +2286,10 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct}}/>)}+</div></div></div>-{/* ── Layers panel — pegado al lado derecho del canvas ── */}<div className="flex-shrink-0 self-stretch flex items-stretch z-10"><LayersPanel@@ -2069,4 +2359,4 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct</div></div>);-});\ No newline at end of file+});diff --git a/app/components/ui/editor/templates-motion/Phone.tsx b/app/components/ui/editor/templates-motion/Phone.tsxnew file mode 100644index 0000000..0d2c1fa--- /dev/null+++ b/app/components/ui/editor/templates-motion/Phone.tsx@@ -0,0 +1,661 @@+"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" },+];++function EasingPicker() {+ const { motionStyle, setMotionStyle } = useMotionContext();+ return (+ <div className="flex gap-1.5">+ {EASING_OPTIONS.map((opt) => {+ const active = motionStyle === opt.id;+ return (+ <button+ key={opt.id}+ type="button"+ onClick={() => setMotionStyle(opt.id)}+ className={`flex flex-col items-center gap-0 p-0 rounded-lg transition-colors flex-1 ${+ active ? "ring-1 ring-blue-500/60" : "hover:bg-white/[0.04]"+ }`}+ >+ <svg+ viewBox="0 -12 48 72"+ className={`w-full aspect-square rounded-t-lg ${active ? "bg-blue-500/10" : "bg-white/[0.04]"}`}+ >+ <line x1="0" y1="48" x2="48" y2="0" stroke="currentColor" opacity="0.08" strokeWidth="1" />+ <path+ d={opt.path} fill="none"+ stroke={active ? "#60a5fa" : "currentColor"}+ strokeWidth="2" strokeLinecap="round"+ opacity={active ? 1 : 0.35}+ />+ </svg>+ <span className={`text-[9px] font-medium truncate w-full text-center py-1 ${active ? "text-blue-300" : "text-white/30"}`}>+ {opt.label}+ </span>+ </button>+ );+ })}+ </div>+ );+}++// ─── Camera variant picker ────────────────────────────────────────────────────+function VariantPicker({+ value,+ onChange,+}: {+ value: string;+ onChange: (id: string) => void;+}) {+ return (+ <div className="grid grid-cols-2 gap-1.5">+ {CAMERA_VARIANTS.map((v) => {+ const active = value === v.id;+ return (+ <button+ key={v.id}+ type="button"+ title={v.description}+ onClick={() => onChange(v.id)}+ className={`flex items-center gap-2 px-2.5 py-2 rounded-xl border transition-all duration-150 text-left ${+ active+ ? "border-blue-500/60 bg-blue-500/10 text-blue-300"+ : "border-white/[0.08] text-white/35 hover:border-white/20 hover:text-white/60 bg-white/[0.02]"+ }`}+ >+ <Icon icon={v.icon} width="13" className="shrink-0" />+ <span className="text-[10px] font-medium truncate">{v.label}</span>+ </button>+ );+ })}+ </div>+ );+}++// ─── Shared sub-components ────────────────────────────────────────────────────+function SectionHeader({ label }: { label: string }) {+ return (+ <div className="text-[9px] uppercase tracking-[0.2em] text-white/25 font-bold px-0.5">+ {label}+ </div>+ );+}++function SliderRow({+ icon, label, value, min, max, step = 1, suffix = "", onChange,+}: {+ icon: string; label: string; value: number;+ min: number; max: number; step?: number; suffix?: string;+ onChange: (v: number) => void;+}) {+ return (+ <div className="flex items-center gap-3">+ <div className="flex items-center gap-1.5 w-20 shrink-0">+ <Icon icon={icon} width="13" className="text-white/30 shrink-0" />+ <span className="text-[10px] text-white/50 truncate">{label}</span>+ </div>+ <input+ type="range" min={min} max={max} step={step} value={value}+ onChange={(e) => onChange(Number(e.target.value))}+ className="flex-1 h-1 appearance-none bg-white/10 rounded-full outline-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:size-3 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:border [&::-webkit-slider-thumb]:border-white/30"+ />+ <span className="text-[10px] font-mono text-white/40 w-6 text-right shrink-0">+ {value}{suffix}+ </span>+ </div>+ );+}++// ─── Editor panel ─────────────────────────────────────────────────────────────+export function PhoneEditorPanel({ template }: EditorPanelProps) {+ const {+ motionDuration, setMotionDuration,+ motionIntensity, setMotionIntensity,+ motionVariantId, setMotionVariantId,+ motionAnimMode, setMotionAnimMode,+ setMotionImageUrl,+ } = useMotionContext();++ const [imageUrl, setImageUrl] = useState<string | null>(null);+ const [isDragging, setIsDragging] = useState(false);++ useEffect(() => {+ setMotionImageUrl(imageUrl);+ }, [imageUrl]);++ const readImageFile = (file: File) => {+ const reader = new FileReader();+ reader.onload = (e) => setImageUrl(e.target?.result as string ?? null);+ reader.readAsDataURL(file);+ };++ return (+ <div className="space-y-4">++ {/* Image upload */}+ <div className="space-y-2">+ <SectionHeader label="Imagen en pantalla" />+ <div+ onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}+ onDragLeave={() => setIsDragging(false)}+ onDrop={(e) => {+ e.preventDefault(); setIsDragging(false);+ const file = e.dataTransfer.files[0];+ if (file?.type.startsWith("image/")) readImageFile(file);+ }}+ className={`relative rounded-xl border-2 border-dashed transition-all duration-200 overflow-hidden ${+ isDragging ? "border-blue-500/60 bg-blue-500/5" : "border-white/[0.1] hover:border-white/20 bg-[#0d0d10]"+ }`}+ >+ {imageUrl ? (+ <div className="relative aspect-video">+ <img src={imageUrl} alt="Source" className="w-full h-full object-cover" />+ <div className="absolute inset-0 bg-black/40 opacity-0 hover:opacity-100 transition-opacity flex items-center justify-center gap-2">+ <label className="flex items-center gap-1.5 text-[10px] font-medium text-white bg-white/10 hover:bg-white/20 border border-white/20 px-3 py-1.5 rounded-lg cursor-pointer transition-colors">+ <Icon icon="ph:swap-bold" width="11" />+ Cambiar+ <input type="file" accept="image/*" className="hidden"+ onChange={(e) => { const f = e.target.files?.[0]; if (f) readImageFile(f); }} />+ </label>+ <button+ onClick={() => setImageUrl(null)}+ className="flex items-center gap-1.5 text-[10px] font-medium text-red-400 bg-red-500/10 hover:bg-red-500/20 border border-red-500/20 px-3 py-1.5 rounded-lg transition-colors"+ >+ <Icon icon="ph:trash-bold" width="11" />+ Quitar+ </button>+ </div>+ </div>+ ) : (+ <label className="flex flex-col items-center justify-center gap-3 py-8 cursor-pointer">+ <div className="size-9 rounded-xl bg-white/5 border border-white/10 flex items-center justify-center">+ <Icon icon="ph:image-square-bold" width="16" className="text-white/30" />+ </div>+ <div className="text-center">+ <p className="text-[10px] text-white/50 font-medium">Suelta una imagen o haz clic</p>+ <p className="text-[9px] text-white/20 mt-0.5">PNG, JPG, WebP — máx 10 MB</p>+ </div>+ <input type="file" accept="image/*" className="hidden"+ onChange={(e) => { const f = e.target.files?.[0]; if (f) readImageFile(f); }} />+ </label>+ )}+ </div>+ <p className="text-[9px] text-white/20 leading-relaxed">+ Sin imagen se muestra el video del canvas en la pantalla del teléfono.+ </p>+ </div>++ {/* Camera path */}+ <div className="space-y-2.5 border-t border-white/[0.05] pt-3">+ <SectionHeader label="Recorrido de cámara" />+ <VariantPicker+ value={motionVariantId ?? DEFAULT_VARIANT_ID}+ onChange={setMotionVariantId}+ />+ <p className="text-[9px] text-white/20 leading-relaxed pt-0.5">+ {CAMERA_VARIANTS.find((v) => v.id === (motionVariantId ?? DEFAULT_VARIANT_ID))?.description ?? ""}+ </p>+ </div>++ {/* Animation mode */}+ <div className="space-y-2 border-t border-white/[0.05] pt-3">+ <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 active = motionAnimMode === m;+ return (+ <button+ key={m}+ type="button"+ onClick={() => setMotionAnimMode(m)}+ title={labels[m]}+ className={`flex flex-col items-center gap-1 py-2 px-1 rounded-xl border transition-all duration-150 ${+ active+ ? "border-blue-500/60 bg-blue-500/10 text-blue-300"+ : "border-white/[0.08] text-white/35 hover:border-white/20 hover:text-white/60 bg-white/[0.02]"+ }`}+ >+ <Icon icon={icons[m]} width="13" className="shrink-0" />+ <span className="text-[9px] font-medium truncate w-full text-center leading-tight">{labels[m]}</span>+ </button>+ );+ })}+ </div>+ </div>++ {/* Motion controls */}+ <div className="space-y-3 border-t border-white/[0.05] pt-3">+ <SectionHeader label="Movimiento" />+ <SliderRow+ icon="ph:waves-bold" label="Intensidad"+ value={motionIntensity} min={0} max={100} suffix="%"+ onChange={setMotionIntensity}+ />+ <SliderRow+ icon="ph:timer-bold" label="Duración"+ value={motionDuration / 1000} min={1} max={16} step={0.5} suffix="s"+ onChange={(v) => setMotionDuration(v * 1000)}+ />+ </div>++ {/* Easing style */}+ <div className="space-y-2 border-t border-white/[0.05] pt-3">+ <SectionHeader label="Estilo de curva" />+ <EasingPicker />+ </div>++ </div>+ );+}++// ─── Template definition ──────────────────────────────────────────────────────+export const phoneTemplate: MotionTemplate = {+ id: "phone",+ title: "Phone",+ description: "Recorridos cinemáticos de cámara en 3D",+ accentColor: "#22d3ee",+ icon: "ph:film-strip-bold",+ tags: ["UI", "Editor"],+ defaultDuration: 4000,+ showPhone: true,+ script: phoneScript,+ EditorPanel: PhoneEditorPanel,+};\ No newline at end of filediff --git a/app/contexts/MotionContext.tsx b/app/contexts/MotionContext.tsxnew file mode 100644index 0000000..1108b7a--- /dev/null+++ b/app/contexts/MotionContext.tsx@@ -0,0 +1,102 @@+"use client";++import { createContext, useContext, useState, type ReactNode } from "react";+import type { MotionStyle, AnimMode } from "@/types/motion.types";++interface MotionState {+ selectedTemplateId: string | null;+ setSelectedTemplateId: (id: string | null) => void;++ motionDuration: number;+ setMotionDuration: (d: number) => void;++ motionImageUrl: string | null;+ setMotionImageUrl: (url: string | null) => void;++ motionIntensity: number;+ setMotionIntensity: (i: number) => void;++ motionStyle: MotionStyle;+ setMotionStyle: (s: MotionStyle) => void;++ /** ID of the active camera-path variant within the current template */+ motionVariantId: string | null;+ setMotionVariantId: (id: string) => void;++ /** Which finite animations play: entry, exit, both, or none */+ motionAnimMode: AnimMode;+ setMotionAnimMode: (m: AnimMode) => void;++ // ── Image mode phone mockup state ──────────────────────────────────────────+ /** Whether the phone mockup is active in image mode */+ imagePhoneActive: boolean;+ setImagePhoneActive: (v: boolean) => void;+ /** X offset (px) from canvas center */+ imagePhoneX: number;+ setImagePhoneX: (v: number) => void;+ /** Y offset (px) from canvas center */+ imagePhoneY: number;+ setImagePhoneY: (v: number) => void;+ /** Canvas-level scale of the phone mockup */+ imagePhoneScale: number;+ setImagePhoneScale: (v: number) => void;+ /** Persisted 3D rotation offset (degrees) from user drag */+ imagePhoneRotX: number;+ 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;+ imagePhonePresetId: string;+ setImagePhonePresetId: (id: string) => void;+}++const MotionContext = createContext<MotionState | null>(null);++export function MotionProvider({ children }: { children: ReactNode }) {+ const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null);+ const [motionDuration, setMotionDuration] = useState(8000); // era 4000+ const [motionImageUrl, setMotionImageUrl] = useState<string | null>(null);+ const [motionIntensity, setMotionIntensity] = useState(70);+ const [motionStyle, setMotionStyle] = useState<MotionStyle>("normal");+ const [motionVariantId, setMotionVariantId] = useState<string | null>(null);+ const [motionAnimMode, setMotionAnimMode] = useState<AnimMode>("entry+exit");++ // Image mode phone mockup+ const [imagePhoneActive, setImagePhoneActive] = useState(false);+ const [imagePhoneX, setImagePhoneX] = useState(0);+ const [imagePhoneY, setImagePhoneY] = useState(0);+ 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');+ return (+ <MotionContext.Provider value={{+ selectedTemplateId, setSelectedTemplateId,+ motionDuration, setMotionDuration,+ motionImageUrl, setMotionImageUrl,+ motionIntensity, setMotionIntensity,+ motionStyle, setMotionStyle,+ motionVariantId, setMotionVariantId,+ motionAnimMode, setMotionAnimMode,+ imagePhoneActive, setImagePhoneActive,+ imagePhoneX, setImagePhoneX,+ imagePhoneY, setImagePhoneY,+ imagePhoneScale, setImagePhoneScale,+ imagePhoneRotX, setImagePhoneRotX,+ imagePhoneRotY, setImagePhoneRotY,+ imagePhoneDevice, setImagePhoneDevice,+ imagePhonePresetId, setImagePhonePresetId+ }}>+ {children}+ </MotionContext.Provider>+ );+}++export function useMotionContext() {+ const ctx = useContext(MotionContext);+ if (!ctx) throw new Error("useMotionContext must be used inside MotionProvider");+ return ctx;+}\ No newline at end of file