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

Add inspector SRT import + custom font upload for caption workflows (#59)

Copilotacc3734faaff
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsx
index 44cea494..01ab38d5 100644
--- a/apps/web/src/components/editor/InspectorPanel.tsx
+++ b/apps/web/src/components/editor/InspectorPanel.tsx
@@ -1,5 +1,5 @@
-import React, { useCallback, useEffect, useMemo, useState } from "react";
-import { ChevronDown, Zap, Captions, Loader2, Sparkles, Trash2 } from "lucide-react";
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { ChevronDown, Zap, Captions, Loader2, Sparkles, Trash2, Upload } from "lucide-react";
import { useProjectStore } from "../../stores/project-store";
import { useTimelineStore } from "../../stores/timeline-store";
import { useUIStore } from "../../stores/ui-store";
@@ -64,6 +64,12 @@ import {
DEFAULT_NOISE_REDUCTION,
} from "../../bridges/audio-bridge-effects";
import { toast } from "../../stores/notification-store";
+import {
+ FONT_CATEGORIES,
+ FONT_FILE_ACCEPT,
+ registerCustomFont,
+ useCustomFonts,
+} from "./inspector/font-options";
import { getNoiseReductionPreset } from "./inspector/noise-reduction-presets";
import {
Input,
@@ -195,6 +201,7 @@ export const InspectorPanel: React.FC = () => {
getClip,
getMediaItem,
addSubtitle,
+ importSRT,
updateSubtitle,
getSubtitle,
getEditingTemplate,
@@ -232,6 +239,9 @@ export const InspectorPanel: React.FC = () => {
const [recipeControlValues, setRecipeControlValues] = useState<
Record<string, Record<string, EditingTemplatePrimitive>>
>({});
+ const srtInputRef = useRef<HTMLInputElement>(null);
+ const subtitleFontInputRef = useRef<HTMLInputElement>(null);
+ const customFonts = useCustomFonts();
useEffect(() => {
setExpandedRecipeApplicationId(null);
@@ -655,6 +665,59 @@ export const InspectorPanel: React.FC = () => {
targetLanguage,
]);
+ const handleSRTImport = useCallback(
+ async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+
+ try {
+ const srtContent = await file.text();
+ const result = await importSRT(srtContent);
+
+ if (result.success) {
+ if (result.errors.length > 0) {
+ toast.warning(
+ "SRT imported with warnings",
+ `${result.errors.length} subtitle segment(s) were skipped.`,
+ );
+ } else {
+ toast.success("SRT imported", "Subtitles were added to the Captions track.");
+ }
+ } else {
+ toast.error("SRT import failed", result.errors[0] || "No valid subtitles found.");
+ }
+ } catch {
+ toast.error("SRT import failed", "Could not read the selected subtitle file.");
+ } finally {
+ event.target.value = "";
+ }
+ },
+ [importSRT],
+ );
+
+ const handleSubtitleFontUpload = useCallback(
+ async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ if (!file || !selectedSubtitle) return;
+
+ const result = await registerCustomFont(file);
+ if (!result.success) {
+ toast.error("Font upload failed", result.error ?? "Unknown error.");
+ } else {
+ updateSubtitle(selectedSubtitle.id, {
+ style: {
+ ...(selectedSubtitle.style || {}),
+ fontFamily: result.fontFamily,
+ } as typeof selectedSubtitle.style,
+ });
+ toast.success("Custom font uploaded", `${result.fontFamily} is ready to use.`);
+ }
+
+ event.target.value = "";
+ },
+ [selectedSubtitle, updateSubtitle],
+ );
+
// Default transform
const defaultTransform: Transform = {
position: { x: 0, y: 0 },
@@ -1018,6 +1081,13 @@ export const InspectorPanel: React.FC = () => {
{clipType === "video" && (
<Section title="AI Auto-Captions" sectionId="auto-captions" defaultOpen={false}>
<div className="space-y-3">
+ <input
+ ref={srtInputRef}
+ type="file"
+ accept=".srt,text/srt,text/plain"
+ onChange={handleSRTImport}
+ className="hidden"
+ />
<div>
<label className="text-[10px] text-text-secondary block mb-1">
Animation Style
@@ -1111,6 +1181,14 @@ export const InspectorPanel: React.FC = () => {
Generate Captions
</button>
)}
+ <button
+ onClick={() => srtInputRef.current?.click()}
+ disabled={isTranscribing}
+ className="w-full py-2 bg-background-tertiary hover:bg-background-tertiary/80 border border-border text-text-primary rounded-lg text-[11px] font-medium transition-all flex items-center justify-center gap-2 disabled:opacity-50"
+ >
+ <Upload size={13} />
+ Import SRT File
+ </button>
</div>
</Section>
)}
@@ -1914,6 +1992,13 @@ export const InspectorPanel: React.FC = () => {
{/* Subtitle Font Settings */}
<Section title="Font">
<div className="space-y-3">
+ <input
+ ref={subtitleFontInputRef}
+ type="file"
+ accept={FONT_FILE_ACCEPT}
+ onChange={handleSubtitleFontUpload}
+ className="hidden"
+ />
<div className="flex items-center justify-between">
<span className="text-[10px] text-text-secondary">
Font Family
@@ -1933,41 +2018,40 @@ export const InspectorPanel: React.FC = () => {
<SelectValue />
</SelectTrigger>
<SelectContent className="bg-background-secondary border-border max-h-60">
- <SelectGroup>
- <SelectLabel className="text-text-muted text-[10px] font-medium">Popular</SelectLabel>
- {["Inter", "Poppins", "Montserrat", "Roboto", "Open Sans", "Lato", "DM Sans"].map((font) => (
- <SelectItem key={font} value={font} style={{ fontFamily: font }}>
- {font}
- </SelectItem>
- ))}
- </SelectGroup>
- <SelectGroup>
- <SelectLabel className="text-text-muted text-[10px] font-medium">Display</SelectLabel>
- {["Bebas Neue", "Anton", "Oswald", "Teko", "Staatliches", "Alfa Slab One"].map((font) => (
- <SelectItem key={font} value={font} style={{ fontFamily: font }}>
- {font}
- </SelectItem>
- ))}
- </SelectGroup>
- <SelectGroup>
- <SelectLabel className="text-text-muted text-[10px] font-medium">Elegant</SelectLabel>
- {["Playfair Display", "Cinzel", "Lora", "Merriweather", "DM Serif Display"].map((font) => (
- <SelectItem key={font} value={font} style={{ fontFamily: font }}>
- {font}
- </SelectItem>
- ))}
- </SelectGroup>
- <SelectGroup>
- <SelectLabel className="text-text-muted text-[10px] font-medium">Handwritten</SelectLabel>
- {["Pacifico", "Lobster", "Dancing Script", "Caveat", "Permanent Marker"].map((font) => (
- <SelectItem key={font} value={font} style={{ fontFamily: font }}>
- {font}
- </SelectItem>
- ))}
- </SelectGroup>
+ {Object.entries(FONT_CATEGORIES).map(([category, fonts]) => (
+ <SelectGroup key={category}>
+ <SelectLabel className="text-text-muted text-[10px] font-medium">
+ {category}
+ </SelectLabel>
+ {fonts.map((font) => (
+ <SelectItem key={font} value={font} style={{ fontFamily: font }}>
+ {font}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ ))}
+ {customFonts.length > 0 && (
+ <SelectGroup>
+ <SelectLabel className="text-text-muted text-[10px] font-medium">
+ Custom Uploads
+ </SelectLabel>
+ {customFonts.map((font) => (
+ <SelectItem key={font} value={font} style={{ fontFamily: font }}>
+ {font}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ )}
</SelectContent>
</Select>
</div>
+ <button
+ onClick={() => subtitleFontInputRef.current?.click()}
+ className="w-full py-1.5 px-2 bg-background-secondary border border-border rounded text-[10px] text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center gap-1.5"
+ >
+ <Upload size={11} />
+ Upload Custom Font
+ </button>
<div className="flex items-center justify-between">
<span className="text-[10px] text-text-secondary">
Font Size
diff --git a/apps/web/src/components/editor/inspector/TextSection.tsx b/apps/web/src/components/editor/inspector/TextSection.tsx
index e54c8358..17a6b7e0 100644
--- a/apps/web/src/components/editor/inspector/TextSection.tsx
+++ b/apps/web/src/components/editor/inspector/TextSection.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useMemo } from "react";
+import React, { useCallback, useMemo, useRef } from "react";
import {
AlignLeft,
AlignCenter,
@@ -10,6 +10,7 @@ import {
Italic,
Underline,
Type,
+ Upload,
} from "lucide-react";
import { useProjectStore } from "../../../stores/project-store";
import type { TextStyle, FontWeight } from "@openreel/core";
@@ -23,6 +24,13 @@ import {
SelectGroup,
SelectLabel,
} from "@openreel/ui";
+import {
+ FONT_CATEGORIES,
+ FONT_FILE_ACCEPT,
+ registerCustomFont,
+ useCustomFonts,
+} from "./font-options";
+import { toast } from "../../../stores/notification-store";
const ColorField: React.FC<{
label: string;
@@ -92,74 +100,11 @@ const ToggleButtonGroup: React.FC<{
</div>
);
-const FONT_CATEGORIES = {
- Popular: [
- "Inter",
- "Poppins",
- "Montserrat",
- "Roboto",
- "Open Sans",
- "Lato",
- "Outfit",
- "DM Sans",
- ],
- "Display & Headlines": [
- "Bebas Neue",
- "Anton",
- "Oswald",
- "Teko",
- "Staatliches",
- "Alfa Slab One",
- "Archivo Black",
- "Black Ops One",
- "Titan One",
- "Righteous",
- "Concert One",
- "Fredoka One",
- "Bungee",
- ],
- "Elegant & Serif": [
- "Playfair Display",
- "Cinzel",
- "Lora",
- "Merriweather",
- "DM Serif Display",
- "Abril Fatface",
- "Roboto Slab",
- "Zilla Slab",
- ],
- "Modern & Clean": [
- "Lexend",
- "Quicksand",
- "Nunito",
- "Rubik",
- "Work Sans",
- "Raleway",
- "Ubuntu",
- "Space Grotesk",
- "Comfortaa",
- ],
- "Handwritten & Script": [
- "Pacifico",
- "Lobster",
- "Dancing Script",
- "Great Vibes",
- "Caveat",
- "Sacramento",
- "Satisfy",
- "Yellowtail",
- "Rock Salt",
- "Permanent Marker",
- ],
- "Fun & Creative": ["Bangers", "Creepster", "Press Start 2P"],
- Monospace: ["Roboto Mono", "Space Mono"],
- System: ["Arial", "Helvetica", "Times New Roman", "Georgia", "Verdana"],
-};
-
const FontSelector: React.FC<{
value: string;
onChange: (font: string) => void;
}> = ({ value, onChange }) => {
+ const customFonts = useCustomFonts();
return (
<div className="flex items-center justify-between">
<span className="text-[10px] text-text-secondary">Font</span>
@@ -180,6 +125,18 @@ const FontSelector: React.FC<{
))}
</SelectGroup>
))}
+ {customFonts.length > 0 && (
+ <SelectGroup>
+ <SelectLabel className="text-text-muted text-[10px] font-medium">
+ Custom Uploads
+ </SelectLabel>
+ {customFonts.map((font) => (
+ <SelectItem key={font} value={font} style={{ fontFamily: font }}>
+ {font}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ )}
</SelectContent>
</Select>
</div>
@@ -203,6 +160,7 @@ export const TextSection: React.FC<TextSectionProps> = ({ clipId }) => {
updateTextTransform,
project,
} = useProjectStore();
+ const fontInputRef = useRef<HTMLInputElement>(null);
const textClip = useMemo(
() => getTextClip(clipId),
@@ -268,6 +226,24 @@ export const TextSection: React.FC<TextSectionProps> = ({ clipId }) => {
updateTextTransform(clipId, { position: { x: 0.5, y: 0.5 } });
}, [clipId, updateTextTransform]);
+ const handleCustomFontSelect = useCallback(
+ async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+
+ const result = await registerCustomFont(file);
+ if (!result.success) {
+ toast.error("Font upload failed", result.error ?? "Unknown error.");
+ } else {
+ await handleStyleChange({ fontFamily: result.fontFamily });
+ toast.success("Custom font uploaded", `${result.fontFamily} is ready to use.`);
+ }
+
+ event.target.value = "";
+ },
+ [handleStyleChange],
+ );
+
if (!textClip) {
return (
<div className="p-4 text-center">
@@ -291,10 +267,24 @@ export const TextSection: React.FC<TextSectionProps> = ({ clipId }) => {
</div>
<div className="space-y-2 p-3 bg-background-tertiary rounded-lg">
+ <input
+ ref={fontInputRef}
+ type="file"
+ accept={FONT_FILE_ACCEPT}
+ onChange={handleCustomFontSelect}
+ className="hidden"
+ />
<FontSelector
value={style.fontFamily}
onChange={(fontFamily) => handleStyleChange({ fontFamily })}
/>
+ <button
+ onClick={() => fontInputRef.current?.click()}
+ className="w-full py-1.5 px-2 bg-background-secondary border border-border rounded text-[10px] text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center gap-1.5"
+ >
+ <Upload size={11} />
+ Upload Custom Font
+ </button>
<NumberInput
label="Size"
value={style.fontSize}
diff --git a/apps/web/src/components/editor/inspector/font-options.ts b/apps/web/src/components/editor/inspector/font-options.ts
new file mode 100644
index 00000000..1629470c
--- /dev/null
+++ b/apps/web/src/components/editor/inspector/font-options.ts
@@ -0,0 +1,242 @@
+import { useEffect, useState } from "react";
+
+const CUSTOM_FONT_EVENT = "openreel:custom-fonts-updated";
+
+const DB_NAME = "openreel-custom-fonts";
+const DB_VERSION = 1;
+const STORE_FONTS = "fonts";
+
+interface StoredFontRecord {
+ family: string;
+ data: ArrayBuffer;
+ uploadedAt: number;
+}
+
+const customFonts: string[] = [];
+
+export const FONT_CATEGORIES = {
+ Popular: [
+ "Inter",
+ "Poppins",
+ "Montserrat",
+ "Roboto",
+ "Open Sans",
+ "Lato",
+ "Outfit",
+ "DM Sans",
+ ],
+ "Display & Headlines": [
+ "Bebas Neue",
+ "Anton",
+ "Oswald",
+ "Teko",
+ "Staatliches",
+ "Alfa Slab One",
+ "Archivo Black",
+ "Black Ops One",
+ "Titan One",
+ "Righteous",
+ "Concert One",
+ "Fredoka One",
+ "Bungee",
+ ],
+ "Elegant & Serif": [
+ "Playfair Display",
+ "Cinzel",
+ "Lora",
+ "Merriweather",
+ "DM Serif Display",
+ "Abril Fatface",
+ "Roboto Slab",
+ "Zilla Slab",
+ ],
+ "Modern & Clean": [
+ "Lexend",
+ "Quicksand",
+ "Nunito",
+ "Rubik",
+ "Work Sans",
+ "Raleway",
+ "Ubuntu",
+ "Space Grotesk",
+ "Comfortaa",
+ ],
+ "Handwritten & Script": [
+ "Pacifico",
+ "Lobster",
+ "Dancing Script",
+ "Great Vibes",
+ "Caveat",
+ "Sacramento",
+ "Satisfy",
+ "Yellowtail",
+ "Rock Salt",
+ "Permanent Marker",
+ ],
+ "Fun & Creative": ["Bangers", "Creepster", "Press Start 2P"],
+ Monospace: ["Roboto Mono", "Space Mono"],
+ System: ["Arial", "Helvetica", "Times New Roman", "Georgia", "Verdana"],
+} as const;
+
+const FONT_EXTENSIONS = /\.(ttf|otf|woff2?)$/i;
+export const FONT_FILE_ACCEPT = ".ttf,.otf,.woff,.woff2";
+
+function notifyCustomFontChange() {
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(new CustomEvent(CUSTOM_FONT_EVENT));
+ }
+}
+
+function toUniqueFontFamily(baseFamily: string) {
+ const family = baseFamily.trim() || "Custom Font";
+ let candidate = family;
+ let suffix = 2;
+
+ while (customFonts.includes(candidate)) {
+ candidate = `${family} ${suffix}`;
+ suffix += 1;
+ }
+
+ return candidate;
+}
+
+function openFontsDB(): Promise<IDBDatabase | null> {
+ return new Promise((resolve) => {
+ if (typeof indexedDB === "undefined") {
+ resolve(null);
+ return;
+ }
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
+ request.onerror = () => resolve(null);
+ request.onsuccess = () => resolve(request.result);
+ request.onupgradeneeded = (event) => {
+ const db = (event.target as IDBOpenDBRequest).result;
+ if (!db.objectStoreNames.contains(STORE_FONTS)) {
+ db.createObjectStore(STORE_FONTS, { keyPath: "family" });
+ }
+ };
+ });
+}
+
+async function persistFont(family: string, data: ArrayBuffer): Promise<void> {
+ const db = await openFontsDB();
+ if (!db) return;
+ await new Promise<void>((resolve) => {
+ const tx = db.transaction(STORE_FONTS, "readwrite");
+ const store = tx.objectStore(STORE_FONTS);
+ const record: StoredFontRecord = { family, data, uploadedAt: Date.now() };
+ store.put(record);
+ tx.oncomplete = () => resolve();
+ tx.onerror = () => resolve();
+ tx.onabort = () => resolve();
+ });
+ db.close();
+}
+
+async function loadStoredFonts(): Promise<StoredFontRecord[]> {
+ const db = await openFontsDB();
+ if (!db) return [];
+ const records = await new Promise<StoredFontRecord[]>((resolve) => {
+ const tx = db.transaction(STORE_FONTS, "readonly");
+ const store = tx.objectStore(STORE_FONTS);
+ const request = store.getAll();
+ request.onsuccess = () => resolve((request.result as StoredFontRecord[]) ?? []);
+ request.onerror = () => resolve([]);
+ });
+ db.close();
+ return records;
+}
+
+export async function removeCustomFont(family: string): Promise<void> {
+ const idx = customFonts.indexOf(family);
+ if (idx >= 0) {
+ customFonts.splice(idx, 1);
+ notifyCustomFontChange();
+ }
+ const db = await openFontsDB();
+ if (!db) return;
+ await new Promise<void>((resolve) => {
+ const tx = db.transaction(STORE_FONTS, "readwrite");
+ tx.objectStore(STORE_FONTS).delete(family);
+ tx.oncomplete = () => resolve();
+ tx.onerror = () => resolve();
+ tx.onabort = () => resolve();
+ });
+ db.close();
+}
+
+let initPromise: Promise<void> | null = null;
+
+export function initCustomFonts(): Promise<void> {
+ if (initPromise) return initPromise;
+ initPromise = (async () => {
+ if (typeof FontFace === "undefined" || typeof document === "undefined") return;
+ const stored = await loadStoredFonts();
+ let changed = false;
+ for (const { family, data } of stored) {
+ if (customFonts.includes(family)) continue;
+ try {
+ const face = new FontFace(family, data);
+ await face.load();
+ document.fonts.add(face);
+ customFonts.push(family);
+ changed = true;
+ } catch {
+ // skip corrupt entries
+ }
+ }
+ if (changed) notifyCustomFontChange();
+ })();
+ return initPromise;
+}
+
+export function getCustomFonts() {
+ return [...customFonts];
+}
+
+export function useCustomFonts() {
+ const [fonts, setFonts] = useState<string[]>(() => getCustomFonts());
+
+ useEffect(() => {
+ const sync = () => setFonts(getCustomFonts());
+ window.addEventListener(CUSTOM_FONT_EVENT, sync);
+ void initCustomFonts().then(sync);
+ return () => window.removeEventListener(CUSTOM_FONT_EVENT, sync);
+ }, []);
+
+ return fonts;
+}
+
+export async function registerCustomFont(
+ file: File,
+): Promise<{ success: true; fontFamily: string } | { success: false; error: string }> {
+ if (!FONT_EXTENSIONS.test(file.name)) {
+ return { success: false, error: "Please upload a .ttf, .otf, .woff, or .woff2 font file." };
+ }
+
+ if (typeof FontFace === "undefined" || typeof document === "undefined") {
+ return { success: false, error: "Custom font upload is not supported in this environment." };
+ }
+
+ try {
+ const baseName = file.name.replace(/\.[^/.]+$/, "");
+ const fontFamily = toUniqueFontFamily(baseName);
+ const fontSource = await file.arrayBuffer();
+ const fontFace = new FontFace(fontFamily, fontSource);
+ await fontFace.load();
+ document.fonts.add(fontFace);
+
+ if (!customFonts.includes(fontFamily)) {
+ customFonts.push(fontFamily);
+ notifyCustomFontChange();
+ }
+
+ await persistFont(fontFamily, fontSource).catch(() => {
+ // best-effort persistence; font is still usable this session
+ });
+
+ return { success: true, fontFamily };
+ } catch {
+ return { success: false, error: "Could not load this font file." };
+ }
+}
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index cfa07159..02681f65 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -5,6 +5,7 @@ import { PostHogProvider } from "posthog-js/react";
import App from "./App";
import "./index.css";
import { registerServiceWorker } from "./services/service-worker";
+import { initCustomFonts } from "./components/editor/inspector/font-options";
const POSTHOG_KEY = import.meta.env.VITE_PUBLIC_POSTHOG_KEY;
const POSTHOG_HOST = import.meta.env.VITE_PUBLIC_POSTHOG_HOST;
@@ -22,6 +23,8 @@ registerServiceWorker().then((registration) => {
}
});
+void initCustomFonts();
+
const root = document.getElementById("root")!;
ReactDOM.createRoot(root).render(
diff --git a/apps/web/src/stores/project-store.test.ts b/apps/web/src/stores/project-store.test.ts
index e9878961..068543b3 100644
--- a/apps/web/src/stores/project-store.test.ts
+++ b/apps/web/src/stores/project-store.test.ts
@@ -1485,4 +1485,64 @@ describe("ProjectStore - Subtitles (consolidated into text clips)", () => {
const presets = await useProjectStore.getState().getSubtitleStylePresets();
expect(Array.isArray(presets)).toBe(true);
});
+
+ it("imports SRT subtitles into a Captions text track", async () => {
+ const srt = `1
+00:00:00,000 --> 00:00:02,000
+Hello world
+
+2
+00:00:02,500 --> 00:00:04,000
+Second caption`;
+
+ const result = await useProjectStore.getState().importSRT(srt);
+
+ expect(result.success).toBe(true);
+ expect(result.errors).toEqual([]);
+
+ const state = useProjectStore.getState();
+ const captionsTrack = state.project.timeline.tracks.find(
+ (track) => track.type === "text" && track.name === "Captions",
+ );
+ expect(captionsTrack).toBeDefined();
+
+ const captionClips = state
+ .getAllTextClips()
+ .filter((clip) => clip.trackId === captionsTrack?.id)
+ .sort((a, b) => a.startTime - b.startTime);
+
+ expect(captionClips).toHaveLength(2);
+ expect(captionClips[0]?.text).toBe("Hello world");
+ expect(captionClips[0]?.startTime).toBe(0);
+ expect(captionClips[0]?.duration).toBe(2);
+ expect(captionClips[1]?.text).toBe("Second caption");
+ expect(captionClips[1]?.startTime).toBe(2.5);
+ expect(captionClips[1]?.duration).toBe(1.5);
+ });
+
+ it("returns warnings when an SRT has invalid segments but still imports valid captions", async () => {
+ const srt = `1
+00:00:00,000 --> 00:00:02,000
+Hello world
+
+bad-index
+00:00:03,000 --> 00:00:04,000
+Ignored block`;
+
+ const result = await useProjectStore.getState().importSRT(srt);
+
+ expect(result.success).toBe(true);
+ expect(result.errors.length).toBeGreaterThan(0);
+
+ const state = useProjectStore.getState();
+ const captionsTrack = state.project.timeline.tracks.find(
+ (track) => track.type === "text" && track.name === "Captions",
+ );
+ const captionClips = state
+ .getAllTextClips()
+ .filter((clip) => clip.trackId === captionsTrack?.id);
+
+ expect(captionClips).toHaveLength(1);
+ expect(captionClips[0]?.text).toBe("Hello world");
+ });
});
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index 40879266..154c0fc6 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -4499,29 +4499,31 @@ export const useProjectStore = create<ProjectState>()(
const subtitleEngine = await useEngineStore
.getState()
.getSubtitleEngine();
-
- const { project } = get();
- const { timeline, result } = subtitleEngine.importSRT(
- project.timeline,
- srtContent,
+ const { project, addSubtitle } = get();
+ const { result } = subtitleEngine.importSRT(project.timeline, srtContent);
+ const errorMessages = result.errors.map(
+ (err: { line: number; message: string }) =>
+ `Line ${err.line}: ${err.message}`,
);
- if (result.success) {
- set({
- project: {
- ...project,
- timeline,
- modifiedAt: Date.now(),
- },
- });
- return { success: true, errors: [] };
- } else {
- const errorMessages = result.errors.map(
- (err: { line: number; message: string }) =>
- `Line ${err.line}: ${err.message}`,
- );
- return { success: false, errors: errorMessages };
+ if (result.subtitles.length === 0) {
+ return {
+ success: false,
+ errors:
+ errorMessages.length > 0
+ ? errorMessages
+ : ["No valid subtitles were found in this SRT file."],
+ };
+ }
+
+ for (const subtitle of result.subtitles) {
+ await addSubtitle(subtitle);
}
+
+ return {
+ success: true,
+ errors: errorMessages,
+ };
},
exportSRT: async () => {