Skip to content

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

Refactor video export and upload processes

CristianOlivera1f6ed498a8700
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsx
index b58c5a1..33c4626 100644
--- a/app/[locale]/(editor)/editor/page.tsx
+++ b/app/[locale]/(editor)/editor/page.tsx
@@ -89,6 +89,9 @@ export default function Editor() {
clearHistory,
} = useUndoRedo<EditorState>(createInitialEditorState());
+ const [undoRedoVersion, setUndoRedoVersion] = useState(-1);
+ const [wallpaperShowAll, setWallpaperShowAll] = useState(false);
+
const handleUndo = useCallback(() => {
undo();
setUndoRedoVersion(v => v + 1);
@@ -99,9 +102,6 @@ export default function Editor() {
setUndoRedoVersion(v => v + 1);
}, [redo]);
- const [undoRedoVersion, setUndoRedoVersion] = useState(-1);
- const [wallpaperShowAll, setWallpaperShowAll] = useState(false);
-
// Image state for photo mode
const [imageUrl, setImageUrl] = useState<string | null>(null);
const imageRef = useRef<HTMLImageElement>(null);
@@ -189,6 +189,46 @@ export default function Editor() {
const [isCropperOpen, setIsCropperOpen] = useState(false);
const [cropArea, setCropArea] = useState<CropArea | undefined>(undefined);
+ const [selectedVideoClipId, setSelectedVideoClipId] = useState<string | null>(null);
+
+ // Multi-video playback: store video blobs and URLs indexed by libraryVideoId
+ const videoBlobsRef = useRef<Map<string, Blob>>(new Map());
+ const videoUrlsRef = useRef<Map<string, string>>(new Map());
+ const [videoUrlsMap, setVideoUrlsMap] = useState<Map<string, string>>(new Map());
+ const setClipUrl = useCallback((id: string, url: string) => {
+ videoUrlsRef.current.set(id, url);
+ setVideoUrlsMap(prev => {
+ const next = new Map(prev);
+ next.set(id, url);
+ return next;
+ });
+ }, []);
+ const deleteClipUrl = useCallback((id: string) => {
+ const url = videoUrlsRef.current.get(id);
+ if (url) URL.revokeObjectURL(url);
+ videoUrlsRef.current.delete(id);
+ setVideoUrlsMap(prev => {
+ if (!prev.has(id)) return prev;
+ const next = new Map(prev);
+ next.delete(id);
+ return next;
+ });
+ }, []);
+ const clearClipUrls = useCallback(() => {
+ for (const url of videoUrlsRef.current.values()) {
+ URL.revokeObjectURL(url);
+ }
+ videoUrlsRef.current.clear();
+ setVideoUrlsMap(new Map());
+ }, []);
+ const activeClipIdRef = useRef<string | null>(null);
+ const activeClipDataRef = useRef<VideoTrackClip | null>(null);
+ const clipAudioStateRef = useRef<Map<string, boolean>>(new Map());
+ const muteOriginalAudioRef = useRef<boolean>(false);
+
+ const lastTimeUpdateRef = useRef(0);
+ const REACT_TIME_UPDATE_INTERVAL_MS = 33;
+
// Computed: which dimensions to use for the canvas
const customAspectRatio = useMemo(() => {
return aspectRatio === "auto"
@@ -344,44 +384,45 @@ export default function Editor() {
if (!isPhotoMode || !currentProject) return;
if (lastRestoredProjectIdRef.current === currentProject.id) return;
- isRestoringProjectRef.current = true;
- lastRestoredProjectIdRef.current = currentProject.id;
-
const imageDataUrl = currentProject.imageDataUrl;
if (!imageDataUrl) {
console.error("Project missing imageDataUrl");
- isRestoringProjectRef.current = false;
return;
}
- setImageUrl(imageDataUrl);
- setBackgroundTab(currentProject.backgroundTab);
- setSelectedWallpaper(currentProject.selectedWallpaper);
- setBackgroundBlur(currentProject.backgroundBlur);
- setSelectedImageUrl(currentProject.selectedImageUrl);
- setBackgroundColorConfig(currentProject.backgroundColorConfig);
- setPadding(currentProject.padding);
- setRoundedCorners(currentProject.roundedCorners);
- setShadows(currentProject.shadows);
- setAspectRatio(currentProject.aspectRatio);
- setCustomDimensions(currentProject.customDimensions);
- setCropArea(currentProject.cropArea);
- setMockupId(currentProject.mockupId);
- setMockupConfig(currentProject.mockupConfig);
- setCanvasElements(currentProject.canvasElements);
- setVideoTransform(currentProject.imageTransform);
- setImageTransform(currentProject.imagePreview3D);
- setApply3DToBackground(currentProject.apply3DToBackground);
- setImageMaskConfig(currentProject.imageMaskConfig);
- setImageZoomScale(currentProject.imageZoomScale ?? 1);
- setImageDimensions({
- width: currentProject.imageWidth,
- height: currentProject.imageHeight,
- });
+ isRestoringProjectRef.current = true;
+ lastRestoredProjectIdRef.current = currentProject.id;
- setTimeout(() => {
- isRestoringProjectRef.current = false;
- }, 500);
+ queueMicrotask(() => {
+ setImageUrl(imageDataUrl);
+ setBackgroundTab(currentProject.backgroundTab);
+ setSelectedWallpaper(currentProject.selectedWallpaper);
+ setBackgroundBlur(currentProject.backgroundBlur);
+ setSelectedImageUrl(currentProject.selectedImageUrl);
+ setBackgroundColorConfig(currentProject.backgroundColorConfig);
+ setPadding(currentProject.padding);
+ setRoundedCorners(currentProject.roundedCorners);
+ setShadows(currentProject.shadows);
+ setAspectRatio(currentProject.aspectRatio);
+ setCustomDimensions(currentProject.customDimensions);
+ setCropArea(currentProject.cropArea);
+ setMockupId(currentProject.mockupId);
+ setMockupConfig(currentProject.mockupConfig);
+ setCanvasElements(currentProject.canvasElements);
+ setVideoTransform(currentProject.imageTransform);
+ setImageTransform(currentProject.imagePreview3D);
+ setApply3DToBackground(currentProject.apply3DToBackground);
+ setImageMaskConfig(currentProject.imageMaskConfig);
+ setImageZoomScale(currentProject.imageZoomScale ?? 1);
+ setImageDimensions({
+ width: currentProject.imageWidth,
+ height: currentProject.imageHeight,
+ });
+
+ setTimeout(() => {
+ isRestoringProjectRef.current = false;
+ }, 500);
+ });
}, [currentProject, isPhotoMode]);
// Image project handlers
@@ -741,18 +782,6 @@ export default function Editor() {
useEffect(() => {
videoClipsRef.current = videoClips;
}, [videoClips]);
- const [selectedVideoClipId, setSelectedVideoClipId] = useState<string | null>(null);
-
- // Multi-video playback: store video blobs and URLs indexed by libraryVideoId
- const videoBlobsRef = useRef<Map<string, Blob>>(new Map());
- const videoUrlsRef = useRef<Map<string, string>>(new Map());
- const activeClipIdRef = useRef<string | null>(null);
- const activeClipDataRef = useRef<VideoTrackClip | null>(null);
- const clipAudioStateRef = useRef<Map<string, boolean>>(new Map());
- const muteOriginalAudioRef = useRef<boolean>(false);
-
- const lastTimeUpdateRef = useRef(0);
- const REACT_TIME_UPDATE_INTERVAL_MS = 33;
const setCurrentTimeThrottled = useCallback((time: number) => {
const now = performance.now();
@@ -1186,31 +1215,18 @@ export default function Editor() {
}
}, []);
- const [thumbnailClipId, setThumbnailClipId] = useState<string | null>(null);
-
const thumbnailsCacheRef = useRef<Map<string, VideoThumbnail[]>>(new Map());
-
const currentDisplayTime = isDraggingPlayhead ? scrubTime : currentTime;
- useEffect(() => {
- if (videoClips.length <= 1) {
- setThumbnailClipId(null);
- return;
- }
+ const thumbnailClipId = useMemo(() => {
+ if (videoClips.length <= 1) return null;
const clipAtTime = getClipAtTime(videoClips, currentDisplayTime);
- if (clipAtTime) {
- setThumbnailClipId(prev => {
- if (prev !== clipAtTime.libraryVideoId) {
- return clipAtTime.libraryVideoId;
- }
- return prev;
- });
- }
- }, [currentDisplayTime, videoClips]);
+ return clipAtTime?.libraryVideoId ?? null;
+ }, [videoClips, currentDisplayTime]);
const thumbnailUrl = useMemo(() => {
if (videoClips.length <= 1 || !thumbnailClipId) return videoUrl;
- return videoUrlsRef.current.get(thumbnailClipId) || videoUrl;
- }, [videoUrl, videoClips.length, thumbnailClipId]);
+ return videoUrlsMap.get(thumbnailClipId) || videoUrl;
+ }, [videoUrl, videoClips.length, thumbnailClipId, videoUrlsMap]);
const thumbnailVideoId = useMemo(() => {
if (videoClips.length <= 1 || !thumbnailClipId) return videoId;
@@ -1282,6 +1298,7 @@ export default function Editor() {
return null;
}, [getRawThumbnailForTime, thumbnailVideoId, findNearestThumbnail]);
+
// Find which clip is active at a given timeline time - using standardized function
const findActiveClipAtTime = useCallback((timelineTime: number): VideoTrackClip | null => {
const clips = videoClipsRef.current;
@@ -1301,14 +1318,12 @@ export default function Editor() {
const currentUrls = videoUrlsRef.current;
const neededIds = new Set(videoClips.map(c => c.libraryVideoId));
- for (const [id, url] of currentUrls.entries()) {
+ for (const [id] of currentUrls.entries()) {
if (!neededIds.has(id)) {
- URL.revokeObjectURL(url);
- currentUrls.delete(id);
+ deleteClipUrl(id);
currentBlobs.delete(id);
}
}
-
for (const clip of videoClips) {
if (!currentBlobs.has(clip.libraryVideoId)) {
try {
@@ -1316,7 +1331,7 @@ export default function Editor() {
if (libraryVideo) {
currentBlobs.set(clip.libraryVideoId, libraryVideo.blob);
const url = URL.createObjectURL(libraryVideo.blob);
- currentUrls.set(clip.libraryVideoId, url);
+ setClipUrl(clip.libraryVideoId, url);
}
} catch (e) {
console.warn("Failed to load video blob for clip:", clip.id, e);
@@ -1328,7 +1343,7 @@ export default function Editor() {
if (videoClips.length > 0) {
loadClipBlobs();
}
- }, [videoClips]);
+ }, [videoClips, setClipUrl, deleteClipUrl]);
const { exportVideo, cancelExport, exportProgress } = useVideoExport(videoRef, canvasRef);
const { uploadVideo, loadUploadedVideo, isUploading } = useVideoUpload();
@@ -1478,9 +1493,7 @@ export default function Editor() {
}
// First video - add to track
- for (const [, url] of videoUrlsRef.current.entries()) {
- URL.revokeObjectURL(url);
- }
+ clearClipUrls(); videoBlobsRef.current.clear();
videoBlobsRef.current.clear();
videoUrlsRef.current.clear();
activeClipIdRef.current = null;
@@ -1535,7 +1548,7 @@ export default function Editor() {
setIsPlaying(false);
setTimeout(() => clearHistory(), 200);
}
- }, [uploadVideo, clearHistory, showNewVideosBadge]);
+ }, [uploadVideo, clearHistory, showNewVideosBadge, clearClipUrls]);
const handleVideoUploadToLibrary = useCallback(async (file: File) => {
try {
@@ -1563,7 +1576,7 @@ export default function Editor() {
if (videoRef.current) {
videoRef.current.playbackRate = speed;
}
- }, []);
+ }, [setGlobalSpeed]);
// Handler to add video from library to the track (concatenate)
const handleAddVideoToTrack = useCallback(async (videoId: string, blob: Blob, duration: number) => {
@@ -1572,11 +1585,7 @@ export default function Editor() {
clipAudioStateRef.current.set(videoId, libraryVideo.hasAudio !== false);
- if (!videoBlobsRef.current.has(videoId)) {
- videoBlobsRef.current.set(videoId, blob);
- const blobUrl = URL.createObjectURL(blob);
- videoUrlsRef.current.set(videoId, blobUrl);
- }
+ if (!videoBlobsRef.current.has(videoId)) { videoBlobsRef.current.set(videoId, blob); const blobUrl = URL.createObjectURL(blob); setClipUrl(videoId, blobUrl); }
const { width: clipWidth, height: clipHeight } = await new Promise<{ width: number; height: number }>((resolve) => {
const probe = document.createElement('video');
@@ -1639,7 +1648,7 @@ export default function Editor() {
return updatedClips;
});
- }, [clearHistory, showNewVideosBadge]);
+ }, [clearHistory, showNewVideosBadge, setClipUrl]);
const activeClipForDims = useMemo(
() => (videoClips.length > 0 ? getClipAtTime(videoClips, currentTime) : null),
@@ -1653,8 +1662,8 @@ export default function Editor() {
const activeClipUrl = useMemo(() => {
if (!activeClipForDims) return videoUrl;
- return videoUrlsRef.current.get(activeClipForDims.libraryVideoId) ?? videoUrl;
- }, [activeClipForDims, videoUrl]);
+ return videoUrlsMap.get(activeClipForDims.libraryVideoId) ?? videoUrl;
+ }, [activeClipForDims, videoUrl, videoUrlsMap]);
// Handlers for video clip management
const handleSelectVideoClip = useCallback((clipId: string | null) => {
@@ -1751,7 +1760,10 @@ export default function Editor() {
setActiveTool("video");
}, [currentTime]);
- const activeClipForSplit = getClipAtTime(videoClipsRef.current, currentTime);
+ const activeClipForSplit = useMemo(
+ () => getClipAtTime(videoClips, currentTime),
+ [videoClips, currentTime]
+ );
const canSplitClip = !!activeClipForSplit && splitClipAtTime(activeClipForSplit, currentTime) !== null;
// Handler to remove video from track when deleted from library (cascade delete)
@@ -1797,15 +1809,9 @@ export default function Editor() {
return newClips;
});
// Clean up blob/URL refs
- if (videoBlobsRef.current.has(libraryVideoId)) {
- videoBlobsRef.current.delete(libraryVideoId);
- }
- if (videoUrlsRef.current.has(libraryVideoId)) {
- const url = videoUrlsRef.current.get(libraryVideoId);
- if (url) URL.revokeObjectURL(url);
- videoUrlsRef.current.delete(libraryVideoId);
- }
- }, []);
+ videoBlobsRef.current.delete(libraryVideoId);
+ deleteClipUrl(libraryVideoId);
+ }, [deleteClipUrl]);
// Handler for per-clip audio toggle from VideosMenu
const handleVideoAudioToggle = useCallback((videoId: string, hasAudio: boolean) => {
@@ -1957,7 +1963,7 @@ export default function Editor() {
}
videoBlobsRef.current.set(libraryVideo.id, videoBlob);
- videoUrlsRef.current.set(libraryVideo.id, videoToLoad.url);
+ setClipUrl(libraryVideo.id, videoToLoad.url);
const originalHasAudio = libraryVideo.originalHasAudio !== false;
clipAudioStateRef.current.set(libraryVideo.id, libraryVideo.hasAudio !== false);
setVideoHasAudioTrack(originalHasAudio);
@@ -2026,7 +2032,7 @@ export default function Editor() {
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => document.removeEventListener("visibilitychange", handleVisibilityChange);
- }, [loadUploadedVideo, clearHistory, isPhotoMode]);
+ }, [loadUploadedVideo, clearHistory, isPhotoMode, setClipUrl]);
useEffect(() => {
bgImagesGetAll()
@@ -2846,6 +2852,22 @@ export default function Editor() {
return () => window.removeEventListener("resize", checkMobile);
}, []);
+ const [currentPreviewThumbnail, setCurrentPreviewThumbnail] = useState<string | null>(null);
+ useEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setCurrentPreviewThumbnail(getThumbnailForTime(currentDisplayTime)?.dataUrl ?? null);
+ }, [currentDisplayTime, getThumbnailForTime]);
+
+ const [zoomFragmentThumbnail, setZoomFragmentThumbnail] = useState<string | null>(null);
+ useEffect(() => {
+ if (!selectedZoomFragment) {
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setZoomFragmentThumbnail(null);
+ return;
+ }
+ setZoomFragmentThumbnail(getThumbnailForTime(selectedZoomFragment.startTime)?.dataUrl ?? null);
+ }, [selectedZoomFragment, getThumbnailForTime]);
+
const handleAspectRatioChange = useCallback((ratio: AspectRatio) => {
setAspectRatio(ratio);
}, []);
@@ -2909,7 +2931,10 @@ export default function Editor() {
]);
// Only show camera if the active clip has camera support
- const activeClip = findActiveClipAtTime(currentTime);
+ const activeClip = useMemo(
+ () => getClipAtTime(videoClips, currentTime),
+ [videoClips, currentTime]
+ );
const shouldShowCamera = activeClip?.hasCamera === true;
const effectiveCameraUrl = shouldShowCamera ? cameraUrl : null;
@@ -2981,7 +3006,7 @@ export default function Editor() {
onUpdateZoomFragment={handleUpdateZoomFragment}
onDeleteZoomFragment={handleDeleteZoomFragment}
videoUrl={videoUrl}
- videoThumbnail={selectedZoomFragment ? getThumbnailForTime(selectedZoomFragment.startTime)?.dataUrl ?? null : null}
+ videoThumbnail={zoomFragmentThumbnail}
currentTime={currentTime}
getThumbnailForTime={getThumbnailForTime}
videoDimensions={videoDimensions}
@@ -3150,7 +3175,7 @@ export default function Editor() {
onZoomChange={handleZoomChange}
videoMaskConfig={videoMaskConfig}
onVideoMaskConfigChange={setVideoMaskConfig}
- videoPreviewImageUrl={getThumbnailForTime(currentDisplayTime)?.dataUrl ?? null}
+ videoPreviewImageUrl={currentPreviewThumbnail}
onSplitClip={handleSplitVideoClip}
canSplitClip={canSplitClip}
/>
@@ -3256,7 +3281,7 @@ export default function Editor() {
onUpdateZoomFragment={handleUpdateZoomFragment}
onDeleteZoomFragment={handleDeleteZoomFragment}
videoUrl={videoUrl}
- videoThumbnail={selectedZoomFragment ? getThumbnailForTime(selectedZoomFragment.startTime)?.dataUrl ?? null : null}
+ videoThumbnail={zoomFragmentThumbnail}
currentTime={currentTime}
getThumbnailForTime={getThumbnailForTime}
videoDimensions={videoDimensions}
diff --git a/app/components/ui/editor/LayersPanel.tsx b/app/components/ui/editor/LayersPanel.tsx
index a250938..fc0d28d 100644
--- a/app/components/ui/editor/LayersPanel.tsx
+++ b/app/components/ui/editor/LayersPanel.tsx
@@ -1,15 +1,42 @@
"use client";
-import { useState, useEffect, useRef, useCallback, useMemo, memo } from "react";
+import {
+ useState,
+ useEffect,
+ useRef,
+ useCallback,
+ useMemo,
+ useSyncExternalStore,
+ memo,
+} from "react";
import { createPortal } from "react-dom";
import { Icon } from "@iconify/react";
import type { CanvasElement } from "@/types/canvas-elements.types";
-import { LayersPanelProps, CtxMenuState, TYPE_ICON, PointerDragState } from "@/types/layers.types";
+import {
+ LayersPanelProps,
+ CtxMenuState,
+ TYPE_ICON,
+ PointerDragState,
+} from "@/types/layers.types";
import { buildLayerNames, buildGroupNumbers } from "@/lib/layers.utils";
import ContextMenu from "./ContextMenu";
import { useTranslations } from "next-intl";
import { TooltipAction } from "@/components/ui/tooltip-action";
+
const VIDEO_SENTINEL = "__video__";
+const MOBILE_QUERY = "(max-width: 639px)";
+
+function subscribeToMobileQuery(callback: () => void) {
+ const mq = window.matchMedia(MOBILE_QUERY);
+ mq.addEventListener("change", callback);
+ return () => mq.removeEventListener("change", callback);
+}
+function getIsMobileSnapshot() {
+ return window.matchMedia(MOBILE_QUERY).matches;
+}
+function getIsMobileServerSnapshot() {
+ return false;
+}
export function LayersPanelInner({
elements,
@@ -34,35 +61,80 @@ export function LayersPanelInner({
hoveredElementId = null,
onHoverElement,
}: LayersPanelProps) {
- const t = useTranslations("editor")
- const [isOpen, setIsOpen] = useState(true);
+ const t = useTranslations("editor");
+ const tActions = useTranslations("elementsMenu");
+
+ // --- open/closed panel, responsive default ---
+ const isMobile = useSyncExternalStore(
+ subscribeToMobileQuery,
+ getIsMobileSnapshot,
+ getIsMobileServerSnapshot
+ );
+ const [isOpen, setIsOpen] = useState(!isMobile);
+ const [prevIsMobile, setPrevIsMobile] = useState(isMobile);
+ if (isMobile !== prevIsMobile) {
+ // Adjusting state when an external value changes, done during render
+ // instead of inside an effect. Runs once per real breakpoint crossing;
+ // manual open/close toggles in between are left untouched.
+ setPrevIsMobile(isMobile);
+ setIsOpen(!isMobile);
+ }
+
+ // --- selection state ---
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const selectedIdsRef = useRef<string[]>([]);
- selectedIdsRef.current = selectedIds;
+ useEffect(() => {
+ selectedIdsRef.current = selectedIds;
+ }, [selectedIds]);
+
+ const [prevSelectedId, setPrevSelectedId] = useState(selectedId);
+ if (selectedId !== prevSelectedId) {
+ setPrevSelectedId(selectedId);
+ setSelectedIds(selectedId ? [selectedId] : []);
+ }
+
+ const multiIdsKey = selectedMultiIds ? selectedMultiIds.join(",") : "";
+ const [prevMultiIdsKey, setPrevMultiIdsKey] = useState(multiIdsKey);
+ if (multiIdsKey !== prevMultiIdsKey) {
+ setPrevMultiIdsKey(multiIdsKey);
+ if (selectedMultiIds && selectedMultiIds.length > 0) {
+ setSelectedIds(selectedMultiIds);
+ }
+ }
+
const [ctxMenu, setCtxMenu] = useState<CtxMenuState | null>(null);
const [videoCtxMenu, setVideoCtxMenu] = useState<{ x: number; y: number } | null>(null);
- const tActions = useTranslations("elementsMenu");
const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set());
- const [groupCtxMenu, setGroupCtxMenu] = useState<{ x: number; y: number; groupId: string } | null>(null);
+ const [groupCtxMenu, setGroupCtxMenu] = useState<{ x: number; y: number; groupId: string } | null>(
+ null
+ );
const [pointerDrag, setPointerDrag] = useState<PointerDragState | null>(null);
const pointerDragRef = useRef<PointerDragState | null>(null);
- pointerDragRef.current = pointerDrag;
+ useEffect(() => {
+ pointerDragRef.current = pointerDrag;
+ }, [pointerDrag]);
const listRef = useRef<HTMLDivElement>(null);
const rowRefs = useRef<Map<string, HTMLDivElement>>(new Map());
const isDraggingRef = useRef(false);
const ignoreSyncUntilRef = useRef<number>(0);
- const syncKey = elements.map((e) => e.id + ":" + e.zIndex + ":" + (e.groupId ?? "")).join(",");
- const insertVideoSentinel = useCallback((ids: string[]): string[] => {
- if (!videoLayerVisible) return ids;
- const zIndexOf = (id: string) => elements.find((e) => e.id === id)?.zIndex ?? 0;
- const idx = ids.findIndex((id) => zIndexOf(id) < 1000);
- return idx === -1
- ? [...ids, VIDEO_SENTINEL]
- : [...ids.slice(0, idx), VIDEO_SENTINEL, ...ids.slice(idx)];
- }, [elements, videoLayerVisible]);
+ const syncKey = elements
+ .map((e) => e.id + ":" + e.zIndex + ":" + (e.groupId ?? ""))
+ .join(",");
+
+ const insertVideoSentinel = useCallback(
+ (ids: string[]): string[] => {
+ if (!videoLayerVisible) return ids;
+ const zIndexOf = (id: string) => elements.find((e) => e.id === id)?.zIndex ?? 0;
+ const idx = ids.findIndex((id) => zIndexOf(id) < 1000);
+ return idx === -1
+ ? [...ids, VIDEO_SENTINEL]
+ : [...ids.slice(0, idx), VIDEO_SENTINEL, ...ids.slice(idx)];
+ },
+ [elements, videoLayerVisible]
+ );
const [displayOrder, setDisplayOrder] = useState<string[]>(() =>
insertVideoSentinel([...elements].sort((a, b) => b.zIndex - a.zIndex).map((e) => e.id))
@@ -76,22 +148,6 @@ export function LayersPanelInner({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [syncKey, videoLayerVisible]);
- useEffect(() => {
- if (selectedId) {
- setSelectedIds((prev) => (prev.includes(selectedId) ? prev : [selectedId]));
- } else {
- setSelectedIds([]);
- }
- }, [selectedId]);
-
- const multiIdsKey = selectedMultiIds ? selectedMultiIds.join(",") : "";
- useEffect(() => {
- if (selectedMultiIds && selectedMultiIds.length > 0) {
- setSelectedIds(selectedMultiIds);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [multiIdsKey]);
-
useEffect(() => {
if (!ctxMenu && !videoCtxMenu && !groupCtxMenu) return;
const close = (e: PointerEvent) => {
@@ -109,9 +165,7 @@ export function LayersPanelInner({
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key !== "Delete" && e.key !== "Backspace") return;
const tag = (e.target as HTMLElement).tagName;
- if (tag === "INPUT" || tag === "TEXTAREA" || (e.target as HTMLElement).isContentEditable)
- return;
-
+ if (tag === "INPUT" || tag === "TEXTAREA" || (e.target as HTMLElement).isContentEditable) return;
const ids = selectedIdsRef.current;
if (ids.length > 0) {
e.stopPropagation();
@@ -125,19 +179,6 @@ export function LayersPanelInner({
return () => window.removeEventListener("keydown", handleKeyDown, true);
}, [onDelete, onSelect]);
- useEffect(() => {
- const mq = window.matchMedia("(max-width: 639px)");
-
- const handler = (e: MediaQueryListEvent) => {
- setIsOpen(!e.matches);
- };
-
- setIsOpen(!mq.matches);
-
- mq.addEventListener("change", handler);
- return () => mq.removeEventListener("change", handler);
- }, []);
-
const handleRowClick = useCallback(
(e: React.MouseEvent, id: string) => {
if (e.shiftKey) {
@@ -169,7 +210,6 @@ export function LayersPanelInner({
const visualRows = useMemo<VisualRow[]>(() => {
const renderedGroupIds = new Set<string>();
const rows: VisualRow[] = [];
-
for (const id of displayOrder) {
if (id === VIDEO_SENTINEL) {
rows.push({ kind: "video" });
@@ -177,7 +217,6 @@ export function LayersPanelInner({
}
const el = elementsById[id];
if (!el) continue;
-
if (el.groupId) {
if (!renderedGroupIds.has(el.groupId)) {
renderedGroupIds.add(el.groupId);
@@ -196,6 +235,96 @@ export function LayersPanelInner({
return rows;
}, [displayOrder, elementsById, collapsedGroups]);
+ const applyReorder = useCallback(
+ (drag: PointerDragState) => {
+ const { id, isGroup, dropIndex, dropTargetGroupId } = drag;
+ let movingIds: string[];
+ if (isGroup) {
+ const gid = id.replace("group:", "");
+ movingIds = displayOrder.filter((did) => elementsById[did]?.groupId === gid);
+ } else {
+ movingIds = [id];
+ }
+ const movingSet = new Set(movingIds);
+
+ if (dropTargetGroupId && !isGroup && id !== VIDEO_SENTINEL && onSetGroupId) {
+ const dragged = elementsById[id];
+ if (dragged && dragged.groupId !== dropTargetGroupId) {
+ ignoreSyncUntilRef.current = Date.now() + 1000;
+ onSetGroupId(id, dropTargetGroupId);
+ }
+ return;
+ }
+
+ let pendingGroupChange: { id: string; groupId: string | undefined } | null = null;
+ if (!isGroup && id !== VIDEO_SENTINEL && onSetGroupId) {
+ const dragged = elementsById[id];
+ if (dragged?.groupId) {
+ const anchorVRow = visualRows[dropIndex];
+ let targetGid: string | undefined;
+ if (anchorVRow?.kind === "element") {
+ targetGid = elementsById[anchorVRow.id]?.groupId;
+ }
+ if (targetGid !== dragged.groupId) {
+ pendingGroupChange = { id, groupId: targetGid };
+ }
+ }
+ }
+
+ const isRowDragged = (r: VisualRow) => {
+ if (r.kind === "video") return movingSet.has(VIDEO_SENTINEL);
+ if (r.kind === "element") return movingSet.has(r.id);
+ if (r.kind === "group") {
+ const firstMember = displayOrder.find((did) => elementsById[did]?.groupId === r.groupId);
+ return firstMember ? movingSet.has(firstMember) : false;
+ }
+ return false;
+ };
+
+ let nonDraggedCount = 0;
+ for (let i = 0; i < dropIndex; i++) {
+ if (!isRowDragged(visualRows[i])) nonDraggedCount++;
+ }
+
+ const without = displayOrder.filter((did) => !movingSet.has(did));
+ const visualRowsWithout = visualRows.filter((r) => !isRowDragged(r));
+ const anchorRow = visualRowsWithout[nonDraggedCount];
+
+ let insertAt = without.length;
+ if (anchorRow) {
+ if (anchorRow.kind === "element") {
+ insertAt = without.indexOf(anchorRow.id);
+ } else if (anchorRow.kind === "group") {
+ const firstMember = without.find((did) => elementsById[did]?.groupId === anchorRow.groupId);
+ if (firstMember) insertAt = without.indexOf(firstMember);
+ }
+ }
+
+ const next = [...without.slice(0, insertAt), ...movingIds, ...without.slice(insertAt)];
+ const changed = next.some((val, i) => val !== displayOrder[i]);
+
+ if (pendingGroupChange) {
+ ignoreSyncUntilRef.current = Date.now() + 1500;
+ onSetGroupId!(pendingGroupChange.id, pendingGroupChange.groupId);
+ }
+
+ if (changed) {
+ ignoreSyncUntilRef.current = Math.max(ignoreSyncUntilRef.current, Date.now() + 1500);
+ setDisplayOrder(next);
+ const videoIdx = next.indexOf(VIDEO_SENTINEL);
+ if (videoIdx === -1) {
+ onReorder(next, []);
+ } else {
+ onReorder(
+ next.slice(0, videoIdx).filter((x) => x !== VIDEO_SENTINEL),
+ next.slice(videoIdx + 1).filter((x) => x !== VIDEO_SENTINEL)
+ );
+ }
+ }
+ },
+ [displayOrder, elementsById, visualRows, onReorder, onSetGroupId]
+ );
+
useEffect(() => {
if (!pointerDrag) return;
const MOVE_THRESHOLD = 5;
@@ -203,17 +332,17 @@ export function LayersPanelInner({
const onMove = (e: MouseEvent) => {
const drag = pointerDragRef.current;
if (!drag) return;
-
const moved = Math.abs(e.clientY - drag.startY) > MOVE_THRESHOLD;
if (!moved && !drag.active) return;
let dropIdx = drag.dropIndex;
let bestDist = Infinity;
let intoGroupId: string | null = null;
- const INTO_ZONE = 0.30;
+ const INTO_ZONE = 0.3;
visualRows.forEach((row, i) => {
- const key = row.kind === "element" ? row.id : row.kind === "group" ? `group:${row.groupId}` : VIDEO_SENTINEL;
+ const key =
+ row.kind === "element" ? row.id : row.kind === "group" ? `group:${row.groupId}` : VIDEO_SENTINEL;
if (key === drag.id) return;
const el = rowRefs.current.get(key);
if (!el) return;
@@ -249,14 +378,18 @@ export function LayersPanelInner({
}
});
- if (!drag.isGroup && !intoGroupId && drag.id !== VIDEO_SENTINEL && dropIdx > 0 && dropIdx < visualRows.length) {
+ if (
+ !drag.isGroup &&
+ !intoGroupId &&
+ drag.id !== VIDEO_SENTINEL &&
+ dropIdx > 0 &&
+ dropIdx < visualRows.length
+ ) {
const prevRow = visualRows[dropIdx - 1];
const nextRow = visualRows[dropIdx];
-
if (prevRow.kind === "element" && nextRow.kind === "element") {
const prevEl = elementsById[prevRow.id];
const nextEl = elementsById[nextRow.id];
-
if (prevEl?.groupId && prevEl.groupId === nextEl?.groupId) {
intoGroupId = prevEl.groupId;
}
@@ -286,7 +419,6 @@ export function LayersPanelInner({
window.addEventListener("mousemove", onMove);
window.addEventListener("mouseup", onUp);
-
return () => {
window.removeEventListener("mousemove", onMove);
window.removeEventListener("mouseup", onUp);
@@ -294,101 +426,6 @@ export function LayersPanelInner({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [!!pointerDrag, visualRows]);
- const applyReorder = useCallback(
- (drag: PointerDragState) => {
- const { id, isGroup, dropIndex, dropTargetGroupId } = drag;
-
- let movingIds: string[];
- if (isGroup) {
- const gid = id.replace("group:", "");
- movingIds = displayOrder.filter((did) => elementsById[did]?.groupId === gid);
- } else {
- movingIds = [id];
- }
- const movingSet = new Set(movingIds);
-
- if (dropTargetGroupId && !isGroup && id !== VIDEO_SENTINEL && onSetGroupId) {
- const dragged = elementsById[id];
- if (dragged && dragged.groupId !== dropTargetGroupId) {
- ignoreSyncUntilRef.current = Date.now() + 1000;
- onSetGroupId(id, dropTargetGroupId);
- }
- return;
- }
-
- let pendingGroupChange: { id: string; groupId: string | undefined } | null = null;
- if (!isGroup && id !== VIDEO_SENTINEL && onSetGroupId) {
- const dragged = elementsById[id];
- if (dragged?.groupId) {
- const anchorVRow = visualRows[dropIndex];
- let targetGid: string | undefined;
- if (anchorVRow?.kind === "element") {
- targetGid = elementsById[anchorVRow.id]?.groupId;
- }
- if (targetGid !== dragged.groupId) {
- pendingGroupChange = { id, groupId: targetGid };
- }
- }
- }
-
- const isRowDragged = (r: VisualRow) => {
- if (r.kind === "video") return movingSet.has(VIDEO_SENTINEL);
-
- if (r.kind === "element") return movingSet.has(r.id);
- if (r.kind === "group") {
- const firstMember = displayOrder.find(
- (did) => elementsById[did]?.groupId === r.groupId
- );
- return firstMember ? movingSet.has(firstMember) : false;
- }
- return false;
- };
-
- let nonDraggedCount = 0;
- for (let i = 0; i < dropIndex; i++) {
- if (!isRowDragged(visualRows[i])) nonDraggedCount++;
- }
-
- const without = displayOrder.filter((did) => !movingSet.has(did));
- const visualRowsWithout = visualRows.filter((r) => !isRowDragged(r));
- const anchorRow = visualRowsWithout[nonDraggedCount];
- let insertAt = without.length;
-
- if (anchorRow) {
- if (anchorRow.kind === "element") {
- insertAt = without.indexOf(anchorRow.id);
- } else if (anchorRow.kind === "group") {
- const firstMember = without.find(
- (did) => elementsById[did]?.groupId === anchorRow.groupId
- );
- if (firstMember) insertAt = without.indexOf(firstMember);
- }
- }
-
- const next = [...without.slice(0, insertAt), ...movingIds, ...without.slice(insertAt)];
- const changed = next.some((val, i) => val !== displayOrder[i]);
-
- if (pendingGroupChange) {
- ignoreSyncUntilRef.current = Date.now() + 1500;
- onSetGroupId!(pendingGroupChange.id, pendingGroupChange.groupId);
- }
- if (changed) {
- ignoreSyncUntilRef.current = Math.max(ignoreSyncUntilRef.current, Date.now() + 1500);
- setDisplayOrder(next);
- const videoIdx = next.indexOf(VIDEO_SENTINEL);
- if (videoIdx === -1) {
- onReorder(next, []);
- } else {
- onReorder(
- next.slice(0, videoIdx).filter((x) => x !== VIDEO_SENTINEL),
- next.slice(videoIdx + 1).filter((x) => x !== VIDEO_SENTINEL)
- );
- }
- }
- },
- [displayOrder, elementsById, visualRows, onReorder, onSetGroupId]
- );
-
const startPointerDrag = useCallback(
(e: React.MouseEvent, id: string, isGroup: boolean) => {
if (e.button !== 0) return;
@@ -400,8 +437,11 @@ export function LayersPanelInner({
});
isDraggingRef.current = true;
const drag: PointerDragState = {
- id, isGroup,
- x: e.clientX, y: e.clientY, startY: e.clientY,
+ id,
+ isGroup,
+ x: e.clientX,
+ y: e.clientY,
+ startY: e.clientY,
dropIndex: vIdx >= 0 ? vIdx : 0,
dropTargetGroupId: null,
active: false,
@@ -418,12 +458,10 @@ export function LayersPanelInner({
if (ctxId) onBringToFront(ctxId);
setCtxMenu(null);
}, [ctxId, onBringToFront]);
-
const handleCtxSendToBack = useCallback(() => {
if (ctxId) onSendToBack(ctxId);
setCtxMenu(null);
}, [ctxId, onSendToBack]);
-
const handleCtxDelete = useCallback(() => {
if (ctxId) {
onDelete(ctxId);
@@ -431,7 +469,6 @@ export function LayersPanelInner({
}
setCtxMenu(null);
}, [ctxId, onDelete]);
-
const handleCtxDeleteSelected = useCallback(() => {
onDelete([...selectedIds]);
setSelectedIds([]);
@@ -442,7 +479,6 @@ export function LayersPanelInner({
(vIdx: number) => {
const isDropTarget = pointerDrag?.active && pointerDrag.dropIndex === vIdx;
const isSelected = isVideoLayerSelected;
-
return (
<div
key="video-layer"
@@ -465,7 +501,7 @@ export function LayersPanelInner({
}}
data-layer-row="video-layer"
className={[
- "group relative flex items-center gap-1.5 h-7 px-2 rounded-md cursor-pointer select-none transition-all duration-100",
+ "group relative flex items-center gap-1.5 h-7 px-2 rounded-md cursor-pointer select-none transition-all duration-100",
isSelected
? "bg-[#00A3FF]/15 text-white"
: "text-neutral-400 hover:bg-white/5 hover:text-neutral-200",
@@ -495,7 +531,6 @@ export function LayersPanelInner({
const isSelected = selectedIds.includes(id);
const isDraggingThis = pointerDrag?.active && pointerDrag.id === id;
const isDropTarget = pointerDrag?.active && pointerDrag.dropIndex === vIdx;
-
const isVisible = el.visible !== false;
const isLocked = el.locked === true;
@@ -556,10 +591,7 @@ export function LayersPanelInner({
icon={TYPE_ICON[el.type]}
className={`size-4.5 shrink-0 ${isSelected ? "text-[#00A3FF]" : "text-neutral-500"}`}
/>
- <span
- className={`flex-1 text-[11px] truncate ${isVisible ? "" : "opacity-40 line-through"
- }`}
- >
+ <span className={`flex-1 text-[11px] truncate ${isVisible ? "" : "opacity-40 line-through"}`}>
{layerNames.get(id) ?? id}
</span>
<div className="flex items-center opacity-0 group-hover:opacity-100 transition-opacity">
@@ -579,7 +611,6 @@ export function LayersPanelInner({
/>
</button>
</TooltipAction>
-
<TooltipAction label={isLocked ? t("layerPanel.tooltips.unlock") : t("layerPanel.tooltips.lock")}>
<button
onClick={(e) => {
@@ -596,7 +627,6 @@ export function LayersPanelInner({
/>
</button>
</TooltipAction>
-
<TooltipAction label={t("layerPanel.tooltips.delete")}>
<button
onClick={(e) => {
@@ -640,7 +670,7 @@ export function LayersPanelInner({
onDelete,
onHoverElement,
hoveredElementId,
- t
+ t,
]
);
@@ -702,7 +732,6 @@ export function LayersPanelInner({
const rows: React.ReactNode[] = [];
let groupCounter = 0;
let vIdx = 0;
-
for (const id of displayOrder) {
if (id === VIDEO_SENTINEL) {
rows.push(renderVideoRow(vIdx++));
@@ -710,7 +739,6 @@ export function LayersPanelInner({
}
const el = elementsById[id];
if (!el) continue;
-
if (el.groupId) {
if (renderedGroupIds.has(el.groupId)) {
continue;
@@ -726,8 +754,7 @@ export function LayersPanelInner({
const thisGroupNum = groupNumbers.get(gid) ?? groupCounter;
const isDraggingThisGroup = pointerDrag?.active && pointerDrag.id === groupKey;
const currentGroupVIdx = vIdx++;
- const isGroupDropTarget =
- pointerDrag?.active && pointerDrag.dropIndex === currentGroupVIdx;
+ const isGroupDropTarget = pointerDrag?.active && pointerDrag.dropIndex === currentGroupVIdx;
rows.push(
<div
@@ -811,6 +838,7 @@ export function LayersPanelInner({
</span>
</div>
);
+
if (!isCollapsed) {
for (const member of groupMembers) {
const childVIdx = vIdx++;
@@ -823,7 +851,6 @@ export function LayersPanelInner({
rows.push(renderLayerRow(el, false, currentVIdx));
}
}
-
if (pointerDrag?.active && pointerDrag.dropIndex === visualRows.length) {
rows.push(
<div key="drop-indicator-bottom" className="relative">
@@ -835,7 +862,6 @@ export function LayersPanelInner({
})()
)}
</div>
-
{selectedIds.length > 1 && (
<div className="shrink-0 border-t border-white/6 px-2 py-1.5 flex items-center gap-1">
<span className="flex-1 text-[11px] text-neutral-500">
@@ -847,7 +873,8 @@ export function LayersPanelInner({
onClick={() => onGroup(selectedIds)}
className="flex items-center gap-1 px-1.5 py-0.5 text-[11px] text-neutral-400 hover:text-white hover:bg-white/10 rounded transition-colors"
>
- <Icon icon="solar:layers-minimalistic-bold" className="size-4" /> {t("layerPanel.groupAction")}
+ <Icon icon="solar:layers-minimalistic-bold" className="size-4" />
+ {t("layerPanel.groupAction")}
</button>
</TooltipAction>
)}
@@ -857,13 +884,13 @@ export function LayersPanelInner({
onClick={() => onUngroup(selectedIds)}
className="flex items-center gap-1 px-1.5 py-0.5 text-[11px] text-neutral-400 hover:text-white hover:bg-white/10 rounded transition-colors"
>
- <Icon icon="solar:layers-bold" className="size-4" /> {t("layerPanel.ungroupAction")}
+ <Icon icon="solar:layers-bold" className="size-4" />
+ {t("layerPanel.ungroupAction")}
</button>
</TooltipAction>
)}
</div>
)}
-
{videoCtxMenu && (
<div
data-ctx-menu
@@ -893,7 +920,6 @@ export function LayersPanelInner({
</button>
</div>
)}
-
{groupCtxMenu && (
<div
data-ctx-menu
@@ -930,7 +956,6 @@ export function LayersPanelInner({
</button>
</div>
)}
-
{ctxMenu &&
(() => {
const allInSameGroup =
@@ -940,7 +965,6 @@ export function LayersPanelInner({
return el?.groupId && el.groupId === elementsById[selectedIds[0]]?.groupId;
});
const anyHasGroup = selectedIds.some((id) => elementsById[id]?.groupId);
-
return (
<ContextMenu
x={ctxMenu.x}
@@ -973,7 +997,6 @@ export function LayersPanelInner({
/>
);
})()}
-
{pointerDrag?.active &&
typeof document !== "undefined" &&
(() => {
@@ -994,7 +1017,6 @@ export function LayersPanelInner({
ghostIcon = TYPE_ICON[dragEl.type];
}
}
-
return createPortal(
<div
className="fixed z-99999 pointer-events-none"
@@ -1005,9 +1027,7 @@ export function LayersPanelInner({
>
<div className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-[#1c1c1f]/90 border border-white/10 shadow-2xl backdrop-blur-sm">
<Icon icon={ghostIcon} className="size-4.5 text-[#00A3FF]" />
- <span className="text-[11px] text-white font-medium max-w-30 truncate">
- {ghostLabel}
- </span>
+ <span className="text-[11px] text-white font-medium max-w-30 truncate">{ghostLabel}</span>
</div>
</div>,
document.body
diff --git a/app/components/ui/editor/PhotoEditorPlaceholder.tsx b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
index 7df7c29..c997db0 100644
--- a/app/components/ui/editor/PhotoEditorPlaceholder.tsx
+++ b/app/components/ui/editor/PhotoEditorPlaceholder.tsx
@@ -3,7 +3,6 @@
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { useState, useCallback, useEffect, useRef } from "react";
-import { SliderControl } from "../../../../components/ui/SliderControl";
import { Button } from "@/components/ui/button";
import { AspectRatioSelect } from "@/app/components/ui/AspectRatioSelect";
import { TooltipAction } from "@/components/ui/tooltip-action";
diff --git a/app/components/ui/editor/ToolsSidebar.tsx b/app/components/ui/editor/ToolsSidebar.tsx
index 4d851ae..1d4c6ae 100644
--- a/app/components/ui/editor/ToolsSidebar.tsx
+++ b/app/components/ui/editor/ToolsSidebar.tsx
@@ -367,15 +367,6 @@ export function ToolsSidebar({
videoSrc: "/videos/preview-camera.mp4"
}}
/>
-
- {/* <SidebarTool
- icon="solar:cursor-bold-duotone"
- label={t("tools.cursor")}
- isActive={activeTool === "cursor"}
- onClick={() => onToolChange("cursor")}
- badge={!isCursorEnabled ? t("tools.soon") : undefined}
- disabled={!isCursorEnabled}
- /> */}
</>
)}
<div className="shrink-0 h-12" aria-hidden="true" />
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index f7063e5..1ae2fd1 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -283,19 +283,56 @@ function VideoCanvasInner({
const lastSetVideoUrlRef = useRef<string | null>(null);
const preservedVideoStateRef = useRef<{ time: number; playing: boolean } | null>(null);
const imagePhoneRescaleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const cameraDragRef = useRef<{
+ pointerId: number;
+ startX: number;
+ startY: number;
+ initialX: number;
+ initialY: number;
+ rect: DOMRect;
+ } | null>(null);
+ const [isDraggingCamera, setIsDraggingCamera] = useState(false);
+
+ // Canvas elements controls state
+ const [hoveredElementId, setHoveredElementId] = useState<string | null>(null);
+ const [isDraggingElement, setIsDraggingElement] = useState(false);
+ const [isDraggingElementRotation, setIsDraggingElementRotation] = useState(false);
+ const [isDraggingElementResize, setIsDraggingElementResize] = useState(false);
+ const elementResizeStart = useRef<ElementResizeStart | null>(null);
+ const elementDragStart = useRef({ x: 0, y: 0, initialX: 0, initialY: 0, initialRotation: 0 });
+ // Positions of ALL selected elements captured once at drag-start (stable ref, never updated during drag)
+ const multiDragStartRef = useRef<Map<string, { x: number; y: number }>>(new Map());
+ // When clicking a multi-selected element, track potential collapse to single (cleared on actual drag)
+ const pendingCollapseRef = useRef<string | null>(null);
+ const wasDragRef = useRef(false);
+ const pendingVideoCollapseRef = useRef(false);
+ const pendingElementsCollapseRef = useRef(false);
+
+ // Drag & drop state for images (photo mode only)
+ const [isDraggingOver, setIsDraggingOver] = useState(false);
+ const canvasContainerRef = useRef<HTMLDivElement>(null);
+
+ // Inline text editing (Figma-style)
+ const [editingTextId, setEditingTextId] = useState<string | null>(null);
+
+ // Multi-select and canvas right-click context menu
+ const [canvasSelectedIds, setCanvasSelectedIds] = useState<string[]>([]);
+ const [canvasCtxMenu, setCanvasCtxMenu] = useState<{ x: number; y: number; isVideo?: boolean } | null>(null);
+ const [videoContainerSize, setVideoContainerSize] = useState({ width: 0, height: 0 });
// Reset lastSetVideoUrlRef when mockupId changes to force src re-assignment on remount
useEffect(() => {
lastSetVideoUrlRef.current = null;
}, [mockupId]);
- useEffect(() => {
+ const [prevOtherSelectionActive, setPrevOtherSelectionActive] = useState(otherSelectionActive);
+ if (otherSelectionActive !== prevOtherSelectionActive) {
+ setPrevOtherSelectionActive(otherSelectionActive);
if (otherSelectionActive) {
setIsVideoSelected(false);
setCanvasSelectedIds([]);
}
- }, [otherSelectionActive]);
-
+ }
useEffect(() => {
const targetUrl = activeClipUrl ?? videoUrl;
if (videoRef.current && targetUrl) {
@@ -339,13 +376,7 @@ function VideoCanvasInner({
// Track the real intrinsic aspect ratio of the video so the "none"
useEffect(() => {
- if (mediaType !== "video") return;
-
- if (activeMediaAspect) {
- setMediaAspect(activeMediaAspect);
- return;
- }
-
+ if (mediaType !== "video" || activeMediaAspect) return;
const video = videoRef.current;
if (!video) return;
const updateAspect = () => {
@@ -399,41 +430,39 @@ function VideoCanvasInner({
const mockupContentRef = useRef<HTMLDivElement>(null);
const [contentInsets, setContentInsets] = useState({ top: 0, bottom: 0, left: 0, right: 0 });
- ctrlScrollWheelRef.current = (e: WheelEvent) => {
- if (!e.ctrlKey) return;
-
- if (imagePhoneActive) {
- e.preventDefault();
- e.stopImmediatePropagation();
- const next = Math.max(0.3, Math.min(3, imagePhoneScale * (e.deltaY < 0 ? 1.05 : 0.95)));
- setImagePhoneScale(next);
- setImagePhoneZoomVisible(true);
- if (imagePhoneZoomTimerRef.current) clearTimeout(imagePhoneZoomTimerRef.current);
- imagePhoneZoomTimerRef.current = setTimeout(() => setImagePhoneZoomVisible(false), 1200);
- return;
- }
-
- if (mediaType === "video" && onPaddingChange) {
- e.preventDefault();
- e.stopImmediatePropagation();
-
- const PADDING_MIN = 0;
- const PADDING_MAX = 30;
- const base = pendingPaddingRef.current ?? padding;
- const step = Math.min(1.5, Math.max(0.15, Math.abs(e.deltaY) * 0.015));
- const next = Math.max(PADDING_MIN, Math.min(PADDING_MAX, base + (e.deltaY < 0 ? -step : step)));
-
- pendingPaddingRef.current = next;
- if (paddingWheelRafRef.current === null) {
- paddingWheelRafRef.current = requestAnimationFrame(() => {
- if (pendingPaddingRef.current !== null) {
- onPaddingChange(pendingPaddingRef.current);
- }
- paddingWheelRafRef.current = null;
- });
+ useEffect(() => {
+ ctrlScrollWheelRef.current = (e: WheelEvent) => {
+ if (!e.ctrlKey) return;
+ if (imagePhoneActive) {
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ const next = Math.max(0.3, Math.min(3, imagePhoneScale * (e.deltaY < 0 ? 1.05 : 0.95)));
+ setImagePhoneScale(next);
+ setImagePhoneZoomVisible(true);
+ if (imagePhoneZoomTimerRef.current) clearTimeout(imagePhoneZoomTimerRef.current);
+ imagePhoneZoomTimerRef.current = setTimeout(() => setImagePhoneZoomVisible(false), 1200);
+ return;
}
- }
- };
+ if (mediaType === "video" && onPaddingChange) {
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ const PADDING_MIN = 0;
+ const PADDING_MAX = 30;
+ const base = pendingPaddingRef.current ?? padding;
+ const step = Math.min(1.5, Math.max(0.15, Math.abs(e.deltaY) * 0.015));
+ const next = Math.max(PADDING_MIN, Math.min(PADDING_MAX, base + (e.deltaY < 0 ? -step : step)));
+ pendingPaddingRef.current = next;
+ if (paddingWheelRafRef.current === null) {
+ paddingWheelRafRef.current = requestAnimationFrame(() => {
+ if (pendingPaddingRef.current !== null) {
+ onPaddingChange(pendingPaddingRef.current);
+ }
+ paddingWheelRafRef.current = null;
+ });
+ }
+ }
+ };
+ });
useEffect(() => {
const el = previewContainerRef.current;
@@ -535,43 +564,6 @@ function VideoCanvasInner({
};
}, [canvasDimensions, imagePhoneRefWidth, isRestoringProjectRef, setImagePhoneX, setImagePhoneY, setImagePhoneScale, setImagePhoneRefWidth]);
- const cameraDragRef = useRef<{
- pointerId: number;
- startX: number;
- startY: number;
- initialX: number;
- initialY: number;
- rect: DOMRect;
- } | null>(null);
- const [isDraggingCamera, setIsDraggingCamera] = useState(false);
-
- // Canvas elements controls state
- const [hoveredElementId, setHoveredElementId] = useState<string | null>(null);
- const [isDraggingElement, setIsDraggingElement] = useState(false);
- const [isDraggingElementRotation, setIsDraggingElementRotation] = useState(false);
- const [isDraggingElementResize, setIsDraggingElementResize] = useState(false);
- const elementResizeStart = useRef<ElementResizeStart | null>(null);
- const elementDragStart = useRef({ x: 0, y: 0, initialX: 0, initialY: 0, initialRotation: 0 });
- // Positions of ALL selected elements captured once at drag-start (stable ref, never updated during drag)
- const multiDragStartRef = useRef<Map<string, { x: number; y: number }>>(new Map());
- // When clicking a multi-selected element, track potential collapse to single (cleared on actual drag)
- const pendingCollapseRef = useRef<string | null>(null);
- const wasDragRef = useRef(false);
- const pendingVideoCollapseRef = useRef(false);
- const pendingElementsCollapseRef = useRef(false);
-
- // Drag & drop state for images (photo mode only)
- const [isDraggingOver, setIsDraggingOver] = useState(false);
- const canvasContainerRef = useRef<HTMLDivElement>(null);
-
- // Inline text editing (Figma-style)
- const [editingTextId, setEditingTextId] = useState<string | null>(null);
-
- // Multi-select and canvas right-click context menu
- const [canvasSelectedIds, setCanvasSelectedIds] = useState<string[]>([]);
- const [canvasCtxMenu, setCanvasCtxMenu] = useState<{ x: number; y: number; isVideo?: boolean } | null>(null);
- const [videoContainerSize, setVideoContainerSize] = useState({ width: 0, height: 0 });
-
useEffect(() => {
const container = videoContainerRef.current;
if (!container) return;
@@ -699,13 +691,16 @@ function VideoCanvasInner({
// Effective aspect ratio for the "none" mockup contain-box, adjusted for
// any active crop — mirrors the same math used in drawFrame's computeContainer.
+ const effectiveMediaAspect = mediaType === "video" ? (activeMediaAspect ?? mediaAspect) : mediaAspect;
+
const mediaContainAspect = useMemo(() => {
- if (!mediaAspect) return null;
+ if (!effectiveMediaAspect) return null;
if (cropArea && (cropArea.width < 100 || cropArea.height < 100)) {
- return mediaAspect * (cropArea.width / cropArea.height);
+ return effectiveMediaAspect * (cropArea.width / cropArea.height);
}
- return mediaAspect;
- }, [mediaAspect, cropArea]);
+ return effectiveMediaAspect;
+ }, [effectiveMediaAspect, cropArea]);
+
const effectivePhoneMaskConfig = useMemo(() => {
return mediaType === "video" ? videoMaskConfig : imageMaskConfig;
}, [mediaType, videoMaskConfig, imageMaskConfig]);
@@ -748,21 +743,22 @@ function VideoCanvasInner({
}
}, [imageUrlToLoad]);
+ const [prevImagePhoneActive, setPrevImagePhoneActive] = useState(imagePhoneActive);
+ if (imagePhoneActive !== prevImagePhoneActive) {
+ setPrevImagePhoneActive(imagePhoneActive);
+ if (!imagePhoneActive) setActivePhoneDevice(null);
+ }
+
useEffect(() => {
- if (!imagePhoneActive) {
- setActivePhoneDevice(null);
- return;
- }
+ if (!imagePhoneActive) return;
if (imagePhoneDevice === activePhoneDevice) return;
-
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- inicia una transición temporizada real (setTimeout), no es sincronización directa de prop
setPhoneTransitioning(true);
setActivePhoneDevice(null);
-
const id = setTimeout(() => {
setActivePhoneDevice(imagePhoneDevice);
setPhoneTransitioning(false);
}, 50);
-
return () => clearTimeout(id);
}, [imagePhoneDevice, imagePhoneActive]);
@@ -1984,6 +1980,11 @@ function VideoCanvasInner({
imagePhoneApiRef.current?.restorePreview();
}
};
+ const [activeVideoElement, setActiveVideoElement] = useState<HTMLVideoElement | null>(null);
+
+ useEffect(() => {
+ setActiveVideoElement(mediaType === "video" ? videoRef.current : null);
+ }, [mediaType, videoRef, videoUrl]);
useImperativeHandle(ref, () => ({
getExportCanvas: () => exportCanvasRef.current,
@@ -2637,7 +2638,7 @@ function VideoCanvasInner({
<Laptop3DViewer
key="laptop"
imageUrl={imageUrl}
- videoElement={mediaType === "video" ? videoRef.current : undefined}
+ videoElement={activeVideoElement ?? undefined}
openingProgress={imagePhoneOpening}
imageMaskConfig={effectivePhoneMaskConfig}
cropArea={cropArea}
@@ -2663,7 +2664,7 @@ function VideoCanvasInner({
<IPhone13ProMax3DViewer
key="iphone-13-pro-max"
imageUrl={imageUrl}
- videoElement={mediaType === "video" ? videoRef.current : undefined}
+ videoElement={activeVideoElement ?? undefined}
imageMaskConfig={effectivePhoneMaskConfig}
cropArea={cropArea}
initialRotationX={imagePhoneRotX}
@@ -2688,7 +2689,7 @@ function VideoCanvasInner({
<IPhone17ProMax3DViewer
key="iphone-17-pro-max"
imageUrl={imageUrl}
- videoElement={mediaType === "video" ? videoRef.current : undefined}
+ videoElement={activeVideoElement ?? undefined}
imageMaskConfig={effectivePhoneMaskConfig}
cropArea={cropArea}
initialRotationX={imagePhoneRotX}
@@ -2713,7 +2714,7 @@ function VideoCanvasInner({
<DoubleIPhone3DViewer
key="double_iphone_13_pro"
imageUrl={imageUrl}
- videoElement={mediaType === "video" ? videoRef.current : undefined}
+ videoElement={activeVideoElement ?? undefined}
imageMaskConfig={effectivePhoneMaskConfig}
cropArea={cropArea}
initialRotationX={imagePhoneRotX}
@@ -2737,7 +2738,7 @@ function VideoCanvasInner({
<IPadMini63DViewer
key="ipad_mini_6_2021"
imageUrl={imageUrl}
- videoElement={mediaType === "video" ? videoRef.current : undefined}
+ videoElement={activeVideoElement ?? undefined}
imageMaskConfig={effectivePhoneMaskConfig}
cropArea={cropArea}
initialRotationX={imagePhoneRotX}
@@ -2762,7 +2763,7 @@ function VideoCanvasInner({
<Phone3DViewer
key={imagePhoneDevice}
imageUrl={imageUrl}
- videoElement={mediaType === "video" ? videoRef.current : undefined}
+ videoElement={activeVideoElement ?? undefined}
imageMaskConfig={effectivePhoneMaskConfig}
cropArea={cropArea}
initialRotationX={imagePhoneRotX}
diff --git a/app/components/ui/editor/VideosMenu.tsx b/app/components/ui/editor/VideosMenu.tsx
index 73e6455..a8722ec 100644
--- a/app/components/ui/editor/VideosMenu.tsx
+++ b/app/components/ui/editor/VideosMenu.tsx
@@ -49,20 +49,24 @@ export function VideosMenu({
const [isDragging, setIsDragging] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
- const loadVideos = useCallback(async () => {
- try {
- const videoList = await getLibraryVideoInfoList();
- setVideos(videoList);
- } catch (error) {
- console.error("Error loading videos:", error);
- } finally {
- setIsLoading(false);
- }
- }, []);
-
useEffect(() => {
- loadVideos();
- }, [loadVideos, refreshTrigger]);
+ let ignore = false;
+
+ getLibraryVideoInfoList()
+ .then((videoList) => {
+ if (!ignore) setVideos(videoList);
+ })
+ .catch((error) => {
+ console.error("Error loading videos:", error);
+ })
+ .finally(() => {
+ if (!ignore) setIsLoading(false);
+ });
+
+ return () => {
+ ignore = true;
+ };
+ }, [refreshTrigger]);
const handleDelete = async (id: string) => {
if (deletingId) return;
@@ -263,8 +267,8 @@ export function VideosMenu({
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, x: -20, scale: 0.95 }}
className={`group relative rounded-lg border overflow-hidden transition-all duration-200 aspect-[16/10] w-full bg-[#000] ${videosInTrackIds.includes(video.id)
- ? "border-blue-500 shadow-[0_0_15px_rgba(59,130,246,0.15)]"
- : "border-neutral-800 hover:border-neutral-700"
+ ? "border-blue-500 shadow-[0_0_15px_rgba(59,130,246,0.15)]"
+ : "border-neutral-800 hover:border-neutral-700"
}`}
>
<div
@@ -296,8 +300,8 @@ export function VideosMenu({
<div
className={`absolute inset-0 flex items-center justify-center transition-opacity z-10 pointer-events-none ${videosInTrackIds.includes(video.id) || addingId === video.id
- ? "opacity-100"
- : "opacity-0 group-hover:opacity-100"
+ ? "opacity-100"
+ : "opacity-0 group-hover:opacity-100"
}`}
>
{addingId === video.id ? (
@@ -306,7 +310,7 @@ export function VideosMenu({
</div>
) : videosInTrackIds.includes(video.id) ? (
<div className="p-2.5 rounded-full bg-blue-500/10 backdrop-blur-sm border border-blue-500/50">
- <Icon icon="solar:check-circle-bold" width="28" className="text-blue-500" />
+ <Icon icon="solar:check-circle-bold" width="28" className="text-white" />
</div>
) : (
<div className="absolute inset-0 flex items-center justify-center bg-black/30 backdrop-blur-[1px]">
@@ -338,10 +342,10 @@ export function VideosMenu({
onClick={() => handleToggleAudio(video.id, video.hasAudio)}
disabled={video.originalHasAudio === false}
className={`p-1.5 rounded-md backdrop-blur-sm border transition-colors ${video.originalHasAudio === false
- ? "text-neutral-500 border-transparent cursor-not-allowed"
- : video.hasAudio === false
- ? "text-red-400 bg-red-500/20 border-red-500/50"
- : "text-neutral-300 bg-neutral-900/50 hover:text-white hover:bg-neutral-800 border-neutral-700/50"
+ ? "text-neutral-500 border-transparent cursor-not-allowed"
+ : video.hasAudio === false
+ ? "text-red-400 bg-red-500/20 border-red-500/50"
+ : "text-neutral-300 bg-neutral-900/50 hover:text-white hover:bg-neutral-800 border-neutral-700/50"
}`}
>
<Icon icon={video.hasAudio === false ? "solar:volume-cross-outline" : "solar:volume-loud-outline"} width="15" />
diff --git a/hooks/useScreenRecording.ts b/hooks/useScreenRecording.ts
index e720cff..84facd9 100644
--- a/hooks/useScreenRecording.ts
+++ b/hooks/useScreenRecording.ts
@@ -1,11 +1,12 @@
"use client";
+
import { useState, useCallback, useRef, useEffect } from "react";
import { useRouter, usePathname } from "@/navigation";
import type { RecordingState, RecordingResult, VideoData, RecordingContextType } from "@/types";
import type { CameraConfig, RecordingSetupConfig } from "@/types/camera.types";
import { DEFAULT_RECORDING_SETUP, requestCameraStream, requestMicrophoneStream } from "@/types/camera.types";
import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";
-import { Input, Output, Mp4OutputFormat, BufferTarget, Conversion, ALL_FORMATS, BufferSource } from "mediabunny";
+import { convertToMp4 } from "@/lib/video-conversion";
export type { RecordingState, RecordingResult, VideoData, RecordingContextType };
@@ -85,10 +86,8 @@ async function saveVideoToIndexedDB(
} catch (e) {
console.warn("Failed to clear thumbnail cache:", e);
}
-
const videoId = generateVideoId();
const db = await getDB();
-
return new Promise((resolve, reject) => {
const storeName = "videos";
const transaction = db.transaction([storeName], "readwrite");
@@ -102,7 +101,6 @@ async function saveVideoToIndexedDB(
cameraBlob: extras.cameraBlob ?? null,
cameraConfig: extras.cameraConfig ?? null,
};
-
const putRequest = store.put(videoData, "currentVideo");
putRequest.onsuccess = () => {
db.close();
@@ -129,17 +127,14 @@ export async function loadVideoFromIndexedDB(): Promise<{
try {
const db = await getDB();
const storeName = "videos";
-
if (!db.objectStoreNames.contains(storeName)) {
db.close();
return null;
}
-
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], "readonly");
const store = transaction.objectStore(storeName);
const getRequest = store.get("currentVideo");
-
getRequest.onsuccess = () => {
db.close();
const data = getRequest.result;
@@ -149,7 +144,6 @@ export async function loadVideoFromIndexedDB(): Promise<{
const timestamp = data.timestamp || Date.now();
const cameraBlob: Blob | null = data.cameraBlob ?? null;
const cameraUrl = cameraBlob ? URL.createObjectURL(cameraBlob) : null;
-
resolve({
blob: data.blob,
duration: data.duration,
@@ -165,14 +159,13 @@ export async function loadVideoFromIndexedDB(): Promise<{
resolve(null);
}
};
-
getRequest.onerror = () => {
db.close();
reject(getRequest.error);
};
});
} catch (error) {
- console.error("Error al cargar video desde la base de datos:", error);
+ console.error("Error loading video from database:", error);
return null;
}
}
@@ -181,17 +174,14 @@ export async function deleteRecordedVideo(): Promise<void> {
try {
const db = await getDB();
const storeName = "videos";
-
if (!db.objectStoreNames.contains(storeName)) {
db.close();
return;
}
-
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], "readwrite");
const store = transaction.objectStore(storeName);
const deleteRequest = store.delete("currentVideo");
-
deleteRequest.onsuccess = () => {
db.close();
resolve();
@@ -207,18 +197,17 @@ export async function deleteRecordedVideo(): Promise<void> {
}
const titles = {
- idle: "openvid - Crea tomas cinemáticas",
- countdown: (count: number) => `Grabando en ${count}...`,
- recording: "Grabando...",
- processing: "⏳ Procesando video...",
+ idle: "openvid - Create cinematic takes",
+ countdown: (count: number) => `Recording in ${count}...`,
+ recording: "Recording...",
+ processing: "⏳ Processing video...",
};
function pickSupportedMimeType(preferred: string[]): string | undefined {
for (const mimeType of preferred) {
try {
if (MediaRecorder.isTypeSupported(mimeType)) return mimeType;
- } catch {
- }
+ } catch { }
}
return undefined;
}
@@ -232,7 +221,6 @@ export function useScreenRecording() {
const [cameraConfig, setCameraConfig] = useState<CameraConfig | null>(null);
const router = useRouter();
const pathname = usePathname();
-
const screenRecorderRef = useRef<MediaRecorder | null>(null);
const cameraRecorderRef = useRef<MediaRecorder | null>(null);
const screenChunksRef = useRef<Blob[]>([]);
@@ -277,7 +265,7 @@ export function useScreenRecording() {
setTitle(titles.countdown(countdown));
} else if (state === "recording") {
const timeStr = recordingTime.toString().padStart(2, "0");
- setTitle(`Grabando ${timeStr}s`);
+ setTitle(`Recording ${timeStr}s`);
} else if (state === "processing") {
setTitle(titles.processing);
}
@@ -334,30 +322,27 @@ export function useScreenRecording() {
screenChunksRef.current = [];
cameraChunksRef.current = [];
startTimeRef.current = Date.now();
-
- const screenMime = pickSupportedMimeType([
- "video/webm;codecs=vp9,opus",
- "video/webm;codecs=vp8,opus",
- "video/webm;codecs=vp9",
- "video/webm;codecs=vp8",
- "video/webm",
- ]) || undefined;
-
+ const screenMime =
+ pickSupportedMimeType([
+ "video/webm;codecs=vp9,opus",
+ "video/webm;codecs=vp8,opus",
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8",
+ "video/webm",
+ ]) || undefined;
const screenRecorder = new MediaRecorder(
screenStream,
screenMime ? { mimeType: screenMime } : undefined
);
screenRecorderRef.current = screenRecorder;
-
screenRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
screenChunksRef.current.push(event.data);
}
};
-
screenRecorder.onerror = (event) => {
- console.error("Error del MediaRecorder (pantalla):", event);
- setError("Error durante la grabación");
+ console.error("MediaRecorder error (screen):", event);
+ setError("Error during recording");
setState("idle");
cleanupStreams();
restoreOriginals();
@@ -365,25 +350,24 @@ export function useScreenRecording() {
let cameraRecorder: MediaRecorder | null = null;
if (camStream) {
- const camMime = pickSupportedMimeType([
- "video/webm;codecs=vp9",
- "video/webm;codecs=vp8",
- "video/webm",
- ]) || undefined;
-
+ const camMime =
+ pickSupportedMimeType([
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8",
+ "video/webm",
+ ]) || undefined;
cameraRecorder = new MediaRecorder(
camStream,
camMime ? { mimeType: camMime } : undefined
);
cameraRecorderRef.current = cameraRecorder;
-
cameraRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
cameraChunksRef.current.push(event.data);
}
};
cameraRecorder.onerror = (event) => {
- console.error("Error del MediaRecorder (cámara):", event);
+ console.error("MediaRecorder error (camera):", event);
};
}
@@ -395,72 +379,35 @@ export function useScreenRecording() {
setState("processing");
const duration = (Date.now() - startTimeRef.current) / 1000;
cleanupStreams();
-
try {
- const rawScreenBlob = screenBlob || new Blob([], { type: screenMime || "video/webm" });
-
- const arrayBuffer = await rawScreenBlob.arrayBuffer();
- const uint8Array = new Uint8Array(arrayBuffer);
-
- const source = new BufferSource(uint8Array);
-
- const input = new Input({
- source: source,
- formats: ALL_FORMATS
- });
-
- const outputTarget = new BufferTarget();
- const output = new Output({
- format: new Mp4OutputFormat(),
- target: outputTarget,
- });
-
- const conversion = await Conversion.init({
- input,
- output,
- video: {
- hardwareAcceleration: 'prefer-hardware',
- keyFrameInterval: 2,
- },
- audio: {
- codec: 'aac',
- sampleRate: 48000,
- numberOfChannels: 2,
- }
+ const rawScreenBlob =
+ screenBlob || new Blob([], { type: screenMime || "video/webm" });
+ const finalMp4Blob = await convertToMp4(rawScreenBlob);
+ await saveVideoToIndexedDB(finalMp4Blob, duration, {
+ cameraBlob,
+ cameraConfig: cameraConfigRef.current,
});
-
- if (!conversion.isValid) {
- console.error("Pistas descartadas:", conversion.discardedTracks);
- throw new Error("No se pudo iniciar la conversión del video.");
- }
-
- await conversion.execute();
-
- if (!outputTarget.buffer) {
- throw new Error("El buffer de salida es nulo. La conversión falló.");
- }
-
- const finalMp4Blob = new Blob([outputTarget.buffer], { type: 'video/mp4' });
-
await saveVideoToIndexedDB(finalMp4Blob, duration, {
cameraBlob,
cameraConfig: cameraConfigRef.current,
});
-
if (pathname === "/editor") {
window.location.reload();
} else {
router.push("/editor");
}
} catch (err) {
- console.error("Error al procesar el video con Mediabunny:", err);
- setError("Error al procesar el video");
+ console.error("Error processing video with Mediabunny:", err);
+ setError("Error processing video");
setState("idle");
restoreOriginals();
}
};
+
screenRecorder.onstop = () => {
- screenBlob = new Blob(screenChunksRef.current, { type: screenMime || "video/webm" });
+ screenBlob = new Blob(screenChunksRef.current, {
+ type: screenMime || "video/webm",
+ });
pendingCount -= 1;
if (pendingCount <= 0) finalize();
else if (cameraRecorder && cameraRecorder.state !== "inactive") {
@@ -470,25 +417,29 @@ export function useScreenRecording() {
if (cameraRecorder) {
cameraRecorder.onstop = () => {
- cameraBlob = new Blob(cameraChunksRef.current, { type: "video/webm" });
+ cameraBlob = new Blob(cameraChunksRef.current, {
+ type: "video/webm",
+ });
pendingCount -= 1;
if (pendingCount <= 0) finalize();
- else if (screenRecorderRef.current && screenRecorderRef.current.state !== "inactive") {
+ else if (
+ screenRecorderRef.current &&
+ screenRecorderRef.current.state !== "inactive"
+ ) {
screenRecorderRef.current.stop();
}
};
}
setState("recording");
-
setTimeout(() => {
startTimeRef.current = Date.now();
screenRecorder.start(1000);
cameraRecorder?.start(1000);
}, 300);
} catch (err) {
- console.error("Error al iniciar grabación:", err);
- setError(err instanceof Error ? err.message : "No se pudo iniciar la grabación");
+ console.error("Error starting recording:", err);
+ setError(err instanceof Error ? err.message : "Could not start recording");
setState("idle");
cleanupStreams();
restoreOriginals();
@@ -500,14 +451,14 @@ export function useScreenRecording() {
const startCountdown = useCallback(
async (setupArg?: RecordingSetupConfig) => {
const setup: RecordingSetupConfig = setupArg ?? DEFAULT_RECORDING_SETUP;
-
try {
setError(null);
setRecordingTime(0);
-
const screenStream = await navigator.mediaDevices.getDisplayMedia({
video: { displaySurface: "browser" },
- audio: setup.systemAudio ? { echoCancellation: true, noiseSuppression: true } : false,
+ audio: setup.systemAudio
+ ? { echoCancellation: true, noiseSuppression: true }
+ : false,
});
screenStreamRef.current = screenStream;
@@ -519,7 +470,7 @@ export function useScreenRecording() {
setCameraStream(camStream);
setCameraConfig(setup.camera);
} catch (err) {
- console.warn("Cámara denegada, continuando sin cámara:", err);
+ console.warn("Camera denied, continuing without camera:", err);
}
}
@@ -532,7 +483,7 @@ export function useScreenRecording() {
});
micStreamRef.current = micStream;
} catch (err) {
- console.warn("Micrófono denegado, continuando sin micrófono:", err);
+ console.warn("Microphone denied, continuing without microphone:", err);
}
}
@@ -543,18 +494,25 @@ export function useScreenRecording() {
if (needsMixing) {
try {
- const AudioCtx = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
+ const AudioCtx =
+ window.AudioContext ||
+ (window as unknown as { webkitAudioContext: typeof AudioContext })
+ .webkitAudioContext;
const audioCtx = new AudioCtx();
audioCtxRef.current = audioCtx;
const destination = audioCtx.createMediaStreamDestination();
if (screenAudioTracks.length > 0) {
- const screenSource = audioCtx.createMediaStreamSource(new MediaStream(screenAudioTracks));
+ const screenSource = audioCtx.createMediaStreamSource(
+ new MediaStream(screenAudioTracks)
+ );
screenSource.connect(destination);
}
if (micAudioTracks.length > 0) {
- const micSource = audioCtx.createMediaStreamSource(new MediaStream(micAudioTracks));
+ const micSource = audioCtx.createMediaStreamSource(
+ new MediaStream(micAudioTracks)
+ );
const micGain = audioCtx.createGain();
micGain.gain.value = setup.microphone.volume;
micSource.connect(micGain);
@@ -566,7 +524,7 @@ export function useScreenRecording() {
...destination.stream.getAudioTracks(),
]);
} catch (err) {
- console.warn("Error al mezclar audio, usando solo audio de pantalla:", err);
+ console.warn("Error mixing audio, using only screen audio:", err);
finalScreenStream = screenStream;
}
}
@@ -593,8 +551,8 @@ export function useScreenRecording() {
}
}, 1000);
} catch (err) {
- console.error("Error al iniciar captura:", err);
- setError("No se pudo iniciar la captura de pantalla");
+ console.error("Error starting capture:", err);
+ setError("Could not start screen capture");
setState("idle");
cleanupStreams();
restoreOriginals();
diff --git a/hooks/useVideoExport.ts b/hooks/useVideoExport.ts
index 5d19506..ab3cb6e 100644
--- a/hooks/useVideoExport.ts
+++ b/hooks/useVideoExport.ts
@@ -77,7 +77,7 @@ export function useVideoExport(
setExportProgress({
status: "error",
progress: 0,
- message: "No hay video para exportar",
+ message: "No video available to export",
});
isExportingRef.current = false;
return;
@@ -87,7 +87,7 @@ export function useVideoExport(
setExportProgress({
status: "error",
progress: 0,
- message: "El video no está cargado correctamente",
+ message: "Video is not loaded correctly",
});
isExportingRef.current = false;
return;
@@ -98,7 +98,7 @@ export function useVideoExport(
setExportProgress({
status: "error",
progress: 0,
- message: "Error al obtener el canvas de exportación",
+ message: "Failed to get the export canvas",
});
isExportingRef.current = false;
return;
@@ -111,19 +111,19 @@ export function useVideoExport(
setExportProgress({
status: "preparing",
progress: 2,
- message: "Preparando video...",
+ message: "Preparing video...",
});
await ensureVideoReady(video);
if (cancellationRef.current.cancelled) {
- throw new Error("Exportación cancelada");
+ throw new Error("Export cancelled");
}
setExportProgress({
status: "preparing",
progress: 5,
- message: "Configurando exportación...",
+ message: "Configuring export...",
});
const originalWidth = exportCanvas.width;
@@ -199,11 +199,11 @@ export function useVideoExport(
message: "",
});
} else {
- console.error("Error durante la exportación:", error);
+ console.error("Error during export:", error);
setExportProgress({
status: "error",
progress: 0,
- message: error instanceof Error ? error.message : "Error durante la exportación",
+ message: error instanceof Error ? error.message : "Error during export",
});
}
} finally {
@@ -247,7 +247,7 @@ async function exportWithFFmpegWebM(
const outputDuration = duration / speed;
const totalFrames = Math.ceil(outputDuration * fps);
- setProgress({ status: "preparing", progress: 3, message: "Cargando motor WebM..." });
+ setProgress({ status: "preparing", progress: 3, message: "Loading WebM engine..." });
const ffmpegBase = `${window.location.origin}/ffmpeg`;
await ffmpeg.load({
@@ -259,7 +259,7 @@ async function exportWithFFmpegWebM(
video.currentTime = trimStart;
await waitForVideoFrame(video);
for (let i = 0; i < totalFrames; i++) {
- if (cancellation.cancelled) throw new Error("Exportación cancelada");
+ if (cancellation.cancelled) throw new Error("Export cancelled");
const outputTime = i / fps;
const contentOffset = Math.min(outputTime * speed, duration - 0.001);
@@ -282,7 +282,7 @@ async function exportWithFFmpegWebM(
setProgress({
status: "encoding",
progress: 8 + Math.round((i / totalFrames) * 60),
- message: `[Paso 1/2] Guardando frame ${i + 1} de ${totalFrames}...`,
+ message: `[Step 1/2] Saving frame ${i + 1} of ${totalFrames}...`,
});
}
@@ -297,12 +297,12 @@ async function exportWithFFmpegWebM(
setProgress({
status: "finalizing",
progress: Math.min(encodingProgress, 90),
- message: `[Paso 2/2] Codificando VP8 con transparencia...`,
+ message: `[Step 2/2] Encoding VP8 with transparency...`,
});
}
});
- setProgress({ status: "finalizing", progress: 70, message: "[Paso 2/2] Iniciando codificación VP8..." });
+ setProgress({ status: "finalizing", progress: 70, message: "[Step 2/2] Starting VP8 encoding..." });
try {
await ffmpeg.exec([
@@ -320,19 +320,19 @@ async function exportWithFFmpegWebM(
for (let i = 0; i < totalFrames; i++) {
await ffmpeg.deleteFile(`frame${String(i).padStart(5, "0")}.png`);
}
- } catch { /* ignorar errores de limpieza */ }
+ } catch { /* ignore cleanup errors */ }
}
- setProgress({ status: "finalizing", progress: 94, message: "Preparando descarga..." });
+ setProgress({ status: "finalizing", progress: 94, message: "Preparing download..." });
const webmData = (await ffmpeg.readFile("output.webm")) as Uint8Array;
const webmBlob = new Blob([new Uint8Array(webmData)], { type: "video/webm" });
- try { await ffmpeg.deleteFile("output.webm"); } catch { /* ignorar */ }
+ try { await ffmpeg.deleteFile("output.webm"); } catch { /* ignore */ }
downloadBlob(webmBlob, `video-transparent-${width}x${height}.webm`);
- setProgress({ status: "complete", progress: 100, message: "¡WebM con transparencia exportado!" });
+ setProgress({ status: "complete", progress: 100, message: "Transparent WebM exported!" });
}
async function exportWithMediabunny(
@@ -350,13 +350,13 @@ async function exportWithMediabunny(
speed: number = 1,
): Promise<void> {
if (cancellation.cancelled) {
- throw new Error("Exportación cancelada");
+ throw new Error("Export cancelled");
}
setProgress({
status: "encoding",
progress: 10,
- message: `Iniciando codificación a ${fps} fps...`,
+ message: `Starting encoding at ${fps} fps...`,
});
const outputDuration = duration / speed;
@@ -389,7 +389,7 @@ async function exportWithMediabunny(
for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
if (cancellation.cancelled) {
- throw new Error("Exportación cancelada");
+ throw new Error("Export cancelled");
}
const outputTime = frameIndex / fps;
@@ -410,7 +410,7 @@ async function exportWithMediabunny(
setProgress({
status: "encoding",
progress,
- message: `Codificando ${frameIndex + 1}/${totalFrames} frames (${fps}fps)...`,
+ message: `Encoding ${frameIndex + 1}/${totalFrames} frames (${fps}fps)...`,
});
}
@@ -420,31 +420,31 @@ async function exportWithMediabunny(
}
if (cancellation.cancelled) {
- throw new Error("Exportación cancelada");
+ throw new Error("Export cancelled");
}
setProgress({
status: "finalizing",
progress: 92,
- message: "Finalizando codificación...",
+ message: "Finalizing encoding...",
});
await output.finalize();
if (cancellation.cancelled) {
- throw new Error("Exportación cancelada");
+ throw new Error("Export cancelled");
}
setProgress({
status: "finalizing",
progress: 96,
- message: "Generando archivo MP4...",
+ message: "Generating MP4 file...",
});
const buffer = (output.target as BufferTarget).buffer;
if (!buffer) {
- throw new Error("No se pudo generar el archivo MP4");
+ throw new Error("Failed to generate the MP4 file");
}
const blob = new Blob([buffer], { type: "video/mp4" });
@@ -453,7 +453,7 @@ async function exportWithMediabunny(
setProgress({
status: "complete",
progress: 100,
- message: "¡Exportación completada!",
+ message: "Export complete!",
});
}
@@ -501,13 +501,13 @@ async function exportWithMediabunnyAndAudio(
}
if (cancellation.cancelled) {
- throw new Error("Exportación cancelada");
+ throw new Error("Export cancelled");
}
setProgress({
status: "encoding",
progress: 5,
- message: hasMultipleClips ? `Preparando exportación multi-clip...` : `Preparando exportación con audio...`,
+ message: hasMultipleClips ? `Preparing multi-clip export...` : `Preparing export with audio...`,
});
const outputDuration = duration / speed;
@@ -537,123 +537,140 @@ async function exportWithMediabunnyAndAudio(
video.pause();
let currentClipId: string | null = null;
+ // Tracks the object URL currently assigned to `video.src` during a
+ // multi-clip export, so we can revoke it as soon as it's replaced or
+ // as soon as the export finishes — instead of leaking one blob: URL
+ // per clip switch for the whole duration of the export.
+ let currentClipBlobUrl: string | null = null;
+
+ const loadClipBlob = async (blob: Blob): Promise<void> => {
+ if (currentClipBlobUrl) {
+ URL.revokeObjectURL(currentClipBlobUrl);
+ }
+ const blobUrl = URL.createObjectURL(blob);
+ currentClipBlobUrl = blobUrl;
+ video.pause();
+ video.src = blobUrl;
+ await new Promise<void>((resolve, reject) => {
+ video.onloadedmetadata = () => resolve();
+ video.onerror = () => reject(new Error("Failed to load video"));
+ });
+ };
- if (hasMultipleClips && clips.length > 0) {
- const sortedClips = [...clips].sort((a, b) => a.startTime - b.startTime);
- const firstClip = sortedClips[0];
- if (firstClip && clipBlobs) {
- const blob = clipBlobs.get(firstClip.libraryVideoId);
- if (blob) {
- const blobUrl = URL.createObjectURL(blob);
- video.src = blobUrl;
- await new Promise<void>((resolve, reject) => {
- video.onloadedmetadata = () => resolve();
- video.onerror = () => reject(new Error("Failed to load video"));
- });
- currentClipId = firstClip.id;
+ try {
+ if (hasMultipleClips && clips.length > 0) {
+ const sortedClips = [...clips].sort((a, b) => a.startTime - b.startTime);
+ const firstClip = sortedClips[0];
+ if (firstClip && clipBlobs) {
+ const blob = clipBlobs.get(firstClip.libraryVideoId);
+ if (blob) {
+ await loadClipBlob(blob);
+ currentClipId = firstClip.id;
+ }
}
+ video.currentTime = clips[0]?.trimStart || 0;
+ } else {
+ video.currentTime = trimStart;
}
- video.currentTime = clips[0]?.trimStart || 0;
- } else {
- video.currentTime = trimStart;
- }
- await waitForVideoFrame(video);
+ await waitForVideoFrame(video);
- const lockedWidth = canvas.width;
- const lockedHeight = canvas.height;
+ const lockedWidth = canvas.width;
+ const lockedHeight = canvas.height;
- for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
- if (cancellation.cancelled) {
- throw new Error("Exportación cancelada");
- }
+ for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
+ if (cancellation.cancelled) {
+ throw new Error("Export cancelled");
+ }
- const outputTime = frameIndex / fps;
- const contentOffset = Math.min(outputTime * speed, duration - 0.001);
- const timelineTime = trimStart + contentOffset;
+ const outputTime = frameIndex / fps;
+ const contentOffset = Math.min(outputTime * speed, duration - 0.001);
+ const timelineTime = trimStart + contentOffset;
+
+ if (hasMultipleClips && clipBlobs) {
+ const activeClipInfo = getActiveClipAtTime(clips, timelineTime);
- if (hasMultipleClips && clipBlobs) {
- const activeClipInfo = getActiveClipAtTime(clips, timelineTime);
-
- if (activeClipInfo) {
- const { clip, clipTime } = activeClipInfo;
-
- if (clip.id !== currentClipId) {
- const newBlob = clipBlobs.get(clip.libraryVideoId);
- if (newBlob) {
- const blobUrl = URL.createObjectURL(newBlob);
- video.pause();
- video.src = blobUrl;
- await new Promise<void>((resolve, reject) => {
- video.onloadedmetadata = () => resolve();
- video.onerror = () => reject(new Error("Failed to load video"));
- });
- currentClipId = clip.id;
+ if (activeClipInfo) {
+ const { clip, clipTime } = activeClipInfo;
+
+ if (clip.id !== currentClipId) {
+ const newBlob = clipBlobs.get(clip.libraryVideoId);
+ if (newBlob) {
+ await loadClipBlob(newBlob);
+ currentClipId = clip.id;
+ }
}
- }
- video.currentTime = clipTime;
- await waitForVideoFrame(video);
+ video.currentTime = clipTime;
+ await waitForVideoFrame(video);
+ }
}
- }
- if (canvas.width !== lockedWidth || canvas.height !== lockedHeight) {
- canvas.width = lockedWidth;
- canvas.height = lockedHeight;
- }
+ if (canvas.width !== lockedWidth || canvas.height !== lockedHeight) {
+ canvas.width = lockedWidth;
+ canvas.height = lockedHeight;
+ }
- await canvasHandle.drawFrame(true, timelineTime);
- await videoSource.add(outputTime, frameDuration);
+ await canvasHandle.drawFrame(true, timelineTime);
+ await videoSource.add(outputTime, frameDuration);
- if (!hasMultipleClips) {
- const nextFrame = frameIndex + 1;
- if (nextFrame < totalFrames) {
- const nextContentOffset = Math.min((nextFrame / fps) * speed, duration - 0.001);
- video.currentTime = trimStart + nextContentOffset;
+ if (!hasMultipleClips) {
+ const nextFrame = frameIndex + 1;
+ if (nextFrame < totalFrames) {
+ const nextContentOffset = Math.min((nextFrame / fps) * speed, duration - 0.001);
+ video.currentTime = trimStart + nextContentOffset;
+ }
}
- }
- if (frameIndex % 10 === 0 || frameIndex === totalFrames - 1) {
- const progress = 5 + Math.round((frameIndex / totalFrames) * 50);
- setProgress({
- status: "encoding",
- progress,
- message: hasMultipleClips
- ? `Codificando clips ${frameIndex + 1}/${totalFrames}...`
- : `Codificando video ${frameIndex + 1}/${totalFrames}...`,
- });
- }
+ if (frameIndex % 10 === 0 || frameIndex === totalFrames - 1) {
+ const progress = 5 + Math.round((frameIndex / totalFrames) * 50);
+ setProgress({
+ status: "encoding",
+ progress,
+ message: hasMultipleClips
+ ? `Encoding clips ${frameIndex + 1}/${totalFrames}...`
+ : `Encoding video ${frameIndex + 1}/${totalFrames}...`,
+ });
+ }
- if (!hasMultipleClips) {
- const nextFrame = frameIndex + 1;
- if (nextFrame < totalFrames) {
- await waitForVideoFrame(video);
+ if (!hasMultipleClips) {
+ const nextFrame = frameIndex + 1;
+ if (nextFrame < totalFrames) {
+ await waitForVideoFrame(video);
+ }
}
}
+ } finally {
+ // Always release the last clip's object URL — whether the loop
+ // finished normally, was cancelled, or threw.
+ if (currentClipBlobUrl) {
+ URL.revokeObjectURL(currentClipBlobUrl);
+ currentClipBlobUrl = null;
+ }
}
if (cancellation.cancelled) {
- throw new Error("Exportación cancelada");
+ throw new Error("Export cancelled");
}
setProgress({
status: "finalizing",
progress: 56,
- message: "Finalizando video...",
+ message: "Finalizing video...",
});
await output.finalize();
const buffer = (output.target as BufferTarget).buffer;
if (!buffer) {
- throw new Error("No se pudo generar el archivo de video");
+ throw new Error("Failed to generate the video file");
}
const videoBlob = new Blob([buffer], { type: "video/mp4" });
if (!needsAudioMixing) {
downloadBlob(videoBlob, `openvid-${width}x${height}.mp4`);
- setProgress({ status: "complete", progress: 100, message: "¡Exportación completada!" });
+ setProgress({ status: "complete", progress: 100, message: "Export complete!" });
return;
}
@@ -672,7 +689,7 @@ async function exportWithMediabunnyAndAudio(
if (!hasUsableSourceBlob && !hasUsableMultiClipAudio && !hasUsableAudioTracks) {
downloadBlob(videoBlob, `openvid-${width}x${height}.mp4`);
- setProgress({ status: "complete", progress: 100, message: "¡Exportación completada!" });
+ setProgress({ status: "complete", progress: 100, message: "Export complete!" });
return;
}
@@ -680,7 +697,7 @@ async function exportWithMediabunnyAndAudio(
setProgress({
status: "finalizing",
progress: 60,
- message: "Cargando motor de audio...",
+ message: "Loading audio engine...",
});
const ffmpeg = new FFmpeg();
@@ -764,7 +781,7 @@ async function exportWithMediabunnyAndAudio(
setProgress({
status: "finalizing",
progress: 70,
- message: "Mezclando audio...",
+ message: "Mixing audio...",
});
const ffmpegArgs: string[] = ["-i", "video.mp4"];
@@ -820,7 +837,7 @@ async function exportWithMediabunnyAndAudio(
const totalAudioInputs = audioInputs.length;
if (totalAudioInputs === 0) {
downloadBlob(videoBlob, `openvid-${width}x${height}.mp4`);
- setProgress({ status: "complete", progress: 100, message: "¡Exportación completada!" });
+ setProgress({ status: "complete", progress: 100, message: "Export complete!" });
return;
} else if (audioInputs.length > 0) {
filterComplex += `${audioInputs.join("")}amix=inputs=${audioInputs.length}:duration=longest:dropout_transition=0:normalize=0,atrim=0:${outputDuration.toFixed(3)},asetpts=PTS-STARTPTS[aout]`;
@@ -842,7 +859,7 @@ async function exportWithMediabunnyAndAudio(
setProgress({
status: "finalizing",
progress: Math.min(mixProgress, 95),
- message: `Procesando audio... ${Math.round(progress * 100)}%`,
+ message: `Processing audio... ${Math.round(progress * 100)}%`,
});
}
});
@@ -855,7 +872,7 @@ async function exportWithMediabunnyAndAudio(
setProgress({
status: "complete",
progress: 100,
- message: "¡Exportación completada (sin mezcla de audio)!",
+ message: "Export complete (without audio mixing)!",
});
return;
}
@@ -863,7 +880,7 @@ async function exportWithMediabunnyAndAudio(
setProgress({
status: "finalizing",
progress: 96,
- message: "Preparando descarga...",
+ message: "Preparing download...",
});
const outputData = (await ffmpeg.readFile("output.mp4")) as Uint8Array;
@@ -886,7 +903,7 @@ async function exportWithMediabunnyAndAudio(
setProgress({
status: "complete",
progress: 100,
- message: "¡Exportación con audio completada!",
+ message: "Export with audio complete!",
});
} catch (ffmpegError) {
console.warn("FFmpeg audio processing failed, exporting video only:", ffmpegError);
@@ -894,7 +911,7 @@ async function exportWithMediabunnyAndAudio(
setProgress({
status: "complete",
progress: 100,
- message: "¡Exportación completada (sin audio)!",
+ message: "Export complete (without audio)!",
});
}
}
@@ -909,7 +926,7 @@ function canvasToBlobFast(canvas: HTMLCanvasElement): Promise<Blob> {
canvas.toBlob(
(blob) => {
if (blob) resolve(blob);
- else reject(new Error("Error al convertir canvas a imagen"));
+ else reject(new Error("Failed to convert canvas to image"));
},
"image/jpeg",
0.95
@@ -935,9 +952,9 @@ async function exportWithFFmpegGif(
const totalFrames = Math.ceil(outputDuration * fps);
try {
- if (cancellation.cancelled) throw new Error("Exportación cancelada");
+ if (cancellation.cancelled) throw new Error("Export cancelled");
- setProgress({ status: "preparing", progress: 3, message: "Cargando motor de exportación GIF..." });
+ setProgress({ status: "preparing", progress: 3, message: "Loading GIF export engine..." });
const baseURL = `${window.location.origin}/ffmpeg`;
@@ -946,14 +963,14 @@ async function exportWithFFmpegGif(
wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
});
- setProgress({ status: "encoding", progress: 8, message: `Capturando ${totalFrames} frames...` });
+ setProgress({ status: "encoding", progress: 8, message: `Capturing ${totalFrames} frames...` });
video.pause();
video.currentTime = trimStart;
await waitForVideoFrame(video);
for (let i = 0; i < totalFrames; i++) {
- if (cancellation.cancelled) throw new Error("Exportación cancelada");
+ if (cancellation.cancelled) throw new Error("Export cancelled");
const outputTime = i / fps;
const contentOffset = Math.min(outputTime * speed, duration - 0.001);
@@ -975,7 +992,7 @@ async function exportWithFFmpegGif(
setProgress({
status: "encoding",
progress,
- message: `Capturando frame ${i + 1}/${totalFrames}...`,
+ message: `Capturing frame ${i + 1}/${totalFrames}...`,
});
}
@@ -984,7 +1001,7 @@ async function exportWithFFmpegGif(
}
}
- setProgress({ status: "finalizing", progress: 60, message: "Generando paleta de colores óptima..." });
+ setProgress({ status: "finalizing", progress: 60, message: "Generating optimal color palette..." });
await ffmpeg.exec([
"-f", "image2",
@@ -994,9 +1011,9 @@ async function exportWithFFmpegGif(
"palette.png",
]);
- if (cancellation.cancelled) throw new Error("Exportación cancelada");
+ if (cancellation.cancelled) throw new Error("Export cancelled");
- setProgress({ status: "finalizing", progress: 78, message: "Sintetizando GIF animado..." });
+ setProgress({ status: "finalizing", progress: 78, message: "Synthesizing animated GIF..." });
await ffmpeg.exec([
"-f", "image2",
@@ -1007,13 +1024,13 @@ async function exportWithFFmpegGif(
"output.gif",
]);
- setProgress({ status: "finalizing", progress: 94, message: "Descargando GIF..." });
+ setProgress({ status: "finalizing", progress: 94, message: "Downloading GIF..." });
const gifData = (await ffmpeg.readFile("output.gif")) as Uint8Array;
const gifBlob = new Blob([new Uint8Array(gifData)], { type: "image/gif" });
downloadBlob(gifBlob, `animation-${width}x${height}.gif`);
- setProgress({ status: "complete", progress: 100, message: "¡GIF exportado exitosamente!" });
+ setProgress({ status: "complete", progress: 100, message: "GIF exported successfully!" });
} finally {
if (ffmpeg.loaded) {
@@ -1024,7 +1041,7 @@ async function exportWithFFmpegGif(
await ffmpeg.deleteFile(`frame${String(i).padStart(5, "0")}.jpg`);
}
} catch (e) {
- console.warn("Error limpiando archivos temporales de FFmpeg", e);
+ console.warn("Error cleaning up temporary FFmpeg files", e);
}
}
}
diff --git a/hooks/useVideoThumbnails.ts b/hooks/useVideoThumbnails.ts
index 93c4646..ac934dd 100644
--- a/hooks/useVideoThumbnails.ts
+++ b/hooks/useVideoThumbnails.ts
@@ -283,21 +283,31 @@ export function useVideoThumbnails(
}, [videoUrl, duration, interval, quality, customWidth, progressive, videoId, generateThumbnailsAtQuality]);
// Generate thumbnails when video URL or videoId changes
+ const prevVideoUrlRef = useRef<string | null>(null);
+
useEffect(() => {
- if (videoUrl && duration > 0) {
- setLowQualityThumbnails([]);
- setHighQualityThumbnails([]);
- setProgress(0);
+ const timer = setTimeout(() => {
+ if (!videoUrl) {
+ setLowQualityThumbnails([]);
+ setHighQualityThumbnails([]);
+ setProgress(0);
+ return;
+ }
- generateThumbnails();
- } else if (!videoUrl) {
- // Clear thumbnails when video is removed
- setLowQualityThumbnails([]);
- setHighQualityThumbnails([]);
- setProgress(0);
- }
+ if (videoUrl !== prevVideoUrlRef.current) {
+ setLowQualityThumbnails([]);
+ setHighQualityThumbnails([]);
+ setProgress(0);
+ prevVideoUrlRef.current = videoUrl;
+ }
+
+ if (duration > 0) {
+ generateThumbnails();
+ }
+ }, 0);
return () => {
+ clearTimeout(timer);
abortRef.current = true;
};
}, [videoUrl, duration, videoId, generateThumbnails]);
diff --git a/lib/video-conversion.ts b/lib/video-conversion.ts
new file mode 100644
index 0000000..a23bb16
--- /dev/null
+++ b/lib/video-conversion.ts
@@ -0,0 +1,99 @@
+import {
+ Input,
+ Output,
+ Mp4OutputFormat,
+ BufferTarget,
+ Conversion,
+ ALL_FORMATS,
+ BlobSource,
+ MP4,
+} from "mediabunny";
+
+const TARGET_VIDEO_CODEC = "avc";
+const TARGET_AUDIO_CODEC = "aac";
+
+export interface VideoFormatCheck {
+ needsConversion: boolean;
+ reason?: string;
+}
+
+export async function checkVideoFormat(file: Blob): Promise<VideoFormatCheck> {
+ const input = new Input({ source: new BlobSource(file), formats: ALL_FORMATS });
+ try {
+ const format = await input.getFormat();
+ if (format !== MP4) {
+ return { needsConversion: true, reason: `non-MP4 container (${format.name})` };
+ }
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (!videoTrack) {
+ return { needsConversion: true, reason: "no readable video track found" };
+ }
+ const videoCodec = await videoTrack.getCodec();
+ const videoDecodable = await videoTrack.canDecode();
+ if (videoCodec !== TARGET_VIDEO_CODEC || !videoDecodable) {
+ return { needsConversion: true, reason: `video codec ${videoCodec ?? "unknown"}` };
+ }
+ const audioTrack = await input.getPrimaryAudioTrack();
+ if (audioTrack) {
+ const audioCodec = await audioTrack.getCodec();
+ const audioDecodable = await audioTrack.canDecode();
+ if (audioCodec !== TARGET_AUDIO_CODEC || !audioDecodable) {
+ return { needsConversion: true, reason: `audio codec ${audioCodec ?? "unknown"}` };
+ }
+ }
+ return { needsConversion: false };
+ } catch (err) {
+ console.warn("Could not inspect the video, forcing conversion instead:", err);
+ return { needsConversion: true, reason: "failed to read the file" };
+ } finally {
+ input.dispose();
+ }
+}
+
+export async function convertToMp4(file: Blob): Promise<Blob> {
+ const input = new Input({ source: new BlobSource(file), formats: ALL_FORMATS });
+ try {
+ const outputTarget = new BufferTarget();
+ const output = new Output({ format: new Mp4OutputFormat(), target: outputTarget });
+
+ const conversion = await Conversion.init({
+ input,
+ output,
+ video: { hardwareAcceleration: "prefer-hardware", keyFrameInterval: 2 },
+ audio: { codec: "aac", sampleRate: 48000, numberOfChannels: 2 },
+ });
+
+ if (!conversion.isValid) {
+ console.error("Discarded tracks:", conversion.discardedTracks);
+ throw new Error("Could not convert the video to MP4.");
+ }
+
+ await conversion.execute();
+
+ if (!outputTarget.buffer) {
+ throw new Error("The output buffer is null. Conversion failed.");
+ }
+
+ return new Blob([outputTarget.buffer], { type: "video/mp4" });
+ } finally {
+ input.dispose();
+ }
+}
+
+export interface NormalizeResult {
+ blob: Blob;
+ wasConverted: boolean;
+ reason?: string;
+}
+
+export async function normalizeVideoFile(file: Blob): Promise<NormalizeResult> {
+ const { needsConversion, reason } = await checkVideoFormat(file);
+
+ if (!needsConversion) {
+ return { blob: file, wasConverted: false };
+ }
+
+ console.info(`Normalizing video to MP4/H.264 — reason: ${reason}`);
+ const mp4Blob = await convertToMp4(file);
+ return { blob: mp4Blob, wasConverted: true, reason };
+}
diff --git a/lib/video-upload-cache.ts b/lib/video-upload-cache.ts
index b991136..4835dbb 100644
--- a/lib/video-upload-cache.ts
+++ b/lib/video-upload-cache.ts
@@ -1,3 +1,5 @@
+import { normalizeVideoFile } from "./video-conversion";
+
const DB_NAME = "openvid-uploaded-videos";
const DB_VERSION = 1;
const STORE_NAME = "videos";
@@ -46,7 +48,7 @@ async function openDB(): Promise<IDBDatabase> {
request.onerror = () => reject(request.error);
request.onsuccess = () => {
dbInstance = request.result;
- cleanupOldUploadCache(dbInstance).catch(() => {});
+ cleanupOldUploadCache(dbInstance).catch(() => { });
resolve(request.result);
};
@@ -67,7 +69,7 @@ function calculateAspectRatio(width: number, height: number): string {
return `${width / divisor}/${height / divisor}`;
}
-async function getVideoMetadata(file: File): Promise<{
+async function getVideoMetadata(source: Blob): Promise<{
duration: number;
width: number;
height: number;
@@ -76,7 +78,14 @@ async function getVideoMetadata(file: File): Promise<{
return new Promise((resolve, reject) => {
const video = document.createElement("video");
video.preload = "metadata";
-
+ const url = URL.createObjectURL(source);
+
+ const cleanup = () => {
+ video.removeAttribute("src");
+ video.load();
+ URL.revokeObjectURL(url);
+ };
+
video.onloadedmetadata = () => {
const metadata = {
duration: video.duration,
@@ -84,31 +93,34 @@ async function getVideoMetadata(file: File): Promise<{
height: video.videoHeight,
aspectRatio: calculateAspectRatio(video.videoWidth, video.videoHeight),
};
-
- URL.revokeObjectURL(video.src);
+ cleanup();
resolve(metadata);
};
-
video.onerror = () => {
- URL.revokeObjectURL(video.src);
+ cleanup();
reject(new Error("Failed to load video metadata"));
};
-
- video.src = URL.createObjectURL(file);
+ video.src = url;
});
}
export async function saveUploadedVideo(file: File): Promise<CachedUploadedVideo> {
try {
const db = await openDB();
-
- const metadata = await getVideoMetadata(file);
-
+
+ const { blob: normalizedBlob, wasConverted } = await normalizeVideoFile(file);
+
+ const metadata = await getVideoMetadata(normalizedBlob);
+
+ const fileName = wasConverted
+ ? `${file.name.replace(/\.[^/.]+$/, "")}.mp4`
+ : file.name;
+
const data: CachedUploadedVideo = {
key: SINGLE_VIDEO_KEY,
- blob: file,
- fileName: file.name,
- fileSize: file.size,
+ blob: normalizedBlob,
+ fileName,
+ fileSize: normalizedBlob.size,
duration: metadata.duration,
width: metadata.width,
height: metadata.height,
@@ -119,14 +131,13 @@ export async function saveUploadedVideo(file: File): Promise<CachedUploadedVideo
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, "readwrite");
const store = transaction.objectStore(STORE_NAME);
-
const request = store.put(data);
-
- request.onerror = () => reject(request.error);
+ request.onerror = () => {
+ reject(request.error);
+ };
request.onsuccess = () => resolve(data);
});
} catch (error) {
- console.error("Failed to save uploaded video:", error);
throw error;
}
}
@@ -183,7 +194,7 @@ export async function getUploadedVideoInfo(): Promise<{
} | null> {
const video = await getUploadedVideo();
if (!video) return null;
-
+
return {
fileName: video.fileName,
fileSize: video.fileSize,
diff --git a/lib/videos-library.ts b/lib/videos-library.ts
index 4865c9a..c7177d8 100644
--- a/lib/videos-library.ts
+++ b/lib/videos-library.ts
@@ -1,4 +1,5 @@
import { ExtendedVideoForDetection, LibraryVideo, LibraryVideoInfo } from "@/types";
+import { normalizeVideoFile } from "./video-conversion";
const DB_NAME = "openvid-videos-library";
const DB_VERSION = 3;
@@ -39,7 +40,7 @@ async function openDB(): Promise<IDBDatabase> {
request.onerror = () => reject(request.error);
request.onsuccess = () => {
dbInstance = request.result;
- cleanupOldLibraryEntries(dbInstance).catch(() => {});
+ cleanupOldLibraryEntries(dbInstance).catch(() => { });
resolve(request.result);
};
@@ -87,6 +88,13 @@ async function getVideoMetadata(file: File): Promise<{
return new Promise((resolve, reject) => {
const video = document.createElement("video");
video.preload = "metadata";
+ const url = URL.createObjectURL(file);
+
+ const cleanup = () => {
+ video.removeAttribute("src");
+ video.load();
+ URL.revokeObjectURL(url);
+ };
video.onloadedmetadata = () => {
const metadata = {
@@ -95,16 +103,16 @@ async function getVideoMetadata(file: File): Promise<{
height: video.videoHeight,
aspectRatio: "auto",
};
- URL.revokeObjectURL(video.src);
+ cleanup();
resolve(metadata);
};
video.onerror = () => {
- URL.revokeObjectURL(video.src);
+ cleanup();
reject(new Error("Failed to load video metadata"));
};
- video.src = URL.createObjectURL(file);
+ video.src = url;
});
}
@@ -113,56 +121,57 @@ async function generateThumbnail(blob: Blob): Promise<string> {
const video = document.createElement("video");
video.preload = "metadata";
video.muted = true;
+ const url = URL.createObjectURL(blob);
+
+ const cleanup = () => {
+ video.removeAttribute("src");
+ video.load();
+ URL.revokeObjectURL(url);
+ };
video.onloadeddata = () => {
const seekTime = video.duration * 0.1;
- if (!isFinite(seekTime) || seekTime < 0) {
- video.currentTime = 0;
- } else {
- video.currentTime = seekTime;
- }
+ video.currentTime = !isFinite(seekTime) || seekTime < 0 ? 0 : seekTime;
};
video.onseeked = () => {
const canvas = document.createElement("canvas");
const aspectRatio = video.videoWidth / video.videoHeight;
-
canvas.width = 320;
canvas.height = Math.round(320 / aspectRatio);
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
-
const thumbnailUrl = canvas.toDataURL("image/jpeg", 0.9);
- URL.revokeObjectURL(video.src);
+ cleanup();
resolve(thumbnailUrl);
} else {
- URL.revokeObjectURL(video.src);
+ cleanup();
reject(new Error("Failed to get canvas context"));
}
};
video.onerror = () => {
- URL.revokeObjectURL(video.src);
+ cleanup();
reject(new Error("Failed to load video for thumbnail"));
};
- video.src = URL.createObjectURL(blob);
+ video.src = url;
});
}
export async function addVideoToLibrary(file: File): Promise<LibraryVideo> {
const db = await openDB();
const metadata = await getVideoMetadata(file);
-
+
let thumbnailUrl: string | undefined;
try {
thumbnailUrl = await generateThumbnail(file);
} catch (e) {
console.warn("Failed to generate thumbnail:", e);
}
-
+
let hasAudio = false;
try {
hasAudio = await detectVideoHasAudio(file);
@@ -170,11 +179,14 @@ export async function addVideoToLibrary(file: File): Promise<LibraryVideo> {
console.warn("Failed to detect audio:", e);
}
+ const { blob: normalizedBlob, wasConverted } = await normalizeVideoFile(file);
+ const fileName = wasConverted ? `${file.name.replace(/\.[^/.]+$/, "")}.mp4` : file.name;
+
const video: LibraryVideo = {
id: generateVideoId(),
- blob: file,
- fileName: file.name,
- fileSize: file.size,
+ blob: normalizedBlob,
+ fileName,
+ fileSize: normalizedBlob.size,
duration: metadata.duration,
width: metadata.width,
height: metadata.height,
@@ -189,7 +201,6 @@ export async function addVideoToLibrary(file: File): Promise<LibraryVideo> {
const transaction = db.transaction(STORE_NAME, "readwrite");
const store = transaction.objectStore(STORE_NAME);
const request = store.add(video);
-
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(video);
});
@@ -204,16 +215,18 @@ export interface AddVideoWithMetadataOptions {
hasAudio?: boolean;
}
-export async function addVideoToLibraryWithMetadata(options: AddVideoWithMetadataOptions): Promise<LibraryVideo> {
+export async function addVideoToLibraryWithMetadata(
+ options: AddVideoWithMetadataOptions
+): Promise<LibraryVideo> {
const db = await openDB();
-
+
let thumbnailUrl: string | undefined;
try {
thumbnailUrl = await generateThumbnail(options.blob);
} catch (e) {
console.warn("Failed to generate thumbnail:", e);
}
-
+
let hasAudio = options.hasAudio;
if (hasAudio === undefined) {
try {
@@ -224,18 +237,23 @@ export async function addVideoToLibraryWithMetadata(options: AddVideoWithMetadat
}
}
+ const { blob: normalizedBlob, wasConverted } = await normalizeVideoFile(options.blob);
+ const fileName = wasConverted
+ ? `${options.fileName.replace(/\.[^/.]+$/, "")}.mp4`
+ : options.fileName;
+
const video: LibraryVideo = {
id: generateVideoId(),
- blob: options.blob,
- fileName: options.fileName,
- fileSize: options.blob.size,
+ blob: normalizedBlob,
+ fileName,
+ fileSize: normalizedBlob.size,
duration: options.duration,
width: options.width,
height: options.height,
aspectRatio: "auto",
uploadedAt: Date.now(),
thumbnailUrl,
- hasAudio: hasAudio,
+ hasAudio,
originalHasAudio: hasAudio,
};
@@ -243,7 +261,6 @@ export async function addVideoToLibraryWithMetadata(options: AddVideoWithMetadat
const transaction = db.transaction(STORE_NAME, "readwrite");
const store = transaction.objectStore(STORE_NAME);
const request = store.add(video);
-
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(video);
});
@@ -305,11 +322,12 @@ export async function detectVideoHasAudio(blob: Blob): Promise<boolean> {
if (settled) return;
settled = true;
clearTimeout(timeoutId);
+ video.removeAttribute("src");
+ video.load();
URL.revokeObjectURL(url);
- video.src = "";
resolve(result);
};
-
+
const timeoutId = setTimeout(() => cleanup(false), 8000);
video.addEventListener("loadedmetadata", async () => {
@@ -374,7 +392,7 @@ export async function deleteLibraryVideo(id: string): Promise<void> {
export async function updateVideoAudioState(id: string, hasAudio: boolean): Promise<void> {
const db = await openDB();
const video = await getLibraryVideo(id);
-
+
if (!video) {
throw new Error(`Video with id ${id} not found`);
}