Skip to content

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

feat: Introduce ZoomMovement functionality and enhance zoom fragment handling; add movement utilities and update related types and interfaces

CristianOlivera1c69ba5613994
diff --git a/lib/canvas.utils.ts b/lib/canvas.utils.ts
index 2e18344..4f179d0 100644
--- a/lib/canvas.utils.ts
+++ b/lib/canvas.utils.ts
@@ -1,5 +1,5 @@
import { AspectRatio } from "@/types/editor.types";
-import { ZoomStateCanvas, ZoomFragment, calculateZoomPhaseState, zoomLevelToFactor, speedToTransitionMs, easeOutQuart } from "@/types/zoom.types";
+import { ZoomStateCanvas, ZoomFragment, calculateZoomPhaseState, zoomLevelToFactor, speedToTransitionMs, easeOutQuart, ZoomMovement } from "@/types/zoom.types";
export function drawRoundedRect(
ctx: CanvasRenderingContext2D,
@@ -204,33 +204,21 @@ export interface ZoomStateCanvasExport extends ZoomStateCanvas {
*/
export function calculateSmoothZoom(
frameTime: number,
- zoomFragments: ZoomFragment[]
+ zoomFragments: ZoomFragment[],
+ zoomMovements: ZoomMovement[] = []
): ZoomStateCanvasExport {
const DEFAULT_STATE: ZoomStateCanvasExport = {
- scale: 1,
- focusX: 50,
- focusY: 50,
- rotateX: 0,
- rotateY: 0,
- perspective: 0,
+ scale: 1, focusX: 50, focusY: 50, rotateX: 0, rotateY: 0, perspective: 0,
};
if (!zoomFragments.length) return DEFAULT_STATE;
const sortedFragments = [...zoomFragments].sort((a, b) => a.startTime - b.startTime);
-
- const activeFragment = sortedFragments.find(
- f => frameTime >= f.startTime && frameTime <= f.endTime
- );
-
- const previousFragment = sortedFragments
- .filter(f => f.endTime < frameTime)
- .sort((a, b) => b.endTime - a.endTime)[0];
+ const activeFragment = sortedFragments.find(f => frameTime >= f.startTime && frameTime <= f.endTime);
+ const previousFragment = sortedFragments.filter(f => f.endTime < frameTime).sort((a, b) => b.endTime - a.endTime)[0];
const isAdvancedZoom = (f: ZoomFragment) => f.enable3D || f.movementEnabled;
-
- // Shared scale curve: entry ramps INSIDE the fragment, then holds flat.
- // Used for BOTH simple and advanced zoom while the fragment is active.
+ const movementsFor = (fragmentId: string) => zoomMovements.filter(m => m.zoomFragmentId === fragmentId);
const computeHeldScale = (fragment: ZoomFragment, time: number): number => {
const transitionSec = speedToTransitionMs(fragment.speed) / 1000;
const targetScale = zoomLevelToFactor(fragment.zoomLevel);
@@ -242,8 +230,6 @@ export function calculateSmoothZoom(
return targetScale;
};
- // Shared exit curve: decays AFTER the fragment ends. Returns null once
- // the exit transition has fully finished (caller falls through to default).
const computeExitScale = (fragment: ZoomFragment, time: number): number | null => {
const transitionSec = speedToTransitionMs(fragment.speed) / 1000;
if (transitionSec <= 0) return null;
@@ -257,62 +243,21 @@ export function calculateSmoothZoom(
if (activeFragment) {
const scale = computeHeldScale(activeFragment, frameTime);
-
if (isAdvancedZoom(activeFragment)) {
- // Rotation + focus/movement still use the existing 3-phase system —
- // that part already matches preview, we only override `scale`.
- const phaseState = calculateZoomPhaseState(activeFragment, frameTime, true);
- return {
- scale,
- focusX: phaseState.focusX,
- focusY: phaseState.focusY,
- rotateX: phaseState.rotateX,
- rotateY: phaseState.rotateY,
- perspective: phaseState.perspective,
- };
+ const phaseState = calculateZoomPhaseState(activeFragment, frameTime, movementsFor(activeFragment.id), true);
+ return { scale, focusX: phaseState.focusX, focusY: phaseState.focusY, rotateX: phaseState.rotateX, rotateY: phaseState.rotateY, perspective: phaseState.perspective };
}
-
- return {
- scale,
- focusX: activeFragment.focusX,
- focusY: activeFragment.focusY,
- rotateX: 0,
- rotateY: 0,
- perspective: 0,
- };
+ return { scale, focusX: activeFragment.focusX, focusY: activeFragment.focusY, rotateX: 0, rotateY: 0, perspective: 0 };
}
if (previousFragment) {
const exitScale = computeExitScale(previousFragment, frameTime);
if (exitScale !== null) {
if (isAdvancedZoom(previousFragment)) {
- const phaseState = calculateZoomPhaseState(previousFragment, frameTime, true);
-
- const focusX = previousFragment.movementEnabled
- ? (previousFragment.movementEndX ?? previousFragment.focusX)
- : previousFragment.focusX;
- const focusY = previousFragment.movementEnabled
- ? (previousFragment.movementEndY ?? previousFragment.focusY)
- : previousFragment.focusY;
-
- return {
- scale: exitScale,
- focusX,
- focusY,
- rotateX: phaseState.rotateX,
- rotateY: phaseState.rotateY,
- perspective: phaseState.perspective,
- };
+ const phaseState = calculateZoomPhaseState(previousFragment, frameTime, movementsFor(previousFragment.id), true);
+ return { scale: exitScale, focusX: phaseState.focusX, focusY: phaseState.focusY, rotateX: phaseState.rotateX, rotateY: phaseState.rotateY, perspective: phaseState.perspective };
}
-
- return {
- scale: exitScale,
- focusX: previousFragment.focusX,
- focusY: previousFragment.focusY,
- rotateX: 0,
- rotateY: 0,
- perspective: 0,
- };
+ return { scale: exitScale, focusX: previousFragment.focusX, focusY: previousFragment.focusY, rotateX: 0, rotateY: 0, perspective: 0 };
}
}
diff --git a/lib/mockup-motion.ts b/lib/mockup-motion.ts
index 305af43..f011d3a 100644
--- a/lib/mockup-motion.ts
+++ b/lib/mockup-motion.ts
@@ -588,13 +588,11 @@ export function sampleMockupMotion(
tx: levelTiltX * 0.6, ty: tiltYMax * 0.20, tz: 0, blur: 0
};
- // NUEVO: Transición intermedia hacia el centro
const h6 = {
s: heroScale, x: 0, y: 0,
tx: lerp(5, 12, i), ty: -lerp(10, 18, i), tz: 0, blur: 0
};
- // NUEVO: Remate Isométrico Majestuoso (En lugar de volver a h0)
const h7_end = {
s: heroScale * lerp(1.1, 1.18, i),
x: 0,
diff --git a/lib/zoom-movement.utils.ts b/lib/zoom-movement.utils.ts
new file mode 100644
index 0000000..a1bf74e
--- /dev/null
+++ b/lib/zoom-movement.utils.ts
@@ -0,0 +1,64 @@
+import type { ZoomMovement } from "@/types/zoom.types";
+
+export const MIN_MOVEMENT_DURATION = 0.3;
+
+export function canAddMovementAt(
+ startTime: number,
+ endTime: number,
+ existingMovements: ZoomMovement[],
+ excludeId?: string
+): boolean {
+ for (const movement of existingMovements) {
+ if (excludeId && movement.id === excludeId) continue;
+ if (startTime < movement.endTime && endTime > movement.startTime) return false;
+ }
+ return true;
+}
+
+function findAllMovementGaps(
+ existingMovements: ZoomMovement[],
+ windowStart: number,
+ windowEnd: number,
+ minDuration: number
+): Array<{ start: number; end: number }> {
+ const gaps: Array<{ start: number; end: number }> = [];
+ const sorted = [...existingMovements].sort((a, b) => a.startTime - b.startTime);
+
+ if (sorted.length === 0) {
+ if (windowEnd - windowStart >= minDuration) gaps.push({ start: windowStart, end: windowEnd });
+ return gaps;
+ }
+ if (sorted[0].startTime - windowStart >= minDuration) {
+ gaps.push({ start: windowStart, 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 (windowEnd - lastEnd >= minDuration) gaps.push({ start: lastEnd, end: windowEnd });
+ return gaps;
+}
+
+export function hasMovementSpaceAvailable(
+ existingMovements: ZoomMovement[],
+ windowStart: number,
+ windowEnd: number,
+ minDuration: number = MIN_MOVEMENT_DURATION
+): boolean {
+ return findAllMovementGaps(existingMovements, windowStart, windowEnd, minDuration).length > 0;
+}
+
+export function findNextMovementSlot(
+ existingMovements: ZoomMovement[],
+ windowStart: number,
+ windowEnd: number,
+ defaultDuration: number
+): { startTime: number; endTime: number } | null {
+ const gaps = findAllMovementGaps(existingMovements, windowStart, windowEnd, Math.min(defaultDuration, MIN_MOVEMENT_DURATION));
+ if (gaps.length === 0) return null;
+ const gap = gaps[0];
+ const duration = Math.min(defaultDuration, gap.end - gap.start);
+ return { startTime: gap.start, endTime: gap.start + duration };
+}
\ No newline at end of file
diff --git a/types/control-panel.types.ts b/types/control-panel.types.ts
index 75ba893..7899e12 100644
--- a/types/control-panel.types.ts
+++ b/types/control-panel.types.ts
@@ -1,6 +1,6 @@
import { BackgroundTab, Tool, VideoThumbnail } from "./editor.types";
import { BackgroundColorConfig } from "./background.types";
-import { ZoomFragment } from "./zoom.types";
+import { ZoomFragment, ZoomMovement } from "./zoom.types";
import { MockupConfig, MenuPage } from "./mockup.types";
import type { CanvasElement } from "./canvas-elements.types";
import type { UploadedAudio, AudioTrack } from "./audio.types";
@@ -33,6 +33,13 @@ export interface ControlPanelProps {
onAddZoomFragment?: () => void;
onUpdateZoomFragment?: (fragmentId: string, updates: Partial<ZoomFragment>) => void;
onDeleteZoomFragment?: (fragmentId: string) => void;
+ zoomMovements?: ZoomMovement[];
+ selectedZoomMovementId?: string | null;
+ onSelectZoomMovement?: (id: string | null) => void;
+ onToggleZoomMovement?: (fragmentId: string, enabled: boolean) => void;
+ onAddZoomMovement?: (fragmentId: string) => void;
+ onDeleteZoomMovement?: (id: string) => void;
+ onUpdateZoomMovementPoint?: (id: string, x: number, y: number) => void;
videoUrl?: string | null;
videoThumbnail?: string | null;
currentTime?: number;
diff --git a/types/editor-state.types.ts b/types/editor-state.types.ts
index 3f2a68c..9b32207 100644
--- a/types/editor-state.types.ts
+++ b/types/editor-state.types.ts
@@ -1,4 +1,4 @@
-import type { BackgroundTab, AspectRatio, BackgroundColorConfig, CropArea, ZoomFragment, AudioTrack } from "@/types";
+import type { BackgroundTab, AspectRatio, BackgroundColorConfig, CropArea, ZoomFragment, AudioTrack, ZoomMovement } from "@/types";
import type { TrimRange } from "@/types/timeline.types";
import type { MockupConfig } from "@/types/mockup.types";
import type { CanvasElement } from "@/types/canvas-elements.types";
@@ -55,6 +55,9 @@ export interface EditorState {
imagePhoneRefWidth: number;
mockupMotionFragments: MockupMotionFragment[];
videoClips: VideoTrackClip[];
+ zoomMovements: ZoomMovement[];
+ imageZoomScale: number;
+ unsplashBgUrl: string;
}
export function createInitialEditorState(overrides?: Partial<EditorState>): EditorState {
@@ -125,5 +128,8 @@ export function createInitialEditorState(overrides?: Partial<EditorState>): Edit
mockupMotionFragments: [],
videoClips: [],
...overrides,
+ zoomMovements: [],
+ imageZoomScale: 1,
+ unsplashBgUrl: "",
};
}
diff --git a/types/editor.types.ts b/types/editor.types.ts
index cc9a783..c5109fc 100644
--- a/types/editor.types.ts
+++ b/types/editor.types.ts
@@ -1,5 +1,5 @@
"use client";
-import type { ZoomFragment } from "./zoom.types";
+import type { ZoomFragment, ZoomMovement } from "./zoom.types";
import type { CanvasElement } from "./canvas-elements.types";
import type { ImageMaskConfig } from "@/types/photo.types";
import type { MockupConfig } from "./mockup.types";
@@ -117,4 +117,10 @@ export interface VideoCanvasProps {
mockupMotionFragments?: MockupMotionFragment[];
videoDuration?: number;
onMockupConfigChange?: (config: Partial<MockupConfig>) => void;
+ selectedZoomFragment?: ZoomFragment | null;
+ onUpdateZoomFragment?: (id: string, updates: Partial<ZoomFragment>) => void;
+ zoomMovements?: ZoomMovement[];
+ selectedZoomMovementId?: string | null;
+ onSelectZoomMovement?: (id: string | null) => void;
+ onUpdateZoomMovement?: (id: string, updates: Partial<ZoomMovement>) => void;
}
diff --git a/types/timeline.types.ts b/types/timeline.types.ts
index 52cad3a..cc0a2f5 100644
--- a/types/timeline.types.ts
+++ b/types/timeline.types.ts
@@ -1,4 +1,4 @@
-import { ZoomFragment } from "./zoom.types";
+import { ZoomFragment, ZoomMovement } from "./zoom.types";
import type { AudioTrack, UploadedAudio } from "./audio.types";
import type { VideoTrackClip } from "./video-track.types";
import { MockupMotionFragment } from "@/lib/mockup-motion";
@@ -53,4 +53,15 @@ export interface TimelineProps {
onSelectElement?: (id: string | null) => void;
onUpdateElement?: (id: string, updates: Partial<CanvasElement>) => void;
onDeleteElement?: (id: string) => void;
-}
\ No newline at end of file
+
+ zoomMovements?: ZoomMovement[];
+ selectedZoomMovementId?: string | null;
+ onSelectZoomMovement?: (id: string | null) => void;
+ onUpdateZoomMovement?: (id: string, updates: Partial<ZoomMovement>) => void;
+ onDeleteZoomMovement?: (id: string) => void;
+ onAddZoomMovementAtRange?: (startTime: number, endTime: number) => void;
+}
+
+export const DEFAULT_ZOOM_FRAGMENT_DURATION = 2;
+export const ELEMENT_ROW_HEIGHT = 55;
+export const DEFAULT_MOVEMENT_DURATION = 1;
\ No newline at end of file
diff --git a/types/zoom.types.ts b/types/zoom.types.ts
index 9fb3fbc..41a10c4 100644
--- a/types/zoom.types.ts
+++ b/types/zoom.types.ts
@@ -9,10 +9,6 @@ export interface ZoomFragment {
focusX: number;
focusY: number;
movementEnabled?: boolean;
- movementEndX?: number;
- movementEndY?: number;
- movementStartOffset?: number;
- movementEndOffset?: number;
enable3D?: boolean;
perspective3DIntensity?: number;
perspective3DAngleX?: number;
@@ -26,6 +22,13 @@ export interface ZoomState {
export interface ZoomFragmentEditorProps {
fragment: ZoomFragment;
+ movements: ZoomMovement[];
+ selectedMovementId?: string | null;
+ onSelectMovement: (id: string | null) => void;
+ onToggleMovement: (enabled: boolean) => void;
+ onAddMovement: () => void;
+ onDeleteMovement: (id: string) => void;
+ onUpdateMovementPoint: (id: string, x: number, y: number) => void;
videoUrl: string | null;
videoThumbnail?: string | null;
currentTime?: number;
@@ -37,7 +40,7 @@ export interface ZoomFragmentEditorProps {
is3DModelActive?: boolean;
}
-// Smoother easing for professional zoom feel (quart curves)
+
export function easeOutQuart(t: number): number {
return 1 - Math.pow(1 - t, 4);
}
@@ -46,7 +49,7 @@ export function easeInOutQuart(t: number): number {
return t < 0.5 ? 8 * t * t * t * t : 1 - Math.pow(-2 * t + 2, 4) / 2;
}
-// Calculate 3-phase zoom state based on current time within fragment
+
export interface ZoomPhaseState {
phase: 'entry' | 'hold' | 'exit';
scale: number;
@@ -61,7 +64,8 @@ export interface ZoomPhaseState {
export function calculateZoomPhaseState(
fragment: ZoomFragment,
currentTime: number,
- forExport: boolean = false
+ movements: ZoomMovement[] = [],
+ forExport: boolean = false,
): ZoomPhaseState {
const totalDuration = fragment.endTime - fragment.startTime;
const elapsed = currentTime - fragment.startTime;
@@ -73,7 +77,6 @@ export function calculateZoomPhaseState(
const transitionSeconds = speedToTransitionMs(fragment.speed) / 1000;
const entryEndTime = fragment.startTime + transitionSeconds;
const exitStartTime = fragment.endTime;
- const holdDuration = Math.max(0, exitStartTime - entryEndTime);
let rotateX = 0;
let rotateY = 0;
@@ -84,12 +87,31 @@ export function calculateZoomPhaseState(
let phase: 'entry' | 'hold' | 'exit' = 'hold';
let progress = normalizedTime;
- const movementEndX = fragment.movementEndX ?? fragment.focusX;
- const movementEndY = fragment.movementEndY ?? fragment.focusY;
+ const sortedMovements = [...movements].sort((a, b) => a.startTime - b.startTime);
+ const finalMovementPoint = sortedMovements.length > 0
+ ? { x: sortedMovements[sortedMovements.length - 1].focusX, y: sortedMovements[sortedMovements.length - 1].focusY }
+ : { x: fragment.focusX, y: fragment.focusY };
+
+ const resolveChainFocus = (time: number): { x: number; y: number } => {
+ let fromPoint = { x: fragment.focusX, y: fragment.focusY };
+ for (const movement of sortedMovements) {
+ if (time <= movement.endTime) {
+ const duration = movement.endTime - movement.startTime;
+ const localProgress = duration > 0 ? (time - movement.startTime) / duration : 1;
+ const eased = easeInOutQuart(Math.max(0, Math.min(1, localProgress)));
+ return {
+ x: fromPoint.x + (movement.focusX - fromPoint.x) * eased,
+ y: fromPoint.y + (movement.focusY - fromPoint.y) * eased,
+ };
+ }
+ fromPoint = { x: movement.focusX, y: movement.focusY };
+ }
+ return fromPoint;
+ };
- // Determine phase and calculate ZOOM values (independent of 3D)
+
if (currentTime < entryEndTime && transitionSeconds > 0) {
- // ENTRY PHASE: Zoom in
+
phase = 'entry';
const entryProgress = (currentTime - fragment.startTime) / transitionSeconds;
progress = Math.max(0, Math.min(1, entryProgress));
@@ -100,7 +122,7 @@ export function calculateZoomPhaseState(
}
} else if (currentTime >= exitStartTime && transitionSeconds > 0) {
- // EXIT PHASE: Zoom out
+
phase = 'exit';
const exitProgress = (currentTime - exitStartTime) / transitionSeconds;
progress = Math.max(0, Math.min(1, exitProgress));
@@ -111,8 +133,8 @@ export function calculateZoomPhaseState(
}
if (fragment.movementEnabled) {
- focusX = movementEndX;
- focusY = movementEndY;
+ focusX = finalMovementPoint.x;
+ focusY = finalMovementPoint.y;
}
} else {
@@ -122,29 +144,14 @@ export function calculateZoomPhaseState(
scale = targetScale;
}
- if (fragment.movementEnabled && holdDuration > 0) {
- const movementStartOffset = fragment.movementStartOffset ?? 0;
- const movementEndOffset = fragment.movementEndOffset ?? holdDuration;
-
- const movementStartTime = entryEndTime + Math.max(0, Math.min(movementStartOffset, holdDuration));
- const movementEndTime = entryEndTime + Math.max(movementStartOffset, Math.min(movementEndOffset, holdDuration));
- const movementDuration = movementEndTime - movementStartTime;
-
- if (currentTime >= movementStartTime && currentTime <= movementEndTime && movementDuration > 0) {
- const movementProgress = (currentTime - movementStartTime) / movementDuration;
- const easedProgress = easeInOutQuart(Math.min(1, movementProgress));
- focusX = fragment.focusX + (movementEndX - fragment.focusX) * easedProgress;
- focusY = fragment.focusY + (movementEndY - fragment.focusY) * easedProgress;
- progress = movementProgress;
- } else if (currentTime > movementEndTime) {
- focusX = movementEndX;
- focusY = movementEndY;
- progress = 1;
- }
+ if (fragment.movementEnabled) {
+ const point = resolveChainFocus(currentTime);
+ focusX = point.x;
+ focusY = point.y;
}
}
- // 3D EFFECT: Completely separate from zoom animation
+
if (enable3D) {
const intensity = (fragment.perspective3DIntensity ?? 50) / 100;
@@ -163,7 +170,7 @@ export function calculateZoomPhaseState(
effect3DOpacity = 1;
}
- // Apply 3D with smooth easing
+
const smoothOpacity = easeInOutQuart(effect3DOpacity);
perspective = 500;
@@ -184,13 +191,6 @@ export function calculateZoomPhaseState(
};
}
-// Calculate available hold time for camera movement
-export function calculateHoldDuration(fragment: ZoomFragment): number {
- const totalDuration = fragment.endTime - fragment.startTime;
- const transitionSeconds = speedToTransitionMs(fragment.speed) / 1000;
- return Math.max(0, totalDuration - 2 * transitionSeconds);
-}
-
export interface ZoomStateCanvas {
scale: number;
focusX: number;
@@ -206,7 +206,6 @@ export interface ZoomState {
const DEFAULT_ZOOM_LEVEL = 1.5;
const DEFAULT_ZOOM_SPEED = 5;
-// Helper to create a new fragment with default values
export function createZoomFragment(
startTime: number,
endTime: number
@@ -223,7 +222,6 @@ export function createZoomFragment(
};
}
-// Helper to generate default fragments when a video loads
export function generateDefaultZoomFragments(
videoDuration: number
): ZoomFragment[] {
@@ -249,7 +247,7 @@ export function generateDefaultZoomFragments(
return fragments;
}
-// Convert zoomLevel (1-10) to actual zoom factor
+
export function zoomLevelToFactor(level: number): number {
const minZoom = 1.2;
const maxZoom = 4.0;
@@ -257,7 +255,7 @@ export function zoomLevelToFactor(level: number): number {
return minZoom + (maxZoom - minZoom) * normalized;
}
-// Convert speed (1-10) to transition duration in milliseconds
+
export function speedToTransitionMs(speed: number): number {
const minMs = 150;
const maxMs = 2000;
@@ -272,3 +270,136 @@ export function formatZoomTime(seconds: number): string {
const secs = Math.floor(seconds % 60);
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
+
+export interface ZoomMovement {
+ id: string;
+ zoomFragmentId: string;
+ name: string;
+ startTime: number;
+ endTime: number;
+ focusX: number;
+ focusY: number;
+}
+
+export function getFragmentHoldBounds(fragment: ZoomFragment): { start: number; end: number } {
+ const transitionSec = speedToTransitionMs(fragment.speed) / 1000;
+ const start = fragment.startTime + transitionSec;
+ const end = fragment.endTime;
+ return start <= end ? { start, end } : { start: fragment.startTime, end: fragment.startTime };
+}
+
+export function calculateHoldDuration(fragment: ZoomFragment): number {
+ const { start, end } = getFragmentHoldBounds(fragment);
+ return Math.max(0, end - start);
+}
+
+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 findAllGapsInRange(
+ existingRanges: Array<{ startTime: number; endTime: number }>,
+ rangeStart: number,
+ rangeEnd: number,
+ minDuration: number
+): Array<{ start: number; end: number }> {
+ const gaps: Array<{ start: number; end: number }> = [];
+ const sorted = [...existingRanges].sort((a, b) => a.startTime - b.startTime);
+
+ if (sorted.length === 0) {
+ if (rangeEnd - rangeStart >= minDuration) gaps.push({ start: rangeStart, end: rangeEnd });
+ return gaps;
+ }
+
+ if (sorted[0].startTime - rangeStart >= minDuration) {
+ gaps.push({ start: rangeStart, 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 (rangeEnd - lastEnd >= minDuration) gaps.push({ start: lastEnd, end: rangeEnd });
+
+ return gaps;
+}
+
+function findAllGaps(
+ existingFragments: ZoomFragment[],
+ videoDuration: number,
+ minDuration: number
+): Array<{ start: number; end: number }> {
+ return findAllGapsInRange(existingFragments, 0, videoDuration, minDuration);
+}
+
+function findValidPositionInGaps(
+ clickTime: number,
+ defaultDuration: number,
+ gaps: Array<{ start: number; end: number }>
+): { startTime: number; endTime: number } | null {
+ 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 };
+ }
+}
+export function findValidFragmentPosition(
+ clickTime: number,
+ defaultDuration: number,
+ existingFragments: ZoomFragment[],
+ videoDuration: number
+): { startTime: number; endTime: number } | null {
+ const gaps = findAllGaps(existingFragments, videoDuration, defaultDuration);
+ return findValidPositionInGaps(clickTime, defaultDuration, gaps);
+}
+
+export function findValidMovementPosition(
+ clickTime: number,
+ defaultDuration: number,
+ existingMovements: ZoomMovement[],
+ holdStart: number,
+ holdEnd: number
+): { startTime: number; endTime: number } | null {
+ const gaps = findAllGapsInRange(existingMovements, holdStart, holdEnd, defaultDuration);
+ return findValidPositionInGaps(clickTime, defaultDuration, gaps);
+}
\ No newline at end of file