"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/

/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/?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. // // A take's clip is not benched here (L3): its old address // (`/takes//clip/`) is the Open in draft page, a navigation of its own. // --------------------------------------------------------------------------- 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(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 (`/clip/`), or null. */ function clipOf(pathname: string, project: string): string | null { const root = `/projects/${project.split("/").map(encodeURIComponent).join("/")}/`; if (!pathname.startsWith(root)) return null; const rest = pathname.slice(root.length).split("/"); return rest.length === 2 && rest[0] === "clip" && rest[1] ? decodeURIComponent(rest[1]) : null; } const playPath = (project: string) => `/projects/${project.split("/").map(encodeURIComponent).join("/")}/play`; // THE WORKSPACE (umtool redesign L7a) is this app grown: its own address (`home`, the project's) is the // screen that stays mounted, as Play's is here, and E opens the clip bench over it in place the same way. export default function CutApp({ project, playTop, children, home: homeAt, kind = "play", }: { project: string; playTop: React.ReactNode; children: React.ReactNode; /** The address of the view that stays mounted (default: Play's, `/projects/

/play`). */ home?: string; /** Its frame's `data-bench-shell`. */ kind?: string; }) { const home = homeAt ?? playPath(project); // The bench's "Back to the cut" names Play's address: inside the workspace that is the workspace too. const isPlay = useCallback((pathname: string) => pathname === home || pathname === playPath(project), [home, project]); const router = useRouter(); const [view, setView] = useState({ kind: "play" }); const viewKind = useRef("play"); viewKind.current = view.kind; 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>()); 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 }, "", home); setView({ kind: "play" }); returned(); }, [home, 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)) { backToPlay(); return; } const id = clipOf(u.pathname, project); if (id) { openClip(id, `${u.pathname}${u.search}`); return; } router.push(href); }, [project, backToPlay, openClip, router, isPlay], ); // 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)) { depth.current = 0; // A history step that stays on the home view (the workspace's mode, present's slides) is not a return. if (viewKind.current === "play") return; 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, isPlay]); // 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) || clipOf(u.pathname, project)) { e.preventDefault(); e.stopPropagation(); navigate(`${u.pathname}${u.search}`); } }; const api = useMemo(() => ({ view: view.kind, openClip, onReturn }), [view.kind, openClip, onReturn]); const b = bench?.state === "ready" ? bench.bench : null; return ( {/* Play: mounted always, hidden (and paused) while the bench is up. */}

{children}
{view.kind === "clip" && (
{b ? ( }> ) : (
{view.id} {bench?.state === "error" ? `the bench did not open: ${bench.error}` : "opening the bench…"}
)}
)} ); }