From 7b0d38f24f5828ff178a9f09d1cfd26d4569fa36 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Sat, 21 Nov 2026 10:33:15 +0530 Subject: [PATCH 1/2] feat(ui): add playback, subtitles, and downloads PlaybackPanel renders the ready state and embeds SubtitleView (active-word highlight, click-to-seek, cue list) and DownloadBar (WAV/SRT/VTT with the API's download naming). usePlayback owns the audio ref, rAF highlight loop, binary search, seeking, and Space/arrow shortcuts. --- frontend/src/App.tsx | 11 +- frontend/src/components/DownloadBar.test.tsx | 79 ++++++ frontend/src/components/DownloadBar.tsx | 152 +++++++++++ .../src/components/PlaybackPanel.test.tsx | 85 ++++++ frontend/src/components/PlaybackPanel.tsx | 180 ++++++++++++ frontend/src/components/SubtitleView.test.tsx | 69 +++++ frontend/src/components/SubtitleView.tsx | 103 +++++++ frontend/src/hooks/usePlayback.test.ts | 94 +++++++ frontend/src/hooks/usePlayback.ts | 257 ++++++++++++++++++ frontend/src/styles.css | 103 +++++++ 10 files changed, 1126 insertions(+), 7 deletions(-) create mode 100644 frontend/src/components/DownloadBar.test.tsx create mode 100644 frontend/src/components/DownloadBar.tsx create mode 100644 frontend/src/components/PlaybackPanel.test.tsx create mode 100644 frontend/src/components/PlaybackPanel.tsx create mode 100644 frontend/src/components/SubtitleView.test.tsx create mode 100644 frontend/src/components/SubtitleView.tsx create mode 100644 frontend/src/hooks/usePlayback.test.ts create mode 100644 frontend/src/hooks/usePlayback.ts diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d9d0057..d3c767c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,9 +1,8 @@ /** * Single page layout (ARCHITECTURE.md section 12). * - * Sections stack in their documented order. The playback and history sections - * stay as placeholders until T3.2/T3.3 replace them, so each task can own its - * own component file. + * Sections stack in their documented order. The history section stays as a + * placeholder until T3.3 replaces it, so that task can own its component file. */ import { useEffect } from "react"; @@ -12,6 +11,7 @@ import { toApiError } from "./api/client"; import { ErrorBanner } from "./components/ErrorBanner"; import { GenerateBar } from "./components/GenerateBar"; import { InputPanel } from "./components/InputPanel"; +import { PlaybackPanel } from "./components/PlaybackPanel"; import { VoicePanel } from "./components/VoicePanel"; import { clampRate, clampVolume } from "./components/validation"; import { useApp } from "./state/appContext"; @@ -73,10 +73,7 @@ export function App() { -
-

Playback and subtitles

-

Audio, word highlighting, seek, and downloads appear here.

-
+

History

diff --git a/frontend/src/components/DownloadBar.test.tsx b/frontend/src/components/DownloadBar.test.tsx new file mode 100644 index 0000000..65a9927 --- /dev/null +++ b/frontend/src/components/DownloadBar.test.tsx @@ -0,0 +1,79 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { AppProvider } from "../state/appContext"; +import type { GenerationDetail } from "../types/contracts"; +import { DownloadBar, downloadFilename, downloadStem, downloadTimestamp } from "./DownloadBar"; + +const DETAIL: GenerationDetail = { + generationId: "11111111-1111-4111-8111-111111111111", + status: "succeeded", + createdAt: "2026-11-20T19:04:45Z", + sourceType: "text", + inputPreview: "Hello world.", + inputFilename: null, + voiceId: "en_US-lessac-medium", + voiceName: "Lessac", + rate: 1, + volume: 1, + durationSeconds: 12.5, + error: null, + text: "Hello world.", + sampleRate: 22050, + alignedWordRatio: 1, + wordTimings: [], + cues: [], +}; + +describe("downloadTimestamp", () => { + it("formats the creation time in UTC", () => { + expect(downloadTimestamp("2026-11-20T19:04:45.123456Z")).toBe("20261120-190445"); + }); + + it("converts offset timestamps to UTC", () => { + expect(downloadTimestamp("2026-11-20T20:04:45+01:00")).toBe("20261120-190445"); + }); +}); + +describe("downloadStem", () => { + it("takes at most six words, lowercased and hyphen-joined", () => { + expect( + downloadStem("Hello, world! This is a test of the filename builder.", "2026-11-20T19:04:45Z"), + ).toBe("hello-world-this-is-a-test_20261120-190445"); + }); + + it("ignores non-ASCII characters the same way the API regex does", () => { + expect(downloadStem("Über café", "2026-11-20T19:04:45Z")).toBe("ber-caf_20261120-190445"); + }); + + it("falls back to speech when the input has no usable characters", () => { + expect(downloadStem(" ", "2026-11-20T19:04:45Z")).toBe("speech_20261120-190445"); + }); +}); + +describe("downloadFilename", () => { + it("appends the file extension", () => { + expect(downloadFilename("Hello world.", "2026-11-20T19:04:45Z", "wav")).toBe( + "hello-world_20261120-190445.wav", + ); + expect(downloadFilename("Hello world.", "2026-11-20T19:04:45Z", "srt")).toBe( + "hello-world_20261120-190445.srt", + ); + expect(downloadFilename("Hello world.", "2026-11-20T19:04:45Z", "vtt")).toBe( + "hello-world_20261120-190445.vtt", + ); + }); +}); + +describe("DownloadBar", () => { + it("offers all three downloads", () => { + const html = renderToStaticMarkup( + + + , + ); + expect(html).toContain("Download audio (WAV)"); + expect(html).toContain("Download subtitles (SRT)"); + expect(html).toContain("Download subtitles (VTT)"); + expect(html).toContain("first words of the input"); + }); +}); diff --git a/frontend/src/components/DownloadBar.tsx b/frontend/src/components/DownloadBar.tsx new file mode 100644 index 0000000..bba1866 --- /dev/null +++ b/frontend/src/components/DownloadBar.tsx @@ -0,0 +1,152 @@ +/** + * Audio and subtitle downloads (ARCHITECTURE.md sections 9.2 and 12, FR-07). + * + * The browser cannot read the server's `Content-Disposition` header through + * `fetch`, so the download name is rebuilt with the same §9.2 rule the API + * uses: first ≤ 6 words of the input, lowercased, joined by `-`, plus the UTC + * `createdAt` timestamp as `YYYYMMDD-HHMMSS`. + */ + +import { useState } from "react"; +import { api } from "../api"; +import { toApiError } from "../api/client"; +import { useApp } from "../state/appContext"; +import type { GenerationDetail, SubtitleFormat } from "../types/contracts"; + +export type DownloadKind = "wav" | SubtitleFormat; + +const SLUG_WORDS = 6; + +function pad(value: number): string { + return String(value).padStart(2, "0"); +} + +/** UTC `YYYYMMDD-HHMMSS`, the timestamp half of the §9.2 download name. */ +export function downloadTimestamp(createdAt: string): string { + const date = new Date(createdAt); + const safe = Number.isNaN(date.getTime()) ? new Date() : date; + return ( + `${safe.getUTCFullYear()}${pad(safe.getUTCMonth() + 1)}${pad(safe.getUTCDate())}` + + `-${pad(safe.getUTCHours())}${pad(safe.getUTCMinutes())}${pad(safe.getUTCSeconds())}` + ); +} + +/** The `{slug}_{timestamp}` stem shared by all three download files. */ +export function downloadStem(input: string, createdAt: string): string { + const words = (input.match(/[A-Za-z0-9]+/g) ?? []).slice(0, SLUG_WORDS); + const slug = + words + .join("-") + .toLowerCase() + .replace(/[^a-z0-9-]/g, "") + .replace(/^-+|-+$/g, "") || "speech"; + return `${slug}_${downloadTimestamp(createdAt)}`; +} + +export function downloadFilename( + input: string, + createdAt: string, + extension: DownloadKind, +): string { + return `${downloadStem(input, createdAt)}.${extension}`; +} + +/** Triggers a browser download for an already-fetched blob. */ +function saveBlob(blob: Blob, filename: string): void { + const url = URL.createObjectURL(blob); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = filename; + anchor.rel = "noopener"; + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + window.setTimeout(() => { + URL.revokeObjectURL(url); + }, 0); +} + +export interface DownloadBarProps { + detail: GenerationDetail; +} + +export function DownloadBar({ detail }: DownloadBarProps) { + const { dispatch } = useApp(); + const [busy, setBusy] = useState(null); + const input = detail.text ?? detail.inputPreview; + + function dispatchFailure(error: unknown): void { + const failure = toApiError(error); + dispatch({ + type: "SET_ERROR", + error: { code: failure.code, message: failure.message, details: failure.details }, + }); + } + + async function downloadAudio(): Promise { + setBusy("wav"); + try { + const blob = await api.getAudioBlob(detail.generationId); + saveBlob(blob, downloadFilename(input, detail.createdAt, "wav")); + } catch (error) { + dispatchFailure(error); + } finally { + setBusy(null); + } + } + + async function downloadSubtitles(format: SubtitleFormat): Promise { + setBusy(format); + try { + const text = await api.getSubtitlesText(detail.generationId, format); + const blob = new Blob([text], { type: "text/plain;charset=utf-8" }); + saveBlob(blob, downloadFilename(input, detail.createdAt, format)); + } catch (error) { + dispatchFailure(error); + } finally { + setBusy(null); + } + } + + const disabled = busy !== null; + + return ( +
+

Downloads

+

+ Files are named after the first words of the input and when the generation was created. +

+
+ + + +
+
+ ); +} diff --git a/frontend/src/components/PlaybackPanel.test.tsx b/frontend/src/components/PlaybackPanel.test.tsx new file mode 100644 index 0000000..4bdff1a --- /dev/null +++ b/frontend/src/components/PlaybackPanel.test.tsx @@ -0,0 +1,85 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { AppProvider, type CurrentGeneration } from "../state/appContext"; +import type { GenerationDetail } from "../types/contracts"; +import { isInteractiveTarget, playbackMessage, PlaybackPanel } from "./PlaybackPanel"; + +const DETAIL: GenerationDetail = { + generationId: "11111111-1111-4111-8111-111111111111", + status: "succeeded", + createdAt: "2026-11-20T19:04:45Z", + sourceType: "text", + inputPreview: "Hello world.", + inputFilename: null, + voiceId: "en_US-lessac-medium", + voiceName: "Lessac", + rate: 1, + volume: 1, + durationSeconds: 1, + error: null, + text: "Hello world.", + sampleRate: 22050, + alignedWordRatio: 1, + wordTimings: [{ text: "Hello", startMs: 0, endMs: 400, aligned: true }], + cues: [{ index: 1, startMs: 0, endMs: 400, text: "Hello" }], +}; + +function current(overrides: Partial): CurrentGeneration { + return { + id: "11111111-1111-4111-8111-111111111111", + status: "succeeded", + sentenceIndex: 0, + sentenceCount: 0, + ...overrides, + }; +} + +describe("playbackMessage", () => { + it("prompts for a generation when nothing exists yet", () => { + expect(playbackMessage(null)).toContain("Generate audio"); + }); + + it("has no message for a succeeded entry with details", () => { + expect(playbackMessage(current({ detail: DETAIL }))).toBeNull(); + }); + + it("explains a succeeded entry whose details are missing", () => { + expect(playbackMessage(current({ detail: undefined }))).toContain( + "details could not be loaded", + ); + }); + + it("explains failed, cancelled, and in-progress entries", () => { + expect(playbackMessage(current({ status: "failed" }))).toContain("failed"); + expect(playbackMessage(current({ status: "cancelled" }))).toContain("cancelled"); + expect(playbackMessage(current({ status: "running" }))).toContain("when generation finishes"); + }); +}); + +describe("isInteractiveTarget", () => { + it("keeps native behavior for form controls and links", () => { + for (const tagName of ["INPUT", "TEXTAREA", "SELECT", "BUTTON", "a"]) { + expect(isInteractiveTarget({ tagName })).toBe(true); + } + expect(isInteractiveTarget({ isContentEditable: true })).toBe(true); + }); + + it("allows shortcuts on non-interactive targets", () => { + expect(isInteractiveTarget(null)).toBe(false); + expect(isInteractiveTarget({ tagName: "DIV" })).toBe(false); + expect(isInteractiveTarget({})).toBe(false); + }); +}); + +describe("PlaybackPanel", () => { + it("renders the section heading and the empty state", () => { + const html = renderToStaticMarkup( + + + , + ); + expect(html).toContain("Playback and subtitles"); + expect(html).toContain("Generate audio to play it back here."); + expect(html).not.toContain(" { + function handleKeyDown(event: KeyboardEvent): void { + if ( + !audioReady || + event.defaultPrevented || + event.altKey || + event.ctrlKey || + event.metaKey || + isInteractiveTarget(event.target) + ) { + return; + } + if (event.key === " " || event.key === "Spacebar") { + event.preventDefault(); + toggle(); + } else if (event.key === "ArrowLeft") { + event.preventDefault(); + skip(-5); + } else if (event.key === "ArrowRight") { + event.preventDefault(); + skip(5); + } + } + + window.addEventListener("keydown", handleKeyDown); + return () => { + window.removeEventListener("keydown", handleKeyDown); + }; + }, [audioReady, skip, toggle]); + + const duration = + detail !== null && detail.durationSeconds !== null + ? `${formatClock(detail.durationSeconds * 1000)} long` + : null; + const aligned = + detail !== null && detail.alignedWordRatio !== null && detail.alignedWordRatio >= 0 + ? `${Math.round(detail.alignedWordRatio * 100)}% of words timed` + : null; + + return ( +
+

Playback and subtitles

+ + {message !== null ?

{message}

: null} + + {detail !== null && current?.status === "succeeded" ? ( + <> + {audioReady && audioUrl !== undefined ? ( +
+ ); +} diff --git a/frontend/src/components/SubtitleView.test.tsx b/frontend/src/components/SubtitleView.test.tsx new file mode 100644 index 0000000..e1f8b9d --- /dev/null +++ b/frontend/src/components/SubtitleView.test.tsx @@ -0,0 +1,69 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import type { Cue, WordTiming } from "../types/contracts"; +import { formatClock, SubtitleView } from "./SubtitleView"; + +const TIMINGS: WordTiming[] = [ + { text: "Hello", startMs: 0, endMs: 400, aligned: true }, + { text: "brave", startMs: 500, endMs: 900, aligned: true }, + { text: "world", startMs: 900, endMs: 1400, aligned: false }, +]; + +const CUES: Cue[] = [ + { index: 1, startMs: 0, endMs: 900, text: "Hello brave" }, + { index: 2, startMs: 1400, endMs: 2000, text: "world" }, +]; + +function render(activeIndex = -1, wordTimings: WordTiming[] | null = TIMINGS): string { + return renderToStaticMarkup( + undefined} + />, + ); +} + +describe("formatClock", () => { + it("formats minutes and seconds, adding hours only when needed", () => { + expect(formatClock(0)).toBe("00:00"); + expect(formatClock(65_000)).toBe("01:05"); + expect(formatClock(3_725_000)).toBe("1:02:05"); + }); + + it("clamps negative values to zero", () => { + expect(formatClock(-10)).toBe("00:00"); + }); +}); + +describe("SubtitleView", () => { + it("renders every word and marks the active one", () => { + const html = render(1); + expect(html).toContain("Hello"); + expect(html).toContain("brave"); + expect(html).toContain("world"); + expect(html).toContain('class="word active"'); + }); + + it("marks words without reliable alignment", () => { + expect(render()).toContain('class="word unaligned"'); + expect(render()).toContain("Timing estimated from nearby words"); + }); + + it("renders a keyboard-reachable button per cue with its timestamp", () => { + const html = render(); + expect(html).toContain('class="cue"'); + expect(html).toContain("00:00"); + expect(html).toContain("00:01"); + expect(html).toContain("Jump to 00:00: Hello brave"); + }); + + it("explains the degraded state when there are no timings", () => { + const html = render(-1, null); + expect(html).toContain("Timing details are unavailable"); + expect(html).not.toContain('class="word'); + expect(html).toContain("` element and playback state. + */ + +import { useEffect, useRef } from "react"; +import { firstWordIndexAtOrAfter } from "../hooks/usePlayback"; +import type { Cue, WordTiming } from "../types/contracts"; + +export interface SubtitleViewProps { + wordTimings: readonly WordTiming[] | null; + cues: readonly Cue[] | null; + activeIndex: number; + onSeekWord: (index: number) => void; +} + +/** `mm:ss` timeline label; hours are added only when needed. */ +export function formatClock(milliseconds: number): string { + const safe = Math.max(0, Math.round(milliseconds)); + const hours = Math.floor(safe / 3_600_000); + const minutes = Math.floor((safe % 3_600_000) / 60_000); + const seconds = Math.floor((safe % 60_000) / 1000); + const pad = (value: number): string => String(value).padStart(2, "0"); + return hours > 0 ? `${hours}:${pad(minutes)}:${pad(seconds)}` : `${pad(minutes)}:${pad(seconds)}`; +} + +export function SubtitleView({ wordTimings, cues, activeIndex, onSeekWord }: SubtitleViewProps) { + const activeRef = useRef(null); + + useEffect(() => { + activeRef.current?.scrollIntoView({ block: "nearest" }); + }, [activeIndex]); + + const hasWords = wordTimings !== null && wordTimings.length > 0; + const playableCues = cues !== null && cues.length > 0 ? cues : []; + + return ( +
+ {hasWords ? ( +

+ {wordTimings.map((word, index) => { + const classes = ["word"]; + if (index === activeIndex) { + classes.push("active"); + } + if (!word.aligned) { + classes.push("unaligned"); + } + return ( + + { + onSeekWord(index); + }} + > + {word.text} + {" "} + + ); + })} +

+ ) : ( +

+ Timing details are unavailable for this generation, so there is no word highlight. Audio + and downloads still work. +

+ )} + + {playableCues.length > 0 ? ( +
+

Sentences

+
    + {playableCues.map((cue) => { + const firstWord = + wordTimings === null ? -1 : firstWordIndexAtOrAfter(wordTimings, cue.startMs); + return ( +
  1. + +
  2. + ); + })} +
+
+ ) : null} +
+ ); +} diff --git a/frontend/src/hooks/usePlayback.test.ts b/frontend/src/hooks/usePlayback.test.ts new file mode 100644 index 0000000..725b8ad --- /dev/null +++ b/frontend/src/hooks/usePlayback.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from "vitest"; +import type { WordTiming } from "../types/contracts"; +import { clampSeconds, findActiveWordIndex, firstWordIndexAtOrAfter } from "./usePlayback"; + +const TIMINGS: WordTiming[] = [ + { text: "One", startMs: 0, endMs: 400, aligned: true }, + { text: "two", startMs: 500, endMs: 900, aligned: true }, + { text: "three", startMs: 900, endMs: 1200, aligned: false }, +]; + +describe("findActiveWordIndex", () => { + it("returns -1 for an empty list", () => { + expect(findActiveWordIndex([], 0)).toBe(-1); + }); + + it("returns -1 before the first word", () => { + expect(findActiveWordIndex(TIMINGS, -1)).toBe(-1); + }); + + it("includes the start and end boundaries of a word", () => { + expect(findActiveWordIndex(TIMINGS, 0)).toBe(0); + expect(findActiveWordIndex(TIMINGS, 400)).toBe(0); + expect(findActiveWordIndex(TIMINGS, 500)).toBe(1); + expect(findActiveWordIndex(TIMINGS, 900)).toBe(2); + expect(findActiveWordIndex(TIMINGS, 1200)).toBe(2); + }); + + it("returns -1 inside a gap between words", () => { + expect(findActiveWordIndex(TIMINGS, 450)).toBe(-1); + expect(findActiveWordIndex(TIMINGS, 1250)).toBe(-1); + }); + + it("returns -1 for non-finite times", () => { + expect(findActiveWordIndex(TIMINGS, Number.NaN)).toBe(-1); + expect(findActiveWordIndex(TIMINGS, Number.POSITIVE_INFINITY)).toBe(-1); + }); + + it("matches a linear scan over a long timing list", () => { + const long: WordTiming[] = Array.from({ length: 257 }, (_, index) => ({ + text: `w${index}`, + startMs: index * 300, + endMs: index * 300 + 250, + aligned: index % 5 !== 0, + })); + const linear = (timeMs: number): number => { + let found = -1; + for (let index = 0; index < long.length; index += 1) { + if (long[index].startMs <= timeMs) { + found = index; + } + } + if (found < 0) { + return -1; + } + return timeMs <= long[found].endMs ? found : -1; + }; + for (let timeMs = -50; timeMs < 77_000; timeMs += 37) { + expect(findActiveWordIndex(long, timeMs)).toBe(linear(timeMs)); + } + }); +}); + +describe("firstWordIndexAtOrAfter", () => { + it("returns -1 for an empty list", () => { + expect(firstWordIndexAtOrAfter([], 0)).toBe(-1); + }); + + it("finds the exact word at a cue start", () => { + expect(firstWordIndexAtOrAfter(TIMINGS, 0)).toBe(0); + expect(firstWordIndexAtOrAfter(TIMINGS, 500)).toBe(1); + }); + + it("finds the next word when a time falls before it", () => { + expect(firstWordIndexAtOrAfter(TIMINGS, 450)).toBe(1); + }); + + it("falls back to the last word when the time is past the end", () => { + expect(firstWordIndexAtOrAfter(TIMINGS, 99_000)).toBe(2); + }); +}); + +describe("clampSeconds", () => { + it("keeps values inside the audio duration", () => { + expect(clampSeconds(3, 10)).toBe(3); + expect(clampSeconds(-2, 10)).toBe(0); + expect(clampSeconds(20, 10)).toBe(10); + }); + + it("only enforces a lower bound when the duration is unknown", () => { + expect(clampSeconds(5, Number.NaN)).toBe(5); + expect(clampSeconds(5, 0)).toBe(5); + expect(clampSeconds(Number.NaN, 10)).toBe(0); + }); +}); diff --git a/frontend/src/hooks/usePlayback.ts b/frontend/src/hooks/usePlayback.ts new file mode 100644 index 0000000..0a23ccc --- /dev/null +++ b/frontend/src/hooks/usePlayback.ts @@ -0,0 +1,257 @@ +/** + * Playback synchronization (ARCHITECTURE.md section 10.3 and section 12). + * + * Owns the `