"use client"; import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { EmptyState } from "@/components/ui/empty-state"; import { KeyHint } from "@/components/ui/kbd"; import type { LitDetail } from "@/components/ui/lit-list"; import { useHydrated } from "@/components/ui/use-hydrated"; import { yearOf } from "@/lib/research/facets.mjs"; import { researchArchiveHref, researchCaseHref, researchCaseQuotesApi, researchCasesApi, researchHref, researchScopeApi, researchWindowApi } from "@/lib/research/hrefs"; import { parseAsk } from "@/lib/research/query.mjs"; import type { FetchAnswer, LogMarks, ResultHit, Scope, ScopeSummary, SearchResponse, SourceOption, WindowResponse } from "@/lib/research/types"; import type { CaseDoc, CaseSummary, CaseView, Quote } from "@/lib/research/case-types"; import Facets, { type FacetPick } from "./Facets"; import Reader from "./Reader"; import Results, { parseLineId } from "./Results"; import ScopeBar from "./ScopeBar"; import { BoardChooser, CaseList, PinDialog } from "./PinTarget"; // --------------------------------------------------------------------------- // RESEARCH (plans/umtool-redesign.md, "Research, first-class"; canvas // `#view-research`): the ask bar, the scope and what it holds, the results as // lit lines grouped by recording with an honest header, the facets, the // reader, and the reading log. // // A search is ONE call for the whole match set (POST /api/research/search -> // enumerate_matches' scan); the page never pages the engine. Facets and "show // more" narrow or extend what is DRAWN, never what was searched. The query and // the scope live in the URL (replaceState), so a search is a link. // // Keys: j/k lines (the list), r read · s skip · u unread (the lit recording, // then the next), c copy citation, p pin to the board (R2), / the ask bar. // // PINS (R2): the lit hit -- its cited cue, read again by the server -- goes to // the chosen case as a snapshot quote, with this search's session, so the // case takes its reading log. With no case chosen, the pin asks which (or // names a new one for the query). The choice is in the URL (`case=`) and // remembered in this browser. // --------------------------------------------------------------------------- const PAGE = 200; const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; const BOARD_KEY = "umtool:research-board"; const summaryOf = (d: CaseDoc): CaseSummary => ({ id: d.id, piece: `c:${d.id}`, title: d.title, quotes: d.quotes.length, sections: d.sections.length, updatedAt: d.updatedAt, scope: d.scope, drifted: d.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length, }); function setUrlCase(id: string | null) { const u = new URL(window.location.href); if (id) u.searchParams.set("case", id); else u.searchParams.delete("case"); window.history.replaceState(null, "", `${u.pathname}${u.search}`); } type Lit = { key: string; i: number }; const nf = new Intl.NumberFormat("en-US"); async function json(r: Response): Promise { const body = await r.json().catch(() => null); if (!r.ok) throw new Error((body as { error?: string } | null)?.error ?? `HTTP ${r.status}`); return body as T; } function sameScope(a: Scope, b: Scope) { return JSON.stringify({ ...a, channels: [...(a.channels ?? [])].sort() }) === JSON.stringify({ ...b, channels: [...(b.channels ?? [])].sort() }); } export default function ResearchView({ sources, initialQuery, initialScope, initialSummary, initialSummaryError, initialCases, initialCase, }: { initialCases: CaseSummary[]; initialCase: string | null; sources: SourceOption[]; initialQuery: string; initialScope: Scope; initialSummary: ScopeSummary | null; initialSummaryError: string | null; }) { const hydrated = useHydrated(); const askRef = useRef(null); const listRef = useRef(null); const [ask, setAsk] = useState(initialQuery); const [scope, setScope] = useState(initialScope); const [summary, setSummary] = useState(initialSummary); const [summaryError, setSummaryError] = useState(initialSummaryError); const [summaryLoading, setSummaryLoading] = useState(false); const [res, setRes] = useState(null); const [ranScope, setRanScope] = useState(null); const [searching, setSearching] = useState(false); const [error, setError] = useState(null); const [marks, setMarks] = useState({}); const [logError, setLogError] = useState(null); const [pick, setPick] = useState({}); const [shown, setShown] = useState(PAGE); const [lit, setLit] = useState(null); const [span, setSpan] = useState(30); const [win, setWin] = useState(null); const [winError, setWinError] = useState(null); const [winLoading, setWinLoading] = useState(false); const [copied, setCopied] = useState(false); const [fetchState, setFetchState] = useState(null); const [fromStored, setFromStored] = useState(false); const [cases, setCases] = useState(initialCases); const [board, setBoard] = useState(initialCase && initialCases.some((c) => c.id === initialCase) ? initialCase : null); const [pinAsk, setPinAsk] = useState<"pin" | "new" | null>(null); const [pinWorking, setPinWorking] = useState(false); const [pinError, setPinError] = useState(null); const [pinned, setPinned] = useState<{ text: string; href?: string; tone?: "error" } | null>(null); // The board chosen last time, when the URL names none. useEffect(() => { if (board) return; try { const was = window.localStorage.getItem(BOARD_KEY); if (was && initialCases.some((c) => c.id === was)) setBoard(was); } catch { /* no storage: nothing remembered */ } // once, on arrival // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const chooseBoard = useCallback((id: string | null) => { setBoard(id); setUrlCase(id); try { if (id) window.localStorage.setItem(BOARD_KEY, id); else window.localStorage.removeItem(BOARD_KEY); } catch { /* the URL still says it */ } }, []); // ── the scope preview, re-read when the scope changes ── const firstScope = useRef(true); useEffect(() => { if (firstScope.current) { firstScope.current = false; return; } const ctl = new AbortController(); setSummaryLoading(true); const t = setTimeout(() => { fetch(researchScopeApi(scope), { signal: ctl.signal, cache: "no-store" }) .then((r) => json(r)) .then((s) => { setSummary(s); setSummaryError(null); }) .catch((e: Error) => { if (e.name !== "AbortError") setSummaryError(e.message); }) .finally(() => setSummaryLoading(false)); }, 200); return () => { clearTimeout(t); ctl.abort(); }; }, [scope]); // ── search: once, the whole set ── const run = useCallback( async (q: string, s: Scope, fresh = false) => { const parsed = parseAsk(q); if (parsed.error) { setError(parsed.error); return; } setSearching(true); setError(null); try { const r = await json( await fetch("/api/research/search", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ q, source: s.source, channels: s.channels, from: s.dateFrom, to: s.dateTo, states: s.states, media: s.mediaType, posts: s.posts, fresh, }), }), ); setRes(r); setRanScope(s); setMarks(r.log.marks); setLogError(r.log.error ?? null); setPick({}); setShown(PAGE); setLit(null); setWin(null); window.history.replaceState(null, "", researchHref({ q, ...s, source: r.source.handle === sources[0]?.handle ? undefined : r.source.handle, case: new URL(window.location.href).searchParams.get("case") ?? undefined })); // The search counted the scope's tracks: the preview can say so now. fetch(researchScopeApi(s), { cache: "no-store" }) .then((x) => json(x)) .then(setSummary) .catch(() => {}); } catch (e) { setError((e as Error).message); } finally { setSearching(false); } }, [sources], ); // A link with ?q= runs on arrival. const ranInitial = useRef(false); useEffect(() => { if (ranInitial.current || !initialQuery) return; ranInitial.current = true; void run(initialQuery, initialScope); }, [initialQuery, initialScope, run]); // ── what is drawn: the facets narrow it ── const visible = useMemo(() => { if (!res) return []; return res.hits.filter((h) => { if (pick.year && yearOf(h.uploadDate) !== pick.year) return false; if (pick.channel && h.channelSlug !== pick.channel) return false; if (pick.track && h.track !== pick.track) return false; if (pick.state && h.state !== pick.state) return false; if (pick.reading && (marks[h.key]?.state ?? "unread") !== pick.reading) return false; return true; }); }, [res, pick, marks]); const drawn = visible.slice(0, shown); const reading = useMemo(() => { const t = { read: 0, skipped: 0, unread: 0 }; for (const h of res?.hits ?? []) t[marks[h.key]?.state ?? "unread"]++; return t; }, [res, marks]); const byKey = useMemo(() => new Map((res?.hits ?? []).map((h) => [h.key, h])), [res]); const litHit: ResultHit | null = lit ? (byKey.get(lit.key) ?? null) : null; const litSnip = litHit && lit ? (litHit.snippets[lit.i] ?? null) : null; const onLight = useCallback((d: LitDetail) => { const p = parseLineId(d.id); if (p) setLit(p); }, []); // ── the reader follows the lit line ── useEffect(() => setSpan(30), [lit?.key, lit?.i]); useEffect(() => { setFetchState(null); setCopied(false); }, [lit?.key, lit?.i]); useEffect(() => { if (!res || !litHit || !litSnip) return; const ctl = new AbortController(); setWinLoading(true); setWinError(null); const t = setTimeout(() => { fetch( researchWindowApi({ source: res.source.handle, channel: litHit.channelKey, video: litHit.videoId, t: litSnip.t, span, ...(litSnip.track ? { track: litSnip.track } : {}), kind: litHit.kind, }), { signal: ctl.signal, cache: "no-store" }, ) .then((r) => json(r)) .then(setWin) .catch((e: Error) => { if (e.name !== "AbortError") { setWin(null); setWinError(e.message); } }) .finally(() => setWinLoading(false)); }, 120); return () => { clearTimeout(t); ctl.abort(); }; }, [res, litHit, litSnip, span]); // ── the reading log ── const markLit = useCallback( async (state: "read" | "skipped" | "unread") => { if (!res || !litHit) return; const key = litHit.key; setMarks((m) => { const next = { ...m }; if (state === "unread") delete next[key]; else next[key] = { state, at: new Date().toISOString() }; return next; }); // On to the next recording, so r r r walks the list. if (state !== "unread") { const sections = [...(listRef.current?.querySelectorAll("[data-hit]") ?? [])]; const at = sections.findIndex((s) => s.dataset.hit === key); const next = sections[at + 1]?.querySelector("[data-lit-line]"); if (next) { next.focus({ preventScroll: true }); next.scrollIntoView({ block: "nearest" }); } } try { const r = await json<{ marks: LogMarks }>( await fetch("/api/research/log", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ session: res.session, key, state, query: res.query, scope: { source: res.source.handle, ...(ranScope ?? {}) }, }), }), ); setMarks(r.marks); setLogError(null); } catch (e) { setLogError((e as Error).message); } }, [res, litHit, ranScope], ); const copy = useCallback(async () => { // Only the lit hit's own window: never a citation left from the line before. if (!win || !litHit || win.videoId !== litHit.videoId) return; try { await navigator.clipboard.writeText(win.citation.text); setCopied(true); setTimeout(() => setCopied(false), 1600); } catch { window.prompt("Copy the citation", win.citation.text); } }, [win, litHit]); // ── fetch clip, through the editor, polled by job ── const fetchClip = useCallback(async () => { if (!res || !litHit || !win) return; const cue = win.cues[win.lit]; const start = cue?.t ?? win.at; const end = cue ? Math.max(cue.end, start + 1) : win.at + 5; setFetchState({ state: "asking" }); try { let a = await json( await fetch("/api/research/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ source: res.source.handle, channel: litHit.channelKey, video: litHit.videoId, start, end, reason: `umtool research: "${res.query}" @ ${win.citation.text.match(/@ ([\d:]+)\]/)?.[1] ?? start}`, ...(fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), }), }), ); setFetchState(a); for (let n = 0; a.state === "queued" && n < 300; n++) { await new Promise((r) => setTimeout(r, 1500)); a = await json( await fetch("/api/research/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ job: a.job }) }), ); setFetchState(a); } if (a.state === "ready") { // The clip is in the corpus now: the window's media list offers it. const w = await json( await fetch(researchWindowApi({ source: res.source.handle, channel: litHit.channelKey, video: litHit.videoId, t: win.at, span: win.span }), { cache: "no-store" }), ); setWin(w); setFetchState(a); } } catch (e) { setFetchState({ state: "failed", message: (e as Error).message }); } }, [res, litHit, win, fromStored]); // ── pin to a board (R2) ── const pinTo = useCallback( async (caseId: string) => { if (!res || !litHit || !litSnip) return; if (litHit.kind !== "post" && litSnip.scope) { setPinned({ text: `A hit in the ${litSnip.scope} has no moment to pin`, tone: "error" }); return; } // The reader's cited cue when it is this hit's window; else the snippet's second. const cue = win && win.videoId === litHit.videoId && win.lit >= 0 ? win.cues[win.lit] : null; setPinWorking(true); try { const r = await json<{ quote: Quote; duplicate: boolean; case: CaseView }>( await fetch(researchCaseQuotesApi(caseId), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ source: res.source.handle, channel: litHit.channelKey, video: litHit.videoId, t: litHit.kind === "post" ? 0 : (cue?.t ?? litSnip.t), ...(litSnip.track ? { track: litSnip.track } : {}), kind: litHit.kind, search: { session: res.session, query: res.query, total: res.total, complete: res.complete, notReached: res.notReached, sourceLabel: res.source.label }, scope: { ...(ranScope ?? {}), source: res.source.handle, query: res.query, ...(res.regex ? { regex: true } : {}) }, }), }), ); const sum = summaryOf(r.case.case); setCases((cs) => [sum, ...cs.filter((c) => c.id !== sum.id)]); setPinned({ text: r.duplicate ? `Already on “${sum.title}” (${r.quote.id})` : `Pinned to “${sum.title}” · ${sum.quotes} ${sum.quotes === 1 ? "quote" : "quotes"}`, href: researchCaseHref(caseId), }); setPinAsk(null); setPinError(null); } catch (e) { if (pinAsk) setPinError((e as Error).message); else setPinned({ text: `Pin: ${(e as Error).message}`, tone: "error" }); } finally { setPinWorking(false); } }, [res, litHit, litSnip, win, ranScope, pinAsk], ); const pin = useCallback(() => { if (!res || !litHit) return; if (board && cases.some((c) => c.id === board)) void pinTo(board); else { setPinError(null); setPinAsk("pin"); } }, [res, litHit, board, cases, pinTo]); const createCase = useCallback( async (title: string) => { setPinWorking(true); setPinError(null); try { const r = await json<{ case: CaseDoc }>( await fetch(researchCasesApi(), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ title, query: res?.query ?? ask, scope: { ...(ranScope ?? scope), ...(res ? { source: res.source.handle } : {}) } }), }), ); const sum = summaryOf(r.case); setCases((cs) => [sum, ...cs]); chooseBoard(sum.id); if (pinAsk === "pin" && res && litHit) await pinTo(sum.id); else { setPinAsk(null); setPinned({ text: `New case “${sum.title}”: pins go to it`, href: researchCaseHref(sum.id) }); } } catch (e) { setPinError((e as Error).message); } finally { setPinWorking(false); } }, [res, ask, ranScope, scope, chooseBoard, pinAsk, litHit, pinTo], ); useEffect(() => setPinned(null), [lit?.key, lit?.i]); // ── keys ── useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented) return; if ((e.target as HTMLElement | null)?.closest?.(TYPING)) return; if (e.key === "/") { e.preventDefault(); askRef.current?.focus(); askRef.current?.select(); } else if (e.key === "r") void markLit("read"); else if (e.key === "s") void markLit("skipped"); else if (e.key === "u") void markLit("unread"); else if (e.key === "c") void copy(); else if (e.key === "p") { e.preventDefault(); pin(); } }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }, [markLit, copy, pin]); const stale = !!res && !!ranScope && !sameScope(ranScope, scope); const filtered = visible.length !== (res?.hits.length ?? 0); const parsedAsk = parseAsk(ask); return ( // On a phone the reader follows the results, and the page scrolls as one.
{ e.preventDefault(); void run(ask, scope, true); }} > { setPinError(null); setPinAsk("new"); }} />
setScope({ ...next, source: next.source || scope.source })} /> {error && (

{error}

)} {res && (
{nf.format(res.total)} {res.total === 1 ? "recording" : "recordings"} {res.complete ? ( · full coverage ) : ( · Partial — not reached: {res.notReached.length ? res.notReached.join(", ") : "—"} {res.stopped ? ` · stopped in ${res.stopped.channel} at page ${res.stopped.page} of ${res.stopped.pages}` : ""} )}{" "} · {nf.format(res.matches)} lines · {nf.format(res.scanned.pages)} pages {res.mirrorsFolded > 0 ? ` · ${res.mirrorsFolded} ${res.mirrorsFolded === 1 ? "mirror" : "mirrors"} folded` : ""} {res.aliases.length ? ` · aliases: ${res.aliases.join(", ")}` : ""} {filtered ? ` · showing ${visible.length} of ${res.total}` : ""} {stale && The scope changed: Search to run it} read {reading.read} of {res.total} {reading.skipped ? ` · ${reading.skipped} skipped` : ""} {res.warnings.length > 0 && {res.warnings.join("; ")}} {logError && ( The reading log: {logError} )}
)} {res ? (
{drawn.length === 0 ? ( {res.total === 0 ? "in this scope" : null} ) : ( )} {visible.length > drawn.length && (
{visible.length - drawn.length} more recordings below
)} {drawn.length > 0 && (
line read skip unread copy citation pin to board ask {res.batches} {res.batches === 1 ? "batch" : "batches"} of 8 for a sweep
)}
setPick(p)} />
) : (
{searching ? (

Searching the whole scope, once…

) : (
ask search A search reads the whole scope once and says what it did not reach. What the archive holds
)} {!searching && }
)}
c.id === board)?.title ?? null} /> { chooseBoard(id); void pinTo(id); }} onCreate={(title) => void createCase(title)} onClose={() => setPinAsk(null)} />
); }