"use client"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; import AppHeader from "@/components/shell/AppHeader"; import { buttonVariants } from "@/components/ui/button"; import { Dialog } from "@/components/ui/dialog"; import { EmptyState } from "@/components/ui/empty-state"; import { KeyHint } from "@/components/ui/kbd"; import { LitList, type LitDetail } from "@/components/ui/lit-list"; import { LitActions, LitLine } from "@/components/ui/lit-line"; import { useHydrated } from "@/components/ui/use-hydrated"; import { groupsOf, moveQuote, moveSection, placeQuote } from "@/lib/research/board.mjs"; import type { BoardGroup, CaseView, Quote } from "@/lib/research/case-types"; import { researchCaseApi, researchCaseExportApi, researchCaseQuoteApi, researchCasePipelineHref, researchCaseVerifyApi, researchFromCaseHref, researchHref, } from "@/lib/research/hrefs"; import HandoffDialog from "./HandoffDialog"; import { runHref } from "@/lib/research/runs-hrefs"; import { triageHref } from "@/lib/hrefs"; import QuoteSlip, { quoteLineId } from "./QuoteSlip"; // --------------------------------------------------------------------------- // THE RESEARCH BOARD (plans/umtool-redesign.md, R2; canvas "Research board", // `#view-board`): a case's quotes as snapshot slips in sections and order, // our claim line and note under each, the flags, and the side panel -- the // hand-offs, the scope, what was searched and read, where it is stored. // // One lit list: section heads and quotes are its lines. Keys (never while // typing): j/k lines · alt+j/alt+k move the lit quote (across sections) or // section · e claim · n note · s speaker checked · m section · x remove · // a add section · r rename (the lit section, else the case) · v re-verify · // c copy as cited markdown · / search more. Drag a quote by its grip. // // Every change is the API's (app/api/research/cases/route.ts); the board // redraws from what it answers. // // ONE WRITER, AND KEYS ON A SETTLED BOARD (the board.spec races, root-caused // after P6a). Every write -- a move, a claim, a note, the speaker check, a // section, a removal, a re-verify -- goes through ONE queue (`write`): run in // the order asked, each computed on the case the previous one left, each // answer applied in order (two writes in flight used to race their answers: // an older one landing last put the speaker check back). While a write is // queued or answering, the board's keys are BUFFERED, not acted on: the list // is about to be redrawn (it remounts on an arrangement), so a key acting now // acts on lines and fields the answer replaces -- `e` focused a field the // redraw took away and the claim typed after it ran as commands (`r` opened // the case's rename, `s` toggled the speaker, Enter renamed the case). Once // the board has settled, the buffer is replayed in order, one key per frame: // a command acts on the redrawn board, text lands in the field it was typed // for (`e` + text + Enter is a saved claim, `a` + text + Enter a section). // --------------------------------------------------------------------------- const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; const sectionLineId = (sid: string | null) => `s:${sid ?? "unsorted"}`; /** A key held while the board settles, replayed after. */ type HeldKey = { key: string; code: string; altKey: boolean; shiftKey: boolean }; /** The keys besides a character that the buffer holds (Tab and the modifiers pass). */ const HOLDABLE = new Set(["Enter", "Escape", "Backspace", "Delete", "ArrowUp", "ArrowDown", "Home", "End"]); async function call(url: string, method: string, body?: unknown): Promise { const r = await fetch(url, { method, headers: { "content-type": "application/json" }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), cache: "no-store", }); const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null; if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); return j as T; } function SectionHead({ g, lit, busy, onRename, onRemove, onDropTop }: { g: BoardGroup; lit: boolean; busy: boolean; onRename: () => void; onRemove: () => void; onDropTop: () => void }) { const [over, setOver] = useState(false); return ( { if (!e.dataTransfer.types.includes("application/x-umtool-quote")) return; e.preventDefault(); setOver(true); }} onDragLeave={() => setOver(false)} onDrop={(e) => { e.preventDefault(); setOver(false); onDropTop(); }} className={`mb-2 flex items-baseline gap-2.5 border-b-0 pb-1.5 pt-3 ${over ? "shadow-[0_2px_0_var(--signal)]" : ""}`} >

{g.title}

