"use client"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { postBenchHref } from "@/lib/hrefs"; import { announceManifestChanged } from "./timelineApi"; import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds, ownPictureOnly, postItemPlan, readingSeconds, refPictureOnly, ruleSeconds, panelEntry } from "umtool-report-to-video/post-item"; import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; import PostThreadPanel from "./PostThreadPanel"; import PostScreensPanel from "./PostScreensPanel"; import { playableEntry } from "umtool-report-to-video/post-thread"; import BlurBoxPad, { type Band } from "./BlurBoxPad"; import PostNarrationPanel from "./PostNarrationPanel"; import PostComboPanel from "./PostComboPanel"; import ComboBadge, { type ComboInfo } from "./review/ComboBadge"; import { liveCombo } from "umtool-report-to-video/post-combo"; import PostZoomPanel from "./PostZoomPanel"; import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; import { captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; import { slamLandings, slamSpan, slamTimes } from "umtool-report-to-video/post-slam"; import { clockPlan } from "umtool-report-to-video/post-clock"; import { progressPlan } from "umtool-report-to-video/post-progress"; import { sceneEntry } from "umtool-report-to-video/post-media-scene"; // --------------------------------------------------------------------------- // THE POST BENCH, the client half (PostBenchPage.tsx): the item played on its // own clock in its final look (PostItemPlayer: the build's card page, the // attachments laid into its slot), and its knobs, each change shown at once // and saved by one write (updatePostItem, POST /api/report/post-item): // // hold the item's whole length (absent: the duration rule) // layout a grid of its 2-4 images, or one after another // redact other authors: auto (the privacy rule), blurred, shown // media[i] a video's or a GIF's in and out (the playhead sets them), // its sound, a crop of any attachment, an image's push-in, // and a video's words: Transcribe asks the EDITOR's // transcription (a job on a local worker), never ASR here // thread a read of the post it answers or quotes: what each is on // screen while it is read and after (PostThreadPanel) // screens the text screenshots in its attachments, transcribed, drawn and // read after its words (PostScreensPanel) // context the post it quotes, the posts it answers: a paraphrase of // a long one, drawn in place of its words with a // "paraphrased" label (its own text kept, shown beside) // --------------------------------------------------------------------------- type Blur = { on: boolean; strength?: number; boxes?: number[][]; label?: string | false; band?: Band; style?: "blur" | "black" | "pixelate" }; type Media = Record & { src: string; kind: string; seconds?: number; start?: number; end?: number; mute?: boolean; crop?: number[]; push?: boolean; words?: string; audio?: boolean; width?: number; height?: number; blur?: Blur }; type Ref = Record & { author?: string; handle?: string; text?: string; paraphrase?: string; media?: Media[]; pictureOnly?: boolean }; type Entry = Record & { id: string; media?: Media[]; hold?: number; mediaLayout?: string; redact?: boolean; quoted?: Ref; parents?: Ref[]; pictureOnly?: boolean }; /** A post with its `pictureOnly` knob set (undefined: the rule, post-picture.mjs). */ const withPictureOnly = >(p: T, v: boolean | undefined): T => { const out = { ...p } as Record; if (v === undefined) delete out.pictureOnly; else out.pictureOnly = v; return out as T; }; const r2 = (v: number) => Math.round(v * 100) / 100; /** A context post with its paraphrase set (undefined: none, its own words). */ const withParaphrase = (ref: Ref, paraphrase: string | undefined): Ref => { const out = { ...ref }; if (paraphrase === undefined) delete out.paraphrase; else out.paraphrase = paraphrase; return out; }; /** A band's edge across: below, above, between, or none. */ const bandAcross = (b: Band | undefined) => (typeof b?.below === "number" ? "below" : typeof b?.above === "number" ? "above" : Array.isArray(b?.between) ? "between" : "none"); const bandEmpty = (b: Band) => (Object.keys(b).length ? b : undefined); /** The band with its edge across set to `to` (none: dropped), the line where it was (or a third of the way down). */ const withAcross = (b: Band | undefined, to: string): Band | undefined => { const { below, above, between, ...rest } = b ?? {}; const at = below ?? above ?? (between ? between[0] : 0.38); if (to === "none") return bandEmpty(rest); return { ...rest, ...(to === "between" ? { between: between ?? [Math.min(at, 0.6), Math.max(0.7, Math.min(0.95, at + 0.3))] } : { [to]: at }) }; }; /** The band with its upright edge set to `to` (all: dropped). */ const withUpright = (b: Band | undefined, to: string): Band | undefined => { const { left, right, ...rest } = b ?? {}; if (to === "all") return bandEmpty(rest); return { ...rest, [to]: left ?? right ?? 0.5 }; }; const CROPS: Array<{ label: string; crop: number[] | null }> = [ { label: "none", crop: null }, { label: "centre 80%", crop: [0.1, 0.1, 0.8, 0.8] }, { label: "top half", crop: [0, 0, 1, 0.5] }, { label: "bottom half", crop: [0, 0.5, 1, 0.5] }, ]; /** Its media scene (post-media-scene.mjs mediaSceneOf), as the page counted it. */ type Scene = { key: string; n: number; of: number; ids: string[]; media: number | null; anchor: { id: string; media: number; entry: { id: string; post: string; media: Array> } }; before: Array> } | null; export default function PostBench({ project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null, scene: savedScene = null, conversation = null, layout = "bench", }: { /** * `inspector`: the workspace's inspector (umtool redesign L7a) -- one column, no way back or to the next post * (the workspace walks the blocks), its keys its own only while the focus is in it. Every save writes the draft. */ layout?: "bench" | "inspector"; project: string; entry: Entry; token: string | null; box: { width: number; height: number }; plan: PostPlan; back: { href: string; label: string }; prev: string | null; next: string | null; fromPlay: boolean; /** The cut's render block (its `postNarration` knobs). */ render?: Record; /** Its combo (post-combo.mjs): the attachment the cut plays again here, its count, its group. */ combo?: ComboInfo | null; /** The timeline entry before it in the cut (post-thread.mjs: a parent that is that item is carried in). */ before?: Record | null; /** Its media scene (post-media-scene.mjs): the neighbours with the same attachment, as saved. */ scene?: Scene; /** The posts its conversation's run leaves on screen (post-conversation.mjs planContext): kept on top or collapsed away. It wins the card over a media scene. */ conversation?: Record | null; }) { const router = useRouter(); const inspector = layout === "inspector"; const rootRef = useRef(null); const [entry, setEntry] = useState(initial); const [saved, setSaved] = useState(initial); const [token, setToken] = useState(initialToken); const [status, setStatus] = useState(null); const [error, setError] = useState(null); // In a media scene (post-media-scene.mjs) the item plays as the scene does: the shared attachment the // anchor's, the scene's earlier messages above its card. Out of it (scene: false, unsaved) at once. // The anchor's own bench: its attachment as it is being edited (its crop, its censor), not as saved. const scene = useMemo( () => entry.scene === false || !savedScene ? null : savedScene.anchor.id === entry.id ? { ...savedScene, anchor: { ...savedScene.anchor, entry: { ...savedScene.anchor.entry, media: (entry.media ?? []) as Array> } } } : savedScene, [entry, savedScene], ); // What plays: never a read the build refuses (post-thread.mjs playableEntry) -- the item silent, the reason said. const shown = useMemo(() => playableEntry(panelEntry(sceneEntry(entry, scene), render)) as Entry, [entry, scene, render]); const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(shown, render, { prev: before, scene: conversation, mediaScene: conversation ? null : scene }) as PostPlan)), [entry, shown, initial, initialPlan, render, before, scene, conversation]); // Its progress bar (post-progress.mjs): the read's span and its parts' ticks. const progressP = useMemo(() => progressPlan(shown, render, plan as never), [shown, render, plan]); const total = plan.total; const [s, setS] = useState(0); const [playing, setPlaying] = useState(false); const raf = useRef(0); useEffect(() => { if (!playing) return; let last = performance.now(); const tick = (now: number) => { const dt = (now - last) / 1000; last = now; setS((x) => { const n = x + dt; if (n >= total) { setPlaying(false); return total; } return n; }); raf.current = requestAnimationFrame(tick); }; raf.current = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf.current); }, [playing, total]); useEffect(() => { const onKey = (ev: KeyboardEvent) => { const tgt = ev.target as HTMLElement | null; if (tgt?.closest("input, textarea, select")) return; if (inspector && !(tgt && rootRef.current?.contains(tgt))) return; if (ev.key === " ") { ev.preventDefault(); setPlaying((p) => (s >= total ? (setS(0), true) : !p)); } // N / P: the next or previous post of the cut (the recording session walks the cut). if ((ev.key === "n" || ev.key === "p") && !ev.metaKey && !ev.ctrlKey && !ev.altKey) { const to = ev.key === "n" ? next : prev; if (to) { ev.preventDefault(); router.push(postBenchHref(project, to, fromPlay ? { play: { at: 0 } } : {})); } } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [s, total, next, prev, project, fromPlay, router, inspector]); const dirty = JSON.stringify(entry) !== JSON.stringify(saved); const media = entry.media ?? []; const setMedia = (i: number, patch: Partial) => setEntry((e) => ({ ...e, media: (e.media ?? []).map((m, j) => (j === i ? clean({ ...m, ...patch }) : m)) })); const clean = (m: Media): Media => { const out = { ...m } as Record; for (const [k, v] of Object.entries(out)) if (v === undefined || v === null) delete out[k]; return out as Media; }; // The patch the writer takes: every knob as it stands now (null: the default again). const patchOf = (e: Entry) => ({ hold: typeof e.hold === "number" ? e.hold : null, mediaLayout: e.mediaLayout ?? null, redact: typeof e.redact === "boolean" ? e.redact : null, // Its read-follow (read-follow.mjs): false is off; its knobs, each null when it is the cut's. follow: e.follow === false ? false : e.follow && typeof e.follow === "object" ? { on: null, dim: null, ease: null, ...(e.follow as Record) } : null, // Its media scene (post-media-scene.mjs): false (never in one), "join", or null (by its attachment). scene: e.scene === false || e.scene === "join" ? e.scene : null, // Its thread read (post-thread.mjs): its knobs, each null when it is the cut's. thread: e.thread && typeof e.thread === "object" ? { parent: null, quoted: null, carry: null, reveal: null, shrink: null, dim: null, seconds: null, pan: null, ...(e.thread as Record) } : null, media: Object.fromEntries( (e.media ?? []).map((m, i) => [ i, { start: typeof m.start === "number" ? m.start : null, end: typeof m.end === "number" ? m.end : null, mute: m.mute === true ? true : null, crop: Array.isArray(m.crop) ? m.crop : null, push: m.push === true ? true : null, // The censoring blur (post-censor.mjs), every key as it stands (null: cleared). blur: m.blur ? { on: m.blur.on === true, strength: m.blur.strength ?? null, boxes: m.blur.boxes?.length ? m.blur.boxes : null, label: m.blur.label === undefined ? null : m.blur.label, band: m.blur.band ?? null, style: m.blur.style ?? null } : null, }, ]), ), // Picture-only (post-picture.mjs): true, false, or null (the rule). pictureOnly: typeof e.pictureOnly === "boolean" ? e.pictureOnly : null, // Its screens (post-screens.mjs): the whole list as it stands (null: none). screens: Array.isArray(e.screens) && e.screens.length ? e.screens : null, ...(e.quoted && typeof e.quoted === "object" ? { quoted: { paraphrase: e.quoted.paraphrase?.trim() ? e.quoted.paraphrase : null, pictureOnly: typeof e.quoted.pictureOnly === "boolean" ? e.quoted.pictureOnly : null } } : {}), ...(Array.isArray(e.parents) && e.parents.length ? { parents: Object.fromEntries(e.parents.map((p, i) => [i, { paraphrase: p?.paraphrase?.trim() ? p.paraphrase : null, pictureOnly: typeof p?.pictureOnly === "boolean" ? p.pictureOnly : null }])) } : {}), }); // The context posts the card draws: the one it quotes, the ones it answers (nearest first). const contexts: Array<{ key: string; label: string; ref: Ref; set: (paraphrase: string | undefined) => void }> = [ ...(Array.isArray(entry.parents) ? entry.parents : []).map((ref, i) => ({ key: `parent.${i}`, label: i === 0 ? "the post it answers" : `the post that answers (${i + 1} up)`, ref, set: (paraphrase: string | undefined) => setEntry((x) => ({ ...x, parents: (x.parents ?? []).map((p, j) => (j === i ? withParaphrase(p, paraphrase) : p)) })), })), ...(entry.quoted && typeof entry.quoted === "object" ? [{ key: "quoted", label: "the post it quotes", ref: entry.quoted, set: (paraphrase: string | undefined) => setEntry((x) => ({ ...x, quoted: withParaphrase(x.quoted ?? {}, paraphrase) })) }] : []), ]; const save = useCallback(async () => { setError(null); setStatus("saving…"); const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "set", id: entry.id, patch: patchOf(entry), token }), }); const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[] }; if (!res.ok || !j.entry) { setStatus(null); setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); return; } setEntry(j.entry); setSaved(j.entry); setToken(j.token ?? null); setStatus("saved"); // The draft moved: whatever else on the page holds it (the workspace's viewer and strip) reads it again. announceManifestChanged(project); // A scene knob changed: the page counts the scene again (its neighbours are read on the server). if ((saved.scene ?? null) !== (j.entry.scene ?? null)) router.refresh(); }, [entry, project, token, saved, router]); // Transcribe a video attachment through the editor (a job), then follow it. const [jobs, setJobs] = useState>({}); const transcribe = async (i: number) => { setError(null); const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "transcribe", id: entry.id, media: i }) }); const j = (await res.json().catch(() => ({}))) as { jobId?: string; error?: string }; if (!res.ok || !j.jobId) { setJobs((x) => ({ ...x, [i]: { job: "", state: "failed", error: j.error ?? `HTTP ${res.status}` } })); return; } setJobs((x) => ({ ...x, [i]: { job: j.jobId!, state: "transcribing" } })); }; useEffect(() => { const running = Object.entries(jobs).filter(([, v]) => v.state === "transcribing" && v.job); if (!running.length) return; const t = setTimeout(async () => { for (const [i, v] of running) { const res = await fetch(`/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&media=${i}&job=${encodeURIComponent(v.job)}`); const j = (await res.json().catch(() => ({}))) as { state?: string; words?: string; error?: string }; if (j.state === "done" && j.words) { setMedia(Number(i), { words: j.words }); setSaved((e) => ({ ...e, media: (e.media ?? []).map((m, k) => (k === Number(i) ? { ...m, words: j.words } : m)) })); router.refresh(); } if (j.state !== "transcribing") setJobs((x) => ({ ...x, [i]: { ...v, state: j.state ?? "failed", error: j.error } })); } }, 2000); return () => clearTimeout(t); }); const zoomMarks = useMemo( () => (wordZoomTimes(entry, render) as Array<{ i: number; t?: number }>) .filter((z) => typeof z.t === "number") .map((z) => ({ i: z.i, ...zoomSpan((entry.fx as Array>)[z.i], z.t as number) })), [entry, render], ); const captionMarks = useMemo( () => (captionTimes(entry, render) as Array<{ i: number; t?: number }>) .filter((c) => typeof c.t === "number") .map((c) => { const f = resolveCaption((entry.fx as Array>)[c.i]); return { i: c.i, t0: Math.max(0, (c.t as number) - f.lead), t3: (c.t as number) + f.hold + 0.35 }; }), [entry, render], ); // Its slams (post-slam.mjs): each from its first glyph in to gone, a tick at each hit. const slamMarks = useMemo( () => (slamTimes(entry, render) as Array<{ i: number; t?: number; end?: number | null }>) .filter((x) => typeof x.t === "number") .map((x) => { const fx = (entry.fx as Array>)[x.i]; const sp = slamSpan(fx, slamLandings(fx, { t: x.t as number, end: x.end ?? null })); return { i: x.i, t0: sp.t0 ?? 0, t3: sp.t3 ?? 0, landings: sp.landings ?? [] }; }), [entry, render], ); const stepOf = (i: number) => plan.steps.find((st) => st.items.some((m) => m.i === i)) ?? null; const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); const reading = readingSeconds(entry); return (
{!inspector && ( {back.label} )} {!inspector && prev && ( ‹ {prev} )} {!inspector && next && ( {next} › )} {s.toFixed(1)} / {total.toFixed(1)} s
setS(Number(e.target.value))} className="flex-1" aria-label="item position" data-post-bench-scrub="" />
{/* The plan, as a strip: the reading span, then each attachment's step. */}
{plan.reading > 0 && (
read {plan.reading.toFixed(1)} s
)} {plan.steps.map((st, k) => (
{st.kind} {st.seconds.toFixed(1)} s
))} {/* Its word zooms (word-zoom.mjs): each from its lead-in to back out. */} {zoomMarks.map((z) => (
))} {/* Its captions (post-caption.mjs): each from its lead-in to gone (one waiting for a zoom is drawn later). */} {captionMarks.map((c) => (
))} {slamMarks.map((m) => (
{m.landings.map((L, j) => ( ))}
))}
{ setEntry(e as Entry); setSaved(e as Entry); setToken(t); }} /> setEntry((e) => f(e) as Entry)} /> setEntry((e) => f(e) as Entry)} onEntry={(e, t) => { setEntry(e as Entry); setSaved(e as Entry); setToken(t); }} /> setEntry((e) => f(e) as Entry)} onEntry={(e, t) => { setEntry(e as Entry); setSaved(e as Entry); setToken(t); }} /> { setEntry(e); setSaved(e); setToken(t); }} onTrim={(i, patch) => setMedia(i, patch)} s={s} setS={setS} setPlaying={setPlaying} prev={prev} next={next} fromPlay={fromPlay} />