"use client"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import CitedClip, { warmCited, type CitedClipHandle } from "@/components/clips/CitedClip"; import { buttonVariants } from "@/components/ui/button"; import { awaitingReview } from "@/lib/inbox/drafts.mjs"; import { editTextOf, isEditableField } from "@/lib/report/draftEdit.mjs"; import { litCount, spokenWords } from "@/lib/clips/words"; import { REJECT_REASONS } from "@/lib/report/rejectReasons.mjs"; import { cn } from "@/lib/utils"; import { useDrafts, type DraftRow, type DraftsView } from "../drafts"; import type { FieldEvidence, FieldProvenance } from "../MediaDrafts"; // --------------------------------------------------------------------------- // THE AUDITION (release 32 R1; the operator's "like a swipe app"): the drafts // review as a deck of cards, one field per card. The model did the heavy // lifting -- it drafted the field and picked the moment; the person's one job // is to LISTEN and rule. So the cited span is already playing, the decision is // one gesture, and the next card is already loaded underneath. // // swipe → / → k KEEP approve the draft as it is // swipe ← / ← x CUT reject it; a reason chip or a few words, never required // swipe ↑ / ↑ e EDIT the value as text on the card; Enter keeps it as edited // swipe ↓ / ↓ s SKIP to the back of the stack // tap the video / space replay the span // z / Backspace UNDO the last keep, cut or skip (20 deep) // tap a word / m mark it MISHEARD (the note says so; the article's page fixes it) // // Decisions write through the drafts route (drafts.review.json), the same as // the list view (`?view=list`). An EDIT writes the field through the // manifest's writer and is undone from the History tab, not with z. // --------------------------------------------------------------------------- type Decision = "kept" | "cut" | "edited"; type Undo = { address: string; kind: "kept" | "cut" | "skip"; prev: { verdict: DraftRow["verdict"]; note: string } }; // The walk's reject vocabulary (lib/report/rejectReasons.mjs: doesn't match, wrong speaker, irrelevant, // repeats, weak, privacy), with the two a drafted MOMENT can also be wrong by, and "too long". A chip // is words in the note, never a verdict on the clip. const CUT_REASONS = ["misheard", "wrong moment", ...REJECT_REASONS.filter((r) => r.id !== "other").map((r) => r.label), "too long"]; const THRESHOLD = 0.3; const FLICK = 0.6; const UNDO_DEPTH = 20; // The next card rises into place (120 ms); with reduced motion it does not move. const DECK_CSS = `@keyframes deck-rise { from { transform: scale(0.97) translateY(4px); } to { transform: none; } } .deck-rise { animation: deck-rise 120ms ease-out; } @keyframes deck-out-right { from { transform: translate(var(--dx), var(--dy)) rotate(var(--r)); } to { transform: translate(120%, 0) rotate(8deg); opacity: 0.6; } } @keyframes deck-out-left { from { transform: translate(var(--dx), var(--dy)) rotate(var(--r)); } to { transform: translate(-120%, 0) rotate(-8deg); opacity: 0.6; } } @keyframes deck-out-down { from { transform: translate(var(--dx), var(--dy)); } to { transform: translate(0, 110%); opacity: 0; } } @keyframes deck-fade { from { opacity: 1; } to { opacity: 0; } } .deck-out-right { animation: deck-out-right 160ms ease-in forwards; } .deck-out-left { animation: deck-out-left 160ms ease-in forwards; } .deck-out-down { animation: deck-out-down 160ms ease-in forwards; } .deck-fade { animation: deck-fade 80ms linear forwards; } @media (prefers-reduced-motion: reduce) { .deck-rise { animation: none; } }`; // KEEP reads from the side the card leaves by: top left; CUT and SKIP top right. const stampClass = (kind: string) => cn( "pointer-events-none absolute top-28 z-10 rotate-[-8deg] rounded-[4px] border-[3px] px-2.5 py-0.5 font-display text-[28px] font-bold uppercase tracking-wide", kind === "KEEP" ? "left-4 border-signal text-signal" : kind === "CUT" ? "right-4 border-muted text-muted line-through" : "right-4 border-seam-2 text-text-2", ); const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; export default function AuditionDeck({ project, initial, provenance, evidence, back, listHref, respell, }: { project: string; initial: DraftsView; provenance: Record; evidence: Record; /** The Media tab. */ back: string; listHref: string; /** The article's page, where a mishearing is fixed (null: no article claims the cut). */ respell: string | null; }) { const drafts = useDrafts(project, initial); const view = drafts.view ?? initial; const rowOf = useCallback((a: string) => view.rows.find((r) => r.address === a) ?? null, [view.rows]); const [queue, setQueue] = useState(() => awaitingReview(initial.rows, provenance).map((r: DraftRow) => r.address)); const [total, setTotal] = useState(queue.length); const [decided, setDecided] = useState>(new Map()); const [skipped, setSkipped] = useState>(new Set()); const [undos, setUndos] = useState([]); const [started, setStarted] = useState(false); const [editing, setEditing] = useState(null); const [editText, setEditText] = useState(""); const [reason, setReason] = useState(""); const [misheard, setMisheard] = useState>>(new Map()); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const [drag, setDrag] = useState<{ dx: number; dy: number } | null>(null); // The card that was just decided, flying out over the next one: a picture of // it only, so a key pressed during the exit is never lost. const [ghost, setGhost] = useState(null); const [reduced, setReduced] = useState(false); const [hints, setHints] = useState(false); const clip = useRef(null); const card = useRef(null); const start = useRef<{ x: number; y: number; t: number; id: number } | null>(null); useEffect(() => { const m = window.matchMedia("(prefers-reduced-motion: reduce)"); setReduced(m.matches); const on = () => setReduced(m.matches); m.addEventListener("change", on); return () => m.removeEventListener("change", on); }, []); const live = queue.filter((a) => !skipped.has(a)); const top = live[0] ?? null; const under = live[1] ?? null; const row = top ? rowOf(top) : null; const ev = row?.entry ? (evidence[row.entry] ?? null) : null; const counts = useMemo(() => { const c = { kept: 0, cut: 0, edited: 0 }; for (const d of decided.values()) c[d] += 1; return c; }, [decided]); const done = decided.size; // Where the deck is: every card ruled or skipped so far, then this one. const at = Math.min(done + skipped.size + 1, total); const hintShown = hints || done + skipped.size < 3; // The card after the next: ask what plays it before it is shown. useEffect(() => { const after = live[2]; const e = after ? evidence[rowOf(after)?.entry ?? ""] : null; if (e?.target) warmCited(e.target); }, [live, evidence, rowOf]); const noteFor = (address: string, extra: string) => { const words = misheard.get(address); const quote = evidence[rowOf(address)?.entry ?? ""]?.quote ?? ""; const marked = words?.size ? `misheard: ${[...words].map((i) => quote.split(/\s+/).filter(Boolean)[i]).filter(Boolean).join(", ")}` : ""; return [extra, marked].filter(Boolean).join(" · "); }; const remember = (u: Undo) => setUndos((s) => [...s.slice(-(UNDO_DEPTH - 1)), u]); const commit = useCallback( async (kind: "kept" | "cut" | "skip", address: string) => { const r = rowOf(address); if (!r) return; const prev = { verdict: r.verdict, note: r.note ?? "" }; setError(null); if (kind === "skip") { setSkipped((s) => new Set(s).add(address)); setQueue((q) => [...q.filter((a) => a !== address), address]); remember({ address, kind, prev }); return; } setQueue((q) => q.filter((a) => a !== address)); setDecided((d) => new Map(d).set(address, kind)); remember({ address, kind, prev }); try { if (kind === "kept") await drafts.act("approve", { address, note: noteFor(address, r.note ?? "") }); else await drafts.act("reject", { address, note: noteFor(address, reason || r.note || "cut on the deck") }); setReason(""); } catch (e) { setError(e instanceof Error ? e.message : String(e)); setQueue((q) => [address, ...q.filter((a) => a !== address)]); setDecided((d) => { const n = new Map(d); n.delete(address); return n; }); setUndos((s) => s.slice(0, -1)); } }, // eslint-disable-next-line react-hooks/exhaustive-deps [rowOf, drafts, reason, misheard, evidence], ); const decide = useCallback( (dir: "right" | "left" | "up" | "down") => { if (!top || busy) return; setStarted(true); if (dir === "up") { setDrag(null); const r = rowOf(top); if (!r) return; setEditing(top); setEditText(editTextOf(r.field, r.text)); return; } const address = top; const id = Date.now(); setGhost({ address, dir, dx: drag?.dx ?? 0, dy: drag?.dy ?? 0, id }); setDrag(null); window.setTimeout(() => setGhost((g) => (g?.id === id ? null : g)), reduced ? 80 : 160); void commit(dir === "right" ? "kept" : dir === "left" ? "cut" : "skip", address); }, [top, busy, drag, rowOf, commit, reduced], ); const undo = useCallback(async () => { const u = undos[undos.length - 1]; if (!u || busy) return; setUndos((s) => s.slice(0, -1)); setError(null); if (u.kind === "skip") { setSkipped((s) => { const n = new Set(s); n.delete(u.address); return n; }); setQueue((q) => [u.address, ...q.filter((a) => a !== u.address)]); return; } setBusy(true); try { if (!u.prev.verdict) await drafts.act("clear", { address: u.address }); else if (u.prev.verdict === "approved") await drafts.act("approve", { address: u.address, note: u.prev.note }); else await drafts.act("reject", { address: u.address, note: u.prev.note || "cut on the deck" }); setDecided((d) => { const n = new Map(d); n.delete(u.address); return n; }); setQueue((q) => [u.address, ...q.filter((a) => a !== u.address)]); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } }, [undos, busy, drafts]); const saveEdit = async () => { if (!editing) return; const address = editing; setBusy(true); setError(null); try { await drafts.act("edit", { address, text: editText, token: view.token ?? null, note: noteFor(address, "edited on the deck") }); setEditing(null); setQueue((q) => q.filter((a) => a !== address)); setDecided((d) => new Map(d).set(address, "edited")); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } }; const toggleWord = (address: string, i: number) => setMisheard((m) => { const n = new Map(m); const s = new Set(n.get(address) ?? []); if (s.has(i)) s.delete(i); else s.add(i); n.set(address, s); return n; }); // The keys. Typing (the edit, the cut's few words) and a focused word keep theirs. useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; const t = e.target as HTMLElement | null; if (editing) { if (e.key === "Escape") { e.preventDefault(); setEditing(null); } return; } if (t?.closest?.(TYPING)) return; if (t?.closest?.("[data-word]") && (e.key === " " || e.key === "Enter")) return; const k = e.key; const act = (fn: () => void) => { e.preventDefault(); fn(); }; if (k === "ArrowRight" || k === "k") act(() => decide("right")); else if (k === "ArrowLeft" || k === "x") act(() => decide("left")); else if (k === "ArrowUp" || k === "e") act(() => decide("up")); else if (k === "ArrowDown" || k === "s") act(() => decide("down")); else if (k === "z" || k === "Backspace") act(() => void undo()); else if (k === " ") act(() => { setStarted(true); clip.current?.playSpan(); }); else if (k === "?") act(() => setHints((h) => !h)); else if (k === "m") act(() => card.current?.querySelector("[data-word]")?.focus()); else if (k === "Escape") (document.activeElement as HTMLElement | null)?.blur?.(); }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }, [decide, undo, editing]); // The drag: past 30 % of the card's width, or a flick, decides; below it springs back. const onPointerDown = (e: React.PointerEvent) => { if (editing || e.button !== 0) return; if ((e.target as HTMLElement).closest("button, a, input, textarea, select, [data-word]")) return; start.current = { x: e.clientX, y: e.clientY, t: performance.now(), id: e.pointerId }; }; const onPointerMove = (e: React.PointerEvent) => { const s = start.current; if (!s || s.id !== e.pointerId) return; const dx = e.clientX - s.x; const dy = e.clientY - s.y; if (!drag && Math.hypot(dx, dy) < 6) return; if (!drag) (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); setDrag({ dx, dy }); }; const onPointerUp = (e: React.PointerEvent) => { const s = start.current; start.current = null; if (!s || !drag) return; const w = card.current?.offsetWidth ?? 400; const dt = Math.max(1, performance.now() - s.t); const { dx, dy } = drag; const horizontal = Math.abs(dx) >= Math.abs(dy); const d = horizontal ? dx : dy; if (Math.abs(d) > THRESHOLD * w || Math.abs(d) / dt > FLICK) { decide(horizontal ? (dx > 0 ? "right" : "left") : dy < 0 ? "up" : "down"); } else setDrag(null); void e; }; // The stamp the drag is heading for. const stamp = drag ? Math.abs(drag.dx) >= Math.abs(drag.dy) ? { kind: drag.dx > 0 ? "KEEP" : "CUT", o: Math.min(1, Math.abs(drag.dx) / ((card.current?.offsetWidth ?? 400) * THRESHOLD)) } : { kind: drag.dy < 0 ? "EDIT" : "SKIP", o: Math.min(1, Math.abs(drag.dy) / ((card.current?.offsetWidth ?? 400) * THRESHOLD)) } : null; const transform = drag ? `translate(${drag.dx}px, ${drag.dy}px) rotate(${drag.dx * 0.04}deg)` : undefined; const toggle = (
Deck List {total ? `${at} / ${total}` : "0 / 0"} · {counts.kept} kept · {counts.cut} cut{counts.edited ? ` · ${counts.edited} edited` : ""} · {skipped.size} skipped
); if (!total) { return (
{toggle}

Nothing is waiting for a verdict.

Back to the Media tab
); } if (!top) { const cut = [...decided].filter(([, d]) => d === "cut").map(([a]) => a); const skip = [...skipped]; return (
{toggle}

{counts.kept} kept · {counts.cut} cut{counts.edited ? ` · ${counts.edited} edited` : ""} {skip.length ? ` · ${skip.length} skipped` : ""}

{[ { label: "Cut", list: cut }, { label: "Skipped", list: skip }, ] .filter((g) => g.list.length) .map((g) => (
{g.label}
    {g.list.map((a) => (
  • {rowOf(a)?.entry ?? rowOf(a)?.label} {rowOf(a)?.text} {g.label === "Cut" && rowOf(a)?.note ? — {rowOf(a)?.note} : null}
  • ))}
))}
{skip.length > 0 && ( )} {cut.length > 0 && ( )} Back to the Media tab
{error &&

{error}

}
); } const peeks = Math.min(3, live.length - 1); return ( // On a phone the bar is the dock: the page clears it and the safe area under it.
{toggle}
{/* The next card, underneath: its media loading already. */} {under && (
)}
{ start.current = null; setDrag(null); }} className="deck-card deck-rise relative z-[2] touch-pan-y select-none rounded-[8px] border border-seam-2 bg-panel shadow-sm outline-none focus-visible:ring-2 focus-visible:ring-signal" style={{ transform, transition: drag ? "none" : "transform 120ms ease-out", }} > {stamp && stamp.o > 0.05 && ( {stamp.kind} )} toggleWord(top, i)} project={project} editing={editing === top} editText={editText} onEditText={setEditText} onSaveEdit={() => void saveEdit()} onCancelEdit={() => setEditing(null)} back={back} respell={respell} busy={busy} /> {!started && (
)}
{ghost && (
{ghost.dir === "right" ? "KEEP" : ghost.dir === "left" ? "CUT" : "SKIP"}
{rowOf(ghost.address)?.label}

{rowOf(ghost.address)?.text}

)}
{/* The stack's edges: as many as fields remain, up to three (depth is the truth). */} {peeks > 0 && (
{Array.from({ length: peeks }, (_, i) => (
))}
)} {/* A cut's reason: optional, one tap. */}
{CUT_REASONS.map((r) => ( ))} setReason(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); (e.target as HTMLInputElement).blur(); decide("left"); } }} placeholder="or why, in a few words" aria-label="Why cut, in a few words" data-cut-note="" maxLength={300} className="min-w-[10rem] flex-1 rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[2px] text-[11.5px] text-text outline-none focus:border-signal max-md:min-h-11 max-md:text-[16px]" />
{error && (

{error}

)} {/* Every gesture is a button too: a bar under the thumb on a phone. */} {/* The one hint row: it fades once three cards are decided; `?` brings it back. */}
); } function DeckButton({ action, label, k, go = false, disabled, onClick }: { action: string; label: string; k: string; go?: boolean; disabled?: boolean; onClick: () => void }) { return ( ); } /** One field's card: what is judged, the span playing, the lit line, where it came from. */ function Card({ address, row, ev, preload = false, playing = false, clipRef, marked = null, onWord, project, editing = false, editText = "", onEditText, onSaveEdit, onCancelEdit, back, respell = null, busy = false, }: { address: string; row: DraftRow | null; ev: FieldEvidence | null; preload?: boolean; playing?: boolean; clipRef?: React.Ref; marked?: Set | null; onWord?: (i: number) => void; project?: string; editing?: boolean; editText?: string; onEditText?: (s: string) => void; onSaveEdit?: () => void; onCancelEdit?: () => void; back?: string; respell?: string | null; busy?: boolean; }) { const [now, setNow] = useState(null); const t = ev?.target ?? null; const words = useMemo(() => (ev?.quote && t ? spokenWords(ev.quote, ev.cues, t.from, t.to) : []), [ev, t]); const lit = now === null ? 0 : litCount(words, now); const value = row?.text ?? ""; const editable = row ? isEditableField(row.field) : false; const misheardWords = marked?.size ? [...marked].map((i) => words[i]?.text).filter(Boolean) : []; return (
{row?.label ?? address} {row?.entry && {row.entry}}
{editing && !editable ? (

{value}

This field is edited in its own section:{" "} the Media tab .{" "}

) : editing ? (