"use client"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import ChainPanel from "@/components/articles/ChainPanel"; import CitedClip from "@/components/clips/CitedClip"; import type { CitedTarget } from "@/lib/clips/types"; import { buttonVariants } from "@/components/ui/button"; import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; import { LitList, type LitDetail } from "@/components/ui/lit-list"; import { useHydrated } from "@/components/ui/use-hydrated"; import { clock } from "@/components/ui/clock"; import { ReaderPane } from "@/components/ui/reader-pane"; import { narrationHref, reviewHref } from "@/lib/hrefs"; import { citationText } from "@/lib/research/facets.mjs"; import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft"; import { awaitingReview } from "@/lib/inbox/drafts.mjs"; import { DraftControl, modelsFor, usePolicy } from "./DraftPanel"; import { DraftAlternatives, announceDraftsChanged, useDrafts, type DraftAct, type DraftRow, type DraftsView, type FieldProvenance } from "./drafts"; import { announceManifestChanged } from "./timelineApi"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; import CopyCitation from "./bench/CopyCitation"; // --------------------------------------------------------------------------- // THE MEDIA SURFACE (plans/umtool-redesign.md, P4b; canvas "Piece · Media"): // every drafted field of the cut, one line each -- what it says, where it came // from (the model, the attempts, the rule a refused attempt broke), its review // -- grouped by the section that drafts it, each section headed by its "Draft // with ". Approve or reject per field, Approve all, Draft everything. // It absorbs release 28's review page (DraftsReview), the project page's Draft // panel and the Iterations tab's media drafts: the Media tab draws it with // the sections' controls, the review bench (`…/review`) draws its field list // alone, one field at a time, with the verdict bar and the reader. // // The fields are ONE lit list (j/k from anywhere); `a` approves the lit field // as it is, `r` rejects it (the note is the answer: the cursor goes there // first). Signal is the lit field's Approve draft only. // --------------------------------------------------------------------------- // Where a drafted field came from: declared beside the drafts view, which carries it from the route. export type { FieldProvenance } from "./drafts"; /** The sections, in Draft everything's order: a field's address starts with its section's task. */ export const MEDIA_SECTIONS: { task: string; label: string }[] = [ { task: "cut", label: "Cut" }, { task: "onscreen", label: "On-screen" }, { task: "teaser", label: "Teaser" }, { task: "flips", label: "Flips" }, { task: "threads", label: "Threads" }, { task: "narrate", label: "Narration" }, { task: "youtube", label: "YouTube" }, { task: "social", label: "Social" }, ]; const sectionOf = (address: string) => address.split("/")[0]; const STATE_WORDS: Record = { approved: "approved", rejected: "rejected", edited: "changed since approved", unreviewed: "not reviewed", }; const STATE_TONE: Record = { approved: "text-meter", rejected: "text-reject-text", edited: "text-doubt-text", unreviewed: "text-muted-2", }; const day = (iso: string | null) => { if (!iso) return null; const d = new Date(iso); return Number.isNaN(d.getTime()) ? null : `${d.toISOString().slice(0, 10)} ${d.toISOString().slice(11, 16)}`; }; /** The provenance line: the file, when and by what, the attempts, the rules refused attempts broke, the review. */ export function ProvenanceLine({ row, prov }: { row: DraftRow; prov: FieldProvenance | null }) { const by = row.drafted?.model ?? prov?.model ?? null; const at = day(row.drafted?.at ?? prov?.at ?? null); const parts: React.ReactNode[] = []; if (prov) parts.push(prov.file); if (row.drafted || prov) parts.push(`drafted${at ? ` ${at}` : ""}${by ? ` by ${by}` : ""}`); else parts.push("written by hand"); if (prov) { if (prov.repaired) parts.push(`repaired from ${prov.attempts} attempt${prov.attempts === 1 ? "" : "s"}`); else if (prov.chosen) parts.push(`attempt ${prov.chosen} of ${prov.attempts}${prov.attempts > 1 ? " chosen" : ""}`); for (const f of prov.failed.filter((x) => x.attempt !== prov.chosen)) { parts.push( attempt {f.attempt} failed: ✕ {f.hard.join("; ")} , ); } if (prov.failed.length === 0 && prov.chosen) parts.push("no rule broken"); if (prov.soft.length) parts.push(flag: {prov.soft.join("; ")}); } else if (row.drafted) { parts.push(`attempt ${row.drafted.attempt}`); } parts.push({STATE_WORDS[row.state]}); return (
{parts.map((p, i) => ( {i > 0 && " · "} {p} ))}
); } /** One drafted field: its name, its words and provenance, Approve draft / Reject (+ note), its alternatives. */ function FieldLine({ row, prov, view, act, lit, go, noteRef, }: { row: DraftRow; prov: FieldProvenance | null; view: DraftsView; act: DraftAct; lit: boolean; /** The lit line's Approve draft is the screen's one filled action (the tab); a bench's is its verdict bar's. */ go: boolean; noteRef?: (el: HTMLInputElement | null) => void; }) { const [note, setNote] = useState(row.note ?? ""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); useEffect(() => setNote(row.note ?? ""), [row.note]); const run = async (action: string, extra: Record = {}) => { setBusy(true); setError(null); try { await act(action, { address: row.address, ...extra }); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } }; const where = row.entry ? `${sectionLabel(row.address)} · ${row.entry}` : `${sectionLabel(row.address)} · ${row.field}`; return (
{row.entry ?? row.label} {where}

{row.text || "—"}

{row.state === "edited" && row.judgedText && (

{row.verdict} on: {row.judgedText}

)} {error && (

{error}

)}
{row.field === "narration" && row.entry && ( edit and play )} setNote(e.target.value)} onBlur={() => { if (note.trim() !== (row.note ?? "") && row.verdict) void run("note", { note }); }} disabled={busy} placeholder="note (a rejection needs one)" aria-label={`note on the draft of ${row.address}`} data-draft-note="" maxLength={2000} className="w-full min-w-0 rounded-[3px] border border-seam-2 bg-ground px-1.5 py-0.5 text-[11.5px] text-text" />
); } // The project id rides on the view so a line can link its narration page. const viewProject = (v: DraftsView) => (v as DraftsView & { project?: string }).project ?? ""; const sectionLabel = (address: string) => MEDIA_SECTIONS.find((s) => s.task === sectionOf(address))?.label ?? sectionOf(address); /** A field that is the operator's, with a draft kept aside for it. */ function LooseLine({ address, view, act }: { address: string; view: DraftsView; act: DraftAct }) { const a = view.alternatives.find((x) => x.address === address)!; return (
{a.entry ?? a.label} yours · a draft kept aside
); } export type MediaFieldsProps = { project: string; view: DraftsView; act: DraftAct; provenance: Record; /** The sections' heads: the Media tab's "Draft with" per task; the bench has none. */ heads?: Partial>; /** Only these sections (a chip's filter). */ only?: string | null; onLit?: (address: string | null) => void; /** The lit field's Approve draft is filled (false on a bench: the verdict bar's is). */ lineGo?: boolean; }; /** The field list: one lit list, grouped by section, `a` / `r` on the lit field. */ export function MediaFields({ project, view, act, provenance, heads, only = null, onLit, lineGo = true }: MediaFieldsProps) { const rows = view.rows; const shown = new Set(rows.map((r) => r.address)); const loose = [...new Set(view.alternatives.filter((a) => !a.inUse && !shown.has(a.address)).map((a) => a.address))]; const [lit, setLit] = useState(null); const notes = useRef(new Map()); const box = useRef(null); const v = useMemo(() => ({ ...view, project }) as DraftsView, [view, project]); const sections = MEDIA_SECTIONS.filter((s) => !only || s.task === only) .map((s) => ({ ...s, rows: rows.filter((r) => sectionOf(r.address) === s.task), loose: loose.filter((a) => sectionOf(a) === s.task), })) .filter((s) => heads?.[s.task] || s.rows.length || s.loose.length); const onLight = useCallback( (d: LitDetail) => { setLit(d.id); onLit?.(d.id); }, [onLit], ); // `a` approves the lit field as it is; `r` rejects it -- with its note, or // the cursor goes to the note first (the note is the answer). const hydrated = useHydrated(); useEffect(() => { if (!hydrated) return; const onKey = (e: KeyboardEvent) => { if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; const t = e.target as HTMLElement | null; if (t?.closest?.("input, textarea, select, video, audio, [contenteditable='true'], dialog[open]")) return; // From the list itself or from nowhere in particular -- never from a // control elsewhere on the tab (the on-screen panel's). if (t && t !== document.body && !box.current?.contains(t)) return; if (e.key !== "a" && e.key !== "r") return; const row = rows.find((r) => r.address === lit); if (!row) return; e.preventDefault(); if (e.key === "a") { if (row.state !== "approved") void act("approve", { address: row.address, note: row.note ?? "" }).catch(() => {}); return; } const input = notes.current.get(row.address); if (input && !input.value.trim()) { input.focus(); return; } void act("reject", { address: row.address, note: input?.value ?? row.note ?? "" }).catch(() => input?.focus()); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [hydrated, rows, lit, act]); if (sections.length === 0) { return (

Nothing in this cut was drafted.

); } return (
{sections.map((s) => ( {heads?.[s.task] &&
{heads[s.task]}
} {s.rows.map((r) => ( { if (el) notes.current.set(r.address, el); else notes.current.delete(r.address); }} /> ))} {s.loose.map((a) => ( ))}
))}
); } /** The gate line: what a final build would say of the review. */ export function GateLine({ view }: { view: DraftsView }) { return (

{view.error ? ( {view.error} ) : view.gate.errors.length ? ( <> A final build refuses {view.gate.errors.length} field{view.gate.errors.length === 1 ? "" : "s"} until approved ( --drafts-unreviewed builds the unapproved anyway; never a rejected one). ) : ( <>A final build takes every draft as it is. )}{" "} Verdicts in {view.file}.

); } /** Approve every field still to review, one after another. */ export function ApproveAll({ view, act, provenance }: { view: DraftsView; act: DraftAct; provenance: Record }) { const hydrated = useHydrated(); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const todo = awaitingReview(view.rows, provenance); if (!todo.length) return null; return ( <> {error && {error}} ); } // ─── the Media tab ─────────────────────────────────────────────────────────── export default function MediaDrafts({ project, initial, provenance: pageProvenance, link, rows, runs: initialRuns, narrated, }: { project: string; initial: DraftsView; provenance: Record; link: ProjectIteration; rows: DraftRowView[]; runs: Partial>; /** Narrated cards: the narration bench's link. */ narrated: number; }) { const router = useRouter(); const drafts = useDrafts(project, initial); const view = drafts.view ?? initial; // The route's, re-read with the rows; the page's until the first re-read. const provenance = view.provenance ?? pageProvenance; const linked = link.ok && link.status === "done"; const { policy, error: policyError } = usePolicy(linked); const [runs, setRuns] = useState(initialRuns); const [running, setRunning] = useState>(link.ok ? link.running : {}); const [only, setOnly] = useState(null); const [allModel, setAllModel] = useState(""); const [allRun, setAllRun] = useState(0); // Draft everything's deck option (release 29 G1, off by default): ticked, // the chain adds the minimal deck to a cut with none before the flips. The // run keeps the value it was started with. const [allDeck, setAllDeck] = useState(false); const [runDeck, setRunDeck] = useState(false); const allModels = modelsFor(policy, "onscreen"); useEffect(() => { if (!allModel && allModels.route) setAllModel(allModels.route); }, [allModels.route, allModel]); // A draft ended: the manifest changed under every section -- re-read it all. const onEnded = useCallback(async (): Promise => { const r = await fetch(`/api/articles/draft?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); if (r?.ok) { const b = await r.json(); setRuns(b.runs ?? {}); if (b.link?.ok) setRunning(b.link.running ?? {}); } announceManifestChanged(project); announceDraftsChanged(project); router.refresh(); }, [project, router]); // A section's head: what it writes, what it holds, its Draft with. A cut // made from no iteration drafts nothing, so only the narration's head (its // bench's link) is drawn there. const heads: Record = {}; for (const row of rows) { if (!linked && !(row.task === "narrate" && narrated > 0)) continue; heads[row.task] = (
{row.writes} {row.state}
{linked ? ( } policy={policy} run={runs[row.task]} runningJob={running[row.task] ?? null} onEnded={onEnded} /> ) : null} {row.task === "narrate" && narrated > 0 && ( Narration — {narrated}: edit and play the words → )}
); } // Every field on the list, drafted or a narration written by hand (the // view's own counts are the drafted fields', the final gate's). const total = view.rows.length; const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 }; for (const r of view.rows) counts[r.state] += 1; // To review: the drafted fields awaiting a verdict -- the tab's count and the Inbox's (awaitingReview). const waiting = awaitingReview(view.rows, provenance).length; const chips = MEDIA_SECTIONS.map((s) => ({ ...s, n: view.rows.filter((r) => sectionOf(r.address) === s.task).length })); return (
{total} field{total === 1 ? "" : "s"} · {counts.approved} approved {counts.rejected ? ` · ${counts.rejected} rejected` : ""} {waiting ? ` · ${waiting} to review` : ""} {link.ok && ( drafts are steps on{" "} {link.article} i{link.n} )} {total > 0 && ( Review drafts — {total} )} {linked && ( <> )}
{!link.ok ? (

Drafting is off: no article iteration made this project.

) : link.status !== "done" ? (

Drafting waits for {link.article} i{link.n}, which is {link.status}.

) : ( policyError && (

{policyError}: drafting needs the editor

) )} {link.ok && allRun > 0 && }
{chips.map((c) => ( ))}
); } const chipClass = (on: boolean) => `inline-flex items-center gap-1.5 whitespace-nowrap rounded-[3px] border px-2 py-[3px] text-[12px] ${on ? "border-muted bg-panel-2 text-text" : "border-seam-2 text-text-2 hover:border-muted"}`; // ─── the review bench (`…/review`) ─────────────────────────────────────────── export type FieldEvidence = { /** The clip's source, on the reader. */ source: string; byline: string[]; cite: { at: number; duration: number } | null; quote: string | null; url: string | null; cues: { start: number; end?: number; text: string }[]; /** What plays the span (components/clips/CitedClip.tsx); null when the entry names no source. */ target?: CitedTarget | null; /** Who is speaking, as the burned-in header names them. */ speaker?: string | null; }; /** * The drafts review as a bench: the field list as the work, ONE question on * the lit field in the verdict bar, and -- for a field drawn over a clip -- * that clip's source on the reader, its cited cue lit. */ export function MediaReview({ project, initial, provenance: pageProvenance, evidence, deckHref, }: { project: string; initial: DraftsView; provenance: Record; evidence: Record; /** The audition deck's address (release 32 R1): the toggle back. */ deckHref?: string; }) { const drafts = useDrafts(project, initial); const view = drafts.view ?? initial; const provenance = view.provenance ?? pageProvenance; const [lit, setLit] = useState(null); const hydrated = useHydrated(); const row = view.rows.find((r) => r.address === lit) ?? null; const todo = awaitingReview(view.rows, provenance); const ev = row?.entry ? (evidence[row.entry] ?? null) : null; const [error, setError] = useState(null); const approve = async () => { if (!row) return; setError(null); try { await drafts.act("approve", { address: row.address, note: row.note ?? "" }); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } }; const reject = () => { if (!row) return; const input = document.querySelector(`[data-draft-row="${CSS.escape(row.address)}"] [data-draft-note]`); if (input && !input.value.trim()) { input.focus(); return; } setError(null); drafts.act("reject", { address: row.address, note: input?.value ?? "" }).catch((e) => setError(e instanceof Error ? e.message : String(e))); }; const where = row ? (row.entry ? `${row.label} of ${row.entry}` : row.label) : ""; const verdict = ( The {where} is approved. ) : ( <>Approve the drafted {where}? ) ) : ( <>Nothing to review. ) } consequence={ !row ? undefined : row.state === "approved" ? todo.length ? `${todo.length} still to review.` : "Every field is approved: a final build takes them as they are." : row.state === "rejected" ? `Rejected${row.note ? `: ${row.note}` : ""} — a final build refuses it.` : "A final build refuses it until it is approved." } > {row && row.state !== "approved" && ( )} {row && row.state !== "rejected" && ( )} {error && {error}} ); const reader = ev ? ( ) : undefined } cues={ev.cues.map((c, i) => ({ t: c.start, text: c.text, lit: ev.cite ? i === litCueOf(ev.cues, ev.cite.at) : i === 0, }))} footer={ev.quote ? : undefined} fine={ev.quote ? `“${ev.quote}”` : undefined} /> ) : (

{row ? "No source window for this field: it is the cut's own words. Read it against the report." : "Light a field to see its source."}

); return ( {deckHref && (
Deck List
)}
); } const litCueOf = (cues: { start: number }[], at: number) => { let best = 0; cues.forEach((c, i) => { if (c.start <= at + 0.02) best = i; }); return best; };