"use client"; import Link from "next/link"; import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { useSharedNotes } from "@/components/notes/NotesProvider"; import { notesOn } from "@/components/notes/AnchoredNotes"; import { NoteThread } from "@/components/notes/NoteThread"; import type { CitedPlay } from "@/lib/clips/types"; import { FlashForwardForm, addToTrailer } from "./CutEditing"; import { edgeClock, newClipEntry, nextFreeId, provenanceWords, quoteBetween, roleOf, snapCut, snapPoints, spanQuote } from "@/lib/report/clipEditorModel.mjs"; import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Speaker, Turn } from "@/lib/report/clipEditorTypes"; import { cn } from "@/lib/utils"; import { ROOM, roomShade } from "umtool-report-to-video/room"; import { startTakeJob } from "../NewTakePanel"; import { refusalOf, timelineOp } from "../timelineApi"; import AssistBox from "../report/AssistBox"; import { AudioBox, BlurBox, MarksBox } from "./ClipKnobs"; import LiveDeckPreview from "./LiveDeckPreview"; import CensorOverlay, { type CensorRegion } from "./CensorOverlay"; // Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional). import type { ReplyProposal } from "@/lib/annotations/types"; import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest"; import WordStrip from "../bench/WordStrip"; // --------------------------------------------------------------------------- // THE CLIP EDITOR (release 35 C2): a person hops in on an assistant's clips. // // the player loops the selected clip's cut (a saved video, a clip // window, or audio -- what /api/cited/play finds) // the strip the clip's neighbourhood (± 60 s, or closer): the speaker // turns coloured by role (host / subject, reactions.json), // laugh marks, the words, the other clips, the cut with drag // handles; a drag on the strip selects a span to add // the edges numeric fields, nudges ±0.1 / ±0.5 / ±2 s, Snap to the // nearest word gap or silence // the decisions Keep / Cut (montage-rulings.json, keyed by the moment), // Split here, Merge with next, Restore the assistant's // version, Add a clip from the selection, Bring in a proposal, // New clip (from the selection, or the span after this clip: // inserted AFTER it through the timeline route's `insert`, // its quote read from the words, Blur picture on it) // the comments a note on the clip (notes.json, anchored to it), its thread // and an agent's replies, resolve / reopen // the short (release 36) a 9:16 box dragged on the player (the clip's // `vertical.crop`), Make a short (a job: shorts/.mp4); // a speaker's name for the captions in the Speakers list // the knobs (video knobs) Marks on every clip -- each mark's verdict, // second (Set at playhead, Shift+S), hold, on/off, count, // label; Add mark at playhead (Shift+M) -- Audio: sync // nudge, gain, fades -- and Blur: the picture blurred at the // encode, its caption, strength, and a span at the playhead // (./ClipKnobs.tsx) // // Every write is one POST to /api/report/clip-editor; the answer is the whole // view again, so the page never guesses what the server did. Edge edits are // drafted locally and written after a short pause, so a run of nudges is one // edit. Nothing here calls a model. // --------------------------------------------------------------------------- // ± 180 s: far enough to select the span just past a long clip (New clip). const REACHES = [180, 60, 20, 6] as const; /** The strip's reach on a clip's first visit, and the player's (it looks for a file this far around the clip). */ const REACH_DEFAULT = 60; const NUDGES = [-2, -0.5, -0.1, 0.1, 0.5, 2] as const; const COMMIT_MS = 450; const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; const ROLE_FILL: Record = { host: "bg-signal", subject: "bg-meter", other: "bg-muted" }; const ROLE_WORD: Record = { host: "host", subject: "subject", other: "other" }; const r2 = (n: number) => Math.round(n * 100) / 100; const cutOf = (c: EditorClip) => ({ cutStart: c.cutStart ?? c.start, cutEnd: c.cutEnd ?? c.end }); const rulingBadge = (r: string) => (r === "keep" ? cn(badgeVariants({ variant: "neutral", size: "sm" }), "border-kept-text text-kept-text") : badgeVariants({ variant: "blocking", size: "sm" })); const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; type Cut = { cutStart: number; cutEnd: number }; async function post(body: Record): Promise<{ ok: boolean; status: number; json: Record }> { const r = await fetch("/api/report/clip-editor", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); const json = (await r.json().catch(() => ({}))) as Record; return { ok: r.ok, status: r.status, json }; } export default function ClipEditor({ project, initialView, initialClip, takesHref, render, takes, }: { project: string; initialView: EditorView; initialClip: string; takesHref: string; render: RenderTarget; takes: number; }) { const [view, setView] = useState(initialView); const [selected, setSelected] = useState(initialClip); const [draft, setDraft] = useState(null); const [reach, setReach] = useState(REACH_DEFAULT); const [hood, setHood] = useState(null); const [playhead, setPlayhead] = useState(null); const [playing, setPlaying] = useState(false); const [selection, setSelection] = useState(null); const [speakerPick, setSpeakerPick] = useState(null); const [rolesChanged, setRolesChanged] = useState(false); const [busy, setBusy] = useState(false); const [framing, setFraming] = useState(false); const [error, setError] = useState(null); const [status, setStatus] = useState(null); const token = useRef(initialView.token); const chain = useRef>(Promise.resolve()); const timer = useRef | null>(null); const pending = useRef<{ clip: string; cut: Cut } | null>(null); const player = useRef(null); const clips = view.clips; const index = Math.max(0, clips.findIndex((c) => c.id === selected)); const clip = clips[index] ?? clips[0]; const committed = cutOf(clip); const cut = draft ?? committed; const speakers = view.reactions?.speakers ?? []; // The assistant (release 36 lane D): labels, a rank to sort by, Suggest, Ask. const assistant = useClipSuggest(project); const [byRank, setByRank] = useState(false); const rankOf = (proposal: string | null | undefined) => assistant.labelOf(proposal)?.rank ?? Number.POSITIVE_INFINITY; // The page's address names the clip, so a reload (or a link) lands on it. useEffect(() => { const u = new URL(window.location.href); if (u.searchParams.get("clip") === clip.id) return; u.searchParams.set("clip", clip.id); window.history.replaceState(null, "", u.toString()); }, [clip.id]); // ---- writes --------------------------------------------------------------- const reload = useCallback(async () => { const r = await fetch(`/api/report/clip-editor?project=${encodeURIComponent(project)}`, { cache: "no-store" }); const j = (await r.json()) as EditorView & { error?: string }; if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); token.current = j.token; setView(j); }, [project]); const write = useCallback( (body: Record, done?: string) => { const run = async () => { setBusy(true); try { const r = await post({ project, token: token.current, ...body }); if (r.status === 409) { await reload(); setError(`${String(r.json.error ?? "the cut changed")} — reloaded; check and try again`); return null; } if (!r.ok) { setError(String(r.json.error ?? `HTTP ${r.status}`)); return null; } const next = r.json.view as EditorView; token.current = next.token; setView(next); setError(null); if (done) setStatus(done); return r.json; } catch (e) { setError(e instanceof Error ? e.message : String(e)); return null; } finally { setBusy(false); } }; const p = chain.current.then(run, run); chain.current = p; return p; }, [project, reload], ); const flush = useCallback(() => { if (timer.current) clearTimeout(timer.current); timer.current = null; const p = pending.current; pending.current = null; if (!p) return chain.current; return write({ op: "trim", clip: p.clip, cutStart: p.cut.cutStart, cutEnd: p.cut.cutEnd }, "Saved the edges").then(() => setDraft(null)); }, [write]); /** Move the edges now; write them after a short pause (a run of nudges is one edit). */ const setEdges = useCallback( (next: Cut, { now = false }: { now?: boolean } = {}) => { const a = r2(Math.max(0, next.cutStart)); const b = r2(next.cutEnd); if (b - a < 0.5) { setError("a clip must be at least half a second"); return; } setError(null); setDraft({ cutStart: a, cutEnd: b }); pending.current = { clip: clip.id, cut: { cutStart: a, cutEnd: b } }; if (timer.current) clearTimeout(timer.current); if (now) void flush(); else timer.current = setTimeout(() => void flush(), COMMIT_MS); }, [clip.id, flush], ); const choose = useCallback( (id: string) => { void flush(); setSelected(id); setDraft(null); setSelection(null); setSpeakerPick(null); setPlayhead(null); setStatus(null); }, [flush], ); useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []); // ---- the neighbourhood ---------------------------------------------------- const duration = hood?.duration ?? view.reactions?.source?.duration ?? null; const viewFrom = Math.max(0, Math.floor(committed.cutStart - reach)); const viewTo = Math.ceil(duration ? Math.min(duration, committed.cutEnd + reach) : committed.cutEnd + reach); useEffect(() => { let live = true; const q = new URLSearchParams({ project, clip: clip.id, from: String(viewFrom), to: String(viewTo) }); void fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" }) .then(async (r) => { const j = await r.json(); if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); if (live) setHood(j as Neighbourhood); }) .catch((e) => live && setError(e instanceof Error ? e.message : String(e))); return () => { live = false; }; }, [project, clip.id, viewFrom, viewTo]); const hoodHere = hood && hood.from === viewFrom && hood.to === viewTo ? hood : null; const points = useMemo(() => (hoodHere ? snapPoints({ words: hoodHere.words, turns: hoodHere.turns, cues: hoodHere.cues }) : []), [hoodHere]); // ---- decisions ------------------------------------------------------------ const rule = (verdict: "keep" | "cut" | null) => { void flush().then(() => write({ op: "ruling", clip: clip.id, verdict }, verdict ? `Ruled ${verdict}` : "Ruling cleared")); }; const splitHere = () => { const at = playhead; if (at === null || at - cut.cutStart < 0.5 || cut.cutEnd - at < 0.5) { setError("put the playhead inside the cut (half a second from either edge) to split there"); return; } void flush().then(() => write({ op: "split", clip: clip.id, at: r2(at) }, `Split at ${edgeClock(at)}`)); }; const next = clips[index + 1] ?? null; const mergeNext = () => { if (!next) return; void flush().then(() => write({ op: "merge", clip: clip.id }, `Merged ${next.id} into ${clip.id}`)); }; const restore = () => { void flush().then(() => write({ op: "restore", clip: clip.id }, "Restored the assistant's version")); }; const addSelection = () => { if (!selection) return; void flush() .then(() => write({ op: "add", clip: clip.id, cutStart: r2(selection.cutStart), cutEnd: r2(selection.cutEnd) }, "Added a clip")) .then((j) => { const id = (j?.result as { id?: string } | undefined)?.id; setSelection(null); if (id) choose(id); }); }; // Flash-forward the selected span (a repeat elsewhere in the cut, or moved // out of the clip), and Add to trailer (the selection, else the cut): UI // notes 2026-10-30, items 2 and 11 (CutEditing.tsx). const [flash, setFlash] = useState<{ from: number; to: number } | null>(null); const selInClip = !!selection && selection.cutEnd - selection.cutStart >= 0.5 && selection.cutStart >= clip.start - 0.02 && selection.cutEnd <= clip.end + 0.02; const openFlash = () => { if (!selection || !selInClip) { setError(`select the span to flash forward on the strip, inside ${clip.id}'s window (${edgeClock(clip.start)}–${edgeClock(clip.end)})`); return; } setFlash({ from: r2(selection.cutStart), to: r2(selection.cutEnd) }); }; const goFlash = (body: Record) => { void flush() .then(() => write(body, body.move ? `Moved ${edgeClock(Number(body.from))}–${edgeClock(Number(body.to))} out of ${clip.id}` : `Flash-forward: a copy of ${edgeClock(Number(body.from))}–${edgeClock(Number(body.to))} put earlier`)) .then((j) => { if (!j) return; setFlash(null); setSelection(null); const id = (j.result as { id?: string } | null)?.id; if (id) setStatus(`${body.move ? "Moved" : "Copied"} to ${id} (a repeat of ${clip.id}${body.move ? ", moved" : ""})`); }); }; const trailer = () => { const span = selInClip && selection ? { from: r2(selection.cutStart), to: r2(selection.cutEnd) } : { from: cut.cutStart, to: cut.cutEnd }; void flush().then(async () => { const r = await addToTrailer(project, clip.id, span); if (r.ok) { setError(null); setStatus(r.message); } else setError(r.message); }); }; // New clip (from the selection, or the span after this clip): the form, then // the timeline route's `insert` after this clip -- snapshotted, checked by // the build's own validators, an edit note on a generated cut -- and the // editor on the new clip. const [newClip, setNewClip] = useState(null); const openNewClip = () => { if (selection) return setNewClip(selection); const len = Math.max(5, clip.end - clip.start); const a = clip.end; const b = duration ? Math.min(duration, a + len) : a + len; setNewClip(b - a >= 0.5 ? { cutStart: r2(a), cutEnd: r2(b) } : { cutStart: r2(Math.max(0, clip.start - len)), cutEnd: r2(clip.start) }); }; const insertClip = async (entry: Record) => { await flush(); setBusy(true); try { const res = await timelineOp(project, token.current, "insert", { afterId: clip.id, entry }); if (!res.ok) { if (res.json.stale) await reload().catch(() => {}); setError(refusalOf(res)); return false; } await reload(); const id = typeof res.json.id === "string" ? res.json.id : null; setNewClip(null); setSelection(null); if (id) { choose(id); setStatus(`New clip ${id} after ${clip.id}`); } return true; } catch (e) { setError(e instanceof Error ? e.message : String(e)); return false; } finally { setBusy(false); } }; const bringIn = (p: Proposal) => { void flush() .then(() => write({ op: "bring-in", proposal: p.id }, `Brought in ${p.id}`)) .then((j) => { const id = (j?.result as { id?: string } | undefined)?.id; if (id) choose(id); }); }; const setRole = (speaker: number, role: "host" | "subject" | "other") => { void write({ op: "role", speaker, role }, `Speaker ${speaker} is the ${ROLE_WORD[role]}`).then((j) => { if (j) setRolesChanged(true); }); }; const setLabel = (speaker: number, label: string) => { void write({ op: "label", speaker, label: label.trim() || null }, label.trim() ? `Speaker ${speaker} is “${label.trim()}” in the captions` : `Speaker ${speaker}'s name cleared`); }; // Room at this clip's edges (release 36 lane E): off writes `room: false`; // on again removes the override when the cut has room, else turns both edges on. // The box shows the choice at once (roomDraft) until the view comes back. const [roomDraft, setRoomDraft] = useState<{ clip: string; on: boolean } | null>(null); const setRoom = (on: boolean) => { const cutHas = !!(view.room?.tail || view.room?.head); const room = on ? (cutHas ? null : { tail: true, head: true }) : cutHas ? false : null; setRoomDraft({ clip: clip.id, on }); void write({ op: "room", clip: clip.id, room }, on ? "Room at this clip's edges" : "No room at this clip's edges").finally(() => setRoomDraft(null)); }; const setCrop = (crop: number[] | null, aspect?: number) => { void write({ op: "vertical", clip: clip.id, crop, ...(crop && aspect ? { aspect: Math.round(aspect * 10000) / 10000 } : {}) }, crop ? "Saved the short's framing" : "The short is framed from the centre"); }; // Re-propose: the clip finder's proposal pass as a job (`umtool clips // propose`, /api/report/clips); clips a person edited are never touched. const [proposing, setProposing] = useState<{ id: string; state: string; error: string | null } | null>(null); const repropose = async () => { await flush(); setError(null); const r = await fetch("/api/report/clips", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, mode: "propose" }) }); const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string; error: string | null }; error?: string }; if (!r.ok || !j.job) setError(j.error ?? `HTTP ${r.status}`); else setProposing({ id: j.job.id, state: j.job.state, error: j.job.error }); }; useEffect(() => { if (!proposing || proposing.state !== "running") return; const t = setInterval(async () => { const r = await fetch(`/api/report/clips?job=${proposing.id}`, { cache: "no-store" }).catch(() => null); if (!r?.ok) return; const j = (await r.json()) as { id: string; state: string; error: string | null }; setProposing({ id: j.id, state: j.state, error: j.error }); if (j.state !== "running") { await reload().catch(() => {}); setRolesChanged(false); setStatus(j.state === "done" ? "Re-proposed: the assistant's untouched clips follow the new roles" : `Re-propose ${j.state}${j.error ? `: ${j.error}` : ""}`); } }, 1500); return () => clearInterval(t); }, [proposing, reload]); // An agent reply's proposal, applied ON THE OPERATOR'S CLICK through the // writer every other edit here uses (release 36 lane D). const canApply = (p: ReplyProposal): string | null => { // The video assistant's proposals (release 38) are applied in its Ask box, not here. if (p.kind === "assist") return "apply it in the assistant's box"; const at = clips.findIndex((c) => c.id === p.clip); if (at < 0) return `${p.clip} is no longer in the cut`; if (p.kind === "merge" && clips[at + 1]?.id !== p.with) return `${p.with} is no longer the next clip`; return null; }; const applyProposal = async (p: ReplyProposal): Promise => { if (p.kind === "assist") return false; await flush(); const j = p.kind === "trim" ? await write({ op: "trim", clip: p.clip, cutStart: p.from, cutEnd: p.to }, `Applied: ${proposalWords(p)}`) : p.kind === "merge" ? await write({ op: "merge", clip: p.clip }, `Applied: ${proposalWords(p)}`) : await write({ op: "ruling", clip: p.clip, verdict: "cut" }, `Applied: ${proposalWords(p)}`); return !!j; }; const rx = view.reactions; const rolesStale = rolesChanged || (!!rx?.rolesChangedAt && (!rx.proposedAt || rx.rolesChangedAt > rx.proposedAt)); const snap = () => { if (!points.length) { setError("nothing to snap to here: no words, cues or turns in this span"); return; } const s = snapCut(cut, points); setEdges(s, { now: true }); }; const nudge = (edge: "in" | "out", d: number) => setEdges(edge === "in" ? { cutStart: cut.cutStart + d, cutEnd: cut.cutEnd } : { cutStart: cut.cutStart, cutEnd: cut.cutEnd + d }); const setAtPlayhead = (edge: "in" | "out") => { if (playhead === null) return; nudge(edge, playhead - (edge === "in" ? cut.cutStart : cut.cutEnd)); }; const seek = (t: number) => { setPlayhead(t); player.current?.seek(t); }; // The video knobs: the 3 s around the playhead, heard. (The marks' keys are the Marks box's.) const listen = () => { if (playhead === null) return; player.current?.listen(playhead); }; // ---- keys ----------------------------------------------------------------- const keyRef = useRef<(e: KeyboardEvent) => void>(() => {}); keyRef.current = (e: KeyboardEvent) => { if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; const t = e.target as HTMLElement | null; if (t?.closest?.(TYPING) || t?.closest?.("dialog[open]")) return; // Shift+S and Shift+M are the Marks box's (a mark's moment at the // playhead, a mark added there); S and M alone split and merge. if (e.shiftKey && (e.key.toLowerCase() === "s" || e.key.toLowerCase() === "m")) return; const k = e.key.length === 1 ? e.key.toLowerCase() : e.key; const act: Record void> = { " ": () => player.current?.toggle(), j: () => seek(Math.max(0, (playhead ?? cut.cutStart) - 2)), l: () => seek((playhead ?? cut.cutStart) + 2), i: () => setAtPlayhead("in"), o: () => setAtPlayhead("out"), s: splitHere, m: mergeNext, k: () => rule("keep"), x: () => rule("cut"), ArrowLeft: () => index > 0 && choose(clips[index - 1].id), ArrowRight: () => index + 1 < clips.length && choose(clips[index + 1].id), }; const f = act[k]; if (!f) return; e.preventDefault(); f(); }; useEffect(() => { const on = (e: KeyboardEvent) => keyRef.current(e); document.addEventListener("keydown", on); return () => document.removeEventListener("keydown", on); }, []); // ---- what plays ----------------------------------------------------------- // Named by the clip's EXTENT, not its cut: a trim inside the extent must // not send the player looking again (and reload the picture) on every save. const targets = useMemo(() => { if (!clip.channel) return []; const base = { channel: clip.channel, video: clip.video, project, clip: clip.id }; const far = REACH_DEFAULT; const spans: [number, number][] = [ [Math.max(0, Math.floor(clip.start - far)), Math.ceil(duration ? Math.min(duration, clip.end + far) : clip.end + far)], [clip.start, clip.end], ]; return spans.filter(([a, b], i) => b > a && spans.findIndex(([x, y]) => x === a && y === b) === i).map(([from, to]) => ({ ...base, from, to })); }, [clip.channel, clip.video, clip.id, clip.start, clip.end, project, duration]); const assist = clip.assist; const prov = provenanceWords(assist); const canRestore = !!assist?.original && (assist.original.cutStart ?? assist.original.start) !== undefined; const edits = assist?.edits ?? []; // What the strip shades as muted: the build's rule on the cut as drawn (the // build snaps it first). The first clip has nothing before it, so no head. const join = view.room?.join ?? 0; const roomEdges = clip.roomEdges ?? null; const shade = roomShade({ cutStart: cut.cutStart, cutEnd: cut.cutEnd, room: roomEdges ? { tail: roomEdges.tail, head: roomEdges.head && index > 0, minGap: view.room?.minGap ?? ROOM.minGap, maxS: view.room?.maxS ?? ROOM.maxS } : null, D: join, words: hoodHere?.words ?? null, cues: hoodHere?.cues ?? null, }); const quoteNow = hoodHere ? quoteBetween({ words: hoodHere.words, cues: hoodHere.cues }, cut.cutStart, cut.cutEnd) : null; const pickRole = speakerPick !== null ? roleOf(speakers, speakerPick) : null; return (
{view.live && (

{view.live.status === "live" ? `Live: the stream is transcribed to ${edgeClock(view.live.transcribedTo)}, mined to ${edgeClock(view.live.minedTo)} (${view.live.passes} pass${view.live.passes === 1 ? "" : "es"}) — the words are provisional; more windows come as it records.` : "Was live: the project reads the final transcript now; its windows stayed where they were."}

{view.live.flags.map((f) => (

{f.why}

))}
)} {/* ---- the clip ---------------------------------------------------- */}

