Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

Merge main into PR #185 and resolve native aspect conflicts

Siddharthe2075f15e991
diff --cc src/components/video-editor/VideoEditor.tsx
index 9666c33cd,49aab9bba..46e49984d
--- a/src/components/video-editor/VideoEditor.tsx
+++ b/src/components/video-editor/VideoEditor.tsx
@@@ -1,1302 -1,1424 +1,1434 @@@
-
-
+ import type { Span } from "dnd-timeline";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
- import { Toaster } from "@/components/ui/sonner";
- import { toast } from "sonner";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
-
- import VideoPlayback, { VideoPlaybackRef } from "./VideoPlayback";
- import PlaybackControls from "./PlaybackControls";
- import TimelineEditor from "./timeline/TimelineEditor";
- import { SettingsPanel } from "./SettingsPanel";
+ import { toast } from "sonner";
+ import { Toaster } from "@/components/ui/sonner";
+ import { useShortcuts } from "@/contexts/ShortcutsContext";
+ import { INITIAL_EDITOR_STATE, useEditorHistory } from "@/hooks/useEditorHistory";
+ import {
+ calculateOutputDimensions,
+ type ExportFormat,
+ type ExportProgress,
+ type ExportQuality,
+ type ExportSettings,
+ GIF_SIZE_PRESETS,
+ GifExporter,
+ type GifFrameRate,
+ type GifSizePreset,
+ VideoExporter,
+ } from "@/lib/exporter";
+ import { matchesShortcut } from "@/lib/shortcuts";
-import { getAspectRatioValue } from "@/utils/aspectRatioUtils";
++import { getAspectRatioValue, getNativeAspectRatioValue } from "@/utils/aspectRatioUtils";
import { ExportDialog } from "./ExportDialog";
+ import PlaybackControls from "./PlaybackControls";
import {
- WALLPAPER_PATHS,
- createProjectData,
- deriveNextId,
- fromFileUrl,
- normalizeProjectEditor,
- toFileUrl,
- validateProjectData,
+ createProjectData,
+ deriveNextId,
+ fromFileUrl,
+ normalizeProjectEditor,
+ toFileUrl,
+ validateProjectData,
} from "./projectPersistence";
-
- import type { Span } from "dnd-timeline";
+ import { SettingsPanel } from "./SettingsPanel";
+ import TimelineEditor from "./timeline/TimelineEditor";
import {
- DEFAULT_ZOOM_DEPTH,
- clampFocusToDepth,
- DEFAULT_CROP_REGION,
- DEFAULT_ANNOTATION_POSITION,
- DEFAULT_ANNOTATION_SIZE,
- DEFAULT_ANNOTATION_STYLE,
- DEFAULT_FIGURE_DATA,
- DEFAULT_PLAYBACK_SPEED,
- type ZoomDepth,
- type ZoomFocus,
- type ZoomRegion,
- type CursorTelemetryPoint,
- type TrimRegion,
- type AnnotationRegion,
- type CropRegion,
- type FigureData,
- type SpeedRegion,
- type PlaybackSpeed,
+ type AnnotationRegion,
+ type CursorTelemetryPoint,
+ clampFocusToDepth,
+ DEFAULT_ANNOTATION_POSITION,
+ DEFAULT_ANNOTATION_SIZE,
+ DEFAULT_ANNOTATION_STYLE,
+ DEFAULT_FIGURE_DATA,
+ DEFAULT_PLAYBACK_SPEED,
+ DEFAULT_ZOOM_DEPTH,
+ type FigureData,
+ type PlaybackSpeed,
+ type SpeedRegion,
+ type TrimRegion,
+ type ZoomDepth,
+ type ZoomFocus,
+ type ZoomRegion,
} from "./types";
- import { VideoExporter, GifExporter, type ExportProgress, type ExportQuality, type ExportSettings, type ExportFormat, type GifFrameRate, type GifSizePreset, GIF_SIZE_PRESETS, calculateOutputDimensions } from "@/lib/exporter";
- import { type AspectRatio, getAspectRatioValue, getNativeAspectRatioValue } from "@/utils/aspectRatioUtils";
- import { getAssetPath } from "@/lib/assetPath";
- import { useShortcuts } from "@/contexts/ShortcutsContext";
- import { matchesShortcut } from "@/lib/shortcuts";
+ import VideoPlayback, { VideoPlaybackRef } from "./VideoPlayback";
export default function VideoEditor() {
- const [videoPath, setVideoPath] = useState<string | null>(null);
- const [videoSourcePath, setVideoSourcePath] = useState<string | null>(null);
- const [currentProjectPath, setCurrentProjectPath] = useState<string | null>(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [isPlaying, setIsPlaying] = useState(false);
- const [currentTime, setCurrentTime] = useState(0);
- const [duration, setDuration] = useState(0);
- const [wallpaper, setWallpaper] = useState<string>(WALLPAPER_PATHS[0]);
- const [shadowIntensity, setShadowIntensity] = useState(0);
- const [showBlur, setShowBlur] = useState(false);
- const [motionBlurEnabled, setMotionBlurEnabled] = useState(false);
- const [borderRadius, setBorderRadius] = useState(0);
- const [padding, setPadding] = useState(50);
- const [cropRegion, setCropRegion] = useState<CropRegion>(DEFAULT_CROP_REGION);
- const [zoomRegions, setZoomRegions] = useState<ZoomRegion[]>([]);
- const [cursorTelemetry, setCursorTelemetry] = useState<CursorTelemetryPoint[]>([]);
- const [selectedZoomId, setSelectedZoomId] = useState<string | null>(null);
- const [trimRegions, setTrimRegions] = useState<TrimRegion[]>([]);
- const [selectedTrimId, setSelectedTrimId] = useState<string | null>(null);
- const [speedRegions, setSpeedRegions] = useState<SpeedRegion[]>([]);
- const [selectedSpeedId, setSelectedSpeedId] = useState<string | null>(null);
- const [annotationRegions, setAnnotationRegions] = useState<AnnotationRegion[]>([]);
- const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);
- const [isExporting, setIsExporting] = useState(false);
- const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);
- const [exportError, setExportError] = useState<string | null>(null);
- const [showExportDialog, setShowExportDialog] = useState(false);
- const [aspectRatio, setAspectRatio] = useState<AspectRatio>('16:9');
- const [exportQuality, setExportQuality] = useState<ExportQuality>('good');
- const [exportFormat, setExportFormat] = useState<ExportFormat>('mp4');
- const [gifFrameRate, setGifFrameRate] = useState<GifFrameRate>(15);
- const [gifLoop, setGifLoop] = useState(true);
- const [gifSizePreset, setGifSizePreset] = useState<GifSizePreset>('medium');
- const [lastSavedSnapshot, setLastSavedSnapshot] = useState<string | null>(null);
-
- const videoPlaybackRef = useRef<VideoPlaybackRef>(null);
- const nextZoomIdRef = useRef(1);
- const nextTrimIdRef = useRef(1);
- const nextSpeedIdRef = useRef(1);
-
- const { shortcuts, isMac } = useShortcuts();
- const nextAnnotationIdRef = useRef(1);
- const nextAnnotationZIndexRef = useRef(1); // Track z-index for stacking order
- const exporterRef = useRef<VideoExporter | null>(null);
-
- const applyLoadedProject = useCallback(async (candidate: unknown, path?: string | null) => {
- if (!validateProjectData(candidate)) {
- return false;
- }
-
- const project = candidate;
- const sourcePath = project.videoPath;
- const normalizedEditor = normalizeProjectEditor(project.editor);
-
- try {
- videoPlaybackRef.current?.pause();
- } catch {
- // no-op
- }
- setIsPlaying(false);
- setCurrentTime(0);
- setDuration(0);
-
- setError(null);
- setVideoSourcePath(sourcePath);
- setVideoPath(toFileUrl(sourcePath));
- setCurrentProjectPath(path ?? null);
-
- setWallpaper(normalizedEditor.wallpaper);
- setShadowIntensity(normalizedEditor.shadowIntensity);
- setShowBlur(normalizedEditor.showBlur);
- setMotionBlurEnabled(normalizedEditor.motionBlurEnabled);
- setBorderRadius(normalizedEditor.borderRadius);
- setPadding(normalizedEditor.padding);
- setCropRegion(normalizedEditor.cropRegion);
- setZoomRegions(normalizedEditor.zoomRegions);
- setTrimRegions(normalizedEditor.trimRegions);
- setSpeedRegions(normalizedEditor.speedRegions);
- setAnnotationRegions(normalizedEditor.annotationRegions);
- setAspectRatio(normalizedEditor.aspectRatio);
- setExportQuality(normalizedEditor.exportQuality);
- setExportFormat(normalizedEditor.exportFormat);
- setGifFrameRate(normalizedEditor.gifFrameRate);
- setGifLoop(normalizedEditor.gifLoop);
- setGifSizePreset(normalizedEditor.gifSizePreset);
-
- setSelectedZoomId(null);
- setSelectedTrimId(null);
- setSelectedSpeedId(null);
- setSelectedAnnotationId(null);
-
- nextZoomIdRef.current = deriveNextId("zoom", normalizedEditor.zoomRegions.map((region) => region.id));
- nextTrimIdRef.current = deriveNextId("trim", normalizedEditor.trimRegions.map((region) => region.id));
- nextSpeedIdRef.current = deriveNextId("speed", normalizedEditor.speedRegions.map((region) => region.id));
- nextAnnotationIdRef.current = deriveNextId(
- "annotation",
- normalizedEditor.annotationRegions.map((region) => region.id),
- );
- nextAnnotationZIndexRef.current =
- normalizedEditor.annotationRegions.reduce((max, region) => Math.max(max, region.zIndex), 0) + 1;
-
- setLastSavedSnapshot(JSON.stringify(createProjectData(sourcePath, normalizedEditor)));
- return true;
- }, []);
-
- const currentProjectSnapshot = useMemo(() => {
- const sourcePath = videoSourcePath ?? (videoPath ? fromFileUrl(videoPath) : null);
- if (!sourcePath) {
- return null;
- }
- return JSON.stringify(
- createProjectData(sourcePath, {
- wallpaper,
- shadowIntensity,
- showBlur,
- motionBlurEnabled,
- borderRadius,
- padding,
- cropRegion,
- zoomRegions,
- trimRegions,
- speedRegions,
- annotationRegions,
- aspectRatio,
- exportQuality,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- }),
- );
- }, [
- videoPath,
- videoSourcePath,
- wallpaper,
- shadowIntensity,
- showBlur,
- motionBlurEnabled,
- borderRadius,
- padding,
- cropRegion,
- zoomRegions,
- trimRegions,
- speedRegions,
- annotationRegions,
- aspectRatio,
- exportQuality,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- ]);
-
- const hasUnsavedChanges = Boolean(
- currentProjectPath &&
- currentProjectSnapshot &&
- lastSavedSnapshot &&
- currentProjectSnapshot !== lastSavedSnapshot,
- );
-
- useEffect(() => {
- async function loadInitialData() {
- try {
- const currentProjectResult = await window.electronAPI.loadCurrentProjectFile();
- if (currentProjectResult.success && currentProjectResult.project) {
- const restored = await applyLoadedProject(
- currentProjectResult.project,
- currentProjectResult.path ?? null,
- );
- if (restored) {
- return;
- }
- }
-
- const result = await window.electronAPI.getCurrentVideoPath();
- if (result.success && result.path) {
- setVideoSourcePath(result.path);
- setVideoPath(toFileUrl(result.path));
- setCurrentProjectPath(null);
- setLastSavedSnapshot(null);
- } else {
- setError("No video to load. Please record or select a video.");
- }
- } catch (err) {
- setError("Error loading video: " + String(err));
- } finally {
- setLoading(false);
- }
- }
-
- loadInitialData();
- }, [applyLoadedProject]);
-
- const saveProject = useCallback(async (forceSaveAs: boolean) => {
- if (!videoPath) {
- toast.error('No video loaded');
- return;
- }
-
- const sourcePath = videoSourcePath ?? fromFileUrl(videoPath);
- if (!sourcePath) {
- toast.error('Unable to determine source video path');
- return;
- }
-
- const projectData = createProjectData(sourcePath, {
- wallpaper,
- shadowIntensity,
- showBlur,
- motionBlurEnabled,
- borderRadius,
- padding,
- cropRegion,
- zoomRegions,
- trimRegions,
- speedRegions,
- annotationRegions,
- aspectRatio,
- exportQuality,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- });
-
- const fileNameBase = sourcePath.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, '') || `project-${Date.now()}`;
- const projectSnapshot = JSON.stringify(projectData);
- const result = await window.electronAPI.saveProjectFile(
- projectData,
- fileNameBase,
- forceSaveAs ? undefined : currentProjectPath ?? undefined,
- );
-
- if (result.canceled) {
- toast.info("Project save canceled");
- return;
- }
-
- if (!result.success) {
- toast.error(result.message || 'Failed to save project');
- return;
- }
-
- if (result.path) {
- setCurrentProjectPath(result.path);
- }
- setLastSavedSnapshot(projectSnapshot);
-
- toast.success(`Project saved to ${result.path}`);
- }, [
- videoPath,
- videoSourcePath,
- currentProjectPath,
- wallpaper,
- shadowIntensity,
- showBlur,
- motionBlurEnabled,
- borderRadius,
- padding,
- cropRegion,
- zoomRegions,
- trimRegions,
- speedRegions,
- annotationRegions,
- aspectRatio,
- exportQuality,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- ]);
-
- useEffect(() => {
- const handleBeforeUnload = (event: BeforeUnloadEvent) => {
- if (!hasUnsavedChanges) {
- return;
- }
-
- event.preventDefault();
- event.returnValue = '';
- };
-
- window.addEventListener('beforeunload', handleBeforeUnload);
- return () => window.removeEventListener('beforeunload', handleBeforeUnload);
- }, [hasUnsavedChanges]);
-
- const handleSaveProject = useCallback(async () => {
- await saveProject(false);
- }, [saveProject]);
-
- const handleSaveProjectAs = useCallback(async () => {
- await saveProject(true);
- }, [saveProject]);
-
- const handleLoadProject = useCallback(async () => {
- const result = await window.electronAPI.loadProjectFile();
-
- if (result.canceled) {
- return;
- }
-
- if (!result.success) {
- toast.error(result.message || 'Failed to load project');
- return;
- }
-
- const restored = await applyLoadedProject(result.project, result.path ?? null);
- if (!restored) {
- toast.error('Invalid project file format');
- return;
- }
-
- toast.success(`Project loaded from ${result.path}`);
- }, [applyLoadedProject]);
-
- useEffect(() => {
- const removeLoadListener = window.electronAPI.onMenuLoadProject(handleLoadProject);
- const removeSaveListener = window.electronAPI.onMenuSaveProject(handleSaveProject);
- const removeSaveAsListener = window.electronAPI.onMenuSaveProjectAs(handleSaveProjectAs);
-
- return () => {
- removeLoadListener?.();
- removeSaveListener?.();
- removeSaveAsListener?.();
- };
- }, [handleLoadProject, handleSaveProject, handleSaveProjectAs]);
-
- useEffect(() => {
- let mounted = true;
-
- async function loadCursorTelemetry() {
- if (!videoPath) {
- if (mounted) {
- setCursorTelemetry([]);
- }
- return;
- }
-
- try {
- const result = await window.electronAPI.getCursorTelemetry(fromFileUrl(videoPath));
- if (mounted) {
- setCursorTelemetry(result.success ? result.samples : []);
- }
- } catch (telemetryError) {
- console.warn('Unable to load cursor telemetry:', telemetryError);
- if (mounted) {
- setCursorTelemetry([]);
- }
- }
- }
-
- loadCursorTelemetry();
-
- return () => {
- mounted = false;
- };
- }, [videoPath]);
-
- // Initialize default wallpaper with resolved asset path
- useEffect(() => {
- let mounted = true;
- (async () => {
- try {
- const resolvedPath = await getAssetPath('wallpapers/wallpaper1.jpg');
- if (mounted) {
- setWallpaper(resolvedPath);
- }
- } catch (err) {
- // If resolution fails, keep the fallback
- console.warn('Failed to resolve default wallpaper path:', err);
- }
- })();
- return () => { mounted = false };
- }, []);
-
- function togglePlayPause() {
- const playback = videoPlaybackRef.current;
- const video = playback?.video;
- if (!playback || !video) return;
-
- if (isPlaying) {
- playback.pause();
- } else {
- playback.play().catch(err => console.error('Video play failed:', err));
- }
- }
-
- function handleSeek(time: number) {
- const video = videoPlaybackRef.current?.video;
- if (!video) return;
- video.currentTime = time;
- }
-
- const handleSelectZoom = useCallback((id: string | null) => {
- setSelectedZoomId(id);
- if (id) setSelectedTrimId(null);
- }, []);
-
- const handleSelectTrim = useCallback((id: string | null) => {
- setSelectedTrimId(id);
- if (id) {
- setSelectedZoomId(null);
- setSelectedAnnotationId(null);
- }
- }, []);
-
- const handleSelectAnnotation = useCallback((id: string | null) => {
- setSelectedAnnotationId(id);
- if (id) {
- setSelectedZoomId(null);
- setSelectedTrimId(null);
- }
- }, []);
-
- const handleZoomAdded = useCallback((span: Span) => {
- const id = `zoom-${nextZoomIdRef.current++}`;
- const newRegion: ZoomRegion = {
- id,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- depth: DEFAULT_ZOOM_DEPTH,
- focus: { cx: 0.5, cy: 0.5 },
- };
- setZoomRegions((prev) => [...prev, newRegion]);
- setSelectedZoomId(id);
- setSelectedTrimId(null);
- setSelectedAnnotationId(null);
- }, []);
-
- const handleZoomSuggested = useCallback((span: Span, focus: ZoomFocus) => {
- const id = `zoom-${nextZoomIdRef.current++}`;
- const newRegion: ZoomRegion = {
- id,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- depth: DEFAULT_ZOOM_DEPTH,
- focus: clampFocusToDepth(focus, DEFAULT_ZOOM_DEPTH),
- };
- setZoomRegions((prev) => [...prev, newRegion]);
- setSelectedZoomId(id);
- setSelectedTrimId(null);
- setSelectedAnnotationId(null);
- }, []);
-
- const handleTrimAdded = useCallback((span: Span) => {
- const id = `trim-${nextTrimIdRef.current++}`;
- const newRegion: TrimRegion = {
- id,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- };
- setTrimRegions((prev) => [...prev, newRegion]);
- setSelectedTrimId(id);
- setSelectedZoomId(null);
- setSelectedAnnotationId(null);
- }, []);
-
- const handleZoomSpanChange = useCallback((id: string, span: Span) => {
- setZoomRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? {
- ...region,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- }
- : region,
- ),
- );
- }, []);
-
- const handleTrimSpanChange = useCallback((id: string, span: Span) => {
- setTrimRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? {
- ...region,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- }
- : region,
- ),
- );
- }, []);
-
- const handleZoomFocusChange = useCallback((id: string, focus: ZoomFocus) => {
- setZoomRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? {
- ...region,
- focus: clampFocusToDepth(focus, region.depth),
- }
- : region,
- ),
- );
- }, []);
-
- const handleZoomDepthChange = useCallback((depth: ZoomDepth) => {
- if (!selectedZoomId) return;
- setZoomRegions((prev) =>
- prev.map((region) =>
- region.id === selectedZoomId
- ? {
- ...region,
- depth,
- focus: clampFocusToDepth(region.focus, depth),
- }
- : region,
- ),
- );
- }, [selectedZoomId]);
-
- const handleZoomDelete = useCallback((id: string) => {
- setZoomRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedZoomId === id) {
- setSelectedZoomId(null);
- }
- }, [selectedZoomId]);
-
- const handleTrimDelete = useCallback((id: string) => {
- setTrimRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedTrimId === id) {
- setSelectedTrimId(null);
- }
- }, [selectedTrimId]);
-
- const handleSelectSpeed = useCallback((id: string | null) => {
- setSelectedSpeedId(id);
- if (id) {
- setSelectedZoomId(null);
- setSelectedTrimId(null);
- setSelectedAnnotationId(null);
- }
- }, []);
-
- const handleSpeedAdded = useCallback((span: Span) => {
- const id = `speed-${nextSpeedIdRef.current++}`;
- const newRegion: SpeedRegion = {
- id,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- speed: DEFAULT_PLAYBACK_SPEED,
- };
- setSpeedRegions((prev) => [...prev, newRegion]);
- setSelectedSpeedId(id);
- setSelectedZoomId(null);
- setSelectedTrimId(null);
- setSelectedAnnotationId(null);
- }, []);
-
- const handleSpeedSpanChange = useCallback((id: string, span: Span) => {
- setSpeedRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? {
- ...region,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- }
- : region,
- ),
- );
- }, []);
-
- const handleSpeedDelete = useCallback((id: string) => {
- setSpeedRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedSpeedId === id) {
- setSelectedSpeedId(null);
- }
- }, [selectedSpeedId]);
-
- const handleSpeedChange = useCallback((speed: PlaybackSpeed) => {
- if (!selectedSpeedId) return;
- setSpeedRegions((prev) =>
- prev.map((region) =>
- region.id === selectedSpeedId ? { ...region, speed } : region,
- ),
- );
- }, [selectedSpeedId]);
-
- const handleAnnotationAdded = useCallback((span: Span) => {
- const id = `annotation-${nextAnnotationIdRef.current++}`;
- const zIndex = nextAnnotationZIndexRef.current++; // Assign z-index based on creation order
- const newRegion: AnnotationRegion = {
- id,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- type: 'text',
- content: 'Enter text...',
- position: { ...DEFAULT_ANNOTATION_POSITION },
- size: { ...DEFAULT_ANNOTATION_SIZE },
- style: { ...DEFAULT_ANNOTATION_STYLE },
- zIndex,
- };
- setAnnotationRegions((prev) => [...prev, newRegion]);
- setSelectedAnnotationId(id);
- setSelectedZoomId(null);
- setSelectedTrimId(null);
- }, []);
-
- const handleAnnotationSpanChange = useCallback((id: string, span: Span) => {
- setAnnotationRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? {
- ...region,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- }
- : region,
- ),
- );
- }, []);
-
- const handleAnnotationDelete = useCallback((id: string) => {
- setAnnotationRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedAnnotationId === id) {
- setSelectedAnnotationId(null);
- }
- }, [selectedAnnotationId]);
-
- const handleAnnotationContentChange = useCallback((id: string, content: string) => {
- setAnnotationRegions((prev) => {
- const updated = prev.map((region) => {
- if (region.id !== id) return region;
-
- // Store content in type-specific fields
- if (region.type === 'text') {
- return { ...region, content, textContent: content };
- } else if (region.type === 'image') {
- return { ...region, content, imageContent: content };
- } else {
- return { ...region, content };
- }
- });
- return updated;
- });
- }, []);
-
- const handleAnnotationTypeChange = useCallback((id: string, type: AnnotationRegion['type']) => {
- setAnnotationRegions((prev) => {
- const updated = prev.map((region) => {
- if (region.id !== id) return region;
-
- const updatedRegion = { ...region, type };
-
- // Restore content from type-specific storage
- if (type === 'text') {
- updatedRegion.content = region.textContent || 'Enter text...';
- } else if (type === 'image') {
- updatedRegion.content = region.imageContent || '';
- } else if (type === 'figure') {
- updatedRegion.content = '';
- if (!region.figureData) {
- updatedRegion.figureData = { ...DEFAULT_FIGURE_DATA };
- }
- }
-
- return updatedRegion;
- });
- return updated;
- });
- }, []);
-
- const handleAnnotationStyleChange = useCallback((id: string, style: Partial<AnnotationRegion['style']>) => {
- setAnnotationRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? { ...region, style: { ...region.style, ...style } }
- : region,
- ),
- );
- }, []);
-
- const handleAnnotationFigureDataChange = useCallback((id: string, figureData: FigureData) => {
- setAnnotationRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? { ...region, figureData }
- : region,
- ),
- );
- }, []);
-
- const handleAnnotationPositionChange = useCallback((id: string, position: { x: number; y: number }) => {
- setAnnotationRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? { ...region, position }
- : region,
- ),
- );
- }, []);
-
- const handleAnnotationSizeChange = useCallback((id: string, size: { width: number; height: number }) => {
- setAnnotationRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? { ...region, size }
- : region,
- ),
- );
- }, []);
-
- // Global Tab prevention
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Tab') {
- // Allow tab only in inputs/textareas
- if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
- return;
- }
- e.preventDefault();
- }
-
- if (matchesShortcut(e, shortcuts.playPause, isMac)) {
- // Allow space only in inputs/textareas
- if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
- return;
- }
- e.preventDefault();
-
- const playback = videoPlaybackRef.current;
- if (playback?.video) {
- if (playback.video.paused) {
- playback.play().catch(console.error);
- } else {
- playback.pause();
- }
- }
- }
- };
-
- window.addEventListener('keydown', handleKeyDown, { capture: true });
- return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });
- }, [shortcuts, isMac]);
-
- useEffect(() => {
- if (selectedZoomId && !zoomRegions.some((region) => region.id === selectedZoomId)) {
- setSelectedZoomId(null);
- }
- }, [selectedZoomId, zoomRegions]);
-
- useEffect(() => {
- if (selectedTrimId && !trimRegions.some((region) => region.id === selectedTrimId)) {
- setSelectedTrimId(null);
- }
- }, [selectedTrimId, trimRegions]);
-
- useEffect(() => {
- if (selectedAnnotationId && !annotationRegions.some((region) => region.id === selectedAnnotationId)) {
- setSelectedAnnotationId(null);
- }
- }, [selectedAnnotationId, annotationRegions]);
-
- useEffect(() => {
- if (selectedSpeedId && !speedRegions.some((region) => region.id === selectedSpeedId)) {
- setSelectedSpeedId(null);
- }
- }, [selectedSpeedId, speedRegions]);
-
- const handleExport = useCallback(async (settings: ExportSettings) => {
- if (!videoPath) {
- toast.error('No video loaded');
- return;
- }
-
- const video = videoPlaybackRef.current?.video;
- if (!video) {
- toast.error('Video not ready');
- return;
- }
-
- setIsExporting(true);
- setExportProgress(null);
- setExportError(null);
-
- try {
- const wasPlaying = isPlaying;
- if (wasPlaying) {
- videoPlaybackRef.current?.pause();
- }
-
- const sourceWidth = video.videoWidth || 1920;
- const sourceHeight = video.videoHeight || 1080;
- const aspectRatioValue = aspectRatio === 'native'
- ? getNativeAspectRatioValue(sourceWidth, sourceHeight, cropRegion)
- : getAspectRatioValue(aspectRatio);
-
- // Get preview CONTAINER dimensions for scaling
- const playbackRef = videoPlaybackRef.current;
- const containerElement = playbackRef?.containerRef?.current;
- const previewWidth = containerElement?.clientWidth || 1920;
- const previewHeight = containerElement?.clientHeight || 1080;
-
- if (settings.format === 'gif' && settings.gifConfig) {
- // GIF Export
- const gifExporter = new GifExporter({
- videoUrl: videoPath,
- width: settings.gifConfig.width,
- height: settings.gifConfig.height,
- frameRate: settings.gifConfig.frameRate,
- loop: settings.gifConfig.loop,
- sizePreset: settings.gifConfig.sizePreset,
- wallpaper,
- zoomRegions,
- trimRegions,
- speedRegions,
- showShadow: shadowIntensity > 0,
- shadowIntensity,
- showBlur,
- motionBlurEnabled,
- borderRadius,
- padding,
- videoPadding: padding,
- cropRegion,
- annotationRegions,
- previewWidth,
- previewHeight,
- onProgress: (progress: ExportProgress) => {
- setExportProgress(progress);
- },
- });
-
- exporterRef.current = gifExporter as unknown as VideoExporter;
- const result = await gifExporter.export();
-
- if (result.success && result.blob) {
- const arrayBuffer = await result.blob.arrayBuffer();
- const timestamp = Date.now();
- const fileName = `export-${timestamp}.gif`;
-
- const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
-
- if (saveResult.canceled) {
- toast.info('Export canceled');
- } else if (saveResult.success) {
- toast.success(`GIF exported successfully to ${saveResult.path}`);
- } else {
- setExportError(saveResult.message || 'Failed to save GIF');
- toast.error(saveResult.message || 'Failed to save GIF');
- }
- } else {
- setExportError(result.error || 'GIF export failed');
- toast.error(result.error || 'GIF export failed');
- }
- } else {
- // MP4 Export
- const quality = settings.quality || exportQuality;
- let exportWidth: number;
- let exportHeight: number;
- let bitrate: number;
-
- if (quality === 'source') {
- // Use source resolution
- exportWidth = sourceWidth;
- exportHeight = sourceHeight;
-
- if (aspectRatioValue === 1) {
- // Square (1:1): use smaller dimension to avoid codec limits
- const baseDimension = Math.floor(Math.min(sourceWidth, sourceHeight) / 2) * 2;
- exportWidth = baseDimension;
- exportHeight = baseDimension;
- } else if (aspectRatioValue > 1) {
- // Landscape: find largest even dimensions that exactly match aspect ratio
- const baseWidth = Math.floor(sourceWidth / 2) * 2;
- let found = false;
- for (let w = baseWidth; w >= 100 && !found; w -= 2) {
- const h = Math.round(w / aspectRatioValue);
- if (h % 2 === 0 && Math.abs((w / h) - aspectRatioValue) < 0.0001) {
- exportWidth = w;
- exportHeight = h;
- found = true;
- }
- }
- if (!found) {
- exportWidth = baseWidth;
- exportHeight = Math.floor((baseWidth / aspectRatioValue) / 2) * 2;
- }
- } else {
- // Portrait: find largest even dimensions that exactly match aspect ratio
- const baseHeight = Math.floor(sourceHeight / 2) * 2;
- let found = false;
- for (let h = baseHeight; h >= 100 && !found; h -= 2) {
- const w = Math.round(h * aspectRatioValue);
- if (w % 2 === 0 && Math.abs((w / h) - aspectRatioValue) < 0.0001) {
- exportWidth = w;
- exportHeight = h;
- found = true;
- }
- }
- if (!found) {
- exportHeight = baseHeight;
- exportWidth = Math.floor((baseHeight * aspectRatioValue) / 2) * 2;
- }
- }
-
- // Calculate visually lossless bitrate matching screen recording optimization
- const totalPixels = exportWidth * exportHeight;
- bitrate = 30_000_000;
- if (totalPixels > 1920 * 1080 && totalPixels <= 2560 * 1440) {
- bitrate = 50_000_000;
- } else if (totalPixels > 2560 * 1440) {
- bitrate = 80_000_000;
- }
- } else {
- // Use quality-based target resolution
- const targetHeight = quality === 'medium' ? 720 : 1080;
-
- // Calculate dimensions maintaining aspect ratio
- exportHeight = Math.floor(targetHeight / 2) * 2;
- exportWidth = Math.floor((exportHeight * aspectRatioValue) / 2) * 2;
-
- // Adjust bitrate for lower resolutions
- const totalPixels = exportWidth * exportHeight;
- if (totalPixels <= 1280 * 720) {
- bitrate = 10_000_000;
- } else if (totalPixels <= 1920 * 1080) {
- bitrate = 20_000_000;
- } else {
- bitrate = 30_000_000;
- }
- }
-
- const exporter = new VideoExporter({
- videoUrl: videoPath,
- width: exportWidth,
- height: exportHeight,
- frameRate: 60,
- bitrate,
- codec: 'avc1.640033',
- wallpaper,
- zoomRegions,
- trimRegions,
- speedRegions,
- showShadow: shadowIntensity > 0,
- shadowIntensity,
- showBlur,
- motionBlurEnabled,
- borderRadius,
- padding,
- cropRegion,
- annotationRegions,
- previewWidth,
- previewHeight,
- onProgress: (progress: ExportProgress) => {
- setExportProgress(progress);
- },
- });
-
- exporterRef.current = exporter;
- const result = await exporter.export();
-
- if (result.success && result.blob) {
- const arrayBuffer = await result.blob.arrayBuffer();
- const timestamp = Date.now();
- const fileName = `export-${timestamp}.mp4`;
-
- const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
-
- if (saveResult.canceled) {
- toast.info('Export canceled');
- } else if (saveResult.success) {
- toast.success(`Video exported successfully to ${saveResult.path}`);
- } else {
- setExportError(saveResult.message || 'Failed to save video');
- toast.error(saveResult.message || 'Failed to save video');
- }
- } else {
- setExportError(result.error || 'Export failed');
- toast.error(result.error || 'Export failed');
- }
- }
-
- if (wasPlaying) {
- videoPlaybackRef.current?.play();
- }
- } catch (error) {
- console.error('Export error:', error);
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- setExportError(errorMessage);
- toast.error(`Export failed: ${errorMessage}`);
- } finally {
- setIsExporting(false);
- exporterRef.current = null;
- // Reset dialog state to ensure it can be opened again on next export
- // This fixes the bug where second export doesn't show save dialog
- setShowExportDialog(false);
- setExportProgress(null);
- }
- }, [videoPath, wallpaper, zoomRegions, trimRegions, speedRegions, shadowIntensity, showBlur, motionBlurEnabled, borderRadius, padding, cropRegion, annotationRegions, isPlaying, aspectRatio, exportQuality]);
-
- const handleOpenExportDialog = useCallback(() => {
- if (!videoPath) {
- toast.error('No video loaded');
- return;
- }
-
- const video = videoPlaybackRef.current?.video;
- if (!video) {
- toast.error('Video not ready');
- return;
- }
-
- // Build export settings from current state
- const sourceWidth = video.videoWidth || 1920;
- const sourceHeight = video.videoHeight || 1080;
- const gifDimensions = calculateOutputDimensions(sourceWidth, sourceHeight, gifSizePreset, GIF_SIZE_PRESETS);
-
- const settings: ExportSettings = {
- format: exportFormat,
- quality: exportFormat === 'mp4' ? exportQuality : undefined,
- gifConfig: exportFormat === 'gif' ? {
- frameRate: gifFrameRate,
- loop: gifLoop,
- sizePreset: gifSizePreset,
- width: gifDimensions.width,
- height: gifDimensions.height,
- } : undefined,
- };
-
- setShowExportDialog(true);
- setExportError(null);
-
- // Start export immediately
- handleExport(settings);
- }, [videoPath, exportFormat, exportQuality, gifFrameRate, gifLoop, gifSizePreset, handleExport]);
-
- const handleCancelExport = useCallback(() => {
- if (exporterRef.current) {
- exporterRef.current.cancel();
- toast.info('Export canceled');
- setShowExportDialog(false);
- setIsExporting(false);
- setExportProgress(null);
- setExportError(null);
- }
- }, []);
-
- if (loading) {
- return (
- <div className="flex items-center justify-center h-screen bg-background">
- <div className="text-foreground">Loading video...</div>
- </div>
- );
- }
- if (error) {
- return (
- <div className="flex items-center justify-center h-screen bg-background">
- <div className="flex flex-col items-center gap-3">
- <div className="text-destructive">{error}</div>
- <button
- type="button"
- onClick={handleLoadProject}
- className="px-3 py-1.5 rounded-md bg-[#34B27B] text-white text-sm hover:bg-[#34B27B]/90"
- >
- Load Project File
- </button>
- </div>
- </div>
- );
- }
-
-
- return (
- <div className="flex flex-col h-screen bg-[#09090b] text-slate-200 overflow-hidden selection:bg-[#34B27B]/30">
- <div
- className="h-10 flex-shrink-0 bg-[#09090b]/80 backdrop-blur-md border-b border-white/5 flex items-center justify-between px-6 z-50"
- style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
- >
- <div className="flex-1" />
- </div>
-
- <div className="flex-1 p-5 gap-4 flex min-h-0 relative">
- {/* Left Column - Video & Timeline */}
- <div className="flex-[7] flex flex-col gap-3 min-w-0 h-full">
- <PanelGroup direction="vertical" className="gap-3">
- {/* Top section: video preview and controls */}
- <Panel defaultSize={70} minSize={40}>
- <div className="w-full h-full flex flex-col items-center justify-center bg-black/40 rounded-2xl border border-white/5 shadow-2xl overflow-hidden">
- {/* Video preview */}
- <div className="w-full flex justify-center items-center" style={{ flex: '1 1 auto', margin: '6px 0 0' }}>
- <div className="relative" style={{ width: 'auto', height: '100%', aspectRatio: aspectRatio === 'native' ? getNativeAspectRatioValue(videoPlaybackRef.current?.video?.videoWidth || 1920, videoPlaybackRef.current?.video?.videoHeight || 1080, cropRegion) : getAspectRatioValue(aspectRatio), maxWidth: '100%', margin: '0 auto', boxSizing: 'border-box' }}>
- <VideoPlayback
- key={videoPath || 'no-video'}
- aspectRatio={aspectRatio}
- ref={videoPlaybackRef}
- videoPath={videoPath || ''}
- onDurationChange={setDuration}
- onTimeUpdate={setCurrentTime}
- currentTime={currentTime}
- onPlayStateChange={setIsPlaying}
- onError={setError}
- wallpaper={wallpaper}
- zoomRegions={zoomRegions}
- selectedZoomId={selectedZoomId}
- onSelectZoom={handleSelectZoom}
- onZoomFocusChange={handleZoomFocusChange}
- isPlaying={isPlaying}
- showShadow={shadowIntensity > 0}
- shadowIntensity={shadowIntensity}
- showBlur={showBlur}
- motionBlurEnabled={motionBlurEnabled}
- borderRadius={borderRadius}
- padding={padding}
- cropRegion={cropRegion}
- trimRegions={trimRegions}
- speedRegions={speedRegions}
- annotationRegions={annotationRegions}
- selectedAnnotationId={selectedAnnotationId}
- onSelectAnnotation={handleSelectAnnotation}
- onAnnotationPositionChange={handleAnnotationPositionChange}
- onAnnotationSizeChange={handleAnnotationSizeChange}
- />
- </div>
- </div>
- {/* Playback controls */}
- <div className="w-full flex justify-center items-center" style={{ height: '48px', flexShrink: 0, padding: '6px 12px', margin: '6px 0 6px 0' }}>
- <div style={{ width: '100%', maxWidth: '700px' }}>
- <PlaybackControls
- isPlaying={isPlaying}
- currentTime={currentTime}
- duration={duration}
- onTogglePlayPause={togglePlayPause}
- onSeek={handleSeek}
- />
- </div>
- </div>
- </div>
- </Panel>
-
- <PanelResizeHandle className="h-3 bg-[#09090b]/80 hover:bg-[#09090b] transition-colors rounded-full mx-4 flex items-center justify-center">
- <div className="w-8 h-1 bg-white/20 rounded-full"></div>
- </PanelResizeHandle>
-
- {/* Timeline section */}
- <Panel defaultSize={30} minSize={20}>
- <div className="h-full bg-[#09090b] rounded-2xl border border-white/5 shadow-lg overflow-hidden flex flex-col">
- <TimelineEditor
- videoDuration={duration}
- currentTime={currentTime}
- onSeek={handleSeek}
- cursorTelemetry={cursorTelemetry}
- zoomRegions={zoomRegions}
- onZoomAdded={handleZoomAdded}
- onZoomSuggested={handleZoomSuggested}
- onZoomSpanChange={handleZoomSpanChange}
- onZoomDelete={handleZoomDelete}
- selectedZoomId={selectedZoomId}
- onSelectZoom={handleSelectZoom}
- trimRegions={trimRegions}
- onTrimAdded={handleTrimAdded}
- onTrimSpanChange={handleTrimSpanChange}
- onTrimDelete={handleTrimDelete}
- selectedTrimId={selectedTrimId}
- onSelectTrim={handleSelectTrim}
- speedRegions={speedRegions}
- onSpeedAdded={handleSpeedAdded}
- onSpeedSpanChange={handleSpeedSpanChange}
- onSpeedDelete={handleSpeedDelete}
- selectedSpeedId={selectedSpeedId}
- onSelectSpeed={handleSelectSpeed}
- annotationRegions={annotationRegions}
- onAnnotationAdded={handleAnnotationAdded}
- onAnnotationSpanChange={handleAnnotationSpanChange}
- onAnnotationDelete={handleAnnotationDelete}
- selectedAnnotationId={selectedAnnotationId}
- onSelectAnnotation={handleSelectAnnotation}
- aspectRatio={aspectRatio}
- onAspectRatioChange={(ratio) => {
- setAspectRatio(ratio);
- if (ratio === 'native') setPadding(0);
- }}
- />
- </div>
- </Panel>
- </PanelGroup>
- </div>
-
- {/* Right section: settings panel */}
- <SettingsPanel
- selected={wallpaper}
- onWallpaperChange={setWallpaper}
- selectedZoomDepth={selectedZoomId ? zoomRegions.find(z => z.id === selectedZoomId)?.depth : null}
- onZoomDepthChange={(depth) => selectedZoomId && handleZoomDepthChange(depth)}
- selectedZoomId={selectedZoomId}
- onZoomDelete={handleZoomDelete}
- selectedTrimId={selectedTrimId}
- onTrimDelete={handleTrimDelete}
- shadowIntensity={shadowIntensity}
- onShadowChange={setShadowIntensity}
- showBlur={showBlur}
- onBlurChange={setShowBlur}
- motionBlurEnabled={motionBlurEnabled}
- onMotionBlurChange={setMotionBlurEnabled}
- borderRadius={borderRadius}
- onBorderRadiusChange={setBorderRadius}
- padding={padding}
- onPaddingChange={setPadding}
- cropRegion={cropRegion}
- onCropChange={setCropRegion}
- aspectRatio={aspectRatio}
- videoElement={videoPlaybackRef.current?.video || null}
- exportQuality={exportQuality}
- onExportQualityChange={setExportQuality}
- exportFormat={exportFormat}
- onExportFormatChange={setExportFormat}
- gifFrameRate={gifFrameRate}
- onGifFrameRateChange={setGifFrameRate}
- gifLoop={gifLoop}
- onGifLoopChange={setGifLoop}
- gifSizePreset={gifSizePreset}
- onGifSizePresetChange={setGifSizePreset}
- gifOutputDimensions={calculateOutputDimensions(
- videoPlaybackRef.current?.video?.videoWidth || 1920,
- videoPlaybackRef.current?.video?.videoHeight || 1080,
- gifSizePreset,
- GIF_SIZE_PRESETS
- )}
- onExport={handleOpenExportDialog}
- selectedAnnotationId={selectedAnnotationId}
- annotationRegions={annotationRegions}
- onAnnotationContentChange={handleAnnotationContentChange}
- onAnnotationTypeChange={handleAnnotationTypeChange}
- onAnnotationStyleChange={handleAnnotationStyleChange}
- onAnnotationFigureDataChange={handleAnnotationFigureDataChange}
- onAnnotationDelete={handleAnnotationDelete}
- onSaveProject={handleSaveProject}
- onLoadProject={handleLoadProject}
- selectedSpeedId={selectedSpeedId}
- selectedSpeedValue={selectedSpeedId ? speedRegions.find(r => r.id === selectedSpeedId)?.speed ?? null : null}
- onSpeedChange={handleSpeedChange}
- onSpeedDelete={handleSpeedDelete}
- />
- </div>
-
- <Toaster theme="dark" className="pointer-events-auto" />
-
- <ExportDialog
- isOpen={showExportDialog}
- onClose={() => setShowExportDialog(false)}
- progress={exportProgress}
- isExporting={isExporting}
- error={exportError}
- onCancel={handleCancelExport}
- exportFormat={exportFormat}
- />
- </div>
- );
+ const {
+ state: editorState,
+ pushState,
+ updateState,
+ commitState,
+ undo,
+ redo,
+ } = useEditorHistory(INITIAL_EDITOR_STATE);
+
+ const {
+ zoomRegions,
+ trimRegions,
+ speedRegions,
+ annotationRegions,
+ cropRegion,
+ wallpaper,
+ shadowIntensity,
+ showBlur,
+ motionBlurEnabled,
+ borderRadius,
+ padding,
+ aspectRatio,
+ } = editorState;
+
+ // ── Non-undoable state
+ const [videoPath, setVideoPath] = useState<string | null>(null);
+ const [videoSourcePath, setVideoSourcePath] = useState<string | null>(null);
+ const [currentProjectPath, setCurrentProjectPath] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [isPlaying, setIsPlaying] = useState(false);
+ const [currentTime, setCurrentTime] = useState(0);
+ const [duration, setDuration] = useState(0);
+ const [cursorTelemetry, setCursorTelemetry] = useState<CursorTelemetryPoint[]>([]);
+ const [selectedZoomId, setSelectedZoomId] = useState<string | null>(null);
+ const [selectedTrimId, setSelectedTrimId] = useState<string | null>(null);
+ const [selectedSpeedId, setSelectedSpeedId] = useState<string | null>(null);
+ const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);
+ const [isExporting, setIsExporting] = useState(false);
+ const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);
+ const [exportError, setExportError] = useState<string | null>(null);
+ const [showExportDialog, setShowExportDialog] = useState(false);
+ const [exportQuality, setExportQuality] = useState<ExportQuality>("good");
+ const [exportFormat, setExportFormat] = useState<ExportFormat>("mp4");
+ const [gifFrameRate, setGifFrameRate] = useState<GifFrameRate>(15);
+ const [gifLoop, setGifLoop] = useState(true);
+ const [gifSizePreset, setGifSizePreset] = useState<GifSizePreset>("medium");
+ const [lastSavedSnapshot, setLastSavedSnapshot] = useState<string | null>(null);
+
+ const videoPlaybackRef = useRef<VideoPlaybackRef>(null);
+ const nextZoomIdRef = useRef(1);
+ const nextTrimIdRef = useRef(1);
+ const nextSpeedIdRef = useRef(1);
+
+ const { shortcuts, isMac } = useShortcuts();
+ const nextAnnotationIdRef = useRef(1);
+ const nextAnnotationZIndexRef = useRef(1);
+ const exporterRef = useRef<VideoExporter | null>(null);
+
+ const applyLoadedProject = useCallback(
+ async (candidate: unknown, path?: string | null) => {
+ if (!validateProjectData(candidate)) {
+ return false;
+ }
+
+ const project = candidate;
+ const sourcePath = fromFileUrl(project.videoPath);
+ const normalizedEditor = normalizeProjectEditor(project.editor);
+
+ try {
+ videoPlaybackRef.current?.pause();
+ } catch {
+ // no-op
+ }
+ setIsPlaying(false);
+ setCurrentTime(0);
+ setDuration(0);
+
+ setError(null);
+ setVideoSourcePath(sourcePath);
+ setVideoPath(toFileUrl(sourcePath));
+ setCurrentProjectPath(path ?? null);
+
+ pushState({
+ wallpaper: normalizedEditor.wallpaper,
+ shadowIntensity: normalizedEditor.shadowIntensity,
+ showBlur: normalizedEditor.showBlur,
+ motionBlurEnabled: normalizedEditor.motionBlurEnabled,
+ borderRadius: normalizedEditor.borderRadius,
+ padding: normalizedEditor.padding,
+ cropRegion: normalizedEditor.cropRegion,
+ zoomRegions: normalizedEditor.zoomRegions,
+ trimRegions: normalizedEditor.trimRegions,
+ speedRegions: normalizedEditor.speedRegions,
+ annotationRegions: normalizedEditor.annotationRegions,
+ aspectRatio: normalizedEditor.aspectRatio,
+ });
+ setExportQuality(normalizedEditor.exportQuality);
+ setExportFormat(normalizedEditor.exportFormat);
+ setGifFrameRate(normalizedEditor.gifFrameRate);
+ setGifLoop(normalizedEditor.gifLoop);
+ setGifSizePreset(normalizedEditor.gifSizePreset);
+
+ setSelectedZoomId(null);
+ setSelectedTrimId(null);
+ setSelectedSpeedId(null);
+ setSelectedAnnotationId(null);
+
+ nextZoomIdRef.current = deriveNextId(
+ "zoom",
+ normalizedEditor.zoomRegions.map((region) => region.id),
+ );
+ nextTrimIdRef.current = deriveNextId(
+ "trim",
+ normalizedEditor.trimRegions.map((region) => region.id),
+ );
+ nextSpeedIdRef.current = deriveNextId(
+ "speed",
+ normalizedEditor.speedRegions.map((region) => region.id),
+ );
+ nextAnnotationIdRef.current = deriveNextId(
+ "annotation",
+ normalizedEditor.annotationRegions.map((region) => region.id),
+ );
+ nextAnnotationZIndexRef.current =
+ normalizedEditor.annotationRegions.reduce(
+ (max, region) => Math.max(max, region.zIndex),
+ 0,
+ ) + 1;
+
+ setLastSavedSnapshot(JSON.stringify(createProjectData(sourcePath, normalizedEditor)));
+ return true;
+ },
+ [pushState],
+ );
+
+ const currentProjectSnapshot = useMemo(() => {
+ const sourcePath = videoSourcePath ?? (videoPath ? fromFileUrl(videoPath) : null);
+ if (!sourcePath) {
+ return null;
+ }
+ return JSON.stringify(
+ createProjectData(sourcePath, {
+ wallpaper,
+ shadowIntensity,
+ showBlur,
+ motionBlurEnabled,
+ borderRadius,
+ padding,
+ cropRegion,
+ zoomRegions,
+ trimRegions,
+ speedRegions,
+ annotationRegions,
+ aspectRatio,
+ exportQuality,
+ exportFormat,
+ gifFrameRate,
+ gifLoop,
+ gifSizePreset,
+ }),
+ );
+ }, [
+ videoPath,
+ videoSourcePath,
+ wallpaper,
+ shadowIntensity,
+ showBlur,
+ motionBlurEnabled,
+ borderRadius,
+ padding,
+ cropRegion,
+ zoomRegions,
+ trimRegions,
+ speedRegions,
+ annotationRegions,
+ aspectRatio,
+ exportQuality,
+ exportFormat,
+ gifFrameRate,
+ gifLoop,
+ gifSizePreset,
+ ]);
+
+ const hasUnsavedChanges = Boolean(
+ currentProjectPath &&
+ currentProjectSnapshot &&
+ lastSavedSnapshot &&
+ currentProjectSnapshot !== lastSavedSnapshot,
+ );
+
+ useEffect(() => {
+ async function loadInitialData() {
+ try {
+ const currentProjectResult = await window.electronAPI.loadCurrentProjectFile();
+ if (currentProjectResult.success && currentProjectResult.project) {
+ const restored = await applyLoadedProject(
+ currentProjectResult.project,
+ currentProjectResult.path ?? null,
+ );
+ if (restored) {
+ return;
+ }
+ }
+
+ const result = await window.electronAPI.getCurrentVideoPath();
+ if (result.success && result.path) {
+ const sourcePath = fromFileUrl(result.path);
+ setVideoSourcePath(sourcePath);
+ setVideoPath(toFileUrl(sourcePath));
+ setCurrentProjectPath(null);
+ setLastSavedSnapshot(null);
+ } else {
+ setError("No video to load. Please record or select a video.");
+ }
+ } catch (err) {
+ setError("Error loading video: " + String(err));
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ loadInitialData();
+ }, [applyLoadedProject]);
+
+ const saveProject = useCallback(
+ async (forceSaveAs: boolean) => {
+ if (!videoPath) {
+ toast.error("No video loaded");
+ return false;
+ }
+
+ const sourcePath = videoSourcePath ?? fromFileUrl(videoPath);
+ if (!sourcePath) {
+ toast.error("Unable to determine source video path");
+ return false;
+ }
+
+ const projectData = createProjectData(sourcePath, {
+ wallpaper,
+ shadowIntensity,
+ showBlur,
+ motionBlurEnabled,
+ borderRadius,
+ padding,
+ cropRegion,
+ zoomRegions,
+ trimRegions,
+ speedRegions,
+ annotationRegions,
+ aspectRatio,
+ exportQuality,
+ exportFormat,
+ gifFrameRate,
+ gifLoop,
+ gifSizePreset,
+ });
+
+ const fileNameBase =
+ sourcePath
+ .split(/[\\/]/)
+ .pop()
+ ?.replace(/\.[^.]+$/, "") || `project-${Date.now()}`;
+ const projectSnapshot = JSON.stringify(projectData);
+ const result = await window.electronAPI.saveProjectFile(
+ projectData,
+ fileNameBase,
+ forceSaveAs ? undefined : (currentProjectPath ?? undefined),
+ );
+
+ if (result.canceled) {
+ toast.info("Project save canceled");
+ return false;
+ }
+
+ if (!result.success) {
+ toast.error(result.message || "Failed to save project");
+ return false;
+ }
+
+ if (result.path) {
+ setCurrentProjectPath(result.path);
+ }
+ setLastSavedSnapshot(projectSnapshot);
+
+ toast.success(`Project saved to ${result.path}`);
+ return true;
+ },
+ [
+ videoPath,
+ videoSourcePath,
+ currentProjectPath,
+ wallpaper,
+ shadowIntensity,
+ showBlur,
+ motionBlurEnabled,
+ borderRadius,
+ padding,
+ cropRegion,
+ zoomRegions,
+ trimRegions,
+ speedRegions,
+ annotationRegions,
+ aspectRatio,
+ exportQuality,
+ exportFormat,
+ gifFrameRate,
+ gifLoop,
+ gifSizePreset,
+ ],
+ );
+
+ useEffect(() => {
+ window.electronAPI.setHasUnsavedChanges(hasUnsavedChanges);
+ }, [hasUnsavedChanges]);
+
+ useEffect(() => {
+ const cleanup = window.electronAPI.onRequestSaveBeforeClose(async () => {
+ return saveProject(false);
+ });
+ return () => cleanup();
+ }, [saveProject]);
+
+ const handleSaveProject = useCallback(async () => {
+ await saveProject(false);
+ }, [saveProject]);
+
+ const handleSaveProjectAs = useCallback(async () => {
+ await saveProject(true);
+ }, [saveProject]);
+
+ const handleLoadProject = useCallback(async () => {
+ const result = await window.electronAPI.loadProjectFile();
+
+ if (result.canceled) {
+ return;
+ }
+
+ if (!result.success) {
+ toast.error(result.message || "Failed to load project");
+ return;
+ }
+
+ const restored = await applyLoadedProject(result.project, result.path ?? null);
+ if (!restored) {
+ toast.error("Invalid project file format");
+ return;
+ }
+
+ toast.success(`Project loaded from ${result.path}`);
+ }, [applyLoadedProject]);
+
+ useEffect(() => {
+ const removeLoadListener = window.electronAPI.onMenuLoadProject(handleLoadProject);
+ const removeSaveListener = window.electronAPI.onMenuSaveProject(handleSaveProject);
+ const removeSaveAsListener = window.electronAPI.onMenuSaveProjectAs(handleSaveProjectAs);
+
+ return () => {
+ removeLoadListener?.();
+ removeSaveListener?.();
+ removeSaveAsListener?.();
+ };
+ }, [handleLoadProject, handleSaveProject, handleSaveProjectAs]);
+
+ useEffect(() => {
+ let mounted = true;
+
+ async function loadCursorTelemetry() {
+ const sourcePath = videoSourcePath ?? (videoPath ? fromFileUrl(videoPath) : null);
+
+ if (!sourcePath) {
+ if (mounted) {
+ setCursorTelemetry([]);
+ }
+ return;
+ }
+
+ try {
+ const result = await window.electronAPI.getCursorTelemetry(sourcePath);
+ if (mounted) {
+ setCursorTelemetry(result.success ? result.samples : []);
+ }
+ } catch (telemetryError) {
+ console.warn("Unable to load cursor telemetry:", telemetryError);
+ if (mounted) {
+ setCursorTelemetry([]);
+ }
+ }
+ }
+
+ loadCursorTelemetry();
+
+ return () => {
+ mounted = false;
+ };
+ }, [videoPath, videoSourcePath]);
+
+ function togglePlayPause() {
+ const playback = videoPlaybackRef.current;
+ const video = playback?.video;
+ if (!playback || !video) return;
+
+ if (isPlaying) {
+ playback.pause();
+ } else {
+ playback.play().catch((err) => console.error("Video play failed:", err));
+ }
+ }
+
+ function handleSeek(time: number) {
+ const video = videoPlaybackRef.current?.video;
+ if (!video) return;
+ video.currentTime = time;
+ }
+
+ const handleSelectZoom = useCallback((id: string | null) => {
+ setSelectedZoomId(id);
+ if (id) setSelectedTrimId(null);
+ }, []);
+
+ const handleSelectTrim = useCallback((id: string | null) => {
+ setSelectedTrimId(id);
+ if (id) {
+ setSelectedZoomId(null);
+ setSelectedAnnotationId(null);
+ }
+ }, []);
+
+ const handleSelectAnnotation = useCallback((id: string | null) => {
+ setSelectedAnnotationId(id);
+ if (id) {
+ setSelectedZoomId(null);
+ setSelectedTrimId(null);
+ }
+ }, []);
+
+ const handleZoomAdded = useCallback(
+ (span: Span) => {
+ const id = `zoom-${nextZoomIdRef.current++}`;
+ const newRegion: ZoomRegion = {
+ id,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ depth: DEFAULT_ZOOM_DEPTH,
+ focus: { cx: 0.5, cy: 0.5 },
+ };
+ pushState((prev) => ({ zoomRegions: [...prev.zoomRegions, newRegion] }));
+ setSelectedZoomId(id);
+ setSelectedTrimId(null);
+ setSelectedAnnotationId(null);
+ },
+ [pushState],
+ );
+
+ const handleZoomSuggested = useCallback(
+ (span: Span, focus: ZoomFocus) => {
+ const id = `zoom-${nextZoomIdRef.current++}`;
+ const newRegion: ZoomRegion = {
+ id,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ depth: DEFAULT_ZOOM_DEPTH,
+ focus: clampFocusToDepth(focus, DEFAULT_ZOOM_DEPTH),
+ };
+ pushState((prev) => ({ zoomRegions: [...prev.zoomRegions, newRegion] }));
+ setSelectedZoomId(id);
+ setSelectedTrimId(null);
+ setSelectedAnnotationId(null);
+ },
+ [pushState],
+ );
+
+ const handleTrimAdded = useCallback(
+ (span: Span) => {
+ const id = `trim-${nextTrimIdRef.current++}`;
+ const newRegion: TrimRegion = {
+ id,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ };
+ pushState((prev) => ({ trimRegions: [...prev.trimRegions, newRegion] }));
+ setSelectedTrimId(id);
+ setSelectedZoomId(null);
+ setSelectedAnnotationId(null);
+ },
+ [pushState],
+ );
+
+ const handleZoomSpanChange = useCallback(
+ (id: string, span: Span) => {
+ pushState((prev) => ({
+ zoomRegions: prev.zoomRegions.map((region) =>
+ region.id === id
+ ? { ...region, startMs: Math.round(span.start), endMs: Math.round(span.end) }
+ : region,
+ ),
+ }));
+ },
+ [pushState],
+ );
+
+ const handleTrimSpanChange = useCallback(
+ (id: string, span: Span) => {
+ pushState((prev) => ({
+ trimRegions: prev.trimRegions.map((region) =>
+ region.id === id
+ ? { ...region, startMs: Math.round(span.start), endMs: Math.round(span.end) }
+ : region,
+ ),
+ }));
+ },
+ [pushState],
+ );
+
+ // Focus drag: updateState for live preview, commitState on pointer-up
+ const handleZoomFocusChange = useCallback(
+ (id: string, focus: ZoomFocus) => {
+ updateState((prev) => ({
+ zoomRegions: prev.zoomRegions.map((region) =>
+ region.id === id ? { ...region, focus: clampFocusToDepth(focus, region.depth) } : region,
+ ),
+ }));
+ },
+ [updateState],
+ );
+
+ const handleZoomDepthChange = useCallback(
+ (depth: ZoomDepth) => {
+ if (!selectedZoomId) return;
+ pushState((prev) => ({
+ zoomRegions: prev.zoomRegions.map((region) =>
+ region.id === selectedZoomId
+ ? { ...region, depth, focus: clampFocusToDepth(region.focus, depth) }
+ : region,
+ ),
+ }));
+ },
+ [selectedZoomId, pushState],
+ );
+
+ const handleZoomDelete = useCallback(
+ (id: string) => {
+ pushState((prev) => ({ zoomRegions: prev.zoomRegions.filter((r) => r.id !== id) }));
+ if (selectedZoomId === id) {
+ setSelectedZoomId(null);
+ }
+ },
+ [selectedZoomId, pushState],
+ );
+
+ const handleTrimDelete = useCallback(
+ (id: string) => {
+ pushState((prev) => ({ trimRegions: prev.trimRegions.filter((r) => r.id !== id) }));
+ if (selectedTrimId === id) {
+ setSelectedTrimId(null);
+ }
+ },
+ [selectedTrimId, pushState],
+ );
+
+ const handleSelectSpeed = useCallback((id: string | null) => {
+ setSelectedSpeedId(id);
+ if (id) {
+ setSelectedZoomId(null);
+ setSelectedTrimId(null);
+ setSelectedAnnotationId(null);
+ }
+ }, []);
+
+ const handleSpeedAdded = useCallback(
+ (span: Span) => {
+ const id = `speed-${nextSpeedIdRef.current++}`;
+ const newRegion: SpeedRegion = {
+ id,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ speed: DEFAULT_PLAYBACK_SPEED,
+ };
+ pushState((prev) => ({ speedRegions: [...prev.speedRegions, newRegion] }));
+ setSelectedSpeedId(id);
+ setSelectedZoomId(null);
+ setSelectedTrimId(null);
+ setSelectedAnnotationId(null);
+ },
+ [pushState],
+ );
+
+ const handleSpeedSpanChange = useCallback(
+ (id: string, span: Span) => {
+ pushState((prev) => ({
+ speedRegions: prev.speedRegions.map((region) =>
+ region.id === id
+ ? {
+ ...region,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ }
+ : region,
+ ),
+ }));
+ },
+ [pushState],
+ );
+
+ const handleSpeedDelete = useCallback(
+ (id: string) => {
+ pushState((prev) => ({
+ speedRegions: prev.speedRegions.filter((region) => region.id !== id),
+ }));
+ if (selectedSpeedId === id) {
+ setSelectedSpeedId(null);
+ }
+ },
+ [selectedSpeedId, pushState],
+ );
+
+ const handleSpeedChange = useCallback(
+ (speed: PlaybackSpeed) => {
+ if (!selectedSpeedId) return;
+ pushState((prev) => ({
+ speedRegions: prev.speedRegions.map((region) =>
+ region.id === selectedSpeedId ? { ...region, speed } : region,
+ ),
+ }));
+ },
+ [selectedSpeedId, pushState],
+ );
+
+ const handleAnnotationAdded = useCallback(
+ (span: Span) => {
+ const id = `annotation-${nextAnnotationIdRef.current++}`;
+ const zIndex = nextAnnotationZIndexRef.current++;
+ const newRegion: AnnotationRegion = {
+ id,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ type: "text",
+ content: "Enter text...",
+ position: { ...DEFAULT_ANNOTATION_POSITION },
+ size: { ...DEFAULT_ANNOTATION_SIZE },
+ style: { ...DEFAULT_ANNOTATION_STYLE },
+ zIndex,
+ };
+ pushState((prev) => ({ annotationRegions: [...prev.annotationRegions, newRegion] }));
+ setSelectedAnnotationId(id);
+ setSelectedZoomId(null);
+ setSelectedTrimId(null);
+ },
+ [pushState],
+ );
+
+ const handleAnnotationSpanChange = useCallback(
+ (id: string, span: Span) => {
+ pushState((prev) => ({
+ annotationRegions: prev.annotationRegions.map((region) =>
+ region.id === id
+ ? { ...region, startMs: Math.round(span.start), endMs: Math.round(span.end) }
+ : region,
+ ),
+ }));
+ },
+ [pushState],
+ );
+
+ const handleAnnotationDelete = useCallback(
+ (id: string) => {
+ pushState((prev) => ({
+ annotationRegions: prev.annotationRegions.filter((r) => r.id !== id),
+ }));
+ if (selectedAnnotationId === id) {
+ setSelectedAnnotationId(null);
+ }
+ },
+ [selectedAnnotationId, pushState],
+ );
+
+ const handleAnnotationContentChange = useCallback(
+ (id: string, content: string) => {
+ pushState((prev) => ({
+ annotationRegions: prev.annotationRegions.map((region) => {
+ if (region.id !== id) return region;
+ if (region.type === "text") {
+ return { ...region, content, textContent: content };
+ } else if (region.type === "image") {
+ return { ...region, content, imageContent: content };
+ }
+ return { ...region, content };
+ }),
+ }));
+ },
+ [pushState],
+ );
+
+ const handleAnnotationTypeChange = useCallback(
+ (id: string, type: AnnotationRegion["type"]) => {
+ pushState((prev) => ({
+ annotationRegions: prev.annotationRegions.map((region) => {
+ if (region.id !== id) return region;
+ const updatedRegion = { ...region, type };
+ if (type === "text") {
+ updatedRegion.content = region.textContent || "Enter text...";
+ } else if (type === "image") {
+ updatedRegion.content = region.imageContent || "";
+ } else if (type === "figure") {
+ updatedRegion.content = "";
+ if (!region.figureData) {
+ updatedRegion.figureData = { ...DEFAULT_FIGURE_DATA };
+ }
+ }
+ return updatedRegion;
+ }),
+ }));
+ },
+ [pushState],
+ );
+
+ const handleAnnotationStyleChange = useCallback(
+ (id: string, style: Partial<AnnotationRegion["style"]>) => {
+ pushState((prev) => ({
+ annotationRegions: prev.annotationRegions.map((region) =>
+ region.id === id ? { ...region, style: { ...region.style, ...style } } : region,
+ ),
+ }));
+ },
+ [pushState],
+ );
+
+ const handleAnnotationFigureDataChange = useCallback(
+ (id: string, figureData: FigureData) => {
+ pushState((prev) => ({
+ annotationRegions: prev.annotationRegions.map((region) =>
+ region.id === id ? { ...region, figureData } : region,
+ ),
+ }));
+ },
+ [pushState],
+ );
+
+ const handleAnnotationPositionChange = useCallback(
+ (id: string, position: { x: number; y: number }) => {
+ pushState((prev) => ({
+ annotationRegions: prev.annotationRegions.map((region) =>
+ region.id === id ? { ...region, position } : region,
+ ),
+ }));
+ },
+ [pushState],
+ );
+
+ const handleAnnotationSizeChange = useCallback(
+ (id: string, size: { width: number; height: number }) => {
+ pushState((prev) => ({
+ annotationRegions: prev.annotationRegions.map((region) =>
+ region.id === id ? { ...region, size } : region,
+ ),
+ }));
+ },
+ [pushState],
+ );
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ const mod = e.ctrlKey || e.metaKey;
+ const key = e.key.toLowerCase();
+
+ if (mod && key === "z" && !e.shiftKey) {
+ e.preventDefault();
+ e.stopPropagation();
+ undo();
+ return;
+ }
+ if (mod && (key === "y" || (key === "z" && e.shiftKey))) {
+ e.preventDefault();
+ e.stopPropagation();
+ redo();
+ return;
+ }
+
+ const isInput =
+ e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement;
+
+ if (e.key === "Tab" && !isInput) {
+ e.preventDefault();
+ }
+
+ if (matchesShortcut(e, shortcuts.playPause, isMac)) {
+ // Allow space only in inputs/textareas
+ if (isInput) {
+ return;
+ }
+ e.preventDefault();
+ const playback = videoPlaybackRef.current;
+ if (playback?.video) {
+ playback.video.paused ? playback.play().catch(console.error) : playback.pause();
+ }
+ }
+ };
+
+ window.addEventListener("keydown", handleKeyDown, { capture: true });
+ return () => window.removeEventListener("keydown", handleKeyDown, { capture: true });
+ }, [undo, redo, shortcuts, isMac]);
+
+ useEffect(() => {
+ if (selectedZoomId && !zoomRegions.some((region) => region.id === selectedZoomId)) {
+ setSelectedZoomId(null);
+ }
+ }, [selectedZoomId, zoomRegions]);
+
+ useEffect(() => {
+ if (selectedTrimId && !trimRegions.some((region) => region.id === selectedTrimId)) {
+ setSelectedTrimId(null);
+ }
+ }, [selectedTrimId, trimRegions]);
+
+ useEffect(() => {
+ if (
+ selectedAnnotationId &&
+ !annotationRegions.some((region) => region.id === selectedAnnotationId)
+ ) {
+ setSelectedAnnotationId(null);
+ }
+ }, [selectedAnnotationId, annotationRegions]);
+
+ useEffect(() => {
+ if (selectedSpeedId && !speedRegions.some((region) => region.id === selectedSpeedId)) {
+ setSelectedSpeedId(null);
+ }
+ }, [selectedSpeedId, speedRegions]);
+
+ const handleExport = useCallback(
+ async (settings: ExportSettings) => {
+ if (!videoPath) {
+ toast.error("No video loaded");
+ return;
+ }
+
+ const video = videoPlaybackRef.current?.video;
+ if (!video) {
+ toast.error("Video not ready");
+ return;
+ }
+
+ setIsExporting(true);
+ setExportProgress(null);
+ setExportError(null);
+
+ try {
+ const wasPlaying = isPlaying;
+ if (wasPlaying) {
+ videoPlaybackRef.current?.pause();
+ }
+
- const aspectRatioValue = getAspectRatioValue(aspectRatio);
+ const sourceWidth = video.videoWidth || 1920;
+ const sourceHeight = video.videoHeight || 1080;
++ const aspectRatioValue =
++ aspectRatio === "native"
++ ? getNativeAspectRatioValue(sourceWidth, sourceHeight, cropRegion)
++ : getAspectRatioValue(aspectRatio);
+
+ // Get preview CONTAINER dimensions for scaling
+ const playbackRef = videoPlaybackRef.current;
+ const containerElement = playbackRef?.containerRef?.current;
+ const previewWidth = containerElement?.clientWidth || 1920;
+ const previewHeight = containerElement?.clientHeight || 1080;
+
+ if (settings.format === "gif" && settings.gifConfig) {
+ // GIF Export
+ const gifExporter = new GifExporter({
+ videoUrl: videoPath,
+ width: settings.gifConfig.width,
+ height: settings.gifConfig.height,
+ frameRate: settings.gifConfig.frameRate,
+ loop: settings.gifConfig.loop,
+ sizePreset: settings.gifConfig.sizePreset,
+ wallpaper,
+ zoomRegions,
+ trimRegions,
+ speedRegions,
+ showShadow: shadowIntensity > 0,
+ shadowIntensity,
+ showBlur,
+ motionBlurEnabled,
+ borderRadius,
+ padding,
+ videoPadding: padding,
+ cropRegion,
+ annotationRegions,
+ previewWidth,
+ previewHeight,
+ onProgress: (progress: ExportProgress) => {
+ setExportProgress(progress);
+ },
+ });
+
+ exporterRef.current = gifExporter as unknown as VideoExporter;
+ const result = await gifExporter.export();
+
+ if (result.success && result.blob) {
+ const arrayBuffer = await result.blob.arrayBuffer();
+ const timestamp = Date.now();
+ const fileName = `export-${timestamp}.gif`;
+
+ const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
+
+ if (saveResult.canceled) {
+ toast.info("Export canceled");
+ } else if (saveResult.success) {
+ toast.success(`GIF exported successfully to ${saveResult.path}`);
+ } else {
+ setExportError(saveResult.message || "Failed to save GIF");
+ toast.error(saveResult.message || "Failed to save GIF");
+ }
+ } else {
+ setExportError(result.error || "GIF export failed");
+ toast.error(result.error || "GIF export failed");
+ }
+ } else {
+ // MP4 Export
+ const quality = settings.quality || exportQuality;
+ let exportWidth: number;
+ let exportHeight: number;
+ let bitrate: number;
+
+ if (quality === "source") {
+ // Use source resolution
+ exportWidth = sourceWidth;
+ exportHeight = sourceHeight;
+
+ if (aspectRatioValue === 1) {
+ // Square (1:1): use smaller dimension to avoid codec limits
+ const baseDimension = Math.floor(Math.min(sourceWidth, sourceHeight) / 2) * 2;
+ exportWidth = baseDimension;
+ exportHeight = baseDimension;
+ } else if (aspectRatioValue > 1) {
+ // Landscape: find largest even dimensions that exactly match aspect ratio
+ const baseWidth = Math.floor(sourceWidth / 2) * 2;
+ let found = false;
+ for (let w = baseWidth; w >= 100 && !found; w -= 2) {
+ const h = Math.round(w / aspectRatioValue);
+ if (h % 2 === 0 && Math.abs(w / h - aspectRatioValue) < 0.0001) {
+ exportWidth = w;
+ exportHeight = h;
+ found = true;
+ }
+ }
+ if (!found) {
+ exportWidth = baseWidth;
+ exportHeight = Math.floor(baseWidth / aspectRatioValue / 2) * 2;
+ }
+ } else {
+ // Portrait: find largest even dimensions that exactly match aspect ratio
+ const baseHeight = Math.floor(sourceHeight / 2) * 2;
+ let found = false;
+ for (let h = baseHeight; h >= 100 && !found; h -= 2) {
+ const w = Math.round(h * aspectRatioValue);
+ if (w % 2 === 0 && Math.abs(w / h - aspectRatioValue) < 0.0001) {
+ exportWidth = w;
+ exportHeight = h;
+ found = true;
+ }
+ }
+ if (!found) {
+ exportHeight = baseHeight;
+ exportWidth = Math.floor((baseHeight * aspectRatioValue) / 2) * 2;
+ }
+ }
+
+ // Calculate visually lossless bitrate matching screen recording optimization
+ const totalPixels = exportWidth * exportHeight;
+ bitrate = 30_000_000;
+ if (totalPixels > 1920 * 1080 && totalPixels <= 2560 * 1440) {
+ bitrate = 50_000_000;
+ } else if (totalPixels > 2560 * 1440) {
+ bitrate = 80_000_000;
+ }
+ } else {
+ // Use quality-based target resolution
+ const targetHeight = quality === "medium" ? 720 : 1080;
+
+ // Calculate dimensions maintaining aspect ratio
+ exportHeight = Math.floor(targetHeight / 2) * 2;
+ exportWidth = Math.floor((exportHeight * aspectRatioValue) / 2) * 2;
+
+ // Adjust bitrate for lower resolutions
+ const totalPixels = exportWidth * exportHeight;
+ if (totalPixels <= 1280 * 720) {
+ bitrate = 10_000_000;
+ } else if (totalPixels <= 1920 * 1080) {
+ bitrate = 20_000_000;
+ } else {
+ bitrate = 30_000_000;
+ }
+ }
+
+ const exporter = new VideoExporter({
+ videoUrl: videoPath,
+ width: exportWidth,
+ height: exportHeight,
+ frameRate: 60,
+ bitrate,
+ codec: "avc1.640033",
+ wallpaper,
+ zoomRegions,
+ trimRegions,
+ speedRegions,
+ showShadow: shadowIntensity > 0,
+ shadowIntensity,
+ showBlur,
+ motionBlurEnabled,
+ borderRadius,
+ padding,
+ cropRegion,
+ annotationRegions,
+ previewWidth,
+ previewHeight,
+ onProgress: (progress: ExportProgress) => {
+ setExportProgress(progress);
+ },
+ });
+
+ exporterRef.current = exporter;
+ const result = await exporter.export();
+
+ if (result.success && result.blob) {
+ const arrayBuffer = await result.blob.arrayBuffer();
+ const timestamp = Date.now();
+ const fileName = `export-${timestamp}.mp4`;
+
+ const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
+
+ if (saveResult.canceled) {
+ toast.info("Export canceled");
+ } else if (saveResult.success) {
+ toast.success(`Video exported successfully to ${saveResult.path}`);
+ } else {
+ setExportError(saveResult.message || "Failed to save video");
+ toast.error(saveResult.message || "Failed to save video");
+ }
+ } else {
+ setExportError(result.error || "Export failed");
+ toast.error(result.error || "Export failed");
+ }
+ }
+
+ if (wasPlaying) {
+ videoPlaybackRef.current?.play();
+ }
+ } catch (error) {
+ console.error("Export error:", error);
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
+ setExportError(errorMessage);
+ toast.error(`Export failed: ${errorMessage}`);
+ } finally {
+ setIsExporting(false);
+ exporterRef.current = null;
+ // Reset dialog state to ensure it can be opened again on next export
+ // This fixes the bug where second export doesn't show save dialog
+ setShowExportDialog(false);
+ setExportProgress(null);
+ }
+ },
+ [
+ videoPath,
+ wallpaper,
+ zoomRegions,
+ trimRegions,
+ speedRegions,
+ shadowIntensity,
+ showBlur,
+ motionBlurEnabled,
+ borderRadius,
+ padding,
+ cropRegion,
+ annotationRegions,
+ isPlaying,
+ aspectRatio,
+ exportQuality,
+ ],
+ );
+
+ const handleOpenExportDialog = useCallback(() => {
+ if (!videoPath) {
+ toast.error("No video loaded");
+ return;
+ }
+
+ const video = videoPlaybackRef.current?.video;
+ if (!video) {
+ toast.error("Video not ready");
+ return;
+ }
+
+ // Build export settings from current state
+ const sourceWidth = video.videoWidth || 1920;
+ const sourceHeight = video.videoHeight || 1080;
+ const gifDimensions = calculateOutputDimensions(
+ sourceWidth,
+ sourceHeight,
+ gifSizePreset,
+ GIF_SIZE_PRESETS,
+ );
+
+ const settings: ExportSettings = {
+ format: exportFormat,
+ quality: exportFormat === "mp4" ? exportQuality : undefined,
+ gifConfig:
+ exportFormat === "gif"
+ ? {
+ frameRate: gifFrameRate,
+ loop: gifLoop,
+ sizePreset: gifSizePreset,
+ width: gifDimensions.width,
+ height: gifDimensions.height,
+ }
+ : undefined,
+ };
+
+ setShowExportDialog(true);
+ setExportError(null);
+
+ // Start export immediately
+ handleExport(settings);
+ }, [videoPath, exportFormat, exportQuality, gifFrameRate, gifLoop, gifSizePreset, handleExport]);
+
+ const handleCancelExport = useCallback(() => {
+ if (exporterRef.current) {
+ exporterRef.current.cancel();
+ toast.info("Export canceled");
+ setShowExportDialog(false);
+ setIsExporting(false);
+ setExportProgress(null);
+ setExportError(null);
+ }
+ }, []);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-screen bg-background">
+ <div className="text-foreground">Loading video...</div>
+ </div>
+ );
+ }
+ if (error) {
+ return (
+ <div className="flex items-center justify-center h-screen bg-background">
+ <div className="flex flex-col items-center gap-3">
+ <div className="text-destructive">{error}</div>
+ <button
+ type="button"
+ onClick={handleLoadProject}
+ className="px-3 py-1.5 rounded-md bg-[#34B27B] text-white text-sm hover:bg-[#34B27B]/90"
+ >
+ Load Project File
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-screen bg-[#09090b] text-slate-200 overflow-hidden selection:bg-[#34B27B]/30">
+ <div
+ className="h-10 flex-shrink-0 bg-[#09090b]/80 backdrop-blur-md border-b border-white/5 flex items-center justify-between px-6 z-50"
+ style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
+ >
+ <div className="flex-1" />
+ </div>
+
+ <div className="flex-1 p-5 gap-4 flex min-h-0 relative">
+ {/* Left Column - Video & Timeline */}
+ <div className="flex-[7] flex flex-col gap-3 min-w-0 h-full">
+ <PanelGroup direction="vertical" className="gap-3">
+ {/* Top section: video preview and controls */}
+ <Panel defaultSize={70} minSize={40}>
+ <div className="w-full h-full flex flex-col items-center justify-center bg-black/40 rounded-2xl border border-white/5 shadow-2xl overflow-hidden">
+ {/* Video preview */}
+ <div
+ className="w-full flex justify-center items-center"
+ style={{ flex: "1 1 auto", margin: "6px 0 0" }}
+ >
+ <div
+ className="relative"
+ style={{
+ width: "auto",
+ height: "100%",
- aspectRatio: getAspectRatioValue(aspectRatio),
++ aspectRatio:
++ aspectRatio === "native"
++ ? getNativeAspectRatioValue(
++ videoPlaybackRef.current?.video?.videoWidth || 1920,
++ videoPlaybackRef.current?.video?.videoHeight || 1080,
++ cropRegion,
++ )
++ : getAspectRatioValue(aspectRatio),
+ maxWidth: "100%",
+ margin: "0 auto",
+ boxSizing: "border-box",
+ }}
+ >
+ <VideoPlayback
+ key={videoPath || "no-video"}
+ aspectRatio={aspectRatio}
+ ref={videoPlaybackRef}
+ videoPath={videoPath || ""}
+ onDurationChange={setDuration}
+ onTimeUpdate={setCurrentTime}
+ currentTime={currentTime}
+ onPlayStateChange={setIsPlaying}
+ onError={setError}
+ wallpaper={wallpaper}
+ zoomRegions={zoomRegions}
+ selectedZoomId={selectedZoomId}
+ onSelectZoom={handleSelectZoom}
+ onZoomFocusChange={handleZoomFocusChange}
+ onZoomFocusDragEnd={commitState}
+ isPlaying={isPlaying}
+ showShadow={shadowIntensity > 0}
+ shadowIntensity={shadowIntensity}
+ showBlur={showBlur}
+ motionBlurEnabled={motionBlurEnabled}
+ borderRadius={borderRadius}
+ padding={padding}
+ cropRegion={cropRegion}
+ trimRegions={trimRegions}
+ speedRegions={speedRegions}
+ annotationRegions={annotationRegions}
+ selectedAnnotationId={selectedAnnotationId}
+ onSelectAnnotation={handleSelectAnnotation}
+ onAnnotationPositionChange={handleAnnotationPositionChange}
+ onAnnotationSizeChange={handleAnnotationSizeChange}
+ />
+ </div>
+ </div>
+ {/* Playback controls */}
+ <div
+ className="w-full flex justify-center items-center"
+ style={{
+ height: "48px",
+ flexShrink: 0,
+ padding: "6px 12px",
+ margin: "6px 0 6px 0",
+ }}
+ >
+ <div style={{ width: "100%", maxWidth: "700px" }}>
+ <PlaybackControls
+ isPlaying={isPlaying}
+ currentTime={currentTime}
+ duration={duration}
+ onTogglePlayPause={togglePlayPause}
+ onSeek={handleSeek}
+ />
+ </div>
+ </div>
+ </div>
+ </Panel>
+
+ <PanelResizeHandle className="h-3 bg-[#09090b]/80 hover:bg-[#09090b] transition-colors rounded-full mx-4 flex items-center justify-center">
+ <div className="w-8 h-1 bg-white/20 rounded-full"></div>
+ </PanelResizeHandle>
+
+ {/* Timeline section */}
+ <Panel defaultSize={30} minSize={20}>
+ <div className="h-full bg-[#09090b] rounded-2xl border border-white/5 shadow-lg overflow-hidden flex flex-col">
+ <TimelineEditor
+ videoDuration={duration}
+ currentTime={currentTime}
+ onSeek={handleSeek}
+ cursorTelemetry={cursorTelemetry}
+ zoomRegions={zoomRegions}
+ onZoomAdded={handleZoomAdded}
+ onZoomSuggested={handleZoomSuggested}
+ onZoomSpanChange={handleZoomSpanChange}
+ onZoomDelete={handleZoomDelete}
+ selectedZoomId={selectedZoomId}
+ onSelectZoom={handleSelectZoom}
+ trimRegions={trimRegions}
+ onTrimAdded={handleTrimAdded}
+ onTrimSpanChange={handleTrimSpanChange}
+ onTrimDelete={handleTrimDelete}
+ selectedTrimId={selectedTrimId}
+ onSelectTrim={handleSelectTrim}
+ speedRegions={speedRegions}
+ onSpeedAdded={handleSpeedAdded}
+ onSpeedSpanChange={handleSpeedSpanChange}
+ onSpeedDelete={handleSpeedDelete}
+ selectedSpeedId={selectedSpeedId}
+ onSelectSpeed={handleSelectSpeed}
+ annotationRegions={annotationRegions}
+ onAnnotationAdded={handleAnnotationAdded}
+ onAnnotationSpanChange={handleAnnotationSpanChange}
+ onAnnotationDelete={handleAnnotationDelete}
+ selectedAnnotationId={selectedAnnotationId}
+ onSelectAnnotation={handleSelectAnnotation}
+ aspectRatio={aspectRatio}
+ onAspectRatioChange={(ar) => pushState({ aspectRatio: ar })}
+ />
+ </div>
+ </Panel>
+ </PanelGroup>
+ </div>
+
+ {/* Right section: settings panel */}
+ <SettingsPanel
+ selected={wallpaper}
+ onWallpaperChange={(w) => pushState({ wallpaper: w })}
+ selectedZoomDepth={
+ selectedZoomId ? zoomRegions.find((z) => z.id === selectedZoomId)?.depth : null
+ }
+ onZoomDepthChange={(depth) => selectedZoomId && handleZoomDepthChange(depth)}
+ selectedZoomId={selectedZoomId}
+ onZoomDelete={handleZoomDelete}
+ selectedTrimId={selectedTrimId}
+ onTrimDelete={handleTrimDelete}
+ shadowIntensity={shadowIntensity}
+ onShadowChange={(v) => updateState({ shadowIntensity: v })}
+ onShadowCommit={commitState}
+ showBlur={showBlur}
+ onBlurChange={(v) => pushState({ showBlur: v })}
+ motionBlurEnabled={motionBlurEnabled}
+ onMotionBlurChange={(v) => pushState({ motionBlurEnabled: v })}
+ borderRadius={borderRadius}
+ onBorderRadiusChange={(v) => updateState({ borderRadius: v })}
+ onBorderRadiusCommit={commitState}
+ padding={padding}
+ onPaddingChange={(v) => updateState({ padding: v })}
+ onPaddingCommit={commitState}
+ cropRegion={cropRegion}
+ onCropChange={(r) => pushState({ cropRegion: r })}
+ aspectRatio={aspectRatio}
+ videoElement={videoPlaybackRef.current?.video || null}
+ exportQuality={exportQuality}
+ onExportQualityChange={setExportQuality}
+ exportFormat={exportFormat}
+ onExportFormatChange={setExportFormat}
+ gifFrameRate={gifFrameRate}
+ onGifFrameRateChange={setGifFrameRate}
+ gifLoop={gifLoop}
+ onGifLoopChange={setGifLoop}
+ gifSizePreset={gifSizePreset}
+ onGifSizePresetChange={setGifSizePreset}
+ gifOutputDimensions={calculateOutputDimensions(
+ videoPlaybackRef.current?.video?.videoWidth || 1920,
+ videoPlaybackRef.current?.video?.videoHeight || 1080,
+ gifSizePreset,
+ GIF_SIZE_PRESETS,
+ )}
+ onExport={handleOpenExportDialog}
+ selectedAnnotationId={selectedAnnotationId}
+ annotationRegions={annotationRegions}
+ onAnnotationContentChange={handleAnnotationContentChange}
+ onAnnotationTypeChange={handleAnnotationTypeChange}
+ onAnnotationStyleChange={handleAnnotationStyleChange}
+ onAnnotationFigureDataChange={handleAnnotationFigureDataChange}
+ onAnnotationDelete={handleAnnotationDelete}
+ onSaveProject={handleSaveProject}
+ onLoadProject={handleLoadProject}
+ selectedSpeedId={selectedSpeedId}
+ selectedSpeedValue={
+ selectedSpeedId
+ ? (speedRegions.find((r) => r.id === selectedSpeedId)?.speed ?? null)
+ : null
+ }
+ onSpeedChange={handleSpeedChange}
+ onSpeedDelete={handleSpeedDelete}
+ />
+ </div>
+
+ <Toaster theme="dark" className="pointer-events-auto" />
+
+ <ExportDialog
+ isOpen={showExportDialog}
+ onClose={() => setShowExportDialog(false)}
+ progress={exportProgress}
+ isExporting={isExporting}
+ error={exportError}
+ onCancel={handleCancelExport}
+ exportFormat={exportFormat}
+ />
+ </div>
+ );
}
diff --cc src/components/video-editor/VideoPlayback.tsx
index 7ca784c67,98a4c236d..3184daf5f
--- a/src/components/video-editor/VideoPlayback.tsx
+++ b/src/components/video-editor/VideoPlayback.tsx
@@@ -1,898 -1,986 +1,1002 @@@
+ import {
+ Application,
+ BlurFilter,
+ Container,
+ Graphics,
+ Sprite,
+ Texture,
+ VideoSource,
+ } from "pixi.js";
import type React from "react";
- import { useEffect, useRef, useImperativeHandle, forwardRef, useState, useMemo, useCallback } from "react";
+ import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+ } from "react";
import { getAssetPath } from "@/lib/assetPath";
- import { Application, Container, Sprite, Graphics, BlurFilter, Texture, VideoSource } from 'pixi.js';
- import { ZOOM_DEPTH_SCALES, type ZoomRegion, type ZoomFocus, type ZoomDepth, type TrimRegion, type SpeedRegion, type AnnotationRegion } from "./types";
- import { DEFAULT_FOCUS, SMOOTHING_FACTOR, MIN_DELTA } from "./videoPlayback/constants";
- import { clamp01 } from "./videoPlayback/mathUtils";
- import { findDominantRegion } from "./videoPlayback/zoomRegionUtils";
-import { type AspectRatio, formatAspectRatioForCSS } from "@/utils/aspectRatioUtils";
++import {
++ type AspectRatio,
++ formatAspectRatioForCSS,
++ getNativeAspectRatioValue,
++} from "@/utils/aspectRatioUtils";
+ import { AnnotationOverlay } from "./AnnotationOverlay";
+ import {
+ type AnnotationRegion,
+ type SpeedRegion,
+ type TrimRegion,
+ ZOOM_DEPTH_SCALES,
+ type ZoomDepth,
+ type ZoomFocus,
+ type ZoomRegion,
+ } from "./types";
+ import { DEFAULT_FOCUS, MIN_DELTA, SMOOTHING_FACTOR } from "./videoPlayback/constants";
import { clampFocusToStage as clampFocusToStageUtil } from "./videoPlayback/focusUtils";
- import { updateOverlayIndicator } from "./videoPlayback/overlayUtils";
import { layoutVideoContent as layoutVideoContentUtil } from "./videoPlayback/layoutUtils";
- import { applyZoomTransform } from "./videoPlayback/zoomTransform";
+ import { clamp01 } from "./videoPlayback/mathUtils";
+ import { updateOverlayIndicator } from "./videoPlayback/overlayUtils";
import { createVideoEventHandlers } from "./videoPlayback/videoEventHandlers";
- import { type AspectRatio, formatAspectRatioForCSS, getNativeAspectRatioValue } from "@/utils/aspectRatioUtils";
- import { AnnotationOverlay } from "./AnnotationOverlay";
+ import { findDominantRegion } from "./videoPlayback/zoomRegionUtils";
+ import { applyZoomTransform } from "./videoPlayback/zoomTransform";
interface VideoPlaybackProps {
- videoPath: string;
- onDurationChange: (duration: number) => void;
- onTimeUpdate: (time: number) => void;
- currentTime: number;
- onPlayStateChange: (playing: boolean) => void;
- onError: (error: string) => void;
- wallpaper?: string;
- zoomRegions: ZoomRegion[];
- selectedZoomId: string | null;
- onSelectZoom: (id: string | null) => void;
- onZoomFocusChange: (id: string, focus: ZoomFocus) => void;
- isPlaying: boolean;
- showShadow?: boolean;
- shadowIntensity?: number;
- showBlur?: boolean;
- motionBlurEnabled?: boolean;
- borderRadius?: number;
- padding?: number;
- cropRegion?: import('./types').CropRegion;
- trimRegions?: TrimRegion[];
- speedRegions?: SpeedRegion[];
- aspectRatio: AspectRatio;
- annotationRegions?: AnnotationRegion[];
- selectedAnnotationId?: string | null;
- onSelectAnnotation?: (id: string | null) => void;
- onAnnotationPositionChange?: (id: string, position: { x: number; y: number }) => void;
- onAnnotationSizeChange?: (id: string, size: { width: number; height: number }) => void;
+ videoPath: string;
+ onDurationChange: (duration: number) => void;
+ onTimeUpdate: (time: number) => void;
+ currentTime: number;
+ onPlayStateChange: (playing: boolean) => void;
+ onError: (error: string) => void;
+ wallpaper?: string;
+ zoomRegions: ZoomRegion[];
+ selectedZoomId: string | null;
+ onSelectZoom: (id: string | null) => void;
+ onZoomFocusChange: (id: string, focus: ZoomFocus) => void;
+ onZoomFocusDragEnd?: () => void;
+ isPlaying: boolean;
+ showShadow?: boolean;
+ shadowIntensity?: number;
+ showBlur?: boolean;
+ motionBlurEnabled?: boolean;
+ borderRadius?: number;
+ padding?: number;
+ cropRegion?: import("./types").CropRegion;
+ trimRegions?: TrimRegion[];
+ speedRegions?: SpeedRegion[];
+ aspectRatio: AspectRatio;
+ annotationRegions?: AnnotationRegion[];
+ selectedAnnotationId?: string | null;
+ onSelectAnnotation?: (id: string | null) => void;
+ onAnnotationPositionChange?: (id: string, position: { x: number; y: number }) => void;
+ onAnnotationSizeChange?: (id: string, size: { width: number; height: number }) => void;
}
export interface VideoPlaybackRef {
- video: HTMLVideoElement | null;
- app: Application | null;
- videoSprite: Sprite | null;
- videoContainer: Container | null;
- containerRef: React.RefObject<HTMLDivElement>;
- play: () => Promise<void>;
- pause: () => void;
+ video: HTMLVideoElement | null;
+ app: Application | null;
+ videoSprite: Sprite | null;
+ videoContainer: Container | null;
+ containerRef: React.RefObject<HTMLDivElement>;
+ play: () => Promise<void>;
+ pause: () => void;
}
- const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(({
- videoPath,
- onDurationChange,
- onTimeUpdate,
- currentTime,
- onPlayStateChange,
- onError,
- wallpaper,
- zoomRegions,
- selectedZoomId,
- onSelectZoom,
- onZoomFocusChange,
- isPlaying,
- showShadow,
- shadowIntensity = 0,
- showBlur,
- motionBlurEnabled = false,
- borderRadius = 0,
- padding = 50,
- cropRegion,
- trimRegions = [],
- speedRegions = [],
- aspectRatio,
- annotationRegions = [],
- selectedAnnotationId,
- onSelectAnnotation,
- onAnnotationPositionChange,
- onAnnotationSizeChange,
- }, ref) => {
- const videoRef = useRef<HTMLVideoElement | null>(null);
- const containerRef = useRef<HTMLDivElement | null>(null);
- const appRef = useRef<Application | null>(null);
- const videoSpriteRef = useRef<Sprite | null>(null);
- const videoContainerRef = useRef<Container | null>(null);
- const cameraContainerRef = useRef<Container | null>(null);
- const timeUpdateAnimationRef = useRef<number | null>(null);
- const [pixiReady, setPixiReady] = useState(false);
- const [videoReady, setVideoReady] = useState(false);
- const overlayRef = useRef<HTMLDivElement | null>(null);
- const focusIndicatorRef = useRef<HTMLDivElement | null>(null);
- const currentTimeRef = useRef(0);
- const zoomRegionsRef = useRef<ZoomRegion[]>([]);
- const selectedZoomIdRef = useRef<string | null>(null);
- const animationStateRef = useRef({ scale: 1, focusX: DEFAULT_FOCUS.cx, focusY: DEFAULT_FOCUS.cy });
- const blurFilterRef = useRef<BlurFilter | null>(null);
- const isDraggingFocusRef = useRef(false);
- const stageSizeRef = useRef({ width: 0, height: 0 });
- const videoSizeRef = useRef({ width: 0, height: 0 });
- const baseScaleRef = useRef(1);
- const baseOffsetRef = useRef({ x: 0, y: 0 });
- const baseMaskRef = useRef({ x: 0, y: 0, width: 0, height: 0 });
- const cropBoundsRef = useRef({ startX: 0, endX: 0, startY: 0, endY: 0 });
- const maskGraphicsRef = useRef<Graphics | null>(null);
- const isPlayingRef = useRef(isPlaying);
- const isSeekingRef = useRef(false);
- const allowPlaybackRef = useRef(false);
- const lockedVideoDimensionsRef = useRef<{ width: number; height: number } | null>(null);
- const layoutVideoContentRef = useRef<(() => void) | null>(null);
- const trimRegionsRef = useRef<TrimRegion[]>([]);
- const speedRegionsRef = useRef<SpeedRegion[]>([]);
- const motionBlurEnabledRef = useRef(motionBlurEnabled);
- const videoReadyRafRef = useRef<number | null>(null);
-
- const clampFocusToStage = useCallback((focus: ZoomFocus, depth: ZoomDepth) => {
- return clampFocusToStageUtil(focus, depth, stageSizeRef.current);
- }, []);
-
- const updateOverlayForRegion = useCallback((region: ZoomRegion | null, focusOverride?: ZoomFocus) => {
- const overlayEl = overlayRef.current;
- const indicatorEl = focusIndicatorRef.current;
-
- if (!overlayEl || !indicatorEl) {
- return;
- }
-
- // Update stage size from overlay dimensions
- const stageWidth = overlayEl.clientWidth;
- const stageHeight = overlayEl.clientHeight;
- if (stageWidth && stageHeight) {
- stageSizeRef.current = { width: stageWidth, height: stageHeight };
- }
-
- updateOverlayIndicator({
- overlayEl,
- indicatorEl,
- region,
- focusOverride,
- videoSize: videoSizeRef.current,
- baseScale: baseScaleRef.current,
- isPlaying: isPlayingRef.current,
- });
- }, []);
-
- const layoutVideoContent = useCallback(() => {
- const container = containerRef.current;
- const app = appRef.current;
- const videoSprite = videoSpriteRef.current;
- const maskGraphics = maskGraphicsRef.current;
- const videoElement = videoRef.current;
- const cameraContainer = cameraContainerRef.current;
-
- if (!container || !app || !videoSprite || !maskGraphics || !videoElement || !cameraContainer) {
- return;
- }
-
- // Lock video dimensions on first layout to prevent resize issues
- if (!lockedVideoDimensionsRef.current && videoElement.videoWidth > 0 && videoElement.videoHeight > 0) {
- lockedVideoDimensionsRef.current = {
- width: videoElement.videoWidth,
- height: videoElement.videoHeight,
- };
- }
-
- const result = layoutVideoContentUtil({
- container,
- app,
- videoSprite,
- maskGraphics,
- videoElement,
- cropRegion,
- lockedVideoDimensions: lockedVideoDimensionsRef.current,
- borderRadius,
- padding,
- });
-
- if (result) {
- stageSizeRef.current = result.stageSize;
- videoSizeRef.current = result.videoSize;
- baseScaleRef.current = result.baseScale;
- baseOffsetRef.current = result.baseOffset;
- baseMaskRef.current = result.maskRect;
- cropBoundsRef.current = result.cropBounds;
-
- // Reset camera container to identity
- cameraContainer.scale.set(1);
- cameraContainer.position.set(0, 0);
-
- const selectedId = selectedZoomIdRef.current;
- const activeRegion = selectedId
- ? zoomRegionsRef.current.find((region) => region.id === selectedId) ?? null
- : null;
-
- updateOverlayForRegion(activeRegion);
- }
- }, [updateOverlayForRegion, cropRegion, borderRadius, padding]);
-
- useEffect(() => {
- layoutVideoContentRef.current = layoutVideoContent;
- }, [layoutVideoContent]);
-
- const selectedZoom = useMemo(() => {
- if (!selectedZoomId) return null;
- return zoomRegions.find((region) => region.id === selectedZoomId) ?? null;
- }, [zoomRegions, selectedZoomId]);
-
- useImperativeHandle(ref, () => ({
- video: videoRef.current,
- app: appRef.current,
- videoSprite: videoSpriteRef.current,
- videoContainer: videoContainerRef.current,
- containerRef,
- play: async () => {
- const vid = videoRef.current;
- if (!vid) return;
- try {
- allowPlaybackRef.current = true;
- await vid.play();
- } catch (error) {
- allowPlaybackRef.current = false;
- throw error;
- }
- },
- pause: () => {
- const video = videoRef.current;
- allowPlaybackRef.current = false;
- if (!video) {
- return;
- }
- video.pause();
- },
- }));
-
- const updateFocusFromClientPoint = (clientX: number, clientY: number) => {
- const overlayEl = overlayRef.current;
- if (!overlayEl) return;
-
- const regionId = selectedZoomIdRef.current;
- if (!regionId) return;
-
- const region = zoomRegionsRef.current.find((r) => r.id === regionId);
- if (!region) return;
-
- const rect = overlayEl.getBoundingClientRect();
- const stageWidth = rect.width;
- const stageHeight = rect.height;
-
- if (!stageWidth || !stageHeight) {
- return;
- }
-
- stageSizeRef.current = { width: stageWidth, height: stageHeight };
-
- const localX = clientX - rect.left;
- const localY = clientY - rect.top;
-
- const unclampedFocus: ZoomFocus = {
- cx: clamp01(localX / stageWidth),
- cy: clamp01(localY / stageHeight),
- };
- const clampedFocus = clampFocusToStage(unclampedFocus, region.depth);
-
- onZoomFocusChange(region.id, clampedFocus);
- updateOverlayForRegion({ ...region, focus: clampedFocus }, clampedFocus);
- };
-
- const handleOverlayPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
- if (isPlayingRef.current) return;
- const regionId = selectedZoomIdRef.current;
- if (!regionId) return;
- const region = zoomRegionsRef.current.find((r) => r.id === regionId);
- if (!region) return;
- onSelectZoom(region.id);
- event.preventDefault();
- isDraggingFocusRef.current = true;
- event.currentTarget.setPointerCapture(event.pointerId);
- updateFocusFromClientPoint(event.clientX, event.clientY);
- };
-
- const handleOverlayPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
- if (!isDraggingFocusRef.current) return;
- event.preventDefault();
- updateFocusFromClientPoint(event.clientX, event.clientY);
- };
-
- const endFocusDrag = (event: React.PointerEvent<HTMLDivElement>) => {
- if (!isDraggingFocusRef.current) return;
- isDraggingFocusRef.current = false;
- try {
- event.currentTarget.releasePointerCapture(event.pointerId);
- } catch {
-
- }
- };
-
- const handleOverlayPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
- endFocusDrag(event);
- };
-
- const handleOverlayPointerLeave = (event: React.PointerEvent<HTMLDivElement>) => {
- endFocusDrag(event);
- };
-
- useEffect(() => {
- zoomRegionsRef.current = zoomRegions;
- }, [zoomRegions]);
-
- useEffect(() => {
- selectedZoomIdRef.current = selectedZoomId;
- }, [selectedZoomId]);
-
- useEffect(() => {
- isPlayingRef.current = isPlaying;
- }, [isPlaying]);
-
- useEffect(() => {
- trimRegionsRef.current = trimRegions;
- }, [trimRegions]);
-
- useEffect(() => {
- speedRegionsRef.current = speedRegions;
- }, [speedRegions]);
-
- useEffect(() => {
- motionBlurEnabledRef.current = motionBlurEnabled;
- }, [motionBlurEnabled]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
-
- const app = appRef.current;
- const cameraContainer = cameraContainerRef.current;
- const video = videoRef.current;
-
- if (!app || !cameraContainer || !video) return;
-
- const tickerWasStarted = app.ticker?.started || false;
- if (tickerWasStarted && app.ticker) {
- app.ticker.stop();
- }
-
- const wasPlaying = !video.paused;
- if (wasPlaying) {
- video.pause();
- }
-
- animationStateRef.current = {
- scale: 1,
- focusX: DEFAULT_FOCUS.cx,
- focusY: DEFAULT_FOCUS.cy,
- };
-
- if (blurFilterRef.current) {
- blurFilterRef.current.blur = 0;
- }
-
- requestAnimationFrame(() => {
- const container = cameraContainerRef.current;
- const videoStage = videoContainerRef.current;
- const sprite = videoSpriteRef.current;
- const currentApp = appRef.current;
- if (!container || !videoStage || !sprite || !currentApp) {
- return;
- }
-
- container.scale.set(1);
- container.position.set(0, 0);
- videoStage.scale.set(1);
- videoStage.position.set(0, 0);
- sprite.scale.set(1);
- sprite.position.set(0, 0);
-
- layoutVideoContent();
-
- applyZoomTransform({
- cameraContainer: container,
- blurFilter: blurFilterRef.current,
- stageSize: stageSizeRef.current,
- baseMask: baseMaskRef.current,
- zoomScale: 1,
- focusX: DEFAULT_FOCUS.cx,
- focusY: DEFAULT_FOCUS.cy,
- motionIntensity: 0,
- isPlaying: false,
- motionBlurEnabled: motionBlurEnabledRef.current,
- });
-
- requestAnimationFrame(() => {
- const finalApp = appRef.current;
- if (wasPlaying && video) {
- video.play().catch(() => {
- });
- }
- if (tickerWasStarted && finalApp?.ticker) {
- finalApp.ticker.start();
- }
- });
- });
- }, [pixiReady, videoReady, layoutVideoContent, cropRegion]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
- const container = containerRef.current;
- if (!container) return;
-
- if (typeof ResizeObserver === 'undefined') {
- return;
- }
-
- const observer = new ResizeObserver(() => {
- layoutVideoContent();
- });
-
- observer.observe(container);
- return () => {
- observer.disconnect();
- };
- }, [pixiReady, videoReady, layoutVideoContent]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
- updateOverlayForRegion(selectedZoom);
- }, [selectedZoom, pixiReady, videoReady, updateOverlayForRegion]);
-
- useEffect(() => {
- const overlayEl = overlayRef.current;
- if (!overlayEl) return;
- if (!selectedZoom) {
- overlayEl.style.cursor = 'default';
- overlayEl.style.pointerEvents = 'none';
- return;
- }
- overlayEl.style.cursor = isPlaying ? 'not-allowed' : 'grab';
- overlayEl.style.pointerEvents = isPlaying ? 'none' : 'auto';
- }, [selectedZoom, isPlaying]);
-
- useEffect(() => {
- const container = containerRef.current;
- if (!container) return;
-
- let mounted = true;
- let app: Application | null = null;
-
- (async () => {
- app = new Application();
-
- await app.init({
- width: container.clientWidth,
- height: container.clientHeight,
- backgroundAlpha: 0,
- antialias: true,
- resolution: window.devicePixelRatio || 1,
- autoDensity: true,
- });
-
- app.ticker.maxFPS = 60;
-
- if (!mounted) {
- app.destroy(true, { children: true, texture: true, textureSource: true });
- return;
- }
-
- appRef.current = app;
- container.appendChild(app.canvas);
-
- // Camera container - this will be scaled/positioned for zoom
- const cameraContainer = new Container();
- cameraContainerRef.current = cameraContainer;
- app.stage.addChild(cameraContainer);
-
- // Video container - holds the masked video sprite
- const videoContainer = new Container();
- videoContainerRef.current = videoContainer;
- cameraContainer.addChild(videoContainer);
-
- setPixiReady(true);
- })();
-
- return () => {
- mounted = false;
- setPixiReady(false);
- if (app && app.renderer) {
- app.destroy(true, { children: true, texture: true, textureSource: true });
- }
- appRef.current = null;
- cameraContainerRef.current = null;
- videoContainerRef.current = null;
- videoSpriteRef.current = null;
- };
- }, []);
-
- useEffect(() => {
- const video = videoRef.current;
- if (!video) return;
- video.pause();
- video.currentTime = 0;
- allowPlaybackRef.current = false;
- lockedVideoDimensionsRef.current = null;
- setVideoReady(false);
- if (videoReadyRafRef.current) {
- cancelAnimationFrame(videoReadyRafRef.current);
- videoReadyRafRef.current = null;
- }
- }, [videoPath]);
-
-
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
-
- const video = videoRef.current;
- const app = appRef.current;
- const videoContainer = videoContainerRef.current;
-
- if (!video || !app || !videoContainer) return;
- if (video.videoWidth === 0 || video.videoHeight === 0) return;
-
- const source = VideoSource.from(video);
- if ('autoPlay' in source) {
- (source as { autoPlay?: boolean }).autoPlay = false;
- }
- if ('autoUpdate' in source) {
- (source as { autoUpdate?: boolean }).autoUpdate = true;
- }
- const videoTexture = Texture.from(source);
-
- const videoSprite = new Sprite(videoTexture);
- videoSpriteRef.current = videoSprite;
-
- const maskGraphics = new Graphics();
- videoContainer.addChild(videoSprite);
- videoContainer.addChild(maskGraphics);
- videoContainer.mask = maskGraphics;
- maskGraphicsRef.current = maskGraphics;
-
- animationStateRef.current = {
- scale: 1,
- focusX: DEFAULT_FOCUS.cx,
- focusY: DEFAULT_FOCUS.cy,
- };
-
- const blurFilter = new BlurFilter();
- blurFilter.quality = 3;
- blurFilter.resolution = app.renderer.resolution;
- blurFilter.blur = 0;
- videoContainer.filters = [blurFilter];
- blurFilterRef.current = blurFilter;
-
- layoutVideoContent();
- video.pause();
-
- const { handlePlay, handlePause, handleSeeked, handleSeeking } = createVideoEventHandlers({
- video,
- isSeekingRef,
- isPlayingRef,
- allowPlaybackRef,
- currentTimeRef,
- timeUpdateAnimationRef,
- onPlayStateChange,
- onTimeUpdate,
- trimRegionsRef,
- speedRegionsRef,
- });
-
- video.addEventListener('play', handlePlay);
- video.addEventListener('pause', handlePause);
- video.addEventListener('ended', handlePause);
- video.addEventListener('seeked', handleSeeked);
- video.addEventListener('seeking', handleSeeking);
-
- return () => {
- video.removeEventListener('play', handlePlay);
- video.removeEventListener('pause', handlePause);
- video.removeEventListener('ended', handlePause);
- video.removeEventListener('seeked', handleSeeked);
- video.removeEventListener('seeking', handleSeeking);
-
- if (timeUpdateAnimationRef.current) {
- cancelAnimationFrame(timeUpdateAnimationRef.current);
- }
-
- if (videoSprite) {
- videoContainer.removeChild(videoSprite);
- videoSprite.destroy();
- }
- if (maskGraphics) {
- videoContainer.removeChild(maskGraphics);
- maskGraphics.destroy();
- }
- videoContainer.mask = null;
- maskGraphicsRef.current = null;
- if (blurFilterRef.current) {
- videoContainer.filters = [];
- blurFilterRef.current.destroy();
- blurFilterRef.current = null;
- }
- videoTexture.destroy(true);
-
- videoSpriteRef.current = null;
- };
- }, [pixiReady, videoReady, onTimeUpdate, updateOverlayForRegion]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
-
- const app = appRef.current;
- const videoSprite = videoSpriteRef.current;
- const videoContainer = videoContainerRef.current;
- if (!app || !videoSprite || !videoContainer) return;
-
- const applyTransform = (motionIntensity: number) => {
- const cameraContainer = cameraContainerRef.current;
- if (!cameraContainer) return;
-
- const state = animationStateRef.current;
-
- applyZoomTransform({
- cameraContainer,
- blurFilter: blurFilterRef.current,
- stageSize: stageSizeRef.current,
- baseMask: baseMaskRef.current,
- zoomScale: state.scale,
- focusX: state.focusX,
- focusY: state.focusY,
- motionIntensity,
- isPlaying: isPlayingRef.current,
- motionBlurEnabled: motionBlurEnabledRef.current,
- });
- };
-
- const ticker = () => {
- const { region, strength } = findDominantRegion(zoomRegionsRef.current, currentTimeRef.current);
-
- const defaultFocus = DEFAULT_FOCUS;
- let targetScaleFactor = 1;
- let targetFocus = defaultFocus;
-
- // If a zoom is selected but video is not playing, show default unzoomed view
- // (the overlay will show where the zoom will be)
- const selectedId = selectedZoomIdRef.current;
- const hasSelectedZoom = selectedId !== null;
- const shouldShowUnzoomedView = hasSelectedZoom && !isPlayingRef.current;
-
- if (region && strength > 0 && !shouldShowUnzoomedView) {
- const zoomScale = ZOOM_DEPTH_SCALES[region.depth];
- const regionFocus = clampFocusToStage(region.focus, region.depth);
-
- // Interpolate scale and focus based on region strength
- targetScaleFactor = 1 + (zoomScale - 1) * strength;
- targetFocus = {
- cx: defaultFocus.cx + (regionFocus.cx - defaultFocus.cx) * strength,
- cy: defaultFocus.cy + (regionFocus.cy - defaultFocus.cy) * strength,
- };
- }
-
- const state = animationStateRef.current;
-
- const prevScale = state.scale;
- const prevFocusX = state.focusX;
- const prevFocusY = state.focusY;
-
- const scaleDelta = targetScaleFactor - state.scale;
- const focusXDelta = targetFocus.cx - state.focusX;
- const focusYDelta = targetFocus.cy - state.focusY;
-
- let nextScale = prevScale;
- let nextFocusX = prevFocusX;
- let nextFocusY = prevFocusY;
-
- if (Math.abs(scaleDelta) > MIN_DELTA) {
- nextScale = prevScale + scaleDelta * SMOOTHING_FACTOR;
- } else {
- nextScale = targetScaleFactor;
- }
-
- if (Math.abs(focusXDelta) > MIN_DELTA) {
- nextFocusX = prevFocusX + focusXDelta * SMOOTHING_FACTOR;
- } else {
- nextFocusX = targetFocus.cx;
- }
-
- if (Math.abs(focusYDelta) > MIN_DELTA) {
- nextFocusY = prevFocusY + focusYDelta * SMOOTHING_FACTOR;
- } else {
- nextFocusY = targetFocus.cy;
- }
-
- state.scale = nextScale;
- state.focusX = nextFocusX;
- state.focusY = nextFocusY;
-
- const motionIntensity = Math.max(
- Math.abs(nextScale - prevScale),
- Math.abs(nextFocusX - prevFocusX),
- Math.abs(nextFocusY - prevFocusY)
- );
-
- applyTransform(motionIntensity);
- };
-
- app.ticker.add(ticker);
- return () => {
- if (app && app.ticker) {
- app.ticker.remove(ticker);
- }
- };
- }, [pixiReady, videoReady, clampFocusToStage]);
-
- const handleLoadedMetadata = (e: React.SyntheticEvent<HTMLVideoElement, Event>) => {
- const video = e.currentTarget;
- onDurationChange(video.duration);
- video.currentTime = 0;
- video.pause();
- allowPlaybackRef.current = false;
- currentTimeRef.current = 0;
-
- if (videoReadyRafRef.current) {
- cancelAnimationFrame(videoReadyRafRef.current);
- videoReadyRafRef.current = null;
- }
-
- const waitForRenderableFrame = () => {
- const hasDimensions = video.videoWidth > 0 && video.videoHeight > 0;
- const hasData = video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA;
- if (hasDimensions && hasData) {
- videoReadyRafRef.current = null;
- setVideoReady(true);
- return;
- }
- videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);
- };
-
- videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);
- };
-
- const [resolvedWallpaper, setResolvedWallpaper] = useState<string | null>(null);
-
- useEffect(() => {
- let mounted = true
- ;(async () => {
- try {
- if (!wallpaper) {
- const def = await getAssetPath('wallpapers/wallpaper1.jpg')
- if (mounted) setResolvedWallpaper(def)
- return
- }
-
- if (wallpaper.startsWith('#') || wallpaper.startsWith('linear-gradient') || wallpaper.startsWith('radial-gradient')) {
- if (mounted) setResolvedWallpaper(wallpaper)
- return
- }
-
- // If it's a data URL (custom uploaded image), use as-is
- if (wallpaper.startsWith('data:')) {
- if (mounted) setResolvedWallpaper(wallpaper)
- return
- }
-
- // If it's an absolute web/http or file path, use as-is
- if (wallpaper.startsWith('http') || wallpaper.startsWith('file://') || wallpaper.startsWith('/')) {
- // If it's an absolute server path (starts with '/'), resolve via getAssetPath as well
- if (wallpaper.startsWith('/')) {
- const rel = wallpaper.replace(/^\//, '')
- const p = await getAssetPath(rel)
- if (mounted) setResolvedWallpaper(p)
- return
- }
- if (mounted) setResolvedWallpaper(wallpaper)
- return
- }
- const p = await getAssetPath(wallpaper.replace(/^\//, ''))
- if (mounted) setResolvedWallpaper(p)
- } catch (err) {
- if (mounted) setResolvedWallpaper(wallpaper || '/wallpapers/wallpaper1.jpg')
- }
- })()
- return () => { mounted = false }
- }, [wallpaper])
-
- useEffect(() => {
- return () => {
- if (videoReadyRafRef.current) {
- cancelAnimationFrame(videoReadyRafRef.current);
- videoReadyRafRef.current = null;
- }
- };
- }, [])
-
- const isImageUrl = Boolean(resolvedWallpaper && (resolvedWallpaper.startsWith('file://') || resolvedWallpaper.startsWith('http') || resolvedWallpaper.startsWith('/') || resolvedWallpaper.startsWith('data:')))
- const backgroundStyle = isImageUrl
- ? { backgroundImage: `url(${resolvedWallpaper || ''})` }
- : { background: resolvedWallpaper || '' };
-
- return (
- <div className="relative rounded-sm overflow-hidden" style={{ width: '100%', aspectRatio: formatAspectRatioForCSS(aspectRatio, aspectRatio === 'native' ? getNativeAspectRatioValue(lockedVideoDimensionsRef.current?.width || 1920, lockedVideoDimensionsRef.current?.height || 1080, cropRegion) : undefined) }}>
- {/* Background layer - always render as DOM element with blur */}
- <div
- className="absolute inset-0 bg-cover bg-center"
- style={{
- ...backgroundStyle,
- filter: showBlur ? 'blur(2px)' : 'none',
- }}
- />
- <div
- ref={containerRef}
- className="absolute inset-0"
- style={{
- filter: (showShadow && shadowIntensity > 0)
- ? `drop-shadow(0 ${shadowIntensity * 12}px ${shadowIntensity * 48}px rgba(0,0,0,${shadowIntensity * 0.7})) drop-shadow(0 ${shadowIntensity * 4}px ${shadowIntensity * 16}px rgba(0,0,0,${shadowIntensity * 0.5})) drop-shadow(0 ${shadowIntensity * 2}px ${shadowIntensity * 8}px rgba(0,0,0,${shadowIntensity * 0.3}))`
- : 'none',
- }}
- />
- {/* Only render overlay after PIXI and video are fully initialized */}
- {pixiReady && videoReady && (
- <div
- ref={overlayRef}
- className="absolute inset-0 select-none"
- style={{ pointerEvents: 'none' }}
- onPointerDown={handleOverlayPointerDown}
- onPointerMove={handleOverlayPointerMove}
- onPointerUp={handleOverlayPointerUp}
- onPointerLeave={handleOverlayPointerLeave}
- >
- <div
- ref={focusIndicatorRef}
- className="absolute rounded-md border border-[#34B27B]/80 bg-[#34B27B]/20 shadow-[0_0_0_1px_rgba(52,178,123,0.35)]"
- style={{ display: 'none', pointerEvents: 'none' }}
- />
- {(() => {
- const filtered = (annotationRegions || []).filter((annotation) => {
- if (typeof annotation.startMs !== 'number' || typeof annotation.endMs !== 'number') return false;
-
- if (annotation.id === selectedAnnotationId) return true;
-
- const timeMs = Math.round(currentTime * 1000);
- return timeMs >= annotation.startMs && timeMs <= annotation.endMs;
- });
-
- // Sort by z-index (lowest to highest) so higher z-index renders on top
- const sorted = [...filtered].sort((a, b) => a.zIndex - b.zIndex);
-
- // Handle click-through cycling: when clicking same annotation, cycle to next
- const handleAnnotationClick = (clickedId: string) => {
- if (!onSelectAnnotation) return;
-
- // If clicking on already selected annotation and there are multiple overlapping
- if (clickedId === selectedAnnotationId && sorted.length > 1) {
- // Find current index and cycle to next
- const currentIndex = sorted.findIndex(a => a.id === clickedId);
- const nextIndex = (currentIndex + 1) % sorted.length;
- onSelectAnnotation(sorted[nextIndex].id);
- } else {
- // First click or clicking different annotation
- onSelectAnnotation(clickedId);
- }
- };
-
- return sorted.map((annotation) => (
- <AnnotationOverlay
- key={annotation.id}
- annotation={annotation}
- isSelected={annotation.id === selectedAnnotationId}
- containerWidth={overlayRef.current?.clientWidth || 800}
- containerHeight={overlayRef.current?.clientHeight || 600}
- onPositionChange={(id, position) => onAnnotationPositionChange?.(id, position)}
- onSizeChange={(id, size) => onAnnotationSizeChange?.(id, size)}
- onClick={handleAnnotationClick}
- zIndex={annotation.zIndex}
- isSelectedBoost={annotation.id === selectedAnnotationId}
- />
- ));
- })()}
- </div>
- )}
- <video
- ref={videoRef}
- src={videoPath}
- className="hidden"
- preload="metadata"
- playsInline
- onLoadedMetadata={handleLoadedMetadata}
- onDurationChange={e => {
- onDurationChange(e.currentTarget.duration);
- }}
- onError={() => onError('Failed to load video')}
- />
- </div>
- );
- });
-
- VideoPlayback.displayName = 'VideoPlayback';
+ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(
+ (
+ {
+ videoPath,
+ onDurationChange,
+ onTimeUpdate,
+ currentTime,
+ onPlayStateChange,
+ onError,
+ wallpaper,
+ zoomRegions,
+ selectedZoomId,
+ onSelectZoom,
+ onZoomFocusChange,
+ onZoomFocusDragEnd,
+ isPlaying,
+ showShadow,
+ shadowIntensity = 0,
+ showBlur,
+ motionBlurEnabled = false,
+ borderRadius = 0,
+ padding = 50,
+ cropRegion,
+ trimRegions = [],
+ speedRegions = [],
+ aspectRatio,
+ annotationRegions = [],
+ selectedAnnotationId,
+ onSelectAnnotation,
+ onAnnotationPositionChange,
+ onAnnotationSizeChange,
+ },
+ ref,
+ ) => {
+ const videoRef = useRef<HTMLVideoElement | null>(null);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const appRef = useRef<Application | null>(null);
+ const videoSpriteRef = useRef<Sprite | null>(null);
+ const videoContainerRef = useRef<Container | null>(null);
+ const cameraContainerRef = useRef<Container | null>(null);
+ const timeUpdateAnimationRef = useRef<number | null>(null);
+ const [pixiReady, setPixiReady] = useState(false);
+ const [videoReady, setVideoReady] = useState(false);
+ const overlayRef = useRef<HTMLDivElement | null>(null);
+ const focusIndicatorRef = useRef<HTMLDivElement | null>(null);
+ const currentTimeRef = useRef(0);
+ const zoomRegionsRef = useRef<ZoomRegion[]>([]);
+ const selectedZoomIdRef = useRef<string | null>(null);
+ const animationStateRef = useRef({
+ scale: 1,
+ focusX: DEFAULT_FOCUS.cx,
+ focusY: DEFAULT_FOCUS.cy,
+ });
+ const blurFilterRef = useRef<BlurFilter | null>(null);
+ const isDraggingFocusRef = useRef(false);
+ const stageSizeRef = useRef({ width: 0, height: 0 });
+ const videoSizeRef = useRef({ width: 0, height: 0 });
+ const baseScaleRef = useRef(1);
+ const baseOffsetRef = useRef({ x: 0, y: 0 });
+ const baseMaskRef = useRef({ x: 0, y: 0, width: 0, height: 0 });
+ const cropBoundsRef = useRef({ startX: 0, endX: 0, startY: 0, endY: 0 });
+ const maskGraphicsRef = useRef<Graphics | null>(null);
+ const isPlayingRef = useRef(isPlaying);
+ const isSeekingRef = useRef(false);
+ const allowPlaybackRef = useRef(false);
+ const lockedVideoDimensionsRef = useRef<{ width: number; height: number } | null>(null);
+ const layoutVideoContentRef = useRef<(() => void) | null>(null);
+ const trimRegionsRef = useRef<TrimRegion[]>([]);
+ const speedRegionsRef = useRef<SpeedRegion[]>([]);
+ const motionBlurEnabledRef = useRef(motionBlurEnabled);
+ const onTimeUpdateRef = useRef(onTimeUpdate);
+ const onPlayStateChangeRef = useRef(onPlayStateChange);
+ const videoReadyRafRef = useRef<number | null>(null);
+
+ const clampFocusToStage = useCallback((focus: ZoomFocus, depth: ZoomDepth) => {
+ return clampFocusToStageUtil(focus, depth, stageSizeRef.current);
+ }, []);
+
+ const updateOverlayForRegion = useCallback(
+ (region: ZoomRegion | null, focusOverride?: ZoomFocus) => {
+ const overlayEl = overlayRef.current;
+ const indicatorEl = focusIndicatorRef.current;
+
+ if (!overlayEl || !indicatorEl) {
+ return;
+ }
+
+ // Update stage size from overlay dimensions
+ const stageWidth = overlayEl.clientWidth;
+ const stageHeight = overlayEl.clientHeight;
+ if (stageWidth && stageHeight) {
+ stageSizeRef.current = { width: stageWidth, height: stageHeight };
+ }
+
+ updateOverlayIndicator({
+ overlayEl,
+ indicatorEl,
+ region,
+ focusOverride,
+ videoSize: videoSizeRef.current,
+ baseScale: baseScaleRef.current,
+ isPlaying: isPlayingRef.current,
+ });
+ },
+ [],
+ );
+
+ const layoutVideoContent = useCallback(() => {
+ const container = containerRef.current;
+ const app = appRef.current;
+ const videoSprite = videoSpriteRef.current;
+ const maskGraphics = maskGraphicsRef.current;
+ const videoElement = videoRef.current;
+ const cameraContainer = cameraContainerRef.current;
+
+ if (
+ !container ||
+ !app ||
+ !videoSprite ||
+ !maskGraphics ||
+ !videoElement ||
+ !cameraContainer
+ ) {
+ return;
+ }
+
+ // Lock video dimensions on first layout to prevent resize issues
+ if (
+ !lockedVideoDimensionsRef.current &&
+ videoElement.videoWidth > 0 &&
+ videoElement.videoHeight > 0
+ ) {
+ lockedVideoDimensionsRef.current = {
+ width: videoElement.videoWidth,
+ height: videoElement.videoHeight,
+ };
+ }
+
+ const result = layoutVideoContentUtil({
+ container,
+ app,
+ videoSprite,
+ maskGraphics,
+ videoElement,
+ cropRegion,
+ lockedVideoDimensions: lockedVideoDimensionsRef.current,
+ borderRadius,
+ padding,
+ });
+
+ if (result) {
+ stageSizeRef.current = result.stageSize;
+ videoSizeRef.current = result.videoSize;
+ baseScaleRef.current = result.baseScale;
+ baseOffsetRef.current = result.baseOffset;
+ baseMaskRef.current = result.maskRect;
+ cropBoundsRef.current = result.cropBounds;
+
+ // Reset camera container to identity
+ cameraContainer.scale.set(1);
+ cameraContainer.position.set(0, 0);
+
+ const selectedId = selectedZoomIdRef.current;
+ const activeRegion = selectedId
+ ? (zoomRegionsRef.current.find((region) => region.id === selectedId) ?? null)
+ : null;
+
+ updateOverlayForRegion(activeRegion);
+ }
+ }, [updateOverlayForRegion, cropRegion, borderRadius, padding]);
+
+ useEffect(() => {
+ layoutVideoContentRef.current = layoutVideoContent;
+ }, [layoutVideoContent]);
+
+ const selectedZoom = useMemo(() => {
+ if (!selectedZoomId) return null;
+ return zoomRegions.find((region) => region.id === selectedZoomId) ?? null;
+ }, [zoomRegions, selectedZoomId]);
+
+ useImperativeHandle(ref, () => ({
+ video: videoRef.current,
+ app: appRef.current,
+ videoSprite: videoSpriteRef.current,
+ videoContainer: videoContainerRef.current,
+ containerRef,
+ play: async () => {
+ const vid = videoRef.current;
+ if (!vid) return;
+ try {
+ allowPlaybackRef.current = true;
+ await vid.play();
+ } catch (error) {
+ allowPlaybackRef.current = false;
+ throw error;
+ }
+ },
+ pause: () => {
+ const video = videoRef.current;
+ allowPlaybackRef.current = false;
+ if (!video) {
+ return;
+ }
+ video.pause();
+ },
+ }));
+
+ const updateFocusFromClientPoint = (clientX: number, clientY: number) => {
+ const overlayEl = overlayRef.current;
+ if (!overlayEl) return;
+
+ const regionId = selectedZoomIdRef.current;
+ if (!regionId) return;
+
+ const region = zoomRegionsRef.current.find((r) => r.id === regionId);
+ if (!region) return;
+
+ const rect = overlayEl.getBoundingClientRect();
+ const stageWidth = rect.width;
+ const stageHeight = rect.height;
+
+ if (!stageWidth || !stageHeight) {
+ return;
+ }
+
+ stageSizeRef.current = { width: stageWidth, height: stageHeight };
+
+ const localX = clientX - rect.left;
+ const localY = clientY - rect.top;
+
+ const unclampedFocus: ZoomFocus = {
+ cx: clamp01(localX / stageWidth),
+ cy: clamp01(localY / stageHeight),
+ };
+ const clampedFocus = clampFocusToStage(unclampedFocus, region.depth);
+
+ onZoomFocusChange(region.id, clampedFocus);
+ updateOverlayForRegion({ ...region, focus: clampedFocus }, clampedFocus);
+ };
+
+ const handleOverlayPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (isPlayingRef.current) return;
+ const regionId = selectedZoomIdRef.current;
+ if (!regionId) return;
+ const region = zoomRegionsRef.current.find((r) => r.id === regionId);
+ if (!region) return;
+ onSelectZoom(region.id);
+ event.preventDefault();
+ isDraggingFocusRef.current = true;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ updateFocusFromClientPoint(event.clientX, event.clientY);
+ };
+
+ const handleOverlayPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (!isDraggingFocusRef.current) return;
+ event.preventDefault();
+ updateFocusFromClientPoint(event.clientX, event.clientY);
+ };
+
+ const endFocusDrag = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (!isDraggingFocusRef.current) return;
+ isDraggingFocusRef.current = false;
+ try {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ } catch {
+ // Pointer may already be released.
+ }
+ onZoomFocusDragEnd?.();
+ };
+
+ const handleOverlayPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
+ endFocusDrag(event);
+ };
+
+ const handleOverlayPointerLeave = (event: React.PointerEvent<HTMLDivElement>) => {
+ endFocusDrag(event);
+ };
+
+ useEffect(() => {
+ zoomRegionsRef.current = zoomRegions;
+ }, [zoomRegions]);
+
+ useEffect(() => {
+ selectedZoomIdRef.current = selectedZoomId;
+ }, [selectedZoomId]);
+
+ useEffect(() => {
+ isPlayingRef.current = isPlaying;
+ }, [isPlaying]);
+
+ useEffect(() => {
+ trimRegionsRef.current = trimRegions;
+ }, [trimRegions]);
+
+ useEffect(() => {
+ speedRegionsRef.current = speedRegions;
+ }, [speedRegions]);
+
+ useEffect(() => {
+ motionBlurEnabledRef.current = motionBlurEnabled;
+ }, [motionBlurEnabled]);
+
+ useEffect(() => {
+ onTimeUpdateRef.current = onTimeUpdate;
+ }, [onTimeUpdate]);
+
+ useEffect(() => {
+ onPlayStateChangeRef.current = onPlayStateChange;
+ }, [onPlayStateChange]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+
+ const app = appRef.current;
+ const cameraContainer = cameraContainerRef.current;
+ const video = videoRef.current;
+
+ if (!app || !cameraContainer || !video) return;
+
+ const tickerWasStarted = app.ticker?.started || false;
+ if (tickerWasStarted && app.ticker) {
+ app.ticker.stop();
+ }
+
+ const wasPlaying = !video.paused;
+ if (wasPlaying) {
+ video.pause();
+ }
+
+ animationStateRef.current = {
+ scale: 1,
+ focusX: DEFAULT_FOCUS.cx,
+ focusY: DEFAULT_FOCUS.cy,
+ };
+
+ if (blurFilterRef.current) {
+ blurFilterRef.current.blur = 0;
+ }
+
+ requestAnimationFrame(() => {
+ const container = cameraContainerRef.current;
+ const videoStage = videoContainerRef.current;
+ const sprite = videoSpriteRef.current;
+ const currentApp = appRef.current;
+ if (!container || !videoStage || !sprite || !currentApp) {
+ return;
+ }
+
+ container.scale.set(1);
+ container.position.set(0, 0);
+ videoStage.scale.set(1);
+ videoStage.position.set(0, 0);
+ sprite.scale.set(1);
+ sprite.position.set(0, 0);
+
+ layoutVideoContent();
+
+ applyZoomTransform({
+ cameraContainer: container,
+ blurFilter: blurFilterRef.current,
+ stageSize: stageSizeRef.current,
+ baseMask: baseMaskRef.current,
+ zoomScale: 1,
+ focusX: DEFAULT_FOCUS.cx,
+ focusY: DEFAULT_FOCUS.cy,
+ motionIntensity: 0,
+ isPlaying: false,
+ motionBlurEnabled: motionBlurEnabledRef.current,
+ });
+
+ requestAnimationFrame(() => {
+ const finalApp = appRef.current;
+ if (wasPlaying && video) {
+ video.play().catch(() => {
+ // Ignore autoplay restoration failures.
+ });
+ }
+ if (tickerWasStarted && finalApp?.ticker) {
+ finalApp.ticker.start();
+ }
+ });
+ });
+ }, [pixiReady, videoReady, layoutVideoContent]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+ const container = containerRef.current;
+ if (!container) return;
+
+ if (typeof ResizeObserver === "undefined") {
+ return;
+ }
+
+ const observer = new ResizeObserver(() => {
+ layoutVideoContent();
+ });
+
+ observer.observe(container);
+ return () => {
+ observer.disconnect();
+ };
+ }, [pixiReady, videoReady, layoutVideoContent]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+ updateOverlayForRegion(selectedZoom);
+ }, [selectedZoom, pixiReady, videoReady, updateOverlayForRegion]);
+
+ useEffect(() => {
+ const overlayEl = overlayRef.current;
+ if (!overlayEl) return;
+ if (!selectedZoom) {
+ overlayEl.style.cursor = "default";
+ overlayEl.style.pointerEvents = "none";
+ return;
+ }
+ overlayEl.style.cursor = isPlaying ? "not-allowed" : "grab";
+ overlayEl.style.pointerEvents = isPlaying ? "none" : "auto";
+ }, [selectedZoom, isPlaying]);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ let mounted = true;
+ let app: Application | null = null;
+
+ (async () => {
+ app = new Application();
+
+ await app.init({
+ width: container.clientWidth,
+ height: container.clientHeight,
+ backgroundAlpha: 0,
+ antialias: true,
+ resolution: window.devicePixelRatio || 1,
+ autoDensity: true,
+ });
+
+ app.ticker.maxFPS = 60;
+
+ if (!mounted) {
+ app.destroy(true, { children: true, texture: true, textureSource: true });
+ return;
+ }
+
+ appRef.current = app;
+ container.appendChild(app.canvas);
+
+ // Camera container - this will be scaled/positioned for zoom
+ const cameraContainer = new Container();
+ cameraContainerRef.current = cameraContainer;
+ app.stage.addChild(cameraContainer);
+
+ // Video container - holds the masked video sprite
+ const videoContainer = new Container();
+ videoContainerRef.current = videoContainer;
+ cameraContainer.addChild(videoContainer);
+
+ setPixiReady(true);
+ })();
+
+ return () => {
+ mounted = false;
+ setPixiReady(false);
+ if (app && app.renderer) {
+ app.destroy(true, { children: true, texture: true, textureSource: true });
+ }
+ appRef.current = null;
+ cameraContainerRef.current = null;
+ videoContainerRef.current = null;
+ videoSpriteRef.current = null;
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!videoPath) {
+ setVideoReady(false);
+ return;
+ }
+
+ const video = videoRef.current;
+ if (!video) return;
+ video.pause();
+ video.currentTime = 0;
+ allowPlaybackRef.current = false;
+ lockedVideoDimensionsRef.current = null;
+ setVideoReady(false);
+ if (videoReadyRafRef.current) {
+ cancelAnimationFrame(videoReadyRafRef.current);
+ videoReadyRafRef.current = null;
+ }
+ }, [videoPath]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+
+ const video = videoRef.current;
+ const app = appRef.current;
+ const videoContainer = videoContainerRef.current;
+
+ if (!video || !app || !videoContainer) return;
+ if (video.videoWidth === 0 || video.videoHeight === 0) return;
+
+ const source = VideoSource.from(video);
+ if ("autoPlay" in source) {
+ (source as { autoPlay?: boolean }).autoPlay = false;
+ }
+ if ("autoUpdate" in source) {
+ (source as { autoUpdate?: boolean }).autoUpdate = true;
+ }
+ const videoTexture = Texture.from(source);
+
+ const videoSprite = new Sprite(videoTexture);
+ videoSpriteRef.current = videoSprite;
+
+ const maskGraphics = new Graphics();
+ videoContainer.addChild(videoSprite);
+ videoContainer.addChild(maskGraphics);
+ videoContainer.mask = maskGraphics;
+ maskGraphicsRef.current = maskGraphics;
+
+ animationStateRef.current = {
+ scale: 1,
+ focusX: DEFAULT_FOCUS.cx,
+ focusY: DEFAULT_FOCUS.cy,
+ };
+
+ const blurFilter = new BlurFilter();
+ blurFilter.quality = 3;
+ blurFilter.resolution = app.renderer.resolution;
+ blurFilter.blur = 0;
+ videoContainer.filters = [blurFilter];
+ blurFilterRef.current = blurFilter;
+
+ layoutVideoContentRef.current?.();
+ video.pause();
+
+ const { handlePlay, handlePause, handleSeeked, handleSeeking } = createVideoEventHandlers({
+ video,
+ isSeekingRef,
+ isPlayingRef,
+ allowPlaybackRef,
+ currentTimeRef,
+ timeUpdateAnimationRef,
+ onPlayStateChange: (playing) => onPlayStateChangeRef.current(playing),
+ onTimeUpdate: (time) => onTimeUpdateRef.current(time),
+ trimRegionsRef,
+ speedRegionsRef,
+ });
+
+ video.addEventListener("play", handlePlay);
+ video.addEventListener("pause", handlePause);
+ video.addEventListener("ended", handlePause);
+ video.addEventListener("seeked", handleSeeked);
+ video.addEventListener("seeking", handleSeeking);
+
+ return () => {
+ video.removeEventListener("play", handlePlay);
+ video.removeEventListener("pause", handlePause);
+ video.removeEventListener("ended", handlePause);
+ video.removeEventListener("seeked", handleSeeked);
+ video.removeEventListener("seeking", handleSeeking);
+
+ if (timeUpdateAnimationRef.current) {
+ cancelAnimationFrame(timeUpdateAnimationRef.current);
+ }
+
+ if (videoSprite) {
+ videoContainer.removeChild(videoSprite);
+ videoSprite.destroy();
+ }
+ if (maskGraphics) {
+ videoContainer.removeChild(maskGraphics);
+ maskGraphics.destroy();
+ }
+ videoContainer.mask = null;
+ maskGraphicsRef.current = null;
+ if (blurFilterRef.current) {
+ videoContainer.filters = [];
+ blurFilterRef.current.destroy();
+ blurFilterRef.current = null;
+ }
+ videoTexture.destroy(true);
+
+ videoSpriteRef.current = null;
+ };
+ }, [pixiReady, videoReady]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+
+ const app = appRef.current;
+ const videoSprite = videoSpriteRef.current;
+ const videoContainer = videoContainerRef.current;
+ if (!app || !videoSprite || !videoContainer) return;
+
+ const applyTransform = (motionIntensity: number) => {
+ const cameraContainer = cameraContainerRef.current;
+ if (!cameraContainer) return;
+
+ const state = animationStateRef.current;
+
+ applyZoomTransform({
+ cameraContainer,
+ blurFilter: blurFilterRef.current,
+ stageSize: stageSizeRef.current,
+ baseMask: baseMaskRef.current,
+ zoomScale: state.scale,
+ focusX: state.focusX,
+ focusY: state.focusY,
+ motionIntensity,
+ isPlaying: isPlayingRef.current,
+ motionBlurEnabled: motionBlurEnabledRef.current,
+ });
+ };
+
+ const ticker = () => {
+ const { region, strength } = findDominantRegion(
+ zoomRegionsRef.current,
+ currentTimeRef.current,
+ );
+
+ const defaultFocus = DEFAULT_FOCUS;
+ let targetScaleFactor = 1;
+ let targetFocus = defaultFocus;
+
+ // If a zoom is selected but video is not playing, show default unzoomed view
+ // (the overlay will show where the zoom will be)
+ const selectedId = selectedZoomIdRef.current;
+ const hasSelectedZoom = selectedId !== null;
+ const shouldShowUnzoomedView = hasSelectedZoom && !isPlayingRef.current;
+
+ if (region && strength > 0 && !shouldShowUnzoomedView) {
+ const zoomScale = ZOOM_DEPTH_SCALES[region.depth];
+ const regionFocus = clampFocusToStage(region.focus, region.depth);
+
+ // Interpolate scale and focus based on region strength
+ targetScaleFactor = 1 + (zoomScale - 1) * strength;
+ targetFocus = {
+ cx: defaultFocus.cx + (regionFocus.cx - defaultFocus.cx) * strength,
+ cy: defaultFocus.cy + (regionFocus.cy - defaultFocus.cy) * strength,
+ };
+ }
+
+ const state = animationStateRef.current;
+
+ const prevScale = state.scale;
+ const prevFocusX = state.focusX;
+ const prevFocusY = state.focusY;
+
+ const scaleDelta = targetScaleFactor - state.scale;
+ const focusXDelta = targetFocus.cx - state.focusX;
+ const focusYDelta = targetFocus.cy - state.focusY;
+
+ let nextScale = prevScale;
+ let nextFocusX = prevFocusX;
+ let nextFocusY = prevFocusY;
+
+ if (Math.abs(scaleDelta) > MIN_DELTA) {
+ nextScale = prevScale + scaleDelta * SMOOTHING_FACTOR;
+ } else {
+ nextScale = targetScaleFactor;
+ }
+
+ if (Math.abs(focusXDelta) > MIN_DELTA) {
+ nextFocusX = prevFocusX + focusXDelta * SMOOTHING_FACTOR;
+ } else {
+ nextFocusX = targetFocus.cx;
+ }
+
+ if (Math.abs(focusYDelta) > MIN_DELTA) {
+ nextFocusY = prevFocusY + focusYDelta * SMOOTHING_FACTOR;
+ } else {
+ nextFocusY = targetFocus.cy;
+ }
+
+ state.scale = nextScale;
+ state.focusX = nextFocusX;
+ state.focusY = nextFocusY;
+
+ const motionIntensity = Math.max(
+ Math.abs(nextScale - prevScale),
+ Math.abs(nextFocusX - prevFocusX),
+ Math.abs(nextFocusY - prevFocusY),
+ );
+
+ applyTransform(motionIntensity);
+ };
+
+ app.ticker.add(ticker);
+ return () => {
+ if (app && app.ticker) {
+ app.ticker.remove(ticker);
+ }
+ };
+ }, [pixiReady, videoReady, clampFocusToStage]);
+
+ const handleLoadedMetadata = (e: React.SyntheticEvent<HTMLVideoElement, Event>) => {
+ const video = e.currentTarget;
+ onDurationChange(video.duration);
+ video.currentTime = 0;
+ video.pause();
+ allowPlaybackRef.current = false;
+ currentTimeRef.current = 0;
+
+ if (videoReadyRafRef.current) {
+ cancelAnimationFrame(videoReadyRafRef.current);
+ videoReadyRafRef.current = null;
+ }
+
+ const waitForRenderableFrame = () => {
+ const hasDimensions = video.videoWidth > 0 && video.videoHeight > 0;
+ const hasData = video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA;
+ if (hasDimensions && hasData) {
+ videoReadyRafRef.current = null;
+ setVideoReady(true);
+ return;
+ }
+ videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);
+ };
+
+ videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);
+ };
+
+ const [resolvedWallpaper, setResolvedWallpaper] = useState<string | null>(null);
+
+ useEffect(() => {
+ let mounted = true;
+ (async () => {
+ try {
+ if (!wallpaper) {
+ const def = await getAssetPath("wallpapers/wallpaper1.jpg");
+ if (mounted) setResolvedWallpaper(def);
+ return;
+ }
+
+ if (
+ wallpaper.startsWith("#") ||
+ wallpaper.startsWith("linear-gradient") ||
+ wallpaper.startsWith("radial-gradient")
+ ) {
+ if (mounted) setResolvedWallpaper(wallpaper);
+ return;
+ }
+
+ // If it's a data URL (custom uploaded image), use as-is
+ if (wallpaper.startsWith("data:")) {
+ if (mounted) setResolvedWallpaper(wallpaper);
+ return;
+ }
+
+ // If it's an absolute web/http or file path, use as-is
+ if (
+ wallpaper.startsWith("http") ||
+ wallpaper.startsWith("file://") ||
+ wallpaper.startsWith("/")
+ ) {
+ // If it's an absolute server path (starts with '/'), resolve via getAssetPath as well
+ if (wallpaper.startsWith("/")) {
+ const rel = wallpaper.replace(/^\//, "");
+ const p = await getAssetPath(rel);
+ if (mounted) setResolvedWallpaper(p);
+ return;
+ }
+ if (mounted) setResolvedWallpaper(wallpaper);
+ return;
+ }
+ const p = await getAssetPath(wallpaper.replace(/^\//, ""));
+ if (mounted) setResolvedWallpaper(p);
+ } catch (_err) {
+ if (mounted) setResolvedWallpaper(wallpaper || "/wallpapers/wallpaper1.jpg");
+ }
+ })();
+ return () => {
+ mounted = false;
+ };
+ }, [wallpaper]);
+
+ useEffect(() => {
+ return () => {
+ if (videoReadyRafRef.current) {
+ cancelAnimationFrame(videoReadyRafRef.current);
+ videoReadyRafRef.current = null;
+ }
+ };
+ }, []);
+
+ const isImageUrl = Boolean(
+ resolvedWallpaper &&
+ (resolvedWallpaper.startsWith("file://") ||
+ resolvedWallpaper.startsWith("http") ||
+ resolvedWallpaper.startsWith("/") ||
+ resolvedWallpaper.startsWith("data:")),
+ );
+ const backgroundStyle = isImageUrl
+ ? { backgroundImage: `url(${resolvedWallpaper || ""})` }
+ : { background: resolvedWallpaper || "" };
+
+ return (
+ <div
+ className="relative rounded-sm overflow-hidden"
- style={{ width: "100%", aspectRatio: formatAspectRatioForCSS(aspectRatio) }}
++ style={{
++ width: "100%",
++ aspectRatio: formatAspectRatioForCSS(
++ aspectRatio,
++ aspectRatio === "native"
++ ? getNativeAspectRatioValue(
++ lockedVideoDimensionsRef.current?.width || 1920,
++ lockedVideoDimensionsRef.current?.height || 1080,
++ cropRegion,
++ )
++ : undefined,
++ ),
++ }}
+ >
+ {/* Background layer - always render as DOM element with blur */}
+ <div
+ className="absolute inset-0 bg-cover bg-center"
+ style={{
+ ...backgroundStyle,
+ filter: showBlur ? "blur(2px)" : "none",
+ }}
+ />
+ <div
+ ref={containerRef}
+ className="absolute inset-0"
+ style={{
+ filter:
+ showShadow && shadowIntensity > 0
+ ? `drop-shadow(0 ${shadowIntensity * 12}px ${shadowIntensity * 48}px rgba(0,0,0,${shadowIntensity * 0.7})) drop-shadow(0 ${shadowIntensity * 4}px ${shadowIntensity * 16}px rgba(0,0,0,${shadowIntensity * 0.5})) drop-shadow(0 ${shadowIntensity * 2}px ${shadowIntensity * 8}px rgba(0,0,0,${shadowIntensity * 0.3}))`
+ : "none",
+ }}
+ />
+ {/* Only render overlay after PIXI and video are fully initialized */}
+ {pixiReady && videoReady && (
+ <div
+ ref={overlayRef}
+ className="absolute inset-0 select-none"
+ style={{ pointerEvents: "none" }}
+ onPointerDown={handleOverlayPointerDown}
+ onPointerMove={handleOverlayPointerMove}
+ onPointerUp={handleOverlayPointerUp}
+ onPointerLeave={handleOverlayPointerLeave}
+ >
+ <div
+ ref={focusIndicatorRef}
+ className="absolute rounded-md border border-[#34B27B]/80 bg-[#34B27B]/20 shadow-[0_0_0_1px_rgba(52,178,123,0.35)]"
+ style={{ display: "none", pointerEvents: "none" }}
+ />
+ {(() => {
+ const filtered = (annotationRegions || []).filter((annotation) => {
+ if (typeof annotation.startMs !== "number" || typeof annotation.endMs !== "number")
+ return false;
+
+ if (annotation.id === selectedAnnotationId) return true;
+
+ const timeMs = Math.round(currentTime * 1000);
+ return timeMs >= annotation.startMs && timeMs <= annotation.endMs;
+ });
+
+ // Sort by z-index (lowest to highest) so higher z-index renders on top
+ const sorted = [...filtered].sort((a, b) => a.zIndex - b.zIndex);
+
+ // Handle click-through cycling: when clicking same annotation, cycle to next
+ const handleAnnotationClick = (clickedId: string) => {
+ if (!onSelectAnnotation) return;
+
+ // If clicking on already selected annotation and there are multiple overlapping
+ if (clickedId === selectedAnnotationId && sorted.length > 1) {
+ // Find current index and cycle to next
+ const currentIndex = sorted.findIndex((a) => a.id === clickedId);
+ const nextIndex = (currentIndex + 1) % sorted.length;
+ onSelectAnnotation(sorted[nextIndex].id);
+ } else {
+ // First click or clicking different annotation
+ onSelectAnnotation(clickedId);
+ }
+ };
+
+ return sorted.map((annotation) => (
+ <AnnotationOverlay
+ key={annotation.id}
+ annotation={annotation}
+ isSelected={annotation.id === selectedAnnotationId}
+ containerWidth={overlayRef.current?.clientWidth || 800}
+ containerHeight={overlayRef.current?.clientHeight || 600}
+ onPositionChange={(id, position) => onAnnotationPositionChange?.(id, position)}
+ onSizeChange={(id, size) => onAnnotationSizeChange?.(id, size)}
+ onClick={handleAnnotationClick}
+ zIndex={annotation.zIndex}
+ isSelectedBoost={annotation.id === selectedAnnotationId}
+ />
+ ));
+ })()}
+ </div>
+ )}
+ <video
+ ref={videoRef}
+ src={videoPath}
+ className="hidden"
+ preload="metadata"
+ playsInline
+ onLoadedMetadata={handleLoadedMetadata}
+ onDurationChange={(e) => {
+ onDurationChange(e.currentTarget.duration);
+ }}
+ onError={() => onError("Failed to load video")}
+ />
+ </div>
+ );
+ },
+ );
+
+ VideoPlayback.displayName = "VideoPlayback";
export default VideoPlayback;
diff --cc src/utils/aspectRatioUtils.ts
index 3b82ebf41,3fc6f90bc..2ad7e4428
--- a/src/utils/aspectRatioUtils.ts
+++ b/src/utils/aspectRatioUtils.ts
@@@ -1,60 -1,51 +1,73 @@@
- export const ASPECT_RATIOS = ['16:9', '9:16', '1:1', '4:3', '4:5', '16:10', '10:16', 'native'] as const;
-export const ASPECT_RATIOS = ["16:9", "9:16", "1:1", "4:3", "4:5", "16:10", "10:16"] as const;
++export const ASPECT_RATIOS = [
++ "16:9",
++ "9:16",
++ "1:1",
++ "4:3",
++ "4:5",
++ "16:10",
++ "10:16",
++ "native",
++] as const;
- export type AspectRatio = typeof ASPECT_RATIOS[number];
+ export type AspectRatio = (typeof ASPECT_RATIOS)[number];
/**
* Returns the numeric value of an aspect ratio.
- * For 'native', returns a fallback of 16/9 — callers with video/crop info
- * should use getNativeAspectRatioValue() instead.
- * Uses exhaustive type checking to ensure all AspectRatio cases are handled.
- * If TypeScript errors here, a new ratio was added to the type but not handled.
++ * For "native", returns a fallback ratio of 16/9.
++ * Callers with source/crop context should use getNativeAspectRatioValue().
*/
export function getAspectRatioValue(aspectRatio: AspectRatio): number {
- switch (aspectRatio) {
- case '16:9': return 16 / 9;
- case '9:16': return 9 / 16;
- case '1:1': return 1;
- case '4:3': return 4 / 3;
- case '4:5': return 4 / 5;
- case '16:10': return 16 / 10;
- case '10:16': return 10 / 16;
- case 'native': return 16 / 9;
- default: {
- const _exhaustiveCheck: never = aspectRatio;
- return _exhaustiveCheck;
- }
- }
+ switch (aspectRatio) {
+ case "16:9":
+ return 16 / 9;
+ case "9:16":
+ return 9 / 16;
+ case "1:1":
+ return 1;
+ case "4:3":
+ return 4 / 3;
+ case "4:5":
+ return 4 / 5;
+ case "16:10":
+ return 16 / 10;
+ case "10:16":
+ return 10 / 16;
++ case "native":
++ return 16 / 9;
+ default: {
- // Ensures all cases are handled - TypeScript errors if missing
+ const _exhaustiveCheck: never = aspectRatio;
+ return _exhaustiveCheck;
+ }
+ }
}
- /**
- * Returns the aspect ratio value for 'native' mode based on the cropped video dimensions.
- */
+export function getNativeAspectRatioValue(
- videoWidth: number,
- videoHeight: number,
- cropRegion?: { x: number; y: number; width: number; height: number },
++ videoWidth: number,
++ videoHeight: number,
++ cropRegion?: { x: number; y: number; width: number; height: number },
+): number {
- const cropW = cropRegion?.width ?? 1;
- const cropH = cropRegion?.height ?? 1;
- return (videoWidth * cropW) / (videoHeight * cropH);
++ const cropW = cropRegion?.width ?? 1;
++ const cropH = cropRegion?.height ?? 1;
++ return (videoWidth * cropW) / (videoHeight * cropH);
+}
+
export function getAspectRatioDimensions(
- aspectRatio: AspectRatio,
- baseWidth: number
+ aspectRatio: AspectRatio,
+ baseWidth: number,
): { width: number; height: number } {
- const ratio = getAspectRatioValue(aspectRatio);
- return {
- width: baseWidth,
- height: baseWidth / ratio,
- };
+ const ratio = getAspectRatioValue(aspectRatio);
+ return {
+ width: baseWidth,
+ height: baseWidth / ratio,
+ };
}
export function getAspectRatioLabel(aspectRatio: AspectRatio): string {
- if (aspectRatio === 'native') return 'Native';
- return aspectRatio;
++ if (aspectRatio === "native") return "Native";
+ return aspectRatio;
}
-
-export function formatAspectRatioForCSS(aspectRatio: AspectRatio): string {
+export function formatAspectRatioForCSS(aspectRatio: AspectRatio, nativeRatio?: number): string {
- if (aspectRatio === 'native') return String(nativeRatio ?? 16 / 9);
- return aspectRatio.replace(':', '/');
++ if (aspectRatio === "native") return String(nativeRatio ?? 16 / 9);
+ return aspectRatio.replace(":", "/");
}