Skip to content

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

merge main into feat/cursor-sway

KBCatsdf1d24f4a5f7
diff --cc electron/electron-env.d.ts
index cf5c2e88,371ea789..94610648
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@@ -1,220 -1,122 +1,227 @@@
-/// <reference types="vite-plugin-electron/electron-env" />
-
-declare namespace NodeJS {
- interface ProcessEnv {
- /**
- * The built directory structure
- *
- * ```tree
- * ├─┬─┬ dist
- * │ │ └── index.html
- * │ │
- * │ ├─┬ dist-electron
- * │ │ ├── main.js
- * │ │ └── preload.js
- * │
- * ```
- */
- APP_ROOT: string
- /** /dist/ or /public/ */
- VITE_PUBLIC: string
- }
-}
-
-// Used in Renderer process, expose in `preload.ts`
-interface Window {
- electronAPI: {
- getSources: (opts: Electron.SourcesOptions) => Promise<ProcessedDesktopSource[]>
- switchToEditor: () => Promise<void>
- openSourceSelector: () => Promise<void>
- selectSource: (source: any) => Promise<any>
- getSelectedSource: () => Promise<any>
- startNativeScreenRecording: (
- source: any,
- options?: {
- capturesSystemAudio?: boolean
- capturesMicrophone?: boolean
- microphoneDeviceId?: string
- microphoneLabel?: string
- }
- ) => Promise<{ success: boolean; path?: string; message?: string; error?: string }>
- stopNativeScreenRecording: () => Promise<{ success: boolean; path?: string; message?: string; error?: string }>
- startFfmpegRecording: (source: any) => Promise<{ success: boolean; path?: string; message?: string; error?: string }>
- stopFfmpegRecording: () => Promise<{ success: boolean; path?: string; message?: string; error?: string }>
- storeRecordedVideo: (videoData: ArrayBuffer, fileName: string) => Promise<{ success: boolean; path?: string; message?: string }>
- getRecordedVideoPath: () => Promise<{ success: boolean; path?: string; message?: string }>
- readLocalFile: (filePath: string) => Promise<{ success: boolean; data?: Uint8Array; error?: string }>
- setRecordingState: (recording: boolean) => Promise<void>
- getCursorTelemetry: (videoPath?: string) => Promise<{ success: boolean; samples: CursorTelemetryPoint[]; message?: string; error?: string }>
- getSystemCursorAssets: () => Promise<{ success: boolean; cursors: Record<string, SystemCursorAsset>; error?: string }>
- onStopRecordingFromTray: (callback: () => void) => () => void
- onRecordingStateChanged: (callback: (state: { recording: boolean; sourceName: string }) => void) => () => void
- onRecordingInterrupted: (callback: (state: { reason: string; message: string }) => void) => () => void
- onCursorStateChanged: (callback: (state: { cursorType: CursorTelemetryPoint['cursorType'] }) => void) => () => void
- openExternalUrl: (url: string) => Promise<{ success: boolean; error?: string }>
- getAccessibilityPermissionStatus: () => Promise<{ success: boolean; trusted: boolean; prompted: boolean; error?: string }>
- requestAccessibilityPermission: () => Promise<{ success: boolean; trusted: boolean; prompted: boolean; error?: string }>
- getScreenRecordingPermissionStatus: () => Promise<{ success: boolean; status: string; error?: string }>
- openScreenRecordingPreferences: () => Promise<{ success: boolean; error?: string }>
- openAccessibilityPreferences: () => Promise<{ success: boolean; error?: string }>
- saveExportedVideo: (videoData: ArrayBuffer, fileName: string) => Promise<{ success: boolean; path?: string; message?: string; canceled?: boolean }>
- openVideoFilePicker: () => Promise<{ success: boolean; path?: string; canceled?: boolean }>
- setCurrentVideoPath: (path: string) => Promise<{ success: boolean }>
- getCurrentVideoPath: () => Promise<{ success: boolean; path?: string }>
- clearCurrentVideoPath: () => Promise<{ success: boolean }>
- saveProjectFile: (projectData: unknown, suggestedName?: string, existingProjectPath?: string) => Promise<{ success: boolean; path?: string; message?: string; canceled?: boolean; error?: string }>
- loadProjectFile: () => Promise<{ success: boolean; path?: string; project?: unknown; message?: string; canceled?: boolean; error?: string }>
- loadCurrentProjectFile: () => Promise<{ success: boolean; path?: string; project?: unknown; message?: string; canceled?: boolean; error?: string }>
- onMenuLoadProject: (callback: () => void) => () => void
- onMenuSaveProject: (callback: () => void) => () => void
- onMenuSaveProjectAs: (callback: () => void) => () => void
- getPlatform: () => Promise<string>
- revealInFolder: (filePath: string) => Promise<{ success: boolean; error?: string; message?: string }>,
- openRecordingsFolder: () => Promise<{ success: boolean; error?: string; message?: string }>,
- getRecordingsDirectory: () => Promise<{ success: boolean; path: string; isDefault: boolean; error?: string }>
- chooseRecordingsDirectory: () => Promise<{ success: boolean; canceled?: boolean; path?: string; isDefault?: boolean; message?: string; error?: string }>
- getShortcuts: () => Promise<Record<string, unknown> | null>
- saveShortcuts: (shortcuts: unknown) => Promise<{ success: boolean; error?: string }>
- hudOverlayHide: () => void;
- hudOverlayClose: () => void;
- setHasUnsavedChanges: (hasChanges: boolean) => void
- onRequestSaveBeforeClose: (callback: () => Promise<void>) => () => void
- isWgcAvailable: () => Promise<{ available: boolean }>
- muxWgcRecording: () => Promise<{ success: boolean; path?: string; message?: string; error?: string }>
- /** Hide the OS cursor before browser capture starts. */
- hideOsCursor: () => Promise<{ success: boolean }>
- /** Countdown timer before recording */
- getCountdownDelay: () => Promise<{ success: boolean; delay: number }>
- setCountdownDelay: (delay: number) => Promise<{ success: boolean; error?: string }>
- startCountdown: (seconds: number) => Promise<{ success: boolean; cancelled?: boolean }>
- cancelCountdown: () => Promise<{ success: boolean }>
- onCountdownTick: (callback: (seconds: number) => void) => () => void
- }
-}
-
-interface ProcessedDesktopSource {
- id: string
- name: string
- display_id: string
- thumbnail: string | null
- appIcon: string | null
- originalName?: string
- sourceType?: 'screen' | 'window'
- appName?: string
- windowTitle?: string
-}
-
-interface CursorTelemetryPoint {
- timeMs: number
- cx: number
- cy: number
- interactionType?: 'move' | 'click' | 'double-click' | 'right-click' | 'middle-click' | 'mouseup'
- cursorType?: 'arrow' | 'text' | 'pointer' | 'crosshair' | 'open-hand' | 'closed-hand' | 'resize-ew' | 'resize-ns' | 'not-allowed'
-}
-
-interface SystemCursorAsset {
- dataUrl: string
- hotspotX: number
- hotspotY: number
- width: number
- height: number
-}
-
+/// <reference types="vite-plugin-electron/electron-env" />
+
+declare namespace NodeJS {
+ interface ProcessEnv {
+ /**
+ * The built directory structure
+ *
+ * ```tree
+ * ├─┬─┬ dist
+ * │ │ └── index.html
+ * │ │
+ * │ ├─┬ dist-electron
+ * │ │ ├── main.js
+ * │ │ └── preload.js
+ * │
+ * ```
+ */
+ APP_ROOT: string;
+ /** /dist/ or /public/ */
+ VITE_PUBLIC: string;
+ }
+}
+
+// Used in Renderer process, expose in `preload.ts`
+interface Window {
+ electronAPI: {
+ getSources: (opts: Electron.SourcesOptions) => Promise<ProcessedDesktopSource[]>;
+ switchToEditor: () => Promise<void>;
+ openSourceSelector: () => Promise<void>;
+ selectSource: (source: any) => Promise<any>;
+ getSelectedSource: () => Promise<any>;
+ startNativeScreenRecording: (
+ source: any,
+ options?: {
+ capturesSystemAudio?: boolean;
+ capturesMicrophone?: boolean;
+ microphoneDeviceId?: string;
+ microphoneLabel?: string;
+ },
+ ) => Promise<{ success: boolean; path?: string; message?: string; error?: string }>;
+ stopNativeScreenRecording: () => Promise<{
+ success: boolean;
+ path?: string;
+ message?: string;
+ error?: string;
+ }>;
+ startFfmpegRecording: (
+ source: any,
+ ) => Promise<{ success: boolean; path?: string; message?: string; error?: string }>;
+ stopFfmpegRecording: () => Promise<{
+ success: boolean;
+ path?: string;
+ message?: string;
+ error?: string;
+ }>;
+ storeRecordedVideo: (
+ videoData: ArrayBuffer,
+ fileName: string,
+ ) => Promise<{ success: boolean; path?: string; message?: string }>;
+ getRecordedVideoPath: () => Promise<{ success: boolean; path?: string; message?: string }>;
+ readLocalFile: (
+ filePath: string,
+ ) => Promise<{ success: boolean; data?: Uint8Array; error?: string }>;
+ setRecordingState: (recording: boolean) => Promise<void>;
+ getCursorTelemetry: (videoPath?: string) => Promise<{
+ success: boolean;
+ samples: CursorTelemetryPoint[];
+ message?: string;
+ error?: string;
+ }>;
+ getSystemCursorAssets: () => Promise<{
+ success: boolean;
+ cursors: Record<string, SystemCursorAsset>;
+ error?: string;
+ }>;
+ onStopRecordingFromTray: (callback: () => void) => () => void;
+ onRecordingStateChanged: (
+ callback: (state: { recording: boolean; sourceName: string }) => void,
+ ) => () => void;
+ onRecordingInterrupted: (
+ callback: (state: { reason: string; message: string }) => void,
+ ) => () => void;
+ onCursorStateChanged: (
+ callback: (state: { cursorType: CursorTelemetryPoint["cursorType"] }) => void,
+ ) => () => void;
+ openExternalUrl: (url: string) => Promise<{ success: boolean; error?: string }>;
+ getAccessibilityPermissionStatus: () => Promise<{
+ success: boolean;
+ trusted: boolean;
+ prompted: boolean;
+ error?: string;
+ }>;
+ requestAccessibilityPermission: () => Promise<{
+ success: boolean;
+ trusted: boolean;
+ prompted: boolean;
+ error?: string;
+ }>;
+ getScreenRecordingPermissionStatus: () => Promise<{
+ success: boolean;
+ status: string;
+ error?: string;
+ }>;
+ openScreenRecordingPreferences: () => Promise<{ success: boolean; error?: string }>;
+ openAccessibilityPreferences: () => Promise<{ success: boolean; error?: string }>;
+ saveExportedVideo: (
+ videoData: ArrayBuffer,
+ fileName: string,
+ ) => Promise<{ success: boolean; path?: string; message?: string; canceled?: boolean }>;
+ openVideoFilePicker: () => Promise<{ success: boolean; path?: string; canceled?: boolean }>;
++ openAudioFilePicker: () => Promise<{ success: boolean; path?: string; canceled?: boolean }>;
+ setCurrentVideoPath: (path: string) => Promise<{ success: boolean }>;
+ getCurrentVideoPath: () => Promise<{ success: boolean; path?: string }>;
+ clearCurrentVideoPath: () => Promise<{ success: boolean }>;
+ saveProjectFile: (
+ projectData: unknown,
+ suggestedName?: string,
+ existingProjectPath?: string,
+ ) => Promise<{
+ success: boolean;
+ path?: string;
+ message?: string;
+ canceled?: boolean;
+ error?: string;
+ }>;
+ loadProjectFile: () => Promise<{
+ success: boolean;
+ path?: string;
+ project?: unknown;
+ message?: string;
+ canceled?: boolean;
+ error?: string;
+ }>;
+ loadCurrentProjectFile: () => Promise<{
+ success: boolean;
+ path?: string;
+ project?: unknown;
+ message?: string;
+ canceled?: boolean;
+ error?: string;
+ }>;
+ onMenuLoadProject: (callback: () => void) => () => void;
+ onMenuSaveProject: (callback: () => void) => () => void;
+ onMenuSaveProjectAs: (callback: () => void) => () => void;
+ getPlatform: () => Promise<string>;
+ revealInFolder: (
+ filePath: string,
+ ) => Promise<{ success: boolean; error?: string; message?: string }>;
+ openRecordingsFolder: () => Promise<{ success: boolean; error?: string; message?: string }>;
+ getRecordingsDirectory: () => Promise<{
+ success: boolean;
+ path: string;
+ isDefault: boolean;
+ error?: string;
+ }>;
+ chooseRecordingsDirectory: () => Promise<{
+ success: boolean;
+ canceled?: boolean;
+ path?: string;
+ isDefault?: boolean;
+ message?: string;
+ error?: string;
+ }>;
+ getShortcuts: () => Promise<Record<string, unknown> | null>;
+ saveShortcuts: (shortcuts: unknown) => Promise<{ success: boolean; error?: string }>;
+ hudOverlayHide: () => void;
+ hudOverlayClose: () => void;
+ getHudOverlayCaptureProtection: () => Promise<{ success: boolean; enabled: boolean }>;
+ setHudOverlayCaptureProtection: (
+ enabled: boolean,
+ ) => Promise<{ success: boolean; enabled: boolean }>;
+ setHasUnsavedChanges: (hasChanges: boolean) => void;
+ onRequestSaveBeforeClose: (callback: () => Promise<void>) => () => void;
+ isWgcAvailable: () => Promise<{ available: boolean }>;
+ muxWgcRecording: () => Promise<{
+ success: boolean;
+ path?: string;
+ message?: string;
+ error?: string;
+ }>;
+ /** Hide the OS cursor before browser capture starts. */
+ hideOsCursor: () => Promise<{ success: boolean }>;
++ /** Countdown timer before recording */
++ getCountdownDelay: () => Promise<{ success: boolean; delay: number }>;
++ setCountdownDelay: (delay: number) => Promise<{ success: boolean; error?: string }>;
++ startCountdown: (seconds: number) => Promise<{ success: boolean; cancelled?: boolean }>;
++ cancelCountdown: () => Promise<{ success: boolean }>;
++ onCountdownTick: (callback: (seconds: number) => void) => () => void;
+ };
+}
+
+interface ProcessedDesktopSource {
+ id: string;
+ name: string;
+ display_id: string;
+ thumbnail: string | null;
+ appIcon: string | null;
+ originalName?: string;
+ sourceType?: "screen" | "window";
+ appName?: string;
+ windowTitle?: string;
+}
+
+interface CursorTelemetryPoint {
+ timeMs: number;
+ cx: number;
+ cy: number;
+ interactionType?: "move" | "click" | "double-click" | "right-click" | "middle-click" | "mouseup";
+ cursorType?:
+ | "arrow"
+ | "text"
+ | "pointer"
+ | "crosshair"
+ | "open-hand"
+ | "closed-hand"
+ | "resize-ew"
+ | "resize-ns"
+ | "not-allowed";
+}
+
+interface SystemCursorAsset {
+ dataUrl: string;
+ hotspotX: number;
+ hotspotY: number;
+ width: number;
+ height: number;
+}
diff --cc electron/native/bin/darwin-arm64/openscreen-native-cursor-monitor
index 9b3e16e1,77d85ce8..c123f707
Binary files differ
diff --cc electron/native/bin/darwin-arm64/openscreen-screencapturekit-helper
index 2f5bda23,447588fd..1391758c
Binary files differ
diff --cc electron/native/bin/darwin-arm64/openscreen-system-cursors
index 131caccd,926b24e0..c36225a8
Binary files differ
diff --cc electron/native/bin/darwin-arm64/openscreen-window-list
index 34ec60b7,977c0283..29f275af
Binary files differ
diff --cc electron/preload.ts
index d149dc91,bc282d8b..e56b0b85
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@@ -1,204 -1,199 +1,212 @@@
-import { contextBridge, ipcRenderer } from 'electron'
-
-contextBridge.exposeInMainWorld('electronAPI', {
- hudOverlayHide: () => {
- ipcRenderer.send('hud-overlay-hide');
- },
- hudOverlayClose: () => {
- ipcRenderer.send('hud-overlay-close');
- },
- getAssetBasePath: async () => {
- // ask main process for the correct base path (production vs dev)
- return await ipcRenderer.invoke('get-asset-base-path')
- },
- readLocalFile: (filePath: string) => {
- return ipcRenderer.invoke('read-local-file', filePath)
- },
- getSources: async (opts: Electron.SourcesOptions) => {
- return await ipcRenderer.invoke('get-sources', opts)
- },
- switchToEditor: () => {
- return ipcRenderer.invoke('switch-to-editor')
- },
- openSourceSelector: () => {
- return ipcRenderer.invoke('open-source-selector')
- },
- selectSource: (source: any) => {
- return ipcRenderer.invoke('select-source', source)
- },
- getSelectedSource: () => {
- return ipcRenderer.invoke('get-selected-source')
- },
- startNativeScreenRecording: (
- source: any,
- options?: {
- capturesSystemAudio?: boolean
- capturesMicrophone?: boolean
- microphoneDeviceId?: string
- microphoneLabel?: string
- },
- ) => {
- return ipcRenderer.invoke('start-native-screen-recording', source, options)
- },
- stopNativeScreenRecording: () => {
- return ipcRenderer.invoke('stop-native-screen-recording')
- },
- startFfmpegRecording: (source: any) => {
- return ipcRenderer.invoke('start-ffmpeg-recording', source)
- },
- stopFfmpegRecording: () => {
- return ipcRenderer.invoke('stop-ffmpeg-recording')
- },
-
- storeRecordedVideo: (videoData: ArrayBuffer, fileName: string) => {
- return ipcRenderer.invoke('store-recorded-video', videoData, fileName)
- },
-
- getRecordedVideoPath: () => {
- return ipcRenderer.invoke('get-recorded-video-path')
- },
- setRecordingState: (recording: boolean) => {
- return ipcRenderer.invoke('set-recording-state', recording)
- },
- setCursorScale: (scale: number) => {
- return ipcRenderer.invoke('set-cursor-scale', scale)
- },
- getCursorTelemetry: (videoPath?: string) => {
- return ipcRenderer.invoke('get-cursor-telemetry', videoPath)
- },
- getSystemCursorAssets: () => {
- return ipcRenderer.invoke('get-system-cursor-assets')
- },
- onStopRecordingFromTray: (callback: () => void) => {
- const listener = () => callback()
- ipcRenderer.on('stop-recording-from-tray', listener)
- return () => ipcRenderer.removeListener('stop-recording-from-tray', listener)
- },
- onRecordingStateChanged: (callback: (state: { recording: boolean; sourceName: string }) => void) => {
- const listener = (_event: Electron.IpcRendererEvent, payload: { recording: boolean; sourceName: string }) => callback(payload)
- ipcRenderer.on('recording-state-changed', listener)
- return () => ipcRenderer.removeListener('recording-state-changed', listener)
- },
- onRecordingInterrupted: (callback: (state: { reason: string; message: string }) => void) => {
- const listener = (_event: Electron.IpcRendererEvent, payload: { reason: string; message: string }) => callback(payload)
- ipcRenderer.on('recording-interrupted', listener)
- return () => ipcRenderer.removeListener('recording-interrupted', listener)
- },
- onCursorStateChanged: (callback: (state: { cursorType: CursorTelemetryPoint['cursorType'] }) => void) => {
- const listener = (_event: Electron.IpcRendererEvent, payload: { cursorType: CursorTelemetryPoint['cursorType'] }) => callback(payload)
- ipcRenderer.on('cursor-state-changed', listener)
- return () => ipcRenderer.removeListener('cursor-state-changed', listener)
- },
- openExternalUrl: (url: string) => {
- return ipcRenderer.invoke('open-external-url', url)
- },
- getAccessibilityPermissionStatus: () => {
- return ipcRenderer.invoke('get-accessibility-permission-status')
- },
- requestAccessibilityPermission: () => {
- return ipcRenderer.invoke('request-accessibility-permission')
- },
- getScreenRecordingPermissionStatus: () => {
- return ipcRenderer.invoke('get-screen-recording-permission-status')
- },
- openScreenRecordingPreferences: () => {
- return ipcRenderer.invoke('open-screen-recording-preferences')
- },
- openAccessibilityPreferences: () => {
- return ipcRenderer.invoke('open-accessibility-preferences')
- },
- saveExportedVideo: (videoData: ArrayBuffer, fileName: string) => {
- return ipcRenderer.invoke('save-exported-video', videoData, fileName)
- },
- openVideoFilePicker: () => {
- return ipcRenderer.invoke('open-video-file-picker')
- },
- openAudioFilePicker: () => {
- return ipcRenderer.invoke('open-audio-file-picker')
- },
- setCurrentVideoPath: (path: string) => {
- return ipcRenderer.invoke('set-current-video-path', path)
- },
- getCurrentVideoPath: () => {
- return ipcRenderer.invoke('get-current-video-path')
- },
- clearCurrentVideoPath: () => {
- return ipcRenderer.invoke('clear-current-video-path')
- },
- saveProjectFile: (projectData: unknown, suggestedName?: string, existingProjectPath?: string) => {
- return ipcRenderer.invoke('save-project-file', projectData, suggestedName, existingProjectPath)
- },
- loadProjectFile: () => {
- return ipcRenderer.invoke('load-project-file')
- },
- loadCurrentProjectFile: () => {
- return ipcRenderer.invoke('load-current-project-file')
- },
- onMenuLoadProject: (callback: () => void) => {
- const listener = () => callback()
- ipcRenderer.on('menu-load-project', listener)
- return () => ipcRenderer.removeListener('menu-load-project', listener)
- },
- onMenuSaveProject: (callback: () => void) => {
- const listener = () => callback()
- ipcRenderer.on('menu-save-project', listener)
- return () => ipcRenderer.removeListener('menu-save-project', listener)
- },
- onMenuSaveProjectAs: (callback: () => void) => {
- const listener = () => callback()
- ipcRenderer.on('menu-save-project-as', listener)
- return () => ipcRenderer.removeListener('menu-save-project-as', listener)
- },
- getPlatform: () => {
- return ipcRenderer.invoke('get-platform')
- },
- revealInFolder: (filePath: string) => {
- return ipcRenderer.invoke('reveal-in-folder', filePath)
- },
- openRecordingsFolder: () => {
- return ipcRenderer.invoke('open-recordings-folder')
- },
- getRecordingsDirectory: () => {
- return ipcRenderer.invoke('get-recordings-directory')
- },
- chooseRecordingsDirectory: () => {
- return ipcRenderer.invoke('choose-recordings-directory')
- },
- getShortcuts: () => {
- return ipcRenderer.invoke('get-shortcuts')
- },
- saveShortcuts: (shortcuts: unknown) => {
- return ipcRenderer.invoke('save-shortcuts', shortcuts)
- },
- setHasUnsavedChanges: (hasChanges: boolean) => {
- ipcRenderer.send('set-has-unsaved-changes', hasChanges)
- },
- onRequestSaveBeforeClose: (callback: () => Promise<void>) => {
- const listener = async () => {
- await callback()
- ipcRenderer.send('save-before-close-done')
- }
- ipcRenderer.on('request-save-before-close', listener)
- return () => ipcRenderer.removeListener('request-save-before-close', listener)
- },
- isWgcAvailable: () => ipcRenderer.invoke('is-wgc-available'),
- muxWgcRecording: () => ipcRenderer.invoke('mux-wgc-recording'),
- // Cursor visibility control for cursor-free browser capture fallback
- hideOsCursor: () => ipcRenderer.invoke('hide-cursor'),
- // Countdown timer before recording
- getCountdownDelay: () => ipcRenderer.invoke('get-countdown-delay'),
- setCountdownDelay: (delay: number) => ipcRenderer.invoke('set-countdown-delay', delay),
- startCountdown: (seconds: number) => ipcRenderer.invoke('start-countdown', seconds),
- cancelCountdown: () => ipcRenderer.invoke('cancel-countdown'),
- onCountdownTick: (callback: (seconds: number) => void) => {
- const listener = (_event: Electron.IpcRendererEvent, seconds: number) => callback(seconds)
- ipcRenderer.on('countdown-tick', listener)
- return () => ipcRenderer.removeListener('countdown-tick', listener)
- },
-})
+import { contextBridge, ipcRenderer } from "electron";
+contextBridge.exposeInMainWorld("electronAPI", {
+ hudOverlayHide: () => {
+ ipcRenderer.send("hud-overlay-hide");
+ },
+ hudOverlayClose: () => {
+ ipcRenderer.send("hud-overlay-close");
+ },
+ getHudOverlayCaptureProtection: () => {
+ return ipcRenderer.invoke("get-hud-overlay-capture-protection");
+ },
+ setHudOverlayCaptureProtection: (enabled: boolean) => {
+ return ipcRenderer.invoke("set-hud-overlay-capture-protection", enabled);
+ },
+ getAssetBasePath: async () => {
- // ask main process for the correct base path (production vs dev)
+ return await ipcRenderer.invoke("get-asset-base-path");
+ },
+ readLocalFile: (filePath: string) => {
+ return ipcRenderer.invoke("read-local-file", filePath);
+ },
+ getSources: async (opts: Electron.SourcesOptions) => {
+ return await ipcRenderer.invoke("get-sources", opts);
+ },
+ switchToEditor: () => {
+ return ipcRenderer.invoke("switch-to-editor");
+ },
+ openSourceSelector: () => {
+ return ipcRenderer.invoke("open-source-selector");
+ },
+ selectSource: (source: any) => {
+ return ipcRenderer.invoke("select-source", source);
+ },
+ getSelectedSource: () => {
+ return ipcRenderer.invoke("get-selected-source");
+ },
+ startNativeScreenRecording: (
+ source: any,
+ options?: {
+ capturesSystemAudio?: boolean;
+ capturesMicrophone?: boolean;
+ microphoneDeviceId?: string;
+ microphoneLabel?: string;
+ },
+ ) => {
+ return ipcRenderer.invoke("start-native-screen-recording", source, options);
+ },
+ stopNativeScreenRecording: () => {
+ return ipcRenderer.invoke("stop-native-screen-recording");
+ },
+ startFfmpegRecording: (source: any) => {
+ return ipcRenderer.invoke("start-ffmpeg-recording", source);
+ },
+ stopFfmpegRecording: () => {
+ return ipcRenderer.invoke("stop-ffmpeg-recording");
+ },
-
+ storeRecordedVideo: (videoData: ArrayBuffer, fileName: string) => {
+ return ipcRenderer.invoke("store-recorded-video", videoData, fileName);
+ },
-
+ getRecordedVideoPath: () => {
+ return ipcRenderer.invoke("get-recorded-video-path");
+ },
+ setRecordingState: (recording: boolean) => {
+ return ipcRenderer.invoke("set-recording-state", recording);
+ },
+ setCursorScale: (scale: number) => {
+ return ipcRenderer.invoke("set-cursor-scale", scale);
+ },
+ getCursorTelemetry: (videoPath?: string) => {
+ return ipcRenderer.invoke("get-cursor-telemetry", videoPath);
+ },
+ getSystemCursorAssets: () => {
+ return ipcRenderer.invoke("get-system-cursor-assets");
+ },
+ onStopRecordingFromTray: (callback: () => void) => {
+ const listener = () => callback();
+ ipcRenderer.on("stop-recording-from-tray", listener);
+ return () => ipcRenderer.removeListener("stop-recording-from-tray", listener);
+ },
+ onRecordingStateChanged: (
+ callback: (state: { recording: boolean; sourceName: string }) => void,
+ ) => {
+ const listener = (
+ _event: Electron.IpcRendererEvent,
+ payload: { recording: boolean; sourceName: string },
+ ) => callback(payload);
+ ipcRenderer.on("recording-state-changed", listener);
+ return () => ipcRenderer.removeListener("recording-state-changed", listener);
+ },
+ onRecordingInterrupted: (callback: (state: { reason: string; message: string }) => void) => {
+ const listener = (
+ _event: Electron.IpcRendererEvent,
+ payload: { reason: string; message: string },
+ ) => callback(payload);
+ ipcRenderer.on("recording-interrupted", listener);
+ return () => ipcRenderer.removeListener("recording-interrupted", listener);
+ },
+ onCursorStateChanged: (
+ callback: (state: { cursorType: CursorTelemetryPoint["cursorType"] }) => void,
+ ) => {
+ const listener = (
+ _event: Electron.IpcRendererEvent,
+ payload: { cursorType: CursorTelemetryPoint["cursorType"] },
+ ) => callback(payload);
+ ipcRenderer.on("cursor-state-changed", listener);
+ return () => ipcRenderer.removeListener("cursor-state-changed", listener);
+ },
+ openExternalUrl: (url: string) => {
+ return ipcRenderer.invoke("open-external-url", url);
+ },
+ getAccessibilityPermissionStatus: () => {
+ return ipcRenderer.invoke("get-accessibility-permission-status");
+ },
+ requestAccessibilityPermission: () => {
+ return ipcRenderer.invoke("request-accessibility-permission");
+ },
+ getScreenRecordingPermissionStatus: () => {
+ return ipcRenderer.invoke("get-screen-recording-permission-status");
+ },
+ openScreenRecordingPreferences: () => {
+ return ipcRenderer.invoke("open-screen-recording-preferences");
+ },
+ openAccessibilityPreferences: () => {
+ return ipcRenderer.invoke("open-accessibility-preferences");
+ },
+ saveExportedVideo: (videoData: ArrayBuffer, fileName: string) => {
+ return ipcRenderer.invoke("save-exported-video", videoData, fileName);
+ },
+ openVideoFilePicker: () => {
+ return ipcRenderer.invoke("open-video-file-picker");
+ },
++ openAudioFilePicker: () => {
++ return ipcRenderer.invoke("open-audio-file-picker");
++ },
+ setCurrentVideoPath: (path: string) => {
+ return ipcRenderer.invoke("set-current-video-path", path);
+ },
+ getCurrentVideoPath: () => {
+ return ipcRenderer.invoke("get-current-video-path");
+ },
+ clearCurrentVideoPath: () => {
+ return ipcRenderer.invoke("clear-current-video-path");
+ },
+ saveProjectFile: (projectData: unknown, suggestedName?: string, existingProjectPath?: string) => {
+ return ipcRenderer.invoke("save-project-file", projectData, suggestedName, existingProjectPath);
+ },
+ loadProjectFile: () => {
+ return ipcRenderer.invoke("load-project-file");
+ },
+ loadCurrentProjectFile: () => {
+ return ipcRenderer.invoke("load-current-project-file");
+ },
+ onMenuLoadProject: (callback: () => void) => {
+ const listener = () => callback();
+ ipcRenderer.on("menu-load-project", listener);
+ return () => ipcRenderer.removeListener("menu-load-project", listener);
+ },
+ onMenuSaveProject: (callback: () => void) => {
+ const listener = () => callback();
+ ipcRenderer.on("menu-save-project", listener);
+ return () => ipcRenderer.removeListener("menu-save-project", listener);
+ },
+ onMenuSaveProjectAs: (callback: () => void) => {
+ const listener = () => callback();
+ ipcRenderer.on("menu-save-project-as", listener);
+ return () => ipcRenderer.removeListener("menu-save-project-as", listener);
+ },
+ getPlatform: () => {
+ return ipcRenderer.invoke("get-platform");
+ },
+ revealInFolder: (filePath: string) => {
+ return ipcRenderer.invoke("reveal-in-folder", filePath);
+ },
+ openRecordingsFolder: () => {
+ return ipcRenderer.invoke("open-recordings-folder");
+ },
+ getRecordingsDirectory: () => {
+ return ipcRenderer.invoke("get-recordings-directory");
+ },
+ chooseRecordingsDirectory: () => {
+ return ipcRenderer.invoke("choose-recordings-directory");
+ },
+ getShortcuts: () => {
+ return ipcRenderer.invoke("get-shortcuts");
+ },
+ saveShortcuts: (shortcuts: unknown) => {
+ return ipcRenderer.invoke("save-shortcuts", shortcuts);
+ },
+ setHasUnsavedChanges: (hasChanges: boolean) => {
+ ipcRenderer.send("set-has-unsaved-changes", hasChanges);
+ },
+ onRequestSaveBeforeClose: (callback: () => Promise<void>) => {
+ const listener = async () => {
+ await callback();
+ ipcRenderer.send("save-before-close-done");
+ };
+ ipcRenderer.on("request-save-before-close", listener);
+ return () => ipcRenderer.removeListener("request-save-before-close", listener);
+ },
+ isWgcAvailable: () => ipcRenderer.invoke("is-wgc-available"),
+ muxWgcRecording: () => ipcRenderer.invoke("mux-wgc-recording"),
- // Cursor visibility control for cursor-free browser capture fallback
+ hideOsCursor: () => ipcRenderer.invoke("hide-cursor"),
++ getCountdownDelay: () => ipcRenderer.invoke("get-countdown-delay"),
++ setCountdownDelay: (delay: number) => ipcRenderer.invoke("set-countdown-delay", delay),
++ startCountdown: (seconds: number) => ipcRenderer.invoke("start-countdown", seconds),
++ cancelCountdown: () => ipcRenderer.invoke("cancel-countdown"),
++ onCountdownTick: (callback: (seconds: number) => void) => {
++ const listener = (_event: Electron.IpcRendererEvent, seconds: number) => callback(seconds);
++ ipcRenderer.on("countdown-tick", listener);
++ return () => ipcRenderer.removeListener("countdown-tick", listener);
++ },
+});
diff --cc electron/windows.ts
index cf52206f,30674666..762f0ae0
--- a/electron/windows.ts
+++ b/electron/windows.ts
@@@ -1,247 -1,247 +1,332 @@@
-import { BrowserWindow, ipcMain } from 'electron'
-import { createRequire } from 'node:module'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url))
-const nodeRequire = createRequire(import.meta.url)
-
-const APP_ROOT = path.join(__dirname, '..')
-const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
-const RENDERER_DIST = path.join(APP_ROOT, 'dist')
-const WINDOW_ICON_PATH = path.join(process.env.VITE_PUBLIC || RENDERER_DIST, 'app-icons', 'recordly-512.png')
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { app, BrowserWindow, ipcMain } from "electron";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const nodeRequire = createRequire(import.meta.url);
+
+const APP_ROOT = path.join(__dirname, "..");
+const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
+const RENDERER_DIST = path.join(APP_ROOT, "dist");
+const WINDOW_ICON_PATH = path.join(
+ process.env.VITE_PUBLIC || RENDERER_DIST,
+ "app-icons",
+ "recordly-512.png",
+);
let hudOverlayWindow: BrowserWindow | null = null;
+let hudOverlayHiddenFromCapture = true;
+let hudOverlayCaptureProtectionLoaded = false;
+ let countdownWindow: BrowserWindow | null = null;
+const HUD_OVERLAY_SETTINGS_FILE = path.join(app.getPath("userData"), "hud-overlay-settings.json");
+
+function isHudOverlayCaptureProtectionSupported(): boolean {
+ return process.platform !== "linux";
+}
+
+function loadHudOverlayCaptureProtectionSetting(): boolean {
+ if (hudOverlayCaptureProtectionLoaded) {
+ return hudOverlayHiddenFromCapture;
+ }
+
+ hudOverlayCaptureProtectionLoaded = true;
+
+ try {
+ if (!fs.existsSync(HUD_OVERLAY_SETTINGS_FILE)) {
+ return hudOverlayHiddenFromCapture;
+ }
+
+ const raw = fs.readFileSync(HUD_OVERLAY_SETTINGS_FILE, "utf-8");
+ const parsed = JSON.parse(raw) as { hiddenFromCapture?: unknown };
+ if (typeof parsed.hiddenFromCapture === "boolean") {
+ hudOverlayHiddenFromCapture = parsed.hiddenFromCapture;
+ }
+ } catch {
+ // Ignore settings read failures and fall back to defaults.
+ }
+
+ return hudOverlayHiddenFromCapture;
+}
+
+function persistHudOverlayCaptureProtectionSetting(enabled: boolean): void {
+ try {
+ fs.writeFileSync(
+ HUD_OVERLAY_SETTINGS_FILE,
+ JSON.stringify({ hiddenFromCapture: enabled }, null, 2),
+ "utf-8",
+ );
+ } catch {
+ // Ignore settings write failures and keep runtime state working.
+ }
+}
+
function getScreen() {
- return nodeRequire('electron').screen as typeof import('electron').screen
+ return nodeRequire("electron").screen as typeof import("electron").screen;
}
-ipcMain.on('hud-overlay-hide', () => {
- if (hudOverlayWindow && !hudOverlayWindow.isDestroyed()) {
- hudOverlayWindow.minimize();
- }
+ipcMain.on("hud-overlay-hide", () => {
+ if (hudOverlayWindow && !hudOverlayWindow.isDestroyed()) {
+ hudOverlayWindow.minimize();
+ }
+});
+
+ipcMain.handle("get-hud-overlay-capture-protection", () => {
+ const enabled = loadHudOverlayCaptureProtectionSetting();
+
+ return {
+ success: true,
+ enabled,
+ };
+});
+
+ipcMain.handle("set-hud-overlay-capture-protection", (_event, enabled: boolean) => {
+ loadHudOverlayCaptureProtectionSetting();
+ hudOverlayHiddenFromCapture = Boolean(enabled);
+ persistHudOverlayCaptureProtectionSetting(hudOverlayHiddenFromCapture);
+
+ if (
+ isHudOverlayCaptureProtectionSupported() &&
+ hudOverlayWindow &&
+ !hudOverlayWindow.isDestroyed()
+ ) {
+ hudOverlayWindow.setContentProtection(hudOverlayHiddenFromCapture);
+ }
+
+ return {
+ success: true,
+ enabled: hudOverlayHiddenFromCapture,
+ };
});
export function createHudOverlayWindow(): BrowserWindow {
- const primaryDisplay = getScreen().getPrimaryDisplay();
- const { workArea } = primaryDisplay;
-
-
- const windowWidth = 660;
- const windowHeight = 170;
-
- const x = Math.floor(workArea.x + (workArea.width - windowWidth) / 2);
- const y = Math.floor(workArea.y + workArea.height - windowHeight - 5);
-
- const win = new BrowserWindow({
- width: windowWidth,
- height: windowHeight,
- minWidth: 660,
- maxWidth: 660,
- minHeight: 170,
- maxHeight: 170,
- x: x,
- y: y,
- frame: false,
- transparent: true,
- resizable: false,
- alwaysOnTop: true,
- skipTaskbar: true,
- hasShadow: false,
- show: false,
- webPreferences: {
- preload: path.join(__dirname, 'preload.mjs'),
- nodeIntegration: false,
- contextIsolation: true,
- backgroundThrottling: false,
- },
- })
-
-
- win.webContents.on('did-finish-load', () => {
- win?.webContents.send('main-process-message', (new Date).toLocaleString())
- setTimeout(() => {
- if (!win.isDestroyed()) {
- win.show()
- }
- }, 100)
- })
-
- hudOverlayWindow = win;
-
- win.on('closed', () => {
- if (hudOverlayWindow === win) {
- hudOverlayWindow = null;
- }
- });
-
-
- if (VITE_DEV_SERVER_URL) {
- win.loadURL(VITE_DEV_SERVER_URL + '?windowType=hud-overlay')
- } else {
- win.loadFile(path.join(RENDERER_DIST, 'index.html'), {
- query: { windowType: 'hud-overlay' }
- })
- }
-
- return win
+ loadHudOverlayCaptureProtectionSetting();
+
+ const primaryDisplay = getScreen().getPrimaryDisplay();
+ const { workArea } = primaryDisplay;
+
+ const windowWidth = 660;
+ const windowHeight = 170;
+
+ const x = Math.floor(workArea.x + (workArea.width - windowWidth) / 2);
+ const y = Math.floor(workArea.y + workArea.height - windowHeight - 5);
+
+ const win = new BrowserWindow({
+ width: windowWidth,
+ height: windowHeight,
+ minWidth: windowWidth,
+ maxWidth: windowWidth,
+ minHeight: windowHeight,
+ maxHeight: windowHeight,
+ x: x,
+ y: y,
+ frame: false,
+ transparent: true,
+ resizable: false,
+ alwaysOnTop: true,
+ skipTaskbar: true,
+ hasShadow: false,
++ show: false,
+ webPreferences: {
+ preload: path.join(__dirname, "preload.mjs"),
+ nodeIntegration: false,
+ contextIsolation: true,
+ backgroundThrottling: false,
+ },
+ });
+
+ if (isHudOverlayCaptureProtectionSupported()) {
+ win.setContentProtection(hudOverlayHiddenFromCapture);
+ }
+
+ win.webContents.on("did-finish-load", () => {
+ win?.webContents.send("main-process-message", new Date().toLocaleString());
++ setTimeout(() => {
++ if (!win.isDestroyed()) {
++ win.show();
++ }
++ }, 100);
+ });
+
+ hudOverlayWindow = win;
+
+ win.on("closed", () => {
+ if (hudOverlayWindow === win) {
+ hudOverlayWindow = null;
+ }
+ });
+
+ if (VITE_DEV_SERVER_URL) {
+ win.loadURL(VITE_DEV_SERVER_URL + "?windowType=hud-overlay");
+ } else {
+ win.loadFile(path.join(RENDERER_DIST, "index.html"), {
+ query: { windowType: "hud-overlay" },
+ });
+ }
+
+ return win;
}
export function createEditorWindow(): BrowserWindow {
- const isMac = process.platform === 'darwin';
-
- const win = new BrowserWindow({
- width: 1200,
- height: 800,
- minWidth: 800,
- minHeight: 600,
- ...(process.platform !== 'darwin' && {
- icon: WINDOW_ICON_PATH,
- }),
- ...(isMac && {
- titleBarStyle: 'hiddenInset',
- trafficLightPosition: { x: 12, y: 12 },
- }),
- transparent: false,
- resizable: true,
- alwaysOnTop: false,
- skipTaskbar: false,
- title: 'Recordly',
- show: false,
- backgroundColor: '#000000',
- webPreferences: {
- preload: path.join(__dirname, 'preload.mjs'),
- nodeIntegration: false,
- contextIsolation: true,
- webSecurity: false,
- backgroundThrottling: false,
- },
- })
-
- win.once('ready-to-show', () => {
- win.show()
- win.maximize()
- })
-
- win.webContents.on('did-finish-load', () => {
- win?.webContents.send('main-process-message', (new Date).toLocaleString())
- })
-
- if (VITE_DEV_SERVER_URL) {
- win.loadURL(VITE_DEV_SERVER_URL + '?windowType=editor')
- } else {
- win.loadFile(path.join(RENDERER_DIST, 'index.html'), {
- query: { windowType: 'editor' }
- })
- }
-
- return win
+ const isMac = process.platform === "darwin";
+
+ const win = new BrowserWindow({
+ width: 1200,
+ height: 800,
+ minWidth: 800,
+ minHeight: 600,
+ ...(process.platform !== "darwin" && {
+ icon: WINDOW_ICON_PATH,
+ }),
+ ...(isMac && {
+ titleBarStyle: "hiddenInset",
+ trafficLightPosition: { x: 12, y: 12 },
+ }),
+ transparent: false,
+ resizable: true,
+ alwaysOnTop: false,
+ skipTaskbar: false,
+ title: "Recordly",
++ show: false,
+ backgroundColor: "#000000",
+ webPreferences: {
+ preload: path.join(__dirname, "preload.mjs"),
+ nodeIntegration: false,
+ contextIsolation: true,
+ webSecurity: false,
+ backgroundThrottling: false,
+ },
+ });
+
- // Maximize the window by default
- win.maximize();
++ win.once("ready-to-show", () => {
++ win.show();
++ win.maximize();
++ });
+
+ win.webContents.on("did-finish-load", () => {
+ win?.webContents.send("main-process-message", new Date().toLocaleString());
+ });
+
+ if (VITE_DEV_SERVER_URL) {
+ win.loadURL(VITE_DEV_SERVER_URL + "?windowType=editor");
+ } else {
+ win.loadFile(path.join(RENDERER_DIST, "index.html"), {
+ query: { windowType: "editor" },
+ });
+ }
+
+ return win;
}
export function createSourceSelectorWindow(): BrowserWindow {
- const { width, height } = getScreen().getPrimaryDisplay().workAreaSize
-
- const win = new BrowserWindow({
- width: 620,
- height: 420,
- minHeight: 350,
- maxHeight: 500,
- x: Math.round((width - 620) / 2),
- y: Math.round((height - 420) / 2),
- frame: false,
- resizable: false,
- alwaysOnTop: true,
- transparent: true,
- show: false,
- ...(process.platform !== 'darwin' && {
- icon: WINDOW_ICON_PATH,
- }),
- backgroundColor: '#00000000',
- webPreferences: {
- preload: path.join(__dirname, 'preload.mjs'),
- nodeIntegration: false,
- contextIsolation: true,
- },
- })
-
- win.webContents.on('did-finish-load', () => {
- setTimeout(() => {
- if (!win.isDestroyed()) {
- win.show()
- }
- }, 100)
- })
-
- if (VITE_DEV_SERVER_URL) {
- win.loadURL(VITE_DEV_SERVER_URL + '?windowType=source-selector')
- } else {
- win.loadFile(path.join(RENDERER_DIST, 'index.html'), {
- query: { windowType: 'source-selector' }
- })
- }
-
- return win
+ const { width, height } = getScreen().getPrimaryDisplay().workAreaSize;
+
+ const win = new BrowserWindow({
+ width: 620,
+ height: 420,
+ minHeight: 350,
+ maxHeight: 500,
+ x: Math.round((width - 620) / 2),
+ y: Math.round((height - 420) / 2),
+ frame: false,
+ resizable: false,
+ alwaysOnTop: true,
+ transparent: true,
++ show: false,
+ ...(process.platform !== "darwin" && {
+ icon: WINDOW_ICON_PATH,
+ }),
+ backgroundColor: "#00000000",
+ webPreferences: {
+ preload: path.join(__dirname, "preload.mjs"),
+ nodeIntegration: false,
+ contextIsolation: true,
+ },
+ });
+
++ win.webContents.on("did-finish-load", () => {
++ setTimeout(() => {
++ if (!win.isDestroyed()) {
++ win.show();
++ }
++ }, 100);
++ });
++
+ if (VITE_DEV_SERVER_URL) {
+ win.loadURL(VITE_DEV_SERVER_URL + "?windowType=source-selector");
+ } else {
+ win.loadFile(path.join(RENDERER_DIST, "index.html"), {
+ query: { windowType: "source-selector" },
+ });
+ }
+
+ return win;
}
+
+ export function createCountdownWindow(): BrowserWindow {
- const primaryDisplay = getScreen().getPrimaryDisplay();
- const { width, height } = primaryDisplay.workAreaSize;
-
- const windowSize = 200;
- const x = Math.floor((width - windowSize) / 2);
- const y = Math.floor((height - windowSize) / 2);
-
- const win = new BrowserWindow({
- width: windowSize,
- height: windowSize,
- x: x,
- y: y,
- frame: false,
- transparent: true,
- resizable: false,
- alwaysOnTop: true,
- skipTaskbar: true,
- hasShadow: false,
- focusable: true,
- webPreferences: {
- preload: path.join(__dirname, 'preload.mjs'),
- nodeIntegration: false,
- contextIsolation: true,
- },
- })
-
- countdownWindow = win;
-
- // Show on all workspaces/spaces so it follows the user
- win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
-
- win.on('closed', () => {
- if (countdownWindow === win) {
- countdownWindow = null;
- }
- });
-
- if (VITE_DEV_SERVER_URL) {
- win.loadURL(VITE_DEV_SERVER_URL + '?windowType=countdown')
- } else {
- win.loadFile(path.join(RENDERER_DIST, 'index.html'), {
- query: { windowType: 'countdown' }
- })
- }
-
- return win
++ const primaryDisplay = getScreen().getPrimaryDisplay();
++ const { width, height } = primaryDisplay.workAreaSize;
++
++ const windowSize = 200;
++ const x = Math.floor((width - windowSize) / 2);
++ const y = Math.floor((height - windowSize) / 2);
++
++ const win = new BrowserWindow({
++ width: windowSize,
++ height: windowSize,
++ x: x,
++ y: y,
++ frame: false,
++ transparent: true,
++ resizable: false,
++ alwaysOnTop: true,
++ skipTaskbar: true,
++ hasShadow: false,
++ focusable: true,
++ show: false,
++ webPreferences: {
++ preload: path.join(__dirname, "preload.mjs"),
++ nodeIntegration: false,
++ contextIsolation: true,
++ },
++ });
++
++ countdownWindow = win;
++
++ win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
++
++ win.webContents.on("did-finish-load", () => {
++ if (!win.isDestroyed()) {
++ win.show();
++ }
++ });
++
++ win.on("closed", () => {
++ if (countdownWindow === win) {
++ countdownWindow = null;
++ }
++ });
++
++ if (VITE_DEV_SERVER_URL) {
++ win.loadURL(VITE_DEV_SERVER_URL + "?windowType=countdown");
++ } else {
++ win.loadFile(path.join(RENDERER_DIST, "index.html"), {
++ query: { windowType: "countdown" },
++ });
++ }
++
++ return win;
+ }
+
+ export function getCountdownWindow(): BrowserWindow | null {
- return countdownWindow;
++ return countdownWindow;
+ }
+
+ export function closeCountdownWindow(): void {
- if (countdownWindow && !countdownWindow.isDestroyed()) {
- countdownWindow.close();
- countdownWindow = null;
- }
++ if (countdownWindow && !countdownWindow.isDestroyed()) {
++ countdownWindow.close();
++ countdownWindow = null;
++ }
+ }
-
diff --cc src/App.tsx
index 2a471f1f,2418ce53..67c5df21
--- a/src/App.tsx
+++ b/src/App.tsx
@@@ -1,63 -1,66 +1,69 @@@
--import { useEffect, useState } from "react";
-import { CountdownOverlay } from "./components/countdown/CountdownOverlay";
--import { LaunchWindow } from "./components/launch/LaunchWindow";
--import { SourceSelector } from "./components/launch/SourceSelector";
--import VideoEditor from "./components/video-editor/VideoEditor";
--import { loadAllCustomFonts } from "./lib/customFonts";
--import { ShortcutsProvider } from "./contexts/ShortcutsContext";
--import { ShortcutsConfigDialog } from "./components/video-editor/ShortcutsConfigDialog";
--import { useI18n } from "./contexts/I18nContext";
--
--export default function App() {
-- const [windowType, setWindowType] = useState('');
-- const { locale, t } = useI18n();
--
-- useEffect(() => {
-- const params = new URLSearchParams(window.location.search);
-- const type = params.get('windowType') || '';
-- setWindowType(type);
--
- if (type === 'hud-overlay' || type === 'source-selector') {
- if (type === 'hud-overlay' || type === 'source-selector' || type === 'countdown') {
-- document.body.style.background = 'transparent';
-- document.documentElement.style.background = 'transparent';
-- document.getElementById('root')?.style.setProperty('background', 'transparent');
-- }
--
-- // Load custom fonts on app initialization
-- loadAllCustomFonts().catch((error) => {
-- console.error('Failed to load custom fonts:', error);
-- });
-- }, []);
--
-- useEffect(() => {
-- document.title = windowType === 'editor'
-- ? t('app.editorTitle', 'Recordly Editor')
-- : t('app.name', 'Recordly');
-- }, [windowType, locale, t]);
--
-- switch (windowType) {
-- case 'hud-overlay':
-- return <LaunchWindow />;
-- case 'source-selector':
-- return <SourceSelector />;
- case 'countdown':
- return <CountdownOverlay />;
-- case 'editor':
-- return (
-- <ShortcutsProvider>
-- <VideoEditor />
-- <ShortcutsConfigDialog />
-- </ShortcutsProvider>
-- );
-- default:
-- return (
-- <div className="flex h-full w-full items-center justify-center bg-slate-950 text-white">
-- <div className="flex items-center gap-4 rounded-2xl border border-white/10 bg-white/5 px-6 py-5 shadow-2xl shadow-black/30 backdrop-blur-xl">
-- <img src="/app-icons/recordly-128.png" alt={t('app.name', 'Recordly')} className="h-12 w-12 rounded-xl" />
-- <div>
-- <h1 className="text-xl font-semibold tracking-tight">{t('app.name', 'Recordly')}</h1>
-- <p className="text-sm text-white/65">{t('app.subtitle', 'Screen recording and editing')}</p>
-- </div>
-- </div>
-- </div>
-- );
-- }
--}
--
++import { useEffect, useState } from "react";
++import { CountdownOverlay } from "./components/countdown/CountdownOverlay";
++import { LaunchWindow } from "./components/launch/LaunchWindow";
++import { SourceSelector } from "./components/launch/SourceSelector";
++import { ShortcutsConfigDialog } from "./components/video-editor/ShortcutsConfigDialog";
++import VideoEditor from "./components/video-editor/VideoEditor";
++import { useI18n } from "./contexts/I18nContext";
++import { ShortcutsProvider } from "./contexts/ShortcutsContext";
++import { loadAllCustomFonts } from "./lib/customFonts";
++
++export default function App() {
++ const [windowType, setWindowType] = useState("");
++ const { locale, t } = useI18n();
++
++ useEffect(() => {
++ const params = new URLSearchParams(window.location.search);
++ const type = params.get("windowType") || "";
++ setWindowType(type);
++
++ if (type === "hud-overlay" || type === "source-selector" || type === "countdown") {
++ document.body.style.background = "transparent";
++ document.documentElement.style.background = "transparent";
++ document.getElementById("root")?.style.setProperty("background", "transparent");
++ }
++
++ loadAllCustomFonts().catch((error) => {
++ console.error("Failed to load custom fonts:", error);
++ });
++ }, []);
++
++ useEffect(() => {
++ document.title =
++ windowType === "editor" ? t("app.editorTitle", "Recordly Editor") : t("app.name", "Recordly");
++ }, [windowType, locale, t]);
++
++ switch (windowType) {
++ case "hud-overlay":
++ return <LaunchWindow />;
++ case "source-selector":
++ return <SourceSelector />;
++ case "countdown":
++ return <CountdownOverlay />;
++ case "editor":
++ return (
++ <ShortcutsProvider>
++ <VideoEditor />
++ <ShortcutsConfigDialog />
++ </ShortcutsProvider>
++ );
++ default:
++ return (
++ <div className="flex h-full w-full items-center justify-center bg-slate-950 text-white">
++ <div className="flex items-center gap-4 rounded-2xl border border-white/10 bg-white/5 px-6 py-5 shadow-2xl shadow-black/30 backdrop-blur-xl">
++ <img
++ src="/app-icons/recordly-128.png"
++ alt={t("app.name", "Recordly")}
++ className="h-12 w-12 rounded-xl"
++ />
++ <div>
++ <h1 className="text-xl font-semibold tracking-tight">{t("app.name", "Recordly")}</h1>
++ <p className="text-sm text-white/65">
++ {t("app.subtitle", "Screen recording and editing")}
++ </p>
++ </div>
++ </div>
++ </div>
++ );
++ }
++}
diff --cc src/components/launch/LaunchWindow.tsx
index 3c4e307c,06c48067..0ee828af
--- a/src/components/launch/LaunchWindow.tsx
+++ b/src/components/launch/LaunchWindow.tsx
@@@ -1,4 -1,3 +1,4 @@@
- import { Eye, EyeOff, Languages } from "lucide-react";
++import { Eye, EyeOff, Languages, Timer } from "lucide-react";
import { useEffect, useState } from "react";
import { BsRecordCircle } from "react-icons/bs";
import { FaRegStopCircle } from "react-icons/fa";
@@@ -25,444 -22,369 +25,479 @@@ import
import styles from "./LaunchWindow.module.css";
export function LaunchWindow() {
- const { locale, setLocale } = useI18n();
- const t = useScopedT('launch');
-
- const LOCALE_LABELS: Record<string, string> = { en: "EN", es: "ES", "zh-CN": "中文" };
- const {
- recording,
- countdownActive,
- toggleRecording,
- microphoneEnabled,
- setMicrophoneEnabled,
- microphoneDeviceId,
- setMicrophoneDeviceId,
- systemAudioEnabled,
- setSystemAudioEnabled,
- countdownDelay,
- setCountdownDelay,
- } = useScreenRecorder();
- const [recordingStart, setRecordingStart] = useState<number | null>(null);
- const [elapsed, setElapsed] = useState(0);
- const showMicControls = microphoneEnabled && !recording;
- const { devices, selectedDeviceId, setSelectedDeviceId } = useMicrophoneDevices(microphoneEnabled);
- const { level } = useAudioLevelMeter({
- enabled: showMicControls,
- deviceId: microphoneDeviceId,
- });
-
- useEffect(() => {
- if (selectedDeviceId && selectedDeviceId !== "default") {
- setMicrophoneDeviceId(selectedDeviceId);
- }
- }, [selectedDeviceId, setMicrophoneDeviceId]);
-
- useEffect(() => {
- let timer: NodeJS.Timeout | null = null;
- if (recording) {
- if (!recordingStart) setRecordingStart(Date.now());
- timer = setInterval(() => {
- if (recordingStart) {
- setElapsed(Math.floor((Date.now() - recordingStart) / 1000));
- }
- }, 1000);
- } else {
- setRecordingStart(null);
- setElapsed(0);
- if (timer) clearInterval(timer);
- }
- return () => {
- if (timer) clearInterval(timer);
- };
- }, [recording, recordingStart]);
-
- const formatTime = (seconds: number) => {
- const m = Math.floor(seconds / 60).toString().padStart(2, "0");
- const s = (seconds % 60).toString().padStart(2, "0");
- return `${m}:${s}`;
- };
-
- const [selectedSource, setSelectedSource] = useState("Screen");
- const [hasSelectedSource, setHasSelectedSource] = useState(false);
- const [recordingsDirectory, setRecordingsDirectory] = useState<string | null>(null);
-
- useEffect(() => {
- const checkSelectedSource = async () => {
- if (window.electronAPI) {
- const source = await window.electronAPI.getSelectedSource();
- if (source) {
- setSelectedSource(source.name);
- setHasSelectedSource(true);
- } else {
- setSelectedSource("Screen");
- setHasSelectedSource(false);
- }
- }
- };
-
- void checkSelectedSource();
- const interval = setInterval(checkSelectedSource, 500);
- return () => clearInterval(interval);
- }, []);
-
- const openSourceSelector = () => {
- window.electronAPI?.openSourceSelector();
- };
-
- const openVideoFile = async () => {
- const result = await window.electronAPI.openVideoFilePicker();
- if (result.canceled) {
- return;
- }
-
- if (result.success && result.path) {
- await window.electronAPI.setCurrentVideoPath(result.path);
- await window.electronAPI.switchToEditor();
- }
- };
-
- const openProjectFile = async () => {
- const result = await window.electronAPI.loadProjectFile();
- if (result.canceled || !result.success) {
- return;
- }
- await window.electronAPI.switchToEditor();
- };
-
- const sendHudOverlayHide = () => {
- window.electronAPI?.hudOverlayHide?.();
- };
-
- const sendHudOverlayClose = () => {
- window.electronAPI?.hudOverlayClose?.();
- };
-
- const chooseRecordingsDirectory = async () => {
- const result = await window.electronAPI.chooseRecordingsDirectory();
- if (result.canceled) {
- return;
- }
- if (result.success && result.path) {
- setRecordingsDirectory(result.path);
- }
- };
-
- useEffect(() => {
- const loadRecordingsDirectory = async () => {
- const result = await window.electronAPI.getRecordingsDirectory();
- if (result.success) {
- setRecordingsDirectory(result.path);
- }
- };
-
- void loadRecordingsDirectory();
- }, []);
-
- const recordingsDirectoryName = recordingsDirectory
- ? recordingsDirectory.split(/[\\/]/).filter(Boolean).pop() || recordingsDirectory
- : "recordings";
- const dividerClass = "mx-1 h-5 w-px shrink-0 bg-white/35";
-
- const toggleMicrophone = () => {
- if (!recording) {
- setMicrophoneEnabled(!microphoneEnabled);
- }
- };
-
- return (
- <div className="w-full h-full flex items-end justify-center bg-transparent overflow-hidden">
- <div className={`flex flex-col items-center gap-2 mx-auto ${styles.electronDrag}`}>
- {showMicControls && (
- <div
- className={`flex items-center gap-2 rounded-full border border-white/15 bg-[rgba(18,18,26,0.92)] px-3 py-2 shadow-xl backdrop-blur-xl ${styles.electronNoDrag}`}
- >
- <select
- value={microphoneDeviceId || selectedDeviceId}
- onChange={(event) => {
- setSelectedDeviceId(event.target.value);
- setMicrophoneDeviceId(event.target.value);
- }}
- className={`max-w-[230px] rounded-full border border-white/15 bg-[#131722] px-3 py-1 text-xs text-slate-100 outline-none ${styles.micSelect}`}
- >
- {devices.map((device) => (
- <option key={device.deviceId} value={device.deviceId}>
- {device.label}
- </option>
- ))}
- </select>
- <AudioLevelMeter level={level} className="w-24" />
- </div>
- )}
-
- <div
- className={`w-full mx-auto flex items-center gap-1.5 px-3 py-2 ${styles.electronDrag} ${styles.hudBar}`}
- style={{
- borderRadius: 9999,
- background: "linear-gradient(135deg, rgba(28,28,36,0.97) 0%, rgba(18,18,26,0.96) 100%)",
- backdropFilter: "blur(16px) saturate(140%)",
- WebkitBackdropFilter: "blur(16px) saturate(140%)",
- border: "1px solid rgba(80,80,120,0.25)",
- minHeight: 48,
- }}
- >
- <div className={`flex items-center px-1 ${styles.electronDrag}`}>
- <RxDragHandleDots2 size={16} className="text-white/35" />
- </div>
-
- <Button
- variant="link"
- size="sm"
- className={`gap-1 text-white/80 bg-transparent hover:bg-transparent px-0 text-xs ${styles.electronNoDrag}`}
- onClick={openSourceSelector}
- disabled={recording}
- title={selectedSource}
- >
- <MdMonitor size={14} className="text-white/80" />
- <ContentClamp truncateLength={6}>{selectedSource}</ContentClamp>
- </Button>
-
- <div className={dividerClass} />
-
- <div className={`flex items-center gap-1 ${styles.electronNoDrag}`}>
- <Button
- variant="link"
- size="icon"
- onClick={() => !recording && setSystemAudioEnabled(!systemAudioEnabled)}
- disabled={recording}
- title={systemAudioEnabled ? t('recording.disableSystemAudio') : t('recording.enableSystemAudio')}
- className="text-white/80 hover:bg-transparent"
- >
- {systemAudioEnabled ? <MdVolumeUp size={16} className="text-[#2563EB]" /> : <MdVolumeOff size={16} className="text-white/35" />}
- </Button>
- <Button
- variant="link"
- size="icon"
- onClick={toggleMicrophone}
- disabled={recording}
- title={microphoneEnabled ? t('recording.disableMicrophone') : t('recording.enableMicrophone')}
- className="text-white/80 hover:bg-transparent"
- >
- {microphoneEnabled ? <MdMic size={16} className="text-[#2563EB]" /> : <MdMicOff size={16} className="text-white/35" />}
- </Button>
- </div>
-
- <div className={dividerClass} />
-
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="link"
- size="sm"
- disabled={recording}
- title={t('recording.countdownDelay')}
- className={`gap-1 text-white/70 hover:bg-transparent px-1 text-xs ${styles.electronNoDrag}`}
- >
- <Timer size={14} />
- <span>{countdownDelay > 0 ? `${countdownDelay}s` : t('recording.noDelay')}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="top"
- align="center"
- className="min-w-[80px] max-h-none overflow-visible bg-[rgba(28,28,36,0.97)] border-white/15 text-white/90 backdrop-blur-xl"
- >
- {[0, 3, 5, 10].map((delay) => (
- <DropdownMenuItem
- key={delay}
- onSelect={() => setCountdownDelay(delay)}
- className={`text-xs cursor-pointer ${
- countdownDelay === delay ? "text-white font-medium" : "text-white/60"
- }`}
- >
- {delay === 0 ? t('recording.noDelay') : `${delay}s`}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
-
- <Button
- variant="link"
- size="sm"
- onClick={hasSelectedSource ? toggleRecording : openSourceSelector}
- disabled={countdownActive || (!hasSelectedSource && !recording)}
- className={`gap-1 text-white bg-transparent hover:bg-transparent px-0 text-xs ${styles.electronNoDrag}`}
- >
- {recording ? (
- <>
- <FaRegStopCircle size={14} className="text-red-400" />
- <span className="text-red-400 font-medium tabular-nums">{formatTime(elapsed)}</span>
- </>
- ) : (
- <>
- <BsRecordCircle size={14} className={hasSelectedSource ? "text-white/85" : "text-white/35"} />
- <span className={hasSelectedSource ? "text-white/80" : "text-white/35"}>{t('recording.record')}</span>
- </>
- )}
- </Button>
-
- <Button
- variant="link"
- size="sm"
- onClick={chooseRecordingsDirectory}
- disabled={recording}
- title={recordingsDirectory ? t('recording.recordingFolder', undefined, { path: recordingsDirectory }) : t('recording.chooseRecordingsFolder')}
- className={`text-white/75 hover:bg-transparent px-1 text-[11px] underline decoration-white/45 underline-offset-2 ${styles.electronNoDrag}`}
- >
- <ContentClamp truncateLength={18}>{t('recording.folderPath', undefined, { name: recordingsDirectoryName })}</ContentClamp>
- </Button>
-
- <div className="ml-auto flex items-center gap-0.5">
- <div className={dividerClass} />
- <Button
- variant="link"
- size="icon"
- onClick={openVideoFile}
- disabled={recording}
- title={t('recording.openVideoFile')}
- className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
- >
- <MdVideoFile size={15} />
- </Button>
- <Button
- variant="link"
- size="icon"
- onClick={openProjectFile}
- disabled={recording}
- title={t('recording.openProject')}
- className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
- >
- <FaFolderOpen size={14} />
- </Button>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="link"
- size="icon"
- title="Language"
- className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
- >
- <Languages size={14} />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="top"
- align="end"
- className="min-w-[90px] bg-[rgba(28,28,36,0.97)] border-white/15 text-white/90 backdrop-blur-xl"
- >
- {SUPPORTED_LOCALES.map((code) => (
- <DropdownMenuItem
- key={code}
- onSelect={() => setLocale(code as AppLocale)}
- className={`text-xs cursor-pointer ${
- locale === code ? "text-white font-medium" : "text-white/60"
- }`}
- >
- {LOCALE_LABELS[code] ?? code}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <div className={dividerClass} />
- <Button
- variant="link"
- size="icon"
- onClick={sendHudOverlayHide}
- title={t('recording.hideHud')}
- className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
- >
- <FiMinus size={16} />
- </Button>
- <Button
- variant="link"
- size="icon"
- onClick={sendHudOverlayClose}
- title={t('recording.closeApp')}
- className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
- >
- <FiX size={16} />
- </Button>
- </div>
- </div>
- </div>
- </div>
- );
-}
+ const { locale, setLocale } = useI18n();
+ const t = useScopedT("launch");
+
+ const LOCALE_LABELS: Record<string, string> = { en: "EN", es: "ES", "zh-CN": "中文" };
+ const {
+ recording,
++ countdownActive,
+ toggleRecording,
+ microphoneEnabled,
+ setMicrophoneEnabled,
+ microphoneDeviceId,
+ setMicrophoneDeviceId,
+ systemAudioEnabled,
+ setSystemAudioEnabled,
++ countdownDelay,
++ setCountdownDelay,
+ } = useScreenRecorder();
+ const [recordingStart, setRecordingStart] = useState<number | null>(null);
+ const [elapsed, setElapsed] = useState(0);
+ const showMicControls = microphoneEnabled && !recording;
+ const { devices, selectedDeviceId, setSelectedDeviceId } =
+ useMicrophoneDevices(microphoneEnabled);
+ const { level } = useAudioLevelMeter({
+ enabled: showMicControls,
+ deviceId: microphoneDeviceId,
+ });
+
+ useEffect(() => {
+ if (selectedDeviceId && selectedDeviceId !== "default") {
+ setMicrophoneDeviceId(selectedDeviceId);
+ }
+ }, [selectedDeviceId, setMicrophoneDeviceId]);
+
+ useEffect(() => {
+ let timer: NodeJS.Timeout | null = null;
+ if (recording) {
+ if (!recordingStart) setRecordingStart(Date.now());
+ timer = setInterval(() => {
+ if (recordingStart) {
+ setElapsed(Math.floor((Date.now() - recordingStart) / 1000));
+ }
+ }, 1000);
+ } else {
+ setRecordingStart(null);
+ setElapsed(0);
+ if (timer) clearInterval(timer);
+ }
+ return () => {
+ if (timer) clearInterval(timer);
+ };
+ }, [recording, recordingStart]);
+
+ const formatTime = (seconds: number) => {
+ const m = Math.floor(seconds / 60)
+ .toString()
+ .padStart(2, "0");
+ const s = (seconds % 60).toString().padStart(2, "0");
+ return `${m}:${s}`;
+ };
+
+ const [selectedSource, setSelectedSource] = useState("Screen");
+ const [hasSelectedSource, setHasSelectedSource] = useState(false);
+ const [recordingsDirectory, setRecordingsDirectory] = useState<string | null>(null);
+ const [hideHudFromCapture, setHideHudFromCapture] = useState(true);
+ const [platform, setPlatform] = useState<string | null>(null);
+
+ useEffect(() => {
+ const checkSelectedSource = async () => {
+ if (window.electronAPI) {
+ const source = await window.electronAPI.getSelectedSource();
+ if (source) {
+ setSelectedSource(source.name);
+ setHasSelectedSource(true);
+ } else {
+ setSelectedSource("Screen");
+ setHasSelectedSource(false);
+ }
+ }
+ };
+
+ void checkSelectedSource();
+ const interval = setInterval(checkSelectedSource, 500);
+ return () => clearInterval(interval);
+ }, []);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ const loadPlatform = async () => {
+ try {
+ const nextPlatform = await window.electronAPI.getPlatform();
+ if (!cancelled) {
+ setPlatform(nextPlatform);
+ }
+ } catch (error) {
+ console.error("Failed to load platform:", error);
+ }
+ };
+
+ void loadPlatform();
+
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ const loadHudCaptureProtection = async () => {
+ try {
+ const result = await window.electronAPI.getHudOverlayCaptureProtection();
+ if (!cancelled && result.success) {
+ setHideHudFromCapture(result.enabled);
+ }
+ } catch (error) {
+ console.error("Failed to load HUD capture protection state:", error);
+ }
+ };
+
+ void loadHudCaptureProtection();
+
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+ const openSourceSelector = () => {
+ window.electronAPI?.openSourceSelector();
+ };
+
+ const openVideoFile = async () => {
+ const result = await window.electronAPI.openVideoFilePicker();
+ if (result.canceled) {
+ return;
+ }
+
+ if (result.success && result.path) {
+ await window.electronAPI.setCurrentVideoPath(result.path);
+ await window.electronAPI.switchToEditor();
+ }
+ };
+
+ const openProjectFile = async () => {
+ const result = await window.electronAPI.loadProjectFile();
+ if (result.canceled || !result.success) {
+ return;
+ }
+ await window.electronAPI.switchToEditor();
+ };
+
+ const sendHudOverlayHide = () => {
+ window.electronAPI?.hudOverlayHide?.();
+ };
+
+ const sendHudOverlayClose = () => {
+ window.electronAPI?.hudOverlayClose?.();
+ };
+
+ const toggleHudCaptureProtection = async () => {
+ const nextValue = !hideHudFromCapture;
+
+ setHideHudFromCapture(nextValue);
+
+ try {
+ const result = await window.electronAPI.setHudOverlayCaptureProtection(nextValue);
+
+ if (!result.success) {
+ setHideHudFromCapture(!nextValue);
+ return;
+ }
+
+ setHideHudFromCapture(result.enabled);
+ } catch (error) {
+ console.error("Failed to update HUD capture protection:", error);
+ setHideHudFromCapture(!nextValue);
+ }
+ };
+
+ const chooseRecordingsDirectory = async () => {
+ const result = await window.electronAPI.chooseRecordingsDirectory();
+ if (result.canceled) {
+ return;
+ }
+ if (result.success && result.path) {
+ setRecordingsDirectory(result.path);
+ }
+ };
+
+ useEffect(() => {
+ const loadRecordingsDirectory = async () => {
+ const result = await window.electronAPI.getRecordingsDirectory();
+ if (result.success) {
+ setRecordingsDirectory(result.path);
+ }
+ };
+
+ void loadRecordingsDirectory();
+ }, []);
+
+ const recordingsDirectoryName = recordingsDirectory
+ ? recordingsDirectory.split(/[\\/]/).filter(Boolean).pop() || recordingsDirectory
+ : "recordings";
+ const dividerClass = "mx-1 h-5 w-px shrink-0 bg-white/35";
+ const supportsHudCaptureProtection = platform !== "linux";
+
+ const toggleMicrophone = () => {
+ if (!recording) {
+ setMicrophoneEnabled(!microphoneEnabled);
+ }
+ };
+
+ return (
+ <div className="flex h-full w-full items-end justify-center overflow-hidden bg-transparent px-3 pb-3 pt-2">
+ <div className={`flex flex-col items-center gap-2 mx-auto ${styles.electronDrag}`}>
+ {showMicControls && (
+ <div
+ className={`flex items-center gap-2 rounded-full border border-white/15 bg-[rgba(18,18,26,0.92)] px-3 py-2 shadow-xl backdrop-blur-xl ${styles.electronNoDrag}`}
+ >
+ <select
+ value={microphoneDeviceId || selectedDeviceId}
+ onChange={(event) => {
+ setSelectedDeviceId(event.target.value);
+ setMicrophoneDeviceId(event.target.value);
+ }}
+ className={`max-w-[230px] rounded-full border border-white/15 bg-[#131722] px-3 py-1 text-xs text-slate-100 outline-none ${styles.micSelect}`}
+ >
+ {devices.map((device) => (
+ <option key={device.deviceId} value={device.deviceId}>
+ {device.label}
+ </option>
+ ))}
+ </select>
+ <AudioLevelMeter level={level} className="w-24" />
+ </div>
+ )}
+
+ <div
+ className={`mx-auto inline-flex max-w-full items-center gap-1.5 px-3 py-2 ${styles.electronDrag} ${styles.hudBar}`}
+ style={{
+ borderRadius: 9999,
+ background: "linear-gradient(135deg, rgba(28,28,36,0.97) 0%, rgba(18,18,26,0.96) 100%)",
+ backdropFilter: "blur(16px) saturate(140%)",
+ WebkitBackdropFilter: "blur(16px) saturate(140%)",
+ border: "1px solid rgba(80,80,120,0.25)",
+ minHeight: 48,
+ }}
+ >
+ <div className={`flex items-center px-1 ${styles.electronDrag}`}>
+ <RxDragHandleDots2 size={16} className="text-white/35" />
+ </div>
+
+ <Button
+ variant="link"
+ size="sm"
+ className={`gap-1 text-white/80 bg-transparent hover:bg-transparent px-0 text-xs ${styles.electronNoDrag}`}
+ onClick={openSourceSelector}
+ disabled={recording}
+ title={selectedSource}
+ >
+ <MdMonitor size={14} className="text-white/80" />
+ <ContentClamp truncateLength={6}>{selectedSource}</ContentClamp>
+ </Button>
+
+ <div className={dividerClass} />
+
+ <div className={`flex items-center gap-1 ${styles.electronNoDrag}`}>
+ {supportsHudCaptureProtection && (
+ <Button
+ variant="link"
+ size="icon"
+ onClick={() => void toggleHudCaptureProtection()}
+ title={
+ hideHudFromCapture
+ ? t("recording.showHudInVideo")
+ : t("recording.hideHudFromVideo")
+ }
+ className="text-white/80 hover:bg-transparent"
+ >
+ {hideHudFromCapture ? (
+ <EyeOff size={16} className="text-white/35" />
+ ) : (
+ <Eye size={16} className="text-[#2563EB]" />
+ )}
+ </Button>
+ )}
+ <Button
+ variant="link"
+ size="icon"
+ onClick={() => !recording && setSystemAudioEnabled(!systemAudioEnabled)}
+ disabled={recording}
+ title={
+ systemAudioEnabled
+ ? t("recording.disableSystemAudio")
+ : t("recording.enableSystemAudio")
+ }
+ className="text-white/80 hover:bg-transparent"
+ >
+ {systemAudioEnabled ? (
+ <MdVolumeUp size={16} className="text-[#2563EB]" />
+ ) : (
+ <MdVolumeOff size={16} className="text-white/35" />
+ )}
+ </Button>
+ <Button
+ variant="link"
+ size="icon"
+ onClick={toggleMicrophone}
+ disabled={recording}
+ title={
+ microphoneEnabled
+ ? t("recording.disableMicrophone")
+ : t("recording.enableMicrophone")
+ }
+ className="text-white/80 hover:bg-transparent"
+ >
+ {microphoneEnabled ? (
+ <MdMic size={16} className="text-[#2563EB]" />
+ ) : (
+ <MdMicOff size={16} className="text-white/35" />
+ )}
+ </Button>
+ </div>
+
+ <div className={dividerClass} />
+
++ <DropdownMenu>
++ <DropdownMenuTrigger asChild>
++ <Button
++ variant="link"
++ size="sm"
++ disabled={recording || countdownActive}
++ title={t("recording.countdownDelay")}
++ className={`gap-1 px-1 text-xs text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
++ >
++ <Timer size={14} />
++ <span>{countdownDelay > 0 ? `${countdownDelay}s` : t("recording.noDelay")}</span>
++ </Button>
++ </DropdownMenuTrigger>
++ <DropdownMenuContent
++ side="top"
++ align="center"
++ className="min-w-[80px] max-h-none overflow-visible border-white/15 bg-[rgba(28,28,36,0.97)] text-white/90 backdrop-blur-xl"
++ >
++ {[0, 3, 5, 10].map((delay) => (
++ <DropdownMenuItem
++ key={delay}
++ onSelect={() => setCountdownDelay(delay)}
++ className={`cursor-pointer text-xs ${
++ countdownDelay === delay ? "font-medium text-white" : "text-white/60"
++ }`}
++ >
++ {delay === 0 ? t("recording.noDelay") : `${delay}s`}
++ </DropdownMenuItem>
++ ))}
++ </DropdownMenuContent>
++ </DropdownMenu>
++
+ <Button
+ variant="link"
+ size="sm"
+ onClick={hasSelectedSource ? toggleRecording : openSourceSelector}
- disabled={!hasSelectedSource && !recording}
++ disabled={countdownActive || (!hasSelectedSource && !recording)}
+ className={`gap-1 text-white bg-transparent hover:bg-transparent px-0 text-xs ${styles.electronNoDrag}`}
+ >
+ {recording ? (
+ <>
+ <FaRegStopCircle size={14} className="text-red-400" />
+ <span className="text-red-400 font-medium tabular-nums">{formatTime(elapsed)}</span>
+ </>
+ ) : (
+ <>
+ <BsRecordCircle
+ size={14}
+ className={hasSelectedSource ? "text-white/85" : "text-white/35"}
+ />
+ <span className={hasSelectedSource ? "text-white/80" : "text-white/35"}>
+ {t("recording.record")}
+ </span>
+ </>
+ )}
+ </Button>
+
+ <Button
+ variant="link"
+ size="sm"
+ onClick={chooseRecordingsDirectory}
+ disabled={recording}
+ title={
+ recordingsDirectory
+ ? t("recording.recordingFolder", undefined, { path: recordingsDirectory })
+ : t("recording.chooseRecordingsFolder")
+ }
+ className={`text-white/75 hover:bg-transparent px-1 text-[11px] underline decoration-white/45 underline-offset-2 ${styles.electronNoDrag}`}
+ >
+ <ContentClamp truncateLength={18}>
+ {t("recording.folderPath", undefined, { name: recordingsDirectoryName })}
+ </ContentClamp>
+ </Button>
+
+ <div className="ml-auto flex items-center gap-0.5">
+ <div className={dividerClass} />
+ <Button
+ variant="link"
+ size="icon"
+ onClick={openVideoFile}
+ disabled={recording}
+ title={t("recording.openVideoFile")}
+ className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
+ >
+ <MdVideoFile size={15} />
+ </Button>
+ <Button
+ variant="link"
+ size="icon"
+ onClick={openProjectFile}
+ disabled={recording}
+ title={t("recording.openProject")}
+ className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
+ >
+ <FaFolderOpen size={14} />
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="link"
+ size="icon"
+ title="Language"
+ className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
+ >
+ <Languages size={14} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="top"
+ align="end"
+ className="min-w-[90px] bg-[rgba(28,28,36,0.97)] border-white/15 text-white/90 backdrop-blur-xl"
+ >
+ {SUPPORTED_LOCALES.map((code) => (
+ <DropdownMenuItem
+ key={code}
+ onSelect={() => setLocale(code as AppLocale)}
+ className={`text-xs cursor-pointer ${
+ locale === code ? "text-white font-medium" : "text-white/60"
+ }`}
+ >
+ {LOCALE_LABELS[code] ?? code}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <div className={dividerClass} />
+ <Button
+ variant="link"
+ size="icon"
+ onClick={sendHudOverlayHide}
+ title={t("recording.hideHud")}
+ className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
+ >
+ <FiMinus size={16} />
+ </Button>
+ <Button
+ variant="link"
+ size="icon"
+ onClick={sendHudOverlayClose}
+ title={t("recording.closeApp")}
+ className={`text-white/70 hover:bg-transparent ${styles.electronNoDrag}`}
+ >
+ <FiX size={16} />
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --cc src/components/video-editor/SettingsPanel.tsx
index d63ad2a9,f5f15cf6..87f63798
--- a/src/components/video-editor/SettingsPanel.tsx
+++ b/src/components/video-editor/SettingsPanel.tsx
@@@ -171,984 -115,845 +171,995 @@@ interface SettingsPanelProps
export default SettingsPanel;
const ZOOM_DEPTH_OPTIONS: Array<{ depth: ZoomDepth; label: string }> = [
- { depth: 1, label: "1.25×" },
- { depth: 2, label: "1.5×" },
- { depth: 3, label: "1.8×" },
- { depth: 4, label: "2.2×" },
- { depth: 5, label: "3.5×" },
- { depth: 6, label: "5×" },
+ { depth: 1, label: "1.25×" },
+ { depth: 2, label: "1.5×" },
+ { depth: 3, label: "1.8×" },
+ { depth: 4, label: "2.2×" },
+ { depth: 5, label: "3.5×" },
+ { depth: 6, label: "5×" },
];
-export function SettingsPanel({
- selected,
- onWallpaperChange,
- selectedZoomDepth,
- onZoomDepthChange,
- selectedZoomId,
- onZoomDelete,
- selectedTrimId,
- onTrimDelete,
- shadowIntensity = 0.67,
- onShadowChange,
- backgroundBlur = 0,
- onBackgroundBlurChange,
- zoomMotionBlur = 0,
- onZoomMotionBlurChange,
- connectZooms = true,
- onConnectZoomsChange,
- showCursor = false,
- onShowCursorChange,
- loopCursor = false,
- onLoopCursorChange,
- cursorSize = 5,
- onCursorSizeChange,
- cursorSmoothing = 2,
- onCursorSmoothingChange,
- cursorMotionBlur = 0.35,
- onCursorMotionBlurChange,
- cursorClickBounce = 1,
- onCursorClickBounceChange,
- borderRadius = 12.5,
- onBorderRadiusChange,
- padding = 50,
- onPaddingChange,
- cropRegion,
- onCropChange,
- aspectRatio,
- videoElement,
- exportQuality = 'good',
- onExportQualityChange,
- exportFormat = 'mp4',
- onExportFormatChange,
- gifFrameRate = 15,
- onGifFrameRateChange,
- gifLoop = true,
- onGifLoopChange,
- gifSizePreset = 'medium',
- onGifSizePresetChange,
- gifOutputDimensions = { width: 1280, height: 720 },
- onSaveProject,
- onLoadProject,
- onExport,
- selectedAnnotationId,
- annotationRegions = [],
- onAnnotationContentChange,
- onAnnotationTypeChange,
- onAnnotationStyleChange,
- onAnnotationFigureDataChange,
- onAnnotationDelete,
- selectedSpeedId,
- selectedSpeedValue,
- onSpeedChange,
- onSpeedDelete,
+export function SettingsPanel({
+ selected,
+ onWallpaperChange,
+ selectedZoomDepth,
+ onZoomDepthChange,
+ selectedZoomId,
+ onZoomDelete,
+ selectedTrimId,
+ onTrimDelete,
+ shadowIntensity = 0.67,
+ onShadowChange,
+ backgroundBlur = 0,
+ onBackgroundBlurChange,
+ zoomMotionBlur = 0,
+ onZoomMotionBlurChange,
+ connectZooms = true,
+ onConnectZoomsChange,
+ showCursor = false,
+ onShowCursorChange,
+ loopCursor = false,
+ onLoopCursorChange,
+ cursorSize = 5,
+ onCursorSizeChange,
+ cursorSmoothing = 2,
+ onCursorSmoothingChange,
+ cursorMotionBlur = 0.35,
+ onCursorMotionBlurChange,
+ cursorClickBounce = 1,
+ onCursorClickBounceChange,
+ cursorSway = DEFAULT_CURSOR_SWAY,
+ onCursorSwayChange,
+ borderRadius = 12.5,
+ onBorderRadiusChange,
+ padding = 50,
+ onPaddingChange,
+ cropRegion,
+ onCropChange,
+ aspectRatio,
+ videoElement,
+ exportQuality = "good",
+ onExportQualityChange,
+ exportFormat = "mp4",
+ onExportFormatChange,
+ gifFrameRate = 15,
+ onGifFrameRateChange,
+ gifLoop = true,
+ onGifLoopChange,
+ gifSizePreset = "medium",
+ onGifSizePresetChange,
+ gifOutputDimensions = { width: 1280, height: 720 },
+ onSaveProject,
+ onLoadProject,
+ onExport,
+ selectedAnnotationId,
+ annotationRegions = [],
+ onAnnotationContentChange,
+ onAnnotationTypeChange,
+ onAnnotationStyleChange,
+ onAnnotationFigureDataChange,
+ onAnnotationDelete,
+ selectedSpeedId,
+ selectedSpeedValue,
+ onSpeedChange,
+ onSpeedDelete,
}: SettingsPanelProps) {
- const tSettings = useScopedT('settings');
- const { t } = useI18n();
- const [wallpaperPreviewPaths, setWallpaperPreviewPaths] = useState<string[]>([]);
- const [customImages, setCustomImages] = useState<string[]>([]);
- const fileInputRef = useRef<HTMLInputElement>(null);
-
- useEffect(() => {
- let mounted = true
- ;(async () => {
- try {
- const resolved = await Promise.all(
- WALLPAPER_RELATIVE_PATHS.map(async (path) => getRenderableAssetUrl(await getAssetPath(path)))
- )
- if (mounted) setWallpaperPreviewPaths(resolved)
- } catch (err) {
- if (mounted) setWallpaperPreviewPaths(WALLPAPER_PATHS)
- }
- })()
- return () => { mounted = false }
- }, [])
- const colorPalette = [
- '#FF0000', '#FFD700', '#00FF00', '#FFFFFF', '#0000FF', '#FF6B00',
- '#9B59B6', '#E91E63', '#00BCD4', '#FF5722', '#8BC34A', '#FFC107',
- '#2563EB', '#000000', '#607D8B', '#795548',
- ];
-
- const [selectedColor, setSelectedColor] = useState('#ADADAD');
- const [gradient, setGradient] = useState<string>(GRADIENTS[0]);
- const [showCropModal, setShowCropModal] = useState(false);
- const cropSnapshotRef = useRef<CropRegion | null>(null);
-
- const zoomEnabled = Boolean(selectedZoomDepth);
- const trimEnabled = Boolean(selectedTrimId);
-
- const handleDeleteClick = () => {
- if (selectedZoomId && onZoomDelete) {
- onZoomDelete(selectedZoomId);
- }
- };
-
- const handleTrimDeleteClick = () => {
- if (selectedTrimId && onTrimDelete) {
- onTrimDelete(selectedTrimId);
- }
- };
-
- const handleCropToggle = () => {
- if (!showCropModal && cropRegion) {
- cropSnapshotRef.current = { ...cropRegion };
- }
- setShowCropModal(!showCropModal);
- };
-
- const handleCropCancel = () => {
- if (cropSnapshotRef.current && onCropChange) {
- onCropChange(cropSnapshotRef.current);
- }
- setShowCropModal(false);
- };
-
- const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
- const files = event.target.files;
- if (!files || files.length === 0) return;
-
- const file = files[0];
-
- // Validate file type - only allow JPG/JPEG
- const validTypes = ['image/jpeg', 'image/jpg'];
- if (!validTypes.includes(file.type)) {
- toast.error(tSettings('background.uploadError'), {
- description: tSettings('background.uploadErrorDescription'),
- });
- event.target.value = '';
- return;
- }
-
- const reader = new FileReader();
-
- reader.onload = (e) => {
- const dataUrl = e.target?.result as string;
- if (dataUrl) {
- setCustomImages(prev => [...prev, dataUrl]);
- onWallpaperChange(dataUrl);
- toast.success(tSettings('background.uploadSuccess'));
- }
- };
-
- reader.onerror = () => {
- toast.error(t('common.failedToUploadImage'), {
- description: t('common.errorReadingFile'),
- });
- };
-
- reader.readAsDataURL(file);
- // Reset input so the same file can be selected again
- event.target.value = '';
- };
-
- const handleRemoveCustomImage = (imageUrl: string, event: React.MouseEvent) => {
- event.stopPropagation();
- setCustomImages(prev => prev.filter(img => img !== imageUrl));
- // If the removed image was selected, clear selection
- if (selected === imageUrl) {
- onWallpaperChange(WALLPAPER_PATHS[0]);
- }
- };
-
- // Find selected annotation
- const selectedAnnotation = selectedAnnotationId
- ? annotationRegions.find(a => a.id === selectedAnnotationId)
- : null;
-
- // If an annotation is selected, show annotation settings instead
- if (selectedAnnotation && onAnnotationContentChange && onAnnotationTypeChange && onAnnotationStyleChange && onAnnotationDelete) {
- return (
- <AnnotationSettingsPanel
- annotation={selectedAnnotation}
- onContentChange={(content) => onAnnotationContentChange(selectedAnnotation.id, content)}
- onTypeChange={(type) => onAnnotationTypeChange(selectedAnnotation.id, type)}
- onStyleChange={(style) => onAnnotationStyleChange(selectedAnnotation.id, style)}
- onFigureDataChange={onAnnotationFigureDataChange ? (figureData) => onAnnotationFigureDataChange(selectedAnnotation.id, figureData) : undefined}
- onDelete={() => onAnnotationDelete(selectedAnnotation.id)}
- />
- );
- }
-
- return (
- <div className="flex-[2] min-w-0 bg-[#09090b] border border-white/5 rounded-2xl flex flex-col shadow-xl h-full overflow-hidden">
- <div className="flex-1 overflow-y-auto custom-scrollbar p-4 pb-0">
- <div className="mb-4">
- <div className="flex items-center justify-between mb-3">
- <span className="text-sm font-medium text-slate-200">{tSettings('zoom.level')}</span>
- <div className="flex items-center gap-2">
- {zoomEnabled && selectedZoomDepth && (
- <span className="text-[10px] uppercase tracking-wider font-medium text-[#2563EB] bg-[#2563EB]/10 px-2 py-0.5 rounded-full">
- {ZOOM_DEPTH_OPTIONS.find(o => o.depth === selectedZoomDepth)?.label}
- </span>
- )}
- <KeyboardShortcutsHelp />
- </div>
- </div>
- <div className="grid grid-cols-6 gap-1.5">
- {ZOOM_DEPTH_OPTIONS.map((option) => {
- const isActive = selectedZoomDepth === option.depth;
- return (
- <Button
- key={option.depth}
- type="button"
- disabled={!zoomEnabled}
- onClick={() => onZoomDepthChange?.(option.depth)}
- className={cn(
- "h-auto w-full rounded-lg border px-1 py-2 text-center shadow-sm transition-all",
- "duration-200 ease-out",
- zoomEnabled ? "opacity-100 cursor-pointer" : "opacity-40 cursor-not-allowed",
- isActive
- ? "border-[#2563EB] bg-[#2563EB] text-white shadow-[#2563EB]/20"
- : "border-white/5 bg-white/5 text-slate-400 hover:bg-white/10 hover:border-white/10 hover:text-slate-200"
- )}
- >
- <span className="text-xs font-semibold">{option.label}</span>
- </Button>
- );
- })}
- </div>
- {!zoomEnabled && (
- <p className="text-[10px] text-slate-500 mt-2 text-center">{tSettings('zoom.selectRegion')}</p>
- )}
- {zoomEnabled && (
- <Button
- onClick={handleDeleteClick}
- variant="destructive"
- size="sm"
- className="mt-2 w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"
- >
- <Trash2 className="w-3 h-3" />
- {tSettings('zoom.deleteZoom')}
- </Button>
- )}
- </div>
-
- {trimEnabled && (
- <div className="mb-4">
- <Button
- onClick={handleTrimDeleteClick}
- variant="destructive"
- size="sm"
- className="w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"
- >
- <Trash2 className="w-3 h-3" />
- {tSettings('trim.deleteRegion')}
- </Button>
- </div>
- )}
-
- <div className="mb-4">
- <div className="flex items-center justify-between mb-3">
- <span className="text-sm font-medium text-slate-200">{tSettings('speed.playbackSpeed')}</span>
- {selectedSpeedId && selectedSpeedValue && (
- <span className="text-[10px] uppercase tracking-wider font-medium text-[#d97706] bg-[#d97706]/10 px-2 py-0.5 rounded-full">
- {SPEED_OPTIONS.find(o => o.speed === selectedSpeedValue)?.label ?? `${selectedSpeedValue}×`}
- </span>
- )}
- </div>
- <div className="grid grid-cols-7 gap-1.5">
- {SPEED_OPTIONS.map((option) => {
- const isActive = selectedSpeedValue === option.speed;
- return (
- <Button
- key={option.speed}
- type="button"
- disabled={!selectedSpeedId}
- onClick={() => onSpeedChange?.(option.speed)}
- className={cn(
- "h-auto w-full rounded-lg border px-1 py-2 text-center shadow-sm transition-all",
- "duration-200 ease-out",
- selectedSpeedId ? "opacity-100 cursor-pointer" : "opacity-40 cursor-not-allowed",
- isActive
- ? "border-[#d97706] bg-[#d97706] text-white shadow-[#d97706]/20"
- : "border-white/5 bg-white/5 text-slate-400 hover:bg-white/10 hover:border-white/10 hover:text-slate-200"
- )}
- >
- <span className="text-xs font-semibold">{option.label}</span>
- </Button>
- );
- })}
- </div>
- {!selectedSpeedId && (
- <p className="text-[10px] text-slate-500 mt-2 text-center">{tSettings('speed.selectRegion')}</p>
- )}
- {selectedSpeedId && (
- <Button
- onClick={() => selectedSpeedId && onSpeedDelete?.(selectedSpeedId)}
- variant="destructive"
- size="sm"
- className="mt-2 w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"
- >
- <Trash2 className="w-3 h-3" />
- {tSettings('speed.deleteRegion')}
- </Button>
- )}
- </div>
-
- <Accordion type="multiple" defaultValue={["effects", "background"]} className="space-y-1">
- <AccordionItem value="effects" className="border-white/5 rounded-xl bg-white/[0.02] px-3">
- <AccordionTrigger className="py-2.5 hover:no-underline">
- <div className="flex items-center gap-2">
- <Sparkles className="w-4 h-4 text-[#2563EB]" />
- <span className="text-xs font-medium">{tSettings('effects.title')}</span>
- </div>
- </AccordionTrigger>
- <AccordionContent className="pb-3">
- <div className="grid grid-cols-2 gap-2 mb-3">
- <div className="flex items-center justify-between p-2 rounded-lg bg-white/5 border border-white/5">
- <div className="text-[10px] font-medium text-slate-300">{tSettings('effects.showCursor')}</div>
- <Switch
- checked={showCursor}
- onCheckedChange={onShowCursorChange}
- className="data-[state=checked]:bg-[#2563EB] scale-90"
- />
- </div>
- <div className="flex items-center justify-between p-2 rounded-lg bg-white/5 border border-white/5">
- <div>
- <div className="text-[10px] font-medium text-slate-300">{tSettings('effects.loopCursor')}</div>
- </div>
- <Switch
- checked={loopCursor}
- onCheckedChange={onLoopCursorChange}
- className="data-[state=checked]:bg-[#2563EB] scale-90"
- />
- </div>
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.backgroundBlur')}
- value={backgroundBlur}
- defaultValue={0}
- min={0}
- max={8}
- step={0.25}
- onChange={(v) => onBackgroundBlurChange?.(v)}
- formatValue={(v) => `${v.toFixed(1)}px`}
- parseInput={(t) => parseFloat(t.replace(/px$/, ''))}
- />
- </div>
- </div>
-
- <div className="grid grid-cols-2 gap-2 mb-3">
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.zoomMotionBlur')}
- value={zoomMotionBlur}
- defaultValue={DEFAULT_ZOOM_MOTION_BLUR}
- min={0}
- max={2}
- step={0.05}
- onChange={(v) => onZoomMotionBlurChange?.(v)}
- formatValue={(v) => `${v.toFixed(2)}×`}
- parseInput={(t) => parseFloat(t.replace(/×$/, ''))}
- />
- </div>
-
- <div className="flex items-center justify-between p-2 rounded-lg bg-white/5 border border-white/5">
- <div className="text-[10px] font-medium text-slate-300">{tSettings('effects.connectZooms')}</div>
- <Switch
- checked={connectZooms}
- onCheckedChange={onConnectZoomsChange}
- className="data-[state=checked]:bg-[#2563EB] scale-90"
- />
- </div>
- </div>
-
- <div className="grid grid-cols-2 gap-2 mb-3">
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.cursorSize')}
- value={cursorSize}
- defaultValue={DEFAULT_CURSOR_SIZE}
- min={0.5}
- max={10}
- step={0.05}
- onChange={(v) => onCursorSizeChange?.(v)}
- formatValue={(v) => `${v.toFixed(2)}×`}
- parseInput={(t) => parseFloat(t.replace(/×$/, ''))}
- />
- </div>
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.cursorSmoothing')}
- value={cursorSmoothing}
- defaultValue={DEFAULT_CURSOR_SMOOTHING}
- min={0}
- max={2}
- step={0.01}
- onChange={(v) => onCursorSmoothingChange?.(v)}
- formatValue={(v) => v <= 0 ? 'Off' : v.toFixed(2)}
- parseInput={(t) => parseFloat(t)}
- />
- </div>
- </div>
-
- <div className="grid grid-cols-2 gap-2 mb-3">
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.cursorMotionBlur')}
- value={cursorMotionBlur}
- defaultValue={DEFAULT_CURSOR_MOTION_BLUR}
- min={0}
- max={2}
- step={0.05}
- onChange={(v) => onCursorMotionBlurChange?.(v)}
- formatValue={(v) => `${v.toFixed(2)}×`}
- parseInput={(t) => parseFloat(t.replace(/×$/, ''))}
- />
- </div>
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.cursorClickBounce')}
- value={cursorClickBounce}
- defaultValue={DEFAULT_CURSOR_CLICK_BOUNCE}
- min={0}
- max={5}
- step={0.05}
- onChange={(v) => onCursorClickBounceChange?.(v)}
- formatValue={(v) => `${v.toFixed(2)}×`}
- parseInput={(t) => parseFloat(t.replace(/×$/, ''))}
- />
- </div>
- </div>
-
- <div className="grid grid-cols-2 gap-2">
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.shadow')}
- value={shadowIntensity}
- defaultValue={0.67}
- min={0}
- max={1}
- step={0.01}
- onChange={(v) => onShadowChange?.(v)}
- formatValue={(v) => `${Math.round(v * 100)}%`}
- parseInput={(t) => parseFloat(t.replace(/%$/, '')) / 100}
- />
- </div>
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.roundness')}
- value={borderRadius}
- defaultValue={12.5}
- min={0}
- max={25}
- step={0.5}
- onChange={(v) => onBorderRadiusChange?.(v)}
- formatValue={(v) => `${v}px`}
- parseInput={(t) => parseFloat(t.replace(/px$/, ''))}
- />
- </div>
- <div className="p-2 rounded-lg bg-white/5 border border-white/5">
- <SliderControl
- label={tSettings('effects.padding')}
- value={padding}
- defaultValue={50}
- min={0}
- max={100}
- step={1}
- onChange={(v) => onPaddingChange?.(v)}
- formatValue={(v) => `${v}%`}
- parseInput={(t) => parseFloat(t.replace(/%$/, ''))}
- />
- </div>
- </div>
-
- <Button
- onClick={handleCropToggle}
- variant="outline"
- className="w-full mt-2 gap-1.5 bg-white/5 text-slate-200 border-white/10 hover:bg-white/10 hover:border-white/20 hover:text-white text-[10px] h-8 transition-all"
- >
- <Crop className="w-3 h-3" />
- {tSettings('crop.title')}
- </Button>
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="background" className="border-white/5 rounded-xl bg-white/[0.02] px-3">
- <AccordionTrigger className="py-2.5 hover:no-underline">
- <div className="flex items-center gap-2">
- <Palette className="w-4 h-4 text-[#2563EB]" />
- <span className="text-xs font-medium">{tSettings('background.title')}</span>
- </div>
- </AccordionTrigger>
- <AccordionContent className="pb-3">
- <Tabs defaultValue="image" className="w-full">
- <TabsList className="mb-2 bg-white/5 border border-white/5 p-0.5 w-full grid grid-cols-3 h-7 rounded-lg">
- <TabsTrigger value="image" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 text-[10px] py-1 rounded-md transition-all">{tSettings('background.image')}</TabsTrigger>
- <TabsTrigger value="color" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 text-[10px] py-1 rounded-md transition-all">{tSettings('background.color')}</TabsTrigger>
- <TabsTrigger value="gradient" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 text-[10px] py-1 rounded-md transition-all">{tSettings('background.gradient')}</TabsTrigger>
- </TabsList>
-
- <div className="max-h-[min(200px,25vh)] overflow-y-auto custom-scrollbar">
- <TabsContent value="image" className="mt-0 space-y-2">
- <input
- type="file"
- ref={fileInputRef}
- onChange={handleImageUpload}
- accept=".jpg,.jpeg,image/jpeg"
- className="hidden"
- />
- <Button
- onClick={() => fileInputRef.current?.click()}
- variant="outline"
- className="w-full gap-2 bg-white/5 text-slate-200 border-white/10 hover:bg-[#2563EB] hover:text-white hover:border-[#2563EB] transition-all h-7 text-[10px]"
- >
- <Upload className="w-3 h-3" />
- {tSettings('background.uploadCustom')}
- </Button>
-
- <div className="grid grid-cols-7 gap-1.5">
- {customImages.map((imageUrl, idx) => {
- const isSelected = selected === imageUrl;
- return (
- <div
- key={`custom-${idx}`}
- className={cn(
- "aspect-square w-9 h-9 rounded-md border-2 overflow-hidden cursor-pointer transition-all duration-200 relative group shadow-sm",
- isSelected
- ? "border-[#2563EB] ring-1 ring-[#2563EB]/30"
- : "border-white/10 hover:border-[#2563EB]/40 opacity-80 hover:opacity-100 bg-white/5"
- )}
- style={{ backgroundImage: `url(${imageUrl})`, backgroundSize: "cover", backgroundPosition: "center" }}
- onClick={() => onWallpaperChange(imageUrl)}
- role="button"
- >
- <button
- onClick={(e) => handleRemoveCustomImage(imageUrl, e)}
- className="absolute top-0.5 right-0.5 w-3 h-3 bg-red-500/90 hover:bg-red-500 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10"
- >
- <X className="w-2 h-2 text-white" />
- </button>
- </div>
- );
- })}
-
- {(wallpaperPreviewPaths.length > 0 ? wallpaperPreviewPaths : WALLPAPER_PATHS).map((previewPath, index) => {
- const wallpaper = BUILT_IN_WALLPAPERS[index];
- const wallpaperValue = WALLPAPER_PATHS[index] ?? previewPath;
- const isSelected = (() => {
- if (!selected) return false;
- if (selected === wallpaperValue || selected === previewPath) return true;
- try {
- const clean = (s: string) => s.replace(/^file:\/\//, '').replace(/^\//, '')
- if (clean(selected).endsWith(clean(wallpaperValue))) return true;
- if (clean(wallpaperValue).endsWith(clean(selected))) return true;
- if (clean(selected).endsWith(clean(previewPath))) return true;
- if (clean(previewPath).endsWith(clean(selected))) return true;
- } catch {}
- return false;
- })();
- return (
- <div
- key={wallpaperValue}
- className={cn(
- "aspect-square w-9 h-9 rounded-md border-2 overflow-hidden cursor-pointer transition-all duration-200 shadow-sm",
- isSelected
- ? "border-[#2563EB] ring-1 ring-[#2563EB]/30"
- : "border-white/10 hover:border-[#2563EB]/40 opacity-80 hover:opacity-100 bg-white/5"
- )}
- aria-label={wallpaper?.label ?? `Wallpaper ${index + 1}`}
- title={wallpaper?.label ?? `Wallpaper ${index + 1}`}
- style={{ backgroundImage: `url(${previewPath})`, backgroundSize: "cover", backgroundPosition: "center" }}
- onClick={() => onWallpaperChange(wallpaperValue)}
- role="button"
- />
- )
- })}
- </div>
- </TabsContent>
-
- <TabsContent value="color" className="mt-0">
- <div className="p-1">
- <Block
- color={selectedColor}
- colors={colorPalette}
- onChange={(color) => {
- setSelectedColor(color.hex);
- onWallpaperChange(color.hex);
- }}
- style={{
- width: '100%',
- borderRadius: '8px',
- }}
- />
- </div>
- </TabsContent>
-
- <TabsContent value="gradient" className="mt-0">
- <div className="grid grid-cols-7 gap-1.5">
- {GRADIENTS.map((g, idx) => (
- <div
- key={g}
- className={cn(
- "aspect-square w-9 h-9 rounded-md border-2 overflow-hidden cursor-pointer transition-all duration-200 shadow-sm",
- gradient === g
- ? "border-[#2563EB] ring-1 ring-[#2563EB]/30"
- : "border-white/10 hover:border-[#2563EB]/40 opacity-80 hover:opacity-100 bg-white/5"
- )}
- style={{ background: g }}
- aria-label={`Gradient ${idx + 1}`}
- onClick={() => { setGradient(g); onWallpaperChange(g); }}
- role="button"
- />
- ))}
- </div>
- </TabsContent>
- </div>
- </Tabs>
- </AccordionContent>
- </AccordionItem>
- </Accordion>
- </div>
-
- {showCropModal && cropRegion && onCropChange && (
- <>
- <div
- className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 animate-in fade-in duration-200"
- onClick={handleCropCancel}
- />
- <div className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-[60] bg-[#09090b] rounded-2xl shadow-2xl border border-white/10 p-8 w-[90vw] max-w-5xl max-h-[90vh] overflow-auto animate-in zoom-in-95 duration-200">
- <div className="flex items-center justify-between mb-6">
- <div>
- <span className="text-xl font-bold text-slate-200">{tSettings('crop.title')}</span>
- <p className="text-sm text-slate-400 mt-2">{tSettings('crop.instruction')}</p>
- </div>
- <Button
- variant="ghost"
- size="icon"
- onClick={handleCropCancel}
- className="hover:bg-white/10 text-slate-400 hover:text-white"
- >
- <X className="w-5 h-5" />
- </Button>
- </div>
- <CropControl
- videoElement={videoElement || null}
- cropRegion={cropRegion}
- onCropChange={onCropChange}
- aspectRatio={aspectRatio}
- />
- <div className="mt-6 flex justify-end">
- <Button
- onClick={() => setShowCropModal(false)}
- size="lg"
- className="bg-[#2563EB] hover:bg-[#2563EB]/90 text-white"
- >
- {t('common.actions.done')}
- </Button>
- </div>
- </div>
- </>
- )}
-
- <div className="flex-shrink-0 p-4 pt-3 border-t border-white/5 bg-[#09090b]">
- <div className="flex items-center gap-2 mb-3">
- <button
- onClick={() => onExportFormatChange?.('mp4')}
- className={cn(
- "flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg border transition-all text-xs font-medium",
- exportFormat === 'mp4'
- ? "bg-[#2563EB]/10 border-[#2563EB]/50 text-white"
- : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:text-slate-200"
- )}
- >
- <Film className="w-3.5 h-3.5" />
- {tSettings('export.mp4')}
- </button>
- <button
- onClick={() => onExportFormatChange?.('gif')}
- className={cn(
- "flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg border transition-all text-xs font-medium",
- exportFormat === 'gif'
- ? "bg-[#2563EB]/10 border-[#2563EB]/50 text-white"
- : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:text-slate-200"
- )}
- >
- <Image className="w-3.5 h-3.5" />
- {tSettings('export.gif')}
- </button>
- </div>
-
- {exportFormat === 'mp4' && (
- <div className="mb-3 bg-white/5 border border-white/5 p-0.5 w-full grid grid-cols-4 h-7 rounded-lg">
- <button
- onClick={() => onExportQualityChange?.('medium')}
- className={cn(
- "rounded-md transition-all text-[10px] font-medium",
- exportQuality === 'medium' ? "bg-white text-black" : "text-slate-400 hover:text-slate-200"
- )}
- >
- {tSettings('export.quality.low')}
- </button>
- <button
- onClick={() => onExportQualityChange?.('good')}
- className={cn(
- "rounded-md transition-all text-[10px] font-medium",
- exportQuality === 'good' ? "bg-white text-black" : "text-slate-400 hover:text-slate-200"
- )}
- >
- {tSettings('export.quality.medium')}
- </button>
- <button
- onClick={() => onExportQualityChange?.('high')}
- className={cn(
- "rounded-md transition-all text-[10px] font-medium",
- exportQuality === 'high' ? "bg-white text-black" : "text-slate-400 hover:text-slate-200"
- )}
- >
- {tSettings('export.quality.high')}
- </button>
- <button
- onClick={() => onExportQualityChange?.('source')}
- className={cn(
- "rounded-md transition-all text-[10px] font-medium",
- exportQuality === 'source' ? "bg-white text-black" : "text-slate-400 hover:text-slate-200"
- )}
- >
- {tSettings('export.quality.original')}
- </button>
- </div>
- )}
-
- {exportFormat === 'gif' && (
- <div className="mb-3 space-y-2">
- <div className="flex items-center gap-2">
- <div className="flex-1 bg-white/5 border border-white/5 p-0.5 grid grid-cols-4 h-7 rounded-lg">
- {GIF_FRAME_RATES.map((rate) => (
- <button
- key={rate.value}
- onClick={() => onGifFrameRateChange?.(rate.value)}
- className={cn(
- "rounded-md transition-all text-[10px] font-medium",
- gifFrameRate === rate.value ? "bg-white text-black" : "text-slate-400 hover:text-slate-200"
- )}
- >
- {rate.value}
- </button>
- ))}
- </div>
- <div className="flex-1 bg-white/5 border border-white/5 p-0.5 grid grid-cols-3 h-7 rounded-lg">
- {Object.entries(GIF_SIZE_PRESETS).map(([key, _preset]) => (
- <button
- key={key}
- onClick={() => onGifSizePresetChange?.(key as GifSizePreset)}
- className={cn(
- "rounded-md transition-all text-[10px] font-medium",
- gifSizePreset === key ? "bg-white text-black" : "text-slate-400 hover:text-slate-200"
- )}
- >
- {key === 'original' ? 'Orig' : key.charAt(0).toUpperCase() + key.slice(1, 3)}
- </button>
- ))}
- </div>
- </div>
- <div className="flex items-center justify-between">
- <span className="text-[10px] text-slate-500">{gifOutputDimensions.width} × {gifOutputDimensions.height}px</span>
- <div className="flex items-center gap-2">
- <span className="text-[10px] text-slate-400">{tSettings('export.loop')}</span>
- <Switch
- checked={gifLoop}
- onCheckedChange={onGifLoopChange}
- className="data-[state=checked]:bg-[#2563EB] scale-75"
- />
- </div>
- </div>
- </div>
- )}
-
- <div className="grid grid-cols-2 gap-2 mb-2">
- <Button
- type="button"
- variant="outline"
- onClick={onLoadProject}
- className="h-8 text-[10px] font-medium gap-1.5 bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
- >
- <FolderOpen className="w-3.5 h-3.5" />
- {tSettings('export.loadProject')}
- </Button>
- <Button
- type="button"
- variant="outline"
- onClick={onSaveProject}
- className="h-8 text-[10px] font-medium gap-1.5 bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
- >
- <Save className="w-3.5 h-3.5" />
- {tSettings('export.saveProject')}
- </Button>
- </div>
-
- <Button
- type="button"
- size="lg"
- onClick={onExport}
- className="w-full py-5 text-sm font-semibold flex items-center justify-center gap-2 bg-[#2563EB] text-white rounded-xl shadow-lg shadow-[#2563EB]/20 hover:bg-[#2563EB]/90 hover:scale-[1.02] active:scale-[0.98] transition-all duration-200"
- >
- <Download className="w-4 h-4" />
- {tSettings('export.exportVideo', undefined, { format: exportFormat === 'gif' ? 'GIF' : 'Video' })}
- </Button>
-
- <div className="flex gap-2 mt-3">
- <button
- type="button"
- onClick={() => {
- window.electronAPI?.openExternalUrl('https://github.com/webadderall/Recordly/issues/new/choose');
- }}
- className="flex-1 flex items-center justify-center gap-1.5 text-[10px] text-slate-500 hover:text-slate-300 py-1.5 transition-colors"
- >
- <Bug className="w-3 h-3 text-[#2563EB]" />
- {tSettings('export.reportBug')}
- </button>
- <button
- type="button"
- onClick={() => {
- window.electronAPI?.openExternalUrl('https://github.com/webadderall/Recordly');
- }}
- className="flex-1 flex items-center justify-center gap-1.5 text-[10px] text-slate-500 hover:text-slate-300 py-1.5 transition-colors"
- >
- <Star className="w-3 h-3 text-yellow-400" />
- {tSettings('export.starOnGithub')}
- </button>
- </div>
- </div>
- </div>
- );
-}
+ const tSettings = useScopedT("settings");
+ const { t } = useI18n();
+ const initialEditorPreferences = useMemo(() => loadEditorPreferences(), []);
+ const [wallpaperPreviewPaths, setWallpaperPreviewPaths] = useState<string[]>([]);
+ const [customImages, setCustomImages] = useState<string[]>(
+ initialEditorPreferences.customWallpapers,
+ );
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ let mounted = true;
+ (async () => {
+ try {
+ const resolved = await Promise.all(
+ WALLPAPER_RELATIVE_PATHS.map(async (path) =>
+ getRenderableAssetUrl(await getAssetPath(path)),
+ ),
+ );
+ if (mounted) setWallpaperPreviewPaths(resolved);
+ } catch {
+ if (mounted) setWallpaperPreviewPaths(WALLPAPER_PATHS);
+ }
+ })();
+ return () => {
+ mounted = false;
+ };
+ }, []);
+ const colorPalette = [
+ "#FF0000",
+ "#FFD700",
+ "#00FF00",
+ "#FFFFFF",
+ "#0000FF",
+ "#FF6B00",
+ "#9B59B6",
+ "#E91E63",
+ "#00BCD4",
+ "#FF5722",
+ "#8BC34A",
+ "#FFC107",
+ "#2563EB",
+ "#000000",
+ "#607D8B",
+ "#795548",
+ ];
+
+ const [selectedColor, setSelectedColor] = useState(
+ isHexWallpaper(selected) ? selected : "#ADADAD",
+ );
+ const [gradient, setGradient] = useState<string>(
+ GRADIENTS.includes(selected) ? selected : GRADIENTS[0],
+ );
+ const [backgroundTab, setBackgroundTab] = useState<BackgroundTab>(() =>
+ getBackgroundTabForWallpaper(selected),
+ );
+ const [showCropModal, setShowCropModal] = useState(false);
+ const cropSnapshotRef = useRef<CropRegion | null>(null);
+
+ useEffect(() => {
+ setBackgroundTab(getBackgroundTabForWallpaper(selected));
+
+ if (isHexWallpaper(selected)) {
+ setSelectedColor(selected);
+ }
+
+ if (GRADIENTS.includes(selected)) {
+ setGradient(selected);
+ }
+
+ if (selected.startsWith("data:image") && !customImages.includes(selected)) {
+ setCustomImages((prev) => [selected, ...prev]);
+ }
+ }, [customImages, selected]);
+
+ useEffect(() => {
+ saveEditorPreferences({ customWallpapers: customImages });
+ }, [customImages]);
+
+ const zoomEnabled = Boolean(selectedZoomDepth);
+ const trimEnabled = Boolean(selectedTrimId);
+
+ const handleDeleteClick = () => {
+ if (selectedZoomId && onZoomDelete) {
+ onZoomDelete(selectedZoomId);
+ }
+ };
+
+ const handleTrimDeleteClick = () => {
+ if (selectedTrimId && onTrimDelete) {
+ onTrimDelete(selectedTrimId);
+ }
+ };
+ const handleCropToggle = () => {
+ if (!showCropModal && cropRegion) {
+ cropSnapshotRef.current = { ...cropRegion };
+ }
+ setShowCropModal(!showCropModal);
+ };
+
+ const handleCropCancel = () => {
+ if (cropSnapshotRef.current && onCropChange) {
+ onCropChange(cropSnapshotRef.current);
+ }
+ setShowCropModal(false);
+ };
+
+ const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const files = event.target.files;
+ if (!files || files.length === 0) return;
+
+ const file = files[0];
+
+ // Validate file type - only allow JPG/JPEG
+ const validTypes = ["image/jpeg", "image/jpg"];
+ if (!validTypes.includes(file.type)) {
+ toast.error(tSettings("background.uploadError"), {
+ description: tSettings("background.uploadErrorDescription"),
+ });
+ event.target.value = "";
+ return;
+ }
+
+ const reader = new FileReader();
+
+ reader.onload = (e) => {
+ const dataUrl = e.target?.result as string;
+ if (dataUrl) {
+ setCustomImages((prev) => [...prev, dataUrl]);
+ onWallpaperChange(dataUrl);
+ toast.success(tSettings("background.uploadSuccess"));
+ }
+ };
+
+ reader.onerror = () => {
+ toast.error(t("common.failedToUploadImage"), {
+ description: t("common.errorReadingFile"),
+ });
+ };
+
+ reader.readAsDataURL(file);
+ // Reset input so the same file can be selected again
+ event.target.value = "";
+ };
+
+ const handleRemoveCustomImage = (imageUrl: string, event: React.MouseEvent) => {
+ event.stopPropagation();
+ setCustomImages((prev) => prev.filter((img) => img !== imageUrl));
+ // If the removed image was selected, clear selection
+ if (selected === imageUrl) {
+ onWallpaperChange(WALLPAPER_PATHS[0]);
+ }
+ };
+
+ // Find selected annotation
+ const selectedAnnotation = selectedAnnotationId
+ ? annotationRegions.find((a) => a.id === selectedAnnotationId)
+ : null;
+
+ // If an annotation is selected, show annotation settings instead
+ if (
+ selectedAnnotation &&
+ onAnnotationContentChange &&
+ onAnnotationTypeChange &&
+ onAnnotationStyleChange &&
+ onAnnotationDelete
+ ) {
+ return (
+ <AnnotationSettingsPanel
+ annotation={selectedAnnotation}
+ onContentChange={(content) => onAnnotationContentChange(selectedAnnotation.id, content)}
+ onTypeChange={(type) => onAnnotationTypeChange(selectedAnnotation.id, type)}
+ onStyleChange={(style) => onAnnotationStyleChange(selectedAnnotation.id, style)}
+ onFigureDataChange={
+ onAnnotationFigureDataChange
+ ? (figureData) => onAnnotationFigureDataChange(selectedAnnotation.id, figureData)
+ : undefined
+ }
+ onDelete={() => onAnnotationDelete(selectedAnnotation.id)}
+ />
+ );
+ }
+
+ return (
+ <div className="flex-[2] min-w-0 bg-[#09090b] border border-white/5 rounded-2xl flex flex-col shadow-xl h-full overflow-hidden">
+ <div className="flex-1 overflow-y-auto custom-scrollbar p-4 pb-0">
+ <div className="mb-4">
+ <div className="flex items-center justify-between mb-3">
+ <span className="text-sm font-medium text-slate-200">{tSettings("zoom.level")}</span>
+ <div className="flex items-center gap-2">
+ {zoomEnabled && selectedZoomDepth && (
+ <span className="text-[10px] uppercase tracking-wider font-medium text-[#2563EB] bg-[#2563EB]/10 px-2 py-0.5 rounded-full">
+ {ZOOM_DEPTH_OPTIONS.find((o) => o.depth === selectedZoomDepth)?.label}
+ </span>
+ )}
+ <KeyboardShortcutsHelp />
+ </div>
+ </div>
+ <div className="grid grid-cols-6 gap-1.5">
+ {ZOOM_DEPTH_OPTIONS.map((option) => {
+ const isActive = selectedZoomDepth === option.depth;
+ return (
+ <Button
+ key={option.depth}
+ type="button"
+ disabled={!zoomEnabled}
+ onClick={() => onZoomDepthChange?.(option.depth)}
+ className={cn(
+ "h-auto w-full rounded-lg border px-1 py-2 text-center shadow-sm transition-all",
+ "duration-200 ease-out",
+ zoomEnabled ? "opacity-100 cursor-pointer" : "opacity-40 cursor-not-allowed",
+ isActive
+ ? "border-[#2563EB] bg-[#2563EB] text-white shadow-[#2563EB]/20"
+ : "border-white/5 bg-white/5 text-slate-400 hover:bg-white/10 hover:border-white/10 hover:text-slate-200",
+ )}
+ >
+ <span className="text-xs font-semibold">{option.label}</span>
+ </Button>
+ );
+ })}
+ </div>
+ {!zoomEnabled && (
+ <p className="text-[10px] text-slate-500 mt-2 text-center">
+ {tSettings("zoom.selectRegion")}
+ </p>
+ )}
+ {zoomEnabled && (
+ <Button
+ onClick={handleDeleteClick}
+ variant="destructive"
+ size="sm"
+ className="mt-2 w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"
+ >
+ <Trash2 className="w-3 h-3" />
+ {tSettings("zoom.deleteZoom")}
+ </Button>
+ )}
+ </div>
+
+ {trimEnabled && (
+ <div className="mb-4">
+ <Button
+ onClick={handleTrimDeleteClick}
+ variant="destructive"
+ size="sm"
+ className="w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"
+ >
+ <Trash2 className="w-3 h-3" />
+ {tSettings("trim.deleteRegion")}
+ </Button>
+ </div>
+ )}
+
+ <div className="mb-4">
+ <div className="flex items-center justify-between mb-3">
+ <span className="text-sm font-medium text-slate-200">
+ {tSettings("speed.playbackSpeed")}
+ </span>
+ {selectedSpeedId && selectedSpeedValue && (
+ <span className="text-[10px] uppercase tracking-wider font-medium text-[#d97706] bg-[#d97706]/10 px-2 py-0.5 rounded-full">
+ {SPEED_OPTIONS.find((o) => o.speed === selectedSpeedValue)?.label ??
+ `${selectedSpeedValue}×`}
+ </span>
+ )}
+ </div>
+ <div className="grid grid-cols-7 gap-1.5">
+ {SPEED_OPTIONS.map((option) => {
+ const isActive = selectedSpeedValue === option.speed;
+ return (
+ <Button
+ key={option.speed}
+ type="button"
+ disabled={!selectedSpeedId}
+ onClick={() => onSpeedChange?.(option.speed)}
+ className={cn(
+ "h-auto w-full rounded-lg border px-1 py-2 text-center shadow-sm transition-all",
+ "duration-200 ease-out",
+ selectedSpeedId
+ ? "opacity-100 cursor-pointer"
+ : "opacity-40 cursor-not-allowed",
+ isActive
+ ? "border-[#d97706] bg-[#d97706] text-white shadow-[#d97706]/20"
+ : "border-white/5 bg-white/5 text-slate-400 hover:bg-white/10 hover:border-white/10 hover:text-slate-200",
+ )}
+ >
+ <span className="text-xs font-semibold">{option.label}</span>
+ </Button>
+ );
+ })}
+ </div>
+ {!selectedSpeedId && (
+ <p className="text-[10px] text-slate-500 mt-2 text-center">
+ {tSettings("speed.selectRegion")}
+ </p>
+ )}
+ {selectedSpeedId && (
+ <Button
+ onClick={() => selectedSpeedId && onSpeedDelete?.(selectedSpeedId)}
+ variant="destructive"
+ size="sm"
+ className="mt-2 w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"
+ >
+ <Trash2 className="w-3 h-3" />
+ {tSettings("speed.deleteRegion")}
+ </Button>
+ )}
+ </div>
+
+ <Accordion type="multiple" defaultValue={["effects", "background"]} className="space-y-1">
+ <AccordionItem value="effects" className="border-white/5 rounded-xl bg-white/[0.02] px-3">
+ <AccordionTrigger className="py-2.5 hover:no-underline">
+ <div className="flex items-center gap-2">
+ <Sparkles className="w-4 h-4 text-[#2563EB]" />
+ <span className="text-xs font-medium">{tSettings("effects.title")}</span>
+ </div>
+ </AccordionTrigger>
+ <AccordionContent className="pb-3">
+ <div className="grid grid-cols-2 gap-2 mb-3">
+ <div className="flex items-center justify-between p-2 rounded-lg bg-white/5 border border-white/5">
+ <div className="text-[10px] font-medium text-slate-300">
+ {tSettings("effects.showCursor")}
+ </div>
+ <Switch
+ checked={showCursor}
+ onCheckedChange={onShowCursorChange}
+ className="data-[state=checked]:bg-[#2563EB] scale-90"
+ />
+ </div>
+ <div className="flex items-center justify-between p-2 rounded-lg bg-white/5 border border-white/5">
+ <div>
+ <div className="text-[10px] font-medium text-slate-300">
+ {tSettings("effects.loopCursor")}
+ </div>
+ </div>
+ <Switch
+ checked={loopCursor}
+ onCheckedChange={onLoopCursorChange}
+ className="data-[state=checked]:bg-[#2563EB] scale-90"
+ />
+ </div>
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.backgroundBlur")}
+ value={backgroundBlur}
+ defaultValue={0}
+ min={0}
+ max={8}
+ step={0.25}
+ onChange={(v) => onBackgroundBlurChange?.(v)}
+ formatValue={(v) => `${v.toFixed(1)}px`}
+ parseInput={(t) => parseFloat(t.replace(/px$/, ""))}
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-2 mb-3">
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.zoomMotionBlur")}
+ value={zoomMotionBlur}
+ defaultValue={DEFAULT_ZOOM_MOTION_BLUR}
+ min={0}
+ max={2}
+ step={0.05}
+ onChange={(v) => onZoomMotionBlurChange?.(v)}
+ formatValue={(v) => `${v.toFixed(2)}×`}
+ parseInput={(t) => parseFloat(t.replace(/×$/, ""))}
+ />
+ </div>
+
+ <div className="flex items-center justify-between p-2 rounded-lg bg-white/5 border border-white/5">
+ <div className="text-[10px] font-medium text-slate-300">
+ {tSettings("effects.connectZooms")}
+ </div>
+ <Switch
+ checked={connectZooms}
+ onCheckedChange={onConnectZoomsChange}
+ className="data-[state=checked]:bg-[#2563EB] scale-90"
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-2 mb-3">
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.cursorSize")}
+ value={cursorSize}
+ defaultValue={DEFAULT_CURSOR_SIZE}
+ min={0.5}
+ max={10}
+ step={0.05}
+ onChange={(v) => onCursorSizeChange?.(v)}
+ formatValue={(v) => `${v.toFixed(2)}×`}
+ parseInput={(t) => parseFloat(t.replace(/×$/, ""))}
+ />
+ </div>
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.cursorSmoothing")}
+ value={cursorSmoothing}
+ defaultValue={DEFAULT_CURSOR_SMOOTHING}
+ min={0}
+ max={2}
+ step={0.01}
+ onChange={(v) => onCursorSmoothingChange?.(v)}
+ formatValue={(v) => (v <= 0 ? "Off" : v.toFixed(2))}
+ parseInput={(t) => parseFloat(t)}
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-2 mb-3">
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.cursorMotionBlur")}
+ value={cursorMotionBlur}
+ defaultValue={DEFAULT_CURSOR_MOTION_BLUR}
+ min={0}
+ max={2}
+ step={0.05}
+ onChange={(v) => onCursorMotionBlurChange?.(v)}
+ formatValue={(v) => `${v.toFixed(2)}×`}
+ parseInput={(t) => parseFloat(t.replace(/×$/, ""))}
+ />
+ </div>
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.cursorClickBounce")}
+ value={cursorClickBounce}
+ defaultValue={DEFAULT_CURSOR_CLICK_BOUNCE}
+ min={0}
+ max={5}
+ step={0.05}
+ onChange={(v) => onCursorClickBounceChange?.(v)}
+ formatValue={(v) => `${v.toFixed(2)}×`}
+ parseInput={(t) => parseFloat(t.replace(/×$/, ""))}
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-2">
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.cursorSway")}
+ value={toCursorSwaySliderValue(cursorSway)}
+ defaultValue={toCursorSwaySliderValue(DEFAULT_CURSOR_SWAY)}
+ min={0}
+ max={toCursorSwaySliderValue(2)}
+ step={toCursorSwaySliderValue(0.05)}
+ onChange={(v) => onCursorSwayChange?.(fromCursorSwaySliderValue(v))}
+ formatValue={(v) => (v <= 0 ? "Off" : `${v.toFixed(2)}×`)}
+ parseInput={(t) => {
+ const normalized = t.trim().toLowerCase();
+ if (normalized === "off") {
+ return 0;
+ }
+
+ return parseFloat(t.replace(/×$/, ""));
+ }}
+ />
+ </div>
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.shadow")}
+ value={shadowIntensity}
+ defaultValue={0}
+ min={0}
+ max={1}
+ step={0.01}
+ onChange={(v) => onShadowChange?.(v)}
+ formatValue={(v) => `${Math.round(v * 100)}%`}
+ parseInput={(t) => parseFloat(t.replace(/%$/, "")) / 100}
+ />
+ </div>
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.roundness")}
+ value={borderRadius}
+ defaultValue={12.5}
+ min={0}
+ max={25}
+ step={0.5}
+ onChange={(v) => onBorderRadiusChange?.(v)}
+ formatValue={(v) => `${v}px`}
+ parseInput={(t) => parseFloat(t.replace(/px$/, ""))}
+ />
+ </div>
+ <div className="p-2 rounded-lg bg-white/5 border border-white/5">
+ <SliderControl
+ label={tSettings("effects.padding")}
+ value={padding}
+ defaultValue={50}
+ min={0}
+ max={100}
+ step={1}
+ onChange={(v) => onPaddingChange?.(v)}
+ formatValue={(v) => `${v}%`}
+ parseInput={(t) => parseFloat(t.replace(/%$/, ""))}
+ />
+ </div>
+ </div>
+
+ <Button
+ onClick={handleCropToggle}
+ variant="outline"
+ className="w-full mt-2 gap-1.5 bg-white/5 text-slate-200 border-white/10 hover:bg-white/10 hover:border-white/20 hover:text-white text-[10px] h-8 transition-all"
+ >
+ <Crop className="w-3 h-3" />
+ {tSettings("crop.title")}
+ </Button>
+ </AccordionContent>
+ </AccordionItem>
+
+ <AccordionItem
+ value="background"
+ className="border-white/5 rounded-xl bg-white/[0.02] px-3"
+ >
+ <AccordionTrigger className="py-2.5 hover:no-underline">
+ <div className="flex items-center gap-2">
+ <Palette className="w-4 h-4 text-[#2563EB]" />
+ <span className="text-xs font-medium">{tSettings("background.title")}</span>
+ </div>
+ </AccordionTrigger>
+ <AccordionContent className="pb-3">
+ <Tabs
+ value={backgroundTab}
+ onValueChange={(value) => setBackgroundTab(value as BackgroundTab)}
+ className="w-full"
+ >
+ <TabsList className="mb-2 bg-white/5 border border-white/5 p-0.5 w-full grid grid-cols-3 h-7 rounded-lg">
+ <TabsTrigger
+ value="image"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 text-[10px] py-1 rounded-md transition-all"
+ >
+ {tSettings("background.image")}
+ </TabsTrigger>
+ <TabsTrigger
+ value="color"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 text-[10px] py-1 rounded-md transition-all"
+ >
+ {tSettings("background.color")}
+ </TabsTrigger>
+ <TabsTrigger
+ value="gradient"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 text-[10px] py-1 rounded-md transition-all"
+ >
+ {tSettings("background.gradient")}
+ </TabsTrigger>
+ </TabsList>
+
+ <div className="max-h-[min(200px,25vh)] overflow-y-auto custom-scrollbar">
+ <TabsContent value="image" className="mt-0 space-y-2">
+ <input
+ type="file"
+ ref={fileInputRef}
+ onChange={handleImageUpload}
+ accept=".jpg,.jpeg,image/jpeg"
+ className="hidden"
+ />
+ <Button
+ onClick={() => fileInputRef.current?.click()}
+ variant="outline"
+ className="w-full gap-2 bg-white/5 text-slate-200 border-white/10 hover:bg-[#2563EB] hover:text-white hover:border-[#2563EB] transition-all h-7 text-[10px]"
+ >
+ <Upload className="w-3 h-3" />
+ {tSettings("background.uploadCustom")}
+ </Button>
+
+ <div className="grid grid-cols-7 gap-1.5">
+ {customImages.map((imageUrl, idx) => {
+ const isSelected = selected === imageUrl;
+ return (
+ <div
+ key={`custom-${idx}`}
+ className={cn(
+ "aspect-square w-9 h-9 rounded-md border-2 overflow-hidden cursor-pointer transition-all duration-200 relative group shadow-sm",
+ isSelected
+ ? "border-[#2563EB] ring-1 ring-[#2563EB]/30"
+ : "border-white/10 hover:border-[#2563EB]/40 opacity-80 hover:opacity-100 bg-white/5",
+ )}
+ style={{
+ backgroundImage: `url(${imageUrl})`,
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ }}
+ onClick={() => onWallpaperChange(imageUrl)}
+ role="button"
+ >
+ <button
+ onClick={(e) => handleRemoveCustomImage(imageUrl, e)}
+ className="absolute top-0.5 right-0.5 w-3 h-3 bg-red-500/90 hover:bg-red-500 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10"
+ >
+ <X className="w-2 h-2 text-white" />
+ </button>
+ </div>
+ );
+ })}
+
+ {(wallpaperPreviewPaths.length > 0
+ ? wallpaperPreviewPaths
+ : WALLPAPER_PATHS
+ ).map((previewPath, index) => {
+ const wallpaper = BUILT_IN_WALLPAPERS[index];
+ const wallpaperValue = WALLPAPER_PATHS[index] ?? previewPath;
+ const isSelected = (() => {
+ if (!selected) return false;
+ if (selected === wallpaperValue || selected === previewPath) return true;
+ try {
+ const clean = (s: string) =>
+ s.replace(/^file:\/\//, "").replace(/^\//, "");
+ if (clean(selected).endsWith(clean(wallpaperValue))) return true;
+ if (clean(wallpaperValue).endsWith(clean(selected))) return true;
+ if (clean(selected).endsWith(clean(previewPath))) return true;
+ if (clean(previewPath).endsWith(clean(selected))) return true;
+ } catch {
+ return false;
+ }
+ return false;
+ })();
+ return (
+ <div
+ key={wallpaperValue}
+ className={cn(
+ "aspect-square w-9 h-9 rounded-md border-2 overflow-hidden cursor-pointer transition-all duration-200 shadow-sm",
+ isSelected
+ ? "border-[#2563EB] ring-1 ring-[#2563EB]/30"
+ : "border-white/10 hover:border-[#2563EB]/40 opacity-80 hover:opacity-100 bg-white/5",
+ )}
+ aria-label={wallpaper?.label ?? `Wallpaper ${index + 1}`}
+ title={wallpaper?.label ?? `Wallpaper ${index + 1}`}
+ style={{
+ backgroundImage: `url(${previewPath})`,
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ }}
+ onClick={() => onWallpaperChange(wallpaperValue)}
+ role="button"
+ />
+ );
+ })}
+ </div>
+ </TabsContent>
+
+ <TabsContent value="color" className="mt-0">
+ <div className="p-1">
+ <Block
+ color={selectedColor}
+ colors={colorPalette}
+ onChange={(color) => {
+ setSelectedColor(color.hex);
+ onWallpaperChange(color.hex);
+ }}
+ style={{
+ width: "100%",
+ borderRadius: "8px",
+ }}
+ />
+ </div>
+ </TabsContent>
+
+ <TabsContent value="gradient" className="mt-0">
+ <div className="grid grid-cols-7 gap-1.5">
+ {GRADIENTS.map((g, idx) => (
+ <div
+ key={g}
+ className={cn(
+ "aspect-square w-9 h-9 rounded-md border-2 overflow-hidden cursor-pointer transition-all duration-200 shadow-sm",
+ gradient === g
+ ? "border-[#2563EB] ring-1 ring-[#2563EB]/30"
+ : "border-white/10 hover:border-[#2563EB]/40 opacity-80 hover:opacity-100 bg-white/5",
+ )}
+ style={{ background: g }}
+ aria-label={`Gradient ${idx + 1}`}
+ onClick={() => {
+ setGradient(g);
+ onWallpaperChange(g);
+ }}
+ role="button"
+ />
+ ))}
+ </div>
+ </TabsContent>
+ </div>
+ </Tabs>
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ </div>
+
+ {showCropModal && cropRegion && onCropChange && (
+ <>
+ <div
+ className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 animate-in fade-in duration-200"
+ onClick={handleCropCancel}
+ />
+ <div className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-[60] bg-[#09090b] rounded-2xl shadow-2xl border border-white/10 p-8 w-[90vw] max-w-5xl max-h-[90vh] overflow-auto animate-in zoom-in-95 duration-200">
+ <div className="flex items-center justify-between mb-6">
+ <div>
+ <span className="text-xl font-bold text-slate-200">{tSettings("crop.title")}</span>
+ <p className="text-sm text-slate-400 mt-2">{tSettings("crop.instruction")}</p>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={handleCropCancel}
+ className="hover:bg-white/10 text-slate-400 hover:text-white"
+ >
+ <X className="w-5 h-5" />
+ </Button>
+ </div>
+ <CropControl
+ videoElement={videoElement || null}
+ cropRegion={cropRegion}
+ onCropChange={onCropChange}
+ aspectRatio={aspectRatio}
+ />
+ <div className="mt-6 flex justify-end">
+ <Button
+ onClick={() => setShowCropModal(false)}
+ size="lg"
+ className="bg-[#2563EB] hover:bg-[#2563EB]/90 text-white"
+ >
+ {t("common.actions.done")}
+ </Button>
+ </div>
+ </div>
+ </>
+ )}
+
+ <div className="flex-shrink-0 p-4 pt-3 border-t border-white/5 bg-[#09090b]">
+ <div className="flex items-center gap-2 mb-3">
+ <button
+ onClick={() => onExportFormatChange?.("mp4")}
+ className={cn(
+ "flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg border transition-all text-xs font-medium",
+ exportFormat === "mp4"
+ ? "bg-[#2563EB]/10 border-[#2563EB]/50 text-white"
+ : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:text-slate-200",
+ )}
+ >
+ <Film className="w-3.5 h-3.5" />
+ {tSettings("export.mp4")}
+ </button>
+ <button
+ onClick={() => onExportFormatChange?.("gif")}
+ className={cn(
+ "flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg border transition-all text-xs font-medium",
+ exportFormat === "gif"
+ ? "bg-[#2563EB]/10 border-[#2563EB]/50 text-white"
+ : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:text-slate-200",
+ )}
+ >
+ <Image className="w-3.5 h-3.5" />
+ {tSettings("export.gif")}
+ </button>
+ </div>
+
+ {exportFormat === "mp4" && (
- <div className="mb-3 bg-white/5 border border-white/5 p-0.5 w-full grid grid-cols-3 h-7 rounded-lg">
++ <div className="mb-3 grid h-7 w-full grid-cols-4 rounded-lg border border-white/5 bg-white/5 p-0.5">
+ <button
+ onClick={() => onExportQualityChange?.("medium")}
+ className={cn(
+ "rounded-md transition-all text-[10px] font-medium",
+ exportQuality === "medium"
+ ? "bg-white text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
+ {tSettings("export.quality.low")}
+ </button>
+ <button
+ onClick={() => onExportQualityChange?.("good")}
+ className={cn(
+ "rounded-md transition-all text-[10px] font-medium",
+ exportQuality === "good"
+ ? "bg-white text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
+ {tSettings("export.quality.medium")}
+ </button>
++ <button
++ onClick={() => onExportQualityChange?.("high")}
++ className={cn(
++ "rounded-md transition-all text-[10px] font-medium",
++ exportQuality === "high"
++ ? "bg-white text-black"
++ : "text-slate-400 hover:text-slate-200",
++ )}
++ >
++ {tSettings("export.quality.high")}
++ </button>
+ <button
+ onClick={() => onExportQualityChange?.("source")}
+ className={cn(
+ "rounded-md transition-all text-[10px] font-medium",
+ exportQuality === "source"
+ ? "bg-white text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
- {tSettings("export.quality.high")}
++ {tSettings("export.quality.original")}
+ </button>
+ </div>
+ )}
+
+ {exportFormat === "gif" && (
+ <div className="mb-3 space-y-2">
+ <div className="flex items-center gap-2">
+ <div className="flex-1 bg-white/5 border border-white/5 p-0.5 grid grid-cols-4 h-7 rounded-lg">
+ {GIF_FRAME_RATES.map((rate) => (
+ <button
+ key={rate.value}
+ onClick={() => onGifFrameRateChange?.(rate.value)}
+ className={cn(
+ "rounded-md transition-all text-[10px] font-medium",
+ gifFrameRate === rate.value
+ ? "bg-white text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
+ {rate.value}
+ </button>
+ ))}
+ </div>
+ <div className="flex-1 bg-white/5 border border-white/5 p-0.5 grid grid-cols-3 h-7 rounded-lg">
+ {Object.entries(GIF_SIZE_PRESETS).map(([key, _preset]) => (
+ <button
+ key={key}
+ onClick={() => onGifSizePresetChange?.(key as GifSizePreset)}
+ className={cn(
+ "rounded-md transition-all text-[10px] font-medium",
+ gifSizePreset === key
+ ? "bg-white text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
+ {key === "original" ? "Orig" : key.charAt(0).toUpperCase() + key.slice(1, 3)}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-[10px] text-slate-500">
+ {gifOutputDimensions.width} × {gifOutputDimensions.height}px
+ </span>
+ <div className="flex items-center gap-2">
+ <span className="text-[10px] text-slate-400">{tSettings("export.loop")}</span>
+ <Switch
+ checked={gifLoop}
+ onCheckedChange={onGifLoopChange}
+ className="data-[state=checked]:bg-[#2563EB] scale-75"
+ />
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div className="grid grid-cols-2 gap-2 mb-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={onLoadProject}
+ className="h-8 text-[10px] font-medium gap-1.5 bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
+ >
+ <FolderOpen className="w-3.5 h-3.5" />
+ {tSettings("export.loadProject")}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={onSaveProject}
+ className="h-8 text-[10px] font-medium gap-1.5 bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
+ >
+ <Save className="w-3.5 h-3.5" />
+ {tSettings("export.saveProject")}
+ </Button>
+ </div>
+
+ <Button
+ type="button"
+ size="lg"
+ onClick={onExport}
+ className="w-full py-5 text-sm font-semibold flex items-center justify-center gap-2 bg-[#2563EB] text-white rounded-xl shadow-lg shadow-[#2563EB]/20 hover:bg-[#2563EB]/90 hover:scale-[1.02] active:scale-[0.98] transition-all duration-200"
+ >
+ <Download className="w-4 h-4" />
+ {tSettings("export.exportVideo", undefined, {
+ format: exportFormat === "gif" ? "GIF" : "Video",
+ })}
+ </Button>
+
+ <div className="flex gap-2 mt-3">
+ <button
+ type="button"
+ onClick={() => {
+ window.electronAPI?.openExternalUrl(
+ "https://github.com/webadderall/Recordly/issues/new/choose",
+ );
+ }}
+ className="flex-1 flex items-center justify-center gap-1.5 text-[10px] text-slate-500 hover:text-slate-300 py-1.5 transition-colors"
+ >
+ <Bug className="w-3 h-3 text-[#2563EB]" />
+ {tSettings("export.reportBug")}
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ window.electronAPI?.openExternalUrl("https://github.com/webadderall/Recordly");
+ }}
+ className="flex-1 flex items-center justify-center gap-1.5 text-[10px] text-slate-500 hover:text-slate-300 py-1.5 transition-colors"
+ >
+ <Star className="w-3 h-3 text-yellow-400" />
+ {tSettings("export.starOnGithub")}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --cc src/components/video-editor/VideoEditor.tsx
index da84af97,34bec02c..b79b2c99
--- a/src/components/video-editor/VideoEditor.tsx
+++ b/src/components/video-editor/VideoEditor.tsx
@@@ -6,78 -6,71 +6,81 @@@ import { toast } from "sonner"
import { Toaster } from "@/components/ui/sonner";
import { useI18n } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
-import { SUPPORTED_LOCALES } from "@/i18n/config";
import type { AppLocale } from "@/i18n/config";
-
-import VideoPlayback, { VideoPlaybackRef } from "./VideoPlayback";
-import PlaybackControls from "./PlaybackControls";
-import TimelineEditor from "./timeline/TimelineEditor";
-import { SettingsPanel } from "./SettingsPanel";
+import { SUPPORTED_LOCALES } from "@/i18n/config";
+import { getAssetPath } from "@/lib/assetPath";
+import {
- calculateOutputDimensions,
- type ExportFormat,
- type ExportProgress,
- type ExportQuality,
- type ExportSettings,
- GIF_SIZE_PRESETS,
- GifExporter,
- type GifFrameRate,
- type GifSizePreset,
- VideoExporter,
++ calculateOutputDimensions,
++ type ExportFormat,
++ type ExportProgress,
++ type ExportQuality,
++ type ExportSettings,
++ GIF_SIZE_PRESETS,
++ GifExporter,
++ type GifFrameRate,
++ type GifSizePreset,
++ VideoExporter,
+} from "@/lib/exporter";
+import { matchesShortcut } from "@/lib/shortcuts";
+import { DEFAULT_WALLPAPER_RELATIVE_PATH } from "@/lib/wallpapers";
+import { type AspectRatio, getAspectRatioValue } from "@/utils/aspectRatioUtils";
import { ExportDialog } from "./ExportDialog";
-import { DEFAULT_WALLPAPER_RELATIVE_PATH, WALLPAPER_PATHS } from "@/lib/wallpapers";
+import { loadEditorPreferences, saveEditorPreferences } from "./editorPreferences";
+import PlaybackControls from "./PlaybackControls";
import {
-- createProjectData,
-- deriveNextId,
-- fromFileUrl,
-- normalizeProjectEditor,
-- toFileUrl,
-- validateProjectData,
++ createProjectData,
++ deriveNextId,
++ fromFileUrl,
++ normalizeProjectEditor,
++ toFileUrl,
++ validateProjectData,
} from "./projectPersistence";
-
+import { SettingsPanel } from "./SettingsPanel";
+import TimelineEditor from "./timeline/TimelineEditor";
+import {
- detectInteractionCandidates,
- normalizeCursorTelemetry,
++ detectInteractionCandidates,
++ normalizeCursorTelemetry,
+} from "./timeline/zoomSuggestionUtils";
import {
- type AnnotationRegion,
- type CropRegion,
- type CursorTelemetryPoint,
- DEFAULT_CURSOR_CLICK_BOUNCE,
- DEFAULT_CURSOR_MOTION_BLUR,
- DEFAULT_CURSOR_SIZE,
- DEFAULT_CURSOR_SMOOTHING,
- DEFAULT_ZOOM_DEPTH,
- DEFAULT_ZOOM_MOTION_BLUR,
-- clampFocusToDepth,
- DEFAULT_CROP_REGION,
-- DEFAULT_ANNOTATION_POSITION,
-- DEFAULT_ANNOTATION_SIZE,
-- DEFAULT_ANNOTATION_STYLE,
-- DEFAULT_FIGURE_DATA,
-- DEFAULT_PLAYBACK_SPEED,
- DEFAULT_ZOOM_DEPTH,
- type FigureData,
- type PlaybackSpeed,
- type SpeedRegion,
- type TrimRegion,
-- type ZoomDepth,
-- type ZoomFocus,
-- type ZoomRegion,
- type CursorTelemetryPoint,
- type TrimRegion,
- type AnnotationRegion,
- type CropRegion,
- type FigureData,
- type SpeedRegion,
- type AudioRegion,
- type PlaybackSpeed,
++ type AnnotationRegion,
++ type AudioRegion,
++ type CropRegion,
++ type CursorTelemetryPoint,
++ clampFocusToDepth,
++ DEFAULT_ANNOTATION_POSITION,
++ DEFAULT_ANNOTATION_SIZE,
++ DEFAULT_ANNOTATION_STYLE,
++ DEFAULT_FIGURE_DATA,
++ DEFAULT_PLAYBACK_SPEED,
++ DEFAULT_ZOOM_DEPTH,
++ type FigureData,
++ type PlaybackSpeed,
++ type SpeedRegion,
++ type TrimRegion,
++ type ZoomDepth,
++ type ZoomFocus,
++ type ZoomRegion,
} from "./types";
-import { VideoExporter, GifExporter, type ExportProgress, type ExportQuality, type ExportSettings, type ExportFormat, type GifFrameRate, type GifSizePreset, GIF_SIZE_PRESETS, calculateOutputDimensions } from "@/lib/exporter";
-import { type AspectRatio, getAspectRatioValue } from "@/utils/aspectRatioUtils";
-import { getAssetPath } from "@/lib/assetPath";
-import { matchesShortcut } from "@/lib/shortcuts";
-import { detectInteractionCandidates, normalizeCursorTelemetry } from "./timeline/zoomSuggestionUtils";
-import { buildLoopedCursorTelemetry, getDisplayedTimelineWindowMs } from "./videoPlayback/cursorLoopTelemetry";
+import VideoPlayback, { VideoPlaybackRef } from "./VideoPlayback";
+import {
- buildLoopedCursorTelemetry,
- getDisplayedTimelineWindowMs,
++ buildLoopedCursorTelemetry,
++ getDisplayedTimelineWindowMs,
+} from "./videoPlayback/cursorLoopTelemetry";
import { findDominantRegion } from "./videoPlayback/zoomRegionUtils";
const LOOP_CURSOR_END_WINDOW_MS = 670;
type EditorHistorySnapshot = {
-- zoomRegions: ZoomRegion[];
-- trimRegions: TrimRegion[];
-- speedRegions: SpeedRegion[];
-- annotationRegions: AnnotationRegion[];
- audioRegions: AudioRegion[];
-- selectedZoomId: string | null;
-- selectedTrimId: string | null;
-- selectedSpeedId: string | null;
-- selectedAnnotationId: string | null;
- selectedAudioId: string | null;
++ zoomRegions: ZoomRegion[];
++ trimRegions: TrimRegion[];
++ speedRegions: SpeedRegion[];
++ annotationRegions: AnnotationRegion[];
++ audioRegions: AudioRegion[];
++ selectedZoomId: string | null;
++ selectedTrimId: string | null;
++ selectedSpeedId: string | null;
++ selectedAnnotationId: string | null;
++ selectedAudioId: string | null;
};
type PendingExportSave = {
@@@ -86,1979 -79,1920 +89,2141 @@@
};
function LanguageSwitcher() {
-- const { locale, setLocale, t } = useI18n();
- const idx = SUPPORTED_LOCALES.indexOf(locale as (typeof SUPPORTED_LOCALES)[number]);
- const idx = SUPPORTED_LOCALES.indexOf(locale as typeof SUPPORTED_LOCALES[number]);
-- const next = SUPPORTED_LOCALES[(idx + 1) % SUPPORTED_LOCALES.length] as AppLocale;
- const labels: Record<string, string> = {
- en: "EN",
- es: "ES",
- "zh-CN": "中文",
- };
- const labels: Record<string, string> = { en: "EN", es: "ES", "zh-CN": "中文" };
-- return (
-- <button
-- type="button"
-- onClick={() => setLocale(next)}
-- className="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-white/90 transition hover:bg-white/8 hover:text-white cursor-pointer"
-- title={t("common.app.language", "Language")}
-- aria-label={t("common.app.language", "Language")}
-- >
-- <Languages className="h-4 w-4" />
-- <span className="text-xs font-normal">{labels[locale] ?? locale.toUpperCase()}</span>
-- </button>
-- );
++ const { locale, setLocale, t } = useI18n();
++ const idx = SUPPORTED_LOCALES.indexOf(locale as (typeof SUPPORTED_LOCALES)[number]);
++ const next = SUPPORTED_LOCALES[(idx + 1) % SUPPORTED_LOCALES.length] as AppLocale;
++ const labels: Record<string, string> = {
++ en: "EN",
++ es: "ES",
++ "zh-CN": "中文",
++ };
++ return (
++ <button
++ type="button"
++ onClick={() => setLocale(next)}
++ className="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-white/90 transition hover:bg-white/8 hover:text-white cursor-pointer"
++ title={t("common.app.language", "Language")}
++ aria-label={t("common.app.language", "Language")}
++ >
++ <Languages className="h-4 w-4" />
++ <span className="text-xs font-normal">{labels[locale] ?? locale.toUpperCase()}</span>
++ </button>
++ );
}
export default function VideoEditor() {
-- const { t } = useI18n();
- 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 [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 [connectZooms, setConnectZooms] = useState(initialEditorPreferences.connectZooms);
- const [showCursor, setShowCursor] = useState(initialEditorPreferences.showCursor);
- const [loopCursor, setLoopCursor] = useState(initialEditorPreferences.loopCursor);
- const [cursorSize, setCursorSize] = useState(initialEditorPreferences.cursorSize);
- const [cursorSmoothing, setCursorSmoothing] = useState(initialEditorPreferences.cursorSmoothing);
- const [cursorMotionBlur, setCursorMotionBlur] = useState(
- initialEditorPreferences.cursorMotionBlur,
- );
- const [cursorClickBounce, setCursorClickBounce] = useState(
- initialEditorPreferences.cursorClickBounce,
- );
- const [cursorSway, setCursorSway] = useState(initialEditorPreferences.cursorSway);
- const [borderRadius, setBorderRadius] = useState(initialEditorPreferences.borderRadius);
- const [padding, setPadding] = useState(initialEditorPreferences.padding);
- const [cropRegion, setCropRegion] = useState<CropRegion>(initialEditorPreferences.cropRegion);
- const [wallpaper, setWallpaper] = useState<string>(WALLPAPER_PATHS[0]);
- const [shadowIntensity, setShadowIntensity] = useState(0.67);
- const [backgroundBlur, setBackgroundBlur] = useState(0);
- const [zoomMotionBlur, setZoomMotionBlur] = useState(DEFAULT_ZOOM_MOTION_BLUR);
- const [connectZooms, setConnectZooms] = useState(true);
- const [showCursor, setShowCursor] = useState(true);
- const [loopCursor, setLoopCursor] = useState(false);
- const [cursorSize, setCursorSize] = useState(DEFAULT_CURSOR_SIZE);
- const [cursorSmoothing, setCursorSmoothing] = useState(DEFAULT_CURSOR_SMOOTHING);
- const [cursorMotionBlur, setCursorMotionBlur] = useState(DEFAULT_CURSOR_MOTION_BLUR);
- const [cursorClickBounce, setCursorClickBounce] = useState(DEFAULT_CURSOR_CLICK_BOUNCE);
- const [borderRadius, setBorderRadius] = useState(12.5);
- const [padding, setPadding] = useState(50);
- const [cropRegion, setCropRegion] = useState<CropRegion>(DEFAULT_CROP_REGION);
-- const [zoomRegions, setZoomRegions] = useState<ZoomRegion[]>([]);
-- const [cursorTelemetry, setCursorTelemetry] = useState<CursorTelemetryPoint[]>([]);
-- const [selectedZoomId, setSelectedZoomId] = useState<string | null>(null);
-- const [trimRegions, setTrimRegions] = useState<TrimRegion[]>([]);
-- const [selectedTrimId, setSelectedTrimId] = useState<string | null>(null);
-- const [speedRegions, setSpeedRegions] = useState<SpeedRegion[]>([]);
-- const [selectedSpeedId, setSelectedSpeedId] = useState<string | null>(null);
-- const [annotationRegions, setAnnotationRegions] = useState<AnnotationRegion[]>([]);
-- const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);
- const [audioRegions, setAudioRegions] = useState<AudioRegion[]>([]);
- const [selectedAudioId, setSelectedAudioId] = useState<string | null>(null);
-- const [isExporting, setIsExporting] = useState(false);
-- const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);
-- const [exportError, setExportError] = useState<string | null>(null);
-- const [showExportDialog, setShowExportDialog] = useState(false);
- const [aspectRatio, setAspectRatio] = useState<AspectRatio>(initialEditorPreferences.aspectRatio);
- const [exportQuality, setExportQuality] = useState<ExportQuality>(
- initialEditorPreferences.exportQuality,
- );
- 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 [aspectRatio, setAspectRatio] = useState<AspectRatio>('16:9');
- const [exportQuality, setExportQuality] = useState<ExportQuality>('good');
- const [exportFormat, setExportFormat] = useState<ExportFormat>('mp4');
- const [gifFrameRate, setGifFrameRate] = useState<GifFrameRate>(15);
- const [gifLoop, setGifLoop] = useState(true);
- const [gifSizePreset, setGifSizePreset] = useState<GifSizePreset>('medium');
-- const [exportedFilePath, setExportedFilePath] = useState<string | undefined>(undefined);
-- const [hasPendingExportSave, setHasPendingExportSave] = useState(false);
-- const [lastSavedSnapshot, setLastSavedSnapshot] = useState<string | null>(null);
--
-- const videoPlaybackRef = useRef<VideoPlaybackRef>(null);
-- const nextZoomIdRef = useRef(1);
-- const nextTrimIdRef = useRef(1);
-- const nextSpeedIdRef = useRef(1);
- const nextAudioIdRef = useRef(1);
--
-- const { shortcuts, isMac } = useShortcuts();
-- const nextAnnotationIdRef = useRef(1);
-- const nextAnnotationZIndexRef = useRef(1); // Track z-index for stacking order
-- const exporterRef = useRef<VideoExporter | null>(null);
-- const autoSuggestedVideoPathRef = useRef<string | null>(null);
-- const historyPastRef = useRef<EditorHistorySnapshot[]>([]);
-- const historyFutureRef = useRef<EditorHistorySnapshot[]>([]);
-- const historyCurrentRef = useRef<EditorHistorySnapshot | null>(null);
-- const applyingHistoryRef = useRef(false);
-- const pendingExportSaveRef = useRef<PendingExportSave | null>(null);
--
-- const cloneSnapshot = useCallback((snapshot: EditorHistorySnapshot): EditorHistorySnapshot => {
-- return {
-- zoomRegions: JSON.parse(JSON.stringify(snapshot.zoomRegions)),
-- trimRegions: JSON.parse(JSON.stringify(snapshot.trimRegions)),
-- speedRegions: JSON.parse(JSON.stringify(snapshot.speedRegions)),
-- annotationRegions: JSON.parse(JSON.stringify(snapshot.annotationRegions)),
- audioRegions: JSON.parse(JSON.stringify(snapshot.audioRegions)),
-- selectedZoomId: snapshot.selectedZoomId,
-- selectedTrimId: snapshot.selectedTrimId,
-- selectedSpeedId: snapshot.selectedSpeedId,
-- selectedAnnotationId: snapshot.selectedAnnotationId,
- selectedAudioId: snapshot.selectedAudioId,
-- };
-- }, []);
--
-- const buildHistorySnapshot = useCallback((): EditorHistorySnapshot => {
-- return {
-- zoomRegions,
-- trimRegions,
-- speedRegions,
-- annotationRegions,
- audioRegions,
-- selectedZoomId,
-- selectedTrimId,
-- selectedSpeedId,
-- selectedAnnotationId,
- selectedAudioId,
-- };
-- }, [
-- zoomRegions,
-- trimRegions,
-- speedRegions,
-- annotationRegions,
- audioRegions,
-- selectedZoomId,
-- selectedTrimId,
-- selectedSpeedId,
-- selectedAnnotationId,
- selectedAudioId,
-- ]);
--
- const applyHistorySnapshot = useCallback(
- (snapshot: EditorHistorySnapshot) => {
- applyingHistoryRef.current = true;
- const cloned = cloneSnapshot(snapshot);
- setZoomRegions(cloned.zoomRegions);
- setTrimRegions(cloned.trimRegions);
- setSpeedRegions(cloned.speedRegions);
- setAnnotationRegions(cloned.annotationRegions);
- setSelectedZoomId(cloned.selectedZoomId);
- setSelectedTrimId(cloned.selectedTrimId);
- setSelectedSpeedId(cloned.selectedSpeedId);
- setSelectedAnnotationId(cloned.selectedAnnotationId);
- const applyHistorySnapshot = useCallback((snapshot: EditorHistorySnapshot) => {
- applyingHistoryRef.current = true;
- const cloned = cloneSnapshot(snapshot);
- setZoomRegions(cloned.zoomRegions);
- setTrimRegions(cloned.trimRegions);
- setSpeedRegions(cloned.speedRegions);
- setAnnotationRegions(cloned.annotationRegions);
- setAudioRegions(cloned.audioRegions);
- setSelectedZoomId(cloned.selectedZoomId);
- setSelectedTrimId(cloned.selectedTrimId);
- setSelectedSpeedId(cloned.selectedSpeedId);
- setSelectedAnnotationId(cloned.selectedAnnotationId);
- setSelectedAudioId(cloned.selectedAudioId);
--
- nextZoomIdRef.current = deriveNextId(
- "zoom",
- cloned.zoomRegions.map((region) => region.id),
- );
- nextTrimIdRef.current = deriveNextId(
- "trim",
- cloned.trimRegions.map((region) => region.id),
- );
- nextSpeedIdRef.current = deriveNextId(
- "speed",
- cloned.speedRegions.map((region) => region.id),
- );
- nextAnnotationIdRef.current = deriveNextId(
- "annotation",
- cloned.annotationRegions.map((region) => region.id),
- );
- nextAnnotationZIndexRef.current =
- cloned.annotationRegions.reduce((max, region) => Math.max(max, region.zIndex), 0) + 1;
- },
- [cloneSnapshot],
- );
- nextZoomIdRef.current = deriveNextId("zoom", cloned.zoomRegions.map((region) => region.id));
- nextTrimIdRef.current = deriveNextId("trim", cloned.trimRegions.map((region) => region.id));
- nextSpeedIdRef.current = deriveNextId("speed", cloned.speedRegions.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;
- }, [cloneSnapshot]);
--
-- const handleUndo = useCallback(() => {
-- if (historyPastRef.current.length === 0) return;
--
-- const current = historyCurrentRef.current ?? cloneSnapshot(buildHistorySnapshot());
-- const previous = historyPastRef.current.pop();
-- if (!previous) return;
--
-- historyFutureRef.current.push(cloneSnapshot(current));
-- historyCurrentRef.current = cloneSnapshot(previous);
-- applyHistorySnapshot(previous);
-- }, [applyHistorySnapshot, buildHistorySnapshot, cloneSnapshot]);
--
-- const handleRedo = useCallback(() => {
-- if (historyFutureRef.current.length === 0) return;
--
-- const current = historyCurrentRef.current ?? cloneSnapshot(buildHistorySnapshot());
-- const next = historyFutureRef.current.pop();
-- if (!next) return;
--
-- historyPastRef.current.push(cloneSnapshot(current));
-- historyCurrentRef.current = cloneSnapshot(next);
-- applyHistorySnapshot(next);
-- }, [applyHistorySnapshot, buildHistorySnapshot, cloneSnapshot]);
--
-- const applyLoadedProject = useCallback(async (candidate: unknown, path?: string | null) => {
-- if (!validateProjectData(candidate)) {
-- return false;
-- }
--
-- const project = candidate;
-- const sourcePath = fromFileUrl(project.videoPath);
-- const normalizedEditor = normalizeProjectEditor(project.editor);
--
-- try {
-- videoPlaybackRef.current?.pause();
-- } catch {
-- // no-op
-- }
-- setIsPlaying(false);
-- setCurrentTime(0);
-- setDuration(0);
--
-- setError(null);
-- setVideoSourcePath(sourcePath);
-- setVideoPath(toFileUrl(sourcePath));
-- setCurrentProjectPath(path ?? null);
--
-- setWallpaper(normalizedEditor.wallpaper);
-- setShadowIntensity(normalizedEditor.shadowIntensity);
-- setBackgroundBlur(normalizedEditor.backgroundBlur);
-- setZoomMotionBlur(normalizedEditor.zoomMotionBlur);
-- setConnectZooms(normalizedEditor.connectZooms);
-- setShowCursor(normalizedEditor.showCursor);
-- setLoopCursor(normalizedEditor.loopCursor);
-- setCursorSize(normalizedEditor.cursorSize);
-- setCursorSmoothing(normalizedEditor.cursorSmoothing);
-- setCursorMotionBlur(normalizedEditor.cursorMotionBlur);
-- setCursorClickBounce(normalizedEditor.cursorClickBounce);
- setCursorSway(normalizedEditor.cursorSway);
-- setBorderRadius(normalizedEditor.borderRadius);
-- setPadding(normalizedEditor.padding);
-- setCropRegion(normalizedEditor.cropRegion);
-- setZoomRegions(normalizedEditor.zoomRegions);
-- setTrimRegions(normalizedEditor.trimRegions);
-- setSpeedRegions(normalizedEditor.speedRegions);
-- setAnnotationRegions(normalizedEditor.annotationRegions);
- setAudioRegions(normalizedEditor.audioRegions);
-- setAspectRatio(normalizedEditor.aspectRatio);
-- setExportQuality(normalizedEditor.exportQuality);
-- setExportFormat(normalizedEditor.exportFormat);
-- setGifFrameRate(normalizedEditor.gifFrameRate);
-- setGifLoop(normalizedEditor.gifLoop);
-- setGifSizePreset(normalizedEditor.gifSizePreset);
--
-- setSelectedZoomId(null);
-- setSelectedTrimId(null);
-- setSelectedSpeedId(null);
-- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
--
- nextZoomIdRef.current = deriveNextId(
- "zoom",
- normalizedEditor.zoomRegions.map((region) => region.id),
- );
- nextTrimIdRef.current = deriveNextId(
- "trim",
- normalizedEditor.trimRegions.map((region) => region.id),
- );
- nextSpeedIdRef.current = deriveNextId(
- "speed",
- normalizedEditor.speedRegions.map((region) => region.id),
- );
- nextZoomIdRef.current = deriveNextId("zoom", normalizedEditor.zoomRegions.map((region) => region.id));
- nextTrimIdRef.current = deriveNextId("trim", normalizedEditor.trimRegions.map((region) => region.id));
- nextSpeedIdRef.current = deriveNextId("speed", normalizedEditor.speedRegions.map((region) => region.id));
- 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;
- normalizedEditor.annotationRegions.reduce((max, region) => Math.max(max, region.zIndex), 0) + 1;
--
-- setLastSavedSnapshot(JSON.stringify(createProjectData(sourcePath, normalizedEditor)));
-- return true;
-- }, []);
--
-- const currentProjectSnapshot = useMemo(() => {
-- const sourcePath = videoSourcePath ?? (videoPath ? fromFileUrl(videoPath) : null);
-- if (!sourcePath) {
-- return null;
-- }
-- return JSON.stringify(
-- createProjectData(sourcePath, {
-- wallpaper,
-- shadowIntensity,
-- backgroundBlur,
-- zoomMotionBlur,
-- connectZooms,
-- showCursor,
-- loopCursor,
-- cursorSize,
-- cursorSmoothing,
-- cursorMotionBlur,
-- cursorClickBounce,
- cursorSway,
-- borderRadius,
-- padding,
-- cropRegion,
-- zoomRegions,
-- trimRegions,
-- speedRegions,
-- annotationRegions,
- audioRegions,
-- aspectRatio,
-- exportQuality,
-- exportFormat,
-- gifFrameRate,
-- gifLoop,
-- gifSizePreset,
-- }),
-- );
-- }, [
-- videoPath,
-- videoSourcePath,
-- wallpaper,
-- shadowIntensity,
-- backgroundBlur,
-- zoomMotionBlur,
-- connectZooms,
-- showCursor,
-- loopCursor,
-- cursorSize,
-- cursorSmoothing,
-- cursorMotionBlur,
-- cursorClickBounce,
- cursorSway,
-- borderRadius,
-- padding,
-- cropRegion,
-- zoomRegions,
-- trimRegions,
-- speedRegions,
- audioRegions,
-- annotationRegions,
-- aspectRatio,
-- exportQuality,
-- exportFormat,
-- gifFrameRate,
-- gifLoop,
-- gifSizePreset,
-- ]);
--
-- useEffect(() => {
-- const snapshot = cloneSnapshot(buildHistorySnapshot());
--
-- if (!historyCurrentRef.current) {
-- historyCurrentRef.current = snapshot;
-- return;
-- }
--
-- if (applyingHistoryRef.current) {
-- historyCurrentRef.current = snapshot;
-- applyingHistoryRef.current = false;
-- return;
-- }
--
-- const currentSerialized = JSON.stringify(historyCurrentRef.current);
-- const nextSerialized = JSON.stringify(snapshot);
-- if (currentSerialized === nextSerialized) {
-- return;
-- }
--
-- historyPastRef.current.push(cloneSnapshot(historyCurrentRef.current));
-- if (historyPastRef.current.length > 100) {
-- historyPastRef.current.shift();
-- }
-- historyCurrentRef.current = snapshot;
-- historyFutureRef.current = [];
-- }, [buildHistorySnapshot, cloneSnapshot]);
--
-- const hasUnsavedChanges = Boolean(
-- currentProjectPath &&
-- currentProjectSnapshot &&
-- lastSavedSnapshot &&
-- currentProjectSnapshot !== lastSavedSnapshot,
-- );
--
-- useEffect(() => {
-- async function loadInitialData() {
-- try {
-- const currentProjectResult = await window.electronAPI.loadCurrentProjectFile();
-- if (currentProjectResult.success && currentProjectResult.project) {
-- const restored = await applyLoadedProject(
-- currentProjectResult.project,
-- currentProjectResult.path ?? null,
-- );
-- if (restored) {
-- return;
-- }
-- }
--
-- const result = await window.electronAPI.getCurrentVideoPath();
-- if (result.success && result.path) {
-- const sourcePath = fromFileUrl(result.path);
-- setVideoSourcePath(sourcePath);
-- setVideoPath(toFileUrl(sourcePath));
-- setCurrentProjectPath(null);
-- setLastSavedSnapshot(null);
-- } else {
-- setError("No video to load. Please record or select a video.");
-- }
-- } catch (err) {
-- setError("Error loading video: " + String(err));
-- } finally {
-- setLoading(false);
-- }
-- }
--
-- loadInitialData();
-- }, [applyLoadedProject]);
--
- useEffect(() => {
- saveEditorPreferences({
- const saveProject = useCallback(async (forceSaveAs: boolean) => {
- if (!videoPath) {
- toast.error('No video loaded');
- return;
- }
-
- const sourcePath = videoSourcePath ?? fromFileUrl(videoPath);
- if (!sourcePath) {
- toast.error('Unable to determine source video path');
- return;
- }
-
- const projectData = createProjectData(sourcePath, {
-- wallpaper,
-- shadowIntensity,
-- backgroundBlur,
-- zoomMotionBlur,
-- connectZooms,
-- showCursor,
-- loopCursor,
-- cursorSize,
-- cursorSmoothing,
-- cursorMotionBlur,
-- cursorClickBounce,
- cursorSway,
-- borderRadius,
-- padding,
-- cropRegion,
- zoomRegions,
- trimRegions,
- speedRegions,
- annotationRegions,
- audioRegions,
-- aspectRatio,
-- exportQuality,
-- exportFormat,
-- gifFrameRate,
-- gifLoop,
-- gifSizePreset,
-- });
-
- const fileNameBase = sourcePath.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, '') || `project-${Date.now()}`;
- const projectSnapshot = JSON.stringify(projectData);
- const result = await window.electronAPI.saveProjectFile(
- projectData,
- fileNameBase,
- forceSaveAs ? undefined : currentProjectPath ?? undefined,
- );
-
- if (result.canceled) {
- toast.info("Project save canceled");
- return;
- }
-
- if (!result.success) {
- toast.error(result.message || 'Failed to save project');
- return;
- }
-
- if (result.path) {
- setCurrentProjectPath(result.path);
- }
- setLastSavedSnapshot(projectSnapshot);
-
- toast.success(`Project saved to ${result.path}`);
-- }, [
- videoPath,
- videoSourcePath,
- currentProjectPath,
-- wallpaper,
-- shadowIntensity,
-- backgroundBlur,
-- zoomMotionBlur,
-- connectZooms,
-- showCursor,
-- loopCursor,
-- cursorSize,
-- cursorSmoothing,
-- cursorMotionBlur,
-- cursorClickBounce,
- cursorSway,
-- borderRadius,
-- padding,
-- cropRegion,
- zoomRegions,
- trimRegions,
- speedRegions,
- annotationRegions,
-- aspectRatio,
-- exportQuality,
-- exportFormat,
-- gifFrameRate,
-- gifLoop,
-- gifSizePreset,
-- ]);
-
- const saveProject = useCallback(
- async (forceSaveAs: boolean) => {
- if (!videoPath) {
- toast.error("No video loaded");
- return;
- }
-
- const sourcePath = videoSourcePath ?? fromFileUrl(videoPath);
- if (!sourcePath) {
- toast.error("Unable to determine source video path");
- return;
- }
-
- const projectData = createProjectData(sourcePath, {
- wallpaper,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- connectZooms,
- showCursor,
- loopCursor,
- cursorSize,
- cursorSmoothing,
- cursorMotionBlur,
- cursorClickBounce,
- cursorSway,
- borderRadius,
- padding,
- cropRegion,
- zoomRegions,
- trimRegions,
- speedRegions,
- annotationRegions,
- aspectRatio,
- exportQuality,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- });
-
- const fileNameBase =
- sourcePath
- .split(/[\\/]/)
- .pop()
- ?.replace(/\.[^.]+$/, "") || `project-${Date.now()}`;
- const projectSnapshot = JSON.stringify(projectData);
- const result = await window.electronAPI.saveProjectFile(
- projectData,
- fileNameBase,
- forceSaveAs ? undefined : (currentProjectPath ?? undefined),
- );
-
- if (result.canceled) {
- toast.info("Project save canceled");
- return;
- }
-
- if (!result.success) {
- toast.error(result.message || "Failed to save project");
- return;
- }
-
- if (result.path) {
- setCurrentProjectPath(result.path);
- }
- setLastSavedSnapshot(projectSnapshot);
-
- toast.success(`Project saved to ${result.path}`);
- },
- [
- videoPath,
- videoSourcePath,
- currentProjectPath,
- wallpaper,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- connectZooms,
- showCursor,
- loopCursor,
- cursorSize,
- cursorSmoothing,
- cursorMotionBlur,
- cursorClickBounce,
- cursorSway,
- borderRadius,
- padding,
- cropRegion,
- zoomRegions,
- trimRegions,
- speedRegions,
- annotationRegions,
- aspectRatio,
- exportQuality,
- exportFormat,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- ],
- );
--
-- useEffect(() => {
-- const handleBeforeUnload = (event: BeforeUnloadEvent) => {
-- if (!hasUnsavedChanges) {
-- return;
-- }
--
-- event.preventDefault();
- event.returnValue = "";
- event.returnValue = '';
-- };
--
- window.addEventListener("beforeunload", handleBeforeUnload);
- return () => window.removeEventListener("beforeunload", handleBeforeUnload);
- window.addEventListener('beforeunload', handleBeforeUnload);
- return () => window.removeEventListener('beforeunload', handleBeforeUnload);
-- }, [hasUnsavedChanges]);
--
-- useEffect(() => {
-- window.electronAPI.setHasUnsavedChanges(hasUnsavedChanges);
-- }, [hasUnsavedChanges]);
--
-- useEffect(() => {
-- const cleanup = window.electronAPI.onRequestSaveBeforeClose(async () => {
-- await saveProject(false);
-- });
--
-- return () => cleanup?.();
-- }, [saveProject]);
--
-- const handleSaveProject = useCallback(async () => {
-- await saveProject(false);
-- }, [saveProject]);
--
-- const handleSaveProjectAs = useCallback(async () => {
-- await saveProject(true);
-- }, [saveProject]);
--
-- const handleLoadProject = useCallback(async () => {
-- const result = await window.electronAPI.loadProjectFile();
--
-- if (result.canceled) {
-- return;
-- }
--
-- if (!result.success) {
- toast.error(result.message || "Failed to load project");
- 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");
- toast.error('Invalid project file format');
-- return;
-- }
--
-- toast.success(`Project loaded from ${result.path}`);
-- }, [applyLoadedProject]);
--
-- useEffect(() => {
-- const removeLoadListener = window.electronAPI.onMenuLoadProject(handleLoadProject);
-- const removeSaveListener = window.electronAPI.onMenuSaveProject(handleSaveProject);
-- const removeSaveAsListener = window.electronAPI.onMenuSaveProjectAs(handleSaveProjectAs);
--
-- return () => {
-- removeLoadListener?.();
-- removeSaveListener?.();
-- removeSaveAsListener?.();
-- };
-- }, [handleLoadProject, handleSaveProject, handleSaveProjectAs]);
--
-- useEffect(() => {
-- let mounted = true;
--
-- async function loadCursorTelemetry() {
-- if (!videoPath) {
-- if (mounted) {
-- setCursorTelemetry([]);
-- }
-- return;
-- }
--
-- try {
-- const result = await window.electronAPI.getCursorTelemetry(fromFileUrl(videoPath));
-- if (mounted) {
-- setCursorTelemetry(result.success ? result.samples : []);
-- }
-- } catch (telemetryError) {
- console.warn("Unable to load cursor telemetry:", telemetryError);
- console.warn('Unable to load cursor telemetry:', telemetryError);
-- if (mounted) {
-- setCursorTelemetry([]);
-- }
-- }
-- }
--
-- loadCursorTelemetry();
--
-- return () => {
-- mounted = false;
-- };
-- }, [videoPath]);
--
-- 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,
- );
- 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
- ) {
- if (normalizedCursorTelemetry.length < 2 || displayedTimelineWindow.endMs <= displayedTimelineWindow.startMs) {
-- return normalizedCursorTelemetry;
-- }
--
-- return buildLoopedCursorTelemetry(
-- normalizedCursorTelemetry,
-- displayedTimelineWindow.endMs,
-- displayedTimelineWindow.startMs,
-- );
-- }, [loopCursor, normalizedCursorTelemetry, displayedTimelineWindow]);
--
-- const effectiveZoomRegions = useMemo(() => {
-- if (!loopCursor || zoomRegions.length === 0) {
-- return zoomRegions;
-- }
--
-- if (displayedTimelineWindow.endMs <= displayedTimelineWindow.startMs) {
-- return zoomRegions;
-- }
--
- const dominantAtStart = findDominantRegion(zoomRegions, displayedTimelineWindow.startMs, {
- connectZooms,
- }).region;
- const dominantAtStart = findDominantRegion(zoomRegions, displayedTimelineWindow.startMs, { connectZooms }).region;
-- if (!dominantAtStart) {
-- return zoomRegions;
-- }
--
- const endWindowStartMs = Math.max(
- displayedTimelineWindow.startMs,
- displayedTimelineWindow.endMs - LOOP_CURSOR_END_WINDOW_MS,
- );
- const endWindowStartMs = Math.max(displayedTimelineWindow.startMs, displayedTimelineWindow.endMs - LOOP_CURSOR_END_WINDOW_MS);
-- const loopEndRegion: ZoomRegion = {
-- id: `${dominantAtStart.id}__loop-end-sync`,
-- startMs: endWindowStartMs,
-- endMs: displayedTimelineWindow.endMs,
-- depth: dominantAtStart.depth,
-- focus: {
-- cx: dominantAtStart.focus.cx,
-- cy: dominantAtStart.focus.cy,
-- },
-- };
--
- return [...zoomRegions.filter((region) => region.id !== loopEndRegion.id), loopEndRegion];
- return [
- ...zoomRegions.filter((region) => region.id !== loopEndRegion.id),
- loopEndRegion,
- ];
-- }, [loopCursor, zoomRegions, displayedTimelineWindow, connectZooms]);
--
-- useEffect(() => {
- if (
- !videoPath ||
- duration <= 0 ||
- zoomRegions.length > 0 ||
- normalizedCursorTelemetry.length < 2
- ) {
- if (!videoPath || duration <= 0 || zoomRegions.length > 0 || normalizedCursorTelemetry.length < 2) {
-- return;
-- }
--
-- if (autoSuggestedVideoPathRef.current === videoPath) {
-- return;
-- }
--
-- const totalMs = Math.max(0, Math.round(duration * 1000));
-- if (totalMs <= 0) {
-- return;
-- }
--
-- const candidates = detectInteractionCandidates(normalizedCursorTelemetry);
-- if (candidates.length === 0) {
-- autoSuggestedVideoPathRef.current = videoPath;
-- return;
-- }
--
-- const DEFAULT_DURATION_MS = 1100;
-- const MIN_SPACING_MS = 1800;
-- const sortedCandidates = [...candidates].sort((a, b) => b.strength - a.strength);
-- const acceptedCenters: number[] = [];
--
-- setZoomRegions((prev) => {
-- if (prev.length > 0) {
-- return prev;
-- }
--
-- const reservedSpans: Array<{ start: number; end: number }> = [];
-- const additions: ZoomRegion[] = [];
-- let nextId = nextZoomIdRef.current;
--
-- sortedCandidates.forEach((candidate) => {
-- const tooCloseToAccepted = acceptedCenters.some(
-- (center) => Math.abs(center - candidate.centerTimeMs) < MIN_SPACING_MS,
-- );
-- if (tooCloseToAccepted) {
-- return;
-- }
--
-- const centeredStart = Math.round(candidate.centerTimeMs - DEFAULT_DURATION_MS / 2);
-- const startMs = Math.max(0, Math.min(centeredStart, totalMs - DEFAULT_DURATION_MS));
-- const endMs = Math.min(totalMs, startMs + DEFAULT_DURATION_MS);
--
- const hasOverlap = reservedSpans.some((span) => endMs > span.start && startMs < span.end);
- const hasOverlap = reservedSpans.some(
- (span) => endMs > span.start && startMs < span.end,
- );
-- if (hasOverlap) {
-- return;
-- }
--
-- additions.push({
-- id: `zoom-${nextId++}`,
-- startMs,
-- endMs,
-- depth: DEFAULT_ZOOM_DEPTH,
-- focus: clampFocusToDepth(candidate.focus, DEFAULT_ZOOM_DEPTH),
-- });
-- reservedSpans.push({ start: startMs, end: endMs });
-- acceptedCenters.push(candidate.centerTimeMs);
-- });
--
-- if (additions.length === 0) {
-- return prev;
-- }
--
-- nextZoomIdRef.current = nextId;
-- return [...prev, ...additions];
-- });
--
-- autoSuggestedVideoPathRef.current = videoPath;
-- }, [videoPath, duration, normalizedCursorTelemetry, zoomRegions.length]);
--
-- // Initialize default wallpaper with resolved asset path
-- useEffect(() => {
-- let mounted = true;
-- (async () => {
-- try {
-- const resolvedPath = await getAssetPath(DEFAULT_WALLPAPER_RELATIVE_PATH);
-- if (mounted) {
-- setWallpaper(resolvedPath);
-- }
-- } catch (err) {
-- // If resolution fails, keep the fallback
- console.warn("Failed to resolve default wallpaper path:", err);
- console.warn('Failed to resolve default wallpaper path:', err);
-- }
-- })();
- return () => {
- mounted = false;
- };
- return () => { mounted = false };
-- }, []);
--
-- function togglePlayPause() {
-- const playback = videoPlaybackRef.current;
-- const video = playback?.video;
-- if (!playback || !video) return;
--
-- if (isPlaying) {
-- playback.pause();
-- } else {
- playback.play().catch((err) => console.error("Video play failed:", err));
- playback.play().catch(err => console.error('Video play failed:', err));
-- }
-- }
--
-- function handleSeek(time: number) {
-- const video = videoPlaybackRef.current?.video;
-- if (!video) return;
-- video.currentTime = time;
-- }
--
-- const handleSelectZoom = useCallback((id: string | null) => {
-- setSelectedZoomId(id);
- if (id) setSelectedTrimId(null);
- if (id) {
- setSelectedTrimId(null);
- setSelectedAudioId(null);
- }
-- }, []);
--
-- const handleSelectTrim = useCallback((id: string | null) => {
-- setSelectedTrimId(id);
-- if (id) {
-- setSelectedZoomId(null);
-- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
-- }
-- }, []);
--
-- const handleSelectAnnotation = useCallback((id: string | null) => {
-- setSelectedAnnotationId(id);
-- if (id) {
-- setSelectedZoomId(null);
-- setSelectedTrimId(null);
- setSelectedAudioId(null);
-- }
-- }, []);
--
-- const handleZoomAdded = useCallback((span: Span) => {
-- const id = `zoom-${nextZoomIdRef.current++}`;
-- const newRegion: ZoomRegion = {
-- id,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
-- depth: DEFAULT_ZOOM_DEPTH,
-- focus: { cx: 0.5, cy: 0.5 },
-- };
-- setZoomRegions((prev) => [...prev, newRegion]);
-- setSelectedZoomId(id);
-- setSelectedTrimId(null);
-- setSelectedAnnotationId(null);
-- }, []);
--
-- const handleZoomSuggested = useCallback((span: Span, focus: ZoomFocus) => {
-- const id = `zoom-${nextZoomIdRef.current++}`;
-- const newRegion: ZoomRegion = {
-- id,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
-- depth: DEFAULT_ZOOM_DEPTH,
-- focus: clampFocusToDepth(focus, DEFAULT_ZOOM_DEPTH),
-- };
-- setZoomRegions((prev) => [...prev, newRegion]);
-- setSelectedZoomId(id);
-- setSelectedTrimId(null);
-- setSelectedAnnotationId(null);
-- }, []);
--
-- const handleTrimAdded = useCallback((span: Span) => {
-- const id = `trim-${nextTrimIdRef.current++}`;
-- const newRegion: TrimRegion = {
-- id,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
-- };
-- setTrimRegions((prev) => [...prev, newRegion]);
-- setSelectedTrimId(id);
-- setSelectedZoomId(null);
-- setSelectedAnnotationId(null);
-- }, []);
--
-- const handleZoomSpanChange = useCallback((id: string, span: Span) => {
-- setZoomRegions((prev) =>
-- prev.map((region) =>
-- region.id === id
-- ? {
-- ...region,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
-- }
-- : region,
-- ),
-- );
-- }, []);
--
-- const handleTrimSpanChange = useCallback((id: string, span: Span) => {
-- setTrimRegions((prev) =>
-- prev.map((region) =>
-- region.id === id
-- ? {
-- ...region,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
-- }
-- : region,
-- ),
-- );
-- }, []);
--
-- const handleZoomFocusChange = useCallback((id: string, focus: ZoomFocus) => {
-- setZoomRegions((prev) =>
-- prev.map((region) =>
-- region.id === id
-- ? {
-- ...region,
-- focus: clampFocusToDepth(focus, region.depth),
-- }
-- : region,
-- ),
-- );
-- }, []);
--
- const handleZoomDepthChange = useCallback(
- (depth: ZoomDepth) => {
- if (!selectedZoomId) return;
- setZoomRegions((prev) =>
- prev.map((region) =>
- region.id === selectedZoomId
- ? {
- ...region,
- depth,
- focus: clampFocusToDepth(region.focus, depth),
- }
- : region,
- ),
- );
- },
- [selectedZoomId],
- );
- const handleZoomDepthChange = useCallback((depth: ZoomDepth) => {
- if (!selectedZoomId) return;
- setZoomRegions((prev) =>
- prev.map((region) =>
- region.id === selectedZoomId
- ? {
- ...region,
- depth,
- focus: clampFocusToDepth(region.focus, depth),
- }
- : region,
- ),
- );
- }, [selectedZoomId]);
--
- const handleZoomDelete = useCallback(
- (id: string) => {
- setZoomRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedZoomId === id) {
- setSelectedZoomId(null);
- }
- },
- [selectedZoomId],
- );
- const handleZoomDelete = useCallback((id: string) => {
- setZoomRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedZoomId === id) {
- setSelectedZoomId(null);
- }
- }, [selectedZoomId]);
--
- const handleTrimDelete = useCallback(
- (id: string) => {
- setTrimRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedTrimId === id) {
- setSelectedTrimId(null);
- }
- },
- [selectedTrimId],
- );
- const handleTrimDelete = useCallback((id: string) => {
- setTrimRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedTrimId === id) {
- setSelectedTrimId(null);
- }
- }, [selectedTrimId]);
--
-- const handleSelectSpeed = useCallback((id: string | null) => {
-- setSelectedSpeedId(id);
-- if (id) {
-- setSelectedZoomId(null);
-- setSelectedTrimId(null);
-- setSelectedAnnotationId(null);
- setSelectedAudioId(null);
-- }
-- }, []);
--
-- const handleSpeedAdded = useCallback((span: Span) => {
-- const id = `speed-${nextSpeedIdRef.current++}`;
-- const newRegion: SpeedRegion = {
-- id,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
-- speed: DEFAULT_PLAYBACK_SPEED,
-- };
-- setSpeedRegions((prev) => [...prev, newRegion]);
-- setSelectedSpeedId(id);
-- setSelectedZoomId(null);
-- setSelectedTrimId(null);
-- setSelectedAnnotationId(null);
-- }, []);
--
-- const handleSpeedSpanChange = useCallback((id: string, span: Span) => {
-- setSpeedRegions((prev) =>
-- prev.map((region) =>
-- region.id === id
-- ? {
-- ...region,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
-- }
-- : region,
-- ),
-- );
-- }, []);
--
- const handleSpeedDelete = useCallback(
- (id: string) => {
- setSpeedRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedSpeedId === id) {
- setSelectedSpeedId(null);
- }
- },
- [selectedSpeedId],
- );
- const handleSpeedDelete = useCallback((id: string) => {
- setSpeedRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedSpeedId === id) {
- setSelectedSpeedId(null);
- }
- }, [selectedSpeedId]);
--
- const handleSpeedChange = useCallback(
- (speed: PlaybackSpeed) => {
- if (!selectedSpeedId) return;
- setSpeedRegions((prev) =>
- prev.map((region) => (region.id === selectedSpeedId ? { ...region, speed } : region)),
- );
- },
- [selectedSpeedId],
- );
- const handleSelectAudio = useCallback((id: string | null) => {
- setSelectedAudioId(id);
- if (id) {
- setSelectedZoomId(null);
- setSelectedTrimId(null);
- setSelectedAnnotationId(null);
- setSelectedSpeedId(null);
- }
- }, []);
-
- const handleAudioAdded = useCallback((span: Span, audioPath: string) => {
- const id = `audio-${nextAudioIdRef.current++}`;
- const newRegion: AudioRegion = {
- id,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- audioPath,
- volume: 1,
- };
- setAudioRegions((prev) => [...prev, newRegion]);
- setSelectedAudioId(id);
- setSelectedZoomId(null);
- setSelectedTrimId(null);
- setSelectedAnnotationId(null);
- setSelectedSpeedId(null);
- }, []);
-
- const handleAudioSpanChange = useCallback((id: string, span: Span) => {
- setAudioRegions((prev) =>
- prev.map((region) =>
- region.id === id
- ? {
- ...region,
- startMs: Math.round(span.start),
- endMs: Math.round(span.end),
- }
- : region,
- ),
- );
- }, []);
-
- const handleAudioDelete = useCallback((id: string) => {
- setAudioRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedAudioId === id) {
- setSelectedAudioId(null);
- }
- }, [selectedAudioId]);
-
- const handleSpeedChange = useCallback((speed: PlaybackSpeed) => {
- if (!selectedSpeedId) return;
- setSpeedRegions((prev) =>
- prev.map((region) =>
- region.id === selectedSpeedId ? { ...region, speed } : region,
- ),
- );
- }, [selectedSpeedId]);
--
-- const handleAnnotationAdded = useCallback((span: Span) => {
-- const id = `annotation-${nextAnnotationIdRef.current++}`;
-- const zIndex = nextAnnotationZIndexRef.current++; // Assign z-index based on creation order
-- const newRegion: AnnotationRegion = {
-- id,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
- type: "text",
- content: "Enter text...",
- type: 'text',
- content: 'Enter text...',
-- position: { ...DEFAULT_ANNOTATION_POSITION },
-- size: { ...DEFAULT_ANNOTATION_SIZE },
-- style: { ...DEFAULT_ANNOTATION_STYLE },
-- zIndex,
-- };
-- setAnnotationRegions((prev) => [...prev, newRegion]);
-- setSelectedAnnotationId(id);
-- setSelectedZoomId(null);
-- setSelectedTrimId(null);
-- }, []);
--
-- const handleAnnotationSpanChange = useCallback((id: string, span: Span) => {
-- setAnnotationRegions((prev) =>
-- prev.map((region) =>
-- region.id === id
-- ? {
-- ...region,
-- startMs: Math.round(span.start),
-- endMs: Math.round(span.end),
-- }
-- : region,
-- ),
-- );
-- }, []);
--
- const handleAnnotationDelete = useCallback(
- (id: string) => {
- setAnnotationRegions((prev) => prev.filter((region) => region.id !== id));
- if (selectedAnnotationId === id) {
- setSelectedAnnotationId(null);
- }
- },
- [selectedAnnotationId],
- );
- const 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") {
- if (region.type === 'text') {
-- return { ...region, content, textContent: content };
- } else if (region.type === "image") {
- } else if (region.type === 'image') {
-- return { ...region, content, imageContent: content };
-- } else {
-- return { ...region, content };
-- }
-- });
-- return updated;
-- });
-- }, []);
--
- const handleAnnotationTypeChange = useCallback((id: string, type: AnnotationRegion["type"]) => {
- 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 (type === 'text') {
- updatedRegion.content = region.textContent || 'Enter text...';
- } else if (type === 'image') {
- updatedRegion.content = region.imageContent || '';
- } else if (type === 'figure') {
- updatedRegion.content = '';
-- if (!region.figureData) {
-- updatedRegion.figureData = { ...DEFAULT_FIGURE_DATA };
-- }
-- }
-
-
-- return updatedRegion;
-- });
-- return updated;
-- });
-- }, []);
--
- const handleAnnotationStyleChange = useCallback(
- (id: string, style: Partial<AnnotationRegion["style"]>) => {
- setAnnotationRegions((prev) =>
- prev.map((region) =>
- region.id === id ? { ...region, style: { ...region.style, ...style } } : region,
- ),
- );
- },
- [],
- );
- const 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)),
- prev.map((region) =>
- region.id === id
- ? { ...region, figureData }
- : region,
- ),
-- );
-- }, []);
-
- const handleAnnotationPositionChange = useCallback(
- (id: string, position: { x: number; y: number }) => {
- setAnnotationRegions((prev) =>
- prev.map((region) => (region.id === id ? { ...region, position } : region)),
- );
- },
- [],
- );
--
- const handleAnnotationSizeChange = useCallback(
- (id: string, size: { width: number; height: number }) => {
- setAnnotationRegions((prev) =>
- prev.map((region) => (region.id === id ? { ...region, size } : region)),
- );
- },
- [],
- );
- 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;
- 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 (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 (!isMac && e.ctrlKey && !e.metaKey && !e.altKey && key === 'y') {
-- if (!isEditableTarget) {
-- e.preventDefault();
-- handleRedo();
-- }
-- return;
-- }
--
- if (e.key === "Tab") {
- 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) {
-- playback.play().catch(console.error);
-- } else {
-- playback.pause();
-- }
-- }
-- }
-- };
-
- window.addEventListener("keydown", handleKeyDown, { capture: true });
- return () => window.removeEventListener("keydown", handleKeyDown, { capture: true });
-
- window.addEventListener('keydown', handleKeyDown, { capture: true });
- return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });
-- }, [shortcuts, isMac, handleUndo, handleRedo]);
--
-- useEffect(() => {
-- if (selectedZoomId && !zoomRegions.some((region) => region.id === selectedZoomId)) {
-- setSelectedZoomId(null);
-- }
-- }, [selectedZoomId, zoomRegions]);
--
-- useEffect(() => {
-- if (selectedTrimId && !trimRegions.some((region) => region.id === selectedTrimId)) {
-- setSelectedTrimId(null);
-- }
-- }, [selectedTrimId, trimRegions]);
--
-- useEffect(() => {
- if (
- selectedAnnotationId &&
- !annotationRegions.some((region) => region.id === selectedAnnotationId)
- ) {
- if (selectedAnnotationId && !annotationRegions.some((region) => region.id === selectedAnnotationId)) {
-- setSelectedAnnotationId(null);
-- }
-- }, [selectedAnnotationId, annotationRegions]);
--
-- useEffect(() => {
-- if (selectedSpeedId && !speedRegions.some((region) => region.id === selectedSpeedId)) {
-- setSelectedSpeedId(null);
-- }
-- }, [selectedSpeedId, speedRegions]);
-
- useEffect(() => {
- if (selectedAudioId && !audioRegions.some((region) => region.id === selectedAudioId)) {
- setSelectedAudioId(null);
- }
- }, [selectedAudioId, audioRegions]);
-
- // Audio playback sync: manage Audio elements that play in sync with video
- const audioElementsRef = useRef<Map<string, HTMLAudioElement>>(new Map());
-
- useEffect(() => {
- const existing = audioElementsRef.current;
- const currentIds = new Set(audioRegions.map(r => r.id));
-
- // Remove old audio elements
- for (const [id, audio] of existing) {
- if (!currentIds.has(id)) {
- audio.pause();
- audio.src = '';
- existing.delete(id);
- }
- }
-
- // Create/update audio elements
- for (const region of audioRegions) {
- let audio = existing.get(region.id);
- if (!audio) {
- audio = new Audio();
- audio.preload = 'auto';
- existing.set(region.id, audio);
- }
- const expectedSrc = toFileUrl(region.audioPath);
- if (audio.src !== expectedSrc) {
- audio.src = expectedSrc;
- }
- audio.volume = Math.max(0, Math.min(1, region.volume));
- }
-
- return () => {
- for (const audio of existing.values()) {
- audio.pause();
- audio.src = '';
- }
- existing.clear();
- };
- }, [audioRegions]);
-
- // Sync audio playback with video currentTime and isPlaying state
- useEffect(() => {
- for (const region of audioRegions) {
- const audio = audioElementsRef.current.get(region.id);
- if (!audio) continue;
-
- const currentTimeMs = currentTime * 1000;
- const isInRegion = currentTimeMs >= region.startMs && currentTimeMs < region.endMs;
-
- if (isPlaying && isInRegion) {
- const audioOffset = (currentTimeMs - region.startMs) / 1000;
- // Only seek if significantly out of sync (> 200ms)
- if (Math.abs(audio.currentTime - audioOffset) > 0.2) {
- audio.currentTime = audioOffset;
- }
- if (audio.paused) {
- audio.play().catch(() => {});
- }
- } else {
- if (!audio.paused) {
- audio.pause();
- }
- }
- }
- }, [isPlaying, currentTime, audioRegions]);
--
-- const showExportSuccessToast = useCallback((filePath: string) => {
-- toast.success(`Exported successfully to ${filePath}`, {
-- action: {
- label: "Show in Folder",
- 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.";
- 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 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;
- }
- const video = videoPlaybackRef.current?.video;
- if (!video) {
- toast.error('Video not ready');
- return;
- }
--
- setIsExporting(true);
- setExportProgress(null);
- setExportError(null);
- pendingExportSaveRef.current = null;
- setHasPendingExportSave(false);
- setIsExporting(true);
- setExportProgress(null);
- setExportError(null);
- pendingExportSaveRef.current = null;
- setHasPendingExportSave(false);
--
- let keepExportDialogOpen = false;
- let keepExportDialogOpen = false;
--
- try {
- const wasPlaying = isPlaying;
- const restoreTime = video.currentTime;
- if (wasPlaying) {
- videoPlaybackRef.current?.pause();
- }
- try {
- const wasPlaying = isPlaying;
- const restoreTime = video.currentTime;
- if (wasPlaying) {
- videoPlaybackRef.current?.pause();
- }
--
- const sourceWidth = video.videoWidth || 1920;
- const sourceHeight = video.videoHeight || 1080;
- const sourceAspectRatio = sourceHeight > 0 ? sourceWidth / sourceHeight : 16 / 9;
- const aspectRatioValue = getAspectRatioValue(aspectRatio, sourceAspectRatio);
- const sourceWidth = video.videoWidth || 1920;
- const sourceHeight = video.videoHeight || 1080;
- const sourceAspectRatio = sourceHeight > 0 ? sourceWidth / sourceHeight : 16 / 9;
- const aspectRatioValue = getAspectRatioValue(aspectRatio, sourceAspectRatio);
--
- // 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;
- // Get preview CONTAINER dimensions for scaling
- const playbackRef = videoPlaybackRef.current;
- const containerElement = playbackRef?.containerRef?.current;
- const previewWidth = containerElement?.clientWidth || 1920;
- const previewHeight = containerElement?.clientHeight || 1080;
--
- if (settings.format === "gif" && settings.gifConfig) {
- // GIF Export
- const gifExporter = new GifExporter({
- videoUrl: videoPath,
- width: settings.gifConfig.width,
- height: settings.gifConfig.height,
- frameRate: settings.gifConfig.frameRate,
- loop: settings.gifConfig.loop,
- sizePreset: settings.gifConfig.sizePreset,
- wallpaper,
- trimRegions,
- speedRegions,
- showShadow: shadowIntensity > 0,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- connectZooms,
- borderRadius,
- padding,
- videoPadding: padding,
- cropRegion,
- annotationRegions,
- zoomRegions: effectiveZoomRegions,
- cursorTelemetry: effectiveCursorTelemetry,
- showCursor,
- cursorSize,
- cursorSmoothing,
- cursorMotionBlur,
- cursorClickBounce,
- cursorSway,
- previewWidth,
- previewHeight,
- onProgress: (progress: ExportProgress) => {
- setExportProgress(progress);
- },
- });
- 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,
- showShadow: shadowIntensity > 0,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- connectZooms,
- borderRadius,
- padding,
- videoPadding: padding,
- cropRegion,
- annotationRegions,
- zoomRegions: effectiveZoomRegions,
- cursorTelemetry: effectiveCursorTelemetry,
- showCursor,
- cursorSize,
- cursorSmoothing,
- cursorMotionBlur,
- cursorClickBounce,
- previewWidth,
- previewHeight,
- onProgress: (progress: ExportProgress) => {
- setExportProgress(progress);
- },
- });
--
- exporterRef.current = gifExporter as unknown as VideoExporter;
- const result = await gifExporter.export();
- exporterRef.current = gifExporter as unknown as VideoExporter;
- const result = await gifExporter.export();
--
- if (result.success && result.blob) {
- const arrayBuffer = await result.blob.arrayBuffer();
- const timestamp = Date.now();
- const fileName = `export-${timestamp}.gif`;
- if (result.success && result.blob) {
- const arrayBuffer = await result.blob.arrayBuffer();
- const timestamp = Date.now();
- const fileName = `export-${timestamp}.gif`;
--
- const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
- const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
--
- if (saveResult.canceled) {
- pendingExportSaveRef.current = { arrayBuffer, fileName };
- 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) {
- showExportSuccessToast(saveResult.path);
- setExportedFilePath(saveResult.path);
- } else {
- setExportError(saveResult.message || "Failed to save GIF");
- toast.error(saveResult.message || "Failed to save GIF");
- }
- if (saveResult.canceled) {
- pendingExportSaveRef.current = { arrayBuffer, fileName };
- 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) {
- showExportSuccessToast(saveResult.path);
- setExportedFilePath(saveResult.path);
-- } else {
- setExportError(result.error || "GIF export failed");
- toast.error(result.error || "GIF export failed");
- setExportError(saveResult.message || 'Failed to save GIF');
- toast.error(saveResult.message || 'Failed to save GIF');
-- }
-- } else {
- // MP4 Export
- const quality = settings.quality || exportQuality;
- let exportWidth: number;
- let exportHeight: number;
- let bitrate: number;
- setExportError(result.error || 'GIF export failed');
- toast.error(result.error || 'GIF export failed');
- }
- } else {
- // MP4 Export
- const quality = settings.quality || exportQuality;
- let exportWidth: number;
- let exportHeight: number;
- let bitrate: number;
--
- if (quality === "source") {
- // Use source resolution
- exportWidth = sourceWidth;
- exportHeight = sourceHeight;
- if (quality === 'source') {
- // Use source resolution
- exportWidth = sourceWidth;
- exportHeight = sourceHeight;
--
- if (aspectRatio === "native") {
- exportWidth = Math.floor(sourceWidth / 2) * 2;
- exportHeight = Math.floor(sourceHeight / 2) * 2;
- } else if (aspectRatioValue === 1) {
- // Square (1:1): use smaller dimension to avoid codec limits
- const baseDimension = Math.floor(Math.min(sourceWidth, sourceHeight) / 2) * 2;
- exportWidth = baseDimension;
- exportHeight = baseDimension;
- } else if (aspectRatioValue > 1) {
- // Landscape: find largest even dimensions that exactly match aspect ratio
- const baseWidth = Math.floor(sourceWidth / 2) * 2;
- let found = false;
- for (let w = baseWidth; w >= 100 && !found; w -= 2) {
- const h = Math.round(w / aspectRatioValue);
- if (h % 2 === 0 && Math.abs(w / h - aspectRatioValue) < 0.0001) {
- exportWidth = w;
- exportHeight = h;
- found = true;
- }
- }
- if (!found) {
- exportWidth = baseWidth;
- exportHeight = Math.floor(baseWidth / aspectRatioValue / 2) * 2;
- }
- } else {
- // Portrait: find largest even dimensions that exactly match aspect ratio
- const baseHeight = Math.floor(sourceHeight / 2) * 2;
- let found = false;
- for (let h = baseHeight; h >= 100 && !found; h -= 2) {
- const w = Math.round(h * aspectRatioValue);
- if (w % 2 === 0 && Math.abs(w / h - aspectRatioValue) < 0.0001) {
- exportWidth = w;
- exportHeight = h;
- found = true;
- }
- }
- if (!found) {
- exportHeight = baseHeight;
- exportWidth = Math.floor((baseHeight * aspectRatioValue) / 2) * 2;
- if (aspectRatio === 'native') {
- exportWidth = Math.floor(sourceWidth / 2) * 2;
- exportHeight = Math.floor(sourceHeight / 2) * 2;
- } else if (aspectRatioValue === 1) {
- // Square (1:1): use smaller dimension to avoid codec limits
- const baseDimension = Math.floor(Math.min(sourceWidth, sourceHeight) / 2) * 2;
- exportWidth = baseDimension;
- exportHeight = baseDimension;
- } else if (aspectRatioValue > 1) {
- // Landscape: find largest even dimensions that exactly match aspect ratio
- const baseWidth = Math.floor(sourceWidth / 2) * 2;
- let found = false;
- for (let w = baseWidth; w >= 100 && !found; w -= 2) {
- const h = Math.round(w / aspectRatioValue);
- if (h % 2 === 0 && Math.abs((w / h) - aspectRatioValue) < 0.0001) {
- exportWidth = w;
- exportHeight = h;
- found = true;
-- }
-- }
-
- // Calculate visually lossless bitrate matching screen recording optimization
- const totalPixels = exportWidth * exportHeight;
- bitrate = 30_000_000;
- if (totalPixels > 1920 * 1080 && totalPixels <= 2560 * 1440) {
- bitrate = 50_000_000;
- } else if (totalPixels > 2560 * 1440) {
- bitrate = 80_000_000;
- if (!found) {
- exportWidth = baseWidth;
- exportHeight = Math.floor((baseWidth / aspectRatioValue) / 2) * 2;
-- }
-- } else {
- // Use quality-based target resolution
- const targetHeight = quality === "medium" ? 720 : 1080;
- // Portrait: find largest even dimensions that exactly match aspect ratio
- const baseHeight = Math.floor(sourceHeight / 2) * 2;
- let found = false;
- for (let h = baseHeight; h >= 100 && !found; h -= 2) {
- const w = Math.round(h * aspectRatioValue);
- if (w % 2 === 0 && Math.abs((w / h) - aspectRatioValue) < 0.0001) {
- exportWidth = w;
- exportHeight = h;
- found = true;
- }
- }
- if (!found) {
- exportHeight = baseHeight;
- exportWidth = Math.floor((baseHeight * aspectRatioValue) / 2) * 2;
- }
- }
--
- // Calculate dimensions maintaining aspect ratio
- exportHeight = Math.floor(targetHeight / 2) * 2;
- exportWidth = Math.floor((exportHeight * aspectRatioValue) / 2) * 2;
- // Calculate visually lossless bitrate matching screen recording optimization
- const totalPixels = exportWidth * exportHeight;
- bitrate = 30_000_000;
- if (totalPixels > 1920 * 1080 && totalPixels <= 2560 * 1440) {
- bitrate = 50_000_000;
- } else if (totalPixels > 2560 * 1440) {
- bitrate = 80_000_000;
- }
- } else {
- // Use source-relative quality scaling.
- // "source" is handled above; this branch maps the remaining tiers.
- const qualityScale =
- quality === 'medium' ? 0.6 : quality === 'good' ? 0.75 : 0.9;
- const maxWidth = Math.max(2, Math.floor((sourceWidth * qualityScale) / 2) * 2);
- const maxHeight = Math.max(2, Math.floor((sourceHeight * qualityScale) / 2) * 2);
- const maxAspect = maxWidth / maxHeight;
--
- // Adjust bitrate for lower resolutions
- const totalPixels = exportWidth * exportHeight;
- if (totalPixels <= 1280 * 720) {
- bitrate = 10_000_000;
- } else if (totalPixels <= 1920 * 1080) {
- bitrate = 20_000_000;
- } else {
- bitrate = 30_000_000;
- }
- if (aspectRatioValue >= maxAspect) {
- exportWidth = maxWidth;
- exportHeight = Math.max(2, Math.floor((exportWidth / aspectRatioValue) / 2) * 2);
- } else {
- exportHeight = maxHeight;
- exportWidth = Math.max(2, Math.floor((exportHeight * aspectRatioValue) / 2) * 2);
-- }
--
- const exporter = new VideoExporter({
- videoUrl: videoPath,
- width: exportWidth,
- height: exportHeight,
- frameRate: 60,
- bitrate,
- codec: "avc1.640033",
- wallpaper,
- trimRegions,
- speedRegions,
- showShadow: shadowIntensity > 0,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- connectZooms,
- borderRadius,
- padding,
- cropRegion,
- annotationRegions,
- zoomRegions: effectiveZoomRegions,
- cursorTelemetry: effectiveCursorTelemetry,
- showCursor,
- cursorSize,
- cursorSmoothing,
- cursorMotionBlur,
- cursorClickBounce,
- cursorSway,
- previewWidth,
- previewHeight,
- onProgress: (progress: ExportProgress) => {
- setExportProgress(progress);
- },
- });
- // Adjust bitrate for lower resolutions
- const totalPixels = exportWidth * exportHeight;
- if (totalPixels <= 1280 * 720) {
- bitrate = 10_000_000;
- } else if (totalPixels <= 1920 * 1080) {
- bitrate = 20_000_000;
- } else {
- bitrate = 30_000_000;
- }
- }
--
- exporterRef.current = exporter;
- const result = await exporter.export();
- const exporter = new VideoExporter({
- videoUrl: videoPath,
- width: exportWidth,
- height: exportHeight,
- frameRate: 60,
- bitrate,
- codec: 'avc1.640033',
- wallpaper,
- trimRegions,
- speedRegions,
- showShadow: shadowIntensity > 0,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- connectZooms,
- borderRadius,
- padding,
- cropRegion,
- annotationRegions,
- zoomRegions: effectiveZoomRegions,
- cursorTelemetry: effectiveCursorTelemetry,
- showCursor,
- cursorSize,
- cursorSmoothing,
- cursorMotionBlur,
- cursorClickBounce,
- audioRegions,
- previewWidth,
- previewHeight,
- onProgress: (progress: ExportProgress) => {
- setExportProgress(progress);
- },
- });
--
- if (result.success && result.blob) {
- const arrayBuffer = await result.blob.arrayBuffer();
- const timestamp = Date.now();
- const fileName = `export-${timestamp}.mp4`;
- exporterRef.current = exporter;
- const result = await exporter.export();
--
- const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
- if (result.success && result.blob) {
- const arrayBuffer = await result.blob.arrayBuffer();
- const timestamp = Date.now();
- const fileName = `export-${timestamp}.mp4`;
--
- if (saveResult.canceled) {
- pendingExportSaveRef.current = { arrayBuffer, fileName };
- 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) {
- showExportSuccessToast(saveResult.path);
- setExportedFilePath(saveResult.path);
- } else {
- setExportError(saveResult.message || "Failed to save video");
- toast.error(saveResult.message || "Failed to save video");
- }
- const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
-
- if (saveResult.canceled) {
- pendingExportSaveRef.current = { arrayBuffer, fileName };
- 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) {
- showExportSuccessToast(saveResult.path);
- setExportedFilePath(saveResult.path);
-- } else {
- setExportError(result.error || "Export failed");
- toast.error(result.error || "Export failed");
- setExportError(saveResult.message || 'Failed to save video');
- toast.error(saveResult.message || 'Failed to save video');
-- }
- }
-
- if (wasPlaying) {
- videoPlaybackRef.current?.play();
-- } else {
- video.currentTime = restoreTime;
- await videoPlaybackRef.current?.refreshFrame();
- }
- } catch (error) {
- console.error("Export error:", error);
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
- setExportError(errorMessage);
- toast.error(`Export failed: ${errorMessage}`);
- } finally {
- if (!isPlaying) {
- await videoPlaybackRef.current?.refreshFrame().catch(() => undefined);
- setExportError(result.error || 'Export failed');
- toast.error(result.error || 'Export failed');
-- }
- setIsExporting(false);
- exporterRef.current = null;
- setShowExportDialog(keepExportDialogOpen);
- setExportProgress(null);
-- }
- },
- [
- videoPath,
- wallpaper,
- trimRegions,
- speedRegions,
- shadowIntensity,
- backgroundBlur,
- zoomMotionBlur,
- connectZooms,
- showCursor,
- effectiveCursorTelemetry,
- cursorSize,
- cursorSmoothing,
- cursorMotionBlur,
- cursorClickBounce,
- cursorSway,
- borderRadius,
- padding,
- cropRegion,
- annotationRegions,
- isPlaying,
- aspectRatio,
- exportQuality,
- effectiveZoomRegions,
- showExportSuccessToast,
- ],
- );
-
- if (wasPlaying) {
- videoPlaybackRef.current?.play();
- } else {
- video.currentTime = restoreTime;
- await videoPlaybackRef.current?.refreshFrame();
- }
- } catch (error) {
- console.error('Export error:', error);
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- setExportError(errorMessage);
- toast.error(`Export failed: ${errorMessage}`);
- } finally {
- if (!isPlaying) {
- await videoPlaybackRef.current?.refreshFrame().catch(() => undefined);
- }
- setIsExporting(false);
- exporterRef.current = null;
- setShowExportDialog(keepExportDialogOpen);
- setExportProgress(null);
- }
- }, [videoPath, wallpaper, zoomRegions, trimRegions, speedRegions, shadowIntensity, backgroundBlur, zoomMotionBlur, connectZooms, showCursor, effectiveCursorTelemetry, cursorSize, cursorSmoothing, cursorMotionBlur, cursorClickBounce, borderRadius, padding, cropRegion, annotationRegions, isPlaying, aspectRatio, exportQuality, showExportSuccessToast]);
--
-- const handleOpenExportDialog = useCallback(() => {
-- if (!videoPath) {
- toast.error("No video loaded");
- toast.error('No video loaded');
-- return;
-- }
--
-- if (hasPendingExportSave) {
-- setShowExportDialog(true);
- setExportError("Save dialog canceled. Click Save Again to save without re-rendering.");
- setExportError('Save dialog canceled. Click Save Again to save without re-rendering.');
-- return;
-- }
--
-- const video = videoPlaybackRef.current?.video;
-- if (!video) {
- toast.error("Video not ready");
- toast.error('Video not ready');
-- return;
-- }
--
-- // Build export settings from current state
-- const sourceWidth = video.videoWidth || 1920;
-- const sourceHeight = video.videoHeight || 1080;
- const gifDimensions = calculateOutputDimensions(
- sourceWidth,
- sourceHeight,
- gifSizePreset,
- GIF_SIZE_PRESETS,
- );
- const gifDimensions = calculateOutputDimensions(sourceWidth, sourceHeight, gifSizePreset, GIF_SIZE_PRESETS);
--
-- const settings: ExportSettings = {
-- format: exportFormat,
- quality: exportFormat === "mp4" ? exportQuality : undefined,
- gifConfig:
- exportFormat === "gif"
- ? {
- frameRate: gifFrameRate,
- loop: gifLoop,
- sizePreset: gifSizePreset,
- width: gifDimensions.width,
- height: gifDimensions.height,
- }
- : undefined,
- quality: exportFormat === 'mp4' ? exportQuality : undefined,
- gifConfig: exportFormat === 'gif' ? {
- frameRate: gifFrameRate,
- loop: gifLoop,
- sizePreset: gifSizePreset,
- width: gifDimensions.width,
- height: gifDimensions.height,
- } : undefined,
-- };
--
-- setShowExportDialog(true);
-- setExportError(null);
--
-- // Start export immediately
-- handleExport(settings);
- }, [
- videoPath,
- hasPendingExportSave,
- exportFormat,
- exportQuality,
- gifFrameRate,
- gifLoop,
- gifSizePreset,
- handleExport,
- ]);
- }, [videoPath, hasPendingExportSave, exportFormat, exportQuality, gifFrameRate, gifLoop, gifSizePreset, handleExport]);
--
-- const handleCancelExport = useCallback(() => {
-- if (exporterRef.current) {
-- exporterRef.current.cancel();
- toast.info("Export canceled");
- toast.info('Export canceled');
-- setShowExportDialog(false);
-- setIsExporting(false);
-- setExportProgress(null);
-- setExportError(null);
-- setExportedFilePath(undefined);
-- }
-- }, []);
--
-- const handleExportDialogClose = useCallback(() => {
-- setShowExportDialog(false);
-- setExportedFilePath(undefined);
-- }, []);
--
-- const handleRetrySaveExport = useCallback(async () => {
-- const pendingSave = pendingExportSaveRef.current;
-- if (!pendingSave) {
-- return;
-- }
--
- const saveResult = await window.electronAPI.saveExportedVideo(
- pendingSave.arrayBuffer,
- pendingSave.fileName,
- );
- const saveResult = await window.electronAPI.saveExportedVideo(pendingSave.arrayBuffer, pendingSave.fileName);
--
-- if (saveResult.canceled) {
- setExportError("Save dialog canceled. Click Save Again to save without re-rendering.");
- toast.info("Save canceled. You can try again.");
- 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) {
-- pendingExportSaveRef.current = null;
-- setHasPendingExportSave(false);
-- setExportError(null);
-- setExportedFilePath(saveResult.path);
-- showExportSuccessToast(saveResult.path);
-- setShowExportDialog(false);
-- return;
-- }
--
- const errorMessage = saveResult.message || "Failed to save video";
- const errorMessage = saveResult.message || 'Failed to save video';
-- setExportError(errorMessage);
-- toast.error(errorMessage);
-- }, [showExportSuccessToast]);
--
-- const openRecordingsFolder = useCallback(async () => {
-- try {
-- const result = await window.electronAPI.openRecordingsFolder();
-- if (!result.success) {
- toast.error(result.message || result.error || "Failed to open recordings folder.");
- toast.error(result.message || result.error || 'Failed to open recordings folder.');
-- }
-- } catch (error) {
-- toast.error(`Failed to open recordings folder: ${String(error)}`);
-- }
-- }, []);
--
-- if (loading) {
-- return (
-- <div className="flex items-center justify-center h-screen bg-background">
-- <div className="text-foreground">Loading video...</div>
-- </div>
-- );
-- }
-- if (error) {
-- return (
-- <div className="flex items-center justify-center h-screen bg-background">
-- <div className="flex flex-col items-center gap-3">
-- <div className="text-destructive">{error}</div>
-- <button
-- type="button"
-- onClick={handleLoadProject}
-- className="px-3 py-1.5 rounded-md bg-[#2563EB] text-white text-sm hover:bg-[#2563EB]/90"
-- >
-- Load Project File
-- </button>
-- </div>
-- </div>
-- );
-- }
-
--
-- return (
-- <div className="flex flex-col h-screen bg-[#09090b] text-slate-200 overflow-hidden selection:bg-[#2563EB]/30">
- <div
- <div
-- className="relative h-10 flex-shrink-0 bg-[#09090b]/80 backdrop-blur-md border-b border-white/5 flex items-center justify-center px-6 z-50"
- style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
- style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
-- >
-- <span className="text-sm font-semibold tracking-tight text-white/90">Recordly</span>
-- <div
-- className="absolute right-4 flex items-center gap-1"
- style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
-- >
-- <LanguageSwitcher />
-- <button
-- type="button"
-- onClick={() => void openRecordingsFolder()}
-- className="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-white/90 transition hover:bg-white/8 hover:text-white cursor-pointer"
-- title={t("common.app.manageRecordings", "Open recordings folder")}
-- aria-label={t("common.app.manageRecordings", "Open recordings folder")}
-- >
-- <FolderOpen className="h-4 w-4" />
- <span className="text-xs font-normal">
- {t("common.app.manageRecordings", "Manage recordings")}
- </span>
- <span className="text-xs font-normal">{t("common.app.manageRecordings", "Manage recordings")}</span>
-- </button>
-- </div>
-- </div>
--
-- <div className="flex-1 p-5 gap-4 flex min-h-0 relative">
-- {/* Left Column - Video & Timeline */}
-- <div className="flex-[7] flex flex-col gap-3 min-w-0 h-full">
-- <PanelGroup direction="vertical" className="gap-3">
-- {/* Top section: video preview and controls */}
-- <Panel defaultSize={70} minSize={40}>
-- <div className="w-full h-full flex flex-col items-center justify-center bg-black/40 rounded-2xl border border-white/5 shadow-2xl overflow-hidden">
-- {/* Video preview */}
- <div
- className="w-full flex justify-center items-center"
- style={{ flex: "1 1 auto", margin: "6px 0 0" }}
- >
- <div
- className="relative"
- style={{
- width: "auto",
- height: "100%",
- aspectRatio: getAspectRatioValue(
- aspectRatio,
- (() => {
- const previewVideo = videoPlaybackRef.current?.video;
- if (previewVideo && previewVideo.videoHeight > 0) {
- return previewVideo.videoWidth / previewVideo.videoHeight;
- }
- return 16 / 9;
- })(),
- ),
- maxWidth: "100%",
- margin: "0 auto",
- boxSizing: "border-box",
- }}
- >
- <div className="w-full flex justify-center items-center" style={{ flex: '1 1 auto', margin: '6px 0 0' }}>
- <div className="relative" style={{ width: 'auto', height: '100%', aspectRatio: getAspectRatioValue(aspectRatio, (() => {
- const previewVideo = videoPlaybackRef.current?.video;
- if (previewVideo && previewVideo.videoHeight > 0) {
- return previewVideo.videoWidth / previewVideo.videoHeight;
- }
- return 16 / 9;
- })()), maxWidth: '100%', margin: '0 auto', boxSizing: 'border-box' }}>
-- <VideoPlayback
- key={videoPath || "no-video"}
- key={videoPath || 'no-video'}
-- aspectRatio={aspectRatio}
-- ref={videoPlaybackRef}
- videoPath={videoPath || ""}
- videoPath={videoPath || ''}
-- onDurationChange={setDuration}
-- 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}
-- zoomMotionBlur={zoomMotionBlur}
-- connectZooms={connectZooms}
-- borderRadius={borderRadius}
-- padding={padding}
-- cropRegion={cropRegion}
-- trimRegions={trimRegions}
-- speedRegions={speedRegions}
-- annotationRegions={annotationRegions}
-- selectedAnnotationId={selectedAnnotationId}
-- onSelectAnnotation={handleSelectAnnotation}
-- onAnnotationPositionChange={handleAnnotationPositionChange}
-- onAnnotationSizeChange={handleAnnotationSizeChange}
-- cursorTelemetry={effectiveCursorTelemetry}
-- showCursor={showCursor}
-- cursorSize={cursorSize}
-- cursorSmoothing={cursorSmoothing}
-- cursorMotionBlur={cursorMotionBlur}
-- cursorClickBounce={cursorClickBounce}
- cursorSway={cursorSway}
-- />
-- </div>
-- </div>
-- {/* Playback controls */}
- <div
- className="w-full flex justify-center items-center"
- style={{
- height: "48px",
- flexShrink: 0,
- padding: "6px 12px",
- margin: "6px 0 6px 0",
- }}
- >
- <div style={{ width: "100%", maxWidth: "700px" }}>
- <div className="w-full flex justify-center items-center" style={{ height: '48px', flexShrink: 0, padding: '6px 12px', margin: '6px 0 6px 0' }}>
- <div style={{ width: '100%', maxWidth: '700px' }}>
-- <PlaybackControls
-- isPlaying={isPlaying}
-- currentTime={currentTime}
-- duration={duration}
-- onTogglePlayPause={togglePlayPause}
-- onSeek={handleSeek}
-- />
-- </div>
-- </div>
-- </div>
-- </Panel>
--
-- <PanelResizeHandle className="h-3 bg-[#09090b]/80 hover:bg-[#09090b] transition-colors rounded-full mx-4 flex items-center justify-center">
-- <div className="w-8 h-1 bg-white/20 rounded-full"></div>
-- </PanelResizeHandle>
--
-- {/* Timeline section */}
-- <Panel defaultSize={30} minSize={20}>
-- <div className="h-full min-h-0 bg-[#09090b] rounded-2xl border border-white/5 shadow-lg overflow-auto flex flex-col">
-- <TimelineEditor
- videoDuration={duration}
- currentTime={currentTime}
- onSeek={handleSeek}
- cursorTelemetry={effectiveCursorTelemetry}
- zoomRegions={effectiveZoomRegions}
- onZoomAdded={handleZoomAdded}
- onZoomSuggested={handleZoomSuggested}
- onZoomSpanChange={handleZoomSpanChange}
- onZoomDelete={handleZoomDelete}
- selectedZoomId={selectedZoomId}
- onSelectZoom={handleSelectZoom}
- trimRegions={trimRegions}
- onTrimAdded={handleTrimAdded}
- onTrimSpanChange={handleTrimSpanChange}
- onTrimDelete={handleTrimDelete}
- selectedTrimId={selectedTrimId}
- onSelectTrim={handleSelectTrim}
- speedRegions={speedRegions}
- onSpeedAdded={handleSpeedAdded}
- onSpeedSpanChange={handleSpeedSpanChange}
- onSpeedDelete={handleSpeedDelete}
- selectedSpeedId={selectedSpeedId}
- onSelectSpeed={handleSelectSpeed}
- annotationRegions={annotationRegions}
- onAnnotationAdded={handleAnnotationAdded}
- onAnnotationSpanChange={handleAnnotationSpanChange}
- onAnnotationDelete={handleAnnotationDelete}
- selectedAnnotationId={selectedAnnotationId}
- onSelectAnnotation={handleSelectAnnotation}
- aspectRatio={aspectRatio}
- onAspectRatioChange={setAspectRatio}
- />
- videoDuration={duration}
- currentTime={currentTime}
- onSeek={handleSeek}
- cursorTelemetry={effectiveCursorTelemetry}
- zoomRegions={effectiveZoomRegions}
- onZoomAdded={handleZoomAdded}
- onZoomSuggested={handleZoomSuggested}
- onZoomSpanChange={handleZoomSpanChange}
- onZoomDelete={handleZoomDelete}
- selectedZoomId={selectedZoomId}
- onSelectZoom={handleSelectZoom}
- trimRegions={trimRegions}
- onTrimAdded={handleTrimAdded}
- onTrimSpanChange={handleTrimSpanChange}
- onTrimDelete={handleTrimDelete}
- selectedTrimId={selectedTrimId}
- onSelectTrim={handleSelectTrim}
- speedRegions={speedRegions}
- onSpeedAdded={handleSpeedAdded}
- onSpeedSpanChange={handleSpeedSpanChange}
- onSpeedDelete={handleSpeedDelete}
- selectedSpeedId={selectedSpeedId}
- onSelectSpeed={handleSelectSpeed}
- audioRegions={audioRegions}
- onAudioAdded={handleAudioAdded}
- onAudioSpanChange={handleAudioSpanChange}
- onAudioDelete={handleAudioDelete}
- selectedAudioId={selectedAudioId}
- onSelectAudio={handleSelectAudio}
- annotationRegions={annotationRegions}
- onAnnotationAdded={handleAnnotationAdded}
- onAnnotationSpanChange={handleAnnotationSpanChange}
- onAnnotationDelete={handleAnnotationDelete}
- selectedAnnotationId={selectedAnnotationId}
- onSelectAnnotation={handleSelectAnnotation}
- aspectRatio={aspectRatio}
- onAspectRatioChange={setAspectRatio}
- />
-- </div>
-- </Panel>
-- </PanelGroup>
-- </div>
--
- {/* Right section: settings panel */}
- <SettingsPanel
- {/* Right section: settings panel */}
- <SettingsPanel
-- selected={wallpaper}
-- onWallpaperChange={setWallpaper}
- selectedZoomDepth={
- selectedZoomId ? zoomRegions.find((z) => z.id === selectedZoomId)?.depth : null
- }
- selectedZoomDepth={selectedZoomId ? zoomRegions.find(z => z.id === selectedZoomId)?.depth : null}
-- onZoomDepthChange={(depth) => selectedZoomId && handleZoomDepthChange(depth)}
-- selectedZoomId={selectedZoomId}
-- onZoomDelete={handleZoomDelete}
-- selectedTrimId={selectedTrimId}
-- onTrimDelete={handleTrimDelete}
-- shadowIntensity={shadowIntensity}
-- onShadowChange={setShadowIntensity}
-- backgroundBlur={backgroundBlur}
-- onBackgroundBlurChange={setBackgroundBlur}
-- zoomMotionBlur={zoomMotionBlur}
-- onZoomMotionBlurChange={setZoomMotionBlur}
-- connectZooms={connectZooms}
-- onConnectZoomsChange={setConnectZooms}
-- showCursor={showCursor}
-- onShowCursorChange={setShowCursor}
-- loopCursor={loopCursor}
-- onLoopCursorChange={setLoopCursor}
-- cursorSize={cursorSize}
-- onCursorSizeChange={setCursorSize}
-- cursorSmoothing={cursorSmoothing}
-- onCursorSmoothingChange={setCursorSmoothing}
-- cursorMotionBlur={cursorMotionBlur}
-- onCursorMotionBlurChange={setCursorMotionBlur}
-- cursorClickBounce={cursorClickBounce}
-- onCursorClickBounceChange={setCursorClickBounce}
- cursorSway={cursorSway}
- onCursorSwayChange={setCursorSway}
-- borderRadius={borderRadius}
-- onBorderRadiusChange={setBorderRadius}
-- padding={padding}
-- onPaddingChange={setPadding}
-- cropRegion={cropRegion}
-- onCropChange={setCropRegion}
-- aspectRatio={aspectRatio}
-- videoElement={videoPlaybackRef.current?.video || null}
-- exportQuality={exportQuality}
-- onExportQualityChange={setExportQuality}
-- exportFormat={exportFormat}
-- onExportFormatChange={setExportFormat}
-- gifFrameRate={gifFrameRate}
-- onGifFrameRateChange={setGifFrameRate}
-- gifLoop={gifLoop}
-- onGifLoopChange={setGifLoop}
-- gifSizePreset={gifSizePreset}
-- onGifSizePresetChange={setGifSizePreset}
-- gifOutputDimensions={calculateOutputDimensions(
-- videoPlaybackRef.current?.video?.videoWidth || 1920,
-- videoPlaybackRef.current?.video?.videoHeight || 1080,
-- gifSizePreset,
- GIF_SIZE_PRESETS,
- GIF_SIZE_PRESETS
-- )}
-- onExport={handleOpenExportDialog}
-- selectedAnnotationId={selectedAnnotationId}
-- annotationRegions={annotationRegions}
-- onAnnotationContentChange={handleAnnotationContentChange}
-- onAnnotationTypeChange={handleAnnotationTypeChange}
-- onAnnotationStyleChange={handleAnnotationStyleChange}
-- onAnnotationFigureDataChange={handleAnnotationFigureDataChange}
-- onAnnotationDelete={handleAnnotationDelete}
-- onSaveProject={handleSaveProject}
-- onLoadProject={handleLoadProject}
-- selectedSpeedId={selectedSpeedId}
- selectedSpeedValue={
- selectedSpeedId
- ? (speedRegions.find((r) => r.id === selectedSpeedId)?.speed ?? null)
- : null
- }
- selectedSpeedValue={selectedSpeedId ? speedRegions.find(r => r.id === selectedSpeedId)?.speed ?? null : null}
-- onSpeedChange={handleSpeedChange}
-- onSpeedDelete={handleSpeedDelete}
-- />
-- </div>
--
-- <Toaster theme="dark" className="pointer-events-auto" />
-
-
-- <ExportDialog
-- isOpen={showExportDialog}
-- onClose={handleExportDialogClose}
-- progress={exportProgress}
-- isExporting={isExporting}
-- error={exportError}
-- onCancel={handleCancelExport}
-- onRetrySave={handleRetrySaveExport}
-- canRetrySave={hasPendingExportSave}
-- exportFormat={exportFormat}
-- exportedFilePath={exportedFilePath}
-- />
-- </div>
-- );
++ const { t } = useI18n();
++ 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 [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 [connectZooms, setConnectZooms] = useState(initialEditorPreferences.connectZooms);
++ const [showCursor, setShowCursor] = useState(initialEditorPreferences.showCursor);
++ const [loopCursor, setLoopCursor] = useState(initialEditorPreferences.loopCursor);
++ const [cursorSize, setCursorSize] = useState(initialEditorPreferences.cursorSize);
++ const [cursorSmoothing, setCursorSmoothing] = useState(initialEditorPreferences.cursorSmoothing);
++ const [cursorMotionBlur, setCursorMotionBlur] = useState(
++ initialEditorPreferences.cursorMotionBlur,
++ );
++ const [cursorClickBounce, setCursorClickBounce] = useState(
++ initialEditorPreferences.cursorClickBounce,
++ );
++ const [cursorSway, setCursorSway] = useState(initialEditorPreferences.cursorSway);
++ const [borderRadius, setBorderRadius] = useState(initialEditorPreferences.borderRadius);
++ const [padding, setPadding] = useState(initialEditorPreferences.padding);
++ const [cropRegion, setCropRegion] = useState<CropRegion>(initialEditorPreferences.cropRegion);
++ const [zoomRegions, setZoomRegions] = useState<ZoomRegion[]>([]);
++ const [cursorTelemetry, setCursorTelemetry] = useState<CursorTelemetryPoint[]>([]);
++ const [selectedZoomId, setSelectedZoomId] = useState<string | null>(null);
++ const [trimRegions, setTrimRegions] = useState<TrimRegion[]>([]);
++ const [selectedTrimId, setSelectedTrimId] = useState<string | null>(null);
++ const [speedRegions, setSpeedRegions] = useState<SpeedRegion[]>([]);
++ const [selectedSpeedId, setSelectedSpeedId] = useState<string | null>(null);
++ const [annotationRegions, setAnnotationRegions] = useState<AnnotationRegion[]>([]);
++ const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);
++ const [audioRegions, setAudioRegions] = useState<AudioRegion[]>([]);
++ const [selectedAudioId, setSelectedAudioId] = useState<string | null>(null);
++ const [isExporting, setIsExporting] = useState(false);
++ const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);
++ const [exportError, setExportError] = useState<string | null>(null);
++ const [showExportDialog, setShowExportDialog] = useState(false);
++ const [aspectRatio, setAspectRatio] = useState<AspectRatio>(initialEditorPreferences.aspectRatio);
++ const [exportQuality, setExportQuality] = useState<ExportQuality>(
++ initialEditorPreferences.exportQuality,
++ );
++ 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 [exportedFilePath, setExportedFilePath] = useState<string | undefined>(undefined);
++ const [hasPendingExportSave, setHasPendingExportSave] = useState(false);
++ const [lastSavedSnapshot, setLastSavedSnapshot] = useState<string | null>(null);
++
++ const videoPlaybackRef = useRef<VideoPlaybackRef>(null);
++ const nextZoomIdRef = useRef(1);
++ const nextTrimIdRef = useRef(1);
++ const nextSpeedIdRef = useRef(1);
++ const nextAudioIdRef = useRef(1);
++
++ const { shortcuts, isMac } = useShortcuts();
++ const nextAnnotationIdRef = useRef(1);
++ const nextAnnotationZIndexRef = useRef(1); // Track z-index for stacking order
++ const exporterRef = useRef<VideoExporter | null>(null);
++ const autoSuggestedVideoPathRef = useRef<string | null>(null);
++ const historyPastRef = useRef<EditorHistorySnapshot[]>([]);
++ const historyFutureRef = useRef<EditorHistorySnapshot[]>([]);
++ const historyCurrentRef = useRef<EditorHistorySnapshot | null>(null);
++ const applyingHistoryRef = useRef(false);
++ const pendingExportSaveRef = useRef<PendingExportSave | null>(null);
++
++ const cloneSnapshot = useCallback((snapshot: EditorHistorySnapshot): EditorHistorySnapshot => {
++ return {
++ zoomRegions: JSON.parse(JSON.stringify(snapshot.zoomRegions)),
++ trimRegions: JSON.parse(JSON.stringify(snapshot.trimRegions)),
++ speedRegions: JSON.parse(JSON.stringify(snapshot.speedRegions)),
++ annotationRegions: JSON.parse(JSON.stringify(snapshot.annotationRegions)),
++ audioRegions: JSON.parse(JSON.stringify(snapshot.audioRegions)),
++ selectedZoomId: snapshot.selectedZoomId,
++ selectedTrimId: snapshot.selectedTrimId,
++ selectedSpeedId: snapshot.selectedSpeedId,
++ selectedAnnotationId: snapshot.selectedAnnotationId,
++ selectedAudioId: snapshot.selectedAudioId,
++ };
++ }, []);
++
++ const buildHistorySnapshot = useCallback((): EditorHistorySnapshot => {
++ return {
++ zoomRegions,
++ trimRegions,
++ speedRegions,
++ annotationRegions,
++ audioRegions,
++ selectedZoomId,
++ selectedTrimId,
++ selectedSpeedId,
++ selectedAnnotationId,
++ selectedAudioId,
++ };
++ }, [
++ zoomRegions,
++ trimRegions,
++ speedRegions,
++ annotationRegions,
++ audioRegions,
++ selectedZoomId,
++ selectedTrimId,
++ selectedSpeedId,
++ selectedAnnotationId,
++ selectedAudioId,
++ ]);
++
++ const applyHistorySnapshot = useCallback(
++ (snapshot: EditorHistorySnapshot) => {
++ applyingHistoryRef.current = true;
++ const cloned = cloneSnapshot(snapshot);
++ setZoomRegions(cloned.zoomRegions);
++ setTrimRegions(cloned.trimRegions);
++ setSpeedRegions(cloned.speedRegions);
++ setAnnotationRegions(cloned.annotationRegions);
++ setAudioRegions(cloned.audioRegions);
++ setSelectedZoomId(cloned.selectedZoomId);
++ setSelectedTrimId(cloned.selectedTrimId);
++ setSelectedSpeedId(cloned.selectedSpeedId);
++ setSelectedAnnotationId(cloned.selectedAnnotationId);
++ setSelectedAudioId(cloned.selectedAudioId);
++
++ nextZoomIdRef.current = deriveNextId(
++ "zoom",
++ cloned.zoomRegions.map((region) => region.id),
++ );
++ nextTrimIdRef.current = deriveNextId(
++ "trim",
++ cloned.trimRegions.map((region) => region.id),
++ );
++ nextSpeedIdRef.current = deriveNextId(
++ "speed",
++ cloned.speedRegions.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;
++ },
++ [cloneSnapshot],
++ );
++
++ const handleUndo = useCallback(() => {
++ if (historyPastRef.current.length === 0) return;
++
++ const current = historyCurrentRef.current ?? cloneSnapshot(buildHistorySnapshot());
++ const previous = historyPastRef.current.pop();
++ if (!previous) return;
++
++ historyFutureRef.current.push(cloneSnapshot(current));
++ historyCurrentRef.current = cloneSnapshot(previous);
++ applyHistorySnapshot(previous);
++ }, [applyHistorySnapshot, buildHistorySnapshot, cloneSnapshot]);
++
++ const handleRedo = useCallback(() => {
++ if (historyFutureRef.current.length === 0) return;
++
++ const current = historyCurrentRef.current ?? cloneSnapshot(buildHistorySnapshot());
++ const next = historyFutureRef.current.pop();
++ if (!next) return;
++
++ historyPastRef.current.push(cloneSnapshot(current));
++ historyCurrentRef.current = cloneSnapshot(next);
++ applyHistorySnapshot(next);
++ }, [applyHistorySnapshot, buildHistorySnapshot, cloneSnapshot]);
++
++ const applyLoadedProject = useCallback(async (candidate: unknown, path?: string | null) => {
++ if (!validateProjectData(candidate)) {
++ return false;
++ }
++
++ const project = candidate;
++ const sourcePath = fromFileUrl(project.videoPath);
++ const normalizedEditor = normalizeProjectEditor(project.editor);
++
++ try {
++ videoPlaybackRef.current?.pause();
++ } catch {
++ // no-op
++ }
++ setIsPlaying(false);
++ setCurrentTime(0);
++ setDuration(0);
++
++ setError(null);
++ setVideoSourcePath(sourcePath);
++ setVideoPath(toFileUrl(sourcePath));
++ setCurrentProjectPath(path ?? null);
++
++ setWallpaper(normalizedEditor.wallpaper);
++ setShadowIntensity(normalizedEditor.shadowIntensity);
++ setBackgroundBlur(normalizedEditor.backgroundBlur);
++ setZoomMotionBlur(normalizedEditor.zoomMotionBlur);
++ setConnectZooms(normalizedEditor.connectZooms);
++ setShowCursor(normalizedEditor.showCursor);
++ setLoopCursor(normalizedEditor.loopCursor);
++ setCursorSize(normalizedEditor.cursorSize);
++ setCursorSmoothing(normalizedEditor.cursorSmoothing);
++ setCursorMotionBlur(normalizedEditor.cursorMotionBlur);
++ setCursorClickBounce(normalizedEditor.cursorClickBounce);
++ setCursorSway(normalizedEditor.cursorSway);
++ setBorderRadius(normalizedEditor.borderRadius);
++ setPadding(normalizedEditor.padding);
++ setCropRegion(normalizedEditor.cropRegion);
++ setZoomRegions(normalizedEditor.zoomRegions);
++ setTrimRegions(normalizedEditor.trimRegions);
++ setSpeedRegions(normalizedEditor.speedRegions);
++ setAnnotationRegions(normalizedEditor.annotationRegions);
++ setAudioRegions(normalizedEditor.audioRegions);
++ setAspectRatio(normalizedEditor.aspectRatio);
++ setExportQuality(normalizedEditor.exportQuality);
++ setExportFormat(normalizedEditor.exportFormat);
++ setGifFrameRate(normalizedEditor.gifFrameRate);
++ setGifLoop(normalizedEditor.gifLoop);
++ setGifSizePreset(normalizedEditor.gifSizePreset);
++
++ setSelectedZoomId(null);
++ setSelectedTrimId(null);
++ setSelectedSpeedId(null);
++ setSelectedAnnotationId(null);
++ setSelectedAudioId(null);
++
++ nextZoomIdRef.current = deriveNextId(
++ "zoom",
++ normalizedEditor.zoomRegions.map((region) => region.id),
++ );
++ nextTrimIdRef.current = deriveNextId(
++ "trim",
++ normalizedEditor.trimRegions.map((region) => region.id),
++ );
++ nextSpeedIdRef.current = deriveNextId(
++ "speed",
++ normalizedEditor.speedRegions.map((region) => region.id),
++ );
++ 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;
++
++ setLastSavedSnapshot(JSON.stringify(createProjectData(sourcePath, normalizedEditor)));
++ return true;
++ }, []);
++
++ const currentProjectSnapshot = useMemo(() => {
++ const sourcePath = videoSourcePath ?? (videoPath ? fromFileUrl(videoPath) : null);
++ if (!sourcePath) {
++ return null;
++ }
++ return JSON.stringify(
++ createProjectData(sourcePath, {
++ wallpaper,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ showCursor,
++ loopCursor,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ borderRadius,
++ padding,
++ cropRegion,
++ zoomRegions,
++ trimRegions,
++ speedRegions,
++ annotationRegions,
++ audioRegions,
++ aspectRatio,
++ exportQuality,
++ exportFormat,
++ gifFrameRate,
++ gifLoop,
++ gifSizePreset,
++ }),
++ );
++ }, [
++ videoPath,
++ videoSourcePath,
++ wallpaper,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ showCursor,
++ loopCursor,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ borderRadius,
++ padding,
++ cropRegion,
++ zoomRegions,
++ trimRegions,
++ speedRegions,
++ audioRegions,
++ annotationRegions,
++ aspectRatio,
++ exportQuality,
++ exportFormat,
++ gifFrameRate,
++ gifLoop,
++ gifSizePreset,
++ ]);
++
++ useEffect(() => {
++ const snapshot = cloneSnapshot(buildHistorySnapshot());
++
++ if (!historyCurrentRef.current) {
++ historyCurrentRef.current = snapshot;
++ return;
++ }
++
++ if (applyingHistoryRef.current) {
++ historyCurrentRef.current = snapshot;
++ applyingHistoryRef.current = false;
++ return;
++ }
++
++ const currentSerialized = JSON.stringify(historyCurrentRef.current);
++ const nextSerialized = JSON.stringify(snapshot);
++ if (currentSerialized === nextSerialized) {
++ return;
++ }
++
++ historyPastRef.current.push(cloneSnapshot(historyCurrentRef.current));
++ if (historyPastRef.current.length > 100) {
++ historyPastRef.current.shift();
++ }
++ historyCurrentRef.current = snapshot;
++ historyFutureRef.current = [];
++ }, [buildHistorySnapshot, cloneSnapshot]);
++
++ const hasUnsavedChanges = Boolean(
++ currentProjectPath &&
++ currentProjectSnapshot &&
++ lastSavedSnapshot &&
++ currentProjectSnapshot !== lastSavedSnapshot,
++ );
++
++ useEffect(() => {
++ async function loadInitialData() {
++ try {
++ const currentProjectResult = await window.electronAPI.loadCurrentProjectFile();
++ if (currentProjectResult.success && currentProjectResult.project) {
++ const restored = await applyLoadedProject(
++ currentProjectResult.project,
++ currentProjectResult.path ?? null,
++ );
++ if (restored) {
++ return;
++ }
++ }
++
++ const result = await window.electronAPI.getCurrentVideoPath();
++ if (result.success && result.path) {
++ const sourcePath = fromFileUrl(result.path);
++ setVideoSourcePath(sourcePath);
++ setVideoPath(toFileUrl(sourcePath));
++ setCurrentProjectPath(null);
++ setLastSavedSnapshot(null);
++ } else {
++ setError("No video to load. Please record or select a video.");
++ }
++ } catch (err) {
++ setError("Error loading video: " + String(err));
++ } finally {
++ setLoading(false);
++ }
++ }
++
++ loadInitialData();
++ }, [applyLoadedProject]);
++
++ useEffect(() => {
++ saveEditorPreferences({
++ wallpaper,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ showCursor,
++ loopCursor,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ borderRadius,
++ padding,
++ cropRegion,
++ aspectRatio,
++ exportQuality,
++ exportFormat,
++ gifFrameRate,
++ gifLoop,
++ gifSizePreset,
++ });
++ }, [
++ wallpaper,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ showCursor,
++ loopCursor,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ borderRadius,
++ padding,
++ cropRegion,
++ aspectRatio,
++ exportQuality,
++ exportFormat,
++ gifFrameRate,
++ gifLoop,
++ gifSizePreset,
++ ]);
++
++ const saveProject = useCallback(
++ async (forceSaveAs: boolean) => {
++ if (!videoPath) {
++ toast.error("No video loaded");
++ return;
++ }
++
++ const sourcePath = videoSourcePath ?? fromFileUrl(videoPath);
++ if (!sourcePath) {
++ toast.error("Unable to determine source video path");
++ return;
++ }
++
++ const projectData = createProjectData(sourcePath, {
++ wallpaper,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ showCursor,
++ loopCursor,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ borderRadius,
++ padding,
++ cropRegion,
++ zoomRegions,
++ trimRegions,
++ speedRegions,
++ annotationRegions,
++ audioRegions,
++ aspectRatio,
++ exportQuality,
++ exportFormat,
++ gifFrameRate,
++ gifLoop,
++ gifSizePreset,
++ });
++
++ const fileNameBase =
++ sourcePath
++ .split(/[\\/]/)
++ .pop()
++ ?.replace(/\.[^.]+$/, "") || `project-${Date.now()}`;
++ const projectSnapshot = JSON.stringify(projectData);
++ const result = await window.electronAPI.saveProjectFile(
++ projectData,
++ fileNameBase,
++ forceSaveAs ? undefined : (currentProjectPath ?? undefined),
++ );
++
++ if (result.canceled) {
++ toast.info("Project save canceled");
++ return;
++ }
++
++ if (!result.success) {
++ toast.error(result.message || "Failed to save project");
++ return;
++ }
++
++ if (result.path) {
++ setCurrentProjectPath(result.path);
++ }
++ setLastSavedSnapshot(projectSnapshot);
++
++ toast.success(`Project saved to ${result.path}`);
++ },
++ [
++ videoPath,
++ videoSourcePath,
++ currentProjectPath,
++ wallpaper,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ showCursor,
++ loopCursor,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ borderRadius,
++ padding,
++ cropRegion,
++ zoomRegions,
++ trimRegions,
++ speedRegions,
++ annotationRegions,
++ audioRegions,
++ aspectRatio,
++ exportQuality,
++ exportFormat,
++ gifFrameRate,
++ gifLoop,
++ gifSizePreset,
++ ],
++ );
++
++ useEffect(() => {
++ const handleBeforeUnload = (event: BeforeUnloadEvent) => {
++ if (!hasUnsavedChanges) {
++ return;
++ }
++
++ event.preventDefault();
++ event.returnValue = "";
++ };
++
++ window.addEventListener("beforeunload", handleBeforeUnload);
++ return () => window.removeEventListener("beforeunload", handleBeforeUnload);
++ }, [hasUnsavedChanges]);
++
++ useEffect(() => {
++ window.electronAPI.setHasUnsavedChanges(hasUnsavedChanges);
++ }, [hasUnsavedChanges]);
++
++ useEffect(() => {
++ const cleanup = window.electronAPI.onRequestSaveBeforeClose(async () => {
++ await saveProject(false);
++ });
++
++ return () => cleanup?.();
++ }, [saveProject]);
++
++ const handleSaveProject = useCallback(async () => {
++ await saveProject(false);
++ }, [saveProject]);
++
++ const handleSaveProjectAs = useCallback(async () => {
++ await saveProject(true);
++ }, [saveProject]);
++
++ const handleLoadProject = useCallback(async () => {
++ const result = await window.electronAPI.loadProjectFile();
++
++ if (result.canceled) {
++ return;
++ }
++
++ if (!result.success) {
++ toast.error(result.message || "Failed to load project");
++ return;
++ }
++
++ const restored = await applyLoadedProject(result.project, result.path ?? null);
++ if (!restored) {
++ toast.error("Invalid project file format");
++ return;
++ }
++
++ toast.success(`Project loaded from ${result.path}`);
++ }, [applyLoadedProject]);
++
++ useEffect(() => {
++ const removeLoadListener = window.electronAPI.onMenuLoadProject(handleLoadProject);
++ const removeSaveListener = window.electronAPI.onMenuSaveProject(handleSaveProject);
++ const removeSaveAsListener = window.electronAPI.onMenuSaveProjectAs(handleSaveProjectAs);
++
++ return () => {
++ removeLoadListener?.();
++ removeSaveListener?.();
++ removeSaveAsListener?.();
++ };
++ }, [handleLoadProject, handleSaveProject, handleSaveProjectAs]);
++
++ useEffect(() => {
++ let mounted = true;
++
++ async function loadCursorTelemetry() {
++ if (!videoPath) {
++ if (mounted) {
++ setCursorTelemetry([]);
++ }
++ return;
++ }
++
++ try {
++ const result = await window.electronAPI.getCursorTelemetry(fromFileUrl(videoPath));
++ if (mounted) {
++ setCursorTelemetry(result.success ? result.samples : []);
++ }
++ } catch (telemetryError) {
++ console.warn("Unable to load cursor telemetry:", telemetryError);
++ if (mounted) {
++ setCursorTelemetry([]);
++ }
++ }
++ }
++
++ loadCursorTelemetry();
++
++ return () => {
++ mounted = false;
++ };
++ }, [videoPath]);
++
++ 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]);
++
++ const effectiveZoomRegions = useMemo(() => {
++ if (!loopCursor || zoomRegions.length === 0) {
++ return zoomRegions;
++ }
++
++ if (displayedTimelineWindow.endMs <= displayedTimelineWindow.startMs) {
++ return zoomRegions;
++ }
++
++ const dominantAtStart = findDominantRegion(zoomRegions, displayedTimelineWindow.startMs, {
++ connectZooms,
++ }).region;
++ if (!dominantAtStart) {
++ return zoomRegions;
++ }
++
++ const endWindowStartMs = Math.max(
++ displayedTimelineWindow.startMs,
++ displayedTimelineWindow.endMs - LOOP_CURSOR_END_WINDOW_MS,
++ );
++ const loopEndRegion: ZoomRegion = {
++ id: `${dominantAtStart.id}__loop-end-sync`,
++ startMs: endWindowStartMs,
++ endMs: displayedTimelineWindow.endMs,
++ depth: dominantAtStart.depth,
++ focus: {
++ cx: dominantAtStart.focus.cx,
++ cy: dominantAtStart.focus.cy,
++ },
++ };
++
++ return [...zoomRegions.filter((region) => region.id !== loopEndRegion.id), loopEndRegion];
++ }, [loopCursor, zoomRegions, displayedTimelineWindow, connectZooms]);
++
++ useEffect(() => {
++ if (
++ !videoPath ||
++ duration <= 0 ||
++ zoomRegions.length > 0 ||
++ normalizedCursorTelemetry.length < 2
++ ) {
++ return;
++ }
++
++ if (autoSuggestedVideoPathRef.current === videoPath) {
++ return;
++ }
++
++ const totalMs = Math.max(0, Math.round(duration * 1000));
++ if (totalMs <= 0) {
++ return;
++ }
++
++ const candidates = detectInteractionCandidates(normalizedCursorTelemetry);
++ if (candidates.length === 0) {
++ autoSuggestedVideoPathRef.current = videoPath;
++ return;
++ }
++
++ const DEFAULT_DURATION_MS = 1100;
++ const MIN_SPACING_MS = 1800;
++ const sortedCandidates = [...candidates].sort((a, b) => b.strength - a.strength);
++ const acceptedCenters: number[] = [];
++
++ setZoomRegions((prev) => {
++ if (prev.length > 0) {
++ return prev;
++ }
++
++ const reservedSpans: Array<{ start: number; end: number }> = [];
++ const additions: ZoomRegion[] = [];
++ let nextId = nextZoomIdRef.current;
++
++ sortedCandidates.forEach((candidate) => {
++ const tooCloseToAccepted = acceptedCenters.some(
++ (center) => Math.abs(center - candidate.centerTimeMs) < MIN_SPACING_MS,
++ );
++ if (tooCloseToAccepted) {
++ return;
++ }
++
++ const centeredStart = Math.round(candidate.centerTimeMs - DEFAULT_DURATION_MS / 2);
++ const startMs = Math.max(0, Math.min(centeredStart, totalMs - DEFAULT_DURATION_MS));
++ const endMs = Math.min(totalMs, startMs + DEFAULT_DURATION_MS);
++
++ const hasOverlap = reservedSpans.some((span) => endMs > span.start && startMs < span.end);
++ if (hasOverlap) {
++ return;
++ }
++
++ additions.push({
++ id: `zoom-${nextId++}`,
++ startMs,
++ endMs,
++ depth: DEFAULT_ZOOM_DEPTH,
++ focus: clampFocusToDepth(candidate.focus, DEFAULT_ZOOM_DEPTH),
++ });
++ reservedSpans.push({ start: startMs, end: endMs });
++ acceptedCenters.push(candidate.centerTimeMs);
++ });
++
++ if (additions.length === 0) {
++ return prev;
++ }
++
++ nextZoomIdRef.current = nextId;
++ return [...prev, ...additions];
++ });
++
++ autoSuggestedVideoPathRef.current = videoPath;
++ }, [videoPath, duration, normalizedCursorTelemetry, zoomRegions.length]);
++
++ // Initialize default wallpaper with resolved asset path
++ useEffect(() => {
++ let mounted = true;
++ (async () => {
++ try {
++ const resolvedPath = await getAssetPath(DEFAULT_WALLPAPER_RELATIVE_PATH);
++ if (mounted) {
++ setWallpaper(resolvedPath);
++ }
++ } catch (err) {
++ // If resolution fails, keep the fallback
++ console.warn("Failed to resolve default wallpaper path:", err);
++ }
++ })();
++ return () => {
++ mounted = false;
++ };
++ }, []);
++
++ function togglePlayPause() {
++ const playback = videoPlaybackRef.current;
++ const video = playback?.video;
++ if (!playback || !video) return;
++
++ if (isPlaying) {
++ playback.pause();
++ } else {
++ playback.play().catch((err) => console.error("Video play failed:", err));
++ }
++ }
++
++ function handleSeek(time: number) {
++ const video = videoPlaybackRef.current?.video;
++ if (!video) return;
++ video.currentTime = time;
++ }
++
++ const handleSelectZoom = useCallback((id: string | null) => {
++ setSelectedZoomId(id);
++ if (id) {
++ setSelectedTrimId(null);
++ setSelectedAudioId(null);
++ }
++ }, []);
++
++ const handleSelectTrim = useCallback((id: string | null) => {
++ setSelectedTrimId(id);
++ if (id) {
++ setSelectedZoomId(null);
++ setSelectedAnnotationId(null);
++ setSelectedAudioId(null);
++ }
++ }, []);
++
++ const handleSelectAnnotation = useCallback((id: string | null) => {
++ setSelectedAnnotationId(id);
++ if (id) {
++ setSelectedZoomId(null);
++ setSelectedTrimId(null);
++ setSelectedAudioId(null);
++ }
++ }, []);
++
++ const handleZoomAdded = useCallback((span: Span) => {
++ const id = `zoom-${nextZoomIdRef.current++}`;
++ const newRegion: ZoomRegion = {
++ id,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ depth: DEFAULT_ZOOM_DEPTH,
++ focus: { cx: 0.5, cy: 0.5 },
++ };
++ setZoomRegions((prev) => [...prev, newRegion]);
++ setSelectedZoomId(id);
++ setSelectedTrimId(null);
++ setSelectedAnnotationId(null);
++ }, []);
++
++ const handleZoomSuggested = useCallback((span: Span, focus: ZoomFocus) => {
++ const id = `zoom-${nextZoomIdRef.current++}`;
++ const newRegion: ZoomRegion = {
++ id,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ depth: DEFAULT_ZOOM_DEPTH,
++ focus: clampFocusToDepth(focus, DEFAULT_ZOOM_DEPTH),
++ };
++ setZoomRegions((prev) => [...prev, newRegion]);
++ setSelectedZoomId(id);
++ setSelectedTrimId(null);
++ setSelectedAnnotationId(null);
++ }, []);
++
++ const handleTrimAdded = useCallback((span: Span) => {
++ const id = `trim-${nextTrimIdRef.current++}`;
++ const newRegion: TrimRegion = {
++ id,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ };
++ setTrimRegions((prev) => [...prev, newRegion]);
++ setSelectedTrimId(id);
++ setSelectedZoomId(null);
++ setSelectedAnnotationId(null);
++ }, []);
++
++ const handleZoomSpanChange = useCallback((id: string, span: Span) => {
++ setZoomRegions((prev) =>
++ prev.map((region) =>
++ region.id === id
++ ? {
++ ...region,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ }
++ : region,
++ ),
++ );
++ }, []);
++
++ const handleTrimSpanChange = useCallback((id: string, span: Span) => {
++ setTrimRegions((prev) =>
++ prev.map((region) =>
++ region.id === id
++ ? {
++ ...region,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ }
++ : region,
++ ),
++ );
++ }, []);
++
++ const handleZoomFocusChange = useCallback((id: string, focus: ZoomFocus) => {
++ setZoomRegions((prev) =>
++ prev.map((region) =>
++ region.id === id
++ ? {
++ ...region,
++ focus: clampFocusToDepth(focus, region.depth),
++ }
++ : region,
++ ),
++ );
++ }, []);
++
++ const handleZoomDepthChange = useCallback(
++ (depth: ZoomDepth) => {
++ if (!selectedZoomId) return;
++ setZoomRegions((prev) =>
++ prev.map((region) =>
++ region.id === selectedZoomId
++ ? {
++ ...region,
++ depth,
++ focus: clampFocusToDepth(region.focus, depth),
++ }
++ : region,
++ ),
++ );
++ },
++ [selectedZoomId],
++ );
++
++ const handleZoomDelete = useCallback(
++ (id: string) => {
++ setZoomRegions((prev) => prev.filter((region) => region.id !== id));
++ if (selectedZoomId === id) {
++ setSelectedZoomId(null);
++ }
++ },
++ [selectedZoomId],
++ );
++
++ const handleTrimDelete = useCallback(
++ (id: string) => {
++ setTrimRegions((prev) => prev.filter((region) => region.id !== id));
++ if (selectedTrimId === id) {
++ setSelectedTrimId(null);
++ }
++ },
++ [selectedTrimId],
++ );
++
++ const handleSelectSpeed = useCallback((id: string | null) => {
++ setSelectedSpeedId(id);
++ if (id) {
++ setSelectedZoomId(null);
++ setSelectedTrimId(null);
++ setSelectedAnnotationId(null);
++ setSelectedAudioId(null);
++ }
++ }, []);
++
++ const handleSpeedAdded = useCallback((span: Span) => {
++ const id = `speed-${nextSpeedIdRef.current++}`;
++ const newRegion: SpeedRegion = {
++ id,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ speed: DEFAULT_PLAYBACK_SPEED,
++ };
++ setSpeedRegions((prev) => [...prev, newRegion]);
++ setSelectedSpeedId(id);
++ setSelectedZoomId(null);
++ setSelectedTrimId(null);
++ setSelectedAnnotationId(null);
++ }, []);
++
++ const handleSpeedSpanChange = useCallback((id: string, span: Span) => {
++ setSpeedRegions((prev) =>
++ prev.map((region) =>
++ region.id === id
++ ? {
++ ...region,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ }
++ : region,
++ ),
++ );
++ }, []);
++
++ const handleSpeedDelete = useCallback(
++ (id: string) => {
++ setSpeedRegions((prev) => prev.filter((region) => region.id !== id));
++ if (selectedSpeedId === id) {
++ setSelectedSpeedId(null);
++ }
++ },
++ [selectedSpeedId],
++ );
++
++ const handleSelectAudio = useCallback((id: string | null) => {
++ setSelectedAudioId(id);
++ if (id) {
++ setSelectedZoomId(null);
++ setSelectedTrimId(null);
++ setSelectedAnnotationId(null);
++ setSelectedSpeedId(null);
++ }
++ }, []);
++
++ const handleAudioAdded = useCallback((span: Span, audioPath: string) => {
++ const id = `audio-${nextAudioIdRef.current++}`;
++ const newRegion: AudioRegion = {
++ id,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ audioPath,
++ volume: 1,
++ };
++ setAudioRegions((prev) => [...prev, newRegion]);
++ setSelectedAudioId(id);
++ setSelectedZoomId(null);
++ setSelectedTrimId(null);
++ setSelectedAnnotationId(null);
++ setSelectedSpeedId(null);
++ }, []);
++
++ const handleAudioSpanChange = useCallback((id: string, span: Span) => {
++ setAudioRegions((prev) =>
++ prev.map((region) =>
++ region.id === id
++ ? {
++ ...region,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ }
++ : region,
++ ),
++ );
++ }, []);
++
++ const handleAudioDelete = useCallback(
++ (id: string) => {
++ setAudioRegions((prev) => prev.filter((region) => region.id !== id));
++ if (selectedAudioId === id) {
++ setSelectedAudioId(null);
++ }
++ },
++ [selectedAudioId],
++ );
++
++ const handleSpeedChange = useCallback(
++ (speed: PlaybackSpeed) => {
++ if (!selectedSpeedId) return;
++ setSpeedRegions((prev) =>
++ prev.map((region) => (region.id === selectedSpeedId ? { ...region, speed } : region)),
++ );
++ },
++ [selectedSpeedId],
++ );
++
++ const handleAnnotationAdded = useCallback((span: Span) => {
++ const id = `annotation-${nextAnnotationIdRef.current++}`;
++ const zIndex = nextAnnotationZIndexRef.current++; // Assign z-index based on creation order
++ const newRegion: AnnotationRegion = {
++ id,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ type: "text",
++ content: "Enter text...",
++ position: { ...DEFAULT_ANNOTATION_POSITION },
++ size: { ...DEFAULT_ANNOTATION_SIZE },
++ style: { ...DEFAULT_ANNOTATION_STYLE },
++ zIndex,
++ };
++ setAnnotationRegions((prev) => [...prev, newRegion]);
++ setSelectedAnnotationId(id);
++ setSelectedZoomId(null);
++ setSelectedTrimId(null);
++ }, []);
++
++ const handleAnnotationSpanChange = useCallback((id: string, span: Span) => {
++ setAnnotationRegions((prev) =>
++ prev.map((region) =>
++ region.id === id
++ ? {
++ ...region,
++ startMs: Math.round(span.start),
++ endMs: Math.round(span.end),
++ }
++ : region,
++ ),
++ );
++ }, []);
++
++ const handleAnnotationDelete = useCallback(
++ (id: string) => {
++ setAnnotationRegions((prev) => prev.filter((region) => region.id !== id));
++ if (selectedAnnotationId === id) {
++ setSelectedAnnotationId(null);
++ }
++ },
++ [selectedAnnotationId],
++ );
++
++ const handleAnnotationContentChange = useCallback((id: string, content: string) => {
++ setAnnotationRegions((prev) => {
++ const updated = prev.map((region) => {
++ if (region.id !== id) return region;
++
++ // Store content in type-specific fields
++ if (region.type === "text") {
++ return { ...region, content, textContent: content };
++ } else if (region.type === "image") {
++ return { ...region, content, imageContent: content };
++ } else {
++ return { ...region, content };
++ }
++ });
++ return updated;
++ });
++ }, []);
++
++ const handleAnnotationTypeChange = useCallback((id: string, type: AnnotationRegion["type"]) => {
++ setAnnotationRegions((prev) => {
++ const updated = prev.map((region) => {
++ if (region.id !== id) return region;
++
++ const updatedRegion = { ...region, type };
++
++ // Restore content from type-specific storage
++ if (type === "text") {
++ updatedRegion.content = region.textContent || "Enter text...";
++ } else if (type === "image") {
++ updatedRegion.content = region.imageContent || "";
++ } else if (type === "figure") {
++ updatedRegion.content = "";
++ if (!region.figureData) {
++ updatedRegion.figureData = { ...DEFAULT_FIGURE_DATA };
++ }
++ }
++
++ return updatedRegion;
++ });
++ return updated;
++ });
++ }, []);
++
++ const handleAnnotationStyleChange = useCallback(
++ (id: string, style: Partial<AnnotationRegion["style"]>) => {
++ setAnnotationRegions((prev) =>
++ prev.map((region) =>
++ region.id === id ? { ...region, style: { ...region.style, ...style } } : region,
++ ),
++ );
++ },
++ [],
++ );
++
++ const handleAnnotationFigureDataChange = useCallback((id: string, figureData: FigureData) => {
++ setAnnotationRegions((prev) =>
++ prev.map((region) => (region.id === id ? { ...region, figureData } : region)),
++ );
++ }, []);
++
++ const handleAnnotationPositionChange = useCallback(
++ (id: string, position: { x: number; y: number }) => {
++ setAnnotationRegions((prev) =>
++ prev.map((region) => (region.id === id ? { ...region, position } : region)),
++ );
++ },
++ [],
++ );
++
++ const handleAnnotationSizeChange = useCallback(
++ (id: string, size: { width: number; height: number }) => {
++ setAnnotationRegions((prev) =>
++ prev.map((region) => (region.id === id ? { ...region, size } : region)),
++ );
++ },
++ [],
++ );
++
++ // Global Tab prevention
++ useEffect(() => {
++ const handleKeyDown = (e: KeyboardEvent) => {
++ 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) {
++ playback.play().catch(console.error);
++ } else {
++ playback.pause();
++ }
++ }
++ }
++ };
++
++ window.addEventListener("keydown", handleKeyDown, { capture: true });
++ return () => window.removeEventListener("keydown", handleKeyDown, { capture: true });
++ }, [shortcuts, isMac, handleUndo, handleRedo]);
++
++ useEffect(() => {
++ if (selectedZoomId && !zoomRegions.some((region) => region.id === selectedZoomId)) {
++ setSelectedZoomId(null);
++ }
++ }, [selectedZoomId, zoomRegions]);
++
++ useEffect(() => {
++ if (selectedTrimId && !trimRegions.some((region) => region.id === selectedTrimId)) {
++ setSelectedTrimId(null);
++ }
++ }, [selectedTrimId, trimRegions]);
++
++ useEffect(() => {
++ if (
++ selectedAnnotationId &&
++ !annotationRegions.some((region) => region.id === selectedAnnotationId)
++ ) {
++ setSelectedAnnotationId(null);
++ }
++ }, [selectedAnnotationId, annotationRegions]);
++
++ useEffect(() => {
++ if (selectedSpeedId && !speedRegions.some((region) => region.id === selectedSpeedId)) {
++ setSelectedSpeedId(null);
++ }
++ }, [selectedSpeedId, speedRegions]);
++
++ useEffect(() => {
++ if (selectedAudioId && !audioRegions.some((region) => region.id === selectedAudioId)) {
++ setSelectedAudioId(null);
++ }
++ }, [selectedAudioId, audioRegions]);
++
++ // Audio playback sync: manage Audio elements that play in sync with video
++ const audioElementsRef = useRef<Map<string, HTMLAudioElement>>(new Map());
++
++ useEffect(() => {
++ const existing = audioElementsRef.current;
++ const currentIds = new Set(audioRegions.map((r) => r.id));
++
++ // Remove old audio elements
++ for (const [id, audio] of existing) {
++ if (!currentIds.has(id)) {
++ audio.pause();
++ audio.src = "";
++ existing.delete(id);
++ }
++ }
++
++ // Create/update audio elements
++ for (const region of audioRegions) {
++ let audio = existing.get(region.id);
++ if (!audio) {
++ audio = new Audio();
++ audio.preload = "auto";
++ existing.set(region.id, audio);
++ }
++ const expectedSrc = toFileUrl(region.audioPath);
++ if (audio.src !== expectedSrc) {
++ audio.src = expectedSrc;
++ }
++ audio.volume = Math.max(0, Math.min(1, region.volume));
++ }
++
++ return () => {
++ for (const audio of existing.values()) {
++ audio.pause();
++ audio.src = "";
++ }
++ existing.clear();
++ };
++ }, [audioRegions]);
++
++ // Sync audio playback with video currentTime and isPlaying state
++ useEffect(() => {
++ for (const region of audioRegions) {
++ const audio = audioElementsRef.current.get(region.id);
++ if (!audio) continue;
++
++ const currentTimeMs = currentTime * 1000;
++ const isInRegion = currentTimeMs >= region.startMs && currentTimeMs < region.endMs;
++
++ if (isPlaying && isInRegion) {
++ const audioOffset = (currentTimeMs - region.startMs) / 1000;
++ // Only seek if significantly out of sync (> 200ms)
++ if (Math.abs(audio.currentTime - audioOffset) > 0.2) {
++ audio.currentTime = audioOffset;
++ }
++ if (audio.paused) {
++ audio.play().catch(() => undefined);
++ }
++ } else {
++ if (!audio.paused) {
++ audio.pause();
++ }
++ }
++ }
++ }, [isPlaying, currentTime, audioRegions]);
++
++ 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);
++ pendingExportSaveRef.current = null;
++ setHasPendingExportSave(false);
++
++ let keepExportDialogOpen = false;
++
++ try {
++ const wasPlaying = isPlaying;
++ const restoreTime = video.currentTime;
++ if (wasPlaying) {
++ videoPlaybackRef.current?.pause();
++ }
++
++ const sourceWidth = video.videoWidth || 1920;
++ const sourceHeight = video.videoHeight || 1080;
++ const sourceAspectRatio = sourceHeight > 0 ? sourceWidth / sourceHeight : 16 / 9;
++ const aspectRatioValue = getAspectRatioValue(aspectRatio, sourceAspectRatio);
++
++ // Get preview CONTAINER dimensions for scaling
++ const playbackRef = videoPlaybackRef.current;
++ const containerElement = playbackRef?.containerRef?.current;
++ const previewWidth = containerElement?.clientWidth || 1920;
++ const previewHeight = containerElement?.clientHeight || 1080;
++
++ if (settings.format === "gif" && settings.gifConfig) {
++ // GIF Export
++ const gifExporter = new GifExporter({
++ videoUrl: videoPath,
++ width: settings.gifConfig.width,
++ height: settings.gifConfig.height,
++ frameRate: settings.gifConfig.frameRate,
++ loop: settings.gifConfig.loop,
++ sizePreset: settings.gifConfig.sizePreset,
++ wallpaper,
++ trimRegions,
++ speedRegions,
++ showShadow: shadowIntensity > 0,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ borderRadius,
++ padding,
++ videoPadding: padding,
++ cropRegion,
++ annotationRegions,
++ zoomRegions: effectiveZoomRegions,
++ cursorTelemetry: effectiveCursorTelemetry,
++ showCursor,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ previewWidth,
++ previewHeight,
++ onProgress: (progress: ExportProgress) => {
++ setExportProgress(progress);
++ },
++ });
++
++ exporterRef.current = gifExporter as unknown as VideoExporter;
++ const result = await gifExporter.export();
++
++ if (result.success && result.blob) {
++ const arrayBuffer = await result.blob.arrayBuffer();
++ const timestamp = Date.now();
++ const fileName = `export-${timestamp}.gif`;
++
++ const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
++
++ if (saveResult.canceled) {
++ pendingExportSaveRef.current = { arrayBuffer, fileName };
++ 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) {
++ showExportSuccessToast(saveResult.path);
++ setExportedFilePath(saveResult.path);
++ } else {
++ setExportError(saveResult.message || "Failed to save GIF");
++ toast.error(saveResult.message || "Failed to save GIF");
++ }
++ } else {
++ setExportError(result.error || "GIF export failed");
++ toast.error(result.error || "GIF export failed");
++ }
++ } else {
++ // MP4 Export
++ const quality = settings.quality || exportQuality;
++ let exportWidth: number;
++ let exportHeight: number;
++ let bitrate: number;
++
++ if (quality === "source") {
++ // Use source resolution
++ exportWidth = sourceWidth;
++ exportHeight = sourceHeight;
++
++ if (aspectRatio === "native") {
++ exportWidth = Math.floor(sourceWidth / 2) * 2;
++ exportHeight = Math.floor(sourceHeight / 2) * 2;
++ } else if (aspectRatioValue === 1) {
++ // Square (1:1): use smaller dimension to avoid codec limits
++ const baseDimension = Math.floor(Math.min(sourceWidth, sourceHeight) / 2) * 2;
++ exportWidth = baseDimension;
++ exportHeight = baseDimension;
++ } else if (aspectRatioValue > 1) {
++ // Landscape: find largest even dimensions that exactly match aspect ratio
++ const baseWidth = Math.floor(sourceWidth / 2) * 2;
++ let found = false;
++ for (let w = baseWidth; w >= 100 && !found; w -= 2) {
++ const h = Math.round(w / aspectRatioValue);
++ if (h % 2 === 0 && Math.abs(w / h - aspectRatioValue) < 0.0001) {
++ exportWidth = w;
++ exportHeight = h;
++ found = true;
++ }
++ }
++ if (!found) {
++ exportWidth = baseWidth;
++ exportHeight = Math.floor(baseWidth / aspectRatioValue / 2) * 2;
++ }
++ } else {
++ // Portrait: find largest even dimensions that exactly match aspect ratio
++ const baseHeight = Math.floor(sourceHeight / 2) * 2;
++ let found = false;
++ for (let h = baseHeight; h >= 100 && !found; h -= 2) {
++ const w = Math.round(h * aspectRatioValue);
++ if (w % 2 === 0 && Math.abs(w / h - aspectRatioValue) < 0.0001) {
++ exportWidth = w;
++ exportHeight = h;
++ found = true;
++ }
++ }
++ if (!found) {
++ exportHeight = baseHeight;
++ exportWidth = Math.floor((baseHeight * aspectRatioValue) / 2) * 2;
++ }
++ }
++
++ // Calculate visually lossless bitrate matching screen recording optimization
++ const totalPixels = exportWidth * exportHeight;
++ bitrate = 30_000_000;
++ if (totalPixels > 1920 * 1080 && totalPixels <= 2560 * 1440) {
++ bitrate = 50_000_000;
++ } else if (totalPixels > 2560 * 1440) {
++ bitrate = 80_000_000;
++ }
++ } else {
++ // Use quality-based target resolution
++ const targetHeight = quality === "medium" ? 720 : 1080;
++
++ // Calculate dimensions maintaining aspect ratio
++ exportHeight = Math.floor(targetHeight / 2) * 2;
++ exportWidth = Math.floor((exportHeight * aspectRatioValue) / 2) * 2;
++
++ // Adjust bitrate for lower resolutions
++ const totalPixels = exportWidth * exportHeight;
++ if (totalPixels <= 1280 * 720) {
++ bitrate = 10_000_000;
++ } else if (totalPixels <= 1920 * 1080) {
++ bitrate = 20_000_000;
++ } else {
++ bitrate = 30_000_000;
++ }
++ }
++
++ const exporter = new VideoExporter({
++ videoUrl: videoPath,
++ width: exportWidth,
++ height: exportHeight,
++ frameRate: 60,
++ bitrate,
++ codec: "avc1.640033",
++ wallpaper,
++ trimRegions,
++ speedRegions,
++ showShadow: shadowIntensity > 0,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ borderRadius,
++ padding,
++ cropRegion,
++ annotationRegions,
++ zoomRegions: effectiveZoomRegions,
++ cursorTelemetry: effectiveCursorTelemetry,
++ showCursor,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ audioRegions,
++ previewWidth,
++ previewHeight,
++ onProgress: (progress: ExportProgress) => {
++ setExportProgress(progress);
++ },
++ });
++
++ exporterRef.current = exporter;
++ const result = await exporter.export();
++
++ if (result.success && result.blob) {
++ const arrayBuffer = await result.blob.arrayBuffer();
++ const timestamp = Date.now();
++ const fileName = `export-${timestamp}.mp4`;
++
++ const saveResult = await window.electronAPI.saveExportedVideo(arrayBuffer, fileName);
++
++ if (saveResult.canceled) {
++ pendingExportSaveRef.current = { arrayBuffer, fileName };
++ 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) {
++ showExportSuccessToast(saveResult.path);
++ setExportedFilePath(saveResult.path);
++ } else {
++ setExportError(saveResult.message || "Failed to save video");
++ toast.error(saveResult.message || "Failed to save video");
++ }
++ } else {
++ setExportError(result.error || "Export failed");
++ toast.error(result.error || "Export failed");
++ }
++ }
++
++ if (wasPlaying) {
++ videoPlaybackRef.current?.play();
++ } else {
++ video.currentTime = restoreTime;
++ await videoPlaybackRef.current?.refreshFrame();
++ }
++ } catch (error) {
++ console.error("Export error:", error);
++ const errorMessage = error instanceof Error ? error.message : "Unknown error";
++ setExportError(errorMessage);
++ toast.error(`Export failed: ${errorMessage}`);
++ } finally {
++ if (!isPlaying) {
++ await videoPlaybackRef.current?.refreshFrame().catch(() => undefined);
++ }
++ setIsExporting(false);
++ exporterRef.current = null;
++ setShowExportDialog(keepExportDialogOpen);
++ setExportProgress(null);
++ }
++ },
++ [
++ videoPath,
++ wallpaper,
++ trimRegions,
++ speedRegions,
++ shadowIntensity,
++ backgroundBlur,
++ zoomMotionBlur,
++ connectZooms,
++ showCursor,
++ effectiveCursorTelemetry,
++ cursorSize,
++ cursorSmoothing,
++ cursorMotionBlur,
++ cursorClickBounce,
++ cursorSway,
++ audioRegions,
++ borderRadius,
++ padding,
++ cropRegion,
++ annotationRegions,
++ isPlaying,
++ aspectRatio,
++ exportQuality,
++ effectiveZoomRegions,
++ showExportSuccessToast,
++ ],
++ );
++
++ const handleOpenExportDialog = useCallback(() => {
++ if (!videoPath) {
++ toast.error("No video loaded");
++ return;
++ }
++
++ if (hasPendingExportSave) {
++ setShowExportDialog(true);
++ setExportError("Save dialog canceled. Click Save Again to save without re-rendering.");
++ return;
++ }
++
++ const video = videoPlaybackRef.current?.video;
++ if (!video) {
++ toast.error("Video not ready");
++ return;
++ }
++
++ // Build export settings from current state
++ const sourceWidth = video.videoWidth || 1920;
++ const sourceHeight = video.videoHeight || 1080;
++ const gifDimensions = calculateOutputDimensions(
++ sourceWidth,
++ sourceHeight,
++ gifSizePreset,
++ GIF_SIZE_PRESETS,
++ );
++
++ const settings: ExportSettings = {
++ format: exportFormat,
++ quality: exportFormat === "mp4" ? exportQuality : undefined,
++ gifConfig:
++ exportFormat === "gif"
++ ? {
++ frameRate: gifFrameRate,
++ loop: gifLoop,
++ sizePreset: gifSizePreset,
++ width: gifDimensions.width,
++ height: gifDimensions.height,
++ }
++ : undefined,
++ };
++
++ setShowExportDialog(true);
++ setExportError(null);
++
++ // Start export immediately
++ handleExport(settings);
++ }, [
++ videoPath,
++ hasPendingExportSave,
++ exportFormat,
++ exportQuality,
++ gifFrameRate,
++ gifLoop,
++ gifSizePreset,
++ handleExport,
++ ]);
++
++ const handleCancelExport = useCallback(() => {
++ if (exporterRef.current) {
++ exporterRef.current.cancel();
++ toast.info("Export canceled");
++ setShowExportDialog(false);
++ setIsExporting(false);
++ setExportProgress(null);
++ setExportError(null);
++ setExportedFilePath(undefined);
++ }
++ }, []);
++
++ const handleExportDialogClose = useCallback(() => {
++ setShowExportDialog(false);
++ setExportedFilePath(undefined);
++ }, []);
++
++ const handleRetrySaveExport = useCallback(async () => {
++ const pendingSave = pendingExportSaveRef.current;
++ if (!pendingSave) {
++ return;
++ }
++
++ const saveResult = await window.electronAPI.saveExportedVideo(
++ pendingSave.arrayBuffer,
++ pendingSave.fileName,
++ );
++
++ 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) {
++ pendingExportSaveRef.current = null;
++ setHasPendingExportSave(false);
++ setExportError(null);
++ setExportedFilePath(saveResult.path);
++ showExportSuccessToast(saveResult.path);
++ setShowExportDialog(false);
++ return;
++ }
++
++ const errorMessage = saveResult.message || "Failed to save video";
++ setExportError(errorMessage);
++ toast.error(errorMessage);
++ }, [showExportSuccessToast]);
++
++ const openRecordingsFolder = useCallback(async () => {
++ try {
++ const result = await window.electronAPI.openRecordingsFolder();
++ if (!result.success) {
++ toast.error(result.message || result.error || "Failed to open recordings folder.");
++ }
++ } catch (error) {
++ toast.error(`Failed to open recordings folder: ${String(error)}`);
++ }
++ }, []);
++
++ if (loading) {
++ return (
++ <div className="flex items-center justify-center h-screen bg-background">
++ <div className="text-foreground">Loading video...</div>
++ </div>
++ );
++ }
++ if (error) {
++ return (
++ <div className="flex items-center justify-center h-screen bg-background">
++ <div className="flex flex-col items-center gap-3">
++ <div className="text-destructive">{error}</div>
++ <button
++ type="button"
++ onClick={handleLoadProject}
++ className="px-3 py-1.5 rounded-md bg-[#2563EB] text-white text-sm hover:bg-[#2563EB]/90"
++ >
++ Load Project File
++ </button>
++ </div>
++ </div>
++ );
++ }
++
++ return (
++ <div className="flex flex-col h-screen bg-[#09090b] text-slate-200 overflow-hidden selection:bg-[#2563EB]/30">
++ <div
++ className="relative h-10 flex-shrink-0 bg-[#09090b]/80 backdrop-blur-md border-b border-white/5 flex items-center justify-center px-6 z-50"
++ style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
++ >
++ <span className="text-sm font-semibold tracking-tight text-white/90">Recordly</span>
++ <div
++ className="absolute right-4 flex items-center gap-1"
++ style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
++ >
++ <LanguageSwitcher />
++ <button
++ type="button"
++ onClick={() => void openRecordingsFolder()}
++ className="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-white/90 transition hover:bg-white/8 hover:text-white cursor-pointer"
++ title={t("common.app.manageRecordings", "Open recordings folder")}
++ aria-label={t("common.app.manageRecordings", "Open recordings folder")}
++ >
++ <FolderOpen className="h-4 w-4" />
++ <span className="text-xs font-normal">
++ {t("common.app.manageRecordings", "Manage recordings")}
++ </span>
++ </button>
++ </div>
++ </div>
++
++ <div className="flex-1 p-5 gap-4 flex min-h-0 relative">
++ {/* Left Column - Video & Timeline */}
++ <div className="flex-[7] flex flex-col gap-3 min-w-0 h-full">
++ <PanelGroup direction="vertical" className="gap-3">
++ {/* Top section: video preview and controls */}
++ <Panel defaultSize={70} minSize={40}>
++ <div className="w-full h-full flex flex-col items-center justify-center bg-black/40 rounded-2xl border border-white/5 shadow-2xl overflow-hidden">
++ {/* Video preview */}
++ <div
++ className="w-full flex justify-center items-center"
++ style={{ flex: "1 1 auto", margin: "6px 0 0" }}
++ >
++ <div
++ className="relative"
++ style={{
++ width: "auto",
++ height: "100%",
++ aspectRatio: getAspectRatioValue(
++ aspectRatio,
++ (() => {
++ const previewVideo = videoPlaybackRef.current?.video;
++ if (previewVideo && previewVideo.videoHeight > 0) {
++ return previewVideo.videoWidth / previewVideo.videoHeight;
++ }
++ return 16 / 9;
++ })(),
++ ),
++ maxWidth: "100%",
++ margin: "0 auto",
++ boxSizing: "border-box",
++ }}
++ >
++ <VideoPlayback
++ key={videoPath || "no-video"}
++ aspectRatio={aspectRatio}
++ ref={videoPlaybackRef}
++ videoPath={videoPath || ""}
++ onDurationChange={setDuration}
++ onTimeUpdate={setCurrentTime}
++ currentTime={currentTime}
++ onPlayStateChange={setIsPlaying}
++ onError={setError}
++ wallpaper={wallpaper}
++ zoomRegions={effectiveZoomRegions}
++ selectedZoomId={selectedZoomId}
++ onSelectZoom={handleSelectZoom}
++ onZoomFocusChange={handleZoomFocusChange}
++ isPlaying={isPlaying}
++ showShadow={shadowIntensity > 0}
++ shadowIntensity={shadowIntensity}
++ backgroundBlur={backgroundBlur}
++ zoomMotionBlur={zoomMotionBlur}
++ connectZooms={connectZooms}
++ borderRadius={borderRadius}
++ padding={padding}
++ cropRegion={cropRegion}
++ trimRegions={trimRegions}
++ speedRegions={speedRegions}
++ annotationRegions={annotationRegions}
++ selectedAnnotationId={selectedAnnotationId}
++ onSelectAnnotation={handleSelectAnnotation}
++ onAnnotationPositionChange={handleAnnotationPositionChange}
++ onAnnotationSizeChange={handleAnnotationSizeChange}
++ cursorTelemetry={effectiveCursorTelemetry}
++ showCursor={showCursor}
++ cursorSize={cursorSize}
++ cursorSmoothing={cursorSmoothing}
++ cursorMotionBlur={cursorMotionBlur}
++ cursorClickBounce={cursorClickBounce}
++ cursorSway={cursorSway}
++ />
++ </div>
++ </div>
++ {/* Playback controls */}
++ <div
++ className="w-full flex justify-center items-center"
++ style={{
++ height: "48px",
++ flexShrink: 0,
++ padding: "6px 12px",
++ margin: "6px 0 6px 0",
++ }}
++ >
++ <div style={{ width: "100%", maxWidth: "700px" }}>
++ <PlaybackControls
++ isPlaying={isPlaying}
++ currentTime={currentTime}
++ duration={duration}
++ onTogglePlayPause={togglePlayPause}
++ onSeek={handleSeek}
++ />
++ </div>
++ </div>
++ </div>
++ </Panel>
++
++ <PanelResizeHandle className="h-3 bg-[#09090b]/80 hover:bg-[#09090b] transition-colors rounded-full mx-4 flex items-center justify-center">
++ <div className="w-8 h-1 bg-white/20 rounded-full"></div>
++ </PanelResizeHandle>
++
++ {/* Timeline section */}
++ <Panel defaultSize={30} minSize={20}>
++ <div className="h-full min-h-0 bg-[#09090b] rounded-2xl border border-white/5 shadow-lg overflow-auto flex flex-col">
++ <TimelineEditor
++ videoDuration={duration}
++ currentTime={currentTime}
++ onSeek={handleSeek}
++ cursorTelemetry={effectiveCursorTelemetry}
++ zoomRegions={effectiveZoomRegions}
++ onZoomAdded={handleZoomAdded}
++ onZoomSuggested={handleZoomSuggested}
++ onZoomSpanChange={handleZoomSpanChange}
++ onZoomDelete={handleZoomDelete}
++ selectedZoomId={selectedZoomId}
++ onSelectZoom={handleSelectZoom}
++ trimRegions={trimRegions}
++ onTrimAdded={handleTrimAdded}
++ onTrimSpanChange={handleTrimSpanChange}
++ onTrimDelete={handleTrimDelete}
++ selectedTrimId={selectedTrimId}
++ onSelectTrim={handleSelectTrim}
++ speedRegions={speedRegions}
++ onSpeedAdded={handleSpeedAdded}
++ onSpeedSpanChange={handleSpeedSpanChange}
++ onSpeedDelete={handleSpeedDelete}
++ selectedSpeedId={selectedSpeedId}
++ onSelectSpeed={handleSelectSpeed}
++ audioRegions={audioRegions}
++ onAudioAdded={handleAudioAdded}
++ onAudioSpanChange={handleAudioSpanChange}
++ onAudioDelete={handleAudioDelete}
++ selectedAudioId={selectedAudioId}
++ onSelectAudio={handleSelectAudio}
++ annotationRegions={annotationRegions}
++ onAnnotationAdded={handleAnnotationAdded}
++ onAnnotationSpanChange={handleAnnotationSpanChange}
++ onAnnotationDelete={handleAnnotationDelete}
++ selectedAnnotationId={selectedAnnotationId}
++ onSelectAnnotation={handleSelectAnnotation}
++ aspectRatio={aspectRatio}
++ onAspectRatioChange={setAspectRatio}
++ />
++ </div>
++ </Panel>
++ </PanelGroup>
++ </div>
++
++ {/* Right section: settings panel */}
++ <SettingsPanel
++ selected={wallpaper}
++ onWallpaperChange={setWallpaper}
++ selectedZoomDepth={
++ selectedZoomId ? zoomRegions.find((z) => z.id === selectedZoomId)?.depth : null
++ }
++ onZoomDepthChange={(depth) => selectedZoomId && handleZoomDepthChange(depth)}
++ selectedZoomId={selectedZoomId}
++ onZoomDelete={handleZoomDelete}
++ selectedTrimId={selectedTrimId}
++ onTrimDelete={handleTrimDelete}
++ shadowIntensity={shadowIntensity}
++ onShadowChange={setShadowIntensity}
++ backgroundBlur={backgroundBlur}
++ onBackgroundBlurChange={setBackgroundBlur}
++ zoomMotionBlur={zoomMotionBlur}
++ onZoomMotionBlurChange={setZoomMotionBlur}
++ connectZooms={connectZooms}
++ onConnectZoomsChange={setConnectZooms}
++ showCursor={showCursor}
++ onShowCursorChange={setShowCursor}
++ loopCursor={loopCursor}
++ onLoopCursorChange={setLoopCursor}
++ cursorSize={cursorSize}
++ onCursorSizeChange={setCursorSize}
++ cursorSmoothing={cursorSmoothing}
++ onCursorSmoothingChange={setCursorSmoothing}
++ cursorMotionBlur={cursorMotionBlur}
++ onCursorMotionBlurChange={setCursorMotionBlur}
++ cursorClickBounce={cursorClickBounce}
++ onCursorClickBounceChange={setCursorClickBounce}
++ cursorSway={cursorSway}
++ onCursorSwayChange={setCursorSway}
++ borderRadius={borderRadius}
++ onBorderRadiusChange={setBorderRadius}
++ padding={padding}
++ onPaddingChange={setPadding}
++ cropRegion={cropRegion}
++ onCropChange={setCropRegion}
++ aspectRatio={aspectRatio}
++ videoElement={videoPlaybackRef.current?.video || null}
++ exportQuality={exportQuality}
++ onExportQualityChange={setExportQuality}
++ exportFormat={exportFormat}
++ onExportFormatChange={setExportFormat}
++ gifFrameRate={gifFrameRate}
++ onGifFrameRateChange={setGifFrameRate}
++ gifLoop={gifLoop}
++ onGifLoopChange={setGifLoop}
++ gifSizePreset={gifSizePreset}
++ onGifSizePresetChange={setGifSizePreset}
++ gifOutputDimensions={calculateOutputDimensions(
++ videoPlaybackRef.current?.video?.videoWidth || 1920,
++ videoPlaybackRef.current?.video?.videoHeight || 1080,
++ gifSizePreset,
++ GIF_SIZE_PRESETS,
++ )}
++ onExport={handleOpenExportDialog}
++ selectedAnnotationId={selectedAnnotationId}
++ annotationRegions={annotationRegions}
++ onAnnotationContentChange={handleAnnotationContentChange}
++ onAnnotationTypeChange={handleAnnotationTypeChange}
++ onAnnotationStyleChange={handleAnnotationStyleChange}
++ onAnnotationFigureDataChange={handleAnnotationFigureDataChange}
++ onAnnotationDelete={handleAnnotationDelete}
++ onSaveProject={handleSaveProject}
++ onLoadProject={handleLoadProject}
++ selectedSpeedId={selectedSpeedId}
++ selectedSpeedValue={
++ selectedSpeedId
++ ? (speedRegions.find((r) => r.id === selectedSpeedId)?.speed ?? null)
++ : null
++ }
++ onSpeedChange={handleSpeedChange}
++ onSpeedDelete={handleSpeedDelete}
++ />
++ </div>
++
++ <Toaster theme="dark" className="pointer-events-auto" />
++
++ <ExportDialog
++ isOpen={showExportDialog}
++ onClose={handleExportDialogClose}
++ progress={exportProgress}
++ isExporting={isExporting}
++ error={exportError}
++ onCancel={handleCancelExport}
++ onRetrySave={handleRetrySaveExport}
++ canRetrySave={hasPendingExportSave}
++ exportFormat={exportFormat}
++ exportedFilePath={exportedFilePath}
++ />
++ </div>
++ );
}
diff --cc src/components/video-editor/projectPersistence.ts
index 6445b46c,af4e1aff..b5e03439
--- a/src/components/video-editor/projectPersistence.ts
+++ b/src/components/video-editor/projectPersistence.ts
@@@ -1,505 -1,391 +1,426 @@@
- import {
- ASPECT_RATIOS,
- type AspectRatio,
- isCustomAspectRatio,
- } from "@/utils/aspectRatioUtils";
- import type {
- ExportFormat,
- ExportQuality,
- GifFrameRate,
- GifSizePreset,
- } from "@/lib/exporter";
-import { ASPECT_RATIOS, type AspectRatio, isCustomAspectRatio } from "@/utils/aspectRatioUtils";
+ import type { ExportFormat, ExportQuality, GifFrameRate, GifSizePreset } from "@/lib/exporter";
import { WALLPAPER_PATHS } from "@/lib/wallpapers";
++import { ASPECT_RATIOS, type AspectRatio, isCustomAspectRatio } from "@/utils/aspectRatioUtils";
import {
-- DEFAULT_CURSOR_CLICK_BOUNCE,
-- DEFAULT_CURSOR_MOTION_BLUR,
-- DEFAULT_CURSOR_SIZE,
-- DEFAULT_CURSOR_SMOOTHING,
- DEFAULT_CURSOR_SWAY,
-- DEFAULT_ANNOTATION_POSITION,
-- DEFAULT_ANNOTATION_SIZE,
-- DEFAULT_ANNOTATION_STYLE,
-- DEFAULT_CROP_REGION,
-- DEFAULT_PLAYBACK_SPEED,
-- DEFAULT_FIGURE_DATA,
-- DEFAULT_ZOOM_DEPTH,
-- DEFAULT_ZOOM_MOTION_BLUR,
-- type AnnotationRegion,
-- type CropRegion,
-- type SpeedRegion,
-- type TrimRegion,
- type AudioRegion,
-- type ZoomRegion,
++ type AnnotationRegion,
++ type AudioRegion,
++ type CropRegion,
++ DEFAULT_ANNOTATION_POSITION,
++ DEFAULT_ANNOTATION_SIZE,
++ DEFAULT_ANNOTATION_STYLE,
++ DEFAULT_CROP_REGION,
++ DEFAULT_CURSOR_CLICK_BOUNCE,
++ DEFAULT_CURSOR_MOTION_BLUR,
++ DEFAULT_CURSOR_SIZE,
++ DEFAULT_CURSOR_SMOOTHING,
++ DEFAULT_CURSOR_SWAY,
++ DEFAULT_FIGURE_DATA,
++ DEFAULT_PLAYBACK_SPEED,
++ DEFAULT_ZOOM_DEPTH,
++ DEFAULT_ZOOM_MOTION_BLUR,
++ type SpeedRegion,
++ type TrimRegion,
++ type ZoomRegion,
} from "./types";
export const PROJECT_VERSION = 1;
export interface ProjectEditorState {
-- wallpaper: string;
-- shadowIntensity: number;
-- backgroundBlur: number;
-- zoomMotionBlur: number;
-- connectZooms: boolean;
-- showCursor: boolean;
-- loopCursor: boolean;
-- cursorSize: number;
-- cursorSmoothing: number;
-- cursorMotionBlur: number;
-- cursorClickBounce: number;
- cursorSway: number;
-- borderRadius: number;
-- padding: number;
-- cropRegion: CropRegion;
-- zoomRegions: ZoomRegion[];
-- trimRegions: TrimRegion[];
-- speedRegions: SpeedRegion[];
-- annotationRegions: AnnotationRegion[];
- audioRegions: AudioRegion[];
-- aspectRatio: AspectRatio;
-- exportQuality: ExportQuality;
-- exportFormat: ExportFormat;
-- gifFrameRate: GifFrameRate;
-- gifLoop: boolean;
-- gifSizePreset: GifSizePreset;
++ wallpaper: string;
++ shadowIntensity: number;
++ backgroundBlur: number;
++ zoomMotionBlur: number;
++ connectZooms: boolean;
++ showCursor: boolean;
++ loopCursor: boolean;
++ cursorSize: number;
++ cursorSmoothing: number;
++ cursorMotionBlur: number;
++ cursorClickBounce: number;
++ cursorSway: number;
++ borderRadius: number;
++ padding: number;
++ cropRegion: CropRegion;
++ zoomRegions: ZoomRegion[];
++ trimRegions: TrimRegion[];
++ speedRegions: SpeedRegion[];
++ annotationRegions: AnnotationRegion[];
++ audioRegions: AudioRegion[];
++ aspectRatio: AspectRatio;
++ exportQuality: ExportQuality;
++ exportFormat: ExportFormat;
++ gifFrameRate: GifFrameRate;
++ gifLoop: boolean;
++ gifSizePreset: GifSizePreset;
}
export interface EditorProjectData {
-- version: number;
-- videoPath: string;
-- editor: ProjectEditorState;
++ version: number;
++ videoPath: string;
++ editor: ProjectEditorState;
}
function isFiniteNumber(value: unknown): value is number {
-- return typeof value === "number" && Number.isFinite(value);
++ return typeof value === "number" && Number.isFinite(value);
}
function clamp(value: number, min: number, max: number) {
-- return Math.min(max, Math.max(min, value));
++ return Math.min(max, Math.max(min, value));
}
function isFileUrl(value: string): boolean {
-- return /^file:\/\//i.test(value);
++ return /^file:\/\//i.test(value);
}
- function encodePathSegments(
- pathname: string,
- keepWindowsDrive = false,
- ): string {
- return pathname
- .split("/")
- .map((segment, index) => {
- if (!segment) return "";
- if (keepWindowsDrive && index === 1 && /^[a-zA-Z]:$/.test(segment)) {
- return segment;
- }
- return encodeURIComponent(segment);
- })
- .join("/");
+ function encodePathSegments(pathname: string, keepWindowsDrive = false): string {
- return pathname
- .split("/")
- .map((segment, index) => {
- if (!segment) return "";
- if (keepWindowsDrive && index === 1 && /^[a-zA-Z]:$/.test(segment)) {
- return segment;
- }
- return encodeURIComponent(segment);
- })
- .join("/");
++ return pathname
++ .split("/")
++ .map((segment, index) => {
++ if (!segment) return "";
++ if (keepWindowsDrive && index === 1 && /^[a-zA-Z]:$/.test(segment)) {
++ return segment;
++ }
++ return encodeURIComponent(segment);
++ })
++ .join("/");
}
export function toFileUrl(filePath: string): string {
-- const normalized = filePath.replace(/\\/g, "/");
--
-- // Windows drive path: C:/Users/...
-- if (/^[a-zA-Z]:\//.test(normalized)) {
-- return `file://${encodePathSegments(`/${normalized}`, true)}`;
-- }
--
-- // UNC path: //server/share/...
-- if (normalized.startsWith("//")) {
-- const [host, ...pathParts] = normalized.replace(/^\/+/, "").split("/");
- const encodedPath = pathParts
- .map((part) => encodeURIComponent(part))
- .join("/");
- const encodedPath = pathParts.map((part) => encodeURIComponent(part)).join("/");
-- return encodedPath ? `file://${host}/${encodedPath}` : `file://${host}/`;
-- }
--
- const absolutePath = normalized.startsWith("/")
- ? normalized
- : `/${normalized}`;
- const absolutePath = normalized.startsWith("/") ? normalized : `/${normalized}`;
-- return `file://${encodePathSegments(absolutePath)}`;
++ const normalized = filePath.replace(/\\/g, "/");
++
++ // Windows drive path: C:/Users/...
++ if (/^[a-zA-Z]:\//.test(normalized)) {
++ return `file://${encodePathSegments(`/${normalized}`, true)}`;
++ }
++
++ // UNC path: //server/share/...
++ if (normalized.startsWith("//")) {
++ const [host, ...pathParts] = normalized.replace(/^\/+/, "").split("/");
++ const encodedPath = pathParts.map((part) => encodeURIComponent(part)).join("/");
++ return encodedPath ? `file://${host}/${encodedPath}` : `file://${host}/`;
++ }
++
++ const absolutePath = normalized.startsWith("/") ? normalized : `/${normalized}`;
++ return `file://${encodePathSegments(absolutePath)}`;
}
export function fromFileUrl(fileUrl: string): string {
-- const value = fileUrl.trim();
-- if (!isFileUrl(value)) {
-- return fileUrl;
-- }
--
-- try {
-- const url = new URL(value);
-- const pathname = decodeURIComponent(url.pathname);
--
-- if (url.host && url.host !== "localhost") {
-- const uncPath = `//${url.host}${pathname.startsWith("/") ? pathname : `/${pathname}`}`;
-- return uncPath.replace(/\//g, "\\");
-- }
--
-- if (/^\/[A-Za-z]:/.test(pathname)) {
-- return pathname.slice(1);
-- }
--
-- return pathname;
-- } catch {
-- const rawFallbackPath = value.replace(/^file:\/\//i, "");
-- let fallbackPath = rawFallbackPath;
-- try {
-- fallbackPath = decodeURIComponent(rawFallbackPath);
-- } catch {
-- // Keep raw best-effort path if percent decoding fails.
-- }
-- return fallbackPath.replace(/^\/([a-zA-Z]:)/, "$1");
-- }
++ const value = fileUrl.trim();
++ if (!isFileUrl(value)) {
++ return fileUrl;
++ }
++
++ try {
++ const url = new URL(value);
++ const pathname = decodeURIComponent(url.pathname);
++
++ if (url.host && url.host !== "localhost") {
++ const uncPath = `//${url.host}${pathname.startsWith("/") ? pathname : `/${pathname}`}`;
++ return uncPath.replace(/\//g, "\\");
++ }
++
++ if (/^\/[A-Za-z]:/.test(pathname)) {
++ return pathname.slice(1);
++ }
++
++ return pathname;
++ } catch {
++ const rawFallbackPath = value.replace(/^file:\/\//i, "");
++ let fallbackPath = rawFallbackPath;
++ try {
++ fallbackPath = decodeURIComponent(rawFallbackPath);
++ } catch {
++ // Keep raw best-effort path if percent decoding fails.
++ }
++ return fallbackPath.replace(/^\/([a-zA-Z]:)/, "$1");
++ }
}
export function deriveNextId(prefix: string, ids: string[]): number {
-- const max = ids.reduce((acc, id) => {
-- const match = id.match(new RegExp(`^${prefix}-(\\d+)$`));
-- if (!match) return acc;
-- const value = Number(match[1]);
-- return Number.isFinite(value) ? Math.max(acc, value) : acc;
-- }, 0);
-- return max + 1;
++ const max = ids.reduce((acc, id) => {
++ const match = id.match(new RegExp(`^${prefix}-(\\d+)$`));
++ if (!match) return acc;
++ const value = Number(match[1]);
++ return Number.isFinite(value) ? Math.max(acc, value) : acc;
++ }, 0);
++ return max + 1;
}
- export function validateProjectData(
- candidate: unknown,
- ): candidate is EditorProjectData {
- if (!candidate || typeof candidate !== "object") return false;
- const project = candidate as Partial<EditorProjectData>;
- if (typeof project.version !== "number") return false;
- if (typeof project.videoPath !== "string" || !project.videoPath) return false;
- if (!project.editor || typeof project.editor !== "object") return false;
- return true;
+ export function validateProjectData(candidate: unknown): candidate is EditorProjectData {
- if (!candidate || typeof candidate !== "object") return false;
- const project = candidate as Partial<EditorProjectData>;
- if (typeof project.version !== "number") return false;
- if (typeof project.videoPath !== "string" || !project.videoPath) return false;
- if (!project.editor || typeof project.editor !== "object") return false;
- return true;
++ if (!candidate || typeof candidate !== "object") return false;
++ const project = candidate as Partial<EditorProjectData>;
++ if (typeof project.version !== "number") return false;
++ if (typeof project.videoPath !== "string" || !project.videoPath) return false;
++ if (!project.editor || typeof project.editor !== "object") return false;
++ return true;
}
- export function normalizeProjectEditor(
- editor: Partial<ProjectEditorState>,
- ): ProjectEditorState {
- const validAspectRatios = new Set<AspectRatio>(ASPECT_RATIOS);
- const legacyMotionBlurEnabled = (
- editor as Partial<{ motionBlurEnabled: boolean }>
- ).motionBlurEnabled;
- const legacyShowBlur = (editor as Partial<{ showBlur: boolean }>).showBlur;
- const normalizedZoomMotionBlur = isFiniteNumber(
- (editor as Partial<ProjectEditorState>).zoomMotionBlur,
- )
- ? clamp(
- (editor as Partial<ProjectEditorState>).zoomMotionBlur as number,
- 0,
- 2,
- )
- : legacyMotionBlurEnabled
- ? 0.35
- : DEFAULT_ZOOM_MOTION_BLUR;
- const normalizedBackgroundBlur = isFiniteNumber(
- (editor as Partial<ProjectEditorState>).backgroundBlur,
- )
- ? clamp(
- (editor as Partial<ProjectEditorState>).backgroundBlur as number,
- 0,
- 8,
- )
- : legacyShowBlur
- ? 2
- : 0;
-
- const normalizedZoomRegions: ZoomRegion[] = Array.isArray(editor.zoomRegions)
- ? editor.zoomRegions
- .filter((region): region is ZoomRegion =>
- Boolean(region && typeof region.id === "string"),
- )
- .map((region) => {
- const rawStart = isFiniteNumber(region.startMs)
- ? Math.round(region.startMs)
- : 0;
- const rawEnd = isFiniteNumber(region.endMs)
- ? Math.round(region.endMs)
- : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
-
- return {
- id: region.id,
- startMs,
- endMs,
- depth: [1, 2, 3, 4, 5, 6].includes(region.depth)
- ? region.depth
- : DEFAULT_ZOOM_DEPTH,
- focus: {
- cx: clamp(
- isFiniteNumber(region.focus?.cx) ? region.focus.cx : 0.5,
- 0,
- 1,
- ),
- cy: clamp(
- isFiniteNumber(region.focus?.cy) ? region.focus.cy : 0.5,
- 0,
- 1,
- ),
- },
- };
- })
- : [];
-
- const normalizedTrimRegions: TrimRegion[] = Array.isArray(editor.trimRegions)
- ? editor.trimRegions
- .filter((region): region is TrimRegion =>
- Boolean(region && typeof region.id === "string"),
- )
- .map((region) => {
- const rawStart = isFiniteNumber(region.startMs)
- ? Math.round(region.startMs)
- : 0;
- const rawEnd = isFiniteNumber(region.endMs)
- ? Math.round(region.endMs)
- : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
- return {
- id: region.id,
- startMs,
- endMs,
- };
- })
- : [];
-
- const normalizedSpeedRegions: SpeedRegion[] = Array.isArray(
- editor.speedRegions,
- )
- ? editor.speedRegions
- .filter((region): region is SpeedRegion =>
- Boolean(region && typeof region.id === "string"),
- )
- .map((region) => {
- const rawStart = isFiniteNumber(region.startMs)
- ? Math.round(region.startMs)
- : 0;
- const rawEnd = isFiniteNumber(region.endMs)
- ? Math.round(region.endMs)
- : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
-
- const speed =
- region.speed === 0.25 ||
- region.speed === 0.5 ||
- region.speed === 0.75 ||
- region.speed === 1.25 ||
- region.speed === 1.5 ||
- region.speed === 1.75 ||
- region.speed === 2
- ? region.speed
- : DEFAULT_PLAYBACK_SPEED;
-
- return {
- id: region.id,
- startMs,
- endMs,
- speed,
- };
- })
- : [];
-
- const normalizedAnnotationRegions: AnnotationRegion[] = Array.isArray(
- editor.annotationRegions,
- )
- ? editor.annotationRegions
- .filter((region): region is AnnotationRegion =>
- Boolean(region && typeof region.id === "string"),
- )
- .map((region, index) => {
- const rawStart = isFiniteNumber(region.startMs)
- ? Math.round(region.startMs)
- : 0;
- const rawEnd = isFiniteNumber(region.endMs)
- ? Math.round(region.endMs)
- : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
-
- return {
- id: region.id,
- startMs,
- endMs,
- type:
- region.type === "image" || region.type === "figure"
- ? region.type
- : "text",
- content: typeof region.content === "string" ? region.content : "",
- textContent:
- typeof region.textContent === "string"
- ? region.textContent
- : undefined,
- imageContent:
- typeof region.imageContent === "string"
- ? region.imageContent
- : undefined,
- position: {
- x: clamp(
- isFiniteNumber(region.position?.x)
- ? region.position.x
- : DEFAULT_ANNOTATION_POSITION.x,
- 0,
- 100,
- ),
- y: clamp(
- isFiniteNumber(region.position?.y)
- ? region.position.y
- : DEFAULT_ANNOTATION_POSITION.y,
- 0,
- 100,
- ),
- },
- size: {
- width: clamp(
- isFiniteNumber(region.size?.width)
- ? region.size.width
- : DEFAULT_ANNOTATION_SIZE.width,
- 1,
- 200,
- ),
- height: clamp(
- isFiniteNumber(region.size?.height)
- ? region.size.height
- : DEFAULT_ANNOTATION_SIZE.height,
- 1,
- 200,
- ),
- },
- style: {
- ...DEFAULT_ANNOTATION_STYLE,
- ...(region.style && typeof region.style === "object"
- ? region.style
- : {}),
- },
- zIndex: isFiniteNumber(region.zIndex) ? region.zIndex : index + 1,
- figureData: region.figureData
- ? {
- ...DEFAULT_FIGURE_DATA,
- ...region.figureData,
- }
- : undefined,
- };
- })
- : [];
-
- const rawCropX = isFiniteNumber(editor.cropRegion?.x)
- ? editor.cropRegion.x
- : DEFAULT_CROP_REGION.x;
- const rawCropY = isFiniteNumber(editor.cropRegion?.y)
- ? editor.cropRegion.y
- : DEFAULT_CROP_REGION.y;
- const rawCropWidth = isFiniteNumber(editor.cropRegion?.width)
- ? editor.cropRegion.width
- : DEFAULT_CROP_REGION.width;
- const rawCropHeight = isFiniteNumber(editor.cropRegion?.height)
- ? editor.cropRegion.height
- : DEFAULT_CROP_REGION.height;
-
- const cropX = clamp(rawCropX, 0, 1);
- const cropY = clamp(rawCropY, 0, 1);
- const cropWidth = clamp(rawCropWidth, 0.01, 1 - cropX);
- const cropHeight = clamp(rawCropHeight, 0.01, 1 - cropY);
-
- return {
- wallpaper:
- typeof editor.wallpaper === "string"
- ? editor.wallpaper
- : WALLPAPER_PATHS[0],
- shadowIntensity:
- typeof editor.shadowIntensity === "number"
- ? editor.shadowIntensity
- : 0.67,
- backgroundBlur: normalizedBackgroundBlur,
- zoomMotionBlur: normalizedZoomMotionBlur,
- connectZooms:
- typeof editor.connectZooms === "boolean" ? editor.connectZooms : true,
- showCursor:
- typeof editor.showCursor === "boolean" ? editor.showCursor : true,
- loopCursor:
- typeof editor.loopCursor === "boolean" ? editor.loopCursor : false,
- cursorSize: isFiniteNumber(editor.cursorSize)
- ? clamp(editor.cursorSize, 0.5, 10)
- : DEFAULT_CURSOR_SIZE,
- cursorSmoothing: isFiniteNumber(editor.cursorSmoothing)
- ? clamp(editor.cursorSmoothing, 0, 2)
- : DEFAULT_CURSOR_SMOOTHING,
- cursorMotionBlur: isFiniteNumber(
- (editor as Partial<ProjectEditorState>).cursorMotionBlur,
- )
- ? clamp(
- (editor as Partial<ProjectEditorState>).cursorMotionBlur as number,
- 0,
- 2,
- )
- : DEFAULT_CURSOR_MOTION_BLUR,
- cursorClickBounce: isFiniteNumber(
- (editor as Partial<ProjectEditorState>).cursorClickBounce,
- )
- ? clamp(
- (editor as Partial<ProjectEditorState>).cursorClickBounce as number,
- 0,
- 5,
- )
- : DEFAULT_CURSOR_CLICK_BOUNCE,
- cursorSway: isFiniteNumber(
- (editor as Partial<ProjectEditorState>).cursorSway,
- )
- ? clamp(
- (editor as Partial<ProjectEditorState>).cursorSway as number,
- 0,
- 2,
- )
- : DEFAULT_CURSOR_SWAY,
- borderRadius:
- typeof editor.borderRadius === "number" ? editor.borderRadius : 12.5,
- padding: isFiniteNumber(editor.padding)
- ? clamp(editor.padding, 0, 100)
- : 50,
- cropRegion: {
- x: cropX,
- y: cropY,
- width: cropWidth,
- height: cropHeight,
- },
- zoomRegions: normalizedZoomRegions,
- trimRegions: normalizedTrimRegions,
- speedRegions: normalizedSpeedRegions,
- annotationRegions: normalizedAnnotationRegions,
- aspectRatio:
- typeof editor.aspectRatio === "string" &&
- (validAspectRatios.has(editor.aspectRatio as AspectRatio) ||
- isCustomAspectRatio(editor.aspectRatio))
- ? (editor.aspectRatio as AspectRatio)
- : "16:9",
- exportQuality:
- editor.exportQuality === "medium" || editor.exportQuality === "source"
- ? editor.exportQuality
- : "good",
- exportFormat: editor.exportFormat === "gif" ? "gif" : "mp4",
- gifFrameRate:
- editor.gifFrameRate === 15 ||
- editor.gifFrameRate === 20 ||
- editor.gifFrameRate === 25 ||
- editor.gifFrameRate === 30
- ? editor.gifFrameRate
- : 15,
- gifLoop: typeof editor.gifLoop === "boolean" ? editor.gifLoop : true,
- gifSizePreset:
- editor.gifSizePreset === "medium" ||
- editor.gifSizePreset === "large" ||
- editor.gifSizePreset === "original"
- ? editor.gifSizePreset
- : "medium",
- };
+ export function normalizeProjectEditor(editor: Partial<ProjectEditorState>): ProjectEditorState {
- const validAspectRatios = new Set<AspectRatio>(ASPECT_RATIOS);
- const legacyMotionBlurEnabled = (editor as Partial<{ motionBlurEnabled: boolean }>).motionBlurEnabled;
- const legacyShowBlur = (editor as Partial<{ showBlur: boolean }>).showBlur;
- const normalizedZoomMotionBlur = isFiniteNumber((editor as Partial<ProjectEditorState>).zoomMotionBlur)
- ? clamp((editor as Partial<ProjectEditorState>).zoomMotionBlur as number, 0, 2)
- : legacyMotionBlurEnabled
- ? 0.35
- : DEFAULT_ZOOM_MOTION_BLUR;
- const normalizedBackgroundBlur = isFiniteNumber((editor as Partial<ProjectEditorState>).backgroundBlur)
- ? clamp((editor as Partial<ProjectEditorState>).backgroundBlur as number, 0, 8)
- : legacyShowBlur
- ? 2
- : 0;
-
- const normalizedZoomRegions: ZoomRegion[] = Array.isArray(editor.zoomRegions)
- ? editor.zoomRegions
- .filter((region): region is ZoomRegion => Boolean(region && typeof region.id === "string"))
- .map((region) => {
- const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
- const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
-
- return {
- id: region.id,
- startMs,
- endMs,
- depth: [1, 2, 3, 4, 5, 6].includes(region.depth) ? region.depth : DEFAULT_ZOOM_DEPTH,
- focus: {
- cx: clamp(isFiniteNumber(region.focus?.cx) ? region.focus.cx : 0.5, 0, 1),
- cy: clamp(isFiniteNumber(region.focus?.cy) ? region.focus.cy : 0.5, 0, 1),
- },
- };
- })
- : [];
-
- const normalizedTrimRegions: TrimRegion[] = Array.isArray(editor.trimRegions)
- ? editor.trimRegions
- .filter((region): region is TrimRegion => Boolean(region && typeof region.id === "string"))
- .map((region) => {
- const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
- const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
- return {
- id: region.id,
- startMs,
- endMs,
- };
- })
- : [];
-
- const normalizedSpeedRegions: SpeedRegion[] = Array.isArray(editor.speedRegions)
- ? editor.speedRegions
- .filter((region): region is SpeedRegion => Boolean(region && typeof region.id === "string"))
- .map((region) => {
- const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
- const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
-
- const speed =
- region.speed === 0.25 ||
- region.speed === 0.5 ||
- region.speed === 0.75 ||
- region.speed === 1.25 ||
- region.speed === 1.5 ||
- region.speed === 1.75 ||
- region.speed === 2
- ? region.speed
- : DEFAULT_PLAYBACK_SPEED;
-
- return {
- id: region.id,
- startMs,
- endMs,
- speed,
- };
- })
- : [];
-
- const normalizedAnnotationRegions: AnnotationRegion[] = Array.isArray(editor.annotationRegions)
- ? editor.annotationRegions
- .filter((region): region is AnnotationRegion => Boolean(region && typeof region.id === "string"))
- .map((region, index) => {
- const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
- const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
-
- return {
- id: region.id,
- startMs,
- endMs,
- type: region.type === "image" || region.type === "figure" ? region.type : "text",
- content: typeof region.content === "string" ? region.content : "",
- textContent: typeof region.textContent === "string" ? region.textContent : undefined,
- imageContent: typeof region.imageContent === "string" ? region.imageContent : undefined,
- position: {
- x: clamp(
- isFiniteNumber(region.position?.x) ? region.position.x : DEFAULT_ANNOTATION_POSITION.x,
- 0,
- 100,
- ),
- y: clamp(
- isFiniteNumber(region.position?.y) ? region.position.y : DEFAULT_ANNOTATION_POSITION.y,
- 0,
- 100,
- ),
- },
- size: {
- width: clamp(
- isFiniteNumber(region.size?.width) ? region.size.width : DEFAULT_ANNOTATION_SIZE.width,
- 1,
- 200,
- ),
- height: clamp(
- isFiniteNumber(region.size?.height) ? region.size.height : DEFAULT_ANNOTATION_SIZE.height,
- 1,
- 200,
- ),
- },
- style: {
- ...DEFAULT_ANNOTATION_STYLE,
- ...(region.style && typeof region.style === "object" ? region.style : {}),
- },
- zIndex: isFiniteNumber(region.zIndex) ? region.zIndex : index + 1,
- figureData: region.figureData
- ? {
- ...DEFAULT_FIGURE_DATA,
- ...region.figureData,
- }
- : undefined,
- };
- })
- : [];
-
- const normalizedAudioRegions: AudioRegion[] = Array.isArray((editor as Partial<ProjectEditorState>).audioRegions)
- ? ((editor as Partial<ProjectEditorState>).audioRegions as AudioRegion[])
- .filter((region): region is AudioRegion => Boolean(region && typeof region.id === "string"))
- .map((region) => {
- const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
- const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
- const startMs = Math.max(0, Math.min(rawStart, rawEnd));
- const endMs = Math.max(startMs + 1, rawEnd);
-
- return {
- id: region.id,
- startMs,
- endMs,
- audioPath: typeof region.audioPath === "string" ? region.audioPath : "",
- volume: isFiniteNumber(region.volume) ? clamp(region.volume, 0, 1) : 1,
- };
- })
- : [];
-
- const rawCropX = isFiniteNumber(editor.cropRegion?.x) ? editor.cropRegion.x : DEFAULT_CROP_REGION.x;
- const rawCropY = isFiniteNumber(editor.cropRegion?.y) ? editor.cropRegion.y : DEFAULT_CROP_REGION.y;
- const rawCropWidth = isFiniteNumber(editor.cropRegion?.width) ? editor.cropRegion.width : DEFAULT_CROP_REGION.width;
- const rawCropHeight = isFiniteNumber(editor.cropRegion?.height)
- ? editor.cropRegion.height
- : DEFAULT_CROP_REGION.height;
-
- const cropX = clamp(rawCropX, 0, 1);
- const cropY = clamp(rawCropY, 0, 1);
- const cropWidth = clamp(rawCropWidth, 0.01, 1 - cropX);
- const cropHeight = clamp(rawCropHeight, 0.01, 1 - cropY);
-
- return {
- wallpaper: typeof editor.wallpaper === "string" ? editor.wallpaper : WALLPAPER_PATHS[0],
- shadowIntensity: typeof editor.shadowIntensity === "number" ? editor.shadowIntensity : 0.67,
- backgroundBlur: normalizedBackgroundBlur,
- zoomMotionBlur: normalizedZoomMotionBlur,
- connectZooms: typeof editor.connectZooms === "boolean" ? editor.connectZooms : true,
- showCursor: typeof editor.showCursor === "boolean" ? editor.showCursor : true,
- loopCursor: typeof editor.loopCursor === "boolean" ? editor.loopCursor : false,
- cursorSize: isFiniteNumber(editor.cursorSize) ? clamp(editor.cursorSize, 0.5, 10) : DEFAULT_CURSOR_SIZE,
- cursorSmoothing: isFiniteNumber(editor.cursorSmoothing)
- ? clamp(editor.cursorSmoothing, 0, 2)
- : DEFAULT_CURSOR_SMOOTHING,
- cursorMotionBlur: isFiniteNumber((editor as Partial<ProjectEditorState>).cursorMotionBlur)
- ? clamp((editor as Partial<ProjectEditorState>).cursorMotionBlur as number, 0, 2)
- : DEFAULT_CURSOR_MOTION_BLUR,
- cursorClickBounce: isFiniteNumber((editor as Partial<ProjectEditorState>).cursorClickBounce)
- ? clamp((editor as Partial<ProjectEditorState>).cursorClickBounce as number, 0, 5)
- : DEFAULT_CURSOR_CLICK_BOUNCE,
- borderRadius: typeof editor.borderRadius === "number" ? editor.borderRadius : 12.5,
- padding: isFiniteNumber(editor.padding) ? clamp(editor.padding, 0, 100) : 50,
- cropRegion: {
- x: cropX,
- y: cropY,
- width: cropWidth,
- height: cropHeight,
- },
- zoomRegions: normalizedZoomRegions,
- trimRegions: normalizedTrimRegions,
- speedRegions: normalizedSpeedRegions,
- annotationRegions: normalizedAnnotationRegions,
- audioRegions: normalizedAudioRegions,
- aspectRatio:
- typeof editor.aspectRatio === "string" &&
- (validAspectRatios.has(editor.aspectRatio as AspectRatio) || isCustomAspectRatio(editor.aspectRatio))
- ? (editor.aspectRatio as AspectRatio)
- : "16:9",
- exportQuality:
- editor.exportQuality === "medium" ||
- editor.exportQuality === "good" ||
- editor.exportQuality === "high" ||
- editor.exportQuality === "source"
- ? editor.exportQuality
- : "good",
- exportFormat: editor.exportFormat === "gif" ? "gif" : "mp4",
- gifFrameRate:
- editor.gifFrameRate === 15 ||
- editor.gifFrameRate === 20 ||
- editor.gifFrameRate === 25 ||
- editor.gifFrameRate === 30
- ? editor.gifFrameRate
- : 15,
- gifLoop: typeof editor.gifLoop === "boolean" ? editor.gifLoop : true,
- gifSizePreset:
- editor.gifSizePreset === "medium" || editor.gifSizePreset === "large" || editor.gifSizePreset === "original"
- ? editor.gifSizePreset
- : "medium",
- };
++ const validAspectRatios = new Set<AspectRatio>(ASPECT_RATIOS);
++ const legacyMotionBlurEnabled = (editor as Partial<{ motionBlurEnabled: boolean }>)
++ .motionBlurEnabled;
++ const legacyShowBlur = (editor as Partial<{ showBlur: boolean }>).showBlur;
++ const normalizedZoomMotionBlur = isFiniteNumber(
++ (editor as Partial<ProjectEditorState>).zoomMotionBlur,
++ )
++ ? clamp((editor as Partial<ProjectEditorState>).zoomMotionBlur as number, 0, 2)
++ : legacyMotionBlurEnabled
++ ? 0.35
++ : DEFAULT_ZOOM_MOTION_BLUR;
++ const normalizedBackgroundBlur = isFiniteNumber(
++ (editor as Partial<ProjectEditorState>).backgroundBlur,
++ )
++ ? clamp((editor as Partial<ProjectEditorState>).backgroundBlur as number, 0, 8)
++ : legacyShowBlur
++ ? 2
++ : 0;
++
++ const normalizedZoomRegions: ZoomRegion[] = Array.isArray(editor.zoomRegions)
++ ? editor.zoomRegions
++ .filter((region): region is ZoomRegion => Boolean(region && typeof region.id === "string"))
++ .map((region) => {
++ const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
++ const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
++ const startMs = Math.max(0, Math.min(rawStart, rawEnd));
++ const endMs = Math.max(startMs + 1, rawEnd);
++
++ return {
++ id: region.id,
++ startMs,
++ endMs,
++ depth: [1, 2, 3, 4, 5, 6].includes(region.depth) ? region.depth : DEFAULT_ZOOM_DEPTH,
++ focus: {
++ cx: clamp(isFiniteNumber(region.focus?.cx) ? region.focus.cx : 0.5, 0, 1),
++ cy: clamp(isFiniteNumber(region.focus?.cy) ? region.focus.cy : 0.5, 0, 1),
++ },
++ };
++ })
++ : [];
++
++ const normalizedTrimRegions: TrimRegion[] = Array.isArray(editor.trimRegions)
++ ? editor.trimRegions
++ .filter((region): region is TrimRegion => Boolean(region && typeof region.id === "string"))
++ .map((region) => {
++ const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
++ const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
++ const startMs = Math.max(0, Math.min(rawStart, rawEnd));
++ const endMs = Math.max(startMs + 1, rawEnd);
++ return {
++ id: region.id,
++ startMs,
++ endMs,
++ };
++ })
++ : [];
++
++ const normalizedSpeedRegions: SpeedRegion[] = Array.isArray(editor.speedRegions)
++ ? editor.speedRegions
++ .filter((region): region is SpeedRegion => Boolean(region && typeof region.id === "string"))
++ .map((region) => {
++ const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
++ const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
++ const startMs = Math.max(0, Math.min(rawStart, rawEnd));
++ const endMs = Math.max(startMs + 1, rawEnd);
++
++ const speed =
++ region.speed === 0.25 ||
++ region.speed === 0.5 ||
++ region.speed === 0.75 ||
++ region.speed === 1.25 ||
++ region.speed === 1.5 ||
++ region.speed === 1.75 ||
++ region.speed === 2
++ ? region.speed
++ : DEFAULT_PLAYBACK_SPEED;
++
++ return {
++ id: region.id,
++ startMs,
++ endMs,
++ speed,
++ };
++ })
++ : [];
++
++ const normalizedAnnotationRegions: AnnotationRegion[] = Array.isArray(editor.annotationRegions)
++ ? editor.annotationRegions
++ .filter((region): region is AnnotationRegion =>
++ Boolean(region && typeof region.id === "string"),
++ )
++ .map((region, index) => {
++ const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
++ const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
++ const startMs = Math.max(0, Math.min(rawStart, rawEnd));
++ const endMs = Math.max(startMs + 1, rawEnd);
++
++ return {
++ id: region.id,
++ startMs,
++ endMs,
++ type: region.type === "image" || region.type === "figure" ? region.type : "text",
++ content: typeof region.content === "string" ? region.content : "",
++ textContent: typeof region.textContent === "string" ? region.textContent : undefined,
++ imageContent: typeof region.imageContent === "string" ? region.imageContent : undefined,
++ position: {
++ x: clamp(
++ isFiniteNumber(region.position?.x)
++ ? region.position.x
++ : DEFAULT_ANNOTATION_POSITION.x,
++ 0,
++ 100,
++ ),
++ y: clamp(
++ isFiniteNumber(region.position?.y)
++ ? region.position.y
++ : DEFAULT_ANNOTATION_POSITION.y,
++ 0,
++ 100,
++ ),
++ },
++ size: {
++ width: clamp(
++ isFiniteNumber(region.size?.width)
++ ? region.size.width
++ : DEFAULT_ANNOTATION_SIZE.width,
++ 1,
++ 200,
++ ),
++ height: clamp(
++ isFiniteNumber(region.size?.height)
++ ? region.size.height
++ : DEFAULT_ANNOTATION_SIZE.height,
++ 1,
++ 200,
++ ),
++ },
++ style: {
++ ...DEFAULT_ANNOTATION_STYLE,
++ ...(region.style && typeof region.style === "object" ? region.style : {}),
++ },
++ zIndex: isFiniteNumber(region.zIndex) ? region.zIndex : index + 1,
++ figureData: region.figureData
++ ? {
++ ...DEFAULT_FIGURE_DATA,
++ ...region.figureData,
++ }
++ : undefined,
++ };
++ })
++ : [];
++
++ const normalizedAudioRegions: AudioRegion[] = Array.isArray(
++ (editor as Partial<ProjectEditorState>).audioRegions,
++ )
++ ? ((editor as Partial<ProjectEditorState>).audioRegions as AudioRegion[])
++ .filter((region): region is AudioRegion => Boolean(region && typeof region.id === "string"))
++ .map((region) => {
++ const rawStart = isFiniteNumber(region.startMs) ? Math.round(region.startMs) : 0;
++ const rawEnd = isFiniteNumber(region.endMs) ? Math.round(region.endMs) : rawStart + 1000;
++ const startMs = Math.max(0, Math.min(rawStart, rawEnd));
++ const endMs = Math.max(startMs + 1, rawEnd);
++
++ return {
++ id: region.id,
++ startMs,
++ endMs,
++ audioPath: typeof region.audioPath === "string" ? region.audioPath : "",
++ volume: isFiniteNumber(region.volume) ? clamp(region.volume, 0, 1) : 1,
++ };
++ })
++ : [];
++
++ const rawCropX = isFiniteNumber(editor.cropRegion?.x)
++ ? editor.cropRegion.x
++ : DEFAULT_CROP_REGION.x;
++ const rawCropY = isFiniteNumber(editor.cropRegion?.y)
++ ? editor.cropRegion.y
++ : DEFAULT_CROP_REGION.y;
++ const rawCropWidth = isFiniteNumber(editor.cropRegion?.width)
++ ? editor.cropRegion.width
++ : DEFAULT_CROP_REGION.width;
++ const rawCropHeight = isFiniteNumber(editor.cropRegion?.height)
++ ? editor.cropRegion.height
++ : DEFAULT_CROP_REGION.height;
++
++ const cropX = clamp(rawCropX, 0, 1);
++ const cropY = clamp(rawCropY, 0, 1);
++ const cropWidth = clamp(rawCropWidth, 0.01, 1 - cropX);
++ const cropHeight = clamp(rawCropHeight, 0.01, 1 - cropY);
++
++ return {
++ wallpaper: typeof editor.wallpaper === "string" ? editor.wallpaper : WALLPAPER_PATHS[0],
++ shadowIntensity: typeof editor.shadowIntensity === "number" ? editor.shadowIntensity : 0.67,
++ backgroundBlur: normalizedBackgroundBlur,
++ zoomMotionBlur: normalizedZoomMotionBlur,
++ connectZooms: typeof editor.connectZooms === "boolean" ? editor.connectZooms : true,
++ showCursor: typeof editor.showCursor === "boolean" ? editor.showCursor : true,
++ loopCursor: typeof editor.loopCursor === "boolean" ? editor.loopCursor : false,
++ cursorSize: isFiniteNumber(editor.cursorSize)
++ ? clamp(editor.cursorSize, 0.5, 10)
++ : DEFAULT_CURSOR_SIZE,
++ cursorSmoothing: isFiniteNumber(editor.cursorSmoothing)
++ ? clamp(editor.cursorSmoothing, 0, 2)
++ : DEFAULT_CURSOR_SMOOTHING,
++ cursorMotionBlur: isFiniteNumber((editor as Partial<ProjectEditorState>).cursorMotionBlur)
++ ? clamp((editor as Partial<ProjectEditorState>).cursorMotionBlur as number, 0, 2)
++ : DEFAULT_CURSOR_MOTION_BLUR,
++ cursorClickBounce: isFiniteNumber((editor as Partial<ProjectEditorState>).cursorClickBounce)
++ ? clamp((editor as Partial<ProjectEditorState>).cursorClickBounce as number, 0, 5)
++ : DEFAULT_CURSOR_CLICK_BOUNCE,
++ cursorSway: isFiniteNumber((editor as Partial<ProjectEditorState>).cursorSway)
++ ? clamp((editor as Partial<ProjectEditorState>).cursorSway as number, 0, 2)
++ : DEFAULT_CURSOR_SWAY,
++ borderRadius: typeof editor.borderRadius === "number" ? editor.borderRadius : 12.5,
++ padding: isFiniteNumber(editor.padding) ? clamp(editor.padding, 0, 100) : 50,
++ cropRegion: {
++ x: cropX,
++ y: cropY,
++ width: cropWidth,
++ height: cropHeight,
++ },
++ zoomRegions: normalizedZoomRegions,
++ trimRegions: normalizedTrimRegions,
++ speedRegions: normalizedSpeedRegions,
++ annotationRegions: normalizedAnnotationRegions,
++ audioRegions: normalizedAudioRegions,
++ aspectRatio:
++ typeof editor.aspectRatio === "string" &&
++ (validAspectRatios.has(editor.aspectRatio as AspectRatio) ||
++ isCustomAspectRatio(editor.aspectRatio))
++ ? (editor.aspectRatio as AspectRatio)
++ : "16:9",
++ exportQuality:
++ editor.exportQuality === "medium" ||
++ editor.exportQuality === "good" ||
++ editor.exportQuality === "high" ||
++ editor.exportQuality === "source"
++ ? editor.exportQuality
++ : "good",
++ exportFormat: editor.exportFormat === "gif" ? "gif" : "mp4",
++ gifFrameRate:
++ editor.gifFrameRate === 15 ||
++ editor.gifFrameRate === 20 ||
++ editor.gifFrameRate === 25 ||
++ editor.gifFrameRate === 30
++ ? editor.gifFrameRate
++ : 15,
++ gifLoop: typeof editor.gifLoop === "boolean" ? editor.gifLoop : true,
++ gifSizePreset:
++ editor.gifSizePreset === "medium" ||
++ editor.gifSizePreset === "large" ||
++ editor.gifSizePreset === "original"
++ ? editor.gifSizePreset
++ : "medium",
++ };
}
-export function createProjectData(videoPath: string, editor: ProjectEditorState): EditorProjectData {
- return {
- version: PROJECT_VERSION,
- videoPath,
- editor,
- };
+export function createProjectData(
- videoPath: string,
- editor: ProjectEditorState,
++ videoPath: string,
++ editor: ProjectEditorState,
+): EditorProjectData {
- return {
- version: PROJECT_VERSION,
- videoPath,
- editor,
- };
++ return {
++ version: PROJECT_VERSION,
++ videoPath,
++ editor,
++ };
}
-
diff --cc src/components/video-editor/timeline/TimelineEditor.tsx
index 9ac424f4,27d02dce..36977b0e
--- a/src/components/video-editor/timeline/TimelineEditor.tsx
+++ b/src/components/video-editor/timeline/TimelineEditor.tsx
@@@ -20,25 -7,22 +7,23 @@@ import
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+ import { Plus, Scissors, ZoomIn, MessageSquare, ChevronDown, Check, Gauge, WandSparkles, Music } from "lucide-react";
+ import { toast } from "sonner";
+ import { cn } from "@/lib/utils";
+ import { v4 as uuidv4 } from 'uuid';
import { useShortcuts } from "@/contexts/ShortcutsContext";
import { matchesShortcut } from "@/lib/shortcuts";
- import { cn } from "@/lib/utils";
import { ASPECT_RATIOS, type AspectRatio, getAspectRatioLabel, isCustomAspectRatio } from "@/utils/aspectRatioUtils";
import { formatShortcut } from "@/utils/platformUtils";
+import { loadEditorPreferences, saveEditorPreferences } from "../editorPreferences";
import { TutorialHelp } from "../TutorialHelp";
- import type {
- AnnotationRegion,
- CursorTelemetryPoint,
- SpeedRegion,
- TrimRegion,
- ZoomFocus,
- ZoomRegion,
- } from "../types";
+ import TimelineWrapper from "./TimelineWrapper";
+ import Row from "./Row";
import Item from "./Item";
import KeyframeMarkers from "./KeyframeMarkers";
- import Row from "./Row";
- import TimelineWrapper from "./TimelineWrapper";
+ import type { Range, Span } from "dnd-timeline";
+ import type { ZoomRegion, TrimRegion, AnnotationRegion, SpeedRegion, AudioRegion, CursorTelemetryPoint, ZoomFocus } from "../types";
+ import { toFileUrl } from "../projectPersistence";
import { detectInteractionCandidates, normalizeCursorTelemetry } from "./zoomSuggestionUtils";
const ZOOM_ROW_ID = "row-zoom";
@@@ -614,39 -615,44 +616,45 @@@ function Timeline(
}
export default function TimelineEditor({
- videoDuration,
- currentTime,
- onSeek,
- cursorTelemetry = [],
- zoomRegions,
- onZoomAdded,
- onZoomSuggested,
- onZoomSpanChange,
- onZoomDelete,
- selectedZoomId,
- onSelectZoom,
- trimRegions = [],
- onTrimAdded,
- onTrimSpanChange,
- onTrimDelete,
- selectedTrimId,
- onSelectTrim,
- annotationRegions = [],
- onAnnotationAdded,
- onAnnotationSpanChange,
- onAnnotationDelete,
- selectedAnnotationId,
- onSelectAnnotation,
- speedRegions = [],
- onSpeedAdded,
- onSpeedSpanChange,
- onSpeedDelete,
- selectedSpeedId,
- onSelectSpeed,
- aspectRatio,
- onAspectRatioChange,
+ videoDuration,
+ currentTime,
+ onSeek,
+ cursorTelemetry = [],
+ zoomRegions,
+ onZoomAdded,
+ onZoomSuggested,
+ onZoomSpanChange,
+ onZoomDelete,
+ selectedZoomId,
+ onSelectZoom,
+ trimRegions = [],
+ onTrimAdded,
+ onTrimSpanChange,
+ onTrimDelete,
+ selectedTrimId,
+ onSelectTrim,
+ annotationRegions = [],
+ onAnnotationAdded,
+ onAnnotationSpanChange,
+ onAnnotationDelete,
+ selectedAnnotationId,
+ onSelectAnnotation,
+ speedRegions = [],
+ onSpeedAdded,
+ onSpeedSpanChange,
+ onSpeedDelete,
+ selectedSpeedId,
+ onSelectSpeed,
+ audioRegions = [],
+ onAudioAdded,
+ onAudioSpanChange,
+ onAudioDelete,
+ selectedAudioId,
+ onSelectAudio,
+ aspectRatio,
+ onAspectRatioChange,
}: TimelineEditorProps) {
+ const initialEditorPreferences = useMemo(() => loadEditorPreferences(), []);
const totalMs = useMemo(() => Math.max(0, Math.round(videoDuration * 1000)), [videoDuration]);
const currentTimeMs = useMemo(() => Math.round(currentTime * 1000), [currentTime]);
const timelineScale = useMemo(() => calculateTimelineScale(videoDuration), [videoDuration]);
diff --cc src/i18n/locales/en/settings.json
index 826d72a6,2ffb67f0..5496efa1
--- a/src/i18n/locales/en/settings.json
+++ b/src/i18n/locales/en/settings.json
@@@ -1,61 -1,61 +1,62 @@@
{
- "zoom": {
- "level": "Zoom Level",
- "selectRegion": "Select a zoom region to adjust",
- "deleteZoom": "Delete Zoom"
- },
- "trim": {
- "deleteRegion": "Delete Trim Region"
- },
- "speed": {
- "playbackSpeed": "Playback Speed",
- "selectRegion": "Select a speed region to adjust",
- "deleteRegion": "Delete Speed Region"
- },
- "effects": {
- "title": "Video Effects",
- "showCursor": "Show Cursor",
- "loopCursor": "Loop cursor",
- "backgroundBlur": "Background Blur",
- "zoomMotionBlur": "Zoom Motion Blur",
- "connectZooms": "Connect Zooms",
- "cursorSize": "Cursor Size",
- "cursorSmoothing": "Cursor Smoothing",
- "off": "Off",
- "cursorMotionBlur": "Cursor Motion Blur",
- "cursorClickBounce": "Cursor Click Bounce",
- "cursorSway": "Cursor Sway",
- "shadow": "Shadow",
- "roundness": "Roundness",
- "padding": "Padding"
- },
- "crop": {
- "title": "Crop Video",
- "instruction": "Drag on each side to adjust the crop area"
- },
- "background": {
- "title": "Background",
- "image": "Image",
- "color": "Color",
- "gradient": "Gradient",
- "uploadCustom": "Upload Custom",
- "uploadSuccess": "Custom image uploaded successfully!",
- "uploadError": "Please upload a JPG or JPEG image file."
- },
- "export": {
- "mp4": "MP4",
- "gif": "GIF",
- "quality": {
- "low": "Low",
- "medium": "Medium",
- "high": "High"
- },
- "loop": "Loop",
- "outputDimensions": "Output: {{dimensions}}px",
- "loadProject": "Load Project",
- "saveProject": "Save Project",
- "exportVideo": "Export {{format}}",
- "reportBug": "Report Bug",
- "starOnGithub": "Star on GitHub"
- }
+ "zoom": {
+ "level": "Zoom Level",
+ "selectRegion": "Select a zoom region to adjust",
+ "deleteZoom": "Delete Zoom"
+ },
+ "trim": {
+ "deleteRegion": "Delete Trim Region"
+ },
+ "speed": {
+ "playbackSpeed": "Playback Speed",
+ "selectRegion": "Select a speed region to adjust",
+ "deleteRegion": "Delete Speed Region"
+ },
+ "effects": {
+ "title": "Video Effects",
+ "showCursor": "Show Cursor",
+ "loopCursor": "Loop cursor",
+ "backgroundBlur": "Background Blur",
+ "zoomMotionBlur": "Zoom Motion Blur",
+ "connectZooms": "Connect Zooms",
+ "cursorSize": "Cursor Size",
+ "cursorSmoothing": "Cursor Smoothing",
+ "off": "Off",
+ "cursorMotionBlur": "Cursor Motion Blur",
+ "cursorClickBounce": "Cursor Click Bounce",
++ "cursorSway": "Cursor Sway",
+ "shadow": "Shadow",
+ "roundness": "Roundness",
+ "padding": "Padding"
+ },
+ "crop": {
+ "title": "Crop Video",
+ "instruction": "Drag on each side to adjust the crop area"
+ },
+ "background": {
+ "title": "Background",
+ "image": "Image",
+ "color": "Color",
+ "gradient": "Gradient",
+ "uploadCustom": "Upload Custom",
+ "uploadSuccess": "Custom image uploaded successfully!",
+ "uploadError": "Please upload a JPG or JPEG image file."
+ },
+ "export": {
+ "mp4": "MP4",
+ "gif": "GIF",
+ "quality": {
+ "low": "Low",
+ "medium": "Medium",
- "high": "High",
- "original": "Original"
++ "high": "High",
++ "original": "Original"
+ },
+ "loop": "Loop",
+ "outputDimensions": "Output: {{dimensions}}px",
+ "loadProject": "Load Project",
+ "saveProject": "Save Project",
+ "exportVideo": "Export {{format}}",
+ "reportBug": "Report Bug",
+ "starOnGithub": "Star on GitHub"
+ }
}
diff --cc src/i18n/locales/es/settings.json
index 9132587c,335bb00d..d71a9714
--- a/src/i18n/locales/es/settings.json
+++ b/src/i18n/locales/es/settings.json
@@@ -1,61 -1,61 +1,62 @@@
{
- "zoom": {
- "level": "Nivel de zoom",
- "selectRegion": "Selecciona una región de zoom para ajustar",
- "deleteZoom": "Eliminar zoom"
- },
- "trim": {
- "deleteRegion": "Eliminar región de recorte"
- },
- "speed": {
- "playbackSpeed": "Velocidad de reproducción",
- "selectRegion": "Selecciona una región de velocidad para ajustar",
- "deleteRegion": "Eliminar región de velocidad"
- },
- "effects": {
- "title": "Efectos de video",
- "showCursor": "Mostrar cursor",
- "loopCursor": "Cursor en bucle",
- "backgroundBlur": "Desenfoque de fondo",
- "zoomMotionBlur": "Desenfoque de movimiento del zoom",
- "connectZooms": "Conectar zooms",
- "cursorSize": "Tamaño del cursor",
- "cursorSmoothing": "Suavizado del cursor",
- "off": "Desactivado",
- "cursorMotionBlur": "Desenfoque de movimiento del cursor",
- "cursorClickBounce": "Rebote de clic del cursor",
- "cursorSway": "Balanceo del cursor",
- "shadow": "Sombra",
- "roundness": "Redondez",
- "padding": "Relleno"
- },
- "crop": {
- "title": "Recortar video",
- "instruction": "Arrastra cada lado para ajustar el área de recorte"
- },
- "background": {
- "title": "Fondo",
- "image": "Imagen",
- "color": "Color",
- "gradient": "Degradado",
- "uploadCustom": "Subir personalizado",
- "uploadSuccess": "¡Imagen personalizada subida exitosamente!",
- "uploadError": "Por favor sube un archivo de imagen JPG o JPEG."
- },
- "export": {
- "mp4": "MP4",
- "gif": "GIF",
- "quality": {
- "low": "Baja",
- "medium": "Media",
- "high": "Alta"
- },
- "loop": "Bucle",
- "outputDimensions": "Salida: {{dimensions}}px",
- "loadProject": "Cargar proyecto",
- "saveProject": "Guardar proyecto",
- "exportVideo": "Exportar {{format}}",
- "reportBug": "Reportar error",
- "starOnGithub": "Estrella en GitHub"
- }
+ "zoom": {
+ "level": "Nivel de zoom",
+ "selectRegion": "Selecciona una región de zoom para ajustar",
+ "deleteZoom": "Eliminar zoom"
+ },
+ "trim": {
+ "deleteRegion": "Eliminar región de recorte"
+ },
+ "speed": {
+ "playbackSpeed": "Velocidad de reproducción",
+ "selectRegion": "Selecciona una región de velocidad para ajustar",
+ "deleteRegion": "Eliminar región de velocidad"
+ },
+ "effects": {
+ "title": "Efectos de video",
+ "showCursor": "Mostrar cursor",
+ "loopCursor": "Cursor en bucle",
+ "backgroundBlur": "Desenfoque de fondo",
+ "zoomMotionBlur": "Desenfoque de movimiento del zoom",
+ "connectZooms": "Conectar zooms",
+ "cursorSize": "Tamaño del cursor",
+ "cursorSmoothing": "Suavizado del cursor",
+ "off": "Desactivado",
+ "cursorMotionBlur": "Desenfoque de movimiento del cursor",
+ "cursorClickBounce": "Rebote de clic del cursor",
++ "cursorSway": "Balanceo del cursor",
+ "shadow": "Sombra",
+ "roundness": "Redondez",
+ "padding": "Relleno"
+ },
+ "crop": {
+ "title": "Recortar video",
+ "instruction": "Arrastra cada lado para ajustar el área de recorte"
+ },
+ "background": {
+ "title": "Fondo",
+ "image": "Imagen",
+ "color": "Color",
+ "gradient": "Degradado",
+ "uploadCustom": "Subir personalizado",
+ "uploadSuccess": "¡Imagen personalizada subida exitosamente!",
+ "uploadError": "Por favor sube un archivo de imagen JPG o JPEG."
+ },
+ "export": {
+ "mp4": "MP4",
+ "gif": "GIF",
+ "quality": {
+ "low": "Baja",
+ "medium": "Media",
- "high": "Alta",
- "original": "Original"
++ "high": "Alta",
++ "original": "Original"
+ },
+ "loop": "Bucle",
+ "outputDimensions": "Salida: {{dimensions}}px",
+ "loadProject": "Cargar proyecto",
+ "saveProject": "Guardar proyecto",
+ "exportVideo": "Exportar {{format}}",
+ "reportBug": "Reportar error",
+ "starOnGithub": "Estrella en GitHub"
+ }
}
diff --cc src/i18n/locales/zh-CN/settings.json
index e492d8bd,5e2ef5bb..ab202354
--- a/src/i18n/locales/zh-CN/settings.json
+++ b/src/i18n/locales/zh-CN/settings.json
@@@ -1,61 -1,61 +1,62 @@@
{
- "zoom": {
- "level": "缩放级别",
- "selectRegion": "选择缩放区域以调整",
- "deleteZoom": "删除缩放"
- },
- "trim": {
- "deleteRegion": "删除修剪区域"
- },
- "speed": {
- "playbackSpeed": "播放速度",
- "selectRegion": "选择变速区域以调整",
- "deleteRegion": "删除变速区域"
- },
- "effects": {
- "title": "视频效果",
- "showCursor": "显示光标",
- "loopCursor": "循环光标",
- "backgroundBlur": "背景模糊",
- "zoomMotionBlur": "缩放运动模糊",
- "connectZooms": "连接缩放",
- "cursorSize": "光标大小",
- "cursorSmoothing": "光标平滑",
- "off": "关",
- "cursorMotionBlur": "光标运动模糊",
- "cursorClickBounce": "光标点击弹跳",
- "cursorSway": "光标摆动",
- "shadow": "阴影",
- "roundness": "圆角",
- "padding": "内边距"
- },
- "crop": {
- "title": "裁剪视频",
- "instruction": "拖动各边以调整裁剪区域"
- },
- "background": {
- "title": "背景",
- "image": "图片",
- "color": "颜色",
- "gradient": "渐变",
- "uploadCustom": "上传自定义",
- "uploadSuccess": "自定义图片上传成功!",
- "uploadError": "请上传 JPG 或 JPEG 图片文件。"
- },
- "export": {
- "mp4": "MP4",
- "gif": "GIF",
- "quality": {
- "low": "低",
- "medium": "中",
- "high": "高"
- },
- "loop": "循环",
- "outputDimensions": "输出:{{dimensions}}px",
- "loadProject": "加载项目",
- "saveProject": "保存项目",
- "exportVideo": "导出{{format}}",
- "reportBug": "报告问题",
- "starOnGithub": "在 GitHub 上加星"
- }
+ "zoom": {
+ "level": "缩放级别",
+ "selectRegion": "选择缩放区域以调整",
+ "deleteZoom": "删除缩放"
+ },
+ "trim": {
+ "deleteRegion": "删除修剪区域"
+ },
+ "speed": {
+ "playbackSpeed": "播放速度",
+ "selectRegion": "选择变速区域以调整",
+ "deleteRegion": "删除变速区域"
+ },
+ "effects": {
+ "title": "视频效果",
+ "showCursor": "显示光标",
+ "loopCursor": "循环光标",
+ "backgroundBlur": "背景模糊",
+ "zoomMotionBlur": "缩放运动模糊",
+ "connectZooms": "连接缩放",
+ "cursorSize": "光标大小",
+ "cursorSmoothing": "光标平滑",
+ "off": "关",
+ "cursorMotionBlur": "光标运动模糊",
+ "cursorClickBounce": "光标点击弹跳",
++ "cursorSway": "光标摆动",
+ "shadow": "阴影",
+ "roundness": "圆角",
+ "padding": "内边距"
+ },
+ "crop": {
+ "title": "裁剪视频",
+ "instruction": "拖动各边以调整裁剪区域"
+ },
+ "background": {
+ "title": "背景",
+ "image": "图片",
+ "color": "颜色",
+ "gradient": "渐变",
+ "uploadCustom": "上传自定义",
+ "uploadSuccess": "自定义图片上传成功!",
+ "uploadError": "请上传 JPG 或 JPEG 图片文件。"
+ },
+ "export": {
+ "mp4": "MP4",
+ "gif": "GIF",
+ "quality": {
+ "low": "低",
+ "medium": "中",
+ "high": "高",
+ "original": "原始"
+ },
+ "loop": "循环",
+ "outputDimensions": "输出:{{dimensions}}px",
+ "loadProject": "加载项目",
+ "saveProject": "保存项目",
+ "exportVideo": "导出{{format}}",
+ "reportBug": "报告问题",
+ "starOnGithub": "在 GitHub 上加星"
+ }
}
diff --cc src/lib/exporter/videoExporter.ts
index 5e44062d,ab2a053e..4c070007
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@@ -1,446 -1,416 +1,444 @@@
- import type { ExportConfig, ExportProgress, ExportResult } from "./types";
-import type { ExportConfig, ExportProgress, ExportResult } from './types';
-import { AudioProcessor } from './audioEncoder';
-import { StreamingVideoDecoder } from './streamingDecoder';
-import { FrameRenderer } from './frameRenderer';
-import { VideoMuxer } from './muxer';
-import type { ZoomRegion, CropRegion, TrimRegion, AnnotationRegion, SpeedRegion, AudioRegion, CursorTelemetryPoint } from '@/components/video-editor/types';
++import type {
++ AnnotationRegion,
++ AudioRegion,
++ CropRegion,
++ CursorTelemetryPoint,
++ SpeedRegion,
++ TrimRegion,
++ ZoomRegion,
++} from "@/components/video-editor/types";
+import { AudioProcessor } from "./audioEncoder";
- import { StreamingVideoDecoder } from "./streamingDecoder";
+import { FrameRenderer } from "./frameRenderer";
+import { VideoMuxer } from "./muxer";
- import type {
- ZoomRegion,
- CropRegion,
- TrimRegion,
- AnnotationRegion,
- SpeedRegion,
- CursorTelemetryPoint,
- } from "@/components/video-editor/types";
++import { StreamingVideoDecoder } from "./streamingDecoder";
++import type { ExportConfig, ExportProgress, ExportResult } from "./types";
interface VideoExporterConfig extends ExportConfig {
-- videoUrl: string;
-- wallpaper: string;
-- zoomRegions: ZoomRegion[];
-- trimRegions?: TrimRegion[];
-- speedRegions?: SpeedRegion[];
-- showShadow: boolean;
-- shadowIntensity: number;
-- backgroundBlur: number;
-- zoomMotionBlur?: number;
-- connectZooms?: boolean;
-- borderRadius?: number;
-- padding?: number;
-- videoPadding?: number;
-- cropRegion: CropRegion;
-- annotationRegions?: AnnotationRegion[];
-- cursorTelemetry?: CursorTelemetryPoint[];
-- showCursor?: boolean;
-- cursorSize?: number;
-- cursorSmoothing?: number;
-- cursorMotionBlur?: number;
-- cursorClickBounce?: number;
- cursorSway?: number;
- audioRegions?: AudioRegion[];
-- previewWidth?: number;
-- previewHeight?: number;
-- onProgress?: (progress: ExportProgress) => void;
++ videoUrl: string;
++ wallpaper: string;
++ zoomRegions: ZoomRegion[];
++ trimRegions?: TrimRegion[];
++ speedRegions?: SpeedRegion[];
++ showShadow: boolean;
++ shadowIntensity: number;
++ backgroundBlur: number;
++ zoomMotionBlur?: number;
++ connectZooms?: boolean;
++ borderRadius?: number;
++ padding?: number;
++ videoPadding?: number;
++ cropRegion: CropRegion;
++ annotationRegions?: AnnotationRegion[];
++ cursorTelemetry?: CursorTelemetryPoint[];
++ showCursor?: boolean;
++ cursorSize?: number;
++ cursorSmoothing?: number;
++ cursorMotionBlur?: number;
++ cursorClickBounce?: number;
++ cursorSway?: number;
++ audioRegions?: AudioRegion[];
++ previewWidth?: number;
++ previewHeight?: number;
++ onProgress?: (progress: ExportProgress) => void;
}
export class VideoExporter {
-- private config: VideoExporterConfig;
-- private streamingDecoder: StreamingVideoDecoder | null = null;
-- private renderer: FrameRenderer | null = null;
-- private encoder: VideoEncoder | null = null;
-- private muxer: VideoMuxer | null = null;
-- private audioProcessor: AudioProcessor | null = null;
-- private cancelled = false;
-- private encodeQueue = 0;
-- // Increased queue size for better throughput with hardware encoding
-- private readonly MAX_ENCODE_QUEUE = 120;
-- private videoDescription: Uint8Array | undefined;
-- private videoColorSpace: VideoColorSpaceInit | undefined;
-- private pendingMuxing: Promise<void> = Promise.resolve();
-- private chunkCount = 0;
-- private readonly WINDOWS_FINALIZATION_TIMEOUT_MS = 60_000;
--
-- constructor(config: VideoExporterConfig) {
-- this.config = config;
-- }
--
-- async export(): Promise<ExportResult> {
-- try {
-- this.cleanup();
-- this.cancelled = false;
--
-- // Initialize streaming decoder and load video metadata
-- this.streamingDecoder = new StreamingVideoDecoder();
- const videoInfo = await this.streamingDecoder.loadMetadata(
- this.config.videoUrl,
- );
- const videoInfo = await this.streamingDecoder.loadMetadata(this.config.videoUrl);
--
-- // Initialize frame renderer
-- this.renderer = new FrameRenderer({
-- width: this.config.width,
-- height: this.config.height,
-- wallpaper: this.config.wallpaper,
-- zoomRegions: this.config.zoomRegions,
-- showShadow: this.config.showShadow,
-- shadowIntensity: this.config.shadowIntensity,
-- backgroundBlur: this.config.backgroundBlur,
-- zoomMotionBlur: this.config.zoomMotionBlur,
-- connectZooms: this.config.connectZooms,
-- borderRadius: this.config.borderRadius,
-- padding: this.config.padding,
-- cropRegion: this.config.cropRegion,
-- videoWidth: videoInfo.width,
-- videoHeight: videoInfo.height,
-- annotationRegions: this.config.annotationRegions,
-- speedRegions: this.config.speedRegions,
-- previewWidth: this.config.previewWidth,
-- previewHeight: this.config.previewHeight,
-- cursorTelemetry: this.config.cursorTelemetry,
-- showCursor: this.config.showCursor,
-- cursorSize: this.config.cursorSize,
-- cursorSmoothing: this.config.cursorSmoothing,
-- cursorMotionBlur: this.config.cursorMotionBlur,
-- cursorClickBounce: this.config.cursorClickBounce,
- cursorSway: this.config.cursorSway,
-- });
-- await this.renderer.initialize();
--
-- // Initialize video encoder
-- await this.initializeEncoder();
--
- const hasAudio = videoInfo.hasAudio;
- const hasAudioRegions = (this.config.audioRegions ?? []).length > 0;
- const hasAudio = videoInfo.hasAudio || hasAudioRegions;
--
-- // Initialize muxer
-- this.muxer = new VideoMuxer(this.config, hasAudio);
-- await this.muxer.initialize();
--
-- // Calculate effective duration and frame count (excluding trim regions)
- const effectiveDuration = this.streamingDecoder.getEffectiveDuration(
- this.config.trimRegions,
- this.config.speedRegions,
- );
- const effectiveDuration = this.streamingDecoder.getEffectiveDuration(this.config.trimRegions, this.config.speedRegions);
-- const totalFrames = Math.ceil(effectiveDuration * this.config.frameRate);
--
- console.log(
- "[VideoExporter] Original duration:",
- videoInfo.duration,
- "s",
- );
- console.log(
- "[VideoExporter] Effective duration:",
- effectiveDuration,
- "s",
- );
- console.log("[VideoExporter] Total frames to export:", totalFrames);
- console.log(
- "[VideoExporter] Using streaming decode (web-demuxer + VideoDecoder)",
- );
- console.log('[VideoExporter] Original duration:', videoInfo.duration, 's');
- console.log('[VideoExporter] Effective duration:', effectiveDuration, 's');
- console.log('[VideoExporter] Total frames to export:', totalFrames);
- console.log('[VideoExporter] Using streaming decode (web-demuxer + VideoDecoder)');
--
-- const frameDuration = 1_000_000 / this.config.frameRate; // in microseconds
-- let frameIndex = 0;
--
-- // Stream decode and process frames — no seeking!
-- await this.streamingDecoder.decodeAll(
-- this.config.frameRate,
-- this.config.trimRegions,
-- this.config.speedRegions,
-- async (videoFrame, _exportTimestampUs, sourceTimestampMs) => {
-- if (this.cancelled) {
-- videoFrame.close();
-- return;
-- }
--
-- const timestamp = frameIndex * frameDuration;
-- const sourceTimestampUs = sourceTimestampMs * 1000;
-- await this.renderer!.renderFrame(videoFrame, sourceTimestampUs);
-- videoFrame.close();
--
-- await this.encodeRenderedFrame(timestamp, frameDuration, frameIndex);
-- frameIndex++;
-- this.reportProgress(frameIndex, totalFrames);
- },
- }
-- );
--
-- if (this.cancelled) {
- return { success: false, error: "Export cancelled" };
- return { success: false, error: 'Export cancelled' };
-- }
--
-- // Finalize encoding
- if (this.encoder && this.encoder.state === "configured") {
- await this.awaitWithWindowsTimeout(
- this.encoder.flush(),
- "encoder flush",
- );
- if (this.encoder && this.encoder.state === 'configured') {
- await this.awaitWithWindowsTimeout(this.encoder.flush(), 'encoder flush');
-- }
--
-- // Wait for queued muxing operations to complete
- await this.awaitWithWindowsTimeout(
- this.pendingMuxing,
- "muxing queued video chunks",
- );
- await this.awaitWithWindowsTimeout(this.pendingMuxing, 'muxing queued video chunks');
--
-- if (hasAudio && !this.cancelled) {
-- const demuxer = this.streamingDecoder.getDemuxer();
- if (demuxer) {
- if (demuxer || hasAudioRegions) {
-- this.audioProcessor = new AudioProcessor();
-- await this.awaitWithWindowsTimeout(
-- this.audioProcessor.process(
- demuxer,
- demuxer!,
-- this.muxer!,
-- this.config.videoUrl,
-- this.config.trimRegions,
-- this.config.speedRegions,
- undefined,
- this.config.audioRegions,
-- ),
- "audio processing",
- 'audio processing',
-- );
-- }
-- }
--
-- // Finalize muxer and get output blob
- const blob = await this.awaitWithWindowsTimeout(
- this.muxer!.finalize(),
- "muxer finalization",
- );
- const blob = await this.awaitWithWindowsTimeout(this.muxer!.finalize(), 'muxer finalization');
--
-- return { success: true, blob };
-- } catch (error) {
- console.error("Export error:", error);
- console.error('Export error:', error);
-- return {
-- success: false,
-- error: error instanceof Error ? error.message : String(error),
-- };
-- } finally {
-- this.cleanup();
-- }
-- }
--
-- private isWindowsPlatform(): boolean {
- if (typeof navigator === "undefined") {
- if (typeof navigator === 'undefined') {
-- return false;
-- }
-- return /Win/i.test(navigator.platform);
-- }
--
- private async awaitWithWindowsTimeout<T>(
- promise: Promise<T>,
- stage: string,
- ): Promise<T> {
- private async awaitWithWindowsTimeout<T>(promise: Promise<T>, stage: string): Promise<T> {
-- if (!this.isWindowsPlatform()) {
-- return promise;
-- }
--
-- let timeoutId: ReturnType<typeof setTimeout> | null = null;
--
-- try {
-- return await Promise.race([
-- promise,
-- new Promise<T>((_, reject) => {
-- timeoutId = setTimeout(() => {
-- reject(new Error(`Export timed out during ${stage} on Windows`));
-- }, this.WINDOWS_FINALIZATION_TIMEOUT_MS);
-- }),
-- ]);
-- } finally {
-- if (timeoutId) {
-- clearTimeout(timeoutId);
-- }
-- }
-- }
--
- private async encodeRenderedFrame(
- timestamp: number,
- frameDuration: number,
- frameIndex: number,
- ) {
- private async encodeRenderedFrame(timestamp: number, frameDuration: number, frameIndex: number) {
-- const canvas = this.renderer!.getCanvas();
--
-- // @ts-ignore - colorSpace not in TypeScript definitions but works at runtime
-- const exportFrame = new VideoFrame(canvas, {
-- timestamp,
-- duration: frameDuration,
-- colorSpace: {
- primaries: "bt709",
- transfer: "iec61966-2-1",
- matrix: "rgb",
- primaries: 'bt709',
- transfer: 'iec61966-2-1',
- matrix: 'rgb',
-- fullRange: true,
-- },
-- });
--
- while (
- this.encoder &&
- this.encoder.encodeQueueSize >= this.MAX_ENCODE_QUEUE &&
- !this.cancelled
- ) {
- await new Promise((resolve) => setTimeout(resolve, 5));
- while (this.encoder && this.encoder.encodeQueueSize >= this.MAX_ENCODE_QUEUE && !this.cancelled) {
- await new Promise(resolve => setTimeout(resolve, 5));
-- }
--
- if (this.encoder && this.encoder.state === "configured") {
- if (this.encoder && this.encoder.state === 'configured') {
-- this.encodeQueue++;
-- this.encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 });
-- } else {
- console.warn(
- `[Frame ${frameIndex}] Encoder not ready! State: ${this.encoder?.state}`,
- );
- console.warn(`[Frame ${frameIndex}] Encoder not ready! State: ${this.encoder?.state}`);
-- }
--
-- exportFrame.close();
-- }
--
-- private reportProgress(currentFrame: number, totalFrames: number) {
-- if (this.config.onProgress) {
-- this.config.onProgress({
-- currentFrame,
-- totalFrames,
-- percentage: totalFrames > 0 ? (currentFrame / totalFrames) * 100 : 100,
-- estimatedTimeRemaining: 0,
-- });
-- }
-- }
--
-- private async initializeEncoder(): Promise<void> {
-- this.encodeQueue = 0;
-- this.pendingMuxing = Promise.resolve();
-- this.chunkCount = 0;
-- let videoDescription: Uint8Array | undefined;
-
- // Ordered from most capable to most compatible. avc1.PPCCLL where PP=profile, CC=constraints, LL=level.
- // High 5.1 → Main 5.1 → Baseline 5.1 → Main 3.1 → Baseline 3.1
- const CODEC_FALLBACK_LIST = this.config.codec
- ? [this.config.codec]
- : ['avc1.640033', 'avc1.4d4033', 'avc1.420033', 'avc1.4d401f', 'avc1.42001f'];
-
- let resolvedCodec: string | null = null;
--
-- this.encoder = new VideoEncoder({
-- output: (chunk, meta) => {
-- // Capture decoder config metadata from encoder output
-- if (meta?.decoderConfig?.description && !videoDescription) {
-- const desc = meta.decoderConfig.description;
- videoDescription = new Uint8Array(
- desc instanceof ArrayBuffer ? desc : (desc as any),
- );
- videoDescription = new Uint8Array(desc instanceof ArrayBuffer ? desc : (desc as any));
-- this.videoDescription = videoDescription;
-- }
-- // Capture colorSpace from encoder metadata if provided
-- if (meta?.decoderConfig?.colorSpace && !this.videoColorSpace) {
-- this.videoColorSpace = meta.decoderConfig.colorSpace;
-- }
--
-- // Stream chunks to muxer in order without retaining an ever-growing promise array
-- const isFirstChunk = this.chunkCount === 0;
-- this.chunkCount++;
--
-- this.pendingMuxing = this.pendingMuxing.then(async () => {
-- try {
-- if (isFirstChunk && this.videoDescription) {
-- // Add decoder config for the first chunk
-- const colorSpace = this.videoColorSpace || {
- primaries: "bt709",
- transfer: "iec61966-2-1",
- matrix: "rgb",
- primaries: 'bt709',
- transfer: 'iec61966-2-1',
- matrix: 'rgb',
-- fullRange: true,
-- };
--
-- const metadata: EncodedVideoChunkMetadata = {
-- decoderConfig: {
- codec: this.config.codec || "avc1.640033",
- codec: resolvedCodec ?? (this.config.codec || 'avc1.640033'),
-- codedWidth: this.config.width,
-- codedHeight: this.config.height,
-- description: this.videoDescription,
-- colorSpace,
-- },
-- };
--
-- await this.muxer!.addVideoChunk(chunk, metadata);
-- } else {
-- await this.muxer!.addVideoChunk(chunk, meta);
-- }
-- } catch (error) {
- console.error("Muxing error:", error);
- console.error('Muxing error:', error);
-- }
-- });
-- this.encodeQueue--;
-- },
-- error: (error) => {
- console.error("[VideoExporter] Encoder error:", error);
- // Stop export encoding failed
- console.error(
- `[VideoExporter] Encoder error (codec: ${resolvedCodec}, ${this.config.width}x${this.config.height}):`,
- error,
- );
- // Stop export — encoding failed
-- this.cancelled = true;
-- },
-- });
-
- const codec = this.config.codec || "avc1.640033";
--
- const encoderConfig: VideoEncoderConfig = {
- codec,
- const baseConfig: Omit<VideoEncoderConfig, 'codec' | 'hardwareAcceleration'> = {
-- width: this.config.width,
-- height: this.config.height,
-- bitrate: this.config.bitrate,
-- framerate: this.config.frameRate,
- latencyMode: "quality", // Changed from 'realtime' to 'quality' for better throughput
- bitrateMode: "variable",
- hardwareAcceleration: "prefer-hardware",
- latencyMode: 'quality',
- bitrateMode: 'variable',
-- };
-
- // Check hardware support first
- const hardwareSupport = await VideoEncoder.isConfigSupported(encoderConfig);
--
- if (hardwareSupport.supported) {
- // Use hardware encoding
- console.log("[VideoExporter] Using hardware acceleration");
- this.encoder.configure(encoderConfig);
- } else {
- // Fall back to software encoding
- console.log(
- "[VideoExporter] Hardware not supported, using software encoding",
- );
- encoderConfig.hardwareAcceleration = "prefer-software";
- for (const candidateCodec of CODEC_FALLBACK_LIST) {
- const hwConfig: VideoEncoderConfig = { ...baseConfig, codec: candidateCodec, hardwareAcceleration: 'prefer-hardware' };
- const hwSupport = await VideoEncoder.isConfigSupported(hwConfig);
- if (hwSupport.supported) {
- resolvedCodec = candidateCodec;
- console.log(`[VideoExporter] Using hardware acceleration with codec ${candidateCodec}`);
- this.encoder.configure(hwConfig);
- return;
- }
--
- const softwareSupport =
- await VideoEncoder.isConfigSupported(encoderConfig);
- if (!softwareSupport.supported) {
- throw new Error("Video encoding not supported on this system");
- const swConfig: VideoEncoderConfig = { ...baseConfig, codec: candidateCodec, hardwareAcceleration: 'prefer-software' };
- const swSupport = await VideoEncoder.isConfigSupported(swConfig);
- if (swSupport.supported) {
- resolvedCodec = candidateCodec;
- console.log(`[VideoExporter] Using software encoding with codec ${candidateCodec}`);
- this.encoder.configure(swConfig);
- return;
-- }
--
- this.encoder.configure(encoderConfig);
- console.warn(`[VideoExporter] Codec ${candidateCodec} not supported (${this.config.width}x${this.config.height}), trying next…`);
-- }
-
- throw new Error(
- `Video encoding not supported on this system. ` +
- `Tried codecs: ${CODEC_FALLBACK_LIST.join(', ')} at ${this.config.width}x${this.config.height}. ` +
- `Your browser or hardware may not support H.264 encoding at this resolution. ` +
- `Try exporting at a lower quality setting.`,
- );
-- }
--
-- cancel(): void {
-- this.cancelled = true;
-- if (this.streamingDecoder) {
-- this.streamingDecoder.cancel();
-- }
-- if (this.audioProcessor) {
-- this.audioProcessor.cancel();
-- }
-- this.cleanup();
-- }
--
-- private cleanup(): void {
-- if (this.encoder) {
-- try {
- if (this.encoder.state === "configured") {
- if (this.encoder.state === 'configured') {
-- this.encoder.close();
-- }
-- } catch (e) {
- console.warn("Error closing encoder:", e);
- console.warn('Error closing encoder:', e);
-- }
-- this.encoder = null;
-- }
--
-- if (this.streamingDecoder) {
-- try {
-- this.streamingDecoder.destroy();
-- } catch (e) {
- console.warn("Error destroying streaming decoder:", e);
- console.warn('Error destroying streaming decoder:', e);
-- }
-- this.streamingDecoder = null;
-- }
--
-- if (this.renderer) {
-- try {
-- this.renderer.destroy();
-- } catch (e) {
- console.warn("Error destroying renderer:", e);
- console.warn('Error destroying renderer:', e);
-- }
-- this.renderer = null;
-- }
--
-- this.muxer = null;
- this.audioProcessor = null;
- this.audioProcessor = null;
-- this.encodeQueue = 0;
-- this.pendingMuxing = Promise.resolve();
-- this.chunkCount = 0;
-- this.videoDescription = undefined;
-- this.videoColorSpace = undefined;
-- }
++ private config: VideoExporterConfig;
++ private streamingDecoder: StreamingVideoDecoder | null = null;
++ private renderer: FrameRenderer | null = null;
++ private encoder: VideoEncoder | null = null;
++ private muxer: VideoMuxer | null = null;
++ private audioProcessor: AudioProcessor | null = null;
++ private cancelled = false;
++ private encodeQueue = 0;
++ // Increased queue size for better throughput with hardware encoding
++ private readonly MAX_ENCODE_QUEUE = 120;
++ private videoDescription: Uint8Array | undefined;
++ private videoColorSpace: VideoColorSpaceInit | undefined;
++ private pendingMuxing: Promise<void> = Promise.resolve();
++ private chunkCount = 0;
++ private readonly WINDOWS_FINALIZATION_TIMEOUT_MS = 60_000;
++
++ constructor(config: VideoExporterConfig) {
++ this.config = config;
++ }
++
++ async export(): Promise<ExportResult> {
++ try {
++ this.cleanup();
++ this.cancelled = false;
++
++ // Initialize streaming decoder and load video metadata
++ this.streamingDecoder = new StreamingVideoDecoder();
++ const videoInfo = await this.streamingDecoder.loadMetadata(this.config.videoUrl);
++
++ // Initialize frame renderer
++ this.renderer = new FrameRenderer({
++ width: this.config.width,
++ height: this.config.height,
++ wallpaper: this.config.wallpaper,
++ zoomRegions: this.config.zoomRegions,
++ showShadow: this.config.showShadow,
++ shadowIntensity: this.config.shadowIntensity,
++ backgroundBlur: this.config.backgroundBlur,
++ zoomMotionBlur: this.config.zoomMotionBlur,
++ connectZooms: this.config.connectZooms,
++ borderRadius: this.config.borderRadius,
++ padding: this.config.padding,
++ cropRegion: this.config.cropRegion,
++ videoWidth: videoInfo.width,
++ videoHeight: videoInfo.height,
++ annotationRegions: this.config.annotationRegions,
++ speedRegions: this.config.speedRegions,
++ previewWidth: this.config.previewWidth,
++ previewHeight: this.config.previewHeight,
++ cursorTelemetry: this.config.cursorTelemetry,
++ showCursor: this.config.showCursor,
++ cursorSize: this.config.cursorSize,
++ cursorSmoothing: this.config.cursorSmoothing,
++ cursorMotionBlur: this.config.cursorMotionBlur,
++ cursorClickBounce: this.config.cursorClickBounce,
++ cursorSway: this.config.cursorSway,
++ });
++ await this.renderer.initialize();
++
++ // Initialize video encoder
++ await this.initializeEncoder();
++
++ const hasAudioRegions = (this.config.audioRegions ?? []).length > 0;
++ const hasAudio = videoInfo.hasAudio || hasAudioRegions;
++
++ // Initialize muxer
++ this.muxer = new VideoMuxer(this.config, hasAudio);
++ await this.muxer.initialize();
++
++ // Calculate effective duration and frame count (excluding trim regions)
++ const effectiveDuration = this.streamingDecoder.getEffectiveDuration(
++ this.config.trimRegions,
++ this.config.speedRegions,
++ );
++ const totalFrames = Math.ceil(effectiveDuration * this.config.frameRate);
++
++ console.log("[VideoExporter] Original duration:", videoInfo.duration, "s");
++ console.log("[VideoExporter] Effective duration:", effectiveDuration, "s");
++ console.log("[VideoExporter] Total frames to export:", totalFrames);
++ console.log("[VideoExporter] Using streaming decode (web-demuxer + VideoDecoder)");
++
++ const frameDuration = 1_000_000 / this.config.frameRate; // in microseconds
++ let frameIndex = 0;
++
++ // Stream decode and process frames — no seeking!
++ await this.streamingDecoder.decodeAll(
++ this.config.frameRate,
++ this.config.trimRegions,
++ this.config.speedRegions,
++ async (videoFrame, _exportTimestampUs, sourceTimestampMs) => {
++ if (this.cancelled) {
++ videoFrame.close();
++ return;
++ }
++
++ const timestamp = frameIndex * frameDuration;
++ const sourceTimestampUs = sourceTimestampMs * 1000;
++ await this.renderer!.renderFrame(videoFrame, sourceTimestampUs);
++ videoFrame.close();
++
++ await this.encodeRenderedFrame(timestamp, frameDuration, frameIndex);
++ frameIndex++;
++ this.reportProgress(frameIndex, totalFrames);
++ },
++ );
++
++ if (this.cancelled) {
++ return { success: false, error: "Export cancelled" };
++ }
++
++ // Finalize encoding
++ if (this.encoder && this.encoder.state === "configured") {
++ await this.awaitWithWindowsTimeout(this.encoder.flush(), "encoder flush");
++ }
++
++ // Wait for queued muxing operations to complete
++ await this.awaitWithWindowsTimeout(this.pendingMuxing, "muxing queued video chunks");
++
++ if (hasAudio && !this.cancelled) {
++ const demuxer = this.streamingDecoder.getDemuxer();
++ if (demuxer || hasAudioRegions) {
++ this.audioProcessor = new AudioProcessor();
++ await this.awaitWithWindowsTimeout(
++ this.audioProcessor.process(
++ demuxer!,
++ this.muxer!,
++ this.config.videoUrl,
++ this.config.trimRegions,
++ this.config.speedRegions,
++ undefined,
++ this.config.audioRegions,
++ ),
++ "audio processing",
++ );
++ }
++ }
++
++ // Finalize muxer and get output blob
++ const blob = await this.awaitWithWindowsTimeout(this.muxer!.finalize(), "muxer finalization");
++
++ return { success: true, blob };
++ } catch (error) {
++ console.error("Export error:", error);
++ return {
++ success: false,
++ error: error instanceof Error ? error.message : String(error),
++ };
++ } finally {
++ this.cleanup();
++ }
++ }
++
++ private isWindowsPlatform(): boolean {
++ if (typeof navigator === "undefined") {
++ return false;
++ }
++ return /Win/i.test(navigator.platform);
++ }
++
++ private async awaitWithWindowsTimeout<T>(promise: Promise<T>, stage: string): Promise<T> {
++ if (!this.isWindowsPlatform()) {
++ return promise;
++ }
++
++ let timeoutId: ReturnType<typeof setTimeout> | null = null;
++
++ try {
++ return await Promise.race([
++ promise,
++ new Promise<T>((_, reject) => {
++ timeoutId = setTimeout(() => {
++ reject(new Error(`Export timed out during ${stage} on Windows`));
++ }, this.WINDOWS_FINALIZATION_TIMEOUT_MS);
++ }),
++ ]);
++ } finally {
++ if (timeoutId) {
++ clearTimeout(timeoutId);
++ }
++ }
++ }
++
++ private async encodeRenderedFrame(timestamp: number, frameDuration: number, frameIndex: number) {
++ const canvas = this.renderer!.getCanvas();
++
++ // @ts-expect-error - colorSpace not in TypeScript definitions but works at runtime
++ const exportFrame = new VideoFrame(canvas, {
++ timestamp,
++ duration: frameDuration,
++ colorSpace: {
++ primaries: "bt709",
++ transfer: "iec61966-2-1",
++ matrix: "rgb",
++ fullRange: true,
++ },
++ });
++
++ while (
++ this.encoder &&
++ this.encoder.encodeQueueSize >= this.MAX_ENCODE_QUEUE &&
++ !this.cancelled
++ ) {
++ await new Promise((resolve) => setTimeout(resolve, 5));
++ }
++
++ if (this.encoder && this.encoder.state === "configured") {
++ this.encodeQueue++;
++ this.encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 });
++ } else {
++ console.warn(`[Frame ${frameIndex}] Encoder not ready! State: ${this.encoder?.state}`);
++ }
++
++ exportFrame.close();
++ }
++
++ private reportProgress(currentFrame: number, totalFrames: number) {
++ if (this.config.onProgress) {
++ this.config.onProgress({
++ currentFrame,
++ totalFrames,
++ percentage: totalFrames > 0 ? (currentFrame / totalFrames) * 100 : 100,
++ estimatedTimeRemaining: 0,
++ });
++ }
++ }
++
++ private async initializeEncoder(): Promise<void> {
++ this.encodeQueue = 0;
++ this.pendingMuxing = Promise.resolve();
++ this.chunkCount = 0;
++ let videoDescription: Uint8Array | undefined;
++
++ // Ordered from most capable to most compatible. avc1.PPCCLL where PP=profile, CC=constraints, LL=level.
++ // High 5.1 → Main 5.1 → Baseline 5.1 → Main 3.1 → Baseline 3.1
++ const CODEC_FALLBACK_LIST = this.config.codec
++ ? [this.config.codec]
++ : ["avc1.640033", "avc1.4d4033", "avc1.420033", "avc1.4d401f", "avc1.42001f"];
++
++ let resolvedCodec: string | null = null;
++
++ this.encoder = new VideoEncoder({
++ output: (chunk, meta) => {
++ // Capture decoder config metadata from encoder output
++ if (meta?.decoderConfig?.description && !videoDescription) {
++ const desc = meta.decoderConfig.description;
++ videoDescription = ArrayBuffer.isView(desc)
++ ? new Uint8Array(desc.buffer, desc.byteOffset, desc.byteLength)
++ : new Uint8Array(desc);
++ this.videoDescription = videoDescription;
++ }
++ // Capture colorSpace from encoder metadata if provided
++ if (meta?.decoderConfig?.colorSpace && !this.videoColorSpace) {
++ this.videoColorSpace = meta.decoderConfig.colorSpace;
++ }
++
++ // Stream chunks to muxer in order without retaining an ever-growing promise array
++ const isFirstChunk = this.chunkCount === 0;
++ this.chunkCount++;
++
++ this.pendingMuxing = this.pendingMuxing.then(async () => {
++ try {
++ if (isFirstChunk && this.videoDescription) {
++ // Add decoder config for the first chunk
++ const colorSpace = this.videoColorSpace || {
++ primaries: "bt709",
++ transfer: "iec61966-2-1",
++ matrix: "rgb",
++ fullRange: true,
++ };
++
++ const metadata: EncodedVideoChunkMetadata = {
++ decoderConfig: {
++ codec: resolvedCodec ?? (this.config.codec || "avc1.640033"),
++ codedWidth: this.config.width,
++ codedHeight: this.config.height,
++ description: this.videoDescription,
++ colorSpace,
++ },
++ };
++
++ await this.muxer!.addVideoChunk(chunk, metadata);
++ } else {
++ await this.muxer!.addVideoChunk(chunk, meta);
++ }
++ } catch (error) {
++ console.error("Muxing error:", error);
++ }
++ });
++ this.encodeQueue--;
++ },
++ error: (error) => {
++ console.error(
++ `[VideoExporter] Encoder error (codec: ${resolvedCodec}, ${this.config.width}x${this.config.height}):`,
++ error,
++ );
++ // Stop export — encoding failed
++ this.cancelled = true;
++ },
++ });
++
++ const baseConfig: Omit<VideoEncoderConfig, "codec" | "hardwareAcceleration"> = {
++ width: this.config.width,
++ height: this.config.height,
++ bitrate: this.config.bitrate,
++ framerate: this.config.frameRate,
++ latencyMode: "quality",
++ bitrateMode: "variable",
++ };
++
++ for (const candidateCodec of CODEC_FALLBACK_LIST) {
++ const hwConfig: VideoEncoderConfig = {
++ ...baseConfig,
++ codec: candidateCodec,
++ hardwareAcceleration: "prefer-hardware",
++ };
++ const hwSupport = await VideoEncoder.isConfigSupported(hwConfig);
++ if (hwSupport.supported) {
++ resolvedCodec = candidateCodec;
++ console.log(`[VideoExporter] Using hardware acceleration with codec ${candidateCodec}`);
++ this.encoder.configure(hwConfig);
++ return;
++ }
++
++ const swConfig: VideoEncoderConfig = {
++ ...baseConfig,
++ codec: candidateCodec,
++ hardwareAcceleration: "prefer-software",
++ };
++ const swSupport = await VideoEncoder.isConfigSupported(swConfig);
++ if (swSupport.supported) {
++ resolvedCodec = candidateCodec;
++ console.log(`[VideoExporter] Using software encoding with codec ${candidateCodec}`);
++ this.encoder.configure(swConfig);
++ return;
++ }
++
++ console.warn(
++ `[VideoExporter] Codec ${candidateCodec} not supported (${this.config.width}x${this.config.height}), trying next...`,
++ );
++ }
++
++ throw new Error(
++ `Video encoding not supported on this system. ` +
++ `Tried codecs: ${CODEC_FALLBACK_LIST.join(", ")} at ${this.config.width}x${this.config.height}. ` +
++ `Your browser or hardware may not support H.264 encoding at this resolution. ` +
++ `Try exporting at a lower quality setting.`,
++ );
++ }
++
++ cancel(): void {
++ this.cancelled = true;
++ if (this.streamingDecoder) {
++ this.streamingDecoder.cancel();
++ }
++ if (this.audioProcessor) {
++ this.audioProcessor.cancel();
++ }
++ this.cleanup();
++ }
++
++ private cleanup(): void {
++ if (this.encoder) {
++ try {
++ if (this.encoder.state === "configured") {
++ this.encoder.close();
++ }
++ } catch (e) {
++ console.warn("Error closing encoder:", e);
++ }
++ this.encoder = null;
++ }
++
++ if (this.streamingDecoder) {
++ try {
++ this.streamingDecoder.destroy();
++ } catch (e) {
++ console.warn("Error destroying streaming decoder:", e);
++ }
++ this.streamingDecoder = null;
++ }
++
++ if (this.renderer) {
++ try {
++ this.renderer.destroy();
++ } catch (e) {
++ console.warn("Error destroying renderer:", e);
++ }
++ this.renderer = null;
++ }
++
++ this.muxer = null;
++ this.audioProcessor = null;
++ this.encodeQueue = 0;
++ this.pendingMuxing = Promise.resolve();
++ this.chunkCount = 0;
++ this.videoDescription = undefined;
++ this.videoColorSpace = undefined;
++ }
}
-