diff --git a/e2e/srt-import.spec.js b/e2e/srt-import.spec.js
new file mode 100644
index 0000000..6d8e1d8
--- /dev/null
+++ b/e2e/srt-import.spec.js
@@ -0,0 +1,37 @@
+import { expect, test } from "@playwright/test";
+
+const firstSrt = `1
+00:00:01,250 --> 00:00:03,500
+Imported first line
+
+2
+00:00:05,000 --> 00:00:06,750
+Imported second line`;
+
+test("imports SRT captions with exact timing and supports replace and append", async ({ page }) => {
+ await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "en"));
+ await page.goto("/");
+ await page.getByRole("button", { name: "Captions", exact: true }).click();
+
+ const input = page.getByTestId("srt-file-input");
+ await input.setInputFiles({ name: "captions.srt", mimeType: "application/x-subrip", buffer: Buffer.from(firstSrt) });
+ await expect(page.locator(".caption-segment")).toHaveCount(2);
+ await expect(page.locator(".caption-context-list")).toContainText("Imported first line");
+ await expect(page.locator(".caption-context-list")).toContainText("Imported second line");
+ const styles = await page.locator(".caption-segment").evaluateAll((clips) => clips.map((clip) => ({ left: clip.style.getPropertyValue("--caption-left"), width: clip.style.getPropertyValue("--caption-width") })));
+ expect(parseFloat(styles[0].left)).toBeGreaterThan(0);
+ expect(parseFloat(styles[1].left)).toBeGreaterThan(parseFloat(styles[0].left));
+ expect(parseFloat(styles[0].width)).toBeGreaterThan(parseFloat(styles[1].width));
+
+ await input.setInputFiles({ name: "more.srt", mimeType: "application/x-subrip", buffer: Buffer.from("1\n00:00:08,000 --> 00:00:09,000\nAppended line") });
+ await page.getByRole("dialog", { name: "How should these captions be imported?" }).getByRole("button", { name: "Append to track", exact: true }).click();
+ await expect(page.locator(".caption-segment")).toHaveCount(3);
+ await expect(page.locator(".caption-context-list")).toContainText("Appended line");
+ await expect(page.locator(".toast")).toContainText("Imported 1 captions; skipped 0");
+
+ await input.setInputFiles({ name: "replacement.srt", mimeType: "application/x-subrip", buffer: Buffer.from("1\n00:00:02,000 --> 00:00:04,000\nReplacement line") });
+ await page.getByRole("dialog", { name: "How should these captions be imported?" }).getByRole("button", { name: "Replace captions", exact: true }).click();
+ await expect(page.locator(".caption-segment")).toHaveCount(1);
+ await expect(page.locator(".caption-context-list")).toContainText("Replacement line");
+ await expect(page.locator(".caption-context-list")).not.toContainText("Imported first line");
+});
diff --git a/src/App.jsx b/src/App.jsx
index 2d35e6a..150939d 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -43,6 +43,7 @@ import { createTimelineReorderControls } from "./lib/timelineReorderControls.js"
import { createTimelineMoveControls } from "./lib/timelineMoveControls.js";
import { createImageResizeControl } from "./lib/imageResizeControl.js";
import { createTimelineClipboardActions } from "./lib/timelineClipboardActions.js";
+import { appendImportedCaptions } from "./lib/subtitles.js";
import { createTimelineCutActions } from "./lib/timelineCutActions.js";
import { createTimelineSegmentCountActions } from "./lib/timelineSegmentCountActions.js";
import { createTimelineDurationActions } from "./lib/timelineDurationActions.js";
@@ -366,6 +367,19 @@ export function App() {
setScript, setSelectedSegmentId, setSelectedTrack,
setVisionRecords, trackLocks,
});
+ const importCaptionSegments = (importedSegments, mode, skipped = 0) => {
+ const nextSegments = mode === "append"
+ ? appendImportedCaptions(captionSegments, importedSegments)
+ : importedSegments;
+ const selectedIndex = nextSegments.findIndex((segment) => segment.id === importedSegments[0]?.id);
+ commitCaptionSegments(
+ nextSegments,
+ t("srtImportComplete").replace("{count}", importedSegments.length).replace("{skipped}", skipped),
+ Math.max(0, selectedIndex),
+ );
+ setCaptionsEnabled(true);
+ setTrackVisibility((current) => ({ ...current, caption: true }));
+ };
const autoEdit = useAutoEdit({
language: activeLanguage, visualSegments, captionSegments, commitCaptionSegments, setCaptionsEnabled,
setTrackVisibility, setSelectedSegmentId, setSelectedTrack, notify, t,
@@ -935,6 +949,7 @@ export function App() {
updateCaptionSegmentText={updateCaptionSegmentText}
toggleCaptionSegmentHidden={toggleCaptionSegmentHidden}
deleteCaptionSegment={deleteCaptionSegment}
+ importCaptionSegments={importCaptionSegments}
seekTo={seekTo}
sourceAudioBlob={sourceAudioBlob}
sourceAudioLinked={sourceAudioLinked}
diff --git a/src/components/VoicePanel.jsx b/src/components/VoicePanel.jsx
index e97b599..efec5fb 100644
--- a/src/components/VoicePanel.jsx
+++ b/src/components/VoicePanel.jsx
@@ -9,6 +9,7 @@ import {
Scissors,
Sparkle,
Trash,
+ UploadSimple,
Waveform,
X,
} from "@phosphor-icons/react";
@@ -20,6 +21,7 @@ import { LIVE_PORTRAIT_WEB_MODEL } from "../config/livePortrait.js";
import { probeLivePortraitWebEnvironment } from "../lib/livePortraitWeb.js";
import { getCaptionVoiceSegment } from "../lib/captionVoice.js";
import { normalizeVisualKeyframes } from "../lib/visualEffects.js";
+import { MAX_SRT_FILE_BYTES, parseSrt } from "../lib/subtitles.js";
import { HistoryPanel, MyVoicesPanel, SmartVisionPanel, VisualEffectsPanel, VoiceSynthesisPanel } from "./panels.jsx";
function AutoEditReviewDialog({ t, autoEdit }) {
@@ -113,7 +115,10 @@ function CaptionContextPanel({
generateCaptionsFromSourceAudio,
isGeneratingCaptions,
automaticCaptionProgress,
+ importCaptionSegments,
}) {
+ const srtInputRef = useRef(null);
+ const [pendingSrt, setPendingSrt] = useState(null);
const selectedIndex = Math.max(
0,
captionSegments.findIndex((segment) => segment.id === selectedCaptionSegment?.id),
@@ -122,6 +127,25 @@ function CaptionContextPanel({
? getSegmentStartTime(captionSegments, selectedIndex, captionTargetDuration)
: 0;
+ async function handleSrtFile(file) {
+ if (!file) return;
+ try {
+ if (file.size > MAX_SRT_FILE_BYTES) throw new Error(t("srtFileTooLarge"));
+ const result = parseSrt(await file.text());
+ if (!result.captions.length) throw new Error(t("srtNoValidCaptions"));
+ if (captionSegments.length) setPendingSrt(result);
+ else importCaptionSegments(result.captions, "replace", result.skipped);
+ } catch (error) {
+ window.alert(error instanceof Error ? error.message : t("srtImportFailed"));
+ }
+ }
+
+ function applyPendingSrt(mode) {
+ if (!pendingSrt) return;
+ importCaptionSegments(pendingSrt.captions, mode, pendingSrt.skipped);
+ setPendingSrt(null);
+ }
+
return (
)}
@@ -192,9 +219,35 @@ function CaptionContextPanel({
) : null}
-
- {t("captionList", "字幕列表")}
+ {t("captionList", "字幕列表")}
+
+ {
+ handleSrtFile(event.target.files?.[0]);
+ event.target.value = "";
+ }}
+ />
+ {pendingSrt ? createPortal(
+
+
+ {t("srtConflictTitle")}
+ {t("srtConflictDescription").replace("{count}", pendingSrt.captions.length)}
+
+
+
+
+
+
+
, document.body,
+ ) : null}
{captionSegments.length ? (
captionSegments.map((segment, index) => (
@@ -409,6 +462,7 @@ export function VoicePanel({
updateCaptionSegmentText,
toggleCaptionSegmentHidden,
deleteCaptionSegment,
+ importCaptionSegments,
seekTo,
sourceAudioBlob,
sourceAudioLinked,
@@ -601,6 +655,7 @@ export function VoicePanel({
updateCaptionSegmentText={updateCaptionSegmentText}
toggleCaptionSegmentHidden={toggleCaptionSegmentHidden}
deleteCaptionSegment={deleteCaptionSegment}
+ importCaptionSegments={importCaptionSegments}
seekTo={seekTo}
sourceAudioBlob={sourceAudioBlob}
generateCaptionsFromSourceAudio={generateCaptionsFromSourceAudio}
diff --git a/src/i18n.js b/src/i18n.js
index 1042446..f02c614 100644
--- a/src/i18n.js
+++ b/src/i18n.js
@@ -384,6 +384,20 @@ const PICTURE_IN_PICTURE_COPY = {
vi: { pictureInPicture: "Hình trong hình", overlayTrack: "Lớp phủ", dropAsOverlay: "Thêm làm lớp phủ", appendAfter: "Thêm vào cuối", dropSlot: "Vị trí thả", layoutPresets: "Bố cục mẫu", moveLayerUp: "Đưa lớp lên", moveLayerDown: "Đưa lớp xuống" },
};
+const SRT_IMPORT_COPY = {
+ zh: { importSrt: "导入 SRT", srtConflictTitle: "如何导入这些字幕?", srtConflictDescription: "文件中有 {count} 条有效字幕。当前字幕轨已有内容,你可以替换或追加。", replaceSrt: "替换现有字幕", appendSrt: "追加到字幕轨", srtImportComplete: "已导入 {count} 条字幕,跳过 {skipped} 条", srtImportFailed: "SRT 字幕导入失败", srtFileTooLarge: "SRT 文件不能超过 5 MB", srtNoValidCaptions: "文件中没有可用的 SRT 字幕" },
+ en: { importSrt: "Import SRT", srtConflictTitle: "How should these captions be imported?", srtConflictDescription: "The file contains {count} valid captions. Replace the current caption track or append to it.", replaceSrt: "Replace captions", appendSrt: "Append to track", srtImportComplete: "Imported {count} captions; skipped {skipped}", srtImportFailed: "Could not import the SRT file", srtFileTooLarge: "The SRT file must be 5 MB or smaller", srtNoValidCaptions: "No valid SRT captions were found" },
+ ja: { importSrt: "SRTを読み込む", srtConflictTitle: "字幕をどのように読み込みますか?", srtConflictDescription: "有効な字幕が{count}件あります。現在の字幕を置き換えるか、追加してください。", replaceSrt: "字幕を置き換える", appendSrt: "トラックに追加", srtImportComplete: "字幕を{count}件読み込み、{skipped}件をスキップしました", srtImportFailed: "SRTを読み込めませんでした", srtFileTooLarge: "SRTファイルは5 MB以下にしてください", srtNoValidCaptions: "有効なSRT字幕がありません" },
+ ko: { importSrt: "SRT 가져오기", srtConflictTitle: "자막을 어떻게 가져올까요?", srtConflictDescription: "유효한 자막 {count}개가 있습니다. 현재 자막을 바꾸거나 트랙에 추가하세요.", replaceSrt: "기존 자막 바꾸기", appendSrt: "트랙에 추가", srtImportComplete: "자막 {count}개를 가져오고 {skipped}개를 건너뜀", srtImportFailed: "SRT를 가져올 수 없습니다", srtFileTooLarge: "SRT 파일은 5 MB 이하여야 합니다", srtNoValidCaptions: "유효한 SRT 자막이 없습니다" },
+ es: { importSrt: "Importar SRT", srtConflictTitle: "¿Cómo quieres importar los subtítulos?", srtConflictDescription: "El archivo contiene {count} subtítulos válidos. Reemplaza la pista actual o añádelos.", replaceSrt: "Reemplazar subtítulos", appendSrt: "Añadir a la pista", srtImportComplete: "Se importaron {count} subtítulos; se omitieron {skipped}", srtImportFailed: "No se pudo importar el SRT", srtFileTooLarge: "El archivo SRT debe tener 5 MB o menos", srtNoValidCaptions: "No se encontraron subtítulos SRT válidos" },
+ fr: { importSrt: "Importer un SRT", srtConflictTitle: "Comment importer ces sous-titres ?", srtConflictDescription: "Le fichier contient {count} sous-titres valides. Remplacez la piste actuelle ou ajoutez-les.", replaceSrt: "Remplacer les sous-titres", appendSrt: "Ajouter à la piste", srtImportComplete: "{count} sous-titres importés, {skipped} ignorés", srtImportFailed: "Impossible d’importer le SRT", srtFileTooLarge: "Le fichier SRT doit faire 5 Mo maximum", srtNoValidCaptions: "Aucun sous-titre SRT valide trouvé" },
+ de: { importSrt: "SRT importieren", srtConflictTitle: "Wie sollen die Untertitel importiert werden?", srtConflictDescription: "Die Datei enthält {count} gültige Untertitel. Aktuelle Spur ersetzen oder ergänzen.", replaceSrt: "Untertitel ersetzen", appendSrt: "Zur Spur hinzufügen", srtImportComplete: "{count} Untertitel importiert, {skipped} übersprungen", srtImportFailed: "SRT konnte nicht importiert werden", srtFileTooLarge: "Die SRT-Datei darf höchstens 5 MB groß sein", srtNoValidCaptions: "Keine gültigen SRT-Untertitel gefunden" },
+ pt: { importSrt: "Importar SRT", srtConflictTitle: "Como importar estas legendas?", srtConflictDescription: "O arquivo contém {count} legendas válidas. Substitua a faixa atual ou acrescente-as.", replaceSrt: "Substituir legendas", appendSrt: "Adicionar à faixa", srtImportComplete: "{count} legendas importadas; {skipped} ignoradas", srtImportFailed: "Não foi possível importar o SRT", srtFileTooLarge: "O arquivo SRT deve ter no máximo 5 MB", srtNoValidCaptions: "Nenhuma legenda SRT válida encontrada" },
+ th: { importSrt: "นำเข้า SRT", srtConflictTitle: "ต้องการนำเข้าคำบรรยายอย่างไร?", srtConflictDescription: "ไฟล์มีคำบรรยายที่ใช้ได้ {count} รายการ เลือกแทนที่หรือเพิ่มต่อท้ายแทร็กปัจจุบัน", replaceSrt: "แทนที่คำบรรยาย", appendSrt: "เพิ่มลงในแทร็ก", srtImportComplete: "นำเข้า {count} รายการ ข้าม {skipped} รายการ", srtImportFailed: "นำเข้า SRT ไม่สำเร็จ", srtFileTooLarge: "ไฟล์ SRT ต้องมีขนาดไม่เกิน 5 MB", srtNoValidCaptions: "ไม่พบคำบรรยาย SRT ที่ใช้ได้" },
+ vi: { importSrt: "Nhập SRT", srtConflictTitle: "Bạn muốn nhập phụ đề thế nào?", srtConflictDescription: "Tệp có {count} phụ đề hợp lệ. Hãy thay thế rãnh hiện tại hoặc nối thêm.", replaceSrt: "Thay phụ đề hiện có", appendSrt: "Nối vào rãnh", srtImportComplete: "Đã nhập {count} phụ đề; bỏ qua {skipped}", srtImportFailed: "Không thể nhập SRT", srtFileTooLarge: "Tệp SRT phải không quá 5 MB", srtNoValidCaptions: "Không tìm thấy phụ đề SRT hợp lệ" },
+ ru: { importSrt: "Импорт SRT", srtConflictTitle: "Как импортировать субтитры?", srtConflictDescription: "В файле {count} корректных субтитров. Замените текущую дорожку или добавьте их.", replaceSrt: "Заменить субтитры", appendSrt: "Добавить на дорожку", srtImportComplete: "Импортировано: {count}, пропущено: {skipped}", srtImportFailed: "Не удалось импортировать SRT", srtFileTooLarge: "Размер SRT-файла не должен превышать 5 МБ", srtNoValidCaptions: "Корректные субтитры SRT не найдены" },
+};
+
export const UI_COPY = {
zh: {
...SMART_WORKSPACE_COPY.zh,
@@ -413,6 +427,7 @@ export const UI_COPY = {
...CONTEXT_PANEL_COPY.zh,
...TTS_BACKEND_COPY.zh,
...CAPTION_WORKSPACE_COPY.zh,
+ ...SRT_IMPORT_COPY.zh,
...RESOURCE_LINK_COPY.zh,
languageKicker: "AI Voice Studio",
languageTitle: "选择界面语言",
@@ -809,6 +824,7 @@ export const UI_COPY = {
...CONTEXT_PANEL_COPY.en,
...TTS_BACKEND_COPY.en,
...CAPTION_WORKSPACE_COPY.en,
+ ...SRT_IMPORT_COPY.en,
...RESOURCE_LINK_COPY.en,
languageKicker: "AI Voice Studio",
languageTitle: "Choose Interface Language",
@@ -1198,6 +1214,7 @@ export const UI_COPY = {
...CONTEXT_PANEL_COPY.ja,
...TTS_BACKEND_COPY.ja,
...CAPTION_WORKSPACE_COPY.ja,
+ ...SRT_IMPORT_COPY.ja,
...RESOURCE_LINK_COPY.ja,
...PICTURE_IN_PICTURE_COPY.ja,
languageTitle: "表示言語を選択",
@@ -1285,6 +1302,7 @@ Object.assign(UI_COPY, {
...CONTEXT_PANEL_COPY.ko,
...TTS_BACKEND_COPY.ko,
...CAPTION_WORKSPACE_COPY.ko,
+ ...SRT_IMPORT_COPY.ko,
...RESOURCE_LINK_COPY.ko,
...PICTURE_IN_PICTURE_COPY.ko,
languageTitle: "인터페이스 언어 선택",
@@ -1348,6 +1366,7 @@ Object.assign(UI_COPY, {
...CONTEXT_PANEL_COPY.es,
...TTS_BACKEND_COPY.es,
...CAPTION_WORKSPACE_COPY.es,
+ ...SRT_IMPORT_COPY.es,
...RESOURCE_LINK_COPY.es,
...PICTURE_IN_PICTURE_COPY.es,
languageTitle: "Elige el idioma",
@@ -1411,6 +1430,7 @@ Object.assign(UI_COPY, {
...CONTEXT_PANEL_COPY.fr,
...TTS_BACKEND_COPY.fr,
...CAPTION_WORKSPACE_COPY.fr,
+ ...SRT_IMPORT_COPY.fr,
...RESOURCE_LINK_COPY.fr,
...PICTURE_IN_PICTURE_COPY.fr,
languageTitle: "Choisir la langue",
@@ -1474,6 +1494,7 @@ Object.assign(UI_COPY, {
...CONTEXT_PANEL_COPY.de,
...TTS_BACKEND_COPY.de,
...CAPTION_WORKSPACE_COPY.de,
+ ...SRT_IMPORT_COPY.de,
...RESOURCE_LINK_COPY.de,
...PICTURE_IN_PICTURE_COPY.de,
languageTitle: "Sprache wählen",
@@ -1537,6 +1558,7 @@ Object.assign(UI_COPY, {
...CONTEXT_PANEL_COPY.pt,
...TTS_BACKEND_COPY.pt,
...CAPTION_WORKSPACE_COPY.pt,
+ ...SRT_IMPORT_COPY.pt,
...RESOURCE_LINK_COPY.pt,
...PICTURE_IN_PICTURE_COPY.pt,
languageTitle: "Escolha o idioma",
@@ -1600,6 +1622,7 @@ Object.assign(UI_COPY, {
...CONTEXT_PANEL_COPY.th,
...TTS_BACKEND_COPY.th,
...CAPTION_WORKSPACE_COPY.th,
+ ...SRT_IMPORT_COPY.th,
...RESOURCE_LINK_COPY.th,
...PICTURE_IN_PICTURE_COPY.th,
languageTitle: "เลือกภาษาอินเทอร์เฟซ",
@@ -1663,6 +1686,7 @@ Object.assign(UI_COPY, {
...CONTEXT_PANEL_COPY.vi,
...TTS_BACKEND_COPY.vi,
...CAPTION_WORKSPACE_COPY.vi,
+ ...SRT_IMPORT_COPY.vi,
...RESOURCE_LINK_COPY.vi,
...PICTURE_IN_PICTURE_COPY.vi,
languageTitle: "Chọn ngôn ngữ giao diện",
@@ -1804,11 +1828,12 @@ export function createTranslator(languageId) {
const copyLanguage = getCopyLanguage(languageId);
const copy = UI_COPY[copyLanguage] ?? UI_COPY.en;
const fallback = UI_COPY.en;
+ const srtImportCopy = SRT_IMPORT_COPY[languageId] ?? SRT_IMPORT_COPY.en;
const exportCopy = EXPORT_RENDER_COPY[copyLanguage] ?? EXPORT_RENDER_COPY.en;
const assetPreviewCopy = ASSET_PREVIEW_COPY[copyLanguage] ?? ASSET_PREVIEW_COPY.en;
const assetDropCopy = ASSET_DROP_COPY[copyLanguage] ?? ASSET_DROP_COPY.en;
const autoCaptionStatusCopy = AUTO_CAPTION_STATUS_COPY[copyLanguage] ?? AUTO_CAPTION_STATUS_COPY.en;
- return (key, fallbackText) => exportCopy[key] ?? EXPORT_RENDER_COPY.en[key] ?? assetPreviewCopy[key] ?? ASSET_PREVIEW_COPY.en[key] ?? assetDropCopy[key] ?? ASSET_DROP_COPY.en[key] ?? autoCaptionStatusCopy[key] ?? AUTO_CAPTION_STATUS_COPY.en[key] ?? copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
+ return (key, fallbackText) => srtImportCopy[key] ?? exportCopy[key] ?? EXPORT_RENDER_COPY.en[key] ?? assetPreviewCopy[key] ?? ASSET_PREVIEW_COPY.en[key] ?? assetDropCopy[key] ?? ASSET_DROP_COPY.en[key] ?? autoCaptionStatusCopy[key] ?? AUTO_CAPTION_STATUS_COPY.en[key] ?? copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
}
export function translateOptionName(languageId, name) {
diff --git a/src/i18nSrtImport.test.js b/src/i18nSrtImport.test.js
new file mode 100644
index 0000000..d623567
--- /dev/null
+++ b/src/i18nSrtImport.test.js
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+import { APP_LANGUAGES, createTranslator } from "./i18n.js";
+
+describe("SRT import translations", () => {
+ it("localizes every user-visible import state in every supported language", () => {
+ const keys = ["importSrt", "srtConflictTitle", "srtConflictDescription", "replaceSrt", "appendSrt", "srtImportComplete", "srtImportFailed", "srtFileTooLarge", "srtNoValidCaptions"];
+ for (const language of APP_LANGUAGES) {
+ const t = createTranslator(language.id);
+ for (const key of keys) expect(t(key), `${language.id}:${key}`).not.toBe(key);
+ }
+ expect(createTranslator("ru")("importSrt")).toBe("Импорт SRT");
+ });
+});
diff --git a/src/lib/subtitles.js b/src/lib/subtitles.js
new file mode 100644
index 0000000..f9f862a
--- /dev/null
+++ b/src/lib/subtitles.js
@@ -0,0 +1,53 @@
+import { makeId } from "./timeline.js";
+
+export const MAX_SRT_FILE_BYTES = 5 * 1024 * 1024;
+export const MAX_SRT_CAPTIONS = 5000;
+
+function parseTimestamp(value) {
+ const match = String(value).trim().match(/^(\d{1,3}):(\d{2}):(\d{2})[,.](\d{1,3})$/);
+ if (!match) return null;
+ const [, hours, minutes, seconds, fraction] = match;
+ if (Number(minutes) > 59 || Number(seconds) > 59) return null;
+ return Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds) + Number(fraction.padEnd(3, "0")) / 1000;
+}
+
+function cleanSrtText(lines) {
+ return lines.join("\n")
+ .replace(/
/gi, "\n")
+ .replace(/<[^>]+>/g, "")
+ .replace(/\{\\[^}]+}/g, "")
+ .trim();
+}
+
+export function parseSrt(source, { maxCaptions = MAX_SRT_CAPTIONS } = {}) {
+ const normalized = String(source ?? "").replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
+ const blocks = normalized.split(/\n{2,}/);
+ const captions = [];
+ let skipped = 0;
+
+ for (const block of blocks) {
+ const lines = block.split("\n").map((line) => line.trimEnd());
+ while (lines.length && !lines[0].trim()) lines.shift();
+ if (!lines.length) continue;
+ const timingIndex = lines.findIndex((line) => line.includes("-->"));
+ if (timingIndex < 0) { skipped += 1; continue; }
+ const timing = lines[timingIndex].split(/\s*-->\s*/);
+ const start = parseTimestamp(timing[0]);
+ const end = parseTimestamp(timing[1]?.split(/\s+/)[0]);
+ const text = cleanSrtText(lines.slice(timingIndex + 1));
+ if (start === null || end === null || end <= start || !text) { skipped += 1; continue; }
+ if (captions.length >= maxCaptions) { skipped += 1; continue; }
+ captions.push({ id: makeId("caption"), text, start, end, hidden: false });
+ }
+
+ captions.sort((a, b) => a.start - b.start || a.end - b.end);
+ return { captions, skipped };
+}
+
+export function appendImportedCaptions(existing, imported) {
+ return [...existing, ...imported].sort((a, b) => {
+ const aStart = Number.isFinite(a.start) ? a.start : Number.POSITIVE_INFINITY;
+ const bStart = Number.isFinite(b.start) ? b.start : Number.POSITIVE_INFINITY;
+ return aStart - bStart;
+ });
+}
diff --git a/src/lib/subtitles.test.js b/src/lib/subtitles.test.js
new file mode 100644
index 0000000..a09b5b2
--- /dev/null
+++ b/src/lib/subtitles.test.js
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { appendImportedCaptions, parseSrt } from "./subtitles.js";
+
+describe("parseSrt", () => {
+ it("parses BOM, CRLF, multiline text, tags, and missing sequence numbers", () => {
+ const result = parseSrt("\uFEFF1\r\n00:00:01,250 --> 00:00:03,500\r\nHello\r\nworld\r\n\r\n00:01:02.005 --> 00:01:04.050\r\nSecond");
+ expect(result.skipped).toBe(0);
+ expect(result.captions).toHaveLength(2);
+ expect(result.captions[0]).toMatchObject({ text: "Hello\nworld", start: 1.25, end: 3.5, hidden: false });
+ expect(result.captions[1]).toMatchObject({ text: "Second", start: 62.005, end: 64.05 });
+ });
+
+ it("skips malformed entries and enforces the caption limit", () => {
+ const result = parseSrt("1\nnot a timestamp\nBad\n\n2\n00:00:04,000 --> 00:00:03,000\nBackwards\n\n3\n00:00:05,000 --> 00:00:06,000\nGood\n\n4\n00:00:07,000 --> 00:00:08,000\nExtra", { maxCaptions: 1 });
+ expect(result.captions.map((caption) => caption.text)).toEqual(["Good"]);
+ expect(result.skipped).toBe(3);
+ });
+});
+
+describe("appendImportedCaptions", () => {
+ it("keeps all captions and orders explicit timings", () => {
+ const result = appendImportedCaptions([{ id: "later", text: "Later", start: 8, end: 9 }], [{ id: "first", text: "First", start: 2, end: 3 }]);
+ expect(result.map((caption) => caption.id)).toEqual(["first", "later"]);
+ });
+});
diff --git a/src/styles.css b/src/styles.css
index 5cb962d..7a9c2d8 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -3672,6 +3672,16 @@ button:disabled {
font-size: 13px;
font-weight: 760;
}
+.caption-context-heading > span { display:flex; align-items:center; gap:7px; min-width:0; }
+.caption-import-button { margin-left:auto; display:inline-flex; align-items:center; gap:5px; border:1px solid rgba(109,225,255,.24); border-radius:7px; padding:5px 8px; color:#bcefff; background:rgba(40,174,215,.08); font-size:11px; cursor:pointer; }
+.caption-import-button:hover { border-color:rgba(109,225,255,.5); background:rgba(40,174,215,.15); }
+.caption-empty-import { display:inline-flex; align-items:center; justify-content:center; gap:6px; margin-top:4px; min-height:34px; padding:0 12px; border:1px solid rgba(86,232,216,.4); border-radius:8px; color:#d9fffa; background:rgba(38,195,181,.12); font-size:12px; font-weight:700; cursor:pointer; }
+.caption-empty-import:hover { border-color:rgba(86,232,216,.72); background:rgba(38,195,181,.2); }
+.srt-import-backdrop { position:fixed; inset:0; z-index:140; display:grid; place-items:center; padding:24px; background:rgba(3,7,11,.78); backdrop-filter:blur(8px); }
+.srt-import-dialog { width:min(420px, 100%); padding:22px; border:1px solid rgba(116,220,255,.22); border-radius:14px; background:#10171f; box-shadow:0 24px 70px rgba(0,0,0,.5); }
+.srt-import-dialog > strong { display:block; color:#f2f8fb; font-size:17px; }
+.srt-import-dialog > p { margin:10px 0 20px; color:#9aabb6; font-size:13px; line-height:1.55; }
+.srt-import-dialog > div { display:flex; justify-content:flex-end; gap:9px; }
.caption-context-list {
display: grid;