{g.quotes.length} {g.id !== null && ( )}
); } type Ask = | { kind: "add-section" } | { kind: "rename-section"; sid: string; title: string } | { kind: "remove-section"; sid: string; title: string; n: number } | { kind: "rename-case" } | { kind: "remove-quote"; q: Quote }; export default function BoardView({ initial }: { initial: CaseView }) { // settings.privacy: a `local:` source's directory as displayed (client-side). const { displayPath } = useDisplay(); const router = useRouter(); const hydrated = useHydrated(); // WHAT IS DRAWN, as ONE state: the case's view, the light, the list's key // (it remounts on an arrangement) and `v`, which answer this is. One state, // so they can never commit apart -- React may render an update made with a // key event's priority before one made from a fetch's continuation, and a // board whose light, list and view committed in different renders sent a // key to a line the next render replaced (race 3). const [board, setBoard] = useState<{ view: CaseView; litId: string | null; listKey: number; v: number }>({ view: initial, litId: null, listKey: 0, v: 0 }); const { view, litId, listKey } = board; // Writes queued or answering (the ref is read synchronously by the keys). const [pending, setPending] = useState(0); const pendingRef = useRef(0); const busy = pending > 0; const [status, setStatus] = useState<{ text: string; href?: string; tone?: "error" } | null>(null); const [ask, setAsk] = useState(null); const [askText, setAskText] = useState(""); const [handoff, setHandoff] = useState<"article" | "video" | "sweep" | null>(null); const [notes, setNotes] = useState(initial.case.notes); const dragging = useRef(null); const doc = view.case; const groups = useMemo(() => groupsOf(doc) as unknown as BoardGroup[], [doc]); const byId = useMemo(() => new Map(doc.quotes.map((q) => [q.id, q])), [doc]); // The light as the list last said it (a ref: a key in the same tick as a // j/k reads where the light is, not where the last render had it). const litRef = useRef(null); const say = (text: string, extra: { href?: string; tone?: "error" } = {}) => setStatus({ text, ...extra }); const fail = (e: unknown) => say((e as Error).message, { tone: "error" }); // After a move, the moved line keeps the light (the list is redrawn). const refocus = useRef(null); useEffect(() => { const id = refocus.current; if (!id) return; refocus.current = null; const el = document.querySelector(`[data-lit-id="${CSS.escape(id)}"]`); el?.focus({ preventScroll: true }); el?.scrollIntoView({ block: "nearest" }); }, [listKey]); // The case as the last answer left it: a queued write is computed on it, not // on the render that queued it. const docRef = useRef(doc); docRef.current = doc; const quoteNow = (qid: string) => docRef.current.quotes.find((q) => q.id === qid) ?? null; // THE ONE QUEUE. `op` runs when every write before it has answered; its // answer is applied before the next starts. A failed write says why and the // ones behind it still run, each on the case as it now is. const chain = useRef>(Promise.resolve()); const write = useCallback((op: () => Promise): Promise => { pendingRef.current += 1; setPending((n) => n + 1); const run = chain.current.then(op).catch((e: unknown) => { fail(e); return null; }); chain.current = run.finally(() => { pendingRef.current -= 1; setPending((n) => n - 1); }); return run; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // SETTLED = no write queued or answering AND the last answer is on screen // with everything that follows a redraw done. An answer is applied (`apply`) // before it is drawn: React commits it in a later task, and runs the passive // effects after the commit later still -- the moved line's refocus above, // the remounted list's light and its j/k listener. A key landing in either // gap (under load, often) acted on a list or a focus about to change: `e` // focused the claim, then the refocus put the focus back on the line (race // 3). So the board is settled only once this effect -- a passive one, // declared after the refocus, and a parent's, so after the list's own -- // has run for answer `applied` (`drawnV`). const applied = useRef(0); const drawnV = useRef(0); useEffect(() => { drawnV.current = board.v; }, [board.v]); const settled = () => pendingRef.current === 0 && drawnV.current === applied.current; /** Draw an answer: its view, and with it the light and a remount when the list was rearranged. */ const apply = (v: CaseView, o: { remount?: boolean; lit?: string | null; focus?: string | null } = {}) => { docRef.current = v.case; applied.current += 1; const n = applied.current; if (o.lit !== undefined) litRef.current = o.lit; if (o.remount) refocus.current = o.focus ?? null; setBoard((b) => ({ view: v, litId: o.lit !== undefined ? o.lit : b.litId, listKey: o.remount ? b.listKey + 1 : b.listKey, v: n })); }; /** An arrangement (sections, order), computed on the case when its turn comes. */ const arrange = useCallback( (next: (d: CaseView["case"]) => { sections: unknown; order: unknown } | null, keep: string | null) => write(async () => { const body = next(docRef.current); if (!body) return; const v = await call(researchCaseApi(docRef.current.id), "PATCH", body); apply(v, { remount: true, focus: keep, ...(keep ? { lit: keep } : {}) }); }), [write], ); /** A quote's fields; `body` may be computed on the quote as it is when the write runs. */ const patchQuote = useCallback( (qid: string, body: Record | ((q: Quote) => Record)) => write(async () => { const q = quoteNow(qid); if (!q) return; const b = typeof body === "function" ? body(q) : body; const r = await call<{ case: CaseView }>(researchCaseQuoteApi(docRef.current.id, qid), "PATCH", b); apply(r.case, "section" in b ? { remount: true, focus: quoteLineId(qid) } : {}); if (b.useCurrentWords) say("The quote now has the transcript's current words; the old ones are kept in its history."); }), // eslint-disable-next-line react-hooks/exhaustive-deps [write], ); /** The case's fields; `keep` the line lit and focused after a section change (from the answer, if a function). */ const patchCase = useCallback( ( body: Record | ((d: CaseView["case"]) => Record), keep: string | null | ((v: CaseView) => string | null) = null, ) => write(async () => { const b = typeof body === "function" ? body(docRef.current) : body; const v = await call(researchCaseApi(docRef.current.id), "PATCH", b); const k = typeof keep === "function" ? keep(v) : keep; apply(v, b.sections ? { remount: true, focus: k, ...(typeof keep === "function" && k ? { lit: k } : {}) } : {}); return v; }), // eslint-disable-next-line react-hooks/exhaustive-deps [write], ); const verify = useCallback( () => write(async () => { say("Re-reading every quote at its cite…"); const r = await call<{ results: { id: string; verify: { status: string; enOrig?: unknown } }[]; case: CaseView }>(researchCaseVerifyApi(docRef.current.id), "POST", {}); apply(r.case); const n = (s: string) => r.results.filter((x) => x.verify.status === s).length; const en = r.results.filter((x) => x.verify.enOrig).length; say( `Re-verified ${r.results.length}: ${n("ok")} as pinned, ${n("drifted")} drifted, ${n("missing")} missing` + (n("unreadable") ? `, ${n("unreadable")} not readable` : "") + (en ? `; en-orig differs at ${en}` : ""), ); }), // eslint-disable-next-line react-hooks/exhaustive-deps [write], ); const copyMarkdown = useCallback(async () => { try { const r = await fetch(researchCaseExportApi(doc.id), { cache: "no-store" }); if (!r.ok) throw new Error((await r.json().catch(() => null))?.error ?? `HTTP ${r.status}`); const md = await r.text(); try { await navigator.clipboard.writeText(md); say(`Copied the board as cited markdown (${md.split("\n").length} lines)`); } catch { window.prompt("Copy the board's markdown", md); } } catch (e) { fail(e); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [doc.id]); const removeQuote = useCallback( (q: Quote) => write(async () => { const r = await call<{ case: CaseView }>(researchCaseQuoteApi(docRef.current.id, q.id), "DELETE"); apply(r.case, { remount: true }); say(`Removed “${q.text.slice(0, 60)}${q.text.length > 60 ? "…" : ""}”`); }), // eslint-disable-next-line react-hooks/exhaustive-deps [write], ); const openAsk = (a: Ask) => { setAsk(a); setAskText(a.kind === "rename-section" ? a.title : a.kind === "rename-case" ? docRef.current.title : ""); }; const submitAsk = async () => { const a = ask; if (!a) return; const t = askText.trim(); setAsk(null); if (a.kind === "add-section" && t) { // The new section is lit and focused in the same redraw that draws it. await patchCase( (d) => ({ sections: [...d.sections, { title: t }] }), (v) => { const added = v.case.sections.at(-1); return added ? sectionLineId(added.id) : null; }, ); } else if (a.kind === "rename-section" && t) { await patchCase((d) => ({ sections: d.sections.map((s) => (s.id === a.sid ? { id: s.id, title: t } : s)) }), sectionLineId(a.sid)); } else if (a.kind === "remove-section") { await patchCase((d) => ({ sections: d.sections.filter((s) => s.id !== a.sid) }), sectionLineId(null)); } else if (a.kind === "rename-case" && t) { await patchCase({ title: t }); } else if (a.kind === "remove-quote") { await removeQuote(a.q); } }; const onDropOn = (target: string, after: boolean) => { const qid = dragging.current; dragging.current = null; if (!qid || qid === target) return; void arrange((d) => { const g = (groupsOf(d) as unknown as BoardGroup[]).find((x) => x.quotes.some((q) => q.id === target)); if (!g) return null; const without = g.quotes.filter((q) => q.id !== qid); const at = without.findIndex((q) => q.id === target) + (after ? 1 : 0); return placeQuote(d, qid, g.id, at); }, quoteLineId(qid)); }; // ── keys ── // // The buffer: a key pressed while a write is queued or answering, or while // earlier keys still wait, is held (in a capture listener, before the list's // own j/k or any field sees it) and replayed once the board has settled. const held = useRef([]); const replaying = useRef(false); const dispatching = useRef(false); const [heldN, setHeldN] = useState(0); const [kick, setKick] = useState(0); // The keys are live (hydrated, every listener attached): a page's first key // before this is the browser's, not the board's. const [keysReady, setKeysReady] = useState(false); useEffect(() => { const onKey = (e: KeyboardEvent) => { if (dispatching.current || e.metaKey || e.ctrlKey) return; if (e.key.length !== 1 && !HOLDABLE.has(e.key)) return; const typing = !!(e.target as HTMLElement | null)?.closest?.(TYPING); // A field the operator is typing in is left alone unless earlier keys // are still waiting (then this one waits behind them, in order). if (held.current.length === 0 && (typing || settled())) return; e.preventDefault(); e.stopImmediatePropagation(); held.current.push({ key: e.key, code: e.code, altKey: e.altKey, shiftKey: e.shiftKey }); setHeldN(held.current.length); }; window.addEventListener("keydown", onKey, true); setKeysReady(true); return () => window.removeEventListener("keydown", onKey, true); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); /** Replay one held key where the focus is now: into a field as text, else as the key it was. */ const replayKey = (k: HeldKey) => { const el = (document.activeElement as HTMLElement | null) ?? document.body; dispatching.current = true; try { const field = el.matches?.("input:not([type=checkbox]):not([type=radio]), textarea") ? (el as HTMLInputElement | HTMLTextAreaElement) : null; if (field && (k.key.length === 1 || k.key === "Backspace")) { const proto = field instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; const next = k.key === "Backspace" ? field.value.slice(0, -1) : field.value + k.key; Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(field, next); field.dispatchEvent(new Event("input", { bubbles: true })); return; } const ev = new KeyboardEvent("keydown", { key: k.key, code: k.code, altKey: k.altKey, shiftKey: k.shiftKey, bubbles: true, cancelable: true }); const handled = !el.dispatchEvent(ev); // What only a trusted key does by itself: Enter submits a form, Escape closes a dialog. if (!handled && field && k.key === "Enter") field.form?.requestSubmit(); if (!handled && k.key === "Escape") el.closest("dialog")?.close(); } finally { dispatching.current = false; } }; // Settled (nothing queued or answering, the redraw committed): replay. useEffect(() => { if (replaying.current || !settled() || held.current.length === 0) return; replaying.current = true; void (async () => { try { while (held.current.length && settled()) { // A frame between keys: what the last one did (a focus, a dialog, a // new light) is on screen before the next one acts. await new Promise((r) => setTimeout(r, 16)); if (!settled()) break; const k = held.current.shift()!; replayKey(k); } } finally { replaying.current = false; setHeldN(held.current.length); // A write that started and answered while this loop waited a frame // changed `pending` under it: look again. if (held.current.length && settled()) setKick((n) => n + 1); } })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [pending, board.v, heldN, kick]); useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.defaultPrevented || e.metaKey || e.ctrlKey) return; if ((e.target as HTMLElement | null)?.closest?.(TYPING)) return; if (document.querySelector("dialog[open]")) return; const id = litRef.current; const d = docRef.current; const litQuote = id?.startsWith("q:") ? (d.quotes.find((q) => q.id === id.slice(2)) ?? null) : null; const litSection = id?.startsWith("s:") && id !== "s:unsorted" ? (d.sections.find((s) => s.id === id.slice(2)) ?? null) : null; if (e.altKey) { const dir = e.code === "KeyJ" || e.key === "ArrowDown" ? 1 : e.code === "KeyK" || e.key === "ArrowUp" ? -1 : 0; if (!dir) return; e.preventDefault(); if (litQuote) void arrange((c) => moveQuote(c, litQuote.id, dir), quoteLineId(litQuote.id)); else if (litSection) void arrange((c) => moveSection(c, litSection.id, dir), sectionLineId(litSection.id)); return; } const focusField = (f: string) => { if (!litQuote) return; const el = document.querySelector(`[data-quote="${CSS.escape(litQuote.id)}"] [data-field="${f}"]`); if (el) { e.preventDefault(); el.focus(); } }; switch (e.key) { case "e": focusField("claim"); break; case "n": focusField("note"); break; case "m": focusField("section"); break; case "s": // Toggled on the quote as it is when the write runs, not as this render drew it. if (litQuote && litQuote.cite.kind !== "post") void patchQuote(litQuote.id, (q) => ({ speakerChecked: !q.speakerChecked })); break; case "x": case "Delete": if (litQuote) openAsk({ kind: "remove-quote", q: litQuote }); break; case "a": e.preventDefault(); openAsk({ kind: "add-section" }); break; case "r": e.preventDefault(); if (litSection) openAsk({ kind: "rename-section", sid: litSection.id, title: litSection.title }); else openAsk({ kind: "rename-case" }); break; case "v": void verify(); break; case "c": void copyMarkdown(); break; case "/": e.preventDefault(); router.push(researchFromCaseHref(docRef.current)); break; } }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }); const onLight = useCallback((d: LitDetail) => { litRef.current = d.id; setBoard((b) => (b.litId === d.id ? b : { ...b, litId: d.id })); }, []); const s = doc.scope; const where = view.sourceLabel ?? (s.source ? displayPath(s.source.replace(/^(local|remote|hub):/, "")) : "no source yet"); const scopeLine = [where, s.channels?.length ? `${s.channels.length} ${s.channels.length === 1 ? "channel" : "channels"}` : "all channels", s.dateFrom || s.dateTo ? `${s.dateFrom ?? "…"} – ${s.dateTo ?? "…"}` : ""].filter(Boolean).join(" · "); const se = doc.search; const meta = [ `${doc.quotes.length} ${doc.quotes.length === 1 ? "quote" : "quotes"}`, `${doc.sections.length} ${doc.sections.length === 1 ? "section" : "sections"}`, s.query ? `from “${s.query}”` : "", view.sourceLabel ?? "", ] .filter(Boolean) .join(" · "); const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; return ( <> Research · case {meta} {drifted > 0 && · {drifted} drifted or missing} } actions={ <> Download .md } /> {/* On a phone the board, then the case panel under it, one column the page scrolls. */}
0 || board.v !== applied.current ? "" : undefined} data-board-keys={keysReady ? "ready" : undefined}> {doc.quotes.length === 0 && doc.sections.length === 0 ? ( Search and pin to it ) : ( {groups.map((g) => (
g.id && openAsk({ kind: "rename-section", sid: g.id, title: g.title })} onRemove={() => g.id && openAsk({ kind: "remove-section", sid: g.id, title: g.title, n: g.quotes.length })} onDropTop={() => { const qid = dragging.current; dragging.current = null; if (qid) void arrange((d) => placeQuote(d, qid, g.id, 0), quoteLineId(qid)); }} /> {g.quotes.map((q) => ( void patchQuote(q.id, body)} onRemove={() => openAsk({ kind: "remove-quote", q })} onDragStart={(id) => (dragging.current = id)} onDropOn={onDropOn} /> ))} {g.quotes.length === 0 &&

Empty: move a quote here with alt+j/k, its Section menu, or a drag.

}
))}
)}
line move claim note speaker section add section rename remove search more {status && ( {status.text} {status.href && ( <> {" · "} Open )} )}