import { notFound } from "next/navigation"; import { projectsHref, clipBenchHref, ingredientHref, playHref } from "@/lib/hrefs"; import type { ClipBenchData } from "@/components/projects/ClipBench"; import type { BenchKey, BenchLink } from "@/components/projects/bench/BenchShell"; import { clipVerdict, cuesInWindow, siblingsOf, walkOrder, walkReadiness, } from "@/lib/projects/report.mjs"; import { walkNeighbours, walkOf } from "@/lib/report/walkData.mjs"; import { projectCache, segmentFor, windowVersion, windowsFor } from "@/lib/report/serve.mjs"; import { FETCH_MAX_WINDOW } from "@/lib/report/driver.mjs"; import { gapWalls } from "umtool-report-to-video/gaps"; import { deckOn } from "umtool-report-to-video/deck"; import { censorRegionsOf } from "umtool-report-to-video/clip-censor"; import { resolveBrandRender } from "umtool-report-to-video/brand"; import { pieceHrefOfProject } from "@/lib/pieces/article"; import { readWorkingCut } from "@/lib/report/workingCut.mjs"; import { effectiveManifest } from "@/lib/report/manifest.mjs"; import type { ProjectRef } from "@/lib/project-types"; // THE CLIP BENCH'S DATA, in one place: what `/projects/

