"use client"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { clipBenchHref, openInDraftHref } from "@/lib/hrefs"; import { blockAnswer, clipKeepable, clipVerdict, reviewProgress } from "@/lib/report/reviewPassModel.mjs"; import AnchoredNotes from "@/components/notes/AnchoredNotes"; import { useSharedNotes } from "@/components/notes/NotesProvider"; import { keepClip, ruledInBench, writeWalkVerdict } from "../bench/walkVerdict"; import { MANIFEST_CHANGED, announceManifestChanged } from "../timelineApi"; import VersionVerdict from "../review/VersionVerdict"; import type { PlayEntry } from "../review/PlayCut"; import { READ_ONLY_SAID } from "./readOnly"; import { aModalIsOpen } from "@/components/ui/modalOpen"; // --------------------------------------------------------------------------- // THE REVIEW PASS (umtool redesign L7b; the workspace's `?mode=review`): the inspector hidden, the viewer playing // the draft block by block, and each block answered here -- // // Keep k a clip: its walk verdict `confirmed` (the bench's writer, bench/walkVerdict.ts) -- only while it has // none or is confirmed: a clip the bench ruled incorrect is shown, never overwritten (Full bench); a post // or a card: `keep` in review-pass.json (lib/report/reviewPass.mjs) // Fix f "needs work", saying what: a `fix` mark in review-pass.json on ANY block -- never a clip's verdict // Note n the notes composer, anchored to the block (notes.json, `umtool notes`) // // -- then on to the next block, playing. After the last, the VERDICT for the draft (saved as a version first when // it has edits: a verdict is a version's) or for the version being reviewed: Like · Maybe · No, L4's writer // (takes/verdicts.json, `umtool takes verdict`). "4 / 12 reviewed"; it resumes on the first block with no answer. // A version (`?take=`) is read-only: its blocks are watched and noted, never marked -- Open in draft to change it. // --------------------------------------------------------------------------- export type Answer = { mark: "keep" | "fix" | "ruled"; note: string | null; verdict?: string }; /** A mark as the server reads it against the cut now: `stale` when its block changed since it was reviewed. */ type Mark = { mark: "keep" | "fix"; note?: string; at: string; stale?: boolean }; /** The pass's state: the marks (review-pass.json), each block's answer, the progress, and the writers. */ export function useReviewPass(project: string, entries: PlayEntry[], on: boolean, readOnly = false) { const [marks, setMarks] = useState>({}); const [loaded, setLoaded] = useState(false); // A clip's answer as just written, until the draft is read again (MANIFEST_CHANGED) and its verdict is in it. const [written, setWritten] = useState>({}); useEffect(() => setWritten({}), [entries]); const marksSeq = useRef(0); const readMarks = useCallback(async () => { const mine = ++marksSeq.current; try { const j = (await (await fetch(`/api/report/review-pass?project=${encodeURIComponent(project)}`, { cache: "no-store" })).json()) as { marks?: Record }; if (mine === marksSeq.current) setMarks(j.marks ?? {}); } finally { if (mine === marksSeq.current) setLoaded(true); } }, [project]); useEffect(() => { if (on) void readMarks().catch(() => {}); }, [on, readMarks]); // The draft changed (a write here or elsewhere): a mark's block may no longer be what was reviewed -- read again. useEffect(() => { if (!on) return; const onChange = (ev: Event) => { if ((ev as CustomEvent).detail?.project === project) void readMarks().catch(() => {}); }; window.addEventListener(MANIFEST_CHANGED, onChange); return () => window.removeEventListener(MANIFEST_CHANGED, onChange); }, [on, project, readMarks]); const seen = useMemo( () => entries.map((e) => { const w = written[e.id]; if (!w || e.type !== "clip") return e; return { ...e, review: { verdict: "confirmed", reason: null, correction: null, rejectNote: null } }; }), [entries, written], ); const progress = useMemo(() => reviewProgress(seen, marks) as { done: number; total: number; next: string | null; ids: string[] }, [seen, marks]); const answers = useMemo(() => { const m = new Map(); for (const e of seen) { const a = blockAnswer(e, marks) as Answer | null; if (a) m.set(e.id, a); } return m; }, [seen, marks]); const postMark = useCallback( async (block: string, mark: "keep" | "fix" | null, note: string | null): Promise => { const r = await fetch("/api/report/review-pass", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, block, mark, note: note ?? undefined }), }); const j = (await r.json().catch(() => ({}))) as { error?: string; doc?: { marks?: Record } }; if (!r.ok) return j.error ?? `HTTP ${r.status}`; setMarks(j.doc?.marks ?? {}); return null; }, [project], ); /** * One block answered. Fix ("needs work"), on any block, is a mark in review-pass.json -- never a clip's verdict. * Keep on a clip is its walk verdict `confirmed` (the bench's writer), only while it has none or is confirmed: a * clip the bench ruled incorrect is the bench's to change. Keep on anything else is a mark. */ const answer = useCallback( async (e: PlayEntry, mark: "keep" | "fix", note: string | null): Promise => { // A version on screen (readOnly.ts): its marks would land on the draft's blocks. if (readOnly) return READ_ONLY_SAID; if (mark === "fix" || e.type !== "clip") return postMark(e.id, mark, note); if (!clipKeepable(e)) return ruledInBench(String(clipVerdict(e))); // The verdict first; a Fix it carried is taken back only once it is written (keepClip). const r = await keepClip({ confirmed: clipVerdict(e) === "confirmed", hasMark: !!marks[e.id], writeVerdict: () => writeWalkVerdict(project, e.id, { verdict: "confirmed" }), clearMark: () => postMark(e.id, null, null), }); if (r.wrote) { setWritten((x) => ({ ...x, [e.id]: { mark: "keep", note: null } })); announceManifestChanged(project); } return r.error; }, [project, readOnly, postMark, marks], ); return { marks, loaded, progress, answers, answer }; } export type ReviewPassState = ReturnType; const VERDICTS = [ { id: "like", label: "Like" }, { id: "maybe", label: "Maybe" }, { id: "no", label: "No" }, ] as const; /** The draft's verdict: saved as a version first (a verdict is a version's), then judged with L4's writer. */ function DraftVerdict({ project, draft }: { project: string; draft: { line: string; parent: string | null; edits: number | null } | null }) { // Always the server's answer (never a shortcut fixed at mount: a Keep is an edit, and the draft read here may be // older than the write it follows). const [saved, setSaved] = useState<{ id: string; saved: boolean } | null>(null); const [busy, setBusy] = useState(false); const [err, setErr] = useState(null); if (saved) { return ( {saved.saved ? ( <> Saved {saved.id} and judged it: ) : ( <> Judged {saved.id}: )} ); } const judge = async (v: (typeof VERDICTS)[number]["id"]) => { setBusy(true); setErr(null); try { // One locked call (versions.mjs judgeDraft): the parent when only review fields differ, else saved, then judged. const r = await fetch("/api/report/review-pass/verdict", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, verdict: v }) }); const j = (await r.json().catch(() => ({}))) as { judged?: string; saved?: boolean; error?: string }; if (!r.ok || !j.judged) throw new Error(j.error ?? `HTTP ${r.status}`); setSaved({ id: j.judged, saved: !!j.saved }); // A version saved for it: the draft's line ("from vN") is read again. Its token did not move (the manifest is // as it was), so the workspace keeps its Redo and its Undo token (the MANIFEST_CHANGED rule, L8b). if (j.saved) announceManifestChanged(project); } catch (e) { setErr(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } }; return ( {draft?.line ?? "The draft"}: {VERDICTS.map((v) => ( ))} {err && ( {err} )} ); } const TYPE_WORD: Record = { clip: "Clip", post: "Post", teaser: "Card", card: "Card", video: "Video" }; export default function ReviewPass({ project, rv, entry, atEnd, take, readOnly, draft, onPrev, onNext, onAnswered, onExit, }: { project: string; rv: ReviewPassState; /** The block under review (null at the end). */ entry: PlayEntry | null; atEnd: boolean; /** A version reviewed read-only, or null for the draft. */ take: { id: string; label: string } | null; /** The workspace's read-only flag (readOnly.ts): Keep and Fix refuse. */ readOnly: boolean; draft: { line: string; parent: string | null; edits: number | null } | null; onPrev: () => void; onNext: () => void; /** A block was answered: the pass moves on (and plays the next). */ onAnswered: () => void; onExit: () => void; }) { const notes = useSharedNotes({ project }); const [fixing, setFixing] = useState(false); const [fixText, setFixText] = useState(""); const [noting, setNoting] = useState(false); const [busy, setBusy] = useState(false); const [err, setErr] = useState(null); const id = entry?.id ?? null; useEffect(() => { setFixing(false); setNoting(false); setErr(null); setFixText(""); }, [id]); const answer = id ? (rv.answers.get(id) ?? null) : null; // Marked once, but the block is not what was reviewed any more (an edge, a post's words, another version opened). const changed = !!(id && rv.marks[id]?.stale); // A Fix gone stale keeps what it said: shown under "changed since reviewed", and the Fix form opens on it. const staleFix = changed && id && rv.marks[id]?.mark === "fix" ? (rv.marks[id]?.note ?? null) : null; // The bench's ruling on a clip (incorrect: a fact error, wrong speaker), shown and left as it is. const bench = entry?.type === "clip" && !clipKeepable(entry) ? { verdict: String(clipVerdict(entry)), words: entry.review?.correction || entry.rejected?.label || entry.review?.reason || null } : null; const go = useCallback( async (mark: "keep" | "fix", note: string | null) => { if (!entry || readOnly || busy || (mark === "keep" && bench)) return; setBusy(true); setErr(null); const e = await rv.answer(entry, mark, note); setBusy(false); if (e) return setErr(e); setFixing(false); onAnswered(); }, [entry, readOnly, busy, rv, onAnswered, bench], ); const openFix = useCallback(() => { if (!entry || readOnly) return; setNoting(false); setFixText(answer?.mark === "fix" ? (answer.note ?? "") : (staleFix ?? "")); setFixing(true); }, [entry, readOnly, answer, staleFix]); // k / f / n: the block's answers (the workspace keeps Space and ← →). const keys = useRef({ go, openFix, setNoting }); keys.current = { go, openFix, setNoting }; useEffect(() => { const onKey = (ev: KeyboardEvent) => { if (ev.metaKey || ev.ctrlKey || ev.altKey) return; // A held key is one answer, never a run of them over blocks nobody watched. if (ev.repeat) return; // A modal is up (⌘K, the Keys): the keys are its. if (aModalIsOpen()) return; const t = ev.target as HTMLElement | null; if (t?.closest("input, textarea, select, [contenteditable=true], [role=dialog]")) return; if (ev.key === "k" || ev.key === "K") void keys.current.go("keep", null); else if (ev.key === "f" || ev.key === "F") keys.current.openFix(); else if (ev.key === "n" || ev.key === "N") keys.current.setNoting(true); else return; ev.preventDefault(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, []); const { done, total } = rv.progress; const btn = (variant: "go" | "outline" | "quiet") => cn(buttonVariants({ variant, size: "md" })); return (
Review pass {take && ( {take.id} · read-only )} {done} / {total} reviewed
{atEnd || !entry ? (

{done === total ? "Every block reviewed" : `${total - done} block${total - done === 1 ? "" : "s"} not reviewed`}

{take ? ( {take.id} “{take.label}”: ) : ( )}
{rv.progress.next && ( )}
) : (
{TYPE_WORD[entry.type] ?? entry.type} {entry.id} {answer && answer.mark !== "ruled" && ( {answer.mark === "keep" ? "kept" : `needs work: ${answer.note ?? ""}`} )}
{changed && !answer && (

changed since reviewed

)} {staleFix && !answer && (

it needed work: {staleFix}

)} {/* A clip the bench ruled (a fact error, wrong speaker): the pass shows it and never overwrites it. */} {bench && (

marked {bench.verdict} in the bench{bench.words ? `: ${bench.words}` : ""}{" "} Full bench

)} {(entry.quote || entry.heading) &&

{entry.type === "clip" && entry.quote ? `“${entry.quote}”` : entry.heading}

}
{readOnly && take && ( Open in draft )}
{fixing && (
{ e.preventDefault(); if (fixText.trim()) void go("fix", fixText.trim()); }} >