Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

perf: lazy load editor and defer engine initialization

Augustus Otub673f49cf71d
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index 7cc3d42c..db446bfe 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -1,5 +1,4 @@
-import { useEffect, useCallback, useRef } from "react";
-import { EditorInterface } from "./components/index";
+import { useEffect, useCallback, useRef, lazy, Suspense } from "react";
import { ToastContainer } from "./components/Toast";
import { ScriptViewDialog } from "./components/editor/ScriptViewDialog";
import { SearchModal } from "./components/editor/SearchModal";
@@ -13,6 +12,19 @@ import { useRouter } from "./hooks/use-router";
import { useProjectRecovery } from "./hooks/useProjectRecovery";
import { SOCIAL_MEDIA_PRESETS, type SocialMediaCategory } from "@openreel/core";
+const EditorInterface = lazy(() =>
+ import("./components/editor/EditorInterface").then((m) => ({
+ default: m.EditorInterface,
+ }))
+);
+
+const LoadingSpinner: React.FC<{ message: string }> = ({ message }) => (
+ <div className="h-screen w-screen bg-background flex flex-col items-center justify-center">
+ <div className="w-10 h-10 border-2 border-primary border-t-transparent rounded-full animate-spin mb-3" />
+ <p className="text-sm text-text-secondary">{message}</p>
+ </div>
+);
+
const PRESET_DIMENSIONS: Record<string, SocialMediaCategory> = {
"1080x1920": "tiktok",
"1920x1080": "youtube-video",
@@ -124,7 +136,9 @@ function App() {
) : showWelcome ? (
<WelcomeScreen initialTab={initialTab} />
) : (
- <EditorInterface />
+ <Suspense fallback={<LoadingSpinner message="Loading editor..." />}>
+ <EditorInterface />
+ </Suspense>
)}
<ToastContainer />
<ScriptViewDialog
diff --git a/apps/web/src/components/editor/SaveTemplateDialog.tsx b/apps/web/src/components/editor/SaveTemplateDialog.tsx
index d8321cfd..5a8750ee 100644
--- a/apps/web/src/components/editor/SaveTemplateDialog.tsx
+++ b/apps/web/src/components/editor/SaveTemplateDialog.tsx
@@ -61,13 +61,9 @@ export const SaveTemplateDialog: React.FC<SaveTemplateDialogProps> = ({
setError(null);
try {
- const templateEngine = getTemplateEngine();
+ const templateEngine = await getTemplateEngine();
const graphicsEngine = getGraphicsEngine();
- if (!templateEngine) {
- throw new Error("Template engine not available");
- }
-
await templateEngine.initialize();
const tagArray = tags
diff --git a/apps/web/src/components/editor/inspector/AdjustmentLayerSection.tsx b/apps/web/src/components/editor/inspector/AdjustmentLayerSection.tsx
index ffce9ee1..2926415c 100644
--- a/apps/web/src/components/editor/inspector/AdjustmentLayerSection.tsx
+++ b/apps/web/src/components/editor/inspector/AdjustmentLayerSection.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useCallback, useMemo } from "react";
+import React, { useState, useCallback, useMemo, useEffect } from "react";
import {
Layers,
Plus,
@@ -99,8 +99,22 @@ export const AdjustmentLayerSection: React.FC<AdjustmentLayerSectionProps> = ({
const [expandedLayer, setExpandedLayer] = useState<string | null>(null);
const [showBlendModes, setShowBlendModes] = useState(false);
-
- const adjustmentLayerEngine = getAdjustmentLayerEngine();
+ const [adjustmentLayerEngine, setAdjustmentLayerEngine] =
+ useState<import("@openreel/core").AdjustmentLayerEngine | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ const loadEngine = async () => {
+ const engine = await getAdjustmentLayerEngine();
+ if (!cancelled) {
+ setAdjustmentLayerEngine(engine);
+ }
+ };
+ loadEngine();
+ return () => {
+ cancelled = true;
+ };
+ }, [getAdjustmentLayerEngine]);
const currentTrack = useMemo(() => {
for (const track of project.timeline.tracks) {
diff --git a/apps/web/src/components/editor/inspector/AutoCaptionPanel.tsx b/apps/web/src/components/editor/inspector/AutoCaptionPanel.tsx
index 751cc22e..8ed261c0 100644
--- a/apps/web/src/components/editor/inspector/AutoCaptionPanel.tsx
+++ b/apps/web/src/components/editor/inspector/AutoCaptionPanel.tsx
@@ -43,27 +43,23 @@ export const AutoCaptionPanel: React.FC = () => {
);
const handleStartTranscription = useCallback(async () => {
- const speechEngine = getSpeechToTextEngine();
- if (!speechEngine) {
- setError("Speech-to-text engine not available");
- return;
- }
-
setError(null);
setSegments([]);
setIsTranscribing(true);
- speechEngine.setOptions({ language: selectedLanguage });
+ try {
+ const speechEngine = await getSpeechToTextEngine();
- speechEngine.onProgress((prog) => {
- setProgress(prog);
- });
+ speechEngine.setOptions({ language: selectedLanguage });
- speechEngine.onSegment((segment) => {
- setSegments((prev) => [...prev, segment]);
- });
+ speechEngine.onProgress((prog) => {
+ setProgress(prog);
+ });
+
+ speechEngine.onSegment((segment) => {
+ setSegments((prev) => [...prev, segment]);
+ });
- try {
await speechEngine.startLiveTranscription();
} catch (err) {
setError(
@@ -73,9 +69,8 @@ export const AutoCaptionPanel: React.FC = () => {
}
}, [getSpeechToTextEngine, selectedLanguage]);
- const handleStopTranscription = useCallback(() => {
- const speechEngine = getSpeechToTextEngine();
- if (!speechEngine) return;
+ const handleStopTranscription = useCallback(async () => {
+ const speechEngine = await getSpeechToTextEngine();
const result = speechEngine.stopTranscription();
setIsTranscribing(false);
@@ -88,7 +83,7 @@ export const AutoCaptionPanel: React.FC = () => {
});
if (selectedStyle !== "default") {
- applySubtitleStylePreset(selectedStyle);
+ await applySubtitleStylePreset(selectedStyle);
}
}
}, [
@@ -98,9 +93,10 @@ export const AutoCaptionPanel: React.FC = () => {
selectedStyle,
]);
- const handleApplySegments = useCallback(() => {
- const speechEngine = getSpeechToTextEngine();
- if (!speechEngine || segments.length === 0) return;
+ const handleApplySegments = useCallback(async () => {
+ if (segments.length === 0) return;
+
+ const speechEngine = await getSpeechToTextEngine();
const subtitles = speechEngine.segmentsToSubtitles(segments);
subtitles.forEach((subtitle) => {
@@ -108,7 +104,7 @@ export const AutoCaptionPanel: React.FC = () => {
});
if (selectedStyle !== "default") {
- applySubtitleStylePreset(selectedStyle);
+ await applySubtitleStylePreset(selectedStyle);
}
setSegments([]);
diff --git a/apps/web/src/components/editor/inspector/GreenScreenSection.tsx b/apps/web/src/components/editor/inspector/GreenScreenSection.tsx
index 1de62c09..91060632 100644
--- a/apps/web/src/components/editor/inspector/GreenScreenSection.tsx
+++ b/apps/web/src/components/editor/inspector/GreenScreenSection.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useCallback, useMemo } from "react";
+import React, { useState, useCallback, useMemo, useEffect } from "react";
import { Video, Pipette, RefreshCw, Eye, EyeOff, Layers } from "lucide-react";
import { useProjectStore } from "../../../stores/project-store";
import { useEngineStore } from "../../../stores/engine-store";
@@ -105,11 +105,22 @@ export const GreenScreenSection: React.FC<GreenScreenSectionProps> = ({
);
const [isPickingColor, setIsPickingColor] = useState(false);
+ const [chromaKeyEngine, setChromaKeyEngine] =
+ useState<import("@openreel/core").ChromaKeyEngine | null>(null);
- const chromaKeyEngine = useMemo(
- () => getChromaKeyEngine(),
- [getChromaKeyEngine],
- );
+ useEffect(() => {
+ let cancelled = false;
+ const loadEngine = async () => {
+ const engine = await getChromaKeyEngine();
+ if (!cancelled) {
+ setChromaKeyEngine(engine);
+ }
+ };
+ loadEngine();
+ return () => {
+ cancelled = true;
+ };
+ }, [getChromaKeyEngine]);
const settings = useMemo<ChromaKeySettings>(() => {
if (!chromaKeyEngine) {
diff --git a/apps/web/src/components/editor/inspector/MaskSection.tsx b/apps/web/src/components/editor/inspector/MaskSection.tsx
index 08f93a03..d83ef2d2 100644
--- a/apps/web/src/components/editor/inspector/MaskSection.tsx
+++ b/apps/web/src/components/editor/inspector/MaskSection.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useCallback, useMemo } from "react";
+import React, { useState, useCallback, useMemo, useEffect } from "react";
import {
Square,
Circle,
@@ -205,8 +205,22 @@ export const MaskSection: React.FC<MaskSectionProps> = ({ clipId }) => {
const [selectedMaskId, setSelectedMaskId] = useState<string | null>(null);
const [expandedMasks, setExpandedMasks] = useState<Set<string>>(new Set());
const [refreshKey, setRefreshKey] = useState(0);
+ const [maskEngine, setMaskEngine] =
+ useState<import("@openreel/core").MaskEngine | null>(null);
- const maskEngine = useMemo(() => getMaskEngine?.(), [getMaskEngine]);
+ useEffect(() => {
+ let cancelled = false;
+ const loadEngine = async () => {
+ const engine = await getMaskEngine();
+ if (!cancelled) {
+ setMaskEngine(engine);
+ }
+ };
+ loadEngine();
+ return () => {
+ cancelled = true;
+ };
+ }, [getMaskEngine]);
const masks = useMemo(() => {
if (!maskEngine) return [];
diff --git a/apps/web/src/components/editor/inspector/MultiCameraPanel.tsx b/apps/web/src/components/editor/inspector/MultiCameraPanel.tsx
index cdde2100..ec4dc5d3 100644
--- a/apps/web/src/components/editor/inspector/MultiCameraPanel.tsx
+++ b/apps/web/src/components/editor/inspector/MultiCameraPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useCallback, useMemo } from "react";
+import React, { useState, useCallback, useMemo, useEffect } from "react";
import {
Video,
Camera,
@@ -176,11 +176,22 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
const [selectedClips, setSelectedClips] = useState<string[]>([]);
+ const [multiCamEngine, setMultiCamEngine] =
+ useState<import("@openreel/core").MultiCamEngine | null>(null);
- const multiCamEngine = useMemo(
- () => getMultiCamEngine?.(),
- [getMultiCamEngine],
- );
+ useEffect(() => {
+ let cancelled = false;
+ const loadEngine = async () => {
+ const engine = await getMultiCamEngine();
+ if (!cancelled) {
+ setMultiCamEngine(engine);
+ }
+ };
+ loadEngine();
+ return () => {
+ cancelled = true;
+ };
+ }, [getMultiCamEngine]);
const groups = useMemo(() => {
return multiCamEngine?.getAllGroups() || [];
diff --git a/apps/web/src/components/editor/inspector/MusicLibraryPanel.tsx b/apps/web/src/components/editor/inspector/MusicLibraryPanel.tsx
index 31c19ab6..b8561020 100644
--- a/apps/web/src/components/editor/inspector/MusicLibraryPanel.tsx
+++ b/apps/web/src/components/editor/inspector/MusicLibraryPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useCallback, useMemo } from "react";
+import React, { useState, useCallback, useMemo, useEffect } from "react";
import {
Music,
Zap,
@@ -121,14 +121,27 @@ export const MusicLibraryPanel: React.FC = () => {
const [selectedMoods, setSelectedMoods] = useState<MoodTag[]>([]);
const [searchQuery, setSearchQuery] = useState("");
const [playingId, setPlayingId] = useState<string | null>(null);
-
- const soundLibrary = getSoundLibraryEngine();
+ const [allMusic, setAllMusic] = useState<SoundItem[]>([]);
+ const [allSfx, setAllSfx] = useState<SoundItem[]>([]);
+
+ useEffect(() => {
+ let cancelled = false;
+ const loadSounds = async () => {
+ const engine = await getSoundLibraryEngine();
+ if (!cancelled) {
+ setAllMusic(engine.getMusic());
+ setAllSfx(engine.getSFX());
+ }
+ };
+ loadSounds();
+ return () => {
+ cancelled = true;
+ };
+ }, [getSoundLibraryEngine]);
const sounds = useMemo(() => {
- if (!soundLibrary) return [];
-
- let results =
- activeTab === "music" ? soundLibrary.getMusic() : soundLibrary.getSFX();
+ let results = activeTab === "music" ? allMusic : allSfx;
+ if (results.length === 0) return [];
if (activeTab === "music" && selectedGenre !== "all") {
results = results.filter((s) => s.subcategory === selectedGenre);
@@ -155,7 +168,8 @@ export const MusicLibraryPanel: React.FC = () => {
return results;
}, [
- soundLibrary,
+ allMusic,
+ allSfx,
activeTab,
selectedGenre,
selectedSfxCategory,
@@ -165,31 +179,32 @@ export const MusicLibraryPanel: React.FC = () => {
const handlePlay = useCallback(
async (sound: SoundItem) => {
- if (!soundLibrary) return;
+ const engine = await getSoundLibraryEngine();
if (playingId === sound.id) {
- soundLibrary.stopPreview();
+ engine.stopPreview();
setPlayingId(null);
} else {
- soundLibrary.stopPreview();
+ engine.stopPreview();
setPlayingId(sound.id);
- await soundLibrary.previewSound(sound);
+ await engine.previewSound(sound);
}
},
- [soundLibrary, playingId],
+ [getSoundLibraryEngine, playingId],
);
- const handleStop = useCallback(() => {
- if (!soundLibrary) return;
- soundLibrary.stopPreview();
+ const handleStop = useCallback(async () => {
+ const engine = await getSoundLibraryEngine();
+ engine.stopPreview();
setPlayingId(null);
- }, [soundLibrary]);
+ }, [getSoundLibraryEngine]);
const handleAddToTimeline = useCallback(
async (sound: SoundItem) => {
- if (!project || !soundLibrary) return;
+ if (!project) return;
- const blob = soundLibrary.getSoundBlob(sound.id);
+ const engine = await getSoundLibraryEngine();
+ const blob = engine.getSoundBlob(sound.id);
if (!blob) {
console.error("[MusicLibrary] Failed to get sound blob for:", sound.id);
return;
@@ -232,7 +247,7 @@ export const MusicLibraryPanel: React.FC = () => {
await addClip(targetTrack.id, mediaId, trackEndTime);
}
},
- [project, soundLibrary, addTrack, addClip, importMedia],
+ [project, getSoundLibraryEngine, addTrack, addClip, importMedia],
);
const toggleMood = useCallback((mood: MoodTag) => {
diff --git a/apps/web/src/components/editor/inspector/NestedSequenceSection.tsx b/apps/web/src/components/editor/inspector/NestedSequenceSection.tsx
index 2c494aff..877a9763 100644
--- a/apps/web/src/components/editor/inspector/NestedSequenceSection.tsx
+++ b/apps/web/src/components/editor/inspector/NestedSequenceSection.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useCallback, useMemo } from "react";
+import React, { useState, useCallback, useMemo, useEffect } from "react";
import {
Layers,
FolderOpen,
@@ -32,8 +32,22 @@ export const NestedSequenceSection: React.FC<NestedSequenceSectionProps> = ({
const [expandedCompound, setExpandedCompound] = useState<string | null>(null);
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
-
- const nestedSequenceEngine = getNestedSequenceEngine();
+ const [nestedSequenceEngine, setNestedSequenceEngine] =
+ useState<import("@openreel/core").NestedSequenceEngine | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ const loadEngine = async () => {
+ const engine = await getNestedSequenceEngine();
+ if (!cancelled) {
+ setNestedSequenceEngine(engine);
+ }
+ };
+ loadEngine();
+ return () => {
+ cancelled = true;
+ };
+ }, [getNestedSequenceEngine]);
const allCompoundClips = useMemo(() => {
return nestedSequenceEngine?.getAllCompoundClips() || [];
diff --git a/apps/web/src/components/editor/inspector/TemplatesBrowserPanel.tsx b/apps/web/src/components/editor/inspector/TemplatesBrowserPanel.tsx
index 0e882ee5..2654cc81 100644
--- a/apps/web/src/components/editor/inspector/TemplatesBrowserPanel.tsx
+++ b/apps/web/src/components/editor/inspector/TemplatesBrowserPanel.tsx
@@ -150,13 +150,9 @@ export const TemplatesBrowserPanel: React.FC<TemplatesBrowserPanelProps> = ({
useEffect(() => {
const loadTemplates = async () => {
setIsLoading(true);
- const templateEngine = getTemplateEngine();
- if (!templateEngine) {
- setIsLoading(false);
- return;
- }
try {
+ const templateEngine = await getTemplateEngine();
await templateEngine.initialize();
const localTemplates = await templateEngine.listTemplates();
const cloudTemplates = await templateCloudService.listTemplates();
@@ -193,8 +189,7 @@ export const TemplatesBrowserPanel: React.FC<TemplatesBrowserPanelProps> = ({
setSelectedTemplateId(templateId);
setApplyError(null);
- const templateEngine = getTemplateEngine();
- if (!templateEngine) return;
+ const templateEngine = await getTemplateEngine();
const selectedTemplate = templates.find((t) => t.id === templateId);
let template = await templateEngine.loadTemplate(templateId);
@@ -225,9 +220,8 @@ export const TemplatesBrowserPanel: React.FC<TemplatesBrowserPanelProps> = ({
const handleApplyTemplate = useCallback(async () => {
if (!selectedTemplateId) return;
- const templateEngine = getTemplateEngine();
+ const templateEngine = await getTemplateEngine();
const titleEngine = getTitleEngine();
- if (!templateEngine) return;
setApplyError(null);
@@ -462,10 +456,9 @@ export const TemplatesBrowserPanel: React.FC<TemplatesBrowserPanelProps> = ({
setIsSaveDialogOpen(false);
const loadTemplates = async () => {
setIsLoading(true);
- const templateEngine = getTemplateEngine();
- if (!templateEngine) return;
try {
+ const templateEngine = await getTemplateEngine();
await templateEngine.initialize();
const localTemplates = await templateEngine.listTemplates();
const cloudTemplates = await templateCloudService.listTemplates();
diff --git a/apps/web/src/components/index.ts b/apps/web/src/components/index.ts
index 75cb8ed3..19e45b27 100644
--- a/apps/web/src/components/index.ts
+++ b/apps/web/src/components/index.ts
@@ -3,4 +3,3 @@
*/
export * from "./audio-mixer";
-export * from "./editor";
diff --git a/apps/web/src/components/welcome/TemplateGallery.tsx b/apps/web/src/components/welcome/TemplateGallery.tsx
index 9d7d2f6d..0d40fd57 100644
--- a/apps/web/src/components/welcome/TemplateGallery.tsx
+++ b/apps/web/src/components/welcome/TemplateGallery.tsx
@@ -40,61 +40,59 @@ export const TemplateGallery: React.FC<TemplateGalleryProps> = ({
const loadTemplates = async () => {
setIsLoading(true);
try {
- const templateEngine = getTemplateEngine();
- if (templateEngine) {
- await templateEngine.initialize();
- const builtinTemplates = templateEngine.getBuiltinTemplates();
- const cloudTemplates =
- await templateCloudService.listScriptableTemplates();
-
- const allTemplates = [
- ...(builtinTemplates.map((t) => {
- const placeholderClipMap = new Map<
- string,
- { clipId: string; trackId: string }
- >();
- for (const track of t.timeline.tracks) {
- for (const clip of track.clips) {
- const pClip = clip as PlaceholderClip;
- if (pClip.isPlaceholder && pClip.placeholderId) {
- placeholderClipMap.set(pClip.placeholderId, {
- clipId: clip.id,
- trackId: track.id,
- });
- }
+ const templateEngine = await getTemplateEngine();
+ await templateEngine.initialize();
+ const builtinTemplates = templateEngine.getBuiltinTemplates();
+ const cloudTemplates =
+ await templateCloudService.listScriptableTemplates();
+
+ const allTemplates = [
+ ...(builtinTemplates.map((t) => {
+ const placeholderClipMap = new Map<
+ string,
+ { clipId: string; trackId: string }
+ >();
+ for (const track of t.timeline.tracks) {
+ for (const clip of track.clips) {
+ const pClip = clip as PlaceholderClip;
+ if (pClip.isPlaceholder && pClip.placeholderId) {
+ placeholderClipMap.set(pClip.placeholderId, {
+ clipId: clip.id,
+ trackId: track.id,
+ });
}
}
-
- return {
- ...t,
- placeholders: t.placeholders.map((p) => {
- const clipInfo = placeholderClipMap.get(p.id);
- return {
- ...p,
- targets: clipInfo
- ? [
- {
- clipId: clipInfo.clipId,
- trackId: clipInfo.trackId,
- property: "content",
- },
- ]
- : [],
- defaultValue: p.defaultValue as unknown,
- };
- }),
- socialCategory: mapCategoryToSocial(t.category),
- };
- }) as ScriptableTemplate[]),
- ...cloudTemplates,
- ];
-
- const unique = Array.from(
- new Map(allTemplates.map((t) => [t.id, t])).values(),
- );
-
- setTemplates(unique);
- }
+ }
+
+ return {
+ ...t,
+ placeholders: t.placeholders.map((p) => {
+ const clipInfo = placeholderClipMap.get(p.id);
+ return {
+ ...p,
+ targets: clipInfo
+ ? [
+ {
+ clipId: clipInfo.clipId,
+ trackId: clipInfo.trackId,
+ property: "content",
+ },
+ ]
+ : [],
+ defaultValue: p.defaultValue as unknown,
+ };
+ }),
+ socialCategory: mapCategoryToSocial(t.category),
+ };
+ }) as ScriptableTemplate[]),
+ ...cloudTemplates,
+ ];
+
+ const unique = Array.from(
+ new Map(allTemplates.map((t) => [t.id, t])).values(),
+ );
+
+ setTemplates(unique);
} catch (error) {
console.error("Failed to load templates:", error);
} finally {
diff --git a/apps/web/src/components/welcome/TemplatePreviewModal.tsx b/apps/web/src/components/welcome/TemplatePreviewModal.tsx
index 809c28e3..baedc0c3 100644
--- a/apps/web/src/components/welcome/TemplatePreviewModal.tsx
+++ b/apps/web/src/components/welcome/TemplatePreviewModal.tsx
@@ -89,11 +89,8 @@ export const TemplatePreviewModal: React.FC<TemplatePreviewModalProps> = ({
setError(null);
try {
- const templateEngine = getTemplateEngine();
+ const templateEngine = await getTemplateEngine();
const titleEngine = getTitleEngine();
- if (!templateEngine) {
- throw new Error("Template engine not available");
- }
const effectiveValues = { ...values };
for (const placeholder of template.placeholders) {
diff --git a/apps/web/src/components/welcome/WelcomeScreen.tsx b/apps/web/src/components/welcome/WelcomeScreen.tsx
index 31457565..3378a4a1 100644
--- a/apps/web/src/components/welcome/WelcomeScreen.tsx
+++ b/apps/web/src/components/welcome/WelcomeScreen.tsx
@@ -14,6 +14,7 @@ import { SOCIAL_MEDIA_PRESETS, type SocialMediaCategory } from "@openreel/core";
import { TemplateGallery } from "./TemplateGallery";
import { RecentProjects } from "./RecentProjects";
import { useRouter } from "../../hooks/use-router";
+import { useEditorPreload } from "../../hooks/useEditorPreload";
interface FormatOption {
id: string;
@@ -141,6 +142,8 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({ initialTab }) => {
const [viewMode, setViewMode] = useState<ViewMode>(initialTab ?? "home");
const [hoveredFormat, setHoveredFormat] = useState<string | null>(null);
+ useEditorPreload(true);
+
const handleCreateProject = useCallback(
(option: FormatOption) => {
const preset = SOCIAL_MEDIA_PRESETS[option.preset];
diff --git a/apps/web/src/hooks/useEditorPreload.ts b/apps/web/src/hooks/useEditorPreload.ts
new file mode 100644
index 00000000..ae2ee201
--- /dev/null
+++ b/apps/web/src/hooks/useEditorPreload.ts
@@ -0,0 +1,26 @@
+import { useEffect, useRef } from "react";
+
+let preloadStarted = false;
+
+export function useEditorPreload(shouldPreload: boolean): void {
+ const hasPreloaded = useRef(false);
+
+ useEffect(() => {
+ if (!shouldPreload || hasPreloaded.current || preloadStarted) {
+ return;
+ }
+
+ preloadStarted = true;
+ hasPreloaded.current = true;
+
+ const preload = () => {
+ import("../components/editor/EditorInterface");
+ };
+
+ if ("requestIdleCallback" in window) {
+ window.requestIdleCallback(preload, { timeout: 2000 });
+ } else {
+ setTimeout(preload, 100);
+ }
+ }, [shouldPreload]);
+}
diff --git a/apps/web/src/stores/engine-store.ts b/apps/web/src/stores/engine-store.ts
index a122fb69..928cbb00 100644
--- a/apps/web/src/stores/engine-store.ts
+++ b/apps/web/src/stores/engine-store.ts
@@ -27,6 +27,18 @@ import {
} from "@openreel/core";
import type { RenderedFrame } from "@openreel/core";
+const lazyEngineCache = new Map<string, unknown>();
+
+async function getOrCreateEngine<T>(
+ key: string,
+ factory: () => T | Promise<T>
+): Promise<T> {
+ if (!lazyEngineCache.has(key)) {
+ lazyEngineCache.set(key, Promise.resolve(factory()));
+ }
+ return lazyEngineCache.get(key) as Promise<T>;
+}
+
export interface AudioLevelData {
peaks: Map<string, number>;
rms: Map<string, number>;
@@ -82,18 +94,18 @@ export interface EngineState {
getAudioEngine: () => AudioEngine | null;
getPlaybackController: () => PlaybackController | null;
getTitleEngine: () => TitleEngine | null;
- getSubtitleEngine: () => SubtitleEngine | null;
+ getSubtitleEngine: () => Promise<SubtitleEngine>;
getGraphicsEngine: () => GraphicsEngine | null;
getPhotoEngine: () => PhotoEngine | null;
getExportEngine: () => ExportEngine | null;
- getSpeechToTextEngine: () => SpeechToTextEngine | null;
- getTemplateEngine: () => TemplateEngine | null;
- getSoundLibraryEngine: () => SoundLibraryEngine | null;
- getChromaKeyEngine: () => ChromaKeyEngine | null;
- getMultiCamEngine: () => MultiCamEngine | null;
- getMaskEngine: () => MaskEngine | null;
- getNestedSequenceEngine: () => NestedSequenceEngine | null;
- getAdjustmentLayerEngine: () => AdjustmentLayerEngine | null;
+ getSpeechToTextEngine: () => Promise<SpeechToTextEngine>;
+ getTemplateEngine: () => Promise<TemplateEngine>;
+ getSoundLibraryEngine: () => Promise<SoundLibraryEngine>;
+ getChromaKeyEngine: () => Promise<ChromaKeyEngine>;
+ getMultiCamEngine: () => Promise<MultiCamEngine>;
+ getMaskEngine: () => Promise<MaskEngine>;
+ getNestedSequenceEngine: () => Promise<NestedSequenceEngine>;
+ getAdjustmentLayerEngine: () => Promise<AdjustmentLayerEngine>;
}
/**
@@ -172,15 +184,6 @@ const DEFAULT_PLAYBACK_STATS: PlaybackStats = {
};
coreTitleEngine.initialize(1920, 1080);
-const eagerSubtitleEngine = new SubtitleEngine();
-const eagerSpeechToTextEngine = new SpeechToTextEngine();
-const eagerTemplateEngine = new TemplateEngine();
-const eagerSoundLibraryEngine = new SoundLibraryEngine();
-const eagerChromaKeyEngine = new ChromaKeyEngine({ width: 1920, height: 1080 });
-const eagerMultiCamEngine = new MultiCamEngine();
-const eagerMaskEngine = new MaskEngine({ width: 1920, height: 1080 });
-const eagerNestedSequenceEngine = new NestedSequenceEngine();
-const eagerAdjustmentLayerEngine = new AdjustmentLayerEngine();
export const useEngineStore = create<EngineState>()(
subscribeWithSelector((set, get) => ({
@@ -192,18 +195,18 @@ export const useEngineStore = create<EngineState>()(
audioEngine: null,
playbackController: null,
titleEngine: coreTitleEngine,
- subtitleEngine: eagerSubtitleEngine,
+ subtitleEngine: null,
graphicsEngine: coreGraphicsEngine,
photoEngine: null,
exportEngine: null,
- speechToTextEngine: eagerSpeechToTextEngine,
- templateEngine: eagerTemplateEngine,
- soundLibraryEngine: eagerSoundLibraryEngine,
- chromaKeyEngine: eagerChromaKeyEngine,
- multiCamEngine: eagerMultiCamEngine,
- maskEngine: eagerMaskEngine,
- nestedSequenceEngine: eagerNestedSequenceEngine,
- adjustmentLayerEngine: eagerAdjustmentLayerEngine,
+ speechToTextEngine: null,
+ templateEngine: null,
+ soundLibraryEngine: null,
+ chromaKeyEngine: null,
+ multiCamEngine: null,
+ maskEngine: null,
+ nestedSequenceEngine: null,
+ adjustmentLayerEngine: null,
currentFrame: null,
playbackStats: DEFAULT_PLAYBACK_STATS,
@@ -240,7 +243,6 @@ export const useEngineStore = create<EngineState>()(
audioEngine,
playbackController,
titleEngine: coreTitleEngine,
- subtitleEngine: eagerSubtitleEngine,
graphicsEngine: coreGraphicsEngine,
photoEngine,
exportEngine,
@@ -273,6 +275,8 @@ export const useEngineStore = create<EngineState>()(
state.currentFrame.image.close();
}
+ lazyEngineCache.clear();
+
set({
initialized: false,
initializing: false,
@@ -368,17 +372,32 @@ export const useEngineStore = create<EngineState>()(
getAudioEngine: () => get().audioEngine,
getPlaybackController: () => get().playbackController,
getTitleEngine: () => get().titleEngine,
- getSubtitleEngine: () => get().subtitleEngine,
+ getSubtitleEngine: () =>
+ getOrCreateEngine("subtitle", () => new SubtitleEngine()),
getGraphicsEngine: () => get().graphicsEngine,
getPhotoEngine: () => get().photoEngine,
getExportEngine: () => get().exportEngine,
- getSpeechToTextEngine: () => get().speechToTextEngine,
- getTemplateEngine: () => get().templateEngine,
- getSoundLibraryEngine: () => get().soundLibraryEngine,
- getChromaKeyEngine: () => get().chromaKeyEngine,
- getMultiCamEngine: () => get().multiCamEngine,
- getMaskEngine: () => get().maskEngine,
- getNestedSequenceEngine: () => get().nestedSequenceEngine,
- getAdjustmentLayerEngine: () => get().adjustmentLayerEngine,
+ getSpeechToTextEngine: () =>
+ getOrCreateEngine("speechToText", () => new SpeechToTextEngine()),
+ getTemplateEngine: () =>
+ getOrCreateEngine("template", () => new TemplateEngine()),
+ getSoundLibraryEngine: () =>
+ getOrCreateEngine("soundLibrary", () => new SoundLibraryEngine()),
+ getChromaKeyEngine: () =>
+ getOrCreateEngine(
+ "chromaKey",
+ () => new ChromaKeyEngine({ width: 1920, height: 1080 })
+ ),
+ getMultiCamEngine: () =>
+ getOrCreateEngine("multiCam", () => new MultiCamEngine()),
+ getMaskEngine: () =>
+ getOrCreateEngine(
+ "mask",
+ () => new MaskEngine({ width: 1920, height: 1080 })
+ ),
+ getNestedSequenceEngine: () =>
+ getOrCreateEngine("nestedSequence", () => new NestedSequenceEngine()),
+ getAdjustmentLayerEngine: () =>
+ getOrCreateEngine("adjustmentLayer", () => new AdjustmentLayerEngine()),
})),
);
diff --git a/apps/web/src/stores/project-store.test.ts b/apps/web/src/stores/project-store.test.ts
index b4fc813c..884715cd 100644
--- a/apps/web/src/stores/project-store.test.ts
+++ b/apps/web/src/stores/project-store.test.ts
@@ -721,7 +721,7 @@ describe("ProjectStore - Subtitles", () => {
expect(subtitle?.text).toBe("Updated");
});
- it("should export SRT", () => {
+ it("should export SRT", async () => {
useProjectStore.getState().addSubtitle({
id: "sub-1",
text: "First subtitle",
@@ -736,13 +736,13 @@ describe("ProjectStore - Subtitles", () => {
},
});
- const srt = useProjectStore.getState().exportSRT();
+ const srt = await useProjectStore.getState().exportSRT();
expect(srt).toContain("First subtitle");
expect(srt).toContain("00:00:00");
});
- it("should get subtitle style presets", () => {
- const presets = useProjectStore.getState().getSubtitleStylePresets();
+ it("should get subtitle style presets", async () => {
+ const presets = await useProjectStore.getState().getSubtitleStylePresets();
expect(Array.isArray(presets)).toBe(true);
});
});
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index e88e0b2e..506f0979 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -232,10 +232,12 @@ export interface ProjectState {
getSubtitle: (
subtitleId: string,
) => import("@openreel/core").Subtitle | undefined;
- importSRT: (srtContent: string) => { success: boolean; errors: string[] };
- exportSRT: () => string;
- applySubtitleStylePreset: (presetName: string) => boolean;
- getSubtitleStylePresets: () => string[];
+ importSRT: (
+ srtContent: string
+ ) => Promise<{ success: boolean; errors: string[] }>;
+ exportSRT: () => Promise<string>;
+ applySubtitleStylePreset: (presetName: string) => Promise<boolean>;
+ getSubtitleStylePresets: () => Promise<string[]>;
// Marker actions
addMarker: (time: number, label?: string, color?: string) => void;
@@ -2512,16 +2514,10 @@ export const useProjectStore = create<ProjectState>()(
);
},
- /**
- * Import SRT file and add subtitles to timeline
- * Parse SRT files using SubtitleEngine
- */
- importSRT: (srtContent: string) => {
- const subtitleEngine = useEngineStore.getState().getSubtitleEngine();
- if (!subtitleEngine) {
- console.error("SubtitleEngine not initialized");
- return { success: false, errors: ["SubtitleEngine not initialized"] };
- }
+ importSRT: async (srtContent: string) => {
+ const subtitleEngine = await useEngineStore
+ .getState()
+ .getSubtitleEngine();
const { project } = get();
const { timeline, result } = subtitleEngine.importSRT(
@@ -2539,39 +2535,26 @@ export const useProjectStore = create<ProjectState>()(
});
return { success: true, errors: [] };
} else {
- // Convert parse errors to string messages
const errorMessages = result.errors.map(
- (err) => `Line ${err.line}: ${err.message}`,
+ (err: { line: number; message: string }) =>
+ `Line ${err.line}: ${err.message}`,
);
return { success: false, errors: errorMessages };
}
},
- /**
- * Export all subtitles to SRT format
- * Export SRT files
- */
- exportSRT: () => {
- const subtitleEngine = useEngineStore.getState().getSubtitleEngine();
- if (!subtitleEngine) {
- console.error("SubtitleEngine not initialized");
- return "";
- }
-
+ exportSRT: async () => {
+ const subtitleEngine = await useEngineStore
+ .getState()
+ .getSubtitleEngine();
const { project } = get();
return subtitleEngine.exportSRT(project.timeline);
},
- /**
- * Apply a style preset to all subtitles
- * Apply subtitle style presets
- */
- applySubtitleStylePreset: (presetName: string) => {
- const subtitleEngine = useEngineStore.getState().getSubtitleEngine();
- if (!subtitleEngine) {
- console.error("SubtitleEngine not initialized");
- return false;
- }
+ applySubtitleStylePreset: async (presetName: string) => {
+ const subtitleEngine = await useEngineStore
+ .getState()
+ .getSubtitleEngine();
const { project } = get();
const result = subtitleEngine.applyStylePreset(
@@ -2594,15 +2577,10 @@ export const useProjectStore = create<ProjectState>()(
return true;
},
- /**
- * Get available subtitle style presets
- * Subtitle style presets
- */
- getSubtitleStylePresets: () => {
- const subtitleEngine = useEngineStore.getState().getSubtitleEngine();
- if (!subtitleEngine) {
- return [];
- }
+ getSubtitleStylePresets: async () => {
+ const subtitleEngine = await useEngineStore
+ .getState()
+ .getSubtitleEngine();
return subtitleEngine.getStylePresets();
},
diff --git a/apps/web/src/stores/utils/engine-helpers.ts b/apps/web/src/stores/utils/engine-helpers.ts
index afa6a279..2b17b60a 100644
--- a/apps/web/src/stores/utils/engine-helpers.ts
+++ b/apps/web/src/stores/utils/engine-helpers.ts
@@ -3,7 +3,11 @@ import { useEngineStore } from "../engine-store";
type EngineStoreState = ReturnType<typeof useEngineStore.getState>;
type EngineType<K extends keyof EngineStoreState> =
- EngineStoreState[K] extends () => infer T ? NonNullable<T> : never;
+ EngineStoreState[K] extends () => infer T
+ ? T extends Promise<infer U>
+ ? NonNullable<U>
+ : NonNullable<T>
+ : never;
export function withEngine<T, R>(
getEngine: () => T | null,
@@ -20,6 +24,15 @@ export function withEngine<T, R>(
return operation(engine);
}
+export async function withAsyncEngine<T, R>(
+ getEngine: () => Promise<T>,
+ _engineName: string,
+ operation: (engine: T) => R | Promise<R>,
+): Promise<R> {
+ const engine = await getEngine();
+ return operation(engine);
+}
+
export function withTitleEngine<R>(
operation: (engine: EngineType<"getTitleEngine">) => R,
): R | null {
@@ -40,10 +53,10 @@ export function withGraphicsEngine<R>(
);
}
-export function withSubtitleEngine<R>(
- operation: (engine: EngineType<"getSubtitleEngine">) => R,
-): R | null {
- return withEngine(
+export async function withSubtitleEngine<R>(
+ operation: (engine: EngineType<"getSubtitleEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getSubtitleEngine,
"SubtitleEngine",
operation,
@@ -90,80 +103,80 @@ export function withExportEngine<R>(
);
}
-export function withMaskEngine<R>(
- operation: (engine: EngineType<"getMaskEngine">) => R,
-): R | null {
- return withEngine(
+export async function withMaskEngine<R>(
+ operation: (engine: EngineType<"getMaskEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getMaskEngine,
"MaskEngine",
operation,
);
}
-export function withChromaKeyEngine<R>(
- operation: (engine: EngineType<"getChromaKeyEngine">) => R,
-): R | null {
- return withEngine(
+export async function withChromaKeyEngine<R>(
+ operation: (engine: EngineType<"getChromaKeyEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getChromaKeyEngine,
"ChromaKeyEngine",
operation,
);
}
-export function withMultiCamEngine<R>(
- operation: (engine: EngineType<"getMultiCamEngine">) => R,
-): R | null {
- return withEngine(
+export async function withMultiCamEngine<R>(
+ operation: (engine: EngineType<"getMultiCamEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getMultiCamEngine,
"MultiCamEngine",
operation,
);
}
-export function withTemplateEngine<R>(
- operation: (engine: EngineType<"getTemplateEngine">) => R,
-): R | null {
- return withEngine(
+export async function withTemplateEngine<R>(
+ operation: (engine: EngineType<"getTemplateEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getTemplateEngine,
"TemplateEngine",
operation,
);
}
-export function withSoundLibraryEngine<R>(
- operation: (engine: EngineType<"getSoundLibraryEngine">) => R,
-): R | null {
- return withEngine(
+export async function withSoundLibraryEngine<R>(
+ operation: (engine: EngineType<"getSoundLibraryEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getSoundLibraryEngine,
"SoundLibraryEngine",
operation,
);
}
-export function withSpeechToTextEngine<R>(
- operation: (engine: EngineType<"getSpeechToTextEngine">) => R,
-): R | null {
- return withEngine(
+export async function withSpeechToTextEngine<R>(
+ operation: (engine: EngineType<"getSpeechToTextEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getSpeechToTextEngine,
"SpeechToTextEngine",
operation,
);
}
-export function withNestedSequenceEngine<R>(
- operation: (engine: EngineType<"getNestedSequenceEngine">) => R,
-): R | null {
- return withEngine(
+export async function withNestedSequenceEngine<R>(
+ operation: (engine: EngineType<"getNestedSequenceEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getNestedSequenceEngine,
"NestedSequenceEngine",
operation,
);
}
-export function withAdjustmentLayerEngine<R>(
- operation: (engine: EngineType<"getAdjustmentLayerEngine">) => R,
-): R | null {
- return withEngine(
+export async function withAdjustmentLayerEngine<R>(
+ operation: (engine: EngineType<"getAdjustmentLayerEngine">) => R | Promise<R>,
+): Promise<R> {
+ return withAsyncEngine(
useEngineStore.getState().getAdjustmentLayerEngine,
"AdjustmentLayerEngine",
operation,
diff --git a/apps/web/src/test/export-integration.test.ts b/apps/web/src/test/export-integration.test.ts
index 979dff6c..eaad99a1 100644
--- a/apps/web/src/test/export-integration.test.ts
+++ b/apps/web/src/test/export-integration.test.ts
@@ -353,7 +353,7 @@ describe("Export Readiness - Subtitle Handling", () => {
expect(updated?.startTime).toBe(0);
});
- it("should export valid SRT format", () => {
+ it("should export valid SRT format", async () => {
const store = useProjectStore.getState();
store.addSubtitle({
@@ -384,7 +384,7 @@ describe("Export Readiness - Subtitle Handling", () => {
},
});
- const srt = store.exportSRT();
+ const srt = await store.exportSRT();
expect(srt).toContain("1");
expect(srt).toContain("First subtitle");
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 13e9cd8a..b735e1cf 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -22,9 +22,19 @@ export default defineConfig({
target: "esnext",
rollupOptions: {
output: {
- manualChunks: {
- react: ["react", "react-dom"],
- zustand: ["zustand"],
+ manualChunks: (id) => {
+ if (id.includes("node_modules/react") || id.includes("node_modules/react-dom")) {
+ return "react";
+ }
+ if (id.includes("node_modules/zustand")) {
+ return "zustand";
+ }
+ if (id.includes("node_modules/three")) {
+ return "three";
+ }
+ if (id.includes("node_modules/@radix-ui")) {
+ return "radix";
+ }
},
},
},