Create professional demos and 3D mockups in seconds, directly in your browser
feat: implement clip trimming functionality and restore options in video editor
CristianOlivera148da3b850321
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsxindex 9200e6c..1834241 100644--- a/app/[locale]/(editor)/editor/page.tsx+++ b/app/[locale]/(editor)/editor/page.tsx@@ -18,7 +18,7 @@ import { useVideoThumbnails, type VideoThumbnail } from "@/hooks/useVideoThumbnaimport { useUndoRedo } from "@/hooks/useUndoRedo";import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";import { addVideoToLibrary, addVideoToLibraryWithMetadata, getLibraryVideoCount, getLibraryVideo, findExistingVideo } from "@/lib/videos-library";-import { calculateTotalDuration, clampClipToRealDuration, findNextClipPosition, getClipAtTime, probeMediaDuration, resequenceClips, reorderVideoClipAt, splitClipAtTime, type VideoTrackClip, probeMediaDimensions } from "@/types/video-track.types";+import { calculateTotalDuration, clampClipToRealDuration, findNextClipPosition, getClipAtTime, probeMediaDuration, resequenceClips, reorderVideoClipAt, splitClipAtTime, type VideoTrackClip, probeMediaDimensions, restoreClipTrim, rippleTrimClip, TrimEdge } from "@/types/video-track.types";import { remapOverlaysAfterClipChange } from "@/lib/timeline-overlay-remap";import type { ExportQuality, BackgroundTab, VideoCanvasHandle, BackgroundColorConfig, AspectRatio, CropArea } from "@/types";import type { TrimRange } from "@/types/timeline.types";@@ -143,7 +143,7 @@ export default function Editor() {const [elementsTextTabTrigger] = useState(0);const [backgroundTab, setBackgroundTab] = useState<BackgroundTab>("wallpaper");- const [selectedWallpaper, setSelectedWallpaper] = useState(8);+ const [selectedWallpaper, setSelectedWallpaper] = useState(1);const [backgroundBlur, setBackgroundBlur] = useState(0);const [padding, setPadding] = useState(10);const [roundedCorners, setRoundedCorners] = useState(15);@@ -610,6 +610,11 @@ export default function Editor() {const videoClipsRef = useRef<VideoTrackClip[]>([]);useEffect(() => {videoClipsRef.current = videoClips;+ const activeId = activeClipIdRef.current;+ if (activeId) {+ const fresh = videoClips.find(c => c.id === activeId);+ if (fresh) activeClipDataRef.current = fresh;+ }}, [videoClips]);const setCurrentTimeThrottled = useCallback((time: number) => {@@ -1090,7 +1095,6 @@ export default function Editor() {handleExportRef.current = handleExport;}, [handleExport]);- // Reanuda una exportación pendiente tras iniciar sesión (redirect login → editor)useEffect(() => {if (!isVideoMode || authLoading || !authUser) return;@@ -1103,13 +1107,11 @@ export default function Editor() {if (timer) clearInterval(timer);return;}- // Esperar a que el proyecto termine de restaurarse desde IndexedDBif (isRestoringProjectRef.current) return;const hasContent = videoClipsRef.current.length > 0 || !!videoBlob;if (!hasContent) {attempts++;- // ~30s sin contenido: no hay nada que exportar, se descartaif (attempts > 120) {clearPendingExport();if (timer) clearInterval(timer);@@ -1387,48 +1389,61 @@ export default function Editor() {return videoDimensions;}, [selectedZoomFragment, videoClips, videoDimensions]);- const handleUpdateVideoClip = useCallback((clipId: string, updates: Partial<VideoTrackClip>) => {- const oldClips = videoClipsRef.current;- setVideoClips(prev => {- let newClips = prev.map(clip =>- clip.id === clipId ? { ...clip, ...updates } : clip- );- if (updates.startTime !== undefined || updates.trimEnd !== undefined || updates.trimStart !== undefined) {- // Magnetic behavior: when a clip is dragged (only startTime changed, no trim),- // re-sequence all clips to close gaps. Trim operations don't resequence.- const isDragOnly = updates.startTime !== undefined- && updates.trimStart === undefined- && updates.trimEnd === undefined;- if (isDragOnly) {- // Sort by startTime before resequencing so the dragged clip- // lands in its new temporal position. resequenceClips itself- // no longer sorts (it must preserve array order for reorders).- newClips = resequenceClips(- [...newClips].sort((a, b) => a.startTime - b.startTime)- ).clips;- }- const newDuration = calculateTotalDuration(newClips);- setVideoDuration(newDuration);- setTrimRange({ start: 0, end: newDuration });- // Remap all overlays (zoom, audio, elements, motion) to the new clip layout.- const remapped = remapOverlaysAfterClipChange({- oldClips, newClips,- zoomFragments: zoomFragmentsRef.current,- zoomMovements,- audioTracks,- canvasElements,- motionFragments: mockupMotionFragments,- });- setZoomFragments(remapped.zoomFragments);- setZoomMovements(remapped.zoomMovements);- setAudioTracks(remapped.audioTracks);- setCanvasElements(remapped.canvasElements);- setMockupMotionFragments(remapped.motionFragments);- }- return newClips;+ const commitClipLayout = useCallback((oldClips: VideoTrackClip[], newClips: VideoTrackClip[]) => {+ videoClipsRef.current = newClips;+ setVideoClips(newClips);++ const newDuration = calculateTotalDuration(newClips);+ setVideoDuration(newDuration);+ setTrimRange({ start: 0, end: newDuration });+ if (currentTimeRef.current > newDuration) setCurrentTime(newDuration);++ const remapped = remapOverlaysAfterClipChange({+ oldClips,+ newClips,+ zoomFragments: zoomFragmentsRef.current,+ zoomMovements,+ audioTracks,+ canvasElements,+ motionFragments: mockupMotionFragments,});+ setZoomFragments(remapped.zoomFragments);+ setZoomMovements(remapped.zoomMovements);+ setAudioTracks(remapped.audioTracks);+ setCanvasElements(remapped.canvasElements);+ setMockupMotionFragments(remapped.motionFragments);}, [zoomMovements, audioTracks, canvasElements, mockupMotionFragments, setZoomFragments, setZoomMovements, setAudioTracks, setCanvasElements, setMockupMotionFragments]);+ const handleUpdateVideoClip = useCallback((clipId: string, updates: Partial<VideoTrackClip>) => {+ const oldClips = videoClipsRef.current;+ const isTrim = updates.trimStart !== undefined || updates.trimEnd !== undefined;++ if (isTrim) {+ const newClips = rippleTrimClip(oldClips, clipId, {+ trimStart: updates.trimStart,+ trimEnd: updates.trimEnd,+ });+ commitClipLayout(oldClips, newClips);+ return;+ }++ let newClips = oldClips.map(c => (c.id === clipId ? { ...c, ...updates } : c));+ if (updates.startTime !== undefined) {+ newClips = resequenceClips([...newClips].sort((a, b) => a.startTime - b.startTime)).clips;+ commitClipLayout(oldClips, newClips);+ } else {+ videoClipsRef.current = newClips;+ setVideoClips(newClips);+ }+ }, [commitClipLayout]);++ const handleRestoreVideoClipTrim = useCallback((clipId: string | null, edge: TrimEdge = "both") => {+ const oldClips = videoClipsRef.current;+ const newClips = restoreClipTrim(oldClips, clipId, edge);+ if (newClips === oldClips) return;+ commitClipLayout(oldClips, newClips);+ }, [commitClipLayout]);+const handleDeleteVideoClip = useCallback((clipId: string) => {const deletedClip = videoClipsRef.current.find(c => c.id === clipId);setVideoClips(prev => {@@ -3126,6 +3141,7 @@ export default function Editor() {onUpdateVideoClip={handleUpdateVideoClip}onDeleteVideoClip={handleDeleteVideoClip}onReorderVideoClip={handleReorderVideoClip}+ onRestoreVideoClipTrim={handleRestoreVideoClipTrim}zoomFragments={zoomFragments}selectedZoomFragmentId={selectedZoomFragmentId}onSelectZoomFragment={handleSelectZoomFragment}diff --git a/app/components/ui/editor/Timeline.tsx b/app/components/ui/editor/Timeline.tsxindex df0c9e2..37f5839 100644--- a/app/components/ui/editor/Timeline.tsx+++ b/app/components/ui/editor/Timeline.tsx@@ -19,8 +19,9 @@ import { findValidFragmentPosition, findValidMovementPosition, getFragmentHoldBoimport { ZoomMovementTrackItem, MIN_MOVEMENT_TRACK_DURATION } from "./ZoomMovementTrackItem";import { collectSnapPoints, findSnap } from "@/lib/timeline-snapping";import { MAX_ZOOM, MIN_ZOOM, ZOOM_STEP } from "@/types/player-control.types";+import { getClipTrimInfo } from "@/types/video-track.types";+const TAIL_PAD = 96;-/** Renders editable media tracks with pointer-anchored wheel and keyboard zoom. */export function Timeline({videoDuration,currentTime,@@ -38,6 +39,7 @@ export function Timeline({onUpdateVideoClip,onDeleteVideoClip,onReorderVideoClip,+ onRestoreVideoClipTrim,zoomFragments = [],selectedZoomFragmentId,onSelectZoomFragment,@@ -229,16 +231,21 @@ export function Timeline({return (currentTime / scaledDuration) * contentWidth;}, [currentTime, scaledDuration, contentWidth]);+ const tailPad = useMemo(+ () => (videoClips.some(c => getClipTrimInfo(c).isTrimmed) ? TAIL_PAD : 0),+ [videoClips]+ );+useEffect(() => {const updateTrackWidth = () => {if (containerRef.current) {- setTrackWidth(containerRef.current.clientWidth - 12 - TIMELINE_LABEL_WIDTH - 5);+ setTrackWidth(containerRef.current.clientWidth - 12 - TIMELINE_LABEL_WIDTH - 5 - tailPad);}};updateTrackWidth();window.addEventListener("resize", updateTrackWidth);return () => window.removeEventListener("resize", updateTrackWidth);- }, []);+ }, [tailPad]);useEffect(() => {if (!isDragging && !isDraggingPlayhead) {@@ -649,8 +656,8 @@ export function Timeline({<divclassName="relative grid min-h-full"style={{- gridTemplateColumns: `${TIMELINE_LABEL_WIDTH}px ${timelineWidth > 0 ? `${timelineWidth}px` : '100%'}`,- width: timelineWidth > 0 ? timelineWidth + TIMELINE_LABEL_WIDTH : '100%',+ gridTemplateColumns: `${TIMELINE_LABEL_WIDTH}px ${timelineWidth > 0 ? `${timelineWidth + tailPad}px` : '100%'}`,+ width: timelineWidth > 0 ? timelineWidth + TIMELINE_LABEL_WIDTH + tailPad : '100%',minWidth: '100%',}}>@@ -750,6 +757,7 @@ export function Timeline({onUpdate={(updates) => onUpdateVideoClip?.(clip.id, updates)}onDelete={() => onDeleteVideoClip?.(clip.id)}onReorder={(draggedId, targetId, placeAfter) => onReorderVideoClip?.(draggedId, targetId, placeAfter)}+ onRestoreTrim={(edge) => onRestoreVideoClipTrim?.(clip.id, edge)}onDragStateChange={setIsDraggingVideoClip}zoomLevel={zoomLevel}activeClipLeftX={activeClipLeftX}diff --git a/app/components/ui/editor/VideoClipTrackItem.tsx b/app/components/ui/editor/VideoClipTrackItem.tsxindex c06bebf..bd19dd9 100644--- a/app/components/ui/editor/VideoClipTrackItem.tsx+++ b/app/components/ui/editor/VideoClipTrackItem.tsx@@ -1,13 +1,13 @@"use client";-import { useState, useRef, useCallback, useMemo, useEffect } from "react";+import { useState, useRef, useCallback, useEffect } from "react";import { motion, useMotionValue, useTransform } from "framer-motion";-import type { VideoTrackClip } from "@/types/video-track.types";+import type { VideoTrackClip, TrimEdge } from "@/types/video-track.types";+import { MIN_CLIP_DURATION, getClipTrimInfo } from "@/types/video-track.types";import { Icon } from "@iconify/react";import type { MotionValue } from "framer-motion";import { collectSnapPoints, findSnap } from "@/lib/timeline-snapping";--const MIN_CLIP_DURATION = 0.1;+import { useTranslations } from "next-intl";interface VideoClipTrackItemProps {clip: VideoTrackClip;@@ -21,6 +21,7 @@ interface VideoClipTrackItemProps {onDelete?: () => void;onDragStateChange?: (isDragging: boolean) => void;onReorder?: (draggedId: string, targetId: string, placeAfter: boolean) => void;+ onRestoreTrim?: (edge: TrimEdge) => void;zoomLevel: number;playheadX: MotionValue<number>;speed?: number;@@ -29,6 +30,19 @@ interface VideoClipTrackItemProps {autoScrollDeltaX?: MotionValue<number>;}+interface ResizeSession {+ x: number;+ width: number;+ trimStart: number;+ trimEnd: number;+ duration: number;+ startTime: number;+ pps: number;+ scrollComp: number;+ lastOffset: number;+ pending: { trimStart: number; trimEnd: number } | null;+}+export function VideoClipTrackItem({clip,isSelected,@@ -38,9 +52,9 @@ export function VideoClipTrackItem({currentTime = 0,onSelect,onUpdate,- onDelete,onDragStateChange,onReorder,+ onRestoreTrim,zoomLevel,playheadX,speed = 1,@@ -48,10 +62,12 @@ export function VideoClipTrackItem({activeClipRightX,autoScrollDeltaX}: VideoClipTrackItemProps) {+ const t = useTranslations("timeline");const [isDragging, setIsDragging] = useState(false);const [isResizing, setIsResizing] = useState<'start' | 'end' | null>(null);const [isHovered, setIsHovered] = useState(false);const containerRef = useRef<HTMLDivElement>(null);+ const resizeRef = useRef<ResizeSession | null>(null);const clipX = useMotionValue(0);const clipWidth = useMotionValue(0);@@ -89,30 +105,6 @@ export function VideoClipTrackItem({}}, [initialLeft, initialWidth, isDragging, isResizing, clipX, clipWidth]);- const boundaries = useMemo(() => {- const sorted = [...otherClips]- .filter(c => c.id !== clip.id)- .sort((a, b) => a.startTime - b.startTime);-- let minStart = 0;- let maxEnd = Infinity;-- for (const other of sorted) {- const otherEnd = other.startTime + (other.trimEnd - other.trimStart);- const clipEnd = clip.startTime + clipDuration;-- if (otherEnd <= clip.startTime) {- minStart = Math.max(minStart, otherEnd);- }- if (other.startTime >= clipEnd) {- maxEnd = Math.min(maxEnd, other.startTime);- break;- }- }-- return { minStart, maxEnd };- }, [otherClips, clip.id, clip.startTime, clipDuration]);-const applyDragDelta = useCallback((deltaX: number) => {if (contentWidth === 0 || totalDuration === 0) return;let newX = clipX.get() + deltaX;@@ -128,30 +120,6 @@ export function VideoClipTrackItem({applyDragDelta(info.delta.x);}, [applyDragDelta]);- const applyResizeStartDelta = useCallback((deltaX: number) => {- if (contentWidth === 0 || totalDuration === 0) return;- const currentX = clipX.get();- const currentWidth = clipWidth.get();- let newX = currentX + deltaX;- let newWidth = currentWidth - deltaX;- const minWidth = timeToPixels(MIN_CLIP_DURATION);- if (newWidth < minWidth) {- newWidth = minWidth;- newX = currentX + currentWidth - minWidth;- }- const minStartTimeBySource = clip.startTime - clip.trimStart;- const minXBySource = timeToPixels(Math.max(0, minStartTimeBySource));- const minX = Math.max(timeToPixels(boundaries.minStart), minXBySource);- if (newX < minX) {- newWidth = newWidth - (minX - newX);- newX = minX;- }- clipX.set(newX);- clipWidth.set(newWidth);- activeClipLeftX?.set(newX);- activeClipRightX?.set(newX + newWidth);- }, [contentWidth, totalDuration, clipX, clipWidth, boundaries, timeToPixels, clip.startTime, clip.trimStart, activeClipLeftX, activeClipRightX]);-const handleDragStart = useCallback(() => {setIsDragging(true);onDragStateChange?.(true);@@ -162,8 +130,6 @@ export function VideoClipTrackItem({setIsDragging(false);onDragStateChange?.(false);- // Detect if the clip was dropped onto another clip (>=50% overlap).- // If so, trigger a reorder instead of a free-drag position update.const draggedCenterPx = clipX.get() + clipWidth.get() / 2;const target = otherClips.find(other => {const otherStartPx = timeToPixels(other.startTime);@@ -173,13 +139,10 @@ export function VideoClipTrackItem({});if (target && onReorder) {- // Determine whether to place before or after the target based on- // the dragged clip's center relative to the target's center.const targetCenterPx = timeToPixels(target.startTime) + timeToPixels(target.trimEnd - target.trimStart) / 2;const placeAfter = draggedCenterPx > targetCenterPx;onReorder(clip.id, target.id, placeAfter);} else {- // Apply magnetic snapping on drop (not during drag) for smooth control.let finalX = clipX.get();const snapThresholdPx = 8;const finalStartTime = pixelsToTime(finalX);@@ -188,10 +151,7 @@ export function VideoClipTrackItem({start: c.startTime,end: c.startTime + (c.trimEnd - c.trimStart),}));- const snapPoints = collectSnapPoints({- clipEdges,- playhead: currentTime,- });+ const snapPoints = collectSnapPoints({ clipEdges, playhead: currentTime });const snapStart = findSnap(finalStartTime, snapPoints, timeToPixels, snapThresholdPx);if (snapStart.offsetPx !== 0) {finalX = timeToPixels(snapStart.time);@@ -201,45 +161,75 @@ export function VideoClipTrackItem({finalX = timeToPixels(snapEnd.time - clipDuration);}}- const newStartTime = pixelsToTime(finalX);- onUpdate({- startTime: Math.max(0, newStartTime),- });+ onUpdate({ startTime: Math.max(0, pixelsToTime(finalX)) });}}, [clipX, clipWidth, pixelsToTime, onUpdate, onDragStateChange, otherClips, timeToPixels, onReorder, clip.id, clipDuration, currentTime]);- const handleResizeStartDrag = useCallback((_e: MouseEvent | TouchEvent | PointerEvent, info: { delta: { x: number } }) => {- applyResizeStartDelta(info.delta.x);- }, [applyResizeStartDelta]);+ const applyResize = useCallback((handle: 'start' | 'end') => {+ const s = resizeRef.current;+ if (!s || s.pps <= 0) return;- const applyResizeEndDelta = useCallback((deltaX: number) => {- if (contentWidth === 0 || totalDuration === 0) return;- const currentX = clipX.get();- const currentWidth = clipWidth.get();- let newWidth = currentWidth + deltaX;- const minWidth = timeToPixels(MIN_CLIP_DURATION);- newWidth = Math.max(minWidth, newWidth);- if (Number.isFinite(boundaries.maxEnd)) {- const maxWidthByBoundary = timeToPixels(boundaries.maxEnd) - currentX;- newWidth = Math.min(newWidth, maxWidthByBoundary);+ const dtRaw = (s.lastOffset + s.scrollComp) / s.pps;+ const len = s.trimEnd - s.trimStart;++ if (handle === 'start') {+ const dt = Math.max(-s.trimStart, Math.min(len - MIN_CLIP_DURATION, dtRaw));+ clipX.set(Math.max(0, s.x + dt * s.pps));+ clipWidth.set(s.width - dt * s.pps);+ s.pending = { trimStart: s.trimStart + dt, trimEnd: s.trimEnd };+ } else {+ const minDt = MIN_CLIP_DURATION - len;+ const maxDt = s.duration - s.trimEnd; // hasta el final del archivo fuente+ let dt = Math.max(minDt, Math.min(maxDt, dtRaw));++ const edgeTime = s.startTime + len + dt;+ const snap = findSnap(edgeTime, collectSnapPoints({ playhead: currentTime, zero: false }), timeToPixels, 8);+ if (snap.offsetPx !== 0) {+ dt = Math.max(minDt, Math.min(maxDt, snap.time - s.startTime - len));+ }++ clipWidth.set(s.width + dt * s.pps);+ s.pending = { trimStart: s.trimStart, trimEnd: s.trimEnd + dt };}- const maxAvailableDuration = clip.duration - clip.trimStart;- const maxWidthBySource = timeToPixels(maxAvailableDuration);- newWidth = Math.min(newWidth, maxWidthBySource);- clipWidth.set(newWidth);- activeClipLeftX?.set(currentX);- activeClipRightX?.set(currentX + newWidth);- }, [contentWidth, totalDuration, clipWidth, clipX, boundaries, timeToPixels, clip.duration, clip.trimStart, activeClipLeftX, activeClipRightX]);-- const handleResizeEndDrag = useCallback((_e: MouseEvent | TouchEvent | PointerEvent, info: { delta: { x: number } }) => {- applyResizeEndDelta(info.delta.x);- }, [applyResizeEndDelta]);-- const handleResizeStart = useCallback((handle: 'start' | 'end') => {++ activeClipLeftX?.set(clipX.get());+ activeClipRightX?.set(clipX.get() + clipWidth.get());+ }, [clipX, clipWidth, currentTime, timeToPixels, activeClipLeftX, activeClipRightX]);++ const beginResize = useCallback((handle: 'start' | 'end') => {+ resizeRef.current = {+ x: clipX.get(),+ width: clipWidth.get(),+ trimStart: clip.trimStart,+ trimEnd: clip.trimEnd,+ duration: clip.duration,+ startTime: clip.startTime,+ pps: totalDuration > 0 ? contentWidth / totalDuration : 0,+ scrollComp: 0,+ lastOffset: 0,+ pending: null,+ };setIsResizing(handle);onDragStateChange?.(true);onSelect();- }, [onDragStateChange, onSelect]);+ }, [clip.trimStart, clip.trimEnd, clip.duration, clip.startTime, clipX, clipWidth, contentWidth, totalDuration, onDragStateChange, onSelect]);++ const dragResize = useCallback((handle: 'start' | 'end', info: { offset: { x: number } }) => {+ const s = resizeRef.current;+ if (!s) return;+ s.lastOffset = info.offset.x;+ applyResize(handle);+ }, [applyResize]);++ const endResize = useCallback(() => {+ const s = resizeRef.current;+ resizeRef.current = null;+ setIsResizing(null);+ onDragStateChange?.(false);+ const p = s?.pending;+ if (!p) return;+ onUpdate({ trimStart: p.trimStart, trimEnd: p.trimEnd });+ }, [onDragStateChange, onUpdate]);const lastAutoScrollRef = useRef(0);useEffect(() => {@@ -249,45 +239,26 @@ export function VideoClipTrackItem({const delta = latest - lastAutoScrollRef.current;lastAutoScrollRef.current = latest;if (delta === 0) return;- if (isDragging) applyDragDelta(delta);- else if (isResizing === 'start') applyResizeStartDelta(delta);- else if (isResizing === 'end') applyResizeEndDelta(delta);- });- }, [autoScrollDeltaX, isDragging, isResizing, applyDragDelta, applyResizeStartDelta, applyResizeEndDelta]);-- const handleResizeEnd = useCallback(() => {- const handle = isResizing;- setIsResizing(null);- onDragStateChange?.(false);-- let finalX = clipX.get();- let finalWidth = clipWidth.get();- const otherEdges = otherClips.map(c => ({ start: c.startTime, end: c.startTime + (c.trimEnd - c.trimStart) }));- const snapPoints = collectSnapPoints({ clipEdges: otherEdges, playhead: currentTime });-- if (handle === 'end') {- const snap = findSnap(pixelsToTime(finalX + finalWidth), snapPoints, timeToPixels, 8);- if (snap.offsetPx !== 0) finalWidth = timeToPixels(snap.time) - finalX;- } else if (handle === 'start') {- const snap = findSnap(pixelsToTime(finalX), snapPoints, timeToPixels, 8);- if (snap.offsetPx !== 0) {- const delta = timeToPixels(snap.time) - finalX;- finalX += delta;- finalWidth -= delta;+ if (isDragging) {+ applyDragDelta(delta);+ } else if (isResizing && resizeRef.current) {+ resizeRef.current.scrollComp += delta;+ applyResize(isResizing);}- }-- const newStartTime = Math.max(0, pixelsToTime(finalX));- const newDuration = pixelsToTime(finalWidth);- const trimDelta = newStartTime - clip.startTime;- const newTrimStart = Math.max(0, clip.trimStart + trimDelta);- const newTrimEnd = Math.min(clip.duration, newTrimStart + newDuration);- const correctedStartTime = clip.startTime + (newTrimStart - clip.trimStart);-- onUpdate({ startTime: correctedStartTime, trimStart: newTrimStart, trimEnd: newTrimEnd });- }, [isResizing, clipX, clipWidth, pixelsToTime, timeToPixels, otherClips, currentTime, clip, onUpdate, onDragStateChange]);+ });+ }, [autoScrollDeltaX, isDragging, isResizing, applyDragDelta, applyResize]);const isInteracting = isDragging || isResizing !== null;+ const { head, tail, isTrimmed } = getClipTrimInfo(clip);+ const showRestore = isTrimmed && (isSelected || isHovered) && !isInteracting && initialWidth > 120;++ const HATCH = 'repeating-linear-gradient(135deg, rgba(74,222,128,0.6) 0 2px, transparent 2px 5px)';+ const startTitle = head > 0.01+ ? t("trimmedStart", { seconds: head.toFixed(1) })+ : t("trimStartHint");+ const endTitle = tail > 0.01+ ? t("trimmedEnd", { seconds: tail.toFixed(1) })+ : t("trimEndHint");const formatDuration = (seconds: number): string => {const mins = Math.floor(seconds / 60);@@ -348,6 +319,13 @@ export function VideoClipTrackItem({}}/>+ {head > 0.01 && (+ <div className="absolute left-0 top-0 bottom-0 w-2 pointer-events-none z-10" style={{ backgroundImage: HATCH }} />+ )}+ {tail > 0.01 && (+ <div className="absolute right-0 top-0 bottom-0 w-2 pointer-events-none z-10" style={{ backgroundImage: HATCH }} />+ )}+<div className="absolute inset-0 flex items-center justify-center pointer-events-none z-10"><span className={`flex items-center gap-2 text-[11px] font-medium drop-shadow-sm transition-colors duration-200 ${isHovered ? 'text-emerald-700 dark:text-emerald-300' : 'text-emerald-700 dark:text-emerald-400'}`}>@@ -360,29 +338,54 @@ export function VideoClipTrackItem({</span></div>+ {showRestore && (+ <button+ type="button"+ className="absolute right-4 top-1/2 -translate-y-1/2 z-30 flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] bg-black/50 text-emerald-100 hover:bg-black/70 transition-colors"+ title={t("restoreTitle")}+ onClick={(e) => {+ e.stopPropagation();+ onRestoreTrim?.('both');+ }}+ >+ <Icon icon="solar:restart-bold" width="11" />+ {t("restore")}+ </button>+ )}+<motion.div+ title={startTitle}className="absolute left-0 top-0 bottom-0 w-3 cursor-ew-resize z-20 group/trim flex items-center justify-center"drag="x"dragConstraints={{ left: 0, right: 0 }}dragElastic={0}dragMomentum={false}- onDrag={handleResizeStartDrag}- onDragStart={() => handleResizeStart('start')}- onDragEnd={handleResizeEnd}+ onDrag={(_e, info) => dragResize('start', info)}+ onDragStart={() => beginResize('start')}+ onDragEnd={endResize}+ onDoubleClick={(e) => {+ e.stopPropagation();+ if (head > 0.01) onRestoreTrim?.('start');+ }}><div className={`w-1.5 h-8 rounded-full transition-all ${isResizing === 'start' ? 'bg-[#4ade80] scale-110' : 'bg-[#34A853] group-hover/trim:bg-[#4ade80]'}`} /></motion.div><motion.div+ title={endTitle}className="absolute right-0 top-0 bottom-0 w-3 cursor-ew-resize z-20 group/trim flex items-center justify-end"drag="x"dragConstraints={{ left: 0, right: 0 }}dragElastic={0}dragMomentum={false}- onDrag={handleResizeEndDrag}- onDragStart={() => handleResizeStart('end')}- onDragEnd={handleResizeEnd}+ onDrag={(_e, info) => dragResize('end', info)}+ onDragStart={() => beginResize('end')}+ onDragEnd={endResize}+ onDoubleClick={(e) => {+ e.stopPropagation();+ if (tail > 0.01) onRestoreTrim?.('end');+ }}><div className={`w-1.5 h-8 rounded-full transition-all ${isResizing === 'end' ? 'bg-[#4ade80] scale-110' : 'bg-[#34A853] group-hover/trim:bg-[#4ade80]'}`} />diff --git a/lib/timeline-overlay-remap.ts b/lib/timeline-overlay-remap.tsindex f3c47b2..39bb59b 100644--- a/lib/timeline-overlay-remap.ts+++ b/lib/timeline-overlay-remap.ts@@ -4,22 +4,12 @@ import type { AudioTrack } from "@/types/audio.types";import type { CanvasElement } from "@/types/canvas-elements.types";import type { MockupMotionFragment } from "@/lib/mockup-motion";-/**- * Keeps timeline overlays (zoom fragments, audio tracks, canvas elements,- * motion fragments) in sync when the video clip layout changes (clip deleted,- * trimmed, or reordered).- *- * Overlays are stored in absolute timeline time. When clips move, shrink, or- * disappear, each overlay interval is mapped through the clip that contains- * it: shifted by that clip's new offset, clamped to its new bounds, and- * dropped entirely when its containing clip was removed.- */-interface ClipRange {oldStart: number;oldEnd: number;newStart: number;newEnd: number;+ trimShift: number;}function buildClipRanges(oldClips: VideoTrackClip[], newClips: VideoTrackClip[]): ClipRange[] {@@ -36,6 +26,7 @@ function buildClipRanges(oldClips: VideoTrackClip[], newClips: VideoTrackClip[])oldEnd: oldClip.startTime + oldDuration,newStart: newClip.startTime,newEnd: newClip.startTime + newDuration,+ trimShift: newClip.trimStart - oldClip.trimStart,});}@@ -65,7 +56,7 @@ function mapInterval(return { start, end };}- const offset = containing.newStart - containing.oldStart;+ const offset = containing.newStart - containing.oldStart - containing.trimShift;let newStart = start + offset;let newEnd = end + offset;@@ -105,7 +96,7 @@ export function remapOverlaysAfterClipChange(input: RemapOverlaysInput): RemapOvconst ranges = buildClipRanges(oldClips, newClips);// Skip all work when nothing relevant changed (pure selection updates etc.)- const layoutChanged = ranges.some(r => r.newStart !== r.oldStart || r.newEnd !== r.oldEnd)+ const layoutChanged = ranges.some(r => r.newStart !== r.oldStart || r.newEnd !== r.oldEnd || r.trimShift !== 0)|| newClips.length !== oldClips.length;if (!layoutChanged) {return {diff --git a/lib/wallpaper.catalog.ts b/lib/wallpaper.catalog.tsindex a553ef1..80f1fa5 100644--- a/lib/wallpaper.catalog.ts+++ b/lib/wallpaper.catalog.ts@@ -35,7 +35,7 @@ const CATEGORY_CONFIGS: CategoryConfig[] = [];let globalIndex = 0;-const CACHE_VERSION = '20260911';+const CACHE_VERSION = '20260925';export const WALLPAPER_CATEGORIES: WallpaperCategory[] = CATEGORY_CONFIGS.map(config => {const items: WallpaperItem[] = [];diff --git a/messages/en.json b/messages/en.jsonindex 5f144fc..861eb00 100644--- a/messages/en.json+++ b/messages/en.json@@ -1191,7 +1191,13 @@"freeRatio": "Free"},"timeline": {- "noSpace": "No space"+ "noSpace": "No space",+ "trimStartHint": "Drag to trim the start",+ "trimEndHint": "Drag to trim the end",+ "trimmedStart": "Trimmed {seconds}s from the start · double-click to restore",+ "trimmedEnd": "Trimmed {seconds}s from the end · double-click to restore",+ "restore": "Restore",+ "restoreTitle": "Restore the clip's original duration"},"audioMenu": {"title": "Audio",diff --git a/messages/es.json b/messages/es.jsonindex a699daa..422a921 100644--- a/messages/es.json+++ b/messages/es.json@@ -1169,7 +1169,13 @@"freeRatio": "Libre"},"timeline": {- "noSpace": "Sin espacio"+ "noSpace": "Sin espacio",+ "trimStartHint": "Arrastra para recortar el inicio",+ "trimEndHint": "Arrastra para recortar el final",+ "trimmedStart": "Recortado {seconds}s al inicio · doble clic para restaurar",+ "trimmedEnd": "Recortado {seconds}s al final · doble clic para restaurar",+ "restore": "Restaurar",+ "restoreTitle": "Restaurar la duración original del clip"},"audioMenu": {"title": "Audio",diff --git a/messages/ko.json b/messages/ko.jsonindex 064eb7f..092c9bd 100644--- a/messages/ko.json+++ b/messages/ko.json@@ -1191,7 +1191,13 @@"freeRatio": "자유"},"timeline": {- "noSpace": "공간 없음"+ "noSpace": "공간 없음",+ "trimStartHint": "드래그하여 시작 부분 자르기",+ "trimEndHint": "드래그하여 끝 부분 자르기",+ "trimmedStart": "시작 부분 {seconds}초 잘림 · 더블 클릭하여 복원",+ "trimmedEnd": "끝 부분 {seconds}초 잘림 · 더블 클릭하여 복원",+ "restore": "복원",+ "restoreTitle": "클립의 원래 길이로 복원"},"audioMenu": {"title": "오디오",diff --git a/messages/ru.json b/messages/ru.jsonindex 53a6774..f7ff698 100644--- a/messages/ru.json+++ b/messages/ru.json@@ -1158,7 +1158,13 @@"freeRatio": "Свободно"},"timeline": {- "noSpace": "Нет места"+ "noSpace": "Нет места",+ "trimStartHint": "Перетащите, чтобы обрезать начало",+ "trimEndHint": "Перетащите, чтобы обрезать конец",+ "trimmedStart": "Обрезано {seconds} с в начале · дважды щёлкните, чтобы восстановить",+ "trimmedEnd": "Обрезано {seconds} с в конце · дважды щёлкните, чтобы восстановить",+ "restore": "Восстановить",+ "restoreTitle": "Восстановить исходную длительность клипа"},"audioMenu": {"title": "Аудио",diff --git a/types/timeline.types.ts b/types/timeline.types.tsindex 5b1ef92..8b5e8f0 100644--- a/types/timeline.types.ts+++ b/types/timeline.types.ts@@ -1,6 +1,6 @@import { ZoomFragment, ZoomMovement } from "./zoom.types";import type { AudioTrack, UploadedAudio } from "./audio.types";-import type { VideoTrackClip } from "./video-track.types";+import type { TrimEdge, VideoTrackClip } from "./video-track.types";import { MockupMotionFragment } from "@/lib/mockup-motion";import { CanvasElement } from "./canvas-elements.types";@@ -61,6 +61,7 @@ export interface TimelineProps {onUpdateZoomMovement?: (id: string, updates: Partial<ZoomMovement>) => void;onDeleteZoomMovement?: (id: string) => void;onAddZoomMovementAtRange?: (startTime: number, endTime: number) => void;+ onRestoreVideoClipTrim?: (clipId: string | null, edge?: TrimEdge) => void;}export const DEFAULT_ZOOM_FRAGMENT_DURATION = 3;diff --git a/types/video-track.types.ts b/types/video-track.types.tsindex b4f2125..94d0347 100644--- a/types/video-track.types.ts+++ b/types/video-track.types.ts@@ -178,4 +178,47 @@ export async function probeMediaDimensions(url: string): Promise<{ width: number: null);}, 2000);});+}++export type TrimEdge = "start" | "end" | "both";++export function getClipTrimInfo(clip: VideoTrackClip) {+ const head = Math.max(0, clip.trimStart);+ const tail = Math.max(0, clip.duration - clip.trimEnd);+ return { head, tail, isTrimmed: head > 0.01 || tail > 0.01 };+}++export function rippleTrimClip(+ clips: VideoTrackClip[],+ clipId: string,+ patch: { trimStart?: number; trimEnd?: number }+): VideoTrackClip[] {+ const ordered = [...clips].sort((a, b) => a.startTime - b.startTime);+ const updated = ordered.map(c => {+ if (c.id !== clipId) return c;+ const rawStart = patch.trimStart ?? c.trimStart;+ const rawEnd = patch.trimEnd ?? c.trimEnd;+ const trimEnd = Math.min(c.duration, Math.max(rawEnd, rawStart + MIN_CLIP_DURATION));+ const trimStart = Math.max(0, Math.min(rawStart, trimEnd - MIN_CLIP_DURATION));+ return { ...c, trimStart, trimEnd };+ });+ return resequenceClips(updated).clips;+}++export function restoreClipTrim(+ clips: VideoTrackClip[],+ clipId: string | null,+ edge: TrimEdge = "both"+): VideoTrackClip[] {+ let changed = false;+ const ordered = [...clips].sort((a, b) => a.startTime - b.startTime);+ const updated = ordered.map(c => {+ if (clipId !== null && c.id !== clipId) return c;+ const trimStart = edge === "end" ? c.trimStart : 0;+ const trimEnd = edge === "start" ? c.trimEnd : c.duration;+ if (trimStart === c.trimStart && trimEnd === c.trimEnd) return c;+ changed = true;+ return { ...c, trimStart, trimEnd };+ });+ return changed ? resequenceClips(updated).clips : clips;}\ No newline at end of file