"use client"; import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { narrationHref, playHref, postBenchHref } from "@/lib/hrefs"; // --------------------------------------------------------------------------- // THE READS PANEL (lane reads-find): every line a voice reads in this video, from GET /api/report/reads (`umtool // reads

--json`). Find searches what is SPOKEN only; Replace offers two scopes, each previewed before it is // applied, and neither synthesizes; Re-read queues the changed lines on the app's queue (one step per item, each the // bench's own command); Listen through plays the re-reads one after another, each with what played before one press // away and a Pick on either. Every button is a form and a job; nothing here asks a model. // --------------------------------------------------------------------------- type Take = { index: number | null; takeFile?: string | null; file: string | null; files?: string[]; key: string | null; reading: number; tuning: Record | null; tunedBy: string | null } | null; type Read = { id: string; kind: "post" | "thread" | "screen" | "card"; item: string; role: string | null; character: { id: string; name: string } | null; voice: string | null; spoken: string; said: string | null; storedAt: string | null; editable: boolean; why: string | null; queueable?: boolean; state: string; because: string[]; take: Take; newTake: Take; matches?: { start: number; end: number }[]; }; type QueueRow = { read: string; item: string; kind: string; qid: string; state: string; error: string | null; before: Take; batch: string }; type Queue = { rows: QueueRow[]; waiting: string | null; counts: Record; batch: string | null }; type Undo = { scope: "reads" | "say"; available: boolean; why: string | null; entry?: { word: string; say: string }; was?: { word: string; say: string } | null } | null; type View = { counts: Record; reads: Read[]; find?: { matches: number; lines: number }; queue: Queue; undo: Undo }; type Line = { id: string; kind: string; item: string; before: string; after: string; creates: string | null }; type Preview = | { scope: "reads"; lines: Line[]; skipped: { id: string; why: string }[]; notes: Record; refused: Record; matches: number; token: string } | { scope: "say"; entry: { word: string; say: string }; was: string | null; stale: { id: string }[]; cards: string[]; matches: number }; const KIND: Record = { post: "post script", thread: "thread part", screen: "screen line", card: "card narration" }; const BECAUSE: Record = { words: "other words", lexicon: "the lexicon", settings: "other settings", voice: "another voice" }; const STATE_CLASS: Record = { fresh: "text-text-2", stale: "text-doubt-text", unpicked: "text-[var(--color-sel)]", none: "text-muted", recorded: "text-muted" }; const btn = buttonVariants({ variant: "outline", size: "sm" }); async function post(body: Record) { const r = await fetch("/api/report/reads", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).catch(() => null); const j = (await r?.json().catch(() => null)) as Record | null; if (!r?.ok) throw new Error(String(j?.error ?? (r ? `HTTP ${r.status}` : "umtool could not be reached"))); return j ?? {}; } /** A read's spoken text with its matches marked. */ function Marked({ text, matches }: { text: string; matches?: { start: number; end: number }[] }) { if (!matches?.length) return <>{text}; const out: React.ReactNode[] = []; let at = 0; matches.forEach((m, i) => { out.push(text.slice(at, m.start)); out.push({text.slice(m.start, m.end)}); at = m.end; }); out.push(text.slice(at)); return <>{out.map((x, i) => {x})}; } export default function ReadsPanel({ project, initialState = "all", initialCharacter = null }: { project: string; initialState?: "all" | "stale"; initialCharacter?: string | null }) { const [view, setView] = useState(null); const [error, setError] = useState(null); const [notice, setNotice] = useState(null); const [busy, setBusy] = useState(false); const [state, setState] = useState<"all" | "stale">(initialState); const [character, setCharacter] = useState(initialCharacter); const [find, setFind] = useState(""); const [matchCase, setMatchCase] = useState(false); const [word, setWord] = useState(false); const [to, setTo] = useState(""); const [preview, setPreview] = useState(null); const [skip, setSkip] = useState>(new Set()); const [ticked, setTicked] = useState>(new Set()); const [characters, setCharacters] = useState<{ id: string; name: string }[]>([]); const load = useCallback(async () => { const q = new URLSearchParams({ project }); if (find.trim()) q.set("find", find); if (matchCase) q.set("case", "1"); if (word) q.set("word", "1"); if (state === "stale") q.set("stale", "1"); if (character) q.set("character", character); const r = await fetch(`/api/report/reads?${q}`, { cache: "no-store" }).catch(() => null); const j = (await r?.json().catch(() => null)) as (View & { error?: string }) | null; if (!r?.ok || !j) { setError(j?.error ?? "the reads could not be read"); return; } setError(null); setView(j); setCharacters((had) => { const all = new Map(had.map((c) => [c.id, c])); for (const x of j.reads) if (x.character) all.set(x.character.id, x.character); return [...all.values()].sort((a, b) => a.name.localeCompare(b.name)); }); }, [project, find, matchCase, word, state, character]); useEffect(() => { const t = setTimeout(() => void load(), find ? 250 : 0); return () => clearTimeout(t); }, [load, find]); // The queue fills in as each re-read lands: polled while anything waits or runs. const going = !!view && (view.queue.counts.waiting > 0 || view.queue.counts.running > 0); useEffect(() => { if (!going) return; const t = setInterval(() => void load(), 2500); return () => clearInterval(t); }, [going, load]); // A new find or replace text: the preview is of other words now. useEffect(() => setPreview(null), [find, to, matchCase, word]); const run = async (what: () => Promise) => { if (busy) return; setBusy(true); setError(null); setNotice(null); try { await what(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); void load(); } }; const ask = (scope: "reads" | "say") => run(async () => { // These reads previews the rows Find counted in this view (its filter too) -- never every match of the video. const j = await post({ project, op: "preview", from: find, to, scope, case: matchCase, word, ...(scope === "reads" ? { only: reads.map((r) => r.id) } : {}) }); setPreview({ ...(j as object), scope } as Preview); setSkip(new Set()); }); const apply = () => run(async () => { if (!preview) return; const only = preview.scope === "reads" ? preview.lines.map((l) => l.id).filter((id) => !skip.has(id)) : []; if (preview.scope === "reads" && !only.length) throw new Error("no line is ticked"); // Apply goes with its preview's token: the draft changed since, and it is refused ("preview again"). await post({ project, op: "replace", from: find, to, scope: preview.scope, case: matchCase, word, ...(preview.scope === "reads" ? { only, token: preview.token } : {}) }); setNotice(preview.scope === "reads" ? `rewritten: ${only.length} read${only.length === 1 ? "" : "s"} (the shown text untouched) -- they are stale now` : `"${preview.entry.word}" is said "${preview.entry.say}" in every read of a post now -- ${preview.stale.length} read${preview.stale.length === 1 ? "" : "s"} stale`); setPreview(null); }); // UNDO: offered only while it applies (the route's replaceUndoState: the draft still as the replace left it, the // entry still as Everywhere set it) -- else said why, quietly. const undo = view?.undo ?? null; const takeBack = () => run(async () => { if (!undo?.available) return; await post({ project, op: "undo" }); setNotice(undo.scope === "reads" ? "the replace is taken back: every line as it was" : undo.was ? `"${undo.was.word}" is said "${undo.was.say}" again, as before` : "the pronunciation entry is removed"); }); const reads = useMemo(() => view?.reads ?? [], [view]); // What Re-read can queue: a stale read the queue can re-read (a piece from a synthesized take is re-read on the bench). const queueableRow = (r: Read) => r.queueable !== false && (r.state === "stale" || r.state === "unpicked" || r.state === "none"); const changed = reads.filter((r) => r.state === "stale" && r.queueable !== false); const toQueue = ticked.size ? [...ticked] : changed.map((r) => r.id); // A tick lasts only while its row is shown and can still be re-read (a filter, a re-read landing, a replace). const tickable = useMemo(() => new Set(reads.filter(queueableRow).map((r) => r.id)), [reads]); useEffect(() => { setTicked((t) => (([...t].every((id) => tickable.has(id))) ? t : new Set([...t].filter((id) => tickable.has(id))))); }, [tickable]); const reread = () => run(async () => { // EXACTLY the reads the button counts -- never "every stale read of the video" (the route refuses an unscoped one). const j = (await post({ project, op: "reread", only: toQueue })) as { steps?: { reads: string[] }[]; skipped?: { id: string; why: string }[] }; const n = (j.steps ?? []).reduce((a, s) => a + s.reads.length, 0); const skipped = j.skipped ?? []; const why = skipped.length ? `${skipped.length} not queued: ${skipped.map((s) => `${s.id} (${s.why})`).join(", ")}` : ""; setNotice(n ? `${n} line${n === 1 ? "" : "s"} queued, one item at a time, in cut order -- each joins its list unpicked${why ? ` · ${why}` : ""}` : `nothing queued${why ? `: ${why}` : ""}`); setTicked(new Set()); }); // ---- Listen through: the newest batch's re-reads, played one after another ---- const queue = view?.queue ?? null; const batchRows = (queue?.rows ?? []).filter((r) => r.batch === queue?.batch); const byId = useMemo(() => new Map(reads.map((r) => [r.id, r])), [reads]); // What a read plays: a card's reading; a post's take; a thread piece's OWN parts, one after another (never the joined take). const audioOf = (item: string, t: Take): string[] => (!t ? [] : t.key ? [`/api/report/narration/audio?${new URLSearchParams({ project, card: item, key: t.key })}`] : (t.files?.length ? t.files : t.file ? [t.file] : []).map((f) => `/api/report/file?${new URLSearchParams({ project, path: f })}`)); const newOf = (q: QueueRow) => { const r = byId.get(q.read); return r ? (r.state === "unpicked" ? r.newTake : r.take) : null; }; const player = useRef(null); const [playing, setPlaying] = useState(null); const playOne = (key: string, urls: string[], then?: () => void) => { player.current?.pause(); if (!urls.length) return then?.(); const [url, ...more] = urls; const a = new Audio(url); player.current = a; setPlaying(key); a.onended = () => { if (more.length) return playOne(key, more, then); setPlaying(null); then?.(); }; void a.play().catch(() => setPlaying(null)); }; const listenThrough = () => { const list = batchRows.filter((q) => q.state === "done").map((q) => ({ key: `${q.read}:new`, urls: audioOf(q.item, newOf(q)) })).filter((x) => x.urls.length); const next = (i: number) => (i < list.length ? playOne(list[i].key, list[i].urls, () => next(i + 1)) : setPlaying(null)); next(0); }; const pick = (which: "new" | "old", only?: string[]) => run(async () => { const j = (await post({ project, op: "pick", which, ...(only ? { only } : {}) })) as { picked?: { item: string }[] }; setNotice(`picked (${which === "new" ? "the new reads" : "what played before"}): ${(j.picked ?? []).map((x) => x.item).join(", ")}`); }); if (!view) return

{error ?? "reading…"}

; const c = view.counts; const unpickedIds = reads.filter((r) => r.state === "unpicked").map((r) => r.id); const unpicked = unpickedIds.length; return (
{Object.entries(c).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(" · ") || "no reads"}
{(["all", "stale"] as const).map((s) => ( ))}
e.preventDefault()} data-reads-find-form=""> setFind(e.target.value)} placeholder="find in what is said" aria-label="Find in spoken text" className="min-w-48 flex-1 rounded border border-seam bg-transparent px-2 py-1" data-reads-find="" /> {find.trim() && ( {view.find?.matches ?? 0} match{view.find?.matches === 1 ? "" : "es"} in {view.find?.lines ?? 0} line{view.find?.lines === 1 ? "" : "s"} · spoken text only )}
{find.trim() && (
setTo(e.target.value)} placeholder="say instead" aria-label="Replace with" className="min-w-48 flex-1 rounded border border-seam bg-transparent px-2 py-1" data-reads-to="" /> {word ? "Everywhere: whole words, every read of a post; never a card" : "Everywhere needs Whole word (a pronunciation entry is whole words)"}
)} {preview && (
{preview.scope === "reads" ? ( <>

These reads: {preview.lines.length} line{preview.lines.length === 1 ? "" : "s"} rewritten in what is SAID, one undo point -- the shown text is never changed; nothing is read until you press Re-read

) : (

Everywhere, from now on: “{preview.entry.word}” said “{preview.entry.say}” in every read of a post, present and future (a pronunciation entry){preview.was ? ` -- changes the existing entry (was "${preview.was}")` : ""} -- {preview.stale.length} read{preview.stale.length === 1 ? "" : "s"} made stale{preview.stale.length ? `: ${preview.stale.map((s) => s.id).join(", ")}` : ""} {preview.cards.length > 0 && cards are not said through the lexicon: use These reads for {preview.cards.join(", ")}}

)}
)} {(notice || error || undo) && (

{notice && {notice}} {error && {error}} {undo?.available && ( )} {undo && !undo.available && undo.why && no undo of the last replace: {undo.why}}

)}
{unpicked > 0 && }
{queue && queue.rows.length > 0 && (
{Object.entries(queue.counts).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(" · ")} {(queue.counts.waiting > 0) && } {batchRows.some((q) => q.state === "done") && }
{queue.waiting &&

{queue.waiting}

}
)} {reads.map((r) => { const cell = "border-t border-seam px-2 py-1 align-top"; const href = r.kind === "card" ? narrationHref(project) : postBenchHref(project, r.item); const url = audioOf(r.item, r.take); return ( ); })}
re-read read character what is said state plays
{queueableRow(r) && ( setTicked((s) => { const n = new Set(s); if (e.target.checked) n.add(r.id); else n.delete(r.id); return n; })} aria-label={`Re-read ${r.id}`} data-read-tick={r.id} /> )} {r.id} {KIND[r.kind]} {r.character?.name ?? —} {r.said && r.said !== r.spoken && said as: {r.said}} {r.kind === "card" && r.state === "stale" && r.because.includes("words") && its words changed with the replace: Re-read makes them play} {r.why && {r.why}} {r.state}{r.because.length ? {r.because.map((b) => BECAUSE[b] ?? b).join(", ")} : null} {url.length ? : —}
); }