"use client"; import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react"; import CopyButton from "@/components/CopyButton"; import { buttonVariants } from "@/components/ui/button"; import { citedKey, type CitedFetchAnswer, type CitedPlay, type CitedTarget } from "@/lib/clips/types"; import { spanClock } from "@/lib/clips/words"; import { cn } from "@/lib/utils"; import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import StoredUrlOption from "./StoredUrlOption"; import CensorOverlay from "@/components/projects/review/CensorOverlay"; // --------------------------------------------------------------------------- // THE CITED CLIP (release 32 R1): the seconds a citation names, played so a // person can hear -- and see -- that the words are there. The one place a // human has to verify, and it needs no model. // // video first a clip window or saved video covering the span, seeked to // the cited second; "Play span" plays from the span's start // and stops at its end; replay is the same press // audio when only audio holds it, with an "audio only" label // Fetch clip when nothing on disk does: one press asks the editor // (/api/cited/fetch -> the editor's fetch-window, as the MCP's // fetch_clip asks), shows its progress, plays when it lands; // a failure is said plainly (a rate limit, corrupt audio); // beside it, "Cut from the stored media URL" when the record // stores one (release 32 R6, StoredUrlOption) // // Two faces: `panel` (native controls, the evidence panel and the reader) and // `card` (the audition deck's: no chrome, tap replays, a span-only scrubber). // Its buttons never take focus, and the media gives it back, so a page's own // keys (approve, reject, j/k) keep working after a play. // --------------------------------------------------------------------------- export type CitedClipHandle = { /** Play the span from its start; pause when playing. */ togglePlay: () => void; /** Play the span from its start, always. */ playSpan: () => void; /** Seek to a source second and play from there. */ seek: (t: number) => void; }; type Looked = { play: CitedPlay | null; fetchLine?: string }; const lookups = new Map>(); function lookup(t: CitedTarget, fresh = false): Promise { const key = citedKey(t); if (fresh) lookups.delete(key); let p = lookups.get(key); if (!p) { const q = new URLSearchParams({ channel: t.channel, video: t.video, from: String(t.from), to: String(t.to) }); if (t.project && t.clip) { q.set("project", t.project); q.set("clip", t.clip); } if (t.audio) q.set("audio", "1"); p = fetch(`/api/cited/play?${q}`, { cache: "no-store" }).then(async (r) => { const j = await r.json(); if (!r.ok) throw new Error(j.error ?? r.statusText); return j as Looked; }); p.catch(() => lookups.delete(key)); lookups.set(key, p); } return p; } /** Ask what plays a span before it is shown (the card after the next). */ export function warmCited(t: CitedTarget): void { void lookup(t).catch(() => {}); } const stopTyping = "input, textarea, select, button, a[href], [contenteditable=''], [contenteditable='true']"; const CitedClip = forwardRef< CitedClipHandle, { target: CitedTarget; /** Known already (the evidence route found it): undefined looks it up, null is a known miss. */ initial?: CitedPlay | null; fetchLine?: string; /** Why these seconds are wanted: stored beside the window. */ reason?: string; report?: string; face?: "panel" | "card"; /** Play the span as soon as it can. */ autoPlay?: boolean; /** Load the media now (the card underneath). */ preload?: boolean; /** Space plays the span (from anywhere that is not a control). */ keys?: boolean; /** The source second, as it plays (the lit line follows it). */ onTime?: (t: number) => void; /** Whether something can play now. */ onPlayable?: (playable: boolean) => void; className?: string; } >(function CitedClip( { target, initial, fetchLine: givenLine, reason, report, face = "panel", autoPlay = false, preload = false, keys = false, onTime, onPlayable, className }, ref, ) { const [play, setPlay] = useState(initial); const [line, setLine] = useState(givenLine); const [lookError, setLookError] = useState(null); const [fetching, setFetching] = useState(null); const [fromStored, setFromStored] = useState(false); const [now, setNow] = useState(target.from); const [picAspect, setPicAspect] = useState(null); const [playing, setPlaying] = useState(false); const media = useRef(null); const spanning = useRef(false); const wantPlay = useRef(autoPlay); const key = citedKey(target); useEffect(() => { if (initial !== undefined) return; let live = true; lookup(target) .then((l) => { if (!live) return; setPlay(l.play); if (l.fetchLine && !givenLine) setLine(l.fetchLine); }) .catch((e) => live && setLookError(e instanceof Error ? e.message : String(e))); return () => { live = false; }; // `target` is named by its key. // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, initial]); useEffect(() => onPlayable?.(!!play), [play, onPlayable]); useEffect(() => { wantPlay.current = autoPlay; if (autoPlay && media.current && media.current.readyState >= 1) playSpanNow(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [autoPlay]); // File time of a source second: the span starts `offset` into the file. const fileT = useCallback((t: number) => (play ? Math.max(0, t - target.from + play.offset) : 0), [play, target.from]); const sourceT = useCallback((ft: number) => (play ? ft - play.offset + target.from : target.from), [play, target.from]); const giveBackFocus = () => { const a = document.activeElement as HTMLElement | null; if (a && media.current && (a === media.current || media.current.contains(a))) a.blur(); }; const playSpanNow = useCallback(() => { const m = media.current; if (!m) return; m.currentTime = fileT(target.from); spanning.current = true; void m.play().catch(() => {}); }, [fileT, target.from]); const api: CitedClipHandle = { playSpan: playSpanNow, togglePlay: () => { const m = media.current; if (!m) return; if (m.paused) playSpanNow(); else m.pause(); }, seek: (t: number) => { const m = media.current; if (!m) return; m.currentTime = fileT(t); spanning.current = t < target.to; void m.play().catch(() => {}); }, }; useImperativeHandle(ref, () => api); useEffect(() => { if (!keys) return; const onKey = (e: KeyboardEvent) => { if (e.key !== " " || e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; const t = e.target as HTMLElement | null; if (t?.closest?.(stopTyping) || t?.closest?.("dialog[open]")) return; if (!media.current) return; e.preventDefault(); api.togglePlay(); }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }); const runFetch = async () => { setFetching({ state: "asking" }); const body = { ...target, reason: reason ?? "umtool: play the cited span", ...(report ? { report } : {}), ...(fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), }; try { let r = await fetch("/api/cited/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); let a = (await r.json()) as CitedFetchAnswer & { error?: string }; for (let polls = 0; r.ok && a.state === "queued" && polls < 600; polls++) { setFetching(a); await new Promise((res) => setTimeout(res, 1000)); r = await fetch("/api/cited/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...target, job: a.job }) }); a = (await r.json()) as CitedFetchAnswer & { error?: string }; } if (!r.ok) { setFetching({ state: "failed", message: a.error ?? `HTTP ${r.status}` }); return; } setFetching(a); if (a.state === "ready") { const found = a.play ?? (await lookup(target, true)).play; lookups.set(key, Promise.resolve({ play: found, ...(line ? { fetchLine: line } : {}) })); wantPlay.current = true; setPlay(found); if (!found) setFetching({ state: "failed", message: "the editor fetched it, but nothing on this disk plays the span" }); } } catch (e) { setFetching({ state: "failed", message: e instanceof Error ? e.message : String(e) }); } }; const span = Math.max(0.001, target.to - target.from); const rel = Math.min(span, Math.max(0, now - target.from)); const card = face === "card"; const status = fetching && fetching.state !== "asking" ? ( {fetching.state === "ready" ? `Clip ${fetching.cached ? "already held" : "fetched"}` : fetching.state === "queued" ? `The editor is fetching it (${fetching.status})…` : fetching.message} ) : null; const mediaProps = { ref: (el: HTMLMediaElement | null) => { media.current = el; }, src: play?.url, preload: preload || autoPlay ? "auto" : "metadata", "data-player": "", tabIndex: -1, onLoadedMetadata: (e: React.SyntheticEvent) => { e.currentTarget.currentTime = play ? (card ? play.offset : Math.max(0, play.offset - (play.kind === "prepared" ? play.offset : 3))) : 0; const el = e.currentTarget; if (el instanceof HTMLVideoElement && el.videoWidth > 0 && el.videoHeight > 0) setPicAspect(el.videoWidth / el.videoHeight); if (wantPlay.current) playSpanNow(); }, onTimeUpdate: (e: React.SyntheticEvent) => { const t = sourceT(e.currentTarget.currentTime); setNow(t); onTime?.(t); if (spanning.current && t >= target.to) { spanning.current = false; e.currentTarget.pause(); } }, onPlay: () => { setPlaying(true); giveBackFocus(); }, onPause: () => { setPlaying(false); giveBackFocus(); }, onSeeked: giveBackFocus, }; const noFocus = (e: React.MouseEvent) => e.preventDefault(); return (
{play ? ( <> {play.audio ? (
{card && ( )}
) : (
)}
{card ? ( api.seek(target.from + Number(e.target.value))} onPointerUp={(e) => e.currentTarget.blur()} className="min-w-0 flex-1 accent-[var(--signal)]" /> ) : ( <> {playing && ( )} )} {spanClock(rel)} / {spanClock(span)} {play.audio && ( audio only )} {!card && {play.label}}
) : play === null ? (
Not on disk
{status} {!card && line && (
or with the MCP {line}
)}
) : (
{lookError ? {lookError} : "looking for the clip…"}
)} {play && status}
); }); export default CitedClip;