Create professional demos and 3D mockups in seconds, directly in your browser
feat: add MotionPresetIcon component with animations and styles
CristianOlivera1bcb5c31724dc
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsxindex 05167a3..4e7fd60 100644--- a/app/[locale]/(editor)/editor/page.tsx+++ b/app/[locale]/(editor)/editor/page.tsx@@ -7,7 +7,7 @@ import { motion, AnimatePresence } from "framer-motion";import { loadVideoFromIndexedDB, deleteRecordedVideo } from "@/hooks/useScreenRecording";import { useVideoUpload } from "@/hooks/useVideoUpload";import { useImageProjects } from "@/hooks/useImageProjects";-import { getUploadedVideo, deleteUploadedVideo } from "@/lib/video-upload-cache";+import { getUploadedVideo, deleteUploadedVideo, saveVideoTrack, getVideoTrack } from "@/lib/video-upload-cache";import { getUploadedImage, deleteUploadedImage } from "@/lib/image-upload-cache";import { useEditorMode } from "@/hooks/useEditorMode";import { useActiveTool } from "@/hooks/useActiveTool";@@ -47,6 +47,7 @@ import Image from "next/image";import Link from "next/link";import { TooltipAction } from "@/components/ui/tooltip-action";import { bgImagesDelete, bgImagesGetAll, bgImagesSave } from "@/lib/bg-images-idb";+import { DEFAULT_MOCKUP_MOTION_CONFIG, findValidMotionPlacement, MockupMotionFragment, MockupMotionPresetId } from "@/lib/mockup-motion";const ControlPanel = lazy(() => import("@/app/components/ui/editor/ControlPanel").then(mod => ({ default: mod.ControlPanel })));const Timeline = lazy(() => import("@/app/components/ui/editor/Timeline").then(mod => ({ default: mod.Timeline })));@@ -276,6 +277,8 @@ export default function Editor() {// Mockup stateconst [mockupId, setMockupId] = useState<string>("none");const [mockupConfig, setMockupConfig] = useState<MockupConfig>(DEFAULT_MOCKUP_CONFIG);+ const [mockupMotionFragments, setMockupMotionFragments] = useState<MockupMotionFragment[]>([]);+ const [selectedMockupMotionFragmentId, setSelectedMockupMotionFragmentId] = useState<string | null>(null);// Canvas elements stateconst [canvasElements, setCanvasElements] = useState<CanvasElement[]>([]);@@ -378,6 +381,73 @@ export default function Editor() {currentProject, isPhotoMode, autoSaveCurrentProject,]);+ const selectedMockupMotionFragment = useMemo(+ () => mockupMotionFragments.find((f) => f.id === selectedMockupMotionFragmentId) ?? null,+ [mockupMotionFragments, selectedMockupMotionFragmentId]+ );++ const handleSelectMockupMotionFragment = useCallback((id: string | null) => {+ setSelectedMockupMotionFragmentId(id);+ // exclusividad mutua con las otras selecciones del timeline+ setSelectedZoomFragmentId(null);+ setSelectedAudioTrackId(null);+ setSelectedVideoClipId(null);+ setSelectedElementId(null);+ }, []);++ const handleUpdateMockupMotionFragment = useCallback(+ (id: string, updates: Partial<MockupMotionFragment>) => {+ setMockupMotionFragments((prev) =>+ prev.map((f) => (f.id === id ? { ...f, ...updates } : f))+ );+ },+ []+ );++ const handleDeleteMockupMotionFragment = useCallback((id: string) => {+ setMockupMotionFragments((prev) => prev.filter((f) => f.id !== id));+ setSelectedMockupMotionFragmentId((prev) => (prev === id ? null : prev));+ }, []);++ const mockupMotionFragmentsRef = useRef<MockupMotionFragment[]>([]);+ useEffect(() => {+ mockupMotionFragmentsRef.current = mockupMotionFragments;+ }, [mockupMotionFragments]);++ const handleAddOrReplaceMotionPreset = useCallback(+ (presetId: MockupMotionPresetId) => {+ const speed = DEFAULT_MOCKUP_MOTION_CONFIG.speed;+ const intensity = DEFAULT_MOCKUP_MOTION_CONFIG.intensity;++ const placement = findValidMotionPlacement(+ presetId,+ speed,+ currentTime,+ mockupMotionFragmentsRef.current,+ videoDuration+ );++ if (!placement) {+ return;+ }++ const newFragment: MockupMotionFragment = {+ id: `motion_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`,+ presetId,+ intensity,+ speed,+ ...placement,+ };+ setMockupMotionFragments((prev) => [...prev, newFragment]);+ setSelectedMockupMotionFragmentId(newFragment.id);+ setActiveTool("motion");+ },+ [currentTime, videoDuration]+ );++ const handleActivateMotionTool = useCallback(() => {+ setActiveTool("motion");+ }, []);// Restore current project when project ID changes (not on every currentProject update)useEffect(() => {@@ -611,6 +681,7 @@ export default function Editor() {setSelectedZoomFragmentId(null);setSelectedVideoClipId(null);setSelectedAudioTrackId(null);+ setSelectedMockupMotionFragmentId(null);if (id) {setActiveTool("elements");}@@ -774,11 +845,9 @@ export default function Editor() {// Video track clips state (multi-video support)const [videoClips, setVideoClips] = useState<VideoTrackClip[]>([]);- // Computed from videoClips - array of library video IDs currently in trackconst videosInTrackIds = useMemo(() =>videoClips.map(clip => clip.libraryVideoId),[videoClips]);- // Ref para acceder al valor actual de videoClips en callbacks (evitar closure stale)const videoClipsRef = useRef<VideoTrackClip[]>([]);useEffect(() => {videoClipsRef.current = videoClips;@@ -796,6 +865,7 @@ export default function Editor() {muteOriginalAudioRef.current = muteOriginalAudio;}, [muteOriginalAudio]);// Audio trim modal state+const [autoTrimModalOpen, setAutoTrimModalOpen] = useState(false);const [pendingAudioUpload, setPendingAudioUpload] = useState<{audio: import("@/types/audio.types").UploadedAudio;@@ -904,7 +974,7 @@ export default function Editor() {apply3DToBackground, imageMaskConfig, videoMaskConfig, imagePhoneActive, imagePhoneX,imagePhoneY, imagePhoneScale, imagePhoneRotX, imagePhoneRotY, imagePhoneRotZ,imagePhonePerspective, imagePhoneDevice, imagePhonePresetId, imagePhoneOpening,- imagePhoneShadow, imagePhoneShadowColor, imagePhoneRefWidth+ imagePhoneShadow, imagePhoneShadowColor, imagePhoneRefWidth, mockupMotionFragments, videoClips,});}, 300);@@ -918,59 +988,91 @@ export default function Editor() {masterVolume, cameraConfig, videoTransform, imageTransform, apply3DToBackground, imageMaskConfig,videoMaskConfig, imagePhoneActive, imagePhoneX, imagePhoneY, imagePhoneScale, imagePhoneRotX,imagePhoneRotY, imagePhoneRotZ, imagePhonePerspective, imagePhoneDevice, imagePhonePresetId,- imagePhoneOpening, imagePhoneShadow, imagePhoneShadowColor, imagePhoneRefWidth, setEditorState+ imagePhoneOpening, imagePhoneShadow, imagePhoneShadowColor, imagePhoneRefWidth, setEditorState, videoClips]);const prevUndoRedoVersionRef = useRef(undoRedoVersion);useEffect(() => {if (prevUndoRedoVersionRef.current === undoRedoVersion) return;prevUndoRedoVersionRef.current = undoRedoVersion;-isRestoringProjectRef.current = true;- setBackgroundTab(editorState.backgroundTab);- setSelectedWallpaper(editorState.selectedWallpaper);- setBackgroundBlur(editorState.backgroundBlur);- setPadding(editorState.padding);- setRoundedCorners(editorState.roundedCorners);- setShadows(editorState.shadows);- setSelectedImageUrl(editorState.selectedImageUrl);- setBackgroundColorConfig(editorState.backgroundColorConfig);- setAspectRatio(editorState.aspectRatio);- setCustomDimensions(editorState.customDimensions);- setCropArea(editorState.cropArea);- setTrimRange(editorState.trimRange);- setZoomFragments(editorState.zoomFragments);- setMockupId(editorState.mockupId);- setMockupConfig(editorState.mockupConfig);- setCanvasElements(editorState.canvasElements);- setAudioTracks(editorState.audioTracks);- setMuteOriginalAudio(editorState.muteOriginalAudio);- setMasterVolume(editorState.masterVolume);- setCameraConfig(editorState.cameraConfig);- setVideoTransform(editorState.videoTransform);- setImageTransform(editorState.imageTransform);- setApply3DToBackground(editorState.apply3DToBackground);- setImageMaskConfig(editorState.imageMaskConfig);- setVideoMaskConfig(editorState.videoMaskConfig);- setImagePhoneActive(editorState.imagePhoneActive);- setImagePhoneX(editorState.imagePhoneX);- setImagePhoneY(editorState.imagePhoneY);- setImagePhoneScale(editorState.imagePhoneScale);- setImagePhoneRotX(editorState.imagePhoneRotX);- setImagePhoneRotY(editorState.imagePhoneRotY);- setImagePhoneRotZ(editorState.imagePhoneRotZ);- setImagePhonePerspective(editorState.imagePhonePerspective);- setImagePhoneDevice(editorState.imagePhoneDevice);- setImagePhonePresetId(editorState.imagePhonePresetId);- setImagePhoneOpening(editorState.imagePhoneOpening);- setImagePhoneShadow(editorState.imagePhoneShadow);- setImagePhoneShadowColor(editorState.imagePhoneShadowColor);- setImagePhoneRefWidth(editorState.imagePhoneRefWidth ?? 0);+ queueMicrotask(() => {+ setBackgroundTab(editorState.backgroundTab);+ setSelectedWallpaper(editorState.selectedWallpaper);+ setBackgroundBlur(editorState.backgroundBlur);+ setPadding(editorState.padding);+ setRoundedCorners(editorState.roundedCorners);+ setShadows(editorState.shadows);+ setSelectedImageUrl(editorState.selectedImageUrl);+ setBackgroundColorConfig(editorState.backgroundColorConfig);+ setAspectRatio(editorState.aspectRatio);+ setCustomDimensions(editorState.customDimensions);+ setCropArea(editorState.cropArea);+ setTrimRange(editorState.trimRange);+ setZoomFragments(editorState.zoomFragments);+ setMockupId(editorState.mockupId);+ setMockupConfig(editorState.mockupConfig);+ setCanvasElements(editorState.canvasElements);+ setAudioTracks(editorState.audioTracks);+ setMuteOriginalAudio(editorState.muteOriginalAudio);+ setMasterVolume(editorState.masterVolume);+ setCameraConfig(editorState.cameraConfig);+ setVideoTransform(editorState.videoTransform);+ setImageTransform(editorState.imageTransform);+ setApply3DToBackground(editorState.apply3DToBackground);+ setImageMaskConfig(editorState.imageMaskConfig);+ setVideoMaskConfig(editorState.videoMaskConfig);+ setImagePhoneActive(editorState.imagePhoneActive);+ setImagePhoneX(editorState.imagePhoneX);+ setImagePhoneY(editorState.imagePhoneY);+ setImagePhoneScale(editorState.imagePhoneScale);+ setImagePhoneRotX(editorState.imagePhoneRotX);+ setImagePhoneRotY(editorState.imagePhoneRotY);+ setImagePhoneRotZ(editorState.imagePhoneRotZ);+ setImagePhonePerspective(editorState.imagePhonePerspective);+ setImagePhoneDevice(editorState.imagePhoneDevice);+ setImagePhonePresetId(editorState.imagePhonePresetId);+ setImagePhoneOpening(editorState.imagePhoneOpening);+ setImagePhoneShadow(editorState.imagePhoneShadow);+ setImagePhoneShadowColor(editorState.imagePhoneShadowColor);+ setImagePhoneRefWidth(editorState.imagePhoneRefWidth ?? 0);+ setMockupMotionFragments(editorState.mockupMotionFragments ?? []);++ const restoredClips = editorState.videoClips ?? [];+ setVideoClips(restoredClips);++ if (restoredClips.length > 0) {+ const newDuration = calculateTotalDuration(restoredClips);+ setVideoDuration(newDuration);+ setTrimRange({ start: 0, end: newDuration });- setTimeout(() => {- isRestoringProjectRef.current = false;- }, 500);+ const clipAtTime = getClipAtTime(restoredClips, currentTime) ?? restoredClips[0];+ activeClipIdRef.current = clipAtTime.id;+ activeClipDataRef.current = clipAtTime;++ const url = videoUrlsRef.current.get(clipAtTime.libraryVideoId);+ if (url) {+ setVideoUrl(url);+ setVideoId(clipAtTime.libraryVideoId);+ if (videoRef.current) {+ videoRef.current.src = url;+ videoRef.current.currentTime = clipAtTime.trimStart;+ }+ }+ } else {+ setVideoUrl(null);+ setVideoId(null);+ setVideoDuration(0);+ setTrimRange({ start: 0, end: 0 });+ activeClipIdRef.current = null;+ activeClipDataRef.current = null;+ }++ setTimeout(() => {+ isRestoringProjectRef.current = false;+ }, 500);+ });}, [undoRedoVersion]);// Handler para cambiar el mockup@@ -1212,6 +1314,7 @@ export default function Editor() {setSelectedZoomFragmentId(null);setSelectedVideoClipId(null);setSelectedElementId(null);+ setSelectedMockupMotionFragmentId(null);if (trackId) {setActiveTool("audio");}@@ -1351,6 +1454,19 @@ export default function Editor() {const { uploadVideo, loadUploadedVideo, isUploading } = useVideoUpload();const [videoBlob, setVideoBlob] = useState<Blob | null>(null);+ const isPlayingRef = useRef(isPlaying);+ const isDraggingPlayheadRef = useRef(isDraggingPlayhead);+ const trimRangeRef = useRef(trimRange);+ const syncAudioPlaybackRef = useRef(syncAudioPlayback);+ useEffect(() => { isPlayingRef.current = isPlaying; }, [isPlaying]);+ useEffect(() => { isDraggingPlayheadRef.current = isDraggingPlayhead; }, [isDraggingPlayhead]);+ useEffect(() => { trimRangeRef.current = trimRange; }, [trimRange]);+ useEffect(() => { syncAudioPlaybackRef.current = syncAudioPlayback; }, [syncAudioPlayback]);+ const currentTimeRef = useRef<number>(0);+ useEffect(() => {+ currentTimeRef.current = currentTime;+ }, [currentTime]);+const handleExport = (quality: ExportQuality) => {/* console.log("=== RECIPE JSON PARA BACKEND (PRUEBAS) ===");const userId = user?.id ?? "USER-ID-NO-DISPONIBLE";@@ -1676,6 +1792,7 @@ export default function Editor() {setSelectedZoomFragmentId(null);setSelectedAudioTrackId(null);setSelectedElementId(null);+ setSelectedMockupMotionFragmentId(null);if (clipId) {setActiveTool("video");}@@ -1738,10 +1855,9 @@ export default function Editor() {const handleSplitVideoClip = useCallback(() => {const clips = videoClipsRef.current;- const clipAtPlayhead = getClipAtTime(clips, currentTime);+ const clipAtPlayhead = getClipAtTime(clips, currentTimeRef.current);if (!clipAtPlayhead) return;-- const result = splitClipAtTime(clipAtPlayhead, currentTime);+ const result = splitClipAtTime(clipAtPlayhead, currentTimeRef.current);if (!result) return;const { updatedClip, newClip } = result;@@ -1762,7 +1878,7 @@ export default function Editor() {setSelectedAudioTrackId(null);setSelectedElementId(null);setActiveTool("video");- }, [currentTime]);+ }, []);const activeClipForSplit = useMemo(() => getClipAtTime(videoClips, currentTime),@@ -1895,12 +2011,54 @@ export default function Editor() {if (isPhotoMode) return;const loadVideo = async () => {try {+ const persistedClips = await getVideoTrack();+ if (persistedClips !== null) {+ if (persistedClips.length > 0 && videoClipsRef.current.length === 0) {+ const validClips: VideoTrackClip[] = [];+ for (const clip of persistedClips) {+ const libVideo = await getLibraryVideo(clip.libraryVideoId);+ if (!libVideo) continue;+ validClips.push(clip);+ if (!videoBlobsRef.current.has(clip.libraryVideoId)) {+ videoBlobsRef.current.set(clip.libraryVideoId, libVideo.blob);+ const url = URL.createObjectURL(libVideo.blob);+ setClipUrl(clip.libraryVideoId, url);+ }+ clipAudioStateRef.current.set(clip.libraryVideoId, libVideo.hasAudio !== false);+ }++ if (validClips.length > 0) {+ const sorted = [...validClips].sort((a, b) => a.startTime - b.startTime);+ setVideoClips(sorted);+ const totalDuration = calculateTotalDuration(sorted);+ setVideoDuration(totalDuration);+ setTrimRange({ start: 0, end: totalDuration });++ const firstClip = sorted[0];+ activeClipIdRef.current = firstClip.id;+ activeClipDataRef.current = firstClip;+ const firstUrl = videoUrlsRef.current.get(firstClip.libraryVideoId);+ if (firstUrl) {+ setVideoUrl(firstUrl);+ setVideoId(firstClip.libraryVideoId);+ lastLoadedVideoIdRef.current = firstClip.libraryVideoId;+ if (videoRef.current) {+ videoRef.current.src = firstUrl;+ }+ }+ setZoomFragments(generateDefaultZoomFragments(totalDuration));+ setVideosLibraryRefresh(prev => prev + 1);+ setTimeout(() => clearHistory(), 200);+ }+ }+ return;+ }+const [uploadedData, recordedData, cachedUpload] = await Promise.all([loadUploadedVideo(),loadVideoFromIndexedDB(),getUploadedVideo(),]);-let videoToLoad: typeof uploadedData | typeof recordedData = null;let videoBlob: Blob | null = null;@@ -2119,12 +2277,11 @@ export default function Editor() {setCurrentTime(timelineTime);syncAudioPlayback(timelineTime, false);} else {- syncAudioPlayback(currentTime, false);+ syncAudioPlayback(currentTimeRef.current, false);}} else {const clips = videoClipsRef.current;- let startTime = currentTime;-+ let startTime = currentTimeRef.current;if (trimRange.end > 0) {if (startTime < trimRange.start || startTime >= trimRange.end) {startTime = trimRange.start;@@ -2187,27 +2344,30 @@ export default function Editor() {}setIsPlaying(!isPlaying);}- }, [isPlaying, currentTime, trimRange.start, trimRange.end, syncAudioPlayback, findActiveClipAtTime, timelineToClipTime]);+ }, [isPlaying, trimRange.start, trimRange.end, syncAudioPlayback, findActiveClipAtTime, timelineToClipTime]);const updateTimeSmoothRef = useRef<() => void>(() => { });const scheduleUpdateFrame = useCallback(() => {- if (animationFrameRef.current) {- cancelAnimationFrame(animationFrameRef.current);+ if (animationFrameRef.current !== null) {+ return;}- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);+ animationFrameRef.current = requestAnimationFrame(() => {+ animationFrameRef.current = null;+ updateTimeSmoothRef.current();+ });}, []);useEffect(() => {updateTimeSmoothRef.current = () => {if (justEndedRef.current) return;if (isSwitchingClipRef.current) {- if (isPlaying && !isDraggingPlayhead) {+ if (isPlayingRef.current && !isDraggingPlayheadRef.current) {scheduleUpdateFrame();}return;}- if (videoRef.current && !isDraggingPlayhead) {+ if (videoRef.current && !isDraggingPlayheadRef.current) {const clips = videoClipsRef.current;if (clips.length > 0) {@@ -2230,7 +2390,7 @@ export default function Editor() {}if (!activeClip) {- if (isPlaying && !isDraggingPlayhead) {+ if (isPlayingRef.current && !isDraggingPlayheadRef.current) {scheduleUpdateFrame();}return;@@ -2243,7 +2403,7 @@ export default function Editor() {if (clipSwitchTimeRef.current !== null) {setCurrentTime(clipSwitchTimeRef.current);- if (isPlaying && !isDraggingPlayhead) {+ if (isPlayingRef.current && !isDraggingPlayheadRef.current) {scheduleUpdateFrame();}return;@@ -2317,7 +2477,7 @@ export default function Editor() {}} else {videoRef.current.pause();- syncAudioPlayback(clipEndOnTimeline, false);+ syncAudioPlaybackRef.current(clipEndOnTimeline, false);setIsPlaying(false);justEndedRef.current = true;setCurrentTime(clipEndOnTimeline);@@ -2326,41 +2486,41 @@ export default function Editor() {}}- if (trimRange.end > 0 && timelineTime >= trimRange.end) {+ if (trimRangeRef.current.end > 0 && timelineTime >= trimRangeRef.current.end) {videoRef.current.pause();- syncAudioPlayback(timelineTime, false);+ syncAudioPlaybackRef.current(timelineTime, false);setIsPlaying(false);justEndedRef.current = true;- setCurrentTime(trimRange.end);+ setCurrentTime(trimRangeRef.current.end);setTimeout(() => { justEndedRef.current = false; }, 300);return;}setCurrentTimeThrottled(timelineTime);- syncAudioPlayback(timelineTime, true);+ syncAudioPlaybackRef.current(timelineTime, true);}} else {const currentVideoTime = videoRef.current.currentTime;- if (trimRange.end > 0 && currentVideoTime >= trimRange.end) {+ if (trimRangeRef.current.end > 0 && currentVideoTime >= trimRangeRef.current.end) {videoRef.current.pause();- syncAudioPlayback(currentVideoTime, false);+ syncAudioPlaybackRef.current(currentVideoTime, false);setIsPlaying(false);justEndedRef.current = true;- setCurrentTime(trimRange.end);+ setCurrentTime(trimRangeRef.current.end);setTimeout(() => { justEndedRef.current = false; }, 300);return;}setCurrentTimeThrottled(currentVideoTime);- syncAudioPlayback(currentVideoTime, true);+ syncAudioPlaybackRef.current(currentVideoTime, true);}}- if (isPlaying && !isDraggingPlayhead) {+ if (isPlayingRef.current && !isDraggingPlayheadRef.current) {scheduleUpdateFrame();}};- }, [isPlaying, isDraggingPlayhead, trimRange.end, syncAudioPlayback]);+ }, [])// Start/stop animation frame loop based on playing stateuseEffect(() => {@@ -2535,6 +2695,8 @@ export default function Editor() {}}, [trimRange.end, isPlaying, syncAudioPlayback]);+ const pendingSeekCanPlayRef = useRef<{ video: HTMLVideoElement; handler: () => void } | null>(null);+const handleSeek = useCallback((time: number) => {scrubTimeRef.current = time;setScrubTime(time);@@ -2559,7 +2721,6 @@ export default function Editor() {if (isDifferentSource && targetUrl) {const wasPlaying = isPlaying;-if (videoRef.current && !videoRef.current.paused) {videoRef.current.pause();}@@ -2567,15 +2728,16 @@ export default function Editor() {cancelAnimationFrame(animationFrameRef.current);animationFrameRef.current = null;}-+ if (pendingSeekCanPlayRef.current) {+ pendingSeekCanPlayRef.current.video.removeEventListener('canplay', pendingSeekCanPlayRef.current.handler);+ pendingSeekCanPlayRef.current = null;+ }activeClipIdRef.current = clipAtTime.id;activeClipDataRef.current = clipAtTime;isSeekingToClipRef.current = true;isSwitchingClipRef.current = true;-const currentVideo = videoRef.current;currentVideo.src = targetUrl;-const onCanPlay = () => {if (currentVideo) {currentVideo.playbackRate = globalSpeedRef.current;@@ -2585,17 +2747,20 @@ export default function Editor() {isSeekingToClipRef.current = false;isSwitchingClipRef.current = false;clipSwitchTimeRef.current = null;-if (wasPlaying) {currentVideo.play().catch(e => {if (e.name !== 'AbortError') console.warn('Play interrupted:', e);});- animationFrameRef.current = requestAnimationFrame(updateTimeSmoothRef.current);+ scheduleUpdateFrame();}}currentVideo?.removeEventListener('canplay', onCanPlay);+ if (pendingSeekCanPlayRef.current?.handler === onCanPlay) {+ pendingSeekCanPlayRef.current = null;+ }};currentVideo.addEventListener('canplay', onCanPlay);+ pendingSeekCanPlayRef.current = { video: currentVideo, handler: onCanPlay };syncAudioPlayback(time, false);return;} else {@@ -2615,7 +2780,7 @@ export default function Editor() {}syncAudioPlayback(time, isPlaying);}- }, [isDraggingPlayhead, isPlaying, syncAudioPlayback, findActiveClipAtTime, timelineToClipTime]);+ }, [isDraggingPlayhead, isPlaying, syncAudioPlayback, findActiveClipAtTime, timelineToClipTime, scheduleUpdateFrame]);// Handler for background image upload (for ControlPanel)const handleImageUpload = useCallback(async (file: File) => {@@ -2673,6 +2838,7 @@ export default function Editor() {setSelectedAudioTrackId(null);setSelectedVideoClipId(null);setSelectedElementId(null);+ setSelectedMockupMotionFragmentId(null);}, []);const handleActivateZoomTool = useCallback(() => {@@ -2858,32 +3024,28 @@ export default function Editor() {handleDeleteZoomFragment(selectedZoomFragmentId);return;}-+ if ((e.key === "Delete" || e.key === "Backspace") && selectedMockupMotionFragmentId) {+ e.preventDefault();+ handleDeleteMockupMotionFragment(selectedMockupMotionFragmentId);+ return;+ }if (e.key === "Escape") {e.preventDefault();- if (textToolActive) {- setTextToolActive(false);- return;- }- if (selectedElementId) {- setSelectedElementId(null);- } else if (selectedVideoClipId) {- setSelectedVideoClipId(null);- } else if (selectedAudioTrackId) {- setSelectedAudioTrackId(null);- } else if (selectedZoomFragmentId) {- setSelectedZoomFragmentId(null);- }+ if (textToolActive) { setTextToolActive(false); return; }+ if (selectedElementId) { setSelectedElementId(null); }+ else if (selectedVideoClipId) { setSelectedVideoClipId(null); }+ else if (selectedAudioTrackId) { setSelectedAudioTrackId(null); }+ else if (selectedZoomFragmentId) { setSelectedZoomFragmentId(null); }+ else if (selectedMockupMotionFragmentId) { setSelectedMockupMotionFragmentId(null); }}-};document.addEventListener("keydown", handleKeyDown);return () => document.removeEventListener("keydown", handleKeyDown);- }, [selectedElementId, selectedZoomFragmentId, selectedAudioTrackId, selectedVideoClipId, deleteCanvasElement, handleDeleteZoomFragment, handleDeleteAudioTrack, handleDeleteVideoClip, copySelectedElement, pasteElement, isPhotoMode, copiedElement, textToolActive, copySelectedZoomFragment, pasteZoomFragment, copiedZoomFragment, activeTool]);+ }, [selectedElementId, selectedZoomFragmentId, selectedAudioTrackId, selectedVideoClipId, selectedMockupMotionFragmentId, deleteCanvasElement, handleDeleteZoomFragment, handleDeleteAudioTrack, handleDeleteVideoClip, handleDeleteMockupMotionFragment, copySelectedElement, pasteElement, isPhotoMode, copiedElement, textToolActive, copySelectedZoomFragment, pasteZoomFragment, copiedZoomFragment, activeTool]);const wasMobileRef = useRef<boolean | null>(null);- const otherSelectionActive = !!(selectedZoomFragmentId || selectedAudioTrackId || selectedVideoClipId);+ const otherSelectionActive = !!(selectedZoomFragmentId || selectedAudioTrackId || selectedVideoClipId || selectedMockupMotionFragmentId);useEffect(() => {const checkMobile = () => {@@ -2904,19 +3066,28 @@ export default function Editor() {}, []);const [currentPreviewThumbnail, setCurrentPreviewThumbnail] = useState<string | null>(null);+ const [zoomFragmentThumbnail, setZoomFragmentThumbnail] = useState<string | null>(null);+useEffect(() => {- // eslint-disable-next-line react-hooks/set-state-in-effect- setCurrentPreviewThumbnail(getThumbnailForTime(currentDisplayTime)?.dataUrl ?? null);+ const timer = setTimeout(() => {+ const thumbnail = getThumbnailForTime(currentDisplayTime)?.dataUrl ?? null;+ setCurrentPreviewThumbnail(thumbnail);+ }, 0);++ return () => clearTimeout(timer);}, [currentDisplayTime, getThumbnailForTime]);- const [zoomFragmentThumbnail, setZoomFragmentThumbnail] = useState<string | null>(null);useEffect(() => {- if (!selectedZoomFragment) {- // eslint-disable-next-line react-hooks/set-state-in-effect- setZoomFragmentThumbnail(null);- return;- }- setZoomFragmentThumbnail(getThumbnailForTime(selectedZoomFragment.startTime)?.dataUrl ?? null);+ const timer = setTimeout(() => {+ if (!selectedZoomFragment) {+ setZoomFragmentThumbnail(null);+ return;+ }+ const thumbnail = getThumbnailForTime(selectedZoomFragment.startTime)?.dataUrl ?? null;+ setZoomFragmentThumbnail(thumbnail);+ }, 0);++ return () => clearTimeout(timer);}, [selectedZoomFragment, getThumbnailForTime]);const handleAspectRatioChange = useCallback((ratio: AspectRatio) => {@@ -2958,6 +3129,18 @@ export default function Editor() {}, 300);}, [trimRange.end, videoDuration, syncAudioPlayback]);+ const saveVideoTrackTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ useEffect(() => {+ if (isPhotoMode) return;+ if (saveVideoTrackTimeoutRef.current) clearTimeout(saveVideoTrackTimeoutRef.current);+ saveVideoTrackTimeoutRef.current = setTimeout(() => {+ saveVideoTrack(videoClips).catch(() => { });+ }, 500);+ return () => {+ if (saveVideoTrackTimeoutRef.current) clearTimeout(saveVideoTrackTimeoutRef.current);+ };+ }, [videoClips, isPhotoMode]);+const layersPanelToolbar = useMemo(() => (<EditorTopBaronExport={handleExport}@@ -3106,6 +3289,13 @@ export default function Editor() {onWallpaperShowAllChange={setWallpaperShowAll}globalSpeed={globalSpeed}onGlobalSpeedChange={handleGlobalSpeedChange}+ mockupMotionFragments={mockupMotionFragments}+ selectedMockupMotionFragment={selectedMockupMotionFragment}+ selectedMockupMotionFragmentId={selectedMockupMotionFragmentId}+ onAddOrReplaceMotionPreset={handleAddOrReplaceMotionPreset}+ onUpdateMockupMotionFragment={handleUpdateMockupMotionFragment}+ onSelectMockupMotionFragment={handleSelectMockupMotionFragment}+ onDeleteMockupMotionFragment={handleDeleteMockupMotionFragment}/></Suspense></motion.div>@@ -3202,6 +3392,8 @@ export default function Editor() {imageZoomScale={imageZoomScale}onImageZoomScaleChange={setImageZoomScale}otherSelectionActive={otherSelectionActive}+ mockupMotionFragments={mockupMotionFragments}+ videoDuration={videoDuration}/>{/* Video mode: Show player controls and timeline */}@@ -3253,6 +3445,7 @@ export default function Editor() {onAddZoomFragment={handleAddZoomFragmentAtRange}onUpdateZoomFragment={handleUpdateZoomFragment}onActivateZoomTool={handleActivateZoomTool}+ onActivateMotionTool={handleActivateMotionTool}audioTracks={audioTracks}uploadedAudios={uploadedAudios}selectedAudioTrackId={selectedAudioTrackId}@@ -3261,6 +3454,11 @@ export default function Editor() {globalSpeed={globalSpeed}isPlaying={isPlaying}onZoomChange={handleZoomChange}+ mockupMotionFragments={mockupMotionFragments}+ selectedMockupMotionFragmentId={selectedMockupMotionFragmentId}+ onSelectMockupMotionFragment={handleSelectMockupMotionFragment}+ onUpdateMockupMotionFragment={handleUpdateMockupMotionFragment}+ onDeleteMockupMotionFragment={handleDeleteMockupMotionFragment}/></Suspense></>diff --git a/app/components/common/UserMenu.tsx b/app/components/common/UserMenu.tsxindex 9c05e73..d638212 100644--- a/app/components/common/UserMenu.tsx+++ b/app/components/common/UserMenu.tsx@@ -63,7 +63,7 @@ export function UserMenu() {<div className="relative w-8 h-8 sm:w-9 sm:h-9 rounded-full overflow-hidden border border-white/10 hover:border-white/30 transition-colors"><Image src={avatarUrl} alt={displayName} fill sizes="36px" className="object-cover" /></div>- <span className="hidden sm:block text-sm font-medium text-neutral-300 max-w-30 truncate">+ <span className="hidden sm:block text-sm font-medium text-neutral-300 max-w-20 truncate">{displayName}</span><Icon icon="solar:alt-arrow-down-linear" className="hidden sm:block size-4 text-neutral-400" aria-hidden="true" />diff --git a/app/components/ui/Skeleton.tsx b/app/components/ui/Skeleton.tsxindex 7864a3e..e00a528 100644--- a/app/components/ui/Skeleton.tsx+++ b/app/components/ui/Skeleton.tsx@@ -537,4 +537,54 @@ export function HistoryMenuSkeleton() {</div></div>);+}++export function MotionMenuSkeleton() {+ return (+ <div className="p-4 flex flex-col gap-4 h-full relative">+ <div className="flex items-center gap-2 shrink-0">+ <Skeleton width={20} height={20} variant="circle" />+ <Skeleton height={14} width={50} />+ </div>++ <div className="flex-1 overflow-y-hidden -mx-1 px-1">+ <div className="flex flex-col gap-6">+ {[6, 6, 2].map((count, sectionIndex) => (+ <div key={sectionIndex}>+ <div className="flex items-center gap-2 mb-3">+ <Skeleton height={9} width={60} />+ <div className="h-px flex-1 bg-white/5" />+ </div>++ <div className="grid grid-cols-2 gap-2.5">+ {Array.from({ length: count }).map((_, i) => (+ <div+ key={i}+ className="rounded-xl border border-neutral-800 bg-black p-2 flex flex-col gap-2"+ >+ <Skeleton+ variant="square"+ className="w-full aspect-[16/10] rounded-lg"+ />+ <Skeleton height={9} width="75%" />+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ </div>++ <div className="shrink-0 flex flex-col gap-4 pt-4 border-t border-white/5">+ {Array.from({ length: 2 }).map((_, i) => (+ <div key={i} className="flex items-center gap-3">+ <Skeleton width={14} height={14} variant="circle" />+ <Skeleton height={10} width={70} />+ <Skeleton height={6} className="flex-1" variant="default" />+ <Skeleton height={10} width={24} />+ </div>+ ))}+ </div>+ </div>+ );}\ No newline at end of filediff --git a/app/components/ui/editor/AudioFragmentTrackItem.tsx b/app/components/ui/editor/AudioFragmentTrackItem.tsxindex d2080fe..be328dc 100644--- a/app/components/ui/editor/AudioFragmentTrackItem.tsx+++ b/app/components/ui/editor/AudioFragmentTrackItem.tsx@@ -160,7 +160,7 @@ export function AudioFragmentTrackItem({return (<motion.divref={containerRef}- className={`absolute h-[90%] top-[5%] rounded-md flex items-center border transition-shadow select-none+ className={`absolute h-[95%] top-[5%] rounded-md flex items-center border transition-shadow select-none${isSelected || isInteracting? 'bg-violet-500/30 border-violet-400/70 shadow-[0_0_10px_rgba(139,92,246,0.3)] z-10': 'bg-violet-600/20 border-violet-500/35 hover:border-violet-500/60'diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsxindex 439a6cc..97446ff 100644--- a/app/components/ui/editor/ControlPanel.tsx+++ b/app/components/ui/editor/ControlPanel.tsx@@ -7,7 +7,7 @@ import { TabButton } from "../../../../components/ui/TabButton";import type { ControlPanelProps } from "@/types/control-panel.types";import Link from "next/link";import Image from "next/image";-import { lazy, Suspense } from "react";+import { lazy, Suspense, useState } from "react";import { useTranslations } from "next-intl";import {@@ -20,13 +20,15 @@ import {ZoomFragmentEditorSkeleton,AudioMenuSkeleton,VideosMenuSkeleton,- HistoryMenuSkeleton+ HistoryMenuSkeleton,+ MotionMenuSkeleton} from "../Skeleton";import { ElementsMenu } from "./ElementsMenu";import { TooltipAction } from "@/components/ui/tooltip-action";import { CameraMenu } from "./CameraMenu";import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";+import { MotionMenu } from "./MotionMenu";const ImageRecentBackgroundGrid = lazy(() => import("../ImageRecentBackgroundGrid").then(mod => ({ default: mod.ImageRecentBackgroundGrid })));const BackgroundColorEditor = lazy(() => import("../BackgroundColorEditor").then(mod => ({ default: mod.BackgroundColorEditor })));@@ -130,11 +132,18 @@ export function ControlPanel({mediaType = "video",globalSpeed = 1,onGlobalSpeedChange,+ mockupMotionFragments = [],+ selectedMockupMotionFragment = null,+ selectedMockupMotionFragmentId = null,+ onAddOrReplaceMotionPreset,+ onUpdateMockupMotionFragment,+ onSelectMockupMotionFragment,+ onDeleteMockupMotionFragment,}: ExtendedControlPanelProps) {const t = useTranslations("controlPanel");const { imagePhoneActive } = useMockup3dContext();-+ const [isGlobalMotionEnabled, setIsGlobalMotionEnabled] = useState(false);return (<div className="relative w-full sm:w-[320px] h-screen bg-[#141417] border-r border-white/10 flex flex-col shrink-0" role="complementary" aria-label="Control panel"><header className="flex items-center justify-between h-13 p-2 border-b border-white/10 shrink-0" role="banner">@@ -295,19 +304,25 @@ export function ControlPanel({/></Suspense>)}- {/*{activeTool === "motion" && (- <Suspense >- {mediaType === "image"- ? <ImageMotionMenu- backgroundColorCss={undefined}- backgroundTab={backgroundTab}- selectedWallpaper={selectedWallpaper}- selectedImageUrl={selectedImageUrl}- />- : <MotionMenu />}+ <Suspense fallback={<MotionMenuSkeleton />}>+ <MotionMenu+ fragments={mockupMotionFragments}+ selectedFragment={selectedMockupMotionFragment}+ onAddOrReplacePreset={(presetId) => onAddOrReplaceMotionPreset?.(presetId)}+ onUpdateSelectedFragment={(updates) =>+ selectedMockupMotionFragmentId &&+ onUpdateMockupMotionFragment?.(selectedMockupMotionFragmentId, updates)+ }+ onSelectFragment={(id) => onSelectMockupMotionFragment?.(id)}+ onDeleteFragment={(id) => onDeleteMockupMotionFragment?.(id)}+ mediaType={mediaType}+ mockupId={mockupId}+ isGlobalMotionEnabled={isGlobalMotionEnabled}+ onToggleGlobalMotion={setIsGlobalMotionEnabled}+ /></Suspense>- )} */}+ )}{activeTool === "video" && (<Suspense fallback={<VideosMenuSkeleton />}>diff --git a/app/components/ui/editor/EditorTopBar.tsx b/app/components/ui/editor/EditorTopBar.tsxindex d770841..a7bf9e5 100644--- a/app/components/ui/editor/EditorTopBar.tsx+++ b/app/components/ui/editor/EditorTopBar.tsx@@ -174,16 +174,13 @@ export function EditorTopBar({<DropdownMenu.Root><DropdownMenu.Trigger asChild><button- className="flex items-center gap-2 pl-2 border-white/10 hover:opacity-80 transition-opacity focus:outline-none"+ className="flex items-center gap-1.5 px-2 border-white/10 hover:opacity-80 transition-opacity focus:outline-none"aria-label={t("auth.userMenu")}>- <div className="hidden sm:flex flex-col items-end leading-none">- <span className="text-[11px] font-medium text-white max-w-20 truncate">{displayName}</span>- <span className="text-[11px] text-neutral-500 max-w-30 truncate">{user.email}</span>- </div><div className="h-8 w-8 rounded-full border border-white/10 bg-neutral-900 overflow-hidden shrink-0 relative"><Image src={avatarUrl} alt={displayName} fill sizes="32px" className="object-cover" unoptimized /></div>+ <Icon icon="mdi:chevron-down" width="16" className="text-white/70" /></button></DropdownMenu.Trigger>diff --git a/app/components/ui/editor/LabelSidebar.tsx b/app/components/ui/editor/LabelSidebar.tsxindex 6f5ba12..f5f36e8 100644--- a/app/components/ui/editor/LabelSidebar.tsx+++ b/app/components/ui/editor/LabelSidebar.tsx@@ -1,8 +1,9 @@interface LabelSidebarProps {audioTracksCount?: number;+ motionTracksCount?: number;}-export default function LabelSidebar({ audioTracksCount = 0 }: LabelSidebarProps) {+export default function LabelSidebar({ audioTracksCount = 0, motionTracksCount = 0 }: LabelSidebarProps) {return (<div className="absolute left-0 top-0 bottom-0 w-14 shrink-0 border-r border-white/5 flex flex-col bg-[#0D0D11] z-30"><div className="h-5.5 border-b border-white/5" />@@ -11,17 +12,22 @@ export default function LabelSidebar({ audioTracksCount = 0 }: LabelSidebarProps<span className="text-[9px] uppercase font-semibold tracking-wider text-zinc-500">Video</span></div>- <div className={`flex items-center px-3 border-t border-white/5 transition-all duration-300 ${- audioTracksCount > 0 ? 'h-10' : 'h-16'- }`}>+ <div className={`flex items-center px-3 border-t border-white/5 transition-all duration-300 ${audioTracksCount > 0 ? 'h-14' : 'h-16'+ }`}><span className="text-[9px] uppercase font-semibold tracking-wider text-zinc-500">Zoom</span></div>{audioTracksCount > 0 && (- <div className="h-10 flex items-center px-3 border-t border-white/5 bg-white/1">+ <div className="h-14 flex items-center px-3 border-t border-white/5 bg-white/1"><span className="text-[9px] uppercase font-semibold tracking-wider text-zinc-500">Audio</span></div>)}++ {motionTracksCount > 0 && (+ <div className="h-14 flex items-center px-3 border-t border-white/5 bg-white/1">+ <span className="text-[9px] uppercase font-semibold tracking-wider text-zinc-500">Motion</span>+ </div>+ )}</div>);}\ No newline at end of filediff --git a/app/components/ui/editor/MockupMotionTrackItem.tsx b/app/components/ui/editor/MockupMotionTrackItem.tsxnew file mode 100644index 0000000..84353a1--- /dev/null+++ b/app/components/ui/editor/MockupMotionTrackItem.tsx@@ -0,0 +1,230 @@+"use client";++import { useState, useCallback, useEffect, useMemo } from "react";+import { motion, useMotionValue } from "framer-motion";+import type { MockupMotionFragment } from "@/lib/mockup-motion";+import { MOCKUP_MOTION_PRESETS } from "@/lib/mockup-motion";+import { useTranslations } from "next-intl";++const MIN_FRAGMENT_DURATION = 0.3;++interface MockupMotionTrackItemProps {+ fragment: MockupMotionFragment;+ isSelected: boolean;+ contentWidth: number;+ videoDuration: number;+ contentDuration: number;+ onSelect: () => void;+ onUpdate: (updates: Partial<MockupMotionFragment>) => void;+ onDelete: () => void;+ onDragStateChange?: (isDragging: boolean) => void;+ otherFragments: MockupMotionFragment[];+}++export function MockupMotionTrackItem({+ fragment,+ isSelected,+ contentWidth,+ videoDuration,+ contentDuration,+ onSelect,+ onUpdate,+ onDelete,+ onDragStateChange,+ otherFragments,+}: MockupMotionTrackItemProps) {+ const t = useTranslations("motionMenu");+ const [isDragging, setIsDragging] = useState(false);+ const [isResizing, setIsResizing] = useState<"start" | "end" | null>(null);++ const label = t(`presets.${fragment.presetId}`);++ const timeToPixels = useCallback(+ (time: number) => (time / videoDuration) * contentWidth,+ [videoDuration, contentWidth]+ );+ const pixelsToTime = useCallback(+ (pixels: number) => (pixels / contentWidth) * videoDuration,+ [contentWidth, videoDuration]+ );++ const fragmentX = useMotionValue(timeToPixels(fragment.startTime));+ const fragmentWidth = useMotionValue(timeToPixels(fragment.endTime - fragment.startTime));++ useEffect(() => {+ if (!isDragging && !isResizing) {+ fragmentX.set(timeToPixels(fragment.startTime));+ fragmentWidth.set(timeToPixels(fragment.endTime - fragment.startTime));+ }+ }, [fragment.startTime, fragment.endTime, isDragging, isResizing, timeToPixels, fragmentX, fragmentWidth]);++ const leftLimit = useMemo(() => {+ const ends = otherFragments+ .filter((f) => f.endTime <= fragment.startTime)+ .map((f) => f.endTime);+ return ends.length > 0 ? Math.max(...ends) : 0;+ }, [otherFragments, fragment.startTime]);++ const rightLimit = useMemo(() => {+ const starts = otherFragments+ .filter((f) => f.startTime >= fragment.endTime)+ .map((f) => f.startTime);+ return starts.length > 0 ? Math.min(...starts) : contentDuration;+ }, [otherFragments, fragment.endTime, contentDuration]);++ const leftLimitPx = timeToPixels(leftLimit);+ const rightLimitPx = timeToPixels(rightLimit);++ const handleBodyDrag = useCallback(+ (_: MouseEvent | TouchEvent | PointerEvent, info: { delta: { x: number } }) => {+ if (contentWidth === 0) return;+ const duration = fragment.endTime - fragment.startTime;+ const widthPx = timeToPixels(duration);+ const maxX = Math.min(timeToPixels(contentDuration - duration), rightLimitPx - widthPx);+ const minX = leftLimitPx;+ const newX = Math.max(minX, Math.min(maxX, fragmentX.get() + info.delta.x));+ fragmentX.set(newX);+ },+ [contentWidth, fragment, contentDuration, timeToPixels, fragmentX, leftLimitPx, rightLimitPx]+ );++ const handleBodyDragEnd = useCallback(() => {+ setIsDragging(false);+ onDragStateChange?.(false);+ const newStart = pixelsToTime(fragmentX.get());+ const duration = fragment.endTime - fragment.startTime;+ onUpdate({+ startTime: Math.max(0, newStart),+ endTime: Math.min(contentDuration, newStart + duration),+ });+ }, [fragmentX, pixelsToTime, fragment, contentDuration, onUpdate, onDragStateChange]);++ const handleResizeStartDrag = useCallback(+ (_: MouseEvent | TouchEvent | PointerEvent, info: { delta: { x: number } }) => {+ if (contentWidth === 0) return;+ const currentX = fragmentX.get();+ const currentWidth = fragmentWidth.get();+ const rightEdge = currentX + currentWidth;+ const minWidth = timeToPixels(MIN_FRAGMENT_DURATION);++ let newX = currentX + info.delta.x;+ newX = Math.max(leftLimitPx, newX);+ newX = Math.min(newX, rightEdge - minWidth);++ fragmentX.set(newX);+ fragmentWidth.set(rightEdge - newX);+ },+ [contentWidth, fragmentX, fragmentWidth, timeToPixels, leftLimitPx]+ );++ const handleResizeEndDrag = useCallback(+ (_: MouseEvent | TouchEvent | PointerEvent, info: { delta: { x: number } }) => {+ if (contentWidth === 0) return;+ const currentX = fragmentX.get();+ const currentWidth = fragmentWidth.get();+ const minWidth = timeToPixels(MIN_FRAGMENT_DURATION);+ const maxWidth = rightLimitPx - currentX;++ const newWidth = Math.max(minWidth, Math.min(maxWidth, currentWidth + info.delta.x));+ fragmentWidth.set(newWidth);+ },+ [contentWidth, fragmentWidth, fragmentX, timeToPixels, rightLimitPx]+ );++ const commitResize = useCallback(() => {+ setIsResizing(null);+ onDragStateChange?.(false);+ const newStart = pixelsToTime(fragmentX.get());+ const newEnd = pixelsToTime(fragmentX.get() + fragmentWidth.get());+ onUpdate({+ startTime: Math.max(0, newStart),+ endTime: Math.min(contentDuration, newEnd),+ });+ }, [fragmentX, fragmentWidth, pixelsToTime, contentDuration, onUpdate, onDragStateChange]);++ const isInteracting = isDragging || isResizing !== null;+ const duration = fragment.endTime - fragment.startTime;++ return (+ <motion.div+ className={`absolute h-[90%] top-[5%] rounded-md flex items-center border transition-shadow select-none ${isSelected || isInteracting+ ? "bg-orange-500/30 border-orange-400/70 shadow-[0_0_10px_rgba(251,146,60,0.35)] z-10"+ : "bg-orange-600/20 border-orange-500/35 hover:border-orange-500/60"+ } ${isDragging ? "cursor-grabbing" : "cursor-grab"}`}+ style={{+ x: fragmentX,+ width: fragmentWidth,+ top: "10%", height: "80%",+ background:+ isSelected || isInteracting+ ? "linear-gradient(180deg, rgba(251,146,60,0.5) 0%, rgba(194,65,12,0.4) 100%)"+ : "linear-gradient(180deg, rgba(245,158,11,0.2) 0%, rgba(146,64,14,0.15) 100%)",+ }}+ drag="x"+ dragConstraints={{ left: 0, right: contentWidth }}+ dragElastic={0}+ dragMomentum={false}+ onDrag={handleBodyDrag}+ onDragStart={() => {+ setIsDragging(true);+ onDragStateChange?.(true);+ }}+ onDragEnd={handleBodyDragEnd}+ onClick={(e) => {+ e.stopPropagation();+ onSelect();+ }}+ whileTap={{ scale: 0.98 }}+ role="slider"+ aria-valuemin={0}+ aria-valuemax={contentDuration}+ aria-valuenow={fragment.startTime}+ aria-label={`${label}, ${duration.toFixed(1)}s`}+ tabIndex={0}+ >+ <motion.div+ className="absolute left-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center"+ drag="x"+ dragConstraints={{ left: 0, right: 0 }}+ dragElastic={0}+ dragMomentum={false}+ onDrag={handleResizeStartDrag}+ onDragStart={() => {+ setIsResizing("start");+ onDragStateChange?.(true);+ }}+ onDragEnd={commitResize}+ onClick={(e) => e.stopPropagation()}+ >+ <div className={`w-1 h-5 rounded-full ${isResizing === "start" ? "bg-orange-300" : "bg-orange-400/60"}`} />+ </motion.div>++ <div className="flex-1 flex flex-col items-center justify-center pointer-events-none overflow-hidden px-2">+ <span className={`text-[10px] truncate ${isSelected || isInteracting ? "text-orange-200" : "text-orange-300/70"}`}>+ {label}+ </span>+ <span className={`text-[8px] truncate ${isSelected || isInteracting ? "text-orange-300/70" : "text-orange-400/45"}`}>+ {duration.toFixed(1)}s+ </span>+ </div>++ <motion.div+ className="absolute right-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center"+ drag="x"+ dragConstraints={{ left: 0, right: 0 }}+ dragElastic={0}+ dragMomentum={false}+ onDrag={handleResizeEndDrag}+ onDragStart={() => {+ setIsResizing("end");+ onDragStateChange?.(true);+ }}+ onDragEnd={commitResize}+ onClick={(e) => e.stopPropagation()}+ >+ <div className={`w-1 h-5 rounded-full ${isResizing === "end" ? "bg-orange-300" : "bg-orange-400/60"}`} />+ </motion.div>+ </motion.div>++ );+}\ No newline at end of filediff --git a/app/components/ui/editor/MotionMenu.tsx b/app/components/ui/editor/MotionMenu.tsxindex 20aa240..8f007af 100644--- a/app/components/ui/editor/MotionMenu.tsx+++ b/app/components/ui/editor/MotionMenu.tsx@@ -1,26 +1,150 @@"use client";-import { Icon } from "@iconify/react";+import { useTranslations } from "next-intl";+import { SliderControl } from "../../../../components/ui/SliderControl";+import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";+import { MOCKUP_MOTION_PRESETS, type MockupMotionPresetId, MockupMotionFragment, } from "@/lib/mockup-motion";+import { MotionPresetIcon, MotionPresetIconStyles, } from "../../../../components/ui/MotionPresetIcon";+import { Toggle } from "@/components/ui/toggle";++interface MotionMenuProps {+ fragments: MockupMotionFragment[];+ selectedFragment: MockupMotionFragment | null;+ onAddOrReplacePreset: (presetId: MockupMotionPresetId) => void;+ onUpdateSelectedFragment: (updates: Partial<MockupMotionFragment>) => void;+ onSelectFragment: (id: string | null) => void;+ onDeleteFragment: (id: string) => void;+ mediaType?: "video" | "image";+ mockupId?: string;+ isGlobalMotionEnabled?: boolean;+ onToggleGlobalMotion?: (enabled: boolean) => void;+}++const CATEGORY_ORDER = ["Entrance", "Continue", "Exit"] as const;-export function MotionMenu() {+export function MotionMenu({+ selectedFragment,+ onAddOrReplacePreset,+ onUpdateSelectedFragment,+ mediaType = "video",+ isGlobalMotionEnabled = false,+ onToggleGlobalMotion,+}: MotionMenuProps) {+ const t = useTranslations("motionMenu");+ const { imagePhoneActive } = useMockup3dContext();+ const hasMockup2D = mediaType === "video" && !imagePhoneActive;++ if (!hasMockup2D) {+ return (+ <div className="p-4 flex flex-col gap-5 h-full relative">+ <div className="flex items-center justify-between shrink-0">+ <div className="flex items-center gap-2 text-white font-medium">+ <Icon icon="ph:film-strip-bold" width="20" aria-hidden="true" />+ <span>{t("title")}</span>+ </div>+ {onToggleGlobalMotion && (+ <label className="flex items-center gap-2 text-xs text-white/40">+ <span>{t("globalMotionLabel")}</span>+ <Toggle checked={isGlobalMotionEnabled} onChange={onToggleGlobalMotion} disabled={true} />+ </label>+ )}+ </div>+ <div className="group bg-[#09090B] border border-dashed border-white/10 squircle-element p-8 text-center transition-colors">+ <div className="w-12 h-12 rounded-full bg-white/5 border border-white/10 flex items-center justify-center mx-auto mb-4 group-hover:scale-105 transition-transform">+ <Icon icon="ph:frame-corners-bold" width="24" className="text-white/40 group-hover:text-white/70 transition-colors" aria-hidden="true" />+ </div>+ <p className="text-sm font-medium text-white/70 mb-1">+ {t("empty2D.title")}+ </p>+ <p className="text-xs text-white/40">{t("empty2D.description")}</p>+ </div>+ </div>+ );+ }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 className="p-4 flex flex-col gap-4 h-full relative min-h-0">+ <MotionPresetIconStyles />+ <div className="flex items-center justify-between shrink-0">+ <div className="flex items-center gap-2 text-white font-medium">+ <Icon icon="ph:film-strip-bold" width="20" aria-hidden="true" />+ <span>{t("title")}</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]">- Animaciones- </span>+ {onToggleGlobalMotion && (+ <label className="flex items-center gap-2 text-xs text-white/40">+ <span>{t("globalMotionLabel")}</span>+ <Toggle checked={isGlobalMotionEnabled} onChange={onToggleGlobalMotion} activeColor="bg-orange-600" />+ </label>+ )}</div>- {/* Grid */}- <div className="grid grid-cols-2 gap-4 items-start">-+ <div className="flex-1 min-h-0 overflow-y-auto custom-scrollbar -mx-1 px-1">+ <div className="flex flex-col gap-6">+ {CATEGORY_ORDER.map((category) => {+ const presets = MOCKUP_MOTION_PRESETS.filter((p) => p.category === category);+ if (presets.length === 0) return null;++ return (+ <div key={category}>+ <div className="flex items-center gap-2 mb-3">+ <span className="text-[11px] font-bold uppercase tracking-widest text-white/70">+ {t(`categories.${category}`)}+ </span>+ </div>+ <div className="grid grid-cols-2 gap-2.5">+ {presets.map((preset) => {+ const isActive = selectedFragment?.presetId === preset.id;+ return (+ <button+ key={preset.id}+ onClick={() => onAddOrReplacePreset(preset.id)}+ className={`group flex flex-col gap-2 rounded-xl border p-2 text-left transition-all duration-200 hover:scale-[1.015] active:scale-[0.98] ${isActive ? "border-orange-600/50 bg-orange-[0.05]" : "border-neutral-800 bg-black hover:border-neutral-700 hover:bg-neutral-900"}`}+ >+ <div className="relative w-full aspect-[16/10] rounded-lg overflow-hidden">+ <MotionPresetIcon+ presetId={preset.id}+ category={preset.category}+ active={isActive}+ fill+ forceAnimate={isGlobalMotionEnabled}+ />+ {isActive && (+ <div className="absolute top-1.5 right-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-orange-600/50 backdrop-blur-sm">+ <Icon icon="ph:check-bold" className="text-white" width="9" aria-hidden="true" />+ </div>+ )}+ </div>+ <span className={`text-[11px] leading-tight truncate transition-colors ${isActive ? "text-white" : "text-neutral-400 group-hover:text-white"}`} >+ {t(`presets.${preset.id}`)}+ </span>+ </button>+ );+ })}+ </div>+ </div>+ );+ })}+ </div></div>++ {selectedFragment && (+ <div className="flex flex-col gap-4 pt-4 border-t border-white/5">+ <SliderControl+ icon="mdi:tune-variant"+ label={t("controls.intensity")}+ value={selectedFragment?.intensity ?? 50}+ min={0} max={100}+ onChange={(v: number) => selectedFragment && onUpdateSelectedFragment({ intensity: v })}+ />+ <SliderControl+ icon="mdi:speedometer"+ label={t("controls.speed")}+ value={selectedFragment?.speed ?? 50}+ min={0} max={100}+ onChange={(v: number) => selectedFragment && onUpdateSelectedFragment({ speed: v })}+ />+ </div>+ )}</div>);}\ No newline at end of filediff --git a/app/components/ui/editor/PhotoEditorPlaceholder.tsx b/app/components/ui/editor/PhotoEditorPlaceholder.tsxindex c997db0..d2f5c22 100644--- a/app/components/ui/editor/PhotoEditorPlaceholder.tsx+++ b/app/components/ui/editor/PhotoEditorPlaceholder.tsx@@ -447,7 +447,7 @@ export function PhotoEditorPlaceholder({return (<div className={`flex flex-col bg-black border-t border-white/10 ${className}`}>- <div className="h-13 shrink-0 border-t border-white/10 flex items-center justify-between px-3 bg-[#0D0D11] overflow-x-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">+ <div className="h-12 shrink-0 border-t border-white/10 flex items-center justify-between px-3 bg-[#0D0D11] overflow-x-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden"><div className="flex items-center gap-2 text-white/70 whitespace-nowrap shrink-0"><Icon icon="mdi:tune-vertical" width={16} aria-hidden="true" /><span className="hidden sm:flex text-xs font-semibold tracking-wide uppercase">diff --git a/app/components/ui/editor/PlayerControls.tsx b/app/components/ui/editor/PlayerControls.tsxindex 741ae74..4f3a811 100644--- a/app/components/ui/editor/PlayerControls.tsx+++ b/app/components/ui/editor/PlayerControls.tsx@@ -105,7 +105,7 @@ export function PlayerControls({return (<div- className="h-13 shrink-0 border-t border-white/10 flex items-center justify-between px-3 bg-[#0D0D11]"+ className="h-12 shrink-0 border-t border-white/10 flex items-center justify-between px-3 bg-[#0D0D11]"role="toolbar"aria-label={t("toolbar")}>diff --git a/app/components/ui/editor/Timeline.tsx b/app/components/ui/editor/Timeline.tsxindex fe4d93f..53b1cc1 100644--- a/app/components/ui/editor/Timeline.tsx+++ b/app/components/ui/editor/Timeline.tsx@@ -10,6 +10,7 @@ import { AudioFragmentTrackItem } from "./AudioFragmentTrackItem";import { VideoClipTrackItem } from "./VideoClipTrackItem";import { Icon } from "@iconify/react";import { useTranslations } from "next-intl";+import { MockupMotionTrackItem } from "./MockupMotionTrackItem";const DEFAULT_ZOOM_FRAGMENT_DURATION = 2;@@ -40,6 +41,12 @@ export function Timeline({selectedAudioTrackId,onSelectAudioTrack,onUpdateAudioTrack,+ mockupMotionFragments = [],+ selectedMockupMotionFragmentId,+ onSelectMockupMotionFragment,+ onUpdateMockupMotionFragment,+ onDeleteMockupMotionFragment,+ onActivateMotionTool,globalSpeed = 1,isPlaying = false,onZoomChange,@@ -362,9 +369,18 @@ export function Timeline({return (<div ref={containerRef} className="flex flex-col w-full pr-2">- <div className="h-38 shrink-0 bg-[#0D0D11] border-t border-white/10 flex flex-col font-mono text-[11px]">+ <div className={`${(audioTracks.length > 0 && mockupMotionFragments.length > 0)+ ? 'h-64'+ : (audioTracks.length > 0 || mockupMotionFragments.length > 0)+ ? 'h-50'+ : 'h-38'+ } shrink-0 bg-[#0D0D11] border-t border-white/10 flex flex-col font-mono text-[11px]`}>+<div className="flex-1 flex flex-col relative overflow-hidden">- <LabelSidebar audioTracksCount={audioTracks.length} />+ <LabelSidebar+ audioTracksCount={audioTracks.length}+ motionTracksCount={mockupMotionFragments.length}+ /><divref={trackRef}@@ -411,7 +427,7 @@ export function Timeline({</motion.div><div- className="h-[22px] border-b border-white/10 relative shrink-0 cursor-pointer bg-zinc-900/40 select-none overflow-hidden"+ className="h-[18px] border-b border-white/10 relative shrink-0 cursor-pointer bg-zinc-900/40 select-none overflow-hidden"onClick={handleTrackClick}><div@@ -549,7 +565,7 @@ export function Timeline({</div><div- className="h-[55px] shrink-0 w-full flex items-center relative"+ className="min-h-[55px] shrink-0 w-full flex items-center relative"onMouseMove={(e) => {if (isDraggingZoomFragment) return;const rect = e.currentTarget.getBoundingClientRect();@@ -603,7 +619,7 @@ export function Timeline({))}{ghostState?.validPosition && (<motion.div- className="absolute top-[10%] h-[80%] pointer-events-none"+ className="absolute top-[5%] h-[90%] pointer-events-none"initial={false}animate={{left: (ghostState.validPosition.startTime / scaledDuration) * contentWidth,@@ -631,7 +647,7 @@ export function Timeline({</div>{audioTracks.length > 0 && (- <div className="h-[55px] shrink-0 w-full flex items-center relative">+ <div className="min-h-[55px] shrink-0 w-full flex items-center relative"><div className="h-full w-full flex items-center relative">{audioTracks.map((track) => {const audio = uploadedAudios?.find(a => a.id === track.audioId);@@ -654,6 +670,35 @@ export function Timeline({</div></div>)}+ {mockupMotionFragments.length > 0 && (+ <div+ className="min-h-[55px] shrink-0 w-full flex items-center relative"+ onClick={(e) => {+ e.stopPropagation();+ onSelectMockupMotionFragment?.(null);+ }}+ >+ <div className="h-full w-full relative">+ {mockupMotionFragments.map((fragment) => (+ <MockupMotionTrackItem+ key={fragment.id}+ fragment={fragment}+ isSelected={fragment.id === selectedMockupMotionFragmentId}+ contentWidth={contentWidth}+ videoDuration={scaledDuration}+ contentDuration={validDuration}+ otherFragments={mockupMotionFragments.filter((f) => f.id !== fragment.id)}+ onSelect={() => {+ onSelectMockupMotionFragment?.(fragment.id);+ onActivateMotionTool?.();+ }}+ onUpdate={(updates) => onUpdateMockupMotionFragment?.(fragment.id, updates)}+ onDelete={() => onDeleteMockupMotionFragment?.(fragment.id)}+ />+ ))}+ </div>+ </div>+ )}</div></div>diff --git a/app/components/ui/editor/ToolsSidebar.tsx b/app/components/ui/editor/ToolsSidebar.tsxindex 1d4c6ae..4943128 100644--- a/app/components/ui/editor/ToolsSidebar.tsx+++ b/app/components/ui/editor/ToolsSidebar.tsx@@ -262,7 +262,7 @@ export function ToolsSidebar({badgeStyle="premium"/>- {/* {isPhotoMode && (+ {!isPhotoMode && (<SidebarToolicon="mage:box-3d"label={t("tools.motion")}@@ -276,7 +276,7 @@ export function ToolsSidebar({badge={t("tools.newTool")}badgeStyle="premium"/>- )} */}+ )}{/* Video-specific tools - hidden in photo mode */}{!isPhotoMode && (diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsxindex edc6a68..ff11e8e 100644--- a/app/components/ui/editor/VideoCanvas.tsx+++ b/app/components/ui/editor/VideoCanvas.tsx@@ -3,35 +3,38 @@import { useRef, useEffect, useImperativeHandle, useMemo, useState, useCallback, memo } from "react";import dynamic from "next/dynamic";import type { VideoCanvasHandle, VideoCanvasProps, VideoThumbnail } from "@/types";-import type { ImageElement, SvgElement } from "@/types/canvas-elements.types";+import type { ImageElement } from "@/types/canvas-elements.types";import { ASPECT_RATIO_DIMENSIONS } from "@/types";import { getWallpaperUrl } from "@/lib/wallpaper.utils";-import { drawRoundedRect, drawRoundedRectBottomOnly, calculateScaledPadding, applyCanvasBackground, getAspectRatioStyle, getAspectRatioNumber, Corner, getCornerStyle, getNearestCorner, snapRotation, drawImageCover, getMockupOuterRadius, CORNER_SIGNS } from "@/lib/canvas.utils";-import { drawMockupToCanvas } from "@/lib/mockup-canvas.utils";+import { calculateScaledPadding, applyCanvasBackground, getAspectRatioStyle, getAspectRatioNumber, Corner, getCornerStyle, getNearestCorner, snapRotation, drawImageCover, getMockupOuterRadius, CORNER_SIGNS } from "@/lib/canvas.utils";import { speedToTransitionMs, ZOOM_EASING, calculateZoomPhaseState, zoomLevelToFactor } from "@/types/zoom.types";import type { ZoomFragment } from "@/types/zoom.types";import PlaceholderEditor from "../PlaceholderEditor";import { MockupWrapper } from "./mockups/MockupWrapper";import { DEFAULT_MOCKUP_CONFIG } from "@/types/mockup.types";import { calculateSmoothZoom } from "@/lib/canvas.utils";-import { getSvgDataUrl } from "@/components/canvas-svg";-import { VIDEO_Z_INDEX, BOTTOM_ONLY_RADIUS_MOCKUPS, SELF_SHADOWING_MOCKUPS } from "@/lib/constants";+import { VIDEO_Z_INDEX } from "@/lib/constants";import { applyPerspective3D, disposePerspective3D } from "@/lib/perspective3d";import { RotationHandleIcon } from "@/components/ui/RotationHandleIcon";import { CanvasElementsLayer, ElementResizeStart } from "./CanvasElementsLayer";import { EditorHoverTooltip } from "./EditorHoverTooltip";import { LayersPanel } from "./LayersPanel";import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";-import { PHONE_H, PHONE_W, DEVICE_3D_DIMENSIONS, DEVICE_VIEWER_DEFAULTS, PHONE_DEVICE_URLS, type ImageMaskConfigLike } from "@/lib/phone3d.utils";+import { PHONE_H, PHONE_W, DEVICE_3D_DIMENSIONS, DEVICE_VIEWER_DEFAULTS, PHONE_DEVICE_URLS } from "@/lib/phone3d.utils";import { Viewer3DControls } from "@/lib/viewer-controls3d";import { ControlsPopup } from "@/components/ui/ControlsPopup";import { CanvasContextMenu } from "@/components/ui/CanvasContextMenu";import { Viewer3DControlsBridge } from "@/components/ui/Viewer3DControlsBridge";-import { applyGradientMaskToRegion, GetMediaMaskStyles } from "@/lib/media-mask.utils";+import { GetMediaMaskStyles } from "@/lib/media-mask.utils";import { MediaContent } from "@/components/ui/MediaContent";import { RotationGuideLine } from "@/components/ui/RotationGuideLine";import { drawCameraOverlayToCtx } from "@/lib/camera-overlay.utils";import DropMedia from "@/components/ui/DropMedia";+import { renderCanvasElements } from "@/lib/canvas-elements-render.utils";+import { drawMaskedImage } from "@/lib/masked-image-draw.utils";+import { drawMockupAndMedia, type MockupDrawContext } from "@/lib/mockup-media-draw.utils";+import { drawPhone3DCompositeWithZoom, type Phone3DCompositeContext } from "@/lib/phone3d-composite-draw.utils";+import { buildMockupMotionCss, MockupMotionTransform, REST_MOCKUP_MOTION, sampleCombinedMockupMotion } from "@/lib/mockup-motion";export type { VideoCanvasHandle, VideoCanvasProps };@@ -68,6 +71,7 @@ const IPadMini63DViewer = dynamic(function VideoCanvasInner({activeTool: _activeTool,mediaType = "video",+ isPlaying = false,imageUrl = null,imageRef,imageTransform,@@ -127,6 +131,8 @@ function VideoCanvasInner({imageZoomScale = 1,onImageZoomScaleChange,otherSelectionActive = false,+ mockupMotionFragments = [],+ videoDuration = 0,}: VideoCanvasProps & { ref?: React.Ref<VideoCanvasHandle> }) {const wallpaperUrl = getWallpaperUrl(selectedWallpaper);@@ -176,9 +182,11 @@ function VideoCanvasInner({};}, []);- // Ref for the non-passive Ctrl+scroll wheel handler (React's onWheel is always passive).- // Updated each render so the closure always has the latest state values.const ctrlScrollWheelRef = useRef<((e: WheelEvent) => void) | null>(null);+ const imagePhoneActiveRef = useRef(imagePhoneActive);+ useEffect(() => { imagePhoneActiveRef.current = imagePhoneActive; }, [imagePhoneActive]);+ const paddingRef = useRef(padding);+ useEffect(() => { paddingRef.current = padding; }, [padding]);// WebGL canvas from image phone Phone3DViewer, captured via onMount prop for exportconst imagePhoneCanvasRef = useRef<HTMLCanvasElement | null>(null);const imagePhoneApiRef = useRef<{@@ -280,9 +288,14 @@ function VideoCanvasInner({// the "none" mockup container to the real letterboxed contain-box instead// of the full available area.const [mediaAspect, setMediaAspect] = useState<number | null>(null);-const lastSetVideoUrlRef = useRef<string | null>(null);- const preservedVideoStateRef = useRef<{ time: number; playing: boolean } | null>(null);+ const lastLogicalUrlRef = useRef<string | null>(null);++ const currentTimePropRef = useRef(currentTime);+ useEffect(() => { currentTimePropRef.current = currentTime; }, [currentTime]);++ const isPlayingPropRef = useRef(isPlaying);+ useEffect(() => { isPlayingPropRef.current = isPlaying; }, [isPlaying]);const imagePhoneRescaleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const cameraDragRef = useRef<{pointerId: number;@@ -337,44 +350,34 @@ function VideoCanvasInner({useEffect(() => {const targetUrl = activeClipUrl ?? videoUrl;if (videoRef.current && targetUrl) {- // Always set src if video element has no src, src is empty, or we just changed mockup- const videoSrc = videoRef.current.src;+ const videoEl = videoRef.current;+ const videoSrc = videoEl.src;const needsSrc = !videoSrc || videoSrc === '' || videoSrc === window.location.href;- const isNewUrl = targetUrl !== lastSetVideoUrlRef.current;+ const isNewAssignment = targetUrl !== lastSetVideoUrlRef.current;++ if (needsSrc || isNewAssignment) {+ const isSameLogicalContent = targetUrl === lastLogicalUrlRef.current;- if (needsSrc || isNewUrl) {- videoRef.current.src = targetUrl;+ videoEl.src = targetUrl;lastSetVideoUrlRef.current = targetUrl;- if (preservedVideoStateRef.current) {- const { time, playing } = preservedVideoStateRef.current;- videoRef.current.currentTime = time;- if (playing) {- videoRef.current.play().catch(() => {- // Ignore play errors (may happen if video not ready)+ if (isSameLogicalContent) {+ videoEl.currentTime = currentTimePropRef.current;+ if (isPlayingPropRef.current) {+ videoEl.play().catch(() => {});}- preservedVideoStateRef.current = null;}++ lastLogicalUrlRef.current = targetUrl;}}if (!videoUrl && !activeClipUrl) {lastSetVideoUrlRef.current = null;+ lastLogicalUrlRef.current = null;}}, [videoUrl, activeClipUrl, videoRef, mockupId]);- // Preserve video state when mockup changes (detect unmount via cleanup)- useEffect(() => {- return () => {- if (videoRef.current && videoUrl) {- preservedVideoStateRef.current = {- time: videoRef.current.currentTime,- playing: !videoRef.current.paused,- };- }- };- }, [mockupId, videoUrl, videoRef]);-// Track the real intrinsic aspect ratio of the video so the "none"useEffect(() => {if (mediaType !== "video" || activeMediaAspect) return;@@ -434,11 +437,10 @@ function VideoCanvasInner({useEffect(() => {ctrlScrollWheelRef.current = (e: WheelEvent) => {if (!e.ctrlKey) return;- if (imagePhoneActive) {+ if (imagePhoneActiveRef.current) {e.preventDefault();e.stopImmediatePropagation();- const next = Math.max(0.3, Math.min(3, imagePhoneScale * (e.deltaY < 0 ? 1.05 : 0.95)));- setImagePhoneScale(next);+ setImagePhoneScale(prev => Math.max(0.3, Math.min(3, prev * (e.deltaY < 0 ? 1.05 : 0.95))));setImagePhoneZoomVisible(true);if (imagePhoneZoomTimerRef.current) clearTimeout(imagePhoneZoomTimerRef.current);imagePhoneZoomTimerRef.current = setTimeout(() => setImagePhoneZoomVisible(false), 1200);@@ -449,7 +451,7 @@ function VideoCanvasInner({e.stopImmediatePropagation();const PADDING_MIN = 0;const PADDING_MAX = 30;- const base = pendingPaddingRef.current ?? padding;+ const base = pendingPaddingRef.current ?? paddingRef.current;const step = Math.min(1.5, Math.max(0.15, Math.abs(e.deltaY) * 0.015));const next = Math.max(PADDING_MIN, Math.min(PADDING_MAX, base + (e.deltaY < 0 ? -step : step)));pendingPaddingRef.current = next;@@ -463,7 +465,7 @@ function VideoCanvasInner({}}};- });+ }, [mediaType, onPaddingChange, setImagePhoneScale]);useEffect(() => {const el = previewContainerRef.current;@@ -536,18 +538,12 @@ function VideoCanvasInner({if (isRestoringProjectRef?.current) return;if (!pendingAspectRescaleRef.current) {- // Resize incidental: NO fue un cambio deliberado de aspect ratio.- // Solo resincronizamos el ancho base para no acumular drift,- // sin tocar la posición ni la escala del overlay.if (imagePhoneRefWidth === 0 || Math.abs(canvasDimensions.width - imagePhoneRefWidth) > 0.5) {setImagePhoneRefWidth(canvasDimensions.width);}return;}- // Cambio deliberado de aspect ratio: acá sí corresponde reescalar- // proporcionalmente, porque el canvas de export realmente cambió- // de tamaño por una acción del usuario.pendingAspectRescaleRef.current = false;if (imagePhoneRefWidth > 0 && Math.abs(canvasDimensions.width - imagePhoneRefWidth) > 0.5) {const ratio = canvasDimensions.width / imagePhoneRefWidth;@@ -690,6 +686,13 @@ function VideoCanvasInner({const hasMask = Object.keys(maskStyles).length > 0;const hasMockup = mockupId && mockupId !== "none";+ const hasMockup2DMotion = mediaType === "video" && !imagePhoneActive && mockupMotionFragments.length > 0;++ const mockupMotionPreview = useMemo<MockupMotionTransform>(+ () => hasMockup2DMotion ? sampleCombinedMockupMotion(mockupMotionFragments, currentTime) : REST_MOCKUP_MOTION,+ [hasMockup2DMotion, mockupMotionFragments, currentTime]+ );+// Effective aspect ratio for the "none" mockup contain-box, adjusted for// any active crop — mirrors the same math used in drawFrame's computeContainer.const effectiveMediaAspect = mediaType === "video" ? (activeMediaAspect ?? mediaAspect) : mediaAspect;@@ -1238,165 +1241,6 @@ function VideoCanvasInner({}};- const drawMaskedImage = (- destCtx: CanvasRenderingContext2D,- img: CanvasImageSource,- x: number,- y: number,- w: number,- h: number,- maskConfig?: ImageMaskConfigLike | null- ) => {- if (!maskConfig?.enabled) {- destCtx.drawImage(img, x, y, w, h);- return;- }- const safeW = Math.max(1, Math.round(w));- const safeH = Math.max(1, Math.round(h));- let off = maskCompositeCanvasRef.current;- if (!off) {- off = document.createElement('canvas');- maskCompositeCanvasRef.current = off;- }- if (off.width !== safeW || off.height !== safeH) {- off.width = safeW;- off.height = safeH;- }- const offCtx = off.getContext('2d');- if (!offCtx) {- destCtx.drawImage(img, x, y, w, h);- return;- }- offCtx.setTransform(1, 0, 0, 1, 0, 0);- offCtx.clearRect(0, 0, safeW, safeH);- offCtx.drawImage(img, 0, 0, safeW, safeH);- applyGradientMaskToRegion(offCtx, 0, 0, safeW, safeH, maskConfig);- destCtx.drawImage(off, x, y, w, h);- };-- // Helper function to render canvas elements (SVG, images, text)- const renderCanvasElements = async (- ctx: CanvasRenderingContext2D,- elements: typeof canvasElements,- canvasWidth: number,- canvasHeight: number,- behindVideo: boolean- ) => {- const filteredElements = elements.filter(el =>- behindVideo ? el.zIndex < VIDEO_Z_INDEX : el.zIndex >= VIDEO_Z_INDEX- );- const sortedElements = [...filteredElements].sort((a, b) => a.zIndex - b.zIndex);-- // Use smaller dimension as reference for consistent scaling across different aspect ratios- const referenceSize = Math.min(canvasWidth, canvasHeight);-- for (const element of sortedElements) {- if (element.type === "svg") {- const svgElement = element as SvgElement;- const svgDataUrl = getSvgDataUrl(svgElement.svgId, svgElement.color || "#FFFFFF");- if (!svgDataUrl) continue;-- const cacheKey = `${svgElement.svgId}-${svgElement.color || "#FFFFFF"}`;- let svgImage = svgImageCacheRef.current.get(cacheKey);- if (!svgImage || svgImage.src !== svgDataUrl) {- svgImage = new Image();- svgImageCacheRef.current.set(cacheKey, svgImage);- svgImage.src = svgDataUrl;- await new Promise<void>((resolve) => {- if (svgImage!.complete) resolve();- else { svgImage!.onload = () => resolve(); svgImage!.onerror = () => resolve(); }- });- } else if (!svgImage.complete) {- await new Promise<void>((resolve) => {- svgImage!.onload = () => resolve();- svgImage!.onerror = () => resolve();- setTimeout(resolve, 500);- });- }-- ctx.save();-- const elemX = (svgElement.x / 100) * canvasWidth;- const elemY = (svgElement.y / 100) * canvasHeight;- const elemWidth = (svgElement.width / 100) * referenceSize;- const elemHeight = (svgElement.height / 100) * referenceSize;-- // Translate to element position, rotate, then draw centered- ctx.translate(elemX, elemY);- ctx.rotate((svgElement.rotation * Math.PI) / 180);- ctx.globalAlpha = svgElement.opacity;-- ctx.drawImage(- svgImage,- -elemWidth / 2,- -elemHeight / 2,- elemWidth,- elemHeight- );-- ctx.restore();- } else if (element.type === "image") {- const img = elementImagesRef.current.get(element.imagePath);- if (!img) continue;-- ctx.save();-- const elemX = (element.x / 100) * canvasWidth;- const elemY = (element.y / 100) * canvasHeight;-- // Calculate element dimensions using reference size to maintain consistent scaling- const elemWidth = (element.width / 100) * referenceSize;- const elemHeight = (element.height / 100) * referenceSize;-- // For images, maintain the original aspect ratio- const imgAspectRatio = img.naturalWidth / img.naturalHeight;- let finalWidth = elemWidth;- let finalHeight = elemHeight;-- const elementAspectRatio = elemWidth / elemHeight;- if (imgAspectRatio > elementAspectRatio) {- finalHeight = elemWidth / imgAspectRatio;- } else {- finalWidth = elemHeight * imgAspectRatio;- }-- ctx.translate(elemX, elemY);- ctx.rotate((element.rotation * Math.PI) / 180);- ctx.globalAlpha = element.opacity;-- ctx.drawImage(- img,- -finalWidth / 2,- -finalHeight / 2,- finalWidth,- finalHeight- );-- ctx.restore();- } else if (element.type === "text") {- ctx.save();-- const elemX = (element.x / 100) * canvasWidth;- const elemY = (element.y / 100) * canvasHeight;-- ctx.translate(elemX, elemY);- ctx.rotate((element.rotation * Math.PI) / 180);- ctx.globalAlpha = element.opacity;-- const scaledFontSize = element.fontSize * (referenceSize / 1080);- const fontWeight = element.fontWeight === 'normal' ? '400' : element.fontWeight === 'medium' ? '500' : '700';- ctx.font = `${fontWeight} ${scaledFontSize}px ${element.fontFamily}`;- ctx.fillStyle = element.color;- ctx.textAlign = 'center';- ctx.textBaseline = 'middle';-- ctx.fillText(element.content, 0, 0);-- ctx.restore();- }- }- };-// Function to draw a frame on the export canvasconst drawFrame = async (highQuality: boolean = true, explicitTimelineTime?: number) => {const canvas = exportCanvasRef.current;@@ -1425,12 +1269,28 @@ function VideoCanvasInner({const scaledRadius = roundedCorners * (canvasLongSide / 896);const scaledShadowBlur = shadows * (canvasLongSide / 896) * 0.8;+ const frameTime = mediaType === "video" ? (explicitTimelineTime ?? (video ? video.currentTime : 0)) : 0;++ const mockupMotionForFrame: MockupMotionTransform | undefined = hasMockup2DMotion+ ? sampleCombinedMockupMotion(mockupMotionFragments, frameTime)+ : undefined;++ const mockupDrawCtx: MockupDrawContext = {+ videoTransform, imageTransform, apply3DToBackground, imageZoomScale, shadows,+ mockupId, mockupConfig, mediaType, cropArea, sourceWidth, sourceHeight,+ canvasWidth, canvasHeight, scaledRadius, scaledShadowBlur, shadowCacheRef,+ mockupMotion: mockupMotionForFrame,+ };++ const phone3dCtx: Phone3DCompositeContext = {+ imagePhoneCanvasRef, imagePhoneApiRef, canvasDimensions, imagePhoneDevice,+ imagePhoneScale, imagePhoneX, imagePhoneY, imagePhoneShadow, imagePhoneShadowColor,+ effectivePhoneMaskConfig, maskCompositeCanvasRef,+ };+ctx.setTransform(1, 0, 0, 1, 0, 0);ctx.clearRect(0, 0, canvasWidth, canvasHeight);- const frameTime = mediaType === "video"- ? (explicitTimelineTime ?? (video ? video.currentTime : 0))- : 0;const zoomState = calculateSmoothZoom(frameTime, zoomFragments);const zoomCenterX = canvasWidth / 2;const zoomCenterY = canvasHeight / 2;@@ -1479,119 +1339,6 @@ function VideoCanvasInner({return { containerX: cX, containerY: cY, containerWidth: cW, containerHeight: cH };};- // Shared helper: draw shadow + mockup + video into a 2D context- const DEG_TO_RAD = Math.PI / 180;- const drawMockupAndMedia = (- c: CanvasRenderingContext2D,- containerX: number, containerY: number, containerWidth: number, containerHeight: number,- source: HTMLVideoElement | HTMLImageElement, applyImageXform: boolean, is3DActive: boolean = false- ) => {- const vCX = containerX + containerWidth / 2;- const vCY = containerY + containerHeight / 2;- const txPx = (videoTransform.translateX / 100) * containerWidth;- const tyPx = (videoTransform.translateY / 100) * containerHeight;-- c.save();- c.translate(vCX + txPx, vCY + tyPx);- c.rotate(videoTransform.rotation * DEG_TO_RAD);-- if (applyImageXform && imageTransform && !apply3DToBackground) {- if (imageTransform.perspective && imageTransform.perspective > 0 && (imageTransform.rotateX !== 0 || imageTransform.rotateY !== 0)) {- const rotXR = imageTransform.rotateX * DEG_TO_RAD;- const rotYR = imageTransform.rotateY * DEG_TO_RAD;- const tanY2 = Math.tan(rotYR);- const tanX2 = Math.tan(rotXR);- const sX2 = 1 / Math.sqrt(1 + tanY2 * tanY2);- const sY2 = 1 / Math.sqrt(1 + tanX2 * tanX2);- c.transform(sX2, tanX2 * sY2, tanY2 * sX2, sY2, 0, 0);- }- c.rotate(imageTransform.rotateZ * DEG_TO_RAD);- c.scale(imageTransform.scale * imageZoomScale, imageTransform.scale * imageZoomScale);- const iTY = (imageTransform.translateY / 100) * containerHeight;- c.translate(0, iTY / (imageTransform.scale * imageZoomScale));- }- c.translate(-vCX, -vCY);-- // Shadow- if (shadows > 0 && !SELF_SHADOWING_MOCKUPS.includes(mockupId)) {- const shadowKey = `${containerWidth.toFixed(1)}x${containerHeight.toFixed(1)}|${scaledRadius.toFixed(1)}|${scaledShadowBlur.toFixed(1)}`;- let cached = shadowCacheRef.current;- if (!cached || cached.key !== shadowKey) {- const margin = Math.ceil(scaledShadowBlur * 3 + scaledShadowBlur * 0.3 + 8);- const buf = document.createElement('canvas');- buf.width = Math.ceil(containerWidth) + margin * 2;- buf.height = Math.ceil(containerHeight) + margin * 2;- const bctx = buf.getContext('2d');- if (bctx) {- bctx.shadowColor = 'rgba(0, 0, 0, 1)';- bctx.shadowBlur = scaledShadowBlur;- bctx.shadowOffsetY = scaledShadowBlur * 0.3;- bctx.fillStyle = 'black';- drawRoundedRect(bctx, margin, margin, containerWidth, containerHeight, scaledRadius);- bctx.fill();- }- cached = { key: shadowKey, canvas: buf, offsetX: margin, offsetY: margin };- shadowCacheRef.current = cached;- }- c.save();- c.drawImage(cached.canvas, containerX - cached.offsetX, containerY - cached.offsetY);- c.restore();- }-- // Mockup frame- const hasMockupLocal = mockupId && mockupId !== "none";- const mockupCfg = mockupConfig || DEFAULT_MOCKUP_CONFIG;- let vX = containerX, vY = containerY, vW = containerWidth, vH = containerHeight, vR = scaledRadius;-- if (hasMockupLocal) {- const mBlur = SELF_SHADOWING_MOCKUPS.includes(mockupId) ? scaledShadowBlur : 0;- const mr = drawMockupToCanvas(c, mockupId, mockupCfg, containerX, containerY, containerWidth, containerHeight, scaledRadius, mBlur, canvasWidth, canvasHeight);- vX = mr.contentX;- vY = mr.contentY;- vW = mr.contentWidth;- vH = mr.contentHeight;- vR = mockupId === "outline"- ? scaledRadius * 1.6- : (mockupId === "iphone-slim" || mockupId === "glass-curve" || mockupId === "glass-full")- ? scaledRadius * 2.5- : scaledRadius;- }-- c.save();- const bottomOnly = hasMockupLocal && BOTTOM_ONLY_RADIUS_MOCKUPS.includes(mockupId);- if (vR > 0) {- if (bottomOnly) {- drawRoundedRectBottomOnly(c, vX, vY, vW, vH, vR);- } else {- drawRoundedRect(c, vX, vY, vW, vH, vR);- }- c.clip();- } else {- c.beginPath();- c.rect(vX, vY, vW, vH);- c.clip();- }- if (mediaType === "video") {- if (is3DActive) {- c.filter = 'saturate(125%) contrast(110%) brightness(105%)';- } else {- c.filter = 'saturate(130%) contrast(104%) brightness(103%)';- }- }-- if (cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0)) {- const sX = (cropArea.x / 100) * sourceWidth;- const sY = (cropArea.y / 100) * sourceHeight;- const cW2 = (cropArea.width / 100) * sourceWidth;- const cH2 = (cropArea.height / 100) * sourceHeight;- c.drawImage(source, sX, sY, cW2, cH2, vX, vY, vW, vH);- } else {- c.drawImage(source, vX, vY, vW, vH);- }- c.restore();- c.restore();- };-if (mediaType === "image") {ctx.save();if (imageTransform && apply3DToBackground) {@@ -1612,14 +1359,14 @@ function VideoCanvasInner({ctx.translate(-zoomCenterX, -zoomCenterY + iTY);}drawBg(ctx);- await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, true);+ await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, true, svgImageCacheRef.current, elementImagesRef.current);const { containerX: cX, containerY: cY, containerWidth: cW, containerHeight: cH } = computeContainer();// Only draw the 2D mockup + media when the 3D phone overlay is NOT active.// In the preview, CSS opacity:0 hides the video layer; here we skip drawing it.if (!imagePhoneActive) {- drawMockupAndMedia(ctx, cX, cY, cW, cH, image!, true);+ drawMockupAndMedia(ctx, cX, cY, cW, cH, image!, true, false, mockupDrawCtx);}- await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, false);+ await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, false, svgImageCacheRef.current, elementImagesRef.current);// ── Composite image phone mockup (WebGL snapshot) onto export canvas ──if (imagePhoneActive && imagePhoneCanvasRef.current) {const phoneGL = imagePhoneCanvasRef.current;@@ -1653,10 +1400,10 @@ function VideoCanvasInner({}if (highQuality) {imagePhoneApiRef.current?.renderAt(drawW, drawH);- drawMaskedImage(ctx, phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH, effectivePhoneMaskConfig);+ drawMaskedImage(ctx, phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH, effectivePhoneMaskConfig, maskCompositeCanvasRef);imagePhoneApiRef.current?.restorePreview();} else {- drawMaskedImage(ctx, phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH, effectivePhoneMaskConfig);+ drawMaskedImage(ctx, phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH, effectivePhoneMaskConfig, maskCompositeCanvasRef);}}@@ -1664,7 +1411,9 @@ function VideoCanvasInner({return;}- const has3DEffect = zoomState.perspective > 0 && (zoomState.rotateX !== 0 || zoomState.rotateY !== 0);+ const motionHasTilt = !!mockupMotionForFrame && (mockupMotionForFrame.rotateX !== 0 || mockupMotionForFrame.rotateY !== 0);+ const has3DEffect =+ (zoomState.perspective > 0 && (zoomState.rotateX !== 0 || zoomState.rotateY !== 0)) || motionHasTilt;const hasZoom = zoomState.scale !== 1;let focusPxX = 0, focusPxY = 0;@@ -1672,10 +1421,7 @@ function VideoCanvasInner({focusPxX = (zoomState.focusX / 100) * canvasWidth;focusPxY = (zoomState.focusY / 100) * canvasHeight;}-- // Find target scale from the active/previous zoom fragment.- // We need S_target to compute the pivot point that gives identity at S=1- // and pins the focus to the canvas center at S=S_target.+const activeFragment = zoomFragments.find(f => frameTime >= f.startTime && frameTime <= f.endTime) ?? zoomFragments@@ -1732,7 +1478,7 @@ function VideoCanvasInner({ctx.save();applyVideoZoom(ctx);- await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, true);+ await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, true, svgImageCacheRef.current, elementImagesRef.current);ctx.restore();await drawCameraOverlayToCtx(ctx, canvasWidth, canvasHeight, cameraVideoRef.current, videoRef.current, cameraConfig);@@ -1743,16 +1489,21 @@ function VideoCanvasInner({fgCtx.save();fgCtx.translate(fgOffsetX, fgOffsetY);if (!imagePhoneActive) {- drawMockupAndMedia(fgCtx, containerX, containerY, containerWidth, containerHeight, video!, false, true);+ drawMockupAndMedia(fgCtx, containerX, containerY, containerWidth, containerHeight, video!, false, true, mockupDrawCtx);}fgCtx.restore();- applyPerspective3D(fgCanvas, zoomState.rotateX, zoomState.rotateY, zoomState.perspective / BLEED_FACTOR);+ applyPerspective3D(+ fgCanvas,+ zoomState.rotateX + (mockupMotionForFrame?.rotateX ?? 0),+ zoomState.rotateY + (mockupMotionForFrame?.rotateY ?? 0),+ (zoomState.perspective || mockupMotionForFrame?.perspectivePx || 900) / BLEED_FACTOR,+ );ctx.save();applyVideoZoom(ctx);ctx.drawImage(fgCanvas, -fgOffsetX, -fgOffsetY, fgWidth, fgHeight);ctx.restore();if (imagePhoneActive && imagePhoneCanvasRef.current) {- drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality, pivotX, pivotY);+ drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality, pivotX, pivotY, phone3dCtx);}} else {const hasVideoMask = !!(videoMaskConfig?.enabled && (@@ -1779,7 +1530,7 @@ function VideoCanvasInner({vlCtx.imageSmoothingEnabled = true;vlCtx.imageSmoothingQuality = 'high';if (!imagePhoneActive) {- drawMockupAndMedia(vlCtx, containerX, containerY, containerWidth, containerHeight, video!, false, false);+ drawMockupAndMedia(vlCtx, containerX, containerY, containerWidth, containerHeight, video!, false, false, mockupDrawCtx);}const vm = videoMaskConfig!;@@ -1865,7 +1616,7 @@ function VideoCanvasInner({ctx.restore();}if (imagePhoneActive && imagePhoneCanvasRef.current) {- drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality, pivotX, pivotY);+ drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality, pivotX, pivotY, phone3dCtx);}@@ -1873,12 +1624,12 @@ function VideoCanvasInner({ctx.save();applyVideoZoom(ctx);if (!imagePhoneActive) {- drawMockupAndMedia(ctx, containerX, containerY, containerWidth, containerHeight, video!, false, false);+ drawMockupAndMedia(ctx, containerX, containerY, containerWidth, containerHeight, video!, false, false, mockupDrawCtx);}ctx.restore();if (imagePhoneActive && imagePhoneCanvasRef.current) {- drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality, pivotX, pivotY);+ drawPhone3DCompositeWithZoom(ctx, canvasWidth, canvasHeight, frameTime, zoomState, highQuality, pivotX, pivotY, phone3dCtx);}}@@ -1886,105 +1637,16 @@ function VideoCanvasInner({ctx.save();applyVideoZoom(ctx);- await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, false);+ await renderCanvasElements(ctx, canvasElements, canvasWidth, canvasHeight, false, svgImageCacheRef.current, elementImagesRef.current);ctx.restore();await drawCameraOverlayToCtx(ctx, canvasWidth, canvasHeight, cameraVideoRef.current, videoRef.current, cameraConfig);};- const drawPhone3DCompositeWithZoom = (- c: CanvasRenderingContext2D,- canvasWidth: number,- canvasHeight: number,- _frameTime: number,- zs: { scale: number; focusX: number; focusY: number },- highQuality: boolean,- pivotX: number,- pivotY: number,- ) => {- const phoneGL = imagePhoneCanvasRef.current!;- const domW = canvasDimensions?.width ?? canvasWidth;- const pxScale = canvasWidth / domW;- const zScale = zs.scale;-- const centerX = canvasWidth / 2;- const centerY = canvasHeight / 2;-- const measuredDims = imagePhoneApiRef.current?.getVisualSize?.();- const deviceDims = measuredDims ?? DEVICE_3D_DIMENSIONS[imagePhoneDevice] ?? { width: PHONE_W, height: PHONE_H };-- const visualOffsetY = (measuredDims?.offsetY ?? 0) * imagePhoneScale * pxScale;-- const baseCx = centerX + imagePhoneX * pxScale;- const baseCy = centerY + imagePhoneY * pxScale + visualOffsetY;-- const baseW = deviceDims.width * imagePhoneScale * pxScale;- const baseH = deviceDims.height * imagePhoneScale * pxScale;-- // LA SOLUCIÓN CORREGIDA:- // Usamos exactamente baseW y baseH. Como baseW ya multiplica por pxScale,- // ya tiene la resolución alta necesaria para la exportación.- // Si multiplicamos aquí, rompemos la cámara 3D o excedemos la memoria WebGL.- if (highQuality) {- imagePhoneApiRef.current?.renderAt(baseW, baseH);- }-- c.save();-- if (zScale !== 1) {- c.translate(pivotX, pivotY);- c.scale(zScale, zScale);- c.translate(-pivotX, -pivotY);- }-- const hasBuiltInShadow = imagePhoneApiRef.current?.hasBuiltInShadow ?? false;-- if (imagePhoneShadow > 0.01 && !hasBuiltInShadow) {- const sT = imagePhoneShadow * imagePhoneShadow;- const sBlur = sT * 60;- const sOpacity = sT * 0.7;- c.save();- c.globalAlpha = sOpacity;- c.filter = `blur(${Math.max(2, sBlur * 0.6) * pxScale}px)`;- c.beginPath();- c.ellipse(- baseCx,- baseCy + baseH / 2 + sBlur * 0.2 * pxScale,- baseW * (0.6 - sT * 0.1) / 2,- Math.max(4, sBlur * 0.55) * pxScale / 2,- 0, 0, Math.PI * 2- );- c.fillStyle = imagePhoneShadowColor;- c.fill();- c.restore();- }-- if (imagePhoneShadow > 0.01) {- c.shadowColor = imagePhoneShadowColor;- c.shadowBlur = 28 * imagePhoneShadow * pxScale;- c.shadowOffsetX = 0;- c.shadowOffsetY = 18 * imagePhoneShadow * pxScale;- }-- drawMaskedImage(c, phoneGL, baseCx - baseW / 2, baseCy - baseH / 2, baseW, baseH, effectivePhoneMaskConfig);-- if (imagePhoneShadow > 0.01) {- c.shadowColor = "transparent";- c.shadowBlur = 0;- c.shadowOffsetY = 0;- }-- c.restore();-- if (highQuality) {- imagePhoneApiRef.current?.restorePreview();- }- };const [activeVideoElement, setActiveVideoElement] = useState<HTMLVideoElement | null>(null);-useEffect(() => {setActiveVideoElement(mediaType === "video" ? videoRef.current : null);- }, [mediaType, videoRef, videoUrl]);+ }, [mediaType, videoRef, videoUrl, mockupId, activeClipUrl, imagePhoneActive]);useImperativeHandle(ref, () => ({getExportCanvas: () => exportCanvasRef.current,@@ -2428,52 +2090,28 @@ function VideoCanvasInner({...(mockupBoxSize? { width: `${mockupBoxSize.width}px`, height: `${mockupBoxSize.height}px` }: { width: '100%', height: '100%' }),+ perspective:+ hasMockup2DMotion && mockupMotionPreview.perspectivePx > 0+ ? `${mockupMotionPreview.perspectivePx}px`+ : undefined,}}>- {isVideoSelected && videoHoverCorner && hasMedia && onVideoTransformChange && !isDraggingVideo && (- <div- data-rotation-handle- style={getCornerStyle(videoHoverCorner, -20)}- onMouseDown={(e) => {- e.preventDefault();- e.stopPropagation();- const container = videoContainerRef.current;- if (!container) return;- const rect = container.getBoundingClientRect();- const centerX = rect.left + rect.width / 2;- const centerY = rect.top + rect.height / 2;- rotationCenterRef.current = { x: centerX, y: centerY };- rotationStartAngleRef.current = Math.atan2(e.clientY - centerY, e.clientX - centerX) * (180 / Math.PI);- setIsDraggingRotation(true);- dragStartPos.current = {- x: e.clientX,- y: e.clientY,- initialRotation: videoTransform.rotation,- initialTranslateX: videoTransform.translateX,- initialTranslateY: videoTransform.translateY,- };- }}- >- <div style={{- transform: `scale(${mediaType === "image" && imageTransform && !apply3DToBackground- ? 1 / (imageTransform.scale * imageZoomScale)- : 1- })`,- transformOrigin: "center center"- }}>- <RotationHandleIcon corner={videoHoverCorner} color="#e5e7eb" />- </div>- </div>- )}- {(isVideoSelected || isVideoHovered) && hasMedia && !isDraggingRotation && !imagePhoneActive && (- <div- className={`absolute -inset-px border pointer-events-none z-10 opacity-80 ${isVideoSelected ? 'border-blue-500' : 'border-white'}`}- style={{ borderRadius: `${getMockupOuterRadius(mockupId, roundedCorners) + 1}px` }}- />- )}-<divclassName="w-full h-full"+ style={+ hasMockup2DMotion+ ? {+ transform: buildMockupMotionCss(mockupMotionPreview),+ transformStyle: "preserve-3d",+ transformOrigin: "center center",+ opacity: mockupMotionPreview.opacity,+ filter:+ mockupMotionPreview.blurPx > 0.4+ ? `blur(${mockupMotionPreview.blurPx}px)`+ : undefined,+ }+ : undefined+ }><MockupWrappermockupId={mockupId}@@ -2484,6 +2122,57 @@ function VideoCanvasInner({>{mockupChildren}</MockupWrapper>++ {(isVideoSelected || isVideoHovered) && hasMedia && !isDraggingRotation && !imagePhoneActive && (+ <div+ className={`absolute -inset-px border pointer-events-none z-10 opacity-80 ${isVideoSelected ? "border-blue-500" : "border-white"+ }`}+ style={{ borderRadius: `${getMockupOuterRadius(mockupId, roundedCorners) + 1}px` }}+ />+ )}++ {isVideoSelected && videoHoverCorner && hasMedia && onVideoTransformChange && !isDraggingVideo && (+ <div+ data-rotation-handle+ style={getCornerStyle(videoHoverCorner, -20)}+ onMouseDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ const container = videoContainerRef.current;+ if (!container) return;+ const rect = container.getBoundingClientRect();+ const centerX = rect.left + rect.width / 2;+ const centerY = rect.top + rect.height / 2;+ rotationCenterRef.current = { x: centerX, y: centerY };+ rotationStartAngleRef.current = Math.atan2(e.clientY - centerY, e.clientX - centerX) * (180 / Math.PI);+ setIsDraggingRotation(true);+ dragStartPos.current = {+ x: e.clientX,+ y: e.clientY,+ initialRotation: videoTransform.rotation,+ initialTranslateX: videoTransform.translateX,+ initialTranslateY: videoTransform.translateY,+ };+ }}+ >+ <div+ style={{+ transform: [+ `scale(${(mediaType === "image" && imageTransform && !apply3DToBackground+ ? 1 / (imageTransform.scale * imageZoomScale)+ : 1) * (hasMockup2DMotion && mockupMotionPreview.scale > 0 ? 1 / mockupMotionPreview.scale : 1)+ })`,+ hasMockup2DMotion+ ? `rotateZ(${-mockupMotionPreview.rotateZ}deg) rotateY(${-mockupMotionPreview.rotateY}deg) rotateX(${-mockupMotionPreview.rotateX}deg)`+ : "",+ ].filter(Boolean).join(" "),+ transformOrigin: "center center",+ }}+ >+ <RotationHandleIcon corner={videoHoverCorner} color="#e5e7eb" />+ </div>+ </div>+ )}</div></div></div>diff --git a/components/ui/MotionPresetIcon.tsx b/components/ui/MotionPresetIcon.tsxnew file mode 100644index 0000000..e67b40c--- /dev/null+++ b/components/ui/MotionPresetIcon.tsx@@ -0,0 +1,210 @@+"use client";++import type { MockupMotionPresetId } from "@/lib/mockup-motion";++type MotionCategory = "Entrance" | "Continue" | "Exit";++const CATEGORY_ACCENT: Record<MotionCategory, string> = {+ Entrance: "59, 130, 246",+ Continue: "167, 139, 250",+ Exit: "251, 113, 133",+};++interface MotionPresetIconProps {+ presetId: MockupMotionPresetId;+ category: MotionCategory;+ active?: boolean;+ size?: number;+ fill?: boolean;+ className?: string;+ forceAnimate?: boolean;+}++export function MotionPresetIcon({+ presetId,+ category,+ active = false,+ size = 40,+ fill = false,+ className = "",+ forceAnimate = false,+}: MotionPresetIconProps) {+ const accent = CATEGORY_ACCENT[category];++ return (+ <div+ className={`mp-stage relative overflow-hidden rounded-[10px] border transition-shadow duration-500 ease-out group-hover:shadow-[0_0_18px_-4px_rgba(var(--mp-accent),0.5)] ${+ active ? "border-white/20 shadow-[0_0_14px_-4px_rgba(var(--mp-accent),0.45)]" : "border-white/10"+ } ${fill ? "h-full w-full" : "shrink-0"} ${forceAnimate ? "force-animate" : ""} ${className}`}+ style={+ {+ ...(fill ? {} : { width: size, height: size }),+ background: "linear-gradient(180deg, #17171a 0%, #050505 100%)",+ "--mp-accent": accent,+ } as React.CSSProperties+ }+ >+ <div className="mp-grid pointer-events-none absolute inset-0" />+ <div className="pointer-events-none absolute inset-0 bg-gradient-to-b from-white/[0.06] to-transparent" />+ <div className="mp-perspective absolute inset-0 flex items-center justify-center">+ <span className={`mp-card mp-card--${presetId}`} />+ </div>+ </div>+ );+}++export function MotionPresetIconStyles() {+ return (+ <style jsx global>{`+ .mp-grid {+ opacity: 0.05;+ background-image: linear-gradient(+ rgba(255, 255, 255, 0.7) 1px,+ transparent 1px+ ),+ linear-gradient(90deg, rgba(255, 255, 255, 0.7) 1px, transparent 1px);+ background-size: 8px 8px;+ }+ .mp-perspective {+ perspective: 260px;+ transform-style: preserve-3d;+ }+ .mp-card {+ display: block;+ width: 42%;+ height: 37%;+ border-radius: 4px;+ background: linear-gradient(+ 135deg,+ rgba(255, 255, 255, 0.95),+ rgba(255, 255, 255, 0.55)+ );+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);+ transform-origin: 50% 50%;+ backface-visibility: hidden;+ }++ /* 2. Añadimos la clase .force-animate junto a .group:hover a todos los selectores */+ @media (prefers-reduced-motion: no-preference) {+ .group:hover .mp-card,+ .force-animate .mp-card {+ will-change: transform, filter, opacity;+ }++ .group:hover .mp-card--rise-settle,+ .force-animate .mp-card--rise-settle {+ animation: mp-rise-settle 1.1s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ .group:hover .mp-card--flip-reveal,+ .force-animate .mp-card--flip-reveal {+ animation: mp-flip-reveal 1.3s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ .group:hover .mp-card--focus-in,+ .force-animate .mp-card--focus-in {+ animation: mp-focus-in 1.1s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ .group:hover .mp-card--depth-emerge,+ .force-animate .mp-card--depth-emerge {+ animation: mp-depth-emerge 1.5s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ .group:hover .mp-card--z-spin-reveal,+ .force-animate .mp-card--z-spin-reveal {+ animation: mp-z-spin-reveal 1.3s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ .group:hover .mp-card--isometric-lift,+ .force-animate .mp-card--isometric-lift {+ animation: mp-isometric-lift 1.3s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ .group:hover .mp-card--cinematic-showcase,+ .force-animate .mp-card--cinematic-showcase {+ animation: mp-cinematic-showcase 2.6s ease-in-out infinite alternate;+ }+ .group:hover .mp-card--panoramic-sweep,+ .force-animate .mp-card--panoramic-sweep {+ animation: mp-panoramic-sweep 2.4s ease-in-out infinite alternate;+ }+ .group:hover .mp-card--macro-track,+ .force-animate .mp-card--macro-track {+ animation: mp-macro-track 2.4s ease-in-out infinite alternate;+ }+ .group:hover .mp-card--rim-light-reveal,+ .force-animate .mp-card--rim-light-reveal {+ animation: mp-rim-light-reveal 2.2s ease-in-out infinite alternate;+ }+ .group:hover .mp-card--surface-orbit,+ .force-animate .mp-card--surface-orbit {+ animation: mp-surface-orbit 2.6s ease-in-out infinite alternate;+ }+ .group:hover .mp-card--low-dolly-reveal,+ .force-animate .mp-card--low-dolly-reveal {+ animation: mp-low-dolly-reveal 2.2s ease-in-out infinite alternate;+ }+ .group:hover .mp-card--exit-fade-down,+ .force-animate .mp-card--exit-fade-down {+ animation: mp-exit-fade-down 1s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ .group:hover .mp-card--exit-scale-blur,+ .force-animate .mp-card--exit-scale-blur {+ animation: mp-exit-scale-blur 1s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ }++ @keyframes mp-rise-settle {+ 0% { transform: translateY(45%); opacity: 0.25; }+ 100% { transform: translateY(0); opacity: 1; }+ }+ @keyframes mp-flip-reveal {+ 0% { transform: rotateY(-62deg) scale(0.92); opacity: 0.35; }+ 100% { transform: rotateY(0deg) scale(1); opacity: 1; }+ }+ @keyframes mp-focus-in {+ 0% { transform: scale(1.22); filter: blur(3.5px); opacity: 0.45; }+ 100% { transform: scale(1); filter: blur(0); opacity: 1; }+ }+ @keyframes mp-depth-emerge {+ 0% { transform: scale(0.45) rotateX(22deg) rotateY(-20deg); filter: blur(5px); opacity: 0; }+ 100% { transform: scale(1) rotateX(0) rotateY(0); filter: blur(0); opacity: 1; }+ }+ @keyframes mp-z-spin-reveal {+ 0% { transform: scale(0.62) rotateZ(-78deg) rotateX(38deg); opacity: 0.5; }+ 100% { transform: scale(1) rotateZ(0) rotateX(0); opacity: 1; }+ }+ @keyframes mp-isometric-lift {+ 0% { transform: scale(1.28) rotateX(42deg) rotateZ(-18deg); }+ 100% { transform: scale(1) rotateX(8deg) rotateZ(0deg); }+ }+ @keyframes mp-cinematic-showcase {+ 0% { transform: scale(1.4) translate(8%, 6%) rotateX(5deg) rotateY(8deg); filter: blur(1.5px); }+ 100% { transform: scale(1) translate(0, 0) rotateX(0) rotateY(0); filter: blur(0); }+ }+ @keyframes mp-panoramic-sweep {+ 0% { transform: scale(1.3) translateX(-16%) rotateY(-24deg); }+ 100% { transform: scale(1.1) translateX(14%) rotateY(16deg); }+ }+ @keyframes mp-macro-track {+ 0% { transform: scale(1.7) translate(10%, 10%) rotateX(32deg); }+ 100% { transform: scale(1) translate(-6%, -6%) rotateX(0deg); }+ }+ @keyframes mp-rim-light-reveal {+ 0% { transform: scale(1.55) rotateX(55deg) rotateY(38deg); filter: brightness(0.35) blur(2.5px); opacity: 0.4; }+ 100% { transform: scale(1) rotateX(0) rotateY(0); filter: brightness(1.2) blur(0); opacity: 1; }+ }+ @keyframes mp-surface-orbit {+ 0% { transform: scale(1.22) rotateX(48deg); }+ 100% { transform: scale(1.05) rotateX(14deg) rotateY(12deg); }+ }+ @keyframes mp-low-dolly-reveal {+ 0% { transform: scale(1.45) rotateX(32deg) translateY(8%); }+ 100% { transform: scale(1) rotateX(8deg) translateY(-4%); }+ }+ @keyframes mp-exit-fade-down {+ 0% { transform: translateY(0); opacity: 1; }+ 100% { transform: translateY(30%); opacity: 0; }+ }+ @keyframes mp-exit-scale-blur {+ 0% { transform: scale(1); filter: blur(0); opacity: 1; }+ 100% { transform: scale(1.3); filter: blur(4.5px); opacity: 0; }+ }+ `}</style>+ );+}\ No newline at end of file