Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(reading): add media transcript stage

XZH071885cd2e4f
diff --git a/web/components/reading/library/AddMaterialsDialog.tsx b/web/components/reading/library/AddMaterialsDialog.tsx
index 67de919e2..a22c68405 100644
--- a/web/components/reading/library/AddMaterialsDialog.tsx
+++ b/web/components/reading/library/AddMaterialsDialog.tsx
@@ -5,6 +5,7 @@ import {
Library,
Link2,
Loader2,
+ Rss,
Search,
Upload,
X,
@@ -19,6 +20,7 @@ import {
} from "react";
import { useTranslation } from "react-i18next";
+import { WatchingBrowser } from "@/components/watching/WatchingBrowser";
import { uploadMaterial } from "@/lib/reading-api";
import {
addReadingWorkspaceMaterial,
@@ -85,6 +87,7 @@ export function AddMaterialsDialog({
const [working, setWorking] = useState(false);
const [error, setError] = useState("");
const [showPicker, setShowPicker] = useState(false);
+ const [showInvidious, setShowInvidious] = useState(false);
const heading =
mode === "create"
@@ -127,6 +130,32 @@ export function AddMaterialsDialog({
setLinkDraft("");
}, [linkDraft]);
+ const importInvidiousUrl = useCallback(
+ async (url: string) => {
+ if (working) return;
+ setWorking(true);
+ setError("");
+ try {
+ const label = url.replace(/^https?:\/\//, "").slice(0, 80);
+ const imported =
+ mode === "add" && workspaceId
+ ? await importReadingUrls({ urls: [url], workspace_id: workspaceId })
+ : await importReadingUrls({
+ urls: [url],
+ workspace_title:
+ mode === "create" && title.trim() ? title.trim() : label,
+ });
+ const workspace = imported.workspace;
+ onDone({ workspace });
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : t("Import failed."));
+ } finally {
+ setWorking(false);
+ }
+ },
+ [mode, onDone, t, title, workspaceId, working],
+ );
+
// Hash new files in the browser and ask the server what it already holds, so
// a duplicate is surfaced while the user can still decide — not after the
// upload silently collapsed onto an existing row.
@@ -427,6 +456,15 @@ export function AddMaterialsDialog({
</div>
</div>
+ <button
+ type="button"
+ onClick={() => setShowInvidious(true)}
+ className="mt-3 flex w-full items-center gap-2 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[11.5px] text-[var(--muted-foreground)] transition hover:border-[var(--primary)] hover:text-[var(--primary)]"
+ >
+ <Rss size={13} />
+ {t("Browse Invidious")}
+ </button>
+
{!!items.length && (
<ul className="mt-3.5 space-y-1.5">
{items.map((item) => (
@@ -488,6 +526,15 @@ export function AddMaterialsDialog({
</button>
</div>
</div>
+
+ {showInvidious && (
+ <WatchingBrowser
+ selectionMode
+ canDismiss
+ onSelectUrl={(url) => void importInvidiousUrl(url)}
+ onDismiss={() => setShowInvidious(false)}
+ />
+ )}
</div>
);
}
diff --git a/web/components/reading/workspace/MediaReadingStage.tsx b/web/components/reading/workspace/MediaReadingStage.tsx
index ee24a4e7b..8facd4b80 100644
--- a/web/components/reading/workspace/MediaReadingStage.tsx
+++ b/web/components/reading/workspace/MediaReadingStage.tsx
@@ -1,6 +1,16 @@
"use client";
-import { ExternalLink, FileAudio } from "lucide-react";
+import {
+ Captions,
+ ChevronDown,
+ ChevronUp,
+ ChevronsDown,
+ ExternalLink,
+ FileAudio,
+ Maximize2,
+ Minimize2,
+ Search,
+} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -27,14 +37,21 @@ import {
youtubeVideoId,
} from "@/lib/reading-video-sources";
import { type ReadingLibraryMaterial } from "@/lib/reading-workspace-api";
+import {
+ stepTranscriptMatch,
+ transcriptMatchIndexes,
+} from "@/lib/transcript-search";
+import { transcriptFollowScrollTop } from "@/lib/transcript-follow";
import { YouTubeReadingPlayer } from "./YouTubeReadingPlayer";
import { BilibiliReadingPlayer } from "./BilibiliReadingPlayer";
-import { timeFromSourceHref } from "@/lib/reading-media-time";
+import { formatMediaTime, timeFromSourceHref } from "@/lib/reading-media-time";
+import type { TranscriptRow } from "./types";
export function MediaReadingStage({
material,
title,
refs,
+ transcript,
transcriptUnavailable,
chaptersOnly,
activeLocator,
@@ -43,6 +60,7 @@ export function MediaReadingStage({
material: ReadingLibraryMaterial;
title: string;
refs: UnitReference[];
+ transcript: TranscriptRow[];
transcriptUnavailable: boolean;
chaptersOnly: boolean;
activeLocator: number;
@@ -52,6 +70,8 @@ export function MediaReadingStage({
const videoRef = useRef<HTMLVideoElement | null>(null);
const audioRef = useRef<HTMLAudioElement | null>(null);
const controllerRef = useRef<ReadingMediaController | null>(null);
+ const mediaStageRef = useRef<HTMLDivElement | null>(null);
+ const transcriptListRef = useRef<HTMLDivElement | null>(null);
const onLocatorChangeRef = useRef(onLocatorChange);
const activeLocatorRef = useRef(activeLocator);
const playbackLocatorRef = useRef(0);
@@ -70,7 +90,22 @@ export function MediaReadingStage({
const [duration, setDuration] = useState(material.duration_seconds || 0);
const [startSeconds, setStartSeconds] = useState(sourceEntryTime);
const [playerError, setPlayerError] = useState("");
+ const [followTranscript, setFollowTranscript] = useState(true);
+ const [transcriptQuery, setTranscriptQuery] = useState("");
+ const [selectedTranscriptMatch, setSelectedTranscriptMatch] = useState(-1);
+ const [isFullscreen, setIsFullscreen] = useState(false);
const activeRef = refs.find((row) => row.locator === activeLocator);
+ const normalizedTranscriptQuery = transcriptQuery.trim();
+ const transcriptMatches = useMemo(
+ () => transcriptMatchIndexes(transcript, normalizedTranscriptQuery),
+ [transcript, normalizedTranscriptQuery],
+ );
+ const activeTranscriptIndex = transcript.findIndex(
+ (row) => row.locator === activeLocator,
+ );
+ const activeCue = activeTranscriptIndex >= 0 ? transcript[activeTranscriptIndex] : null;
+ const nextCue =
+ activeTranscriptIndex >= 0 ? transcript[activeTranscriptIndex + 1] : null;
const timedRefs = useMemo(
() =>
refs
@@ -92,6 +127,90 @@ export function MediaReadingStage({
activeLocatorRef.current = activeLocator;
}, [activeLocator]);
+ useEffect(() => {
+ const onFullscreenChange = () =>
+ setIsFullscreen(document.fullscreenElement === mediaStageRef.current);
+ document.addEventListener("fullscreenchange", onFullscreenChange);
+ return () =>
+ document.removeEventListener("fullscreenchange", onFullscreenChange);
+ }, []);
+
+ const toggleFullscreen = useCallback(() => {
+ const node = mediaStageRef.current;
+ if (!node) return;
+ if (document.fullscreenElement === node) {
+ void document.exitFullscreen().catch(() => undefined);
+ return;
+ }
+ const request = node.requestFullscreen();
+ if (request) {
+ request.catch(() =>
+ setPlayerError(t("Fullscreen is unavailable for this player.")),
+ );
+ }
+ }, [t]);
+
+ const selectCue = useCallback(
+ (row: TranscriptRow) => {
+ const seconds = timeFromSourceHref(row.sourceHref);
+ if (seconds !== null) {
+ controllerRef.current?.seek(seconds);
+ setReadingViewport({ locator: row.locator, timeSeconds: seconds });
+ }
+ onLocatorChangeRef.current(row.locator);
+ },
+ [],
+ );
+
+ const moveTranscriptMatch = useCallback(
+ (direction: 1 | -1) => {
+ if (!transcriptMatches.length) return;
+ const next = stepTranscriptMatch(
+ selectedTranscriptMatch,
+ transcriptMatches.length,
+ direction,
+ );
+ const row = transcript[transcriptMatches[next]];
+ if (!row) return;
+ setFollowTranscript(false);
+ setSelectedTranscriptMatch(next);
+ selectCue(row);
+ window.requestAnimationFrame(() => {
+ transcriptListRef.current
+ ?.querySelector<HTMLElement>(`[data-transcript-cue="${transcriptMatches[next]}"]`)
+ ?.scrollIntoView({ block: "center" });
+ });
+ },
+ [selectCue, selectedTranscriptMatch, transcript, transcriptMatches],
+ );
+
+ useEffect(() => {
+ if (!followTranscript || !activeCue) return;
+ const list = transcriptListRef.current;
+ const activeRow = list?.querySelector<HTMLButtonElement>(
+ '[data-active-cue="true"]',
+ );
+ if (!list || !activeRow) return;
+ const targetTop = transcriptFollowScrollTop({
+ rowOffset:
+ activeRow.getBoundingClientRect().top -
+ list.getBoundingClientRect().top +
+ list.scrollTop,
+ rowHeight: activeRow.clientHeight,
+ viewportHeight: list.clientHeight,
+ contentHeight: list.scrollHeight,
+ currentScrollTop: list.scrollTop,
+ });
+ if (Math.abs(targetTop - list.scrollTop) < 1) return;
+ const prefersReducedMotion = window.matchMedia(
+ "(prefers-reduced-motion: reduce)",
+ ).matches;
+ list.scrollTo({
+ top: targetTop,
+ behavior: prefersReducedMotion ? "instant" : "smooth",
+ });
+ }, [activeCue, followTranscript]);
+
const locatorAtTime = useCallback(
(seconds: number) => {
let locator = timedRefs[0]?.locator ?? 1;
@@ -357,6 +476,9 @@ export function MediaReadingStage({
: material.source_kind === "bilibili"
? "Bilibili"
: t("Native media");
+ const visibleTranscriptIndexes = normalizedTranscriptQuery
+ ? transcriptMatches
+ : transcript.map((_, index) => index);
return (
<div className="flex h-full min-h-0 flex-col">
@@ -368,6 +490,17 @@ export function MediaReadingStage({
</p>
</div>
<div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={toggleFullscreen}
+ aria-label={
+ isFullscreen ? t("Exit fullscreen") : t("Enter fullscreen")
+ }
+ aria-pressed={isFullscreen}
+ className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--primary)]"
+ >
+ {isFullscreen ? <Minimize2 size={11} /> : <Maximize2 size={11} />}
+ </button>
{officialUrl && (
<a
href={officialUrl}
@@ -383,59 +516,125 @@ export function MediaReadingStage({
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-5 lg:p-7">
<div className="mx-auto flex h-full max-w-[980px] flex-col">
- {material.source_kind === "youtube" && youtubeId ? (
- <div className="relative aspect-video w-full overflow-hidden rounded-2xl bg-black shadow-[0_18px_50px_rgba(0,0,0,.18)]">
- <YouTubeReadingPlayer
- videoId={youtubeId}
- startSeconds={startSeconds}
- title={title}
- onController={handleController}
- onTime={handleTime}
- onPersist={persist}
- onError={handlePlayerError}
- />
- </div>
- ) : material.source_kind === "bilibili" && bilibiliSource ? (
- <div className="relative aspect-video w-full overflow-hidden rounded-2xl bg-black shadow-[0_18px_50px_rgba(0,0,0,.18)]">
- <BilibiliReadingPlayer
- key={`${material.material_id}-${Math.floor(startSeconds)}`}
- source={bilibiliSource}
- startSeconds={startSeconds}
- duration={timelineDuration}
- title={title}
- onController={handleController}
- onTime={handleTime}
- onError={handlePlayerError}
- />
- </div>
- ) : material.render_mode === "audio" ? (
- <div className="flex min-h-[260px] flex-col items-center justify-center rounded-2xl border border-[var(--border)] bg-[var(--card)] p-8 shadow-[0_18px_50px_rgba(0,0,0,.08)] dark:border-[var(--border)] dark:bg-[var(--card)]">
- <span className="mb-5 flex size-20 items-center justify-center rounded-full bg-[var(--muted)] text-[var(--primary)]">
- <FileAudio size={30} />
- </span>
- <p className="mb-5 max-w-md text-center font-serif text-[20px] font-medium">
- {title}
- </p>
- <audio
- ref={audioRef}
+ <div
+ ref={mediaStageRef}
+ data-fullscreen={isFullscreen || undefined}
+ className={`relative flex flex-col gap-3 ${
+ isFullscreen
+ ? "min-h-0 flex-1 bg-black p-3 sm:p-5"
+ : ""
+ }`}
+ >
+ {isFullscreen && (
+ <button
+ type="button"
+ onClick={toggleFullscreen}
+ aria-label={t("Exit fullscreen")}
+ className="absolute right-3 top-3 z-10 rounded-md bg-black/60 p-2 text-white hover:bg-black/80"
+ >
+ <Minimize2 size={13} />
+ </button>
+ )}
+ {material.source_kind === "youtube" && youtubeId ? (
+ <div
+ className={`relative aspect-video w-full overflow-hidden bg-black shadow-[0_18px_50px_rgba(0,0,0,.18)] ${
+ isFullscreen
+ ? "mx-auto max-h-[calc(100vh-136px)] max-w-full rounded-lg"
+ : "rounded-2xl"
+ }`}
+ >
+ <YouTubeReadingPlayer
+ videoId={youtubeId}
+ startSeconds={startSeconds}
+ title={title}
+ onController={handleController}
+ onTime={handleTime}
+ onPersist={persist}
+ onError={handlePlayerError}
+ />
+ </div>
+ ) : material.source_kind === "bilibili" && bilibiliSource ? (
+ <div
+ className={`relative aspect-video w-full overflow-hidden bg-black shadow-[0_18px_50px_rgba(0,0,0,.18)] ${
+ isFullscreen
+ ? "mx-auto max-h-[calc(100vh-136px)] max-w-full rounded-lg"
+ : "rounded-2xl"
+ }`}
+ >
+ <BilibiliReadingPlayer
+ key={`${material.material_id}-${Math.floor(startSeconds)}`}
+ source={bilibiliSource}
+ startSeconds={startSeconds}
+ duration={timelineDuration}
+ title={title}
+ onController={handleController}
+ onTime={handleTime}
+ onError={handlePlayerError}
+ />
+ </div>
+ ) : material.render_mode === "audio" ? (
+ <div className="flex min-h-[260px] flex-col items-center justify-center rounded-2xl border border-[var(--border)] bg-[var(--card)] p-8 shadow-[0_18px_50px_rgba(0,0,0,.08)] dark:border-[var(--border)] dark:bg-[var(--card)]">
+ <span className="mb-5 flex size-20 items-center justify-center rounded-full bg-[var(--muted)] text-[var(--primary)]">
+ <FileAudio size={30} />
+ </span>
+ <p className="mb-5 max-w-md text-center font-serif text-[20px] font-medium">
+ {title}
+ </p>
+ <audio
+ ref={audioRef}
+ controls
+ preload="metadata"
+ src={rawMaterialUrl(material.material_id)}
+ onError={handleUnplayable}
+ className="w-full max-w-xl"
+ />
+ </div>
+ ) : (
+ <video
+ ref={videoRef}
controls
preload="metadata"
+ poster={material.cover_url || undefined}
src={rawMaterialUrl(material.material_id)}
onError={handleUnplayable}
- className="w-full max-w-xl"
+ className={`aspect-video w-full bg-black object-contain shadow-[0_18px_50px_rgba(0,0,0,.18)] ${
+ isFullscreen ? "rounded-lg" : "rounded-2xl"
+ }`}
/>
+ )}
+
+ <div
+ aria-live="polite"
+ className="grid shrink-0 grid-cols-1 gap-1 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[11.5px] leading-[1.55] dark:border-[var(--border)] dark:bg-[var(--card)]"
+ >
+ {[activeCue, nextCue].map((row, index) =>
+ row ? (
+ <button
+ key={`${row.locator}-${index}`}
+ type="button"
+ data-testid={`media-caption-${index === 0 ? "current" : "next"}`}
+ onClick={() => selectCue(row)}
+ className={`flex min-w-0 items-baseline gap-2 rounded-md px-1 py-0.5 text-left ${
+ index === 0
+ ? "font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]"
+ }`}
+ >
+ <span className="w-9 shrink-0 text-right text-[10px] tabular-nums text-[var(--muted-foreground)]">
+ {formatMediaTime(
+ timeFromSourceHref(row.sourceHref) || 0,
+ )}
+ </span>
+ <span className="line-clamp-1 min-w-0">{row.text}</span>
+ </button>
+ ) : index === 0 ? (
+ <p key="caption-current-empty" className="truncate px-1 py-0.5 text-[var(--muted-foreground)]">
+ {transcriptUnavailable ? t("No transcript available") : t("Beginning")}
+ </p>
+ ) : null,
+ )}
</div>
- ) : (
- <video
- ref={videoRef}
- controls
- preload="metadata"
- poster={material.cover_url || undefined}
- src={rawMaterialUrl(material.material_id)}
- onError={handleUnplayable}
- className="aspect-video w-full rounded-2xl bg-black object-contain shadow-[0_18px_50px_rgba(0,0,0,.18)]"
- />
- )}
+ </div>
{(playerError || transcriptUnavailable) && (
<div className="mt-3 rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-3 text-[10.5px] leading-relaxed text-[var(--muted-foreground)] dark:border-[var(--border)] dark:bg-[var(--card)]">
@@ -501,6 +700,160 @@ export function MediaReadingStage({
</button>
</div>
</div>
+
+ <div className="mt-4 rounded-xl border border-[var(--border)] bg-[var(--card)] dark:border-[var(--border)] dark:bg-[var(--card)]">
+ <div className="flex flex-wrap items-center gap-2 border-b border-[var(--border)] px-3 py-2 dark:border-[var(--border)]">
+ <label className="relative min-w-[180px] flex-1">
+ <span className="sr-only">{t("Search transcript")}</span>
+ <Search
+ size={11}
+ className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)]"
+ />
+ <input
+ type="search"
+ value={transcriptQuery}
+ aria-label={t("Search transcript")}
+ placeholder={t("Search transcript")}
+ onChange={(event) => {
+ const next = event.target.value;
+ setTranscriptQuery(next);
+ setSelectedTranscriptMatch(-1);
+ if (next.trim()) setFollowTranscript(false);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ setTranscriptQuery("");
+ setSelectedTranscriptMatch(-1);
+ return;
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ moveTranscriptMatch(event.shiftKey ? -1 : 1);
+ }
+ }}
+ className="h-8 w-full rounded-lg border border-[var(--border)] bg-[var(--background)] pl-8 pr-2 text-[10.5px] outline-none"
+ />
+ </label>
+ {!!normalizedTranscriptQuery && (
+ <span
+ aria-live="polite"
+ className="text-[10px] tabular-nums text-[var(--muted-foreground)]"
+ >
+ {t("{{count}} transcript matches", {
+ count: transcriptMatches.length,
+ })}
+ </span>
+ )}
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ disabled={!transcriptMatches.length}
+ aria-label={t("Previous transcript match")}
+ onClick={() => moveTranscriptMatch(-1)}
+ className="rounded-md border border-[var(--border)] p-1.5 text-[var(--muted-foreground)] disabled:opacity-40"
+ >
+ <ChevronUp size={11} />
+ </button>
+ <button
+ type="button"
+ disabled={!transcriptMatches.length}
+ aria-label={t("Next transcript match")}
+ onClick={() => moveTranscriptMatch(1)}
+ className="rounded-md border border-[var(--border)] p-1.5 text-[var(--muted-foreground)] disabled:opacity-40"
+ >
+ <ChevronDown size={11} />
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ setFollowTranscript((current) => !current)
+ }
+ disabled={Boolean(normalizedTranscriptQuery)}
+ aria-pressed={followTranscript}
+ className={`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[10px] font-medium disabled:cursor-not-allowed disabled:opacity-40 ${
+ followTranscript
+ ? "border-[var(--primary)] text-[var(--primary)]"
+ : "border-[var(--border)] text-[var(--muted-foreground)]"
+ }`}
+ >
+ <ChevronsDown size={11} />
+ {t("Follow playback")}
+ </button>
+ </div>
+ </div>
+ <div
+ ref={transcriptListRef}
+ data-testid="reading-media-transcript-list"
+ className="max-h-[min(48vh,460px)] min-h-[180px] overflow-y-auto p-2"
+ onWheel={() => setFollowTranscript(false)}
+ onTouchMove={() => setFollowTranscript(false)}
+ onPointerDown={(event) => {
+ if (event.target === event.currentTarget)
+ setFollowTranscript(false);
+ }}
+ onKeyDown={(event) => {
+ if (
+ ["ArrowDown", "ArrowUp", "PageDown", "PageUp", "Home", "End"].includes(
+ event.key,
+ )
+ )
+ setFollowTranscript(false);
+ }}
+ >
+ {transcriptUnavailable ? (
+ <p className="p-3 text-[10.5px] text-[var(--muted-foreground)]">
+ {chaptersOnly
+ ? t("Only chapter markers are available for this video.")
+ : t("No transcript cues available.")}
+ </p>
+ ) : normalizedTranscriptQuery && transcriptMatches.length === 0 ? (
+ <p className="p-3 text-[10.5px] text-[var(--muted-foreground)]">
+ {t("No transcript matches.")}
+ </p>
+ ) : transcript.length === 0 ? (
+ <p className="p-3 text-[10.5px] text-[var(--muted-foreground)]">
+ {t("No transcript cues available.")}
+ </p>
+ ) : (
+ <div className="space-y-0.5">
+ {visibleTranscriptIndexes.map((index) => {
+ const row = transcript[index];
+ const active = row.locator === activeLocator;
+ const selectedMatch =
+ Boolean(normalizedTranscriptQuery) &&
+ transcriptMatches[selectedTranscriptMatch] === index;
+ return (
+ <button
+ key={`${row.locator}-${row.sourceHref}`}
+ type="button"
+ data-active-cue={active ? "true" : undefined}
+ data-transcript-cue={index}
+ onClick={() => {
+ setFollowTranscript(false);
+ selectCue(row);
+ }}
+ className={`flex w-full items-baseline gap-2 rounded-md px-2 py-1 text-left text-[10.5px] ${
+ active
+ ? "bg-[color-mix(in_srgb,var(--primary)_10%,transparent)] text-[var(--primary)]"
+ : selectedMatch
+ ? "bg-[color-mix(in_srgb,var(--primary)_7%,transparent)] text-[var(--foreground)]"
+ : "text-[var(--foreground)] hover:bg-[var(--muted)]"
+ }`}
+ >
+ <span className="w-9 shrink-0 text-right text-[10px] tabular-nums text-[var(--muted-foreground)]">
+ {row.title}
+ </span>
+ <span className="line-clamp-2 min-w-0 leading-[1.5]">
+ {row.text}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
</div>
</div>
</div>
diff --git a/web/components/reading/workspace/ReadingWorkspace.tsx b/web/components/reading/workspace/ReadingWorkspace.tsx
index b8060c331..fd9fb8b26 100644
--- a/web/components/reading/workspace/ReadingWorkspace.tsx
+++ b/web/components/reading/workspace/ReadingWorkspace.tsx
@@ -596,6 +596,7 @@ export function ReadingWorkspacePage() {
material={activeTab.material}
title={activeTab.material.title}
refs={material?.unit_refs ?? []}
+ transcript={material?.unit === "segment" ? transcript : []}
transcriptUnavailable={transcriptUnavailable}
chaptersOnly={chaptersOnly}
activeLocator={activeLocator}
diff --git a/web/components/watching/WatchingBrowser.tsx b/web/components/watching/WatchingBrowser.tsx
index dc22efa47..617e3c327 100644
--- a/web/components/watching/WatchingBrowser.tsx
+++ b/web/components/watching/WatchingBrowser.tsx
@@ -28,9 +28,13 @@ type BrowserView = "feed" | "playlists" | "search" | "playlist";
export function WatchingBrowser({
onDismiss,
canDismiss,
+ selectionMode = false,
+ onSelectUrl,
}: {
onDismiss(): void;
canDismiss: boolean;
+ selectionMode?: boolean;
+ onSelectUrl?(url: string): void;
}) {
const { t } = useTranslation();
const router = useRouter();
@@ -179,23 +183,28 @@ export function WatchingBrowser({
}
function select(url: string) {
remember(scroll.current?.scrollTop || 0);
- router.push(`/watching?video=${encodeURIComponent(url)}`);
+ if (onSelectUrl) onSelectUrl(url);
+ else router.push(`/watching?video=${encodeURIComponent(url)}`);
onDismiss();
}
return (
<section className="watching-browser" aria-label={t("Browse videos")}>
<header className="flex flex-wrap items-center justify-between gap-3 border-b border-[var(--border)] p-5">
<div>
- <h1 className="text-xl font-semibold">{t("Immersive Watching")}</h1>
+ <h1 className="text-xl font-semibold">
+ {selectionMode ? t("Browse Invidious") : t("Immersive Watching")}
+ </h1>
<p className="mt-1 text-sm text-[var(--muted-foreground)]">
- {t("Your videos, with room to learn.")}
+ {selectionMode
+ ? t("Choose a video to add to this collection.")
+ : t("Your videos, with room to learn.")}
</p>
</div>
<div className="flex items-center gap-2 text-sm">
{canDismiss && (
<button className="watching-browser-button" onClick={onDismiss}>
<ArrowLeft size={16} />
- {t("Back to video")}
+ {selectionMode ? t("Close") : t("Back to video")}
</button>
)}
<button
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ea72027d8..5977db82b 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2120,6 +2120,8 @@
"Create one to upload documents and retrieve grounded context in chat.": "Create one to upload documents and retrieve grounded context in chat.",
"docs": "docs",
"Exit fullscreen": "Exit fullscreen",
+ "Enter fullscreen": "Enter fullscreen",
+ "Fullscreen is unavailable for this player.": "Fullscreen is unavailable for this player.",
"Move to…": "Move to…",
"Move to": "Move to",
"Root": "Root",
@@ -3063,6 +3065,12 @@
"The attachment could not be downloaded.": "The attachment could not be downloaded.",
"The attachment could not be opened in Immersive Reading.": "The attachment could not be opened in Immersive Reading.",
"No transcript available": "No transcript available",
+ "No transcript cues available.": "No transcript cues available.",
+ "No transcript matches.": "No transcript matches.",
+ "Next transcript match": "Next transcript match",
+ "Previous transcript match": "Previous transcript match",
+ "Search transcript": "Search transcript",
+ "{{count}} transcript matches": "{{count}} transcript matches",
"Playback still works. Transcript-grounded explanation and timestamp search are unavailable for this video.": "Playback still works. Transcript-grounded explanation and timestamp search are unavailable for this video.",
"Native media": "Native media",
"Open official": "Open official",
@@ -3472,6 +3480,7 @@
"This material could not be opened.": "This material could not be opened.",
"Notes organized, each one citing where it came from.": "Notes organized, each one citing where it came from.",
"Search this material": "Search this material",
+ "Only chapter markers are available for this video.": "Only chapter markers are available for this video.",
"This material has no outline to navigate yet.": "This material has no outline to navigate yet.",
"The outline appears once processing finishes.": "The outline appears once processing finishes.",
"Add material to begin a reading conversation.": "Add material to begin a reading conversation.",
@@ -3603,6 +3612,8 @@
"Retry captions": "Retry captions",
"Explain here": "Explain here",
"Follow playback": "Follow playback",
+ "Browse Invidious": "Browse Invidious",
+ "Choose a video to add to this collection.": "Choose a video to add to this collection.",
"YouTube playback failed.": "YouTube playback failed.",
"YouTube learning video": "YouTube learning video",
"The configured Invidious stream could not be played.": "The configured Invidious stream could not be played.",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 702df3f39..b1e2e2e34 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2120,6 +2120,8 @@
"Create one to upload documents and retrieve grounded context in chat.": "创建一个知识库,上传文档,在对话中检索有依据的内容。",
"docs": "篇文档",
"Exit fullscreen": "退出全屏",
+ "Enter fullscreen": "进入全屏",
+ "Fullscreen is unavailable for this player.": "此播放器不支持全屏。",
"Move to…": "移动到…",
"Move to": "移动到",
"Root": "根目录",
@@ -3063,6 +3065,12 @@
"The attachment could not be downloaded.": "无法下载该附件。",
"The attachment could not be opened in Immersive Reading.": "无法在沉浸式阅读中打开该附件。",
"No transcript available": "暂无可用字幕",
+ "No transcript cues available.": "没有可用的字幕行。",
+ "No transcript matches.": "没有匹配的字幕。",
+ "Next transcript match": "下一个字幕匹配",
+ "Previous transcript match": "上一个字幕匹配",
+ "Search transcript": "搜索字幕",
+ "{{count}} transcript matches": "{{count}} 条字幕匹配",
"Playback still works. Transcript-grounded explanation and timestamp search are unavailable for this video.": "视频仍可正常播放,但当前无法进行基于字幕的讲解与时间戳搜索。",
"Native media": "原生媒体",
"Open official": "在官方页面打开",
@@ -3472,6 +3480,7 @@
"This material could not be opened.": "无法打开这份资料。",
"Notes organized, each one citing where it came from.": "笔记已整理,每条都标注了出处。",
"Search this material": "搜索这份资料",
+ "Only chapter markers are available for this video.": "这个视频只有章节标记可用。",
"This material has no outline to navigate yet.": "这份资料还没有可导航的目录。",
"The outline appears once processing finishes.": "解析完成后会显示目录。",
"Add material to begin a reading conversation.": "添加资料后开始阅读对话。",
@@ -3603,6 +3612,8 @@
"Retry captions": "重试字幕",
"Explain here": "解释此处",
"Follow playback": "跟随播放",
+ "Browse Invidious": "浏览 Invidious",
+ "Choose a video to add to this collection.": "选择要添加到这个资料组的视频。",
"YouTube playback failed.": "YouTube 播放失败。",
"YouTube learning video": "YouTube 学习视频",
"The configured Invidious stream could not be played.": "无法播放已配置的 Invidious 视频流。",
diff --git a/web/tests/media-reading-stage.spec.tsx b/web/tests/media-reading-stage.spec.tsx
new file mode 100644
index 000000000..f57243e0e
--- /dev/null
+++ b/web/tests/media-reading-stage.spec.tsx
@@ -0,0 +1,192 @@
+import React from "react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MediaReadingStage } from "@/components/reading/workspace/MediaReadingStage";
+import type { ReadingLibraryMaterial } from "@/lib/reading-workspace-api";
+import type { TranscriptRow } from "@/components/reading/workspace/types";
+
+const mock = vi.hoisted(() => ({
+ currentTime: 0,
+ seeks: [] as number[],
+ getPosition: vi.fn(),
+ savePosition: vi.fn(),
+ select: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/lib/reading-api", () => ({
+ getReadingPosition: mock.getPosition,
+ saveReadingPosition: mock.savePosition,
+ rawMaterialUrl: (id: string) => `/materials/${id}/raw`,
+}));
+
+vi.mock("@/components/reading/workspace/YouTubeReadingPlayer", () => ({
+ YouTubeReadingPlayer(props: {
+ onController(controller: unknown): void;
+ onTime(seconds: number, duration: number): void;
+ }) {
+ React.useEffect(() => {
+ props.onController({
+ currentTime: () => mock.currentTime,
+ duration: () => 180,
+ seek: (seconds: number) => mock.seeks.push(seconds),
+ tracksPosition: true,
+ });
+ props.onTime(mock.currentTime, 180);
+ }, [props]);
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ mock.currentTime = 65;
+ props.onTime(mock.currentTime, 180);
+ }}
+ >
+ emit playback
+ </button>
+ );
+ },
+}));
+
+const material: ReadingLibraryMaterial = {
+ material_id: "media-1",
+ content_id: "content-1",
+ filename: "lecture.mp4",
+ title: "Lecture",
+ source_kind: "youtube",
+ source_url: "https://www.youtube.com/watch?v=abc123xyz00",
+ mime: "video/youtube",
+ render_mode: "video",
+ cover_url: "",
+ duration_seconds: 180,
+ status: "ready",
+ progress: 1,
+ error_code: "",
+ error_detail: "",
+ created_at: 1,
+ updated_at: 1,
+ last_opened_at: 1,
+};
+
+const refs = [0, 30, 65].map((seconds, index) => ({
+ locator: index + 1,
+ title: `0:${String(seconds).padStart(2, "0")}`,
+ source_href: `#t=${seconds}`,
+}));
+
+const transcript: TranscriptRow[] = [
+ { locator: 1, title: "0:00", text: "Opening sentence", sourceHref: "#t=0" },
+ { locator: 2, title: "0:30", text: "Middle passage", sourceHref: "#t=30" },
+ { locator: 3, title: "1:05", text: "Later passage", sourceHref: "#t=65" },
+];
+
+function renderStage(activeLocator = 1) {
+ const onLocatorChange = vi.fn();
+ const view = render(
+ <MediaReadingStage
+ material={material}
+ title="Lecture"
+ refs={refs}
+ transcript={transcript}
+ transcriptUnavailable={false}
+ chaptersOnly={false}
+ activeLocator={activeLocator}
+ onLocatorChange={onLocatorChange}
+ />,
+ );
+ return { onLocatorChange, view };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mock.currentTime = 0;
+ mock.seeks = [];
+ mock.getPosition.mockResolvedValue({ locator: 1, source_anchor: "#t=0" });
+ mock.savePosition.mockResolvedValue(undefined);
+});
+
+describe("MediaReadingStage", () => {
+ it("shows the current and next caption and seeks from either line", () => {
+ renderStage();
+ expect(screen.getByTestId("media-caption-current")).toHaveTextContent(
+ "Opening sentence",
+ );
+ expect(screen.getByTestId("media-caption-next")).toHaveTextContent(
+ "Middle passage",
+ );
+
+ fireEvent.click(screen.getByTestId("media-caption-next"));
+ expect(mock.seeks).toContain(30);
+ });
+
+ it("searches the transcript and advances wrapping matches", () => {
+ const { onLocatorChange } = renderStage();
+ const input = screen.getByLabelText("Search transcript");
+
+ fireEvent.change(input, { target: { value: "missing" } });
+ expect(screen.getByText("No transcript matches.")).toBeVisible();
+ expect(screen.getByLabelText("Next transcript match")).toBeDisabled();
+
+ fireEvent.change(input, { target: { value: "later" } });
+ fireEvent.click(screen.getByLabelText("Next transcript match"));
+
+ expect(mock.seeks).toContain(65);
+ expect(onLocatorChange).toHaveBeenCalledWith(3);
+ });
+
+ it("follows playback, pauses on reader scroll, and resumes on request", async () => {
+ const { onLocatorChange, view } = renderStage();
+ const list = await screen.findByTestId("reading-media-transcript-list");
+ list.scrollTo = vi.fn();
+ Object.defineProperty(list, "clientHeight", { value: 200 });
+ Object.defineProperty(list, "scrollHeight", { value: 900 });
+ list.getBoundingClientRect = () =>
+ ({ top: 0, height: 200 }) as DOMRect;
+
+ list
+ .querySelectorAll("button")
+ .forEach(
+ (row) => {
+ row.getBoundingClientRect = () =>
+ ({ top: 150, height: 20 }) as DOMRect;
+ Object.defineProperty(row, "clientHeight", { value: 20 });
+ },
+ );
+ fireEvent.click(screen.getByRole("button", { name: "emit playback" }));
+ view.rerender(
+ <MediaReadingStage
+ material={material}
+ title="Lecture"
+ refs={refs}
+ transcript={transcript}
+ transcriptUnavailable={false}
+ chaptersOnly={false}
+ activeLocator={3}
+ onLocatorChange={onLocatorChange}
+ />,
+ );
+
+ await waitFor(() => expect(list.scrollTo).toHaveBeenCalled());
+ fireEvent.wheel(list);
+ expect(
+ screen.getByRole("button", { name: "Follow playback" }),
+ ).toHaveAttribute("aria-pressed", "false");
+
+ fireEvent.click(screen.getByRole("button", { name: "Follow playback" }));
+ expect(
+ screen.getByRole("button", { name: "Follow playback" }),
+ ).toHaveAttribute("aria-pressed", "true");
+ });
+
+ it("opens the media stage in fullscreen", () => {
+ const requestFullscreen = vi.fn().mockResolvedValue(undefined);
+ HTMLElement.prototype.requestFullscreen = requestFullscreen;
+ renderStage();
+
+ fireEvent.click(screen.getByLabelText("Enter fullscreen"));
+ expect(requestFullscreen).toHaveBeenCalled();
+ });
+});
diff --git a/web/tests/reading-add-invidious.spec.tsx b/web/tests/reading-add-invidious.spec.tsx
new file mode 100644
index 000000000..e14f61f38
--- /dev/null
+++ b/web/tests/reading-add-invidious.spec.tsx
@@ -0,0 +1,88 @@
+import React from "react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { AddMaterialsDialog } from "@/components/reading/library/AddMaterialsDialog";
+
+const mock = vi.hoisted(() => ({
+ addMaterial: vi.fn(),
+ checkDuplicates: vi.fn(),
+ createWorkspace: vi.fn(),
+ importUrls: vi.fn(),
+ listLibrary: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/components/watching/WatchingBrowser", () => ({
+ WatchingBrowser: ({ onSelectUrl, onDismiss }: {
+ onSelectUrl?(url: string): void;
+ onDismiss(): void;
+ }) => (
+ <button
+ type="button"
+ onClick={() => {
+ onSelectUrl?.("https://youtu.be/abc123xyz00");
+ onDismiss();
+ }}
+ >
+ Select video
+ </button>
+ ),
+}));
+
+vi.mock("@/lib/reading-api", () => ({
+ uploadMaterial: vi.fn(),
+}));
+
+vi.mock("@/lib/reading-workspace-api", () => ({
+ addReadingWorkspaceMaterial: mock.addMaterial,
+ checkReadingDuplicates: mock.checkDuplicates,
+ createReadingWorkspace: mock.createWorkspace,
+ importReadingUrls: mock.importUrls,
+ listReadingLibraryMaterials: mock.listLibrary,
+ readingContentId: vi.fn(),
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mock.checkDuplicates.mockResolvedValue([]);
+ mock.importUrls.mockResolvedValue({
+ workspace: { workspace_id: "workspace-1" },
+ });
+});
+
+describe("Reading Add Materials Invidious entry", () => {
+ it("imports a selected video through Reading instead of the Watching route", async () => {
+ const onDone = vi.fn();
+ render(
+ <AddMaterialsDialog
+ mode="add"
+ workspaceId="workspace-1"
+ onClose={vi.fn()}
+ onDone={onDone}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Browse Invidious" }));
+ fireEvent.click(screen.getByRole("button", { name: "Select video" }));
+ await waitFor(() =>
+ expect(mock.importUrls).toHaveBeenCalledWith({
+ urls: ["https://youtu.be/abc123xyz00"],
+ workspace_id: "workspace-1",
+ }),
+ );
+ await waitFor(() =>
+ expect(onDone).toHaveBeenCalledWith({
+ workspace: { workspace_id: "workspace-1" },
+ }),
+ );
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("button", { name: "Select video" }),
+ ).toBeNull(),
+ );
+ expect(mock.addMaterial).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/tests/watching-browser.spec.tsx b/web/tests/watching-browser.spec.tsx
index 383e2c877..fd958bb73 100644
--- a/web/tests/watching-browser.spec.tsx
+++ b/web/tests/watching-browser.spec.tsx
@@ -46,6 +46,27 @@ describe("Watching account browser", () => {
);
expect(mock.browse.mock.calls[0][0]).toBe("feed");
});
+
+ it("returns a selection to Reading instead of opening the Watching route", async () => {
+ const onSelectUrl = vi.fn();
+ render(
+ <WatchingBrowser
+ canDismiss
+ selectionMode
+ onSelectUrl={onSelectUrl}
+ onDismiss={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Neural networks/ }),
+ );
+
+ expect(onSelectUrl).toHaveBeenCalledWith(
+ "https://www.youtube.com/watch?v=aircAruvnKk",
+ );
+ expect(mock.push).not.toHaveBeenCalled();
+ });
it("allows anonymous search and guides account-only browsing", async () => {
mock.account.mockResolvedValue({ connected: false });
render(<WatchingBrowser canDismiss={false} onDismiss={vi.fn()} />);