/clip/` renders // (ClipBenchPage) and what Play's in-place bench fetches (GET /api/report/bench, // components/projects/cutApp/CutApp.tsx) -- the same function, so the bench in // the app and the bench on its own page can never disagree. The clip id is // validated as a MEMBER of the timeline, never as a path. // // `order: "cut"` (the bench opened inside Play): p / n step along the CUT -- // the reel strip's neighbours, every clip judged or not -- not the walk's // recording order; the walk is a different journey. // // The DRAFT's clips only (L3): a take's clip is never benched -- its old // address (`…/takes//clip/`) is the Open in draft page -- so there is // no take here (the take walk's paths went with E1, 9 Nov). /** BenchTop's props, as data (the server page and the app both draw it). */ export type BenchTopSpec = { trail: { href: string; label: string }[]; back: { href: string; label: string }; kind: string; here: string; phone?: "hidden"; slot?: boolean; pos: { index: number; total: number }; prev: BenchLink | null; next: BenchLink | null; keys: BenchKey[]; note: string; /** The clip's source, across its life cycle (lane L5). */ life?: BenchLink | null; }; /** * @returns null when the clip is not a clip of the cut -- the page's 404 */ export async function clipBenchData( project: ProjectRef, clipId: string, { search = {}, order = "walk" }: { search?: Record; order?: "walk" | "cut" } = {}, ): Promise<{ data: ClipBenchData; top: BenchTopSpec } | null> { // `?all=1`: the walk visits every fetched clip, judged or not. const all = search.all === "1"; let walk: Awaited>; try { walk = await walkOf(project, { all }); } catch { return null; } const manifest = walk.manifest; const detail = walk.detail; const entry = detail.entries.find( (e: { id: string; kind: string }) => e.id === clipId && e.kind === "clip", ); if (!entry) return null; // In WALK order (by source date, each recording's clips together): `p`/`n` // step through the recordings, not the cut (lib/projects/report.mjs, walkOrder). const clips = walkOrder(detail.entries) as typeof detail.entries; const i = clips.findIndex((e: { id: string }) => e.id === clipId); // ---- where `p` and `n` go ------------------------------------------------ // // The walk visits the clips that still NEED JUDGEMENT and are FETCHED, in // walk order (by source). A clip nobody can play is a dead end -- there is nothing to // judge and the only move is to press `n` again -- and one already answered is // the round trip a walk exists to remove. A URL still opens ANY clip: this // page renders it, says what it has (or has not) got, and points its links at // the fetched, unjudged neighbours on either side. (walkData.mjs, the // reading `umtool walk` prints; `all` keeps the judged ones on it too.) const readiness = walkReadiness(clips); const walkNb = walkNeighbours(walk.order, walk.onWalk, clipId); // In the cut's order (Play's bench): the clips either side on the timeline, judged or not. const cutClips = ((detail.entries ?? []) as { id: string; kind: string }[]).filter((e) => e.kind === "clip"); const ci = cutClips.findIndex((e) => e.id === clipId); const { prev, next } = order === "cut" ? { prev: ci > 0 ? cutClips[ci - 1].id : null, next: ci >= 0 && ci + 1 < cutClips.length ? cutClips[ci + 1].id : null } : walkNb; // One listing of clips-raw for the page: readClipDetail already built one to // answer `fetched` for every clip, and this is the same question for this one. const windows = await windowsFor(project, entry, await projectCache(project, manifest)); // The mtime rides along so a re-render busts the browser's cache: the segment // is written back to the SAME path, and without it the player would keep // showing the cut from before the edit. const seg = await segmentFor(project, clipId); const widest = windows[0] ?? null; const view = widest ? { from: widest.from, to: widest.to } : { from: Math.max(0, entry.start - 20), to: entry.end + 20 }; const cues = await cuesInWindow(project.dir, clipId, view.from, view.to, { manifest }); const data: ClipBenchData = { project: project.id, clip: { id: entry.id, video: entry.video, channel: entry.channel ?? null, start: entry.start, end: entry.end, cite: entry.cite ?? null, quote: entry.quote ?? null, note: entry.note ?? null, correction: entry.correction ?? null, title: entry.title ?? null, date: entry.date ?? null, citeUrl: entry.citeUrl ?? null, channelTitle: entry.channelTitle ?? null, lock: !!entry.lock, lockStart: !!entry.lockStart, lockEnd: !!entry.lockEnd, cutStart: entry.cutStart ?? null, cutEnd: entry.cutEnd ?? null, lockCut: !!entry.lockCut, // The mute mark, from the manifest's own entry: readClipDetail's rows // carry the fields it reads, and this is not one of them. muteFrom: ((manifest.timeline ?? []) as { id: string; muteFrom?: number }[]).find((e) => e.id === clipId) ?.muteFrom ?? null, // Seconds cut out of its middle (gaps.mjs), likewise from the manifest's own entry -- each with its own // mark and why when it says (common gapCue.mjs). gaps: ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) ?.gaps ?? [], // The mark at its gaps' joins, the clip's own settings (lane gap-cue), from the manifest's own entry. gapCue: (() => { const v = ((manifest.timeline ?? []) as { id: string; gapCue?: unknown }[]).find((e) => e.id === clipId)?.gapCue; return v && typeof v === "object" && !Array.isArray(v) ? (v as NonNullable) : null; })(), // The seconds no gap may cover (claim marks, a stamp), from the manifest's own entry. marks: gapWalls({ ...(((manifest.timeline ?? []) as { id: string }[]).find((e) => e.id === clipId) ?? {}), type: "clip", muteFrom: null }) .marks.map((m) => ({ id: m.id, at: m.at })), verdict: entry.verdict === "confirmed" || entry.verdict === "incorrect" || entry.verdict === "rejected" ? entry.verdict : null, // What the walk said that is not a verdict, and a deliberate repeat. walkNote: typeof entry.walkNote === "string" ? entry.walkNote : null, star: entry.star === true, repeatOf: typeof entry.repeatOf === "string" ? entry.repeatOf : null, // Why it was rejected (lib/report/rejectReasons.mjs), from the manifest's own entry. ...(() => { const own = ((manifest.timeline ?? []) as { id: string; reason?: unknown; rejectNote?: unknown }[]).find((e) => e.id === clipId); return { reason: typeof own?.reason === "string" ? own.reason : null, rejectNote: typeof own?.rejectNote === "string" ? own.rejectNote : null, }; })(), // From the manifest's own entry: what the on-screen panel says over this // clip, when somebody has written it. onscreen: ((manifest.timeline ?? []) as { id: string; onscreen?: { title?: string; subtitle?: string } }[]).find( (e) => e.id === clipId, )?.onscreen ?? null, }, // Whether the cut is built with the on-screen panel. Decides whether the // bench composes a preview of it; the fields are there either way. deckOn: deckOn(manifest.render ?? {}), // Every region the cut hides on it (clip-censor.mjs): the bench draws them over the raw window. // The project's mark at gaps' joins (render.gapCue) as the build reads it: the look preset under it. gapCue: (() => { let render = (manifest.render ?? {}) as Record; try { render = ((effectiveManifest(manifest) as { render?: Record }).render ?? {}) as Record; } catch { // An unknown preset: the manifest's own word (the build says what is wrong). } const v = render.gapCue; return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : null; })(), // The deck's accent (render.palette.accent, the brand's when it names one): the mark's border unless a gapCue // `border` names a colour (common gapCueBorderOf). null: the render has none. gapCueAccent: (() => { try { const render = resolveBrandRender(((effectiveManifest(manifest) as { render?: Record }).render ?? {}) as Record) as { palette?: { accent?: unknown }; }; return typeof render?.palette?.accent === "string" ? render.palette.accent : null; } catch { // An unknown preset or brand: the build says what is wrong. return null; } })(), hidden: censorRegionsOf(((manifest.timeline ?? []) as { id: string }[]).find((e) => e.id === clipId) ?? {}, manifest.render ?? {}, manifest.provenance ?? {}), generatedBy: typeof manifest.generatedBy === "string" ? manifest.generatedBy : null, view, // `v`: the version of each window's bytes, for the media URLs (serve.mjs, "A REPLACED FILE IS A NEW FILE"). windows: await Promise.all( windows.map(async (w: { name: string; from: number; to: number; path: string }) => ({ name: w.name, from: w.from, to: w.to, v: await windowVersion(w), })), ), proposed: entry.proposed ?? null, endsSentence: entry.endsSentence ?? null, noPunctuation: !!entry.noPunctuation, sourceDuration: entry.duration ?? null, segment: seg?.rel ?? entry.segment ?? null, segmentMtime: seg?.mtimeMs ?? null, // What the header would say with no overrides. Shown beside the fields that // replace it, because "the archive says 2019" is the whole reason `date` // exists. sourceTitle: entry.sourceTitleClean ?? null, uploadDate: entry.uploadDate ?? null, sourceChannel: entry.sourceChannel ?? null, sourceChannelDefault: entry.sourceChannelDefault ?? null, prev: prev, next: next, index: order === "cut" ? ci + 1 : i + 1, total: order === "cut" ? cutClips.length : clips.length, // The OTHERS, so the bench can add this clip's own answer to the count // without a reload and without knowing anything about the rest of the cut. /** The walk's own reading: fetched clips that still need an answer. */ ready: readiness.ready, needing: readiness.needing, /** Is there a cached file holding THIS clip's window, end to end? */ fetched: !!entry.fetched, reviewedOthers: clips.filter( (e: { id: string }) => e.id !== clipId && clipVerdict(e) !== "unreviewed", ).length, cues: cues?.cues ?? [], siblings: siblingsOf(manifest, clipId), // The project's manifest token. token: walk.token, fetchPad: manifest.render?.fetchPad ?? 3, // The widest the fetch route will go. The BUTTON has to know it: it names // the pad it will ask for, and "that is as wide as it goes" is a different // sentence from a number the server quietly clamps. maxWindow: FETCH_MAX_WINDOW, // The widest cached RAW window: it has no chrome burned in, which is what a // mix is looking at, and it exists as soon as the clip has been fetched // once. start/end are the window minus the file's own start, because a mix // spec is relative to the file it names. mixHref: widest ? `/tools/mix?${new URLSearchParams({ // The window's own path; see ReportProject — a window may live in // the corpus rather than under out/clips-raw. body: widest.path, start: (entry.start - widest.from).toFixed(2), end: (entry.end - widest.from).toFixed(2), from: project.id, clip: clipId, })}` : null, }; // The piece this view belongs to: the article's when an article claims the project (P4a-2). const back = await pieceHrefOfProject(project.id, { tab: "cut" }); // ---- opened from Play the cut ("Edit this clip") -------------------------- // // `?from=play` rides every walk link from here (p / n / Confirm's advance), // so "Back to the cut" survives walking on; `at` is only ever the clip Play // was on. Back lands on the PROJECT's cut, positioned by clip id plus the // offset into it -- never by raw cut seconds, which the edit just moved for // everything after this clip. An address that names the take Play was on // (`?take=`) keeps it on Back, and the bench says its edits go to the cut. const fromPlay = search.from === "play"; const withOrder = (h: string) => (order === "cut" ? `${h}${h.includes("?") ? "&" : "?"}order=cut` : h); const playTake = fromPlay && search.take ? search.take : null; const atRaw = Number(search.at); const at = fromPlay && Number.isFinite(atRaw) && atRaw > 0 ? atRaw : 0; const href = (id: string) => withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {})); data.walkHrefs = { prev: prev ? href(prev) : null, next: next ? href(next) : null, back, backLabel: project.name, }; data.fromPlay = fromPlay ? { href: playHref(project.id, { take: playTake, clip: clipId, at }), take: playTake } : null; // Walk → Play (the audit's "no way back"): the cut, from this clip. data.playHere = fromPlay ? null : playHref(project.id, { clip: clipId }); // The working cut's name: the bench edits the project's manifest, the latest take is what it was made into. data.working = await readWorkingCut(project.dir).catch(() => null); const top: BenchTopSpec = { trail: [{ href: projectsHref(), label: "Projects" }], back: { href: back, label: project.name }, kind: order === "cut" ? "Clip bench · the cut's order" : "Clip bench", here: clipId, // The walk on a phone draws its own place bar (ClipBench). phone: "hidden", // The head's slot: Back to the cut (from Play), or Play from here. slot: true, pos: { index: order === "cut" ? ci + 1 : i + 1, total: order === "cut" ? cutClips.length : clips.length }, prev: prev ? { href: href(prev), label: prev, attrs: { "data-clip-nav": "prev" } } : null, next: next ? { href: href(next), label: next, attrs: { "data-clip-nav": "next" } } : null, keys: [ { keys: ["y"], label: "confirm" }, { keys: ["x"], label: "note" }, { keys: ["[", "]", ",", "."], label: "nudge" }, { keys: ["space"], label: "play" }, { keys: ["p", "n"], label: order === "cut" ? "the cut" : "walk" }, ], // Which source is playing. note: `${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`, // Its source's life cycle: found, downloaded, … published (lane L5). life: entry.channel && entry.video ? { href: ingredientHref(String(entry.channel), String(entry.video)), label: "Life cycle" } : null, }; return { data, top }; } /** clipBenchData, or the page's 404. */ export async function clipBenchDataOr404(...args: Parameters) { const r = await clipBenchData(...args); if (!r) notFound(); return r; }