Skip to content

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

Refactor ZoomFragmentTrackItem: Remove unused functions and add ZoomMovementTrackItem component for movement tracking; update HeroEditorPreview styles and SwatchGrid shadow; introduce ZoomPointOverlay for visual point representation

CristianOlivera133e7a40a3e91
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsx
index 34f1bfb..eb5355c 100644
--- a/app/[locale]/(editor)/editor/page.tsx
+++ b/app/[locale]/(editor)/editor/page.tsx
@@ -18,7 +18,7 @@ import { useUndoRedo } from "@/hooks/useUndoRedo";
import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";
import { addVideoToLibrary, addVideoToLibraryWithMetadata, getLibraryVideoCount, getLibraryVideo, findExistingVideo } from "@/lib/videos-library";
import { calculateTotalDuration, findNextClipPosition, getClipAtTime, splitClipAtTime, type VideoTrackClip } from "@/types/video-track.types";
-import type { ExportQuality, BackgroundTab, VideoCanvasHandle, BackgroundColorConfig, AspectRatio, CropArea, ZoomFragment, AudioTrack, ImageExportFormat, UploadedAudio } from "@/types";
+import type { ExportQuality, BackgroundTab, VideoCanvasHandle, BackgroundColorConfig, AspectRatio, CropArea, ZoomFragment, AudioTrack, ImageExportFormat, UploadedAudio, ZoomMovement } from "@/types";
import type { TrimRange } from "@/types/timeline.types";
import type { MockupConfig, MenuPage } from "@/types/mockup.types";
import type { EditorState } from "@/types/editor-state.types";
@@ -29,14 +29,13 @@ import type { CameraConfig } from "@/types/camera.types";
import type { Preview3DConfig, ImageMaskConfig } from "@/types/photo.types";
import { DEFAULT_MASK_CONFIG, PREVIEW_CONFIGS } from "@/types/photo.types";
import { MOCKUPS } from "@/lib/mockup-data";
-import { gradientToCss, generateDefaultZoomFragments, createZoomFragment, ASPECT_RATIO_DIMENSIONS } from "@/types";
+import { gradientToCss, generateDefaultZoomFragments, createZoomFragment, ASPECT_RATIO_DIMENSIONS, getFragmentHoldBounds, findValidFragmentPosition, canAddFragmentAt } from "@/types";
import { ToolsSidebar } from "@/app/components/ui/editor/ToolsSidebar";
import { MobileToolsMenu } from "@/app/components/ui/editor/MobileToolsMenu";
import { MobileControlPanel } from "@/app/components/ui/editor/MobileControlPanel";
import { EditorTopBar } from "@/app/components/ui/editor/EditorTopBar";
import { VideoCanvas } from "@/app/components/ui/editor/VideoCanvas";
import { PlayerControls } from "@/app/components/ui/editor/PlayerControls";
-import { canAddFragmentAt, findValidFragmentPosition } from "@/app/components/ui/editor/ZoomFragmentTrackItem";
import { LoadingSpinner } from "@/components/ui/LoadingSpinner";
import { TimelineSkeleton } from "@/app/components/ui/Skeleton";
import { AudioTrimModal } from "@/app/components/ui/editor/AudioTrimModal";
@@ -46,6 +45,9 @@ import Image from "next/image";
import Link from "next/link";
import { TooltipAction } from "@/components/ui/tooltip-action";
import { DEFAULT_MOCKUP_MOTION_CONFIG, findValidMotionPlacement, MockupMotionFragment, MockupMotionPresetId } from "@/lib/mockup-motion";
+import { findNextMovementSlot } from "@/lib/zoom-movement.utils";
+import { useTranslations } from "next-intl";
+import { MIN_MOVEMENT_TRACK_DURATION } from "@/app/components/ui/editor/ZoomMovementTrackItem";
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 })));
@@ -57,6 +59,7 @@ const PhotoEditorPlaceholder = lazy(() => import("@/app/components/ui/editor/Pho
export default function Editor() {
// Editor mode (video/photo) from URL params
const { mode: editorMode, isVideoMode, isPhotoMode } = useEditorMode();
+ const tZoom = useTranslations("zoomFragmentEditor");
const {
imagePhoneActive, setImagePhoneActive,
@@ -299,6 +302,16 @@ export default function Editor() {
const isRestoringProjectRef = useRef(false);
const isLoadingFromCacheRef = useRef(false);
const lastRestoredProjectIdRef = useRef<string | null>(null);
+ const [copiedZoomFragment, setCopiedZoomFragment] = useState<Omit<ZoomFragment, 'id' | 'startTime' | 'endTime'> | null>(null);
+ const [zoomMovements, setZoomMovements] = useState<ZoomMovement[]>([]);
+ const [copiedZoomMovements, setCopiedZoomMovements] = useState<Array<{
+ name: string; startFrac: number; endFrac: number; focusX: number; focusY: number;
+ }>>([]);
+ const [copiedMockupMotionFragment, setCopiedMockupMotionFragment] =
+ useState<Omit<MockupMotionFragment, 'id' | 'startTime' | 'endTime'> | null>(null);
+ const [selectedZoomMovementId, setSelectedZoomMovementId] = useState<string | null>(null);
+ // Default duration for new zoom fragments
+ const DEFAULT_ZOOM_FRAGMENT_DURATION = 2;
useEffect(() => {
return () => {
@@ -354,9 +367,11 @@ export default function Editor() {
const handleSelectMockupMotionFragment = useCallback((id: string | null) => {
setSelectedMockupMotionFragmentId(id);
setSelectedZoomFragmentId(null);
+ setSelectedZoomMovementId(null);
setSelectedAudioTrackId(null);
setSelectedVideoClipId(null);
setSelectedElementId(null);
+ setMultiSelectedElementIds([]);
}, []);
const handleUpdateMockupMotionFragment = useCallback(
@@ -555,7 +570,9 @@ export default function Editor() {
const selectCanvasElement = useCallback((id: string | null) => {
setSelectedElementId(id);
+ setMultiSelectedElementIds([]);
setSelectedZoomFragmentId(null);
+ setSelectedZoomMovementId(null);
setSelectedVideoClipId(null);
setSelectedAudioTrackId(null);
setSelectedMockupMotionFragmentId(null);
@@ -842,31 +859,67 @@ export default function Editor() {
const updateEditorStateDebounced = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
if (updateEditorStateDebounced.current) clearTimeout(updateEditorStateDebounced.current);
-
updateEditorStateDebounced.current = setTimeout(() => {
setEditorState({
- backgroundTab, selectedWallpaper, backgroundBlur, padding, roundedCorners, shadows,
- selectedImageUrl, backgroundColorConfig, aspectRatio, customDimensions, cropArea,
- trimRange, zoomFragments, mockupId, mockupConfig, canvasElements, audioTracks,
- muteOriginalAudio, masterVolume, cameraConfig, videoTransform, imageTransform,
- apply3DToBackground, imageMaskConfig, videoMaskConfig, imagePhoneActive, imagePhoneX,
- imagePhoneY, imagePhoneScale, imagePhoneRotX, imagePhoneRotY, imagePhoneRotZ,
- imagePhonePerspective, imagePhoneDevice, imagePhonePresetId, imagePhoneOpening,
- imagePhoneShadow, imagePhoneShadowColor, imagePhoneRefWidth, mockupMotionFragments, videoClips,
+ backgroundTab,
+ selectedWallpaper,
+ backgroundBlur,
+ padding,
+ roundedCorners,
+ shadows,
+ selectedImageUrl,
+ unsplashBgUrl,
+ backgroundColorConfig,
+ aspectRatio,
+ customDimensions,
+ cropArea,
+ trimRange,
+ zoomFragments,
+ zoomMovements,
+ mockupId,
+ mockupConfig,
+ canvasElements,
+ audioTracks,
+ muteOriginalAudio,
+ masterVolume,
+ cameraConfig,
+ videoTransform,
+ imageTransform,
+ apply3DToBackground,
+ imageMaskConfig,
+ videoMaskConfig,
+ imageZoomScale,
+ imagePhoneActive,
+ imagePhoneX,
+ imagePhoneY,
+ imagePhoneScale,
+ imagePhoneRotX,
+ imagePhoneRotY,
+ imagePhoneRotZ,
+ imagePhonePerspective,
+ imagePhoneDevice,
+ imagePhonePresetId,
+ imagePhoneOpening,
+ imagePhoneShadow,
+ imagePhoneShadowColor,
+ imagePhoneRefWidth,
+ mockupMotionFragments,
+ videoClips,
});
}, 300);
-
return () => {
if (updateEditorStateDebounced.current) clearTimeout(updateEditorStateDebounced.current);
};
}, [
backgroundTab, selectedWallpaper, backgroundBlur, padding, roundedCorners, shadows,
- selectedImageUrl, backgroundColorConfig, aspectRatio, customDimensions, cropArea, trimRange,
- zoomFragments, mockupId, mockupConfig, canvasElements, audioTracks, muteOriginalAudio,
- masterVolume, cameraConfig, videoTransform, imageTransform, apply3DToBackground, imageMaskConfig,
- videoMaskConfig, imagePhoneActive, imagePhoneX, imagePhoneY, imagePhoneScale, imagePhoneRotX,
- imagePhoneRotY, imagePhoneRotZ, imagePhonePerspective, imagePhoneDevice, imagePhonePresetId,
- imagePhoneOpening, imagePhoneShadow, imagePhoneShadowColor, imagePhoneRefWidth, setEditorState, videoClips
+ selectedImageUrl, unsplashBgUrl, backgroundColorConfig, aspectRatio, customDimensions,
+ cropArea, trimRange, zoomFragments, zoomMovements, mockupId, mockupConfig, canvasElements,
+ audioTracks, muteOriginalAudio, masterVolume, cameraConfig, videoTransform, imageTransform,
+ apply3DToBackground, imageMaskConfig, videoMaskConfig, imageZoomScale,
+ imagePhoneActive, imagePhoneX, imagePhoneY, imagePhoneScale, imagePhoneRotX, imagePhoneRotY,
+ imagePhoneRotZ, imagePhonePerspective, imagePhoneDevice, imagePhonePresetId, imagePhoneOpening,
+ imagePhoneShadow, imagePhoneShadowColor, imagePhoneRefWidth, mockupMotionFragments,
+ setEditorState, videoClips
]);
const prevUndoRedoVersionRef = useRef(undoRedoVersion);
@@ -883,12 +936,14 @@ export default function Editor() {
setRoundedCorners(editorState.roundedCorners);
setShadows(editorState.shadows);
setSelectedImageUrl(editorState.selectedImageUrl);
+ setUnsplashBgUrl(editorState.unsplashBgUrl ?? "");
setBackgroundColorConfig(editorState.backgroundColorConfig);
setAspectRatio(editorState.aspectRatio);
setCustomDimensions(editorState.customDimensions);
setCropArea(editorState.cropArea);
setTrimRange(editorState.trimRange);
setZoomFragments(editorState.zoomFragments);
+ setZoomMovements(editorState.zoomMovements ?? []);
setMockupId(editorState.mockupId);
setMockupConfig(editorState.mockupConfig);
setCanvasElements(editorState.canvasElements);
@@ -900,6 +955,7 @@ export default function Editor() {
setImageTransform(editorState.imageTransform);
setApply3DToBackground(editorState.apply3DToBackground);
setImageMaskConfig(editorState.imageMaskConfig);
+ setImageZoomScale(editorState.imageZoomScale ?? 1);
setVideoMaskConfig(editorState.videoMaskConfig);
setImagePhoneActive(editorState.imagePhoneActive);
setImagePhoneX(editorState.imagePhoneX);
@@ -918,33 +974,33 @@ export default function Editor() {
setMockupMotionFragments(editorState.mockupMotionFragments ?? []);
const restoredClips = editorState.videoClips ?? [];
+ const clipsUnchanged = restoredClips === videoClipsRef.current;
setVideoClips(restoredClips);
- if (restoredClips.length > 0) {
- const newDuration = calculateTotalDuration(restoredClips);
- setVideoDuration(newDuration);
- setTrimRange({ start: 0, end: newDuration });
-
- 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) {
+ if (!clipsUnchanged) {
+ if (restoredClips.length > 0) {
+ const newDuration = calculateTotalDuration(restoredClips);
+ setVideoDuration(newDuration);
+ const stillActiveClip = activeClipIdRef.current
+ ? restoredClips.find(c => c.id === activeClipIdRef.current)
+ : null;
+ const clipAtTime = stillActiveClip ?? getClipAtTime(restoredClips, currentTime) ?? restoredClips[0];
+ activeClipIdRef.current = clipAtTime.id;
+ activeClipDataRef.current = clipAtTime;
+ const url = videoUrlsRef.current.get(clipAtTime.libraryVideoId);
+ if (url && videoRef.current && videoRef.current.src !== url) {
+ setVideoUrl(url);
+ setVideoId(clipAtTime.libraryVideoId);
videoRef.current.src = url;
videoRef.current.currentTime = clipAtTime.trimStart;
}
+ } else {
+ setVideoUrl(null);
+ setVideoId(null);
+ setVideoDuration(0);
+ activeClipIdRef.current = null;
+ activeClipDataRef.current = null;
}
- } else {
- setVideoUrl(null);
- setVideoId(null);
- setVideoDuration(0);
- setTrimRange({ start: 0, end: 0 });
- activeClipIdRef.current = null;
- activeClipDataRef.current = null;
}
setTimeout(() => {
@@ -1002,7 +1058,7 @@ export default function Editor() {
}, []);
const [copiedElements, setCopiedElements] = useState<CanvasElement[]>([]);
- const lastCopyActionRef = useRef<'element' | 'zoom' | null>(null);
+ const lastCopyActionRef = useRef<'element' | 'zoom' | 'motion' | null>(null);
useEffect(() => {
const handleWindowFocus = () => {
@@ -1013,7 +1069,12 @@ export default function Editor() {
}, []);
const copySelectedElement = useCallback(() => {
- const idsToCopy = multiSelectedElementIds.length > 1 ? multiSelectedElementIds : (selectedElementId ? [selectedElementId] : []);
+ const multiSelectionIsValid =
+ multiSelectedElementIds.length > 1 &&
+ (!selectedElementId || multiSelectedElementIds.includes(selectedElementId));
+ const idsToCopy = multiSelectionIsValid
+ ? multiSelectedElementIds
+ : (selectedElementId ? [selectedElementId] : []);
if (idsToCopy.length === 0) return;
const elements = canvasElements.filter(el => idsToCopy.includes(el.id));
if (elements.length > 0) {
@@ -1226,9 +1287,11 @@ export default function Editor() {
const handleSelectAudioTrack = useCallback((trackId: string | null) => {
setSelectedAudioTrackId(trackId);
setSelectedZoomFragmentId(null);
+ setSelectedZoomMovementId(null);
setSelectedVideoClipId(null);
setSelectedElementId(null);
setSelectedMockupMotionFragmentId(null);
+ setMultiSelectedElementIds([]);
if (trackId) {
setActiveTool("audio");
}
@@ -1627,11 +1690,12 @@ export default function Editor() {
// Handlers for video clip management
const handleSelectVideoClip = useCallback((clipId: string | null) => {
setSelectedVideoClipId(clipId);
- // Clear other selections when selecting video clip (mutual exclusivity)
setSelectedZoomFragmentId(null);
+ setSelectedZoomMovementId(null);
setSelectedAudioTrackId(null);
setSelectedElementId(null);
setSelectedMockupMotionFragmentId(null);
+ setMultiSelectedElementIds([]);
if (clipId) {
setActiveTool("video");
}
@@ -2068,10 +2132,29 @@ export default function Editor() {
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleUndo, handleRedo, canUndo, canRedo]);
- const [copiedZoomFragment, setCopiedZoomFragment] = useState<Omit<ZoomFragment, 'id' | 'startTime' | 'endTime'> | null>(null);
-
- // Default duration for new zoom fragments
- const DEFAULT_ZOOM_FRAGMENT_DURATION = 2;
+ const pasteMockupMotionFragment = useCallback(() => {
+ if (!copiedMockupMotionFragment) return;
+ const original = selectedMockupMotionFragmentId
+ ? mockupMotionFragmentsRef.current.find(f => f.id === selectedMockupMotionFragmentId)
+ : null;
+ const hintTime = original ? original.endTime : currentTime;
+ const placement = findValidMotionPlacement(
+ copiedMockupMotionFragment.presetId,
+ copiedMockupMotionFragment.speed,
+ hintTime,
+ mockupMotionFragmentsRef.current,
+ videoDuration
+ );
+ if (!placement) return;
+ const newFragment: MockupMotionFragment = {
+ ...copiedMockupMotionFragment,
+ id: `motion_${crypto.randomUUID()}`,
+ ...placement,
+ };
+ setMockupMotionFragments(prev => [...prev, newFragment]);
+ setSelectedMockupMotionFragmentId(newFragment.id);
+ setActiveTool("motion");
+ }, [copiedMockupMotionFragment, selectedMockupMotionFragmentId, currentTime, videoDuration]);
const pasteZoomFragment = useCallback(() => {
if (!copiedZoomFragment) return;
@@ -2089,10 +2172,26 @@ export default function Editor() {
startTime: position.startTime,
endTime: position.endTime,
};
+
+ if (copiedZoomFragment.movementEnabled && copiedZoomMovements.length > 0) {
+ const { start: hs, end: he } = getFragmentHoldBounds(newFragment);
+ const span = he - hs;
+ const newMovements: ZoomMovement[] = copiedZoomMovements.map(cm => ({
+ id: crypto.randomUUID(),
+ zoomFragmentId: newFragment.id,
+ name: cm.name,
+ startTime: hs + cm.startFrac * span,
+ endTime: hs + cm.endFrac * span,
+ focusX: cm.focusX,
+ focusY: cm.focusY,
+ }));
+ setZoomMovements(prev => [...prev, ...newMovements]);
+ }
+
setZoomFragments(prev => [...prev, newFragment].sort((a, b) => a.startTime - b.startTime));
setSelectedZoomFragmentId(newFragment.id);
setActiveTool("zoom");
- }, [copiedZoomFragment, selectedZoomFragmentId, currentTime, videoDuration]);
+ }, [copiedZoomFragment, selectedZoomFragmentId, currentTime, videoDuration, zoomMovements, setZoomMovements, copiedZoomMovements]);
useEffect(() => {
const handlePaste = async (e: ClipboardEvent) => {
@@ -2105,6 +2204,13 @@ export default function Editor() {
pasteZoomFragment();
return;
}
+
+ if (lastCopyActionRef.current === 'motion' && activeTool === 'motion' && copiedMockupMotionFragment) {
+ e.preventDefault();
+ pasteMockupMotionFragment();
+ return;
+ }
+
if (lastCopyActionRef.current === 'element' && copiedElements.length > 0) {
e.preventDefault();
pasteElement();
@@ -2134,6 +2240,11 @@ export default function Editor() {
pasteZoomFragment();
return;
}
+ if (activeTool === 'motion' && copiedMockupMotionFragment) {
+ e.preventDefault();
+ pasteMockupMotionFragment();
+ return;
+ }
if (copiedElements.length > 0) {
e.preventDefault();
pasteElement();
@@ -2141,7 +2252,7 @@ export default function Editor() {
};
window.addEventListener('paste', handlePaste);
return () => window.removeEventListener('paste', handlePaste);
- }, [isPhotoMode, handleImageUploadToCanvas, handleVideoUpload, activeTool, copiedZoomFragment, pasteZoomFragment, copiedElements, pasteElement]);
+ }, [isPhotoMode, handleImageUploadToCanvas, handleVideoUpload, activeTool, copiedZoomFragment, pasteZoomFragment, copiedElements, pasteElement, copiedMockupMotionFragment, pasteMockupMotionFragment]);
const togglePlayPause = useCallback(() => {
if (videoRef.current) {
@@ -2679,10 +2790,12 @@ export default function Editor() {
// Zoom fragment handlers
const handleSelectZoomFragment = useCallback((fragmentId: string | null) => {
setSelectedZoomFragmentId(fragmentId);
+ setSelectedZoomMovementId(null);
setSelectedAudioTrackId(null);
setSelectedVideoClipId(null);
setSelectedElementId(null);
setSelectedMockupMotionFragmentId(null);
+ setMultiSelectedElementIds([]);
}, []);
const handleActivateZoomTool = useCallback(() => {
@@ -2714,16 +2827,178 @@ export default function Editor() {
}, []);
const handleUpdateZoomFragment = useCallback((fragmentId: string, updates: Partial<ZoomFragment>) => {
- setZoomFragments(prev => prev.map(f =>
- f.id === fragmentId ? { ...f, ...updates } : f
- ).sort((a, b) => a.startTime - b.startTime));
+ const oldFragment = zoomFragmentsRef.current.find(f => f.id === fragmentId);
+ const affectsHoldBounds = 'startTime' in updates || 'endTime' in updates || 'speed' in updates;
+ const oldBounds = oldFragment && affectsHoldBounds ? getFragmentHoldBounds(oldFragment) : null;
+
+ setZoomFragments(prev =>
+ prev.map(f => (f.id === fragmentId ? { ...f, ...updates } : f)).sort((a, b) => a.startTime - b.startTime)
+ );
+
+ if (!oldFragment || !oldBounds) return;
+
+ const newFragment = { ...oldFragment, ...updates };
+ const newBounds = getFragmentHoldBounds(newFragment);
+
+ if (Math.abs(oldBounds.start - newBounds.start) < 1e-4 && Math.abs(oldBounds.end - newBounds.end) < 1e-4) {
+ return;
+ }
+
+ const newSpan = newBounds.end - newBounds.start;
+
+ setZoomMovements(prev => prev.map(m => {
+ if (m.zoomFragmentId !== fragmentId) return m;
+
+ const duration = m.endTime - m.startTime;
+ const delta = newBounds.start - oldBounds.start;
+
+ let newStart = m.startTime + delta;
+ let newEnd = newStart + duration;
+
+ if (newStart < newBounds.start) {
+ newStart = newBounds.start;
+ newEnd = newStart + duration;
+ }
+ if (newEnd > newBounds.end) {
+ newEnd = newBounds.end;
+ newStart = Math.max(newBounds.start, newEnd - duration);
+ }
+ if (newEnd - newStart > newSpan) {
+ newStart = newBounds.start;
+ newEnd = newBounds.end;
+ }
+
+ return { ...m, startTime: newStart, endTime: newEnd };
+ }));
+ }, []);
+
+ const handleToggleZoomMovement = useCallback((fragmentId: string, enabled: boolean) => {
+ if (enabled) {
+ const fragment = zoomFragments.find(f => f.id === fragmentId);
+ if (!fragment) return;
+
+ const { start, end } = getFragmentHoldBounds(fragment);
+ const holdSpan = end - start;
+
+ if (holdSpan < MIN_MOVEMENT_TRACK_DURATION) {
+ return;
+ }
+
+ const slot = findNextMovementSlot([], start, end, MIN_MOVEMENT_TRACK_DURATION);
+
+ handleUpdateZoomFragment(fragmentId, { movementEnabled: true });
+
+ if (slot) {
+ const newMovement: ZoomMovement = {
+ id: crypto.randomUUID(),
+ zoomFragmentId: fragmentId,
+ name: tZoom("movement.defaultName", { number: 1 }),
+ startTime: slot.startTime,
+ endTime: slot.endTime,
+ focusX: Math.min(85, Math.max(15, fragment.focusX + 25)),
+ focusY: Math.min(85, Math.max(15, fragment.focusY + 25)),
+ };
+ setZoomMovements(prev => [...prev, newMovement]);
+ setSelectedZoomMovementId(newMovement.id);
+ }
+ } else {
+ handleUpdateZoomFragment(fragmentId, { movementEnabled: false });
+ setZoomMovements(prev => prev.filter(m => m.zoomFragmentId !== fragmentId));
+ setSelectedZoomMovementId(null);
+ }
+ }, [zoomFragments, handleUpdateZoomFragment, tZoom]);
+
+
+ const handleAddZoomMovement = useCallback((fragmentId: string) => {
+ const fragment = zoomFragments.find(f => f.id === fragmentId);
+ if (!fragment) return;
+
+ const siblings = zoomMovements.filter(m => m.zoomFragmentId === fragmentId).sort((a, b) => a.startTime - b.startTime);
+ const { start, end } = getFragmentHoldBounds(fragment);
+ const slot = findNextMovementSlot(siblings, start, end, MIN_MOVEMENT_TRACK_DURATION);
+
+ if (!slot) {
+ return;
+ }
+
+ const last = siblings[siblings.length - 1];
+ const from = last ? { x: last.focusX, y: last.focusY } : { x: fragment.focusX, y: fragment.focusY };
+
+ const newMovement: ZoomMovement = {
+ id: crypto.randomUUID(),
+ zoomFragmentId: fragmentId,
+ name: tZoom("movement.defaultName", { number: siblings.length + 1 }),
+ startTime: slot.startTime,
+ endTime: slot.endTime,
+ focusX: Math.min(85, Math.max(15, from.x + 25)),
+ focusY: Math.min(85, Math.max(15, from.y + 25)),
+ };
+ setZoomMovements(prev => [...prev, newMovement]);
+ setSelectedZoomMovementId(newMovement.id);
+ }, [zoomFragments, zoomMovements, tZoom]);
+
+ const handleAddZoomMovementAtRange = useCallback((fragmentId: string, startTime: number, endTime: number) => {
+ const fragment = zoomFragmentsRef.current.find(f => f.id === fragmentId);
+ if (!fragment) return;
+
+ const siblings = zoomMovements.filter(m => m.zoomFragmentId === fragmentId);
+ const last = [...siblings].sort((a, b) => a.startTime - b.startTime).slice(-1)[0];
+ const from = last ? { x: last.focusX, y: last.focusY } : { x: fragment.focusX, y: fragment.focusY };
+
+ const newMovement: ZoomMovement = {
+ id: crypto.randomUUID(),
+ zoomFragmentId: fragmentId,
+ name: tZoom("movement.defaultName", { number: siblings.length + 1 }),
+ startTime,
+ endTime,
+ focusX: Math.min(85, Math.max(15, from.x + 25)),
+ focusY: Math.min(85, Math.max(15, from.y + 25)),
+ };
+
+ setZoomMovements(prev => [...prev, newMovement]);
+ setSelectedZoomMovementId(newMovement.id);
+ }, [zoomMovements, tZoom]);
+
+ const handleUpdateZoomMovement = useCallback((id: string, updates: Partial<ZoomMovement>) => {
+ setZoomMovements(prev => prev.map(m => m.id === id ? { ...m, ...updates } : m));
+ }, []);
+
+ const handleDeleteZoomMovement = useCallback((id: string) => {
+ setZoomMovements(prev => {
+ const target = prev.find(m => m.id === id);
+ const next = prev.filter(m => m.id !== id);
+ if (target) {
+ const stillHasSiblings = next.some(m => m.zoomFragmentId === target.zoomFragmentId);
+ if (!stillHasSiblings) {
+ setZoomFragments(fPrev =>
+ fPrev.map(f => (f.id === target.zoomFragmentId ? { ...f, movementEnabled: false } : f))
+ );
+ }
+ }
+ return next;
+ });
+ setSelectedZoomMovementId(prev => (prev === id ? null : prev));
+ }, []);
+
+ const handleSelectZoomMovement = useCallback((id: string | null) => {
+ setSelectedZoomMovementId(id);
+ if (id) {
+ setSelectedAudioTrackId(null);
+ setSelectedVideoClipId(null);
+ setSelectedElementId(null);
+ setSelectedMockupMotionFragmentId(null);
+ setMultiSelectedElementIds([]);
+ setActiveTool("zoom");
+ }
}, []);
const handleDeleteZoomFragment = useCallback((fragmentId: string) => {
setZoomFragments(prev => prev.filter(f => f.id !== fragmentId));
+ setZoomMovements(prev => prev.filter(m => m.zoomFragmentId !== fragmentId));
if (selectedZoomFragmentId === fragmentId) {
setSelectedZoomFragmentId(null);
}
+ setSelectedZoomMovementId(null);
}, [selectedZoomFragmentId]);
// Get currently selected zoom fragment - memoized
@@ -2732,12 +3007,32 @@ export default function Editor() {
[zoomFragments, selectedZoomFragmentId]
);
+ const copySelectedMockupMotionFragment = useCallback(() => {
+ if (!selectedMockupMotionFragment) return;
+ const { id, startTime, endTime, ...config } = selectedMockupMotionFragment;
+ setCopiedMockupMotionFragment(config);
+ lastCopyActionRef.current = 'motion';
+ }, [selectedMockupMotionFragment]);
+
const copySelectedZoomFragment = useCallback(() => {
if (!selectedZoomFragment) return;
- const { id, startTime, endTime, ...config } = selectedZoomFragment;
+ const { ...config } = selectedZoomFragment;
setCopiedZoomFragment(config);
+
+ const { start: hs, end: he } = getFragmentHoldBounds(selectedZoomFragment);
+ const span = he - hs;
+ const related = zoomMovements
+ .filter(m => m.zoomFragmentId === selectedZoomFragment.id)
+ .map(m => ({
+ name: m.name,
+ startFrac: span > 0 ? (m.startTime - hs) / span : 0,
+ endFrac: span > 0 ? (m.endTime - hs) / span : 1,
+ focusX: m.focusX,
+ focusY: m.focusY,
+ }));
+ setCopiedZoomMovements(related);
lastCopyActionRef.current = 'zoom';
- }, [selectedZoomFragment]);
+ }, [selectedZoomFragment, zoomMovements]);
const backgroundColorCss = useMemo((): string | undefined => {
if (backgroundTab === "color" && backgroundColorConfig) {
@@ -2802,10 +3097,14 @@ export default function Editor() {
copySelectedZoomFragment();
return;
}
+
+ if (selectedMockupMotionFragmentId) {
+ e.preventDefault();
+ copySelectedMockupMotionFragment();
+ return;
+ }
}
- // Ctrl+V se maneja por completo en el listener de 'paste' (más abajo
- // en este archivo), para no competir por el mismo atajo con el
- // pegado de archivos del portapapeles del sistema.
+
if ((e.key === "Delete" || e.key === "Backspace") && (selectedElementId || multiSelectedElementIds.length > 0)) {
e.preventDefault();
const idsToDelete = multiSelectedElementIds.length > 1 ? multiSelectedElementIds : selectedElementId;
@@ -2826,22 +3125,31 @@ export default function Editor() {
return;
}
+ if ((e.key === "Delete" || e.key === "Backspace") && selectedZoomMovementId) {
+ e.preventDefault();
+ handleDeleteZoomMovement(selectedZoomMovementId);
+ return;
+ }
+
if ((e.key === "Delete" || e.key === "Backspace") && selectedZoomFragmentId) {
e.preventDefault();
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 (selectedZoomMovementId) { setSelectedZoomMovementId(null); }
else if (selectedZoomFragmentId) { setSelectedZoomFragmentId(null); }
else if (selectedMockupMotionFragmentId) { setSelectedMockupMotionFragmentId(null); }
}
@@ -2849,7 +3157,13 @@ export default function Editor() {
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
- }, [selectedElementId, multiSelectedElementIds, selectedZoomFragmentId, selectedAudioTrackId, selectedVideoClipId, selectedMockupMotionFragmentId, deleteCanvasElement, handleDeleteZoomFragment, handleDeleteAudioTrack, handleDeleteVideoClip, handleDeleteMockupMotionFragment, copySelectedElement, textToolActive, copySelectedZoomFragment, activeTool]);
+ }, [
+ selectedElementId, multiSelectedElementIds, selectedZoomFragmentId, selectedZoomMovementId,
+ selectedAudioTrackId, selectedVideoClipId, selectedMockupMotionFragmentId,
+ deleteCanvasElement, handleDeleteZoomFragment, handleDeleteZoomMovement,
+ handleDeleteAudioTrack, handleDeleteVideoClip, handleDeleteMockupMotionFragment,
+ copySelectedElement, textToolActive, copySelectedZoomFragment, activeTool, copySelectedMockupMotionFragment
+ ]);
const wasMobileRef = useRef<boolean | null>(null);
const otherSelectionActive = !!(selectedZoomFragmentId || selectedAudioTrackId || selectedVideoClipId || selectedMockupMotionFragmentId);
@@ -3038,6 +3352,13 @@ export default function Editor() {
onAddZoomFragment={() => handleAddZoomFragment(currentTime)}
onUpdateZoomFragment={handleUpdateZoomFragment}
onDeleteZoomFragment={handleDeleteZoomFragment}
+ zoomMovements={zoomMovements}
+ selectedZoomMovementId={selectedZoomMovementId}
+ onSelectZoomMovement={handleSelectZoomMovement}
+ onToggleZoomMovement={handleToggleZoomMovement}
+ onAddZoomMovement={handleAddZoomMovement}
+ onDeleteZoomMovement={handleDeleteZoomMovement}
+ onUpdateZoomMovementPoint={(id, x, y) => handleUpdateZoomMovement(id, { focusX: x, focusY: y })}
videoUrl={videoUrl}
videoThumbnail={zoomFragmentThumbnail}
currentTime={currentTime}
@@ -3199,6 +3520,12 @@ export default function Editor() {
mockupMotionFragments={mockupMotionFragments}
videoDuration={videoDuration}
onMockupConfigChange={handleMockupConfigChange}
+ selectedZoomFragment={selectedZoomFragment}
+ onUpdateZoomFragment={handleUpdateZoomFragment}
+ zoomMovements={zoomMovements}
+ selectedZoomMovementId={selectedZoomMovementId}
+ onSelectZoomMovement={handleSelectZoomMovement}
+ onUpdateZoomMovement={handleUpdateZoomMovement}
/>
{/* Video mode: Show player controls and timeline */}
@@ -3250,6 +3577,11 @@ export default function Editor() {
onAddZoomFragment={handleAddZoomFragmentAtRange}
onUpdateZoomFragment={handleUpdateZoomFragment}
onActivateZoomTool={handleActivateZoomTool}
+ zoomMovements={zoomMovements}
+ selectedZoomMovementId={selectedZoomMovementId}
+ onSelectZoomMovement={handleSelectZoomMovement}
+ onUpdateZoomMovement={handleUpdateZoomMovement}
+ onDeleteZoomMovement={handleDeleteZoomMovement}
onActivateMotionTool={handleActivateMotionTool}
audioTracks={audioTracks}
uploadedAudios={uploadedAudios}
@@ -3269,6 +3601,9 @@ export default function Editor() {
onSelectElement={selectCanvasElement}
onUpdateElement={updateCanvasElement}
onDeleteElement={deleteCanvasElement}
+ onAddZoomMovementAtRange={(start, end) =>
+ selectedZoomFragmentId && handleAddZoomMovementAtRange(selectedZoomFragmentId, start, end)
+ }
/>
</Suspense>
</>
diff --git a/app/components/common/UserMenuDropdown.tsx b/app/components/common/UserMenuDropdown.tsx
index 936a10c..08fef9f 100644
--- a/app/components/common/UserMenuDropdown.tsx
+++ b/app/components/common/UserMenuDropdown.tsx
@@ -54,11 +54,13 @@ function writeThemeCookie(theme: Theme) {
interface UserMenuDropdownProps {
trigger: React.ReactNode;
showTheme?: boolean;
+ editorMode?: "video" | "photo";
}
export function UserMenuDropdown({
trigger,
showTheme = false,
+ editorMode,
}: UserMenuDropdownProps) {
const t = useTranslations('userMenu');
const { user, profile } = useAuth();
@@ -122,6 +124,9 @@ export function UserMenuDropdown({
user?.email?.split("@")[0] ||
t('defaultUser');
const provider = profile?.provider || meta.provider || "email";
+ const editorHref = editorMode === "video" ? "/editor?mode=photo" : "/editor";
+ const editorLabel = editorMode === "video" ? t("photoEditor") : editorMode === "photo" ? t("videoEditor") : t("editor");
+ const editorIcon = editorMode === "video" ? "solar:gallery-wide-linear" : "solar:video-frame-cut-2-linear";
return (
<DropdownMenu.Root>
@@ -149,10 +154,10 @@ export function UserMenuDropdown({
</DropdownMenu.Item>
<DropdownMenu.Item asChild>
- <Link href="/editor" className={itemClasses}>
- <Icon icon="solar:video-frame-cut-2-linear" className="size-4" aria-hidden="true" />
- <span>{t('editor')}</span>
- </Link>
+ <a href={editorHref} className={itemClasses}>
+ <Icon icon={editorIcon} className="size-4" aria-hidden="true" />
+ <span>{editorLabel}</span>
+ </a>
</DropdownMenu.Item>
{showTheme && (
@@ -195,9 +200,9 @@ export function UserMenuDropdown({
</>
)}
-<DropdownMenu.Separator className="h-px bg-border my-1" />
+ <DropdownMenu.Separator className="h-px bg-border my-1" />
- <SignOutItem />
+ <SignOutItem />
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
diff --git a/app/components/ui/RecordingSetupDialog.tsx b/app/components/ui/RecordingSetupDialog.tsx
index 8f91ad7..991c736 100644
--- a/app/components/ui/RecordingSetupDialog.tsx
+++ b/app/components/ui/RecordingSetupDialog.tsx
@@ -598,7 +598,7 @@ export default function RecordingSetupDialog({ open, onClose, onStart }: Props)
</div>
</div>
- <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-border bg-muted">
+ <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
<Button variant="outline" onClick={handleCancel}>
{t("actions.cancel")}
</Button>
diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsx
index 44283df..79e868b 100644
--- a/app/components/ui/editor/ControlPanel.tsx
+++ b/app/components/ui/editor/ControlPanel.tsx
@@ -66,6 +66,13 @@ export function ControlPanel({
onAddZoomFragment,
onUpdateZoomFragment,
onDeleteZoomFragment,
+ zoomMovements =[],
+ selectedZoomMovementId,
+ onSelectZoomMovement,
+ onToggleZoomMovement,
+ onAddZoomMovement,
+ onDeleteZoomMovement,
+ onUpdateZoomMovementPoint,
videoUrl,
videoThumbnail,
currentTime = 0,
@@ -134,16 +141,16 @@ export function ControlPanel({
const hasMockup2D = mediaType === "video" && !imagePhoneActive;
const [isDark, setIsDark] = useState(
- () => typeof window !== "undefined" && document.documentElement.classList.contains("dark")
+ () => typeof window !== "undefined" && document.documentElement.classList.contains("dark")
);
useEffect(() => {
- const html = document.documentElement;
- const update = () => setIsDark(html.classList.contains("dark"));
- update();
- const observer = new MutationObserver(update);
- observer.observe(html, { attributes: true, attributeFilter: ["class"] });
- return () => observer.disconnect();
+ const html = document.documentElement;
+ const update = () => setIsDark(html.classList.contains("dark"));
+ update();
+ const observer = new MutationObserver(update);
+ observer.observe(html, { attributes: true, attributeFilter: ["class"] });
+ return () => observer.disconnect();
}, []);
return (
@@ -402,6 +409,13 @@ export function ControlPanel({
<ZoomFragmentEditor
key={selectedZoomFragment.id}
fragment={selectedZoomFragment}
+ movements={zoomMovements.filter(m => m.zoomFragmentId === selectedZoomFragment.id)}
+ selectedMovementId={selectedZoomMovementId}
+ onSelectMovement={(id) => onSelectZoomMovement?.(id)}
+ onToggleMovement={(enabled) => onToggleZoomMovement?.(selectedZoomFragment.id, enabled)}
+ onAddMovement={() => onAddZoomMovement?.(selectedZoomFragment.id)}
+ onDeleteMovement={(id) => onDeleteZoomMovement?.(id)}
+ onUpdateMovementPoint={(id, x, y) => onUpdateZoomMovementPoint?.(id, x, y)}
videoUrl={videoUrl ?? null}
videoThumbnail={videoThumbnail}
currentTime={currentTime}
diff --git a/app/components/ui/editor/EditorTopBar.tsx b/app/components/ui/editor/EditorTopBar.tsx
index 4e89b37..cfef003 100644
--- a/app/components/ui/editor/EditorTopBar.tsx
+++ b/app/components/ui/editor/EditorTopBar.tsx
@@ -159,6 +159,7 @@ export function EditorTopBar({
) : (
<UserMenuDropdown
showTheme
+ editorMode={editorMode}
trigger={
<button
className="flex items-center gap-1.5 px-2 border-border hover:opacity-80 transition-opacity focus:outline-none"
diff --git a/app/components/ui/editor/ElementFragmentTrackItem.tsx b/app/components/ui/editor/ElementFragmentTrackItem.tsx
index 68267b0..e265c3e 100644
--- a/app/components/ui/editor/ElementFragmentTrackItem.tsx
+++ b/app/components/ui/editor/ElementFragmentTrackItem.tsx
@@ -127,7 +127,7 @@ export function ElementFragmentTrackItem({
return (
<motion.div
- className={`absolute rounded-md flex items-center border transition-shadow select-none focus:outline-none ${isSelected || isInteracting
+ className={`absolute h-[90%] top-[5%] rounded-md flex items-center border transition-shadow select-none focus:outline-none ${isSelected || isInteracting
? `${style.activeBorder} ${style.glow} z-10`
: `${style.idleBorder} hover:brightness-125`
} ${isDragging ? "cursor-grabbing" : "cursor-grab"}`}
diff --git a/app/components/ui/editor/LabelSidebar.tsx b/app/components/ui/editor/LabelSidebar.tsx
index 2a3d697..5191705 100644
--- a/app/components/ui/editor/LabelSidebar.tsx
+++ b/app/components/ui/editor/LabelSidebar.tsx
@@ -4,34 +4,38 @@ interface LabelSidebarProps {
audioTracksCount?: number;
motionTracksCount?: number;
elementsCount?: number;
+ showMovementRow?: boolean;
}
-export default function LabelSidebar({
- audioTracksCount = 0,
- motionTracksCount = 0,
- elementsCount = 0
-}: LabelSidebarProps) {
+export default function LabelSidebar({ audioTracksCount = 0, motionTracksCount = 0, elementsCount = 0, showMovementRow = false }: LabelSidebarProps) {
const t = useTranslations('labelSidebar');
- const hasAdditionalRows = audioTracksCount > 0 || motionTracksCount > 0 || elementsCount > 0;
+ const hasAdditionalRows = audioTracksCount > 0 || motionTracksCount > 0 || elementsCount > 0 || showMovementRow;
return (
<div className="absolute left-0 top-0 bottom-0 w-14 shrink-0 border-r border-border flex flex-col bg-background z-30">
<div className="h-5.5 border-b border-border" />
- <div className="flex-1 flex items-center px-3">
+ <div className="h-14 flex-1 flex items-center px-3">
<span className="text-[9px] uppercase font-semibold tracking-wider text-muted-foreground">
{t('video')}
</span>
</div>
- <div className={`flex items-center px-3 border-t border-border transition-all duration-300 ${
- hasAdditionalRows ? 'h-14' : 'h-16'
- }`}>
+ <div className={`flex items-center px-3 border-t border-border transition-all duration-300 ${hasAdditionalRows ? 'h-14' : 'h-16'
+ }`}>
<span className="text-[9px] uppercase font-semibold tracking-wider text-muted-foreground">
{t('zoom')}
</span>
</div>
+ {showMovementRow && (
+ <div className="h-14 flex items-center px-3 border-t border-dashed border-emerald-500/20 bg-emerald-500/5">
+ <span className="text-[9px] uppercase font-semibold tracking-wider text-emerald-600/70 dark:text-emerald-400/70">
+ {t('movement')}
+ </span>
+ </div>
+ )}
+
{elementsCount > 0 && (
<div className="h-14 flex items-center px-3 border-t border-border bg-muted/40">
<span className="text-[9px] uppercase font-semibold tracking-wider text-muted-foreground">
diff --git a/app/components/ui/editor/Timeline.tsx b/app/components/ui/editor/Timeline.tsx
index 8a02bce..15d4d0c 100644
--- a/app/components/ui/editor/Timeline.tsx
+++ b/app/components/ui/editor/Timeline.tsx
@@ -3,9 +3,9 @@ import { useRef, useMemo, useCallback, useEffect, useState } from "react";
import { motion, useMotionValue, useTransform, animate, PanInfo } from "framer-motion";
import { formatTime, getZoomMultiplier } from "@/lib/video.utils";
import { TIMELINE_LABEL_WIDTH, MIN_TRIM_DURATION } from "@/lib/constants";
-import type { TimelineProps } from "@/types/timeline.types";
+import { DEFAULT_MOVEMENT_DURATION, DEFAULT_ZOOM_FRAGMENT_DURATION, ELEMENT_ROW_HEIGHT, type TimelineProps } from "@/types/timeline.types";
import LabelSidebar from "./LabelSidebar";
-import { ZoomFragmentTrackItem, findValidFragmentPosition } from "./ZoomFragmentTrackItem";
+import { ZoomFragmentTrackItem } from "./ZoomFragmentTrackItem";
import { AudioFragmentTrackItem } from "./AudioFragmentTrackItem";
import { VideoClipTrackItem } from "./VideoClipTrackItem";
import { Icon } from "@iconify/react";
@@ -15,9 +15,8 @@ import { assignAudioLanes } from "@/lib/audio.utils";
import { MIN_VISUAL_WIDTH_PX } from "@/types";
import { assignElementLanes } from "@/lib/canvas-elements-timeline.utils";
import { ElementFragmentTrackItem } from "./ElementFragmentTrackItem";
-
-const DEFAULT_ZOOM_FRAGMENT_DURATION = 2;
-const ELEMENT_ROW_HEIGHT = 48;
+import { findValidFragmentPosition, findValidMovementPosition, getFragmentHoldBounds } from "@/types/zoom.types";
+import { ZoomMovementTrackItem, MIN_MOVEMENT_TRACK_DURATION } from "./ZoomMovementTrackItem";
export function Timeline({
videoDuration,
@@ -60,6 +59,11 @@ export function Timeline({
globalSpeed = 1,
isPlaying = false,
onZoomChange,
+ zoomMovements = [],
+ selectedZoomMovementId = null,
+ onSelectZoomMovement,
+ onUpdateZoomMovement,
+ onAddZoomMovementAtRange
}: TimelineProps) {
const t = useTranslations("timeline");
const trackRef = useRef<HTMLDivElement>(null);
@@ -79,6 +83,14 @@ export function Timeline({
const pendingGhostXRef = useRef<number | null>(null);
const lastValidPositionRef = useRef<{ startTime: number; endTime: number } | null>(null);
+ const [draggingMovementId, setDraggingMovementId] = useState<string | null>(null);
+ const [hoveredMovementId, setHoveredMovementId] = useState<string | null>(null);
+ const [isHoveringMovementRow, setIsHoveringMovementRow] = useState(false);
+ const [movementGhostX, setMovementGhostX] = useState(0);
+ const movementGhostRafRef = useRef<number | null>(null);
+ const pendingMovementGhostXRef = useRef<number | null>(null);
+ const lastValidMovementPositionRef = useRef<{ startTime: number; endTime: number } | null>(null);
+
const isOverFragment = useMemo(() => {
return hoveredFragmentId ? zoomFragments.some(f => f.id === hoveredFragmentId) : false;
}, [hoveredFragmentId, zoomFragments]);
@@ -176,13 +188,20 @@ export function Timeline({
[elementLanes],
);
+ const selectedFragmentForMovement = useMemo(
+ () => zoomFragments.find(f => f.id === selectedZoomFragmentId) ?? null,
+ [zoomFragments, selectedZoomFragmentId]
+ );
+
+ const showMovementRow = !!selectedFragmentForMovement?.movementEnabled;
const totalLanesCount = useMemo(() => {
let count = 0;
+ if (showMovementRow) count += 1;
if (canvasElements.length > 0) count += elementLaneCount;
if (audioTracks.length > 0) count += audioLaneCount;
if (mockupMotionFragments.length > 0) count += 1;
return count;
- }, [canvasElements.length, elementLaneCount, audioTracks.length, audioLaneCount, mockupMotionFragments.length]);
+ }, [showMovementRow, canvasElements.length, elementLaneCount, audioTracks.length, audioLaneCount, mockupMotionFragments.length]);
useEffect(() => {
if (!isDraggingTrim) {
@@ -415,6 +434,48 @@ export function Timeline({
lastValidPositionRef.current = ghostState?.validPosition ?? null;
}, [ghostState]);
+ const fragmentMovements = useMemo(
+ () => selectedFragmentForMovement
+ ? zoomMovements.filter(m => m.zoomFragmentId === selectedFragmentForMovement.id)
+ : [],
+ [zoomMovements, selectedFragmentForMovement]
+ );
+
+ const movementHoldBounds = useMemo(
+ () => selectedFragmentForMovement ? getFragmentHoldBounds(selectedFragmentForMovement) : null,
+ [selectedFragmentForMovement]
+ );
+
+ const isOverMovement = useMemo(
+ () => hoveredMovementId ? fragmentMovements.some(m => m.id === hoveredMovementId) : false,
+ [hoveredMovementId, fragmentMovements]
+ );
+
+ const isDraggingMovementItem = useMemo(
+ () => draggingMovementId ? fragmentMovements.some(m => m.id === draggingMovementId) : false,
+ [draggingMovementId, fragmentMovements]
+ );
+
+ const movementGhostState = useMemo(() => {
+ if (!isHoveringMovementRow || isDraggingMovementItem || isOverMovement) return null;
+ if (contentWidth === 0 || scaledDuration === 0 || !movementHoldBounds) return null;
+ const holdSpan = movementHoldBounds.end - movementHoldBounds.start;
+ if (holdSpan < MIN_MOVEMENT_TRACK_DURATION) return null;
+ const hoverTime = (movementGhostX / contentWidth) * scaledDuration;
+ const validPosition = findValidMovementPosition(
+ hoverTime,
+ Math.min(DEFAULT_MOVEMENT_DURATION, holdSpan),
+ fragmentMovements,
+ movementHoldBounds.start,
+ movementHoldBounds.end
+ );
+ return { validPosition };
+ }, [isHoveringMovementRow, isDraggingMovementItem, isOverMovement, movementGhostX, contentWidth, scaledDuration, movementHoldBounds, fragmentMovements]);
+
+ useEffect(() => {
+ lastValidMovementPositionRef.current = movementGhostState?.validPosition ?? null;
+ }, [movementGhostState]);
+
return (
<div ref={containerRef} className="flex flex-col w-full pr-2">
<div
@@ -434,15 +495,15 @@ export function Timeline({
audioTracksCount={audioTracks.length}
motionTracksCount={mockupMotionFragments.length}
elementsCount={canvasElements.length}
+ showMovementRow={showMovementRow}
/>
<div
ref={trackRef}
- className={`flex-1 flex flex-col overflow-x-auto custom-scrollbar pl-14 pr-2 ${audioTracks.length > 0 || elementLaneCount > 1 || canvasElements.length > 0
+ className={`flex-1 flex flex-col overflow-x-auto custom-scrollbar pl-14 pr-2 ${audioTracks.length > 0 || elementLaneCount > 1 || canvasElements.length > 0 || showMovementRow
? "overflow-y-auto no-scrollbar"
: "overflow-y-hidden"
- }`}
- >
+ }`}>
<div
className="relative flex flex-col min-h-full h-max pb-1"
style={{ width: timelineWidth > 0 ? timelineWidth : '100%', minWidth: '100%' }}
@@ -514,7 +575,7 @@ export function Timeline({
<div className="flex-1 flex flex-col min-h-max" onClick={handleTrackClick}>
- <div className="flex-1 min-h-[55px] shrink-0 flex items-center py-0.5 relative">
+ <div className="flex-1 min-h-[55px] max-h-[65px] shrink-0 flex items-center py-0.5 relative">
<div className="h-full w-full rounded-md flex items-center relative bg-muted/40 dark:bg-[#0a1510] border border-border">
{videoClips.length > 0 ? (
<>
@@ -701,15 +762,104 @@ export function Timeline({
)}
</div>
</div>
+ {(() => {
+ if (!selectedFragmentForMovement?.movementEnabled || !movementHoldBounds) return null;
+ const { start: holdStart, end: holdEnd } = movementHoldBounds;
+ const leftPx = (holdStart / scaledDuration) * contentWidth;
+ const rightPx = (holdEnd / scaledDuration) * contentWidth;
- {canvasElements.length > 0 && (
- <div className="shrink-0 w-full relative" style={{ minHeight: elementLaneCount * ELEMENT_ROW_HEIGHT }}>
+ return (
<div
- className="h-full w-full relative"
+ className="min-h-[55px] shrink-0 w-full flex items-center relative bg-black/10 dark:bg-white/10"
+ onMouseMove={(e) => {
+ if (isDraggingMovementItem) return;
+ const rect = e.currentTarget.getBoundingClientRect();
+ pendingMovementGhostXRef.current = e.clientX - rect.left;
+ if (movementGhostRafRef.current === null) {
+ movementGhostRafRef.current = requestAnimationFrame(() => {
+ if (pendingMovementGhostXRef.current !== null) setMovementGhostX(pendingMovementGhostXRef.current);
+ movementGhostRafRef.current = null;
+ });
+ }
+ setIsHoveringMovementRow(true);
+ }}
+ onMouseLeave={() => setIsHoveringMovementRow(false)}
onClick={(e) => {
e.stopPropagation();
- onSelectElement?.(null);
+ if (isOverMovement || isDraggingMovementItem || !onAddZoomMovementAtRange) return;
+ const validPosition = lastValidMovementPositionRef.current;
+ if (validPosition) {
+ onAddZoomMovementAtRange(validPosition.startTime, validPosition.endTime);
+ }
}}
+ >
+ <div className="h-full w-full relative">
+ <div className="absolute top-0 bottom-0 left-0 bg-white dark:bg-black pointer-events-none" style={{ width: leftPx }} />
+ <div className="absolute top-0 bottom-0 bg-white dark:bg-black pointer-events-none" style={{ left: rightPx, right: 0 }} />
+
+ {fragmentMovements
+ .slice()
+ .sort((a, b) => a.startTime - b.startTime)
+ .map((movement, i) => (
+ <ZoomMovementTrackItem
+ key={movement.id}
+ movement={movement}
+ index={i + 1}
+ isSelected={movement.id === selectedZoomMovementId}
+ contentWidth={contentWidth}
+ videoDuration={scaledDuration}
+ holdStart={holdStart}
+ holdEnd={holdEnd}
+ otherMovements={fragmentMovements.filter(m => m.id !== movement.id)}
+ onSelect={() => onSelectZoomMovement?.(movement.id)}
+ onUpdate={(updates) => onUpdateZoomMovement?.(movement.id, updates)}
+ onDragStateChange={(dragging) => {
+ if (dragging) {
+ setDraggingMovementId(movement.id);
+ setHoveredMovementId(movement.id);
+ setIsHoveringMovementRow(false);
+ } else {
+ setDraggingMovementId(prev => (prev === movement.id ? null : prev));
+ }
+ }}
+ onMouseEnter={() => setHoveredMovementId(movement.id)}
+ onMouseLeave={() => setHoveredMovementId(prev => (prev === movement.id ? null : prev))}
+ />
+ ))}
+
+ {movementGhostState?.validPosition && (
+ <motion.div
+ className="absolute top-1/2 -translate-y-1/2 h-[80%] pointer-events-none"
+ initial={false}
+ animate={{
+ left: (movementGhostState.validPosition.startTime / scaledDuration) * contentWidth,
+ width: ((movementGhostState.validPosition.endTime - movementGhostState.validPosition.startTime) / scaledDuration) * contentWidth,
+ }}
+ transition={{ duration: 0 }}
+ >
+ <div className="w-full h-full rounded border border-dashed border-emerald-400/50 bg-emerald-500/10 flex flex-col items-center justify-center gap-0.5">
+ <Icon icon="qlementine-icons:zoom-12" width="12" height="12" className="text-emerald-600 dark:text-emerald-400" aria-hidden="true" />
+ <span className="text-[8px] font-mono text-emerald-600/60 dark:text-emerald-400/60">+ Movement</span>
+ </div>
+ </motion.div>
+ )}
+
+ {isHoveringMovementRow && !isDraggingMovementItem && !isOverMovement && movementGhostState && !movementGhostState.validPosition && (
+ <div className="absolute top-[10%] h-[80%] w-32 pointer-events-none" style={{ left: movementGhostX - 64 }}>
+ <div className="w-full h-full rounded border border-dashed border-red-400/50 bg-red-500/10 flex flex-col items-center justify-center gap-0.5">
+ <span className="text-[8px] font-mono text-red-600/60 dark:text-red-400/60">{t("noSpace")}</span>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ })()}
+
+ {canvasElements.length > 0 && (
+ <div className="min-h-[55px] shrink-0 w-full flex items-center relative">
+ <div className="h-full w-full flex items-center relative"
+ onClick={(e) => { e.stopPropagation(); onSelectElement?.(null); }}
>
{canvasElements.map((element) => (
<ElementFragmentTrackItem
@@ -731,7 +881,7 @@ export function Timeline({
)}
{audioTracks.length > 0 && (
- <div className="shrink-0 w-full relative" style={{ minHeight: audioLaneCount * 55 }}>
+ <div className="shrink-0 w-full relative">
<div className="h-full w-full relative">
{audioTracks.map((track) => {
const audio = uploadedAudios?.find(a => a.id === track.audioId);
@@ -762,12 +912,8 @@ export function Timeline({
</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="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) => (
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 04f7843..4110d23 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -33,11 +33,12 @@ import { drawPhone3DCompositeWithZoom, type Phone3DCompositeContext } from "@/li
import { buildMockupMotionCss, MockupMotionTransform, REST_MOCKUP_MOTION, sampleCombinedMockupMotion } from "@/lib/mockup-motion";
import { Mockup3DFrame } from "./mockups-3d/Mockup3DFrame";
import { filterVisibleElements } from "@/lib/canvas-elements-timeline.utils";
+import { ZoomPointOverlay } from "@/components/ui/ZoomPointOverlay";
export type { VideoCanvasHandle, VideoCanvasProps };
function VideoCanvasInner({
- activeTool: _activeTool,
+ activeTool,
mediaType = "video",
isPlaying = false,
imageUrl = null,
@@ -102,7 +103,13 @@ function VideoCanvasInner({
mockupMotionFragments = [],
videoDuration = 0,
onSelectedElementIdsChange,
- onMockupConfigChange
+ onMockupConfigChange,
+ selectedZoomFragment = null,
+ onUpdateZoomFragment,
+ zoomMovements = [],
+ selectedZoomMovementId = null,
+ onSelectZoomMovement,
+ onUpdateZoomMovement,
}: VideoCanvasProps & {
ref?: React.Ref<VideoCanvasHandle>;
onSelectedElementIdsChange?: (ids: string[]) => void;
@@ -142,6 +149,7 @@ function VideoCanvasInner({
const pendingPaddingRef = useRef<number | null>(null);
const zoomWheelRafRef = useRef<number | null>(null);
const pendingZoomRef = useRef<number | null>(null);
+
useEffect(() => {
return () => {
if (paddingWheelRafRef.current !== null) {
@@ -153,6 +161,62 @@ function VideoCanvasInner({
};
}, []);
+ const zoomMovementsForSelected = useMemo(
+ () => zoomMovements.filter(m => m.zoomFragmentId === selectedZoomFragment?.id).sort((a, b) => a.startTime - b.startTime),
+ [zoomMovements, selectedZoomFragment?.id]
+ );
+
+ const zoomPointChain = useMemo(() => {
+ if (!selectedZoomFragment) return [];
+ const chain: Array<{ id: string; x: number; y: number; label: string }> = [
+ { id: "origin", x: selectedZoomFragment.focusX, y: selectedZoomFragment.focusY, label: "A" },
+ ];
+ zoomMovementsForSelected.forEach((m, i) => chain.push({ id: m.id, x: m.focusX, y: m.focusY, label: String(i + 1) }));
+ return chain;
+ }, [selectedZoomFragment, zoomMovementsForSelected]);
+
+ const zoomActivePointId = selectedZoomMovementId ?? "origin";
+
+ const updateZoomPoint = useCallback((pointId: string, x: number, y: number) => {
+ if (!selectedZoomFragment) return;
+ if (pointId === "origin") onUpdateZoomFragment?.(selectedZoomFragment.id, { focusX: x, focusY: y });
+ else onUpdateZoomMovement?.(pointId, { focusX: x, focusY: y });
+ }, [selectedZoomFragment, onUpdateZoomFragment, onUpdateZoomMovement]);
+
+ const handleZoomFocusPointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>, pointId: string) => {
+ if (!selectedZoomFragment) return;
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ onSelectZoomMovement?.(pointId === "origin" ? null : pointId);
+ const container = previewContainerRef.current;
+ if (!container) return;
+ const move = (ev: PointerEvent) => {
+ const rect = container.getBoundingClientRect();
+ const x = Math.max(0, Math.min(100, ((ev.clientX - rect.left) / rect.width) * 100));
+ const y = Math.max(0, Math.min(100, ((ev.clientY - rect.top) / rect.height) * 100));
+ updateZoomPoint(pointId, x, y);
+ };
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ }, [selectedZoomFragment, onSelectZoomMovement, updateZoomPoint]);
+
+ const handleZoomOverlayClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
+ if (!selectedZoomFragment) return;
+ e.stopPropagation();
+ if ((e.target as HTMLElement).closest("[data-zoom-drag-handle]")) return;
+ const container = previewContainerRef.current;
+ if (!container) return;
+ const rect = container.getBoundingClientRect();
+ const x = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
+ const y = Math.max(0, Math.min(100, ((e.clientY - rect.top) / rect.height) * 100));
+ updateZoomPoint(zoomActivePointId, x, y);
+ }, [selectedZoomFragment, zoomActivePointId, updateZoomPoint]);
+
const ctrlScrollWheelRef = useRef<((e: WheelEvent) => void) | null>(null);
const imagePhoneActiveRef = useRef(imagePhoneActive);
useEffect(() => { imagePhoneActiveRef.current = imagePhoneActive; }, [imagePhoneActive]);
@@ -211,7 +275,8 @@ function VideoCanvasInner({
}
// Calculate 3-phase state
- const phaseState = calculateZoomPhaseState(activeZoomFragment, currentTime);
+ const fragmentMovements = zoomMovements.filter(m => m.zoomFragmentId === activeZoomFragment.id);
+ const phaseState = calculateZoomPhaseState(activeZoomFragment, currentTime, fragmentMovements);
const translateX = 50 - phaseState.focusX;
const translateY = 50 - phaseState.focusY;
@@ -229,7 +294,7 @@ function VideoCanvasInner({
perspective: phaseState.perspective,
isMoving,
};
- }, [activeZoomFragment, zoomFragments, currentTime]);
+ }, [activeZoomFragment, zoomFragments, currentTime, zoomMovements]);
const shouldShowUnsplashOverride = backgroundTab === "wallpaper" && unsplashOverrideUrl !== "";
const shouldShowWallpaper = backgroundTab === "wallpaper" && selectedWallpaper >= 0 && !shouldShowUnsplashOverride;
@@ -1266,7 +1331,7 @@ function VideoCanvasInner({
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
- const zoomState = calculateSmoothZoom(frameTime, zoomFragments);
+ const zoomState = calculateSmoothZoom(frameTime, zoomFragments, zoomMovements);
const zoomCenterX = canvasWidth / 2;
const zoomCenterY = canvasHeight / 2;
const backgroundImage = (shouldShowCustomImage || shouldShowUnsplashOverride) ? customImageRef.current : (shouldShowWallpaper ? wallpaperImageRef.current : null);
@@ -2479,6 +2544,23 @@ function VideoCanvasInner({
</div>
)}
+ {/* Zoom fragment focus/movement points overlay */}
+ {selectedZoomFragment && !textToolActive && (
+ <div
+ className="absolute inset-0"
+ style={{ zIndex: 250 }}
+ onClick={handleZoomOverlayClick}
+ >
+ <ZoomPointOverlay
+ points={zoomPointChain}
+ zoomLevel={selectedZoomFragment.zoomLevel}
+ activePointId={zoomActivePointId}
+ onPointPointerDown={handleZoomFocusPointerDown}
+ markerId="canvas-zoom-chain-arrowhead"
+ />
+ </div>
+ )}
+
{/* Text tool crosshair overlay — captures clicks to place text */}
{textToolActive && (
<div
diff --git a/app/components/ui/editor/ZoomFragmentEditor.tsx b/app/components/ui/editor/ZoomFragmentEditor.tsx
index 99cfed0..f64354f 100644
--- a/app/components/ui/editor/ZoomFragmentEditor.tsx
+++ b/app/components/ui/editor/ZoomFragmentEditor.tsx
@@ -1,385 +1,269 @@
"use client";
-
-import { useRef, useMemo, useState, useEffect } from "react";
+import { useRef, useMemo, useEffect } from "react";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { SliderControl } from "../../../../components/ui/SliderControl";
import type { ZoomFragmentEditorProps } from "@/types/zoom.types";
-import { formatZoomTime, zoomLevelToFactor, speedToTransitionMs, calculateHoldDuration } from "@/types/zoom.types";
+import { formatZoomTime, zoomLevelToFactor, speedToTransitionMs, getFragmentHoldBounds } from "@/types/zoom.types";
+import { hasMovementSpaceAvailable } from "@/lib/zoom-movement.utils";
import { TooltipAction } from "@/components/ui/tooltip-action";
import { DetailPageHeader } from "@/components/ui/DetailHeaderMenu";
import { Toggle } from "@/components/ui/toggle";
import { DirectionPad } from "@/components/ui/DirectionPad";
+import { Button } from "@/components/ui/button";
+import { ZoomPointOverlay } from "@/components/ui/ZoomPointOverlay";
+import { MIN_MOVEMENT_TRACK_DURATION } from "./ZoomMovementTrackItem";
export function ZoomFragmentEditor({
- fragment, videoUrl, videoThumbnail, currentTime = 0,
- getThumbnailForTime, videoDimensions, onBack, onDelete, onUpdate, is3DModelActive = false,
+ fragment,
+ movements,
+ selectedMovementId,
+ onSelectMovement,
+ onToggleMovement,
+ onAddMovement,
+ onDeleteMovement,
+ onUpdateMovementPoint,
+ videoUrl,
+ videoThumbnail,
+ currentTime = 0,
+ getThumbnailForTime,
+ videoDimensions,
+ onBack,
+ onDelete,
+ onUpdate,
+ is3DModelActive = false,
}: ZoomFragmentEditorProps) {
- const t = useTranslations("zoomFragmentEditor");
- const tCommon = useTranslations("editor");
- const focusPreviewRef = useRef<HTMLDivElement>(null);
- const [editingPoint, setEditingPoint] = useState<'start' | 'end'>('start');
+ const t = useTranslations("zoomFragmentEditor");
+ const tCommon = useTranslations("editor");
+ const focusPreviewRef = useRef<HTMLDivElement>(null);
- useEffect(() => {
- if (is3DModelActive && fragment.enable3D) {
- onUpdate({ enable3D: false });
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [is3DModelActive]);
+ useEffect(() => {
+ if (is3DModelActive && fragment.enable3D) onUpdate({ enable3D: false });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [is3DModelActive]);
- const dynamicThumbnail = useMemo(() => {
- if (!getThumbnailForTime) return videoThumbnail || null;
- const thumb = getThumbnailForTime(currentTime);
- return thumb?.dataUrl || videoThumbnail || null;
- }, [getThumbnailForTime, currentTime, videoThumbnail]);
+ const dynamicThumbnail = useMemo(() => {
+ if (!getThumbnailForTime) return videoThumbnail || null;
+ const thumb = getThumbnailForTime(currentTime);
+ return thumb?.dataUrl || videoThumbnail || null;
+ }, [getThumbnailForTime, currentTime, videoThumbnail]);
- const movementEndX = fragment.movementEndX ?? fragment.focusX;
- const movementEndY = fragment.movementEndY ?? fragment.focusY;
- const movementEnabled = fragment.movementEnabled ?? false;
+ const movementEnabled = fragment.movementEnabled ?? false;
+ const sortedMovements = useMemo(
+ () => [...movements].sort((a, b) => a.startTime - b.startTime),
+ [movements]
+ );
+ const activePointId = selectedMovementId ?? "origin";
- const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>, point: 'start' | 'end') => {
- e.preventDefault();
- e.stopPropagation();
- e.currentTarget.setPointerCapture(e.pointerId);
- setEditingPoint(point);
- const move = (ev: PointerEvent) => {
- if (!focusPreviewRef.current) return;
- const rect = focusPreviewRef.current.getBoundingClientRect();
- const x = Math.max(0, Math.min(100, ((ev.clientX - rect.left) / rect.width) * 100));
- const y = Math.max(0, Math.min(100, ((ev.clientY - rect.top) / rect.height) * 100));
- if (point === 'start') { onUpdate({ focusX: x, focusY: y }); }
- else { onUpdate({ movementEndX: x, movementEndY: y }); }
- };
- const up = () => {
- window.removeEventListener("pointermove", move);
- window.removeEventListener("pointerup", up);
- };
- window.addEventListener("pointermove", move);
- window.addEventListener("pointerup", up);
- };
+ const pointChain = useMemo(() => {
+ const chain: Array<{ id: string; x: number; y: number; label: string }> = [
+ { id: "origin", x: fragment.focusX, y: fragment.focusY, label: "A" },
+ ];
+ sortedMovements.forEach((m, i) => chain.push({ id: m.id, x: m.focusX, y: m.focusY, label: String(i + 1) }));
+ return chain;
+ }, [fragment.focusX, fragment.focusY, sortedMovements]);
- const handlePreviewClick = (e: React.MouseEvent<HTMLDivElement>) => {
- if ((e.target as HTMLElement).closest('[data-drag-handle]')) return;
- if (!focusPreviewRef.current) return;
- const rect = focusPreviewRef.current.getBoundingClientRect();
- const x = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
- const y = Math.max(0, Math.min(100, ((e.clientY - rect.top) / rect.height) * 100));
- if (movementEnabled && editingPoint === 'end') { onUpdate({ movementEndX: x, movementEndY: y }); }
- else { onUpdate({ focusX: x, focusY: y }); }
- };
+ const updatePoint = (pointId: string, x: number, y: number) => {
+ if (pointId === "origin") onUpdate({ focusX: x, focusY: y });
+ else onUpdateMovementPoint(pointId, x, y);
+ };
- const handleToggleMovement = () => {
- if (!movementEnabled) {
- const holdDuration = calculateHoldDuration(fragment);
- const endX = Math.min(85, Math.max(15, fragment.focusX + 25));
- const endY = Math.min(85, Math.max(15, fragment.focusY + 25));
- onUpdate({ movementEnabled: true, movementEndX: endX, movementEndY: endY, movementStartOffset: 0, movementEndOffset: holdDuration });
- } else {
- onUpdate({ movementEnabled: false });
- }
+ const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>, pointId: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ onSelectMovement(pointId === "origin" ? null : pointId);
+ const move = (ev: PointerEvent) => {
+ if (!focusPreviewRef.current) return;
+ const rect = focusPreviewRef.current.getBoundingClientRect();
+ const x = Math.max(0, Math.min(100, ((ev.clientX - rect.left) / rect.width) * 100));
+ const y = Math.max(0, Math.min(100, ((ev.clientY - rect.top) / rect.height) * 100));
+ updatePoint(pointId, x, y);
};
-
- const handleToggle3D = () => {
- onUpdate({ enable3D: !(fragment.enable3D ?? false) });
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
};
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ };
- return (
- <div className="flex flex-col h-full text-foreground">
- {/* Header */}
- <div className="flex items-center gap-2 p-3 border-b border-border shrink-0">
- <DetailPageHeader
- label={t("title")}
- icon="ph:arrow-left-bold"
- onBack={onBack}
- />
- <TooltipAction label={t("deleteTooltip")}>
- <button onClick={onDelete} className="ml-auto flex items-center gap-1.5 text-[11px] text-destructive/80 hover:text-destructive px-2 py-1 rounded-md transition-colors shrink-0">
- <Icon icon="ph:trash-bold" width="12" />
- {t("actions.delete")}
- </button>
- </TooltipAction>
- </div>
+ const handlePreviewClick = (e: React.MouseEvent<HTMLDivElement>) => {
+ if ((e.target as HTMLElement).closest("[data-drag-handle]")) return;
+ if (!focusPreviewRef.current) return;
+ const rect = focusPreviewRef.current.getBoundingClientRect();
+ const x = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
+ const y = Math.max(0, Math.min(100, ((e.clientY - rect.top) / rect.height) * 100));
+ updatePoint(activePointId, x, y);
+ };
- <div className="flex-1 overflow-y-auto custom-scrollbar px-4 py-4 space-y-5">
+ const holdBounds = useMemo(() => getFragmentHoldBounds(fragment), [fragment]);
+ const holdDuration = Math.max(0, holdBounds.end - holdBounds.start);
+ const isTooShort = holdDuration < MIN_MOVEMENT_TRACK_DURATION;
+ const canAddMovement = hasMovementSpaceAvailable(sortedMovements, holdBounds.start, holdBounds.end);
- {/* Focus point preview */}
- <div>
- <div className="flex items-center gap-2 text-xs mb-2 text-muted-foreground">
- <Icon icon="material-symbols:center-focus-strong-outline" width="16" />
- <span>{movementEnabled ? t("focusPoints.multiple") : t("focusPoints.single")}</span>
- {movementEnabled && (
- <div className="ml-auto flex gap-1">
- <button
- onClick={() => setEditingPoint('start')}
- className={`px-2 py-0.5 rounded text-[11px] font-mono transition-colors ${editingPoint === 'start' ? 'bg-blue-500/30 text-blue-600 dark:text-blue-300 border border-blue-500/50' : 'bg-muted/60 text-muted-foreground/80 hover:bg-muted'}`}
- >
- {t("focusPoints.start")}
- </button>
- <button
- onClick={() => setEditingPoint('end')}
- className={`px-2 py-0.5 rounded text-[11px] font-mono transition-colors ${editingPoint === 'end' ? 'bg-emerald-500/30 text-emerald-600 dark:text-emerald-300 border border-emerald-500/50' : 'bg-muted/60 text-muted-foreground/80 hover:bg-muted'}`}
- >
- {t("focusPoints.end")}
- </button>
- </div>
- )}
- </div>
- <div
- ref={focusPreviewRef}
- className="relative w-full squircle-element overflow-hidden bg-muted dark:bg-[#0a0a0e] border border-border select-none"
- style={{ aspectRatio: videoDimensions ? `${videoDimensions.width}/${videoDimensions.height}` : "16/9" }}
- onClick={handlePreviewClick}
- >
- {dynamicThumbnail ? (
- <img src={dynamicThumbnail} alt={t("preview.alt")} className="absolute inset-0 w-full h-full object-cover opacity-60 pointer-events-none" />
- ) : videoUrl ? (
- <video src={videoUrl} className="absolute inset-0 w-full h-full object-cover opacity-60 pointer-events-none" muted />
- ) : null}
+ const handleToggle3D = () => onUpdate({ enable3D: !(fragment.enable3D ?? false) });
- <div
- className="absolute border border-dashed border-blue-500/50 bg-linear-to-b from-blue-500/20 to-transparent squircle-element pointer-events-none transition-opacity duration-200"
- style={{ width: `${100 / zoomLevelToFactor(fragment.zoomLevel)}%`, height: `${100 / zoomLevelToFactor(fragment.zoomLevel)}%`, left: `${fragment.focusX}%`, top: `${fragment.focusY}%`, transform: 'translate(-50%, -50%)', opacity: movementEnabled && editingPoint === 'end' ? 0.4 : 1, willChange: "left, top" }}
- />
+ return (
+ <div className="flex flex-col h-full text-foreground">
+ <div className="flex items-center gap-2 p-3 border-b border-border shrink-0">
+ <DetailPageHeader label={t("title")} icon="ph:arrow-left-bold" onBack={onBack} />
+ <TooltipAction label={t("deleteTooltip")}>
+ <button onClick={onDelete} className="ml-auto flex items-center gap-1.5 text-[11px] text-destructive/80 hover:text-destructive px-2 py-1 rounded-md transition-colors shrink-0">
+ <Icon icon="ph:trash-bold" width="12" />
+ {t("actions.delete")}
+ </button>
+ </TooltipAction>
+ </div>
- {movementEnabled && (() => {
- const dx = movementEndX - fragment.focusX;
- const dy = movementEndY - fragment.focusY;
- const dist = Math.sqrt(dx * dx + dy * dy);
- const radius = dist > 0 ? 5.5 : 0;
- const ratio = dist > 0 ? (dist - radius) / dist : 0;
- const x2 = fragment.focusX + dx * ratio;
- const y2 = fragment.focusY + dy * ratio;
- return (
- <svg className="absolute inset-0 w-full h-full pointer-events-none" style={{ zIndex: 5, willChange: "contents" }}>
- <defs>
- <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
- <polygon points="0 0, 10 3.5, 0 7" fill="rgba(16, 185, 129, 0.7)" />
- </marker>
- </defs>
- <line x1={`${fragment.focusX}%`} y1={`${fragment.focusY}%`} x2={`${x2}%`} y2={`${y2}%`} stroke="rgba(16, 185, 129, 0.5)" strokeWidth="2" strokeDasharray="6 4" markerEnd="url(#arrowhead)" />
- </svg>
- );
- })()}
+ <div className="flex-1 overflow-y-auto custom-scrollbar px-4 py-4 space-y-5">
+ <div>
+ <div className="flex items-center gap-2 text-xs mb-2 text-muted-foreground">
+ <Icon icon="material-symbols:center-focus-strong-outline" width="16" />
+ <span>{movementEnabled ? t("focusPoints.multiple") : t("focusPoints.single")}</span>
+ </div>
+ <div
+ ref={focusPreviewRef}
+ className="relative w-full squircle-element overflow-hidden bg-muted dark:bg-[#0a0a0e] border border-border select-none"
+ style={{ aspectRatio: videoDimensions ? `${videoDimensions.width}/${videoDimensions.height}` : "16/9" }}
+ onClick={handlePreviewClick}
+ >
+ {dynamicThumbnail ? (
+ <img src={dynamicThumbnail} alt={t("preview.alt")} className="absolute inset-0 w-full h-full object-cover opacity-60 pointer-events-none" />
+ ) : videoUrl ? (
+ <video src={videoUrl} className="absolute inset-0 w-full h-full object-cover opacity-60 pointer-events-none" muted />
+ ) : null}
- {movementEnabled && (
- <div
- className="absolute border border-dashed border-emerald-500/50 bg-linear-to-b from-emerald-500/20 to-transparent squircle-element pointer-events-none transition-opacity duration-200"
- style={{ width: `${100 / zoomLevelToFactor(fragment.zoomLevel)}%`, height: `${100 / zoomLevelToFactor(fragment.zoomLevel)}%`, left: `${movementEndX}%`, top: `${movementEndY}%`, transform: 'translate(-50%, -50%)', opacity: editingPoint === 'start' ? 0.4 : 1, willChange: "left, top" }}
- />
- )}
-
- <div data-drag-handle className={`absolute z-10 cursor-grab active:cursor-grabbing touch-none transition-[opacity,transform] duration-150 ${movementEnabled && editingPoint === 'end' ? 'opacity-60 scale-90' : ''}`} style={{ left: `${fragment.focusX}%`, top: `${fragment.focusY}%`, transform: "translate(-50%, -50%)", willChange: "left, top" }} onPointerDown={(e) => handlePointerDown(e, 'start')}>
- <div className="size-8 rounded-full bg-blue-500 shadow-lg border-2 border-white/80 hover:scale-110 transition-transform flex items-center justify-center">
- <span className="text-[8px] font-bold text-white">A</span>
- </div>
- </div>
+ <ZoomPointOverlay
+ points={pointChain}
+ zoomLevel={fragment.zoomLevel}
+ activePointId={activePointId}
+ onPointPointerDown={handlePointerDown}
+ markerId="preview-zoom-chain-arrowhead"
+ />
+ </div>
+ </div>
- {movementEnabled && (
- <div data-drag-handle className={`absolute z-10 cursor-grab active:cursor-grabbing touch-none transition-[opacity,transform] duration-150 ${editingPoint === 'start' ? 'opacity-60 scale-90' : ''}`} style={{ left: `${movementEndX}%`, top: `${movementEndY}%`, transform: "translate(-50%, -50%)", willChange: "left, top" }} onPointerDown={(e) => handlePointerDown(e, 'end')}>
- <div className="size-8 rounded-full bg-emerald-500 shadow-lg border-2 border-white/80 hover:scale-110 transition-transform flex items-center justify-center">
- <span className="text-[8px] font-bold text-white">B</span>
- </div>
- </div>
- )}
+ <div className="space-y-3 p-3 bg-muted/40 border border-border squircle-element">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Icon icon="mdi:vector-line" width="16" className="text-muted-foreground" />
+ <div>
+ <p className="text-xs font-medium text-foreground/90">{t("movement.title")}</p>
+ <p className="text-[11px] text-muted-foreground">{t("movement.subtitle")}</p>
+ </div>
+ </div>
+ <div className={isTooShort ? "opacity-50 cursor-not-allowed" : ""}>
+ <Toggle
+ checked={movementEnabled}
+ onChange={() => !isTooShort && onToggleMovement(!movementEnabled)}
+ activeColor="bg-emerald-500"
+ />
+ </div>
+ </div>
- <div className="absolute bottom-2 left-0 right-0 flex justify-center pointer-events-none">
- <span className="text-[7px] text-muted-foreground/50 font-mono uppercase tracking-[0.3em]">
- {movementEnabled ? t("preview.dragAB") : t("preview.dragOrClick")}
- </span>
- </div>
+ {isTooShort ? (
+ <div className="p-3 bg-amber-500/10 border border-amber-500/20 squircle-element">
+ <div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400">
+ <span>{t("movement.tooShort")}</span>
+ </div>
+ </div>
+ ) : (
+ movementEnabled && (
+ <div className="space-y-3 pt-1">
+ <div className="flex flex-col gap-1.5">
+ {sortedMovements.map((m) => (
+ <div
+ key={m.id}
+ className={`flex items-center justify-between pl-3 pr-2 py-1.5 rounded-lg text-[11px] font-mono border transition-colors cursor-pointer w-full ${activePointId === m.id
+ ? "bg-emerald-500/20 text-emerald-600 dark:text-emerald-300 border-emerald-500/40"
+ : "bg-muted/40 text-muted-foreground/80 hover:bg-muted border-border/50"
+ }`}
+ onClick={() => onSelectMovement(m.id)}
+ >
+ <div className="flex items-center gap-2 truncate">
+ <div className={`size-1.5 rounded-full shrink-0 ${activePointId === m.id ? "bg-emerald-500" : "bg-muted-foreground/30"}`} />
+ <span className="truncate">{m.name}</span>
+ </div>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onDeleteMovement(m.id);
+ }}
+ className="p-1 rounded-md hover:bg-destructive/20 hover:text-destructive transition-colors shrink-0"
+ aria-label={t("movement.deleteMovement")}
+ >
+ <Icon icon="ph:x-bold" width="11" />
+ </button>
</div>
+ ))}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onAddMovement}
+ disabled={!canAddMovement}
+ className="w-full border-dashed text-muted-foreground hover:text-foreground font-mono text-[11px] mt-1"
+ >
+ <Icon icon="ph:plus-bold" />
+ {t("movement.addMovement")}
+ </Button>
</div>
+ </div>
+ )
+ )}
+ </div>
- {/* Camera movement */}
- <div className="space-y-3 p-3 bg-muted/40 border border-border squircle-element">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Icon icon="mdi:vector-line" width="16" className="text-muted-foreground" />
- <div>
- <p className="text-xs font-medium text-foreground/90">{t("movement.title")}</p>
- <p className="text-[11px] text-muted-foreground">{t("movement.subtitle")}</p>
- </div>
- </div>
- <Toggle
- checked={movementEnabled ?? false}
- onChange={handleToggleMovement}
- activeColor="bg-emerald-500"
- />
- </div>
-
- {movementEnabled && (() => {
- const holdDuration = calculateHoldDuration(fragment);
- const startOffset = fragment.movementStartOffset ?? 0;
- const endOffset = fragment.movementEndOffset ?? holdDuration;
- const transitionSec = speedToTransitionMs(fragment.speed) / 1000;
- const totalDuration = fragment.endTime - fragment.startTime;
- const entryPct = (transitionSec / totalDuration) * 100;
- const exitPct = (transitionSec / totalDuration) * 100;
- const holdPct = Math.max(0, 100 - entryPct - exitPct);
- const moveStartPct = holdDuration > 0 ? (startOffset / holdDuration) * 100 : 0;
- const moveEndPct = holdDuration > 0 ? (endOffset / holdDuration) * 100 : 100;
-
- const handleTimelineDrag = (e: React.MouseEvent<HTMLDivElement>, type: 'start' | 'end' | 'range') => {
- const timeline = e.currentTarget.closest('[data-hold-timeline]') as HTMLElement;
- if (!timeline) return;
- const rect = timeline.getBoundingClientRect();
- const initialX = e.clientX;
- const initialStartOffset = startOffset;
- const initialEndOffset = endOffset;
- const minTimeGap = Math.max(0.1, (24 / (rect.width || 1)) * holdDuration);
- const handleMove = (ev: MouseEvent) => {
- const deltaX = ev.clientX - initialX;
- const deltaPct = (deltaX / rect.width) * 100;
- const deltaTime = (deltaPct / 100) * holdDuration;
- if (type === 'start') {
- const newStart = Math.max(0, Math.min(initialEndOffset - minTimeGap, initialStartOffset + deltaTime));
- onUpdate({ movementStartOffset: Math.round(newStart * 10) / 10 });
- } else if (type === 'end') {
- const newEnd = Math.max(initialStartOffset + minTimeGap, Math.min(holdDuration, initialEndOffset + deltaTime));
- onUpdate({ movementEndOffset: Math.round(newEnd * 10) / 10 });
- } else if (type === 'range') {
- const duration = initialEndOffset - initialStartOffset;
- const newStart = Math.max(0, Math.min(holdDuration - duration, initialStartOffset + deltaTime));
- onUpdate({ movementStartOffset: Math.round(newStart * 10) / 10, movementEndOffset: Math.round((newStart + duration) * 10) / 10 });
- }
- };
- const handleUp = () => { window.removeEventListener('mousemove', handleMove); window.removeEventListener('mouseup', handleUp); };
- window.addEventListener('mousemove', handleMove);
- window.addEventListener('mouseup', handleUp);
- };
-
- return holdDuration > 0.1 ? (
- <div className="space-y-3 p-3 bg-card border border-border squircle-element-camera group transition-all">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2 text-[11px] font-medium text-muted-foreground">
- <span>{t("movement.timeline.title")}</span>
- </div>
- <div className="flex items-center gap-2">
- <span className="text-[11px] font-mono text-emerald-600 dark:text-emerald-400/80 bg-emerald-500/5 px-1.5 py-0.5 rounded border border-emerald-500/10">
- {t("movement.timeline.active", { seconds: (endOffset - startOffset).toFixed(1) })}
- </span>
- </div>
- </div>
-
- <div className="space-y-3">
- <div className="relative h-9 flex rounded-md overflow-hidden bg-muted border border-border">
- <div className="h-full bg-muted/40 border-r border-border flex items-center justify-center opacity-40 hover:opacity-100 transition-opacity" style={{ width: `${entryPct}%` }}>
- <Icon icon="iconamoon:zoom-in-fill" width="12" className="text-muted-foreground" />
- </div>
- <div className="h-full relative flex-1 bg-transparent" style={{ width: `${holdPct}%` }} data-hold-timeline>
- <div className="absolute top-1.5 bottom-1.5 bg-emerald-500/20 border border-emerald-500/40 rounded-sm cursor-grab active:cursor-grabbing hover:bg-emerald-500/30 transition-all" style={{ left: `min(${moveStartPct}%, calc(100% - 28px))`, width: `${moveEndPct - moveStartPct}%`, minWidth: '28px' }} onMouseDown={(e) => handleTimelineDrag(e, 'range')}>
- <div className="absolute -left-1.5 top-0 bottom-0 w-4 cursor-ew-resize group/left flex items-center justify-center z-20" onMouseDown={(e) => { e.stopPropagation(); handleTimelineDrag(e, 'start'); }}>
- <div className="w-0.5 h-3 bg-emerald-400/50 group-hover/left:bg-emerald-300 rounded-full transition-colors" />
- </div>
- <div className="absolute inset-0 flex items-center justify-center pointer-events-none opacity-30">
- <div className="w-1 h-1 bg-emerald-400 rounded-full mx-0.5" />
- </div>
- <div className="absolute -right-1.5 top-0 bottom-0 w-4 cursor-ew-resize group/right flex items-center justify-center z-20" onMouseDown={(e) => { e.stopPropagation(); handleTimelineDrag(e, 'end'); }}>
- <div className="w-0.5 h-3 bg-emerald-400/50 group-hover/right:bg-emerald-300 rounded-full transition-colors" />
- </div>
- </div>
- <div className="absolute inset-0 flex justify-between px-1 pointer-events-none opacity-25">
- {[...Array(6)].map((_, i) => (<div key={i} className="w-px h-full bg-foreground/20" />))}
- </div>
- </div>
- <div className="h-full bg-muted/40 border-l border-border flex items-center justify-center opacity-40 hover:opacity-100 transition-opacity" style={{ width: `${exitPct}%` }}>
- <Icon icon="iconamoon:zoom-out-fill" width="12" className="text-muted-foreground" />
- </div>
- </div>
-
- <div className="flex items-center justify-between px-0.5">
- <div className="flex gap-4 text-[9px] font-mono text-muted-foreground/80">
- <span className="flex items-center gap-1.5">
- <span className="text-emerald-500/50">{t("movement.timeline.startLabel")}</span>
- <span className="text-foreground/80">{startOffset.toFixed(1)}s</span>
- </span>
- <span className="flex items-center gap-1.5">
- <span className="text-emerald-500/50">{t("movement.timeline.endLabel")}</span>
- <span className="text-foreground/80">{endOffset.toFixed(1)}s</span>
- </span>
- </div>
- </div>
- </div>
- </div>
- ) : (
- <div className="p-3 bg-amber-500/10 border border-amber-500/20 squircle-element">
- <div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400">
- <span>{t("movement.tooShort")}</span>
- </div>
- </div>
- );
- })()}
+ {!is3DModelActive && (
+ <div className="space-y-3 p-3 bg-muted/40 border border-border squircle-element">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Icon icon="mdi:cube-outline" width="16" className="text-muted-foreground" />
+ <div>
+ <p className="text-xs font-medium text-foreground/90">{tCommon("effect3d.title")}</p>
+ <p className="text-[11px] text-muted-foreground">{tCommon("effect3d.subtitle")}</p>
</div>
+ </div>
+ <Toggle checked={fragment.enable3D ?? false} onChange={handleToggle3D} activeColor="bg-gray-400" />
+ </div>
+ {fragment.enable3D && (
+ <div className="space-y-3 pt-3 border-t border-border">
+ <SliderControl icon="mdi:brightness-6" label={tCommon("effect3d.intensity")} value={fragment.perspective3DIntensity ?? 50} min={0} max={100} step={5} onChange={(value) => onUpdate({ perspective3DIntensity: value })} suffix="%" />
+ {(() => {
+ const defaultAngleX = ((fragment.focusY - 50) / 50) * 15;
+ const defaultAngleY = -((fragment.focusX - 50) / 50) * 15;
+ const angleX = fragment.perspective3DAngleX ?? defaultAngleX;
+ const angleY = fragment.perspective3DAngleY ?? defaultAngleY;
+ return (
+ <DirectionPad angleX={angleX} angleY={angleY} onChange={(x, y) => onUpdate({ perspective3DAngleX: x, perspective3DAngleY: y })} accentRgb="156,163,175" label={tCommon("effect3d.direction")} hint={tCommon("effect3d.directionHint")} className="aspect-square max-w-[220px]" />
+ );
+ })()}
+ </div>
+ )}
+ </div>
+ )}
- {/* 3D effect */}
- {!is3DModelActive && (
- <div className="space-y-3 p-3 bg-muted/40 border border-border squircle-element">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Icon icon="mdi:cube-outline" width="16" className="text-muted-foreground" />
- <div>
- <p className="text-xs font-medium text-foreground/90">{tCommon("effect3d.title")}</p>
- <p className="text-[11px] text-muted-foreground">{tCommon("effect3d.subtitle")}</p>
- </div>
- </div>
- <Toggle
- checked={fragment.enable3D ?? false}
- onChange={handleToggle3D}
- activeColor="bg-gray-400"
- />
- </div>
-
- {fragment.enable3D && (
- <div className="space-y-3 pt-3 border-t border-border">
- <SliderControl icon="mdi:brightness-6" label={tCommon("effect3d.intensity")} value={fragment.perspective3DIntensity ?? 50} min={0} max={100} step={5} onChange={(value) => onUpdate({ perspective3DIntensity: value })} suffix="%" />
- {(() => {
- const defaultAngleX = ((fragment.focusY - 50) / 50) * 15;
- const defaultAngleY = -((fragment.focusX - 50) / 50) * 15;
- const angleX = fragment.perspective3DAngleX ?? defaultAngleX;
- const angleY = fragment.perspective3DAngleY ?? defaultAngleY;
- return (
- <DirectionPad
- angleX={angleX}
- angleY={angleY}
- onChange={(x, y) => onUpdate({ perspective3DAngleX: x, perspective3DAngleY: y })}
- accentRgb="156,163,175"
- label={tCommon("effect3d.direction")}
- hint={tCommon("effect3d.directionHint")}
- className="aspect-square max-w-[220px]"
- />
- );
- })()}
- </div>
- )}
- </div>
- )}
-
- <SliderControl icon="mdi:magnify-plus-outline" label={t("sliders.zoomLevel")} value={fragment.zoomLevel} min={1} max={10} step={0.1} onChange={(value) => onUpdate({ zoomLevel: value })} />
- <SliderControl icon="mdi:speedometer" label={t("sliders.transitionSpeed")} value={fragment.speed} min={1} max={10} step={0.1} onChange={(value) => onUpdate({ speed: value })} />
+ <SliderControl icon="mdi:magnify-plus-outline" label={t("sliders.zoomLevel")} value={fragment.zoomLevel} min={1} max={10} step={0.1} onChange={(value) => onUpdate({ zoomLevel: value })} />
+ <SliderControl icon="mdi:speedometer" label={t("sliders.transitionSpeed")} value={fragment.speed} min={1} max={10} step={0.1} onChange={(value) => onUpdate({ speed: value })} />
- <div className="h-px bg-border" />
+ <div className="h-px bg-border" />
- <div className="space-y-2">
- <div className="flex items-center justify-between text-[11px]">
- <span className="text-muted-foreground/70">{t("info.fragmentDuration")}</span>
- <span className="font-mono text-muted-foreground bg-muted px-2 py-0.5 rounded">
- {formatZoomTime(fragment.startTime)} - {formatZoomTime(fragment.endTime)}
- </span>
- </div>
- <div className="flex items-center justify-between text-[11px]">
- <span className="text-muted-foreground/70">{t("info.zoomFactor")}</span>
- <span className="font-mono text-muted-foreground bg-muted px-2 py-0.5 rounded">
- {zoomLevelToFactor(fragment.zoomLevel).toFixed(1)}×
- </span>
- </div>
- <div className="flex items-center justify-between text-[11px]">
- <span className="text-muted-foreground/70">{t("info.transitionDuration")}</span>
- <span className="font-mono text-muted-foreground bg-muted px-2 py-0.5 rounded">
- {(speedToTransitionMs(fragment.speed) / 1000).toFixed(1)}s
- </span>
- </div>
- </div>
- </div>
+ <div className="space-y-2">
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="text-muted-foreground/70">{t("info.fragmentDuration")}</span>
+ <span className="font-mono text-muted-foreground bg-muted px-2 py-0.5 rounded">
+ {formatZoomTime(fragment.startTime)} - {formatZoomTime(fragment.endTime)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="text-muted-foreground/70">{t("info.zoomFactor")}</span>
+ <span className="font-mono text-muted-foreground bg-muted px-2 py-0.5 rounded">{zoomLevelToFactor(fragment.zoomLevel).toFixed(1)}×</span>
+ </div>
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="text-muted-foreground/70">{t("info.transitionDuration")}</span>
+ <span className="font-mono text-muted-foreground bg-muted px-2 py-0.5 rounded">{(speedToTransitionMs(fragment.speed) / 1000).toFixed(1)}s</span>
+ </div>
</div>
- );
+ </div>
+ </div>
+ );
}
\ No newline at end of file
diff --git a/app/components/ui/editor/ZoomFragmentTrackItem.tsx b/app/components/ui/editor/ZoomFragmentTrackItem.tsx
index 5efb499..4848966 100644
--- a/app/components/ui/editor/ZoomFragmentTrackItem.tsx
+++ b/app/components/ui/editor/ZoomFragmentTrackItem.tsx
@@ -275,121 +275,4 @@ export function ZoomFragmentTrackItem({
</motion.div>
</motion.div>
);
-}
-
-export function canAddFragmentAt(
- startTime: number,
- endTime: number,
- existingFragments: ZoomFragment[],
- excludeFragmentId?: string
-): boolean {
- for (const fragment of existingFragments) {
- if (excludeFragmentId && fragment.id === excludeFragmentId) continue;
-
- const overlaps = startTime < fragment.endTime && endTime > fragment.startTime;
- if (overlaps) return false;
- }
- return true;
-}
-
-function findAllGaps(
- existingFragments: ZoomFragment[],
- videoDuration: number,
- minDuration: number
-): Array<{ start: number; end: number }> {
- const gaps: Array<{ start: number; end: number }> = [];
- const sorted = [...existingFragments].sort((a, b) => a.startTime - b.startTime);
-
- if (sorted.length === 0) {
- if (videoDuration >= minDuration) {
- gaps.push({ start: 0, end: videoDuration });
- }
- return gaps;
- }
-
- if (sorted[0].startTime >= minDuration) {
- gaps.push({ start: 0, end: sorted[0].startTime });
- }
-
- for (let i = 0; i < sorted.length - 1; i++) {
- const gapStart = sorted[i].endTime;
- const gapEnd = sorted[i + 1].startTime;
- if (gapEnd - gapStart >= minDuration) {
- gaps.push({ start: gapStart, end: gapEnd });
- }
- }
-
- const lastEnd = sorted[sorted.length - 1].endTime;
- if (videoDuration - lastEnd >= minDuration) {
- gaps.push({ start: lastEnd, end: videoDuration });
- }
-
- return gaps;
-}
-
-export function findValidFragmentPosition(
- clickTime: number,
- defaultDuration: number,
- existingFragments: ZoomFragment[],
- videoDuration: number
-): { startTime: number; endTime: number } | null {
- const gaps = findAllGaps(existingFragments, videoDuration, defaultDuration);
-
- if (gaps.length === 0) {
- return null;
- }
-
- for (const gap of gaps) {
- if (clickTime >= gap.start && clickTime <= gap.end) {
- const halfDuration = defaultDuration / 2;
- let startTime = clickTime - halfDuration;
- let endTime = clickTime + halfDuration;
-
- if (startTime < gap.start) {
- startTime = gap.start;
- endTime = startTime + defaultDuration;
- }
- if (endTime > gap.end) {
- endTime = gap.end;
- startTime = endTime - defaultDuration;
- }
-
- return { startTime, endTime };
- }
- }
-
- let closestGap = gaps[0];
- let closestDistance = Infinity;
-
- for (const gap of gaps) {
- const distToStart = Math.abs(clickTime - gap.start);
- const distToEnd = Math.abs(clickTime - gap.end);
- const gapCenter = (gap.start + gap.end) / 2;
- const distToCenter = Math.abs(clickTime - gapCenter);
-
- const minDist = Math.min(distToStart, distToEnd, distToCenter);
-
- if (minDist < closestDistance) {
- closestDistance = minDist;
- closestGap = gap;
- }
- }
-
- if (clickTime <= closestGap.start) {
- return {
- startTime: closestGap.start,
- endTime: closestGap.start + defaultDuration,
- };
- } else if (clickTime >= closestGap.end) {
- return {
- startTime: closestGap.end - defaultDuration,
- endTime: closestGap.end,
- };
- } else {
- return {
- startTime: closestGap.start,
- endTime: closestGap.start + defaultDuration,
- };
- }
-}
-
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/ZoomMovementTrackItem.tsx b/app/components/ui/editor/ZoomMovementTrackItem.tsx
new file mode 100644
index 0000000..8131b22
--- /dev/null
+++ b/app/components/ui/editor/ZoomMovementTrackItem.tsx
@@ -0,0 +1,156 @@
+"use client";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { motion, useMotionValue } from "framer-motion";
+import type { ZoomMovement } from "@/types/zoom.types";
+
+export const MIN_MOVEMENT_TRACK_DURATION = 0.6;
+
+interface ZoomMovementTrackItemProps {
+ movement: ZoomMovement;
+ index: number;
+ isSelected: boolean;
+ contentWidth: number;
+ videoDuration: number;
+ holdStart: number;
+ holdEnd: number;
+ otherMovements: ZoomMovement[];
+ onSelect: () => void;
+ onUpdate: (updates: Partial<ZoomMovement>) => void;
+ onDragStateChange?: (isDragging: boolean) => void;
+ onMouseEnter?: () => void;
+ onMouseLeave?: () => void;
+}
+
+export function ZoomMovementTrackItem({
+ movement, index, isSelected, contentWidth, videoDuration,
+ holdStart, holdEnd, otherMovements, onSelect, onUpdate, onDragStateChange, onMouseEnter, onMouseLeave,
+}: ZoomMovementTrackItemProps) {
+ const [isDragging, setIsDragging] = useState(false);
+ const [isResizing, setIsResizing] = useState<"start" | "end" | null>(null);
+
+ const timeToPixels = useCallback((time: number) => (time / videoDuration) * contentWidth, [videoDuration, contentWidth]);
+ const pixelsToTime = useCallback((pixels: number) => (pixels / contentWidth) * videoDuration, [contentWidth, videoDuration]);
+
+ const fragmentX = useMotionValue(0);
+ const fragmentWidth = useMotionValue(0);
+ const initialLeft = timeToPixels(movement.startTime);
+ const initialWidth = timeToPixels(movement.endTime - movement.startTime);
+
+ useEffect(() => {
+ if (!isDragging && !isResizing) {
+ fragmentX.set(initialLeft);
+ fragmentWidth.set(initialWidth);
+ }
+ }, [initialLeft, initialWidth, isDragging, isResizing, fragmentX, fragmentWidth]);
+
+ const boundaries = useMemo(() => {
+ const sorted = [...otherMovements].sort((a, b) => a.startTime - b.startTime);
+ let minStart = holdStart;
+ let maxEnd = holdEnd;
+ for (const other of sorted) {
+ if (other.endTime <= movement.startTime) minStart = Math.max(minStart, other.endTime);
+ if (other.startTime >= movement.endTime) { maxEnd = Math.min(maxEnd, other.startTime); break; }
+ }
+ return { minStart, maxEnd };
+ }, [otherMovements, movement.startTime, movement.endTime, holdStart, holdEnd]);
+
+ const handleDrag = useCallback((_: unknown, info: { delta: { x: number } }) => {
+ if (contentWidth === 0 || videoDuration === 0) return;
+ const currentX = fragmentX.get();
+ const duration = movement.endTime - movement.startTime;
+ let newX = currentX + info.delta.x;
+ const minX = timeToPixels(boundaries.minStart);
+ const maxX = timeToPixels(boundaries.maxEnd - duration);
+ newX = Math.max(minX, Math.min(maxX, newX));
+ fragmentX.set(newX);
+ }, [contentWidth, videoDuration, fragmentX, movement, boundaries, timeToPixels]);
+
+ const handleDragStart = useCallback(() => { setIsDragging(true); onDragStateChange?.(true); }, [onDragStateChange]);
+ const handleDragEnd = useCallback(() => {
+ setIsDragging(false); onDragStateChange?.(false);
+ const newStart = pixelsToTime(fragmentX.get());
+ const duration = movement.endTime - movement.startTime;
+ onUpdate({ startTime: Math.max(holdStart, newStart), endTime: Math.min(holdEnd, newStart + duration) });
+ }, [fragmentX, pixelsToTime, movement, holdStart, holdEnd, onUpdate, onDragStateChange]);
+
+ const handleResizeStartDrag = useCallback((_: unknown, info: { delta: { x: number } }) => {
+ if (contentWidth === 0 || videoDuration === 0) return;
+ const currentX = fragmentX.get();
+ const currentWidth = fragmentWidth.get();
+ let newX = currentX + info.delta.x;
+ let newWidth = currentWidth - info.delta.x;
+ const minWidth = timeToPixels(MIN_MOVEMENT_TRACK_DURATION);
+ if (newWidth < minWidth) { newWidth = minWidth; newX = currentX + currentWidth - minWidth; }
+ const minX = timeToPixels(boundaries.minStart);
+ if (newX < minX) { const diff = minX - newX; newX = minX; newWidth = currentWidth - diff; }
+ fragmentX.set(newX); fragmentWidth.set(newWidth);
+ }, [contentWidth, videoDuration, fragmentX, fragmentWidth, boundaries, timeToPixels]);
+
+ const handleResizeEndDrag = useCallback((_: unknown, info: { delta: { x: number } }) => {
+ if (contentWidth === 0 || videoDuration === 0) return;
+ const currentWidth = fragmentWidth.get();
+ let newWidth = currentWidth + info.delta.x;
+ const minWidth = timeToPixels(MIN_MOVEMENT_TRACK_DURATION);
+ newWidth = Math.max(minWidth, newWidth);
+ const currentX = fragmentX.get();
+ const maxWidth = timeToPixels(boundaries.maxEnd) - currentX;
+ newWidth = Math.min(newWidth, maxWidth);
+ fragmentWidth.set(newWidth);
+ }, [contentWidth, videoDuration, fragmentWidth, fragmentX, boundaries, timeToPixels]);
+
+ const handleResizeStart = useCallback((h: "start" | "end") => { setIsResizing(h); onDragStateChange?.(true); }, [onDragStateChange]);
+ const handleResizeEnd = useCallback(() => {
+ setIsResizing(null); onDragStateChange?.(false);
+ const newStart = pixelsToTime(fragmentX.get());
+ const newEnd = pixelsToTime(fragmentX.get() + fragmentWidth.get());
+ onUpdate({ startTime: Math.max(holdStart, newStart), endTime: Math.min(holdEnd, newEnd) });
+ }, [fragmentX, fragmentWidth, pixelsToTime, holdStart, holdEnd, onUpdate, onDragStateChange]);
+
+ const duration = movement.endTime - movement.startTime;
+ const isInteracting = isDragging || isResizing !== null;
+
+ return (
+ <motion.div
+ className={`absolute h-[80%] top-1/2 -translate-y-1/2 rounded-md flex items-center border transition-shadow select-none focus:outline-none ${isSelected || isInteracting
+ ? "bg-emerald-500/30 border-emerald-400/70 shadow-[0_0_10px_rgba(16,185,129,0.3)] z-10"
+ : "border-emerald-500/35 hover:border-emerald-500/60"
+ } ${isDragging ? "cursor-grabbing" : "cursor-grab"}`}
+ style={{ x: fragmentX, width: fragmentWidth }}
+ drag="x"
+ dragConstraints={{ left: 0, right: contentWidth }}
+ dragElastic={0}
+ dragMomentum={false}
+ onDrag={handleDrag}
+ onDragStart={handleDragStart}
+ onDragEnd={handleDragEnd}
+ onClick={(e) => { e.stopPropagation(); onSelect(); }}
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
+ whileTap={{ scale: 0.98 }}
+ role="slider"
+ aria-label={`Movement ${index}: ${movement.name}, ${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={() => handleResizeStart("start")} onDragEnd={handleResizeEnd}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className={`w-1 h-5 rounded-full ${isResizing === "start" ? "bg-emerald-300 scale-110" : "bg-emerald-500/70"}`} />
+ </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 text-emerald-700 dark:text-emerald-200">{movement.name}</span>
+ <span className="text-[9px] truncate text-emerald-700/60 dark:text-emerald-300/60">{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={() => handleResizeStart("end")} onDragEnd={handleResizeEnd}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className={`w-1 h-5 rounded-full ${isResizing === "end" ? "bg-emerald-300 scale-110" : "bg-emerald-500/70"}`} />
+ </motion.div>
+ </motion.div>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/home/HeroEditorPreview.tsx b/app/components/ui/home/HeroEditorPreview.tsx
index 63ed61f..48c2f3b 100644
--- a/app/components/ui/home/HeroEditorPreview.tsx
+++ b/app/components/ui/home/HeroEditorPreview.tsx
@@ -168,7 +168,7 @@ function EditorCanvas({
}}
>
<div
- className="absolute overflow-hidden bg-black squircle-corner"
+ className="absolute overflow-hidden bg-black squircle-element sm:squircle-corner"
style={{
inset: `${paddingPct}%`,
borderRadius: `${roundedPx}px`,
diff --git a/components/ui/HeroEditorPreviewComponents.tsx b/components/ui/HeroEditorPreviewComponents.tsx
index 2f52eba..0c867c1 100644
--- a/components/ui/HeroEditorPreviewComponents.tsx
+++ b/components/ui/HeroEditorPreviewComponents.tsx
@@ -466,7 +466,7 @@ export const SwatchGrid = memo(function SwatchGrid({
boxShadow:
isActiveCategory && i === activeIndex
? `0 0 0 2px white, 0 0 0 3.5px ${ACCENT}`
- : "0 0 0 1px rgba(0,0,0,0.08)",
+ : "0 0 0 2px rgba(0,0,0,0.05)",
}}
/>
))}
diff --git a/components/ui/ZoomPointOverlay.tsx b/components/ui/ZoomPointOverlay.tsx
new file mode 100644
index 0000000..e99d241
--- /dev/null
+++ b/components/ui/ZoomPointOverlay.tsx
@@ -0,0 +1,104 @@
+"use client";
+
+import React from "react";
+import { zoomLevelToFactor } from "@/types/zoom.types";
+
+export interface ZoomPoint {
+ id: string;
+ x: number;
+ y: number;
+ label: string;
+}
+
+interface ZoomPointOverlayProps {
+ points: ZoomPoint[];
+ zoomLevel: number;
+ activePointId: string | null;
+ onPointPointerDown: (e: React.PointerEvent<HTMLDivElement>, id: string) => void;
+ markerId?: string;
+}
+
+export function ZoomPointOverlay({
+ points,
+ zoomLevel,
+ activePointId,
+ onPointPointerDown,
+ markerId = "default-chain-arrowhead"
+}: ZoomPointOverlayProps) {
+ if (points.length === 0) return null;
+
+ const VISUAL_SCALE = 0.7;
+ const rawBoxSize = 100 / zoomLevelToFactor(zoomLevel);
+ const boxSize = `${rawBoxSize * VISUAL_SCALE}%`;
+
+ return (
+ <>
+ {points.length > 1 && (
+ <svg className="absolute inset-0 w-full h-full pointer-events-none" style={{ zIndex: 1 }}>
+ <defs>
+ <marker id={markerId} markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" fill="rgba(16, 185, 129, 0.7)" />
+ </marker>
+ </defs>
+ {points.slice(1).map((point, i) => {
+ const from = points[i];
+ const dx = point.x - from.x;
+ const dy = point.y - from.y;
+ const dist = Math.sqrt(dx * dx + dy * dy);
+ const radius = dist > 0 ? 5.5 : 0;
+ const ratio = dist > 0 ? (dist - radius) / dist : 0;
+ const x2 = from.x + dx * ratio;
+ const y2 = from.y + dy * ratio;
+
+ return (
+ <line
+ key={point.id}
+ x1={`${from.x}%`} y1={`${from.y}%`}
+ x2={`${x2}%`} y2={`${y2}%`}
+ stroke="#10b981"
+ strokeWidth="2.5"
+ strokeDasharray="6 4"
+ markerEnd={`url(#${markerId})`}
+ />
+ );
+ })}
+ </svg>
+ )}
+
+ {points.map((point) => (
+ <div key={point.id}>
+ <div
+ className="absolute border border-dashed squircle-element pointer-events-none transition-opacity duration-200"
+ style={{
+ width: boxSize,
+ height: boxSize,
+ left: `${point.x}%`,
+ top: `${point.y}%`,
+ transform: "translate(-50%, -50%)",
+ opacity: point.id === activePointId ? 1 : 0.4,
+ borderColor: point.id === "origin" ? "rgba(59,130,246,0.5)" : "rgba(16,185,129,0.5)",
+ background: point.id === "origin"
+ ? "linear-gradient(to bottom, rgba(59,130,246,0.5), transparent)"
+ : "linear-gradient(to bottom, rgba(16,185,129,0.5), transparent)",
+ }}
+ />
+
+ <div
+ data-zoom-drag-handle
+ className={`absolute z-10 cursor-grab active:cursor-grabbing touch-none transition-[opacity,transform] duration-150 ${
+ point.id === activePointId ? "" : "scale-90"
+ }`}
+ style={{ left: `${point.x}%`, top: `${point.y}%`, transform: "translate(-50%, -50%)" }}
+ onPointerDown={(e) => onPointPointerDown(e, point.id)}
+ >
+ <div className={`size-8 rounded-full shadow-lg border-2 border-white/90 hover:scale-110 transition-transform flex items-center justify-center ${
+ point.id === "origin" ? "bg-blue-500" : "bg-emerald-500"
+ }`}>
+ <span className="text-[10px] font-bold text-white">{point.label}</span>
+ </div>
+ </div>
+ </div>
+ ))}
+ </>
+ );
+}
\ No newline at end of file