Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 76b5617bf2fe1bdad4a60ee2b79b6ff4341e77c2
parent ac0c878f636849b3ffc9c1f0759d44c8f76eaab1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun,  1 Nov 2026 11:46:10 -0500

umtool: Play and the clip bench are one app -- Edit this clip opens the bench in place with Play kept mounted (deck, sound, edges, zoom, take), Back/Forward step between them, and the standalone bench gains ▶ Play the cut from here

The audit (each side a page load): Play started over on every return -- the
deck composed, the edges measured, the sound decoded again, 38-61 s on the
127-clip Ember cut -- the take was dropped, a second Play was pushed onto the
history, and the bench had no way back to Play.

- components/projects/cutApp/CutApp.tsx on /play: Play is never unmounted; the
  bench opens in place from GET /api/report/bench, built by the same function
  the bench's page renders from (lib/report/benchData.ts, extracted from
  ClipBenchPage). history.pushState moves the address
  (/clip/<id>?from=play&at&take&order=cut), popstate switches the view, "Back
  to the cut" goes back the entries it pushed; links and keys inside the bench
  stay in the app (ClipBench `navigate`). The neighbours are read ahead.
- order=cut: inside Play the bench's p / n are the cut's neighbours (every
  clip), "40 of 127"; the walk's order is unchanged on its own page.
- Play reads its view again in place (GET /api/report/play-view) instead of
  router.refresh(), whose landing rewrote the address the bench had just
  pushed; it recomposes only when the manifest's token moved; hidden it is
  paused and its keys and URL writes are off; shown again it finds the clip it
  left by id and source second ("Back at … (the cut changed)").
