Skip to content

Create polished demo videos without editing skills. Mac/Windows/Linux

Refactor the video editor and restore responsive interactions

webadderalleab7b0f9780c
diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsx
index f8e0dea5..84c973b4 100644
--- a/src/components/video-editor/VideoEditor.tsx
+++ b/src/components/video-editor/VideoEditor.tsx
@@ -1,397 +1,25 @@
-import {
- BookmarkSimple,
- Check,
- CaretDown as ChevronDown,
- ClosedCaptioning,
- Crop,
- Cursor,
- DownloadSimple as Download,
- FolderOpen,
- Gear,
- Pause,
- Camera as PhCameraRegular,
- Play,
- Plus,
- PuzzlePiece,
- ArrowClockwise as Redo2,
- Scissors,
- SkipBack,
- SkipForward,
- Sparkle,
- ArrowCounterClockwise as Undo2,
- UserCircle as User,
- SpeakerLow as Volume1,
- SpeakerHigh as Volume2,
- SpeakerX as VolumeX,
- MagicWand as WandSparkles,
- X,
- MagnifyingGlassPlus as ZoomIn,
-} from "@phosphor-icons/react";
-import type { Span } from "dnd-timeline";
-import { motion } from "motion/react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { toast } from "sonner";
-import { EditorAnnouncementBanner } from "@/components/announcements/EditorAnnouncementBanner";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Input } from "@/components/ui/input";
-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
-import { Toaster } from "@/components/ui/sonner";
+/* biome-ignore-all lint/correctness/useExhaustiveDependencies: setters returned by the editor's domain-state hooks are stable React dispatchers. */
+import { useCallback, useEffect, useMemo } from "react";
import { useI18n } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
-import { OPEN_EDITOR_SECTION_EVENT } from "@/lib/announcementActions";
-import { type AnnouncementEditorSection, isAnnouncementEditorSection } from "@/lib/announcements";
-import {
- calculateOutputDimensions,
- DEFAULT_MP4_CODEC,
- type ExportBackendPreference,
- type ExportEncodingMode,
- type ExportFormat,
- type ExportMp4FrameRate,
- type ExportPipelineModel,
- type ExportProgress,
- type ExportQuality,
- type ExportSettings,
- FrameRenderer,
- GIF_SIZE_PRESETS,
- GifExporter,
- type GifFrameRate,
- type GifSizePreset,
- ModernVideoExporter,
- probeSupportedMp4Dimensions,
- type SupportedMp4Dimensions,
- VideoExporter,
-} from "@/lib/exporter";
-import { getMp4ExportBitrate, getSourceQualityBitrate } from "@/lib/exporter/exportBitrate";
-import {
- canUseInMemoryExportSaveFallback,
- describeBlockedInMemoryExportSave,
-} from "@/lib/exporter/exportSavePolicy";
-import { matchesShortcut } from "@/lib/shortcuts";
-import { cn } from "@/lib/utils";
-import {
- ASPECT_RATIOS,
- type AspectRatio,
- getAspectRatioLabel,
- getAspectRatioValue,
-} from "@/utils/aspectRatioUtils";
-import { planClipSpeedChange } from "./clipSpeedChange";
-import {
- calculateMp4ExportDimensions,
- calculateMp4SourceDimensions,
- type Mp4SupportProbeSnapshot,
- shouldDebounceMp4SupportProbe,
-} from "./exportDimensions";
-import { resolveSavingExportProgress } from "./exportProgressState";
-import { resolveExportStartSettings } from "./exportStartSettings";
-import { resolveExportStatusModel } from "./exportStatusModel";
-import { resolveMp4ExportRouting } from "./mp4ExportRouting";
-import { resolveMp4ExportSettings } from "./mp4ExportSettings";
-import { useNvidiaCudaExportOptIn } from "./useNvidiaCudaExportOptIn";
-
-const PhCursorFill = (props: { className?: string; weight?: "fill" | "regular" }) => (
- <Cursor weight="fill" className={props.className} />
-);
-const PhCamera = (props: { className?: string; weight?: "fill" | "regular" }) => (
- <PhCameraRegular weight={props.weight ?? "regular"} className={props.className} />
-);
-const PhCaptions = (props: { className?: string; weight?: "fill" | "regular" }) => (
- <ClosedCaptioning weight={props.weight ?? "regular"} className={props.className} />
-);
-const PhPuzzle = (props: { className?: string; weight?: "fill" | "regular" }) => (
- <PuzzlePiece weight={props.weight ?? "regular"} className={props.className} />
-);
-const PhSparkle = (props: { className?: string; weight?: "fill" | "regular" }) => (
- <Sparkle weight={props.weight ?? "regular"} className={props.className} />
-);
-const PhSettings = (props: { className?: string; weight?: "fill" | "regular" }) => (
- <Gear weight={props.weight ?? "regular"} className={props.className} />
-);
-
-import type { SourceAudioTrackSettings } from "@/components/video-editor/audio/audioTypes";
-import { useVideoEditorAudio } from "./audio/useVideoEditorAudio";
-import { resolveAutoCaptionSourcePath } from "./autoCaptionSource";
-import { CropControl } from "./CropControl";
-import {
- type CaptionEditTarget,
- normalizeCaptionEditText,
- normalizeCaptionWords,
- updateCaptionCuesForEditedTarget,
-} from "./captionEditing";
-import {
- addCue,
- type CaptionRetimeSpan,
- createCaptionCue,
- deleteCue,
- mergeCues,
- retimeCue,
- splitCue,
-} from "./captionOps";
-import { ExportSettingsMenu } from "./ExportSettingsMenu";
-import ExtensionManager from "./ExtensionManager";
-import {
- createEditorHistoryStack,
- type EditorHistorySnapshot,
- recordEditorHistorySnapshot,
- redoEditorHistoryStack,
- resetEditorHistoryStack,
- undoEditorHistoryStack,
-} from "./editorHistory";
-import {
- type EditorPreset,
- type EditorPresetSnapshot,
- loadEditorPreferences,
- loadEditorPresets,
- saveEditorPreferences,
- saveEditorPresets,
- serializeEditorPresetSnapshot,
-} from "./editorPreferences";
-import ProjectBrowserDialog, { type ProjectLibraryEntry } from "./ProjectBrowserDialog";
-import { hasUnsavedProjectChanges } from "./projectDirtyState";
-import {
- createProjectData,
- deriveNextId,
- type EditorProjectData,
- fromFileUrl,
- normalizeProjectEditor,
- resolveVideoUrl,
- stripPersistedDevMotionBlurSettings,
- toFileUrl,
- validateProjectData,
-} from "./projectPersistence";
-import { SettingsPanel } from "./SettingsPanel";
+import { getAspectRatioValue } from "@/utils/aspectRatioUtils";
+import { loadEditorPreferences } from "./editorPreferences";
+import { useEditorExportController } from "./export/useEditorExportController";
+import { useExportDimensions } from "./export/useExportDimensions";
+import { useExportSession } from "./export/useExportSession";
+import { useExportSettings } from "./export/useExportSettings";
+import { useTimelineEditingController } from "./hooks/useTimelineEditingController";
+import { EditorShell } from "./layout/EditorShell";
+import { useEditorSettingsPanelProps } from "./layout/useEditorSettingsPanelProps";
+import { useVideoEditorPresets } from "./presets/useVideoEditorPresets";
+import { useEditorProjectController } from "./project/useEditorProjectController";
+import { useProjectLibraryController } from "./project/useProjectLibraryController";
import { getDevOpenRecordingConfig, getSmokeExportConfig } from "./smokeExportConfig";
-import { createSmokeExportProgressSampler } from "./smokeExportProgress";
-import {
- APP_HEADER_ICON_BUTTON_CLASS,
- DiscordLinkButton,
- FeedbackDialog,
- openExternalLink,
- RECORDLY_ISSUES_URL,
-} from "./TutorialHelp";
-import TimelineEditor, { type TimelineEditorHandle } from "./timeline/TimelineEditor";
-import {
- normalizeCursorTelemetry,
- shouldAutoApplyFreshRecordingZoomsForSource,
-} from "./timeline/zoomSuggestionUtils";
-import {
- type AnnotationRegion,
- type AudioRegion,
- type AutoCaptionSettings,
- type CaptionCue,
- type ClipRegion,
- type CropRegion,
- type CursorClickEffectStyle,
- type CursorStyle,
- type CursorTelemetryPoint,
- clampFocusToDepth,
- clipsToTrims,
- DEFAULT_ANNOTATION_POSITION,
- DEFAULT_ANNOTATION_SIZE,
- DEFAULT_ANNOTATION_STYLE,
- DEFAULT_AUTO_CAPTION_SETTINGS,
- DEFAULT_AUTO_ZOOM_DEPTH,
- DEFAULT_CONNECTED_ZOOM_DURATION_MS,
- DEFAULT_CONNECTED_ZOOM_EASING,
- DEFAULT_CONNECTED_ZOOM_GAP_MS,
- DEFAULT_CROP_REGION,
- DEFAULT_CURSOR_STYLE,
- DEFAULT_FIGURE_DATA,
- DEFAULT_WEBCAM_OVERLAY,
- DEFAULT_WEBCAM_TIME_OFFSET_MS,
- DEFAULT_ZOOM_IN_DURATION_MS,
- DEFAULT_ZOOM_IN_EASING,
- DEFAULT_ZOOM_IN_OVERLAP_MS,
- DEFAULT_ZOOM_MOTION_BLUR_TUNING,
- DEFAULT_ZOOM_OUT_DURATION_MS,
- DEFAULT_ZOOM_OUT_EASING,
- type EditorEffectSection,
- extendAutoFullTrackClip,
- type FigureData,
- getClipSourceEndMs,
- getTimelineDurationMs,
- type Padding,
- mapSourceTimeToTimelineTime as resolveSourceTimeToTimelineTime,
- mapTimelineTimeToSourceTime as resolveTimelineTimeToSourceTime,
- type SpeedRegion,
- type TrimRegion,
- trimsToClips,
- type WebcamOverlaySettings,
- type ZoomDepth,
- type ZoomFocus,
- type ZoomMode,
- type ZoomMotionBlurTuning,
- type ZoomRegion,
- type ZoomTransitionEasing,
-} from "./types";
-import VideoPlayback, { VideoPlaybackRef } from "./VideoPlayback";
-import {
- buildLoopedCursorTelemetry,
- getDisplayedTimelineWindowMs,
-} from "./videoPlayback/cursorLoopTelemetry";
-
-type PendingExportSave = {
- fileName: string;
- arrayBuffer?: ArrayBuffer;
- tempFilePath?: string;
- captionSidecar?: {
- format: "srt" | "vtt" | "both";
- cues: Array<{
- startMs: number;
- endMs: number;
- text: string;
- }>;
- };
-};
-
-type CancelableExporter = {
- cancel(): void;
-};
-
-const EXPORT_BLOB_STREAM_CHUNK_BYTES = 16 * 1024 * 1024;
-const MP4_CROP_PROBE_DEBOUNCE_MS = 200;
-
-async function streamExportBlobToTempFile(blob: Blob, extension: string): Promise<string | null> {
- if (
- typeof window === "undefined" ||
- !window.electronAPI?.openExportStream ||
- !window.electronAPI?.writeExportStreamChunk ||
- !window.electronAPI?.closeExportStream
- ) {
- return null;
- }
-
- const openResult = await window.electronAPI.openExportStream({ extension });
- if (!openResult.success || !openResult.streamId || !openResult.tempPath) {
- throw new Error(openResult.error || "Failed to open export stream");
- }
-
- const { streamId } = openResult;
- let position = 0;
-
- try {
- while (position < blob.size) {
- const chunk = blob.slice(position, position + EXPORT_BLOB_STREAM_CHUNK_BYTES);
- const chunkBuffer = await chunk.arrayBuffer();
- const writeResult = await window.electronAPI.writeExportStreamChunk(
- streamId,
- position,
- new Uint8Array(chunkBuffer),
- );
- if (!writeResult.success) {
- throw new Error(writeResult.error || "Failed to write export stream chunk");
- }
- position += chunkBuffer.byteLength;
- }
-
- const closeResult = await window.electronAPI.closeExportStream(streamId);
- if (!closeResult.success || !closeResult.tempPath) {
- throw new Error(closeResult.error || "Failed to close export stream");
- }
-
- return closeResult.tempPath;
- } catch (error) {
- try {
- await window.electronAPI.closeExportStream(streamId, { abort: true });
- } catch {
- // Best-effort cleanup; preserve the original error below.
- }
- throw error;
- }
-}
-
-type SaveProjectOptions = {
- silent?: boolean;
- remountPreviewAfterSave?: boolean;
- refreshLibraryAfterSave?: boolean;
- captureThumbnail?: boolean;
-};
-
-type NamedProjectSaveMode = "rename" | "copy";
-
-type PendingProjectSaveDialog = {
- resolve: (saved: boolean) => void;
-};
-
-type PendingUnsavedChangesDialogDecision = "cancel" | "discard" | "save";
-
-type PendingUnsavedChangesDialog = {
- resolve: (decision: PendingUnsavedChangesDialogDecision) => void;
-};
-
-async function writeSmokeExportReport(
- outputPath: string | null,
- report: Record<string, unknown>,
-): Promise<void> {
- if (!outputPath || typeof window === "undefined") {
- return;
- }
-
- try {
- const reportBytes = new TextEncoder().encode(JSON.stringify(report, null, 2));
- const reportBuffer = reportBytes.buffer.slice(
- reportBytes.byteOffset,
- reportBytes.byteOffset + reportBytes.byteLength,
- ) as ArrayBuffer;
- await window.electronAPI.writeExportedVideoToPath(
- reportBuffer,
- `${outputPath}.report.json`,
- );
- } catch (error) {
- console.error("[smoke-export] Failed to write report", error);
- }
-}
-
-const SMOKE_EXPORT_READY_TIMEOUT_MS = 30_000;
-const DEFAULT_MP4_EXPORT_FRAME_RATE: ExportMp4FrameRate = 30;
-const PROJECT_AUTOSAVE_DELAY_MS = 1000;
-const EXPORT_ERROR_TOAST_DURATION_MS = 20000;
-
-function summarizeErrorMessage(message: string): string {
- const firstLine = message
- .split(/\r?\n/)
- .map((line) => line.trim())
- .find((line) => line.length > 0);
-
- return firstLine ?? message;
-}
-
-function showExportErrorToast(message: string) {
- const summary = summarizeErrorMessage(message);
- toast.error(summary, {
- description: summary === message ? undefined : message,
- duration: EXPORT_ERROR_TOAST_DURATION_MS,
- });
-}
-
-function cloneStructured<T>(value: T): T {
- return globalThis.structuredClone(value);
-}
-
-function getErrorMessage(error: unknown): string {
- if (error instanceof Error) {
- return error.message;
- }
-
- if (typeof error === "string") {
- return error.replace(/^Error:\s*/i, "");
- }
-
- return "Something went wrong";
-}
+import { useAppearanceState } from "./state/useAppearanceState";
+import { useEditorUiState } from "./state/useEditorUiState";
+import { useProjectState } from "./state/useProjectState";
+import { useTimelineState } from "./state/useTimelineState";
+import { useNvidiaCudaExportOptIn } from "./useNvidiaCudaExportOptIn";
export default function VideoEditor() {
const { t } = useI18n();
@@ -404,235 +32,78 @@ export default function VideoEditor() {
getDevOpenRecordingConfig(typeof window === "undefined" ? "" : window.location.search),
[],
);
- const [appPlatform, setAppPlatform] = useState<string>(
- typeof navigator !== "undefined" && /Mac/i.test(navigator.platform) ? "darwin" : "",
- );
const initialEditorPreferences = useMemo(() => loadEditorPreferences(), []);
- const [videoPath, setVideoPath] = useState<string | null>(null);
- const [videoSourcePath, setVideoSourcePath] = useState<string | null>(null);
- const [currentProjectPath, setCurrentProjectPath] = useState<string | null>(null);
- const [projectLibraryEntries, setProjectLibraryEntries] = useState<ProjectLibraryEntry[]>([]);
- const [projectBrowserOpen, setProjectBrowserOpen] = useState(false);
- const [isEditingProjectName, setIsEditingProjectName] = useState(false);
- const [projectNameDraft, setProjectNameDraft] = useState("");
- const [isSavingProjectName, setIsSavingProjectName] = useState(false);
- const [projectSaveDialogOpen, setProjectSaveDialogOpen] = useState(false);
- const [projectSaveDialogDraft, setProjectSaveDialogDraft] = useState("");
- const [isSavingProjectDialog, setIsSavingProjectDialog] = useState(false);
- const [unsavedChangesDialogOpen, setUnsavedChangesDialogOpen] = useState(false);
- const [unsavedChangesDialogActionLabel, setUnsavedChangesDialogActionLabel] =
- useState("continue");
- 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>(initialEditorPreferences.wallpaper);
- const [shadowIntensity, setShadowIntensity] = useState(
- initialEditorPreferences.shadowIntensity,
- );
- const [backgroundBlur, setBackgroundBlur] = useState(initialEditorPreferences.backgroundBlur);
- const [zoomMotionBlur, setZoomMotionBlur] = useState(initialEditorPreferences.zoomMotionBlur);
- const [zoomMotionBlurTuning, setZoomMotionBlurTuning] = useState<ZoomMotionBlurTuning>(
- initialEditorPreferences.zoomMotionBlurTuning ?? DEFAULT_ZOOM_MOTION_BLUR_TUNING,
- );
- const [zoomTemporalMotionBlur, setZoomTemporalMotionBlur] = useState(
- initialEditorPreferences.zoomTemporalMotionBlur,
- );
- const [zoomMotionBlurSampleCount, setZoomMotionBlurSampleCount] = useState<number | null>(
- initialEditorPreferences.zoomMotionBlurSampleCount,
- );
- const [zoomMotionBlurShutterFraction, setZoomMotionBlurShutterFraction] = useState<
- number | null
- >(initialEditorPreferences.zoomMotionBlurShutterFraction);
- const [autoApplyFreshRecordingAutoZooms, setAutoApplyFreshRecordingAutoZooms] = useState(
- initialEditorPreferences.autoApplyFreshRecordingAutoZooms,
- );
- const [connectZooms, setConnectZooms] = useState(initialEditorPreferences.connectZooms);
- const [zoomInDurationMs, setZoomInDurationMs] = useState(
- initialEditorPreferences.zoomInDurationMs ?? DEFAULT_ZOOM_IN_DURATION_MS,
- );
- const [zoomInOverlapMs, setZoomInOverlapMs] = useState(
- initialEditorPreferences.zoomInOverlapMs ?? DEFAULT_ZOOM_IN_OVERLAP_MS,
- );
- const [zoomOutDurationMs, setZoomOutDurationMs] = useState(
- initialEditorPreferences.zoomOutDurationMs ?? DEFAULT_ZOOM_OUT_DURATION_MS,
- );
- const [connectedZoomGapMs, setConnectedZoomGapMs] = useState(
- initialEditorPreferences.connectedZoomGapMs ?? DEFAULT_CONNECTED_ZOOM_GAP_MS,
- );
- const [connectedZoomDurationMs, setConnectedZoomDurationMs] = useState(
- initialEditorPreferences.connectedZoomDurationMs ?? DEFAULT_CONNECTED_ZOOM_DURATION_MS,
- );
- const [zoomInEasing, setZoomInEasing] = useState<ZoomTransitionEasing>(
- initialEditorPreferences.zoomInEasing ?? DEFAULT_ZOOM_IN_EASING,
- );
- const [zoomOutEasing, setZoomOutEasing] = useState<ZoomTransitionEasing>(
- initialEditorPreferences.zoomOutEasing ?? DEFAULT_ZOOM_OUT_EASING,
- );
- const [connectedZoomEasing, setConnectedZoomEasing] = useState<ZoomTransitionEasing>(
- initialEditorPreferences.connectedZoomEasing ?? DEFAULT_CONNECTED_ZOOM_EASING,
- );
- const [showCursor, setShowCursor] = useState(initialEditorPreferences.showCursor);
- const [loopCursor, setLoopCursor] = useState(initialEditorPreferences.loopCursor);
- const [cursorStyle, setCursorStyle] = useState<CursorStyle>(
- initialEditorPreferences.cursorStyle ?? DEFAULT_CURSOR_STYLE,
- );
- const [cursorSize, setCursorSize] = useState(initialEditorPreferences.cursorSize);
- const [cursorSmoothing, setCursorSmoothing] = useState(
- initialEditorPreferences.cursorSmoothing,
- );
- const [cursorSpringStiffnessMultiplier, setCursorSpringStiffnessMultiplier] = useState(
- initialEditorPreferences.cursorSpringStiffnessMultiplier,
- );
- const [cursorSpringDampingMultiplier, setCursorSpringDampingMultiplier] = useState(
- initialEditorPreferences.cursorSpringDampingMultiplier,
- );
- const [cursorSpringMassMultiplier, setCursorSpringMassMultiplier] = useState(
- initialEditorPreferences.cursorSpringMassMultiplier,
- );
- const [cameraSpringStiffnessMultiplier, setCameraSpringStiffnessMultiplier] = useState(
- initialEditorPreferences.cameraSpringStiffnessMultiplier,
- );
- const [cameraSpringDampingMultiplier, setCameraSpringDampingMultiplier] = useState(
- initialEditorPreferences.cameraSpringDampingMultiplier,
- );
- const [cameraSpringMassMultiplier, setCameraSpringMassMultiplier] = useState(
- initialEditorPreferences.cameraSpringMassMultiplier,
- );
- const [sessionShowCursorOverride, setSessionShowCursorOverride] = useState<boolean | null>(
- null,
- );
- const [sessionNativeCaptureUnavailable, setSessionNativeCaptureUnavailable] = useState(false);
- const [nativeCaptureUnavailableModalOpen, setNativeCaptureUnavailableModalOpen] =
- useState(false);
- const [zoomSmoothness, setZoomSmoothness] = useState(0.5);
- const [zoomClassicMode, setZoomClassicMode] = useState(false);
- const [cursorMotionBlur, setCursorMotionBlur] = useState(
- initialEditorPreferences.cursorMotionBlur,
- );
- const [cursorClickEffect, setCursorClickEffect] = useState<CursorClickEffectStyle>(
- initialEditorPreferences.cursorClickEffect,
- );
- const [cursorClickEffectColor, setCursorClickEffectColor] = useState(
- initialEditorPreferences.cursorClickEffectColor,
- );
- const [cursorClickEffectScale, setCursorClickEffectScale] = useState(
- initialEditorPreferences.cursorClickEffectScale,
- );
- const [cursorClickEffectOpacity, setCursorClickEffectOpacity] = useState(
- initialEditorPreferences.cursorClickEffectOpacity,
- );
- const [cursorClickEffectDurationMs, setCursorClickEffectDurationMs] = useState(
- initialEditorPreferences.cursorClickEffectDurationMs,
- );
- const [cursorClickBounce, setCursorClickBounce] = useState(
- initialEditorPreferences.cursorClickBounce,
- );
- const [cursorClickBounceDuration, setCursorClickBounceDuration] = useState(
- initialEditorPreferences.cursorClickBounceDuration,
- );
- const [cursorSway, setCursorSway] = useState(initialEditorPreferences.cursorSway);
- const [borderRadius, setBorderRadius] = useState(initialEditorPreferences.borderRadius);
- const [padding, setPadding] = useState(initialEditorPreferences.padding);
- const [cropRegion, setCropRegion] = useState<CropRegion>(DEFAULT_CROP_REGION);
- const [webcam, setWebcam] = useState<WebcamOverlaySettings>(
- initialEditorPreferences.webcam ?? DEFAULT_WEBCAM_OVERLAY,
- );
- const [resolvedWebcamVideoUrl, setResolvedWebcamVideoUrl] = useState<string | null>(null);
- const [zoomRegions, setZoomRegions] = useState<ZoomRegion[]>([]);
- const [cursorTelemetry, setCursorTelemetry] = useState<CursorTelemetryPoint[]>([]);
- // Tracks the videoSourcePath for which the cursor telemetry IPC has already
- // resolved. The smoke-export auto-trigger waits on this so long recordings
- // still bake cursor/zoom animations into the output — without it, the
- // auto-export fires as soon as the video loads and the telemetry arrives
- // after encoding has started.
- const [cursorTelemetrySourcePath, setCursorTelemetrySourcePath] = useState<string | null>(null);
- const [selectedZoomId, setSelectedZoomId] = useState<string | null>(null);
- const [trimRegions, setTrimRegions] = useState<TrimRegion[]>([]);
- const [clipRegions, setClipRegions] = useState<ClipRegion[]>([]);
- const [selectedClipId, setSelectedClipId] = useState<string | null>(null);
- const [speedRegions, setSpeedRegions] = useState<SpeedRegion[]>([]);
- const [annotationRegions, setAnnotationRegions] = useState<AnnotationRegion[]>([]);
- const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);
- const [audioRegions, setAudioRegions] = useState<AudioRegion[]>([]);
- const [selectedAudioId, setSelectedAudioId] = useState<string | null>(null);
- const [selectedCaptionId, setSelectedCaptionId] = useState<string | null>(null);
- const [sourceAudioTrackSettingsByClip, setSourceAudioTrackSettingsByClip] = useState<
- Record<string, SourceAudioTrackSettings>
- >({});
- const [defaultSourceAudioTrackSettings, setDefaultSourceAudioTrackSettings] =
- useState<SourceAudioTrackSettings>({});
- const [sourceAudioFallbackRefreshKey, setSourceAudioFallbackRefreshKey] = useState(0);
- const [hasClipSourceAudio, setHasClipSourceAudio] = useState(false);
- const [autoCaptions, setAutoCaptions] = useState<CaptionCue[]>([]);
- const [autoCaptionSettings, setAutoCaptionSettings] = useState<AutoCaptionSettings>(
- DEFAULT_AUTO_CAPTION_SETTINGS,
- );
- const [includeCaptionSidecar, setIncludeCaptionSidecar] = useState(false);
- const [whisperExecutablePath, setWhisperExecutablePath] = useState<string | null>(
- initialEditorPreferences.whisperExecutablePath,
- );
- const [whisperModelPath, setWhisperModelPath] = useState<string | null>(
- initialEditorPreferences.whisperModelPath,
- );
- const [downloadedWhisperModelPath, setDownloadedWhisperModelPath] = useState<string | null>(
- null,
- );
- const [whisperModelDownloadStatus, setWhisperModelDownloadStatus] = useState<
- "idle" | "downloading" | "downloaded" | "error"
- >(initialEditorPreferences.whisperModelPath ? "downloaded" : "idle");
- const [whisperModelDownloadProgress, setWhisperModelDownloadProgress] = useState(0);
- const [isGeneratingCaptions, setIsGeneratingCaptions] = useState(false);
- const [isExporting, setIsExporting] = useState(false);
- const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);
- const [exportError, setExportError] = useState<string | null>(null);
- const [showExportDropdown, setShowExportDropdown] = useState(false);
- const [previewVolume, setPreviewVolume] = useState(1);
- const applySessionPresentation = useCallback(
- (
- session:
- | {
- hideOverlayCursorByDefault?: boolean;
- nativeCaptureUnavailable?: boolean;
- }
- | null
- | undefined,
- ) => {
- setSessionShowCursorOverride(session?.hideOverlayCursorByDefault ? false : null);
- setSessionNativeCaptureUnavailable(Boolean(session?.nativeCaptureUnavailable));
- setNativeCaptureUnavailableModalOpen(Boolean(session?.nativeCaptureUnavailable));
- },
- [],
- );
+ const timeline = useTimelineState();
+ const project = useProjectState();
+ const { videoPath, setVideoPath, videoSourcePath, setVideoSourcePath, loading, error } =
+ project;
+ const appearance = useAppearanceState(initialEditorPreferences);
+ const { showCursor, setShowCursor, cropRegion, setCropRegion } = appearance;
+ const ui = useEditorUiState(initialEditorPreferences, cropRegion, setCropRegion);
+ const {
+ appPlatform,
+ isPlaying,
+ setIsPlaying,
+ currentTime,
+ setCurrentTime,
+ duration,
+ setDuration,
+ sessionShowCursorOverride,
+ setSessionShowCursorOverride,
+ sessionNativeCaptureUnavailable,
+ setNativeCaptureUnavailableModalOpen,
+ whisperExecutablePath,
+ setWhisperExecutablePath,
+ whisperModelPath,
+ setWhisperModelPath,
+ downloadedWhisperModelPath,
+ setDownloadedWhisperModelPath,
+ whisperModelDownloadStatus,
+ setWhisperModelDownloadStatus,
+ whisperModelDownloadProgress,
+ setWhisperModelDownloadProgress,
+ isGeneratingCaptions,
+ setIsGeneratingCaptions,
+ previewVolume,
+ aspectRatio,
+ setAspectRatio,
+ activeEffectSection,
+ setActiveEffectSection,
+ setPreviewVersion,
+ isPreviewReady,
+ setIsPreviewReady,
+ setAutoSuggestZoomsTrigger,
+ videoPlaybackRef,
+ projectNameInputRef,
+ projectSaveDialogInputRef,
+ nextZoomIdRef,
+ nextClipIdRef,
+ clipInitializedRef,
+ autoFullTrackClipIdRef,
+ autoFullTrackClipEndMsRef,
+ nextAudioIdRef,
+ nextAnnotationIdRef,
+ nextAnnotationZIndexRef,
+ autoSuggestedVideoPathRef,
+ pendingFreshRecordingAutoZoomPathRef,
+ pendingFreshRecordingAutoSuggestTimeoutRef,
+ pendingFreshRecordingAutoSuggestTelemetryCountRef,
+ timelineRef,
+ applySessionPresentation,
+ } = ui;
const effectiveShowCursor = sessionShowCursorOverride ?? showCursor;
- const [aspectRatio, setAspectRatio] = useState<AspectRatio>(
- initialEditorPreferences.aspectRatio,
- );
- const [activeEffectSection, setActiveEffectSection] = useState<EditorEffectSection>("scene");
- useEffect(() => {
- const handleOpenEditorSection = (event: Event) => {
- const section = (event as CustomEvent<AnnouncementEditorSection>).detail;
- if (isAnnouncementEditorSection(section)) {
- setActiveEffectSection(section);
- }
- };
-
- window.addEventListener(OPEN_EDITOR_SECTION_EVENT, handleOpenEditorSection);
- return () => window.removeEventListener(OPEN_EDITOR_SECTION_EVENT, handleOpenEditorSection);
- }, []);
- const [exportQuality, setExportQuality] = useState<ExportQuality>(
- initialEditorPreferences.exportQuality,
- );
- const [exportEncodingMode, setExportEncodingMode] = useState<ExportEncodingMode>(
- initialEditorPreferences.exportEncodingMode,
- );
- const [exportBackendPreference, setExportBackendPreference] = useState<ExportBackendPreference>(
- initialEditorPreferences.exportBackendPreference,
- );
- const [exportPipelineModel, setExportPipelineModel] = useState<ExportPipelineModel>(
- initialEditorPreferences.exportPipelineModel,
- );
+ const headerLeftControlsPaddingClass = appPlatform === "darwin" ? "pl-[76px]" : "";
+ const { cursorTelemetrySourcePath, autoCaptions, autoCaptionSettings } = timeline;
+ const exportSettings = useExportSettings(initialEditorPreferences, autoCaptions);
+ const {
+ includeCaptionSidecar,
+ mp4FrameRate,
+ gifSizePreset,
+ captionSidecarCues,
+ setExportPipelineModel,
+ } = exportSettings;
+ const exportSession = useExportSession();
+ const { exporterRef, pendingExportSaveRef } = exportSession;
const enableModernExportPipeline = useCallback(() => {
setExportPipelineModel("modern");
}, []);
@@ -643,38 +114,7 @@ export default function VideoEditor() {
} = useNvidiaCudaExportOptIn({
onEnabled: enableModernExportPipeline,
});
- const [mp4FrameRate, setMp4FrameRate] = useState<ExportMp4FrameRate>(
- initialEditorPreferences.mp4FrameRate ?? DEFAULT_MP4_EXPORT_FRAME_RATE,
- );
- const [exportFormat, setExportFormat] = useState<ExportFormat>(
- initialEditorPreferences.exportFormat,
- );
- const [gifFrameRate, setGifFrameRate] = useState<GifFrameRate>(
- initialEditorPreferences.gifFrameRate,
- );
- const [gifLoop, setGifLoop] = useState(initialEditorPreferences.gifLoop);
- const [gifSizePreset, setGifSizePreset] = useState<GifSizePreset>(
- initialEditorPreferences.gifSizePreset,
- );
const hasCaptionsForSidecar = autoCaptionSettings.enabled && autoCaptions.length > 0;
- const captionSidecarCues = useMemo(
- () =>
- autoCaptions
- .filter(
- (cue) =>
- Number.isFinite(cue.startMs) &&
- Number.isFinite(cue.endMs) &&
- cue.endMs > cue.startMs &&
- typeof cue.text === "string" &&
- cue.text.trim().length > 0,
- )
- .map((cue) => ({
- startMs: cue.startMs,
- endMs: cue.endMs,
- text: cue.text,
- })),
- [autoCaptions],
- );
const captionSidecarPayload =
hasCaptionsForSidecar && captionSidecarCues.length > 0 && includeCaptionSidecar
? {
@@ -682,64 +122,7 @@ export default function VideoEditor() {
cues: captionSidecarCues,
}
: undefined;
- const [exportedFilePath, setExportedFilePath] = useState<string | undefined>(undefined);
- const [hasPendingExportSave, setHasPendingExportSave] = useState(false);
- const [lastSavedSnapshot, setLastSavedSnapshot] = useState<EditorProjectData | null>(null);
- const [editorPresets, setEditorPresets] = useState<EditorPreset[]>(() => loadEditorPresets());
- const [activeEditorPresetId, setActiveEditorPresetId] = useState<string | null>(null);
- const [presetPopoverOpen, setPresetPopoverOpen] = useState(false);
- const [presetNameDraft, setPresetNameDraft] = useState("");
- const [showCropModal, setShowCropModal] = useState(false);
- const [previewVersion, setPreviewVersion] = useState(0);
- const [isPreviewReady, setIsPreviewReady] = useState(false);
- const [autoSuggestZoomsTrigger, setAutoSuggestZoomsTrigger] = useState(0);
- const headerLeftControlsPaddingClass = appPlatform === "darwin" ? "pl-[76px]" : "";
-
- const videoPlaybackRef = useRef<VideoPlaybackRef>(null);
- const projectBrowserTriggerRef = useRef<HTMLButtonElement | null>(null);
- const projectBrowserFallbackTriggerRef = useRef<HTMLButtonElement | null>(null);
- const projectNameInputRef = useRef<HTMLInputElement | null>(null);
- const projectSaveDialogInputRef = useRef<HTMLInputElement | null>(null);
- const nextZoomIdRef = useRef(1);
- const nextClipIdRef = useRef(1);
- const nextAudioIdRef = useRef(1);
-
const { shortcuts, isMac } = useShortcuts();
- const nextAnnotationIdRef = useRef(1);
- const nextAnnotationZIndexRef = useRef(1); // Track z-index for stacking order
- const exporterRef = useRef<CancelableExporter | null>(null);
- const autoSuggestedVideoPathRef = useRef<string | null>(null);
- const pendingFreshRecordingAutoZoomPathRef = useRef<string | null>(null);
- const editorHistoryRef = useRef(createEditorHistoryStack());
- const applyingHistoryRef = useRef(false);
- const pendingExportSaveRef = useRef<PendingExportSave | null>(null);
- const pendingTelemetryRetryTimeoutRef = useRef<number | null>(null);
- const pendingFreshRecordingAutoSuggestTimeoutRef = useRef<number | null>(null);
- const pendingFreshRecordingAutoSuggestTelemetryCountRef = useRef(0);
- const cropSnapshotRef = useRef<CropRegion | null>(null);
- const mp4SupportRequestRef = useRef(0);
- const previousMp4SupportProbeRef = useRef<Mp4SupportProbeSnapshot | null>(null);
- const smokeExportStartedRef = useRef(false);
- const projectAutosaveTimeoutRef = useRef<number | null>(null);
- const pendingProjectSaveDialogRef = useRef<PendingProjectSaveDialog | null>(null);
- const pendingUnsavedChangesDialogRef = useRef<PendingUnsavedChangesDialog | null>(null);
- const projectSaveQueueRef = useRef<Promise<unknown>>(Promise.resolve());
- const smokeExportReadyStateRef = useRef<Record<string, unknown>>({});
- const [historyVersion, setHistoryVersion] = useState(0);
- const timelineRef = useRef<TimelineEditorHandle>(null);
-
- function formatTime(seconds: number) {
- if (!isFinite(seconds) || isNaN(seconds) || seconds < 0) return "0:00";
- const mins = Math.floor(seconds / 60);
- const secs = Math.floor(seconds % 60);
- return `${mins}:${secs.toString().padStart(2, "0")}`;
- }
-
- useEffect(() => {
- void window.electronAPI?.getPlatform?.()?.then((platform) => {
- setAppPlatform(platform);
- });
- }, []);
useEffect(() => {
autoSuggestedVideoPathRef.current = null;
@@ -750,597 +133,26 @@ export default function VideoEditor() {
}
}, []);
- const [supportedMp4SourceDimensions, setSupportedMp4SourceDimensions] =
- useState<SupportedMp4Dimensions>({
- width: 1920,
- height: 1080,
- capped: false,
- encoderPath: null,
- });
-
- const syncHistoryButtons = useCallback(() => {
- setHistoryVersion((version) => version + 1);
- }, []);
-
- const captureEditorPresetSnapshot = useCallback(
- (): EditorPresetSnapshot => ({
- wallpaper,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning: { ...zoomMotionBlurTuning },
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- showCursor,
- loopCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- borderRadius,
- padding: { ...padding },
- cropRegion: { ...cropRegion },
- webcam: { ...webcam },
- aspectRatio,
- exportEncodingMode,
- exportBackendPreference,
- exportPipelineModel,
- exportQuality,
- mp4FrameRate,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- autoCaptionSettings: { ...autoCaptionSettings },
- whisperExecutablePath,
- whisperModelPath,
- }),
- [
- wallpaper,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- showCursor,
- loopCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- borderRadius,
- padding,
- cropRegion,
- webcam,
- aspectRatio,
- exportEncodingMode,
- exportBackendPreference,
- exportPipelineModel,
- exportQuality,
- mp4FrameRate,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- autoCaptionSettings,
- whisperExecutablePath,
- whisperModelPath,
- ],
- );
-
- const currentPresetSnapshot = useMemo(
- () => captureEditorPresetSnapshot(),
- [captureEditorPresetSnapshot],
- );
- const currentPresetSignature = useMemo(
- () => serializeEditorPresetSnapshot(currentPresetSnapshot),
- [currentPresetSnapshot],
- );
- const currentEditorPreset = useMemo(
- () => editorPresets.find((preset) => preset.id === activeEditorPresetId) ?? null,
- [activeEditorPresetId, editorPresets],
- );
-
- useEffect(() => {
- const activePreset = currentEditorPreset;
- if (
- activePreset &&
- serializeEditorPresetSnapshot(activePreset.snapshot) === currentPresetSignature
- ) {
- return;
- }
-
- const matchingPreset =
- editorPresets.find(
- (preset) =>
- serializeEditorPresetSnapshot(preset.snapshot) === currentPresetSignature,
- ) ?? null;
- const nextActivePresetId = matchingPreset?.id ?? null;
- if (nextActivePresetId !== activeEditorPresetId) {
- setActiveEditorPresetId(nextActivePresetId);
- }
- }, [activeEditorPresetId, currentEditorPreset, currentPresetSignature, editorPresets]);
-
- useEffect(() => {
- if (!presetPopoverOpen) {
- setPresetNameDraft("");
- }
- }, [presetPopoverOpen]);
-
- const applyEditorPresetSnapshot = useCallback((snapshot: EditorPresetSnapshot) => {
- setWallpaper(snapshot.wallpaper);
- setShadowIntensity(snapshot.shadowIntensity);
- setBackgroundBlur(snapshot.backgroundBlur);
- setZoomMotionBlur(snapshot.zoomMotionBlur);
- setZoomMotionBlurTuning({ ...snapshot.zoomMotionBlurTuning });
- setZoomTemporalMotionBlur(snapshot.zoomTemporalMotionBlur);
- setZoomMotionBlurSampleCount(snapshot.zoomMotionBlurSampleCount);
- setZoomMotionBlurShutterFraction(snapshot.zoomMotionBlurShutterFraction);
- setConnectZooms(snapshot.connectZooms);
- setZoomInDurationMs(snapshot.zoomInDurationMs);
- setZoomInOverlapMs(snapshot.zoomInOverlapMs);
- setZoomOutDurationMs(snapshot.zoomOutDurationMs);
- setConnectedZoomGapMs(snapshot.connectedZoomGapMs);
- setConnectedZoomDurationMs(snapshot.connectedZoomDurationMs);
- setZoomInEasing(snapshot.zoomInEasing);
- setZoomOutEasing(snapshot.zoomOutEasing);
- setConnectedZoomEasing(snapshot.connectedZoomEasing);
- setShowCursor(snapshot.showCursor);
- setLoopCursor(snapshot.loopCursor);
- setCursorStyle(snapshot.cursorStyle);
- setCursorSize(snapshot.cursorSize);
- setCursorSmoothing(snapshot.cursorSmoothing);
- setCursorSpringStiffnessMultiplier(snapshot.cursorSpringStiffnessMultiplier);
- setCursorSpringDampingMultiplier(snapshot.cursorSpringDampingMultiplier);
- setCursorSpringMassMultiplier(snapshot.cursorSpringMassMultiplier);
- setCameraSpringStiffnessMultiplier(snapshot.cameraSpringStiffnessMultiplier);
- setCameraSpringDampingMultiplier(snapshot.cameraSpringDampingMultiplier);
- setCameraSpringMassMultiplier(snapshot.cameraSpringMassMultiplier);
- setCursorMotionBlur(snapshot.cursorMotionBlur);
- setCursorClickEffect(snapshot.cursorClickEffect);
- setCursorClickEffectColor(snapshot.cursorClickEffectColor);
- setCursorClickEffectScale(snapshot.cursorClickEffectScale);
- setCursorClickEffectOpacity(snapshot.cursorClickEffectOpacity);
- setCursorClickEffectDurationMs(snapshot.cursorClickEffectDurationMs);
- setCursorClickBounce(snapshot.cursorClickBounce);
- setCursorClickBounceDuration(snapshot.cursorClickBounceDuration);
- setCursorSway(snapshot.cursorSway);
- setBorderRadius(snapshot.borderRadius);
- setPadding({ ...snapshot.padding });
- setCropRegion({ ...snapshot.cropRegion });
- setWebcam({ ...snapshot.webcam });
- setAspectRatio(snapshot.aspectRatio);
- setExportEncodingMode(snapshot.exportEncodingMode);
- setExportBackendPreference(snapshot.exportBackendPreference);
- setExportPipelineModel(snapshot.exportPipelineModel);
- setExportQuality(snapshot.exportQuality);
- setMp4FrameRate(snapshot.mp4FrameRate);
- setExportFormat(snapshot.exportFormat);
- setGifFrameRate(snapshot.gifFrameRate);
- setGifLoop(snapshot.gifLoop);
- setGifSizePreset(snapshot.gifSizePreset);
- setAutoCaptionSettings({ ...snapshot.autoCaptionSettings });
- setWhisperExecutablePath(snapshot.whisperExecutablePath);
- setWhisperModelPath(snapshot.whisperModelPath);
- }, []);
-
- const handleApplyEditorPreset = useCallback(
- (presetId: string) => {
- const preset = editorPresets.find((item) => item.id === presetId);
- if (!preset) {
- return;
- }
-
- setActiveEditorPresetId(preset.id);
- applyEditorPresetSnapshot(preset.snapshot);
- toast.success(
- t("editor.presets.toasts.applied", 'Applied preset "{{name}}"', {
- name: preset.name,
- }),
- );
- },
- [applyEditorPresetSnapshot, editorPresets, t],
- );
-
- const handleSaveEditorPreset = useCallback(
- (name: string) => {
- const normalizedName = name.trim().replace(/\s+/g, " ");
- if (normalizedName.length === 0) {
- toast.error(t("editor.presets.errors.nameRequired", "Enter a preset name."));
- return false;
- }
-
- const hasDuplicateName = editorPresets.some(
- (preset) => preset.name.toLocaleLowerCase() === normalizedName.toLocaleLowerCase(),
- );
- if (hasDuplicateName) {
- toast.error(
- t(
- "editor.presets.errors.duplicateName",
- "A preset with that name already exists.",
- ),
- );
- return false;
- }
-
- const snapshot = captureEditorPresetSnapshot();
- const timestamp = new Date().toISOString();
- const nextPreset: EditorPreset = {
- id: crypto.randomUUID(),
- name: normalizedName,
- createdAt: timestamp,
- updatedAt: timestamp,
- snapshot,
- };
- const nextPresets: EditorPreset[] = [nextPreset, ...editorPresets];
-
- if (!saveEditorPresets(nextPresets)) {
- toast.error(
- t(
- "editor.presets.errors.saveFailed",
- "Could not save that preset. Check your browser storage settings and try again.",
- ),
- );
- return false;
- }
-
- setEditorPresets(nextPresets);
- setActiveEditorPresetId(nextPreset.id);
- toast.success(
- t("editor.presets.toasts.saved", 'Saved preset "{{name}}"', {
- name: normalizedName,
- }),
- );
- return true;
- },
- [captureEditorPresetSnapshot, editorPresets, t],
- );
-
- const handleDeleteEditorPreset = useCallback(
- (presetId: string) => {
- const preset = editorPresets.find((item) => item.id === presetId);
- if (!preset) {
- return;
- }
-
- const nextPresets = editorPresets.filter((item) => item.id !== presetId);
- if (!saveEditorPresets(nextPresets)) {
- toast.error(
- t(
- "editor.presets.errors.deleteFailed",
- "Could not delete that preset. Check your browser storage settings and try again.",
- ),
- );
- return;
- }
-
- setEditorPresets(nextPresets);
- if (preset.id === activeEditorPresetId) {
- setActiveEditorPresetId(null);
- }
- toast.success(
- t("editor.presets.toasts.deleted", 'Deleted preset "{{name}}"', {
- name: preset.name,
- }),
- );
- },
- [activeEditorPresetId, editorPresets, t],
- );
-
- const handleSavePresetSubmit = useCallback(() => {
- const didSave = handleSaveEditorPreset(presetNameDraft);
- if (didSave) {
- setPresetNameDraft("");
- }
- }, [handleSaveEditorPreset, presetNameDraft]);
-
- const clearPendingExportSave = useCallback(() => {
- const pending = pendingExportSaveRef.current;
- pendingExportSaveRef.current = null;
- setHasPendingExportSave(false);
- if (pending?.tempFilePath && typeof window !== "undefined") {
- // Best-effort cleanup — main-process also reaps stale temp files on
- // before-quit, so we ignore failures here.
- void window.electronAPI.discardExportedTemp?.(pending.tempFilePath);
- }
- }, []);
-
- const refreshProjectLibrary = useCallback(async () => {
- try {
- const result = await window.electronAPI.listProjectFiles();
- if (!result.success) {
- throw new Error(result.error || "Failed to load project library");
- }
-
- setProjectLibraryEntries(result.entries);
- } catch (projectLibraryError) {
- console.warn("Unable to refresh project library:", projectLibraryError);
- }
- }, []);
-
- const captureProjectThumbnail = useCallback(async () => {
- const previewHandle = videoPlaybackRef.current;
- const previewVideo = previewHandle?.video ?? null;
- const previewCanvas = previewHandle?.app?.canvas ?? null;
-
- if (previewHandle && previewVideo && previewVideo.paused) {
- try {
- await previewHandle.refreshFrame();
- await new Promise((resolve) => requestAnimationFrame(() => resolve(undefined)));
- } catch (thumbnailRefreshError) {
- console.warn(
- "Unable to refresh preview frame before thumbnail capture:",
- thumbnailRefreshError,
- );
- }
- }
-
- const canvas = document.createElement("canvas");
- const targetWidth = 320;
- const targetHeight = 180;
- canvas.width = targetWidth;
- canvas.height = targetHeight;
-
- const context = canvas.getContext("2d");
- if (!context) {
- return null;
- }
- context.imageSmoothingEnabled = true;
- context.imageSmoothingQuality = "high";
- const editorBgHsl = getComputedStyle(document.documentElement)
- .getPropertyValue("--editor-bg")
- .trim();
- context.fillStyle = editorBgHsl ? `hsl(${editorBgHsl})` : "#111113";
- context.fillRect(0, 0, targetWidth, targetHeight);
-
- const previewWidth = previewHandle?.containerRef.current?.clientWidth || 1920;
- const previewHeight = previewHandle?.containerRef.current?.clientHeight || 1080;
- const frameTimestampUs = Math.max(0, Math.round(currentTime * 1_000_000));
-
- if (previewVideo && previewVideo.videoWidth > 0 && previewVideo.videoHeight > 0) {
- let videoFrame: VideoFrame | null = null;
- let frameRenderer: FrameRenderer | null = null;
-
- try {
- videoFrame = new VideoFrame(previewVideo, { timestamp: frameTimestampUs });
- frameRenderer = new FrameRenderer({
- width: targetWidth,
- height: targetHeight,
- wallpaper,
- zoomRegions,
- showShadow: shadowIntensity > 0,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- borderRadius,
- padding,
- cropRegion,
- webcam,
- webcamUrl:
- resolvedWebcamVideoUrl ??
- (webcam.sourcePath ? toFileUrl(webcam.sourcePath) : null),
- videoWidth: previewVideo.videoWidth,
- videoHeight: previewVideo.videoHeight,
- annotationRegions,
- autoCaptions,
- autoCaptionSettings,
- speedRegions: (() => {
- const clipDerived: SpeedRegion[] = clipRegions
- .filter((clip) => clip.speed !== 1)
- .map((clip) => ({
- id: `clip-speed-${clip.id}`,
- startMs: clip.startMs,
- endMs: getClipSourceEndMs(clip),
- speed: clip.speed as SpeedRegion["speed"],
- }));
- if (clipDerived.length === 0) return speedRegions;
- const result = [...speedRegions];
- for (const cs of clipDerived) {
- const overlaps = speedRegions.some(
- (sr) => sr.endMs > cs.startMs && sr.startMs < cs.endMs,
- );
- if (!overlaps) {
- result.push(cs);
- }
- }
- return result;
- })(),
- previewWidth,
- previewHeight,
- cursorTelemetry,
- showCursor: effectiveShowCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- zoomSmoothness,
- zoomClassicMode,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- });
- await frameRenderer.initialize();
- await frameRenderer.renderFrame(videoFrame, frameTimestampUs);
- return frameRenderer.getCanvas().toDataURL("image/png");
- } catch (thumbnailRenderError) {
- console.warn(
- "Unable to render thumbnail from composed frame:",
- thumbnailRenderError,
- );
- } finally {
- videoFrame?.close();
- frameRenderer?.destroy();
- }
- }
-
- const drawableSource =
- previewCanvas && previewCanvas.width > 0 && previewCanvas.height > 0
- ? previewCanvas
- : previewVideo && previewVideo.videoWidth > 0 && previewVideo.videoHeight > 0
- ? previewVideo
- : null;
-
- if (!drawableSource) {
- return null;
- }
-
- const sourceWidth =
- drawableSource instanceof HTMLVideoElement
- ? drawableSource.videoWidth
- : drawableSource.width;
- const sourceHeight =
- drawableSource instanceof HTMLVideoElement
- ? drawableSource.videoHeight
- : drawableSource.height;
-
- if (sourceWidth <= 0 || sourceHeight <= 0) {
- return null;
- }
-
- const scale = Math.min(targetWidth / sourceWidth, targetHeight / sourceHeight);
- const drawWidth = Math.round(sourceWidth * scale);
- const drawHeight = Math.round(sourceHeight * scale);
- const offsetX = Math.round((targetWidth - drawWidth) / 2);
- const offsetY = Math.round((targetHeight - drawHeight) / 2);
-
- try {
- context.drawImage(drawableSource, offsetX, offsetY, drawWidth, drawHeight);
- return canvas.toDataURL("image/png");
- } catch (thumbnailError) {
- console.warn("Unable to capture project thumbnail:", thumbnailError);
- return null;
- }
- }, [
- annotationRegions,
- autoCaptionSettings,
- autoCaptions,
- backgroundBlur,
- borderRadius,
- connectZooms,
- connectedZoomDurationMs,
- connectedZoomEasing,
- connectedZoomGapMs,
- cropRegion,
+ const presets = useVideoEditorPresets({
+ t,
+ appearance,
+ timeline,
+ exportSettings,
+ aspectRatio,
+ setAspectRatio,
+ whisperExecutablePath,
+ setWhisperExecutablePath,
+ whisperModelPath,
+ setWhisperModelPath,
+ });
+ const { refreshProjectLibrary, captureProjectThumbnail } = useProjectLibraryController({
+ project,
+ appearance,
+ timeline,
+ videoPlaybackRef,
currentTime,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorMotionBlur,
- cursorSize,
- cursorSmoothing,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cursorSpringStiffnessMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- zoomSmoothness,
- cursorStyle,
- cursorSway,
- cursorTelemetry,
- clipRegions,
- padding,
- resolvedWebcamVideoUrl,
- shadowIntensity,
effectiveShowCursor,
- speedRegions,
- wallpaper,
- webcam,
- zoomInDurationMs,
- zoomInEasing,
- zoomInOverlapMs,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- zoomOutDurationMs,
- zoomOutEasing,
- zoomRegions,
- zoomClassicMode,
- ]);
-
- const markExportAsSaving = useCallback(() => {
- setExportProgress(resolveSavingExportProgress);
- }, []);
-
+ });
const handleShowCursorChange = useCallback((nextShowCursor: boolean) => {
setSessionShowCursorOverride(null);
setShowCursor(nextShowCursor);
@@ -1351,106 +163,6 @@ export default function VideoEditor() {
setPreviewVersion((version) => version + 1);
}, []);
- const clearPendingProjectAutosave = useCallback(() => {
- if (projectAutosaveTimeoutRef.current !== null) {
- window.clearTimeout(projectAutosaveTimeoutRef.current);
- projectAutosaveTimeoutRef.current = null;
- }
- }, []);
-
- const queueProjectSave = useCallback((task: () => Promise<boolean>) => {
- const run = projectSaveQueueRef.current.catch(() => undefined).then(task);
- projectSaveQueueRef.current = run.catch(() => undefined);
- return run;
- }, []);
-
- const saveBlobExport = useCallback(
- async (
- blob: Blob,
- fileName: string,
- outputPath: string | null = null,
- captionSidecar?: PendingExportSave["captionSidecar"],
- ) => {
- const extension = fileName.split(".").pop()?.toLowerCase() || "bin";
- const hasExportStreamApi =
- typeof window !== "undefined" &&
- typeof window.electronAPI?.openExportStream === "function" &&
- typeof window.electronAPI?.writeExportStreamChunk === "function" &&
- typeof window.electronAPI?.closeExportStream === "function";
- let streamError: unknown = null;
-
- try {
- const tempFilePath = await streamExportBlobToTempFile(blob, extension);
- if (tempFilePath) {
- return {
- saveResult: await window.electronAPI.finalizeExportedVideo({
- tempPath: tempFilePath,
- fileName,
- outputPath,
- captionSidecar,
- }),
- pendingSave: {
- fileName,
- tempFilePath,
- captionSidecar,
- } satisfies PendingExportSave,
- };
- }
- } catch (error) {
- streamError = error;
- console.warn("[export] Temp-file blob save failed", error);
- }
-
- if (
- !canUseInMemoryExportSaveFallback({
- blobSize: blob.size,
- extension,
- hasExportStreamApi,
- })
- ) {
- const message = describeBlockedInMemoryExportSave({
- blobSize: blob.size,
- extension,
- });
- console.error("[export] Refusing in-memory blob save fallback", {
- fileName,
- blobSize: blob.size,
- extension,
- hasExportStreamApi,
- streamError,
- });
- throw new Error(message);
- }
-
- console.warn("[export] Falling back to in-memory blob save", {
- fileName,
- blobSize: blob.size,
- extension,
- hasExportStreamApi,
- });
- const arrayBuffer = await blob.arrayBuffer();
- return {
- saveResult: outputPath
- ? await window.electronAPI.writeExportedVideoToPath(
- arrayBuffer,
- outputPath,
- captionSidecar,
- )
- : await window.electronAPI.saveExportedVideo(
- arrayBuffer,
- fileName,
- captionSidecar,
- ),
- pendingSave: {
- fileName,
- arrayBuffer,
- captionSidecar,
- } satisfies PendingExportSave,
- };
- },
- [],
- );
-
useEffect(() => {
return () => {
exporterRef.current?.cancel();
@@ -1460,18 +172,10 @@ export default function VideoEditor() {
if (pending?.tempFilePath && typeof window !== "undefined") {
void window.electronAPI.discardExportedTemp?.(pending.tempFilePath);
}
- if (pendingTelemetryRetryTimeoutRef.current !== null) {
- window.clearTimeout(pendingTelemetryRetryTimeoutRef.current);
- pendingTelemetryRetryTimeoutRef.current = null;
- }
if (pendingFreshRecordingAutoSuggestTimeoutRef.current !== null) {
window.clearTimeout(pendingFreshRecordingAutoSuggestTimeoutRef.current);
pendingFreshRecordingAutoSuggestTimeoutRef.current = null;
}
- if (projectAutosaveTimeoutRef.current !== null) {
- window.clearTimeout(projectAutosaveTimeoutRef.current);
- projectAutosaveTimeoutRef.current = null;
- }
};
}, []);
@@ -1479,4007 +183,145 @@ export default function VideoEditor() {
void refreshProjectLibrary();
}, [refreshProjectLibrary]);
- const canUndo = editorHistoryRef.current.past.length > 0;
- const canRedo = editorHistoryRef.current.future.length > 0;
-
- void historyVersion;
-
- const gifOutputDimensions = useMemo(
- () =>
- calculateOutputDimensions(
- videoPlaybackRef.current?.video?.videoWidth || 1920,
- videoPlaybackRef.current?.video?.videoHeight || 1080,
- gifSizePreset,
- GIF_SIZE_PRESETS,
- ),
- [gifSizePreset],
- );
-
- const mp4SourceDimensions = useMemo(() => {
- const sourceVideo = isPreviewReady ? videoPlaybackRef.current?.video : null;
- return {
- width: sourceVideo?.videoWidth || 1920,
- height: sourceVideo?.videoHeight || 1080,
- };
- }, [isPreviewReady]);
-
- const desiredMp4SourceDimensions = useMemo(() => {
- return calculateMp4SourceDimensions(
- mp4SourceDimensions.width,
- mp4SourceDimensions.height,
- aspectRatio,
- cropRegion,
- );
- }, [aspectRatio, cropRegion, mp4SourceDimensions.height, mp4SourceDimensions.width]);
-
- const mp4OutputDimensions = useMemo(() => {
- const baseWidth = supportedMp4SourceDimensions.encoderPath
- ? supportedMp4SourceDimensions.width
- : desiredMp4SourceDimensions.width;
- const baseHeight = supportedMp4SourceDimensions.encoderPath
- ? supportedMp4SourceDimensions.height
- : desiredMp4SourceDimensions.height;
-
- return {
- medium: calculateMp4ExportDimensions(baseWidth, baseHeight, "medium"),
- good: calculateMp4ExportDimensions(baseWidth, baseHeight, "good"),
- high: calculateMp4ExportDimensions(baseWidth, baseHeight, "high"),
- source: calculateMp4ExportDimensions(baseWidth, baseHeight, "source"),
- };
- }, [
- desiredMp4SourceDimensions.height,
- desiredMp4SourceDimensions.width,
- supportedMp4SourceDimensions.encoderPath,
- supportedMp4SourceDimensions.height,
- supportedMp4SourceDimensions.width,
- ]);
-
- const ensureSupportedMp4SourceDimensions = useCallback(
- async (frameRate: ExportMp4FrameRate) => {
- const result = await probeSupportedMp4Dimensions({
- width: desiredMp4SourceDimensions.width,
- height: desiredMp4SourceDimensions.height,
- frameRate,
- codec: DEFAULT_MP4_CODEC,
- getBitrate: getSourceQualityBitrate,
- });
-
- if (!result.encoderPath) {
- throw new Error(
- `Video encoding not supported on this system. Tried codec ${DEFAULT_MP4_CODEC} at ${frameRate} FPS up to ${desiredMp4SourceDimensions.width}x${desiredMp4SourceDimensions.height}.`,
- );
- }
-
- return result;
- },
- [desiredMp4SourceDimensions.height, desiredMp4SourceDimensions.width],
- );
-
- useEffect(() => {
- let cancelled = false;
- const requestId = mp4SupportRequestRef.current + 1;
- mp4SupportRequestRef.current = requestId;
- const probeSnapshot: Mp4SupportProbeSnapshot = {
- sourceWidth: mp4SourceDimensions.width,
- sourceHeight: mp4SourceDimensions.height,
- targetWidth: desiredMp4SourceDimensions.width,
- targetHeight: desiredMp4SourceDimensions.height,
- aspectRatio,
- frameRate: mp4FrameRate,
- };
- const shouldDebounce = shouldDebounceMp4SupportProbe(
- previousMp4SupportProbeRef.current,
- probeSnapshot,
- );
- previousMp4SupportProbeRef.current = probeSnapshot;
- setSupportedMp4SourceDimensions({
- width: desiredMp4SourceDimensions.width,
- height: desiredMp4SourceDimensions.height,
- capped: false,
- encoderPath: null,
- });
-
- const runProbe = () => {
- void ensureSupportedMp4SourceDimensions(mp4FrameRate)
- .then((result) => {
- if (cancelled || requestId !== mp4SupportRequestRef.current) {
- return;
- }
- setSupportedMp4SourceDimensions(result);
- })
- .catch(() => {
- if (cancelled || requestId !== mp4SupportRequestRef.current) {
- return;
- }
- setSupportedMp4SourceDimensions({
- width: desiredMp4SourceDimensions.width,
- height: desiredMp4SourceDimensions.height,
- capped: false,
- encoderPath: null,
- });
- });
- };
-
- const timeoutId = shouldDebounce
- ? window.setTimeout(runProbe, MP4_CROP_PROBE_DEBOUNCE_MS)
- : null;
- if (timeoutId === null) {
- runProbe();
- }
-
- return () => {
- cancelled = true;
- if (timeoutId !== null) {
- window.clearTimeout(timeoutId);
- }
- };
- }, [
+ const exportDimensions = useExportDimensions({
+ videoPlaybackRef,
+ isPreviewReady,
aspectRatio,
- desiredMp4SourceDimensions.height,
- desiredMp4SourceDimensions.width,
- ensureSupportedMp4SourceDimensions,
+ cropRegion,
mp4FrameRate,
- mp4SourceDimensions.height,
- mp4SourceDimensions.width,
- ]);
-
- const editorSectionButtons = useMemo(
- () => [
- { id: "scene" as const, label: t("settings.sections.scene", "Scene"), icon: PhSparkle },
- {
- id: "cursor" as const,
- label: t("settings.sections.cursor", "Cursor"),
- icon: PhCursorFill,
- },
- {
- id: "webcam" as const,
- label: t("settings.sections.webcam", "Webcam"),
- icon: PhCamera,
- },
- {
- id: "captions" as const,
- label: t("settings.sections.captions", "Captions"),
- icon: PhCaptions,
- },
- {
- id: "settings" as const,
- label: t("settings.sections.settings", "Settings"),
- icon: PhSettings,
- },
- {
- id: "extensions" as const,
- label: t("settings.sections.extensions", "Extensions"),
- icon: PhPuzzle,
- },
- ],
- [t],
- );
-
- useEffect(() => {
- if (activeEffectSection === "frame" || activeEffectSection === "crop") {
- setActiveEffectSection("scene");
- }
- }, [activeEffectSection]);
-
- const buildPersistedEditorState = useCallback(
- (
- editor: Partial<{
- wallpaper: string;
- shadowIntensity: number;
- backgroundBlur: number;
- zoomMotionBlur: number;
- zoomMotionBlurTuning: ZoomMotionBlurTuning;
- zoomTemporalMotionBlur: number;
- zoomMotionBlurSampleCount: number | null;
- zoomMotionBlurShutterFraction: number | null;
- connectZooms: boolean;
- zoomInDurationMs: number;
- zoomInOverlapMs: number;
- zoomOutDurationMs: number;
- connectedZoomGapMs: number;
- connectedZoomDurationMs: number;
- zoomInEasing: ZoomTransitionEasing;
- zoomOutEasing: ZoomTransitionEasing;
- connectedZoomEasing: ZoomTransitionEasing;
- showCursor: boolean;
- loopCursor: boolean;
- cursorStyle: CursorStyle;
- cursorSize: number;
- cursorSmoothing: number;
- cursorSpringStiffnessMultiplier: number;
- cursorSpringDampingMultiplier: number;
- cursorSpringMassMultiplier: number;
- cameraSpringStiffnessMultiplier: number;
- cameraSpringDampingMultiplier: number;
- cameraSpringMassMultiplier: number;
- zoomSmoothness: number;
- zoomClassicMode: boolean;
- cursorMotionBlur: number;
- cursorClickEffect: CursorClickEffectStyle;
- cursorClickEffectColor: string;
- cursorClickEffectScale: number;
- cursorClickEffectOpacity: number;
- cursorClickEffectDurationMs: number;
- cursorClickBounce: number;
- cursorClickBounceDuration: number;
- cursorSway: number;
- borderRadius: number;
- padding: Padding;
- cropRegion: CropRegion;
- webcam: WebcamOverlaySettings;
- zoomRegions: ZoomRegion[];
- trimRegions: TrimRegion[];
- clipRegions: ClipRegion[];
- speedRegions: SpeedRegion[];
- annotationRegions: AnnotationRegion[];
- audioRegions: AudioRegion[];
- autoCaptions: CaptionCue[];
- autoCaptionSettings: AutoCaptionSettings;
- aspectRatio: AspectRatio;
- exportEncodingMode: ExportEncodingMode;
- exportBackendPreference: ExportBackendPreference;
- exportPipelineModel: ExportPipelineModel;
- exportQuality: ExportQuality;
- mp4FrameRate: ExportMp4FrameRate;
- exportFormat: ExportFormat;
- gifFrameRate: GifFrameRate;
- gifLoop: boolean;
- gifSizePreset: GifSizePreset;
- sourceAudioTrackSettingsByClip: Record<string, SourceAudioTrackSettings>;
- defaultSourceAudioTrackSettings: SourceAudioTrackSettings;
- }>,
- ) => {
- return stripPersistedDevMotionBlurSettings(editor);
- },
- [],
- );
-
- const currentSourcePath = useMemo(
- () => videoSourcePath ?? (videoPath ? fromFileUrl(videoPath) : null),
- [videoPath, videoSourcePath],
- );
- const projectDisplayName = useMemo(() => {
- const fileName =
- currentProjectPath?.split(/[\\/]/).pop() ??
- currentSourcePath?.split(/[\\/]/).pop() ??
- "";
- const withoutExtension = fileName.replace(/\.recordly$/i, "").replace(/\.[^.]+$/, "");
- return withoutExtension || t("editor.project.untitled", "Untitled");
- }, [currentProjectPath, currentSourcePath, t]);
-
- useEffect(() => {
- if (!isEditingProjectName) {
- setProjectNameDraft(projectDisplayName);
- }
- }, [isEditingProjectName, projectDisplayName]);
-
- useEffect(() => {
- if (!isEditingProjectName) {
- return;
- }
+ gifSizePreset,
+ });
- const frameId = window.requestAnimationFrame(() => {
- projectNameInputRef.current?.focus();
- projectNameInputRef.current?.select();
- });
-
- return () => {
- window.cancelAnimationFrame(frameId);
- };
- }, [isEditingProjectName]);
-
- useEffect(() => {
- if (!projectSaveDialogOpen) {
- return;
- }
-
- const frameId = window.requestAnimationFrame(() => {
- projectSaveDialogInputRef.current?.focus();
- projectSaveDialogInputRef.current?.select();
- });
-
- return () => {
- window.cancelAnimationFrame(frameId);
- };
- }, [projectSaveDialogOpen]);
-
- const currentPersistedEditorState = useMemo(
- () =>
- buildPersistedEditorState({
- wallpaper,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- showCursor,
- loopCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- zoomSmoothness,
- zoomClassicMode,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- borderRadius,
- padding,
- cropRegion,
- webcam,
- zoomRegions,
- trimRegions,
- clipRegions,
- speedRegions,
- annotationRegions,
- audioRegions,
- autoCaptions,
- autoCaptionSettings,
- aspectRatio,
- exportEncodingMode,
- exportBackendPreference,
- exportPipelineModel,
- exportQuality,
- mp4FrameRate,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- sourceAudioTrackSettingsByClip,
- defaultSourceAudioTrackSettings,
- }),
- [
- buildPersistedEditorState,
- wallpaper,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- showCursor,
- loopCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- zoomSmoothness,
- zoomClassicMode,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- borderRadius,
- padding,
- cropRegion,
- webcam,
- zoomRegions,
- trimRegions,
- clipRegions,
- speedRegions,
- annotationRegions,
- audioRegions,
- autoCaptions,
- autoCaptionSettings,
- aspectRatio,
- exportEncodingMode,
- exportBackendPreference,
- exportPipelineModel,
- exportQuality,
- mp4FrameRate,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- sourceAudioTrackSettingsByClip,
- defaultSourceAudioTrackSettings,
- ],
- );
-
- const buildHistorySnapshot = useCallback((): EditorHistorySnapshot => {
- return {
- zoomRegions,
- clipRegions,
- speedRegions,
- annotationRegions,
- audioRegions,
- autoCaptions,
- selectedZoomId,
- selectedClipId,
- selectedAnnotationId,
- selectedAudioId,
- };
- }, [
- zoomRegions,
- clipRegions,
- speedRegions,
- annotationRegions,
- audioRegions,
- autoCaptions,
- selectedZoomId,
- selectedClipId,
- selectedAnnotationId,
- selectedAudioId,
- ]);
-
- const applyHistorySnapshot = useCallback((snapshot: EditorHistorySnapshot) => {
- applyingHistoryRef.current = true;
- const cloned = cloneStructured(snapshot);
- setZoomRegions(cloned.zoomRegions);
- setClipRegions(cloned.clipRegions);
- setSpeedRegions(cloned.speedRegions);
- setAnnotationRegions(cloned.annotationRegions);
- setAudioRegions(cloned.audioRegions);
- setAutoCaptions(cloned.autoCaptions);
- setSelectedZoomId(cloned.selectedZoomId);
- setSelectedClipId(cloned.selectedClipId);
- setSelectedAnnotationId(cloned.selectedAnnotationId);
- setSelectedAudioId(cloned.selectedAudioId);
-
- nextZoomIdRef.current = deriveNextId(
- "zoom",
- cloned.zoomRegions.map((region) => region.id),
- );
- nextClipIdRef.current = deriveNextId(
- "clip",
- cloned.clipRegions.map((region) => region.id),
- );
- nextAnnotationIdRef.current = deriveNextId(
- "annotation",
- cloned.annotationRegions.map((region) => region.id),
- );
- nextAudioIdRef.current = deriveNextId(
- "audio",
- cloned.audioRegions.map((region) => region.id),
- );
- nextAnnotationZIndexRef.current =
- cloned.annotationRegions.reduce((max, region) => Math.max(max, region.zIndex), 0) + 1;
- }, []);
-
- const handleUndo = useCallback(() => {
- const previous = undoEditorHistoryStack(editorHistoryRef.current, buildHistorySnapshot());
- if (!previous) return;
-
- applyHistorySnapshot(previous);
- syncHistoryButtons();
- }, [applyHistorySnapshot, buildHistorySnapshot, syncHistoryButtons]);
-
- const handleRedo = useCallback(() => {
- const next = redoEditorHistoryStack(editorHistoryRef.current, buildHistorySnapshot());
- if (!next) return;
-
- applyHistorySnapshot(next);
- syncHistoryButtons();
- }, [applyHistorySnapshot, buildHistorySnapshot, syncHistoryButtons]);
-
- 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(
- stripPersistedDevMotionBlurSettings(project.editor ?? {}),
- );
-
- try {
- videoPlaybackRef.current?.pause();
- } catch {
- // no-op
- }
- setIsPlaying(false);
- setCurrentTime(0);
- setDuration(0);
-
- setError(null);
- setVideoSourcePath(sourcePath);
- setVideoPath(await resolveVideoUrl(sourcePath));
- setCurrentProjectPath(path ?? null);
- pendingFreshRecordingAutoZoomPathRef.current = null;
- if (normalizedEditor.webcam.sourcePath) {
- await window.electronAPI.setCurrentRecordingSession?.(
- {
- videoPath: sourcePath,
- webcamPath: normalizedEditor.webcam.sourcePath,
- timeOffsetMs: normalizedEditor.webcam.timeOffsetMs,
- },
- {
- preserveProjectPath: Boolean(path),
- },
- );
- const sessionResult = await window.electronAPI.getCurrentRecordingSession?.();
- applySessionPresentation(sessionResult?.success ? sessionResult.session : null);
- } else {
- await window.electronAPI.setCurrentVideoPath(sourcePath, {
- preserveProjectPath: Boolean(path),
- });
- applySessionPresentation(null);
- }
-
- setWallpaper(normalizedEditor.wallpaper);
- setShadowIntensity(normalizedEditor.shadowIntensity);
- setBackgroundBlur(normalizedEditor.backgroundBlur);
- setZoomMotionBlur(normalizedEditor.zoomMotionBlur);
- setZoomMotionBlurTuning({ ...normalizedEditor.zoomMotionBlurTuning });
- setZoomTemporalMotionBlur(normalizedEditor.zoomTemporalMotionBlur);
- setZoomMotionBlurSampleCount(normalizedEditor.zoomMotionBlurSampleCount);
- setZoomMotionBlurShutterFraction(normalizedEditor.zoomMotionBlurShutterFraction);
- setConnectZooms(normalizedEditor.connectZooms);
- setZoomInDurationMs(normalizedEditor.zoomInDurationMs);
- setZoomInOverlapMs(normalizedEditor.zoomInOverlapMs);
- setZoomOutDurationMs(normalizedEditor.zoomOutDurationMs);
- setConnectedZoomGapMs(normalizedEditor.connectedZoomGapMs);
- setConnectedZoomDurationMs(normalizedEditor.connectedZoomDurationMs);
- setZoomInEasing(normalizedEditor.zoomInEasing);
- setZoomOutEasing(normalizedEditor.zoomOutEasing);
- setConnectedZoomEasing(normalizedEditor.connectedZoomEasing);
- setShowCursor(normalizedEditor.showCursor);
- setLoopCursor(normalizedEditor.loopCursor);
- setCursorStyle(normalizedEditor.cursorStyle);
- setCursorSize(normalizedEditor.cursorSize);
- setCursorSmoothing(normalizedEditor.cursorSmoothing);
- setCursorSpringStiffnessMultiplier(normalizedEditor.cursorSpringStiffnessMultiplier);
- setCursorSpringDampingMultiplier(normalizedEditor.cursorSpringDampingMultiplier);
- setCursorSpringMassMultiplier(normalizedEditor.cursorSpringMassMultiplier);
- setCameraSpringStiffnessMultiplier(normalizedEditor.cameraSpringStiffnessMultiplier);
- setCameraSpringDampingMultiplier(normalizedEditor.cameraSpringDampingMultiplier);
- setCameraSpringMassMultiplier(normalizedEditor.cameraSpringMassMultiplier);
- setCursorClickEffect(normalizedEditor.cursorClickEffect);
- setCursorClickEffectColor(normalizedEditor.cursorClickEffectColor);
- setCursorClickEffectScale(normalizedEditor.cursorClickEffectScale);
- setCursorClickEffectOpacity(normalizedEditor.cursorClickEffectOpacity);
- setCursorClickEffectDurationMs(normalizedEditor.cursorClickEffectDurationMs);
- setZoomSmoothness(normalizedEditor.zoomSmoothness);
- setZoomClassicMode(normalizedEditor.zoomClassicMode);
- setCursorMotionBlur(normalizedEditor.cursorMotionBlur);
- setCursorClickBounce(normalizedEditor.cursorClickBounce);
- setCursorClickBounceDuration(normalizedEditor.cursorClickBounceDuration);
- setCursorSway(normalizedEditor.cursorSway);
- setBorderRadius(normalizedEditor.borderRadius);
- setPadding(normalizedEditor.padding);
- setCropRegion(normalizedEditor.cropRegion);
- setWebcam(normalizedEditor.webcam);
- setZoomRegions(normalizedEditor.zoomRegions);
- setTrimRegions(normalizedEditor.trimRegions);
- setClipRegions(normalizedEditor.clipRegions);
- clipInitializedRef.current = normalizedEditor.clipRegions.length > 0;
- autoFullTrackClipIdRef.current = null;
- autoFullTrackClipEndMsRef.current = null;
- setSpeedRegions(normalizedEditor.speedRegions);
- setAnnotationRegions(normalizedEditor.annotationRegions);
- setAudioRegions(normalizedEditor.audioRegions);
- setSourceAudioTrackSettingsByClip(
- normalizedEditor.sourceAudioTrackSettingsByClip ?? {},
- );
- setDefaultSourceAudioTrackSettings(
- normalizedEditor.defaultSourceAudioTrackSettings ?? {},
- );
- setAutoCaptions(normalizedEditor.autoCaptions);
- setAutoCaptionSettings(normalizedEditor.autoCaptionSettings);
- setAspectRatio(normalizedEditor.aspectRatio);
- setExportEncodingMode(normalizedEditor.exportEncodingMode);
- setExportBackendPreference(normalizedEditor.exportBackendPreference);
- setExportPipelineModel(normalizedEditor.exportPipelineModel);
- setExportQuality(normalizedEditor.exportQuality);
- setMp4FrameRate(normalizedEditor.mp4FrameRate);
- setExportFormat(normalizedEditor.exportFormat);
- setGifFrameRate(normalizedEditor.gifFrameRate);
- setGifLoop(normalizedEditor.gifLoop);
- setGifSizePreset(normalizedEditor.gifSizePreset);
-
- setSelectedZoomId(null);
- setSelectedClipId(null);
- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
-
- nextZoomIdRef.current = deriveNextId(
- "zoom",
- normalizedEditor.zoomRegions.map((region) => region.id),
- );
- nextClipIdRef.current = deriveNextId(
- "clip",
- normalizedEditor.clipRegions.map((region: ClipRegion) => region.id),
- );
- nextAudioIdRef.current = deriveNextId(
- "audio",
- normalizedEditor.audioRegions.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;
-
- resetEditorHistoryStack(editorHistoryRef.current);
- applyingHistoryRef.current = false;
- syncHistoryButtons();
-
- setLastSavedSnapshot(
- cloneStructured(
- createProjectData(
- sourcePath,
- buildPersistedEditorState(normalizedEditor),
- project.projectId ?? null,
- ),
- ),
- );
- await refreshProjectLibrary();
- return true;
- },
- [
- applySessionPresentation,
- buildPersistedEditorState,
- refreshProjectLibrary,
- syncHistoryButtons,
- ],
- );
-
- const currentProjectSnapshot = useMemo(() => {
- if (!currentSourcePath) {
- return null;
- }
- return createProjectData(
- currentSourcePath,
- currentPersistedEditorState,
- lastSavedSnapshot?.projectId ?? null,
- );
- }, [currentPersistedEditorState, currentSourcePath, lastSavedSnapshot?.projectId]);
-
- const resolveProjectSaveDialog = useCallback((saved: boolean) => {
- const pendingDialog = pendingProjectSaveDialogRef.current;
- pendingProjectSaveDialogRef.current = null;
- setProjectSaveDialogOpen(false);
- setIsSavingProjectDialog(false);
- pendingDialog?.resolve(saved);
- }, []);
-
- const openProjectSaveDialog = useCallback((initialName: string) => {
- pendingProjectSaveDialogRef.current?.resolve(false);
- setProjectSaveDialogDraft(initialName);
- setProjectSaveDialogOpen(true);
- setIsSavingProjectDialog(false);
-
- return new Promise<boolean>((resolve) => {
- pendingProjectSaveDialogRef.current = { resolve };
- });
- }, []);
-
- const resolveUnsavedChangesDialog = useCallback(
- (decision: PendingUnsavedChangesDialogDecision) => {
- const pendingDialog = pendingUnsavedChangesDialogRef.current;
- pendingUnsavedChangesDialogRef.current = null;
- setUnsavedChangesDialogOpen(false);
- pendingDialog?.resolve(decision);
- },
- [],
- );
-
- const openUnsavedChangesDialog = useCallback((actionLabel: string) => {
- pendingUnsavedChangesDialogRef.current?.resolve("cancel");
- setUnsavedChangesDialogActionLabel(actionLabel);
- setUnsavedChangesDialogOpen(true);
-
- return new Promise<PendingUnsavedChangesDialogDecision>((resolve) => {
- pendingUnsavedChangesDialogRef.current = { resolve };
- });
- }, []);
-
- const syncRecordingSessionWebcam = useCallback(
- async (webcamPath: string | null, timeOffsetMs?: number) => {
- if (!currentSourcePath || !window.electronAPI.setCurrentRecordingSession) {
- return;
- }
-
- await window.electronAPI.setCurrentRecordingSession(
- {
- videoPath: currentSourcePath,
- webcamPath,
- timeOffsetMs:
- webcamPath && Number.isFinite(timeOffsetMs)
- ? (timeOffsetMs ?? DEFAULT_WEBCAM_TIME_OFFSET_MS)
- : webcamPath
- ? webcam.timeOffsetMs
- : DEFAULT_WEBCAM_TIME_OFFSET_MS,
- },
- {
- preserveProjectPath: Boolean(currentProjectPath),
- },
- );
- },
- [currentProjectPath, currentSourcePath, webcam.timeOffsetMs],
- );
-
- const syncActiveVideoSource = useCallback(
- async (sourcePath: string, webcamPath?: string | null) => {
- if (webcamPath) {
- await window.electronAPI.setCurrentRecordingSession?.(
- {
- videoPath: sourcePath,
- webcamPath,
- timeOffsetMs: webcam.timeOffsetMs,
- },
- {
- preserveProjectPath: Boolean(currentProjectPath),
- },
- );
- return;
- }
-
- await window.electronAPI.setCurrentVideoPath(sourcePath, {
- preserveProjectPath: Boolean(currentProjectPath),
- });
- },
- [currentProjectPath, webcam.timeOffsetMs],
- );
-
- const resetSourceScopedEditorState = useCallback(() => {
- setZoomRegions([]);
- setTrimRegions([]);
- setClipRegions([]);
- clipInitializedRef.current = false;
- autoFullTrackClipIdRef.current = null;
- autoFullTrackClipEndMsRef.current = null;
- setSpeedRegions([]);
- setAnnotationRegions([]);
- setAudioRegions([]);
- setCursorTelemetry([]);
- setCursorTelemetrySourcePath(null);
- setSourceAudioTrackSettingsByClip({});
- setDefaultSourceAudioTrackSettings({});
- setHasClipSourceAudio(false);
- setAutoCaptions([]);
- setAutoCaptionSettings((prev) => ({ ...prev, enabled: false }));
- setSelectedZoomId(null);
- setSelectedClipId(null);
- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
- nextZoomIdRef.current = 1;
- nextClipIdRef.current = 1;
- nextAudioIdRef.current = 1;
- nextAnnotationIdRef.current = 1;
- nextAnnotationZIndexRef.current = 1;
- pendingFreshRecordingAutoSuggestTelemetryCountRef.current = 0;
- autoSuggestedVideoPathRef.current = null;
- resetEditorHistoryStack(editorHistoryRef.current);
- applyingHistoryRef.current = false;
- syncHistoryButtons();
- }, [syncHistoryButtons]);
-
- const handleUploadWebcam = useCallback(async () => {
- const result = await window.electronAPI.openVideoFilePicker();
- if (!result.success || !result.path) {
- return;
- }
-
- setWebcam((prev) => ({
- ...prev,
- enabled: true,
- sourcePath: result.path ?? null,
- timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
- }));
-
- await syncRecordingSessionWebcam(result.path, DEFAULT_WEBCAM_TIME_OFFSET_MS);
- toast.success(t("settings.effects.webcamFootageAdded"));
- }, [syncRecordingSessionWebcam, t]);
-
- const handleClearWebcam = useCallback(async () => {
- setWebcam((prev) => ({
- ...prev,
- enabled: false,
- sourcePath: null,
- timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
- }));
-
- await syncRecordingSessionWebcam(null);
- toast.success(t("settings.effects.webcamFootageRemoved"));
- }, [syncRecordingSessionWebcam, t]);
-
- useEffect(() => {
- const snapshot = buildHistorySnapshot();
- const result = recordEditorHistorySnapshot(editorHistoryRef.current, snapshot, {
- applyingHistory: applyingHistoryRef.current,
- });
-
- if (result === "applied") {
- applyingHistoryRef.current = false;
- }
-
- if (result !== "unchanged") {
- syncHistoryButtons();
- }
- }, [buildHistorySnapshot, syncHistoryButtons]);
-
- const hasUnsavedChanges = useMemo(
- () => hasUnsavedProjectChanges(currentProjectSnapshot, lastSavedSnapshot),
- [currentProjectSnapshot, lastSavedSnapshot],
- );
-
- useEffect(() => {
- async function loadInitialData() {
- try {
- if (smokeExportConfig.enabled && smokeExportConfig.projectPath) {
- const projectResult = await window.electronAPI.openProjectFileAtPath(
- smokeExportConfig.projectPath,
- );
- if (!projectResult.success || !projectResult.project) {
- setError(
- `Smoke export failed to load project ${smokeExportConfig.projectPath}: ${
- projectResult.error || projectResult.message || "unknown error"
- }`,
- );
- return;
- }
- const restored = await applyLoadedProject(
- projectResult.project,
- projectResult.path ?? smokeExportConfig.projectPath,
- );
- if (!restored) {
- setError(
- `Smoke export could not apply project ${smokeExportConfig.projectPath}`,
- );
- return;
- }
- setError(null);
- return;
- }
-
- if (!smokeExportConfig.enabled && devOpenRecordingConfig.inputPath) {
- const sourcePath = fromFileUrl(devOpenRecordingConfig.inputPath);
- const sourceVideoUrl = await resolveVideoUrl(sourcePath);
- const webcamSourcePath = devOpenRecordingConfig.webcamInputPath
- ? fromFileUrl(devOpenRecordingConfig.webcamInputPath)
- : null;
- setVideoSourcePath(sourcePath);
- setVideoPath(sourceVideoUrl);
- setCurrentProjectPath(null);
- setLastSavedSnapshot(null);
- resetSourceScopedEditorState();
- pendingFreshRecordingAutoZoomPathRef.current = autoApplyFreshRecordingAutoZooms
- ? sourceVideoUrl
- : null;
- setWebcam((prev) => ({
- ...prev,
- enabled: Boolean(webcamSourcePath),
- sourcePath: webcamSourcePath,
- timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
- }));
- setError(null);
- return;
- }
-
- if (smokeExportConfig.enabled) {
- if (!smokeExportConfig.inputPath) {
- setError("Smoke export input path is missing.");
- return;
- }
-
- const sourcePath = fromFileUrl(smokeExportConfig.inputPath);
- const sourceVideoUrl = await resolveVideoUrl(sourcePath);
- const smokeWebcamSourcePath = smokeExportConfig.webcamInputPath
- ? fromFileUrl(smokeExportConfig.webcamInputPath)
- : null;
- setVideoSourcePath(sourcePath);
- setVideoPath(sourceVideoUrl);
- setCurrentProjectPath(null);
- setLastSavedSnapshot(null);
- resetSourceScopedEditorState();
- pendingFreshRecordingAutoZoomPathRef.current = null;
- setWebcam((prev) => ({
- ...prev,
- enabled: !!smokeWebcamSourcePath,
- sourcePath: smokeWebcamSourcePath,
- timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
- shadow:
- smokeExportConfig.webcamShadow === undefined
- ? prev.shadow
- : smokeExportConfig.webcamShadow,
- size:
- smokeExportConfig.webcamSize === undefined
- ? prev.size
- : smokeExportConfig.webcamSize,
- width:
- smokeExportConfig.webcamSize === undefined
- ? (prev.width ?? prev.size)
- : smokeExportConfig.webcamSize,
- height:
- smokeExportConfig.webcamSize === undefined
- ? (prev.height ?? prev.size)
- : smokeExportConfig.webcamSize,
- }));
- setError(null);
- return;
- }
-
- const currentProjectResult = await window.electronAPI.loadCurrentProjectFile();
- if (currentProjectResult.success && currentProjectResult.project) {
- const restored = await applyLoadedProject(
- currentProjectResult.project,
- currentProjectResult.path ?? null,
- );
- if (restored) {
- // Re-apply user preferences so stale project data does not
- // overwrite the last-used padding, aspect ratio, export
- // settings, etc. that were saved to localStorage.
- setPadding(initialEditorPreferences.padding);
- setBorderRadius(initialEditorPreferences.borderRadius);
- setAspectRatio(initialEditorPreferences.aspectRatio);
- setExportFormat(initialEditorPreferences.exportFormat);
- setMp4FrameRate(
- initialEditorPreferences.mp4FrameRate ?? DEFAULT_MP4_EXPORT_FRAME_RATE,
- );
- setExportQuality(initialEditorPreferences.exportQuality);
- setExportEncodingMode(initialEditorPreferences.exportEncodingMode);
- setExportBackendPreference(
- initialEditorPreferences.exportBackendPreference,
- );
- setExportPipelineModel(initialEditorPreferences.exportPipelineModel);
- setGifFrameRate(initialEditorPreferences.gifFrameRate);
- setGifLoop(initialEditorPreferences.gifLoop);
- setGifSizePreset(initialEditorPreferences.gifSizePreset);
- return;
- }
- }
-
- const sessionResult = await window.electronAPI.getCurrentRecordingSession?.();
- if (sessionResult?.success && sessionResult.session?.videoPath) {
- const sourcePath = fromFileUrl(sessionResult.session.videoPath);
- const sourceVideoUrl = await resolveVideoUrl(sourcePath);
- setVideoSourcePath(sourcePath);
- setVideoPath(sourceVideoUrl);
- setCurrentProjectPath(null);
- setLastSavedSnapshot(null);
- resetSourceScopedEditorState();
- pendingFreshRecordingAutoZoomPathRef.current = autoApplyFreshRecordingAutoZooms
- ? sourceVideoUrl
- : null;
- applySessionPresentation(sessionResult.session);
- setWebcam((prev) => ({
- ...prev,
- enabled: Boolean(sessionResult.session?.webcamPath),
- sourcePath: sessionResult.session?.webcamPath ?? null,
- timeOffsetMs:
- sessionResult.session?.timeOffsetMs ?? DEFAULT_WEBCAM_TIME_OFFSET_MS,
- }));
- return;
- }
-
- const result = await window.electronAPI.getCurrentVideoPath();
- if (result.success && result.path) {
- const sourcePath = fromFileUrl(result.path);
- const sourceVideoUrl = await resolveVideoUrl(sourcePath);
- setVideoSourcePath(sourcePath);
- setVideoPath(sourceVideoUrl);
- setCurrentProjectPath(null);
- setLastSavedSnapshot(null);
- resetSourceScopedEditorState();
- pendingFreshRecordingAutoZoomPathRef.current = null;
- applySessionPresentation(null);
- setWebcam((prev) => ({
- ...prev,
- enabled: false,
- sourcePath: null,
- timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
- }));
- } 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,
- applySessionPresentation,
- autoApplyFreshRecordingAutoZooms,
- devOpenRecordingConfig.inputPath,
- devOpenRecordingConfig.webcamInputPath,
- initialEditorPreferences,
- resetSourceScopedEditorState,
- smokeExportConfig.enabled,
- smokeExportConfig.inputPath,
- smokeExportConfig.projectPath,
- smokeExportConfig.webcamInputPath,
- smokeExportConfig.webcamShadow,
- smokeExportConfig.webcamSize,
- ]);
-
- useEffect(() => {
- if (!window.electronAPI.onRecordingSessionChanged) {
- return;
- }
-
- return window.electronAPI.onRecordingSessionChanged((session) => {
- const sessionSourcePath = session?.videoPath ? fromFileUrl(session.videoPath) : null;
- const sessionWebcamPath = session?.webcamPath ? fromFileUrl(session.webcamPath) : null;
- console.log("[VideoEditor] onRecordingSessionChanged received!", {
- hasSession: Boolean(session),
- hasSessionVideoPath: Boolean(session?.videoPath),
- hasVideoSourcePath: Boolean(videoSourcePath),
- match: sessionSourcePath === videoSourcePath,
- hasWebcamPath: Boolean(sessionWebcamPath),
- });
-
- if (!session || sessionSourcePath !== videoSourcePath) {
- return;
- }
-
- setWebcam((prev) => ({
- ...prev,
- enabled: Boolean(sessionWebcamPath),
- sourcePath: sessionWebcamPath,
- timeOffsetMs: sessionWebcamPath
- ? (session.timeOffsetMs ?? prev.timeOffsetMs)
- : DEFAULT_WEBCAM_TIME_OFFSET_MS,
- }));
- setSourceAudioFallbackRefreshKey((key) => key + 1);
- });
- }, [videoSourcePath]);
-
- useEffect(() => {
- let cancelled = false;
- if (!webcam.sourcePath) {
- setResolvedWebcamVideoUrl(null);
- return;
- }
- void resolveVideoUrl(webcam.sourcePath).then((url) => {
- if (!cancelled) setResolvedWebcamVideoUrl(url);
- });
- return () => {
- cancelled = true;
- };
- }, [webcam.sourcePath]);
-
- useEffect(() => {
- if (!autoApplyFreshRecordingAutoZooms) {
- pendingFreshRecordingAutoZoomPathRef.current = null;
- }
- }, [autoApplyFreshRecordingAutoZooms]);
-
- useEffect(() => {
- saveEditorPreferences({
- wallpaper,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- autoApplyFreshRecordingAutoZooms,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- showCursor,
- loopCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- borderRadius,
- padding,
- webcam,
- aspectRatio,
- exportEncodingMode,
- exportBackendPreference,
- exportPipelineModel,
- exportQuality,
- mp4FrameRate,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- whisperExecutablePath,
- whisperModelPath,
- });
- }, [
- wallpaper,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- autoApplyFreshRecordingAutoZooms,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- showCursor,
- loopCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- borderRadius,
- padding,
- webcam,
- aspectRatio,
- exportEncodingMode,
- exportBackendPreference,
- exportPipelineModel,
- exportQuality,
- mp4FrameRate,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- whisperExecutablePath,
- whisperModelPath,
- ]);
-
- useEffect(() => {
- const unsubscribe = window.electronAPI.onWhisperSmallModelDownloadProgress((state) => {
- setWhisperModelDownloadStatus(state.status);
- setWhisperModelDownloadProgress(state.progress);
- if (state.status === "downloaded") {
- setDownloadedWhisperModelPath(state.path ?? null);
- setWhisperModelPath((currentPath) => currentPath ?? state.path ?? null);
- }
- if (state.status === "idle") {
- setDownloadedWhisperModelPath(null);
- }
- if (state.status === "error" && state.error) {
- toast.error(state.error);
- }
- });
-
- void (async () => {
- const result = await window.electronAPI.getWhisperSmallModelStatus();
- if (!result.success) {
- return;
- }
-
- if (result.exists && result.path) {
- setDownloadedWhisperModelPath(result.path);
- setWhisperModelPath((currentPath) => currentPath ?? result.path ?? null);
- setWhisperModelDownloadStatus("downloaded");
- setWhisperModelDownloadProgress(100);
- return;
- }
-
- setDownloadedWhisperModelPath(null);
- setWhisperModelDownloadStatus("idle");
- setWhisperModelDownloadProgress(0);
- })();
-
- return () => unsubscribe?.();
- }, []);
-
- const handlePickWhisperExecutable = useCallback(async () => {
- const result = await window.electronAPI.openWhisperExecutablePicker();
- if (!result.success || !result.path) {
- return;
- }
-
- setWhisperExecutablePath(result.path);
- toast.success("Whisper executable selected");
- }, []);
-
- const handleDownloadWhisperSmallModel = useCallback(async () => {
- if (whisperModelDownloadStatus === "downloading") {
- return;
- }
-
- setWhisperModelDownloadStatus("downloading");
- setWhisperModelDownloadProgress(0);
- const result = await window.electronAPI.downloadWhisperSmallModel();
- if (!result.success) {
- setWhisperModelDownloadStatus("error");
- toast.error(result.error || "Failed to download Whisper small model");
- return;
- }
-
- if (result.path) {
- setDownloadedWhisperModelPath(result.path);
- setWhisperModelPath(result.path);
- }
- }, [whisperModelDownloadStatus]);
-
- const handlePickWhisperModel = useCallback(async () => {
- const result = await window.electronAPI.openWhisperModelPicker();
- if (!result.success || !result.path) {
- return;
- }
-
- setWhisperModelPath(result.path);
- toast.success("Whisper model selected");
- }, []);
-
- const handleDeleteWhisperSmallModel = useCallback(async () => {
- const result = await window.electronAPI.deleteWhisperSmallModel();
- if (!result.success) {
- toast.error(result.error || "Failed to delete Whisper small model");
- // Reset download state so re-download is not blocked
- setWhisperModelDownloadStatus("idle");
- setWhisperModelDownloadProgress(0);
- return;
- }
-
- setWhisperModelPath((currentPath) =>
- currentPath === downloadedWhisperModelPath ? null : currentPath,
- );
- setDownloadedWhisperModelPath(null);
- setWhisperModelDownloadStatus("idle");
- setWhisperModelDownloadProgress(0);
- toast.success("Whisper small model deleted");
- }, [downloadedWhisperModelPath]);
-
- const handleGenerateAutoCaptions = useCallback(async () => {
- if (isGeneratingCaptions) {
- return;
- }
-
- let sourcePath = resolveAutoCaptionSourcePath({
- videoSourcePath,
- videoPath,
- });
-
- if (!sourcePath) {
- const sessionResult = await window.electronAPI.getCurrentRecordingSession?.();
- const currentVideoResult = await window.electronAPI.getCurrentVideoPath();
- sourcePath = resolveAutoCaptionSourcePath({
- recordingSessionVideoPath:
- sessionResult?.success && sessionResult.session?.videoPath
- ? sessionResult.session.videoPath
- : null,
- currentVideoPath: currentVideoResult.success
- ? (currentVideoResult.path ?? null)
- : null,
- });
- }
-
- if (!sourcePath) {
- toast.error("No source video is loaded");
- return;
- }
-
- if (sourcePath !== videoSourcePath) {
- setVideoSourcePath(sourcePath);
- setVideoPath(await resolveVideoUrl(sourcePath));
- }
-
- await syncActiveVideoSource(sourcePath, webcam.sourcePath ?? null);
-
- if (!whisperModelPath) {
- toast.error("Select a Whisper model or download the small model first");
- return;
- }
-
- setIsGeneratingCaptions(true);
- try {
- const result = await window.electronAPI.generateAutoCaptions({
- videoPath: sourcePath,
- whisperExecutablePath: whisperExecutablePath ?? undefined,
- whisperModelPath,
- language: autoCaptionSettings.language,
- });
-
- if (!result.success || !result.cues) {
- toast.error(
- result.message ||
- getErrorMessage(result.error) ||
- "Failed to generate captions",
- );
- return;
- }
-
- setAutoCaptions(result.cues);
- if (result.cues.length > 0) {
- setAutoCaptionSettings((prev) => ({ ...prev, enabled: true }));
- }
- toast.success(result.message || `Generated ${result.cues.length} captions`);
- } catch (error) {
- toast.error(getErrorMessage(error));
- } finally {
- setIsGeneratingCaptions(false);
- }
- }, [
- autoCaptionSettings.language,
- isGeneratingCaptions,
- webcam.sourcePath,
- syncActiveVideoSource,
- videoPath,
- videoSourcePath,
- whisperExecutablePath,
- whisperModelPath,
- ]);
-
- const handleClearAutoCaptions = useCallback(() => {
- setAutoCaptions([]);
- setAutoCaptionSettings((prev) => ({ ...prev, enabled: false }));
- }, []);
-
- const handleSaveAutoCaptionEdit = useCallback(
- (target: CaptionEditTarget, text: string) => {
- setAutoCaptions((captions) => updateCaptionCuesForEditedTarget(captions, target, text));
- toast.success(t("settings.captions.editSaved", "Caption updated"));
- },
- [t],
- );
-
- const saveProject = useCallback(
- async (forceSaveAs: boolean, options?: SaveProjectOptions) => {
- clearPendingProjectAutosave();
- return queueProjectSave(async () => {
- if (!currentSourcePath) {
- if (!options?.silent) {
- toast.error("No video loaded");
- }
- return false;
- }
-
- const shouldCaptureThumbnail = options?.captureThumbnail ?? true;
- const shouldRefreshLibrary = options?.refreshLibraryAfterSave ?? true;
- const shouldRemountPreview = options?.remountPreviewAfterSave ?? true;
-
- try {
- const projectData =
- currentProjectSnapshot?.videoPath === currentSourcePath
- ? currentProjectSnapshot
- : createProjectData(
- currentSourcePath,
- currentPersistedEditorState,
- lastSavedSnapshot?.projectId ?? null,
- );
-
- const fileNameBase =
- currentSourcePath
- .split(/[\\/]/)
- .pop()
- ?.replace(/\.[^.]+$/, "") || `project-${Date.now()}`;
- let targetProjectPath = forceSaveAs
- ? undefined
- : (currentProjectPath ?? undefined);
-
- if (!forceSaveAs && !targetProjectPath) {
- const activeProjectResult =
- await window.electronAPI.loadCurrentProjectFile();
- if (activeProjectResult.success && activeProjectResult.path) {
- targetProjectPath = activeProjectResult.path;
- setCurrentProjectPath(activeProjectResult.path);
- }
- }
-
- if (forceSaveAs || !targetProjectPath) {
- if (options?.silent) {
- return false;
- }
-
- return openProjectSaveDialog(projectDisplayName || fileNameBase);
- }
-
- const thumbnailDataUrl = shouldCaptureThumbnail
- ? await captureProjectThumbnail()
- : undefined;
-
- const result = await window.electronAPI.saveProjectFile(
- projectData,
- fileNameBase,
- targetProjectPath,
- thumbnailDataUrl,
- );
-
- if (result.canceled) {
- if (!options?.silent) {
- toast.info("Project save canceled");
- }
- return false;
- }
-
- if (!result.success) {
- if (!options?.silent) {
- toast.error(result.message || "Failed to save project");
- }
- return false;
- }
-
- if (result.path) {
- setCurrentProjectPath(result.path);
- }
- setLastSavedSnapshot(
- cloneStructured(
- createProjectData(
- projectData.videoPath,
- projectData.editor,
- result.projectId ?? projectData.projectId ?? null,
- ),
- ),
- );
- if (shouldRefreshLibrary) {
- await refreshProjectLibrary();
- }
-
- if (!options?.silent) {
- toast.success(`Project saved to ${result.path}`);
- }
- return true;
- } finally {
- if (shouldRemountPreview) {
- remountPreview();
- }
- }
- });
- },
- [
- captureProjectThumbnail,
- clearPendingProjectAutosave,
- currentSourcePath,
- currentProjectPath,
- currentProjectSnapshot,
- currentPersistedEditorState,
- lastSavedSnapshot?.projectId,
- openProjectSaveDialog,
- projectDisplayName,
- queueProjectSave,
- refreshProjectLibrary,
- remountPreview,
- ],
- );
-
- 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 () => {
- const saved = await saveProject(true);
- if (saved) {
- setProjectBrowserOpen(false);
- }
- }, [saveProject]);
-
- useEffect(() => {
- if (!currentProjectPath || !hasUnsavedChanges) {
- clearPendingProjectAutosave();
- return;
- }
-
- projectAutosaveTimeoutRef.current = window.setTimeout(() => {
- projectAutosaveTimeoutRef.current = null;
- void saveProject(false, {
- silent: true,
- remountPreviewAfterSave: false,
- refreshLibraryAfterSave: false,
- captureThumbnail: false,
- });
- }, PROJECT_AUTOSAVE_DELAY_MS);
-
- return () => {
- clearPendingProjectAutosave();
- };
- }, [clearPendingProjectAutosave, currentProjectPath, hasUnsavedChanges, saveProject]);
-
- /**
- * Saves the current project directly into the projects library under a chosen name.
- */
- const saveProjectWithName = useCallback(
- async (projectName: string, mode: NamedProjectSaveMode = "rename") => {
- const trimmedProjectName = projectName.trim();
- if (!trimmedProjectName) {
- toast.error("Project name is required");
- return false;
- }
-
- if (!currentSourcePath) {
- toast.error("No video loaded");
- return false;
- }
-
- try {
- const projectData =
- currentProjectSnapshot?.videoPath === currentSourcePath
- ? currentProjectSnapshot
- : createProjectData(
- currentSourcePath,
- currentPersistedEditorState,
- lastSavedSnapshot?.projectId ?? null,
- );
- const thumbnailDataUrl = await captureProjectThumbnail();
- const result = await window.electronAPI.saveProjectFileNamed(
- projectData,
- trimmedProjectName,
- thumbnailDataUrl,
- mode,
- );
-
- 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(
- cloneStructured(
- createProjectData(
- projectData.videoPath,
- projectData.editor,
- result.projectId ?? projectData.projectId ?? null,
- ),
- ),
- );
- await refreshProjectLibrary();
- toast.success(result.path ? `Project saved to ${result.path}` : "Project saved");
- return true;
- } finally {
- remountPreview();
- }
- },
- [
- captureProjectThumbnail,
- currentPersistedEditorState,
- currentProjectSnapshot,
- currentSourcePath,
- lastSavedSnapshot?.projectId,
- refreshProjectLibrary,
- remountPreview,
- ],
- );
-
- const handleProjectSaveDialogSubmit = useCallback(
- async (event?: React.FormEvent<HTMLFormElement>) => {
- event?.preventDefault();
- const trimmedProjectName = projectSaveDialogDraft.trim();
-
- if (!trimmedProjectName) {
- toast.error("Project name is required");
- projectSaveDialogInputRef.current?.focus();
- return;
- }
-
- setIsSavingProjectDialog(true);
- let saved = false;
- try {
- saved = await saveProjectWithName(trimmedProjectName, "copy");
- } catch (error) {
- toast.error(getErrorMessage(error));
- } finally {
- setIsSavingProjectDialog(false);
- }
-
- if (saved) {
- resolveProjectSaveDialog(true);
- return;
- }
-
- projectSaveDialogInputRef.current?.focus();
- projectSaveDialogInputRef.current?.select();
- },
- [projectSaveDialogDraft, resolveProjectSaveDialog, saveProjectWithName],
- );
-
- /**
- * Resets the inline project-name editor back to the current saved display name.
- */
- const closeProjectNameEditor = useCallback(() => {
- setProjectNameDraft(projectDisplayName);
- setIsEditingProjectName(false);
- }, [projectDisplayName]);
-
- /**
- * Commits the inline project-name editor and persists the project under that name.
- */
- const handleProjectNameSubmit = useCallback(
- async (event?: React.FormEvent<HTMLFormElement>) => {
- event?.preventDefault();
- const trimmedProjectName = projectNameDraft.trim();
- if (!trimmedProjectName) {
- closeProjectNameEditor();
- return;
- }
-
- setIsSavingProjectName(true);
- let saved = false;
- try {
- saved = await saveProjectWithName(trimmedProjectName, "rename");
- } catch (error) {
- toast.error(getErrorMessage(error));
- } finally {
- setIsSavingProjectName(false);
- }
-
- if (saved) {
- setIsEditingProjectName(false);
- return;
- }
-
- projectNameInputRef.current?.focus();
- projectNameInputRef.current?.select();
- },
- [closeProjectNameEditor, projectNameDraft, saveProjectWithName],
- );
-
- const confirmReplaceSourceWithUnsavedChanges = useCallback(
- async (actionLabel: string) => {
- if (!hasUnsavedChanges) {
- return true;
- }
-
- const decision = await openUnsavedChangesDialog(actionLabel);
- if (decision === "discard") {
- return true;
- }
-
- if (decision === "save") {
- return saveProject(false);
- }
-
- return false;
- },
- [hasUnsavedChanges, openUnsavedChangesDialog, saveProject],
- );
-
- const handleOpenProjectFromLibrary = useCallback(
- async (projectPath: string) => {
- if (!(await confirmReplaceSourceWithUnsavedChanges("open another project"))) {
- return;
- }
-
- const result = await window.electronAPI.openProjectFileAtPath(projectPath);
-
- 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;
- }
-
- setProjectBrowserOpen(false);
- await refreshProjectLibrary();
- toast.success(`Project loaded from ${result.path}`);
- },
- [applyLoadedProject, confirmReplaceSourceWithUnsavedChanges, refreshProjectLibrary],
- );
-
- const handleImportMediaOrProject = useCallback(async () => {
- if (!(await confirmReplaceSourceWithUnsavedChanges("import a file"))) {
- return;
- }
-
- const result = await window.electronAPI.openVideoFilePicker({ includeProjects: true });
-
- if (result.canceled) {
- return;
- }
-
- if (!result.success) {
- toast.error(result.message || "Failed to import file");
- return;
- }
-
- if (result.kind === "project" || result.project) {
- const restored = await applyLoadedProject(result.project, result.path ?? null);
- if (!restored) {
- toast.error("Invalid project file format");
- return;
- }
-
- setProjectBrowserOpen(false);
- await refreshProjectLibrary();
- toast.success(result.path ? `Project loaded from ${result.path}` : "Project loaded");
- return;
- }
-
- if (!result.path) {
- toast.error("No media file selected");
- return;
- }
-
- const sourcePath = fromFileUrl(result.path);
- const sourceVideoUrl = await resolveVideoUrl(sourcePath);
- try {
- videoPlaybackRef.current?.pause();
- } catch {
- // no-op
- }
-
- setIsPlaying(false);
- setCurrentTime(0);
- setDuration(0);
- setVideoSourcePath(sourcePath);
- setVideoPath(sourceVideoUrl);
- setCurrentProjectPath(null);
- setLastSavedSnapshot(null);
- resetSourceScopedEditorState();
- pendingFreshRecordingAutoZoomPathRef.current = autoApplyFreshRecordingAutoZooms
- ? sourceVideoUrl
- : null;
- setWebcam((prev) => ({
- ...prev,
- enabled: false,
- sourcePath: null,
- timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
- }));
- applySessionPresentation(null);
- await window.electronAPI.setCurrentVideoPath(sourcePath, { preserveProjectPath: false });
- setProjectBrowserOpen(false);
- await refreshProjectLibrary();
- toast.success("Media imported");
- }, [
- applyLoadedProject,
- applySessionPresentation,
- autoApplyFreshRecordingAutoZooms,
- confirmReplaceSourceWithUnsavedChanges,
- refreshProjectLibrary,
- resetSourceScopedEditorState,
- ]);
-
- const handleOpenProjectBrowser = useCallback(async () => {
- if (projectBrowserOpen) {
- setProjectBrowserOpen(false);
- return;
- }
-
- await refreshProjectLibrary();
- setProjectBrowserOpen(true);
- }, [projectBrowserOpen, refreshProjectLibrary]);
-
- useEffect(() => {
- const removeLoadListener = window.electronAPI.onMenuLoadProject(() => {
- void handleOpenProjectBrowser();
- });
- const removeSaveListener = window.electronAPI.onMenuSaveProject(handleSaveProject);
- const removeSaveAsListener = window.electronAPI.onMenuSaveProjectAs(handleSaveProjectAs);
-
- return () => {
- removeLoadListener?.();
- removeSaveListener?.();
- removeSaveAsListener?.();
- };
- }, [handleOpenProjectBrowser, handleSaveProject, handleSaveProjectAs]);
-
- useEffect(() => {
- let mounted = true;
- let retryAttempts = 0;
-
- async function loadCursorTelemetry() {
- if (!videoPath || !videoSourcePath) {
- if (mounted) {
- setCursorTelemetry([]);
- setCursorTelemetrySourcePath(null);
- }
- return;
- }
-
- try {
- const result = await window.electronAPI.getCursorTelemetry(videoSourcePath);
- if (mounted) {
- const samples = result.success ? result.samples : [];
- setCursorTelemetry(samples);
- setCursorTelemetrySourcePath(videoSourcePath);
-
- const shouldRetryFreshRecordingTelemetry =
- pendingFreshRecordingAutoZoomPathRef.current === videoPath &&
- autoSuggestedVideoPathRef.current !== videoPath &&
- retryAttempts < 12;
-
- if (shouldRetryFreshRecordingTelemetry) {
- retryAttempts += 1;
- pendingTelemetryRetryTimeoutRef.current = window.setTimeout(() => {
- pendingTelemetryRetryTimeoutRef.current = null;
- if (mounted) {
- void loadCursorTelemetry();
- }
- }, 350);
- }
- }
- } catch (telemetryError) {
- console.warn("Unable to load cursor telemetry:", telemetryError);
- if (mounted) {
- setCursorTelemetry([]);
- setCursorTelemetrySourcePath(videoSourcePath);
- if (
- pendingFreshRecordingAutoZoomPathRef.current === videoPath &&
- autoSuggestedVideoPathRef.current !== videoPath &&
- retryAttempts < 12
- ) {
- retryAttempts += 1;
- pendingTelemetryRetryTimeoutRef.current = window.setTimeout(() => {
- pendingTelemetryRetryTimeoutRef.current = null;
- if (mounted) {
- void loadCursorTelemetry();
- }
- }, 350);
- }
- }
- }
- }
-
- if (pendingTelemetryRetryTimeoutRef.current !== null) {
- window.clearTimeout(pendingTelemetryRetryTimeoutRef.current);
- pendingTelemetryRetryTimeoutRef.current = null;
- }
-
- loadCursorTelemetry();
-
- return () => {
- mounted = false;
- if (pendingTelemetryRetryTimeoutRef.current !== null) {
- window.clearTimeout(pendingTelemetryRetryTimeoutRef.current);
- pendingTelemetryRetryTimeoutRef.current = null;
- }
- };
- }, [videoPath, videoSourcePath]);
-
- const normalizedCursorTelemetry = useMemo(() => {
- if (cursorTelemetry.length === 0) {
- return [] as CursorTelemetryPoint[];
- }
-
- const totalMs = Math.max(0, Math.round(duration * 1000));
- return normalizeCursorTelemetry(
- cursorTelemetry,
- totalMs > 0 ? totalMs : Number.MAX_SAFE_INTEGER,
- );
- }, [cursorTelemetry, duration]);
-
- const displayedTimelineWindow = useMemo(() => {
- const totalMs = Math.max(0, Math.round(duration * 1000));
- return getDisplayedTimelineWindowMs(totalMs, trimRegions);
- }, [duration, trimRegions]);
-
- const effectiveCursorTelemetry = useMemo(() => {
- if (!loopCursor) {
- return normalizedCursorTelemetry;
- }
-
- if (
- normalizedCursorTelemetry.length < 2 ||
- displayedTimelineWindow.endMs <= displayedTimelineWindow.startMs
- ) {
- return normalizedCursorTelemetry;
- }
-
- return buildLoopedCursorTelemetry(
- normalizedCursorTelemetry,
- displayedTimelineWindow.endMs,
- displayedTimelineWindow.startMs,
- );
- }, [loopCursor, normalizedCursorTelemetry, displayedTimelineWindow]);
-
- // Initialize a full-track clip when duration is first known
- const clipInitializedRef = useRef(false);
- const autoFullTrackClipIdRef = useRef<string | null>(null);
- const autoFullTrackClipEndMsRef = useRef<number | null>(null);
- useEffect(() => {
- const totalMs = Math.round(duration * 1000);
- if (totalMs <= 0) return;
- if (!clipInitializedRef.current) {
- if (clipRegions.length === 0) {
- const nextClipRegions =
- trimRegions.length > 0
- ? trimsToClips(trimRegions, totalMs)
- : (() => {
- const id = `clip-${nextClipIdRef.current++}`;
- autoFullTrackClipIdRef.current = id;
- autoFullTrackClipEndMsRef.current = totalMs;
- return [{ id, startMs: 0, endMs: totalMs, speed: 1 }];
- })();
-
- if (trimRegions.length > 0) {
- nextClipIdRef.current = deriveNextId(
- "clip",
- nextClipRegions.map((region) => region.id),
- );
- }
-
- setClipRegions(nextClipRegions);
- if (speedRegions.length > 0) {
- // Legacy speed regions no longer have dedicated editing surfaces.
- // Clear them during clip bootstrap so old projects do not keep
- // hidden playback changes that users cannot inspect or edit.
- setSpeedRegions([]);
- }
- }
- clipInitializedRef.current = true;
- return;
- }
-
- const extendedClipRegions = extendAutoFullTrackClip(
- clipRegions,
- autoFullTrackClipIdRef.current,
- autoFullTrackClipEndMsRef.current,
- totalMs,
- );
- if (!extendedClipRegions) return;
-
- autoFullTrackClipEndMsRef.current = totalMs;
- setClipRegions(extendedClipRegions);
- }, [duration, clipRegions, trimRegions, speedRegions]);
-
- // Derive trimRegions from clipRegions so export/playback pipelines stay unchanged
- useEffect(() => {
- const totalMs = Math.round(duration * 1000);
- if (totalMs <= 0 || clipRegions.length === 0) return;
- setTrimRegions(clipsToTrims(clipRegions, totalMs));
- }, [clipRegions, duration]);
-
- const mapTimelineTimeToSourceTime = useCallback(
- (timeMs: number) => resolveTimelineTimeToSourceTime(timeMs, clipRegions),
- [clipRegions],
- );
-
- const mapSourceTimeToTimelineTime = useCallback(
- (timeMs: number) => resolveSourceTimeToTimelineTime(timeMs, clipRegions),
- [clipRegions],
- );
-
- const effectiveZoomRegions = useMemo<ZoomRegion[]>(
- () =>
- zoomRegions.map((region) => ({
- ...region,
- startMs: mapTimelineTimeToSourceTime(region.startMs),
- endMs: mapTimelineTimeToSourceTime(region.endMs),
- })),
- [zoomRegions, mapTimelineTimeToSourceTime],
- );
-
- const effectiveCaptionRegions = useMemo<CaptionCue[]>(
- () =>
- autoCaptions.map((cue) => ({
- ...cue,
- startMs: mapSourceTimeToTimelineTime(cue.startMs),
- endMs: mapSourceTimeToTimelineTime(cue.endMs),
- })),
- [autoCaptions, mapSourceTimeToTimelineTime],
- );
-
- const timelinePlayheadTime = useMemo(
- () => mapSourceTimeToTimelineTime(currentTime * 1000) / 1000,
- [currentTime, mapSourceTimeToTimelineTime],
- );
- const timelineDuration = useMemo(
- () => getTimelineDurationMs(clipRegions, duration * 1000) / 1000,
- [clipRegions, duration],
- );
-
- // Merge clip speeds into speed regions so playback + export respect per-clip speed
- const effectiveSpeedRegions = useMemo<SpeedRegion[]>(() => {
- const clipDerived: SpeedRegion[] = clipRegions
- .filter((clip) => clip.speed !== 1)
- .map((clip) => ({
- id: `clip-speed-${clip.id}`,
- startMs: clip.startMs,
- endMs: getClipSourceEndMs(clip),
- speed: clip.speed as SpeedRegion["speed"],
- }));
- if (clipDerived.length === 0) return speedRegions;
- const result = [...speedRegions];
- for (const cs of clipDerived) {
- const overlaps = speedRegions.some(
- (sr) => sr.endMs > cs.startMs && sr.startMs < cs.endMs,
- );
- if (!overlaps) {
- result.push(cs);
- }
- }
- return result;
- }, [clipRegions, speedRegions]);
- const audio = useVideoEditorAudio({
- currentSourcePath,
- selectedClipId,
- clipRegions,
- audioRegions,
- effectiveSpeedRegions,
- sourceAudioTrackSettingsByClip,
- setSourceAudioTrackSettingsByClip,
- defaultSourceAudioTrackSettings,
- setDefaultSourceAudioTrackSettings,
- currentTime,
- timelineTime: timelinePlayheadTime,
- duration,
- isPlaying,
- previewVolume,
- sourceAudioFallbackRefreshKey,
- summarizeErrorMessage,
- onSourceFallbackLoadError: (error) => {
- toast.warning(
- `Could not load companion audio source: ${summarizeErrorMessage(getErrorMessage(error))}`,
- { duration: 10000 },
- );
- },
- });
-
- const getActivePlayback = useCallback(() => videoPlaybackRef.current, []);
-
- const startPlayback = useCallback(() => {
- const playback = getActivePlayback();
- const video = playback?.video;
- if (!playback || !video) return;
-
- audio.playSourceAudioPreview();
- playback.play().catch((err) => console.error("Video play failed:", err));
- }, [audio.playSourceAudioPreview, getActivePlayback]);
-
- function togglePlayPause() {
- const playback = getActivePlayback();
- const video = playback?.video;
- if (!playback || !video) return;
-
- if (!video.paused && !video.ended) {
- playback.pause();
- } else {
- startPlayback();
- }
- }
-
- const handleAutoSuggestZoomsConsumed = useCallback(() => {
- setAutoSuggestZoomsTrigger(0);
- }, []);
-
- const handleSeek = useCallback(
- (time: number, options: { pause?: boolean } = {}) => {
- const playback = getActivePlayback();
- const video = playback?.video;
- if (!video) return;
-
- if (options.pause && !video.paused) {
- playback?.pause();
- }
-
- video.currentTime = mapTimelineTimeToSourceTime(time * 1000) / 1000;
- },
- [getActivePlayback, mapTimelineTimeToSourceTime],
- );
-
- const handleTimelineSeek = useCallback(
- (time: number) => {
- handleSeek(time, { pause: true });
- },
- [handleSeek],
- );
-
- const handleSelectCaption = useCallback(
- (id: string | null) => {
- setSelectedCaptionId(id);
- if (!id) {
- setActiveEffectSection((section) => (section === "caption" ? "scene" : section));
- return;
- }
- setActiveEffectSection("caption");
- setSelectedZoomId(null);
- setSelectedClipId(null);
- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
- const cue = autoCaptions.find((value) => value.id === id);
- if (cue) {
- handleSeek(mapSourceTimeToTimelineTime(cue.startMs) / 1000, { pause: true });
- }
- },
- [autoCaptions, handleSeek, mapSourceTimeToTimelineTime],
- );
-
- const handleBeginCaptionEdit = useCallback((id: string) => {
- videoPlaybackRef.current?.cancelCaptionEdit();
- setSelectedCaptionId(id);
- }, []);
-
- const handleCaptionTextEdit = useCallback((id: string, text: string) => {
- setAutoCaptions((captions) => {
- const cue = captions.find((value) => value.id === id);
- if (!cue) {
- return captions;
- }
- const words = normalizeCaptionWords(cue);
- if (words.length === 0) {
- // Text-only cue (e.g. a caption added manually from the timeline,
- // which starts empty with no words). updateCaptionCuesForEditedTarget
- // can't seed a cue that has no words, so set the text directly — the
- // renderer derives placeholder word timings from the cue text.
- const normalized = normalizeCaptionEditText(text);
- return captions.map((value) =>
- value.id === id ? { ...value, text: normalized } : value,
- );
- }
- const target: CaptionEditTarget = {
- id: cue.id,
- startMs: cue.startMs,
- endMs: cue.endMs,
- text: cue.text,
- words: words.map((word, index) => ({
- cueId: cue.id,
- cueWordIndex: index,
- startMs: word.startMs,
- endMs: word.endMs,
- text: word.text,
- leadingSpace: Boolean(word.leadingSpace),
- })),
- };
- return updateCaptionCuesForEditedTarget(captions, target, text);
- });
- }, []);
-
- const handleCaptionRetime = useCallback((id: string, span: CaptionRetimeSpan) => {
- videoPlaybackRef.current?.cancelCaptionEdit();
- setAutoCaptions((captions) => retimeCue(captions, id, span));
- }, []);
-
- const handleCaptionSplit = useCallback((id: string, atMs: number) => {
- videoPlaybackRef.current?.cancelCaptionEdit();
- setAutoCaptions((captions) => splitCue(captions, id, atMs));
- }, []);
-
- const handleCaptionMerge = useCallback((idA: string, idB: string) => {
- videoPlaybackRef.current?.cancelCaptionEdit();
- setAutoCaptions((captions) => mergeCues(captions, idA, idB));
- }, []);
-
- const handleCaptionDelete = useCallback((id: string) => {
- videoPlaybackRef.current?.cancelCaptionEdit();
- setSelectedCaptionId((prev) => (prev === id ? null : prev));
- setAutoCaptions((captions) => deleteCue(captions, id));
- }, []);
-
- const handleCaptionAdded = useCallback(
- (span: Span) => {
- videoPlaybackRef.current?.cancelCaptionEdit();
- // span is in timeline-ms; caption cues are stored in source-ms.
- const newCue = createCaptionCue({
- startMs: mapTimelineTimeToSourceTime(span.start),
- endMs: mapTimelineTimeToSourceTime(span.end),
- });
- setAutoCaptions((captions) => addCue(captions, newCue));
- // Select the new caption and open its side-panel editor.
- setSelectedCaptionId(newCue.id);
- setActiveEffectSection("caption");
- setSelectedZoomId(null);
- setSelectedClipId(null);
- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
- handleSeek(span.start / 1000, { pause: true });
- },
- [handleSeek, mapTimelineTimeToSourceTime],
- );
-
- const handlePreviewSkipBack = useCallback(() => {
- const currentMs = timelinePlayheadTime * 1000;
- const keyframes = timelineRef.current?.keyframes ?? [];
- const previous = [...keyframes]
- .reverse()
- .find((keyframe) => keyframe.time < currentMs - 50);
- handleSeek(previous ? previous.time / 1000 : Math.max(0, timelinePlayheadTime - 5));
- }, [handleSeek, timelinePlayheadTime]);
-
- const handlePreviewSkipForward = useCallback(() => {
- const currentMs = timelinePlayheadTime * 1000;
- const keyframes = timelineRef.current?.keyframes ?? [];
- const next = keyframes.find((keyframe) => keyframe.time > currentMs + 50);
- handleSeek(next ? next.time / 1000 : Math.min(timelineDuration, timelinePlayheadTime + 5));
- }, [handleSeek, timelineDuration, timelinePlayheadTime]);
-
- const handleSelectZoom = useCallback((id: string | null) => {
- setSelectedZoomId(id);
- if (id) {
- setActiveEffectSection("zoom");
- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
- setSelectedCaptionId(null);
- } else {
- setActiveEffectSection((s) => (s === "zoom" ? "scene" : s));
- }
- }, []);
-
- const handleSelectAnnotation = useCallback((id: string | null) => {
- setSelectedAnnotationId(id);
- if (id) {
- setSelectedZoomId(null);
- setSelectedAudioId(null);
- setSelectedCaptionId(null);
- }
- }, []);
-
- const handleZoomAdded = useCallback(
- (span: Span) => {
- const id = `zoom-${nextZoomIdRef.current++}`;
- const defaultDepth: ZoomDepth = 2;
- const newRegion: ZoomRegion = {
- id,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- depth: defaultDepth,
- focus: clampFocusToDepth({ cx: 0.5, cy: 0.5 }, defaultDepth),
- mode: "auto",
- };
- if (videoPath && pendingFreshRecordingAutoZoomPathRef.current === videoPath) {
- autoSuggestedVideoPathRef.current = videoPath;
- pendingFreshRecordingAutoZoomPathRef.current = null;
- }
- setZoomRegions((prev) => [...prev, newRegion]);
- setSelectedZoomId(id);
- setSelectedAnnotationId(null);
- setSelectedCaptionId(null);
- },
- [videoPath],
- );
-
- 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_AUTO_ZOOM_DEPTH,
- focus: clampFocusToDepth(focus, DEFAULT_AUTO_ZOOM_DEPTH),
- mode: "auto",
- };
- if (videoPath && pendingFreshRecordingAutoZoomPathRef.current === videoPath) {
- autoSuggestedVideoPathRef.current = videoPath;
- pendingFreshRecordingAutoZoomPathRef.current = null;
- }
- setZoomRegions((prev) => [...prev, newRegion]);
- // Don't auto-select suggested zooms — they follow cursor and don't need user interaction
- },
- [videoPath],
- );
-
- useEffect(() => {
- if (
- videoPath &&
- pendingFreshRecordingAutoZoomPathRef.current === videoPath &&
- isPreviewReady &&
- !shouldAutoApplyFreshRecordingZoomsForSource(
- videoPlaybackRef.current?.video?.videoWidth,
- videoPlaybackRef.current?.video?.videoHeight,
- )
- ) {
- pendingFreshRecordingAutoZoomPathRef.current = null;
- if (pendingFreshRecordingAutoSuggestTimeoutRef.current !== null) {
- window.clearTimeout(pendingFreshRecordingAutoSuggestTimeoutRef.current);
- pendingFreshRecordingAutoSuggestTimeoutRef.current = null;
- }
- return;
- }
-
- if (
- !videoPath ||
- loading ||
- !isPreviewReady ||
- duration <= 0 ||
- zoomRegions.length > 0 ||
- normalizedCursorTelemetry.length < 2
- ) {
- if (pendingFreshRecordingAutoSuggestTimeoutRef.current !== null) {
- window.clearTimeout(pendingFreshRecordingAutoSuggestTimeoutRef.current);
- pendingFreshRecordingAutoSuggestTimeoutRef.current = null;
- }
- return;
- }
-
- if (pendingFreshRecordingAutoZoomPathRef.current !== videoPath) {
- return;
- }
-
- if (autoSuggestedVideoPathRef.current === videoPath) {
- pendingFreshRecordingAutoZoomPathRef.current = null;
- return;
- }
-
- const telemetryPointCount = cursorTelemetry.length;
- if (pendingFreshRecordingAutoSuggestTelemetryCountRef.current === telemetryPointCount) {
- return;
- }
-
- pendingFreshRecordingAutoSuggestTelemetryCountRef.current = telemetryPointCount;
-
- if (pendingFreshRecordingAutoSuggestTimeoutRef.current !== null) {
- window.clearTimeout(pendingFreshRecordingAutoSuggestTimeoutRef.current);
- pendingFreshRecordingAutoSuggestTimeoutRef.current = null;
- }
-
- pendingFreshRecordingAutoSuggestTimeoutRef.current = window.setTimeout(() => {
- pendingFreshRecordingAutoSuggestTimeoutRef.current = null;
- if (
- pendingFreshRecordingAutoZoomPathRef.current !== videoPath ||
- autoSuggestedVideoPathRef.current === videoPath ||
- zoomRegions.length > 0
- ) {
- return;
- }
-
- setAutoSuggestZoomsTrigger((value) => value + 1);
- }, 500);
- }, [
- videoPath,
- loading,
- isPreviewReady,
- duration,
- cursorTelemetry.length,
- normalizedCursorTelemetry,
- zoomRegions,
- ]);
-
- useEffect(() => {
- if (
- !videoPath ||
- !isPreviewReady ||
- zoomRegions.length === 0 ||
- autoSuggestedVideoPathRef.current !== videoPath ||
- shouldAutoApplyFreshRecordingZoomsForSource(
- videoPlaybackRef.current?.video?.videoWidth,
- videoPlaybackRef.current?.video?.videoHeight,
- )
- ) {
- return;
- }
-
- autoSuggestedVideoPathRef.current = null;
- setZoomRegions((prev) => {
- const next = prev.filter((region) => region.mode !== "auto");
- return next.length === prev.length ? prev : next;
- });
- }, [videoPath, isPreviewReady, zoomRegions]);
-
- 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 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 handleZoomModeChange = useCallback(
- (mode: ZoomMode) => {
- if (!selectedZoomId) return;
- setZoomRegions((prev) =>
- prev.map((region) => (region.id === selectedZoomId ? { ...region, mode } : region)),
- );
- },
- [selectedZoomId],
- );
-
- const handleZoomDelete = useCallback(
- (id: string) => {
- setZoomRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedZoomId === id) {
- setSelectedZoomId(null);
- }
- },
- [selectedZoomId],
- );
-
- const handleSelectClip = useCallback((id: string | null) => {
- setSelectedClipId(id);
- if (id) {
- setActiveEffectSection("clip");
- setSelectedZoomId(null);
- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
- setSelectedCaptionId(null);
- } else {
- setActiveEffectSection((s) => (s === "clip" ? "scene" : s));
- }
- }, []);
-
- const handleClipSplit = useCallback(
- (splitMs: number) => {
- setClipRegions((prev) => {
- const target = prev.find((c) => splitMs > c.startMs && splitMs < c.endMs);
- if (!target) return prev;
- const leftId = `clip-${nextClipIdRef.current++}`;
- const rightId = `clip-${nextClipIdRef.current++}`;
- const left: ClipRegion = {
- id: leftId,
- startMs: target.startMs,
- endMs: Math.round(splitMs),
- speed: target.speed,
- muted: target.muted,
- };
- const right: ClipRegion = {
- id: rightId,
- startMs: Math.round(splitMs),
- endMs: target.endMs,
- speed: target.speed,
- muted: target.muted,
- };
- if (selectedClipId === target.id) {
- setSelectedClipId(leftId);
- }
- return prev.flatMap((c) => (c.id === target.id ? [left, right] : [c]));
- });
- },
- [selectedClipId],
- );
-
- const handleClipSpanChange = useCallback(
- (id: string, span: Span) => {
- const oldClip = clipRegions.find((c) => c.id === id);
- const newStart = Math.round(span.start);
- const newEnd = Math.round(span.end);
- const removedSegments = oldClip
- ? [
- ...(newStart > oldClip.startMs
- ? [{ startMs: oldClip.startMs, endMs: newStart }]
- : []),
- ...(newEnd < oldClip.endMs
- ? [{ startMs: newEnd, endMs: oldClip.endMs }]
- : []),
- ]
- : [];
-
- if (oldClip) {
- const startDelta = newStart - oldClip.startMs;
- const endDelta = newEnd - oldClip.endMs;
- const isMove = Math.abs(startDelta - endDelta) < 1 && Math.abs(startDelta) > 0;
-
- if (isMove) {
- const delta = startDelta;
- setZoomRegions((prev) =>
- prev.map((zoom) => {
- const overlaps =
- zoom.startMs < oldClip.endMs && zoom.endMs > oldClip.startMs;
- if (overlaps) {
- return {
- ...zoom,
- startMs: zoom.startMs + delta,
- endMs: zoom.endMs + delta,
- };
- }
- return zoom;
- }),
- );
- }
- }
-
- if (removedSegments.length > 0) {
- const removeTrimmedRegions = <T extends { startMs: number; endMs: number }>(
- regions: T[],
- ): T[] =>
- regions.filter(
- (region) =>
- !removedSegments.some(
- (segment) =>
- region.startMs < segment.endMs &&
- region.endMs > segment.startMs,
- ),
- );
- setZoomRegions((prev) => removeTrimmedRegions(prev));
- setAnnotationRegions((prev) => removeTrimmedRegions(prev));
- setSpeedRegions((prev) => removeTrimmedRegions(prev));
- setAudioRegions((prev) => removeTrimmedRegions(prev));
- }
-
- setClipRegions((prev) =>
- prev.map((clip) =>
- clip.id === id ? { ...clip, startMs: newStart, endMs: newEnd } : clip,
- ),
- );
- },
- [clipRegions],
- );
-
- const handleClipSpeedChange = useCallback(
- (speed: number) => {
- if (!selectedClipId) return;
- if (!Number.isFinite(speed) || speed <= 0) {
- return;
- }
- const plan = planClipSpeedChange({
- clipRegions,
- zoomRegions,
- selectedClipId,
- speed,
- });
- if (!plan) return;
-
- if ("blockedReason" in plan) {
- toast.warning(
- plan.blockedReason === "clip-overlap"
- ? t(
- "editor.timeline.speedClipOverlap",
- "Speed change would overlap the next clip. Move or split clips before slowing this section.",
- )
- : t(
- "editor.timeline.speedZoomOverlap",
- "Speed change would overlap another zoom. Move or delete the overlapping zoom first.",
- ),
- );
- return;
- }
-
- setClipRegions(plan.clipRegions);
- setZoomRegions(plan.zoomRegions);
- },
- [selectedClipId, clipRegions, zoomRegions, t],
- );
-
- const handleClipMutedChange = useCallback(
- (muted: boolean) => {
- if (!selectedClipId) return;
- setClipRegions((prev) =>
- prev.map((clip) => (clip.id === selectedClipId ? { ...clip, muted } : clip)),
- );
- },
- [selectedClipId],
- );
-
- const handleClipShowSourceAudioChange = useCallback(
- (showSourceAudio: boolean) => {
- if (!selectedClipId) return;
- setClipRegions((prev) =>
- prev.map((clip) =>
- clip.id === selectedClipId ? { ...clip, showSourceAudio } : clip,
- ),
- );
- },
- [selectedClipId],
- );
-
- const handleClipDelete = useCallback(
- (id: string) => {
- const deletedClip = clipRegions.find((clip) => clip.id === id);
- setClipRegions((prev) => prev.filter((clip) => clip.id !== id));
- if (deletedClip) {
- const { startMs, endMs } = deletedClip;
- setZoomRegions((prev) =>
- prev.filter((region) => region.endMs <= startMs || region.startMs >= endMs),
- );
- setAnnotationRegions((prev) =>
- prev.filter((region) => region.endMs <= startMs || region.startMs >= endMs),
- );
- setSpeedRegions((prev) =>
- prev.filter((region) => region.endMs <= startMs || region.startMs >= endMs),
- );
- setAudioRegions((prev) =>
- prev.filter((region) => region.endMs <= startMs || region.startMs >= endMs),
- );
- }
- if (selectedClipId === id) {
- setSelectedClipId(null);
- }
- },
- [clipRegions, selectedClipId],
- );
-
- const handleSelectAudio = useCallback((id: string | null) => {
- setSelectedAudioId(id);
- if (id) {
- setSelectedZoomId(null);
- setSelectedAnnotationId(null);
- setSelectedCaptionId(null);
- setActiveEffectSection("audio");
- }
- }, []);
-
- const handleAudioAdded = useCallback((span: Span, audioPath: string, trackIndex?: number) => {
- const id = `audio-${nextAudioIdRef.current++}`;
- const newRegion: AudioRegion = {
- id,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- audioPath,
- volume: 1,
- normalize: false,
- trackIndex,
- };
- setAudioRegions((prev) => [...prev, newRegion]);
- setSelectedAudioId(id);
- setSelectedZoomId(null);
- setSelectedAnnotationId(null);
- setSelectedCaptionId(null);
- setActiveEffectSection("audio");
- }, []);
-
- const handleAudioSpanChange = useCallback((id: string, span: Span, trackIndex?: number) => {
- const normalizedTrackIndex =
- typeof trackIndex === "number" && Number.isFinite(trackIndex)
- ? Math.max(0, Math.floor(trackIndex))
- : undefined;
-
- setAudioRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? {
- ...region,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- ...(normalizedTrackIndex === undefined
- ? {}
- : { trackIndex: normalizedTrackIndex }),
- }
- : region,
- ),
- );
- }, []);
-
- const handleAudioVolumeChange = useCallback(
- (volume: number) => {
- if (!selectedAudioId) {
- return;
- }
-
- if (!Number.isFinite(volume)) {
- return;
- }
-
- const nextVolume = Math.max(0, Math.min(1, volume));
- setAudioRegions((prev) =>
- prev.map((region) =>
- region.id === selectedAudioId ? { ...region, volume: nextVolume } : region,
- ),
- );
- },
- [selectedAudioId],
- );
-
- const handleAudioDelete = useCallback(
- (id: string) => {
- setAudioRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedAudioId === id) {
- setSelectedAudioId(null);
- }
- },
- [selectedAudioId],
- );
-
- const handleAudioNormalizeChange = useCallback(
- (normalize: boolean) => {
- if (!selectedAudioId) {
- return;
- }
- setAudioRegions((prev) =>
- prev.map((region) =>
- region.id === selectedAudioId ? { ...region, normalize } : region,
- ),
- );
- },
- [selectedAudioId],
- );
-
- const handleAnnotationAdded = useCallback((span: Span, trackIndex = 0) => {
- 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,
- trackIndex,
- };
- setAnnotationRegions((prev) => [...prev, newRegion]);
- setSelectedAnnotationId(id);
- setSelectedZoomId(null);
- }, []);
-
- const handleAnnotationSpanChange = useCallback(
- (id: string, span: Span, trackIndex?: number) => {
- const normalizedTrackIndex =
- typeof trackIndex === "number" && Number.isFinite(trackIndex)
- ? Math.max(0, Math.floor(trackIndex))
- : undefined;
-
- setAnnotationRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? {
- ...region,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- ...(normalizedTrackIndex === undefined
- ? {}
- : { trackIndex: normalizedTrackIndex }),
- }
- : 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 };
- }
- } else if (type === "blur") {
- updatedRegion.content = "";
- if (region.blurIntensity === undefined) {
- updatedRegion.blurIntensity = 20;
- }
- }
-
- 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 handleAnnotationBlurIntensityChange = useCallback((id: string, blurIntensity: number) => {
- setAnnotationRegions((prev) =>
- prev.map((region) => (region.id === id ? { ...region, blurIntensity } : region)),
- );
- }, []);
-
- const handleAnnotationBlurColorChange = useCallback((id: string, blurColor: string) => {
- setAnnotationRegions((prev) =>
- prev.map((region) => (region.id === id ? { ...region, blurColor } : 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) => {
- const target = e.target as HTMLElement | null;
- const isEditableTarget =
- target instanceof HTMLInputElement ||
- target instanceof HTMLTextAreaElement ||
- target?.isContentEditable;
-
- const usesPrimaryModifier = isMac ? e.metaKey : e.ctrlKey;
- const key = e.key.toLowerCase();
-
- if (usesPrimaryModifier && !e.altKey && key === "z") {
- if (!isEditableTarget) {
- e.preventDefault();
- if (e.shiftKey) {
- handleRedo();
- } else {
- handleUndo();
- }
- }
- return;
- }
-
- if (!isMac && e.ctrlKey && !e.metaKey && !e.altKey && key === "y") {
- if (!isEditableTarget) {
- e.preventDefault();
- handleRedo();
- }
- return;
- }
-
- if (e.key === "Tab") {
- // Allow tab only in inputs/textareas
- if (isEditableTarget) {
- return;
- }
- e.preventDefault();
- }
-
- if (matchesShortcut(e, shortcuts.playPause, isMac)) {
- // Allow space only in inputs/textareas
- if (isEditableTarget) {
- return;
- }
- e.preventDefault();
-
- const playback = videoPlaybackRef.current;
- if (playback?.video) {
- if (playback.video.paused) {
- startPlayback();
- } else {
- playback.pause();
- }
- }
- }
- };
-
- window.addEventListener("keydown", handleKeyDown, { capture: true });
- return () => window.removeEventListener("keydown", handleKeyDown, { capture: true });
- }, [shortcuts, isMac, handleUndo, handleRedo, startPlayback]);
-
- useEffect(() => {
- if (selectedZoomId && !zoomRegions.some((region) => region.id === selectedZoomId)) {
- setSelectedZoomId(null);
- }
- }, [selectedZoomId, zoomRegions]);
-
- useEffect(() => {
- if (
- selectedAnnotationId &&
- !annotationRegions.some((region) => region.id === selectedAnnotationId)
- ) {
- setSelectedAnnotationId(null);
- }
- }, [selectedAnnotationId, annotationRegions]);
-
- useEffect(() => {
- if (selectedAudioId && !audioRegions.some((region) => region.id === selectedAudioId)) {
- setSelectedAudioId(null);
- }
- }, [selectedAudioId, audioRegions]);
-
- useEffect(() => {
- if (selectedCaptionId && !autoCaptions.some((cue) => cue.id === selectedCaptionId)) {
- setSelectedCaptionId(null);
- }
- }, [selectedCaptionId, autoCaptions]);
-
- const showExportSuccessToast = useCallback((filePath: string) => {
- toast.success(`Exported successfully to ${filePath}`, {
- action: {
- label: "Show in Folder",
- onClick: async () => {
- try {
- const result = await window.electronAPI.revealInFolder(filePath);
- if (!result.success) {
- const errorMessage =
- result.error ||
- result.message ||
- "Failed to reveal item in folder.";
- toast.error(errorMessage);
- }
- } catch (err) {
- toast.error(`Error revealing in folder: ${String(err)}`);
- }
- },
- },
- });
- }, []);
-
- 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);
- clearPendingExportSave();
- const smokeExportStartedAt = smokeExportConfig.enabled ? performance.now() : null;
-
- let keepExportDialogOpen = false;
-
- try {
- const wasPlaying = isPlaying;
- const restoreTime = video.currentTime;
- if (wasPlaying) {
- videoPlaybackRef.current?.pause();
- }
-
- // 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;
- const effectiveShadowIntensity =
- smokeExportConfig.enabled && smokeExportConfig.shadowIntensity !== undefined
- ? smokeExportConfig.shadowIntensity
- : shadowIntensity;
- const smokeProgressSampler = createSmokeExportProgressSampler({
- enabled: smokeExportConfig.enabled,
- startedAtMs: smokeExportStartedAt,
- });
- const smokeProgressSamples = smokeProgressSampler.samples;
- const recordSmokeProgress = smokeProgressSampler.record;
-
- 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,
- trimRegions,
- speedRegions: effectiveSpeedRegions,
- showShadow: effectiveShadowIntensity > 0,
- shadowIntensity: effectiveShadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- borderRadius,
- padding,
- videoPadding: padding,
- cropRegion,
- webcam,
- webcamUrl:
- resolvedWebcamVideoUrl ??
- (webcam.sourcePath ? toFileUrl(webcam.sourcePath) : null),
- annotationRegions,
- autoCaptions,
- autoCaptionSettings,
- zoomRegions: effectiveZoomRegions,
- cursorTelemetry: effectiveCursorTelemetry,
- showCursor: effectiveShowCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- zoomSmoothness,
- zoomClassicMode,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- previewWidth,
- previewHeight,
- maxDecodeQueue: smokeExportConfig.maxDecodeQueue,
- maxPendingFrames: smokeExportConfig.maxPendingFrames,
- onProgress: (progress: ExportProgress) => {
- recordSmokeProgress(progress);
- setExportProgress(progress);
- },
- });
-
- exporterRef.current = gifExporter as unknown as VideoExporter;
- const result = await gifExporter.export();
-
- if (result.success && result.blob) {
- const timestamp = Date.now();
- const fileName = `export-${timestamp}.gif`;
- markExportAsSaving();
-
- const { saveResult, pendingSave } = await saveBlobExport(
- result.blob,
- fileName,
- smokeExportConfig.enabled ? smokeExportConfig.outputPath : null,
- );
-
- if (saveResult.canceled) {
- pendingExportSaveRef.current = pendingSave;
- setHasPendingExportSave(true);
- setExportError(
- "Save dialog canceled. Click Save Again to save without re-rendering.",
- );
- toast.info("Save canceled. You can save again without re-exporting.");
- keepExportDialogOpen = true;
- } else if (saveResult.success && saveResult.path) {
- if (smokeExportStartedAt !== null) {
- console.log(
- `[smoke-export] Completed in ${Math.round(performance.now() - smokeExportStartedAt)}ms (${saveResult.path})`,
- );
- }
- showExportSuccessToast(saveResult.path);
- setExportedFilePath(saveResult.path);
- if (smokeExportConfig.enabled) {
- window.close();
- return;
- }
- } else {
- setExportError(saveResult.message || "Failed to save GIF");
- toast.error(saveResult.message || "Failed to save GIF");
- if (smokeExportConfig.enabled) {
- window.close();
- return;
- }
- }
- } else {
- setExportError(result.error || "GIF export failed");
- toast.error(result.error || "GIF export failed");
- if (smokeExportConfig.enabled) {
- window.close();
- return;
- }
- }
- } else {
- // MP4 Export
- const { quality, encodingMode, selectedMp4FrameRate } =
- resolveMp4ExportSettings({
- smokeExportConfig: {
- enabled: smokeExportConfig.enabled,
- quality: smokeExportConfig.quality,
- encodingMode: smokeExportConfig.encodingMode,
- fps: smokeExportConfig.fps,
- },
- settings,
- exportQuality,
- exportEncodingMode,
- mp4FrameRate,
- });
- const {
- pipelineModel,
- useExperimentalNativeExport,
- useExperimentalNvidiaCudaExport,
- backendPreference,
- } = resolveMp4ExportRouting({
- smokeExportConfig: {
- enabled: smokeExportConfig.enabled,
- pipelineModel: smokeExportConfig.pipelineModel,
- useNativeExport: smokeExportConfig.useNativeExport,
- backendPreference: smokeExportConfig.backendPreference,
- },
- settings,
- exportPipelineModel,
- exportBackendPreference,
- experimentalNvidiaCudaExport,
- nvidiaCudaExportAvailable,
- });
- const supportedSourceDimensions =
- await ensureSupportedMp4SourceDimensions(selectedMp4FrameRate);
- const { width: exportWidth, height: exportHeight } =
- calculateMp4ExportDimensions(
- supportedSourceDimensions.width,
- supportedSourceDimensions.height,
- quality,
- );
- const bitrate = getMp4ExportBitrate({
- width: exportWidth,
- height: exportHeight,
- frameRate: selectedMp4FrameRate,
- quality,
- encodingMode,
- useModernNativeStaticLayout: useExperimentalNativeExport,
- });
- const sourceAudioTrackSettingsForExport =
- selectedClipId !== null
- ? audio.selectedClipSourceAudioTrackSettings
- : audio.activeSourceAudioTrackSettings;
-
- const exporterConfig = {
- videoUrl: videoPath,
- width: exportWidth,
- height: exportHeight,
- frameRate: selectedMp4FrameRate,
- bitrate,
- codec: DEFAULT_MP4_CODEC,
- encodingMode,
- preferredEncoderPath: supportedSourceDimensions.encoderPath,
- preferredRenderBackend: smokeExportConfig.renderBackend,
- experimentalNativeExport: useExperimentalNativeExport,
- experimentalNvidiaCudaExport: useExperimentalNvidiaCudaExport,
- maxEncodeQueue: smokeExportConfig.maxEncodeQueue,
- maxDecodeQueue: smokeExportConfig.maxDecodeQueue,
- maxPendingFrames: smokeExportConfig.maxPendingFrames,
- wallpaper,
- trimRegions,
- speedRegions: effectiveSpeedRegions,
- showShadow: effectiveShadowIntensity > 0,
- shadowIntensity: effectiveShadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- borderRadius,
- padding,
- cropRegion,
- webcam,
- webcamUrl:
- resolvedWebcamVideoUrl ??
- (webcam.sourcePath ? toFileUrl(webcam.sourcePath) : null),
- annotationRegions,
- autoCaptions,
- autoCaptionSettings,
- zoomRegions: effectiveZoomRegions,
- cursorTelemetry: effectiveCursorTelemetry,
- showCursor: effectiveShowCursor,
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- zoomSmoothness,
- zoomClassicMode,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- audioRegions,
- clipRegions,
- sourceAudioFallbackPaths: audio.sourceAudioFallbackPaths,
- sourceAudioFallbackStartDelayMsByPath:
- audio.sourceAudioFallbackStartDelayMsByPath,
- sourceAudioTrackSettings: sourceAudioTrackSettingsForExport,
- previewWidth,
- previewHeight,
- onProgress: (progress: ExportProgress) => {
- recordSmokeProgress(progress);
- setExportProgress(progress);
- },
- };
-
- const exporter =
- pipelineModel === "modern"
- ? new ModernVideoExporter({
- ...exporterConfig,
- backendPreference,
- })
- : new VideoExporter(exporterConfig);
-
- exporterRef.current = exporter;
- const result = await exporter.export();
- const smokeExportElapsedMs =
- smokeExportStartedAt !== null
- ? Math.round(performance.now() - smokeExportStartedAt)
- : undefined;
-
- if (result.success && (result.blob || result.tempFilePath)) {
- const timestamp = Date.now();
- const fileName = `export-${timestamp}.mp4`;
- const sidecarForThisExport =
- settings.includeCaptionSidecar && captionSidecarPayload
- ? captionSidecarPayload
- : undefined;
- markExportAsSaving();
-
- let saveResult: {
- success: boolean;
- path?: string;
- message?: string;
- canceled?: boolean;
- };
- let pendingOnCancel: PendingExportSave;
-
- if (result.tempFilePath) {
- // Preferred path: main process already holds the finished MP4 on
- // disk, so we just ask it to move the temp file into place. This
- // avoids ever allocating a multi-GiB ArrayBuffer in the renderer.
- saveResult = await window.electronAPI.finalizeExportedVideo({
- tempPath: result.tempFilePath,
- fileName,
- outputPath:
- smokeExportConfig.enabled && smokeExportConfig.outputPath
- ? smokeExportConfig.outputPath
- : null,
- captionSidecar: sidecarForThisExport,
- });
- pendingOnCancel = {
- fileName,
- tempFilePath: result.tempFilePath,
- captionSidecar: sidecarForThisExport,
- };
- } else if (result.blob) {
- // Legacy fallback: some export paths still surface a Blob, but in
- // Electron we stream it into a temp file first so save/finalize
- // never requires a giant renderer ArrayBuffer.
- const blobSave = await saveBlobExport(
- result.blob,
- fileName,
- smokeExportConfig.enabled ? smokeExportConfig.outputPath : null,
- sidecarForThisExport,
- );
- saveResult = blobSave.saveResult;
- pendingOnCancel = blobSave.pendingSave;
- } else {
- saveResult = { success: false, message: "Export produced no output" };
- pendingOnCancel = { fileName };
- }
-
- if (saveResult.canceled) {
- if (smokeExportConfig.enabled) {
- await writeSmokeExportReport(smokeExportConfig.outputPath, {
- success: false,
- phase: "save",
- format: "mp4",
- pipelineModel,
- backendPreference,
- encodingMode,
- shadowIntensity: effectiveShadowIntensity,
- elapsedMs: smokeExportElapsedMs,
- error: "Save canceled",
- progressSamples: smokeProgressSamples,
- metrics: result.metrics,
- });
- }
- pendingExportSaveRef.current = pendingOnCancel;
- setHasPendingExportSave(true);
- setExportError(
- "Save dialog canceled. Click Save Again to save without re-rendering.",
- );
- toast.info("Save canceled. You can save again without re-exporting.");
- keepExportDialogOpen = true;
- } else if (saveResult.success && saveResult.path) {
- if (smokeExportConfig.enabled) {
- await writeSmokeExportReport(smokeExportConfig.outputPath, {
- success: true,
- phase: "saved",
- format: "mp4",
- pipelineModel,
- backendPreference,
- encodingMode,
- shadowIntensity: effectiveShadowIntensity,
- elapsedMs: smokeExportElapsedMs,
- outputPath: saveResult.path,
- progressSamples: smokeProgressSamples,
- metrics: result.metrics,
- });
- }
- if (smokeExportStartedAt !== null) {
- console.log(
- `[smoke-export] Completed in ${Math.round(performance.now() - smokeExportStartedAt)}ms (${saveResult.path})`,
- );
- }
- showExportSuccessToast(saveResult.path);
- setExportedFilePath(saveResult.path);
- if (smokeExportConfig.enabled) {
- window.close();
- return;
- }
- } else {
- if (smokeExportConfig.enabled) {
- await writeSmokeExportReport(smokeExportConfig.outputPath, {
- success: false,
- phase: "save",
- format: "mp4",
- pipelineModel,
- backendPreference,
- encodingMode,
- shadowIntensity: effectiveShadowIntensity,
- elapsedMs: smokeExportElapsedMs,
- error: saveResult.message || "Failed to save video",
- progressSamples: smokeProgressSamples,
- metrics: result.metrics,
- });
- }
- setExportError(saveResult.message || "Failed to save video");
- showExportErrorToast(saveResult.message || "Failed to save video");
- // Keep the pending-save entry so the user can retry without
- // re-rendering. The temp file is still on disk (the main
- // process only moves/deletes it on success) and the
- // ArrayBuffer fallback still references its in-memory blob.
- if (pendingOnCancel.tempFilePath || pendingOnCancel.arrayBuffer) {
- pendingExportSaveRef.current = pendingOnCancel;
- setHasPendingExportSave(true);
- keepExportDialogOpen = true;
- }
- if (smokeExportConfig.enabled) {
- window.close();
- return;
- }
- }
- } else {
- if (smokeExportConfig.enabled) {
- await writeSmokeExportReport(smokeExportConfig.outputPath, {
- success: false,
- phase: "export",
- format: "mp4",
- pipelineModel,
- backendPreference,
- encodingMode,
- shadowIntensity: effectiveShadowIntensity,
- elapsedMs: smokeExportElapsedMs,
- error: result.error || "Export failed",
- progressSamples: smokeProgressSamples,
- metrics: result.metrics,
- });
- }
- setExportError(result.error || "Export failed");
- showExportErrorToast(result.error || "Export failed");
- keepExportDialogOpen = true;
- if (smokeExportConfig.enabled) {
- window.close();
- return;
- }
- }
- }
-
- if (wasPlaying) {
- videoPlaybackRef.current?.play();
- } else {
- video.currentTime = restoreTime;
- }
- } catch (error) {
- console.error("Export error:", error);
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
- if (smokeExportConfig.enabled) {
- await writeSmokeExportReport(smokeExportConfig.outputPath, {
- success: false,
- phase: "exception",
- format: settings.format,
- elapsedMs:
- smokeExportStartedAt !== null
- ? Math.round(performance.now() - smokeExportStartedAt)
- : undefined,
- error: errorMessage,
- });
- }
- setExportError(errorMessage);
- showExportErrorToast(`Export failed: ${errorMessage}`);
- keepExportDialogOpen = true;
- if (smokeExportConfig.enabled) {
- window.close();
- }
- } finally {
- setIsExporting(false);
- exporterRef.current = null;
- setShowExportDropdown(keepExportDialogOpen);
- remountPreview();
- }
- },
- [
- clearPendingExportSave,
- videoPath,
- wallpaper,
- trimRegions,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- zoomMotionBlurTuning,
- zoomTemporalMotionBlur,
- zoomMotionBlurSampleCount,
- zoomMotionBlurShutterFraction,
- connectZooms,
- zoomInDurationMs,
- zoomInOverlapMs,
- zoomOutDurationMs,
- connectedZoomGapMs,
- connectedZoomDurationMs,
- zoomInEasing,
- zoomOutEasing,
- connectedZoomEasing,
- effectiveShowCursor,
- cursorStyle,
- effectiveCursorTelemetry,
- cursorSize,
- cursorSmoothing,
- cursorSpringStiffnessMultiplier,
- cursorSpringDampingMultiplier,
- cursorSpringMassMultiplier,
- cameraSpringStiffnessMultiplier,
- cameraSpringDampingMultiplier,
- cameraSpringMassMultiplier,
- zoomSmoothness,
- zoomClassicMode,
- cursorMotionBlur,
- cursorClickEffect,
- cursorClickEffectColor,
- cursorClickEffectScale,
- cursorClickEffectOpacity,
- cursorClickEffectDurationMs,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- audioRegions,
- clipRegions,
- audio.sourceAudioFallbackPaths,
- audio.sourceAudioFallbackStartDelayMsByPath,
- audio.activeSourceAudioTrackSettings,
- audio.selectedClipSourceAudioTrackSettings,
- exportEncodingMode,
- exportBackendPreference,
- exportPipelineModel,
- experimentalNvidiaCudaExport,
- nvidiaCudaExportAvailable,
- borderRadius,
- padding,
- cropRegion,
- webcam,
- resolvedWebcamVideoUrl,
- annotationRegions,
- autoCaptions,
- autoCaptionSettings,
- captionSidecarPayload,
- isPlaying,
- exportQuality,
- effectiveZoomRegions,
- ensureSupportedMp4SourceDimensions,
- markExportAsSaving,
- mp4FrameRate,
- remountPreview,
- showExportSuccessToast,
- smokeExportConfig.backendPreference,
- smokeExportConfig.renderBackend,
- smokeExportConfig.enabled,
- smokeExportConfig.useNativeExport,
- smokeExportConfig.maxDecodeQueue,
- smokeExportConfig.maxEncodeQueue,
- smokeExportConfig.maxPendingFrames,
- smokeExportConfig.outputPath,
- smokeExportConfig.pipelineModel,
- smokeExportConfig.shadowIntensity,
- effectiveSpeedRegions,
- selectedClipId,
- smokeExportConfig.encodingMode,
- smokeExportConfig.fps,
- smokeExportConfig.quality,
- saveBlobExport,
- ],
- );
-
- useEffect(() => {
- smokeExportReadyStateRef.current = {
- cursorTelemetrySourcePath,
- duration,
- hasVideoPath: Boolean(videoPath),
- isPreviewReady,
- loading,
- projectPath: smokeExportConfig.projectPath ?? null,
- videoSourcePath,
- };
- }, [
- cursorTelemetrySourcePath,
+ const projectController = useEditorProjectController({
+ t,
+ project,
+ appearance,
+ timeline,
+ exportSettings,
+ initialPreferences: initialEditorPreferences,
+ smokeConfig: smokeExportConfig,
+ devConfig: devOpenRecordingConfig,
+ aspectRatio,
+ setAspectRatio,
+ videoPath,
+ setVideoPath,
+ videoSourcePath,
+ setVideoSourcePath,
+ currentTime,
+ setCurrentTime,
+ setIsPlaying,
+ setDuration,
+ whisperExecutablePath,
+ setWhisperExecutablePath,
+ whisperModelPath,
+ setWhisperModelPath,
+ downloadedWhisperModelPath,
+ setDownloadedWhisperModelPath,
+ whisperModelDownloadStatus,
+ setWhisperModelDownloadStatus,
+ setWhisperModelDownloadProgress,
+ isGeneratingCaptions,
+ setIsGeneratingCaptions,
+ videoPlaybackRef,
+ projectNameInputRef,
+ projectSaveDialogInputRef,
+ nextZoomIdRef,
+ nextClipIdRef,
+ nextAudioIdRef,
+ nextAnnotationIdRef,
+ nextAnnotationZIndexRef,
+ clipInitializedRef,
+ autoFullTrackClipIdRef,
+ autoFullTrackClipEndMsRef,
+ pendingFreshRecordingAutoZoomPathRef,
+ pendingFreshRecordingAutoSuggestTelemetryCountRef,
+ autoSuggestedVideoPathRef,
+ applySessionPresentation,
+ refreshProjectLibrary,
+ captureProjectThumbnail,
+ remountPreview,
+ });
+ const {
+ snapshot: { currentSourcePath },
+ history: { handleUndo, handleRedo },
+ lifecycle: { handleUploadWebcam, handleClearWebcam },
+ autoCaption: autoCaptionController,
+ } = projectController;
+
+ const editing = useTimelineEditingController({
+ t,
+ shortcuts,
+ isMac,
+ timeline,
+ appearance,
+ videoPath,
+ videoSourcePath,
+ currentSourcePath,
duration,
- isPreviewReady,
+ currentTime,
+ isPlaying,
+ previewVolume,
loading,
- smokeExportConfig.projectPath,
+ isPreviewReady,
+ setActiveEffectSection,
+ setAutoSuggestZoomsTrigger,
+ videoPlaybackRef,
+ timelineRef,
+ nextZoomIdRef,
+ nextClipIdRef,
+ nextAudioIdRef,
+ nextAnnotationIdRef,
+ nextAnnotationZIndexRef,
+ clipInitializedRef,
+ autoFullTrackClipIdRef,
+ autoFullTrackClipEndMsRef,
+ autoSuggestedVideoPathRef,
+ pendingFreshRecordingAutoZoomPathRef,
+ pendingFreshRecordingAutoSuggestTimeoutRef,
+ pendingFreshRecordingAutoSuggestTelemetryCountRef,
+ handleUndo,
+ handleRedo,
+ });
+ const {
+ cursor: { effectiveCursorTelemetry },
+ projection,
+ audio,
+ captionCommands,
+ zoomCommands,
+ clipCommands,
+ audioCommands,
+ annotationCommands,
+ } = editing;
+ const { effectiveSpeedRegions, effectiveZoomRegions } = projection;
+
+ const exportController = useEditorExportController({
+ t,
videoPath,
videoSourcePath,
- ]);
-
- useEffect(() => {
- if (!smokeExportConfig.enabled) {
- return;
- }
-
- const timeoutId = window.setTimeout(() => {
- if (smokeExportStartedRef.current) {
- return;
- }
-
- smokeExportStartedRef.current = true;
- void writeSmokeExportReport(smokeExportConfig.outputPath, {
- success: false,
- phase: "ready",
- error: `Smoke export did not become ready within ${SMOKE_EXPORT_READY_TIMEOUT_MS}ms.`,
- readyState: smokeExportReadyStateRef.current,
- }).finally(() => window.close());
- }, SMOKE_EXPORT_READY_TIMEOUT_MS);
-
- return () => window.clearTimeout(timeoutId);
- }, [smokeExportConfig.enabled, smokeExportConfig.outputPath]);
-
- useEffect(() => {
- if (!smokeExportConfig.enabled || smokeExportStartedRef.current) {
- return;
- }
-
- if (error) {
- smokeExportStartedRef.current = true;
- console.error(`[smoke-export] ${error}`);
- void writeSmokeExportReport(smokeExportConfig.outputPath, {
- success: false,
- phase: "load",
- error,
- readyState: smokeExportReadyStateRef.current,
- }).finally(() => window.close());
- return;
- }
-
- if (!videoPath || loading || !isPreviewReady || duration <= 0) {
- return;
- }
-
- // When smoke-export opens a .recordly project, the cursor telemetry
- // sidecar is loaded asynchronously after the editor state applies.
- // Without this gate the auto-export fires before telemetry arrives and
- // produces a video with no cursor/zoom animations.
- if (
- smokeExportConfig.projectPath &&
- videoSourcePath &&
- cursorTelemetrySourcePath !== videoSourcePath
- ) {
- return;
- }
-
- smokeExportStartedRef.current = true;
- void handleExport({
- format: "mp4",
- quality: "good",
- encodingMode: smokeExportConfig.encodingMode ?? "balanced",
- });
- }, [
- cursorTelemetrySourcePath,
+ videoPlaybackRef,
+ isPlaying,
+ duration,
error,
- handleExport,
- isPreviewReady,
loading,
- duration,
- smokeExportConfig.enabled,
- smokeExportConfig.encodingMode,
- smokeExportConfig.outputPath,
- smokeExportConfig.projectPath,
- videoPath,
- videoSourcePath,
- ]);
-
- const handleOpenExportDropdown = useCallback(() => {
- if (!videoPath) {
- toast.error("No video loaded");
- return;
- }
-
- if (hasPendingExportSave) {
- setShowExportDropdown(true);
- setExportError("Save dialog canceled. Click Save Again to save without re-rendering.");
- return;
- }
- setShowExportDropdown(true);
- setExportProgress(null);
- setExportError(null);
- }, [videoPath, hasPendingExportSave]);
-
- const handleStartExportFromDropdown = useCallback(() => {
- const video = videoPlaybackRef.current?.video;
- if (!videoPath) {
- toast.error("No video loaded");
- return;
- }
- if (!video) {
- toast.error("Video not ready");
- return;
- }
-
- const sourceWidth = video.videoWidth || 1920;
- const sourceHeight = video.videoHeight || 1080;
- const settings = resolveExportStartSettings({
- sourceWidth,
- sourceHeight,
- exportFormat,
- includeCaptionSidecar: hasCaptionsForSidecar && includeCaptionSidecar,
- exportEncodingMode,
- exportQuality,
- mp4FrameRate,
- exportBackendPreference,
- exportPipelineModel,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- });
-
- setExportError(null);
- setExportedFilePath(undefined);
- setShowExportDropdown(true);
- handleExport(settings);
- }, [
- videoPath,
- exportFormat,
- exportEncodingMode,
- exportQuality,
- mp4FrameRate,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
+ isPreviewReady,
+ appearance,
+ timeline,
+ settings: exportSettings,
+ session: exportSession,
+ dimensions: exportDimensions,
+ audio,
+ smokeConfig: smokeExportConfig,
+ effectiveSpeedRegions,
+ effectiveZoomRegions,
+ effectiveCursorTelemetry,
+ effectiveShowCursor,
+ cursorTelemetrySourcePath,
hasCaptionsForSidecar,
- includeCaptionSidecar,
- exportBackendPreference,
- exportPipelineModel,
- handleExport,
- ]);
-
- const handleCancelExport = useCallback(() => {
- if (exporterRef.current) {
- exporterRef.current.cancel();
- toast.info("Export canceled");
- clearPendingExportSave();
- setShowExportDropdown(false);
- setIsExporting(false);
- setExportProgress(null);
- setExportError(null);
- setExportedFilePath(undefined);
- }
- }, [clearPendingExportSave]);
-
- const handleExportDropdownClose = useCallback(() => {
- clearPendingExportSave();
- setShowExportDropdown(false);
- setExportProgress(null);
- setExportError(null);
- setExportedFilePath(undefined);
- }, [clearPendingExportSave]);
-
- const handleRetrySaveExport = useCallback(async () => {
- const pendingSave = pendingExportSaveRef.current;
- if (!pendingSave) {
- return;
- }
-
- let saveResult: {
- success: boolean;
- path?: string;
- message?: string;
- canceled?: boolean;
- };
-
- if (pendingSave.tempFilePath) {
- saveResult = await window.electronAPI.finalizeExportedVideo({
- tempPath: pendingSave.tempFilePath,
- fileName: pendingSave.fileName,
- outputPath: null,
- captionSidecar: pendingSave.captionSidecar,
- });
- } else if (pendingSave.arrayBuffer) {
- saveResult = await window.electronAPI.saveExportedVideo(
- pendingSave.arrayBuffer,
- pendingSave.fileName,
- pendingSave.captionSidecar,
- );
- } else {
- saveResult = { success: false, message: "No pending export to save" };
- }
-
- if (saveResult.canceled) {
- setExportError("Save dialog canceled. Click Save Again to save without re-rendering.");
- toast.info("Save canceled. You can try again.");
- return;
- }
-
- if (saveResult.success && saveResult.path) {
- // finalizeExportedVideo already moved the temp file into place, so the
- // pending-save entry no longer refers to a file on disk. Flip the flag
- // directly to avoid clearPendingExportSave issuing a spurious discard.
- pendingExportSaveRef.current = null;
- setHasPendingExportSave(false);
- setExportError(null);
- setExportedFilePath(saveResult.path);
- showExportSuccessToast(saveResult.path);
- setShowExportDropdown(true);
- return;
- }
-
- const errorMessage = saveResult.message || "Failed to save video";
- setExportError(errorMessage);
- toast.error(errorMessage);
- }, [showExportSuccessToast]);
-
- const handleOpenCropEditor = useCallback(() => {
- cropSnapshotRef.current = { ...cropRegion };
- setShowCropModal(true);
- }, [cropRegion]);
-
- const handleCloseCropEditor = useCallback(() => {
- setShowCropModal(false);
- }, []);
-
- const handleCancelCropEditor = useCallback(() => {
- if (cropSnapshotRef.current) {
- setCropRegion(cropSnapshotRef.current);
- }
- setShowCropModal(false);
- }, []);
-
- const isCropped = useMemo(() => {
- const top = Math.round(cropRegion.y * 100);
- const left = Math.round(cropRegion.x * 100);
- const bottom = Math.round((1 - cropRegion.y - cropRegion.height) * 100);
- const right = Math.round((1 - cropRegion.x - cropRegion.width) * 100);
- return top > 0 || left > 0 || bottom > 0 || right > 0;
- }, [cropRegion]);
-
- const revealExportedFile = useCallback(async () => {
- if (!exportedFilePath) return;
-
- try {
- const result = await window.electronAPI.revealInFolder(exportedFilePath);
- if (!result.success) {
- toast.error(result.error || result.message || "Failed to reveal item in folder.");
- }
- } catch (error) {
- toast.error(`Failed to reveal item in folder: ${String(error)}`);
- }
- }, [exportedFilePath]);
-
- const openLightningIssues = useCallback(async () => {
- await openExternalLink(
- RECORDLY_ISSUES_URL,
- t("editor.feedback.openFailed", "Failed to open link."),
- );
- }, [t]);
-
- const {
- isExportSaving,
- isExportPreparing,
- isExportFinalizing,
- isRenderingAudio,
- exportFinalizingProgress,
- exportFinalizingPercent,
- isExportFinalSaveIndeterminate,
- isLightningExportInProgress,
- shouldSuspendPreviewRendering,
- isLegacyExportInProgress,
- renderSpeedFps,
- runtimeLabel: exportRuntimeLabel,
- nativeSkipLabel: exportNativeSkipLabel,
- } = resolveExportStatusModel({
- isExporting,
- exportProgress,
- exportFormat,
- exportPipelineModel,
+ captionSidecarPayload,
+ experimentalNvidiaCudaExport,
+ nvidiaCudaExportAvailable,
+ remountPreview,
});
- const exportRenderSpeedLabel = renderSpeedFps
- ? t("editor.exportStatus.renderSpeed", "Render speed {{fps}} FPS", {
- fps: renderSpeedFps,
- })
- : null;
- const exportPercentLabel = exportProgress
- ? isExportPreparing
- ? t("editor.exportStatus.preparing", "Preparing export...")
- : isExportSaving
- ? t("editor.exportStatus.saving", "Opening save dialog...")
- : isRenderingAudio
- ? t("editor.exportStatus.renderingAudio", "Rendering audio {{percent}}%", {
- percent: Math.round((exportProgress.audioProgress ?? 0) * 100),
- })
- : isExportFinalizing
- ? exportFormat === "mp4" && exportPipelineModel === "modern"
- ? isExportFinalSaveIndeterminate
- ? t(
- "editor.exportStatus.muxingAndSaving",
- "Muxing audio and saving file...",
- )
- : t(
- "editor.exportStatus.muxingAndSavingPercent",
- "Muxing and saving {{percent}}%",
- {
- percent: exportFinalizingPercent ?? 100,
- },
- )
- : t(
- "editor.exportStatus.finalizingPercent",
- "Finalizing {{percent}}%",
- {
- percent: exportFinalizingPercent ?? 100,
- },
- )
- : t("editor.exportStatus.completePercent", "{{percent}}% complete", {
- percent: Math.round(exportProgress.percentage),
- })
- : t("editor.exportStatus.preparing", "Preparing export...");
const previewAspectRatioValue = getAspectRatioValue(
aspectRatio,
(() => {
@@ -5490,1399 +332,55 @@ export default function VideoEditor() {
return 16 / 9;
})(),
);
- const renderPreviewPlayback = (
- playbackRef: typeof videoPlaybackRef | undefined,
- suspendRendering: boolean,
- keySuffix: "inline" | "fullscreen",
- ) => (
- <VideoPlayback
- key={`${videoPath || "no-video"}:${previewVersion}:${keySuffix}`}
- aspectRatio={aspectRatio}
- ref={playbackRef}
- videoPath={videoPath || ""}
- onDurationChange={setDuration}
- onPreviewReadyChange={setIsPreviewReady}
- onTimeUpdate={setCurrentTime}
- currentTime={currentTime}
- onPlayStateChange={setIsPlaying}
- onError={setError}
- wallpaper={wallpaper}
- zoomRegions={effectiveZoomRegions}
- selectedZoomId={selectedZoomId}
- onSelectZoom={handleSelectZoom}
- onZoomFocusChange={handleZoomFocusChange}
- isPlaying={isPlaying}
- showShadow={shadowIntensity > 0}
- shadowIntensity={shadowIntensity}
- backgroundBlur={backgroundBlur}
- connectZooms={connectZooms}
- zoomInDurationMs={zoomInDurationMs}
- zoomInOverlapMs={zoomInOverlapMs}
- zoomOutDurationMs={zoomOutDurationMs}
- connectedZoomGapMs={connectedZoomGapMs}
- connectedZoomDurationMs={connectedZoomDurationMs}
- zoomInEasing={zoomInEasing}
- zoomOutEasing={zoomOutEasing}
- connectedZoomEasing={connectedZoomEasing}
- borderRadius={0}
- padding={padding}
- cropRegion={cropRegion}
- webcam={webcam}
- webcamVideoPath={webcam.sourcePath ? resolvedWebcamVideoUrl : null}
- trimRegions={trimRegions}
- speedRegions={effectiveSpeedRegions}
- annotationRegions={annotationRegions}
- autoCaptions={autoCaptions}
- autoCaptionSettings={autoCaptionSettings}
- onEditAutoCaption={handleSaveAutoCaptionEdit}
- selectedAnnotationId={selectedAnnotationId}
- onSelectAnnotation={handleSelectAnnotation}
- onAnnotationPositionChange={handleAnnotationPositionChange}
- onAnnotationSizeChange={handleAnnotationSizeChange}
- cursorTelemetry={effectiveCursorTelemetry}
- showCursor={effectiveShowCursor}
- cursorStyle={cursorStyle}
- cursorSize={cursorSize}
- cursorSmoothing={cursorSmoothing}
- cursorSpringStiffnessMultiplier={cursorSpringStiffnessMultiplier}
- cursorSpringDampingMultiplier={cursorSpringDampingMultiplier}
- cursorSpringMassMultiplier={cursorSpringMassMultiplier}
- cameraSpringStiffnessMultiplier={cameraSpringStiffnessMultiplier}
- cameraSpringDampingMultiplier={cameraSpringDampingMultiplier}
- cameraSpringMassMultiplier={cameraSpringMassMultiplier}
- zoomSmoothness={zoomSmoothness}
- zoomClassicMode={zoomClassicMode}
- zoomMotionBlur={zoomMotionBlur}
- zoomMotionBlurTuning={zoomMotionBlurTuning}
- cursorMotionBlur={cursorMotionBlur}
- cursorClickEffect={cursorClickEffect}
- cursorClickEffectColor={cursorClickEffectColor}
- cursorClickEffectScale={cursorClickEffectScale}
- cursorClickEffectOpacity={cursorClickEffectOpacity}
- cursorClickEffectDurationMs={cursorClickEffectDurationMs}
- cursorClickBounce={cursorClickBounce}
- cursorClickBounceDuration={cursorClickBounceDuration}
- cursorSway={cursorSway}
- volume={
- audio.shouldMutePreviewVideo || audio.isCurrentClipMuted
- ? 0
- : Math.max(0, Math.min(1, previewVolume * audio.embeddedSourcePreviewGain))
- }
- suspendRendering={suspendRendering}
- />
- );
-
- const projectSaveDialog = (
- <Dialog
- open={projectSaveDialogOpen}
- onOpenChange={(open) => {
- if (open) {
- setProjectSaveDialogOpen(true);
- return;
- }
-
- if (!isSavingProjectDialog) {
- resolveProjectSaveDialog(false);
- }
- }}
- >
- <DialogContent className="max-w-sm border-foreground/10 bg-editor-dialog text-foreground">
- <form onSubmit={(event) => void handleProjectSaveDialogSubmit(event)}>
- <DialogHeader>
- <DialogTitle>{t("editor.project.saveTitle", "Save Project")}</DialogTitle>
- <DialogDescription className="text-muted-foreground">
- {t(
- "editor.project.saveDescription",
- "Name this project. It will be saved in your Recordly Projects folder.",
- )}
- </DialogDescription>
- </DialogHeader>
- <div className="py-4">
- <label className="mb-2 block text-xs font-medium text-muted-foreground">
- {t("editor.project.saveNameLabel", "Project name")}
- </label>
- <div className="flex items-center overflow-hidden rounded-md border border-foreground/10 bg-editor-panel">
- <Input
- ref={projectSaveDialogInputRef}
- value={projectSaveDialogDraft}
- onChange={(event) => setProjectSaveDialogDraft(event.target.value)}
- disabled={isSavingProjectDialog}
- className="h-10 flex-1 border-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0"
- aria-label={t("editor.project.saveNameLabel", "Project name")}
- />
- <span className="shrink-0 px-3 text-xs font-medium text-muted-foreground/70">
- .recordly
- </span>
- </div>
- </div>
- <DialogFooter>
- <Button
- type="button"
- variant="ghost"
- onClick={() => resolveProjectSaveDialog(false)}
- disabled={isSavingProjectDialog}
- >
- {t("common.actions.cancel", "Cancel")}
- </Button>
- <Button type="submit" disabled={isSavingProjectDialog}>
- {isSavingProjectDialog
- ? t("editor.project.saving", "Saving...")
- : t("common.actions.save", "Save")}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- );
-
- const unsavedChangesDialog = (
- <Dialog
- open={unsavedChangesDialogOpen}
- onOpenChange={(open) => {
- if (open) {
- setUnsavedChangesDialogOpen(true);
- return;
- }
-
- resolveUnsavedChangesDialog("cancel");
- }}
- >
- <DialogContent className="max-w-sm border-foreground/10 bg-editor-dialog text-foreground">
- <DialogHeader>
- <DialogTitle>Unsaved changes</DialogTitle>
- <DialogDescription className="text-muted-foreground">
- {`Save your current project before you ${unsavedChangesDialogActionLabel}?`}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button
- type="button"
- variant="ghost"
- onClick={() => resolveUnsavedChangesDialog("cancel")}
- >
- {t("common.actions.cancel", "Cancel")}
- </Button>
- <Button
- type="button"
- variant="ghost"
- onClick={() => resolveUnsavedChangesDialog("discard")}
- >
- Discard changes
- </Button>
- <Button type="button" onClick={() => resolveUnsavedChangesDialog("save")}>
- Save project
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-
- const projectBrowser = (
- <ProjectBrowserDialog
- open={projectBrowserOpen}
- onOpenChange={setProjectBrowserOpen}
- entries={projectLibraryEntries}
- anchorRef={error ? projectBrowserFallbackTriggerRef : projectBrowserTriggerRef}
- onImportFile={() => {
- void handleImportMediaOrProject();
- }}
- onOpenProject={(projectPath) => {
- void handleOpenProjectFromLibrary(projectPath);
- }}
- />
- );
- const nativeCaptureUnavailableDialog = (
- <Dialog
- open={nativeCaptureUnavailableModalOpen}
- onOpenChange={setNativeCaptureUnavailableModalOpen}
- >
- <DialogContent className="max-w-md bg-editor-dialog border-foreground/10 text-foreground">
- <DialogHeader>
- <DialogTitle>
- {t(
- "editor.nativeCaptureUnavailable.title",
- "Nothing’s broken, but we won’t be able to render an animated cursor overlay.",
- )}
- </DialogTitle>
- <DialogDescription className="text-muted-foreground">
- {t(
- "editor.nativeCaptureUnavailable.description",
- "Your device does not support native capture. This could be for a variety of reasons we haven’t figured out yet. This doesn’t break Recordly, but it does make cursor smoothing impossible.",
- )}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button onClick={() => setNativeCaptureUnavailableModalOpen(false)}>
- {t("editor.nativeCaptureUnavailable.confirm", "Okay")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-
- if (loading) {
- return (
- <div className="flex h-screen items-center justify-center bg-background">
- <div className="text-foreground">Loading video...</div>
- {projectBrowser}
- {projectSaveDialog}
- {unsavedChangesDialog}
- {nativeCaptureUnavailableDialog}
- <Toaster className="pointer-events-auto" />
- </div>
- );
- }
- if (error) {
- return (
- <div className="flex h-screen items-center justify-center bg-background">
- <div className="flex flex-col items-center gap-3">
- <div className="text-destructive">{error}</div>
- <button
- ref={projectBrowserFallbackTriggerRef}
- type="button"
- onClick={handleOpenProjectBrowser}
- className="rounded-[5px] bg-neutral-800 px-3 py-1.5 text-sm font-semibold text-white shadow-[0_14px_32px_rgba(0,0,0,0.18)] transition-colors hover:bg-neutral-700 dark:bg-white dark:text-black dark:hover:bg-white/90"
- >
- Open Projects
- </button>
- </div>
- {projectBrowser}
- {projectSaveDialog}
- {unsavedChangesDialog}
- {nativeCaptureUnavailableDialog}
- <Toaster className="pointer-events-auto" />
- </div>
- );
- }
-
+ const settingsPanelProps = useEditorSettingsPanelProps({
+ activeEffectSection,
+ appearance,
+ timeline,
+ audio,
+ zoomCommands,
+ clipCommands,
+ audioCommands,
+ captionCommands,
+ annotationCommands,
+ autoCaptionController,
+ effectiveShowCursor,
+ handleShowCursorChange,
+ currentTime,
+ isPlaying,
+ aspectRatio,
+ setAspectRatio,
+ whisperExecutablePath,
+ whisperModelPath,
+ whisperModelDownloadStatus,
+ whisperModelDownloadProgress,
+ isGeneratingCaptions,
+ sessionNativeCaptureUnavailable,
+ setNativeCaptureUnavailableModalOpen,
+ handleUploadWebcam,
+ handleClearWebcam,
+ });
return (
- <div className="flex flex-col h-screen bg-editor-bg text-foreground overflow-hidden selection:bg-[#2563EB]/30">
- <div
- className="relative flex h-11 flex-shrink-0 items-center justify-between bg-editor-header/88 px-5 backdrop-blur-md border-b border-foreground/10 z-50"
- style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
- >
- <div
- className={`flex items-center gap-1.5 justify-self-start ${headerLeftControlsPaddingClass}`}
- style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
- >
- <Button
- ref={projectBrowserTriggerRef}
- type="button"
- variant="ghost"
- size="sm"
- onClick={handleOpenProjectBrowser}
- className={APP_HEADER_ICON_BUTTON_CLASS}
- title={t("editor.project.projects", "Open projects")}
- aria-label={t("editor.project.projects", "Open projects")}
- >
- <FolderOpen className="h-4 w-4" />
- </Button>
- <DiscordLinkButton />
- <FeedbackDialog />
- <div className="ml-1 h-5 w-px bg-foreground/10" />
- <Button
- type="button"
- variant="ghost"
- onClick={handleUndo}
- disabled={!canUndo}
- className="inline-flex h-8 w-8 items-center justify-center rounded-[5px] border border-foreground/10 bg-foreground/5 p-0 text-foreground transition-colors hover:bg-foreground/10 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"
- title={t("common.actions.undo", "Undo")}
- aria-label={t("common.actions.undo", "Undo")}
- >
- <Undo2 className="h-4 w-4" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- onClick={handleRedo}
- disabled={!canRedo}
- className="inline-flex h-8 w-8 items-center justify-center rounded-[5px] border border-foreground/10 bg-foreground/5 p-0 text-foreground transition-colors hover:bg-foreground/10 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"
- title={t("common.actions.redo", "Redo")}
- aria-label={t("common.actions.redo", "Redo")}
- >
- <Redo2 className="h-4 w-4" />
- </Button>
- </div>
- <div
- className="absolute left-1/2 flex min-w-0 -translate-x-1/2 items-center justify-center"
- style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
- >
- {isEditingProjectName ? (
- <form
- onSubmit={(event) => void handleProjectNameSubmit(event)}
- className="flex max-w-[min(52vw,460px)] items-baseline gap-1 rounded-[7px] border border-foreground/10 bg-editor-panel/[0.88] px-2.5 py-1 shadow-[0_10px_28px_rgba(0,0,0,0.18)]"
- >
- {hasUnsavedChanges ? (
- <span className="mt-[1px] size-2 shrink-0 rounded-full bg-[#2563EB]" />
- ) : null}
- <input
- ref={projectNameInputRef}
- type="text"
- value={projectNameDraft}
- onChange={(event) => setProjectNameDraft(event.target.value)}
- onBlur={() => {
- if (!isSavingProjectName) {
- closeProjectNameEditor();
- }
- }}
- onKeyDown={(event) => {
- if (event.key === "Escape") {
- event.preventDefault();
- closeProjectNameEditor();
- }
- }}
- disabled={isSavingProjectName}
- className="min-w-[10ch] max-w-[min(40vw,360px)] bg-transparent text-sm font-semibold tracking-tight text-foreground/95 outline-none placeholder:text-muted-foreground/60 disabled:cursor-wait"
- style={{ width: `${Math.max(projectNameDraft.length, 10)}ch` }}
- aria-label={t("editor.project.renameInput", "Project name")}
- />
- <span className="shrink-0 text-xs font-medium tracking-tight text-muted-foreground/70">
- .recordly
- </span>
- </form>
- ) : (
- <button
- type="button"
- onClick={() => setIsEditingProjectName(true)}
- className="inline-flex max-w-[min(52vw,460px)] items-baseline gap-1 rounded-[7px] px-2.5 py-1 transition-colors hover:bg-foreground/5"
- title={t("editor.project.renameTitle", "Rename project")}
- aria-label={t("editor.project.renameTitle", "Rename project")}
- >
- {hasUnsavedChanges ? (
- <span className="mt-[1px] size-2 shrink-0 rounded-full bg-[#2563EB]" />
- ) : null}
- <span className="truncate text-sm font-semibold tracking-tight text-foreground/90">
- {projectDisplayName}
- </span>
- <span className="shrink-0 text-xs font-medium tracking-tight text-muted-foreground/70">
- .recordly
- </span>
- </button>
- )}
- </div>
- <div
- className="flex items-center justify-self-end"
- style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
- >
- <Popover open={presetPopoverOpen} onOpenChange={setPresetPopoverOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- title={t("editor.presets.open", "Open presets")}
- aria-label={t("editor.presets.open", "Open presets")}
- className="inline-flex items-center gap-1.5 bg-transparent p-0 text-sm font-medium tracking-tight text-foreground outline-none transition-opacity hover:opacity-80"
- >
- <span className="flex items-center gap-1.5">
- <BookmarkSimple weight="fill" className="h-4 w-4" />
- <span>
- {currentEditorPreset?.name ??
- t("editor.presets.label", "Presets")}
- </span>
- </span>
- <ChevronDown className="h-3.5 w-3.5 text-foreground" />
- </button>
- </PopoverTrigger>
- <PopoverContent
- align="end"
- sideOffset={10}
- className="w-[300px] rounded-2xl border border-foreground/10 bg-editor-surface-alt p-3 shadow-xl"
- >
- <div className="space-y-3">
- <form
- onSubmit={(event) => {
- event.preventDefault();
- handleSavePresetSubmit();
- }}
- className="space-y-2"
- >
- <p className="text-[11px] font-medium text-foreground">
- {t(
- "editor.presets.saveCurrentAs",
- "Save current preset as",
- )}
- </p>
- <div className="flex items-center gap-2">
- <Input
- value={presetNameDraft}
- onChange={(event) =>
- setPresetNameDraft(event.target.value)
- }
- className="h-9 rounded-xl border-foreground/10 bg-background/70 text-sm"
- placeholder={t(
- "editor.presets.namePlaceholder",
- "Preset name",
- )}
- aria-label={t(
- "editor.presets.namePlaceholder",
- "Preset name",
- )}
- />
- <Button
- type="submit"
- size="sm"
- className="h-9 rounded-xl bg-[#2563EB] px-3 text-white hover:bg-[#1d4ed8]"
- >
- {t("common.actions.save", "Save")}
- </Button>
- </div>
- </form>
-
- <div className="space-y-2">
- <p className="text-[11px] font-medium text-foreground">
- {t("editor.presets.savedList", "Saved presets")}
- </p>
- <div className="max-h-56 space-y-1 overflow-y-auto pr-1 custom-scrollbar">
- {editorPresets.length === 0 ? (
- <div className="rounded-xl border border-dashed border-foreground/10 px-3 py-4 text-center text-[11px] text-muted-foreground">
- {t("editor.presets.empty", "No presets yet.")}
- </div>
- ) : (
- editorPresets.map((preset) => {
- const isActive =
- preset.id === currentEditorPreset?.id;
- return (
- <div
- key={preset.id}
- className={cn(
- "flex items-center gap-2 rounded-xl border px-2 py-2 text-sm transition-colors",
- isActive
- ? "border-[#2563EB]/20 bg-[#2563EB]/10 text-foreground"
- : "border-foreground/8 bg-foreground/[0.03] text-muted-foreground hover:bg-foreground/[0.06] hover:text-foreground",
- )}
- >
- <button
- type="button"
- onClick={() =>
- handleApplyEditorPreset(preset.id)
- }
- className="flex min-w-0 flex-1 items-center justify-between text-left"
- >
- <span className="truncate pr-3">
- {preset.name}
- </span>
- {isActive ? (
- <Check className="h-3.5 w-3.5 shrink-0 text-[#2563EB]" />
- ) : null}
- </button>
- <button
- type="button"
- onClick={() =>
- handleDeleteEditorPreset(preset.id)
- }
- className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/8 hover:text-foreground"
- aria-label={t(
- "editor.presets.deleteAriaLabel",
- "Delete preset {{name}}",
- { name: preset.name },
- )}
- title={t(
- "editor.presets.deleteAriaLabel",
- "Delete preset {{name}}",
- { name: preset.name },
- )}
- >
- <X className="h-3.5 w-3.5" />
- </button>
- </div>
- );
- })
- )}
- </div>
- </div>
- </div>
- </PopoverContent>
- </Popover>
- <div
- aria-hidden="true"
- className="mx-2 h-4 w-px shrink-0 bg-foreground/10 opacity-0"
- />
- <DropdownMenu
- open={showExportDropdown}
- onOpenChange={setShowExportDropdown}
- modal={false}
- >
- <DropdownMenuTrigger asChild>
- <Button
- type="button"
- onClick={handleOpenExportDropdown}
- className="inline-flex h-8 min-w-[112px] items-center justify-center gap-2 rounded-[5px] bg-[#2563EB] px-4.5 text-white transition-colors hover:bg-[#2563EB]/92"
- >
- <Download className="h-4 w-4" />
- <span className="text-sm font-semibold tracking-tight">
- {t("common.actions.export", "Export")}
- </span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- sideOffset={10}
- className="w-[360px] border-none bg-transparent p-0 shadow-none"
- >
- {isExporting ? (
- <div className="rounded-2xl border border-foreground/10 bg-editor-surface p-4 text-foreground shadow-2xl">
- <div className="mb-3 flex items-center justify-between gap-3">
- <div>
- <p className="text-sm font-semibold text-foreground">
- {t("editor.exportStatus.exporting", "Exporting")}
- </p>
- <p className="text-xs text-muted-foreground">
- {t(
- "editor.exportStatus.renderingFile",
- "Rendering your file.",
- )}
- </p>
- {isLightningExportInProgress ? (
- <p className="mt-1 flex items-center gap-1 text-[11px] text-muted-foreground/70">
- PLEASE
- <button
- type="button"
- onClick={() => void openLightningIssues()}
- className="underline decoration-slate-500/70 underline-offset-2 transition-colors hover:text-foreground"
- >
- report bugs
- </button>
- with Lightning export
- <span aria-hidden="true">{"\u{1F64F}"}</span>
- </p>
- ) : null}
- {isLegacyExportInProgress ? (
- <p className="mt-1 text-[11px] text-muted-foreground/70">
- Export too slow? Cancel and try Lightning
- export!
- </p>
- ) : null}
- </div>
- <Button
- type="button"
- variant="outline"
- onClick={handleCancelExport}
- className="h-8 border-red-500/20 bg-red-500/10 px-3 text-xs text-red-400 hover:bg-red-500/20"
- >
- {t("common.actions.cancel")}
- </Button>
- </div>
- <div className="h-2 overflow-hidden rounded-full border border-foreground/5 bg-foreground/5">
- {isExportPreparing ||
- isExportSaving ||
- isExportFinalSaveIndeterminate ? (
- <div className="indeterminate-progress h-full rounded-full bg-transparent" />
- ) : (
- <div
- className="h-full bg-[#2563EB] transition-all duration-300 ease-out"
- style={{
- width: `${Math.min(isRenderingAudio ? (exportProgress?.audioProgress ?? 0) * 100 : (exportFinalizingProgress ?? exportProgress?.percentage ?? 8), 100)}%`,
- }}
- />
- )}
- </div>
- <p className="mt-2 text-xs text-muted-foreground">
- {exportPercentLabel}
- </p>
- {isRenderingAudio ? (
- <p className="mt-1 text-[11px] text-muted-foreground/70">
- {t(
- "editor.export.processingAudioEdits",
- "Processing audio with speed/overlay edits",
- )}
- </p>
- ) : exportRenderSpeedLabel ? (
- <p className="mt-1 text-[11px] text-muted-foreground/70">
- {exportRenderSpeedLabel}
- </p>
- ) : null}
- {exportRuntimeLabel ? (
- <p className="mt-1 text-[11px] text-muted-foreground/70">
- Path: {exportRuntimeLabel}
- </p>
- ) : null}
- {exportNativeSkipLabel ? (
- <p className="mt-1 text-[11px] text-amber-500/80">
- {exportNativeSkipLabel}
- </p>
- ) : null}
- </div>
- ) : exportError ? (
- <div className="rounded-2xl border border-foreground/10 bg-editor-surface p-4 text-foreground shadow-2xl">
- <p className="text-sm font-semibold text-foreground">
- {t("editor.exportStatus.issue", "Export issue")}
- </p>
- {exportRuntimeLabel ? (
- <p className="mt-1 text-[11px] text-muted-foreground/70">
- Path: {exportRuntimeLabel}
- </p>
- ) : null}
- <p className="mt-1 whitespace-pre-line text-xs leading-relaxed text-muted-foreground">
- {exportError}
- </p>
- <div className="mt-4 flex gap-2">
- {hasPendingExportSave ? (
- <Button
- type="button"
- onClick={handleRetrySaveExport}
- className="h-8 flex-1 rounded-[5px] bg-[#2563EB] text-xs font-semibold text-white hover:bg-[#2563EB]/92"
- >
- {t("editor.actions.saveAgain", "Save Again")}
- </Button>
- ) : null}
- <Button
- type="button"
- variant="outline"
- onClick={handleExportDropdownClose}
- className="h-8 flex-1 border-foreground/10 bg-foreground/5 text-xs text-muted-foreground hover:bg-foreground/10"
- >
- {t("common.actions.close", "Close")}
- </Button>
- </div>
- </div>
- ) : exportedFilePath ? (
- <div className="rounded-2xl border border-foreground/10 bg-editor-surface p-4 text-foreground shadow-2xl">
- <p className="text-sm font-semibold text-foreground">
- {t("editor.exportStatus.complete", "Export complete")}
- </p>
- <p className="mt-1 text-xs text-muted-foreground">
- {t(
- "editor.exportStatus.savedSuccessfully",
- "Your file was saved successfully.",
- )}
- </p>
- {exportRuntimeLabel ? (
- <p className="mt-1 text-[11px] text-muted-foreground/70">
- Path: {exportRuntimeLabel}
- </p>
- ) : null}
- <p className="mt-3 truncate text-xs text-muted-foreground/70">
- {exportedFilePath.split("/").pop()}
- </p>
- <div className="mt-4 flex gap-2">
- <Button
- type="button"
- onClick={revealExportedFile}
- className="h-8 flex-1 rounded-[5px] bg-[#2563EB] text-xs font-semibold text-white hover:bg-[#2563EB]/92"
- >
- {t("editor.actions.showInFolder", "Show In Folder")}
- </Button>
- <Button
- type="button"
- variant="outline"
- onClick={handleExportDropdownClose}
- className="h-8 flex-1 border-foreground/10 bg-foreground/5 text-xs text-muted-foreground hover:bg-foreground/10"
- >
- Done
- </Button>
- </div>
- </div>
- ) : (
- <ExportSettingsMenu
- exportFormat={exportFormat}
- onExportFormatChange={setExportFormat}
- exportEncodingMode={exportEncodingMode}
- onExportEncodingModeChange={setExportEncodingMode}
- mp4FrameRate={mp4FrameRate}
- onMp4FrameRateChange={setMp4FrameRate}
- exportPipelineModel={exportPipelineModel}
- onExportPipelineModelChange={setExportPipelineModel}
- experimentalNvidiaCudaExport={
- experimentalNvidiaCudaExport && nvidiaCudaExportAvailable
- }
- onExperimentalNvidiaCudaExportChange={
- setExperimentalNvidiaCudaExport
- }
- nvidiaCudaExportAvailable={nvidiaCudaExportAvailable}
- exportQuality={exportQuality}
- onExportQualityChange={setExportQuality}
- gifFrameRate={gifFrameRate}
- onGifFrameRateChange={setGifFrameRate}
- gifLoop={gifLoop}
- onGifLoopChange={setGifLoop}
- gifSizePreset={gifSizePreset}
- onGifSizePresetChange={setGifSizePreset}
- showCaptionSidecarOption={
- hasCaptionsForSidecar && exportFormat === "mp4"
- }
- includeCaptionSidecar={includeCaptionSidecar}
- onIncludeCaptionSidecarChange={setIncludeCaptionSidecar}
- mp4OutputDimensions={mp4OutputDimensions}
- gifOutputDimensions={gifOutputDimensions}
- onExport={handleStartExportFromDropdown}
- className="shadow-2xl"
- />
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- <EditorAnnouncementBanner />
-
- <div className="relative flex min-h-0 flex-1 flex-col gap-3 p-4">
- <div className="flex min-h-0 flex-1 gap-3 relative z-10">
- {/* Settings sidebar */}
- <div className="flex flex-shrink-0 gap-1.5">
- {/* Icon rail */}
- <div className="flex flex-shrink-0 flex-col items-center gap-0.5 px-2 py-2">
- {editorSectionButtons.map((section) => {
- const isActive = activeEffectSection === section.id;
- return (
- <div key={section.id} className="flex items-center">
- <motion.button
- type="button"
- onClick={() => setActiveEffectSection(section.id)}
- title={section.label}
- className="group relative flex h-9 w-9 items-center justify-center rounded-lg outline-none focus:outline-none focus-visible:outline-none"
- animate={{ opacity: isActive ? 1 : 0.55 }}
- transition={{ duration: 0.14 }}
- >
- {isActive && (
- <motion.span
- layoutId="rail-active-bg"
- className="absolute inset-0 rounded-lg bg-foreground/[0.08]"
- transition={{
- type: "spring",
- stiffness: 450,
- damping: 35,
- }}
- />
- )}
- <motion.span
- className="relative z-10"
- animate={{
- color: isActive
- ? "#2563EB"
- : "hsl(var(--foreground))",
- }}
- transition={{ duration: 0.14 }}
- >
- <section.icon
- className="h-[27px] w-[27px]"
- weight={isActive ? "fill" : "regular"}
- />
- </motion.span>
- </motion.button>
- <div className="ml-1.5 h-1.5 w-1.5 flex-shrink-0">
- {isActive && (
- <motion.span
- layoutId="rail-active-dot"
- className="block h-1.5 w-1.5 rounded-full bg-[#2563EB]"
- initial={{ opacity: 0, scale: 0.5 }}
- animate={{ opacity: 1, scale: 1 }}
- exit={{ opacity: 0, scale: 0.5 }}
- transition={{
- type: "spring",
- stiffness: 500,
- damping: 32,
- }}
- />
- )}
- </div>
- </div>
- );
- })}
- <div className="mt-auto flex flex-col items-center gap-0.5 pt-3">
- <motion.button
- type="button"
- onClick={() => toast.info("Account coming soon")}
- title="Account"
- className="group relative flex h-9 w-9 items-center justify-center rounded-lg text-foreground/55 outline-none transition hover:text-foreground focus:outline-none focus-visible:outline-none"
- whileHover={{ opacity: 1 }}
- initial={{ opacity: 0.55 }}
- >
- <motion.span className="absolute inset-0 rounded-lg bg-foreground/[0.04] opacity-0 transition group-hover:opacity-100" />
- <User className="relative z-10 h-[22px] w-[22px]" />
- </motion.button>
- </div>
- </div>
- {/* Panel */}
- {activeEffectSection === "extensions" ? (
- <ExtensionManager />
- ) : (
- <SettingsPanel
- panelMode="editor"
- activeEffectSection={activeEffectSection}
- selected={wallpaper}
- onWallpaperChange={setWallpaper}
- selectedZoomDepth={
- selectedZoomId
- ? zoomRegions.find((z) => z.id === selectedZoomId)?.depth
- : null
- }
- onZoomDepthChange={(depth) =>
- selectedZoomId && handleZoomDepthChange(depth)
- }
- selectedZoomId={selectedZoomId}
- selectedZoomMode={
- selectedZoomId
- ? (zoomRegions.find((z) => z.id === selectedZoomId)?.mode ??
- "auto")
- : null
- }
- onZoomModeChange={(mode) =>
- selectedZoomId && handleZoomModeChange(mode)
- }
- onZoomDelete={handleZoomDelete}
- selectedClipId={selectedClipId}
- selectedClipSpeed={
- selectedClipId
- ? (clipRegions.find((c) => c.id === selectedClipId)
- ?.speed ?? 1)
- : null
- }
- selectedClipMuted={
- selectedClipId
- ? (clipRegions.find((c) => c.id === selectedClipId)
- ?.muted ?? false)
- : null
- }
- selectedClipShowSourceAudio={
- selectedClipId
- ? (clipRegions.find((c) => c.id === selectedClipId)
- ?.showSourceAudio ?? false)
- : null
- }
- onClipSpeedChange={handleClipSpeedChange}
- onClipMutedChange={handleClipMutedChange}
- onClipShowSourceAudioChange={handleClipShowSourceAudioChange}
- onClipDelete={handleClipDelete}
- hasClipSourceAudio={hasClipSourceAudio}
- sourceAudioTrackMeta={audio.sourceAudioTrackMeta}
- sourceAudioTrackSettings={
- audio.selectedClipSourceAudioTrackSettings
- }
- onSourceAudioTrackVolumeChange={
- audio.onSelectedClipSourceAudioTrackVolumeChange
- }
- onSourceAudioTrackNormalizeChange={
- audio.onSelectedClipSourceAudioTrackNormalizeChange
- }
- selectedAudioId={selectedAudioId}
- selectedAudioVolume={
- selectedAudioId
- ? (audioRegions.find((r) => r.id === selectedAudioId)
- ?.volume ?? null)
- : null
- }
- selectedAudioNormalize={
- selectedAudioId
- ? (audioRegions.find((r) => r.id === selectedAudioId)
- ?.normalize ?? false)
- : null
- }
- onAudioVolumeChange={handleAudioVolumeChange}
- onAudioNormalizeChange={handleAudioNormalizeChange}
- onAudioDelete={handleAudioDelete}
- shadowIntensity={shadowIntensity}
- onShadowChange={setShadowIntensity}
- backgroundBlur={backgroundBlur}
- onBackgroundBlurChange={setBackgroundBlur}
- autoApplyFreshRecordingAutoZooms={autoApplyFreshRecordingAutoZooms}
- onAutoApplyFreshRecordingAutoZoomsChange={
- setAutoApplyFreshRecordingAutoZooms
- }
- connectZooms={connectZooms}
- onConnectZoomsChange={setConnectZooms}
- zoomInDurationMs={zoomInDurationMs}
- onZoomInDurationMsChange={setZoomInDurationMs}
- zoomInOverlapMs={zoomInOverlapMs}
- onZoomInOverlapMsChange={setZoomInOverlapMs}
- zoomOutDurationMs={zoomOutDurationMs}
- onZoomOutDurationMsChange={setZoomOutDurationMs}
- connectedZoomGapMs={connectedZoomGapMs}
- onConnectedZoomGapMsChange={setConnectedZoomGapMs}
- connectedZoomDurationMs={connectedZoomDurationMs}
- onConnectedZoomDurationMsChange={setConnectedZoomDurationMs}
- zoomInEasing={zoomInEasing}
- onZoomInEasingChange={setZoomInEasing}
- zoomOutEasing={zoomOutEasing}
- onZoomOutEasingChange={setZoomOutEasing}
- connectedZoomEasing={connectedZoomEasing}
- onConnectedZoomEasingChange={setConnectedZoomEasing}
- showCursor={effectiveShowCursor}
- onShowCursorChange={handleShowCursorChange}
- loopCursor={loopCursor}
- onLoopCursorChange={setLoopCursor}
- cursorStyle={cursorStyle}
- onCursorStyleChange={setCursorStyle}
- cursorSize={cursorSize}
- onCursorSizeChange={setCursorSize}
- cursorSmoothing={cursorSmoothing}
- onCursorSmoothingChange={setCursorSmoothing}
- cursorSpringStiffnessMultiplier={cursorSpringStiffnessMultiplier}
- onCursorSpringStiffnessMultiplierChange={
- setCursorSpringStiffnessMultiplier
- }
- cursorSpringDampingMultiplier={cursorSpringDampingMultiplier}
- onCursorSpringDampingMultiplierChange={
- setCursorSpringDampingMultiplier
- }
- cursorSpringMassMultiplier={cursorSpringMassMultiplier}
- onCursorSpringMassMultiplierChange={setCursorSpringMassMultiplier}
- cameraSpringStiffnessMultiplier={cameraSpringStiffnessMultiplier}
- onCameraSpringStiffnessMultiplierChange={
- setCameraSpringStiffnessMultiplier
- }
- cameraSpringDampingMultiplier={cameraSpringDampingMultiplier}
- onCameraSpringDampingMultiplierChange={
- setCameraSpringDampingMultiplier
- }
- cameraSpringMassMultiplier={cameraSpringMassMultiplier}
- onCameraSpringMassMultiplierChange={setCameraSpringMassMultiplier}
- zoomClassicMode={zoomClassicMode}
- onZoomClassicModeChange={setZoomClassicMode}
- cursorClickEffect={cursorClickEffect}
- cursorClickEffectColor={cursorClickEffectColor}
- onCursorClickEffectChange={setCursorClickEffect}
- onCursorClickEffectColorChange={setCursorClickEffectColor}
- cursorClickEffectScale={cursorClickEffectScale}
- onCursorClickEffectScaleChange={setCursorClickEffectScale}
- cursorClickEffectOpacity={cursorClickEffectOpacity}
- onCursorClickEffectOpacityChange={setCursorClickEffectOpacity}
- cursorClickEffectDurationMs={cursorClickEffectDurationMs}
- onCursorClickEffectDurationMsChange={setCursorClickEffectDurationMs}
- cursorClickBounce={cursorClickBounce}
- onCursorClickBounceChange={setCursorClickBounce}
- cursorClickBounceDuration={cursorClickBounceDuration}
- onCursorClickBounceDurationChange={setCursorClickBounceDuration}
- cursorSway={cursorSway}
- onCursorSwayChange={setCursorSway}
- borderRadius={borderRadius}
- onBorderRadiusChange={setBorderRadius}
- webcam={webcam}
- webcamPreviewSrc={webcam.sourcePath ? resolvedWebcamVideoUrl : null}
- webcamPreviewCurrentTime={currentTime}
- webcamPreviewPlaying={isPlaying}
- onWebcamChange={setWebcam}
- onUploadWebcam={handleUploadWebcam}
- onClearWebcam={handleClearWebcam}
- padding={padding}
- onPaddingChange={setPadding}
- cropRegion={cropRegion}
- onCropChange={setCropRegion}
- aspectRatio={aspectRatio}
- onAspectRatioChange={setAspectRatio}
- selectedAnnotationId={selectedAnnotationId}
- annotationRegions={annotationRegions}
- autoCaptions={autoCaptions}
- autoCaptionSettings={autoCaptionSettings}
- whisperExecutablePath={whisperExecutablePath}
- whisperModelPath={whisperModelPath}
- whisperModelDownloadStatus={whisperModelDownloadStatus}
- whisperModelDownloadProgress={whisperModelDownloadProgress}
- isGeneratingCaptions={isGeneratingCaptions}
- onAutoCaptionSettingsChange={setAutoCaptionSettings}
- onPickWhisperExecutable={handlePickWhisperExecutable}
- onPickWhisperModel={handlePickWhisperModel}
- onGenerateAutoCaptions={handleGenerateAutoCaptions}
- onClearAutoCaptions={handleClearAutoCaptions}
- captionCurrentTimeMs={Math.round(currentTime * 1000)}
- selectedCaptionId={selectedCaptionId}
- onBeginCaptionEdit={handleBeginCaptionEdit}
- onCaptionTextEdit={handleCaptionTextEdit}
- onCaptionRetime={handleCaptionRetime}
- onCaptionSplit={handleCaptionSplit}
- onCaptionMerge={handleCaptionMerge}
- onCaptionDelete={handleCaptionDelete}
- onDownloadWhisperSmallModel={handleDownloadWhisperSmallModel}
- onDeleteWhisperSmallModel={handleDeleteWhisperSmallModel}
- nativeCaptureUnavailableSession={sessionNativeCaptureUnavailable}
- onOpenNativeCaptureUnavailableModal={() =>
- setNativeCaptureUnavailableModalOpen(true)
- }
- onAnnotationContentChange={handleAnnotationContentChange}
- onAnnotationTypeChange={handleAnnotationTypeChange}
- onAnnotationStyleChange={handleAnnotationStyleChange}
- onAnnotationFigureDataChange={handleAnnotationFigureDataChange}
- onAnnotationBlurIntensityChange={
- handleAnnotationBlurIntensityChange
- }
- onAnnotationBlurColorChange={handleAnnotationBlurColorChange}
- onAnnotationDelete={handleAnnotationDelete}
- />
- )}
- </div>
- {/* Right column: preview + timeline */}
- <div className="flex min-h-0 flex-1 flex-col gap-3">
- {/* Preview */}
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="relative flex flex-1 min-h-0 flex-col overflow-hidden">
- {/* Aspect ratio + crop controls above preview */}
- <div className="flex items-center justify-center gap-2 py-1.5 flex-shrink-0">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="sm"
- className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground hover:bg-foreground/10 transition-all gap-1"
- >
- <span className="font-medium">
- {getAspectRatioLabel(aspectRatio)}
- </span>
- <ChevronDown className="w-3 h-3" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="center"
- className="bg-editor-surface-alt border-foreground/10"
- >
- {ASPECT_RATIOS.map((ratio) => (
- <DropdownMenuItem
- key={ratio}
- onClick={() => setAspectRatio(ratio)}
- className="text-muted-foreground hover:text-foreground hover:bg-foreground/10 cursor-pointer flex items-center justify-between gap-3"
- >
- <span>{getAspectRatioLabel(ratio)}</span>
- {aspectRatio === ratio && (
- <Check className="w-3 h-3 text-[#2563EB]" />
- )}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <div className="w-[1px] h-4 bg-foreground/20" />
- <Button
- variant="ghost"
- size="sm"
- onClick={handleOpenCropEditor}
- className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground hover:bg-foreground/10 transition-all gap-1.5"
- >
- <Crop className="w-3.5 h-3.5" />
- <span className="font-medium">
- {t("settings.crop.title")}
- </span>
- {isCropped ? (
- <span className="h-1.5 w-1.5 rounded-full bg-[#2563EB]" />
- ) : null}
- </Button>
- </div>
- {/* Video preview */}
- <div
- className="flex w-full min-h-0 flex-1 items-stretch"
- style={{ flex: "1 1 auto", margin: "6px 0 0" }}
- >
- <div className="flex min-w-0 flex-1 items-center justify-center px-1">
- <div
- className="relative"
- style={{
- width: "auto",
- height: "100%",
- aspectRatio: previewAspectRatioValue,
- maxWidth: "100%",
- margin: "0 auto",
- boxSizing: "border-box",
- }}
- >
- {renderPreviewPlayback(
- videoPlaybackRef,
- shouldSuspendPreviewRendering,
- "inline",
- )}
- </div>
- </div>
- </div>
- </div>
- </div>
- {/* Toolbar - sits at bottom of right column, only spans preview width */}
- <div className="relative flex flex-shrink-0 items-center px-1 py-1">
- {/* Left tools */}
- <div className="z-10 flex min-w-0 flex-1 items-center gap-1.5">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="sm"
- className="h-7 gap-1 rounded-full border border-foreground/[0.08] bg-foreground/[0.04] px-2.5 text-[11px] text-foreground/65 shadow-[inset_0_1px_0_hsl(var(--foreground)/0.06)] transition-all hover:bg-foreground/[0.08] hover:text-foreground"
- >
- <Plus className="w-3.5 h-3.5" />
- <span className="font-medium">
- {t("editor.toolbar.addLayer")}
- </span>
- <ChevronDown className="w-3 h-3" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="start"
- className="bg-editor-surface-alt border-foreground/10"
- >
- <DropdownMenuItem
- onClick={() => {
- const nextTrackIndex =
- annotationRegions.length > 0
- ? Math.max(
- ...annotationRegions.map(
- (r) => r.trackIndex ?? 0,
- ),
- ) + 1
- : 0;
- timelineRef.current?.addAnnotation(nextTrackIndex);
- }}
- className="text-muted-foreground hover:text-foreground hover:bg-foreground/10 cursor-pointer"
- >
- {t("timeline.annotation.label")}
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => {
- const nextTrackIndex =
- audioRegions.length > 0
- ? Math.max(
- ...audioRegions.map(
- (region) =>
- region.trackIndex ?? 0,
- ),
- ) + 1
- : 0;
- timelineRef.current?.addAudio(nextTrackIndex);
- }}
- className="text-muted-foreground hover:text-foreground hover:bg-foreground/10 cursor-pointer"
- >
- {t("timeline.audio.label")}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- <div className="w-[1px] h-4 bg-foreground/10 mx-1" />
- <Button
- onClick={() => timelineRef.current?.addZoom()}
- variant="ghost"
- size="icon"
- className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-[#2563EB]/10 hover:text-[#2563EB]"
- title={t("timeline.zoom.addZoom")}
- >
- <ZoomIn className="w-4 h-4" />
- </Button>
- <Button
- onClick={() => timelineRef.current?.suggestZooms()}
- variant="ghost"
- size="icon"
- className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-[#2563EB]/10 hover:text-[#2563EB]"
- title={t("timeline.zoom.suggestZooms")}
- >
- <WandSparkles className="w-4 h-4" />
- </Button>
- <Button
- onClick={() => timelineRef.current?.splitClip()}
- variant="ghost"
- size="icon"
- className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-foreground/10 hover:text-foreground"
- title={t("editor.toolbar.splitClip")}
- >
- <Scissors className="w-4 h-4" />
- </Button>
- </div>
- {/* Playback controls - centered */}
- <div className="absolute inset-0 z-10 flex items-center justify-center pointer-events-none">
- <div className="flex items-center gap-1.5 pointer-events-auto">
- <span className="mr-1 text-[10px] font-medium tabular-nums text-muted-foreground">
- {formatTime(timelinePlayheadTime)}
- </span>
- <Button
- variant="ghost"
- size="icon"
- className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-foreground/10 hover:text-foreground"
- title={t("editor.playback.skipBack")}
- onClick={handlePreviewSkipBack}
- >
- <SkipBack className="w-3.5 h-3.5" weight="fill" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className={`h-7 w-7 rounded-full border border-foreground/10 transition-all shadow-[0_8px_18px_rgba(0,0,0,0.18)] ${isPlaying ? "bg-foreground/10 text-foreground hover:bg-foreground/20" : "bg-neutral-800 text-white hover:bg-neutral-700 dark:bg-white dark:text-black dark:hover:bg-white/90"}`}
- onClick={togglePlayPause}
- title={isPlaying ? "Pause" : "Play"}
- >
- {isPlaying ? (
- <Pause className="w-3.5 h-3.5" weight="fill" />
- ) : (
- <Play className="w-3.5 h-3.5" weight="fill" />
- )}
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-foreground/10 hover:text-foreground"
- title={t("editor.playback.skipForward")}
- onClick={handlePreviewSkipForward}
- >
- <SkipForward className="w-3.5 h-3.5" weight="fill" />
- </Button>
- <span className="text-[10px] font-medium text-muted-foreground/70 tabular-nums ml-1">
- {formatTime(timelineDuration)}
- </span>
- </div>
- </div>
- {/* Right: collapse + volume */}
- <div className="z-10 ml-auto flex items-center gap-2">
- <div className="flex items-center gap-1.5">
- <button
- type="button"
- className="text-muted-foreground hover:text-foreground transition-colors"
- title={t("editor.playback.muteUnmute")}
- onClick={() =>
- setPreviewVolume(previewVolume <= 0.001 ? 1 : 0)
- }
- >
- {previewVolume <= 0.001 ? (
- <VolumeX className="w-3.5 h-3.5" />
- ) : previewVolume < 0.5 ? (
- <Volume1 className="w-3.5 h-3.5" />
- ) : (
- <Volume2 className="w-3.5 h-3.5" />
- )}
- </button>
- <div className="relative flex h-7 w-24 select-none items-center overflow-hidden rounded-full border border-foreground/[0.06] bg-editor-bg/80 shadow-[inset_0_1px_0_hsl(var(--foreground)/0.06)]">
- <div
- className="absolute inset-y-[3px] left-[3px] right-auto rounded-[10px] bg-foreground/[0.08]"
- style={{
- width:
- previewVolume > 0
- ? `max(calc(${previewVolume * 100}% - 6px), 1.2rem)`
- : 0,
- }}
- />
- <div
- className="pointer-events-none absolute bottom-[18%] top-[18%] z-10 w-[2px] rounded-full bg-foreground/95 shadow-[0_0_10px_rgba(37,99,235,0.28)]"
- style={{ left: `calc(${previewVolume * 100}% - 8px)` }}
- />
- <span className="pointer-events-none relative z-10 pl-2 text-[10px] font-medium text-muted-foreground">
- {Math.round(previewVolume * 100)}%
- </span>
- <input
- type="range"
- min="0"
- max="1"
- step="0.01"
- value={previewVolume}
- onChange={(e) =>
- setPreviewVolume(Number(e.target.value))
- }
- className="absolute inset-0 h-full w-full cursor-ew-resize opacity-0"
- />
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div
- className="flex-shrink-0 flex flex-col"
- style={{
- height: "15%",
- minHeight: 160,
- }}
- >
- <TimelineEditor
- ref={timelineRef}
- videoDuration={timelineDuration}
- currentTime={currentTime}
- playheadTime={timelinePlayheadTime}
- onSeek={handleTimelineSeek}
- videoPath={videoPath}
- videoSourcePath={videoSourcePath}
- cursorTelemetrySourcePath={cursorTelemetrySourcePath}
- cursorTelemetry={normalizedCursorTelemetry}
- autoSuggestZoomsTrigger={autoSuggestZoomsTrigger}
- onAutoSuggestZoomsConsumed={handleAutoSuggestZoomsConsumed}
- disableSuggestedZooms={!autoApplyFreshRecordingAutoZooms}
- zoomRegions={zoomRegions}
- onZoomAdded={handleZoomAdded}
- onZoomSuggested={handleZoomSuggested}
- onZoomSpanChange={handleZoomSpanChange}
- onZoomDelete={handleZoomDelete}
- selectedZoomId={selectedZoomId}
- onSelectZoom={handleSelectZoom}
- trimRegions={trimRegions}
- clipRegions={clipRegions}
- onClipSplit={handleClipSplit}
- onClipSpanChange={handleClipSpanChange}
- selectedClipId={selectedClipId}
- onSelectClip={handleSelectClip}
- audioRegions={audioRegions}
- onAudioAdded={handleAudioAdded}
- onAudioSpanChange={handleAudioSpanChange}
- onAudioDelete={handleAudioDelete}
- selectedAudioId={selectedAudioId}
- onSelectAudio={handleSelectAudio}
- captionRegions={effectiveCaptionRegions}
- onCaptionSpanChange={(id, span) =>
- handleCaptionRetime(id, {
- startMs: mapTimelineTimeToSourceTime(span.start),
- endMs: mapTimelineTimeToSourceTime(span.end),
- })
- }
- selectedCaptionId={selectedCaptionId}
- onSelectCaption={handleSelectCaption}
- onCaptionDelete={handleCaptionDelete}
- onCaptionAdded={handleCaptionAdded}
- captionsEnabled={autoCaptionSettings.enabled}
- captionQuickAddEnabled={autoCaptionSettings.timelineQuickAdd}
- annotationRegions={annotationRegions}
- onAnnotationAdded={handleAnnotationAdded}
- onAnnotationSpanChange={handleAnnotationSpanChange}
- onAnnotationDelete={handleAnnotationDelete}
- selectedAnnotationId={selectedAnnotationId}
- onSelectAnnotation={handleSelectAnnotation}
- showSourceAudioTrack={clipRegions.some((c) => c.showSourceAudio)}
- sourceAudioResourceVersion={sourceAudioFallbackRefreshKey}
- sourceAudioTrackSettings={audio.activeSourceAudioTrackSettings}
- getSourceAudioTrackSettingsForClip={
- audio.getSourceAudioTrackSettingsForClip
- }
- onSourceAudioAvailabilityChange={(available) => {
- setHasClipSourceAudio(available);
- }}
- onSourceAudioTracksMetaChange={(tracks) => {
- audio.onSourceAudioTracksMetaChange(tracks);
- }}
- />
- </div>
- </div>
-
- {showCropModal ? (
- <>
- <div
- className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm animate-in fade-in duration-200"
- onClick={handleCancelCropEditor}
- />
- <div className="fixed left-1/2 top-1/2 z-[60] max-h-[90vh] w-[90vw] max-w-5xl -translate-x-1/2 -translate-y-1/2 overflow-auto rounded-2xl border border-foreground/10 bg-editor-dialog p-8 shadow-2xl animate-in zoom-in-95 duration-200">
- <div className="mb-6 flex items-center justify-between">
- <div>
- <span className="text-xl font-bold text-foreground">
- {t("settings.crop.title")}
- </span>
- <p className="mt-2 text-sm text-muted-foreground">
- {t("settings.crop.instruction")}
- </p>
- </div>
- <Button
- variant="ghost"
- size="icon"
- onClick={handleCancelCropEditor}
- className="text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
- >
- <X className="h-5 w-5" />
- </Button>
- </div>
- <CropControl
- videoElement={videoPlaybackRef.current?.video || null}
- cropRegion={cropRegion}
- onCropChange={setCropRegion}
- aspectRatio={aspectRatio}
- />
- <div className="mt-6 flex justify-end">
- <Button
- onClick={handleCloseCropEditor}
- size="lg"
- className="bg-[#2563EB] text-white hover:bg-[#2563EB]/90"
- >
- {t("common.actions.done")}
- </Button>
- </div>
- </div>
- </>
- ) : null}
-
- {projectBrowser}
- {projectSaveDialog}
- {unsavedChangesDialog}
- {nativeCaptureUnavailableDialog}
-
- <Toaster className="pointer-events-auto" />
- </div>
+ <EditorShell
+ t={t}
+ project={project}
+ appearance={appearance}
+ timeline={timeline}
+ ui={ui}
+ presets={presets}
+ projectController={projectController}
+ editing={editing}
+ exportController={exportController}
+ exportSettings={exportSettings}
+ exportSession={exportSession}
+ exportDimensions={exportDimensions}
+ settingsPanelProps={settingsPanelProps}
+ headerLeftControlsPaddingClass={headerLeftControlsPaddingClass}
+ hasCaptionsForSidecar={hasCaptionsForSidecar}
+ nvidiaCudaExportAvailable={nvidiaCudaExportAvailable}
+ experimentalNvidiaCudaExport={experimentalNvidiaCudaExport}
+ setExperimentalNvidiaCudaExport={setExperimentalNvidiaCudaExport}
+ effectiveShowCursor={effectiveShowCursor}
+ previewAspectRatioValue={previewAspectRatioValue}
+ />
);
}
diff --git a/src/components/video-editor/captions/useAutoCaptionController.ts b/src/components/video-editor/captions/useAutoCaptionController.ts
new file mode 100644
index 00000000..3ec81ee7
--- /dev/null
+++ b/src/components/video-editor/captions/useAutoCaptionController.ts
@@ -0,0 +1,246 @@
+import { type Dispatch, type SetStateAction, useCallback, useEffect } from "react";
+import { toast } from "sonner";
+import { resolveAutoCaptionSourcePath } from "../autoCaptionSource";
+import { type CaptionEditTarget, updateCaptionCuesForEditedTarget } from "../captionEditing";
+import { resolveVideoUrl } from "../projectPersistence";
+import type { AutoCaptionSettings, CaptionCue } from "../types";
+import { getErrorMessage } from "../videoEditorUtils";
+
+type DownloadStatus = "idle" | "downloading" | "downloaded" | "error";
+type Translator = (
+ key: string,
+ fallback?: string,
+ params?: Record<string, string | number>,
+) => string;
+
+interface UseAutoCaptionControllerParams {
+ t: Translator;
+ videoPath: string | null;
+ setVideoPath: Dispatch<SetStateAction<string | null>>;
+ videoSourcePath: string | null;
+ setVideoSourcePath: Dispatch<SetStateAction<string | null>>;
+ webcamSourcePath: string | null;
+ whisperExecutablePath: string | null;
+ setWhisperExecutablePath: Dispatch<SetStateAction<string | null>>;
+ whisperModelPath: string | null;
+ setWhisperModelPath: Dispatch<SetStateAction<string | null>>;
+ downloadedWhisperModelPath: string | null;
+ setDownloadedWhisperModelPath: Dispatch<SetStateAction<string | null>>;
+ whisperModelDownloadStatus: DownloadStatus;
+ setWhisperModelDownloadStatus: Dispatch<SetStateAction<DownloadStatus>>;
+ setWhisperModelDownloadProgress: Dispatch<SetStateAction<number>>;
+ isGeneratingCaptions: boolean;
+ setIsGeneratingCaptions: Dispatch<SetStateAction<boolean>>;
+ autoCaptionSettings: AutoCaptionSettings;
+ setAutoCaptionSettings: Dispatch<SetStateAction<AutoCaptionSettings>>;
+ setAutoCaptions: Dispatch<SetStateAction<CaptionCue[]>>;
+ syncActiveVideoSource: (sourcePath: string, webcamPath?: string | null) => Promise<void>;
+}
+
+export function useAutoCaptionController({
+ t,
+ videoPath,
+ setVideoPath,
+ videoSourcePath,
+ setVideoSourcePath,
+ webcamSourcePath,
+ whisperExecutablePath,
+ setWhisperExecutablePath,
+ whisperModelPath,
+ setWhisperModelPath,
+ downloadedWhisperModelPath,
+ setDownloadedWhisperModelPath,
+ whisperModelDownloadStatus,
+ setWhisperModelDownloadStatus,
+ setWhisperModelDownloadProgress,
+ isGeneratingCaptions,
+ setIsGeneratingCaptions,
+ autoCaptionSettings,
+ setAutoCaptionSettings,
+ setAutoCaptions,
+ syncActiveVideoSource,
+}: UseAutoCaptionControllerParams) {
+ useEffect(() => {
+ const unsubscribe = window.electronAPI.onWhisperSmallModelDownloadProgress((state) => {
+ setWhisperModelDownloadStatus(state.status);
+ setWhisperModelDownloadProgress(state.progress);
+ if (state.status === "downloaded") {
+ setDownloadedWhisperModelPath(state.path ?? null);
+ setWhisperModelPath((current) => current ?? state.path ?? null);
+ } else if (state.status === "idle") {
+ setDownloadedWhisperModelPath(null);
+ } else if (state.status === "error" && state.error) {
+ toast.error(state.error);
+ }
+ });
+
+ void window.electronAPI.getWhisperSmallModelStatus().then((result) => {
+ if (!result.success) return;
+ if (result.exists && result.path) {
+ setDownloadedWhisperModelPath(result.path);
+ setWhisperModelPath((current) => current ?? result.path ?? null);
+ setWhisperModelDownloadStatus("downloaded");
+ setWhisperModelDownloadProgress(100);
+ } else {
+ setDownloadedWhisperModelPath(null);
+ setWhisperModelDownloadStatus("idle");
+ setWhisperModelDownloadProgress(0);
+ }
+ });
+
+ return () => unsubscribe?.();
+ }, [
+ setDownloadedWhisperModelPath,
+ setWhisperModelDownloadProgress,
+ setWhisperModelDownloadStatus,
+ setWhisperModelPath,
+ ]);
+
+ const handlePickWhisperExecutable = useCallback(async () => {
+ const result = await window.electronAPI.openWhisperExecutablePicker();
+ if (!result.success || !result.path) return;
+ setWhisperExecutablePath(result.path);
+ toast.success("Whisper executable selected");
+ }, [setWhisperExecutablePath]);
+
+ const handleDownloadWhisperSmallModel = useCallback(async () => {
+ if (whisperModelDownloadStatus === "downloading") return;
+ setWhisperModelDownloadStatus("downloading");
+ setWhisperModelDownloadProgress(0);
+ const result = await window.electronAPI.downloadWhisperSmallModel();
+ if (!result.success) {
+ setWhisperModelDownloadStatus("error");
+ toast.error(result.error || "Failed to download Whisper small model");
+ return;
+ }
+ if (result.path) {
+ setDownloadedWhisperModelPath(result.path);
+ setWhisperModelPath(result.path);
+ }
+ }, [
+ setDownloadedWhisperModelPath,
+ setWhisperModelDownloadProgress,
+ setWhisperModelDownloadStatus,
+ setWhisperModelPath,
+ whisperModelDownloadStatus,
+ ]);
+
+ const handlePickWhisperModel = useCallback(async () => {
+ const result = await window.electronAPI.openWhisperModelPicker();
+ if (!result.success || !result.path) return;
+ setWhisperModelPath(result.path);
+ toast.success("Whisper model selected");
+ }, [setWhisperModelPath]);
+
+ const handleDeleteWhisperSmallModel = useCallback(async () => {
+ const result = await window.electronAPI.deleteWhisperSmallModel();
+ if (!result.success) {
+ toast.error(result.error || "Failed to delete Whisper small model");
+ setWhisperModelDownloadStatus("idle");
+ setWhisperModelDownloadProgress(0);
+ return;
+ }
+ setWhisperModelPath((current) => (current === downloadedWhisperModelPath ? null : current));
+ setDownloadedWhisperModelPath(null);
+ setWhisperModelDownloadStatus("idle");
+ setWhisperModelDownloadProgress(0);
+ toast.success("Whisper small model deleted");
+ }, [
+ downloadedWhisperModelPath,
+ setDownloadedWhisperModelPath,
+ setWhisperModelDownloadProgress,
+ setWhisperModelDownloadStatus,
+ setWhisperModelPath,
+ ]);
+
+ const handleGenerateAutoCaptions = useCallback(async () => {
+ if (isGeneratingCaptions) return;
+ let sourcePath = resolveAutoCaptionSourcePath({ videoSourcePath, videoPath });
+ if (!sourcePath) {
+ const sessionResult = await window.electronAPI.getCurrentRecordingSession?.();
+ const currentVideoResult = await window.electronAPI.getCurrentVideoPath();
+ sourcePath = resolveAutoCaptionSourcePath({
+ recordingSessionVideoPath:
+ sessionResult?.success && sessionResult.session?.videoPath
+ ? sessionResult.session.videoPath
+ : null,
+ currentVideoPath: currentVideoResult.success
+ ? (currentVideoResult.path ?? null)
+ : null,
+ });
+ }
+ if (!sourcePath) {
+ toast.error("No source video is loaded");
+ return;
+ }
+ if (sourcePath !== videoSourcePath) {
+ await syncActiveVideoSource(sourcePath, webcamSourcePath);
+ setVideoSourcePath(sourcePath);
+ setVideoPath(await resolveVideoUrl(sourcePath));
+ } else {
+ await syncActiveVideoSource(sourcePath, webcamSourcePath);
+ }
+ if (!whisperModelPath) {
+ toast.error("Select a Whisper model or download the small model first");
+ return;
+ }
+
+ setIsGeneratingCaptions(true);
+ try {
+ const result = await window.electronAPI.generateAutoCaptions({
+ videoPath: sourcePath,
+ whisperExecutablePath: whisperExecutablePath ?? undefined,
+ whisperModelPath,
+ language: autoCaptionSettings.language,
+ });
+ if (!result.success || !result.cues) {
+ toast.error(
+ result.message ||
+ getErrorMessage(result.error) ||
+ "Failed to generate captions",
+ );
+ return;
+ }
+ setAutoCaptions(result.cues);
+ if (result.cues.length > 0) {
+ setAutoCaptionSettings((current) => ({ ...current, enabled: true }));
+ }
+ toast.success(result.message || `Generated ${result.cues.length} captions`);
+ } catch (error) {
+ toast.error(getErrorMessage(error));
+ } finally {
+ setIsGeneratingCaptions(false);
+ }
+ }, [
+ autoCaptionSettings.language,
+ isGeneratingCaptions,
+ setAutoCaptionSettings,
+ setAutoCaptions,
+ setIsGeneratingCaptions,
+ setVideoPath,
+ setVideoSourcePath,
+ syncActiveVideoSource,
+ videoPath,
+ videoSourcePath,
+ webcamSourcePath,
+ whisperExecutablePath,
+ whisperModelPath,
+ ]);
+
+ const handleSaveAutoCaptionEdit = useCallback(
+ (target: CaptionEditTarget, text: string) => {
+ setAutoCaptions((captions) => updateCaptionCuesForEditedTarget(captions, target, text));
+ toast.success(t("settings.captions.editSaved", "Caption updated"));
+ },
+ [setAutoCaptions, t],
+ );
+
+ return {
+ handlePickWhisperExecutable,
+ handleDownloadWhisperSmallModel,
+ handlePickWhisperModel,
+ handleDeleteWhisperSmallModel,
+ handleGenerateAutoCaptions,
+ handleSaveAutoCaptionEdit,
+ };
+}
diff --git a/src/components/video-editor/export/buildExportRenderOptions.ts b/src/components/video-editor/export/buildExportRenderOptions.ts
new file mode 100644
index 00000000..137de934
--- /dev/null
+++ b/src/components/video-editor/export/buildExportRenderOptions.ts
@@ -0,0 +1,93 @@
+import type { ExportProgress } from "@/lib/exporter";
+import { toFileUrl } from "../projectPersistence";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useTimelineState } from "../state/useTimelineState";
+import type { CaptionCue, CursorTelemetryPoint, SpeedRegion, ZoomRegion } from "../types";
+
+type AppearanceState = ReturnType<typeof useAppearanceState>;
+type TimelineState = ReturnType<typeof useTimelineState>;
+
+type BuildExportRenderOptionsInput = {
+ appearance: AppearanceState;
+ timeline: TimelineState;
+ effectiveSpeedRegions: SpeedRegion[];
+ effectiveZoomRegions: ZoomRegion[];
+ effectiveCursorTelemetry: CursorTelemetryPoint[];
+ effectiveShowCursor: boolean;
+ previewWidth: number;
+ previewHeight: number;
+ shadowIntensity: number;
+ onProgress: (progress: ExportProgress) => void;
+};
+
+export function buildExportRenderOptions({
+ appearance,
+ timeline,
+ effectiveSpeedRegions,
+ effectiveZoomRegions,
+ effectiveCursorTelemetry,
+ effectiveShowCursor,
+ previewWidth,
+ previewHeight,
+ shadowIntensity,
+ onProgress,
+}: BuildExportRenderOptionsInput) {
+ return {
+ wallpaper: appearance.wallpaper,
+ trimRegions: timeline.trimRegions,
+ speedRegions: effectiveSpeedRegions,
+ showShadow: shadowIntensity > 0,
+ shadowIntensity,
+ backgroundBlur: appearance.backgroundBlur,
+ zoomMotionBlur: appearance.zoomMotionBlur,
+ zoomMotionBlurTuning: appearance.zoomMotionBlurTuning,
+ zoomTemporalMotionBlur: appearance.zoomTemporalMotionBlur,
+ zoomMotionBlurSampleCount: appearance.zoomMotionBlurSampleCount,
+ zoomMotionBlurShutterFraction: appearance.zoomMotionBlurShutterFraction,
+ connectZooms: appearance.connectZooms,
+ zoomInDurationMs: appearance.zoomInDurationMs,
+ zoomInOverlapMs: appearance.zoomInOverlapMs,
+ zoomOutDurationMs: appearance.zoomOutDurationMs,
+ connectedZoomGapMs: appearance.connectedZoomGapMs,
+ connectedZoomDurationMs: appearance.connectedZoomDurationMs,
+ zoomInEasing: appearance.zoomInEasing,
+ zoomOutEasing: appearance.zoomOutEasing,
+ connectedZoomEasing: appearance.connectedZoomEasing,
+ borderRadius: appearance.borderRadius,
+ padding: appearance.padding,
+ cropRegion: appearance.cropRegion,
+ webcam: appearance.webcam,
+ webcamUrl:
+ appearance.resolvedWebcamVideoUrl ??
+ (appearance.webcam.sourcePath ? toFileUrl(appearance.webcam.sourcePath) : null),
+ annotationRegions: timeline.annotationRegions,
+ autoCaptions: timeline.autoCaptions as CaptionCue[],
+ autoCaptionSettings: timeline.autoCaptionSettings,
+ zoomRegions: effectiveZoomRegions,
+ cursorTelemetry: effectiveCursorTelemetry,
+ showCursor: effectiveShowCursor,
+ cursorStyle: appearance.cursorStyle,
+ cursorSize: appearance.cursorSize,
+ cursorSmoothing: appearance.cursorSmoothing,
+ cursorSpringStiffnessMultiplier: appearance.cursorSpringStiffnessMultiplier,
+ cursorSpringDampingMultiplier: appearance.cursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier: appearance.cursorSpringMassMultiplier,
+ cameraSpringStiffnessMultiplier: appearance.cameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier: appearance.cameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier: appearance.cameraSpringMassMultiplier,
+ zoomSmoothness: appearance.zoomSmoothness,
+ zoomClassicMode: appearance.zoomClassicMode,
+ cursorMotionBlur: appearance.cursorMotionBlur,
+ cursorClickEffect: appearance.cursorClickEffect,
+ cursorClickEffectColor: appearance.cursorClickEffectColor,
+ cursorClickEffectScale: appearance.cursorClickEffectScale,
+ cursorClickEffectOpacity: appearance.cursorClickEffectOpacity,
+ cursorClickEffectDurationMs: appearance.cursorClickEffectDurationMs,
+ cursorClickBounce: appearance.cursorClickBounce,
+ cursorClickBounceDuration: appearance.cursorClickBounceDuration,
+ cursorSway: appearance.cursorSway,
+ previewWidth,
+ previewHeight,
+ onProgress,
+ };
+}
diff --git a/src/components/video-editor/export/exportPersistence.ts b/src/components/video-editor/export/exportPersistence.ts
new file mode 100644
index 00000000..678564c4
--- /dev/null
+++ b/src/components/video-editor/export/exportPersistence.ts
@@ -0,0 +1,154 @@
+export interface PendingExportSave {
+ fileName: string;
+ arrayBuffer?: ArrayBuffer;
+ tempFilePath?: string;
+ captionSidecar?: {
+ format: "srt" | "vtt" | "both";
+ cues: Array<{
+ startMs: number;
+ endMs: number;
+ text: string;
+ }>;
+ };
+}
+
+const EXPORT_BLOB_STREAM_CHUNK_BYTES = 16 * 1024 * 1024;
+
+export async function streamExportBlobToTempFile(
+ blob: Blob,
+ extension: string,
+): Promise<string | null> {
+ if (
+ typeof window === "undefined" ||
+ !window.electronAPI?.openExportStream ||
+ !window.electronAPI?.writeExportStreamChunk ||
+ !window.electronAPI?.closeExportStream
+ ) {
+ return null;
+ }
+
+ const openResult = await window.electronAPI.openExportStream({ extension });
+ if (!openResult.success || !openResult.streamId || !openResult.tempPath) {
+ throw new Error(openResult.error || "Failed to open export stream");
+ }
+
+ const { streamId } = openResult;
+ let position = 0;
+ try {
+ while (position < blob.size) {
+ const chunk = blob.slice(position, position + EXPORT_BLOB_STREAM_CHUNK_BYTES);
+ const chunkBuffer = await chunk.arrayBuffer();
+ const writeResult = await window.electronAPI.writeExportStreamChunk(
+ streamId,
+ position,
+ new Uint8Array(chunkBuffer),
+ );
+ if (!writeResult.success) {
+ throw new Error(writeResult.error || "Failed to write export stream chunk");
+ }
+ position += chunkBuffer.byteLength;
+ }
+
+ const closeResult = await window.electronAPI.closeExportStream(streamId);
+ if (!closeResult.success || !closeResult.tempPath) {
+ throw new Error(closeResult.error || "Failed to close export stream");
+ }
+ return closeResult.tempPath;
+ } catch (error) {
+ try {
+ await window.electronAPI.closeExportStream(streamId, { abort: true });
+ } catch {
+ // Best-effort cleanup; preserve the original error.
+ }
+ throw error;
+ }
+}
+
+export async function saveExportBlob(
+ blob: Blob,
+ fileName: string,
+ outputPath: string | null = null,
+ captionSidecar?: PendingExportSave["captionSidecar"],
+) {
+ const extension = fileName.split(".").pop()?.toLowerCase() || "bin";
+ const hasExportStreamApi =
+ typeof window !== "undefined" &&
+ typeof window.electronAPI?.openExportStream === "function" &&
+ typeof window.electronAPI?.writeExportStreamChunk === "function" &&
+ typeof window.electronAPI?.closeExportStream === "function";
+ let streamError: unknown = null;
+
+ try {
+ const tempFilePath = await streamExportBlobToTempFile(blob, extension);
+ if (tempFilePath) {
+ return {
+ saveResult: await window.electronAPI.finalizeExportedVideo({
+ tempPath: tempFilePath,
+ fileName,
+ outputPath,
+ captionSidecar,
+ }),
+ pendingSave: { fileName, tempFilePath, captionSidecar } satisfies PendingExportSave,
+ };
+ }
+ } catch (error) {
+ streamError = error;
+ console.warn("[export] Temp-file blob save failed", error);
+ }
+
+ if (!canUseInMemoryExportSaveFallback({ blobSize: blob.size, extension, hasExportStreamApi })) {
+ const message = describeBlockedInMemoryExportSave({ blobSize: blob.size, extension });
+ console.error("[export] Refusing in-memory blob save fallback", {
+ fileName,
+ blobSize: blob.size,
+ extension,
+ hasExportStreamApi,
+ streamError,
+ });
+ throw new Error(message);
+ }
+
+ console.warn("[export] Falling back to in-memory blob save", {
+ fileName,
+ blobSize: blob.size,
+ extension,
+ hasExportStreamApi,
+ });
+ const arrayBuffer = await blob.arrayBuffer();
+ return {
+ saveResult: outputPath
+ ? await window.electronAPI.writeExportedVideoToPath(
+ arrayBuffer,
+ outputPath,
+ captionSidecar,
+ )
+ : await window.electronAPI.saveExportedVideo(arrayBuffer, fileName, captionSidecar),
+ pendingSave: { fileName, arrayBuffer, captionSidecar } satisfies PendingExportSave,
+ };
+}
+
+export async function writeSmokeExportReport(
+ outputPath: string | null,
+ report: Record<string, unknown>,
+): Promise<void> {
+ if (!outputPath || typeof window === "undefined") return;
+
+ try {
+ const reportBytes = new TextEncoder().encode(JSON.stringify(report, null, 2));
+ const reportBuffer = reportBytes.buffer.slice(
+ reportBytes.byteOffset,
+ reportBytes.byteOffset + reportBytes.byteLength,
+ ) as ArrayBuffer;
+ await window.electronAPI.writeExportedVideoToPath(
+ reportBuffer,
+ `${outputPath}.report.json`,
+ );
+ } catch (error) {
+ console.error("[smoke-export] Failed to write report", error);
+ }
+}
+
+import {
+ canUseInMemoryExportSaveFallback,
+ describeBlockedInMemoryExportSave,
+} from "@/lib/exporter/exportSavePolicy";
diff --git a/src/components/video-editor/export/exportRunnerSupport.ts b/src/components/video-editor/export/exportRunnerSupport.ts
new file mode 100644
index 00000000..11c8cf8e
--- /dev/null
+++ b/src/components/video-editor/export/exportRunnerSupport.ts
@@ -0,0 +1,69 @@
+import type { RefObject } from "react";
+import { useCallback } from "react";
+import { toast } from "sonner";
+import type { SupportedMp4Dimensions } from "@/lib/exporter";
+import type { useVideoEditorAudio } from "../audio/useVideoEditorAudio";
+import type { getSmokeExportConfig } from "../smokeExportConfig";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useTimelineState } from "../state/useTimelineState";
+import type { CursorTelemetryPoint, SpeedRegion, ZoomRegion } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+import { summarizeErrorMessage } from "../videoEditorUtils";
+import type { PendingExportSave } from "./exportPersistence";
+import type { useExportSession } from "./useExportSession";
+import type { useExportSettings } from "./useExportSettings";
+
+export type ExportRunnerInput = {
+ videoPath: string | null;
+ videoPlaybackRef: RefObject<VideoPlaybackRef | null>;
+ isPlaying: boolean;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ exportSession: ReturnType<typeof useExportSession>;
+ audio: ReturnType<typeof useVideoEditorAudio>;
+ smokeExportConfig: ReturnType<typeof getSmokeExportConfig>;
+ effectiveSpeedRegions: SpeedRegion[];
+ effectiveZoomRegions: ZoomRegion[];
+ effectiveCursorTelemetry: CursorTelemetryPoint[];
+ effectiveShowCursor: boolean;
+ ensureSupportedMp4SourceDimensions: (
+ frameRate: ReturnType<typeof useExportSettings>["mp4FrameRate"],
+ ) => Promise<SupportedMp4Dimensions>;
+ captionSidecarPayload?: PendingExportSave["captionSidecar"];
+ experimentalNvidiaCudaExport: boolean;
+ nvidiaCudaExportAvailable: boolean;
+ remountPreview: () => void;
+};
+
+export function showExportErrorToast(message: string) {
+ const summary = summarizeErrorMessage(message);
+ toast.error(summary, {
+ description: summary === message ? undefined : message,
+ duration: 20_000,
+ });
+}
+
+export function useExportSuccessToast() {
+ return useCallback((filePath: string) => {
+ toast.success(`Exported successfully to ${filePath}`, {
+ action: {
+ label: "Show in Folder",
+ onClick: async () => {
+ try {
+ const result = await window.electronAPI.revealInFolder(filePath);
+ if (!result.success) {
+ toast.error(
+ result.error ||
+ result.message ||
+ "Failed to reveal item in folder.",
+ );
+ }
+ } catch (error) {
+ toast.error(`Error revealing in folder: ${String(error)}`);
+ }
+ },
+ },
+ });
+ }, []);
+}
diff --git a/src/components/video-editor/export/useEditorExportController.ts b/src/components/video-editor/export/useEditorExportController.ts
new file mode 100644
index 00000000..60911c7d
--- /dev/null
+++ b/src/components/video-editor/export/useEditorExportController.ts
@@ -0,0 +1,102 @@
+import type { RefObject } from "react";
+import { useCallback } from "react";
+import type { useI18n } from "@/contexts/I18nContext";
+import type { useVideoEditorAudio } from "../audio/useVideoEditorAudio";
+import type { getSmokeExportConfig } from "../smokeExportConfig";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useTimelineState } from "../state/useTimelineState";
+import { openExternalLink, RECORDLY_ISSUES_URL } from "../TutorialHelp";
+import type { CursorTelemetryPoint, SpeedRegion, ZoomRegion } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+import { useExportDialogActions } from "./useExportDialogActions";
+import type { useExportDimensions } from "./useExportDimensions";
+import { useExportRunner } from "./useExportRunner";
+import type { useExportSession } from "./useExportSession";
+import type { useExportSettings } from "./useExportSettings";
+import { useExportStatusViewModel } from "./useExportStatusViewModel";
+import { useSmokeExportAutomation } from "./useSmokeExportAutomation";
+
+type Input = {
+ t: ReturnType<typeof useI18n>["t"];
+ videoPath: string | null;
+ videoSourcePath: string | null;
+ videoPlaybackRef: RefObject<VideoPlaybackRef>;
+ isPlaying: boolean;
+ duration: number;
+ error: string | null;
+ loading: boolean;
+ isPreviewReady: boolean;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ settings: ReturnType<typeof useExportSettings>;
+ session: ReturnType<typeof useExportSession>;
+ dimensions: ReturnType<typeof useExportDimensions>;
+ audio: ReturnType<typeof useVideoEditorAudio>;
+ smokeConfig: ReturnType<typeof getSmokeExportConfig>;
+ effectiveSpeedRegions: SpeedRegion[];
+ effectiveZoomRegions: ZoomRegion[];
+ effectiveCursorTelemetry: CursorTelemetryPoint[];
+ effectiveShowCursor: boolean;
+ cursorTelemetrySourcePath: string | null;
+ hasCaptionsForSidecar: boolean;
+ captionSidecarPayload?: Parameters<typeof useExportRunner>[0]["captionSidecarPayload"];
+ experimentalNvidiaCudaExport: boolean;
+ nvidiaCudaExportAvailable: boolean;
+ remountPreview: () => void;
+};
+
+export function useEditorExportController(input: Input) {
+ const runner = useExportRunner({
+ videoPath: input.videoPath,
+ videoPlaybackRef: input.videoPlaybackRef,
+ isPlaying: input.isPlaying,
+ appearance: input.appearance,
+ timeline: input.timeline,
+ exportSettings: input.settings,
+ exportSession: input.session,
+ audio: input.audio,
+ smokeExportConfig: input.smokeConfig,
+ effectiveSpeedRegions: input.effectiveSpeedRegions,
+ effectiveZoomRegions: input.effectiveZoomRegions,
+ effectiveCursorTelemetry: input.effectiveCursorTelemetry,
+ effectiveShowCursor: input.effectiveShowCursor,
+ ensureSupportedMp4SourceDimensions: input.dimensions.ensureSupportedMp4SourceDimensions,
+ captionSidecarPayload: input.captionSidecarPayload,
+ experimentalNvidiaCudaExport: input.experimentalNvidiaCudaExport,
+ nvidiaCudaExportAvailable: input.nvidiaCudaExportAvailable,
+ remountPreview: input.remountPreview,
+ });
+ const dialogActions = useExportDialogActions({
+ videoPath: input.videoPath,
+ videoPlaybackRef: input.videoPlaybackRef,
+ hasCaptionsForSidecar: input.hasCaptionsForSidecar,
+ settings: input.settings,
+ session: input.session,
+ handleExport: runner.handleExport,
+ showExportSuccessToast: runner.showExportSuccessToast,
+ });
+ useSmokeExportAutomation({
+ config: input.smokeConfig,
+ cursorTelemetrySourcePath: input.cursorTelemetrySourcePath,
+ duration: input.duration,
+ error: input.error,
+ isPreviewReady: input.isPreviewReady,
+ loading: input.loading,
+ videoPath: input.videoPath,
+ videoSourcePath: input.videoSourcePath,
+ handleExport: runner.handleExport,
+ });
+ const status = useExportStatusViewModel({
+ t: input.t,
+ session: input.session,
+ settings: input.settings,
+ });
+ const openLightningIssues = useCallback(async () => {
+ await openExternalLink(
+ RECORDLY_ISSUES_URL,
+ input.t("editor.feedback.openFailed", "Failed to open link."),
+ );
+ }, [input.t]);
+
+ return { dialogActions, status, openLightningIssues };
+}
diff --git a/src/components/video-editor/export/useExportDialogActions.ts b/src/components/video-editor/export/useExportDialogActions.ts
new file mode 100644
index 00000000..94ee9405
--- /dev/null
+++ b/src/components/video-editor/export/useExportDialogActions.ts
@@ -0,0 +1,162 @@
+import { type RefObject, useCallback } from "react";
+import { toast } from "sonner";
+import type { ExportSettings } from "@/lib/exporter";
+import { resolveExportStartSettings } from "../exportStartSettings";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+import type { useExportSession } from "./useExportSession";
+import type { useExportSettings } from "./useExportSettings";
+
+type ExportSession = ReturnType<typeof useExportSession>;
+type ExportSettingsState = ReturnType<typeof useExportSettings>;
+
+type UseExportDialogActionsInput = {
+ videoPath: string | null;
+ videoPlaybackRef: RefObject<VideoPlaybackRef | null>;
+ hasCaptionsForSidecar: boolean;
+ settings: ExportSettingsState;
+ session: ExportSession;
+ handleExport: (settings: ExportSettings) => void;
+ showExportSuccessToast: (filePath: string) => void;
+};
+
+export function useExportDialogActions({
+ videoPath,
+ videoPlaybackRef,
+ hasCaptionsForSidecar,
+ settings,
+ session,
+ handleExport,
+ showExportSuccessToast,
+}: UseExportDialogActionsInput) {
+ const handleOpenExportDropdown = useCallback(() => {
+ if (!videoPath) {
+ toast.error("No video loaded");
+ return;
+ }
+
+ if (session.hasPendingExportSave) {
+ session.setShowExportDropdown(true);
+ session.setExportError(
+ "Save dialog canceled. Click Save Again to save without re-rendering.",
+ );
+ return;
+ }
+ session.setShowExportDropdown(true);
+ session.setExportProgress(null);
+ session.setExportError(null);
+ }, [videoPath, session]);
+
+ const handleStartExportFromDropdown = useCallback(() => {
+ const video = videoPlaybackRef.current?.video;
+ if (!videoPath) {
+ toast.error("No video loaded");
+ return;
+ }
+ if (!video) {
+ toast.error("Video not ready");
+ return;
+ }
+
+ const resolvedSettings = resolveExportStartSettings({
+ sourceWidth: video.videoWidth || 1920,
+ sourceHeight: video.videoHeight || 1080,
+ exportFormat: settings.exportFormat,
+ includeCaptionSidecar: hasCaptionsForSidecar && settings.includeCaptionSidecar,
+ exportEncodingMode: settings.exportEncodingMode,
+ exportQuality: settings.exportQuality,
+ mp4FrameRate: settings.mp4FrameRate,
+ exportBackendPreference: settings.exportBackendPreference,
+ exportPipelineModel: settings.exportPipelineModel,
+ gifFrameRate: settings.gifFrameRate,
+ gifLoop: settings.gifLoop,
+ gifSizePreset: settings.gifSizePreset,
+ });
+
+ session.setExportError(null);
+ session.setExportedFilePath(undefined);
+ session.setShowExportDropdown(true);
+ handleExport(resolvedSettings);
+ }, [videoPath, videoPlaybackRef, hasCaptionsForSidecar, settings, session, handleExport]);
+
+ const handleCancelExport = useCallback(() => {
+ if (!session.exporterRef.current) return;
+ session.exporterRef.current.cancel();
+ toast.info("Export canceled");
+ session.clearPendingExportSave();
+ session.setShowExportDropdown(false);
+ session.setIsExporting(false);
+ session.setExportProgress(null);
+ session.setExportError(null);
+ session.setExportedFilePath(undefined);
+ }, [session]);
+
+ const handleExportDropdownClose = useCallback(() => {
+ session.clearPendingExportSave();
+ session.setShowExportDropdown(false);
+ session.setExportProgress(null);
+ session.setExportError(null);
+ session.setExportedFilePath(undefined);
+ }, [session]);
+
+ const handleRetrySaveExport = useCallback(async () => {
+ const pendingSave = session.pendingExportSaveRef.current;
+ if (!pendingSave) return;
+
+ const saveResult = pendingSave.tempFilePath
+ ? await window.electronAPI.finalizeExportedVideo({
+ tempPath: pendingSave.tempFilePath,
+ fileName: pendingSave.fileName,
+ outputPath: null,
+ captionSidecar: pendingSave.captionSidecar,
+ })
+ : pendingSave.arrayBuffer
+ ? await window.electronAPI.saveExportedVideo(
+ pendingSave.arrayBuffer,
+ pendingSave.fileName,
+ pendingSave.captionSidecar,
+ )
+ : { success: false, message: "No pending export to save" };
+
+ if (saveResult.canceled) {
+ session.setExportError(
+ "Save dialog canceled. Click Save Again to save without re-rendering.",
+ );
+ toast.info("Save canceled. You can try again.");
+ return;
+ }
+ if (saveResult.success && saveResult.path) {
+ session.pendingExportSaveRef.current = null;
+ session.setHasPendingExportSave(false);
+ session.setExportError(null);
+ session.setExportedFilePath(saveResult.path);
+ showExportSuccessToast(saveResult.path);
+ session.setShowExportDropdown(true);
+ return;
+ }
+
+ const errorMessage = saveResult.message || "Failed to save video";
+ session.setExportError(errorMessage);
+ toast.error(errorMessage);
+ }, [session, showExportSuccessToast]);
+
+ const revealExportedFile = useCallback(async () => {
+ if (!session.exportedFilePath) return;
+ try {
+ const result = await window.electronAPI.revealInFolder(session.exportedFilePath);
+ if (!result.success) {
+ toast.error(result.error || result.message || "Failed to reveal item in folder.");
+ }
+ } catch (error) {
+ toast.error(`Failed to reveal item in folder: ${String(error)}`);
+ }
+ }, [session.exportedFilePath]);
+
+ return {
+ handleOpenExportDropdown,
+ handleStartExportFromDropdown,
+ handleCancelExport,
+ handleExportDropdownClose,
+ handleRetrySaveExport,
+ revealExportedFile,
+ };
+}
diff --git a/src/components/video-editor/export/useExportDimensions.ts b/src/components/video-editor/export/useExportDimensions.ts
new file mode 100644
index 00000000..f7be627f
--- /dev/null
+++ b/src/components/video-editor/export/useExportDimensions.ts
@@ -0,0 +1,155 @@
+import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ calculateOutputDimensions,
+ DEFAULT_MP4_CODEC,
+ type ExportMp4FrameRate,
+ GIF_SIZE_PRESETS,
+ type GifSizePreset,
+ probeSupportedMp4Dimensions,
+ type SupportedMp4Dimensions,
+} from "@/lib/exporter";
+import { getSourceQualityBitrate } from "@/lib/exporter/exportBitrate";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import {
+ calculateMp4ExportDimensions,
+ calculateMp4SourceDimensions,
+ type Mp4SupportProbeSnapshot,
+ shouldDebounceMp4SupportProbe,
+} from "../exportDimensions";
+import type { CropRegion } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+
+const MP4_CROP_PROBE_DEBOUNCE_MS = 200;
+
+type Input = {
+ videoPlaybackRef: RefObject<VideoPlaybackRef | null>;
+ isPreviewReady: boolean;
+ aspectRatio: AspectRatio;
+ cropRegion: CropRegion;
+ mp4FrameRate: ExportMp4FrameRate;
+ gifSizePreset: GifSizePreset;
+};
+
+export function useExportDimensions({
+ videoPlaybackRef,
+ isPreviewReady,
+ aspectRatio,
+ cropRegion,
+ mp4FrameRate,
+ gifSizePreset,
+}: Input) {
+ const [supportedSourceDimensions, setSupportedSourceDimensions] =
+ useState<SupportedMp4Dimensions>({
+ width: 1920,
+ height: 1080,
+ capped: false,
+ encoderPath: null,
+ });
+ const requestRef = useRef(0);
+ const previousProbeRef = useRef<Mp4SupportProbeSnapshot | null>(null);
+ const gifOutputDimensions = useMemo(
+ () =>
+ calculateOutputDimensions(
+ videoPlaybackRef.current?.video?.videoWidth || 1920,
+ videoPlaybackRef.current?.video?.videoHeight || 1080,
+ gifSizePreset,
+ GIF_SIZE_PRESETS,
+ ),
+ [gifSizePreset, videoPlaybackRef],
+ );
+ const sourceDimensions = useMemo(() => {
+ const video = isPreviewReady ? videoPlaybackRef.current?.video : null;
+ return { width: video?.videoWidth || 1920, height: video?.videoHeight || 1080 };
+ }, [isPreviewReady, videoPlaybackRef]);
+ const desiredSourceDimensions = useMemo(
+ () =>
+ calculateMp4SourceDimensions(
+ sourceDimensions.width,
+ sourceDimensions.height,
+ aspectRatio,
+ cropRegion,
+ ),
+ [sourceDimensions, aspectRatio, cropRegion],
+ );
+ const outputDimensions = useMemo(() => {
+ const width = supportedSourceDimensions.encoderPath
+ ? supportedSourceDimensions.width
+ : desiredSourceDimensions.width;
+ const height = supportedSourceDimensions.encoderPath
+ ? supportedSourceDimensions.height
+ : desiredSourceDimensions.height;
+ return {
+ medium: calculateMp4ExportDimensions(width, height, "medium"),
+ good: calculateMp4ExportDimensions(width, height, "good"),
+ high: calculateMp4ExportDimensions(width, height, "high"),
+ source: calculateMp4ExportDimensions(width, height, "source"),
+ };
+ }, [supportedSourceDimensions, desiredSourceDimensions]);
+ const ensureSupportedSourceDimensions = useCallback(
+ async (frameRate: ExportMp4FrameRate) => {
+ const result = await probeSupportedMp4Dimensions({
+ width: desiredSourceDimensions.width,
+ height: desiredSourceDimensions.height,
+ frameRate,
+ codec: DEFAULT_MP4_CODEC,
+ getBitrate: getSourceQualityBitrate,
+ });
+ if (!result.encoderPath) {
+ throw new Error(
+ `Video encoding not supported on this system. Tried codec ${DEFAULT_MP4_CODEC} at ${frameRate} FPS up to ${desiredSourceDimensions.width}x${desiredSourceDimensions.height}.`,
+ );
+ }
+ return result;
+ },
+ [desiredSourceDimensions],
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ const requestId = ++requestRef.current;
+ const snapshot: Mp4SupportProbeSnapshot = {
+ sourceWidth: sourceDimensions.width,
+ sourceHeight: sourceDimensions.height,
+ targetWidth: desiredSourceDimensions.width,
+ targetHeight: desiredSourceDimensions.height,
+ aspectRatio,
+ frameRate: mp4FrameRate,
+ };
+ const shouldDebounce = shouldDebounceMp4SupportProbe(previousProbeRef.current, snapshot);
+ previousProbeRef.current = snapshot;
+ const fallback = { ...desiredSourceDimensions, capped: false, encoderPath: null };
+ setSupportedSourceDimensions(fallback);
+ const runProbe = () => {
+ void ensureSupportedSourceDimensions(mp4FrameRate)
+ .then((result) => {
+ if (!cancelled && requestId === requestRef.current)
+ setSupportedSourceDimensions(result);
+ })
+ .catch(() => {
+ if (!cancelled && requestId === requestRef.current)
+ setSupportedSourceDimensions(fallback);
+ });
+ };
+ const timeoutId = shouldDebounce
+ ? window.setTimeout(runProbe, MP4_CROP_PROBE_DEBOUNCE_MS)
+ : null;
+ if (timeoutId === null) runProbe();
+ return () => {
+ cancelled = true;
+ if (timeoutId !== null) window.clearTimeout(timeoutId);
+ };
+ }, [
+ sourceDimensions,
+ desiredSourceDimensions,
+ aspectRatio,
+ mp4FrameRate,
+ ensureSupportedSourceDimensions,
+ ]);
+
+ return {
+ gifOutputDimensions,
+ mp4OutputDimensions: outputDimensions,
+ supportedMp4SourceDimensions: supportedSourceDimensions,
+ ensureSupportedMp4SourceDimensions: ensureSupportedSourceDimensions,
+ };
+}
diff --git a/src/components/video-editor/export/useExportRunner.ts b/src/components/video-editor/export/useExportRunner.ts
new file mode 100644
index 00000000..89bbb4e0
--- /dev/null
+++ b/src/components/video-editor/export/useExportRunner.ts
@@ -0,0 +1,500 @@
+import { useCallback, useRef } from "react";
+import { toast } from "sonner";
+import {
+ DEFAULT_MP4_CODEC,
+ type ExportSettings,
+ GifExporter,
+ ModernVideoExporter,
+ VideoExporter,
+} from "@/lib/exporter";
+import { getMp4ExportBitrate } from "@/lib/exporter/exportBitrate";
+import { calculateMp4ExportDimensions } from "../exportDimensions";
+import { resolveMp4ExportRouting } from "../mp4ExportRouting";
+import { resolveMp4ExportSettings } from "../mp4ExportSettings";
+import { createSmokeExportProgressSampler } from "../smokeExportProgress";
+import { buildExportRenderOptions } from "./buildExportRenderOptions";
+import {
+ type PendingExportSave,
+ saveExportBlob,
+ writeSmokeExportReport,
+} from "./exportPersistence";
+import {
+ type ExportRunnerInput,
+ showExportErrorToast,
+ useExportSuccessToast,
+} from "./exportRunnerSupport";
+
+export function useExportRunner(input: ExportRunnerInput) {
+ const inputRef = useRef(input);
+ inputRef.current = input;
+ const showExportSuccessToast = useExportSuccessToast();
+
+ const handleExport = useCallback(
+ async (settings: ExportSettings) => {
+ const {
+ videoPath,
+ videoPlaybackRef,
+ isPlaying,
+ appearance,
+ timeline,
+ exportSettings,
+ exportSession,
+ audio,
+ smokeExportConfig,
+ effectiveSpeedRegions,
+ effectiveZoomRegions,
+ effectiveCursorTelemetry,
+ effectiveShowCursor,
+ ensureSupportedMp4SourceDimensions,
+ captionSidecarPayload,
+ experimentalNvidiaCudaExport,
+ nvidiaCudaExportAvailable,
+ remountPreview,
+ } = inputRef.current;
+ const { shadowIntensity, padding } = appearance;
+ const { audioRegions, clipRegions, selectedClipId } = timeline;
+ const {
+ exportQuality,
+ exportEncodingMode,
+ exportBackendPreference,
+ exportPipelineModel,
+ mp4FrameRate,
+ } = exportSettings;
+ const {
+ setIsExporting,
+ setExportProgress,
+ setExportError,
+ setShowExportDropdown,
+ setExportedFilePath,
+ setHasPendingExportSave,
+ exporterRef,
+ pendingExportSaveRef,
+ clearPendingExportSave,
+ markExportAsSaving,
+ } = exportSession;
+ 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);
+ clearPendingExportSave();
+ const smokeExportStartedAt = smokeExportConfig.enabled ? performance.now() : null;
+
+ let keepExportDialogOpen = false;
+
+ try {
+ const wasPlaying = isPlaying;
+ const restoreTime = video.currentTime;
+ if (wasPlaying) {
+ videoPlaybackRef.current?.pause();
+ }
+
+ // 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;
+ const effectiveShadowIntensity =
+ smokeExportConfig.enabled && smokeExportConfig.shadowIntensity !== undefined
+ ? smokeExportConfig.shadowIntensity
+ : shadowIntensity;
+ const smokeProgressSampler = createSmokeExportProgressSampler({
+ enabled: smokeExportConfig.enabled,
+ startedAtMs: smokeExportStartedAt,
+ });
+ const smokeProgressSamples = smokeProgressSampler.samples;
+ const recordSmokeProgress = smokeProgressSampler.record;
+
+ 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,
+ ...buildExportRenderOptions({
+ appearance,
+ timeline,
+ effectiveSpeedRegions,
+ effectiveZoomRegions,
+ effectiveCursorTelemetry,
+ effectiveShowCursor,
+ previewWidth,
+ previewHeight,
+ shadowIntensity: effectiveShadowIntensity,
+ onProgress: (progress) => {
+ recordSmokeProgress(progress);
+ setExportProgress(progress);
+ },
+ }),
+ videoPadding: padding,
+ maxDecodeQueue: smokeExportConfig.maxDecodeQueue,
+ maxPendingFrames: smokeExportConfig.maxPendingFrames,
+ });
+
+ exporterRef.current = gifExporter as unknown as VideoExporter;
+ const result = await gifExporter.export();
+
+ if (result.success && result.blob) {
+ const timestamp = Date.now();
+ const fileName = `export-${timestamp}.gif`;
+ markExportAsSaving();
+
+ const { saveResult, pendingSave } = await saveExportBlob(
+ result.blob,
+ fileName,
+ smokeExportConfig.enabled ? smokeExportConfig.outputPath : null,
+ );
+
+ if (saveResult.canceled) {
+ pendingExportSaveRef.current = pendingSave;
+ setHasPendingExportSave(true);
+ setExportError(
+ "Save dialog canceled. Click Save Again to save without re-rendering.",
+ );
+ toast.info("Save canceled. You can save again without re-exporting.");
+ keepExportDialogOpen = true;
+ } else if (saveResult.success && saveResult.path) {
+ if (smokeExportStartedAt !== null) {
+ console.log(
+ `[smoke-export] Completed in ${Math.round(performance.now() - smokeExportStartedAt)}ms (${saveResult.path})`,
+ );
+ }
+ showExportSuccessToast(saveResult.path);
+ setExportedFilePath(saveResult.path);
+ if (smokeExportConfig.enabled) {
+ window.close();
+ return;
+ }
+ } else {
+ setExportError(saveResult.message || "Failed to save GIF");
+ toast.error(saveResult.message || "Failed to save GIF");
+ if (smokeExportConfig.enabled) {
+ window.close();
+ return;
+ }
+ }
+ } else {
+ setExportError(result.error || "GIF export failed");
+ toast.error(result.error || "GIF export failed");
+ if (smokeExportConfig.enabled) {
+ window.close();
+ return;
+ }
+ }
+ } else {
+ // MP4 Export
+ const { quality, encodingMode, selectedMp4FrameRate } =
+ resolveMp4ExportSettings({
+ smokeExportConfig: {
+ enabled: smokeExportConfig.enabled,
+ quality: smokeExportConfig.quality,
+ encodingMode: smokeExportConfig.encodingMode,
+ fps: smokeExportConfig.fps,
+ },
+ settings,
+ exportQuality,
+ exportEncodingMode,
+ mp4FrameRate,
+ });
+ const {
+ pipelineModel,
+ useExperimentalNativeExport,
+ useExperimentalNvidiaCudaExport,
+ backendPreference,
+ } = resolveMp4ExportRouting({
+ smokeExportConfig: {
+ enabled: smokeExportConfig.enabled,
+ pipelineModel: smokeExportConfig.pipelineModel,
+ useNativeExport: smokeExportConfig.useNativeExport,
+ backendPreference: smokeExportConfig.backendPreference,
+ },
+ settings,
+ exportPipelineModel,
+ exportBackendPreference,
+ experimentalNvidiaCudaExport,
+ nvidiaCudaExportAvailable,
+ });
+ const supportedSourceDimensions =
+ await ensureSupportedMp4SourceDimensions(selectedMp4FrameRate);
+ const { width: exportWidth, height: exportHeight } =
+ calculateMp4ExportDimensions(
+ supportedSourceDimensions.width,
+ supportedSourceDimensions.height,
+ quality,
+ );
+ const bitrate = getMp4ExportBitrate({
+ width: exportWidth,
+ height: exportHeight,
+ frameRate: selectedMp4FrameRate,
+ quality,
+ encodingMode,
+ useModernNativeStaticLayout: useExperimentalNativeExport,
+ });
+ const sourceAudioTrackSettingsForExport =
+ selectedClipId !== null
+ ? audio.selectedClipSourceAudioTrackSettings
+ : audio.activeSourceAudioTrackSettings;
+
+ const exporterConfig = {
+ videoUrl: videoPath,
+ width: exportWidth,
+ height: exportHeight,
+ frameRate: selectedMp4FrameRate,
+ bitrate,
+ codec: DEFAULT_MP4_CODEC,
+ encodingMode,
+ preferredEncoderPath: supportedSourceDimensions.encoderPath,
+ preferredRenderBackend: smokeExportConfig.renderBackend,
+ experimentalNativeExport: useExperimentalNativeExport,
+ experimentalNvidiaCudaExport: useExperimentalNvidiaCudaExport,
+ maxEncodeQueue: smokeExportConfig.maxEncodeQueue,
+ maxDecodeQueue: smokeExportConfig.maxDecodeQueue,
+ maxPendingFrames: smokeExportConfig.maxPendingFrames,
+ ...buildExportRenderOptions({
+ appearance,
+ timeline,
+ effectiveSpeedRegions,
+ effectiveZoomRegions,
+ effectiveCursorTelemetry,
+ effectiveShowCursor,
+ previewWidth,
+ previewHeight,
+ shadowIntensity: effectiveShadowIntensity,
+ onProgress: (progress) => {
+ recordSmokeProgress(progress);
+ setExportProgress(progress);
+ },
+ }),
+ audioRegions,
+ clipRegions,
+ sourceAudioFallbackPaths: audio.sourceAudioFallbackPaths,
+ sourceAudioFallbackStartDelayMsByPath:
+ audio.sourceAudioFallbackStartDelayMsByPath,
+ sourceAudioTrackSettings: sourceAudioTrackSettingsForExport,
+ };
+
+ const exporter =
+ pipelineModel === "modern"
+ ? new ModernVideoExporter({
+ ...exporterConfig,
+ backendPreference,
+ })
+ : new VideoExporter(exporterConfig);
+
+ exporterRef.current = exporter;
+ const result = await exporter.export();
+ const smokeExportElapsedMs =
+ smokeExportStartedAt !== null
+ ? Math.round(performance.now() - smokeExportStartedAt)
+ : undefined;
+
+ if (result.success && (result.blob || result.tempFilePath)) {
+ const timestamp = Date.now();
+ const fileName = `export-${timestamp}.mp4`;
+ const sidecarForThisExport =
+ settings.includeCaptionSidecar && captionSidecarPayload
+ ? captionSidecarPayload
+ : undefined;
+ markExportAsSaving();
+
+ let saveResult: {
+ success: boolean;
+ path?: string;
+ message?: string;
+ canceled?: boolean;
+ };
+ let pendingOnCancel: PendingExportSave;
+
+ if (result.tempFilePath) {
+ // Preferred path: main process already holds the finished MP4 on
+ // disk, so we just ask it to move the temp file into place. This
+ // avoids ever allocating a multi-GiB ArrayBuffer in the renderer.
+ saveResult = await window.electronAPI.finalizeExportedVideo({
+ tempPath: result.tempFilePath,
+ fileName,
+ outputPath:
+ smokeExportConfig.enabled && smokeExportConfig.outputPath
+ ? smokeExportConfig.outputPath
+ : null,
+ captionSidecar: sidecarForThisExport,
+ });
+ pendingOnCancel = {
+ fileName,
+ tempFilePath: result.tempFilePath,
+ captionSidecar: sidecarForThisExport,
+ };
+ } else if (result.blob) {
+ // Legacy fallback: some export paths still surface a Blob, but in
+ // Electron we stream it into a temp file first so save/finalize
+ // never requires a giant renderer ArrayBuffer.
+ const blobSave = await saveExportBlob(
+ result.blob,
+ fileName,
+ smokeExportConfig.enabled ? smokeExportConfig.outputPath : null,
+ sidecarForThisExport,
+ );
+ saveResult = blobSave.saveResult;
+ pendingOnCancel = blobSave.pendingSave;
+ } else {
+ saveResult = { success: false, message: "Export produced no output" };
+ pendingOnCancel = { fileName };
+ }
+
+ if (saveResult.canceled) {
+ if (smokeExportConfig.enabled) {
+ await writeSmokeExportReport(smokeExportConfig.outputPath, {
+ success: false,
+ phase: "save",
+ format: "mp4",
+ pipelineModel,
+ backendPreference,
+ encodingMode,
+ shadowIntensity: effectiveShadowIntensity,
+ elapsedMs: smokeExportElapsedMs,
+ error: "Save canceled",
+ progressSamples: smokeProgressSamples,
+ metrics: result.metrics,
+ });
+ }
+ pendingExportSaveRef.current = pendingOnCancel;
+ setHasPendingExportSave(true);
+ setExportError(
+ "Save dialog canceled. Click Save Again to save without re-rendering.",
+ );
+ toast.info("Save canceled. You can save again without re-exporting.");
+ keepExportDialogOpen = true;
+ } else if (saveResult.success && saveResult.path) {
+ if (smokeExportConfig.enabled) {
+ await writeSmokeExportReport(smokeExportConfig.outputPath, {
+ success: true,
+ phase: "saved",
+ format: "mp4",
+ pipelineModel,
+ backendPreference,
+ encodingMode,
+ shadowIntensity: effectiveShadowIntensity,
+ elapsedMs: smokeExportElapsedMs,
+ outputPath: saveResult.path,
+ progressSamples: smokeProgressSamples,
+ metrics: result.metrics,
+ });
+ }
+ if (smokeExportStartedAt !== null) {
+ console.log(
+ `[smoke-export] Completed in ${Math.round(performance.now() - smokeExportStartedAt)}ms (${saveResult.path})`,
+ );
+ }
+ showExportSuccessToast(saveResult.path);
+ setExportedFilePath(saveResult.path);
+ if (smokeExportConfig.enabled) {
+ window.close();
+ return;
+ }
+ } else {
+ if (smokeExportConfig.enabled) {
+ await writeSmokeExportReport(smokeExportConfig.outputPath, {
+ success: false,
+ phase: "save",
+ format: "mp4",
+ pipelineModel,
+ backendPreference,
+ encodingMode,
+ shadowIntensity: effectiveShadowIntensity,
+ elapsedMs: smokeExportElapsedMs,
+ error: saveResult.message || "Failed to save video",
+ progressSamples: smokeProgressSamples,
+ metrics: result.metrics,
+ });
+ }
+ setExportError(saveResult.message || "Failed to save video");
+ showExportErrorToast(saveResult.message || "Failed to save video");
+ // Keep the pending-save entry so the user can retry without
+ // re-rendering. The temp file is still on disk (the main
+ // process only moves/deletes it on success) and the
+ // ArrayBuffer fallback still references its in-memory blob.
+ if (pendingOnCancel.tempFilePath || pendingOnCancel.arrayBuffer) {
+ pendingExportSaveRef.current = pendingOnCancel;
+ setHasPendingExportSave(true);
+ keepExportDialogOpen = true;
+ }
+ if (smokeExportConfig.enabled) {
+ window.close();
+ return;
+ }
+ }
+ } else {
+ if (smokeExportConfig.enabled) {
+ await writeSmokeExportReport(smokeExportConfig.outputPath, {
+ success: false,
+ phase: "export",
+ format: "mp4",
+ pipelineModel,
+ backendPreference,
+ encodingMode,
+ shadowIntensity: effectiveShadowIntensity,
+ elapsedMs: smokeExportElapsedMs,
+ error: result.error || "Export failed",
+ progressSamples: smokeProgressSamples,
+ metrics: result.metrics,
+ });
+ }
+ setExportError(result.error || "Export failed");
+ showExportErrorToast(result.error || "Export failed");
+ keepExportDialogOpen = true;
+ if (smokeExportConfig.enabled) {
+ window.close();
+ return;
+ }
+ }
+ }
+
+ if (wasPlaying) {
+ videoPlaybackRef.current?.play();
+ } else {
+ video.currentTime = restoreTime;
+ }
+ } catch (error) {
+ console.error("Export error:", error);
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
+ if (smokeExportConfig.enabled) {
+ await writeSmokeExportReport(smokeExportConfig.outputPath, {
+ success: false,
+ phase: "exception",
+ format: settings.format,
+ elapsedMs:
+ smokeExportStartedAt !== null
+ ? Math.round(performance.now() - smokeExportStartedAt)
+ : undefined,
+ error: errorMessage,
+ });
+ }
+ setExportError(errorMessage);
+ showExportErrorToast(`Export failed: ${errorMessage}`);
+ keepExportDialogOpen = true;
+ if (smokeExportConfig.enabled) {
+ window.close();
+ }
+ } finally {
+ setIsExporting(false);
+ exporterRef.current = null;
+ setShowExportDropdown(keepExportDialogOpen);
+ remountPreview();
+ }
+ },
+ [showExportSuccessToast],
+ );
+
+ return { handleExport, showExportSuccessToast };
+}
diff --git a/src/components/video-editor/export/useExportSession.ts b/src/components/video-editor/export/useExportSession.ts
new file mode 100644
index 00000000..b9c92d4e
--- /dev/null
+++ b/src/components/video-editor/export/useExportSession.ts
@@ -0,0 +1,49 @@
+import { useCallback, useRef, useState } from "react";
+import type { ExportProgress } from "@/lib/exporter";
+import { resolveSavingExportProgress } from "../exportProgressState";
+import type { PendingExportSave } from "./exportPersistence";
+
+export type CancelableExporter = { cancel(): void };
+
+export function useExportSession() {
+ const [isExporting, setIsExporting] = useState(false);
+ const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);
+ const [exportError, setExportError] = useState<string | null>(null);
+ const [showExportDropdown, setShowExportDropdown] = useState(false);
+ const [exportedFilePath, setExportedFilePath] = useState<string>();
+ const [hasPendingExportSave, setHasPendingExportSave] = useState(false);
+ const exporterRef = useRef<CancelableExporter | null>(null);
+ const pendingExportSaveRef = useRef<PendingExportSave | null>(null);
+
+ const clearPendingExportSave = useCallback(() => {
+ const pendingSave = pendingExportSaveRef.current;
+ pendingExportSaveRef.current = null;
+ setHasPendingExportSave(false);
+ if (pendingSave?.tempFilePath && typeof window !== "undefined") {
+ void window.electronAPI.discardExportedTemp?.(pendingSave.tempFilePath);
+ }
+ }, []);
+
+ const markExportAsSaving = useCallback(() => {
+ setExportProgress(resolveSavingExportProgress);
+ }, []);
+
+ return {
+ isExporting,
+ setIsExporting,
+ exportProgress,
+ setExportProgress,
+ exportError,
+ setExportError,
+ showExportDropdown,
+ setShowExportDropdown,
+ exportedFilePath,
+ setExportedFilePath,
+ hasPendingExportSave,
+ setHasPendingExportSave,
+ exporterRef,
+ pendingExportSaveRef,
+ clearPendingExportSave,
+ markExportAsSaving,
+ };
+}
diff --git a/src/components/video-editor/export/useExportSettings.ts b/src/components/video-editor/export/useExportSettings.ts
new file mode 100644
index 00000000..7cd88330
--- /dev/null
+++ b/src/components/video-editor/export/useExportSettings.ts
@@ -0,0 +1,74 @@
+import { useMemo, useState } from "react";
+import type {
+ ExportBackendPreference,
+ ExportEncodingMode,
+ ExportFormat,
+ ExportMp4FrameRate,
+ ExportPipelineModel,
+ ExportQuality,
+ GifFrameRate,
+ GifSizePreset,
+} from "@/lib/exporter";
+import type { EditorPreferences } from "../editorPreferences";
+import type { CaptionCue } from "../types";
+
+const DEFAULT_MP4_EXPORT_FRAME_RATE: ExportMp4FrameRate = 30;
+
+export function useExportSettings(preferences: EditorPreferences, autoCaptions: CaptionCue[]) {
+ const [includeCaptionSidecar, setIncludeCaptionSidecar] = useState(false);
+ const [exportQuality, setExportQuality] = useState<ExportQuality>(preferences.exportQuality);
+ const [exportEncodingMode, setExportEncodingMode] = useState<ExportEncodingMode>(
+ preferences.exportEncodingMode,
+ );
+ const [exportBackendPreference, setExportBackendPreference] = useState<ExportBackendPreference>(
+ preferences.exportBackendPreference,
+ );
+ const [exportPipelineModel, setExportPipelineModel] = useState<ExportPipelineModel>(
+ preferences.exportPipelineModel,
+ );
+ const [mp4FrameRate, setMp4FrameRate] = useState<ExportMp4FrameRate>(
+ preferences.mp4FrameRate ?? DEFAULT_MP4_EXPORT_FRAME_RATE,
+ );
+ const [exportFormat, setExportFormat] = useState<ExportFormat>(preferences.exportFormat);
+ const [gifFrameRate, setGifFrameRate] = useState<GifFrameRate>(preferences.gifFrameRate);
+ const [gifLoop, setGifLoop] = useState(preferences.gifLoop);
+ const [gifSizePreset, setGifSizePreset] = useState<GifSizePreset>(preferences.gifSizePreset);
+ const captionSidecarCues = useMemo(
+ () =>
+ autoCaptions
+ .filter(
+ (cue) =>
+ Number.isFinite(cue.startMs) &&
+ Number.isFinite(cue.endMs) &&
+ cue.endMs > cue.startMs &&
+ typeof cue.text === "string" &&
+ cue.text.trim().length > 0,
+ )
+ .map(({ startMs, endMs, text }) => ({ startMs, endMs, text })),
+ [autoCaptions],
+ );
+
+ return {
+ includeCaptionSidecar,
+ setIncludeCaptionSidecar,
+ exportQuality,
+ setExportQuality,
+ exportEncodingMode,
+ setExportEncodingMode,
+ exportBackendPreference,
+ setExportBackendPreference,
+ exportPipelineModel,
+ setExportPipelineModel,
+ mp4FrameRate,
+ setMp4FrameRate,
+ exportFormat,
+ setExportFormat,
+ gifFrameRate,
+ setGifFrameRate,
+ gifLoop,
+ setGifLoop,
+ gifSizePreset,
+ setGifSizePreset,
+ captionSidecarCues,
+ };
+}
diff --git a/src/components/video-editor/export/useExportStatusViewModel.ts b/src/components/video-editor/export/useExportStatusViewModel.ts
new file mode 100644
index 00000000..1af90e92
--- /dev/null
+++ b/src/components/video-editor/export/useExportStatusViewModel.ts
@@ -0,0 +1,58 @@
+import type { useI18n } from "@/contexts/I18nContext";
+import { resolveExportStatusModel } from "../exportStatusModel";
+import type { useExportSession } from "./useExportSession";
+import type { useExportSettings } from "./useExportSettings";
+
+type Input = {
+ t: ReturnType<typeof useI18n>["t"];
+ session: ReturnType<typeof useExportSession>;
+ settings: ReturnType<typeof useExportSettings>;
+};
+
+export function useExportStatusViewModel({ t, session, settings }: Input) {
+ const status = resolveExportStatusModel({
+ isExporting: session.isExporting,
+ exportProgress: session.exportProgress,
+ exportFormat: settings.exportFormat,
+ exportPipelineModel: settings.exportPipelineModel,
+ });
+ const exportRenderSpeedLabel = status.renderSpeedFps
+ ? t("editor.exportStatus.renderSpeed", "Render speed {{fps}} FPS", {
+ fps: status.renderSpeedFps,
+ })
+ : null;
+ const progress = session.exportProgress;
+ const exportPercentLabel = progress
+ ? status.isExportPreparing
+ ? t("editor.exportStatus.preparing", "Preparing export...")
+ : status.isExportSaving
+ ? t("editor.exportStatus.saving", "Opening save dialog...")
+ : status.isRenderingAudio
+ ? t("editor.exportStatus.renderingAudio", "Rendering audio {{percent}}%", {
+ percent: Math.round((progress.audioProgress ?? 0) * 100),
+ })
+ : status.isExportFinalizing
+ ? settings.exportFormat === "mp4" &&
+ settings.exportPipelineModel === "modern"
+ ? status.isExportFinalSaveIndeterminate
+ ? t(
+ "editor.exportStatus.muxingAndSaving",
+ "Muxing audio and saving file...",
+ )
+ : t(
+ "editor.exportStatus.muxingAndSavingPercent",
+ "Muxing and saving {{percent}}%",
+ { percent: status.exportFinalizingPercent ?? 100 },
+ )
+ : t(
+ "editor.exportStatus.finalizingPercent",
+ "Finalizing {{percent}}%",
+ { percent: status.exportFinalizingPercent ?? 100 },
+ )
+ : t("editor.exportStatus.completePercent", "{{percent}}% complete", {
+ percent: Math.round(progress.percentage),
+ })
+ : t("editor.exportStatus.preparing", "Preparing export...");
+
+ return { ...status, exportRenderSpeedLabel, exportPercentLabel };
+}
diff --git a/src/components/video-editor/export/useSmokeExportAutomation.ts b/src/components/video-editor/export/useSmokeExportAutomation.ts
new file mode 100644
index 00000000..a7830e5e
--- /dev/null
+++ b/src/components/video-editor/export/useSmokeExportAutomation.ts
@@ -0,0 +1,108 @@
+import { useEffect, useRef } from "react";
+import type { ExportSettings } from "@/lib/exporter";
+import type { getSmokeExportConfig } from "../smokeExportConfig";
+import { writeSmokeExportReport } from "./exportPersistence";
+
+const SMOKE_EXPORT_READY_TIMEOUT_MS = 30_000;
+
+type UseSmokeExportAutomationInput = {
+ config: ReturnType<typeof getSmokeExportConfig>;
+ cursorTelemetrySourcePath: string | null;
+ duration: number;
+ error: string | null;
+ isPreviewReady: boolean;
+ loading: boolean;
+ videoPath: string | null;
+ videoSourcePath: string | null;
+ handleExport: (settings: ExportSettings) => void;
+};
+
+export function useSmokeExportAutomation({
+ config,
+ cursorTelemetrySourcePath,
+ duration,
+ error,
+ isPreviewReady,
+ loading,
+ videoPath,
+ videoSourcePath,
+ handleExport,
+}: UseSmokeExportAutomationInput) {
+ const startedRef = useRef(false);
+ const readyStateRef = useRef<Record<string, unknown>>({});
+
+ useEffect(() => {
+ readyStateRef.current = {
+ cursorTelemetrySourcePath,
+ duration,
+ hasVideoPath: Boolean(videoPath),
+ isPreviewReady,
+ loading,
+ projectPath: config.projectPath ?? null,
+ videoSourcePath,
+ };
+ }, [
+ cursorTelemetrySourcePath,
+ duration,
+ isPreviewReady,
+ loading,
+ config.projectPath,
+ videoPath,
+ videoSourcePath,
+ ]);
+
+ useEffect(() => {
+ if (!config.enabled) return;
+ const timeoutId = window.setTimeout(() => {
+ if (startedRef.current) return;
+ startedRef.current = true;
+ void writeSmokeExportReport(config.outputPath, {
+ success: false,
+ phase: "ready",
+ error: `Smoke export did not become ready within ${SMOKE_EXPORT_READY_TIMEOUT_MS}ms.`,
+ readyState: readyStateRef.current,
+ }).finally(() => window.close());
+ }, SMOKE_EXPORT_READY_TIMEOUT_MS);
+ return () => window.clearTimeout(timeoutId);
+ }, [config.enabled, config.outputPath]);
+
+ useEffect(() => {
+ if (!config.enabled || startedRef.current) return;
+ if (error) {
+ startedRef.current = true;
+ console.error(`[smoke-export] ${error}`);
+ void writeSmokeExportReport(config.outputPath, {
+ success: false,
+ phase: "load",
+ error,
+ readyState: readyStateRef.current,
+ }).finally(() => window.close());
+ return;
+ }
+ if (!videoPath || loading || !isPreviewReady || duration <= 0) return;
+ if (
+ config.projectPath &&
+ videoSourcePath &&
+ cursorTelemetrySourcePath !== videoSourcePath
+ ) {
+ return;
+ }
+
+ startedRef.current = true;
+ void handleExport({
+ format: "mp4",
+ quality: "good",
+ encodingMode: config.encodingMode ?? "balanced",
+ });
+ }, [
+ cursorTelemetrySourcePath,
+ error,
+ handleExport,
+ isPreviewReady,
+ loading,
+ duration,
+ config,
+ videoPath,
+ videoSourcePath,
+ ]);
+}
diff --git a/src/components/video-editor/hooks/useAnnotationRegionCommands.ts b/src/components/video-editor/hooks/useAnnotationRegionCommands.ts
new file mode 100644
index 00000000..e6cd9942
--- /dev/null
+++ b/src/components/video-editor/hooks/useAnnotationRegionCommands.ts
@@ -0,0 +1,179 @@
+import type { Span } from "dnd-timeline";
+import { type Dispatch, type MutableRefObject, type SetStateAction, useCallback } from "react";
+import {
+ type AnnotationRegion,
+ DEFAULT_ANNOTATION_POSITION,
+ DEFAULT_ANNOTATION_SIZE,
+ DEFAULT_ANNOTATION_STYLE,
+ DEFAULT_FIGURE_DATA,
+ type FigureData,
+} from "../types";
+
+interface UseAnnotationRegionCommandsParams {
+ setAnnotationRegions: Dispatch<SetStateAction<AnnotationRegion[]>>;
+ selectedAnnotationId: string | null;
+ setSelectedAnnotationId: Dispatch<SetStateAction<string | null>>;
+ setSelectedZoomId: Dispatch<SetStateAction<string | null>>;
+ nextAnnotationIdRef: MutableRefObject<number>;
+ nextAnnotationZIndexRef: MutableRefObject<number>;
+}
+
+export function useAnnotationRegionCommands({
+ setAnnotationRegions,
+ selectedAnnotationId,
+ setSelectedAnnotationId,
+ setSelectedZoomId,
+ nextAnnotationIdRef,
+ nextAnnotationZIndexRef,
+}: UseAnnotationRegionCommandsParams) {
+ const handleAnnotationAdded = useCallback(
+ (span: Span, trackIndex = 0) => {
+ const id = `annotation-${nextAnnotationIdRef.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: nextAnnotationZIndexRef.current++,
+ trackIndex,
+ };
+ setAnnotationRegions((current) => [...current, newRegion]);
+ setSelectedAnnotationId(id);
+ setSelectedZoomId(null);
+ },
+ [
+ nextAnnotationIdRef,
+ nextAnnotationZIndexRef,
+ setAnnotationRegions,
+ setSelectedAnnotationId,
+ setSelectedZoomId,
+ ],
+ );
+
+ const handleAnnotationSpanChange = useCallback(
+ (id: string, span: Span, trackIndex?: number) => {
+ const normalizedTrackIndex =
+ typeof trackIndex === "number" && Number.isFinite(trackIndex)
+ ? Math.max(0, Math.floor(trackIndex))
+ : undefined;
+ setAnnotationRegions((current) =>
+ current.map((region) =>
+ region.id === id
+ ? {
+ ...region,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ ...(normalizedTrackIndex === undefined
+ ? {}
+ : { trackIndex: normalizedTrackIndex }),
+ }
+ : region,
+ ),
+ );
+ },
+ [setAnnotationRegions],
+ );
+
+ const handleAnnotationDelete = useCallback(
+ (id: string) => {
+ setAnnotationRegions((current) => current.filter((region) => region.id !== id));
+ if (selectedAnnotationId === id) setSelectedAnnotationId(null);
+ },
+ [selectedAnnotationId, setAnnotationRegions, setSelectedAnnotationId],
+ );
+
+ const handleAnnotationContentChange = useCallback(
+ (id: string, content: string) => {
+ setAnnotationRegions((current) =>
+ current.map((region) => {
+ if (region.id !== id) return region;
+ if (region.type === "text") return { ...region, content, textContent: content };
+ if (region.type === "image")
+ return { ...region, content, imageContent: content };
+ return { ...region, content };
+ }),
+ );
+ },
+ [setAnnotationRegions],
+ );
+
+ const handleAnnotationTypeChange = useCallback(
+ (id: string, type: AnnotationRegion["type"]) => {
+ setAnnotationRegions((current) =>
+ current.map((region) => {
+ if (region.id !== id) return region;
+ const updated = { ...region, type };
+ if (type === "text") updated.content = region.textContent || "Enter text...";
+ else if (type === "image") updated.content = region.imageContent || "";
+ else if (type === "figure") {
+ updated.content = "";
+ if (!region.figureData) updated.figureData = { ...DEFAULT_FIGURE_DATA };
+ } else if (type === "blur") {
+ updated.content = "";
+ if (region.blurIntensity === undefined) updated.blurIntensity = 20;
+ }
+ return updated;
+ }),
+ );
+ },
+ [setAnnotationRegions],
+ );
+
+ const updateRegion = useCallback(
+ (id: string, patch: Partial<AnnotationRegion>) => {
+ setAnnotationRegions((current) =>
+ current.map((region) => (region.id === id ? { ...region, ...patch } : region)),
+ );
+ },
+ [setAnnotationRegions],
+ );
+
+ const handleAnnotationStyleChange = useCallback(
+ (id: string, style: Partial<AnnotationRegion["style"]>) => {
+ setAnnotationRegions((current) =>
+ current.map((region) =>
+ region.id === id ? { ...region, style: { ...region.style, ...style } } : region,
+ ),
+ );
+ },
+ [setAnnotationRegions],
+ );
+ const handleAnnotationFigureDataChange = useCallback(
+ (id: string, figureData: FigureData) => updateRegion(id, { figureData }),
+ [updateRegion],
+ );
+ const handleAnnotationBlurIntensityChange = useCallback(
+ (id: string, blurIntensity: number) => updateRegion(id, { blurIntensity }),
+ [updateRegion],
+ );
+ const handleAnnotationBlurColorChange = useCallback(
+ (id: string, blurColor: string) => updateRegion(id, { blurColor }),
+ [updateRegion],
+ );
+ const handleAnnotationPositionChange = useCallback(
+ (id: string, position: { x: number; y: number }) => updateRegion(id, { position }),
+ [updateRegion],
+ );
+ const handleAnnotationSizeChange = useCallback(
+ (id: string, size: { width: number; height: number }) => updateRegion(id, { size }),
+ [updateRegion],
+ );
+
+ return {
+ handleAnnotationAdded,
+ handleAnnotationSpanChange,
+ handleAnnotationDelete,
+ handleAnnotationContentChange,
+ handleAnnotationTypeChange,
+ handleAnnotationStyleChange,
+ handleAnnotationFigureDataChange,
+ handleAnnotationBlurIntensityChange,
+ handleAnnotationBlurColorChange,
+ handleAnnotationPositionChange,
+ handleAnnotationSizeChange,
+ };
+}
diff --git a/src/components/video-editor/hooks/useAudioRegionCommands.ts b/src/components/video-editor/hooks/useAudioRegionCommands.ts
new file mode 100644
index 00000000..c02a8f6d
--- /dev/null
+++ b/src/components/video-editor/hooks/useAudioRegionCommands.ts
@@ -0,0 +1,140 @@
+import type { Span } from "dnd-timeline";
+import { type Dispatch, type MutableRefObject, type SetStateAction, useCallback } from "react";
+import type { AudioRegion, EditorEffectSection } from "../types";
+
+interface UseAudioRegionCommandsParams {
+ setAudioRegions: Dispatch<SetStateAction<AudioRegion[]>>;
+ selectedAudioId: string | null;
+ setSelectedAudioId: Dispatch<SetStateAction<string | null>>;
+ setSelectedZoomId: Dispatch<SetStateAction<string | null>>;
+ setSelectedAnnotationId: Dispatch<SetStateAction<string | null>>;
+ setSelectedCaptionId: Dispatch<SetStateAction<string | null>>;
+ setActiveEffectSection: Dispatch<SetStateAction<EditorEffectSection>>;
+ nextAudioIdRef: MutableRefObject<number>;
+}
+
+export function useAudioRegionCommands({
+ setAudioRegions,
+ selectedAudioId,
+ setSelectedAudioId,
+ setSelectedZoomId,
+ setSelectedAnnotationId,
+ setSelectedCaptionId,
+ setActiveEffectSection,
+ nextAudioIdRef,
+}: UseAudioRegionCommandsParams) {
+ const handleSelectAudio = useCallback(
+ (id: string | null) => {
+ setSelectedAudioId(id);
+ if (id) {
+ setSelectedZoomId(null);
+ setSelectedAnnotationId(null);
+ setSelectedCaptionId(null);
+ setActiveEffectSection("audio");
+ }
+ },
+ [
+ setActiveEffectSection,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setSelectedCaptionId,
+ setSelectedZoomId,
+ ],
+ );
+
+ const handleAudioAdded = useCallback(
+ (span: Span, audioPath: string, trackIndex?: number) => {
+ const id = `audio-${nextAudioIdRef.current++}`;
+ const newRegion: AudioRegion = {
+ id,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ audioPath,
+ volume: 1,
+ normalize: false,
+ trackIndex,
+ };
+ setAudioRegions((current) => [...current, newRegion]);
+ setSelectedAudioId(id);
+ setSelectedZoomId(null);
+ setSelectedAnnotationId(null);
+ setSelectedCaptionId(null);
+ setActiveEffectSection("audio");
+ },
+ [
+ nextAudioIdRef,
+ setActiveEffectSection,
+ setAudioRegions,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setSelectedCaptionId,
+ setSelectedZoomId,
+ ],
+ );
+
+ const handleAudioSpanChange = useCallback(
+ (id: string, span: Span, trackIndex?: number) => {
+ const normalizedTrackIndex =
+ typeof trackIndex === "number" && Number.isFinite(trackIndex)
+ ? Math.max(0, Math.floor(trackIndex))
+ : undefined;
+ setAudioRegions((current) =>
+ current.map((region) =>
+ region.id === id
+ ? {
+ ...region,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ ...(normalizedTrackIndex === undefined
+ ? {}
+ : { trackIndex: normalizedTrackIndex }),
+ }
+ : region,
+ ),
+ );
+ },
+ [setAudioRegions],
+ );
+
+ const handleAudioVolumeChange = useCallback(
+ (volume: number) => {
+ if (!selectedAudioId || !Number.isFinite(volume)) return;
+ const nextVolume = Math.max(0, Math.min(1, volume));
+ setAudioRegions((current) =>
+ current.map((region) =>
+ region.id === selectedAudioId ? { ...region, volume: nextVolume } : region,
+ ),
+ );
+ },
+ [selectedAudioId, setAudioRegions],
+ );
+
+ const handleAudioDelete = useCallback(
+ (id: string) => {
+ setAudioRegions((current) => current.filter((region) => region.id !== id));
+ if (selectedAudioId === id) setSelectedAudioId(null);
+ },
+ [selectedAudioId, setAudioRegions, setSelectedAudioId],
+ );
+
+ const handleAudioNormalizeChange = useCallback(
+ (normalize: boolean) => {
+ if (!selectedAudioId) return;
+ setAudioRegions((current) =>
+ current.map((region) =>
+ region.id === selectedAudioId ? { ...region, normalize } : region,
+ ),
+ );
+ },
+ [selectedAudioId, setAudioRegions],
+ );
+
+ return {
+ handleSelectAudio,
+ handleAudioAdded,
+ handleAudioSpanChange,
+ handleAudioVolumeChange,
+ handleAudioDelete,
+ handleAudioNormalizeChange,
+ };
+}
diff --git a/src/components/video-editor/hooks/useCaptionCommands.ts b/src/components/video-editor/hooks/useCaptionCommands.ts
new file mode 100644
index 00000000..d541cbcb
--- /dev/null
+++ b/src/components/video-editor/hooks/useCaptionCommands.ts
@@ -0,0 +1,204 @@
+import type { Span } from "dnd-timeline";
+import { type Dispatch, type RefObject, type SetStateAction, useCallback } from "react";
+import {
+ type CaptionEditTarget,
+ normalizeCaptionEditText,
+ normalizeCaptionWords,
+ updateCaptionCuesForEditedTarget,
+} from "../captionEditing";
+import {
+ addCue,
+ type CaptionRetimeSpan,
+ createCaptionCue,
+ deleteCue,
+ mergeCues,
+ retimeCue,
+ splitCue,
+} from "../captionOps";
+import type { AutoCaptionSettings, CaptionCue, EditorEffectSection } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+
+interface UseCaptionCommandsParams {
+ autoCaptions: CaptionCue[];
+ setAutoCaptions: Dispatch<SetStateAction<CaptionCue[]>>;
+ setAutoCaptionSettings: Dispatch<SetStateAction<AutoCaptionSettings>>;
+ setSelectedCaptionId: Dispatch<SetStateAction<string | null>>;
+ setSelectedZoomId: Dispatch<SetStateAction<string | null>>;
+ setSelectedClipId: Dispatch<SetStateAction<string | null>>;
+ setSelectedAnnotationId: Dispatch<SetStateAction<string | null>>;
+ setSelectedAudioId: Dispatch<SetStateAction<string | null>>;
+ setActiveEffectSection: Dispatch<SetStateAction<EditorEffectSection>>;
+ videoPlaybackRef: RefObject<VideoPlaybackRef>;
+ mapSourceTimeToTimelineTime: (timeMs: number) => number;
+ mapTimelineTimeToSourceTime: (timeMs: number) => number;
+ handleSeek: (time: number, options?: { pause?: boolean }) => void;
+}
+
+export function useCaptionCommands({
+ autoCaptions,
+ setAutoCaptions,
+ setAutoCaptionSettings,
+ setSelectedCaptionId,
+ setSelectedZoomId,
+ setSelectedClipId,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setActiveEffectSection,
+ videoPlaybackRef,
+ mapSourceTimeToTimelineTime,
+ mapTimelineTimeToSourceTime,
+ handleSeek,
+}: UseCaptionCommandsParams) {
+ const handleSelectCaption = useCallback(
+ (id: string | null) => {
+ setSelectedCaptionId(id);
+ if (!id) {
+ setActiveEffectSection((section) => (section === "caption" ? "scene" : section));
+ return;
+ }
+ setActiveEffectSection("caption");
+ setSelectedZoomId(null);
+ setSelectedClipId(null);
+ setSelectedAnnotationId(null);
+ setSelectedAudioId(null);
+ const cue = autoCaptions.find((value) => value.id === id);
+ if (cue) {
+ handleSeek(mapSourceTimeToTimelineTime(cue.startMs) / 1000, { pause: true });
+ }
+ },
+ [
+ autoCaptions,
+ handleSeek,
+ mapSourceTimeToTimelineTime,
+ setActiveEffectSection,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setSelectedCaptionId,
+ setSelectedClipId,
+ setSelectedZoomId,
+ ],
+ );
+
+ const handleBeginCaptionEdit = useCallback(
+ (id: string) => {
+ videoPlaybackRef.current?.cancelCaptionEdit();
+ setSelectedCaptionId(id);
+ },
+ [setSelectedCaptionId, videoPlaybackRef],
+ );
+
+ const handleCaptionTextEdit = useCallback(
+ (id: string, text: string) => {
+ setAutoCaptions((captions) => {
+ const cue = captions.find((value) => value.id === id);
+ if (!cue) return captions;
+
+ const words = normalizeCaptionWords(cue);
+ if (words.length === 0) {
+ const normalized = normalizeCaptionEditText(text);
+ return captions.map((value) =>
+ value.id === id ? { ...value, text: normalized } : value,
+ );
+ }
+
+ const target: CaptionEditTarget = {
+ id: cue.id,
+ startMs: cue.startMs,
+ endMs: cue.endMs,
+ text: cue.text,
+ words: words.map((word, index) => ({
+ cueId: cue.id,
+ cueWordIndex: index,
+ startMs: word.startMs,
+ endMs: word.endMs,
+ text: word.text,
+ leadingSpace: Boolean(word.leadingSpace),
+ })),
+ };
+ return updateCaptionCuesForEditedTarget(captions, target, text);
+ });
+ },
+ [setAutoCaptions],
+ );
+
+ const cancelEdit = useCallback(
+ () => videoPlaybackRef.current?.cancelCaptionEdit(),
+ [videoPlaybackRef],
+ );
+ const handleCaptionRetime = useCallback(
+ (id: string, span: CaptionRetimeSpan) => {
+ cancelEdit();
+ setAutoCaptions((captions) => retimeCue(captions, id, span));
+ },
+ [cancelEdit, setAutoCaptions],
+ );
+ const handleCaptionSplit = useCallback(
+ (id: string, atMs: number) => {
+ cancelEdit();
+ setAutoCaptions((captions) => splitCue(captions, id, atMs));
+ },
+ [cancelEdit, setAutoCaptions],
+ );
+ const handleCaptionMerge = useCallback(
+ (idA: string, idB: string) => {
+ cancelEdit();
+ setAutoCaptions((captions) => mergeCues(captions, idA, idB));
+ },
+ [cancelEdit, setAutoCaptions],
+ );
+ const handleCaptionDelete = useCallback(
+ (id: string) => {
+ cancelEdit();
+ setSelectedCaptionId((current) => (current === id ? null : current));
+ setAutoCaptions((captions) => deleteCue(captions, id));
+ },
+ [cancelEdit, setAutoCaptions, setSelectedCaptionId],
+ );
+
+ const handleCaptionAdded = useCallback(
+ (span: Span) => {
+ cancelEdit();
+ const newCue = createCaptionCue({
+ startMs: mapTimelineTimeToSourceTime(span.start),
+ endMs: mapTimelineTimeToSourceTime(span.end),
+ });
+ setAutoCaptions((captions) => addCue(captions, newCue));
+ setSelectedCaptionId(newCue.id);
+ setActiveEffectSection("caption");
+ setSelectedZoomId(null);
+ setSelectedClipId(null);
+ setSelectedAnnotationId(null);
+ setSelectedAudioId(null);
+ handleSeek(span.start / 1000, { pause: true });
+ },
+ [
+ cancelEdit,
+ handleSeek,
+ mapTimelineTimeToSourceTime,
+ setActiveEffectSection,
+ setAutoCaptions,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setSelectedCaptionId,
+ setSelectedClipId,
+ setSelectedZoomId,
+ ],
+ );
+
+ const handleClearAutoCaptions = useCallback(() => {
+ setAutoCaptions([]);
+ setAutoCaptionSettings((current) => ({ ...current, enabled: false }));
+ }, [setAutoCaptionSettings, setAutoCaptions]);
+
+ return {
+ handleSelectCaption,
+ handleBeginCaptionEdit,
+ handleCaptionTextEdit,
+ handleCaptionRetime,
+ handleCaptionSplit,
+ handleCaptionMerge,
+ handleCaptionDelete,
+ handleCaptionAdded,
+ handleClearAutoCaptions,
+ };
+}
diff --git a/src/components/video-editor/hooks/useClipRegionCommands.ts b/src/components/video-editor/hooks/useClipRegionCommands.ts
new file mode 100644
index 00000000..aa40256f
--- /dev/null
+++ b/src/components/video-editor/hooks/useClipRegionCommands.ts
@@ -0,0 +1,259 @@
+import type { Span } from "dnd-timeline";
+import { type Dispatch, type MutableRefObject, type SetStateAction, useCallback } from "react";
+import { toast } from "sonner";
+import { planClipSpeedChange } from "../clipSpeedChange";
+import type {
+ AnnotationRegion,
+ AudioRegion,
+ ClipRegion,
+ EditorEffectSection,
+ SpeedRegion,
+ ZoomRegion,
+} from "../types";
+
+type Translator = (
+ key: string,
+ fallback?: string,
+ params?: Record<string, string | number>,
+) => string;
+
+interface UseClipRegionCommandsParams {
+ clipRegions: ClipRegion[];
+ setClipRegions: Dispatch<SetStateAction<ClipRegion[]>>;
+ zoomRegions: ZoomRegion[];
+ setZoomRegions: Dispatch<SetStateAction<ZoomRegion[]>>;
+ setAnnotationRegions: Dispatch<SetStateAction<AnnotationRegion[]>>;
+ setSpeedRegions: Dispatch<SetStateAction<SpeedRegion[]>>;
+ setAudioRegions: Dispatch<SetStateAction<AudioRegion[]>>;
+ selectedClipId: string | null;
+ setSelectedClipId: Dispatch<SetStateAction<string | null>>;
+ setSelectedZoomId: Dispatch<SetStateAction<string | null>>;
+ setSelectedAnnotationId: Dispatch<SetStateAction<string | null>>;
+ setSelectedAudioId: Dispatch<SetStateAction<string | null>>;
+ setSelectedCaptionId: Dispatch<SetStateAction<string | null>>;
+ setActiveEffectSection: Dispatch<SetStateAction<EditorEffectSection>>;
+ nextClipIdRef: MutableRefObject<number>;
+ t: Translator;
+}
+
+export function useClipRegionCommands({
+ clipRegions,
+ setClipRegions,
+ zoomRegions,
+ setZoomRegions,
+ setAnnotationRegions,
+ setSpeedRegions,
+ setAudioRegions,
+ selectedClipId,
+ setSelectedClipId,
+ setSelectedZoomId,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setSelectedCaptionId,
+ setActiveEffectSection,
+ nextClipIdRef,
+ t,
+}: UseClipRegionCommandsParams) {
+ const handleSelectClip = useCallback(
+ (id: string | null) => {
+ setSelectedClipId(id);
+ if (id) {
+ setActiveEffectSection("clip");
+ setSelectedZoomId(null);
+ setSelectedAnnotationId(null);
+ setSelectedAudioId(null);
+ setSelectedCaptionId(null);
+ } else {
+ setActiveEffectSection((section) => (section === "clip" ? "scene" : section));
+ }
+ },
+ [
+ setActiveEffectSection,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setSelectedCaptionId,
+ setSelectedClipId,
+ setSelectedZoomId,
+ ],
+ );
+
+ const handleClipSplit = useCallback(
+ (splitMs: number) => {
+ setClipRegions((current) => {
+ const target = current.find(
+ (clip) => splitMs > clip.startMs && splitMs < clip.endMs,
+ );
+ if (!target) return current;
+ const leftId = `clip-${nextClipIdRef.current++}`;
+ const rightId = `clip-${nextClipIdRef.current++}`;
+ const left: ClipRegion = {
+ id: leftId,
+ startMs: target.startMs,
+ endMs: Math.round(splitMs),
+ speed: target.speed,
+ muted: target.muted,
+ };
+ const right: ClipRegion = {
+ id: rightId,
+ startMs: Math.round(splitMs),
+ endMs: target.endMs,
+ speed: target.speed,
+ muted: target.muted,
+ };
+ if (selectedClipId === target.id) setSelectedClipId(leftId);
+ return current.flatMap((clip) => (clip.id === target.id ? [left, right] : [clip]));
+ });
+ },
+ [nextClipIdRef, selectedClipId, setClipRegions, setSelectedClipId],
+ );
+
+ const handleClipSpanChange = useCallback(
+ (id: string, span: Span) => {
+ const oldClip = clipRegions.find((clip) => clip.id === id);
+ const newStart = Math.round(span.start);
+ const newEnd = Math.round(span.end);
+ const removedSegments = oldClip
+ ? [
+ ...(newStart > oldClip.startMs
+ ? [{ startMs: oldClip.startMs, endMs: newStart }]
+ : []),
+ ...(newEnd < oldClip.endMs
+ ? [{ startMs: newEnd, endMs: oldClip.endMs }]
+ : []),
+ ]
+ : [];
+
+ if (oldClip) {
+ const startDelta = newStart - oldClip.startMs;
+ const endDelta = newEnd - oldClip.endMs;
+ if (Math.abs(startDelta - endDelta) < 1 && Math.abs(startDelta) > 0) {
+ setZoomRegions((current) =>
+ current.map((zoom) =>
+ zoom.startMs < oldClip.endMs && zoom.endMs > oldClip.startMs
+ ? {
+ ...zoom,
+ startMs: zoom.startMs + startDelta,
+ endMs: zoom.endMs + startDelta,
+ }
+ : zoom,
+ ),
+ );
+ }
+ }
+
+ if (removedSegments.length > 0) {
+ const removeTrimmedRegions = <T extends { startMs: number; endMs: number }>(
+ regions: T[],
+ ) =>
+ regions.filter(
+ (region) =>
+ !removedSegments.some(
+ (segment) =>
+ region.startMs < segment.endMs &&
+ region.endMs > segment.startMs,
+ ),
+ );
+ setZoomRegions((current) => removeTrimmedRegions(current));
+ setAnnotationRegions((current) => removeTrimmedRegions(current));
+ setSpeedRegions((current) => removeTrimmedRegions(current));
+ setAudioRegions((current) => removeTrimmedRegions(current));
+ }
+
+ setClipRegions((current) =>
+ current.map((clip) =>
+ clip.id === id ? { ...clip, startMs: newStart, endMs: newEnd } : clip,
+ ),
+ );
+ },
+ [
+ clipRegions,
+ setAnnotationRegions,
+ setAudioRegions,
+ setClipRegions,
+ setSpeedRegions,
+ setZoomRegions,
+ ],
+ );
+
+ const handleClipSpeedChange = useCallback(
+ (speed: number) => {
+ if (!selectedClipId || !Number.isFinite(speed) || speed <= 0) return;
+ const plan = planClipSpeedChange({ clipRegions, zoomRegions, selectedClipId, speed });
+ if (!plan) return;
+ if ("blockedReason" in plan) {
+ toast.warning(
+ plan.blockedReason === "clip-overlap"
+ ? t(
+ "editor.timeline.speedClipOverlap",
+ "Speed change would overlap the next clip. Move or split clips before slowing this section.",
+ )
+ : t(
+ "editor.timeline.speedZoomOverlap",
+ "Speed change would overlap another zoom. Move or delete the overlapping zoom first.",
+ ),
+ );
+ return;
+ }
+ setClipRegions(plan.clipRegions);
+ setZoomRegions(plan.zoomRegions);
+ },
+ [clipRegions, selectedClipId, setClipRegions, setZoomRegions, t, zoomRegions],
+ );
+
+ const handleClipMutedChange = useCallback(
+ (muted: boolean) => {
+ if (!selectedClipId) return;
+ setClipRegions((current) =>
+ current.map((clip) => (clip.id === selectedClipId ? { ...clip, muted } : clip)),
+ );
+ },
+ [selectedClipId, setClipRegions],
+ );
+ const handleClipShowSourceAudioChange = useCallback(
+ (showSourceAudio: boolean) => {
+ if (!selectedClipId) return;
+ setClipRegions((current) =>
+ current.map((clip) =>
+ clip.id === selectedClipId ? { ...clip, showSourceAudio } : clip,
+ ),
+ );
+ },
+ [selectedClipId, setClipRegions],
+ );
+
+ const handleClipDelete = useCallback(
+ (id: string) => {
+ const deletedClip = clipRegions.find((clip) => clip.id === id);
+ setClipRegions((current) => current.filter((clip) => clip.id !== id));
+ if (deletedClip) {
+ const outsideDeletedClip = (region: { startMs: number; endMs: number }) =>
+ region.endMs <= deletedClip.startMs || region.startMs >= deletedClip.endMs;
+ setZoomRegions((current) => current.filter(outsideDeletedClip));
+ setAnnotationRegions((current) => current.filter(outsideDeletedClip));
+ setSpeedRegions((current) => current.filter(outsideDeletedClip));
+ setAudioRegions((current) => current.filter(outsideDeletedClip));
+ }
+ if (selectedClipId === id) setSelectedClipId(null);
+ },
+ [
+ clipRegions,
+ selectedClipId,
+ setAnnotationRegions,
+ setAudioRegions,
+ setClipRegions,
+ setSelectedClipId,
+ setSpeedRegions,
+ setZoomRegions,
+ ],
+ );
+
+ return {
+ handleSelectClip,
+ handleClipSplit,
+ handleClipSpanChange,
+ handleClipSpeedChange,
+ handleClipMutedChange,
+ handleClipShowSourceAudioChange,
+ handleClipDelete,
+ };
+}
diff --git a/src/components/video-editor/hooks/useCursorTelemetry.ts b/src/components/video-editor/hooks/useCursorTelemetry.ts
new file mode 100644
index 00000000..4913a76c
--- /dev/null
+++ b/src/components/video-editor/hooks/useCursorTelemetry.ts
@@ -0,0 +1,131 @@
+import { type MutableRefObject, useEffect, useMemo, useRef } from "react";
+import type { useTimelineState } from "../state/useTimelineState";
+import { normalizeCursorTelemetry } from "../timeline/zoomSuggestionUtils";
+import type { CursorTelemetryPoint } from "../types";
+import {
+ buildLoopedCursorTelemetry,
+ getDisplayedTimelineWindowMs,
+} from "../videoPlayback/cursorLoopTelemetry";
+
+type UseCursorTelemetryInput = {
+ videoPath: string | null;
+ videoSourcePath: string | null;
+ duration: number;
+ loopCursor: boolean;
+ timeline: ReturnType<typeof useTimelineState>;
+ pendingFreshRecordingAutoZoomPathRef: MutableRefObject<string | null>;
+ autoSuggestedVideoPathRef: MutableRefObject<string | null>;
+};
+
+export function useCursorTelemetry({
+ videoPath,
+ videoSourcePath,
+ duration,
+ loopCursor,
+ timeline,
+ pendingFreshRecordingAutoZoomPathRef,
+ autoSuggestedVideoPathRef,
+}: UseCursorTelemetryInput) {
+ const pendingRetryTimeoutRef = useRef<number | null>(null);
+ const { setCursorTelemetry, setCursorTelemetrySourcePath } = timeline;
+
+ useEffect(() => {
+ let mounted = true;
+ let retryAttempts = 0;
+ async function load() {
+ if (!videoPath || !videoSourcePath) {
+ if (mounted) {
+ setCursorTelemetry([]);
+ setCursorTelemetrySourcePath(null);
+ }
+ return;
+ }
+ try {
+ const result = await window.electronAPI.getCursorTelemetry(videoSourcePath);
+ if (!mounted) return;
+ setCursorTelemetry(result.success ? result.samples : []);
+ setCursorTelemetrySourcePath(videoSourcePath);
+ if (
+ pendingFreshRecordingAutoZoomPathRef.current === videoPath &&
+ autoSuggestedVideoPathRef.current !== videoPath &&
+ retryAttempts < 12
+ ) {
+ retryAttempts += 1;
+ pendingRetryTimeoutRef.current = window.setTimeout(() => {
+ pendingRetryTimeoutRef.current = null;
+ if (mounted) void load();
+ }, 350);
+ }
+ } catch (error) {
+ console.warn("Unable to load cursor telemetry:", error);
+ if (!mounted) return;
+ setCursorTelemetry([]);
+ setCursorTelemetrySourcePath(videoSourcePath);
+ if (
+ pendingFreshRecordingAutoZoomPathRef.current === videoPath &&
+ autoSuggestedVideoPathRef.current !== videoPath &&
+ retryAttempts < 12
+ ) {
+ retryAttempts += 1;
+ pendingRetryTimeoutRef.current = window.setTimeout(() => {
+ pendingRetryTimeoutRef.current = null;
+ if (mounted) void load();
+ }, 350);
+ }
+ }
+ }
+
+ if (pendingRetryTimeoutRef.current !== null) {
+ window.clearTimeout(pendingRetryTimeoutRef.current);
+ pendingRetryTimeoutRef.current = null;
+ }
+ void load();
+ return () => {
+ mounted = false;
+ if (pendingRetryTimeoutRef.current !== null) {
+ window.clearTimeout(pendingRetryTimeoutRef.current);
+ pendingRetryTimeoutRef.current = null;
+ }
+ };
+ }, [
+ videoPath,
+ videoSourcePath,
+ setCursorTelemetry,
+ setCursorTelemetrySourcePath,
+ pendingFreshRecordingAutoZoomPathRef,
+ autoSuggestedVideoPathRef,
+ ]);
+
+ const normalized = useMemo(() => {
+ if (timeline.cursorTelemetry.length === 0) return [] as CursorTelemetryPoint[];
+ const totalMs = Math.max(0, Math.round(duration * 1000));
+ return normalizeCursorTelemetry(
+ timeline.cursorTelemetry,
+ totalMs > 0 ? totalMs : Number.MAX_SAFE_INTEGER,
+ );
+ }, [timeline.cursorTelemetry, duration]);
+ const displayedWindow = useMemo(
+ () =>
+ getDisplayedTimelineWindowMs(
+ Math.max(0, Math.round(duration * 1000)),
+ timeline.trimRegions,
+ ),
+ [duration, timeline.trimRegions],
+ );
+ const effective = useMemo(() => {
+ if (
+ !loopCursor ||
+ normalized.length < 2 ||
+ displayedWindow.endMs <= displayedWindow.startMs
+ ) {
+ return normalized;
+ }
+ return buildLoopedCursorTelemetry(
+ normalized,
+ displayedWindow.endMs,
+ displayedWindow.startMs,
+ );
+ }, [loopCursor, normalized, displayedWindow]);
+
+ return { normalizedCursorTelemetry: normalized, effectiveCursorTelemetry: effective };
+}
diff --git a/src/components/video-editor/hooks/useEditorGlobalInteractions.ts b/src/components/video-editor/hooks/useEditorGlobalInteractions.ts
new file mode 100644
index 00000000..259da9d6
--- /dev/null
+++ b/src/components/video-editor/hooks/useEditorGlobalInteractions.ts
@@ -0,0 +1,99 @@
+import { type RefObject, useEffect } from "react";
+import type { useShortcuts } from "@/contexts/ShortcutsContext";
+import { matchesShortcut } from "@/lib/shortcuts";
+import type { useTimelineState } from "../state/useTimelineState";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+
+type Input = {
+ timeline: ReturnType<typeof useTimelineState>;
+ videoPlaybackRef: RefObject<VideoPlaybackRef | null>;
+ shortcuts: ReturnType<typeof useShortcuts>["shortcuts"];
+ isMac: boolean;
+ handleUndo: () => void;
+ handleRedo: () => void;
+ startPlayback: () => void;
+};
+
+export function useEditorGlobalInteractions({
+ timeline,
+ videoPlaybackRef,
+ shortcuts,
+ isMac,
+ handleUndo,
+ handleRedo,
+ startPlayback,
+}: Input) {
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const target = event.target as HTMLElement | null;
+ const editable =
+ target instanceof HTMLInputElement ||
+ target instanceof HTMLTextAreaElement ||
+ target?.isContentEditable;
+ const primaryModifier = isMac ? event.metaKey : event.ctrlKey;
+ const key = event.key.toLowerCase();
+
+ if (primaryModifier && !event.altKey && key === "z") {
+ if (!editable) {
+ event.preventDefault();
+ if (event.shiftKey) handleRedo();
+ else handleUndo();
+ }
+ return;
+ }
+ if (!isMac && event.ctrlKey && !event.metaKey && !event.altKey && key === "y") {
+ if (!editable) {
+ event.preventDefault();
+ handleRedo();
+ }
+ return;
+ }
+ if (event.key === "Tab" && !editable) event.preventDefault();
+ if (!matchesShortcut(event, shortcuts.playPause, isMac) || editable) return;
+ event.preventDefault();
+ const playback = videoPlaybackRef.current;
+ if (!playback?.video) return;
+ if (playback.video.paused) startPlayback();
+ else playback.pause();
+ };
+ window.addEventListener("keydown", handleKeyDown, { capture: true });
+ return () => window.removeEventListener("keydown", handleKeyDown, { capture: true });
+ }, [shortcuts, isMac, handleUndo, handleRedo, startPlayback, videoPlaybackRef]);
+
+ useEffect(() => {
+ if (
+ timeline.selectedZoomId &&
+ !timeline.zoomRegions.some(({ id }) => id === timeline.selectedZoomId)
+ ) {
+ timeline.setSelectedZoomId(null);
+ }
+ }, [timeline.selectedZoomId, timeline.zoomRegions, timeline.setSelectedZoomId]);
+ useEffect(() => {
+ if (
+ timeline.selectedAnnotationId &&
+ !timeline.annotationRegions.some(({ id }) => id === timeline.selectedAnnotationId)
+ ) {
+ timeline.setSelectedAnnotationId(null);
+ }
+ }, [
+ timeline.selectedAnnotationId,
+ timeline.annotationRegions,
+ timeline.setSelectedAnnotationId,
+ ]);
+ useEffect(() => {
+ if (
+ timeline.selectedAudioId &&
+ !timeline.audioRegions.some(({ id }) => id === timeline.selectedAudioId)
+ ) {
+ timeline.setSelectedAudioId(null);
+ }
+ }, [timeline.selectedAudioId, timeline.audioRegions, timeline.setSelectedAudioId]);
+ useEffect(() => {
+ if (
+ timeline.selectedCaptionId &&
+ !timeline.autoCaptions.some(({ id }) => id === timeline.selectedCaptionId)
+ ) {
+ timeline.setSelectedCaptionId(null);
+ }
+ }, [timeline.selectedCaptionId, timeline.autoCaptions, timeline.setSelectedCaptionId]);
+}
diff --git a/src/components/video-editor/hooks/useEditorHistory.ts b/src/components/video-editor/hooks/useEditorHistory.ts
new file mode 100644
index 00000000..992817b6
--- /dev/null
+++ b/src/components/video-editor/hooks/useEditorHistory.ts
@@ -0,0 +1,171 @@
+import { type MutableRefObject, useCallback, useEffect, useRef, useState } from "react";
+import {
+ createEditorHistoryStack,
+ type EditorHistorySnapshot,
+ recordEditorHistorySnapshot,
+ redoEditorHistoryStack,
+ resetEditorHistoryStack,
+ undoEditorHistoryStack,
+} from "../editorHistory";
+import { deriveNextId } from "../projectPersistence";
+import type { useTimelineState } from "../state/useTimelineState";
+import { cloneStructured } from "../videoEditorUtils";
+
+type Input = {
+ timeline: ReturnType<typeof useTimelineState>;
+ nextZoomIdRef: MutableRefObject<number>;
+ nextClipIdRef: MutableRefObject<number>;
+ nextAnnotationIdRef: MutableRefObject<number>;
+ nextAudioIdRef: MutableRefObject<number>;
+ nextAnnotationZIndexRef: MutableRefObject<number>;
+};
+
+export function useEditorHistory({
+ timeline,
+ nextZoomIdRef,
+ nextClipIdRef,
+ nextAnnotationIdRef,
+ nextAudioIdRef,
+ nextAnnotationZIndexRef,
+}: Input) {
+ const {
+ zoomRegions,
+ clipRegions,
+ speedRegions,
+ annotationRegions,
+ audioRegions,
+ autoCaptions,
+ selectedZoomId,
+ selectedClipId,
+ selectedAnnotationId,
+ selectedAudioId,
+ setZoomRegions,
+ setClipRegions,
+ setSpeedRegions,
+ setAnnotationRegions,
+ setAudioRegions,
+ setAutoCaptions,
+ setSelectedZoomId,
+ setSelectedClipId,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ } = timeline;
+ const historyRef = useRef(createEditorHistoryStack());
+ const applyingRef = useRef(false);
+ const [version, setVersion] = useState(0);
+ const syncButtons = useCallback(() => setVersion((value) => value + 1), []);
+ const buildSnapshot = useCallback(
+ (): EditorHistorySnapshot => ({
+ zoomRegions,
+ clipRegions,
+ speedRegions,
+ annotationRegions,
+ audioRegions,
+ autoCaptions,
+ selectedZoomId,
+ selectedClipId,
+ selectedAnnotationId,
+ selectedAudioId,
+ }),
+ [
+ zoomRegions,
+ clipRegions,
+ speedRegions,
+ annotationRegions,
+ audioRegions,
+ autoCaptions,
+ selectedZoomId,
+ selectedClipId,
+ selectedAnnotationId,
+ selectedAudioId,
+ ],
+ );
+ const applySnapshot = useCallback(
+ (snapshot: EditorHistorySnapshot) => {
+ applyingRef.current = true;
+ const cloned = cloneStructured(snapshot);
+ setZoomRegions(cloned.zoomRegions);
+ setClipRegions(cloned.clipRegions);
+ setSpeedRegions(cloned.speedRegions);
+ setAnnotationRegions(cloned.annotationRegions);
+ setAudioRegions(cloned.audioRegions);
+ setAutoCaptions(cloned.autoCaptions);
+ setSelectedZoomId(cloned.selectedZoomId);
+ setSelectedClipId(cloned.selectedClipId);
+ setSelectedAnnotationId(cloned.selectedAnnotationId);
+ setSelectedAudioId(cloned.selectedAudioId);
+ nextZoomIdRef.current = deriveNextId(
+ "zoom",
+ cloned.zoomRegions.map(({ id }) => id),
+ );
+ nextClipIdRef.current = deriveNextId(
+ "clip",
+ cloned.clipRegions.map(({ id }) => id),
+ );
+ nextAnnotationIdRef.current = deriveNextId(
+ "annotation",
+ cloned.annotationRegions.map(({ id }) => id),
+ );
+ nextAudioIdRef.current = deriveNextId(
+ "audio",
+ cloned.audioRegions.map(({ id }) => id),
+ );
+ nextAnnotationZIndexRef.current =
+ cloned.annotationRegions.reduce((max, region) => Math.max(max, region.zIndex), 0) +
+ 1;
+ },
+ [
+ setZoomRegions,
+ setClipRegions,
+ setSpeedRegions,
+ setAnnotationRegions,
+ setAudioRegions,
+ setAutoCaptions,
+ setSelectedZoomId,
+ setSelectedClipId,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ nextZoomIdRef,
+ nextClipIdRef,
+ nextAnnotationIdRef,
+ nextAudioIdRef,
+ nextAnnotationZIndexRef,
+ ],
+ );
+ const handleUndo = useCallback(() => {
+ const previous = undoEditorHistoryStack(historyRef.current, buildSnapshot());
+ if (previous) {
+ applySnapshot(previous);
+ syncButtons();
+ }
+ }, [applySnapshot, buildSnapshot, syncButtons]);
+ const handleRedo = useCallback(() => {
+ const next = redoEditorHistoryStack(historyRef.current, buildSnapshot());
+ if (next) {
+ applySnapshot(next);
+ syncButtons();
+ }
+ }, [applySnapshot, buildSnapshot, syncButtons]);
+ const resetHistory = useCallback(() => {
+ resetEditorHistoryStack(historyRef.current);
+ applyingRef.current = false;
+ syncButtons();
+ }, [syncButtons]);
+
+ useEffect(() => {
+ const result = recordEditorHistorySnapshot(historyRef.current, buildSnapshot(), {
+ applyingHistory: applyingRef.current,
+ });
+ if (result === "applied") applyingRef.current = false;
+ if (result !== "unchanged") syncButtons();
+ }, [buildSnapshot, syncButtons]);
+
+ void version;
+ return {
+ canUndo: historyRef.current.past.length > 0,
+ canRedo: historyRef.current.future.length > 0,
+ handleUndo,
+ handleRedo,
+ resetHistory,
+ };
+}
diff --git a/src/components/video-editor/hooks/useEditorPlaybackControls.ts b/src/components/video-editor/hooks/useEditorPlaybackControls.ts
new file mode 100644
index 00000000..733dee93
--- /dev/null
+++ b/src/components/video-editor/hooks/useEditorPlaybackControls.ts
@@ -0,0 +1,82 @@
+import { type RefObject, useCallback } from "react";
+import type { TimelineEditorHandle } from "../timeline/TimelineEditor";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+
+interface UseEditorPlaybackControlsParams {
+ videoPlaybackRef: RefObject<VideoPlaybackRef>;
+ timelineRef: RefObject<TimelineEditorHandle>;
+ playSourceAudioPreview: () => void;
+ mapTimelineTimeToSourceTime: (timeMs: number) => number;
+ timelinePlayheadTime: number;
+ timelineDuration: number;
+}
+
+export function useEditorPlaybackControls({
+ videoPlaybackRef,
+ timelineRef,
+ playSourceAudioPreview,
+ mapTimelineTimeToSourceTime,
+ timelinePlayheadTime,
+ timelineDuration,
+}: UseEditorPlaybackControlsParams) {
+ const getActivePlayback = useCallback(() => videoPlaybackRef.current, [videoPlaybackRef]);
+
+ const startPlayback = useCallback(() => {
+ const playback = getActivePlayback();
+ if (!playback?.video) return;
+
+ playSourceAudioPreview();
+ playback.play().catch((error) => console.error("Video play failed:", error));
+ }, [getActivePlayback, playSourceAudioPreview]);
+
+ const togglePlayPause = useCallback(() => {
+ const playback = getActivePlayback();
+ const video = playback?.video;
+ if (!playback || !video) return;
+
+ if (!video.paused && !video.ended) playback.pause();
+ else startPlayback();
+ }, [getActivePlayback, startPlayback]);
+
+ const handleSeek = useCallback(
+ (time: number, options: { pause?: boolean } = {}) => {
+ const playback = getActivePlayback();
+ const video = playback?.video;
+ if (!video) return;
+
+ if (options.pause && !video.paused) playback?.pause();
+ video.currentTime = mapTimelineTimeToSourceTime(time * 1000) / 1000;
+ },
+ [getActivePlayback, mapTimelineTimeToSourceTime],
+ );
+
+ const handleTimelineSeek = useCallback(
+ (time: number) => handleSeek(time, { pause: true }),
+ [handleSeek],
+ );
+
+ const handlePreviewSkipBack = useCallback(() => {
+ const currentMs = timelinePlayheadTime * 1000;
+ const keyframes = timelineRef.current?.keyframes ?? [];
+ const previous = [...keyframes]
+ .reverse()
+ .find((keyframe) => keyframe.time < currentMs - 50);
+ handleSeek(previous ? previous.time / 1000 : Math.max(0, timelinePlayheadTime - 5));
+ }, [handleSeek, timelinePlayheadTime, timelineRef]);
+
+ const handlePreviewSkipForward = useCallback(() => {
+ const currentMs = timelinePlayheadTime * 1000;
+ const keyframes = timelineRef.current?.keyframes ?? [];
+ const next = keyframes.find((keyframe) => keyframe.time > currentMs + 50);
+ handleSeek(next ? next.time / 1000 : Math.min(timelineDuration, timelinePlayheadTime + 5));
+ }, [handleSeek, timelineDuration, timelinePlayheadTime, timelineRef]);
+
+ return {
+ startPlayback,
+ togglePlayPause,
+ handleSeek,
+ handleTimelineSeek,
+ handlePreviewSkipBack,
+ handlePreviewSkipForward,
+ };
+}
diff --git a/src/components/video-editor/hooks/useFreshRecordingAutoZoom.ts b/src/components/video-editor/hooks/useFreshRecordingAutoZoom.ts
new file mode 100644
index 00000000..bdde5833
--- /dev/null
+++ b/src/components/video-editor/hooks/useFreshRecordingAutoZoom.ts
@@ -0,0 +1,153 @@
+import {
+ type Dispatch,
+ type MutableRefObject,
+ type RefObject,
+ type SetStateAction,
+ useCallback,
+ useEffect,
+} from "react";
+import { shouldAutoApplyFreshRecordingZoomsForSource } from "../timeline/zoomSuggestionUtils";
+import type { CursorTelemetryPoint, ZoomRegion } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+
+interface UseFreshRecordingAutoZoomParams {
+ videoPath: string | null;
+ loading: boolean;
+ isPreviewReady: boolean;
+ duration: number;
+ cursorTelemetryCount: number;
+ normalizedCursorTelemetry: CursorTelemetryPoint[];
+ zoomRegions: ZoomRegion[];
+ setZoomRegions: Dispatch<SetStateAction<ZoomRegion[]>>;
+ setAutoSuggestZoomsTrigger: Dispatch<SetStateAction<number>>;
+ videoPlaybackRef: RefObject<VideoPlaybackRef>;
+ autoSuggestedVideoPathRef: MutableRefObject<string | null>;
+ pendingFreshRecordingAutoZoomPathRef: MutableRefObject<string | null>;
+ pendingFreshRecordingAutoSuggestTimeoutRef: MutableRefObject<number | null>;
+ pendingFreshRecordingAutoSuggestTelemetryCountRef: MutableRefObject<number>;
+}
+
+export function useFreshRecordingAutoZoom({
+ videoPath,
+ loading,
+ isPreviewReady,
+ duration,
+ cursorTelemetryCount,
+ normalizedCursorTelemetry,
+ zoomRegions,
+ setZoomRegions,
+ setAutoSuggestZoomsTrigger,
+ videoPlaybackRef,
+ autoSuggestedVideoPathRef,
+ pendingFreshRecordingAutoZoomPathRef,
+ pendingFreshRecordingAutoSuggestTimeoutRef,
+ pendingFreshRecordingAutoSuggestTelemetryCountRef,
+}: UseFreshRecordingAutoZoomParams) {
+ const handleAutoSuggestZoomsConsumed = useCallback(() => {
+ setAutoSuggestZoomsTrigger(0);
+ }, [setAutoSuggestZoomsTrigger]);
+
+ useEffect(() => {
+ if (
+ videoPath &&
+ pendingFreshRecordingAutoZoomPathRef.current === videoPath &&
+ isPreviewReady &&
+ !shouldAutoApplyFreshRecordingZoomsForSource(
+ videoPlaybackRef.current?.video?.videoWidth,
+ videoPlaybackRef.current?.video?.videoHeight,
+ )
+ ) {
+ pendingFreshRecordingAutoZoomPathRef.current = null;
+ if (pendingFreshRecordingAutoSuggestTimeoutRef.current !== null) {
+ window.clearTimeout(pendingFreshRecordingAutoSuggestTimeoutRef.current);
+ pendingFreshRecordingAutoSuggestTimeoutRef.current = null;
+ }
+ return;
+ }
+
+ if (
+ !videoPath ||
+ loading ||
+ !isPreviewReady ||
+ duration <= 0 ||
+ zoomRegions.length > 0 ||
+ normalizedCursorTelemetry.length < 2
+ ) {
+ if (pendingFreshRecordingAutoSuggestTimeoutRef.current !== null) {
+ window.clearTimeout(pendingFreshRecordingAutoSuggestTimeoutRef.current);
+ pendingFreshRecordingAutoSuggestTimeoutRef.current = null;
+ }
+ return;
+ }
+
+ if (pendingFreshRecordingAutoZoomPathRef.current !== videoPath) return;
+ if (autoSuggestedVideoPathRef.current === videoPath) {
+ pendingFreshRecordingAutoZoomPathRef.current = null;
+ return;
+ }
+ if (pendingFreshRecordingAutoSuggestTelemetryCountRef.current === cursorTelemetryCount) {
+ return;
+ }
+
+ pendingFreshRecordingAutoSuggestTelemetryCountRef.current = cursorTelemetryCount;
+ if (pendingFreshRecordingAutoSuggestTimeoutRef.current !== null) {
+ window.clearTimeout(pendingFreshRecordingAutoSuggestTimeoutRef.current);
+ }
+
+ pendingFreshRecordingAutoSuggestTimeoutRef.current = window.setTimeout(() => {
+ pendingFreshRecordingAutoSuggestTimeoutRef.current = null;
+ if (
+ pendingFreshRecordingAutoZoomPathRef.current !== videoPath ||
+ autoSuggestedVideoPathRef.current === videoPath ||
+ zoomRegions.length > 0
+ ) {
+ return;
+ }
+ setAutoSuggestZoomsTrigger((value) => value + 1);
+ }, 500);
+ }, [
+ videoPath,
+ loading,
+ isPreviewReady,
+ duration,
+ cursorTelemetryCount,
+ normalizedCursorTelemetry,
+ zoomRegions,
+ autoSuggestedVideoPathRef,
+ pendingFreshRecordingAutoSuggestTelemetryCountRef,
+ pendingFreshRecordingAutoSuggestTimeoutRef,
+ pendingFreshRecordingAutoZoomPathRef,
+ setAutoSuggestZoomsTrigger,
+ videoPlaybackRef,
+ ]);
+
+ useEffect(() => {
+ if (
+ !videoPath ||
+ !isPreviewReady ||
+ zoomRegions.length === 0 ||
+ autoSuggestedVideoPathRef.current !== videoPath ||
+ shouldAutoApplyFreshRecordingZoomsForSource(
+ videoPlaybackRef.current?.video?.videoWidth,
+ videoPlaybackRef.current?.video?.videoHeight,
+ )
+ ) {
+ return;
+ }
+
+ autoSuggestedVideoPathRef.current = null;
+ setZoomRegions((current) => {
+ const next = current.filter((region) => region.mode !== "auto");
+ return next.length === current.length ? current : next;
+ });
+ }, [
+ autoSuggestedVideoPathRef,
+ isPreviewReady,
+ setZoomRegions,
+ videoPath,
+ videoPlaybackRef,
+ zoomRegions,
+ ]);
+
+ return { handleAutoSuggestZoomsConsumed };
+}
diff --git a/src/components/video-editor/hooks/useTimelineEditingController.ts b/src/components/video-editor/hooks/useTimelineEditingController.ts
new file mode 100644
index 00000000..a61a29e1
--- /dev/null
+++ b/src/components/video-editor/hooks/useTimelineEditingController.ts
@@ -0,0 +1,234 @@
+import type { Dispatch, MutableRefObject, RefObject, SetStateAction } from "react";
+import { useCallback } from "react";
+import { toast } from "sonner";
+import type { useI18n } from "@/contexts/I18nContext";
+import type { useShortcuts } from "@/contexts/ShortcutsContext";
+import { useVideoEditorAudio } from "../audio/useVideoEditorAudio";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useTimelineState } from "../state/useTimelineState";
+import type { TimelineEditorHandle } from "../timeline/TimelineEditor";
+import type { EditorEffectSection } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+import { getErrorMessage, summarizeErrorMessage } from "../videoEditorUtils";
+import { useAnnotationRegionCommands } from "./useAnnotationRegionCommands";
+import { useAudioRegionCommands } from "./useAudioRegionCommands";
+import { useCaptionCommands } from "./useCaptionCommands";
+import { useClipRegionCommands } from "./useClipRegionCommands";
+import { useCursorTelemetry } from "./useCursorTelemetry";
+import { useEditorGlobalInteractions } from "./useEditorGlobalInteractions";
+import { useEditorPlaybackControls } from "./useEditorPlaybackControls";
+import { useFreshRecordingAutoZoom } from "./useFreshRecordingAutoZoom";
+import { useTimelineProjection } from "./useTimelineProjection";
+import { useZoomRegionCommands } from "./useZoomRegionCommands";
+
+type Input = {
+ t: ReturnType<typeof useI18n>["t"];
+ shortcuts: ReturnType<typeof useShortcuts>["shortcuts"];
+ isMac: boolean;
+ timeline: ReturnType<typeof useTimelineState>;
+ appearance: ReturnType<typeof useAppearanceState>;
+ videoPath: string | null;
+ videoSourcePath: string | null;
+ currentSourcePath: string | null;
+ duration: number;
+ currentTime: number;
+ isPlaying: boolean;
+ previewVolume: number;
+ loading: boolean;
+ isPreviewReady: boolean;
+ setActiveEffectSection: Dispatch<SetStateAction<EditorEffectSection>>;
+ setAutoSuggestZoomsTrigger: Dispatch<SetStateAction<number>>;
+ videoPlaybackRef: RefObject<VideoPlaybackRef>;
+ timelineRef: RefObject<TimelineEditorHandle>;
+ nextZoomIdRef: MutableRefObject<number>;
+ nextClipIdRef: MutableRefObject<number>;
+ nextAudioIdRef: MutableRefObject<number>;
+ nextAnnotationIdRef: MutableRefObject<number>;
+ nextAnnotationZIndexRef: MutableRefObject<number>;
+ clipInitializedRef: MutableRefObject<boolean>;
+ autoFullTrackClipIdRef: MutableRefObject<string | null>;
+ autoFullTrackClipEndMsRef: MutableRefObject<number | null>;
+ autoSuggestedVideoPathRef: MutableRefObject<string | null>;
+ pendingFreshRecordingAutoZoomPathRef: MutableRefObject<string | null>;
+ pendingFreshRecordingAutoSuggestTimeoutRef: MutableRefObject<number | null>;
+ pendingFreshRecordingAutoSuggestTelemetryCountRef: MutableRefObject<number>;
+ handleUndo: () => void;
+ handleRedo: () => void;
+};
+
+export function useTimelineEditingController(input: Input) {
+ const { timeline } = input;
+ const handleSourceFallbackLoadError = useCallback((error: unknown) => {
+ toast.warning(
+ `Could not load companion audio source: ${summarizeErrorMessage(getErrorMessage(error))}`,
+ { duration: 10000 },
+ );
+ }, []);
+ const cursor = useCursorTelemetry({
+ videoPath: input.videoPath,
+ videoSourcePath: input.videoSourcePath,
+ duration: input.duration,
+ loopCursor: input.appearance.loopCursor,
+ timeline,
+ pendingFreshRecordingAutoZoomPathRef: input.pendingFreshRecordingAutoZoomPathRef,
+ autoSuggestedVideoPathRef: input.autoSuggestedVideoPathRef,
+ });
+ const projection = useTimelineProjection({
+ timeline,
+ duration: input.duration,
+ currentTime: input.currentTime,
+ nextClipIdRef: input.nextClipIdRef,
+ initializedRef: input.clipInitializedRef,
+ autoFullTrackIdRef: input.autoFullTrackClipIdRef,
+ autoFullTrackEndRef: input.autoFullTrackClipEndMsRef,
+ });
+ const audio = useVideoEditorAudio({
+ currentSourcePath: input.currentSourcePath,
+ selectedClipId: timeline.selectedClipId,
+ clipRegions: timeline.clipRegions,
+ audioRegions: timeline.audioRegions,
+ effectiveSpeedRegions: projection.effectiveSpeedRegions,
+ sourceAudioTrackSettingsByClip: timeline.sourceAudioTrackSettingsByClip,
+ setSourceAudioTrackSettingsByClip: timeline.setSourceAudioTrackSettingsByClip,
+ defaultSourceAudioTrackSettings: timeline.defaultSourceAudioTrackSettings,
+ setDefaultSourceAudioTrackSettings: timeline.setDefaultSourceAudioTrackSettings,
+ currentTime: input.currentTime,
+ timelineTime: projection.timelinePlayheadTime,
+ duration: input.duration,
+ isPlaying: input.isPlaying,
+ previewVolume: input.previewVolume,
+ sourceAudioFallbackRefreshKey: timeline.sourceAudioFallbackRefreshKey,
+ summarizeErrorMessage,
+ onSourceFallbackLoadError: handleSourceFallbackLoadError,
+ });
+ const playback = useEditorPlaybackControls({
+ videoPlaybackRef: input.videoPlaybackRef,
+ timelineRef: input.timelineRef,
+ playSourceAudioPreview: audio.playSourceAudioPreview,
+ mapTimelineTimeToSourceTime: projection.mapTimelineTimeToSourceTime,
+ timelinePlayheadTime: projection.timelinePlayheadTime,
+ timelineDuration: projection.timelineDuration,
+ });
+ const captionCommands = useCaptionCommands({
+ autoCaptions: timeline.autoCaptions,
+ setAutoCaptions: timeline.setAutoCaptions,
+ setAutoCaptionSettings: timeline.setAutoCaptionSettings,
+ setSelectedCaptionId: timeline.setSelectedCaptionId,
+ setSelectedZoomId: timeline.setSelectedZoomId,
+ setSelectedClipId: timeline.setSelectedClipId,
+ setSelectedAnnotationId: timeline.setSelectedAnnotationId,
+ setSelectedAudioId: timeline.setSelectedAudioId,
+ setActiveEffectSection: input.setActiveEffectSection,
+ videoPlaybackRef: input.videoPlaybackRef,
+ mapSourceTimeToTimelineTime: projection.mapSourceTimeToTimelineTime,
+ mapTimelineTimeToSourceTime: projection.mapTimelineTimeToSourceTime,
+ handleSeek: playback.handleSeek,
+ });
+ const zoomCommands = useZoomRegionCommands({
+ videoPath: input.videoPath,
+ setZoomRegions: timeline.setZoomRegions,
+ selectedZoomId: timeline.selectedZoomId,
+ setSelectedZoomId: timeline.setSelectedZoomId,
+ setSelectedAnnotationId: timeline.setSelectedAnnotationId,
+ setSelectedAudioId: timeline.setSelectedAudioId,
+ setSelectedCaptionId: timeline.setSelectedCaptionId,
+ setActiveEffectSection: input.setActiveEffectSection,
+ nextZoomIdRef: input.nextZoomIdRef,
+ autoSuggestedVideoPathRef: input.autoSuggestedVideoPathRef,
+ pendingFreshRecordingAutoZoomPathRef: input.pendingFreshRecordingAutoZoomPathRef,
+ });
+ const handleSelectAnnotation = useCallback(
+ (id: string | null) => {
+ timeline.setSelectedAnnotationId(id);
+ if (id) {
+ timeline.setSelectedZoomId(null);
+ timeline.setSelectedAudioId(null);
+ timeline.setSelectedCaptionId(null);
+ }
+ },
+ [
+ timeline.setSelectedAnnotationId,
+ timeline.setSelectedZoomId,
+ timeline.setSelectedAudioId,
+ timeline.setSelectedCaptionId,
+ ],
+ );
+ const freshZoom = useFreshRecordingAutoZoom({
+ videoPath: input.videoPath,
+ loading: input.loading,
+ isPreviewReady: input.isPreviewReady,
+ duration: input.duration,
+ cursorTelemetryCount: timeline.cursorTelemetry.length,
+ normalizedCursorTelemetry: cursor.normalizedCursorTelemetry,
+ zoomRegions: timeline.zoomRegions,
+ setZoomRegions: timeline.setZoomRegions,
+ setAutoSuggestZoomsTrigger: input.setAutoSuggestZoomsTrigger,
+ videoPlaybackRef: input.videoPlaybackRef,
+ autoSuggestedVideoPathRef: input.autoSuggestedVideoPathRef,
+ pendingFreshRecordingAutoZoomPathRef: input.pendingFreshRecordingAutoZoomPathRef,
+ pendingFreshRecordingAutoSuggestTimeoutRef:
+ input.pendingFreshRecordingAutoSuggestTimeoutRef,
+ pendingFreshRecordingAutoSuggestTelemetryCountRef:
+ input.pendingFreshRecordingAutoSuggestTelemetryCountRef,
+ });
+ const clipCommands = useClipRegionCommands({
+ clipRegions: timeline.clipRegions,
+ setClipRegions: timeline.setClipRegions,
+ zoomRegions: timeline.zoomRegions,
+ setZoomRegions: timeline.setZoomRegions,
+ setAnnotationRegions: timeline.setAnnotationRegions,
+ setSpeedRegions: timeline.setSpeedRegions,
+ setAudioRegions: timeline.setAudioRegions,
+ selectedClipId: timeline.selectedClipId,
+ setSelectedClipId: timeline.setSelectedClipId,
+ setSelectedZoomId: timeline.setSelectedZoomId,
+ setSelectedAnnotationId: timeline.setSelectedAnnotationId,
+ setSelectedAudioId: timeline.setSelectedAudioId,
+ setSelectedCaptionId: timeline.setSelectedCaptionId,
+ setActiveEffectSection: input.setActiveEffectSection,
+ nextClipIdRef: input.nextClipIdRef,
+ t: input.t,
+ });
+ const audioCommands = useAudioRegionCommands({
+ setAudioRegions: timeline.setAudioRegions,
+ selectedAudioId: timeline.selectedAudioId,
+ setSelectedAudioId: timeline.setSelectedAudioId,
+ setSelectedZoomId: timeline.setSelectedZoomId,
+ setSelectedAnnotationId: timeline.setSelectedAnnotationId,
+ setSelectedCaptionId: timeline.setSelectedCaptionId,
+ setActiveEffectSection: input.setActiveEffectSection,
+ nextAudioIdRef: input.nextAudioIdRef,
+ });
+ const annotationCommands = useAnnotationRegionCommands({
+ setAnnotationRegions: timeline.setAnnotationRegions,
+ selectedAnnotationId: timeline.selectedAnnotationId,
+ setSelectedAnnotationId: timeline.setSelectedAnnotationId,
+ setSelectedZoomId: timeline.setSelectedZoomId,
+ nextAnnotationIdRef: input.nextAnnotationIdRef,
+ nextAnnotationZIndexRef: input.nextAnnotationZIndexRef,
+ });
+
+ useEditorGlobalInteractions({
+ timeline,
+ videoPlaybackRef: input.videoPlaybackRef,
+ shortcuts: input.shortcuts,
+ isMac: input.isMac,
+ handleUndo: input.handleUndo,
+ handleRedo: input.handleRedo,
+ startPlayback: playback.startPlayback,
+ });
+
+ return {
+ cursor,
+ projection,
+ audio,
+ playback,
+ captionCommands,
+ zoomCommands,
+ clipCommands,
+ audioCommands,
+ annotationCommands,
+ handleSelectAnnotation,
+ handleAutoSuggestZoomsConsumed: freshZoom.handleAutoSuggestZoomsConsumed,
+ };
+}
diff --git a/src/components/video-editor/hooks/useTimelineProjection.ts b/src/components/video-editor/hooks/useTimelineProjection.ts
new file mode 100644
index 00000000..29d3d9cc
--- /dev/null
+++ b/src/components/video-editor/hooks/useTimelineProjection.ts
@@ -0,0 +1,157 @@
+/* biome-ignore-all lint/correctness/useExhaustiveDependencies: mutable timeline bootstrap refs intentionally do not trigger effects. */
+import { type MutableRefObject, useCallback, useEffect, useMemo } from "react";
+import { deriveNextId } from "../projectPersistence";
+import type { useTimelineState } from "../state/useTimelineState";
+import {
+ type CaptionCue,
+ clipsToTrims,
+ extendAutoFullTrackClip,
+ getClipSourceEndMs,
+ getTimelineDurationMs,
+ mapSourceTimeToTimelineTime,
+ mapTimelineTimeToSourceTime,
+ type SpeedRegion,
+ trimsToClips,
+ type ZoomRegion,
+} from "../types";
+
+type Input = {
+ timeline: ReturnType<typeof useTimelineState>;
+ duration: number;
+ currentTime: number;
+ nextClipIdRef: MutableRefObject<number>;
+ initializedRef: MutableRefObject<boolean>;
+ autoFullTrackIdRef: MutableRefObject<string | null>;
+ autoFullTrackEndRef: MutableRefObject<number | null>;
+};
+
+export function useTimelineProjection({
+ timeline,
+ duration,
+ currentTime,
+ nextClipIdRef,
+ initializedRef,
+ autoFullTrackIdRef,
+ autoFullTrackEndRef,
+}: Input) {
+ const { clipRegions, trimRegions, speedRegions, zoomRegions, autoCaptions } = timeline;
+
+ useEffect(() => {
+ const totalMs = Math.round(duration * 1000);
+ if (totalMs <= 0) return;
+ if (!initializedRef.current) {
+ if (clipRegions.length === 0) {
+ const nextRegions =
+ trimRegions.length > 0
+ ? trimsToClips(trimRegions, totalMs)
+ : (() => {
+ const id = `clip-${nextClipIdRef.current++}`;
+ autoFullTrackIdRef.current = id;
+ autoFullTrackEndRef.current = totalMs;
+ return [{ id, startMs: 0, endMs: totalMs, speed: 1 as const }];
+ })();
+ if (trimRegions.length > 0) {
+ nextClipIdRef.current = deriveNextId(
+ "clip",
+ nextRegions.map(({ id }) => id),
+ );
+ }
+ timeline.setClipRegions(nextRegions);
+ if (speedRegions.length > 0) timeline.setSpeedRegions([]);
+ }
+ initializedRef.current = true;
+ return;
+ }
+
+ const extended = extendAutoFullTrackClip(
+ clipRegions,
+ autoFullTrackIdRef.current,
+ autoFullTrackEndRef.current,
+ totalMs,
+ );
+ if (!extended) return;
+ autoFullTrackEndRef.current = totalMs;
+ timeline.setClipRegions(extended);
+ }, [
+ duration,
+ clipRegions,
+ trimRegions,
+ speedRegions,
+ nextClipIdRef,
+ timeline.setClipRegions,
+ timeline.setSpeedRegions,
+ ]);
+
+ useEffect(() => {
+ const totalMs = Math.round(duration * 1000);
+ if (totalMs > 0 && clipRegions.length > 0) {
+ timeline.setTrimRegions(clipsToTrims(clipRegions, totalMs));
+ }
+ }, [clipRegions, duration, timeline.setTrimRegions]);
+
+ const toSourceTime = useCallback(
+ (timeMs: number) => mapTimelineTimeToSourceTime(timeMs, clipRegions),
+ [clipRegions],
+ );
+ const toTimelineTime = useCallback(
+ (timeMs: number) => mapSourceTimeToTimelineTime(timeMs, clipRegions),
+ [clipRegions],
+ );
+ const effectiveZoomRegions = useMemo<ZoomRegion[]>(
+ () =>
+ zoomRegions.map((region) => ({
+ ...region,
+ startMs: toSourceTime(region.startMs),
+ endMs: toSourceTime(region.endMs),
+ })),
+ [zoomRegions, toSourceTime],
+ );
+ const effectiveCaptionRegions = useMemo<CaptionCue[]>(
+ () =>
+ autoCaptions.map((cue) => ({
+ ...cue,
+ startMs: toTimelineTime(cue.startMs),
+ endMs: toTimelineTime(cue.endMs),
+ })),
+ [autoCaptions, toTimelineTime],
+ );
+ const timelinePlayheadTime = useMemo(
+ () => toTimelineTime(currentTime * 1000) / 1000,
+ [currentTime, toTimelineTime],
+ );
+ const timelineDuration = useMemo(
+ () => getTimelineDurationMs(clipRegions, duration * 1000) / 1000,
+ [clipRegions, duration],
+ );
+ const effectiveSpeedRegions = useMemo<SpeedRegion[]>(() => {
+ const clipDerived = clipRegions
+ .filter(({ speed }) => speed !== 1)
+ .map((clip) => ({
+ id: `clip-speed-${clip.id}`,
+ startMs: clip.startMs,
+ endMs: getClipSourceEndMs(clip),
+ speed: clip.speed as SpeedRegion["speed"],
+ }));
+ if (clipDerived.length === 0) return speedRegions;
+ return [
+ ...speedRegions,
+ ...clipDerived.filter(
+ (candidate) =>
+ !speedRegions.some(
+ (region) =>
+ region.endMs > candidate.startMs && region.startMs < candidate.endMs,
+ ),
+ ),
+ ];
+ }, [clipRegions, speedRegions]);
+
+ return {
+ mapTimelineTimeToSourceTime: toSourceTime,
+ mapSourceTimeToTimelineTime: toTimelineTime,
+ effectiveZoomRegions,
+ effectiveCaptionRegions,
+ timelinePlayheadTime,
+ timelineDuration,
+ effectiveSpeedRegions,
+ };
+}
diff --git a/src/components/video-editor/hooks/useZoomRegionCommands.ts b/src/components/video-editor/hooks/useZoomRegionCommands.ts
new file mode 100644
index 00000000..425f53f8
--- /dev/null
+++ b/src/components/video-editor/hooks/useZoomRegionCommands.ts
@@ -0,0 +1,182 @@
+import type { Span } from "dnd-timeline";
+import { type Dispatch, type MutableRefObject, type SetStateAction, useCallback } from "react";
+import {
+ clampFocusToDepth,
+ DEFAULT_AUTO_ZOOM_DEPTH,
+ type EditorEffectSection,
+ type ZoomDepth,
+ type ZoomFocus,
+ type ZoomMode,
+ type ZoomRegion,
+} from "../types";
+
+interface UseZoomRegionCommandsParams {
+ videoPath: string | null;
+ setZoomRegions: Dispatch<SetStateAction<ZoomRegion[]>>;
+ selectedZoomId: string | null;
+ setSelectedZoomId: Dispatch<SetStateAction<string | null>>;
+ setSelectedAnnotationId: Dispatch<SetStateAction<string | null>>;
+ setSelectedAudioId: Dispatch<SetStateAction<string | null>>;
+ setSelectedCaptionId: Dispatch<SetStateAction<string | null>>;
+ setActiveEffectSection: Dispatch<SetStateAction<EditorEffectSection>>;
+ nextZoomIdRef: MutableRefObject<number>;
+ autoSuggestedVideoPathRef: MutableRefObject<string | null>;
+ pendingFreshRecordingAutoZoomPathRef: MutableRefObject<string | null>;
+}
+
+export function useZoomRegionCommands({
+ videoPath,
+ setZoomRegions,
+ selectedZoomId,
+ setSelectedZoomId,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setSelectedCaptionId,
+ setActiveEffectSection,
+ nextZoomIdRef,
+ autoSuggestedVideoPathRef,
+ pendingFreshRecordingAutoZoomPathRef,
+}: UseZoomRegionCommandsParams) {
+ const handleSelectZoom = useCallback(
+ (id: string | null) => {
+ setSelectedZoomId(id);
+ if (id) {
+ setActiveEffectSection("zoom");
+ setSelectedAnnotationId(null);
+ setSelectedAudioId(null);
+ setSelectedCaptionId(null);
+ } else {
+ setActiveEffectSection((section) => (section === "zoom" ? "scene" : section));
+ }
+ },
+ [
+ setActiveEffectSection,
+ setSelectedAnnotationId,
+ setSelectedAudioId,
+ setSelectedCaptionId,
+ setSelectedZoomId,
+ ],
+ );
+
+ const markFreshRecordingSuggestion = useCallback(() => {
+ if (videoPath && pendingFreshRecordingAutoZoomPathRef.current === videoPath) {
+ autoSuggestedVideoPathRef.current = videoPath;
+ pendingFreshRecordingAutoZoomPathRef.current = null;
+ }
+ }, [autoSuggestedVideoPathRef, pendingFreshRecordingAutoZoomPathRef, videoPath]);
+
+ const handleZoomAdded = useCallback(
+ (span: Span) => {
+ const id = `zoom-${nextZoomIdRef.current++}`;
+ const depth: ZoomDepth = 2;
+ const newRegion: ZoomRegion = {
+ id,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ depth,
+ focus: clampFocusToDepth({ cx: 0.5, cy: 0.5 }, depth),
+ mode: "auto",
+ };
+ markFreshRecordingSuggestion();
+ setZoomRegions((current) => [...current, newRegion]);
+ setSelectedZoomId(id);
+ setSelectedAnnotationId(null);
+ setSelectedCaptionId(null);
+ },
+ [
+ markFreshRecordingSuggestion,
+ nextZoomIdRef,
+ setSelectedAnnotationId,
+ setSelectedCaptionId,
+ setSelectedZoomId,
+ setZoomRegions,
+ ],
+ );
+
+ const handleZoomSuggested = useCallback(
+ (span: Span, focus: ZoomFocus) => {
+ const newRegion: ZoomRegion = {
+ id: `zoom-${nextZoomIdRef.current++}`,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ depth: DEFAULT_AUTO_ZOOM_DEPTH,
+ focus: clampFocusToDepth(focus, DEFAULT_AUTO_ZOOM_DEPTH),
+ mode: "auto",
+ };
+ markFreshRecordingSuggestion();
+ setZoomRegions((current) => [...current, newRegion]);
+ },
+ [markFreshRecordingSuggestion, nextZoomIdRef, setZoomRegions],
+ );
+
+ const handleZoomSpanChange = useCallback(
+ (id: string, span: Span) => {
+ setZoomRegions((current) =>
+ current.map((region) =>
+ region.id === id
+ ? {
+ ...region,
+ startMs: Math.round(span.start),
+ endMs: Math.round(span.end),
+ }
+ : region,
+ ),
+ );
+ },
+ [setZoomRegions],
+ );
+ const handleZoomFocusChange = useCallback(
+ (id: string, focus: ZoomFocus) => {
+ setZoomRegions((current) =>
+ current.map((region) =>
+ region.id === id
+ ? { ...region, focus: clampFocusToDepth(focus, region.depth) }
+ : region,
+ ),
+ );
+ },
+ [setZoomRegions],
+ );
+ const handleZoomDepthChange = useCallback(
+ (depth: ZoomDepth) => {
+ if (!selectedZoomId) return;
+ setZoomRegions((current) =>
+ current.map((region) =>
+ region.id === selectedZoomId
+ ? { ...region, depth, focus: clampFocusToDepth(region.focus, depth) }
+ : region,
+ ),
+ );
+ },
+ [selectedZoomId, setZoomRegions],
+ );
+ const handleZoomModeChange = useCallback(
+ (mode: ZoomMode) => {
+ if (!selectedZoomId) return;
+ setZoomRegions((current) =>
+ current.map((region) =>
+ region.id === selectedZoomId ? { ...region, mode } : region,
+ ),
+ );
+ },
+ [selectedZoomId, setZoomRegions],
+ );
+ const handleZoomDelete = useCallback(
+ (id: string) => {
+ setZoomRegions((current) => current.filter((region) => region.id !== id));
+ if (selectedZoomId === id) setSelectedZoomId(null);
+ },
+ [selectedZoomId, setSelectedZoomId, setZoomRegions],
+ );
+
+ return {
+ handleSelectZoom,
+ handleZoomAdded,
+ handleZoomSuggested,
+ handleZoomSpanChange,
+ handleZoomFocusChange,
+ handleZoomDepthChange,
+ handleZoomModeChange,
+ handleZoomDelete,
+ };
+}
diff --git a/src/components/video-editor/layout/CropEditorDialog.tsx b/src/components/video-editor/layout/CropEditorDialog.tsx
new file mode 100644
index 00000000..fe1e88e6
--- /dev/null
+++ b/src/components/video-editor/layout/CropEditorDialog.tsx
@@ -0,0 +1,74 @@
+import { X } from "@phosphor-icons/react";
+import type { Dispatch, SetStateAction } from "react";
+import { Button } from "@/components/ui/button";
+import type { useI18n } from "@/contexts/I18nContext";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import { CropControl } from "../CropControl";
+import type { CropRegion } from "../types";
+
+type Props = {
+ open: boolean;
+ t: ReturnType<typeof useI18n>["t"];
+ videoElement: HTMLVideoElement | null;
+ cropRegion: CropRegion;
+ setCropRegion: Dispatch<SetStateAction<CropRegion>>;
+ aspectRatio: AspectRatio;
+ onCancel: () => void;
+ onDone: () => void;
+};
+
+export function CropEditorDialog({
+ open,
+ t,
+ videoElement,
+ cropRegion,
+ setCropRegion,
+ aspectRatio,
+ onCancel,
+ onDone,
+}: Props) {
+ if (!open) return null;
+ return (
+ <>
+ <div
+ className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm animate-in fade-in duration-200"
+ onClick={onCancel}
+ />
+ <div className="fixed left-1/2 top-1/2 z-[60] max-h-[90vh] w-[90vw] max-w-5xl -translate-x-1/2 -translate-y-1/2 overflow-auto rounded-2xl border border-foreground/10 bg-editor-dialog p-8 shadow-2xl animate-in zoom-in-95 duration-200">
+ <div className="mb-6 flex items-center justify-between">
+ <div>
+ <span className="text-xl font-bold text-foreground">
+ {t("settings.crop.title")}
+ </span>
+ <p className="mt-2 text-sm text-muted-foreground">
+ {t("settings.crop.instruction")}
+ </p>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={onCancel}
+ className="text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
+ >
+ <X className="h-5 w-5" />
+ </Button>
+ </div>
+ <CropControl
+ videoElement={videoElement}
+ cropRegion={cropRegion}
+ onCropChange={setCropRegion}
+ aspectRatio={aspectRatio}
+ />
+ <div className="mt-6 flex justify-end">
+ <Button
+ onClick={onDone}
+ size="lg"
+ className="bg-[#2563EB] text-white hover:bg-[#2563EB]/90"
+ >
+ {t("common.actions.done")}
+ </Button>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorDialogs.tsx b/src/components/video-editor/layout/EditorDialogs.tsx
new file mode 100644
index 00000000..0f195e2e
--- /dev/null
+++ b/src/components/video-editor/layout/EditorDialogs.tsx
@@ -0,0 +1,203 @@
+import type { Dispatch, FormEvent, RefObject, SetStateAction } from "react";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import ProjectBrowserDialog, { type ProjectLibraryEntry } from "../ProjectBrowserDialog";
+
+export type UnsavedChangesDecision = "cancel" | "discard" | "save";
+
+type Translator = (
+ key: string,
+ fallback?: string,
+ params?: Record<string, string | number>,
+) => string;
+
+interface EditorDialogsProps {
+ t: Translator;
+ projectSaveDialogOpen: boolean;
+ setProjectSaveDialogOpen: Dispatch<SetStateAction<boolean>>;
+ projectSaveDialogDraft: string;
+ setProjectSaveDialogDraft: Dispatch<SetStateAction<string>>;
+ projectSaveDialogInputRef: RefObject<HTMLInputElement>;
+ isSavingProjectDialog: boolean;
+ resolveProjectSaveDialog: (saved: boolean) => void;
+ handleProjectSaveDialogSubmit: (event?: FormEvent<HTMLFormElement>) => Promise<void>;
+ unsavedChangesDialogOpen: boolean;
+ setUnsavedChangesDialogOpen: Dispatch<SetStateAction<boolean>>;
+ unsavedChangesDialogActionLabel: string;
+ resolveUnsavedChangesDialog: (decision: UnsavedChangesDecision) => void;
+ projectBrowserOpen: boolean;
+ setProjectBrowserOpen: Dispatch<SetStateAction<boolean>>;
+ projectLibraryEntries: ProjectLibraryEntry[];
+ projectBrowserAnchorRef: RefObject<HTMLButtonElement>;
+ handleImportMediaOrProject: () => Promise<void>;
+ handleOpenProjectFromLibrary: (projectPath: string) => Promise<void>;
+ nativeCaptureUnavailableModalOpen: boolean;
+ setNativeCaptureUnavailableModalOpen: Dispatch<SetStateAction<boolean>>;
+}
+
+export function EditorDialogs({
+ t,
+ projectSaveDialogOpen,
+ setProjectSaveDialogOpen,
+ projectSaveDialogDraft,
+ setProjectSaveDialogDraft,
+ projectSaveDialogInputRef,
+ isSavingProjectDialog,
+ resolveProjectSaveDialog,
+ handleProjectSaveDialogSubmit,
+ unsavedChangesDialogOpen,
+ setUnsavedChangesDialogOpen,
+ unsavedChangesDialogActionLabel,
+ resolveUnsavedChangesDialog,
+ projectBrowserOpen,
+ setProjectBrowserOpen,
+ projectLibraryEntries,
+ projectBrowserAnchorRef,
+ handleImportMediaOrProject,
+ handleOpenProjectFromLibrary,
+ nativeCaptureUnavailableModalOpen,
+ setNativeCaptureUnavailableModalOpen,
+}: EditorDialogsProps) {
+ return (
+ <>
+ <Dialog
+ open={projectSaveDialogOpen}
+ onOpenChange={(open) => {
+ if (open) setProjectSaveDialogOpen(true);
+ else if (!isSavingProjectDialog) resolveProjectSaveDialog(false);
+ }}
+ >
+ <DialogContent className="max-w-sm border-foreground/10 bg-editor-dialog text-foreground">
+ <form onSubmit={(event) => void handleProjectSaveDialogSubmit(event)}>
+ <DialogHeader>
+ <DialogTitle>
+ {t("editor.project.saveTitle", "Save Project")}
+ </DialogTitle>
+ <DialogDescription className="text-muted-foreground">
+ {t(
+ "editor.project.saveDescription",
+ "Name this project. It will be saved in your Recordly Projects folder.",
+ )}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="py-4">
+ <label className="mb-2 block text-xs font-medium text-muted-foreground">
+ {t("editor.project.saveNameLabel", "Project name")}
+ </label>
+ <div className="flex items-center overflow-hidden rounded-md border border-foreground/10 bg-editor-panel">
+ <Input
+ ref={projectSaveDialogInputRef}
+ value={projectSaveDialogDraft}
+ onChange={(event) =>
+ setProjectSaveDialogDraft(event.target.value)
+ }
+ disabled={isSavingProjectDialog}
+ className="h-10 flex-1 border-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0"
+ aria-label={t("editor.project.saveNameLabel", "Project name")}
+ />
+ <span className="shrink-0 px-3 text-xs font-medium text-muted-foreground/70">
+ .recordly
+ </span>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => resolveProjectSaveDialog(false)}
+ disabled={isSavingProjectDialog}
+ >
+ {t("common.actions.cancel", "Cancel")}
+ </Button>
+ <Button type="submit" disabled={isSavingProjectDialog}>
+ {isSavingProjectDialog
+ ? t("editor.project.saving", "Saving...")
+ : t("common.actions.save", "Save")}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog
+ open={unsavedChangesDialogOpen}
+ onOpenChange={(open) => {
+ if (open) setUnsavedChangesDialogOpen(true);
+ else resolveUnsavedChangesDialog("cancel");
+ }}
+ >
+ <DialogContent className="max-w-sm border-foreground/10 bg-editor-dialog text-foreground">
+ <DialogHeader>
+ <DialogTitle>Unsaved changes</DialogTitle>
+ <DialogDescription className="text-muted-foreground">
+ {`Save your current project before you ${unsavedChangesDialogActionLabel}?`}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => resolveUnsavedChangesDialog("cancel")}
+ >
+ {t("common.actions.cancel", "Cancel")}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => resolveUnsavedChangesDialog("discard")}
+ >
+ Discard changes
+ </Button>
+ <Button type="button" onClick={() => resolveUnsavedChangesDialog("save")}>
+ Save project
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <ProjectBrowserDialog
+ open={projectBrowserOpen}
+ onOpenChange={setProjectBrowserOpen}
+ entries={projectLibraryEntries}
+ anchorRef={projectBrowserAnchorRef}
+ onImportFile={() => void handleImportMediaOrProject()}
+ onOpenProject={(projectPath) => void handleOpenProjectFromLibrary(projectPath)}
+ />
+
+ <Dialog
+ open={nativeCaptureUnavailableModalOpen}
+ onOpenChange={setNativeCaptureUnavailableModalOpen}
+ >
+ <DialogContent className="max-w-md bg-editor-dialog border-foreground/10 text-foreground">
+ <DialogHeader>
+ <DialogTitle>
+ {t(
+ "editor.nativeCaptureUnavailable.title",
+ "Nothing’s broken, but we won’t be able to render an animated cursor overlay.",
+ )}
+ </DialogTitle>
+ <DialogDescription className="text-muted-foreground">
+ {t(
+ "editor.nativeCaptureUnavailable.description",
+ "Your device does not support native capture. This could be for a variety of reasons we haven’t figured out yet. This doesn’t break Recordly, but it does make cursor smoothing impossible.",
+ )}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button onClick={() => setNativeCaptureUnavailableModalOpen(false)}>
+ {t("editor.nativeCaptureUnavailable.confirm", "Okay")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorExportMenu.tsx b/src/components/video-editor/layout/EditorExportMenu.tsx
new file mode 100644
index 00000000..bd52e3c2
--- /dev/null
+++ b/src/components/video-editor/layout/EditorExportMenu.tsx
@@ -0,0 +1,298 @@
+import { DownloadSimple as Download } from "@phosphor-icons/react";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import type { useI18n } from "@/contexts/I18nContext";
+import { ExportSettingsMenu } from "../ExportSettingsMenu";
+import type { useExportDimensions } from "../export/useExportDimensions";
+import type { useExportSession } from "../export/useExportSession";
+import type { useExportSettings } from "../export/useExportSettings";
+import type { useExportStatusViewModel } from "../export/useExportStatusViewModel";
+
+type Props = {
+ t: ReturnType<typeof useI18n>["t"];
+ exportSettings: ReturnType<typeof useExportSettings>;
+ exportSession: ReturnType<typeof useExportSession>;
+ exportDimensions: ReturnType<typeof useExportDimensions>;
+ exportStatus: ReturnType<typeof useExportStatusViewModel>;
+ hasCaptionsForSidecar: boolean;
+ nvidiaCudaExportAvailable: boolean;
+ experimentalNvidiaCudaExport: boolean;
+ setExperimentalNvidiaCudaExport: (enabled: boolean) => void;
+ handleOpenExportDropdown: () => void;
+ handleExportDropdownClose: () => void;
+ handleCancelExport: () => void;
+ handleRetrySaveExport: () => void;
+ handleStartExportFromDropdown: () => void;
+ revealExportedFile: () => void;
+ openLightningIssues: () => void;
+};
+
+export function EditorExportMenu(props: Props) {
+ const {
+ t,
+ exportSettings,
+ exportSession,
+ exportDimensions,
+ exportStatus,
+ hasCaptionsForSidecar,
+ nvidiaCudaExportAvailable,
+ experimentalNvidiaCudaExport,
+ setExperimentalNvidiaCudaExport,
+ handleOpenExportDropdown,
+ handleExportDropdownClose,
+ handleCancelExport,
+ handleRetrySaveExport,
+ handleStartExportFromDropdown,
+ revealExportedFile,
+ openLightningIssues,
+ } = props;
+ const {
+ exportQuality,
+ setExportQuality,
+ exportEncodingMode,
+ setExportEncodingMode,
+ exportPipelineModel,
+ setExportPipelineModel,
+ mp4FrameRate,
+ setMp4FrameRate,
+ exportFormat,
+ setExportFormat,
+ gifFrameRate,
+ setGifFrameRate,
+ gifLoop,
+ setGifLoop,
+ gifSizePreset,
+ setGifSizePreset,
+ includeCaptionSidecar,
+ setIncludeCaptionSidecar,
+ } = exportSettings;
+ const {
+ isExporting,
+ exportProgress,
+ exportError,
+ showExportDropdown,
+ setShowExportDropdown,
+ exportedFilePath,
+ hasPendingExportSave,
+ } = exportSession;
+ const { gifOutputDimensions, mp4OutputDimensions } = exportDimensions;
+ const {
+ isExportPreparing,
+ isExportSaving,
+ isRenderingAudio,
+ isExportFinalSaveIndeterminate,
+ isLightningExportInProgress,
+ isLegacyExportInProgress,
+ exportFinalizingProgress,
+ exportRenderSpeedLabel,
+ exportPercentLabel,
+ runtimeLabel: exportRuntimeLabel,
+ nativeSkipLabel: exportNativeSkipLabel,
+ } = exportStatus;
+
+ return (
+ <DropdownMenu open={showExportDropdown} onOpenChange={setShowExportDropdown} modal={false}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ onClick={handleOpenExportDropdown}
+ className="inline-flex h-8 min-w-[112px] items-center justify-center gap-2 rounded-[5px] bg-[#2563EB] px-4.5 text-white transition-colors hover:bg-[#2563EB]/92"
+ >
+ <Download className="h-4 w-4" />
+ <span className="text-sm font-semibold tracking-tight">
+ {t("common.actions.export", "Export")}
+ </span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ sideOffset={10}
+ className="w-[360px] border-none bg-transparent p-0 shadow-none"
+ >
+ {isExporting ? (
+ <div className="rounded-2xl border border-foreground/10 bg-editor-surface p-4 text-foreground shadow-2xl">
+ <div className="mb-3 flex items-center justify-between gap-3">
+ <div>
+ <p className="text-sm font-semibold text-foreground">
+ {t("editor.exportStatus.exporting", "Exporting")}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("editor.exportStatus.renderingFile", "Rendering your file.")}
+ </p>
+ {isLightningExportInProgress ? (
+ <p className="mt-1 flex items-center gap-1 text-[11px] text-muted-foreground/70">
+ PLEASE{" "}
+ <button
+ type="button"
+ onClick={() => void openLightningIssues()}
+ className="underline decoration-slate-500/70 underline-offset-2 transition-colors hover:text-foreground"
+ >
+ report bugs
+ </button>
+ with Lightning export{" "}
+ <span aria-hidden="true">{"\u{1F64F}"}</span>
+ </p>
+ ) : null}
+ {isLegacyExportInProgress ? (
+ <p className="mt-1 text-[11px] text-muted-foreground/70">
+ Export too slow? Cancel and try Lightning export!
+ </p>
+ ) : null}
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleCancelExport}
+ className="h-8 border-red-500/20 bg-red-500/10 px-3 text-xs text-red-400 hover:bg-red-500/20"
+ >
+ {t("common.actions.cancel")}
+ </Button>
+ </div>
+ <div className="h-2 overflow-hidden rounded-full border border-foreground/5 bg-foreground/5">
+ {isExportPreparing ||
+ isExportSaving ||
+ isExportFinalSaveIndeterminate ? (
+ <div className="indeterminate-progress h-full rounded-full bg-transparent" />
+ ) : (
+ <div
+ className="h-full bg-[#2563EB] transition-all duration-300 ease-out"
+ style={{
+ width: `${Math.min(isRenderingAudio ? (exportProgress?.audioProgress ?? 0) * 100 : (exportFinalizingProgress ?? exportProgress?.percentage ?? 8), 100)}%`,
+ }}
+ />
+ )}
+ </div>
+ <p className="mt-2 text-xs text-muted-foreground">{exportPercentLabel}</p>
+ {isRenderingAudio ? (
+ <p className="mt-1 text-[11px] text-muted-foreground/70">
+ {t(
+ "editor.export.processingAudioEdits",
+ "Processing audio with speed/overlay edits",
+ )}
+ </p>
+ ) : exportRenderSpeedLabel ? (
+ <p className="mt-1 text-[11px] text-muted-foreground/70">
+ {exportRenderSpeedLabel}
+ </p>
+ ) : null}
+ {exportRuntimeLabel ? (
+ <p className="mt-1 text-[11px] text-muted-foreground/70">
+ Path: {exportRuntimeLabel}
+ </p>
+ ) : null}
+ {exportNativeSkipLabel ? (
+ <p className="mt-1 text-[11px] text-amber-500/80">
+ {exportNativeSkipLabel}
+ </p>
+ ) : null}
+ </div>
+ ) : exportError ? (
+ <div className="rounded-2xl border border-foreground/10 bg-editor-surface p-4 text-foreground shadow-2xl">
+ <p className="text-sm font-semibold text-foreground">
+ {t("editor.exportStatus.issue", "Export issue")}
+ </p>
+ {exportRuntimeLabel ? (
+ <p className="mt-1 text-[11px] text-muted-foreground/70">
+ Path: {exportRuntimeLabel}
+ </p>
+ ) : null}
+ <p className="mt-1 whitespace-pre-line text-xs leading-relaxed text-muted-foreground">
+ {exportError}
+ </p>
+ <div className="mt-4 flex gap-2">
+ {hasPendingExportSave ? (
+ <Button
+ type="button"
+ onClick={handleRetrySaveExport}
+ className="h-8 flex-1 rounded-[5px] bg-[#2563EB] text-xs font-semibold text-white hover:bg-[#2563EB]/92"
+ >
+ {t("editor.actions.saveAgain", "Save Again")}
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleExportDropdownClose}
+ className="h-8 flex-1 border-foreground/10 bg-foreground/5 text-xs text-muted-foreground hover:bg-foreground/10"
+ >
+ {t("common.actions.close", "Close")}
+ </Button>
+ </div>
+ </div>
+ ) : exportedFilePath ? (
+ <div className="rounded-2xl border border-foreground/10 bg-editor-surface p-4 text-foreground shadow-2xl">
+ <p className="text-sm font-semibold text-foreground">
+ {t("editor.exportStatus.complete", "Export complete")}
+ </p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t(
+ "editor.exportStatus.savedSuccessfully",
+ "Your file was saved successfully.",
+ )}
+ </p>
+ {exportRuntimeLabel ? (
+ <p className="mt-1 text-[11px] text-muted-foreground/70">
+ Path: {exportRuntimeLabel}
+ </p>
+ ) : null}
+ <p className="mt-3 truncate text-xs text-muted-foreground/70">
+ {exportedFilePath.split("/").pop()}
+ </p>
+ <div className="mt-4 flex gap-2">
+ <Button
+ type="button"
+ onClick={revealExportedFile}
+ className="h-8 flex-1 rounded-[5px] bg-[#2563EB] text-xs font-semibold text-white hover:bg-[#2563EB]/92"
+ >
+ {t("editor.actions.showInFolder", "Show In Folder")}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleExportDropdownClose}
+ className="h-8 flex-1 border-foreground/10 bg-foreground/5 text-xs text-muted-foreground hover:bg-foreground/10"
+ >
+ Done
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <ExportSettingsMenu
+ exportFormat={exportFormat}
+ onExportFormatChange={setExportFormat}
+ exportEncodingMode={exportEncodingMode}
+ onExportEncodingModeChange={setExportEncodingMode}
+ mp4FrameRate={mp4FrameRate}
+ onMp4FrameRateChange={setMp4FrameRate}
+ exportPipelineModel={exportPipelineModel}
+ onExportPipelineModelChange={setExportPipelineModel}
+ experimentalNvidiaCudaExport={
+ experimentalNvidiaCudaExport && nvidiaCudaExportAvailable
+ }
+ onExperimentalNvidiaCudaExportChange={setExperimentalNvidiaCudaExport}
+ nvidiaCudaExportAvailable={nvidiaCudaExportAvailable}
+ exportQuality={exportQuality}
+ onExportQualityChange={setExportQuality}
+ gifFrameRate={gifFrameRate}
+ onGifFrameRateChange={setGifFrameRate}
+ gifLoop={gifLoop}
+ onGifLoopChange={setGifLoop}
+ gifSizePreset={gifSizePreset}
+ onGifSizePresetChange={setGifSizePreset}
+ showCaptionSidecarOption={hasCaptionsForSidecar && exportFormat === "mp4"}
+ includeCaptionSidecar={includeCaptionSidecar}
+ onIncludeCaptionSidecarChange={setIncludeCaptionSidecar}
+ mp4OutputDimensions={mp4OutputDimensions}
+ gifOutputDimensions={gifOutputDimensions}
+ onExport={handleStartExportFromDropdown}
+ className="shadow-2xl"
+ />
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorHeader.tsx b/src/components/video-editor/layout/EditorHeader.tsx
new file mode 100644
index 00000000..76fd0cd6
--- /dev/null
+++ b/src/components/video-editor/layout/EditorHeader.tsx
@@ -0,0 +1,227 @@
+import {
+ FolderOpen,
+ ArrowClockwise as Redo2,
+ ArrowCounterClockwise as Undo2,
+} from "@phosphor-icons/react";
+import type { CSSProperties, FormEvent, RefObject } from "react";
+import { Button } from "@/components/ui/button";
+import type { useI18n } from "@/contexts/I18nContext";
+import type { useExportDimensions } from "../export/useExportDimensions";
+import type { useExportSession } from "../export/useExportSession";
+import type { useExportSettings } from "../export/useExportSettings";
+import type { useExportStatusViewModel } from "../export/useExportStatusViewModel";
+import type { useVideoEditorPresets } from "../presets/useVideoEditorPresets";
+import type { useProjectState } from "../state/useProjectState";
+import { APP_HEADER_ICON_BUTTON_CLASS, DiscordLinkButton, FeedbackDialog } from "../TutorialHelp";
+import { EditorExportMenu } from "./EditorExportMenu";
+import { EditorPresetMenu } from "./EditorPresetMenu";
+
+type Props = {
+ t: ReturnType<typeof useI18n>["t"];
+ headerLeftControlsPaddingClass: string;
+ project: ReturnType<typeof useProjectState>;
+ projectBrowserTriggerRef: RefObject<HTMLButtonElement>;
+ projectNameInputRef: RefObject<HTMLInputElement>;
+ projectDisplayName: string;
+ hasUnsavedChanges: boolean;
+ canUndo: boolean;
+ canRedo: boolean;
+ handleOpenProjectBrowser: () => void;
+ handleUndo: () => void;
+ handleRedo: () => void;
+ handleProjectNameSubmit: (event?: FormEvent<HTMLFormElement>) => void;
+ closeProjectNameEditor: () => void;
+ presets: ReturnType<typeof useVideoEditorPresets>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ exportSession: ReturnType<typeof useExportSession>;
+ exportDimensions: ReturnType<typeof useExportDimensions>;
+ exportStatus: ReturnType<typeof useExportStatusViewModel>;
+ hasCaptionsForSidecar: boolean;
+ nvidiaCudaExportAvailable: boolean;
+ experimentalNvidiaCudaExport: boolean;
+ setExperimentalNvidiaCudaExport: (enabled: boolean) => void;
+ handleOpenExportDropdown: () => void;
+ handleExportDropdownClose: () => void;
+ handleCancelExport: () => void;
+ handleRetrySaveExport: () => void;
+ handleStartExportFromDropdown: () => void;
+ revealExportedFile: () => void;
+ openLightningIssues: () => void;
+};
+
+export function EditorHeader(props: Props) {
+ const {
+ t,
+ headerLeftControlsPaddingClass,
+ project,
+ projectBrowserTriggerRef,
+ projectNameInputRef,
+ projectDisplayName,
+ hasUnsavedChanges,
+ canUndo,
+ canRedo,
+ handleOpenProjectBrowser,
+ handleUndo,
+ handleRedo,
+ handleProjectNameSubmit,
+ closeProjectNameEditor,
+ presets,
+ exportSettings,
+ exportSession,
+ exportDimensions,
+ exportStatus,
+ hasCaptionsForSidecar,
+ nvidiaCudaExportAvailable,
+ experimentalNvidiaCudaExport,
+ setExperimentalNvidiaCudaExport,
+ handleOpenExportDropdown,
+ handleExportDropdownClose,
+ handleCancelExport,
+ handleRetrySaveExport,
+ handleStartExportFromDropdown,
+ revealExportedFile,
+ openLightningIssues,
+ } = props;
+ const {
+ isEditingProjectName,
+ setIsEditingProjectName,
+ projectNameDraft,
+ setProjectNameDraft,
+ isSavingProjectName,
+ } = project;
+
+ return (
+ <div
+ className="relative z-50 flex h-11 flex-shrink-0 items-center justify-between border-b border-foreground/10 bg-editor-header/88 px-5 backdrop-blur-md"
+ style={{ WebkitAppRegion: "drag" } as CSSProperties}
+ >
+ <div
+ className={`flex items-center justify-self-start gap-1.5 ${headerLeftControlsPaddingClass}`}
+ style={{ WebkitAppRegion: "no-drag" } as CSSProperties}
+ >
+ <Button
+ ref={projectBrowserTriggerRef}
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={handleOpenProjectBrowser}
+ className={APP_HEADER_ICON_BUTTON_CLASS}
+ title={t("editor.project.projects", "Open projects")}
+ aria-label={t("editor.project.projects", "Open projects")}
+ >
+ <FolderOpen className="h-4 w-4" />
+ </Button>
+ <DiscordLinkButton />
+ <FeedbackDialog />
+ <div className="ml-1 h-5 w-px bg-foreground/10" />
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={handleUndo}
+ disabled={!canUndo}
+ className="inline-flex h-8 w-8 items-center justify-center rounded-[5px] border border-foreground/10 bg-foreground/5 p-0 text-foreground transition-colors hover:bg-foreground/10 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"
+ title={t("common.actions.undo", "Undo")}
+ aria-label={t("common.actions.undo", "Undo")}
+ >
+ <Undo2 className="h-4 w-4" />
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={handleRedo}
+ disabled={!canRedo}
+ className="inline-flex h-8 w-8 items-center justify-center rounded-[5px] border border-foreground/10 bg-foreground/5 p-0 text-foreground transition-colors hover:bg-foreground/10 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"
+ title={t("common.actions.redo", "Redo")}
+ aria-label={t("common.actions.redo", "Redo")}
+ >
+ <Redo2 className="h-4 w-4" />
+ </Button>
+ </div>
+
+ <div
+ className="absolute left-1/2 flex min-w-0 -translate-x-1/2 items-center justify-center"
+ style={{ WebkitAppRegion: "no-drag" } as CSSProperties}
+ >
+ {isEditingProjectName ? (
+ <form
+ onSubmit={(event) => void handleProjectNameSubmit(event)}
+ className="flex max-w-[min(52vw,460px)] items-baseline gap-1 rounded-[7px] border border-foreground/10 bg-editor-panel/[0.88] px-2.5 py-1 shadow-[0_10px_28px_rgba(0,0,0,0.18)]"
+ >
+ {hasUnsavedChanges ? (
+ <span className="mt-[1px] size-2 shrink-0 rounded-full bg-[#2563EB]" />
+ ) : null}
+ <input
+ ref={projectNameInputRef}
+ type="text"
+ value={projectNameDraft}
+ onChange={(event) => setProjectNameDraft(event.target.value)}
+ onBlur={() => {
+ if (!isSavingProjectName) closeProjectNameEditor();
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ closeProjectNameEditor();
+ }
+ }}
+ disabled={isSavingProjectName}
+ className="min-w-[10ch] max-w-[min(40vw,360px)] bg-transparent text-sm font-semibold tracking-tight text-foreground/95 outline-none placeholder:text-muted-foreground/60 disabled:cursor-wait"
+ style={{ width: `${Math.max(projectNameDraft.length, 10)}ch` }}
+ aria-label={t("editor.project.renameInput", "Project name")}
+ />
+ <span className="shrink-0 text-xs font-medium tracking-tight text-muted-foreground/70">
+ .recordly
+ </span>
+ </form>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setIsEditingProjectName(true)}
+ className="inline-flex max-w-[min(52vw,460px)] items-baseline gap-1 rounded-[7px] px-2.5 py-1 transition-colors hover:bg-foreground/5"
+ title={t("editor.project.renameTitle", "Rename project")}
+ aria-label={t("editor.project.renameTitle", "Rename project")}
+ >
+ {hasUnsavedChanges ? (
+ <span className="mt-[1px] size-2 shrink-0 rounded-full bg-[#2563EB]" />
+ ) : null}
+ <span className="truncate text-sm font-semibold tracking-tight text-foreground/90">
+ {projectDisplayName}
+ </span>
+ <span className="shrink-0 text-xs font-medium tracking-tight text-muted-foreground/70">
+ .recordly
+ </span>
+ </button>
+ )}
+ </div>
+
+ <div
+ className="flex items-center justify-self-end"
+ style={{ WebkitAppRegion: "no-drag" } as CSSProperties}
+ >
+ <EditorPresetMenu t={t} presets={presets} />
+ <div
+ aria-hidden="true"
+ className="mx-2 h-4 w-px shrink-0 bg-foreground/10 opacity-0"
+ />
+ <EditorExportMenu
+ t={t}
+ exportSettings={exportSettings}
+ exportSession={exportSession}
+ exportDimensions={exportDimensions}
+ exportStatus={exportStatus}
+ hasCaptionsForSidecar={hasCaptionsForSidecar}
+ nvidiaCudaExportAvailable={nvidiaCudaExportAvailable}
+ experimentalNvidiaCudaExport={experimentalNvidiaCudaExport}
+ setExperimentalNvidiaCudaExport={setExperimentalNvidiaCudaExport}
+ handleOpenExportDropdown={handleOpenExportDropdown}
+ handleExportDropdownClose={handleExportDropdownClose}
+ handleCancelExport={handleCancelExport}
+ handleRetrySaveExport={handleRetrySaveExport}
+ handleStartExportFromDropdown={handleStartExportFromDropdown}
+ revealExportedFile={revealExportedFile}
+ openLightningIssues={openLightningIssues}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorPresetMenu.tsx b/src/components/video-editor/layout/EditorPresetMenu.tsx
new file mode 100644
index 00000000..1c360a55
--- /dev/null
+++ b/src/components/video-editor/layout/EditorPresetMenu.tsx
@@ -0,0 +1,137 @@
+import { BookmarkSimple, CaretDown, Check, X } from "@phosphor-icons/react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import type { useI18n } from "@/contexts/I18nContext";
+import { cn } from "@/lib/utils";
+import type { useVideoEditorPresets } from "../presets/useVideoEditorPresets";
+
+type Props = {
+ t: ReturnType<typeof useI18n>["t"];
+ presets: ReturnType<typeof useVideoEditorPresets>;
+};
+
+export function EditorPresetMenu({ t, presets }: Props) {
+ const {
+ editorPresets,
+ presetPopoverOpen,
+ setPresetPopoverOpen,
+ presetNameDraft,
+ setPresetNameDraft,
+ currentEditorPreset,
+ handleApplyEditorPreset,
+ handleDeleteEditorPreset,
+ handleSavePresetSubmit,
+ } = presets;
+
+ return (
+ <Popover open={presetPopoverOpen} onOpenChange={setPresetPopoverOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ title={t("editor.presets.open", "Open presets")}
+ aria-label={t("editor.presets.open", "Open presets")}
+ className="inline-flex items-center gap-1.5 bg-transparent p-0 text-sm font-medium tracking-tight text-foreground outline-none transition-opacity hover:opacity-80"
+ >
+ <span className="flex items-center gap-1.5">
+ <BookmarkSimple weight="fill" className="h-4 w-4" />
+ <span>
+ {currentEditorPreset?.name ?? t("editor.presets.label", "Presets")}
+ </span>
+ </span>
+ <CaretDown className="h-3.5 w-3.5 text-foreground" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ sideOffset={10}
+ className="w-[300px] rounded-2xl border border-foreground/10 bg-editor-surface-alt p-3 shadow-xl"
+ >
+ <div className="space-y-3">
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ handleSavePresetSubmit();
+ }}
+ className="space-y-2"
+ >
+ <p className="text-[11px] font-medium text-foreground">
+ {t("editor.presets.saveCurrentAs", "Save current preset as")}
+ </p>
+ <div className="flex items-center gap-2">
+ <Input
+ value={presetNameDraft}
+ onChange={(event) => setPresetNameDraft(event.target.value)}
+ className="h-9 rounded-xl border-foreground/10 bg-background/70 text-sm"
+ placeholder={t("editor.presets.namePlaceholder", "Preset name")}
+ aria-label={t("editor.presets.namePlaceholder", "Preset name")}
+ />
+ <Button
+ type="submit"
+ size="sm"
+ className="h-9 rounded-xl bg-[#2563EB] px-3 text-white hover:bg-[#1d4ed8]"
+ >
+ {t("common.actions.save", "Save")}
+ </Button>
+ </div>
+ </form>
+ <div className="space-y-2">
+ <p className="text-[11px] font-medium text-foreground">
+ {t("editor.presets.savedList", "Saved presets")}
+ </p>
+ <div className="max-h-56 space-y-1 overflow-y-auto pr-1 custom-scrollbar">
+ {editorPresets.length === 0 ? (
+ <div className="rounded-xl border border-dashed border-foreground/10 px-3 py-4 text-center text-[11px] text-muted-foreground">
+ {t("editor.presets.empty", "No presets yet.")}
+ </div>
+ ) : (
+ editorPresets.map((preset) => {
+ const isActive = preset.id === currentEditorPreset?.id;
+ return (
+ <div
+ key={preset.id}
+ className={cn(
+ "flex items-center gap-2 rounded-xl border px-2 py-2 text-sm transition-colors",
+ isActive
+ ? "border-[#2563EB]/20 bg-[#2563EB]/10 text-foreground"
+ : "border-foreground/8 bg-foreground/[0.03] text-muted-foreground hover:bg-foreground/[0.06] hover:text-foreground",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => handleApplyEditorPreset(preset.id)}
+ className="flex min-w-0 flex-1 items-center justify-between text-left"
+ >
+ <span className="truncate pr-3">{preset.name}</span>
+ {isActive ? (
+ <Check className="h-3.5 w-3.5 shrink-0 text-[#2563EB]" />
+ ) : null}
+ </button>
+ <button
+ type="button"
+ onClick={() => handleDeleteEditorPreset(preset.id)}
+ className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/8 hover:text-foreground"
+ aria-label={t(
+ "editor.presets.deleteAriaLabel",
+ "Delete preset {{name}}",
+ { name: preset.name },
+ )}
+ title={t(
+ "editor.presets.deleteAriaLabel",
+ "Delete preset {{name}}",
+ { name: preset.name },
+ )}
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorPreviewPanel.tsx b/src/components/video-editor/layout/EditorPreviewPanel.tsx
new file mode 100644
index 00000000..7c422db4
--- /dev/null
+++ b/src/components/video-editor/layout/EditorPreviewPanel.tsx
@@ -0,0 +1,391 @@
+import {
+ CaretDown,
+ Check,
+ Crop,
+ MagicWand,
+ MagnifyingGlassPlus,
+ Pause,
+ Play,
+ Plus,
+ Scissors,
+ SkipBack,
+ SkipForward,
+ SpeakerHigh,
+ SpeakerLow,
+ SpeakerX,
+} from "@phosphor-icons/react";
+import type { Dispatch, RefObject, SetStateAction } from "react";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import type { useI18n } from "@/contexts/I18nContext";
+import { ASPECT_RATIOS, type AspectRatio, getAspectRatioLabel } from "@/utils/aspectRatioUtils";
+import type { useVideoEditorAudio } from "../audio/useVideoEditorAudio";
+import type { CaptionEditTarget } from "../captionEditing";
+import type { useAnnotationRegionCommands } from "../hooks/useAnnotationRegionCommands";
+import type { useEditorPlaybackControls } from "../hooks/useEditorPlaybackControls";
+import type { useTimelineProjection } from "../hooks/useTimelineProjection";
+import type { useZoomRegionCommands } from "../hooks/useZoomRegionCommands";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useTimelineState } from "../state/useTimelineState";
+import type { TimelineEditorHandle } from "../timeline/TimelineEditor";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+import { EditorVideoPreview } from "./EditorVideoPreview";
+
+type Props = {
+ t: ReturnType<typeof useI18n>["t"];
+ videoPath: string | null;
+ previewVersion: number;
+ aspectRatio: AspectRatio;
+ setAspectRatio: Dispatch<SetStateAction<AspectRatio>>;
+ previewAspectRatioValue: number;
+ videoPlaybackRef: RefObject<VideoPlaybackRef>;
+ timelineRef: RefObject<TimelineEditorHandle>;
+ currentTime: number;
+ isPlaying: boolean;
+ previewVolume: number;
+ setPreviewVolume: Dispatch<SetStateAction<number>>;
+ suspendRendering: boolean;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ audio: ReturnType<typeof useVideoEditorAudio>;
+ projection: ReturnType<typeof useTimelineProjection>;
+ playback: ReturnType<typeof useEditorPlaybackControls>;
+ zoomCommands: ReturnType<typeof useZoomRegionCommands>;
+ annotationCommands: ReturnType<typeof useAnnotationRegionCommands>;
+ effectiveCursorTelemetry: ReturnType<typeof useTimelineState>["cursorTelemetry"];
+ effectiveShowCursor: boolean;
+ isCropped: boolean;
+ handleOpenCropEditor: () => void;
+ handleSaveAutoCaptionEdit: (target: CaptionEditTarget, text: string) => void;
+ handleSelectAnnotation: (id: string | null) => void;
+ setDuration: Dispatch<SetStateAction<number>>;
+ setIsPreviewReady: Dispatch<SetStateAction<boolean>>;
+ setCurrentTime: Dispatch<SetStateAction<number>>;
+ setIsPlaying: Dispatch<SetStateAction<boolean>>;
+ setError: Dispatch<SetStateAction<string | null>>;
+};
+
+function formatTime(seconds: number) {
+ if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
+}
+
+export function EditorPreviewPanel(props: Props) {
+ const {
+ t,
+ videoPath,
+ previewVersion,
+ aspectRatio,
+ setAspectRatio,
+ previewAspectRatioValue,
+ videoPlaybackRef,
+ timelineRef,
+ currentTime,
+ isPlaying,
+ previewVolume,
+ setPreviewVolume,
+ suspendRendering,
+ appearance,
+ timeline,
+ audio,
+ projection,
+ playback,
+ zoomCommands,
+ annotationCommands,
+ effectiveCursorTelemetry,
+ effectiveShowCursor,
+ isCropped,
+ handleOpenCropEditor,
+ handleSaveAutoCaptionEdit,
+ handleSelectAnnotation,
+ setDuration,
+ setIsPreviewReady,
+ setCurrentTime,
+ setIsPlaying,
+ setError,
+ } = props;
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-3">
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">
+ <div className="flex flex-shrink-0 items-center justify-center gap-2 py-1.5">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1 px-2 text-xs text-muted-foreground transition-all hover:bg-foreground/10 hover:text-foreground"
+ >
+ <span className="font-medium">
+ {getAspectRatioLabel(aspectRatio)}
+ </span>
+ <CaretDown className="h-3 w-3" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="center"
+ className="border-foreground/10 bg-editor-surface-alt"
+ >
+ {ASPECT_RATIOS.map((ratio) => (
+ <DropdownMenuItem
+ key={ratio}
+ onClick={() => setAspectRatio(ratio)}
+ className="flex cursor-pointer items-center justify-between gap-3 text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
+ >
+ <span>{getAspectRatioLabel(ratio)}</span>
+ {aspectRatio === ratio ? (
+ <Check className="h-3 w-3 text-[#2563EB]" />
+ ) : null}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <div className="h-4 w-px bg-foreground/20" />
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={handleOpenCropEditor}
+ className="h-7 gap-1.5 px-2 text-xs text-muted-foreground transition-all hover:bg-foreground/10 hover:text-foreground"
+ >
+ <Crop className="h-3.5 w-3.5" />
+ <span className="font-medium">{t("settings.crop.title")}</span>
+ {isCropped ? (
+ <span className="h-1.5 w-1.5 rounded-full bg-[#2563EB]" />
+ ) : null}
+ </Button>
+ </div>
+ <div
+ className="flex min-h-0 w-full flex-1 items-stretch"
+ style={{ flex: "1 1 auto", margin: "6px 0 0" }}
+ >
+ <div className="flex min-w-0 flex-1 items-center justify-center px-1">
+ <div
+ className="relative"
+ style={{
+ width: "auto",
+ height: "100%",
+ aspectRatio: previewAspectRatioValue,
+ maxWidth: "100%",
+ margin: "0 auto",
+ boxSizing: "border-box",
+ }}
+ >
+ <EditorVideoPreview
+ videoPath={videoPath}
+ previewVersion={previewVersion}
+ aspectRatio={aspectRatio}
+ playbackRef={videoPlaybackRef}
+ currentTime={currentTime}
+ isPlaying={isPlaying}
+ previewVolume={previewVolume}
+ suspendRendering={suspendRendering}
+ appearance={appearance}
+ timeline={timeline}
+ audio={audio}
+ effectiveZoomRegions={projection.effectiveZoomRegions}
+ effectiveSpeedRegions={projection.effectiveSpeedRegions}
+ effectiveCursorTelemetry={effectiveCursorTelemetry}
+ effectiveShowCursor={effectiveShowCursor}
+ setDuration={setDuration}
+ setIsPreviewReady={setIsPreviewReady}
+ setCurrentTime={setCurrentTime}
+ setIsPlaying={setIsPlaying}
+ setError={setError}
+ handlers={{
+ onSelectZoom: zoomCommands.handleSelectZoom,
+ onZoomFocusChange: zoomCommands.handleZoomFocusChange,
+ onEditAutoCaption: handleSaveAutoCaptionEdit,
+ onSelectAnnotation: handleSelectAnnotation,
+ onAnnotationPositionChange:
+ annotationCommands.handleAnnotationPositionChange,
+ onAnnotationSizeChange:
+ annotationCommands.handleAnnotationSizeChange,
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="relative flex flex-shrink-0 items-center px-1 py-1">
+ <div className="z-10 flex min-w-0 flex-1 items-center gap-1.5">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1 rounded-full border border-foreground/[0.08] bg-foreground/[0.04] px-2.5 text-[11px] text-foreground/65 shadow-[inset_0_1px_0_hsl(var(--foreground)/0.06)] transition-all hover:bg-foreground/[0.08] hover:text-foreground"
+ >
+ <Plus className="h-3.5 w-3.5" />
+ <span className="font-medium">{t("editor.toolbar.addLayer")}</span>
+ <CaretDown className="h-3 w-3" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="border-foreground/10 bg-editor-surface-alt"
+ >
+ <DropdownMenuItem
+ onClick={() => {
+ const nextTrack =
+ timeline.annotationRegions.length > 0
+ ? Math.max(
+ ...timeline.annotationRegions.map(
+ (region) => region.trackIndex ?? 0,
+ ),
+ ) + 1
+ : 0;
+ timelineRef.current?.addAnnotation(nextTrack);
+ }}
+ className="cursor-pointer text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
+ >
+ {t("timeline.annotation.label")}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => {
+ const nextTrack =
+ timeline.audioRegions.length > 0
+ ? Math.max(
+ ...timeline.audioRegions.map(
+ (region) => region.trackIndex ?? 0,
+ ),
+ ) + 1
+ : 0;
+ timelineRef.current?.addAudio(nextTrack);
+ }}
+ className="cursor-pointer text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
+ >
+ {t("timeline.audio.label")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <div className="mx-1 h-4 w-px bg-foreground/10" />
+ <Button
+ onClick={() => timelineRef.current?.addZoom()}
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-[#2563EB]/10 hover:text-[#2563EB]"
+ title={t("timeline.zoom.addZoom")}
+ >
+ <MagnifyingGlassPlus className="h-4 w-4" />
+ </Button>
+ <Button
+ onClick={() => timelineRef.current?.suggestZooms()}
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-[#2563EB]/10 hover:text-[#2563EB]"
+ title={t("timeline.zoom.suggestZooms")}
+ >
+ <MagicWand className="h-4 w-4" />
+ </Button>
+ <Button
+ onClick={() => timelineRef.current?.splitClip()}
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-foreground/10 hover:text-foreground"
+ title={t("editor.toolbar.splitClip")}
+ >
+ <Scissors className="h-4 w-4" />
+ </Button>
+ </div>
+
+ <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center">
+ <div className="pointer-events-auto flex items-center gap-1.5">
+ <span className="mr-1 text-[10px] font-medium tabular-nums text-muted-foreground">
+ {formatTime(projection.timelinePlayheadTime)}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-foreground/10 hover:text-foreground"
+ title={t("editor.playback.skipBack")}
+ onClick={playback.handlePreviewSkipBack}
+ >
+ <SkipBack className="h-3.5 w-3.5" weight="fill" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className={`h-7 w-7 rounded-full border border-foreground/10 shadow-[0_8px_18px_rgba(0,0,0,0.18)] transition-all ${isPlaying ? "bg-foreground/10 text-foreground hover:bg-foreground/20" : "bg-neutral-800 text-white hover:bg-neutral-700 dark:bg-white dark:text-black dark:hover:bg-white/90"}`}
+ onClick={playback.togglePlayPause}
+ title={isPlaying ? "Pause" : "Play"}
+ >
+ {isPlaying ? (
+ <Pause className="h-3.5 w-3.5" weight="fill" />
+ ) : (
+ <Play className="h-3.5 w-3.5" weight="fill" />
+ )}
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 rounded-full text-muted-foreground transition-all hover:bg-foreground/10 hover:text-foreground"
+ title={t("editor.playback.skipForward")}
+ onClick={playback.handlePreviewSkipForward}
+ >
+ <SkipForward className="h-3.5 w-3.5" weight="fill" />
+ </Button>
+ <span className="ml-1 text-[10px] font-medium tabular-nums text-muted-foreground/70">
+ {formatTime(projection.timelineDuration)}
+ </span>
+ </div>
+ </div>
+
+ <div className="z-10 ml-auto flex items-center gap-2">
+ <div className="flex items-center gap-1.5">
+ <button
+ type="button"
+ className="text-muted-foreground transition-colors hover:text-foreground"
+ title={t("editor.playback.muteUnmute")}
+ onClick={() => setPreviewVolume(previewVolume <= 0.001 ? 1 : 0)}
+ >
+ {previewVolume <= 0.001 ? (
+ <SpeakerX className="h-3.5 w-3.5" />
+ ) : previewVolume < 0.5 ? (
+ <SpeakerLow className="h-3.5 w-3.5" />
+ ) : (
+ <SpeakerHigh className="h-3.5 w-3.5" />
+ )}
+ </button>
+ <div className="relative flex h-7 w-24 select-none items-center overflow-hidden rounded-full border border-foreground/[0.06] bg-editor-bg/80 shadow-[inset_0_1px_0_hsl(var(--foreground)/0.06)]">
+ <div
+ className="absolute inset-y-[3px] left-[3px] right-auto rounded-[10px] bg-foreground/[0.08]"
+ style={{
+ width:
+ previewVolume > 0
+ ? `max(calc(${previewVolume * 100}% - 6px), 1.2rem)`
+ : 0,
+ }}
+ />
+ <div
+ className="pointer-events-none absolute bottom-[18%] top-[18%] z-10 w-0.5 rounded-full bg-foreground/95 shadow-[0_0_10px_rgba(37,99,235,0.28)]"
+ style={{ left: `calc(${previewVolume * 100}% - 8px)` }}
+ />
+ <span className="pointer-events-none relative z-10 pl-2 text-[10px] font-medium text-muted-foreground">
+ {Math.round(previewVolume * 100)}%
+ </span>
+ <input
+ type="range"
+ min="0"
+ max="1"
+ step="0.01"
+ value={previewVolume}
+ onChange={(event) => setPreviewVolume(Number(event.target.value))}
+ className="absolute inset-0 h-full w-full cursor-ew-resize opacity-0"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorShell.tsx b/src/components/video-editor/layout/EditorShell.tsx
new file mode 100644
index 00000000..b2defeb3
--- /dev/null
+++ b/src/components/video-editor/layout/EditorShell.tsx
@@ -0,0 +1,260 @@
+import type { ComponentProps } from "react";
+import { EditorAnnouncementBanner } from "@/components/announcements/EditorAnnouncementBanner";
+import { Toaster } from "@/components/ui/sonner";
+import type { useI18n } from "@/contexts/I18nContext";
+import type { useEditorExportController } from "../export/useEditorExportController";
+import type { useExportDimensions } from "../export/useExportDimensions";
+import type { useExportSession } from "../export/useExportSession";
+import type { useExportSettings } from "../export/useExportSettings";
+import type { useTimelineEditingController } from "../hooks/useTimelineEditingController";
+import type { useVideoEditorPresets } from "../presets/useVideoEditorPresets";
+import type { useEditorProjectController } from "../project/useEditorProjectController";
+import { SettingsPanel } from "../SettingsPanel";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useEditorUiState } from "../state/useEditorUiState";
+import type { useProjectState } from "../state/useProjectState";
+import type { useTimelineState } from "../state/useTimelineState";
+import { CropEditorDialog } from "./CropEditorDialog";
+import { EditorDialogs } from "./EditorDialogs";
+import { EditorHeader } from "./EditorHeader";
+import { EditorPreviewPanel } from "./EditorPreviewPanel";
+import { EditorSidebar } from "./EditorSidebar";
+import { EditorTimelinePanel } from "./EditorTimelinePanel";
+
+type Props = {
+ t: ReturnType<typeof useI18n>["t"];
+ project: ReturnType<typeof useProjectState>;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ ui: ReturnType<typeof useEditorUiState>;
+ presets: ReturnType<typeof useVideoEditorPresets>;
+ projectController: ReturnType<typeof useEditorProjectController>;
+ editing: ReturnType<typeof useTimelineEditingController>;
+ exportController: ReturnType<typeof useEditorExportController>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ exportSession: ReturnType<typeof useExportSession>;
+ exportDimensions: ReturnType<typeof useExportDimensions>;
+ settingsPanelProps: ComponentProps<typeof SettingsPanel>;
+ headerLeftControlsPaddingClass: string;
+ hasCaptionsForSidecar: boolean;
+ nvidiaCudaExportAvailable: boolean;
+ experimentalNvidiaCudaExport: boolean;
+ setExperimentalNvidiaCudaExport: (enabled: boolean) => void;
+ effectiveShowCursor: boolean;
+ previewAspectRatioValue: number;
+};
+
+export function EditorShell(props: Props) {
+ const {
+ t,
+ project,
+ appearance,
+ timeline,
+ ui,
+ presets,
+ projectController,
+ editing,
+ exportController,
+ exportSettings,
+ exportSession,
+ exportDimensions,
+ settingsPanelProps,
+ headerLeftControlsPaddingClass,
+ hasCaptionsForSidecar,
+ nvidiaCudaExportAvailable,
+ experimentalNvidiaCudaExport,
+ setExperimentalNvidiaCudaExport,
+ effectiveShowCursor,
+ previewAspectRatioValue,
+ } = props;
+ const {
+ snapshot,
+ history,
+ lifecycle,
+ autoCaption,
+ saveActions,
+ openActions,
+ hasUnsavedChanges,
+ } = projectController;
+ const {
+ cursor,
+ projection,
+ audio,
+ playback,
+ captionCommands,
+ zoomCommands,
+ clipCommands,
+ audioCommands,
+ annotationCommands,
+ handleSelectAnnotation,
+ handleAutoSuggestZoomsConsumed,
+ } = editing;
+ const { dialogActions, status: exportStatus, openLightningIssues } = exportController;
+ const editorDialogs = (
+ <EditorDialogs
+ t={t}
+ projectSaveDialogOpen={project.projectSaveDialogOpen}
+ setProjectSaveDialogOpen={project.setProjectSaveDialogOpen}
+ projectSaveDialogDraft={project.projectSaveDialogDraft}
+ setProjectSaveDialogDraft={project.setProjectSaveDialogDraft}
+ projectSaveDialogInputRef={ui.projectSaveDialogInputRef}
+ isSavingProjectDialog={project.isSavingProjectDialog}
+ resolveProjectSaveDialog={lifecycle.resolveProjectSaveDialog}
+ handleProjectSaveDialogSubmit={saveActions.handleProjectSaveDialogSubmit}
+ unsavedChangesDialogOpen={project.unsavedChangesDialogOpen}
+ setUnsavedChangesDialogOpen={project.setUnsavedChangesDialogOpen}
+ unsavedChangesDialogActionLabel={project.unsavedChangesDialogActionLabel}
+ resolveUnsavedChangesDialog={lifecycle.resolveUnsavedChangesDialog}
+ projectBrowserOpen={project.projectBrowserOpen}
+ setProjectBrowserOpen={project.setProjectBrowserOpen}
+ projectLibraryEntries={project.projectLibraryEntries}
+ projectBrowserAnchorRef={
+ project.error ? ui.projectBrowserFallbackTriggerRef : ui.projectBrowserTriggerRef
+ }
+ handleImportMediaOrProject={openActions.handleImportMediaOrProject}
+ handleOpenProjectFromLibrary={openActions.handleOpenProjectFromLibrary}
+ nativeCaptureUnavailableModalOpen={ui.nativeCaptureUnavailableModalOpen}
+ setNativeCaptureUnavailableModalOpen={ui.setNativeCaptureUnavailableModalOpen}
+ />
+ );
+ if (project.loading)
+ return (
+ <div className="flex h-screen items-center justify-center bg-background">
+ <div className="text-foreground">Loading video...</div>
+ {editorDialogs}
+ <Toaster className="pointer-events-auto" />
+ </div>
+ );
+ if (project.error)
+ return (
+ <div className="flex h-screen items-center justify-center bg-background">
+ <div className="flex flex-col items-center gap-3">
+ <div className="text-destructive">{project.error}</div>
+ <button
+ ref={ui.projectBrowserFallbackTriggerRef}
+ type="button"
+ onClick={openActions.handleOpenProjectBrowser}
+ className="rounded-[5px] bg-neutral-800 px-3 py-1.5 text-sm font-semibold text-white shadow-[0_14px_32px_rgba(0,0,0,0.18)] transition-colors hover:bg-neutral-700 dark:bg-white dark:text-black dark:hover:bg-white/90"
+ >
+ Open Projects
+ </button>
+ </div>
+ {editorDialogs}
+ <Toaster className="pointer-events-auto" />
+ </div>
+ );
+
+ return (
+ <div className="flex h-screen flex-col overflow-hidden bg-editor-bg text-foreground selection:bg-[#2563EB]/30">
+ <EditorHeader
+ t={t}
+ headerLeftControlsPaddingClass={headerLeftControlsPaddingClass}
+ project={project}
+ projectBrowserTriggerRef={ui.projectBrowserTriggerRef}
+ projectNameInputRef={ui.projectNameInputRef}
+ projectDisplayName={snapshot.projectDisplayName}
+ hasUnsavedChanges={hasUnsavedChanges}
+ canUndo={history.canUndo}
+ canRedo={history.canRedo}
+ handleOpenProjectBrowser={openActions.handleOpenProjectBrowser}
+ handleUndo={history.handleUndo}
+ handleRedo={history.handleRedo}
+ handleProjectNameSubmit={saveActions.handleProjectNameSubmit}
+ closeProjectNameEditor={saveActions.closeProjectNameEditor}
+ presets={presets}
+ exportSettings={exportSettings}
+ exportSession={exportSession}
+ exportDimensions={exportDimensions}
+ exportStatus={exportStatus}
+ hasCaptionsForSidecar={hasCaptionsForSidecar}
+ nvidiaCudaExportAvailable={nvidiaCudaExportAvailable}
+ experimentalNvidiaCudaExport={experimentalNvidiaCudaExport}
+ setExperimentalNvidiaCudaExport={setExperimentalNvidiaCudaExport}
+ handleOpenExportDropdown={dialogActions.handleOpenExportDropdown}
+ handleExportDropdownClose={dialogActions.handleExportDropdownClose}
+ handleCancelExport={dialogActions.handleCancelExport}
+ handleRetrySaveExport={dialogActions.handleRetrySaveExport}
+ handleStartExportFromDropdown={dialogActions.handleStartExportFromDropdown}
+ revealExportedFile={dialogActions.revealExportedFile}
+ openLightningIssues={openLightningIssues}
+ />
+ <EditorAnnouncementBanner />
+ <div className="relative flex min-h-0 flex-1 flex-col gap-3 p-4">
+ <div className="relative z-10 flex min-h-0 flex-1 gap-3">
+ <EditorSidebar
+ t={t}
+ activeSection={ui.activeEffectSection}
+ setActiveSection={ui.setActiveEffectSection}
+ settingsPanelProps={settingsPanelProps}
+ />
+ <EditorPreviewPanel
+ t={t}
+ videoPath={project.videoPath}
+ previewVersion={ui.previewVersion}
+ aspectRatio={ui.aspectRatio}
+ setAspectRatio={ui.setAspectRatio}
+ previewAspectRatioValue={previewAspectRatioValue}
+ videoPlaybackRef={ui.videoPlaybackRef}
+ timelineRef={ui.timelineRef}
+ currentTime={ui.currentTime}
+ isPlaying={ui.isPlaying}
+ previewVolume={ui.previewVolume}
+ setPreviewVolume={ui.setPreviewVolume}
+ suspendRendering={exportStatus.shouldSuspendPreviewRendering}
+ appearance={appearance}
+ timeline={timeline}
+ audio={audio}
+ projection={projection}
+ playback={playback}
+ zoomCommands={zoomCommands}
+ annotationCommands={annotationCommands}
+ effectiveCursorTelemetry={cursor.effectiveCursorTelemetry}
+ effectiveShowCursor={effectiveShowCursor}
+ isCropped={ui.isCropped}
+ handleOpenCropEditor={ui.handleOpenCropEditor}
+ handleSaveAutoCaptionEdit={autoCaption.handleSaveAutoCaptionEdit}
+ handleSelectAnnotation={handleSelectAnnotation}
+ setDuration={ui.setDuration}
+ setIsPreviewReady={ui.setIsPreviewReady}
+ setCurrentTime={ui.setCurrentTime}
+ setIsPlaying={ui.setIsPlaying}
+ setError={project.setError}
+ />
+ </div>
+ <EditorTimelinePanel
+ timelineRef={ui.timelineRef}
+ timeline={timeline}
+ projection={projection}
+ playback={playback}
+ audio={audio}
+ zoomCommands={zoomCommands}
+ clipCommands={clipCommands}
+ audioCommands={audioCommands}
+ captionCommands={captionCommands}
+ annotationCommands={annotationCommands}
+ videoPath={project.videoPath}
+ videoSourcePath={project.videoSourcePath}
+ cursorTelemetrySourcePath={timeline.cursorTelemetrySourcePath}
+ normalizedCursorTelemetry={cursor.normalizedCursorTelemetry}
+ autoSuggestZoomsTrigger={ui.autoSuggestZoomsTrigger}
+ handleAutoSuggestZoomsConsumed={handleAutoSuggestZoomsConsumed}
+ disableSuggestedZooms={!appearance.autoApplyFreshRecordingAutoZooms}
+ currentTime={ui.currentTime}
+ handleSelectAnnotation={handleSelectAnnotation}
+ />
+ </div>
+ {editorDialogs}
+ <CropEditorDialog
+ open={ui.showCropModal}
+ t={t}
+ videoElement={ui.videoPlaybackRef.current?.video ?? null}
+ cropRegion={appearance.cropRegion}
+ setCropRegion={appearance.setCropRegion}
+ aspectRatio={ui.aspectRatio}
+ onCancel={ui.handleCancelCropEditor}
+ onDone={ui.handleCloseCropEditor}
+ />
+ <Toaster className="pointer-events-auto" />
+ </div>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorSidebar.tsx b/src/components/video-editor/layout/EditorSidebar.tsx
new file mode 100644
index 00000000..d3c1bcd0
--- /dev/null
+++ b/src/components/video-editor/layout/EditorSidebar.tsx
@@ -0,0 +1,121 @@
+import {
+ Camera,
+ ClosedCaptioning,
+ Cursor,
+ Gear,
+ PuzzlePiece,
+ Sparkle,
+ UserCircle,
+} from "@phosphor-icons/react";
+import { motion } from "motion/react";
+import type { ComponentProps, Dispatch, SetStateAction } from "react";
+import { useMemo } from "react";
+import { toast } from "sonner";
+import type { useI18n } from "@/contexts/I18nContext";
+import ExtensionManager from "../ExtensionManager";
+import { SettingsPanel } from "../SettingsPanel";
+import type { EditorEffectSection } from "../types";
+
+type Props = {
+ t: ReturnType<typeof useI18n>["t"];
+ activeSection: EditorEffectSection;
+ setActiveSection: Dispatch<SetStateAction<EditorEffectSection>>;
+ settingsPanelProps: ComponentProps<typeof SettingsPanel>;
+};
+
+export function EditorSidebar({ t, activeSection, setActiveSection, settingsPanelProps }: Props) {
+ const sections = useMemo(
+ () => [
+ { id: "scene" as const, label: t("settings.sections.scene", "Scene"), icon: Sparkle },
+ { id: "cursor" as const, label: t("settings.sections.cursor", "Cursor"), icon: Cursor },
+ { id: "webcam" as const, label: t("settings.sections.webcam", "Webcam"), icon: Camera },
+ {
+ id: "captions" as const,
+ label: t("settings.sections.captions", "Captions"),
+ icon: ClosedCaptioning,
+ },
+ {
+ id: "settings" as const,
+ label: t("settings.sections.settings", "Settings"),
+ icon: Gear,
+ },
+ {
+ id: "extensions" as const,
+ label: t("settings.sections.extensions", "Extensions"),
+ icon: PuzzlePiece,
+ },
+ ],
+ [t],
+ );
+ return (
+ <div className="flex flex-shrink-0 gap-1.5">
+ <div className="flex flex-shrink-0 flex-col items-center gap-0.5 px-2 py-2">
+ {sections.map((section) => {
+ const isActive = activeSection === section.id;
+ return (
+ <div key={section.id} className="flex items-center">
+ <motion.button
+ type="button"
+ onClick={() => setActiveSection(section.id)}
+ title={section.label}
+ className="group relative flex h-9 w-9 items-center justify-center rounded-lg outline-none focus:outline-none focus-visible:outline-none"
+ animate={{ opacity: isActive ? 1 : 0.55 }}
+ transition={{ duration: 0.14 }}
+ >
+ {isActive ? (
+ <motion.span
+ layoutId="rail-active-bg"
+ className="absolute inset-0 rounded-lg bg-foreground/[0.08]"
+ transition={{ type: "spring", stiffness: 450, damping: 35 }}
+ />
+ ) : null}
+ <motion.span
+ className="relative z-10"
+ animate={{
+ color: isActive ? "#2563EB" : "hsl(var(--foreground))",
+ }}
+ transition={{ duration: 0.14 }}
+ >
+ <section.icon
+ className="h-[27px] w-[27px]"
+ weight={isActive ? "fill" : "regular"}
+ />
+ </motion.span>
+ </motion.button>
+ <div className="ml-1.5 h-1.5 w-1.5 flex-shrink-0">
+ {isActive ? (
+ <motion.span
+ layoutId="rail-active-dot"
+ className="block h-1.5 w-1.5 rounded-full bg-[#2563EB]"
+ initial={{ opacity: 0, scale: 0.5 }}
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, scale: 0.5 }}
+ transition={{ type: "spring", stiffness: 500, damping: 32 }}
+ />
+ ) : null}
+ </div>
+ </div>
+ );
+ })}
+ <div className="mt-auto flex flex-col items-center gap-0.5 pt-3">
+ <motion.button
+ type="button"
+ onClick={() => toast.info("Account coming soon")}
+ title="Account"
+ className="group relative flex h-9 w-9 items-center justify-center rounded-lg text-foreground/55 outline-none transition hover:text-foreground focus:outline-none focus-visible:outline-none"
+ whileHover={{ opacity: 1 }}
+ initial={{ opacity: 0.55 }}
+ >
+ <motion.span className="absolute inset-0 rounded-lg bg-foreground/[0.04] opacity-0 transition group-hover:opacity-100" />
+ <UserCircle className="relative z-10 h-[22px] w-[22px]" />
+ </motion.button>
+ </div>
+ </div>
+ {activeSection === "extensions" ? (
+ <ExtensionManager />
+ ) : (
+ <SettingsPanel {...settingsPanelProps} />
+ )}
+ </div>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorTimelinePanel.tsx b/src/components/video-editor/layout/EditorTimelinePanel.tsx
new file mode 100644
index 00000000..78bfca53
--- /dev/null
+++ b/src/components/video-editor/layout/EditorTimelinePanel.tsx
@@ -0,0 +1,120 @@
+import type { RefObject } from "react";
+import type { useVideoEditorAudio } from "../audio/useVideoEditorAudio";
+import type { useAnnotationRegionCommands } from "../hooks/useAnnotationRegionCommands";
+import type { useAudioRegionCommands } from "../hooks/useAudioRegionCommands";
+import type { useCaptionCommands } from "../hooks/useCaptionCommands";
+import type { useClipRegionCommands } from "../hooks/useClipRegionCommands";
+import type { useEditorPlaybackControls } from "../hooks/useEditorPlaybackControls";
+import type { useTimelineProjection } from "../hooks/useTimelineProjection";
+import type { useZoomRegionCommands } from "../hooks/useZoomRegionCommands";
+import type { useTimelineState } from "../state/useTimelineState";
+import TimelineEditor, { type TimelineEditorHandle } from "../timeline/TimelineEditor";
+
+type Props = {
+ timelineRef: RefObject<TimelineEditorHandle>;
+ timeline: ReturnType<typeof useTimelineState>;
+ projection: ReturnType<typeof useTimelineProjection>;
+ playback: ReturnType<typeof useEditorPlaybackControls>;
+ audio: ReturnType<typeof useVideoEditorAudio>;
+ zoomCommands: ReturnType<typeof useZoomRegionCommands>;
+ clipCommands: ReturnType<typeof useClipRegionCommands>;
+ audioCommands: ReturnType<typeof useAudioRegionCommands>;
+ captionCommands: ReturnType<typeof useCaptionCommands>;
+ annotationCommands: ReturnType<typeof useAnnotationRegionCommands>;
+ videoPath: string | null;
+ videoSourcePath: string | null;
+ cursorTelemetrySourcePath: string | null;
+ normalizedCursorTelemetry: ReturnType<typeof useTimelineState>["cursorTelemetry"];
+ autoSuggestZoomsTrigger: number;
+ handleAutoSuggestZoomsConsumed: () => void;
+ disableSuggestedZooms: boolean;
+ currentTime: number;
+ handleSelectAnnotation: (id: string | null) => void;
+};
+
+export function EditorTimelinePanel(props: Props) {
+ const {
+ timelineRef,
+ timeline,
+ projection,
+ playback,
+ audio,
+ zoomCommands,
+ clipCommands,
+ audioCommands,
+ captionCommands,
+ annotationCommands,
+ videoPath,
+ videoSourcePath,
+ cursorTelemetrySourcePath,
+ normalizedCursorTelemetry,
+ autoSuggestZoomsTrigger,
+ handleAutoSuggestZoomsConsumed,
+ disableSuggestedZooms,
+ currentTime,
+ handleSelectAnnotation,
+ } = props;
+
+ return (
+ <div className="flex flex-shrink-0 flex-col" style={{ height: "15%", minHeight: 160 }}>
+ <TimelineEditor
+ ref={timelineRef}
+ videoDuration={projection.timelineDuration}
+ currentTime={currentTime}
+ playheadTime={projection.timelinePlayheadTime}
+ onSeek={playback.handleTimelineSeek}
+ videoPath={videoPath}
+ videoSourcePath={videoSourcePath}
+ cursorTelemetrySourcePath={cursorTelemetrySourcePath}
+ cursorTelemetry={normalizedCursorTelemetry}
+ autoSuggestZoomsTrigger={autoSuggestZoomsTrigger}
+ onAutoSuggestZoomsConsumed={handleAutoSuggestZoomsConsumed}
+ disableSuggestedZooms={disableSuggestedZooms}
+ zoomRegions={timeline.zoomRegions}
+ onZoomAdded={zoomCommands.handleZoomAdded}
+ onZoomSuggested={zoomCommands.handleZoomSuggested}
+ onZoomSpanChange={zoomCommands.handleZoomSpanChange}
+ onZoomDelete={zoomCommands.handleZoomDelete}
+ selectedZoomId={timeline.selectedZoomId}
+ onSelectZoom={zoomCommands.handleSelectZoom}
+ trimRegions={timeline.trimRegions}
+ clipRegions={timeline.clipRegions}
+ onClipSplit={clipCommands.handleClipSplit}
+ onClipSpanChange={clipCommands.handleClipSpanChange}
+ selectedClipId={timeline.selectedClipId}
+ onSelectClip={clipCommands.handleSelectClip}
+ audioRegions={timeline.audioRegions}
+ onAudioAdded={audioCommands.handleAudioAdded}
+ onAudioSpanChange={audioCommands.handleAudioSpanChange}
+ onAudioDelete={audioCommands.handleAudioDelete}
+ selectedAudioId={timeline.selectedAudioId}
+ onSelectAudio={audioCommands.handleSelectAudio}
+ captionRegions={projection.effectiveCaptionRegions}
+ onCaptionSpanChange={(id, span) =>
+ captionCommands.handleCaptionRetime(id, {
+ startMs: projection.mapTimelineTimeToSourceTime(span.start),
+ endMs: projection.mapTimelineTimeToSourceTime(span.end),
+ })
+ }
+ selectedCaptionId={timeline.selectedCaptionId}
+ onSelectCaption={captionCommands.handleSelectCaption}
+ onCaptionDelete={captionCommands.handleCaptionDelete}
+ onCaptionAdded={captionCommands.handleCaptionAdded}
+ captionsEnabled={timeline.autoCaptionSettings.enabled}
+ captionQuickAddEnabled={timeline.autoCaptionSettings.timelineQuickAdd}
+ annotationRegions={timeline.annotationRegions}
+ onAnnotationAdded={annotationCommands.handleAnnotationAdded}
+ onAnnotationSpanChange={annotationCommands.handleAnnotationSpanChange}
+ onAnnotationDelete={annotationCommands.handleAnnotationDelete}
+ selectedAnnotationId={timeline.selectedAnnotationId}
+ onSelectAnnotation={handleSelectAnnotation}
+ showSourceAudioTrack={timeline.clipRegions.some((clip) => clip.showSourceAudio)}
+ sourceAudioResourceVersion={timeline.sourceAudioFallbackRefreshKey}
+ sourceAudioTrackSettings={audio.activeSourceAudioTrackSettings}
+ getSourceAudioTrackSettingsForClip={audio.getSourceAudioTrackSettingsForClip}
+ onSourceAudioAvailabilityChange={timeline.setHasClipSourceAudio}
+ onSourceAudioTracksMetaChange={audio.onSourceAudioTracksMetaChange}
+ />
+ </div>
+ );
+}
diff --git a/src/components/video-editor/layout/EditorVideoPreview.tsx b/src/components/video-editor/layout/EditorVideoPreview.tsx
new file mode 100644
index 00000000..93b90312
--- /dev/null
+++ b/src/components/video-editor/layout/EditorVideoPreview.tsx
@@ -0,0 +1,141 @@
+import type { ComponentProps, Dispatch, RefObject, SetStateAction } from "react";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import type { useVideoEditorAudio } from "../audio/useVideoEditorAudio";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useTimelineState } from "../state/useTimelineState";
+import type { CursorTelemetryPoint, SpeedRegion, ZoomRegion } from "../types";
+import VideoPlayback, { type VideoPlaybackRef } from "../VideoPlayback";
+
+type PlaybackProps = ComponentProps<typeof VideoPlayback>;
+type Handlers = Pick<
+ PlaybackProps,
+ | "onSelectZoom"
+ | "onZoomFocusChange"
+ | "onEditAutoCaption"
+ | "onSelectAnnotation"
+ | "onAnnotationPositionChange"
+ | "onAnnotationSizeChange"
+>;
+
+type Props = {
+ videoPath: string | null;
+ previewVersion: number;
+ aspectRatio: AspectRatio;
+ playbackRef: RefObject<VideoPlaybackRef>;
+ currentTime: number;
+ isPlaying: boolean;
+ previewVolume: number;
+ suspendRendering: boolean;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ audio: ReturnType<typeof useVideoEditorAudio>;
+ effectiveZoomRegions: ZoomRegion[];
+ effectiveSpeedRegions: SpeedRegion[];
+ effectiveCursorTelemetry: CursorTelemetryPoint[];
+ effectiveShowCursor: boolean;
+ setDuration: Dispatch<SetStateAction<number>>;
+ setIsPreviewReady: Dispatch<SetStateAction<boolean>>;
+ setCurrentTime: Dispatch<SetStateAction<number>>;
+ setIsPlaying: Dispatch<SetStateAction<boolean>>;
+ setError: Dispatch<SetStateAction<string | null>>;
+ handlers: Handlers;
+};
+
+export function EditorVideoPreview({
+ videoPath,
+ previewVersion,
+ aspectRatio,
+ playbackRef,
+ currentTime,
+ isPlaying,
+ previewVolume,
+ suspendRendering,
+ appearance,
+ timeline,
+ audio,
+ effectiveZoomRegions,
+ effectiveSpeedRegions,
+ effectiveCursorTelemetry,
+ effectiveShowCursor,
+ setDuration,
+ setIsPreviewReady,
+ setCurrentTime,
+ setIsPlaying,
+ setError,
+ handlers,
+}: Props) {
+ return (
+ <VideoPlayback
+ key={`${videoPath || "no-video"}:${previewVersion}:inline`}
+ aspectRatio={aspectRatio}
+ ref={playbackRef}
+ videoPath={videoPath || ""}
+ onDurationChange={setDuration}
+ onPreviewReadyChange={setIsPreviewReady}
+ onTimeUpdate={setCurrentTime}
+ currentTime={currentTime}
+ onPlayStateChange={setIsPlaying}
+ onError={setError}
+ wallpaper={appearance.wallpaper}
+ zoomRegions={effectiveZoomRegions}
+ selectedZoomId={timeline.selectedZoomId}
+ isPlaying={isPlaying}
+ showShadow={appearance.shadowIntensity > 0}
+ shadowIntensity={appearance.shadowIntensity}
+ backgroundBlur={appearance.backgroundBlur}
+ connectZooms={appearance.connectZooms}
+ zoomInDurationMs={appearance.zoomInDurationMs}
+ zoomInOverlapMs={appearance.zoomInOverlapMs}
+ zoomOutDurationMs={appearance.zoomOutDurationMs}
+ connectedZoomGapMs={appearance.connectedZoomGapMs}
+ connectedZoomDurationMs={appearance.connectedZoomDurationMs}
+ zoomInEasing={appearance.zoomInEasing}
+ zoomOutEasing={appearance.zoomOutEasing}
+ connectedZoomEasing={appearance.connectedZoomEasing}
+ borderRadius={0}
+ padding={appearance.padding}
+ cropRegion={appearance.cropRegion}
+ webcam={appearance.webcam}
+ webcamVideoPath={
+ appearance.webcam.sourcePath ? appearance.resolvedWebcamVideoUrl : null
+ }
+ trimRegions={timeline.trimRegions}
+ speedRegions={effectiveSpeedRegions}
+ annotationRegions={timeline.annotationRegions}
+ autoCaptions={timeline.autoCaptions}
+ autoCaptionSettings={timeline.autoCaptionSettings}
+ selectedAnnotationId={timeline.selectedAnnotationId}
+ cursorTelemetry={effectiveCursorTelemetry}
+ showCursor={effectiveShowCursor}
+ cursorStyle={appearance.cursorStyle}
+ cursorSize={appearance.cursorSize}
+ cursorSmoothing={appearance.cursorSmoothing}
+ cursorSpringStiffnessMultiplier={appearance.cursorSpringStiffnessMultiplier}
+ cursorSpringDampingMultiplier={appearance.cursorSpringDampingMultiplier}
+ cursorSpringMassMultiplier={appearance.cursorSpringMassMultiplier}
+ cameraSpringStiffnessMultiplier={appearance.cameraSpringStiffnessMultiplier}
+ cameraSpringDampingMultiplier={appearance.cameraSpringDampingMultiplier}
+ cameraSpringMassMultiplier={appearance.cameraSpringMassMultiplier}
+ zoomSmoothness={appearance.zoomSmoothness}
+ zoomClassicMode={appearance.zoomClassicMode}
+ zoomMotionBlur={appearance.zoomMotionBlur}
+ zoomMotionBlurTuning={appearance.zoomMotionBlurTuning}
+ cursorMotionBlur={appearance.cursorMotionBlur}
+ cursorClickEffect={appearance.cursorClickEffect}
+ cursorClickEffectColor={appearance.cursorClickEffectColor}
+ cursorClickEffectScale={appearance.cursorClickEffectScale}
+ cursorClickEffectOpacity={appearance.cursorClickEffectOpacity}
+ cursorClickEffectDurationMs={appearance.cursorClickEffectDurationMs}
+ cursorClickBounce={appearance.cursorClickBounce}
+ cursorClickBounceDuration={appearance.cursorClickBounceDuration}
+ cursorSway={appearance.cursorSway}
+ volume={
+ audio.shouldMutePreviewVideo || audio.isCurrentClipMuted
+ ? 0
+ : Math.max(0, Math.min(1, previewVolume * audio.embeddedSourcePreviewGain))
+ }
+ suspendRendering={suspendRendering}
+ {...handlers}
+ />
+ );
+}
diff --git a/src/components/video-editor/layout/useEditorSettingsPanelProps.ts b/src/components/video-editor/layout/useEditorSettingsPanelProps.ts
new file mode 100644
index 00000000..fc7427c2
--- /dev/null
+++ b/src/components/video-editor/layout/useEditorSettingsPanelProps.ts
@@ -0,0 +1,228 @@
+import type { ComponentProps, Dispatch, SetStateAction } from "react";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import type { useVideoEditorAudio } from "../audio/useVideoEditorAudio";
+import type { useAutoCaptionController } from "../captions/useAutoCaptionController";
+import type { useAnnotationRegionCommands } from "../hooks/useAnnotationRegionCommands";
+import type { useAudioRegionCommands } from "../hooks/useAudioRegionCommands";
+import type { useCaptionCommands } from "../hooks/useCaptionCommands";
+import type { useClipRegionCommands } from "../hooks/useClipRegionCommands";
+import type { useZoomRegionCommands } from "../hooks/useZoomRegionCommands";
+import { SettingsPanel } from "../SettingsPanel";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useTimelineState } from "../state/useTimelineState";
+import type { EditorEffectSection } from "../types";
+
+type Input = {
+ activeEffectSection: EditorEffectSection;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ audio: ReturnType<typeof useVideoEditorAudio>;
+ zoomCommands: ReturnType<typeof useZoomRegionCommands>;
+ clipCommands: ReturnType<typeof useClipRegionCommands>;
+ audioCommands: ReturnType<typeof useAudioRegionCommands>;
+ captionCommands: ReturnType<typeof useCaptionCommands>;
+ annotationCommands: ReturnType<typeof useAnnotationRegionCommands>;
+ autoCaptionController: ReturnType<typeof useAutoCaptionController>;
+ effectiveShowCursor: boolean;
+ handleShowCursorChange: (show: boolean) => void;
+ currentTime: number;
+ isPlaying: boolean;
+ aspectRatio: AspectRatio;
+ setAspectRatio: Dispatch<SetStateAction<AspectRatio>>;
+ whisperExecutablePath: string | null;
+ whisperModelPath: string | null;
+ whisperModelDownloadStatus: "idle" | "downloading" | "downloaded" | "error";
+ whisperModelDownloadProgress: number;
+ isGeneratingCaptions: boolean;
+ sessionNativeCaptureUnavailable: boolean;
+ setNativeCaptureUnavailableModalOpen: Dispatch<SetStateAction<boolean>>;
+ handleUploadWebcam: () => void;
+ handleClearWebcam: () => void;
+};
+
+export function useEditorSettingsPanelProps(input: Input): ComponentProps<typeof SettingsPanel> {
+ const {
+ activeEffectSection,
+ appearance,
+ timeline,
+ audio,
+ zoomCommands,
+ clipCommands,
+ audioCommands,
+ captionCommands,
+ annotationCommands,
+ autoCaptionController,
+ effectiveShowCursor,
+ handleShowCursorChange,
+ currentTime,
+ isPlaying,
+ aspectRatio,
+ setAspectRatio,
+ whisperExecutablePath,
+ whisperModelPath,
+ whisperModelDownloadStatus,
+ whisperModelDownloadProgress,
+ isGeneratingCaptions,
+ sessionNativeCaptureUnavailable,
+ setNativeCaptureUnavailableModalOpen,
+ handleUploadWebcam,
+ handleClearWebcam,
+ } = input;
+ const selectedZoom = timeline.zoomRegions.find(
+ (region) => region.id === timeline.selectedZoomId,
+ );
+ const selectedClip = timeline.clipRegions.find(
+ (region) => region.id === timeline.selectedClipId,
+ );
+ const selectedAudio = timeline.audioRegions.find(
+ (region) => region.id === timeline.selectedAudioId,
+ );
+
+ return {
+ panelMode: "editor",
+ activeEffectSection,
+ selected: appearance.wallpaper,
+ onWallpaperChange: appearance.setWallpaper,
+ selectedZoomDepth: selectedZoom?.depth ?? null,
+ onZoomDepthChange: (depth) =>
+ timeline.selectedZoomId && zoomCommands.handleZoomDepthChange(depth),
+ selectedZoomId: timeline.selectedZoomId,
+ selectedZoomMode: selectedZoom?.mode ?? (timeline.selectedZoomId ? "auto" : null),
+ onZoomModeChange: (mode) =>
+ timeline.selectedZoomId && zoomCommands.handleZoomModeChange(mode),
+ onZoomDelete: zoomCommands.handleZoomDelete,
+ selectedClipId: timeline.selectedClipId,
+ selectedClipSpeed: selectedClip?.speed ?? (timeline.selectedClipId ? 1 : null),
+ selectedClipMuted: selectedClip?.muted ?? (timeline.selectedClipId ? false : null),
+ selectedClipShowSourceAudio:
+ selectedClip?.showSourceAudio ?? (timeline.selectedClipId ? false : null),
+ onClipSpeedChange: clipCommands.handleClipSpeedChange,
+ onClipMutedChange: clipCommands.handleClipMutedChange,
+ onClipShowSourceAudioChange: clipCommands.handleClipShowSourceAudioChange,
+ onClipDelete: clipCommands.handleClipDelete,
+ hasClipSourceAudio: timeline.hasClipSourceAudio,
+ sourceAudioTrackMeta: audio.sourceAudioTrackMeta,
+ sourceAudioTrackSettings: audio.selectedClipSourceAudioTrackSettings,
+ onSourceAudioTrackVolumeChange: audio.onSelectedClipSourceAudioTrackVolumeChange,
+ onSourceAudioTrackNormalizeChange: audio.onSelectedClipSourceAudioTrackNormalizeChange,
+ selectedAudioId: timeline.selectedAudioId,
+ selectedAudioVolume: selectedAudio?.volume ?? null,
+ selectedAudioNormalize:
+ selectedAudio?.normalize ?? (timeline.selectedAudioId ? false : null),
+ onAudioVolumeChange: audioCommands.handleAudioVolumeChange,
+ onAudioNormalizeChange: audioCommands.handleAudioNormalizeChange,
+ onAudioDelete: audioCommands.handleAudioDelete,
+ shadowIntensity: appearance.shadowIntensity,
+ onShadowChange: appearance.setShadowIntensity,
+ backgroundBlur: appearance.backgroundBlur,
+ onBackgroundBlurChange: appearance.setBackgroundBlur,
+ autoApplyFreshRecordingAutoZooms: appearance.autoApplyFreshRecordingAutoZooms,
+ onAutoApplyFreshRecordingAutoZoomsChange: appearance.setAutoApplyFreshRecordingAutoZooms,
+ connectZooms: appearance.connectZooms,
+ onConnectZoomsChange: appearance.setConnectZooms,
+ zoomInDurationMs: appearance.zoomInDurationMs,
+ onZoomInDurationMsChange: appearance.setZoomInDurationMs,
+ zoomInOverlapMs: appearance.zoomInOverlapMs,
+ onZoomInOverlapMsChange: appearance.setZoomInOverlapMs,
+ zoomOutDurationMs: appearance.zoomOutDurationMs,
+ onZoomOutDurationMsChange: appearance.setZoomOutDurationMs,
+ connectedZoomGapMs: appearance.connectedZoomGapMs,
+ onConnectedZoomGapMsChange: appearance.setConnectedZoomGapMs,
+ connectedZoomDurationMs: appearance.connectedZoomDurationMs,
+ onConnectedZoomDurationMsChange: appearance.setConnectedZoomDurationMs,
+ zoomInEasing: appearance.zoomInEasing,
+ onZoomInEasingChange: appearance.setZoomInEasing,
+ zoomOutEasing: appearance.zoomOutEasing,
+ onZoomOutEasingChange: appearance.setZoomOutEasing,
+ connectedZoomEasing: appearance.connectedZoomEasing,
+ onConnectedZoomEasingChange: appearance.setConnectedZoomEasing,
+ showCursor: effectiveShowCursor,
+ onShowCursorChange: handleShowCursorChange,
+ loopCursor: appearance.loopCursor,
+ onLoopCursorChange: appearance.setLoopCursor,
+ cursorStyle: appearance.cursorStyle,
+ onCursorStyleChange: appearance.setCursorStyle,
+ cursorSize: appearance.cursorSize,
+ onCursorSizeChange: appearance.setCursorSize,
+ cursorSmoothing: appearance.cursorSmoothing,
+ onCursorSmoothingChange: appearance.setCursorSmoothing,
+ cursorSpringStiffnessMultiplier: appearance.cursorSpringStiffnessMultiplier,
+ onCursorSpringStiffnessMultiplierChange: appearance.setCursorSpringStiffnessMultiplier,
+ cursorSpringDampingMultiplier: appearance.cursorSpringDampingMultiplier,
+ onCursorSpringDampingMultiplierChange: appearance.setCursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier: appearance.cursorSpringMassMultiplier,
+ onCursorSpringMassMultiplierChange: appearance.setCursorSpringMassMultiplier,
+ cameraSpringStiffnessMultiplier: appearance.cameraSpringStiffnessMultiplier,
+ onCameraSpringStiffnessMultiplierChange: appearance.setCameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier: appearance.cameraSpringDampingMultiplier,
+ onCameraSpringDampingMultiplierChange: appearance.setCameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier: appearance.cameraSpringMassMultiplier,
+ onCameraSpringMassMultiplierChange: appearance.setCameraSpringMassMultiplier,
+ zoomClassicMode: appearance.zoomClassicMode,
+ onZoomClassicModeChange: appearance.setZoomClassicMode,
+ cursorClickEffect: appearance.cursorClickEffect,
+ cursorClickEffectColor: appearance.cursorClickEffectColor,
+ onCursorClickEffectChange: appearance.setCursorClickEffect,
+ onCursorClickEffectColorChange: appearance.setCursorClickEffectColor,
+ cursorClickEffectScale: appearance.cursorClickEffectScale,
+ onCursorClickEffectScaleChange: appearance.setCursorClickEffectScale,
+ cursorClickEffectOpacity: appearance.cursorClickEffectOpacity,
+ onCursorClickEffectOpacityChange: appearance.setCursorClickEffectOpacity,
+ cursorClickEffectDurationMs: appearance.cursorClickEffectDurationMs,
+ onCursorClickEffectDurationMsChange: appearance.setCursorClickEffectDurationMs,
+ cursorClickBounce: appearance.cursorClickBounce,
+ onCursorClickBounceChange: appearance.setCursorClickBounce,
+ cursorClickBounceDuration: appearance.cursorClickBounceDuration,
+ onCursorClickBounceDurationChange: appearance.setCursorClickBounceDuration,
+ cursorSway: appearance.cursorSway,
+ onCursorSwayChange: appearance.setCursorSway,
+ borderRadius: appearance.borderRadius,
+ onBorderRadiusChange: appearance.setBorderRadius,
+ webcam: appearance.webcam,
+ webcamPreviewSrc: appearance.webcam.sourcePath ? appearance.resolvedWebcamVideoUrl : null,
+ webcamPreviewCurrentTime: currentTime,
+ webcamPreviewPlaying: isPlaying,
+ onWebcamChange: appearance.setWebcam,
+ onUploadWebcam: handleUploadWebcam,
+ onClearWebcam: handleClearWebcam,
+ padding: appearance.padding,
+ onPaddingChange: appearance.setPadding,
+ cropRegion: appearance.cropRegion,
+ onCropChange: appearance.setCropRegion,
+ aspectRatio,
+ onAspectRatioChange: setAspectRatio,
+ selectedAnnotationId: timeline.selectedAnnotationId,
+ annotationRegions: timeline.annotationRegions,
+ autoCaptions: timeline.autoCaptions,
+ autoCaptionSettings: timeline.autoCaptionSettings,
+ whisperExecutablePath,
+ whisperModelPath,
+ whisperModelDownloadStatus,
+ whisperModelDownloadProgress,
+ isGeneratingCaptions,
+ onAutoCaptionSettingsChange: timeline.setAutoCaptionSettings,
+ onPickWhisperExecutable: autoCaptionController.handlePickWhisperExecutable,
+ onPickWhisperModel: autoCaptionController.handlePickWhisperModel,
+ onGenerateAutoCaptions: autoCaptionController.handleGenerateAutoCaptions,
+ onClearAutoCaptions: captionCommands.handleClearAutoCaptions,
+ captionCurrentTimeMs: Math.round(currentTime * 1000),
+ selectedCaptionId: timeline.selectedCaptionId,
+ onBeginCaptionEdit: captionCommands.handleBeginCaptionEdit,
+ onCaptionTextEdit: captionCommands.handleCaptionTextEdit,
+ onCaptionRetime: captionCommands.handleCaptionRetime,
+ onCaptionSplit: captionCommands.handleCaptionSplit,
+ onCaptionMerge: captionCommands.handleCaptionMerge,
+ onCaptionDelete: captionCommands.handleCaptionDelete,
+ onDownloadWhisperSmallModel: autoCaptionController.handleDownloadWhisperSmallModel,
+ onDeleteWhisperSmallModel: autoCaptionController.handleDeleteWhisperSmallModel,
+ nativeCaptureUnavailableSession: sessionNativeCaptureUnavailable,
+ onOpenNativeCaptureUnavailableModal: () => setNativeCaptureUnavailableModalOpen(true),
+ onAnnotationContentChange: annotationCommands.handleAnnotationContentChange,
+ onAnnotationTypeChange: annotationCommands.handleAnnotationTypeChange,
+ onAnnotationStyleChange: annotationCommands.handleAnnotationStyleChange,
+ onAnnotationFigureDataChange: annotationCommands.handleAnnotationFigureDataChange,
+ onAnnotationBlurIntensityChange: annotationCommands.handleAnnotationBlurIntensityChange,
+ onAnnotationBlurColorChange: annotationCommands.handleAnnotationBlurColorChange,
+ onAnnotationDelete: annotationCommands.handleAnnotationDelete,
+ };
+}
diff --git a/src/components/video-editor/presets/useEditorPreferencesPersistence.ts b/src/components/video-editor/presets/useEditorPreferencesPersistence.ts
new file mode 100644
index 00000000..2d44dfa0
--- /dev/null
+++ b/src/components/video-editor/presets/useEditorPreferencesPersistence.ts
@@ -0,0 +1,133 @@
+import { useEffect } from "react";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import { saveEditorPreferences } from "../editorPreferences";
+import type { useExportSettings } from "../export/useExportSettings";
+import type { useAppearanceState } from "../state/useAppearanceState";
+
+type Input = {
+ appearance: ReturnType<typeof useAppearanceState>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ aspectRatio: AspectRatio;
+ whisperExecutablePath: string | null;
+ whisperModelPath: string | null;
+};
+
+export function useEditorPreferencesPersistence({
+ appearance,
+ exportSettings,
+ aspectRatio,
+ whisperExecutablePath,
+ whisperModelPath,
+}: Input) {
+ useEffect(() => {
+ saveEditorPreferences({
+ wallpaper: appearance.wallpaper,
+ shadowIntensity: appearance.shadowIntensity,
+ backgroundBlur: appearance.backgroundBlur,
+ zoomMotionBlur: appearance.zoomMotionBlur,
+ zoomMotionBlurTuning: appearance.zoomMotionBlurTuning,
+ zoomTemporalMotionBlur: appearance.zoomTemporalMotionBlur,
+ zoomMotionBlurSampleCount: appearance.zoomMotionBlurSampleCount,
+ zoomMotionBlurShutterFraction: appearance.zoomMotionBlurShutterFraction,
+ autoApplyFreshRecordingAutoZooms: appearance.autoApplyFreshRecordingAutoZooms,
+ connectZooms: appearance.connectZooms,
+ zoomInDurationMs: appearance.zoomInDurationMs,
+ zoomInOverlapMs: appearance.zoomInOverlapMs,
+ zoomOutDurationMs: appearance.zoomOutDurationMs,
+ connectedZoomGapMs: appearance.connectedZoomGapMs,
+ connectedZoomDurationMs: appearance.connectedZoomDurationMs,
+ zoomInEasing: appearance.zoomInEasing,
+ zoomOutEasing: appearance.zoomOutEasing,
+ connectedZoomEasing: appearance.connectedZoomEasing,
+ showCursor: appearance.showCursor,
+ loopCursor: appearance.loopCursor,
+ cursorStyle: appearance.cursorStyle,
+ cursorSize: appearance.cursorSize,
+ cursorSmoothing: appearance.cursorSmoothing,
+ cursorSpringStiffnessMultiplier: appearance.cursorSpringStiffnessMultiplier,
+ cursorSpringDampingMultiplier: appearance.cursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier: appearance.cursorSpringMassMultiplier,
+ cameraSpringStiffnessMultiplier: appearance.cameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier: appearance.cameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier: appearance.cameraSpringMassMultiplier,
+ cursorMotionBlur: appearance.cursorMotionBlur,
+ cursorClickEffect: appearance.cursorClickEffect,
+ cursorClickEffectColor: appearance.cursorClickEffectColor,
+ cursorClickEffectScale: appearance.cursorClickEffectScale,
+ cursorClickEffectOpacity: appearance.cursorClickEffectOpacity,
+ cursorClickEffectDurationMs: appearance.cursorClickEffectDurationMs,
+ cursorClickBounce: appearance.cursorClickBounce,
+ cursorClickBounceDuration: appearance.cursorClickBounceDuration,
+ cursorSway: appearance.cursorSway,
+ borderRadius: appearance.borderRadius,
+ padding: appearance.padding,
+ webcam: appearance.webcam,
+ aspectRatio,
+ exportEncodingMode: exportSettings.exportEncodingMode,
+ exportBackendPreference: exportSettings.exportBackendPreference,
+ exportPipelineModel: exportSettings.exportPipelineModel,
+ exportQuality: exportSettings.exportQuality,
+ mp4FrameRate: exportSettings.mp4FrameRate,
+ exportFormat: exportSettings.exportFormat,
+ gifFrameRate: exportSettings.gifFrameRate,
+ gifLoop: exportSettings.gifLoop,
+ gifSizePreset: exportSettings.gifSizePreset,
+ whisperExecutablePath,
+ whisperModelPath,
+ });
+ }, [
+ appearance.wallpaper,
+ appearance.shadowIntensity,
+ appearance.backgroundBlur,
+ appearance.zoomMotionBlur,
+ appearance.zoomMotionBlurTuning,
+ appearance.zoomTemporalMotionBlur,
+ appearance.zoomMotionBlurSampleCount,
+ appearance.zoomMotionBlurShutterFraction,
+ appearance.autoApplyFreshRecordingAutoZooms,
+ appearance.connectZooms,
+ appearance.zoomInDurationMs,
+ appearance.zoomInOverlapMs,
+ appearance.zoomOutDurationMs,
+ appearance.connectedZoomGapMs,
+ appearance.connectedZoomDurationMs,
+ appearance.zoomInEasing,
+ appearance.zoomOutEasing,
+ appearance.connectedZoomEasing,
+ appearance.showCursor,
+ appearance.loopCursor,
+ appearance.cursorStyle,
+ appearance.cursorSize,
+ appearance.cursorSmoothing,
+ appearance.cursorSpringStiffnessMultiplier,
+ appearance.cursorSpringDampingMultiplier,
+ appearance.cursorSpringMassMultiplier,
+ appearance.cameraSpringStiffnessMultiplier,
+ appearance.cameraSpringDampingMultiplier,
+ appearance.cameraSpringMassMultiplier,
+ appearance.cursorMotionBlur,
+ appearance.cursorClickEffect,
+ appearance.cursorClickEffectColor,
+ appearance.cursorClickEffectScale,
+ appearance.cursorClickEffectOpacity,
+ appearance.cursorClickEffectDurationMs,
+ appearance.cursorClickBounce,
+ appearance.cursorClickBounceDuration,
+ appearance.cursorSway,
+ appearance.borderRadius,
+ appearance.padding,
+ appearance.webcam,
+ aspectRatio,
+ exportSettings.exportEncodingMode,
+ exportSettings.exportBackendPreference,
+ exportSettings.exportPipelineModel,
+ exportSettings.exportQuality,
+ exportSettings.mp4FrameRate,
+ exportSettings.exportFormat,
+ exportSettings.gifFrameRate,
+ exportSettings.gifLoop,
+ exportSettings.gifSizePreset,
+ whisperExecutablePath,
+ whisperModelPath,
+ ]);
+}
diff --git a/src/components/video-editor/presets/useEditorPresets.ts b/src/components/video-editor/presets/useEditorPresets.ts
new file mode 100644
index 00000000..d092dbe9
--- /dev/null
+++ b/src/components/video-editor/presets/useEditorPresets.ts
@@ -0,0 +1,172 @@
+import { type Dispatch, type SetStateAction, useCallback, useEffect, useMemo } from "react";
+import { toast } from "sonner";
+import {
+ type EditorPreset,
+ type EditorPresetSnapshot,
+ saveEditorPresets,
+ serializeEditorPresetSnapshot,
+} from "../editorPreferences";
+
+type Translator = (
+ key: string,
+ fallback?: string,
+ params?: Record<string, string | number>,
+) => string;
+
+interface UseEditorPresetsParams {
+ t: Translator;
+ currentSnapshot: EditorPresetSnapshot;
+ applySnapshot: (snapshot: EditorPresetSnapshot) => void;
+ editorPresets: EditorPreset[];
+ setEditorPresets: Dispatch<SetStateAction<EditorPreset[]>>;
+ activePresetId: string | null;
+ setActivePresetId: Dispatch<SetStateAction<string | null>>;
+ presetPopoverOpen: boolean;
+ presetNameDraft: string;
+ setPresetNameDraft: Dispatch<SetStateAction<string>>;
+}
+
+export function useEditorPresets({
+ t,
+ currentSnapshot,
+ applySnapshot,
+ editorPresets,
+ setEditorPresets,
+ activePresetId,
+ setActivePresetId,
+ presetPopoverOpen,
+ presetNameDraft,
+ setPresetNameDraft,
+}: UseEditorPresetsParams) {
+ const currentSignature = useMemo(
+ () => serializeEditorPresetSnapshot(currentSnapshot),
+ [currentSnapshot],
+ );
+ const currentEditorPreset = useMemo(
+ () => editorPresets.find((preset) => preset.id === activePresetId) ?? null,
+ [activePresetId, editorPresets],
+ );
+
+ useEffect(() => {
+ if (
+ currentEditorPreset &&
+ serializeEditorPresetSnapshot(currentEditorPreset.snapshot) === currentSignature
+ ) {
+ return;
+ }
+
+ const matchingPreset =
+ editorPresets.find(
+ (preset) => serializeEditorPresetSnapshot(preset.snapshot) === currentSignature,
+ ) ?? null;
+ const nextActiveId = matchingPreset?.id ?? null;
+ if (nextActiveId !== activePresetId) setActivePresetId(nextActiveId);
+ }, [activePresetId, currentEditorPreset, currentSignature, editorPresets, setActivePresetId]);
+
+ useEffect(() => {
+ if (!presetPopoverOpen) setPresetNameDraft("");
+ }, [presetPopoverOpen, setPresetNameDraft]);
+
+ const handleApplyEditorPreset = useCallback(
+ (presetId: string) => {
+ const preset = editorPresets.find((item) => item.id === presetId);
+ if (!preset) return;
+ setActivePresetId(preset.id);
+ applySnapshot(preset.snapshot);
+ toast.success(
+ t("editor.presets.toasts.applied", 'Applied preset "{{name}}"', {
+ name: preset.name,
+ }),
+ );
+ },
+ [applySnapshot, editorPresets, setActivePresetId, t],
+ );
+
+ const handleSaveEditorPreset = useCallback(
+ (name: string) => {
+ const normalizedName = name.trim().replace(/\s+/g, " ");
+ if (!normalizedName) {
+ toast.error(t("editor.presets.errors.nameRequired", "Enter a preset name."));
+ return false;
+ }
+ if (
+ editorPresets.some(
+ (preset) =>
+ preset.name.toLocaleLowerCase() === normalizedName.toLocaleLowerCase(),
+ )
+ ) {
+ toast.error(
+ t(
+ "editor.presets.errors.duplicateName",
+ "A preset with that name already exists.",
+ ),
+ );
+ return false;
+ }
+
+ const timestamp = new Date().toISOString();
+ const nextPreset: EditorPreset = {
+ id: crypto.randomUUID(),
+ name: normalizedName,
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ snapshot: currentSnapshot,
+ };
+ const nextPresets = [nextPreset, ...editorPresets];
+ if (!saveEditorPresets(nextPresets)) {
+ toast.error(
+ t(
+ "editor.presets.errors.saveFailed",
+ "Could not save that preset. Check your browser storage settings and try again.",
+ ),
+ );
+ return false;
+ }
+ setEditorPresets(nextPresets);
+ setActivePresetId(nextPreset.id);
+ toast.success(
+ t("editor.presets.toasts.saved", 'Saved preset "{{name}}"', {
+ name: normalizedName,
+ }),
+ );
+ return true;
+ },
+ [currentSnapshot, editorPresets, setActivePresetId, setEditorPresets, t],
+ );
+
+ const handleDeleteEditorPreset = useCallback(
+ (presetId: string) => {
+ const preset = editorPresets.find((item) => item.id === presetId);
+ if (!preset) return;
+ const nextPresets = editorPresets.filter((item) => item.id !== presetId);
+ if (!saveEditorPresets(nextPresets)) {
+ toast.error(
+ t(
+ "editor.presets.errors.deleteFailed",
+ "Could not delete that preset. Check your browser storage settings and try again.",
+ ),
+ );
+ return;
+ }
+ setEditorPresets(nextPresets);
+ if (preset.id === activePresetId) setActivePresetId(null);
+ toast.success(
+ t("editor.presets.toasts.deleted", 'Deleted preset "{{name}}"', {
+ name: preset.name,
+ }),
+ );
+ },
+ [activePresetId, editorPresets, setActivePresetId, setEditorPresets, t],
+ );
+
+ const handleSavePresetSubmit = useCallback(() => {
+ if (handleSaveEditorPreset(presetNameDraft)) setPresetNameDraft("");
+ }, [handleSaveEditorPreset, presetNameDraft, setPresetNameDraft]);
+
+ return {
+ currentEditorPreset,
+ handleApplyEditorPreset,
+ handleDeleteEditorPreset,
+ handleSavePresetSubmit,
+ };
+}
diff --git a/src/components/video-editor/presets/useVideoEditorPresets.ts b/src/components/video-editor/presets/useVideoEditorPresets.ts
new file mode 100644
index 00000000..4acac0f9
--- /dev/null
+++ b/src/components/video-editor/presets/useVideoEditorPresets.ts
@@ -0,0 +1,194 @@
+import { type Dispatch, type SetStateAction, useCallback, useMemo, useState } from "react";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import { type EditorPresetSnapshot, loadEditorPresets } from "../editorPreferences";
+import type { useExportSettings } from "../export/useExportSettings";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useTimelineState } from "../state/useTimelineState";
+import { useEditorPresets } from "./useEditorPresets";
+
+type Input = {
+ t: Parameters<typeof useEditorPresets>[0]["t"];
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ aspectRatio: AspectRatio;
+ setAspectRatio: Dispatch<SetStateAction<AspectRatio>>;
+ whisperExecutablePath: string | null;
+ setWhisperExecutablePath: Dispatch<SetStateAction<string | null>>;
+ whisperModelPath: string | null;
+ setWhisperModelPath: Dispatch<SetStateAction<string | null>>;
+};
+
+export function useVideoEditorPresets({
+ t,
+ appearance,
+ timeline,
+ exportSettings,
+ aspectRatio,
+ setAspectRatio,
+ whisperExecutablePath,
+ setWhisperExecutablePath,
+ whisperModelPath,
+ setWhisperModelPath,
+}: Input) {
+ const [editorPresets, setEditorPresets] = useState(() => loadEditorPresets());
+ const [activeEditorPresetId, setActiveEditorPresetId] = useState<string | null>(null);
+ const [presetPopoverOpen, setPresetPopoverOpen] = useState(false);
+ const [presetNameDraft, setPresetNameDraft] = useState("");
+
+ const currentSnapshot = useMemo<EditorPresetSnapshot>(
+ () => ({
+ wallpaper: appearance.wallpaper,
+ shadowIntensity: appearance.shadowIntensity,
+ backgroundBlur: appearance.backgroundBlur,
+ zoomMotionBlur: appearance.zoomMotionBlur,
+ zoomMotionBlurTuning: { ...appearance.zoomMotionBlurTuning },
+ zoomTemporalMotionBlur: appearance.zoomTemporalMotionBlur,
+ zoomMotionBlurSampleCount: appearance.zoomMotionBlurSampleCount,
+ zoomMotionBlurShutterFraction: appearance.zoomMotionBlurShutterFraction,
+ connectZooms: appearance.connectZooms,
+ zoomInDurationMs: appearance.zoomInDurationMs,
+ zoomInOverlapMs: appearance.zoomInOverlapMs,
+ zoomOutDurationMs: appearance.zoomOutDurationMs,
+ connectedZoomGapMs: appearance.connectedZoomGapMs,
+ connectedZoomDurationMs: appearance.connectedZoomDurationMs,
+ zoomInEasing: appearance.zoomInEasing,
+ zoomOutEasing: appearance.zoomOutEasing,
+ connectedZoomEasing: appearance.connectedZoomEasing,
+ showCursor: appearance.showCursor,
+ loopCursor: appearance.loopCursor,
+ cursorStyle: appearance.cursorStyle,
+ cursorSize: appearance.cursorSize,
+ cursorSmoothing: appearance.cursorSmoothing,
+ cursorSpringStiffnessMultiplier: appearance.cursorSpringStiffnessMultiplier,
+ cursorSpringDampingMultiplier: appearance.cursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier: appearance.cursorSpringMassMultiplier,
+ cameraSpringStiffnessMultiplier: appearance.cameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier: appearance.cameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier: appearance.cameraSpringMassMultiplier,
+ cursorMotionBlur: appearance.cursorMotionBlur,
+ cursorClickEffect: appearance.cursorClickEffect,
+ cursorClickEffectColor: appearance.cursorClickEffectColor,
+ cursorClickEffectScale: appearance.cursorClickEffectScale,
+ cursorClickEffectOpacity: appearance.cursorClickEffectOpacity,
+ cursorClickEffectDurationMs: appearance.cursorClickEffectDurationMs,
+ cursorClickBounce: appearance.cursorClickBounce,
+ cursorClickBounceDuration: appearance.cursorClickBounceDuration,
+ cursorSway: appearance.cursorSway,
+ borderRadius: appearance.borderRadius,
+ padding: { ...appearance.padding },
+ cropRegion: { ...appearance.cropRegion },
+ webcam: { ...appearance.webcam },
+ aspectRatio,
+ exportEncodingMode: exportSettings.exportEncodingMode,
+ exportBackendPreference: exportSettings.exportBackendPreference,
+ exportPipelineModel: exportSettings.exportPipelineModel,
+ exportQuality: exportSettings.exportQuality,
+ mp4FrameRate: exportSettings.mp4FrameRate,
+ exportFormat: exportSettings.exportFormat,
+ gifFrameRate: exportSettings.gifFrameRate,
+ gifLoop: exportSettings.gifLoop,
+ gifSizePreset: exportSettings.gifSizePreset,
+ autoCaptionSettings: { ...timeline.autoCaptionSettings },
+ whisperExecutablePath,
+ whisperModelPath,
+ }),
+ [
+ appearance,
+ timeline.autoCaptionSettings,
+ exportSettings,
+ aspectRatio,
+ whisperExecutablePath,
+ whisperModelPath,
+ ],
+ );
+
+ const applySnapshot = useCallback(
+ (snapshot: EditorPresetSnapshot) => {
+ appearance.setWallpaper(snapshot.wallpaper);
+ appearance.setShadowIntensity(snapshot.shadowIntensity);
+ appearance.setBackgroundBlur(snapshot.backgroundBlur);
+ appearance.setZoomMotionBlur(snapshot.zoomMotionBlur);
+ appearance.setZoomMotionBlurTuning({ ...snapshot.zoomMotionBlurTuning });
+ appearance.setZoomTemporalMotionBlur(snapshot.zoomTemporalMotionBlur);
+ appearance.setZoomMotionBlurSampleCount(snapshot.zoomMotionBlurSampleCount);
+ appearance.setZoomMotionBlurShutterFraction(snapshot.zoomMotionBlurShutterFraction);
+ appearance.setConnectZooms(snapshot.connectZooms);
+ appearance.setZoomInDurationMs(snapshot.zoomInDurationMs);
+ appearance.setZoomInOverlapMs(snapshot.zoomInOverlapMs);
+ appearance.setZoomOutDurationMs(snapshot.zoomOutDurationMs);
+ appearance.setConnectedZoomGapMs(snapshot.connectedZoomGapMs);
+ appearance.setConnectedZoomDurationMs(snapshot.connectedZoomDurationMs);
+ appearance.setZoomInEasing(snapshot.zoomInEasing);
+ appearance.setZoomOutEasing(snapshot.zoomOutEasing);
+ appearance.setConnectedZoomEasing(snapshot.connectedZoomEasing);
+ appearance.setShowCursor(snapshot.showCursor);
+ appearance.setLoopCursor(snapshot.loopCursor);
+ appearance.setCursorStyle(snapshot.cursorStyle);
+ appearance.setCursorSize(snapshot.cursorSize);
+ appearance.setCursorSmoothing(snapshot.cursorSmoothing);
+ appearance.setCursorSpringStiffnessMultiplier(snapshot.cursorSpringStiffnessMultiplier);
+ appearance.setCursorSpringDampingMultiplier(snapshot.cursorSpringDampingMultiplier);
+ appearance.setCursorSpringMassMultiplier(snapshot.cursorSpringMassMultiplier);
+ appearance.setCameraSpringStiffnessMultiplier(snapshot.cameraSpringStiffnessMultiplier);
+ appearance.setCameraSpringDampingMultiplier(snapshot.cameraSpringDampingMultiplier);
+ appearance.setCameraSpringMassMultiplier(snapshot.cameraSpringMassMultiplier);
+ appearance.setCursorMotionBlur(snapshot.cursorMotionBlur);
+ appearance.setCursorClickEffect(snapshot.cursorClickEffect);
+ appearance.setCursorClickEffectColor(snapshot.cursorClickEffectColor);
+ appearance.setCursorClickEffectScale(snapshot.cursorClickEffectScale);
+ appearance.setCursorClickEffectOpacity(snapshot.cursorClickEffectOpacity);
+ appearance.setCursorClickEffectDurationMs(snapshot.cursorClickEffectDurationMs);
+ appearance.setCursorClickBounce(snapshot.cursorClickBounce);
+ appearance.setCursorClickBounceDuration(snapshot.cursorClickBounceDuration);
+ appearance.setCursorSway(snapshot.cursorSway);
+ appearance.setBorderRadius(snapshot.borderRadius);
+ appearance.setPadding({ ...snapshot.padding });
+ appearance.setCropRegion({ ...snapshot.cropRegion });
+ appearance.setWebcam({ ...snapshot.webcam });
+ setAspectRatio(snapshot.aspectRatio);
+ exportSettings.setExportEncodingMode(snapshot.exportEncodingMode);
+ exportSettings.setExportBackendPreference(snapshot.exportBackendPreference);
+ exportSettings.setExportPipelineModel(snapshot.exportPipelineModel);
+ exportSettings.setExportQuality(snapshot.exportQuality);
+ exportSettings.setMp4FrameRate(snapshot.mp4FrameRate);
+ exportSettings.setExportFormat(snapshot.exportFormat);
+ exportSettings.setGifFrameRate(snapshot.gifFrameRate);
+ exportSettings.setGifLoop(snapshot.gifLoop);
+ exportSettings.setGifSizePreset(snapshot.gifSizePreset);
+ timeline.setAutoCaptionSettings({ ...snapshot.autoCaptionSettings });
+ setWhisperExecutablePath(snapshot.whisperExecutablePath);
+ setWhisperModelPath(snapshot.whisperModelPath);
+ },
+ [
+ appearance,
+ exportSettings,
+ timeline,
+ setAspectRatio,
+ setWhisperExecutablePath,
+ setWhisperModelPath,
+ ],
+ );
+
+ const actions = useEditorPresets({
+ t,
+ currentSnapshot,
+ applySnapshot,
+ editorPresets,
+ setEditorPresets,
+ activePresetId: activeEditorPresetId,
+ setActivePresetId: setActiveEditorPresetId,
+ presetPopoverOpen,
+ presetNameDraft,
+ setPresetNameDraft,
+ });
+ return {
+ editorPresets,
+ activeEditorPresetId,
+ presetPopoverOpen,
+ setPresetPopoverOpen,
+ presetNameDraft,
+ setPresetNameDraft,
+ ...actions,
+ };
+}
diff --git a/src/components/video-editor/project/useEditorProjectController.ts b/src/components/video-editor/project/useEditorProjectController.ts
new file mode 100644
index 00000000..727ba01d
--- /dev/null
+++ b/src/components/video-editor/project/useEditorProjectController.ts
@@ -0,0 +1,231 @@
+import type { Dispatch, MutableRefObject, RefObject, SetStateAction } from "react";
+import { useMemo } from "react";
+import type { useI18n } from "@/contexts/I18nContext";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import { useAutoCaptionController } from "../captions/useAutoCaptionController";
+import { loadEditorPreferences } from "../editorPreferences";
+import type { useExportSettings } from "../export/useExportSettings";
+import { useEditorHistory } from "../hooks/useEditorHistory";
+import { useEditorPreferencesPersistence } from "../presets/useEditorPreferencesPersistence";
+import { hasUnsavedProjectChanges } from "../projectDirtyState";
+import { getDevOpenRecordingConfig, getSmokeExportConfig } from "../smokeExportConfig";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useProjectState } from "../state/useProjectState";
+import type { useTimelineState } from "../state/useTimelineState";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+import { useInitialEditorSource } from "./useInitialEditorSource";
+import type { useProjectLibraryController } from "./useProjectLibraryController";
+import { useProjectLifecycle } from "./useProjectLifecycle";
+import { useProjectOpenActions } from "./useProjectOpenActions";
+import { useProjectSaveActions } from "./useProjectSaveActions";
+import { useProjectSnapshotModel } from "./useProjectSnapshotModel";
+
+type Input = {
+ t: ReturnType<typeof useI18n>["t"];
+ project: ReturnType<typeof useProjectState>;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ initialPreferences: ReturnType<typeof loadEditorPreferences>;
+ smokeConfig: ReturnType<typeof getSmokeExportConfig>;
+ devConfig: ReturnType<typeof getDevOpenRecordingConfig>;
+ aspectRatio: AspectRatio;
+ setAspectRatio: Dispatch<SetStateAction<AspectRatio>>;
+ videoPath: string | null;
+ setVideoPath: Dispatch<SetStateAction<string | null>>;
+ videoSourcePath: string | null;
+ setVideoSourcePath: Dispatch<SetStateAction<string | null>>;
+ currentTime: number;
+ setCurrentTime: Dispatch<SetStateAction<number>>;
+ setIsPlaying: Dispatch<SetStateAction<boolean>>;
+ setDuration: Dispatch<SetStateAction<number>>;
+ whisperExecutablePath: string | null;
+ setWhisperExecutablePath: Dispatch<SetStateAction<string | null>>;
+ whisperModelPath: string | null;
+ setWhisperModelPath: Dispatch<SetStateAction<string | null>>;
+ downloadedWhisperModelPath: string | null;
+ setDownloadedWhisperModelPath: Dispatch<SetStateAction<string | null>>;
+ whisperModelDownloadStatus: "idle" | "downloading" | "downloaded" | "error";
+ setWhisperModelDownloadStatus: Dispatch<
+ SetStateAction<"idle" | "downloading" | "downloaded" | "error">
+ >;
+ setWhisperModelDownloadProgress: Dispatch<SetStateAction<number>>;
+ isGeneratingCaptions: boolean;
+ setIsGeneratingCaptions: Dispatch<SetStateAction<boolean>>;
+ videoPlaybackRef: RefObject<VideoPlaybackRef>;
+ projectNameInputRef: RefObject<HTMLInputElement>;
+ projectSaveDialogInputRef: RefObject<HTMLInputElement>;
+ nextZoomIdRef: MutableRefObject<number>;
+ nextClipIdRef: MutableRefObject<number>;
+ nextAudioIdRef: MutableRefObject<number>;
+ nextAnnotationIdRef: MutableRefObject<number>;
+ nextAnnotationZIndexRef: MutableRefObject<number>;
+ clipInitializedRef: MutableRefObject<boolean>;
+ autoFullTrackClipIdRef: MutableRefObject<string | null>;
+ autoFullTrackClipEndMsRef: MutableRefObject<number | null>;
+ pendingFreshRecordingAutoZoomPathRef: MutableRefObject<string | null>;
+ pendingFreshRecordingAutoSuggestTelemetryCountRef: MutableRefObject<number>;
+ autoSuggestedVideoPathRef: MutableRefObject<string | null>;
+ applySessionPresentation: (
+ session:
+ | { hideOverlayCursorByDefault?: boolean; nativeCaptureUnavailable?: boolean }
+ | null
+ | undefined,
+ ) => void;
+ refreshProjectLibrary: ReturnType<typeof useProjectLibraryController>["refreshProjectLibrary"];
+ captureProjectThumbnail: ReturnType<
+ typeof useProjectLibraryController
+ >["captureProjectThumbnail"];
+ remountPreview: () => void;
+};
+
+export function useEditorProjectController(input: Input) {
+ const snapshot = useProjectSnapshotModel({
+ t: input.t,
+ project: input.project,
+ appearance: input.appearance,
+ timeline: input.timeline,
+ exportSettings: input.exportSettings,
+ aspectRatio: input.aspectRatio,
+ projectNameInputRef: input.projectNameInputRef,
+ projectSaveDialogInputRef: input.projectSaveDialogInputRef,
+ });
+ const history = useEditorHistory({
+ timeline: input.timeline,
+ nextZoomIdRef: input.nextZoomIdRef,
+ nextClipIdRef: input.nextClipIdRef,
+ nextAnnotationIdRef: input.nextAnnotationIdRef,
+ nextAudioIdRef: input.nextAudioIdRef,
+ nextAnnotationZIndexRef: input.nextAnnotationZIndexRef,
+ });
+ const lifecycle = useProjectLifecycle({
+ t: input.t,
+ project: input.project,
+ appearance: input.appearance,
+ timeline: input.timeline,
+ exportSettings: input.exportSettings,
+ aspectRatio: input.aspectRatio,
+ setAspectRatio: input.setAspectRatio,
+ currentSourcePath: snapshot.currentSourcePath,
+ currentPersistedEditorState: snapshot.currentPersistedEditorState,
+ videoPlaybackRef: input.videoPlaybackRef,
+ setIsPlaying: input.setIsPlaying,
+ setCurrentTime: input.setCurrentTime,
+ setDuration: input.setDuration,
+ applySessionPresentation: input.applySessionPresentation,
+ refreshProjectLibrary: input.refreshProjectLibrary,
+ buildPersistedEditorState: snapshot.buildPersistedEditorState,
+ resetHistory: history.resetHistory,
+ refs: {
+ nextZoomIdRef: input.nextZoomIdRef,
+ nextClipIdRef: input.nextClipIdRef,
+ nextAudioIdRef: input.nextAudioIdRef,
+ nextAnnotationIdRef: input.nextAnnotationIdRef,
+ nextAnnotationZIndexRef: input.nextAnnotationZIndexRef,
+ clipInitializedRef: input.clipInitializedRef,
+ autoFullTrackClipIdRef: input.autoFullTrackClipIdRef,
+ autoFullTrackClipEndMsRef: input.autoFullTrackClipEndMsRef,
+ pendingFreshRecordingAutoZoomPathRef: input.pendingFreshRecordingAutoZoomPathRef,
+ pendingFreshRecordingAutoSuggestTelemetryCountRef:
+ input.pendingFreshRecordingAutoSuggestTelemetryCountRef,
+ autoSuggestedVideoPathRef: input.autoSuggestedVideoPathRef,
+ },
+ });
+ const hasUnsavedChanges = useMemo(
+ () =>
+ hasUnsavedProjectChanges(
+ lifecycle.currentProjectSnapshot,
+ input.project.lastSavedSnapshot,
+ ),
+ [lifecycle.currentProjectSnapshot, input.project.lastSavedSnapshot],
+ );
+
+ useInitialEditorSource({
+ project: input.project,
+ appearance: input.appearance,
+ timeline: input.timeline,
+ exportSettings: input.exportSettings,
+ initialPreferences: input.initialPreferences,
+ smokeConfig: input.smokeConfig,
+ devConfig: input.devConfig,
+ videoSourcePath: input.videoSourcePath,
+ pendingFreshRecordingAutoZoomPathRef: input.pendingFreshRecordingAutoZoomPathRef,
+ setAspectRatio: input.setAspectRatio,
+ applyLoadedProject: lifecycle.applyLoadedProject,
+ resetSourceScopedEditorState: lifecycle.resetSourceScopedEditorState,
+ applySessionPresentation: input.applySessionPresentation,
+ });
+ useEditorPreferencesPersistence({
+ appearance: input.appearance,
+ exportSettings: input.exportSettings,
+ aspectRatio: input.aspectRatio,
+ whisperExecutablePath: input.whisperExecutablePath,
+ whisperModelPath: input.whisperModelPath,
+ });
+ const autoCaption = useAutoCaptionController({
+ t: input.t,
+ videoPath: input.videoPath,
+ setVideoPath: input.setVideoPath,
+ videoSourcePath: input.videoSourcePath,
+ setVideoSourcePath: input.setVideoSourcePath,
+ webcamSourcePath: input.appearance.webcam.sourcePath ?? null,
+ whisperExecutablePath: input.whisperExecutablePath,
+ setWhisperExecutablePath: input.setWhisperExecutablePath,
+ whisperModelPath: input.whisperModelPath,
+ setWhisperModelPath: input.setWhisperModelPath,
+ downloadedWhisperModelPath: input.downloadedWhisperModelPath,
+ setDownloadedWhisperModelPath: input.setDownloadedWhisperModelPath,
+ whisperModelDownloadStatus: input.whisperModelDownloadStatus,
+ setWhisperModelDownloadStatus: input.setWhisperModelDownloadStatus,
+ setWhisperModelDownloadProgress: input.setWhisperModelDownloadProgress,
+ isGeneratingCaptions: input.isGeneratingCaptions,
+ setIsGeneratingCaptions: input.setIsGeneratingCaptions,
+ autoCaptionSettings: input.timeline.autoCaptionSettings,
+ setAutoCaptionSettings: input.timeline.setAutoCaptionSettings,
+ setAutoCaptions: input.timeline.setAutoCaptions,
+ syncActiveVideoSource: lifecycle.syncActiveVideoSource,
+ });
+ const saveActions = useProjectSaveActions({
+ project: input.project,
+ currentSourcePath: snapshot.currentSourcePath,
+ currentProjectSnapshot: lifecycle.currentProjectSnapshot,
+ currentPersistedEditorState: snapshot.currentPersistedEditorState,
+ projectDisplayName: snapshot.projectDisplayName,
+ hasUnsavedChanges,
+ projectSaveDialogInputRef: input.projectSaveDialogInputRef,
+ projectNameInputRef: input.projectNameInputRef,
+ openProjectSaveDialog: lifecycle.openProjectSaveDialog,
+ resolveProjectSaveDialog: lifecycle.resolveProjectSaveDialog,
+ captureProjectThumbnail: input.captureProjectThumbnail,
+ refreshProjectLibrary: input.refreshProjectLibrary,
+ remountPreview: input.remountPreview,
+ });
+ const openActions = useProjectOpenActions({
+ project: input.project,
+ appearance: input.appearance,
+ videoPlaybackRef: input.videoPlaybackRef,
+ pendingFreshRecordingAutoZoomPathRef: input.pendingFreshRecordingAutoZoomPathRef,
+ hasUnsavedChanges,
+ setIsPlaying: input.setIsPlaying,
+ setCurrentTime: input.setCurrentTime,
+ setDuration: input.setDuration,
+ applyLoadedProject: lifecycle.applyLoadedProject,
+ openUnsavedChangesDialog: lifecycle.openUnsavedChangesDialog,
+ saveProject: saveActions.saveProject,
+ refreshProjectLibrary: input.refreshProjectLibrary,
+ resetSourceScopedEditorState: lifecycle.resetSourceScopedEditorState,
+ applySessionPresentation: input.applySessionPresentation,
+ handleSaveProject: saveActions.handleSaveProject,
+ handleSaveProjectAs: saveActions.handleSaveProjectAs,
+ });
+
+ return {
+ snapshot,
+ history,
+ lifecycle,
+ autoCaption,
+ saveActions,
+ openActions,
+ hasUnsavedChanges,
+ };
+}
diff --git a/src/components/video-editor/project/useInitialEditorSource.ts b/src/components/video-editor/project/useInitialEditorSource.ts
new file mode 100644
index 00000000..e1871889
--- /dev/null
+++ b/src/components/video-editor/project/useInitialEditorSource.ts
@@ -0,0 +1,274 @@
+/* biome-ignore-all lint/correctness/useExhaustiveDependencies: editor state setters are stable and initial source loading intentionally runs once per launch configuration. */
+import { type MutableRefObject, useEffect, useRef } from "react";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import type { EditorPreferences } from "../editorPreferences";
+import type { useExportSettings } from "../export/useExportSettings";
+import { fromFileUrl, resolveVideoUrl } from "../projectPersistence";
+import type { getDevOpenRecordingConfig, getSmokeExportConfig } from "../smokeExportConfig";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useProjectState } from "../state/useProjectState";
+import type { useTimelineState } from "../state/useTimelineState";
+import { DEFAULT_WEBCAM_TIME_OFFSET_MS } from "../types";
+
+type SessionPresentation = {
+ hideOverlayCursorByDefault?: boolean;
+ nativeCaptureUnavailable?: boolean;
+};
+
+type Input = {
+ project: ReturnType<typeof useProjectState>;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ initialPreferences: EditorPreferences;
+ smokeConfig: ReturnType<typeof getSmokeExportConfig>;
+ devConfig: ReturnType<typeof getDevOpenRecordingConfig>;
+ videoSourcePath: string | null;
+ pendingFreshRecordingAutoZoomPathRef: MutableRefObject<string | null>;
+ setAspectRatio: (value: AspectRatio) => void;
+ applyLoadedProject: (candidate: unknown, path?: string | null) => Promise<boolean>;
+ resetSourceScopedEditorState: () => void;
+ applySessionPresentation: (session: SessionPresentation | null | undefined) => void;
+};
+
+export function useInitialEditorSource({
+ project,
+ appearance,
+ timeline,
+ exportSettings,
+ initialPreferences,
+ smokeConfig,
+ devConfig,
+ videoSourcePath,
+ pendingFreshRecordingAutoZoomPathRef,
+ setAspectRatio,
+ applyLoadedProject,
+ resetSourceScopedEditorState,
+ applySessionPresentation,
+}: Input) {
+ const initialLoadStartedRef = useRef(false);
+
+ useEffect(() => {
+ // This effect owns launch-time hydration. Several of the callbacks it uses
+ // intentionally close over live editor state, so their identities may change
+ // after hydration updates that state. Never interpret that as a request to
+ // reload the source and reset the editor again.
+ if (initialLoadStartedRef.current) return;
+ initialLoadStartedRef.current = true;
+
+ async function loadInitialData() {
+ try {
+ if (smokeConfig.enabled && smokeConfig.projectPath) {
+ const result = await window.electronAPI.openProjectFileAtPath(
+ smokeConfig.projectPath,
+ );
+ if (!result.success || !result.project) {
+ project.setError(
+ `Smoke export failed to load project ${smokeConfig.projectPath}: ${result.error || result.message || "unknown error"}`,
+ );
+ return;
+ }
+ if (
+ !(await applyLoadedProject(
+ result.project,
+ result.path ?? smokeConfig.projectPath,
+ ))
+ ) {
+ project.setError(
+ `Smoke export could not apply project ${smokeConfig.projectPath}`,
+ );
+ return;
+ }
+ project.setError(null);
+ return;
+ }
+
+ if (!smokeConfig.enabled && devConfig.inputPath) {
+ const sourcePath = fromFileUrl(devConfig.inputPath);
+ const webcamPath = devConfig.webcamInputPath
+ ? fromFileUrl(devConfig.webcamInputPath)
+ : null;
+ if (webcamPath) {
+ await window.electronAPI.setCurrentRecordingSession?.({
+ videoPath: sourcePath,
+ webcamPath,
+ timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ });
+ } else {
+ await window.electronAPI.setCurrentVideoPath(sourcePath);
+ }
+ const sourceUrl = await resolveVideoUrl(sourcePath);
+ project.setVideoSourcePath(sourcePath);
+ project.setVideoPath(sourceUrl);
+ project.setCurrentProjectPath(null);
+ project.setLastSavedSnapshot(null);
+ resetSourceScopedEditorState();
+ pendingFreshRecordingAutoZoomPathRef.current =
+ appearance.autoApplyFreshRecordingAutoZooms ? sourceUrl : null;
+ appearance.setWebcam((previous) => ({
+ ...previous,
+ enabled: Boolean(webcamPath),
+ sourcePath: webcamPath,
+ timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ }));
+ project.setError(null);
+ return;
+ }
+
+ if (smokeConfig.enabled) {
+ if (!smokeConfig.inputPath) {
+ project.setError("Smoke export input path is missing.");
+ return;
+ }
+ const sourcePath = fromFileUrl(smokeConfig.inputPath);
+ const webcamPath = smokeConfig.webcamInputPath
+ ? fromFileUrl(smokeConfig.webcamInputPath)
+ : null;
+ if (webcamPath) {
+ await window.electronAPI.setCurrentRecordingSession?.({
+ videoPath: sourcePath,
+ webcamPath,
+ timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ });
+ } else {
+ await window.electronAPI.setCurrentVideoPath(sourcePath);
+ }
+ const sourceUrl = await resolveVideoUrl(sourcePath);
+ project.setVideoSourcePath(sourcePath);
+ project.setVideoPath(sourceUrl);
+ project.setCurrentProjectPath(null);
+ project.setLastSavedSnapshot(null);
+ resetSourceScopedEditorState();
+ pendingFreshRecordingAutoZoomPathRef.current = null;
+ appearance.setWebcam((previous) => ({
+ ...previous,
+ enabled: Boolean(webcamPath),
+ sourcePath: webcamPath,
+ timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ shadow: smokeConfig.webcamShadow ?? previous.shadow,
+ size: smokeConfig.webcamSize ?? previous.size,
+ width: smokeConfig.webcamSize ?? previous.width ?? previous.size,
+ height: smokeConfig.webcamSize ?? previous.height ?? previous.size,
+ }));
+ project.setError(null);
+ return;
+ }
+
+ const currentProject = await window.electronAPI.loadCurrentProjectFile();
+ if (
+ currentProject.success &&
+ currentProject.project &&
+ (await applyLoadedProject(currentProject.project, currentProject.path ?? null))
+ ) {
+ appearance.setPadding(initialPreferences.padding);
+ appearance.setBorderRadius(initialPreferences.borderRadius);
+ setAspectRatio(initialPreferences.aspectRatio);
+ exportSettings.setExportFormat(initialPreferences.exportFormat);
+ exportSettings.setMp4FrameRate(initialPreferences.mp4FrameRate ?? 30);
+ exportSettings.setExportQuality(initialPreferences.exportQuality);
+ exportSettings.setExportEncodingMode(initialPreferences.exportEncodingMode);
+ exportSettings.setExportBackendPreference(
+ initialPreferences.exportBackendPreference,
+ );
+ exportSettings.setExportPipelineModel(initialPreferences.exportPipelineModel);
+ exportSettings.setGifFrameRate(initialPreferences.gifFrameRate);
+ exportSettings.setGifLoop(initialPreferences.gifLoop);
+ exportSettings.setGifSizePreset(initialPreferences.gifSizePreset);
+ return;
+ }
+
+ const sessionResult = await window.electronAPI.getCurrentRecordingSession?.();
+ if (sessionResult?.success && sessionResult.session?.videoPath) {
+ const sourcePath = fromFileUrl(sessionResult.session.videoPath);
+ const sourceUrl = await resolveVideoUrl(sourcePath);
+ project.setVideoSourcePath(sourcePath);
+ project.setVideoPath(sourceUrl);
+ project.setCurrentProjectPath(null);
+ project.setLastSavedSnapshot(null);
+ resetSourceScopedEditorState();
+ pendingFreshRecordingAutoZoomPathRef.current =
+ appearance.autoApplyFreshRecordingAutoZooms ? sourceUrl : null;
+ applySessionPresentation(sessionResult.session);
+ appearance.setWebcam((previous) => ({
+ ...previous,
+ enabled: Boolean(sessionResult.session?.webcamPath),
+ sourcePath: sessionResult.session?.webcamPath ?? null,
+ timeOffsetMs:
+ sessionResult.session?.timeOffsetMs ?? DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ }));
+ return;
+ }
+
+ const currentVideo = await window.electronAPI.getCurrentVideoPath();
+ if (!currentVideo.success || !currentVideo.path) {
+ project.setError("No video to load. Please record or select a video.");
+ return;
+ }
+ const sourcePath = fromFileUrl(currentVideo.path);
+ project.setVideoSourcePath(sourcePath);
+ project.setVideoPath(await resolveVideoUrl(sourcePath));
+ project.setCurrentProjectPath(null);
+ project.setLastSavedSnapshot(null);
+ resetSourceScopedEditorState();
+ pendingFreshRecordingAutoZoomPathRef.current = null;
+ applySessionPresentation(null);
+ appearance.setWebcam((previous) => ({
+ ...previous,
+ enabled: false,
+ sourcePath: null,
+ timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ }));
+ } catch (error) {
+ project.setError(`Error loading video: ${String(error)}`);
+ } finally {
+ project.setLoading(false);
+ }
+ }
+ void loadInitialData();
+ }, [
+ applyLoadedProject,
+ applySessionPresentation,
+ devConfig,
+ initialPreferences,
+ resetSourceScopedEditorState,
+ smokeConfig,
+ ]);
+
+ useEffect(() => {
+ if (!window.electronAPI.onRecordingSessionChanged) return;
+ return window.electronAPI.onRecordingSessionChanged((session) => {
+ const sessionSourcePath = session?.videoPath ? fromFileUrl(session.videoPath) : null;
+ const webcamPath = session?.webcamPath ? fromFileUrl(session.webcamPath) : null;
+ if (!session || sessionSourcePath !== videoSourcePath) return;
+ appearance.setWebcam((previous) => ({
+ ...previous,
+ enabled: Boolean(webcamPath),
+ sourcePath: webcamPath,
+ timeOffsetMs: webcamPath
+ ? (session.timeOffsetMs ?? previous.timeOffsetMs)
+ : DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ }));
+ timeline.setSourceAudioFallbackRefreshKey((key) => key + 1);
+ });
+ }, [videoSourcePath, appearance.setWebcam, timeline.setSourceAudioFallbackRefreshKey]);
+
+ useEffect(() => {
+ let cancelled = false;
+ if (!appearance.webcam.sourcePath) {
+ appearance.setResolvedWebcamVideoUrl(null);
+ return;
+ }
+ void resolveVideoUrl(appearance.webcam.sourcePath).then((url) => {
+ if (!cancelled) appearance.setResolvedWebcamVideoUrl(url);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [appearance.webcam.sourcePath, appearance.setResolvedWebcamVideoUrl]);
+
+ useEffect(() => {
+ if (!appearance.autoApplyFreshRecordingAutoZooms) {
+ pendingFreshRecordingAutoZoomPathRef.current = null;
+ }
+ }, [appearance.autoApplyFreshRecordingAutoZooms, pendingFreshRecordingAutoZoomPathRef]);
+}
diff --git a/src/components/video-editor/project/useProjectLibraryController.ts b/src/components/video-editor/project/useProjectLibraryController.ts
new file mode 100644
index 00000000..255297ca
--- /dev/null
+++ b/src/components/video-editor/project/useProjectLibraryController.ts
@@ -0,0 +1,326 @@
+/* biome-ignore-all lint/correctness/useExhaustiveDependencies: grouped editor domain objects contain the thumbnail renderer dependencies. */
+import { type RefObject, useCallback } from "react";
+import { FrameRenderer } from "@/lib/exporter";
+import { toFileUrl } from "../projectPersistence";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useProjectState } from "../state/useProjectState";
+import type { useTimelineState } from "../state/useTimelineState";
+import { getClipSourceEndMs, type SpeedRegion } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+
+type Input = {
+ project: ReturnType<typeof useProjectState>;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ videoPlaybackRef: RefObject<VideoPlaybackRef | null>;
+ currentTime: number;
+ effectiveShowCursor: boolean;
+};
+
+export function useProjectLibraryController({
+ project,
+ appearance,
+ timeline,
+ videoPlaybackRef,
+ currentTime,
+ effectiveShowCursor,
+}: Input) {
+ const { setProjectLibraryEntries } = project;
+ const {
+ backgroundBlur,
+ borderRadius,
+ connectZooms,
+ connectedZoomDurationMs,
+ connectedZoomEasing,
+ connectedZoomGapMs,
+ cropRegion,
+ cursorClickBounce,
+ cursorClickBounceDuration,
+ cursorClickEffect,
+ cursorClickEffectColor,
+ cursorClickEffectScale,
+ cursorClickEffectOpacity,
+ cursorClickEffectDurationMs,
+ cursorMotionBlur,
+ cursorSize,
+ cursorSmoothing,
+ cursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier,
+ cursorSpringStiffnessMultiplier,
+ cameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier,
+ zoomSmoothness,
+ cursorStyle,
+ cursorSway,
+ padding,
+ resolvedWebcamVideoUrl,
+ shadowIntensity,
+ wallpaper,
+ webcam,
+ zoomInDurationMs,
+ zoomInEasing,
+ zoomInOverlapMs,
+ zoomMotionBlur,
+ zoomMotionBlurTuning,
+ zoomTemporalMotionBlur,
+ zoomMotionBlurSampleCount,
+ zoomMotionBlurShutterFraction,
+ zoomOutDurationMs,
+ zoomOutEasing,
+ zoomClassicMode,
+ } = appearance;
+ const {
+ annotationRegions,
+ autoCaptionSettings,
+ autoCaptions,
+ cursorTelemetry,
+ clipRegions,
+ speedRegions,
+ zoomRegions,
+ } = timeline;
+ const refreshProjectLibrary = useCallback(async () => {
+ try {
+ const result = await window.electronAPI.listProjectFiles();
+ if (!result.success) {
+ throw new Error(result.error || "Failed to load project library");
+ }
+
+ setProjectLibraryEntries(result.entries);
+ } catch (projectLibraryError) {
+ console.warn("Unable to refresh project library:", projectLibraryError);
+ }
+ }, []);
+
+ const captureProjectThumbnail = useCallback(async () => {
+ const previewHandle = videoPlaybackRef.current;
+ const previewVideo = previewHandle?.video ?? null;
+ const previewCanvas = previewHandle?.app?.canvas ?? null;
+
+ if (previewHandle && previewVideo && previewVideo.paused) {
+ try {
+ await previewHandle.refreshFrame();
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(undefined)));
+ } catch (thumbnailRefreshError) {
+ console.warn(
+ "Unable to refresh preview frame before thumbnail capture:",
+ thumbnailRefreshError,
+ );
+ }
+ }
+
+ const canvas = document.createElement("canvas");
+ const targetWidth = 320;
+ const targetHeight = 180;
+ canvas.width = targetWidth;
+ canvas.height = targetHeight;
+
+ const context = canvas.getContext("2d");
+ if (!context) {
+ return null;
+ }
+ context.imageSmoothingEnabled = true;
+ context.imageSmoothingQuality = "high";
+ const editorBgHsl = getComputedStyle(document.documentElement)
+ .getPropertyValue("--editor-bg")
+ .trim();
+ context.fillStyle = editorBgHsl ? `hsl(${editorBgHsl})` : "#111113";
+ context.fillRect(0, 0, targetWidth, targetHeight);
+
+ const previewWidth = previewHandle?.containerRef.current?.clientWidth || 1920;
+ const previewHeight = previewHandle?.containerRef.current?.clientHeight || 1080;
+ const frameTimestampUs = Math.max(0, Math.round(currentTime * 1_000_000));
+
+ if (previewVideo && previewVideo.videoWidth > 0 && previewVideo.videoHeight > 0) {
+ let videoFrame: VideoFrame | null = null;
+ let frameRenderer: FrameRenderer | null = null;
+
+ try {
+ videoFrame = new VideoFrame(previewVideo, { timestamp: frameTimestampUs });
+ frameRenderer = new FrameRenderer({
+ width: targetWidth,
+ height: targetHeight,
+ wallpaper,
+ zoomRegions,
+ showShadow: shadowIntensity > 0,
+ shadowIntensity,
+ backgroundBlur,
+ zoomMotionBlur,
+ zoomMotionBlurTuning,
+ zoomTemporalMotionBlur,
+ zoomMotionBlurSampleCount,
+ zoomMotionBlurShutterFraction,
+ connectZooms,
+ zoomInDurationMs,
+ zoomInOverlapMs,
+ zoomOutDurationMs,
+ connectedZoomGapMs,
+ connectedZoomDurationMs,
+ zoomInEasing,
+ zoomOutEasing,
+ connectedZoomEasing,
+ borderRadius,
+ padding,
+ cropRegion,
+ webcam,
+ webcamUrl:
+ resolvedWebcamVideoUrl ??
+ (webcam.sourcePath ? toFileUrl(webcam.sourcePath) : null),
+ videoWidth: previewVideo.videoWidth,
+ videoHeight: previewVideo.videoHeight,
+ annotationRegions,
+ autoCaptions,
+ autoCaptionSettings,
+ speedRegions: (() => {
+ const clipDerived: SpeedRegion[] = clipRegions
+ .filter((clip) => clip.speed !== 1)
+ .map((clip) => ({
+ id: `clip-speed-${clip.id}`,
+ startMs: clip.startMs,
+ endMs: getClipSourceEndMs(clip),
+ speed: clip.speed as SpeedRegion["speed"],
+ }));
+ if (clipDerived.length === 0) return speedRegions;
+ const result = [...speedRegions];
+ for (const cs of clipDerived) {
+ const overlaps = speedRegions.some(
+ (sr) => sr.endMs > cs.startMs && sr.startMs < cs.endMs,
+ );
+ if (!overlaps) {
+ result.push(cs);
+ }
+ }
+ return result;
+ })(),
+ previewWidth,
+ previewHeight,
+ cursorTelemetry,
+ showCursor: effectiveShowCursor,
+ cursorStyle,
+ cursorSize,
+ cursorSmoothing,
+ cursorSpringStiffnessMultiplier,
+ cursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier,
+ cameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier,
+ zoomSmoothness,
+ zoomClassicMode,
+ cursorMotionBlur,
+ cursorClickEffect,
+ cursorClickEffectColor,
+ cursorClickEffectScale,
+ cursorClickEffectOpacity,
+ cursorClickEffectDurationMs,
+ cursorClickBounce,
+ cursorClickBounceDuration,
+ cursorSway,
+ });
+ await frameRenderer.initialize();
+ await frameRenderer.renderFrame(videoFrame, frameTimestampUs);
+ return frameRenderer.getCanvas().toDataURL("image/png");
+ } catch (thumbnailRenderError) {
+ console.warn(
+ "Unable to render thumbnail from composed frame:",
+ thumbnailRenderError,
+ );
+ } finally {
+ videoFrame?.close();
+ frameRenderer?.destroy();
+ }
+ }
+
+ const drawableSource =
+ previewCanvas && previewCanvas.width > 0 && previewCanvas.height > 0
+ ? previewCanvas
+ : previewVideo && previewVideo.videoWidth > 0 && previewVideo.videoHeight > 0
+ ? previewVideo
+ : null;
+
+ if (!drawableSource) {
+ return null;
+ }
+
+ const sourceWidth =
+ drawableSource instanceof HTMLVideoElement
+ ? drawableSource.videoWidth
+ : drawableSource.width;
+ const sourceHeight =
+ drawableSource instanceof HTMLVideoElement
+ ? drawableSource.videoHeight
+ : drawableSource.height;
+
+ if (sourceWidth <= 0 || sourceHeight <= 0) {
+ return null;
+ }
+
+ const scale = Math.min(targetWidth / sourceWidth, targetHeight / sourceHeight);
+ const drawWidth = Math.round(sourceWidth * scale);
+ const drawHeight = Math.round(sourceHeight * scale);
+ const offsetX = Math.round((targetWidth - drawWidth) / 2);
+ const offsetY = Math.round((targetHeight - drawHeight) / 2);
+
+ try {
+ context.drawImage(drawableSource, offsetX, offsetY, drawWidth, drawHeight);
+ return canvas.toDataURL("image/png");
+ } catch (thumbnailError) {
+ console.warn("Unable to capture project thumbnail:", thumbnailError);
+ return null;
+ }
+ }, [
+ annotationRegions,
+ autoCaptionSettings,
+ autoCaptions,
+ backgroundBlur,
+ borderRadius,
+ connectZooms,
+ connectedZoomDurationMs,
+ connectedZoomEasing,
+ connectedZoomGapMs,
+ cropRegion,
+ currentTime,
+ cursorClickBounce,
+ cursorClickBounceDuration,
+ cursorClickEffect,
+ cursorClickEffectColor,
+ cursorClickEffectScale,
+ cursorClickEffectOpacity,
+ cursorClickEffectDurationMs,
+ cursorMotionBlur,
+ cursorSize,
+ cursorSmoothing,
+ cursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier,
+ cursorSpringStiffnessMultiplier,
+ cameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier,
+ zoomSmoothness,
+ cursorStyle,
+ cursorSway,
+ cursorTelemetry,
+ clipRegions,
+ padding,
+ resolvedWebcamVideoUrl,
+ shadowIntensity,
+ effectiveShowCursor,
+ speedRegions,
+ wallpaper,
+ webcam,
+ zoomInDurationMs,
+ zoomInEasing,
+ zoomInOverlapMs,
+ zoomMotionBlur,
+ zoomMotionBlurTuning,
+ zoomTemporalMotionBlur,
+ zoomMotionBlurSampleCount,
+ zoomMotionBlurShutterFraction,
+ zoomOutDurationMs,
+ zoomOutEasing,
+ zoomRegions,
+ zoomClassicMode,
+ ]);
+
+ return { refreshProjectLibrary, captureProjectThumbnail };
+}
diff --git a/src/components/video-editor/project/useProjectLifecycle.ts b/src/components/video-editor/project/useProjectLifecycle.ts
new file mode 100644
index 00000000..909f0cfa
--- /dev/null
+++ b/src/components/video-editor/project/useProjectLifecycle.ts
@@ -0,0 +1,388 @@
+/* biome-ignore-all lint/correctness/useExhaustiveDependencies: editor domain setters and refs are stable. */
+import {
+ type Dispatch,
+ type MutableRefObject,
+ type RefObject,
+ type SetStateAction,
+ useCallback,
+ useMemo,
+ useRef,
+} from "react";
+import { toast } from "sonner";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import type { useExportSettings } from "../export/useExportSettings";
+import type { UnsavedChangesDecision } from "../layout/EditorDialogs";
+import {
+ createProjectData,
+ deriveNextId,
+ fromFileUrl,
+ normalizeProjectEditor,
+ resolveVideoUrl,
+ stripPersistedDevMotionBlurSettings,
+ validateProjectData,
+} from "../projectPersistence";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useProjectState } from "../state/useProjectState";
+import type { useTimelineState } from "../state/useTimelineState";
+import { DEFAULT_WEBCAM_TIME_OFFSET_MS } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+import { cloneStructured } from "../videoEditorUtils";
+
+type Input = {
+ t: (key: string) => string;
+ project: ReturnType<typeof useProjectState>;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ aspectRatio: AspectRatio;
+ setAspectRatio: Dispatch<SetStateAction<AspectRatio>>;
+ currentSourcePath: string | null;
+ currentPersistedEditorState: Parameters<typeof createProjectData>[1];
+ videoPlaybackRef: RefObject<VideoPlaybackRef | null>;
+ setIsPlaying: Dispatch<SetStateAction<boolean>>;
+ setCurrentTime: Dispatch<SetStateAction<number>>;
+ setDuration: Dispatch<SetStateAction<number>>;
+ applySessionPresentation: (
+ session:
+ | { hideOverlayCursorByDefault?: boolean; nativeCaptureUnavailable?: boolean }
+ | null
+ | undefined,
+ ) => void;
+ refreshProjectLibrary: () => Promise<void>;
+ buildPersistedEditorState: (
+ editor: Parameters<typeof createProjectData>[1],
+ ) => Parameters<typeof createProjectData>[1];
+ resetHistory: () => void;
+ refs: {
+ nextZoomIdRef: MutableRefObject<number>;
+ nextClipIdRef: MutableRefObject<number>;
+ nextAudioIdRef: MutableRefObject<number>;
+ nextAnnotationIdRef: MutableRefObject<number>;
+ nextAnnotationZIndexRef: MutableRefObject<number>;
+ clipInitializedRef: MutableRefObject<boolean>;
+ autoFullTrackClipIdRef: MutableRefObject<string | null>;
+ autoFullTrackClipEndMsRef: MutableRefObject<number | null>;
+ pendingFreshRecordingAutoZoomPathRef: MutableRefObject<string | null>;
+ pendingFreshRecordingAutoSuggestTelemetryCountRef: MutableRefObject<number>;
+ autoSuggestedVideoPathRef: MutableRefObject<string | null>;
+ };
+};
+
+export function useProjectLifecycle(input: Input) {
+ const { project, appearance } = input;
+ const inputRef = useRef(input);
+ inputRef.current = input;
+ const pendingSaveDialogRef = useRef<{ resolve(saved: boolean): void } | null>(null);
+ const pendingUnsavedDialogRef = useRef<{
+ resolve(decision: UnsavedChangesDecision): void;
+ } | null>(null);
+
+ const applyLoadedProject = useCallback(async (candidate: unknown, path?: string | null) => {
+ const current = inputRef.current;
+ const { project, appearance, timeline, exportSettings, refs } = current;
+ if (!validateProjectData(candidate)) return false;
+ const loadedProject = candidate;
+ const sourcePath = fromFileUrl(loadedProject.videoPath);
+ const editor = normalizeProjectEditor(
+ stripPersistedDevMotionBlurSettings(loadedProject.editor ?? {}),
+ );
+ try {
+ current.videoPlaybackRef.current?.pause();
+ } catch {
+ /* preview may be tearing down */
+ }
+ current.setIsPlaying(false);
+ current.setCurrentTime(0);
+ current.setDuration(0);
+ project.setError(null);
+ project.setVideoSourcePath(sourcePath);
+ project.setCurrentProjectPath(path ?? null);
+ refs.pendingFreshRecordingAutoZoomPathRef.current = null;
+ if (editor.webcam.sourcePath) {
+ await window.electronAPI.setCurrentRecordingSession?.(
+ {
+ videoPath: sourcePath,
+ webcamPath: editor.webcam.sourcePath,
+ timeOffsetMs: editor.webcam.timeOffsetMs,
+ },
+ { preserveProjectPath: Boolean(path) },
+ );
+ const session = await window.electronAPI.getCurrentRecordingSession?.();
+ current.applySessionPresentation(session?.success ? session.session : null);
+ } else {
+ await window.electronAPI.setCurrentVideoPath(sourcePath, {
+ preserveProjectPath: Boolean(path),
+ });
+ current.applySessionPresentation(null);
+ }
+ project.setVideoPath(await resolveVideoUrl(sourcePath));
+
+ appearance.setWallpaper(editor.wallpaper);
+ appearance.setShadowIntensity(editor.shadowIntensity);
+ appearance.setBackgroundBlur(editor.backgroundBlur);
+ appearance.setZoomMotionBlur(editor.zoomMotionBlur);
+ appearance.setZoomMotionBlurTuning({ ...editor.zoomMotionBlurTuning });
+ appearance.setZoomTemporalMotionBlur(editor.zoomTemporalMotionBlur);
+ appearance.setZoomMotionBlurSampleCount(editor.zoomMotionBlurSampleCount);
+ appearance.setZoomMotionBlurShutterFraction(editor.zoomMotionBlurShutterFraction);
+ appearance.setConnectZooms(editor.connectZooms);
+ appearance.setZoomInDurationMs(editor.zoomInDurationMs);
+ appearance.setZoomInOverlapMs(editor.zoomInOverlapMs);
+ appearance.setZoomOutDurationMs(editor.zoomOutDurationMs);
+ appearance.setConnectedZoomGapMs(editor.connectedZoomGapMs);
+ appearance.setConnectedZoomDurationMs(editor.connectedZoomDurationMs);
+ appearance.setZoomInEasing(editor.zoomInEasing);
+ appearance.setZoomOutEasing(editor.zoomOutEasing);
+ appearance.setConnectedZoomEasing(editor.connectedZoomEasing);
+ appearance.setShowCursor(editor.showCursor);
+ appearance.setLoopCursor(editor.loopCursor);
+ appearance.setCursorStyle(editor.cursorStyle);
+ appearance.setCursorSize(editor.cursorSize);
+ appearance.setCursorSmoothing(editor.cursorSmoothing);
+ appearance.setCursorSpringStiffnessMultiplier(editor.cursorSpringStiffnessMultiplier);
+ appearance.setCursorSpringDampingMultiplier(editor.cursorSpringDampingMultiplier);
+ appearance.setCursorSpringMassMultiplier(editor.cursorSpringMassMultiplier);
+ appearance.setCameraSpringStiffnessMultiplier(editor.cameraSpringStiffnessMultiplier);
+ appearance.setCameraSpringDampingMultiplier(editor.cameraSpringDampingMultiplier);
+ appearance.setCameraSpringMassMultiplier(editor.cameraSpringMassMultiplier);
+ appearance.setCursorClickEffect(editor.cursorClickEffect);
+ appearance.setCursorClickEffectColor(editor.cursorClickEffectColor);
+ appearance.setCursorClickEffectScale(editor.cursorClickEffectScale);
+ appearance.setCursorClickEffectOpacity(editor.cursorClickEffectOpacity);
+ appearance.setCursorClickEffectDurationMs(editor.cursorClickEffectDurationMs);
+ appearance.setZoomSmoothness(editor.zoomSmoothness);
+ appearance.setZoomClassicMode(editor.zoomClassicMode);
+ appearance.setCursorMotionBlur(editor.cursorMotionBlur);
+ appearance.setCursorClickBounce(editor.cursorClickBounce);
+ appearance.setCursorClickBounceDuration(editor.cursorClickBounceDuration);
+ appearance.setCursorSway(editor.cursorSway);
+ appearance.setBorderRadius(editor.borderRadius);
+ appearance.setPadding(editor.padding);
+ appearance.setCropRegion(editor.cropRegion);
+ appearance.setWebcam(editor.webcam);
+ timeline.setZoomRegions(editor.zoomRegions);
+ timeline.setTrimRegions(editor.trimRegions);
+ timeline.setClipRegions(editor.clipRegions);
+ refs.clipInitializedRef.current = editor.clipRegions.length > 0;
+ refs.autoFullTrackClipIdRef.current = null;
+ refs.autoFullTrackClipEndMsRef.current = null;
+ timeline.setSpeedRegions(editor.speedRegions);
+ timeline.setAnnotationRegions(editor.annotationRegions);
+ timeline.setAudioRegions(editor.audioRegions);
+ timeline.setSourceAudioTrackSettingsByClip(editor.sourceAudioTrackSettingsByClip ?? {});
+ timeline.setDefaultSourceAudioTrackSettings(editor.defaultSourceAudioTrackSettings ?? {});
+ timeline.setAutoCaptions(editor.autoCaptions);
+ timeline.setAutoCaptionSettings(editor.autoCaptionSettings);
+ current.setAspectRatio(editor.aspectRatio);
+ exportSettings.setExportEncodingMode(editor.exportEncodingMode);
+ exportSettings.setExportBackendPreference(editor.exportBackendPreference);
+ exportSettings.setExportPipelineModel(editor.exportPipelineModel);
+ exportSettings.setExportQuality(editor.exportQuality);
+ exportSettings.setMp4FrameRate(editor.mp4FrameRate);
+ exportSettings.setExportFormat(editor.exportFormat);
+ exportSettings.setGifFrameRate(editor.gifFrameRate);
+ exportSettings.setGifLoop(editor.gifLoop);
+ exportSettings.setGifSizePreset(editor.gifSizePreset);
+ timeline.setSelectedZoomId(null);
+ timeline.setSelectedClipId(null);
+ timeline.setSelectedAnnotationId(null);
+ timeline.setSelectedAudioId(null);
+ refs.nextZoomIdRef.current = deriveNextId(
+ "zoom",
+ editor.zoomRegions.map(({ id }) => id),
+ );
+ refs.nextClipIdRef.current = deriveNextId(
+ "clip",
+ editor.clipRegions.map(({ id }) => id),
+ );
+ refs.nextAudioIdRef.current = deriveNextId(
+ "audio",
+ editor.audioRegions.map(({ id }) => id),
+ );
+ refs.nextAnnotationIdRef.current = deriveNextId(
+ "annotation",
+ editor.annotationRegions.map(({ id }) => id),
+ );
+ refs.nextAnnotationZIndexRef.current =
+ editor.annotationRegions.reduce((max, region) => Math.max(max, region.zIndex), 0) + 1;
+ current.resetHistory();
+ project.setLastSavedSnapshot(
+ cloneStructured(
+ createProjectData(
+ sourcePath,
+ current.buildPersistedEditorState(editor),
+ loadedProject.projectId ?? null,
+ ),
+ ),
+ );
+ await current.refreshProjectLibrary();
+ return true;
+ }, []);
+
+ const currentProjectSnapshot = useMemo(
+ () =>
+ input.currentSourcePath
+ ? createProjectData(
+ input.currentSourcePath,
+ input.currentPersistedEditorState,
+ project.lastSavedSnapshot?.projectId ?? null,
+ )
+ : null,
+ [
+ input.currentSourcePath,
+ input.currentPersistedEditorState,
+ project.lastSavedSnapshot?.projectId,
+ ],
+ );
+ const resolveProjectSaveDialog = useCallback(
+ (saved: boolean) => {
+ const pending = pendingSaveDialogRef.current;
+ pendingSaveDialogRef.current = null;
+ project.setProjectSaveDialogOpen(false);
+ project.setIsSavingProjectDialog(false);
+ pending?.resolve(saved);
+ },
+ [project.setProjectSaveDialogOpen, project.setIsSavingProjectDialog],
+ );
+ const openProjectSaveDialog = useCallback(
+ (initialName: string) => {
+ pendingSaveDialogRef.current?.resolve(false);
+ project.setProjectSaveDialogDraft(initialName);
+ project.setProjectSaveDialogOpen(true);
+ project.setIsSavingProjectDialog(false);
+ return new Promise<boolean>((resolve) => {
+ pendingSaveDialogRef.current = { resolve };
+ });
+ },
+ [
+ project.setProjectSaveDialogDraft,
+ project.setProjectSaveDialogOpen,
+ project.setIsSavingProjectDialog,
+ ],
+ );
+ const resolveUnsavedChangesDialog = useCallback(
+ (decision: UnsavedChangesDecision) => {
+ const pending = pendingUnsavedDialogRef.current;
+ pendingUnsavedDialogRef.current = null;
+ project.setUnsavedChangesDialogOpen(false);
+ pending?.resolve(decision);
+ },
+ [project.setUnsavedChangesDialogOpen],
+ );
+ const openUnsavedChangesDialog = useCallback(
+ (actionLabel: string) => {
+ pendingUnsavedDialogRef.current?.resolve("cancel");
+ project.setUnsavedChangesDialogActionLabel(actionLabel);
+ project.setUnsavedChangesDialogOpen(true);
+ return new Promise<UnsavedChangesDecision>((resolve) => {
+ pendingUnsavedDialogRef.current = { resolve };
+ });
+ },
+ [project.setUnsavedChangesDialogActionLabel, project.setUnsavedChangesDialogOpen],
+ );
+
+ const syncRecordingSessionWebcam = useCallback(
+ async (webcamPath: string | null, offset?: number) => {
+ if (!input.currentSourcePath || !window.electronAPI.setCurrentRecordingSession) return;
+ await window.electronAPI.setCurrentRecordingSession(
+ {
+ videoPath: input.currentSourcePath,
+ webcamPath,
+ timeOffsetMs:
+ webcamPath && Number.isFinite(offset)
+ ? (offset ?? DEFAULT_WEBCAM_TIME_OFFSET_MS)
+ : webcamPath
+ ? appearance.webcam.timeOffsetMs
+ : DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ },
+ { preserveProjectPath: Boolean(project.currentProjectPath) },
+ );
+ },
+ [input.currentSourcePath, project.currentProjectPath, appearance.webcam.timeOffsetMs],
+ );
+ const syncActiveVideoSource = useCallback(
+ async (sourcePath: string, webcamPath?: string | null) => {
+ if (webcamPath) {
+ await window.electronAPI.setCurrentRecordingSession?.(
+ {
+ videoPath: sourcePath,
+ webcamPath,
+ timeOffsetMs: appearance.webcam.timeOffsetMs,
+ },
+ { preserveProjectPath: Boolean(project.currentProjectPath) },
+ );
+ } else
+ await window.electronAPI.setCurrentVideoPath(sourcePath, {
+ preserveProjectPath: Boolean(project.currentProjectPath),
+ });
+ },
+ [appearance.webcam.timeOffsetMs, project.currentProjectPath],
+ );
+ const resetSourceScopedEditorState = useCallback(() => {
+ const current = inputRef.current;
+ const { timeline, refs } = current;
+ timeline.setZoomRegions([]);
+ timeline.setTrimRegions([]);
+ timeline.setClipRegions([]);
+ refs.clipInitializedRef.current = false;
+ refs.autoFullTrackClipIdRef.current = null;
+ refs.autoFullTrackClipEndMsRef.current = null;
+ timeline.setSpeedRegions([]);
+ timeline.setAnnotationRegions([]);
+ timeline.setAudioRegions([]);
+ timeline.setCursorTelemetry([]);
+ timeline.setCursorTelemetrySourcePath(null);
+ timeline.setSourceAudioTrackSettingsByClip({});
+ timeline.setDefaultSourceAudioTrackSettings({});
+ timeline.setHasClipSourceAudio(false);
+ timeline.setAutoCaptions([]);
+ timeline.setAutoCaptionSettings((previous) => ({ ...previous, enabled: false }));
+ timeline.setSelectedZoomId(null);
+ timeline.setSelectedClipId(null);
+ timeline.setSelectedAnnotationId(null);
+ timeline.setSelectedAudioId(null);
+ refs.nextZoomIdRef.current = 1;
+ refs.nextClipIdRef.current = 1;
+ refs.nextAudioIdRef.current = 1;
+ refs.nextAnnotationIdRef.current = 1;
+ refs.nextAnnotationZIndexRef.current = 1;
+ refs.pendingFreshRecordingAutoSuggestTelemetryCountRef.current = 0;
+ refs.autoSuggestedVideoPathRef.current = null;
+ current.resetHistory();
+ }, []);
+ const handleUploadWebcam = useCallback(async () => {
+ const result = await window.electronAPI.openVideoFilePicker();
+ if (!result.success || !result.path) return;
+ appearance.setWebcam((previous) => ({
+ ...previous,
+ enabled: true,
+ sourcePath: result.path ?? null,
+ timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ }));
+ await syncRecordingSessionWebcam(result.path, DEFAULT_WEBCAM_TIME_OFFSET_MS);
+ toast.success(input.t("settings.effects.webcamFootageAdded"));
+ }, [appearance.setWebcam, syncRecordingSessionWebcam, input.t]);
+ const handleClearWebcam = useCallback(async () => {
+ appearance.setWebcam((previous) => ({
+ ...previous,
+ enabled: false,
+ sourcePath: null,
+ timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ }));
+ await syncRecordingSessionWebcam(null);
+ toast.success(input.t("settings.effects.webcamFootageRemoved"));
+ }, [appearance.setWebcam, syncRecordingSessionWebcam, input.t]);
+
+ return {
+ applyLoadedProject,
+ currentProjectSnapshot,
+ resolveProjectSaveDialog,
+ openProjectSaveDialog,
+ resolveUnsavedChangesDialog,
+ openUnsavedChangesDialog,
+ syncActiveVideoSource,
+ resetSourceScopedEditorState,
+ handleUploadWebcam,
+ handleClearWebcam,
+ };
+}
diff --git a/src/components/video-editor/project/useProjectOpenActions.ts b/src/components/video-editor/project/useProjectOpenActions.ts
new file mode 100644
index 00000000..127e5ec5
--- /dev/null
+++ b/src/components/video-editor/project/useProjectOpenActions.ts
@@ -0,0 +1,181 @@
+import {
+ type Dispatch,
+ type MutableRefObject,
+ type RefObject,
+ type SetStateAction,
+ useCallback,
+ useEffect,
+} from "react";
+import { toast } from "sonner";
+import { fromFileUrl, resolveVideoUrl } from "../projectPersistence";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useProjectState } from "../state/useProjectState";
+import { DEFAULT_WEBCAM_TIME_OFFSET_MS } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+
+type Set<T> = Dispatch<SetStateAction<T>>;
+
+type UseProjectOpenActionsInput = {
+ project: ReturnType<typeof useProjectState>;
+ appearance: ReturnType<typeof useAppearanceState>;
+ videoPlaybackRef: RefObject<VideoPlaybackRef | null>;
+ pendingFreshRecordingAutoZoomPathRef: MutableRefObject<string | null>;
+ hasUnsavedChanges: boolean;
+ setIsPlaying: Set<boolean>;
+ setCurrentTime: Set<number>;
+ setDuration: Set<number>;
+ applyLoadedProject: (candidate: unknown, path?: string | null) => Promise<boolean>;
+ openUnsavedChangesDialog: (actionLabel: string) => Promise<"save" | "discard" | "cancel">;
+ saveProject: (forceSaveAs: boolean) => Promise<boolean>;
+ refreshProjectLibrary: () => Promise<void>;
+ resetSourceScopedEditorState: () => void;
+ applySessionPresentation: (session: null) => void;
+ handleSaveProject: () => Promise<unknown>;
+ handleSaveProjectAs: () => Promise<unknown>;
+};
+
+export function useProjectOpenActions({
+ project,
+ appearance,
+ videoPlaybackRef,
+ pendingFreshRecordingAutoZoomPathRef,
+ hasUnsavedChanges,
+ setIsPlaying,
+ setCurrentTime,
+ setDuration,
+ applyLoadedProject,
+ openUnsavedChangesDialog,
+ saveProject,
+ refreshProjectLibrary,
+ resetSourceScopedEditorState,
+ applySessionPresentation,
+ handleSaveProject,
+ handleSaveProjectAs,
+}: UseProjectOpenActionsInput) {
+ const confirmReplaceSourceWithUnsavedChanges = useCallback(
+ async (actionLabel: string) => {
+ if (!hasUnsavedChanges) return true;
+ const decision = await openUnsavedChangesDialog(actionLabel);
+ if (decision === "discard") return true;
+ if (decision === "save") return saveProject(false);
+ return false;
+ },
+ [hasUnsavedChanges, openUnsavedChangesDialog, saveProject],
+ );
+
+ const handleOpenProjectFromLibrary = useCallback(
+ async (projectPath: string) => {
+ if (!(await confirmReplaceSourceWithUnsavedChanges("open another project"))) return;
+ const result = await window.electronAPI.openProjectFileAtPath(projectPath);
+ if (result.canceled) return;
+ if (!result.success) {
+ toast.error(result.message || "Failed to load project");
+ return;
+ }
+ if (!(await applyLoadedProject(result.project, result.path ?? null))) {
+ toast.error("Invalid project file format");
+ return;
+ }
+ project.setProjectBrowserOpen(false);
+ await refreshProjectLibrary();
+ toast.success(`Project loaded from ${result.path}`);
+ },
+ [
+ applyLoadedProject,
+ confirmReplaceSourceWithUnsavedChanges,
+ project,
+ refreshProjectLibrary,
+ ],
+ );
+
+ const handleImportMediaOrProject = useCallback(async () => {
+ if (!(await confirmReplaceSourceWithUnsavedChanges("import a file"))) return;
+ const result = await window.electronAPI.openVideoFilePicker({ includeProjects: true });
+ if (result.canceled) return;
+ if (!result.success) {
+ toast.error(result.message || "Failed to import file");
+ return;
+ }
+ if (result.kind === "project" || result.project) {
+ if (!(await applyLoadedProject(result.project, result.path ?? null))) {
+ toast.error("Invalid project file format");
+ return;
+ }
+ project.setProjectBrowserOpen(false);
+ await refreshProjectLibrary();
+ toast.success(result.path ? `Project loaded from ${result.path}` : "Project loaded");
+ return;
+ }
+ if (!result.path) {
+ toast.error("No media file selected");
+ return;
+ }
+
+ const sourcePath = fromFileUrl(result.path);
+ await window.electronAPI.setCurrentVideoPath(sourcePath, { preserveProjectPath: false });
+ const sourceVideoUrl = await resolveVideoUrl(sourcePath);
+ try {
+ videoPlaybackRef.current?.pause();
+ } catch {
+ // The preview may already be tearing down.
+ }
+ setIsPlaying(false);
+ setCurrentTime(0);
+ setDuration(0);
+ project.setVideoSourcePath(sourcePath);
+ project.setVideoPath(sourceVideoUrl);
+ project.setCurrentProjectPath(null);
+ project.setLastSavedSnapshot(null);
+ resetSourceScopedEditorState();
+ pendingFreshRecordingAutoZoomPathRef.current = appearance.autoApplyFreshRecordingAutoZooms
+ ? sourceVideoUrl
+ : null;
+ appearance.setWebcam((previous) => ({
+ ...previous,
+ enabled: false,
+ sourcePath: null,
+ timeOffsetMs: DEFAULT_WEBCAM_TIME_OFFSET_MS,
+ }));
+ applySessionPresentation(null);
+ project.setProjectBrowserOpen(false);
+ await refreshProjectLibrary();
+ toast.success("Media imported");
+ }, [
+ confirmReplaceSourceWithUnsavedChanges,
+ applyLoadedProject,
+ project,
+ appearance,
+ videoPlaybackRef,
+ setIsPlaying,
+ setCurrentTime,
+ setDuration,
+ resetSourceScopedEditorState,
+ pendingFreshRecordingAutoZoomPathRef,
+ applySessionPresentation,
+ refreshProjectLibrary,
+ ]);
+
+ const handleOpenProjectBrowser = useCallback(() => {
+ if (project.projectBrowserOpen) {
+ project.setProjectBrowserOpen(false);
+ return;
+ }
+ project.setProjectBrowserOpen(true);
+ void refreshProjectLibrary();
+ }, [project.projectBrowserOpen, project.setProjectBrowserOpen, refreshProjectLibrary]);
+
+ useEffect(() => {
+ const removeLoad = window.electronAPI.onMenuLoadProject(
+ () => void handleOpenProjectBrowser(),
+ );
+ const removeSave = window.electronAPI.onMenuSaveProject(handleSaveProject);
+ const removeSaveAs = window.electronAPI.onMenuSaveProjectAs(handleSaveProjectAs);
+ return () => {
+ removeLoad?.();
+ removeSave?.();
+ removeSaveAs?.();
+ };
+ }, [handleOpenProjectBrowser, handleSaveProject, handleSaveProjectAs]);
+
+ return { handleOpenProjectFromLibrary, handleImportMediaOrProject, handleOpenProjectBrowser };
+}
diff --git a/src/components/video-editor/project/useProjectSaveActions.ts b/src/components/video-editor/project/useProjectSaveActions.ts
new file mode 100644
index 00000000..78b424bf
--- /dev/null
+++ b/src/components/video-editor/project/useProjectSaveActions.ts
@@ -0,0 +1,337 @@
+import { type RefObject, useCallback, useEffect, useRef } from "react";
+import { toast } from "sonner";
+import { createProjectData, type EditorProjectData } from "../projectPersistence";
+import type { useProjectState } from "../state/useProjectState";
+import { cloneStructured, getErrorMessage } from "../videoEditorUtils";
+
+const PROJECT_AUTOSAVE_DELAY_MS = 1_000;
+
+type SaveProjectOptions = {
+ silent?: boolean;
+ remountPreviewAfterSave?: boolean;
+ refreshLibraryAfterSave?: boolean;
+ captureThumbnail?: boolean;
+};
+
+type UseProjectSaveActionsInput = {
+ project: ReturnType<typeof useProjectState>;
+ currentSourcePath: string | null;
+ currentProjectSnapshot: EditorProjectData | null;
+ currentPersistedEditorState: Parameters<typeof createProjectData>[1];
+ projectDisplayName: string;
+ hasUnsavedChanges: boolean;
+ projectSaveDialogInputRef: RefObject<HTMLInputElement | null>;
+ projectNameInputRef: RefObject<HTMLInputElement | null>;
+ openProjectSaveDialog: (initialName: string) => Promise<boolean>;
+ resolveProjectSaveDialog: (saved: boolean) => void;
+ captureProjectThumbnail: () => Promise<string | null>;
+ refreshProjectLibrary: () => Promise<void>;
+ remountPreview: () => void;
+};
+
+export function useProjectSaveActions({
+ project,
+ currentSourcePath,
+ currentProjectSnapshot,
+ currentPersistedEditorState,
+ projectDisplayName,
+ hasUnsavedChanges,
+ projectSaveDialogInputRef,
+ projectNameInputRef,
+ openProjectSaveDialog,
+ resolveProjectSaveDialog,
+ captureProjectThumbnail,
+ refreshProjectLibrary,
+ remountPreview,
+}: UseProjectSaveActionsInput) {
+ const {
+ currentProjectPath,
+ lastSavedSnapshot,
+ projectSaveDialogDraft,
+ projectNameDraft,
+ setCurrentProjectPath,
+ setLastSavedSnapshot,
+ setIsSavingProjectDialog,
+ setProjectNameDraft,
+ setIsEditingProjectName,
+ setIsSavingProjectName,
+ setProjectBrowserOpen,
+ } = project;
+ const autosaveTimeoutRef = useRef<number | null>(null);
+ const saveQueueRef = useRef<Promise<unknown>>(Promise.resolve());
+ const clearPendingAutosave = useCallback(() => {
+ if (autosaveTimeoutRef.current !== null) {
+ window.clearTimeout(autosaveTimeoutRef.current);
+ autosaveTimeoutRef.current = null;
+ }
+ }, []);
+ const queueSave = useCallback((task: () => Promise<boolean>) => {
+ const run = saveQueueRef.current.catch(() => undefined).then(task);
+ saveQueueRef.current = run.catch(() => undefined);
+ return run;
+ }, []);
+
+ const saveProject = useCallback(
+ async (forceSaveAs: boolean, options?: SaveProjectOptions) => {
+ clearPendingAutosave();
+ return queueSave(async () => {
+ if (!currentSourcePath) {
+ if (!options?.silent) toast.error("No video loaded");
+ return false;
+ }
+
+ const captureThumbnail = options?.captureThumbnail ?? true;
+ const refreshLibrary = options?.refreshLibraryAfterSave ?? true;
+ const remount = options?.remountPreviewAfterSave ?? true;
+ try {
+ const projectData =
+ currentProjectSnapshot?.videoPath === currentSourcePath
+ ? currentProjectSnapshot
+ : createProjectData(
+ currentSourcePath,
+ currentPersistedEditorState,
+ lastSavedSnapshot?.projectId ?? null,
+ );
+ const fileNameBase =
+ currentSourcePath
+ .split(/[\\/]/)
+ .pop()
+ ?.replace(/\.[^.]+$/, "") || `project-${Date.now()}`;
+ let targetPath = forceSaveAs ? undefined : (currentProjectPath ?? undefined);
+
+ if (!forceSaveAs && !targetPath) {
+ const activeProject = await window.electronAPI.loadCurrentProjectFile();
+ if (activeProject.success && activeProject.path) {
+ targetPath = activeProject.path;
+ setCurrentProjectPath(activeProject.path);
+ }
+ }
+ if (forceSaveAs || !targetPath) {
+ if (options?.silent) return false;
+ return openProjectSaveDialog(projectDisplayName || fileNameBase);
+ }
+
+ const thumbnail = captureThumbnail
+ ? await captureProjectThumbnail()
+ : undefined;
+ const result = await window.electronAPI.saveProjectFile(
+ projectData,
+ fileNameBase,
+ targetPath,
+ thumbnail,
+ );
+ if (result.canceled) {
+ if (!options?.silent) toast.info("Project save canceled");
+ return false;
+ }
+ if (!result.success) {
+ if (!options?.silent)
+ toast.error(result.message || "Failed to save project");
+ return false;
+ }
+
+ if (result.path) setCurrentProjectPath(result.path);
+ setLastSavedSnapshot(
+ cloneStructured(
+ createProjectData(
+ projectData.videoPath,
+ projectData.editor,
+ result.projectId ?? projectData.projectId ?? null,
+ ),
+ ),
+ );
+ if (refreshLibrary) await refreshProjectLibrary();
+ if (!options?.silent) toast.success(`Project saved to ${result.path}`);
+ return true;
+ } finally {
+ if (remount) remountPreview();
+ }
+ });
+ },
+ [
+ clearPendingAutosave,
+ queueSave,
+ currentSourcePath,
+ currentProjectSnapshot,
+ currentPersistedEditorState,
+ currentProjectPath,
+ lastSavedSnapshot,
+ setCurrentProjectPath,
+ setLastSavedSnapshot,
+ openProjectSaveDialog,
+ projectDisplayName,
+ captureProjectThumbnail,
+ refreshProjectLibrary,
+ remountPreview,
+ ],
+ );
+
+ useEffect(() => {
+ window.electronAPI.setHasUnsavedChanges(hasUnsavedChanges);
+ }, [hasUnsavedChanges]);
+ useEffect(
+ () => window.electronAPI.onRequestSaveBeforeClose(() => saveProject(false)),
+ [saveProject],
+ );
+ useEffect(() => {
+ if (!currentProjectPath || !hasUnsavedChanges) {
+ clearPendingAutosave();
+ return;
+ }
+ autosaveTimeoutRef.current = window.setTimeout(() => {
+ autosaveTimeoutRef.current = null;
+ void saveProject(false, {
+ silent: true,
+ remountPreviewAfterSave: false,
+ refreshLibraryAfterSave: false,
+ captureThumbnail: false,
+ });
+ }, PROJECT_AUTOSAVE_DELAY_MS);
+ return clearPendingAutosave;
+ }, [clearPendingAutosave, currentProjectPath, hasUnsavedChanges, saveProject]);
+ useEffect(() => clearPendingAutosave, [clearPendingAutosave]);
+
+ const saveProjectWithName = useCallback(
+ async (name: string, mode: "rename" | "copy" = "rename") => {
+ const trimmedName = name.trim();
+ if (!trimmedName) {
+ toast.error("Project name is required");
+ return false;
+ }
+ if (!currentSourcePath) {
+ toast.error("No video loaded");
+ return false;
+ }
+ try {
+ const projectData =
+ currentProjectSnapshot?.videoPath === currentSourcePath
+ ? currentProjectSnapshot
+ : createProjectData(
+ currentSourcePath,
+ currentPersistedEditorState,
+ lastSavedSnapshot?.projectId ?? null,
+ );
+ const result = await window.electronAPI.saveProjectFileNamed(
+ projectData,
+ trimmedName,
+ await captureProjectThumbnail(),
+ mode,
+ );
+ 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(
+ cloneStructured(
+ createProjectData(
+ projectData.videoPath,
+ projectData.editor,
+ result.projectId ?? projectData.projectId ?? null,
+ ),
+ ),
+ );
+ await refreshProjectLibrary();
+ toast.success(result.path ? `Project saved to ${result.path}` : "Project saved");
+ return true;
+ } finally {
+ remountPreview();
+ }
+ },
+ [
+ currentSourcePath,
+ currentProjectSnapshot,
+ currentPersistedEditorState,
+ lastSavedSnapshot,
+ setCurrentProjectPath,
+ setLastSavedSnapshot,
+ captureProjectThumbnail,
+ refreshProjectLibrary,
+ remountPreview,
+ ],
+ );
+
+ const handleProjectSaveDialogSubmit = useCallback(
+ async (event?: React.FormEvent<HTMLFormElement>) => {
+ event?.preventDefault();
+ const name = projectSaveDialogDraft.trim();
+ if (!name) {
+ toast.error("Project name is required");
+ projectSaveDialogInputRef.current?.focus();
+ return;
+ }
+ setIsSavingProjectDialog(true);
+ let saved = false;
+ try {
+ saved = await saveProjectWithName(name, "copy");
+ } catch (error) {
+ toast.error(getErrorMessage(error));
+ } finally {
+ setIsSavingProjectDialog(false);
+ }
+ if (saved) resolveProjectSaveDialog(true);
+ else {
+ projectSaveDialogInputRef.current?.focus();
+ projectSaveDialogInputRef.current?.select();
+ }
+ },
+ [
+ projectSaveDialogDraft,
+ setIsSavingProjectDialog,
+ projectSaveDialogInputRef,
+ resolveProjectSaveDialog,
+ saveProjectWithName,
+ ],
+ );
+
+ const closeProjectNameEditor = useCallback(() => {
+ setProjectNameDraft(projectDisplayName);
+ setIsEditingProjectName(false);
+ }, [setProjectNameDraft, setIsEditingProjectName, projectDisplayName]);
+ const handleProjectNameSubmit = useCallback(
+ async (event?: React.FormEvent<HTMLFormElement>) => {
+ event?.preventDefault();
+ const name = projectNameDraft.trim();
+ if (!name) return closeProjectNameEditor();
+ setIsSavingProjectName(true);
+ let saved = false;
+ try {
+ saved = await saveProjectWithName(name, "rename");
+ } catch (error) {
+ toast.error(getErrorMessage(error));
+ } finally {
+ setIsSavingProjectName(false);
+ }
+ if (saved) setIsEditingProjectName(false);
+ else {
+ projectNameInputRef.current?.focus();
+ projectNameInputRef.current?.select();
+ }
+ },
+ [
+ projectNameDraft,
+ setIsSavingProjectName,
+ setIsEditingProjectName,
+ projectNameInputRef,
+ closeProjectNameEditor,
+ saveProjectWithName,
+ ],
+ );
+ const handleSaveProject = useCallback(() => saveProject(false), [saveProject]);
+ const handleSaveProjectAs = useCallback(async () => {
+ if (await saveProject(true)) setProjectBrowserOpen(false);
+ }, [saveProject, setProjectBrowserOpen]);
+
+ return {
+ saveProject,
+ handleSaveProject,
+ handleSaveProjectAs,
+ handleProjectSaveDialogSubmit,
+ closeProjectNameEditor,
+ handleProjectNameSubmit,
+ };
+}
diff --git a/src/components/video-editor/project/useProjectSnapshotModel.ts b/src/components/video-editor/project/useProjectSnapshotModel.ts
new file mode 100644
index 00000000..9031a54c
--- /dev/null
+++ b/src/components/video-editor/project/useProjectSnapshotModel.ts
@@ -0,0 +1,215 @@
+import { type RefObject, useCallback, useEffect, useMemo } from "react";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import type { useExportSettings } from "../export/useExportSettings";
+import {
+ fromFileUrl,
+ type ProjectEditorState,
+ stripPersistedDevMotionBlurSettings,
+} from "../projectPersistence";
+import type { useAppearanceState } from "../state/useAppearanceState";
+import type { useProjectState } from "../state/useProjectState";
+import type { useTimelineState } from "../state/useTimelineState";
+
+type Input = {
+ t: (key: string, fallback?: string) => string;
+ project: ReturnType<typeof useProjectState>;
+ appearance: ReturnType<typeof useAppearanceState>;
+ timeline: ReturnType<typeof useTimelineState>;
+ exportSettings: ReturnType<typeof useExportSettings>;
+ aspectRatio: AspectRatio;
+ projectNameInputRef: RefObject<HTMLInputElement | null>;
+ projectSaveDialogInputRef: RefObject<HTMLInputElement | null>;
+};
+
+export function useProjectSnapshotModel({
+ t,
+ project,
+ appearance,
+ timeline,
+ exportSettings,
+ aspectRatio,
+ projectNameInputRef,
+ projectSaveDialogInputRef,
+}: Input) {
+ const buildPersistedEditorState = useCallback(
+ (editor: Partial<ProjectEditorState>) => stripPersistedDevMotionBlurSettings(editor),
+ [],
+ );
+ const currentSourcePath = useMemo(
+ () =>
+ project.videoSourcePath ?? (project.videoPath ? fromFileUrl(project.videoPath) : null),
+ [project.videoPath, project.videoSourcePath],
+ );
+ const projectDisplayName = useMemo(() => {
+ const fileName =
+ project.currentProjectPath?.split(/[\\/]/).pop() ??
+ currentSourcePath?.split(/[\\/]/).pop() ??
+ "";
+ return (
+ fileName.replace(/\.recordly$/i, "").replace(/\.[^.]+$/, "") ||
+ t("editor.project.untitled", "Untitled")
+ );
+ }, [project.currentProjectPath, currentSourcePath, t]);
+
+ useEffect(() => {
+ if (!project.isEditingProjectName) project.setProjectNameDraft(projectDisplayName);
+ }, [project.isEditingProjectName, project.setProjectNameDraft, projectDisplayName]);
+ useEffect(() => {
+ if (!project.isEditingProjectName) return;
+ const frameId = window.requestAnimationFrame(() => {
+ projectNameInputRef.current?.focus();
+ projectNameInputRef.current?.select();
+ });
+ return () => window.cancelAnimationFrame(frameId);
+ }, [project.isEditingProjectName, projectNameInputRef]);
+ useEffect(() => {
+ if (!project.projectSaveDialogOpen) return;
+ const frameId = window.requestAnimationFrame(() => {
+ projectSaveDialogInputRef.current?.focus();
+ projectSaveDialogInputRef.current?.select();
+ });
+ return () => window.cancelAnimationFrame(frameId);
+ }, [project.projectSaveDialogOpen, projectSaveDialogInputRef]);
+
+ const currentPersistedEditorState = useMemo(
+ () =>
+ buildPersistedEditorState({
+ wallpaper: appearance.wallpaper,
+ shadowIntensity: appearance.shadowIntensity,
+ backgroundBlur: appearance.backgroundBlur,
+ zoomMotionBlur: appearance.zoomMotionBlur,
+ zoomMotionBlurTuning: appearance.zoomMotionBlurTuning,
+ zoomTemporalMotionBlur: appearance.zoomTemporalMotionBlur,
+ zoomMotionBlurSampleCount: appearance.zoomMotionBlurSampleCount,
+ zoomMotionBlurShutterFraction: appearance.zoomMotionBlurShutterFraction,
+ connectZooms: appearance.connectZooms,
+ zoomInDurationMs: appearance.zoomInDurationMs,
+ zoomInOverlapMs: appearance.zoomInOverlapMs,
+ zoomOutDurationMs: appearance.zoomOutDurationMs,
+ connectedZoomGapMs: appearance.connectedZoomGapMs,
+ connectedZoomDurationMs: appearance.connectedZoomDurationMs,
+ zoomInEasing: appearance.zoomInEasing,
+ zoomOutEasing: appearance.zoomOutEasing,
+ connectedZoomEasing: appearance.connectedZoomEasing,
+ showCursor: appearance.showCursor,
+ loopCursor: appearance.loopCursor,
+ cursorStyle: appearance.cursorStyle,
+ cursorSize: appearance.cursorSize,
+ cursorSmoothing: appearance.cursorSmoothing,
+ cursorSpringStiffnessMultiplier: appearance.cursorSpringStiffnessMultiplier,
+ cursorSpringDampingMultiplier: appearance.cursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier: appearance.cursorSpringMassMultiplier,
+ cameraSpringStiffnessMultiplier: appearance.cameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier: appearance.cameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier: appearance.cameraSpringMassMultiplier,
+ zoomSmoothness: appearance.zoomSmoothness,
+ zoomClassicMode: appearance.zoomClassicMode,
+ cursorMotionBlur: appearance.cursorMotionBlur,
+ cursorClickEffect: appearance.cursorClickEffect,
+ cursorClickEffectColor: appearance.cursorClickEffectColor,
+ cursorClickEffectScale: appearance.cursorClickEffectScale,
+ cursorClickEffectOpacity: appearance.cursorClickEffectOpacity,
+ cursorClickEffectDurationMs: appearance.cursorClickEffectDurationMs,
+ cursorClickBounce: appearance.cursorClickBounce,
+ cursorClickBounceDuration: appearance.cursorClickBounceDuration,
+ cursorSway: appearance.cursorSway,
+ borderRadius: appearance.borderRadius,
+ padding: appearance.padding,
+ cropRegion: appearance.cropRegion,
+ webcam: appearance.webcam,
+ zoomRegions: timeline.zoomRegions,
+ trimRegions: timeline.trimRegions,
+ clipRegions: timeline.clipRegions,
+ speedRegions: timeline.speedRegions,
+ annotationRegions: timeline.annotationRegions,
+ audioRegions: timeline.audioRegions,
+ autoCaptions: timeline.autoCaptions,
+ autoCaptionSettings: timeline.autoCaptionSettings,
+ aspectRatio,
+ exportEncodingMode: exportSettings.exportEncodingMode,
+ exportBackendPreference: exportSettings.exportBackendPreference,
+ exportPipelineModel: exportSettings.exportPipelineModel,
+ exportQuality: exportSettings.exportQuality,
+ mp4FrameRate: exportSettings.mp4FrameRate,
+ exportFormat: exportSettings.exportFormat,
+ gifFrameRate: exportSettings.gifFrameRate,
+ gifLoop: exportSettings.gifLoop,
+ gifSizePreset: exportSettings.gifSizePreset,
+ sourceAudioTrackSettingsByClip: timeline.sourceAudioTrackSettingsByClip,
+ defaultSourceAudioTrackSettings: timeline.defaultSourceAudioTrackSettings,
+ }),
+ [
+ appearance.wallpaper,
+ appearance.shadowIntensity,
+ appearance.backgroundBlur,
+ appearance.zoomMotionBlur,
+ appearance.zoomMotionBlurTuning,
+ appearance.zoomTemporalMotionBlur,
+ appearance.zoomMotionBlurSampleCount,
+ appearance.zoomMotionBlurShutterFraction,
+ appearance.connectZooms,
+ appearance.zoomInDurationMs,
+ appearance.zoomInOverlapMs,
+ appearance.zoomOutDurationMs,
+ appearance.connectedZoomGapMs,
+ appearance.connectedZoomDurationMs,
+ appearance.zoomInEasing,
+ appearance.zoomOutEasing,
+ appearance.connectedZoomEasing,
+ appearance.showCursor,
+ appearance.loopCursor,
+ appearance.cursorStyle,
+ appearance.cursorSize,
+ appearance.cursorSmoothing,
+ appearance.cursorSpringStiffnessMultiplier,
+ appearance.cursorSpringDampingMultiplier,
+ appearance.cursorSpringMassMultiplier,
+ appearance.cameraSpringStiffnessMultiplier,
+ appearance.cameraSpringDampingMultiplier,
+ appearance.cameraSpringMassMultiplier,
+ appearance.zoomSmoothness,
+ appearance.zoomClassicMode,
+ appearance.cursorMotionBlur,
+ appearance.cursorClickEffect,
+ appearance.cursorClickEffectColor,
+ appearance.cursorClickEffectScale,
+ appearance.cursorClickEffectOpacity,
+ appearance.cursorClickEffectDurationMs,
+ appearance.cursorClickBounce,
+ appearance.cursorClickBounceDuration,
+ appearance.cursorSway,
+ appearance.borderRadius,
+ appearance.padding,
+ appearance.cropRegion,
+ appearance.webcam,
+ timeline.zoomRegions,
+ timeline.trimRegions,
+ timeline.clipRegions,
+ timeline.speedRegions,
+ timeline.annotationRegions,
+ timeline.audioRegions,
+ timeline.autoCaptions,
+ timeline.autoCaptionSettings,
+ aspectRatio,
+ exportSettings.exportEncodingMode,
+ exportSettings.exportBackendPreference,
+ exportSettings.exportPipelineModel,
+ exportSettings.exportQuality,
+ exportSettings.mp4FrameRate,
+ exportSettings.exportFormat,
+ exportSettings.gifFrameRate,
+ exportSettings.gifLoop,
+ exportSettings.gifSizePreset,
+ timeline.sourceAudioTrackSettingsByClip,
+ timeline.defaultSourceAudioTrackSettings,
+ buildPersistedEditorState,
+ ],
+ );
+
+ return {
+ buildPersistedEditorState,
+ currentSourcePath,
+ projectDisplayName,
+ currentPersistedEditorState,
+ };
+}
diff --git a/src/components/video-editor/projectPersistence.test.ts b/src/components/video-editor/projectPersistence.test.ts
index 82a7fbcb..0e7a3f04 100644
--- a/src/components/video-editor/projectPersistence.test.ts
+++ b/src/components/video-editor/projectPersistence.test.ts
@@ -1,8 +1,33 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { normalizeProjectEditor } from "./projectPersistence";
+import { normalizeProjectEditor, resolveVideoUrl } from "./projectPersistence";
import { ADVANCED_VERTICAL_PADDING_MAX } from "./types";
+afterEach(() => vi.unstubAllGlobals());
+
+describe("resolveVideoUrl", () => {
+ it("does not send an already renderable URL through the local-path IPC", async () => {
+ const getLocalMediaUrl = vi.fn();
+ vi.stubGlobal("window", { electronAPI: { getLocalMediaUrl } });
+
+ await expect(resolveVideoUrl("http://127.0.0.1:1234/video?path=test")).resolves.toBe(
+ "http://127.0.0.1:1234/video?path=test",
+ );
+ expect(getLocalMediaUrl).not.toHaveBeenCalled();
+ });
+
+ it("normalizes a file URL before requesting a local media URL", async () => {
+ const getLocalMediaUrl = vi.fn().mockResolvedValue({
+ success: true,
+ url: "http://127.0.0.1:1234/video?path=clip",
+ });
+ vi.stubGlobal("window", { electronAPI: { getLocalMediaUrl } });
+
+ await resolveVideoUrl("file:///Users/demo/My%20Clip.mp4");
+ expect(getLocalMediaUrl).toHaveBeenCalledWith("/Users/demo/My Clip.mp4");
+ });
+});
+
describe("normalizeProjectEditor", () => {
it("preserves the extended advanced vertical padding range", () => {
const editor = normalizeProjectEditor({
diff --git a/src/components/video-editor/projectPersistence.ts b/src/components/video-editor/projectPersistence.ts
index 00193bb9..8e71bde7 100644
--- a/src/components/video-editor/projectPersistence.ts
+++ b/src/components/video-editor/projectPersistence.ts
@@ -317,15 +317,20 @@ export function deriveNextId(prefix: string, ids: string[]): number {
* media server is unavailable.
*/
export async function resolveVideoUrl(sourcePath: string): Promise<string> {
+ const trimmedSourcePath = sourcePath.trim();
+ if (/^(?:https?:|blob:|data:)/i.test(trimmedSourcePath)) {
+ return trimmedSourcePath;
+ }
+ const localPath = fromFileUrl(trimmedSourcePath);
try {
- const result = await window.electronAPI.getLocalMediaUrl(sourcePath);
+ const result = await window.electronAPI.getLocalMediaUrl(localPath);
if (result.success) {
return result.url;
}
} catch {
// Media server unavailable — fall through to file:// URL.
}
- return toFileUrl(sourcePath);
+ return toFileUrl(localPath);
}
export function validateProjectData(candidate: unknown): candidate is EditorProjectData {
diff --git a/src/components/video-editor/state/useAppearanceState.ts b/src/components/video-editor/state/useAppearanceState.ts
new file mode 100644
index 00000000..7335fe7b
--- /dev/null
+++ b/src/components/video-editor/state/useAppearanceState.ts
@@ -0,0 +1,219 @@
+import { useState } from "react";
+import type { EditorPreferences } from "../editorPreferences";
+import type {
+ CropRegion,
+ CursorClickEffectStyle,
+ CursorStyle,
+ WebcamOverlaySettings,
+ ZoomMotionBlurTuning,
+ ZoomTransitionEasing,
+} from "../types";
+import {
+ DEFAULT_CONNECTED_ZOOM_DURATION_MS,
+ DEFAULT_CONNECTED_ZOOM_EASING,
+ DEFAULT_CONNECTED_ZOOM_GAP_MS,
+ DEFAULT_CROP_REGION,
+ DEFAULT_CURSOR_STYLE,
+ DEFAULT_WEBCAM_OVERLAY,
+ DEFAULT_ZOOM_IN_DURATION_MS,
+ DEFAULT_ZOOM_IN_EASING,
+ DEFAULT_ZOOM_IN_OVERLAP_MS,
+ DEFAULT_ZOOM_MOTION_BLUR_TUNING,
+ DEFAULT_ZOOM_OUT_DURATION_MS,
+ DEFAULT_ZOOM_OUT_EASING,
+} from "../types";
+
+export function useAppearanceState(preferences: EditorPreferences) {
+ const [wallpaper, setWallpaper] = useState(preferences.wallpaper);
+ const [shadowIntensity, setShadowIntensity] = useState(preferences.shadowIntensity);
+ const [backgroundBlur, setBackgroundBlur] = useState(preferences.backgroundBlur);
+ const [zoomMotionBlur, setZoomMotionBlur] = useState(preferences.zoomMotionBlur);
+ const [zoomMotionBlurTuning, setZoomMotionBlurTuning] = useState<ZoomMotionBlurTuning>(
+ preferences.zoomMotionBlurTuning ?? DEFAULT_ZOOM_MOTION_BLUR_TUNING,
+ );
+ const [zoomTemporalMotionBlur, setZoomTemporalMotionBlur] = useState(
+ preferences.zoomTemporalMotionBlur,
+ );
+ const [zoomMotionBlurSampleCount, setZoomMotionBlurSampleCount] = useState<number | null>(
+ preferences.zoomMotionBlurSampleCount,
+ );
+ const [zoomMotionBlurShutterFraction, setZoomMotionBlurShutterFraction] = useState<
+ number | null
+ >(preferences.zoomMotionBlurShutterFraction);
+ const [autoApplyFreshRecordingAutoZooms, setAutoApplyFreshRecordingAutoZooms] = useState(
+ preferences.autoApplyFreshRecordingAutoZooms,
+ );
+ const [connectZooms, setConnectZooms] = useState(preferences.connectZooms);
+ const [zoomInDurationMs, setZoomInDurationMs] = useState(
+ preferences.zoomInDurationMs ?? DEFAULT_ZOOM_IN_DURATION_MS,
+ );
+ const [zoomInOverlapMs, setZoomInOverlapMs] = useState(
+ preferences.zoomInOverlapMs ?? DEFAULT_ZOOM_IN_OVERLAP_MS,
+ );
+ const [zoomOutDurationMs, setZoomOutDurationMs] = useState(
+ preferences.zoomOutDurationMs ?? DEFAULT_ZOOM_OUT_DURATION_MS,
+ );
+ const [connectedZoomGapMs, setConnectedZoomGapMs] = useState(
+ preferences.connectedZoomGapMs ?? DEFAULT_CONNECTED_ZOOM_GAP_MS,
+ );
+ const [connectedZoomDurationMs, setConnectedZoomDurationMs] = useState(
+ preferences.connectedZoomDurationMs ?? DEFAULT_CONNECTED_ZOOM_DURATION_MS,
+ );
+ const [zoomInEasing, setZoomInEasing] = useState<ZoomTransitionEasing>(
+ preferences.zoomInEasing ?? DEFAULT_ZOOM_IN_EASING,
+ );
+ const [zoomOutEasing, setZoomOutEasing] = useState<ZoomTransitionEasing>(
+ preferences.zoomOutEasing ?? DEFAULT_ZOOM_OUT_EASING,
+ );
+ const [connectedZoomEasing, setConnectedZoomEasing] = useState<ZoomTransitionEasing>(
+ preferences.connectedZoomEasing ?? DEFAULT_CONNECTED_ZOOM_EASING,
+ );
+ const [showCursor, setShowCursor] = useState(preferences.showCursor);
+ const [loopCursor, setLoopCursor] = useState(preferences.loopCursor);
+ const [cursorStyle, setCursorStyle] = useState<CursorStyle>(
+ preferences.cursorStyle ?? DEFAULT_CURSOR_STYLE,
+ );
+ const [cursorSize, setCursorSize] = useState(preferences.cursorSize);
+ const [cursorSmoothing, setCursorSmoothing] = useState(preferences.cursorSmoothing);
+ const [cursorSpringStiffnessMultiplier, setCursorSpringStiffnessMultiplier] = useState(
+ preferences.cursorSpringStiffnessMultiplier,
+ );
+ const [cursorSpringDampingMultiplier, setCursorSpringDampingMultiplier] = useState(
+ preferences.cursorSpringDampingMultiplier,
+ );
+ const [cursorSpringMassMultiplier, setCursorSpringMassMultiplier] = useState(
+ preferences.cursorSpringMassMultiplier,
+ );
+ const [cameraSpringStiffnessMultiplier, setCameraSpringStiffnessMultiplier] = useState(
+ preferences.cameraSpringStiffnessMultiplier,
+ );
+ const [cameraSpringDampingMultiplier, setCameraSpringDampingMultiplier] = useState(
+ preferences.cameraSpringDampingMultiplier,
+ );
+ const [cameraSpringMassMultiplier, setCameraSpringMassMultiplier] = useState(
+ preferences.cameraSpringMassMultiplier,
+ );
+ const [zoomSmoothness, setZoomSmoothness] = useState(0.5);
+ const [zoomClassicMode, setZoomClassicMode] = useState(false);
+ const [cursorMotionBlur, setCursorMotionBlur] = useState(preferences.cursorMotionBlur);
+ const [cursorClickEffect, setCursorClickEffect] = useState<CursorClickEffectStyle>(
+ preferences.cursorClickEffect,
+ );
+ const [cursorClickEffectColor, setCursorClickEffectColor] = useState(
+ preferences.cursorClickEffectColor,
+ );
+ const [cursorClickEffectScale, setCursorClickEffectScale] = useState(
+ preferences.cursorClickEffectScale,
+ );
+ const [cursorClickEffectOpacity, setCursorClickEffectOpacity] = useState(
+ preferences.cursorClickEffectOpacity,
+ );
+ const [cursorClickEffectDurationMs, setCursorClickEffectDurationMs] = useState(
+ preferences.cursorClickEffectDurationMs,
+ );
+ const [cursorClickBounce, setCursorClickBounce] = useState(preferences.cursorClickBounce);
+ const [cursorClickBounceDuration, setCursorClickBounceDuration] = useState(
+ preferences.cursorClickBounceDuration,
+ );
+ const [cursorSway, setCursorSway] = useState(preferences.cursorSway);
+ const [borderRadius, setBorderRadius] = useState(preferences.borderRadius);
+ const [padding, setPadding] = useState(preferences.padding);
+ const [cropRegion, setCropRegion] = useState<CropRegion>(DEFAULT_CROP_REGION);
+ const [webcam, setWebcam] = useState<WebcamOverlaySettings>(
+ preferences.webcam ?? DEFAULT_WEBCAM_OVERLAY,
+ );
+ const [resolvedWebcamVideoUrl, setResolvedWebcamVideoUrl] = useState<string | null>(null);
+
+ return {
+ wallpaper,
+ setWallpaper,
+ shadowIntensity,
+ setShadowIntensity,
+ backgroundBlur,
+ setBackgroundBlur,
+ zoomMotionBlur,
+ setZoomMotionBlur,
+ zoomMotionBlurTuning,
+ setZoomMotionBlurTuning,
+ zoomTemporalMotionBlur,
+ setZoomTemporalMotionBlur,
+ zoomMotionBlurSampleCount,
+ setZoomMotionBlurSampleCount,
+ zoomMotionBlurShutterFraction,
+ setZoomMotionBlurShutterFraction,
+ autoApplyFreshRecordingAutoZooms,
+ setAutoApplyFreshRecordingAutoZooms,
+ connectZooms,
+ setConnectZooms,
+ zoomInDurationMs,
+ setZoomInDurationMs,
+ zoomInOverlapMs,
+ setZoomInOverlapMs,
+ zoomOutDurationMs,
+ setZoomOutDurationMs,
+ connectedZoomGapMs,
+ setConnectedZoomGapMs,
+ connectedZoomDurationMs,
+ setConnectedZoomDurationMs,
+ zoomInEasing,
+ setZoomInEasing,
+ zoomOutEasing,
+ setZoomOutEasing,
+ connectedZoomEasing,
+ setConnectedZoomEasing,
+ showCursor,
+ setShowCursor,
+ loopCursor,
+ setLoopCursor,
+ cursorStyle,
+ setCursorStyle,
+ cursorSize,
+ setCursorSize,
+ cursorSmoothing,
+ setCursorSmoothing,
+ cursorSpringStiffnessMultiplier,
+ setCursorSpringStiffnessMultiplier,
+ cursorSpringDampingMultiplier,
+ setCursorSpringDampingMultiplier,
+ cursorSpringMassMultiplier,
+ setCursorSpringMassMultiplier,
+ cameraSpringStiffnessMultiplier,
+ setCameraSpringStiffnessMultiplier,
+ cameraSpringDampingMultiplier,
+ setCameraSpringDampingMultiplier,
+ cameraSpringMassMultiplier,
+ setCameraSpringMassMultiplier,
+ zoomSmoothness,
+ setZoomSmoothness,
+ zoomClassicMode,
+ setZoomClassicMode,
+ cursorMotionBlur,
+ setCursorMotionBlur,
+ cursorClickEffect,
+ setCursorClickEffect,
+ cursorClickEffectColor,
+ setCursorClickEffectColor,
+ cursorClickEffectScale,
+ setCursorClickEffectScale,
+ cursorClickEffectOpacity,
+ setCursorClickEffectOpacity,
+ cursorClickEffectDurationMs,
+ setCursorClickEffectDurationMs,
+ cursorClickBounce,
+ setCursorClickBounce,
+ cursorClickBounceDuration,
+ setCursorClickBounceDuration,
+ cursorSway,
+ setCursorSway,
+ borderRadius,
+ setBorderRadius,
+ padding,
+ setPadding,
+ cropRegion,
+ setCropRegion,
+ webcam,
+ setWebcam,
+ resolvedWebcamVideoUrl,
+ setResolvedWebcamVideoUrl,
+ };
+}
diff --git a/src/components/video-editor/state/useEditorUiState.ts b/src/components/video-editor/state/useEditorUiState.ts
new file mode 100644
index 00000000..4d6e34d5
--- /dev/null
+++ b/src/components/video-editor/state/useEditorUiState.ts
@@ -0,0 +1,177 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { OPEN_EDITOR_SECTION_EVENT } from "@/lib/announcementActions";
+import { type AnnouncementEditorSection, isAnnouncementEditorSection } from "@/lib/announcements";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import type { loadEditorPreferences } from "../editorPreferences";
+import type { TimelineEditorHandle } from "../timeline/TimelineEditor";
+import type { CropRegion, EditorEffectSection } from "../types";
+import type { VideoPlaybackRef } from "../VideoPlayback";
+
+type SessionPresentation = {
+ hideOverlayCursorByDefault?: boolean;
+ nativeCaptureUnavailable?: boolean;
+};
+
+export function useEditorUiState(
+ initialPreferences: ReturnType<typeof loadEditorPreferences>,
+ cropRegion: CropRegion,
+ setCropRegion: (region: CropRegion) => void,
+) {
+ const [appPlatform, setAppPlatform] = useState(
+ typeof navigator !== "undefined" && /Mac/i.test(navigator.platform) ? "darwin" : "",
+ );
+ const [isPlaying, setIsPlaying] = useState(false);
+ const [currentTime, setCurrentTime] = useState(0);
+ const [duration, setDuration] = useState(0);
+ const [sessionShowCursorOverride, setSessionShowCursorOverride] = useState<boolean | null>(
+ null,
+ );
+ const [sessionNativeCaptureUnavailable, setSessionNativeCaptureUnavailable] = useState(false);
+ const [nativeCaptureUnavailableModalOpen, setNativeCaptureUnavailableModalOpen] =
+ useState(false);
+ const [whisperExecutablePath, setWhisperExecutablePath] = useState<string | null>(
+ initialPreferences.whisperExecutablePath,
+ );
+ const [whisperModelPath, setWhisperModelPath] = useState<string | null>(
+ initialPreferences.whisperModelPath,
+ );
+ const [downloadedWhisperModelPath, setDownloadedWhisperModelPath] = useState<string | null>(
+ null,
+ );
+ const [whisperModelDownloadStatus, setWhisperModelDownloadStatus] = useState<
+ "idle" | "downloading" | "downloaded" | "error"
+ >(initialPreferences.whisperModelPath ? "downloaded" : "idle");
+ const [whisperModelDownloadProgress, setWhisperModelDownloadProgress] = useState(0);
+ const [isGeneratingCaptions, setIsGeneratingCaptions] = useState(false);
+ const [previewVolume, setPreviewVolume] = useState(1);
+ const [aspectRatio, setAspectRatio] = useState<AspectRatio>(initialPreferences.aspectRatio);
+ const [activeEffectSection, setActiveEffectSection] = useState<EditorEffectSection>("scene");
+ const [showCropModal, setShowCropModal] = useState(false);
+ const [previewVersion, setPreviewVersion] = useState(0);
+ const [isPreviewReady, setIsPreviewReady] = useState(false);
+ const [autoSuggestZoomsTrigger, setAutoSuggestZoomsTrigger] = useState(0);
+
+ const videoPlaybackRef = useRef<VideoPlaybackRef>(null);
+ const projectBrowserTriggerRef = useRef<HTMLButtonElement | null>(null);
+ const projectBrowserFallbackTriggerRef = useRef<HTMLButtonElement | null>(null);
+ const projectNameInputRef = useRef<HTMLInputElement | null>(null);
+ const projectSaveDialogInputRef = useRef<HTMLInputElement | null>(null);
+ const nextZoomIdRef = useRef(1);
+ const nextClipIdRef = useRef(1);
+ const clipInitializedRef = useRef(false);
+ const autoFullTrackClipIdRef = useRef<string | null>(null);
+ const autoFullTrackClipEndMsRef = useRef<number | null>(null);
+ const nextAudioIdRef = useRef(1);
+ const nextAnnotationIdRef = useRef(1);
+ const nextAnnotationZIndexRef = useRef(1);
+ const autoSuggestedVideoPathRef = useRef<string | null>(null);
+ const pendingFreshRecordingAutoZoomPathRef = useRef<string | null>(null);
+ const pendingFreshRecordingAutoSuggestTimeoutRef = useRef<number | null>(null);
+ const pendingFreshRecordingAutoSuggestTelemetryCountRef = useRef(0);
+ const cropSnapshotRef = useRef<CropRegion | null>(null);
+ const timelineRef = useRef<TimelineEditorHandle>(null);
+
+ useEffect(() => {
+ void window.electronAPI?.getPlatform?.()?.then(setAppPlatform);
+ }, []);
+ useEffect(() => {
+ const handleOpenEditorSection = (event: Event) => {
+ const section = (event as CustomEvent<AnnouncementEditorSection>).detail;
+ if (isAnnouncementEditorSection(section)) setActiveEffectSection(section);
+ };
+ window.addEventListener(OPEN_EDITOR_SECTION_EVENT, handleOpenEditorSection);
+ return () => window.removeEventListener(OPEN_EDITOR_SECTION_EVENT, handleOpenEditorSection);
+ }, []);
+ useEffect(() => {
+ if (activeEffectSection === "frame" || activeEffectSection === "crop")
+ setActiveEffectSection("scene");
+ }, [activeEffectSection]);
+
+ const applySessionPresentation = useCallback(
+ (session: SessionPresentation | null | undefined) => {
+ setSessionShowCursorOverride(session?.hideOverlayCursorByDefault ? false : null);
+ setSessionNativeCaptureUnavailable(Boolean(session?.nativeCaptureUnavailable));
+ setNativeCaptureUnavailableModalOpen(Boolean(session?.nativeCaptureUnavailable));
+ },
+ [],
+ );
+ const handleOpenCropEditor = useCallback(() => {
+ cropSnapshotRef.current = { ...cropRegion };
+ setShowCropModal(true);
+ }, [cropRegion]);
+ const handleCloseCropEditor = useCallback(() => setShowCropModal(false), []);
+ const handleCancelCropEditor = useCallback(() => {
+ if (cropSnapshotRef.current) setCropRegion(cropSnapshotRef.current);
+ setShowCropModal(false);
+ }, [setCropRegion]);
+ const isCropped = useMemo(() => {
+ const top = Math.round(cropRegion.y * 100);
+ const left = Math.round(cropRegion.x * 100);
+ const bottom = Math.round((1 - cropRegion.y - cropRegion.height) * 100);
+ const right = Math.round((1 - cropRegion.x - cropRegion.width) * 100);
+ return top > 0 || left > 0 || bottom > 0 || right > 0;
+ }, [cropRegion]);
+
+ return {
+ appPlatform,
+ isPlaying,
+ setIsPlaying,
+ currentTime,
+ setCurrentTime,
+ duration,
+ setDuration,
+ sessionShowCursorOverride,
+ setSessionShowCursorOverride,
+ sessionNativeCaptureUnavailable,
+ nativeCaptureUnavailableModalOpen,
+ setNativeCaptureUnavailableModalOpen,
+ whisperExecutablePath,
+ setWhisperExecutablePath,
+ whisperModelPath,
+ setWhisperModelPath,
+ downloadedWhisperModelPath,
+ setDownloadedWhisperModelPath,
+ whisperModelDownloadStatus,
+ setWhisperModelDownloadStatus,
+ whisperModelDownloadProgress,
+ setWhisperModelDownloadProgress,
+ isGeneratingCaptions,
+ setIsGeneratingCaptions,
+ previewVolume,
+ setPreviewVolume,
+ aspectRatio,
+ setAspectRatio,
+ activeEffectSection,
+ setActiveEffectSection,
+ showCropModal,
+ previewVersion,
+ setPreviewVersion,
+ isPreviewReady,
+ setIsPreviewReady,
+ autoSuggestZoomsTrigger,
+ setAutoSuggestZoomsTrigger,
+ videoPlaybackRef,
+ projectBrowserTriggerRef,
+ projectBrowserFallbackTriggerRef,
+ projectNameInputRef,
+ projectSaveDialogInputRef,
+ nextZoomIdRef,
+ nextClipIdRef,
+ clipInitializedRef,
+ autoFullTrackClipIdRef,
+ autoFullTrackClipEndMsRef,
+ nextAudioIdRef,
+ nextAnnotationIdRef,
+ nextAnnotationZIndexRef,
+ autoSuggestedVideoPathRef,
+ pendingFreshRecordingAutoZoomPathRef,
+ pendingFreshRecordingAutoSuggestTimeoutRef,
+ pendingFreshRecordingAutoSuggestTelemetryCountRef,
+ timelineRef,
+ applySessionPresentation,
+ handleOpenCropEditor,
+ handleCloseCropEditor,
+ handleCancelCropEditor,
+ isCropped,
+ };
+}
diff --git a/src/components/video-editor/state/useProjectState.ts b/src/components/video-editor/state/useProjectState.ts
new file mode 100644
index 00000000..1b5a3d7a
--- /dev/null
+++ b/src/components/video-editor/state/useProjectState.ts
@@ -0,0 +1,58 @@
+import { useState } from "react";
+import type { ProjectLibraryEntry } from "../ProjectBrowserDialog";
+import type { EditorProjectData } from "../projectPersistence";
+
+export function useProjectState() {
+ const [videoPath, setVideoPath] = useState<string | null>(null);
+ const [videoSourcePath, setVideoSourcePath] = useState<string | null>(null);
+ const [currentProjectPath, setCurrentProjectPath] = useState<string | null>(null);
+ const [projectLibraryEntries, setProjectLibraryEntries] = useState<ProjectLibraryEntry[]>([]);
+ const [projectBrowserOpen, setProjectBrowserOpen] = useState(false);
+ const [isEditingProjectName, setIsEditingProjectName] = useState(false);
+ const [projectNameDraft, setProjectNameDraft] = useState("");
+ const [isSavingProjectName, setIsSavingProjectName] = useState(false);
+ const [projectSaveDialogOpen, setProjectSaveDialogOpen] = useState(false);
+ const [projectSaveDialogDraft, setProjectSaveDialogDraft] = useState("");
+ const [isSavingProjectDialog, setIsSavingProjectDialog] = useState(false);
+ const [unsavedChangesDialogOpen, setUnsavedChangesDialogOpen] = useState(false);
+ const [unsavedChangesDialogActionLabel, setUnsavedChangesDialogActionLabel] =
+ useState("continue");
+ const [lastSavedSnapshot, setLastSavedSnapshot] = useState<EditorProjectData | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ return {
+ videoPath,
+ setVideoPath,
+ videoSourcePath,
+ setVideoSourcePath,
+ currentProjectPath,
+ setCurrentProjectPath,
+ projectLibraryEntries,
+ setProjectLibraryEntries,
+ projectBrowserOpen,
+ setProjectBrowserOpen,
+ isEditingProjectName,
+ setIsEditingProjectName,
+ projectNameDraft,
+ setProjectNameDraft,
+ isSavingProjectName,
+ setIsSavingProjectName,
+ projectSaveDialogOpen,
+ setProjectSaveDialogOpen,
+ projectSaveDialogDraft,
+ setProjectSaveDialogDraft,
+ isSavingProjectDialog,
+ setIsSavingProjectDialog,
+ unsavedChangesDialogOpen,
+ setUnsavedChangesDialogOpen,
+ unsavedChangesDialogActionLabel,
+ setUnsavedChangesDialogActionLabel,
+ lastSavedSnapshot,
+ setLastSavedSnapshot,
+ loading,
+ setLoading,
+ error,
+ setError,
+ };
+}
diff --git a/src/components/video-editor/state/useTimelineState.ts b/src/components/video-editor/state/useTimelineState.ts
new file mode 100644
index 00000000..155d9a54
--- /dev/null
+++ b/src/components/video-editor/state/useTimelineState.ts
@@ -0,0 +1,82 @@
+import { useState } from "react";
+import type { SourceAudioTrackSettings } from "../audio/audioTypes";
+import type {
+ AnnotationRegion,
+ AudioRegion,
+ AutoCaptionSettings,
+ CaptionCue,
+ ClipRegion,
+ CursorTelemetryPoint,
+ SpeedRegion,
+ TrimRegion,
+ ZoomRegion,
+} from "../types";
+import { DEFAULT_AUTO_CAPTION_SETTINGS } from "../types";
+
+export function useTimelineState() {
+ const [zoomRegions, setZoomRegions] = useState<ZoomRegion[]>([]);
+ const [cursorTelemetry, setCursorTelemetry] = useState<CursorTelemetryPoint[]>([]);
+ const [cursorTelemetrySourcePath, setCursorTelemetrySourcePath] = useState<string | null>(null);
+ const [selectedZoomId, setSelectedZoomId] = useState<string | null>(null);
+ const [trimRegions, setTrimRegions] = useState<TrimRegion[]>([]);
+ const [clipRegions, setClipRegions] = useState<ClipRegion[]>([]);
+ const [selectedClipId, setSelectedClipId] = useState<string | null>(null);
+ const [speedRegions, setSpeedRegions] = useState<SpeedRegion[]>([]);
+ const [annotationRegions, setAnnotationRegions] = useState<AnnotationRegion[]>([]);
+ const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);
+ const [audioRegions, setAudioRegions] = useState<AudioRegion[]>([]);
+ const [selectedAudioId, setSelectedAudioId] = useState<string | null>(null);
+ const [selectedCaptionId, setSelectedCaptionId] = useState<string | null>(null);
+ const [sourceAudioTrackSettingsByClip, setSourceAudioTrackSettingsByClip] = useState<
+ Record<string, SourceAudioTrackSettings>
+ >({});
+ const [defaultSourceAudioTrackSettings, setDefaultSourceAudioTrackSettings] =
+ useState<SourceAudioTrackSettings>({});
+ const [sourceAudioFallbackRefreshKey, setSourceAudioFallbackRefreshKey] = useState(0);
+ const [hasClipSourceAudio, setHasClipSourceAudio] = useState(false);
+ const [autoCaptions, setAutoCaptions] = useState<CaptionCue[]>([]);
+ const [autoCaptionSettings, setAutoCaptionSettings] = useState<AutoCaptionSettings>(
+ DEFAULT_AUTO_CAPTION_SETTINGS,
+ );
+
+ return {
+ zoomRegions,
+ setZoomRegions,
+ cursorTelemetry,
+ setCursorTelemetry,
+ cursorTelemetrySourcePath,
+ setCursorTelemetrySourcePath,
+ selectedZoomId,
+ setSelectedZoomId,
+ trimRegions,
+ setTrimRegions,
+ clipRegions,
+ setClipRegions,
+ selectedClipId,
+ setSelectedClipId,
+ speedRegions,
+ setSpeedRegions,
+ annotationRegions,
+ setAnnotationRegions,
+ selectedAnnotationId,
+ setSelectedAnnotationId,
+ audioRegions,
+ setAudioRegions,
+ selectedAudioId,
+ setSelectedAudioId,
+ selectedCaptionId,
+ setSelectedCaptionId,
+ sourceAudioTrackSettingsByClip,
+ setSourceAudioTrackSettingsByClip,
+ defaultSourceAudioTrackSettings,
+ setDefaultSourceAudioTrackSettings,
+ sourceAudioFallbackRefreshKey,
+ setSourceAudioFallbackRefreshKey,
+ hasClipSourceAudio,
+ setHasClipSourceAudio,
+ autoCaptions,
+ setAutoCaptions,
+ autoCaptionSettings,
+ setAutoCaptionSettings,
+ };
+}
diff --git a/src/components/video-editor/videoEditorUtils.ts b/src/components/video-editor/videoEditorUtils.ts
new file mode 100644
index 00000000..f5bc1e07
--- /dev/null
+++ b/src/components/video-editor/videoEditorUtils.ts
@@ -0,0 +1,18 @@
+export function summarizeErrorMessage(message: string): string {
+ const firstLine = message
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .find((line) => line.length > 0);
+
+ return firstLine ?? message;
+}
+
+export function cloneStructured<T>(value: T): T {
+ return globalThis.structuredClone(value);
+}
+
+export function getErrorMessage(error: unknown): string {
+ if (error instanceof Error) return error.message;
+ if (typeof error === "string") return error.replace(/^Error:\s*/i, "");
+ return "Something went wrong";
+}