Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(web): cover numeric captions in the transcript parser

Akshar Patel2cf80250e256
diff --git a/apps/web/__tests__/unit/transcript-numbers.test.ts b/apps/web/__tests__/unit/transcript-numbers.test.ts
index 27863c025..ec8e953f4 100644
--- a/apps/web/__tests__/unit/transcript-numbers.test.ts
+++ b/apps/web/__tests__/unit/transcript-numbers.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
+import { parseTranscriptVTT } from "@/app/s/[videoId]/_components/utils/parse-transcript-vtt";
import {
formatTranscriptAsVTT,
parseVTT,
@@ -6,7 +7,10 @@ import {
import { formatToWebVTT } from "@/lib/transcribe-utils";
import { updateVttEntryText } from "@/lib/transcript-vtt";
-describe("numeric transcript captions", () => {
+describe.each([
+ { name: "embed", parse: parseVTT },
+ { name: "transcript", parse: parseTranscriptVTT },
+])("$name numeric captions", ({ parse }) => {
it("preserves numbers separated into their own caption by a pause", () => {
const vtt = formatToWebVTT({
words: [
@@ -18,23 +22,23 @@ describe("numeric transcript captions", () => {
],
});
- expect(parseVTT(vtt).map(({ id, text }) => ({ id, text }))).toEqual([
+ expect(parse(vtt).map(({ id, text }) => ({ id, text }))).toEqual([
{ id: 1, text: "The year is" },
{ id: 2, text: "2026" },
{ id: 3, text: "Next." },
]);
- expect(formatTranscriptAsVTT(parseVTT(vtt))).toContain("\n2026\n");
+ expect(formatTranscriptAsVTT(parse(vtt))).toContain("\n2026\n");
});
- it("retains a numeric correction after reparsing the saved transcript", () => {
+ it.each(["0", "007"])("retains a saved correction to %s", (text) => {
const original = formatToWebVTT({
words: [{ text: "Zero.", start: 0, end: 1000 }],
});
- const saved = updateVttEntryText(original, 1, "0");
+ const saved = updateVttEntryText(original, 1, text);
expect(saved.updated).toBe(true);
- expect(parseVTT(saved.content)).toEqual([
- { id: 1, text: "0", timestamp: "00:00", startTime: 0 },
+ expect(parse(saved.content)).toMatchObject([
+ { id: 1, text, timestamp: "00:00", startTime: 0 },
]);
});
@@ -42,8 +46,18 @@ describe("numeric transcript captions", () => {
const vtt =
"WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\n\n2\n00:00:01.000 --> 00:00:02.000\nHello\n";
- expect(parseVTT(vtt)).toEqual([
+ expect(parse(vtt)).toMatchObject([
{ id: 2, timestamp: "00:01", startTime: 1, text: "Hello" },
]);
});
});
+
+it("preserves fractional seek and end times when reloading a saved numeric caption", () => {
+ const original = "WEBVTT\n\n1\n00:00:01.500 --> 00:00:02.750\nBond\n";
+ const saved = updateVttEntryText(original, 1, "007");
+
+ expect(saved.updated).toBe(true);
+ expect(parseTranscriptVTT(saved.content)).toEqual([
+ { id: 1, text: "007", timestamp: "00:01", startTime: 1.5, endTime: 2.75 },
+ ]);
+});
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
index e46d59bf8..de9a8b253 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
@@ -25,6 +25,8 @@ import { formatTranscriptAsParagraphs } from "@/lib/transcript-text";
import { normalizeTranscriptCueText } from "@/lib/transcript-vtt";
import type { VideoData } from "../../types";
import { type CaptionLanguage, useCaptionContext } from "../CaptionContext";
+import type { TranscriptEntry } from "../utils/parse-transcript-vtt";
+import { parseTranscriptVTT } from "../utils/parse-transcript-vtt";
interface TranscriptProps {
data: VideoData;
@@ -32,119 +34,6 @@ interface TranscriptProps {
user?: { id: string } | null;
}
-interface TranscriptEntry {
- id: number;
- timestamp: string;
- text: string;
- startTime: number;
- endTime: number;
-}
-
-const parseVTT = (vttContent: string): TranscriptEntry[] => {
- const lines = vttContent.split("\n");
- const entries: TranscriptEntry[] = [];
- let currentEntry: Partial<TranscriptEntry & { startTime: number }> = {};
- let currentId = 0;
-
- const timeToSeconds = (timeStr: string): number | null => {
- const parts = timeStr.split(":");
- if (parts.length !== 3) return null;
-
- const [hoursStr, minutesStr, secondsStr] = parts;
- if (!hoursStr || !minutesStr || !secondsStr) return null;
-
- const hours = parseInt(hoursStr, 10);
- const minutes = parseInt(minutesStr, 10);
- const seconds = parseInt(secondsStr, 10);
-
- if (Number.isNaN(hours) || Number.isNaN(minutes) || Number.isNaN(seconds))
- return null;
-
- return hours * 3600 + minutes * 60 + seconds;
- };
-
- const parseTimestamp = (
- timestamp: string,
- ): { mm_ss: string; totalSeconds: number } | null => {
- const parts = timestamp.split(":");
- if (parts.length !== 3) return null;
-
- const [hoursStr, minutesStr, secondsWithMs] = parts;
- if (!hoursStr || !minutesStr || !secondsWithMs) return null;
-
- const secondsPart = secondsWithMs.split(".")[0];
- if (!secondsPart) return null;
-
- const totalSeconds = timeToSeconds(
- `${hoursStr}:${minutesStr}:${secondsPart}`,
- );
- if (totalSeconds === null) return null;
-
- const fractionPart = secondsWithMs.split(".")[1];
- const fraction = fractionPart ? Number(`0.${fractionPart}`) : 0;
-
- return {
- mm_ss: `${minutesStr}:${secondsPart}`,
- totalSeconds: totalSeconds + (Number.isFinite(fraction) ? fraction : 0),
- };
- };
-
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line?.trim()) {
- currentEntry = {};
- continue;
- }
-
- const trimmedLine = line.trim();
-
- if (trimmedLine === "WEBVTT") continue;
-
- if (!currentEntry.timestamp && /^\d+$/.test(trimmedLine)) {
- currentId = parseInt(trimmedLine, 10);
- continue;
- }
-
- if (trimmedLine.includes("-->")) {
- const [startTimeStr, endTimeStr] = trimmedLine.split(" --> ");
- if (!startTimeStr || !endTimeStr) continue;
-
- const startTimestamp = parseTimestamp(startTimeStr);
- const endTimestamp = parseTimestamp(endTimeStr);
- if (startTimestamp) {
- currentEntry = {
- id: currentId,
- timestamp: startTimestamp.mm_ss,
- startTime: startTimestamp.totalSeconds,
- endTime: endTimestamp?.totalSeconds ?? startTimestamp.totalSeconds,
- };
- }
- continue;
- }
-
- if (currentEntry.timestamp && !currentEntry.text) {
- const textContent =
- trimmedLine.startsWith('"') && trimmedLine.endsWith('"')
- ? trimmedLine.slice(1, -1)
- : trimmedLine;
-
- currentEntry.text = textContent;
- if (
- currentEntry.id !== undefined &&
- currentEntry.timestamp &&
- currentEntry.text &&
- currentEntry.startTime !== undefined
- ) {
- entries.push(currentEntry as TranscriptEntry);
- }
- currentEntry = {};
- }
- }
-
- const sortedEntries = entries.sort((a, b) => a.startTime - b.startTime);
- return sortedEntries;
-};
-
/** Module-level so the last live transcript survives component remounts and
* router refreshes during the live→canonical handoff. */
const lastLiveTranscript = new Map<
@@ -271,7 +160,8 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
const isLiveTranscriptActive =
liveTranscript?.kind === "ready" && liveTranscript.state === "active";
const liveTranscriptData = useMemo(
- () => (liveTranscriptContent ? parseVTT(liveTranscriptContent) : []),
+ () =>
+ liveTranscriptContent ? parseTranscriptVTT(liveTranscriptContent) : [],
[liveTranscriptContent],
);
@@ -316,10 +206,10 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
useEffect(() => {
const vttContent = captionContext.currentVttContent;
if (vttContent) {
- const parsed = parseVTT(vttContent);
+ const parsed = parseTranscriptVTT(vttContent);
setTranscriptData(parsed);
} else if (transcriptContent && selectedLanguage === "original") {
- const parsed = parseVTT(transcriptContent);
+ const parsed = parseTranscriptVTT(transcriptContent);
setTranscriptData(parsed);
}
}, [captionContext.currentVttContent, transcriptContent, selectedLanguage]);
diff --git a/apps/web/app/s/[videoId]/_components/utils/parse-transcript-vtt.ts b/apps/web/app/s/[videoId]/_components/utils/parse-transcript-vtt.ts
new file mode 100644
index 000000000..d62fccfb4
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/utils/parse-transcript-vtt.ts
@@ -0,0 +1,112 @@
+export interface TranscriptEntry {
+ id: number;
+ timestamp: string;
+ text: string;
+ startTime: number;
+ endTime: number;
+}
+
+export const parseTranscriptVTT = (vttContent: string): TranscriptEntry[] => {
+ const lines = vttContent.split("\n");
+ const entries: TranscriptEntry[] = [];
+ let currentEntry: Partial<TranscriptEntry & { startTime: number }> = {};
+ let currentId = 0;
+
+ const timeToSeconds = (timeStr: string): number | null => {
+ const parts = timeStr.split(":");
+ if (parts.length !== 3) return null;
+
+ const [hoursStr, minutesStr, secondsStr] = parts;
+ if (!hoursStr || !minutesStr || !secondsStr) return null;
+
+ const hours = parseInt(hoursStr, 10);
+ const minutes = parseInt(minutesStr, 10);
+ const seconds = parseInt(secondsStr, 10);
+
+ if (Number.isNaN(hours) || Number.isNaN(minutes) || Number.isNaN(seconds))
+ return null;
+
+ return hours * 3600 + minutes * 60 + seconds;
+ };
+
+ const parseTimestamp = (
+ timestamp: string,
+ ): { mm_ss: string; totalSeconds: number } | null => {
+ const parts = timestamp.split(":");
+ if (parts.length !== 3) return null;
+
+ const [hoursStr, minutesStr, secondsWithMs] = parts;
+ if (!hoursStr || !minutesStr || !secondsWithMs) return null;
+
+ const secondsPart = secondsWithMs.split(".")[0];
+ if (!secondsPart) return null;
+
+ const totalSeconds = timeToSeconds(
+ `${hoursStr}:${minutesStr}:${secondsPart}`,
+ );
+ if (totalSeconds === null) return null;
+
+ const fractionPart = secondsWithMs.split(".")[1];
+ const fraction = fractionPart ? Number(`0.${fractionPart}`) : 0;
+
+ return {
+ mm_ss: `${minutesStr}:${secondsPart}`,
+ totalSeconds: totalSeconds + (Number.isFinite(fraction) ? fraction : 0),
+ };
+ };
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (!line?.trim()) {
+ currentEntry = {};
+ continue;
+ }
+
+ const trimmedLine = line.trim();
+
+ if (trimmedLine === "WEBVTT") continue;
+
+ if (!currentEntry.timestamp && /^\d+$/.test(trimmedLine)) {
+ currentId = parseInt(trimmedLine, 10);
+ continue;
+ }
+
+ if (trimmedLine.includes("-->")) {
+ const [startTimeStr, endTimeStr] = trimmedLine.split(" --> ");
+ if (!startTimeStr || !endTimeStr) continue;
+
+ const startTimestamp = parseTimestamp(startTimeStr);
+ const endTimestamp = parseTimestamp(endTimeStr);
+ if (startTimestamp) {
+ currentEntry = {
+ id: currentId,
+ timestamp: startTimestamp.mm_ss,
+ startTime: startTimestamp.totalSeconds,
+ endTime: endTimestamp?.totalSeconds ?? startTimestamp.totalSeconds,
+ };
+ }
+ continue;
+ }
+
+ if (currentEntry.timestamp && !currentEntry.text) {
+ const textContent =
+ trimmedLine.startsWith('"') && trimmedLine.endsWith('"')
+ ? trimmedLine.slice(1, -1)
+ : trimmedLine;
+
+ currentEntry.text = textContent;
+ if (
+ currentEntry.id !== undefined &&
+ currentEntry.timestamp &&
+ currentEntry.text &&
+ currentEntry.startTime !== undefined
+ ) {
+ entries.push(currentEntry as TranscriptEntry);
+ }
+ currentEntry = {};
+ }
+ }
+
+ const sortedEntries = entries.sort((a, b) => a.startTime - b.startTime);
+ return sortedEntries;
+};