Add custom SRT subtitle import

This commit is contained in:
haixin.yang committed 2026-07-20 15:33:02 +08:00
1 parent 88902d82e4
commit 8a45619ecf
8 files changed
+236 -3

No files matched your search

+37
View File
@@ -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");
});
+15
View File
@@ -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}
+57 -2
View File
@@ -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 (
<div className="caption-context-panel">
<label className="field-label" htmlFor="caption-context-input">
@@ -147,6 +171,9 @@ function CaptionContextPanel({
<ClosedCaptioning size={28} weight="duotone" />
<strong>{t("noCaptionSegments")}</strong>
<span>{t("captionEmptyHint", "字幕片段可拖动到字幕轨道,并在这里同步编辑。")}</span>
<button className="caption-empty-import" type="button" onClick={() => srtInputRef.current?.click()}>
<UploadSimple size={15} />{t("importSrt")}
</button>
</div>
)}
@@ -192,9 +219,35 @@ function CaptionContextPanel({
) : null}
<div className="caption-context-heading">
<ListBullets size={16} />
<span>{t("captionList", "字幕列表")}</span>
<span><ListBullets size={16} />{t("captionList", "字幕列表")}</span>
<button className="caption-import-button" type="button" onClick={() => srtInputRef.current?.click()}>
<UploadSimple size={14} />{t("importSrt")}
</button>
<input
ref={srtInputRef}
className="sr-only"
type="file"
accept=".srt,application/x-subrip,text/plain"
data-testid="srt-file-input"
onChange={(event) => {
handleSrtFile(event.target.files?.[0]);
event.target.value = "";
}}
/>
</div>
{pendingSrt ? createPortal(
<div className="srt-import-backdrop" role="presentation">
<section className="srt-import-dialog" role="dialog" aria-modal="true" aria-label={t("srtConflictTitle")}>
<strong>{t("srtConflictTitle")}</strong>
<p>{t("srtConflictDescription").replace("{count}", pendingSrt.captions.length)}</p>
<div>
<button className="panel-secondary" type="button" onClick={() => setPendingSrt(null)}>{t("cancel")}</button>
<button className="panel-secondary" type="button" onClick={() => applyPendingSrt("append")}>{t("appendSrt")}</button>
<button className="auto-edit-apply" type="button" onClick={() => applyPendingSrt("replace")}>{t("replaceSrt")}</button>
</div>
</section>
</div>, document.body,
) : null}
<div className="caption-context-list">
{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}
+26 -1
View File
@@ -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) {
+13
View File
@@ -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");
});
});
+53
View File
@@ -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(/<br\s*\/?>/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;
});
}
+25
View File
@@ -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\n<i>Hello</i>\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"]);
});
});
+10
View File
@@ -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;