"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 type { ClipDeckShow } from "@/lib/hrefs";
import type { ClipCard, ClipDeckView, ClipRuling } from "@/lib/report/clipDeck";
import { cn } from "@/lib/utils";
import { startTakeJob } from "../NewTakePanel";
// ---------------------------------------------------------------------------
// THE CLIP DECK (release 34 N1): a montage's instances, ruled by ear -- the
// co-host hazard is the point: a co-host's or a guest's line, or a post read
// out, credited to the host. One card per instance, its cut playing; the
// decision is one gesture, the next card is underneath. Built on the drafts
// review's audition deck (AuditionDeck.tsx, release 32 R1): the same swipe,
// stamps, undo and bar under the thumb; its own verdicts.
//
// swipe → / → k KEEP it is him, saying it
// swipe ← / ← x CUT out of the montage (a reason chip or a few words, never required)
// swipe ↓ / ↓ n NOT HIM another speaker: a co-host, a guest, a clip played
// swipe ↑ / ↑ r READ ALOUD him reading a post, a tweet, a quote out
// e EDIT the phrase the cut is cut to (Enter keeps it, wider)
// s SKIP to the back
// w WIDER: play the clip's whole extent, not just the phrase
// tap the video / space replay
// z / Backspace UNDO the last ruling or skip (20 deep)
//
// Rulings write through /api/report/montage-rulings (montage-rulings.json,
// keyed by the moment, so a re-seed keeps them); a render leaves out every
// clip ruled cut, not him or read aloud, and numbers the kept ones 1…N.
// ---------------------------------------------------------------------------
type Verdict = ClipRuling["verdict"];
type Dir = "right" | "left" | "down" | "up";
type Undo = { id: string; kind: "rule" | "skip"; prev: ClipRuling | null };
type Plan = { kept: { id: string; n: number | null; of: number | null; match: string | null }[]; left: { id: string; verdict: Verdict; reason: string }[]; lines: string[] };
const VERDICT_OF: Record
= { right: "keep", left: "cut", down: "not-him", up: "read-aloud" };
const STAMP: Record = { keep: "KEEP", cut: "CUT", "not-him": "NOT HIM", "read-aloud": "READ ALOUD" };
const WORDS: Record = { keep: "kept", cut: "cut", "not-him": "not him", "read-aloud": "read aloud" };
const REASONS = ["co-host", "guest", "a clip played", "a post read out", "chat read out", "wrong moment", "doesn't match"];
const SHOWS: { show: ClipDeckShow; label: string }[] = [
{ show: "unruled", label: "Unruled" },
{ show: "doubtful", label: "Doubtful first" },
{ show: "ruled", label: "Ruled" },
{ show: "all", label: "All" },
];
const THRESHOLD = 0.3;
const FLICK = 0.6;
const UNDO_DEPTH = 20;
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-out-up { 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-out-up { animation: deck-out-up 160ms ease-in forwards; }
.deck-fade { animation: deck-fade 80ms linear forwards; }
@media (prefers-reduced-motion: reduce) { .deck-rise { animation: none; } }`;
const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
const stampClass = (v: Verdict) =>
cn(
"pointer-events-none absolute top-24 z-10 rotate-[-8deg] rounded-[4px] border-[3px] px-2.5 py-0.5 font-display text-[24px] font-bold uppercase tracking-wide",
v === "keep" ? "left-4 border-signal text-signal" : v === "cut" ? "right-4 border-muted text-muted line-through" : "right-4 border-seam-2 text-text-2",
);
const doubt = (c: ClipCard) => (c.voice?.label === "unlikely" ? 0 : c.voice?.label === "unsure" ? 1 : c.voiceCheck ? 2 : 3);
/** The cards a filter walks, in the order it walks them. */
function queueOf(cards: ClipCard[], rulings: Record, show: ClipDeckShow): string[] {
const ruled = (c: ClipCard) => !!rulings[c.key];
if (show === "all") return cards.map((c) => c.id);
if (show === "ruled") return cards.filter(ruled).map((c) => c.id);
const open = cards.filter((c) => !ruled(c));
if (show === "unruled") return open.map((c) => c.id);
// Doubtful first: the voice match's unlikely (lowest score first), then its
// unsure, then a voice check in the clip's note, then the rest in order.
return open
.map((c, i) => ({ c, i }))
.sort((a, b) => doubt(a.c) - doubt(b.c) || (a.c.voice && b.c.voice ? a.c.voice.score - b.c.voice.score : 0) || a.i - b.i)
.map(({ c }) => c.id);
}
/** The quote, its phrase marked (case and punctuation aside). */
function Quote({ quote, phrase }: { quote: string; phrase: string }) {
const words = phrase.toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? [];
const re = words.length ? new RegExp(words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^\\p{L}\\p{N}']+"), "iu") : null;
const m = re ? re.exec(quote) : null;
if (!m) return <>“{quote}”>;
return (
<>
“{quote.slice(0, m.index)}
{m[0]}
{quote.slice(m.index + m[0].length)}”
>
);
}
export default function ClipDeck({
project,
view,
initialShow,
back,
takesHref,
voicePanel = null,
fetchPanel = null,
}: {
project: string;
view: ClipDeckView;
initialShow: ClipDeckShow;
back: string;
takesHref: string;
/** Release 34 N2's "Score the voices" (VoiceMatchPanel), shown in the head. */
voicePanel?: React.ReactNode;
/** Release 35's "Fetch windows" and stand-ins (FetchWindowsPanel / StandInsPanel), shown in the head. */
fetchPanel?: React.ReactNode;
}) {
const cards = view.cards;
const byId = useMemo(() => new Map(cards.map((c) => [c.id, c])), [cards]);
const [rulings, setRulings] = useState>(view.rulings);
const [show, setShow] = useState(initialShow);
const [queue, setQueue] = useState(() => queueOf(cards, view.rulings, initialShow));
const [total, setTotal] = useState(queue.length);
const [walked, setWalked] = useState(0);
const [skipped, setSkipped] = useState>(new Set());
const [undos, setUndos] = useState([]);
const [started, setStarted] = useState(false);
const [wide, setWide] = useState(false);
const [editing, setEditing] = useState(false);
const [matchText, setMatchText] = useState("");
const [reason, setReason] = useState("");
const [error, setError] = useState(view.rulingsError);
const [busy, setBusy] = useState(false);
const [offer, setOffer] = useState(view.offer);
const [imported, setImported] = useState(null);
const [drag, setDrag] = useState<{ dx: number; dy: number } | null>(null);
const [ghost, setGhost] = useState(null);
const [reduced, setReduced] = useState(false);
const [hints, setHints] = useState(false);
const clip = useRef(null);
const cardEl = useRef(null);
const start = useRef<{ x: number; y: number; t: number; id: number } | null>(null);
const writable = !view.rulingsError;
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((id) => !skipped.has(id));
const topId = live[0] ?? null;
const top = topId ? (byId.get(topId) ?? null) : null;
const under = live[1] ? (byId.get(live[1]) ?? null) : null;
const counts = useMemo(() => {
const c: Record = { keep: 0, cut: 0, "not-him": 0, "read-aloud": 0 };
for (const card of cards) {
const r = rulings[card.key];
if (r) c[r.verdict] += 1;
}
return c;
}, [cards, rulings]);
const ruledCount = counts.keep + counts.cut + counts["not-him"] + counts["read-aloud"];
const at = Math.min(walked + skipped.size + 1, total);
const hintShown = hints || walked + skipped.size < 3;
// The card after the next: ask what plays it before it is shown.
useEffect(() => {
const after = live[2] ? byId.get(live[2]) : null;
if (after?.cut) warmCited(after.cut);
}, [live, byId]);
const walk = useCallback(
(s: ClipDeckShow, from: Record = rulings) => {
const q = queueOf(cards, from, s);
setShow(s);
setQueue(q);
setTotal(q.length);
setWalked(0);
setSkipped(new Set());
setEditing(false);
try {
const u = new URL(window.location.href);
u.searchParams.set("show", s);
window.history.replaceState(null, "", u);
} catch {}
},
[cards, rulings],
);
const post = async (body: Record) => {
const r = await fetch("/api/report/montage-rulings", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ project, ...body }),
cache: "no-store",
});
const j = (await r.json().catch(() => ({}))) as { error?: string; rulings?: Record; written?: string[] };
if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
if (j.rulings) setRulings(j.rulings);
return j;
};
const remember = (u: Undo) => setUndos((s) => [...s.slice(-(UNDO_DEPTH - 1)), u]);
const rule = useCallback(
async (id: string, verdict: Verdict, extra: { match?: string } = {}) => {
const c = byId.get(id);
if (!c || !writable) return;
const prev = rulings[c.key] ?? null;
setError(null);
setQueue((q) => q.filter((x) => x !== id));
setWalked((n) => n + 1);
remember({ id, kind: "rule", prev });
const ruling: Record = { verdict, reason };
// A ruling keeps a phrase it had unless this one sets it.
const match = extra.match ?? prev?.match;
if (match && match !== c.phrase) ruling.match = match;
setRulings((r) => ({ ...r, [c.key]: { verdict, reason, ...(ruling.match ? { match: ruling.match } : {}), at: new Date().toISOString() } }));
try {
await post({ clip: id, ruling });
setReason("");
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
setQueue((q) => [id, ...q.filter((x) => x !== id)]);
setWalked((n) => Math.max(0, n - 1));
setUndos((s) => s.slice(0, -1));
setRulings((r) => {
const n = { ...r };
if (prev) n[c.key] = prev;
else delete n[c.key];
return n;
});
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[byId, rulings, reason, writable],
);
const decide = useCallback(
(dir: Dir | "skip") => {
if (!topId || busy || editing) return;
setStarted(true);
const id = topId;
const at_ = Date.now();
const gdir: Dir = dir === "skip" ? "down" : dir;
setGhost({ id, dir: gdir, dx: drag?.dx ?? 0, dy: drag?.dy ?? 0, at: at_ });
setDrag(null);
setWide(false);
window.setTimeout(() => setGhost((g) => (g?.at === at_ ? null : g)), reduced ? 80 : 160);
if (dir === "skip") {
setSkipped((s) => new Set(s).add(id));
setQueue((q) => [...q.filter((x) => x !== id), id]);
remember({ id, kind: "skip", prev: null });
return;
}
void rule(id, VERDICT_OF[dir]);
},
[topId, busy, editing, drag, reduced, rule],
);
const undo = useCallback(async () => {
const u = undos[undos.length - 1];
if (!u || busy) return;
setUndos((s) => s.slice(0, -1));
setError(null);
setEditing(false);
if (u.kind === "skip") {
setSkipped((s) => {
const n = new Set(s);
n.delete(u.id);
return n;
});
setQueue((q) => [u.id, ...q.filter((x) => x !== u.id)]);
return;
}
const c = byId.get(u.id);
if (!c) return;
setBusy(true);
try {
await post({ clip: u.id, ruling: u.prev ? { verdict: u.prev.verdict, reason: u.prev.reason, ...(u.prev.match ? { match: u.prev.match } : {}) } : null });
setWalked((n) => Math.max(0, n - 1));
setQueue((q) => [u.id, ...q.filter((x) => x !== u.id)]);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [undos, busy, byId]);
const openEdit = useCallback(() => {
if (!top || busy) return;
setStarted(true);
setEditing(true);
setMatchText(rulings[top.key]?.match ?? top.phrase);
}, [top, busy, rulings]);
const saveEdit = () => {
if (!top) return;
const m = matchText.trim().replace(/\s+/g, " ");
setEditing(false);
void rule(top.id, "keep", { match: m && m !== top.phrase ? m : undefined });
};
const importEarlier = async () => {
setBusy(true);
setError(null);
try {
const j = await post({ import: true });
const n = j.written?.length ?? 0;
setImported(n);
setOffer({ count: 0, left: 0, matched: 0, unmapped: offer.unmapped });
if (j.rulings) walk(show, j.rulings);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};
// The keys. Typing (the phrase, the few words) keeps its own.
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(false);
}
return;
}
if (t?.closest?.(TYPING)) 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 === "ArrowDown" || k === "n") act(() => decide("down"));
else if (k === "ArrowUp" || k === "r") act(() => decide("up"));
else if (k === "s") act(() => decide("skip"));
else if (k === "e") act(openEdit);
else if (k === "w")
act(() => {
setStarted(true);
setWide((w) => !w);
});
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 === "Escape") (document.activeElement as HTMLElement | null)?.blur?.();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [decide, undo, editing, openEdit]);
// 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")) 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 = () => {
const s = start.current;
start.current = null;
if (!s || !drag) return;
const w = cardEl.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);
};
const width = cardEl.current?.offsetWidth ?? 400;
const stamp: { v: Verdict; o: number } | null = drag
? Math.abs(drag.dx) >= Math.abs(drag.dy)
? { v: drag.dx > 0 ? "keep" : "cut", o: Math.min(1, Math.abs(drag.dx) / (width * THRESHOLD)) }
: { v: drag.dy < 0 ? "read-aloud" : "not-him", o: Math.min(1, Math.abs(drag.dy) / (width * THRESHOLD)) }
: null;
const counter = (
{total ? `${at} / ${total}` : "0 / 0"} · {counts.keep} kept · {counts.cut} cut · {counts["not-him"]} not him · {counts["read-aloud"]} read aloud
{skipped.size ? ` · ${skipped.size} skipped` : ""}
);
const head = (
{SHOWS.map((s) => (
e.preventDefault()}
onClick={() => walk(s.show)}
className={cn(buttonVariants({ variant: show === s.show ? "pressed" : "outline", size: "sm" }), "max-md:min-h-11 max-md:px-3 max-md:text-[13px]")}
>
{s.label}
))}
{ruledCount} of {cards.length} ruled
{counter}
{offer.count > 0 && (
edits.json has {offer.count} earlier ruling{offer.count === 1 ? "" : "s"}
{offer.left ? ` · ${offer.left} left out` : ""}
{offer.matched ? ` · ${offer.matched} phrase${offer.matched === 1 ? "" : "s"} widened` : ""}
void importEarlier()} className={buttonVariants({ variant: "outline", size: "sm" })}>
Import {offer.count} earlier ruling{offer.count === 1 ? "" : "s"}
)}
{imported !== null && (
Imported {imported} earlier ruling{imported === 1 ? "" : "s"}.
)}
{view.voiceMatch && (
voice match: {view.voiceMatch.count} clips scored{view.voiceMatch.model ? ` · ${view.voiceMatch.model}` : ""}
)}
{voicePanel}
{fetchPanel}
);
if (!top) {
return (
{head}
setSkipped(new Set())}
rerender={view.rerender}
takes={view.takes}
takesHref={takesHref}
back={back}
/>
{error && (
{error}
)}
);
}
const target = wide ? (top.extent ?? top.cut) : top.cut;
const peeks = Math.min(3, live.length - 1);
const ghostCard = ghost ? byId.get(ghost.id) : null;
return (
// On a phone the bar is the dock: the page clears it and the safe area under it.
{head}
{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: drag ? `translate(${drag.dx}px, ${drag.dy}px) rotate(${drag.dx * 0.04}deg)` : undefined,
transition: drag ? "none" : "transform 120ms ease-out",
}}
>
{stamp && stamp.o > 0.05 && (
{STAMP[stamp.v]}
)}
setEditing(false)}
/>
{!started && (
{
setStarted(true);
clip.current?.playSpan();
}}
>
Start listening
)}
{ghost && ghostCard && (
{ghostCard.id}
{ghostCard.phrase}
)}
{peeks > 0 && (
{Array.from({ length: peeks }, (_, i) => (
))}
)}
{/* Why: optional, one tap, said with the next ruling. */}
{REASONS.map((r) => (
e.preventDefault()}
onClick={() => setReason(reason === r ? "" : r)}
className={cn("rounded-full border px-2 py-[2px] text-[11.5px] max-md:min-h-11 max-md:px-3 max-md:text-[13px]", reason === r ? "border-muted bg-panel-2 text-text" : "border-seam-2 text-muted-2 hover:text-text")}
>
{r}
))}
setReason(e.target.value)}
placeholder="or why, in a few words"
aria-label="Why, in a few words"
data-reason-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]"
/>
{ setStarted(true); setWide((w) => !w); }} />
decide("skip")} disabled={busy} />
{error && (
{error}
)}
{/* Every gesture is a button too: a bar under the thumb on a phone. */}
void undo()} />
decide("left")} />
decide("down")} />
decide("up")} />
decide("right")} />
← cut · ↓ not him · ↑ read aloud · keep → · e phrase · w wider · s skip · space replays · z undoes · ? keys
);
}
function DeckButton({ action, label, k, go = false, disabled, onClick }: { action: string; label: string; k: string; go?: boolean; disabled?: boolean; onClick: () => void }) {
return (
e.preventDefault()}
onClick={onClick}
className={cn(buttonVariants({ variant: go ? "go" : "outline", size: "lg" }), "flex-col gap-0 px-1 py-2 text-[12.5px] leading-tight md:flex-row md:gap-1.5 md:text-[13px] max-md:min-h-12")}
>
{label}
{k}
);
}
function QuietButton({ action, label, k, pressed, disabled, onClick }: { action: string; label: string; k: string; pressed?: boolean; disabled?: boolean; onClick: () => void }) {
return (
e.preventDefault()}
onClick={onClick}
className={cn(buttonVariants({ variant: pressed ? "pressed" : "quiet", size: "sm" }), "max-md:min-h-11 max-md:px-3 max-md:text-[13px]")}
>
{label} {k}
);
}
/** One instance: the phrase, its cut playing, the quote, where and when, the note, the voice match. */
function Card({
card,
ruling,
target,
wide = false,
preload = false,
playing = false,
clipRef,
project,
editing = false,
matchText = "",
onMatchText,
onSaveEdit,
onCancelEdit,
}: {
card: ClipCard;
ruling: ClipRuling | null;
target: ClipCard["cut"];
wide?: boolean;
preload?: boolean;
playing?: boolean;
clipRef?: React.Ref;
project?: string;
editing?: boolean;
matchText?: string;
onMatchText?: (s: string) => void;
onSaveEdit?: () => void;
onCancelEdit?: () => void;
}) {
const phrase = ruling?.match ?? card.phrase;
return (
{card.n !== null ? `#${card.n}${card.of ? ` of ${card.of}` : ""}` : card.id}
{card.id}
{ruling && (
{WORDS[ruling.verdict]}
{ruling.reason ? ` · ${ruling.reason}` : ""}
)}
{card.voice && (
voice {card.voice.label} · {card.voice.score.toFixed(2)}
)}
{editing ? (
) : (
{phrase}
)}
{target ? (
) : (
No span to play.
)}
{wide &&
playing the whole clip, not just the phrase
}
{card.quote && (
)}
{[card.date, card.platform, card.channel, card.video].filter(Boolean).join(" · ")}
{card.note && (
{card.note}
)}
);
}
/** The end of a walk: the counts, what the next render makes, and the take made again. */
function EndCard({
project,
cards,
rulings,
counts,
skipped,
total,
onWalk,
onSkipped,
rerender,
takes,
takesHref,
back,
}: {
project: string;
cards: ClipCard[];
rulings: Record;
counts: Record;
skipped: string[];
total: number;
onWalk: (s: ClipDeckShow) => void;
onSkipped: () => void;
rerender: ClipDeckView["rerender"];
takes: number;
takesHref: string;
back: string;
}) {
const [plan, setPlan] = useState(null);
const [planError, setPlanError] = useState(null);
const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null);
const [jobError, setJobError] = useState(null);
const open = cards.filter((c) => !rulings[c.key]).length;
const since = rerender?.builtAt ? Object.values(rulings).filter((r) => r.at > (rerender.builtAt as string)).length : null;
// What the next render makes: the very rules a build applies, asked of the server.
useEffect(() => {
let gone = false;
void fetch(`/api/report/montage-rulings?project=${encodeURIComponent(project)}`, { cache: "no-store" })
.then(async (r) => {
const j = await r.json();
if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
if (!gone) setPlan(j.plan as Plan);
})
.catch((e) => !gone && setPlanError(e instanceof Error ? e.message : String(e)));
return () => {
gone = true;
};
}, [project, rulings]);
useEffect(() => {
if (!job || job.state !== "running") return;
const t = setInterval(async () => {
const r = await fetch(`/api/report/takes/make?job=${job.id}`, { cache: "no-store" }).catch(() => null);
if (!r?.ok) return;
const j = (await r.json()) as { id: string; state: string; error: string | null };
setJob({ id: j.id, state: j.state, error: j.error });
}, 1500);
return () => clearInterval(t);
}, [job]);
const remake = async () => {
if (!rerender) return;
setJobError(null);
const r = await startTakeJob({ project, rebuild: rerender.take });
if (r.error || !r.job) setJobError(r.error ?? "the take did not start");
else setJob({ id: r.job.id, state: r.job.state, error: r.job.error });
};
const leftOut = cards.filter((c) => rulings[c.key] && rulings[c.key].verdict !== "keep");
return (
{counts.keep} kept · {counts.cut} cut · {counts["not-him"]} not him · {counts["read-aloud"]} read aloud
{total ? `${total} walked` : "Nothing to walk here"}
{open ? ` · ${open} still unruled` : " · every clip is ruled"}
{skipped.length ? ` · ${skipped.length} skipped` : ""}
{leftOut.length > 0 && (
Left out of the render
{leftOut.map((c) => (
{c.id} {c.phrase} — {WORDS[rulings[c.key].verdict]}
{rulings[c.key].reason ? `: ${rulings[c.key].reason}` : ""}
· {c.date}
))}
)}
The next render
{plan ? (
{plan.kept.length} clip{plan.kept.length === 1 ? "" : "s"}, numbered 1–{plan.kept.length}:{" "}
k.id).join(" ")} className="font-mono text-[11.5px] text-muted">
{plan.kept.map((k) => k.id).join(" ")}
) : (
{planError ?? "…"}
)}
{rerender ? (
void remake()}
className={buttonVariants({ variant: "go", size: "md" })}
>
Re-render the take — {rerender.label}
) : (
{takes ? "Choose a take to render again" : "Make a take"}
)}
{skipped.length > 0 && (
The skipped ones
)}
{open > 0 && (
onWalk("unruled")} data-deck-again="unruled">
The unruled ones
)}
onWalk("ruled")} data-deck-again="ruled">
Walk the ruled ones again
Back to the cut
{rerender && (
{rerender.why === "latest" ? `The latest take, ${rerender.take}` : rerender.why === "picked" ? "The picked take" : "The newest whole-cut take"}
{since !== null ? ` · ${since} ruling${since === 1 ? "" : "s"} since it was made` : ""}
)}
{job && (
{job.state === "running" ? "Rendering" : job.state === "done" ? "Rendered" : `Failed${job.error ? `: ${job.error}` : ""}`} —{" "}
the Takes page
)}
{jobError && (
{jobError}
)}
);
}