{clip.id}

{edgeClock(cut.cutStart)} – {edgeClock(cut.cutEnd)} · {(cut.cutEnd - cut.cutStart).toFixed(1)} s {draft && unsaved} {clip.blur && ( {view.blur?.rendered === false ? "blur off in this cut" : "blurred in the render"} )} {clip.ruling && ( {clip.ruling === "keep" ? "kept" : "cut"} )} {index + 1} of {clips.length}
{prov && (

{prov}

)} {(quoteNow ?? clip.quote) && (

{quoteNow || clip.quote}

)}
{/* ---- the list, the proposals, the speakers, the take --------------- */}
); } // --------------------------------------------------------------------------- // The player: what /api/cited/play finds for the neighbourhood, else the // clip's extent, else its cut; loops the cut. // --------------------------------------------------------------------------- type PlayerHandle = { toggle: () => void; seek: (t: number) => void; listen: (t: number) => void; /** The media element and the source second it is at: the live preview draws and clocks from them. */ media: () => HTMLMediaElement | null; sourceTime: () => number | null; }; /** The short's framing on the player: the clip's crop (null = the centre) and its writer. */ type Frame = { crop: number[] | null; onChange: (crop: number[] | null, aspect?: number) => void; busy: boolean }; type Target = { channel: string; video: string; from: number; to: number; project: string; clip: string }; const Player = forwardRef void; onPlaying: (p: boolean) => void; frame?: Frame | null; hidden?: CensorRegion[]; at?: number | null }>(function Player({ clipId, targets, cut, onTime, onPlaying, frame = null, hidden = [], at = null }, ref) { const [found, setFound] = useState<{ play: CitedPlay; from: number } | null | undefined>(undefined); const [dims, setDims] = useState<{ w: number; h: number } | null>(null); const media = useRef(null); // The seek to the cut on load is the player's own, not a person's: it must // not move the playhead somebody just set by clicking a word. const ownSeek = useRef(false); const listenTimer = useRef | null>(null); const cutRef = useRef(cut); cutRef.current = cut; const key = targets.map((t) => `${t.clip}|${t.from}|${t.to}`).join(","); // Bumped when a fetch from the "nothing on disk" state finishes: look again. const [attempt, setAttempt] = useState(0); useEffect(() => { let live = true; // The same file at the same clock keeps playing: only a different answer // replaces the media element. const settle = (next: { play: CitedPlay; from: number } | null) => setFound((was) => (was && next && was.play.url === next.play.url && was.play.offset - was.from === next.play.offset - next.from ? was : next)); (async () => { for (const t of targets) { const q = new URLSearchParams({ channel: t.channel, video: t.video, from: String(t.from), to: String(t.to), project: t.project, clip: t.clip }); const r = await fetch(`/api/cited/play?${q}`, { cache: "no-store" }).catch(() => null); const j = r?.ok ? ((await r.json()) as { play: CitedPlay | null }) : null; if (j?.play) { if (live) settle({ play: j.play, from: t.from }); return; } } if (live) settle(null); })(); return () => { live = false; }; // `targets` is named by its key. // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, attempt]); // COMING BACK TO THE PAGE (lane/clip-fixes; operator, 6 Nov: "I just had to // refresh"): the back button restores this page from the browser's cache // (pageshow, persisted) or a hidden tab comes back, and what is on disk may // have changed meanwhile (a window fetched on the bench). Look again -- the // same file at the same clock keeps playing (settle), so it costs a request. useEffect(() => { const again = () => { const m = media.current; if (m && !m.paused) return; setAttempt((a) => a + 1); }; const onShow = (e: PageTransitionEvent) => { if (e.persisted) again(); }; const onVis = () => { if (document.visibilityState === "visible") again(); }; window.addEventListener("pageshow", onShow); document.addEventListener("visibilitychange", onVis); return () => { window.removeEventListener("pageshow", onShow); document.removeEventListener("visibilitychange", onVis); }; }, []); // Another clip on the same file: go to its cut, paused. useEffect(() => { const m = media.current; if (!m || m.readyState < 1 || !found) return; m.pause(); ownSeek.current = true; m.currentTime = Math.max(0, cutRef.current.cutStart - found.from + found.play.offset); // Only a change of clip moves the picture. // eslint-disable-next-line react-hooks/exhaustive-deps }, [clipId]); const fileT = (t: number) => (found ? Math.max(0, t - found.from + found.play.offset) : 0); const sourceT = (ft: number) => (found ? ft - found.play.offset + found.from : 0); useImperativeHandle(ref, () => ({ media: () => media.current, sourceTime: () => (found && media.current ? sourceT(media.current.currentTime) : null), toggle: () => { const m = media.current; if (!m) return; if (!m.paused) return m.pause(); const t = sourceT(m.currentTime); if (t < cutRef.current.cutStart - 0.05 || t >= cutRef.current.cutEnd - 0.05) m.currentTime = fileT(cutRef.current.cutStart); void m.play().catch(() => {}); }, seek: (t: number) => { const m = media.current; if (!m) return; ownSeek.current = true; m.currentTime = fileT(t); }, // The 3 s around a second, then stop where it started (the Audio box's "listen"). listen: (t: number) => { const m = media.current; if (!m) return; if (listenTimer.current) clearTimeout(listenTimer.current); ownSeek.current = true; m.currentTime = fileT(Math.max(0, t - 1.5)); void m.play().catch(() => {}); listenTimer.current = setTimeout(() => { m.pause(); ownSeek.current = true; m.currentTime = fileT(t); }, 3000); }, })); if (found === undefined) return
looking for the clip…
; if (found === null) return (
Nothing on disk plays this clip. {targets[0] ? ( setAttempt((n) => n + 1)} /> ) : ( Fetch its window from the Cut tab (Fetch windows), then come back. )}
); const props = { ref: (el: HTMLMediaElement | null) => { media.current = el; }, src: found.play.url, preload: "auto", "data-player": "", tabIndex: -1, controls: true, onLoadedMetadata: (e: React.SyntheticEvent) => { ownSeek.current = true; e.currentTarget.currentTime = fileT(cutRef.current.cutStart); const v = e.currentTarget as HTMLVideoElement; if (v.videoWidth > 0 && v.videoHeight > 0) setDims({ w: v.videoWidth, h: v.videoHeight }); }, onSeeked: (e: React.SyntheticEvent) => { if (ownSeek.current) ownSeek.current = false; else onTime(sourceT(e.currentTarget.currentTime)); }, onTimeUpdate: (e: React.SyntheticEvent) => { if (e.currentTarget.paused) return; const t = sourceT(e.currentTarget.currentTime); onTime(t); // Loop the cut while it plays inside it. if (!e.currentTarget.paused && t >= cutRef.current.cutEnd && t < cutRef.current.cutEnd + 0.6) e.currentTarget.currentTime = fileT(cutRef.current.cutStart); }, onPlay: () => onPlaying(true), onPause: () => onPlaying(false), onFocus: (e: React.FocusEvent) => e.currentTarget.blur(), }; return (
{found.play.audio ? (
); }); // --------------------------------------------------------------------------- // The strip: [from, to] across the width. Turns by role, laughs, word ticks, // the other clips, the cut with two handles, the playhead, a selection. // --------------------------------------------------------------------------- function Strip({ from, to, cut, hood, room = null, speakers, others, playhead, selection, speakerPick, onSeek, onEdge, onSelect, onTurn, onOther, }: { from: number; to: number; cut: Cut; hood: Neighbourhood | null; /** Room at the edges (release 36 lane E): the muted head and tail to shade. */ room?: { head: number[] | null; tail: number[] | null } | null; speakers: Speaker[]; others: EditorClip[]; playhead: number | null; selection: Cut | null; speakerPick: number | null; onSeek: (t: number) => void; onEdge: (edge: "in" | "out", t: number, done: boolean) => void; onSelect: (s: Cut | null) => void; onTurn: (t: Turn) => void; onOther: (id: string) => void; }) { const box = useRef(null); const span = Math.max(0.001, to - from); const pct = (t: number) => `${(Math.min(Math.max(t, from), to) - from) / span * 100}%`; const width = (a: number, b: number) => `${Math.max(0, Math.min(b, to) - Math.max(a, from)) / span * 100}%`; const tAt = (clientX: number) => { const r = box.current!.getBoundingClientRect(); return r2(from + ((clientX - r.left) / Math.max(1, r.width)) * span); }; const drag = useRef<{ kind: "in" | "out" | "select"; x0: number; t0: number } | null>(null); const down = (kind: "in" | "out" | "select") => (e: React.PointerEvent) => { if (e.button !== 0) return; e.stopPropagation(); (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); drag.current = { kind, x0: e.clientX, t0: tAt(e.clientX) }; }; const move = (e: React.PointerEvent) => { const d = drag.current; if (!d) return; const t = tAt(e.clientX); if (d.kind === "select") { if (Math.abs(e.clientX - d.x0) > 4) onSelect({ cutStart: Math.min(d.t0, t), cutEnd: Math.max(d.t0, t) }); } else onEdge(d.kind, t, false); }; const up = (e: React.PointerEvent) => { const d = drag.current; drag.current = null; if (!d) return; const t = tAt(e.clientX); if (d.kind === "select") { if (Math.abs(e.clientX - d.x0) <= 4) { onSelect(null); onSeek(t); } else if (Math.abs(t - d.t0) < 0.5) onSelect(null); } else onEdge(d.kind, t, true); }; const turns = hood?.turns ?? []; const role = (sp: number) => roleOf(speakers, sp); return (
{/* turns, top lane */} {turns.map((t, i) => { const r = role(t.speaker); return ( ); })} {/* the selection to add */} {selection && } {/* room at the edges: muted picture either side of the cut */} {(["head", "tail"] as const).map((edge) => { const sp = room?.[edge]; if (!sp) return null; return ( ); })} {/* the cut */} {(["in", "out"] as const).map((edge) => ( ))} {playhead !== null && playhead >= from && playhead <= to && }
); } /** The words of the neighbourhood as text: the cut's lit, the one playing marked; a click seeks there (bench/WordStrip.tsx). */ const Words = WordStrip; function EdgeControl({ edge, value, onNudge, onSet, onPlayhead }: { edge: "in" | "out"; value: number; onNudge: (d: number) => void; onSet: (v: number) => void; onPlayhead: (() => void) | null }) { const [text, setText] = useState(String(value)); useEffect(() => setText(String(value)), [value]); const commit = () => { const v = Number(text); if (Number.isFinite(v) && v !== value) onSet(v); else setText(String(value)); }; return (
setText(e.target.value)} onBlur={commit} onKeyDown={(e) => { if (e.key === "Enter") { commit(); (e.target as HTMLInputElement).blur(); } if (e.key === "Escape") { setText(String(value)); (e.target as HTMLInputElement).blur(); } }} className="num w-[6.5em] rounded border border-seam-2 bg-ground px-1.5 py-0.5 font-mono text-[12px] text-text outline-none focus:border-signal" /> {NUDGES.map((d) => ( ))}
); } /** The notes on one clip: its thread (an agent's replies too), resolve / reopen, a box for another. */ function ClipNotes({ project, clipId, assistant, canApply, onApply, }: { project: string; clipId: string; /** Release 36 lane D: Ask the assistant on a comment, and Apply its proposal. */ assistant?: ClipSuggest; canApply?: (p: ReplyProposal) => string | null; onApply?: (p: ReplyProposal) => Promise; }) { const notes = useSharedNotes({ project }); const reloadNotes = notes.reload; // An Ask's reply lands in notes.json from the editor's job: read it again when a job ends. useEffect(() => { if (assistant?.ended) void reloadNotes(); }, [assistant?.ended, reloadNotes]); const askJob = assistant?.job && assistant.job.mode === "ask" ? assistant.job : null; const askBlocked = assistant?.view?.route?.why ?? null; const [text, setText] = useState(""); const mine = notesOn(notes.notes, { kind: "entry", entry: clipId }).filter((n) => n.anchor.kind !== "moment"); const open = mine.filter((n) => n.status === "open").length; const add = async () => { if (!text.trim()) return; const n = await notes.write({ op: "add", text, anchor: { kind: "entry", entry: clipId } }); if (n) setText(""); }; return (

Comments{mine.length ? ` — ${open} open of ${mine.length}` : ""}

{mine.map((n) => ( edit · {n.anchor.field} : null} actions={ assistant?.view?.hasReactions && n.status === "open" && n.anchor.kind === "entry" ? ( ) : null } afterReply={ canApply && onApply ? (r, i) => ( void onApply(p).then((ok) => { if (ok) void notes.write({ op: "reply", id: n.id, text: `Applied: ${proposalWords(p)}` }); }) } /> ) : undefined } /> ))}