- Walk → Play: a bench opened on its own (not from Play, not a take's) has
  ▶ Play the cut from here in its head.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/report/bench/route.ts | 21+++++++++++++++++++++
Aumtool/app/api/report/play-view/route.ts | 16++++++++++++++++
Mumtool/components/projects/ClipBench.tsx | 33+++++++++++++++++++++++++++------
Mumtool/components/projects/ClipBenchPage.tsx | 259+++----------------------------------------------------------------------------
Mumtool/components/projects/PlayCutPage.tsx | 6++++--
Aumtool/components/projects/cutApp/CutApp.tsx | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 110++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Aumtool/lib/report/benchData.ts | 294+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 690 insertions(+), 281 deletions(-)

diff --git a/umtool/app/api/report/bench/route.ts b/umtool/app/api/report/bench/route.ts @@ -0,0 +1,21 @@ +import { projectRef } from "@/lib/projects"; +import { clipBenchData } from "@/lib/report/benchData"; + +export const dynamic = "force-dynamic"; + +// THE CLIP BENCH'S DATA as JSON, for Play's in-place bench (components/projects/cutApp/CutApp.tsx): +// GET ?project=<id>&clip=<id>[&take=<id>][&from=play&at=<s>][&order=cut] +// +// The same function the bench's own page renders from (lib/report/benchData.ts), +// so the bench inside Play and the one on its own page cannot disagree. A clip +// that is not a clip of the cut is a 404, as the page's. +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const project = await projectRef(q.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const clip = q.get("clip") ?? ""; + const search = Object.fromEntries([...q.entries()].filter(([k]) => k !== "project" && k !== "clip")); + const r = await clipBenchData(project, clip, { search, take: q.get("walkTake") || null, order: q.get("order") === "cut" ? "cut" : "walk" }); + if (!r) return Response.json({ error: `${clip} is not a clip of the cut` }, { status: 404 }); + return Response.json(r, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/app/api/report/play-view/route.ts b/umtool/app/api/report/play-view/route.ts @@ -0,0 +1,16 @@ +import { projectRef } from "@/lib/projects"; +import { playView } from "@/lib/report/playView.mjs"; + +export const dynamic = "force-dynamic"; + +// PLAY'S VIEW as JSON (lib/report/playView.mjs): what `/projects/<p>/play` renders, read again +// in place after an edit (components/projects/review/PlayCut.tsx reloadView) rather than by a +// router refresh. GET ?project=<id>[&take=<id> | &cut=1]; no take: the latest take. +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const project = await projectRef(q.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const view = await playView(project, { take: q.get("take") || null, bare: q.get("cut") === "1" }); + if ("error" in view) return Response.json(view, { status: 400 }); + return Response.json(view, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -5,7 +5,7 @@ import { rejectionOf } from "@/lib/report/rejectReasons.mjs"; import AnchoredNotes, { notesOn } from "@/components/notes/AnchoredNotes"; import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { useSharedNotes, wroteNotes } from "@/components/notes/NotesProvider"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { createPortal } from "react-dom"; import Link from "next/link"; import { useRouter } from "next/navigation"; @@ -319,6 +319,8 @@ export type ClipBenchData = { * if one was (its render does not change when this manifest does). */ fromPlay?: { href: string; take: string | null } | null; + /** Walk → Play: the cut from this clip (the bench opened on its own, not from Play, not a take's). */ + playHere?: string | null; /** * WALKING A TAKE (/projects/<p>/takes/<take>/clip/<id>): the clip is the * take's -- the project's manifest with the take's patch applied -- and @@ -523,7 +525,18 @@ type Session = { more?: AudioBufferSourceNode[]; }; -export default function ClipBench({ data }: { data: ClipBenchData }) { +export default function ClipBench({ + data, + navigate, +}: { + data: ClipBenchData; + /** + * Inside Play (components/projects/cutApp/CutApp.tsx): every move this bench makes -- p / n, + * Confirm's advance, Back to the cut -- goes through here, so Play stays mounted and the + * history is the app's. Absent, Next's router. + */ + navigate?: (href: string) => void; +}) { // The project's notes: this clip's row notes, and the edit notes a save on a // generated manifest leaves (the save says so, and they are re-read). const notes = useSharedNotes({ project: data.project }); @@ -595,7 +608,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const [segPaused, setSegPaused] = useState(true); const [segDur, setSegDur] = useState(0); - const router = useRouter(); + const nextRouter = useRouter(); + const router = useMemo(() => (navigate ? { ...nextRouter, push: (h: string) => navigate(h) } : nextRouter), [navigate, nextRouter]); const video = useRef<HTMLVideoElement | null>(null); // A REF, not state. Two saves can be in flight -- tab out of `title` straight // into `date` and both blur handlers fire -- and the second must carry the @@ -695,8 +709,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // The desk's "Back to the cut" lives in the bench head (BenchTop's slot). const [topSlot, setTopSlot] = useState<Element | null>(null); useEffect(() => { - if (data.fromPlay) setTopSlot(document.querySelector("[data-bench-top-slot]")); - }, [data.fromPlay]); + if (data.fromPlay || data.playHere) setTopSlot(document.querySelector("[data-bench-top-slot]")); + }, [data.fromPlay, data.playHere]); const hrefOf = useCallback( (which: "prev" | "next") => { const id = which === "prev" ? data.prev : data.next; @@ -3171,7 +3185,14 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { ); // The desk's Back to the cut, in the bench head. const deskBack = - data.fromPlay && topSlot + !data.fromPlay && data.playHere && topSlot + ? createPortal( + <a href={data.playHere} data-play-from-here="" className={buttonVariants({ variant: "outline", size: "sm" })} title="Play the cut from this clip (the reel strip, the deck, the notes)"> + ▶ Play the cut from here + </a>, + topSlot, + ) + : data.fromPlay && topSlot ? createPortal( <> <button diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -1,24 +1,11 @@ -import { notFound } from "next/navigation"; -import { projectsHref, clipBenchHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs"; import { BenchFrame, BenchTop } from "./bench/BenchShell"; -import ClipBench, { type ClipBenchData } from "./ClipBench"; -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_PAD } from "@/lib/report/driver.mjs"; -import { deckOn } from "umtool-report-to-video/deck"; -import { pieceHrefOfProject } from "@/lib/pieces/article"; +import ClipBench from "./ClipBench"; +import { clipBenchDataOr404 } from "@/lib/report/benchData"; import type { ProjectRef } from "@/lib/project-types"; -// The server half of the bench: resolve the clip, read what it needs, and hand -// it over. The clip id is validated as a MEMBER of the timeline, never as a -// path -- the same rule every other name that crosses the wire here follows. +// The server half of the bench: lib/report/benchData.ts reads what it needs +// (the same function Play's in-place bench fetches through /api/report/bench), +// and this page draws it in the bench shell. export default async function ClipBenchPage({ project, @@ -36,243 +23,11 @@ export default async function ClipBenchPage({ */ take?: string | null; }) { - // `?all=1`: the walk visits every fetched clip, judged or not. - const all = search.all === "1"; - let walk: Awaited<ReturnType<typeof walkOf>>; - try { - walk = await walkOf(project, { take, all }); - } catch { - notFound(); - } - 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) notFound(); - - // 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 { prev, next } = walkNeighbours(walk.order, walk.onWalk, clipId); - - // 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. A take's clip has none: the - // project's segments are the project's cut. - const seg = take ? null : 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, - 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. - gaps: - ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) - ?.gaps ?? [], - 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 ?? {}), - 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: take ? null : (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, - prev: prev, - next: next, - index: i + 1, - total: 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, or -- walking a take -- the take's. - 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. - maxPad: FETCH_MAX_PAD, - // 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). - // Walking a take, Back is the take's walk (its overview), on the Takes page's side. - const back = take ? takeWalkHref(project.id, take, { all }) : 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. A take's render does not change when the - // project's manifest does, so a take's Back is the project's cut too, and - // the bench says so (`take`). - const fromPlay = !take && search.from === "play"; - 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) => - take ? takeClipHref(project.id, take, id, { all }) : clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {}); - data.walkHrefs = { - prev: prev ? href(prev) : null, - next: next ? href(next) : null, - back, - backLabel: take ? `take ${take}` : project.name, - }; - if (take && walk.take) { - const timeline = (manifest.timeline ?? []) as { id: string }[]; - data.take = { - id: take, - label: walk.take.label, - draft: walk.take.draft, - editable: walk.take.editable, - all, - takesHref: takesHref(project.id), - walkHref: takeWalkHref(project.id, take, { all }), - toggleAllHref: takeClipHref(project.id, take, clipId, { all: !all }), - clipHref: Object.fromEntries(data.siblings.map((sb: { id: string }) => [sb.id, takeClipHref(project.id, take, sb.id, { all })])), - at: timeline.findIndex((e) => e.id === clipId), - entries: timeline.length, - }; - } - data.fromPlay = fromPlay ? { href: playHref(project.id, { clip: clipId, at }), take: playTake } : null; + const { data, top } = await clipBenchDataOr404(project, clipId, { search, take, order: search.order === "cut" ? "cut" : "walk" }); return ( // The bench shell (P4b): its top bar here, the body -- the work, the // verdict bar, the reader -- in ClipBench, which owns their state. - <BenchFrame - kind="clip" - top={ - <BenchTop - trail={ - take - ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }] - : [{ href: projectsHref(), label: "Projects" }] - } - back={{ href: back, label: take ? `take ${take}` : project.name }} - kind={take ? "Take walk" : "Clip bench"} - here={clipId} - // The walk on a phone draws its own place bar (ClipBench). - phone="hidden" - slot={fromPlay} - pos={{ index: i + 1, total: 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: "walk" }, - ]} - // Which source is playing. - note={`${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`} - /> - } - > + <BenchFrame kind="clip" top={<BenchTop {...top} />}> <ClipBench data={data} /> </BenchFrame> ); diff --git a/umtool/components/projects/PlayCutPage.tsx b/umtool/components/projects/PlayCutPage.tsx @@ -6,6 +6,7 @@ import { playView } from "@/lib/report/playView.mjs"; import { NotesProvider } from "@/components/notes/NotesProvider"; import { BenchFrame, BenchTop } from "./bench/BenchShell"; import PlayCut, { type PlayViewData } from "./review/PlayCut"; +import CutApp from "./cutApp/CutApp"; // `/projects/<project>/play` (and `?take=<id>`) -- THE PLAY VIEW // (umtool/docs/knobs.md, "Play the cut"): the whole cut, or a take, played in the browser in @@ -58,8 +59,9 @@ export default async function PlayCutPage({ </BenchFrame> ); } + // Play and the clip bench as ONE app (cutApp/CutApp.tsx): Play stays mounted, the bench opens in place. return ( - <BenchFrame kind="play" top={top}> + <CutApp project={project.id} playTop={top}> <NotesProvider target={{ project: project.id }}> <PlayCut view={view as PlayViewData} @@ -67,6 +69,6 @@ export default async function PlayCutPage({ initialAt={clip ? { clip, at: Number.isFinite(Number(at)) ? Math.max(0, Number(at)) : 0 } : null} /> </NotesProvider> - </BenchFrame> + </CutApp> ); } diff --git a/umtool/components/projects/cutApp/CutApp.tsx b/umtool/components/projects/cutApp/CutApp.tsx @@ -0,0 +1,232 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; +import { BenchFrame, BenchTop } from "../bench/BenchShell"; +import ClipBench, { type ClipBenchData } from "../ClipBench"; +import type { BenchTopSpec } from "@/lib/report/benchData"; + +// --------------------------------------------------------------------------- +// PLAY AND WALK AS ONE APP (operator, 1 Nov 2026: "'play the cut' and 'walk +// the cut' have trouble transitioning back and forth ... a core user flow"). +// +// The audit (each side a page load) found Play starting over on every return +// -- the deck composed again, the edges measured again, the sound decoded +// again: 38-61 s on a 127-clip cut -- the take dropped, a second Play pushed +// onto the history, and no way from the bench back to Play at all. +// +// So on `/projects/<p>/play` Play is never unmounted. Edit this clip (E) +// opens the clip bench IN PLACE -- its data from GET /api/report/bench, the +// same function the bench's own page renders from (lib/report/benchData.ts) +// -- with Play hidden and paused under it, everything it had kept: the +// composed deck, the decoded sound, the edges, the strip's zoom, the take. +// The URL moves by history.pushState (`/clip/<id>?from=play&at&order=cut`), +// so Back and Forward step between the two, a reload or a link is the +// server's page as it always was, and history never stacks a second Play: +// "Back to the cut" goes back the entries the app pushed. The bench walks +// the CUT's order here (p / n are the reel strip's neighbours). Back on Play +// the view is read again (router.refresh: the bench may have saved), and +// Play recomposes only when the manifest's token moved. +// --------------------------------------------------------------------------- + +type View = { kind: "play" } | { kind: "clip"; id: string; href: string }; +type Bench = { data: ClipBenchData; top: BenchTopSpec }; + +export type CutAppApi = { + view: View["kind"]; + /** Open the bench on a clip, in place (`href`: the bench's address, from clipBenchHref). */ + openClip: (id: string, href: string) => void; + /** Called each time Play is shown again (Play reads its view again: the bench may have saved). */ + onReturn: (fn: () => void) => () => void; +}; +const Ctx = createContext<CutAppApi | null>(null); +/** Play's handle on the app: null when Play is drawn on its own (a test page, an old build). */ +export const useCutApp = () => useContext(Ctx); + +/** The clip id in a bench address of this project, or null. */ +function clipOf(pathname: string, project: string): string | null { + const base = `/projects/${project.split("/").map(encodeURIComponent).join("/")}/clip/`; + if (!pathname.startsWith(base)) return null; + const rest = pathname.slice(base.length); + return rest && !rest.includes("/") ? decodeURIComponent(rest) : null; +} +const isPlay = (pathname: string, project: string) => pathname === `/projects/${project.split("/").map(encodeURIComponent).join("/")}/play`; + +export default function CutApp({ project, playTop, children }: { project: string; playTop: React.ReactNode; children: React.ReactNode }) { + const router = useRouter(); + const [view, setView] = useState<View>({ kind: "play" }); + const [bench, setBench] = useState<{ key: string; state: "loading" | "ready" | "error"; bench?: Bench; error?: string } | null>(null); + // How many entries the app pushed past Play: "Back to the cut" goes back that many. + const depth = useRef(0); + const seq = useRef(0); + const returns = useRef(new Set<() => void>()); + const onReturn = useCallback((fn: () => void) => { + returns.current.add(fn); + return () => { + returns.current.delete(fn); + }; + }, []); + const returned = useCallback(() => { + for (const fn of returns.current) fn(); + }, []); + + // The neighbours (p / n) are read ahead while you work on a clip, so stepping is instant; a + // clip already visited is always read again (you may have saved on it). + const ahead = useRef(new Map<string, Promise<{ ok: boolean; status: number; body: Bench & { error?: string } }>>()); + const fetchBench = useCallback( + (id: string, href: string) => { + const u = new URL(href, window.location.origin); + const q = new URLSearchParams(u.search); + q.set("project", project); + q.set("clip", id); + q.set("order", "cut"); + return fetch(`/api/report/bench?${q.toString()}`, { cache: "no-store" }).then(async (r) => ({ ok: r.ok, status: r.status, body: (await r.json().catch(() => ({}))) as Bench & { error?: string } })); + }, + [project], + ); + const load = useCallback( + async (id: string, href: string) => { + const mine = ++seq.current; + const pending = ahead.current.get(href) ?? fetchBench(id, href); + ahead.current.clear(); + setBench({ key: href, state: "loading" }); + try { + const r = await pending; + if (mine !== seq.current) return; + if (!r.ok) setBench({ key: href, state: "error", error: r.body.error ?? `HTTP ${r.status}` }); + else { + setBench({ key: href, state: "ready", bench: r.body }); + for (const nb of [r.body.top.next, r.body.top.prev]) { + if (!nb) continue; + const nu = new URL(nb.href, window.location.origin); + const nid = clipOf(nu.pathname, project); + const nh = `${nu.pathname}${nu.search}`; + if (nid && !ahead.current.has(nh)) ahead.current.set(nh, fetchBench(nid, nh).catch((e) => ({ ok: false, status: 0, body: { error: String(e) } as Bench & { error?: string } }))); + } + } + } catch (e) { + if (mine === seq.current) setBench({ key: href, state: "error", error: e instanceof Error ? e.message : String(e) }); + } + }, + [project, fetchBench], + ); + + const withCutOrder = (href: string) => { + const u = new URL(href, window.location.origin); + u.searchParams.set("order", "cut"); + return `${u.pathname}${u.search}`; + }; + const openClip = useCallback( + (id: string, href: string) => { + const h = withCutOrder(href); + depth.current += 1; + window.history.pushState({ ...(window.history.state ?? {}), cutApp: depth.current }, "", h); + setView({ kind: "clip", id, href: h }); + void load(id, h); + }, + [load], + ); + + const backToPlay = useCallback(() => { + if (depth.current > 0) { + const n = depth.current; + depth.current = 0; + window.history.go(-n); + return; + } + // Opened straight on a bench entry (a Forward into it): Play's own address. + window.history.pushState({ ...(window.history.state ?? {}), cutApp: 0 }, "", `/projects/${project}/play`); + setView({ kind: "play" }); + returned(); + }, [project, returned]); + + /** Every move the bench makes: within the app when it is this project's bench or Play, else a page. */ + const navigate = useCallback( + (href: string) => { + const u = new URL(href, window.location.origin); + if (isPlay(u.pathname, project)) { + backToPlay(); + return; + } + const id = clipOf(u.pathname, project); + if (id && !u.pathname.includes("/takes/")) { + openClip(id, `${u.pathname}${u.search}`); + return; + } + router.push(href); + }, + [project, backToPlay, openClip, router], + ); + + // Back / Forward: the address says which view. + useEffect(() => { + const onPop = () => { + const p = window.location.pathname; + const st = (window.history.state ?? {}) as { cutApp?: number }; + if (isPlay(p, project)) { + depth.current = 0; + setView({ kind: "play" }); + setBench(null); + returned(); + return; + } + const id = clipOf(p, project); + if (id) { + depth.current = typeof st.cutApp === "number" ? st.cutApp : depth.current; + const h = `${p}${window.location.search}`; + setView({ kind: "clip", id, href: h }); + void load(id, h); + } + }; + window.addEventListener("popstate", onPop); + return () => window.removeEventListener("popstate", onPop); + }, [project, load, returned]); + + // A click on an in-app link inside the bench (its head's ‹ prev / next ›, a sibling, Back to the cut): the app's. + const onClickCapture = (e: React.MouseEvent) => { + if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; + const a = (e.target as HTMLElement | null)?.closest?.("a[href]") as HTMLAnchorElement | null; + if (!a || a.target === "_blank") return; + const u = new URL(a.href, window.location.origin); + if (u.origin !== window.location.origin) return; + if (isPlay(u.pathname, project) || (clipOf(u.pathname, project) && !u.pathname.includes("/takes/"))) { + e.preventDefault(); + e.stopPropagation(); + navigate(`${u.pathname}${u.search}`); + } + }; + + const api = useMemo<CutAppApi>(() => ({ view: view.kind, openClip, onReturn }), [view.kind, openClip, onReturn]); + const b = bench?.state === "ready" ? bench.bench : null; + return ( + <Ctx.Provider value={api}> + {/* Play: mounted always, hidden (and paused) while the bench is up. */} + <div className={view.kind === "play" ? "contents" : "hidden"} data-cut-app-play={view.kind === "play" ? "shown" : "hidden"}> + <BenchFrame kind="play" top={playTop}> + {children} + </BenchFrame> + </div> + {view.kind === "clip" && ( + <div className="contents" data-cut-app-bench={view.id} onClickCapture={onClickCapture}> + {b ? ( + <BenchFrame kind="clip" top={<BenchTop {...b.top} />}> + <ClipBench key={view.href} data={b.data} navigate={navigate} /> + </BenchFrame> + ) : ( + <div className="flex h-full flex-col"> + <div className="flex items-center gap-3 border-b border-seam px-4 py-2 text-[12px]"> + <button type="button" className="ink-link" data-cut-app-back="" onClick={backToPlay}> + ‹ Back to the cut + </button> + <span className="font-mono text-text">{view.id}</span> + <span className="text-muted" data-cut-app-loading={bench?.state ?? ""}> + {bench?.state === "error" ? `the bench did not open: ${bench.error}` : "opening the bench…"} + </span> + </div> + </div> + )} + </div> + )} + </Ctx.Provider> + ); +} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -24,6 +24,7 @@ import { useWaveZoom, ZoomControls } from "../bench/GapsZoom"; import { followVis, itemSections } from "@/lib/report/stripDrag.mjs"; import RejectClip from "./RejectClip"; import WhatPlays, { type WorkingCut } from "./WhatPlays"; +import { useCutApp } from "../cutApp/CutApp"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; // --------------------------------------------------------------------------- @@ -221,7 +222,7 @@ const STRIP_H = 120; const timecode = (t: number) => `${runningTime(t)}.${Math.floor(((Math.max(0, t) % 1) + 1e-9) * 10)}`; export default function PlayCut({ - view, + view: served, initialNote, initialAt = null, }: { @@ -231,6 +232,32 @@ export default function PlayCut({ initialAt?: { clip: string; at: number } | null; }) { const router = useRouter(); + // THE VIEW, read again in place (GET /api/report/play-view) after an edit -- never by + // router.refresh(): a refresh commits Next's own idea of the URL when it lands, which undid + // the bench's address when it was opened meanwhile. A new view from the server (a take + // link) replaces it. + const [view, setView] = useState(served); + useEffect(() => setView(served), [served]); + const reloadSeq = useRef(0); + const reloadView = useCallback(async () => { + const mine = ++reloadSeq.current; + const q = new URLSearchParams({ project: served.project }); + if (view.take && !view.take.defaulted) q.set("take", view.take.id); + else if (!view.take) q.set("cut", "1"); + try { + const r = await fetch(`/api/report/play-view?${q.toString()}`, { cache: "no-store" }); + const j = (await r.json()) as PlayViewData & { error?: string }; + if (mine === reloadSeq.current && r.ok && !j.error) setView(j); + } catch { + // The view stays as it was; Reload the cut asks again. + } + }, [served.project, view.take]); + // Inside the one app (cutApp/CutApp.tsx): Edit opens the bench in place, and the keys are Play's only while it shows. + const app = useCutApp(); + const shown = !app || app.view === "play"; + useEffect(() => app?.onReturn(() => void reloadView()), [app, reloadView]); + const shownRef = useRef(shown); + shownRef.current = shown; const project = view.project; const take = view.take?.id ?? null; // Edits made here (Reject, a reorder, the bench) write the PROJECT'S manifest, which a take @@ -343,6 +370,20 @@ export default function PlayCut({ // composed schedule replacing the estimate's, the render's edges arriving. // Let go once both have settled. A card keeps its offset. const anchor = useRef<{ clip: string; at: number; src?: number; t?: number } | null>(initialAt); + // A place set to be found again (back from the bench, after a reorder): the effect below runs + // for it even when the plan did not change. + const [anchorTick, setAnchorTick] = useState(0); + // ...and held until the view read again after it arrives (a refresh is on its way), at most 20 s. + const awaitView = useRef(0); + const holdForView = useCallback(() => { + awaitView.current = performance.now(); + setAnchorTick((n) => n + 1); + }, []); + useEffect(() => { + if (!awaitView.current) return; + awaitView.current = 0; + setAnchorTick((n) => n + 1); + }, [view]); // THE PLACE IN THE URL: Play keeps where it is -- the clip, the offset into // it, the cut second and the rejected-clips toggle -- in its own URL // (replaceState, at most once a second, never a history entry of its own), @@ -377,19 +418,40 @@ export default function PlayCut({ if (it.clip && a.src === undefined && edges.state !== "measuring") a.src = sourceAt(it, inside(it.from + a.at)) ?? undefined; const landed = it.clip && a.src !== undefined ? inside(cutAtSource(it, a.src)) : inside(it.from + a.at); seekTo(landed); - if (composeState !== "composing" && edges.state !== "measuring") { + const waiting = awaitView.current > 0 && performance.now() - awaitView.current < 20_000; + if (composeState !== "composing" && edges.state !== "measuring" && !waiting) { anchor.current = null; // The cut second it was left at is not where that clip's offset is now: an edit moved it. if (a.t !== undefined && Math.abs(landed - a.t) > 0.1) setBackToast(`Back at ${a.clip} · ${timecode(landed)} (the cut changed)`); } - }, [plan, composeState, edges.state, seekTo]); + }, [plan, composeState, edges.state, seekTo, anchorTick]); // A structural write landed (Reject, its undo): the view and the chrome are read again. const afterStructure = useCallback(() => { setPlaying(false); - router.refresh(); + void reloadView(); + }, [reloadView, setPlaying]); + // The deck is composed again whenever the manifest moved (its token): a Reject, a reorder, an + // Apply, the bench's save seen on the way back -- once, however the view came to be re-read. + const composedFor = useRef(view.token); + useEffect(() => { + if (view.token === composedFor.current) return; + composedFor.current = view.token; if (view.deckOn) void compose(); - }, [router, view.deckOn, compose, setPlaying]); + }, [view.token, view.deckOn, compose]); + // Hidden under the bench (the one app), Play does not play on; shown again, it finds the clip it + // left by its id and the source second (an edit on the bench may have moved it in the cut). + const leftAt = useRef<{ clip: string; at: number; t: number } | null>(null); + const wasShown = useRef(shown); + useEffect(() => { + if (!shown) setPlaying(false); + else if (!wasShown.current && leftAt.current) { + anchor.current = { ...leftAt.current }; + leftAt.current = null; + holdForView(); + } + wasShown.current = shown; + }, [shown, setPlaying, holdForView]); // ---- the controls ---------------------------------------------------------------- const next = useCallback(() => seekTo(startOf(planRef.current, now().cur + 1)), [seekTo, now]); @@ -504,9 +566,17 @@ export default function PlayCut({ if (!h) return; setPlaying(false); // Where Back lands: this place, written now (the one push is the bench's). - window.history.replaceState(null, "", placeHref()); + window.history.replaceState(window.history.state, "", placeHref()); + if (app) { + // In place: Play stays as it is; on the way back the clip (and the source second) is found again. + const e = now(); + const it = planRef.current.items[e.cur]; + leftAt.current = it ? { clip: it.id, at: Math.max(0, e.t - it.from), t: e.t } : null; + app.openClip(it?.id ?? "", h); + return; + } router.push(h); - }, [editHref, router, setPlaying, placeHref]); + }, [editHref, router, setPlaying, placeHref, app, now]); const lastPlace = useRef(0); // A navigation in flight (a take link, Play the latest): Play's own URL write would land on // top of it and cancel it (the audit's "a take link clicked while playing is cancelled"), so @@ -523,7 +593,7 @@ export default function PlayCut({ // Not while a place is still being restored: the URL holds it until it lands. if (anchor.current) return; const due = () => { - if (navigating.current) return; + if (navigating.current || !shownRef.current) return; lastPlace.current = performance.now(); const h = placeHref(); if (h !== `${window.location.pathname}${window.location.search}${window.location.hash}`) window.history.replaceState(null, "", h); @@ -570,7 +640,8 @@ export default function PlayCut({ const e = now(); const it = planRef.current.items[e.cur]; if (it) anchor.current = { clip: it.id, at: Math.max(0, e.t - it.from) }; - }, [now]); + holdForView(); + }, [now, holdForView]); const timelineWrite = useCallback( async (body: Record<string, unknown>) => { const r = await fetch("/api/report/timeline", { @@ -590,7 +661,7 @@ export default function PlayCut({ const { r, j } = await timelineWrite(body); if (r.status === 409 && j.stale) { setEdit({ busy: false, error: "The cut changed since this page read it — read again; drop it again", done: null }); - router.refresh(); + void reloadView(); return; } if (!r.ok) { @@ -600,10 +671,9 @@ export default function PlayCut({ lastToken.current = j.token ?? null; holdPlace(); setEdit({ busy: true, error: null, done: { words: e.words, token: j.token ?? null } }); - router.refresh(); - if (view.deckOn) void compose(); + void reloadView(); }, - [timelineWrite, holdPlace, router, view.deckOn, compose], + [timelineWrite, holdPlace, reloadView], ); const undoEdit = useCallback(async () => { const d = edit.done; @@ -618,9 +688,8 @@ export default function PlayCut({ lastToken.current = j.token ?? null; holdPlace(); setEdit({ busy: true, error: null, done: { ...d, undone: true } }); - router.refresh(); - if (view.deckOn) void compose(); - }, [edit.done, timelineWrite, holdPlace, router, view.deckOn, compose]); + void reloadView(); + }, [edit.done, timelineWrite, holdPlace, reloadView]); const editableWhy = !editable ? `take ${take} has its own timeline: reorder it on its walk (umtool timeline <p> --take ${take} move)` : null; @@ -629,6 +698,7 @@ export default function PlayCut({ const [help, setHelp] = useState(false); useEffect(() => { const onKey = (ev: KeyboardEvent) => { + if (!shownRef.current) return; const tgt = ev.target as HTMLElement | null; if (ev.key === "Escape") { if (help) setHelp(false); @@ -660,6 +730,7 @@ export default function PlayCut({ }; // Space on a focused button would click it too on keyup: the key is the transport's here. const onUp = (ev: KeyboardEvent) => { + if (!shownRef.current) return; const tgt = ev.target as HTMLElement | null; if (ev.key === " " && !tgt?.closest("input, textarea, select, [contenteditable=true]")) ev.preventDefault(); }; @@ -1096,7 +1167,7 @@ export default function PlayCut({ data-play-reload="" title="read the cut again after an edit elsewhere" onClick={() => { - router.refresh(); + void reloadView(); if (view.deckOn) void compose(); }} > @@ -1126,10 +1197,7 @@ export default function PlayCut({ onNote={noteHere} onClose={closeDraft} onSeek={(n) => seekTo(noteT(n.anchor as CutAnchor))} - onApplied={() => { - router.refresh(); - if (view.deckOn) void compose(); - }} + onApplied={() => void reloadView()} exportable={(id) => { const e = entryOf.get(id); return e?.type === "clip" && !!e.media; diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -0,0 +1,294 @@ +import { notFound } from "next/navigation"; +import { projectsHref, clipBenchHref, playHref, takeClipHref, takeWalkHref, takesHref } 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_PAD } from "@/lib/report/driver.mjs"; +import { deckOn } from "umtool-report-to-video/deck"; +import { pieceHrefOfProject } from "@/lib/pieces/article"; +import type { ProjectRef } from "@/lib/project-types"; + +// THE CLIP BENCH'S DATA, in one place: what `/projects/<p>/clip/<id>` 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. + +/** 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; +}; + +/** + * @returns null when the clip is not a clip of the cut (or the take) -- the page's 404 + */ +export async function clipBenchData( + project: ProjectRef, + clipId: string, + { search = {}, take = null, order = "walk" }: { search?: Record<string, string | undefined>; take?: string | null; 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<ReturnType<typeof walkOf>>; + try { + walk = await walkOf(project, { take, 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. A take's clip has none: the + // project's segments are the project's cut. + const seg = take ? null : 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, + 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. + gaps: + ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) + ?.gaps ?? [], + 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 ?? {}), + 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: take ? null : (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, + 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, or -- walking a take -- the take's. + 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. + maxPad: FETCH_MAX_PAD, + // 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). + // Walking a take, Back is the take's walk (its overview), on the Takes page's side. + const back = take ? takeWalkHref(project.id, take, { all }) : 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. A take's render does not change when the + // project's manifest does, so a take's Back is the project's cut too, and + // the bench says so (`take`). + const fromPlay = !take && 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) => + take ? takeClipHref(project.id, take, id, { all }) : withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {})); + data.walkHrefs = { + prev: prev ? href(prev) : null, + next: next ? href(next) : null, + back, + backLabel: take ? `take ${take}` : project.name, + }; + if (take && walk.take) { + const timeline = (manifest.timeline ?? []) as { id: string }[]; + data.take = { + id: take, + label: walk.take.label, + draft: walk.take.draft, + editable: walk.take.editable, + all, + takesHref: takesHref(project.id), + walkHref: takeWalkHref(project.id, take, { all }), + toggleAllHref: takeClipHref(project.id, take, clipId, { all: !all }), + clipHref: Object.fromEntries(data.siblings.map((sb: { id: string }) => [sb.id, takeClipHref(project.id, take, sb.id, { all })])), + at: timeline.findIndex((e) => e.id === clipId), + entries: timeline.length, + }; + } + 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 = take || fromPlay ? null : playHref(project.id, { clip: clipId }); + const top: BenchTopSpec = { + trail: take ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }] : [{ href: projectsHref(), label: "Projects" }], + back: { href: back, label: take ? `take ${take}` : project.name }, + kind: take ? "Take walk" : 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: fromPlay || !take, + 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}` : ""}`, + }; + return { data, top }; +} + +/** clipBenchData, or the page's 404. */ +export async function clipBenchDataOr404(...args: Parameters<typeof clipBenchData>) { + const r = await clipBenchData(...args); + if (!r) notFound(); + return r; +}