commit 570aa862cf8313d990a356b23ef0c30b477bae87 parent d8aaeb65719332ff5e25328e51ce006086de66fd Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Fri, 23 Oct 2026 22:17:57 -0400 umtool Play the cut: the screening room -- reel strip, Now on the reader, dailies notes with kinds, JKL keys The Play view to the design brief: a head (title, take switcher, running time), the player, the REEL STRIP (a cell per entry as wide as it plays, tinted by its recording's date, hatched without media, section seams with their first date, the counter's staircase in meter with its total at the end and at the playhead, notes as signal pins, the playhead, a ruler; click or drag to scrub, a cell's Enter jumps), NOW on the reader (the clip's words, the spoken line lit, what comes next), and the notes column in reel order (Note at mm:ss.s, kind chips stored as the cut anchor's `ask`, Pause while I write, Open/All/Resolved, Send N open notes to the assistant). Keys: Space, J K L, arrows, N P, [ ], M, Esc, ?. The two <video>s now sit full size under the opaque frame, so a paused clip's frame is decoded and drawn; the canvas redraws when the frame is replaced. `umtool notes` and the assistant's request say what a note asks for. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
18 files changed, 1292 insertions(+), 344 deletions(-)
diff --git a/common/lib/report/draft/tasks/videoAssist.test.ts b/common/lib/report/draft/tasks/videoAssist.test.ts @@ -119,6 +119,7 @@ test("a note taken in the Play view: its text with where it was taken is the req const request = await noteRequestOf(dir, ASSIST_NOTE); assert.equal(request, "this drags — start later (noted while playing take short-19 at 1:12.4, in clip r002 at source 94.8 s)"); assert.equal(cutContextOf({ t: 3 }), "(noted while playing the cut at 0:03.0)"); + assert.equal(cutContextOf({ t: 3, entry: "c01", ask: "trim" }), "(noted while playing the cut at 0:03.0, in clip c01; asks for a trim)"); let prompt = ""; ol.push((body: { messages: { role: string; content: string }[] }) => { prompt = userOfOllama(body); diff --git a/common/lib/report/draft/tasks/videoAssist.ts b/common/lib/report/draft/tasks/videoAssist.ts @@ -90,13 +90,14 @@ const cutClock = (t: number) => { * 1:12.4, in clip c04 at source 194.2 s)". The clip names what "this" is; a * take's patch is not what the ops edit (they edit the project's cut). */ -export function cutContextOf(a: { t?: unknown; entry?: unknown; sourceT?: unknown; take?: unknown }): string { +export function cutContextOf(a: { t?: unknown; entry?: unknown; sourceT?: unknown; take?: unknown; ask?: unknown }): string { const where = [`at ${cutClock(Number(a.t))}`]; if (typeof a.entry === "string" && a.entry) { where.push(`in clip ${a.entry}${typeof a.sourceT === "number" && Number.isFinite(a.sourceT) ? ` at source ${a.sourceT.toFixed(1)} s` : ""}`); } const take = typeof a.take === "string" && a.take ? `take ${a.take}` : "the cut"; - return `(noted while playing ${take} ${where.join(", ")})`; + const ask = typeof a.ask === "string" && /^[a-z]{2,8}$/.test(a.ask) && a.ask !== "other" ? `; asks for a ${a.ask}` : ""; + return `(noted while playing ${take} ${where.join(", ")}${ask})`; } /** @@ -113,7 +114,7 @@ export async function noteRequestOf(dir: string, noteId: string): Promise<string } const notes = (doc as { notes?: unknown[] })?.notes; const n = Array.isArray(notes) - ? (notes.find((x) => (x as { id?: unknown })?.id === noteId) as { text?: unknown; status?: unknown; anchor?: { kind?: unknown; t?: unknown; entry?: unknown; sourceT?: unknown; take?: unknown } } | undefined) + ? (notes.find((x) => (x as { id?: unknown })?.id === noteId) as { text?: unknown; status?: unknown; anchor?: { kind?: unknown; t?: unknown; entry?: unknown; sourceT?: unknown; take?: unknown; ask?: unknown } } | undefined) : undefined; if (!n) throw new VideoAssistRefusal(`no note ${noteId} in ${dir}/notes.json`); const kind = n.anchor?.kind; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,7 +1,7 @@ # Changelog ## [Unreleased] -- **umtool plays a whole report video, or one take of it, in the browser without rendering it, and takes notes as it plays.** The Cut tab's **Play the cut** (and **Play** beside each take on the takes page) opens `/projects/<project>/play`: every clip plays in order from its fetched window, with the on-screen panel, the tally, the stamps, the markers and the finale drawn over it as the live preview draws them, on one clock across the whole cut, the next clip loaded behind the one playing. A take plays the project's video as it is now with the take's changes, including a take with its own clip list and one a recipe names that was never rendered; **Blurred clips: uncensored** on a take plays its clips as recorded. Space plays and pauses, N and P move between clips, ← and → move 5 seconds, a clip list jumps, and the speed keeps the voice's pitch. A line under the picture lists what it does not do: each crossfade is a hard cut at its middle, cards and teasers are placeholders with their heading, edges are not snapped to silence, and the sound is the recording's. A clip with nothing fetched is a named placeholder and the video plays on. M (or **Note at playhead**) pauses and saves a note at that second of the cut, naming the clip on screen, its second in the recording and the take; the notes list in order, a click plays from there, `umtool notes <project>` prints each with where it was taken, and **Send to the assistant** on a note (or **Send all open notes**) asks the video assistant, whose reply lands on the note and whose edits wait for **Apply all**. With no assistant configured the button says why. Needs a restart of umtool. +- **umtool plays a whole report video, or one take of it, in the browser without rendering it, and takes timecoded notes as it plays.** The Cut tab's **Play the cut** (and **Play** beside each take on the takes page) opens `/projects/<project>/play`: every clip plays in order from its fetched window, with the on-screen panel, the tally, the stamps, the markers and the finale drawn over it as the live preview draws them, on one clock across the whole cut, the next clip loaded behind the one playing. A take plays the project's video as it is now with the take's changes, including a take with its own clip list and one a recipe names that was never rendered; **Blurred clips: uncensored** on a take plays its clips as recorded. Under the picture, the **reel strip** shows the whole cut at once: a cell per clip or card as wide as it plays, shaded by the recording's date, hatched when its media is not fetched, the sections' boundaries with their first date, the counter (the tally) drawn as a staircase with its total at the end and at the playhead, and each note as a pin; click or drag on it to move through the cut. Under the strip, **Now** shows what the clip on screen says with the spoken line lit, and which clip comes next. Space plays and pauses, J K L go back, pause and play (L again is faster, at the voice's own pitch), ← and → move 5 seconds, N and P move between clips, [ and ] between notes, and ? lists the keys. A line under the picture lists what it does not do: each crossfade is a hard cut at its middle, cards and teasers are placeholders with their heading, edges are not snapped to silence, and the sound is the recording's. A clip with nothing fetched says "No media for this clip — fetch it" and the video plays on. M (or **Note at 09:44**) saves a note at that second of the cut, naming the clip on screen, its second in the recording, the take, and what it asks for (Trim, Cut, Move, Fact, Look or Other); playback pauses while you write and goes on when it is saved (**Pause while I write**). The notes list in cut order (open, all or resolved), a timecode plays from there, `umtool notes <project>` prints each with where it was taken and what it asks for, and **Send to the assistant** on a note (or **Send N open notes to the assistant**) asks the video assistant, whose reply lands on the note and whose edits wait for **Apply all**. With no assistant configured the button says why. Needs a restart of umtool. - **umtool's clip walk goes through the recordings in date order.** `p`/`n` and the Cut tab's walk used to follow the cut, which can open on a finale and end years earlier. The walk now goes by each clip's date (its on-screen date, else the recording's upload date), with a recording's clips together in the order they come in it, so what is left out between two clips, or split off into a clip of its own, comes up next. The cut's own order is unchanged. - **A clip from a stream captured live can be trimmed again in umtool's clip editor.** Such a stream's record has no length, which umtool passed on as zero, so every drag of a clip's edge snapped back to the left with "that is the edge of what is cached". An unknown length is now treated as unknown. - **umtool's clip editor opens a clip from a whole saved recording as a short excerpt.** When the only file holding a clip was the whole recording (hours long), the editor used all of it as its view: a waveform of the whole stream with the clip a sliver in it, and a video seeking hours into a large file. It now cuts the clip and 45 seconds either side from the recording once, on the umtool machine, and works on that; the cut starts when the clip is opened and is kept for the next time. The rendered video still cuts from the whole recording. diff --git a/umtool/components/projects/PlayCutPage.tsx b/umtool/components/projects/PlayCutPage.tsx @@ -16,13 +16,6 @@ import PlayCut, { type PlayViewData } from "./review/PlayCut"; // notes`), or the video assistant's to answer. lib/report/playView.mjs reads // what it plays; nothing here fetches, cuts or renders. -const KEYS = [ - { keys: ["Space"], label: "play" }, - { keys: ["N", "P"], label: "next / prev clip" }, - { keys: ["←", "→"], label: "∓5 s" }, - { keys: ["M"], label: "note" }, -]; - export default async function PlayCutPage({ project, take, note }: { project: ProjectRef; take?: string; note?: string }) { const [view, back] = await Promise.all([playView(project, { take: take || null }), pieceHrefOfProject(project.id, { tab: "cut" })]); const top = ( @@ -31,7 +24,6 @@ export default async function PlayCutPage({ project, take, note }: { project: Pr back={{ href: back, label: project.id }} kind="Play the cut" here={"error" in view || !view.take ? "the cut" : `take ${view.take.id}`} - keys={KEYS} /> ); if ("error" in view) { diff --git a/umtool/components/projects/report/AssistBox.tsx b/umtool/components/projects/report/AssistBox.tsx @@ -282,12 +282,15 @@ export function AssistReplyApply({ busy, apply, onApplied, + variant = "go", }: { reply: NoteReply; proposals: Proposals | null; busy: boolean; apply: (ids: string[] | null, at?: string) => Promise<boolean>; onApplied: () => void; + /** "outline" where the page's one primary action is another (the Play view's Save note). */ + variant?: "go" | "outline"; }) { const pr = r.proposal; if (!pr || pr.kind !== "assist" || r.author !== "agent") return null; @@ -311,7 +314,7 @@ export function AssistReplyApply({ if (ok) onApplied(); }) } - className={buttonVariants({ variant: "go", size: "sm" })} + className={buttonVariants({ variant, size: "sm" })} > Apply all </button> diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -3,26 +3,29 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { useSharedNotes } from "@/components/notes/NotesProvider"; -import { NoteComposer, NoteThread } from "@/components/notes/NoteThread"; -import type { Anchor, Note } from "@/lib/annotations/types"; +import { NoteThread } from "@/components/notes/NoteThread"; +import type { Anchor, CutAsk, Note } from "@/lib/annotations/types"; import { playHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; import { footageAt } from "@/lib/report/footage-move.mjs"; import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs"; -import { clockText, cutAtSource, cutNotesRequest, itemIndexAt, playPlan, shownSeconds, sourceAt, startOf } from "@/lib/report/playCut.mjs"; +import { + counterSteps, cutAtSource, cutNotesRequest, itemIndexAt, playPlan, runningTime, seamsOf, sourceAt, startOf, +} from "@/lib/report/playCut.mjs"; import { tallyVerdicts } from "umtool-report-to-video/factcheck"; import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; -import { AssistReplyApply, ProposalList, jobLine, routeLine, useAssist } from "../report/AssistBox"; +import { AssistReplyApply, ProposalList, routeLine, jobLine, useAssist } from "../report/AssistBox"; import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection"; import { drawFootage, type FootageBlur } from "./footageCanvas"; +import ReelStrip, { type StripCounter } from "./ReelStrip"; // --------------------------------------------------------------------------- -// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): the whole cut -- or a take -- played -// continuously in this browser in its final look, with no render; and the -// notes taken as it plays. +// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The +// whole cut -- or a take -- played continuously in this browser in its final +// look, with no render, and timecoded notes left as it plays that become the +// next cut. // // THE CLOCK is one cut clock across every entry (lib/report/playCut.mjs): // the estimate's segments (the live preview's schedule when the cut has a @@ -44,13 +47,21 @@ import { drawFootage, type FootageBlur } from "./footageCanvas"; // the footage box by footageCanvas.ts, blurred as the build blurs it unless // the cut (or the take) renders uncensored. // -// THE NOTES: `m` (or Note at playhead) pauses and takes a note anchored to -// the cut second, the clip on screen and its source second, and the take -// (anchor `cut`, the project's notes.json through the notes route). Listed -// in cut order; a click seeks there. `umtool notes <project>` prints them for -// an agent; Send to the assistant asks the video assistant (the editor's -// `video-assist`, routed by settings.generation), which replies on the note -// with an Apply -- nothing is written until the operator's click. +// THE PAGE (the design brief): the player; under it the REEL STRIP +// (ReelStrip.tsx, the signature: the cut as film, the counter's staircase, +// the notes' pins, the playhead, the ruler); under that NOW, on the reader +// surface: what the clip on screen says, the spoken line lit as it plays; +// beside them the NOTES in reel order. Desk tokens for the tool, the reader +// for what a source said, SIGNAL for the one interaction colour (the +// playhead, the pins, Save note), METER for the count. +// +// THE NOTES: M (or "Note at 09:44") takes a note anchored to the cut second, +// the clip on screen and its source second, the take, and what it asks for +// (Trim, Cut, Move, Fact, Look, Other: the anchor's `ask`) -- the project's +// notes.json through the notes route. `umtool notes <project>` prints them +// for an agent; "Send to the assistant" asks the video assistant (the +// editor's `video-assist`, routed by settings.generation), which replies on +// the note with an Apply -- nothing is written until the operator's click. // --------------------------------------------------------------------------- export type PlayEntry = { @@ -58,6 +69,10 @@ export type PlayEntry = { type: string; heading: string; date?: string | null; + dateKey?: number | null; + dateLabel?: string | null; + section?: unknown; + channel?: string | null; quote?: string | null; video?: string; start?: number; @@ -70,9 +85,12 @@ export type PlayEntry = { export type PlayViewData = { project: string; + title: string; take: { id: string; label: string; summary: string; made: boolean; from: string } | null; note: string | null; takes: { id: string; label: string; made: boolean }[]; + counter: { verdicts: { id: string; label: string }[]; stamps: { landed: number; verdict: string; count: number }[] }; + markers: { after: string; label: string }[]; leadIn: number; transition: number; blurRendered: boolean; @@ -87,15 +105,47 @@ type LiveDoc = DeckPreviewDoc & { schedule: DeckPreviewDoc["schedule"] & { finale?: { from: number; to: number } }; }; type Ui = { t: number; cur: number; playing: boolean; ended: boolean; waiting: boolean }; +type CutAnchor = Extract<Anchor, { kind: "cut" }>; /** The clip bench's speeds; the <video> keeps the voice's pitch by itself (`preservesPitch`). */ const RATES = [0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3] as const; +/** L, tapped while playing: the next of these. */ +const L_RATES = [1, 1.5, 2, 2.5, 3]; const SKIP_S = 5; +/** The player is as wide as leaves the strip and Now on screen under it (never under 480 px). */ +const PLAYER_MAX_W = "max(480px, min(1100px, calc((100dvh - 430px) * 16 / 9)))"; +const PAUSE_KEY = "umtool.play.pauseWhileWriting"; + +/** The dailies' kinds of note: what it asks for, and its key (with Alt, in the composer). */ +const ASKS: { id: CutAsk; label: string; key: string }[] = [ + { id: "trim", label: "Trim", key: "t" }, + { id: "cut", label: "Cut", key: "c" }, + { id: "move", label: "Move", key: "m" }, + { id: "fact", label: "Fact", key: "f" }, + { id: "look", label: "Look", key: "l" }, + { id: "other", label: "Other", key: "o" }, +]; + +const KEYS: { keys: string; what: string }[] = [ + { keys: "Space", what: "play / pause" }, + { keys: "J", what: "back 5 s (tap again: further)" }, + { keys: "K", what: "pause" }, + { keys: "L", what: "play (tap again: 1.5×, 2×, …)" }, + { keys: "← →", what: "5 s back / on" }, + { keys: "P N", what: "previous / next clip" }, + { keys: "[ ]", what: "previous / next note" }, + { keys: "M", what: "note at the playhead" }, + { keys: "Alt+T C M F L O", what: "the note's kind, while writing" }, + { keys: "Enter", what: "save the note (Shift+Enter: a new line)" }, + { keys: "Esc", what: "close the note, or this" }, + { keys: "?", what: "these keys" }, +]; const APPROXIMATE = - "approximate: each crossfade is a hard cut at its middle; cards, teasers and images are placeholders; the edges are not snapped to silence; the sound is the source's (no room, no Audio knobs); the clock is the estimate's"; + "Approximate: crossfades are hard cuts at their middle, cards and teasers are placeholders, edges are not snapped to silence, the sound is the recording's own, the clock is the estimate's." -const fmtLen = (s: number) => (s >= 60 ? clockText(s).replace(/\.\d$/, "") : `${s.toFixed(1)} s`); +/** `mm:ss.s` -- a note's or the playhead's timecode. */ +const timecode = (t: number) => `${runningTime(t)}.${Math.floor(((Math.max(0, t) % 1) + 1e-9) * 10)}`; export default function PlayCut({ view, initialNote }: { view: PlayViewData; initialNote: string | null }) { const router = useRouter(); @@ -305,7 +355,7 @@ export default function PlayCut({ view, initialNote }: { view: PlayViewData; ini ); // Every animation frame: the clock, the cut to the next entry, the picture. - const lastDraw = useRef({ key: "" }); + const lastDraw = useRef<{ key: string; el: HTMLCanvasElement | null }>({ key: "", el: null }); useEffect(() => { let raf = 0; const tick = (now: number) => { @@ -362,8 +412,9 @@ export default function PlayCut({ view, initialNote }: { view: PlayViewData; ini ? { strength: b.strength ?? BLUR_STRENGTH.default, caption: b.caption ?? BLUR_CAPTION_DEFAULT } : null; const key = `${cur.id}|${video ? video.currentTime : -1}|${bgRef.current}|${el.width}x${el.height}|${blurNow ? `${blurNow.strength}${blurNow.caption}` : ""}`; - if (key === lastDraw.current.key) return; - lastDraw.current.key = key; + // A new canvas (the composed frame replacing the plain one) is drawn even while nothing moves. + if (key === lastDraw.current.key && el === lastDraw.current.el) return; + lastDraw.current = { key, el }; el.dataset.playBlur = blurNow ? "on" : "off"; drawFootage(el, video, bgRef.current, blurNow); }; @@ -375,25 +426,68 @@ export default function PlayCut({ view, initialNote }: { view: PlayViewData; ini const next = useCallback(() => seekTo(startOf(planRef.current, eng.current.cur + 1)), [seekTo]); const prev = useCallback(() => seekTo(startOf(planRef.current, eng.current.cur - 1)), [seekTo]); const skip = useCallback((d: number) => seekTo(eng.current.t + d), [seekTo]); + const changeRate = useCallback((r: number) => setRate(r), []); + // J tapped again within a moment steps further back each time (there is no true reverse). + const jTap = useRef({ at: 0, step: SKIP_S }); + const back = useCallback(() => { + const now = performance.now(); + jTap.current.step = now - jTap.current.at < 800 ? Math.min(60, jTap.current.step * 2) : SKIP_S; + jTap.current.at = now; + skip(-jTap.current.step); + }, [skip]); + const lPlay = useCallback(() => { + if (!eng.current.playing) { + setPlaying(true); + return; + } + const up = L_RATES.find((r) => r > eng.current.rate + 1e-6); + if (up) changeRate(up); + }, [setPlaying, changeRate]); // ---- the notes ------------------------------------------------------------------- const notes = useSharedNotes({ project }); const mine = useMemo( - () => - notes.notes - .filter((n) => n.anchor.kind === "cut" && (n.anchor.take ?? null) === take) - .sort((a, b) => (a.anchor as { t: number }).t - (b.anchor as { t: number }).t), + () => notes.notes.filter((n) => n.anchor.kind === "cut" && (n.anchor.take ?? null) === take).sort((a, b) => (a.anchor as CutAnchor).t - (b.anchor as CutAnchor).t), [notes.notes, take], ); - const [drafting, setDrafting] = useState<Extract<Anchor, { kind: "cut" }> | null>(null); + const [drafting, setDrafting] = useState<CutAnchor | null>(null); + const [pauseWhileWriting, setPauseWhileWriting] = useState(true); + useEffect(() => { + try { + if (window.localStorage.getItem(PAUSE_KEY) === "off") setPauseWhileWriting(false); + } catch { + // No storage: on, the default. + } + }, []); + const resumeAfter = useRef(false); const noteHere = useCallback(() => { const e = eng.current; const item = planRef.current.items[e.cur]; if (!item) return; - setPlaying(false); + resumeAfter.current = false; + if (pauseWhileWriting && e.playing) { + resumeAfter.current = true; + setPlaying(false); + } const src = item.clip ? sourceAt(item, e.t) : null; setDrafting({ kind: "cut", t: Math.round(e.t * 100) / 100, entry: item.id, ...(src !== null ? { sourceT: src } : {}), ...(take ? { take } : {}) }); - }, [setPlaying, take]); + }, [pauseWhileWriting, setPlaying, take]); + const closeDraft = useCallback(() => { + setDrafting(null); + if (resumeAfter.current) { + resumeAfter.current = false; + setPlaying(true); + } + }, [setPlaying]); + const stepNote = useCallback( + (d: 1 | -1) => { + const t = eng.current.t; + const ts = mine.map((n) => (n.anchor as CutAnchor).t); + const to = d > 0 ? ts.find((x) => x > t + 0.05) : [...ts].reverse().find((x) => x < t - 0.05); + if (to !== undefined) seekTo(to); + }, + [mine, seekTo], + ); // `?note=<id>` (the Inbox's link): seek to it once the notes are read. const sought = useRef(false); @@ -402,20 +496,32 @@ export default function PlayCut({ view, initialNote }: { view: PlayViewData; ini const n = mine.find((x) => x.id === initialNote); if (!n) return; sought.current = true; - seekTo((n.anchor as { t: number }).t); + seekTo((n.anchor as CutAnchor).t); }, [initialNote, mine, seekTo]); // ---- the keys ---------------------------------------------------------------------- + const [help, setHelp] = useState(false); useEffect(() => { const onKey = (ev: KeyboardEvent) => { const tgt = ev.target as HTMLElement | null; + if (ev.key === "Escape") { + if (help) setHelp(false); + return; + } if (tgt && (tgt.closest("input, textarea, select, [contenteditable=true]") || ev.metaKey || ev.ctrlKey || ev.altKey)) return; - if (ev.key === " ") setPlaying(!eng.current.playing); - else if (ev.key === "n") next(); - else if (ev.key === "p") prev(); - else if (ev.key === "ArrowRight") skip(SKIP_S); - else if (ev.key === "ArrowLeft") skip(-SKIP_S); - else if (ev.key === "m") noteHere(); + const k = ev.key; + if (k === " ") setPlaying(!eng.current.playing); + else if (k === "j" || k === "J") back(); + else if (k === "k" || k === "K") setPlaying(false); + else if (k === "l" || k === "L") lPlay(); + else if (k === "n" || k === "N") next(); + else if (k === "p" || k === "P") prev(); + else if (k === "ArrowRight") skip(SKIP_S); + else if (k === "ArrowLeft") skip(-SKIP_S); + else if (k === "[") stepNote(-1); + else if (k === "]") stepNote(1); + else if (k === "m" || k === "M") noteHere(); + else if (k === "?") setHelp((h) => !h); else return; ev.preventDefault(); }; @@ -430,7 +536,7 @@ export default function PlayCut({ view, initialNote }: { view: PlayViewData; ini window.removeEventListener("keydown", onKey); window.removeEventListener("keyup", onUp); }; - }, [next, prev, skip, noteHere, setPlaying]); + }, [back, help, lPlay, next, prev, skip, stepNote, noteHere, setPlaying]); // ---- what is on screen ------------------------------------------------------------- const t = ui.t; @@ -449,25 +555,37 @@ export default function PlayCut({ view, initialNote }: { view: PlayViewData; ini const broken = !!item && !!failed[item.id]; const placeholder = item && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null; const pct = (n: number, of: number) => `${(n / of) * 100}%`; - const segTitle = (id: string) => schedule?.segments.find((s) => s.id === id)?.title || null; + + // The reel strip's counter: the composed schedule's stamps when there is one, else the estimate's. + const counters = useMemo<StripCounter[]>(() => { + const stamps = (schedule?.factcheck?.stamps as { landed: number; verdict: string; count?: number }[] | undefined) ?? view.counter.stamps; + const labels = new Map(view.counter.verdicts.map((v) => [v.id, v.label])); + const ids = [...new Set(stamps.map((s) => s.verdict))]; + return ids.map((id) => ({ id, label: doc?.verdictLabels?.[id] ?? labels.get(id) ?? id, steps: counterSteps(stamps, id) })); + }, [schedule, view.counter, doc?.verdictLabels]); + const seams = useMemo(() => seamsOf(view.entries, view.markers), [view.entries, view.markers]); + const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: (n.anchor as CutAnchor).t, text: n.text, open: n.status === "open" })), [mine]); + const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]); const placeholderCard = placeholder ? ( <div data-play-placeholder={placeholder.kind} data-play-missing={placeholder.kind === "missing" ? placeholder.item.id : undefined} - className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-1 p-6 text-center" + className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-1.5 p-6 text-center" style={{ background: placeholder.kind === "card" ? bg : "transparent" }} > {placeholder.kind === "card" ? ( <> - <span className="rounded bg-black/50 px-1.5 py-0.5 font-mono text-[11px] uppercase tracking-wide text-white/70">{placeholder.item.type}</span> - <span className="max-w-[80%] text-[clamp(14px,2.4vw,30px)] font-semibold text-white">{placeholder.entry?.heading ?? placeholder.item.id}</span> - <span className="text-[11px] text-white/60">not drawn here: the build renders it</span> + <span className="micro text-white/60">{placeholder.item.type}</span> + <span className="max-w-[80%] font-display text-[clamp(15px,2.6vw,32px)] font-semibold text-white">{placeholder.entry?.heading ?? placeholder.item.id}</span> + <span className="text-[11px] text-white/55">a placeholder: the build draws it</span> </> ) : ( - <span className="rounded bg-black/75 px-2 py-1 text-[12px] text-white"> - {placeholder.item.id}: {broken ? failed[placeholder.item.id] : "not fetched"} — {placeholder.entry?.video}@{placeholder.entry?.start}–{placeholder.entry?.end} - {", playing on as a placeholder"} + <span className="rounded-[3px] bg-black/75 px-2.5 py-1 text-[12.5px] text-white"> + {broken ? `${failed[placeholder.item.id]} — ${placeholder.item.id} plays on as a placeholder` : `No media for ${placeholder.item.id} — fetch it`} + <span className="mt-0.5 block font-mono text-[11px] text-white/60"> + {placeholder.entry?.video}@{placeholder.entry?.start}–{placeholder.entry?.end} + </span> </span> )} </div> @@ -476,6 +594,7 @@ export default function PlayCut({ view, initialNote }: { view: PlayViewData; ini const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => ( <canvas ref={canvas} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} /> ); + const iconBtn = cn(buttonVariants({ variant: "outline", size: "sm" }), "min-w-9 font-mono"); return ( <div @@ -484,208 +603,349 @@ export default function PlayCut({ view, initialNote }: { view: PlayViewData; ini data-play-t={String(Math.round(t * 100) / 100)} data-play-item={item?.id ?? ""} data-play-compose={composeState} - className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_380px]" + className="flex flex-col min-[900px]:min-h-0 min-[900px]:flex-1 min-[900px]:overflow-hidden" > - <main className="deck-main min-h-0 space-y-2 overflow-auto p-4"> - {/* The two players: never shown, drawn into the canvas. */} - <div className="pointer-events-none fixed left-0 top-0 h-px w-px overflow-hidden opacity-0" aria-hidden> - <video ref={vA} data-play-slot="0" preload="auto" playsInline onError={() => onMediaError(0)} /> - <video ref={vB} data-play-slot="1" preload="auto" playsInline onError={() => onMediaError(1)} /> - </div> + {/* ---- the head: the cut's title, what plays, the running time ---- */} + <header className="flex flex-wrap items-center gap-x-4 gap-y-1.5 border-b border-seam px-4 py-2"> + <h1 className="m-0 min-w-0 truncate font-display text-[17px] font-semibold tracking-[-0.01em] text-text">{view.title}</h1> + <nav aria-label="What plays" className="flex flex-wrap items-center rounded-[3px] border border-seam-2 p-0.5 text-[12px]" data-play-takes=""> + {[{ id: null as string | null, label: "The cut", made: true }, ...view.takes].map((tk) => { + const on = (tk.id ?? null) === take; + return ( + <Link + key={tk.id ?? "cut"} + href={playHref(project, { take: tk.id })} + aria-current={on ? "page" : undefined} + data-play-take-link={tk.id ?? ""} + title={tk.id ? `${tk.label}${tk.made ? "" : " (not rendered yet)"}` : "the project's cut"} + className={cn("rounded-[2px] px-2 py-0.5", on ? "bg-panel-2 font-medium text-text" : "text-muted-2 hover:text-text", !tk.made && "italic")} + > + {tk.id ?? "The cut"} + </Link> + ); + })} + </nav> + <span className="ml-auto font-mono text-[15px] tabular-nums text-text" data-play-clock=""> + {runningTime(t)} <span className="text-muted">/ {runningTime(plan.total)}</span> + </span> + <button type="button" onClick={() => setHelp(true)} className={iconBtn} aria-label="keys" title="keys (?)" data-play-help=""> + ? + </button> + </header> + {view.take && ( + <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2" data-play-take={view.take.id}> + take “{view.take.label}”: the project’s cut with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"} + {view.take.summary ? ` · ${view.take.summary}` : ""} + </p> + )} - <div className="w-full max-w-[960px]"> - {doc && g && box ? ( - <DeckFrame preview={doc} t={t} texts={{}} testid="play-deck"> - <div className="absolute inset-0" style={{ background: bg }} /> - {footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)} - {placeholderCard} - {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={t} testid="play-feed" />} - {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={t} />} - {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={t} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />} - {doc.finale && finaleNow && ( - <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-play-finale=""> - <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={t} ready="finale:ready" testid="play-finale" name="finale" /> - </div> - )} - </DeckFrame> - ) : ( - <div className="relative w-full overflow-hidden rounded border border-[var(--color-line)] bg-black" style={{ aspectRatio: "16 / 9" }} data-testid="play-plain"> - {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)} - {placeholderCard} + <div className="grid grid-cols-1 min-[900px]:min-h-0 min-[900px]:flex-1 min-[900px]:grid-cols-[minmax(0,1fr)_minmax(300px,380px)]"> + <main className="deck-main min-w-0 space-y-3 p-4 min-[900px]:min-h-0 min-[900px]:overflow-auto"> + {/* ---- the player ---- + The two <video>s sit full size UNDER the frame (which is opaque + and drawn from them): an element the browser can see on the + page loads and decodes a paused frame, where a hidden 1 px one + was left at its metadata. They stay put while the frame above + switches from plain to composed. */} + <div className="relative w-full" style={{ maxWidth: PLAYER_MAX_W }}> + <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden> + <video ref={vA} data-play-slot="0" preload="auto" playsInline onError={() => onMediaError(0)} className="absolute inset-0 h-full w-full" /> + <video ref={vB} data-play-slot="1" preload="auto" playsInline onError={() => onMediaError(1)} className="absolute inset-0 h-full w-full" /> </div> - )} - </div> + <div className="relative"> + {doc && g && box ? ( + <DeckFrame preview={doc} t={t} texts={{}} testid="play-deck"> + <div className="absolute inset-0" style={{ background: bg }} /> + {footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)} + {placeholderCard} + {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={t} testid="play-feed" />} + {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={t} />} + {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={t} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />} + {doc.finale && finaleNow && ( + <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-play-finale=""> + <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={t} ready="finale:ready" testid="play-finale" name="finale" /> + </div> + )} + </DeckFrame> + ) : ( + <div className="relative w-full overflow-hidden rounded border border-seam bg-black" style={{ aspectRatio: "16 / 9" }} data-testid="play-plain"> + {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)} + {placeholderCard} + </div> + )} + </div> + </div> - {/* ---- the transport ---- */} - <div className="flex flex-wrap items-center gap-2 text-[12px]" data-play-transport=""> - <button type="button" data-play-prev="" onClick={prev} className={buttonVariants({ variant: "quiet", size: "sm" })} title="previous entry (p)"> - ‹ prev - </button> - <button type="button" data-play-back="" onClick={() => skip(-SKIP_S)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="back 5 s (←)"> - −5 s - </button> - <button type="button" data-play-toggle="" onClick={() => setPlaying(!ui.playing)} className={buttonVariants({ variant: "go", size: "sm" })} title="play / pause (space)"> - {ui.playing ? "Pause" : ui.ended ? "Play again" : "Play"} - </button> - <button type="button" data-play-fwd="" onClick={() => skip(SKIP_S)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="on 5 s (→)"> - +5 s - </button> - <button type="button" data-play-next="" onClick={next} className={buttonVariants({ variant: "quiet", size: "sm" })} title="next entry (n)"> - next › - </button> - <label className="inline-flex items-center gap-1 text-text-2"> - speed - <select data-play-rate="" value={rate} onChange={(e) => setRate(Number(e.target.value))} className="rounded border border-seam-2 bg-ground px-1 py-0.5 text-[12px] text-text"> - {RATES.map((r) => ( - <option key={r} value={r}> - {r}× - </option> - ))} - </select> - </label> - <span className="num font-mono text-[12px] text-text" data-play-clock=""> - {clockText(t)} / {clockText(plan.total)} - </span> - {item && ( - <span className="num font-mono text-[11.5px] text-muted" data-play-readout=""> - {ui.cur + 1} of {plan.items.length} · {item.id} - {segTitle(item.id) ? ` · ${segTitle(item.id)}` : ""} + {/* ---- the transport ---- */} + <div className="flex flex-wrap items-center gap-1.5 text-[12px]" data-play-transport=""> + <button type="button" data-play-prev="" onClick={prev} className={iconBtn} title="previous clip (P)" aria-label="previous clip"> + ‹ Prev + </button> + <button type="button" data-play-back="" onClick={() => skip(-SKIP_S)} className={iconBtn} title="back 5 s (←, J)"> + −5 + </button> + <button type="button" data-play-toggle="" onClick={() => setPlaying(!ui.playing)} className={cn(iconBtn, "min-w-20")} title="play / pause (Space)"> + {ui.playing ? "Pause" : ui.ended ? "Play again" : "Play"} + </button> + <button type="button" data-play-fwd="" onClick={() => skip(SKIP_S)} className={iconBtn} title="on 5 s (→)"> + +5 + </button> + <button type="button" data-play-next="" onClick={next} className={iconBtn} title="next clip (N)" aria-label="next clip"> + Next › + </button> + <label className="ml-1 inline-flex items-center gap-1 text-muted-2"> + <span className="sr-only">speed</span> + <select data-play-rate="" value={rate} onChange={(e) => changeRate(Number(e.target.value))} className="rounded-[3px] border border-seam-2 bg-ground px-1 py-[3px] font-mono text-[12px] text-text" title="speed (L while playing); the voice keeps its pitch"> + {RATES.map((r) => ( + <option key={r} value={r}> + {r}× + </option> + ))} + </select> + </label> + {item && ( + <span className="min-w-0 truncate font-mono text-[11.5px] text-muted" data-play-readout=""> + {ui.cur + 1}/{plan.items.length} · {item.id} + </span> + )} + {ui.waiting && <span className="text-[11.5px] text-muted" data-play-waiting="">loading…</span>} + <span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px] text-muted" data-play-hud=""> + {tally.length > 0 && <span className="sr-only" data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")} />} + {schedule?.factcheck && ( + <span data-play-stamp={stamp ? `${stamp.claim}:${stamp.phase}` : ""}>{stamp ? `stamp ${stamp.claim}` : ""}</span> + )} + {finaleNow && <span data-play-finale-up="">finale</span>} + {composeState === "composing" && <span>composing the chrome…</span>} + {composeState === "no-deck" && <span>no on-screen deck: the footage alone</span>} </span> + </div> + {composeState === "error" && ( + <p role="alert" className="m-0 text-[11.5px] text-reject-text" data-play-compose-error=""> + The chrome did not compose: {composeError}. The footage plays without it; Recompose after fixing the cut. + </p> )} - {ui.waiting && <span className="micro" data-play-waiting="">loading…</span>} - <button type="button" data-play-note-add="" onClick={noteHere} className={cn(buttonVariants({ size: "sm" }), "ml-auto")} title="pause and take a note here (m)"> - Note at playhead - </button> - </div> + {doc?.finale?.error && <p className="m-0 text-[11.5px] text-reject-text">The finale did not compose: {doc.finale.error}</p>} - <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-text-2" data-play-hud=""> - {tally.length > 0 && <span data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")}>tally {tally.map((r) => `${doc?.verdictLabels?.[r.verdict] ?? r.verdict} ${r.count}`).join(" · ")}</span>} - {schedule?.factcheck && <span data-play-stamp={stamp ? `${stamp.claim}:${stamp.phase}` : ""}>{stamp ? `stamp ${stamp.claim} (${stamp.phase})` : "no stamp on screen"}</span>} - {finaleNow && <span data-play-finale-up="">finale</span>} - {composeState === "composing" && <span className="micro">composing the chrome…</span>} - {composeState === "no-deck" && <span className="text-muted">no on-screen deck in this cut: the footage alone</span>} - {composeState === "error" && ( - <span role="alert" className="text-reject-text" data-play-compose-error=""> - the chrome did not compose: {composeError} + {/* ---- the reel strip ---- */} + <ReelStrip + items={plan.items} + total={plan.total} + entries={stripEntries} + t={t} + cur={ui.cur} + seams={seams} + counters={counters} + pins={pins} + failed={failed} + timecode={timecode} + onSeek={seekTo} + onSeekItem={(i) => seekTo(startOf(planRef.current, i))} + /> + + {/* ---- now ---- */} + <NowReader project={project} item={item} entry={entry ?? null} t={t} next={plan.items[ui.cur + 1] ?? null} nextEntry={plan.items[ui.cur + 1] ? (entryOf.get(plan.items[ui.cur + 1].id) ?? null) : null} broken={broken} /> + + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-[11px] text-muted" data-play-approximate=""> + <span> + {APPROXIMATE} + {!view.blurRendered ? " Blurred clips play unblurred (render.blur off)." : ""} + {view.note ? ` ${view.note}.` : ""} </span> - )} - {composeState !== "composing" && view.deckOn && ( - <button type="button" className="ink-link" onClick={() => void compose()} title="compose the pages again from the manifest"> - Recompose + {composeState !== "composing" && view.deckOn && ( + <button type="button" className="ink-link" onClick={() => void compose()} title="compose the pages again from the manifest"> + Recompose + </button> + )} + <button + type="button" + className="ink-link" + data-play-reload="" + title="read the cut again after an edit elsewhere" + onClick={() => { + router.refresh(); + if (view.deckOn) void compose(); + }} + > + Reload the cut </button> - )} - <button - type="button" - className="ink-link" - data-play-reload="" - title="read the cut again (after an edit elsewhere) and compose its pages again" - onClick={() => { + </div> + </main> + + {/* ---- the notes ---- */} + <aside className="flex min-h-0 flex-col border-t border-seam bg-panel min-[900px]:border-l min-[900px]:border-t-0" data-play-side=""> + <PlayNotes + project={project} + take={take} + notes={notes} + mine={mine} + drafting={drafting} + nowLabel={timecode(t)} + pauseWhileWriting={pauseWhileWriting} + onPauseWhileWriting={(on) => { + setPauseWhileWriting(on); + try { + window.localStorage.setItem(PAUSE_KEY, on ? "on" : "off"); + } catch { + // A preference, not state. + } + }} + onNote={noteHere} + onClose={closeDraft} + onSeek={(n) => seekTo((n.anchor as CutAnchor).t)} + onApplied={() => { router.refresh(); if (view.deckOn) void compose(); }} - > - Reload the cut - </button> - </div> - <p className="m-0 text-[11px] text-muted" data-play-approximate=""> - {APPROXIMATE} - {!view.blurRendered ? " · blurred clips play unblurred (render.blur off)" : ""} - {view.note ? ` · ${view.note}` : ""} - </p> - {doc?.finale?.error && <p className="m-0 text-[11px] text-reject-text">the finale did not compose: {doc.finale.error}</p>} - </main> - - {/* ---- the side: what plays, the takes, the notes ---- */} - <aside className="flex min-h-0 flex-col gap-3 overflow-auto border-t border-seam bg-panel p-3 lg:border-l lg:border-t-0" data-play-side=""> - <section data-play-takes=""> - <h2 className="micro m-0 mb-1">Playing</h2> - <div className="flex flex-wrap gap-1.5 text-[12px]"> - <Link href={playHref(project)} aria-current={take ? undefined : "page"} data-play-take-link="" className={take ? "ink-link" : "font-medium text-text"}> - the cut - </Link> - {view.takes.map((tk) => ( - <Link - key={tk.id} - href={playHref(project, { take: tk.id })} - aria-current={tk.id === take ? "page" : undefined} - data-play-take-link={tk.id} - className={tk.id === take ? "font-medium text-text" : "ink-link"} - title={tk.made ? tk.label : `${tk.label} (not rendered yet)`} - > - {tk.id} - {tk.made ? "" : "*"} - </Link> - ))} + /> + </aside> + </div> + + {help && ( + <div role="dialog" aria-modal="true" aria-label="Keys" className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4" onClick={() => setHelp(false)} data-play-keys=""> + <div className="w-full max-w-[420px] rounded-[3px] border border-seam-2 bg-panel p-4 text-[12.5px] text-text-2" onClick={(e) => e.stopPropagation()}> + <div className="mb-2 flex items-center"> + <h2 className="micro m-0">Keys</h2> + <button type="button" autoFocus onClick={() => setHelp(false)} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}> + Close + </button> + </div> + <dl className="m-0 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1"> + {KEYS.map((k) => ( + <div key={k.keys} className="contents"> + <dt className="font-mono text-text">{k.keys}</dt> + <dd className="m-0">{k.what}</dd> + </div> + ))} + </dl> </div> - {view.take && ( - <p className="m-0 mt-1 text-[11.5px] text-text-2" data-play-take={view.take.id}> - take “{view.take.label}”: the project’s manifest with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"} - </p> - )} - </section> - - <section> - <h2 className="micro m-0 mb-1"> - {plan.items.length} entries · {clockText(plan.total)} - </h2> - <ol className="m-0 list-none space-y-0.5 p-0" data-play-list=""> - {plan.items.map((it, i) => { - const e = entryOf.get(it.id); - const date = it.clip ? segTitle(it.id) || e?.date : null; - return ( - <li key={it.id}> - <button - type="button" - data-play-row={it.id} - aria-current={i === ui.cur ? "true" : undefined} - onClick={() => seekTo(it.from)} - className={cn("flex w-full items-baseline gap-2 rounded-[3px] px-1.5 py-1 text-left text-[12px]", i === ui.cur ? "bg-panel-2 text-text" : "text-text-2 hover:bg-panel-2")} - > - <span className="font-mono">{it.id}</span> - <span className="min-w-0 flex-1 truncate text-muted">{it.clip ? (date ?? "") : `${it.type} · ${e?.heading ?? ""}`}</span> - {it.clip && !e?.media && <span className={badgeVariants({ variant: "blocking", size: "sm" })} data-play-row-missing="">not fetched</span>} - {failed[it.id] && <span className={badgeVariants({ variant: "blocking", size: "sm" })}>no media</span>} - {e?.blur && <span className="text-[10.5px] text-muted">{view.blurRendered ? "blurred" : "unblurred"}</span>} - <span className="num font-mono text-[11px] text-muted">{fmtLen(shownSeconds(it))}</span> - </button> - </li> - ); - })} - </ol> - </section> - - <PlayNotes - project={project} - take={take} - notes={notes} - mine={mine} - drafting={drafting} - onCancel={() => setDrafting(null)} - onAdded={() => setDrafting(null)} - onSeek={(n) => seekTo((n.anchor as { t: number }).t)} - onApplied={() => { - router.refresh(); - if (view.deckOn) void compose(); - }} - /> - </aside> + </div> + )} </div> ); } // --------------------------------------------------------------------------- -// The notes taken while playing: the composer at the playhead, the list in -// cut order (a click seeks), each one sent to the assistant on a click. +// NOW: what the clip on screen says, on the reader (paper is the record), its +// spoken line lit as it plays; what comes next. A card is our words: the desk. // --------------------------------------------------------------------------- +type Cue = { start: number; end: number; text: string }; +const cueCache = new Map<string, Promise<Cue[] | null>>(); + +function NowReader({ + project, + item, + entry, + t, + next, + nextEntry, + broken, +}: { + project: string; + item: ReturnType<typeof playPlan>["items"][number] | null; + entry: PlayEntry | null; + t: number; + next: ReturnType<typeof playPlan>["items"][number] | null; + nextEntry: PlayEntry | null; + broken: boolean; +}) { + const [cues, setCues] = useState<{ key: string; cues: Cue[] | null } | null>(null); + const clip = item?.clip ?? null; + const key = clip && entry?.video ? `${entry.channel ?? ""}|${entry.video}|${clip.sourceFrom}|${clip.sourceTo}` : null; + useEffect(() => { + if (!key || !clip || !entry?.video) return; + let live = true; + if (!cueCache.has(key)) { + const q = new URLSearchParams({ project, video: entry.video, from: String(clip.sourceFrom), to: String(clip.sourceTo), ...(entry.channel ? { channel: entry.channel } : {}) }); + cueCache.set( + key, + fetch(`/api/report/cues?${q}`, { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : null)) + .then((j: { cues?: Cue[] } | null) => j?.cues ?? null) + .catch(() => null), + ); + } + void cueCache.get(key)!.then((c) => { + if (live) setCues({ key, cues: c }); + }); + return () => { + live = false; + }; + }, [key, project, clip, entry?.video, entry?.channel]); + const src = item && clip ? sourceAt(item, t) : null; + const list = cues?.key === key ? (cues.cues ?? []) : []; + const lit = src === null ? -1 : list.findIndex((c) => src >= c.start && src < c.end); + const box = useRef<HTMLDivElement | null>(null); + useEffect(() => { + const el = box.current?.querySelector<HTMLElement>("[data-lit]"); + const b = box.current; + if (el && b) b.scrollTop = Math.max(0, el.offsetTop - b.clientHeight / 3); + }, [lit, key]); + if (!item) return null; + const nextLine = next ? ( + <p className="m-0 text-[11.5px]" data-play-next-up={next.id}> + next: <span className="font-mono">{next.id}</span> + {nextEntry?.dateLabel ? ` · ${nextEntry.dateLabel}` : next.clip ? "" : ` · ${next.type}`} + </p> + ) : ( + <p className="m-0 text-[11.5px]">the end of the cut</p> + ); + + if (!clip) { + return ( + <section data-play-now={item.id} className="rounded-[3px] border border-seam bg-panel px-3.5 py-2.5 text-text-2"> + <p className="m-0 font-mono text-[11.5px] text-muted"> + {item.id} · {item.type} + </p> + <p className="m-0 mt-1 text-[14px] text-text">{entry?.heading}</p> + <div className="mt-2 text-muted">{nextLine}</div> + </section> + ); + } + return ( + <section data-play-now={item.id} className="reader rounded-[2px]"> + <header className="flex flex-wrap items-baseline gap-x-2 border-b border-reader-seam px-3.5 py-1.5"> + <span className="font-mono text-[12px] font-medium">{item.id}</span> + {entry?.dateLabel && <span className="text-[12px] text-reader-2">{entry.dateLabel}</span>} + {entry?.video && <span className="font-mono text-[11px] text-reader-dim">{entry.video}</span>} + {(!entry?.media || broken) && <span className="text-[11.5px] text-reader-dim">· No media for this clip — fetch it</span>} + </header> + <div ref={box} className="relative max-h-[124px] overflow-auto py-1.5 font-serif text-[14.5px] leading-[1.45]" data-play-words=""> + {list.length > 0 ? ( + list.map((c, i) => ( + <div key={`${c.start}-${i}`} className="lit-line reader-cue" data-lit={i === lit ? "" : undefined} data-play-cue={c.start}> + <span className="reader-t">{runningTime(c.start)}</span> + <span>{c.text}</span> + </div> + )) + ) : ( + <p className="m-0 px-3.5 py-1 text-reader-2">{entry?.quote ? `“${entry.quote}”` : "No transcript for this recording."}</p> + )} + </div> + <div className="border-t border-reader-seam px-3.5 py-1.5 text-reader-dim">{nextLine}</div> + </section> + ); +} + +// --------------------------------------------------------------------------- +// THE NOTES, in reel order: the composer at the playhead (kind chips, Save +// note), Open / All / Resolved, each note's timecode a seek, the assistant +// on a note or on every open one, its proposals Applied only on a click. +// --------------------------------------------------------------------------- + +type Filter = "open" | "all" | "resolved"; + function PlayNotes({ project, take, notes, mine, drafting, - onCancel, - onAdded, + nowLabel, + pauseWhileWriting, + onPauseWhileWriting, + onNote, + onClose, onSeek, onApplied, }: { @@ -693,9 +953,12 @@ function PlayNotes({ take: string | null; notes: ReturnType<typeof useSharedNotes>; mine: Note[]; - drafting: Extract<Anchor, { kind: "cut" }> | null; - onCancel: () => void; - onAdded: () => void; + drafting: CutAnchor | null; + nowLabel: string; + pauseWhileWriting: boolean; + onPauseWhileWriting: (on: boolean) => void; + onNote: () => void; + onClose: () => void; onSeek: (n: Note) => void; onApplied: () => void; }) { @@ -704,88 +967,138 @@ function PlayNotes({ useEffect(() => { if (a.ended) void reloadNotes(); }, [a.ended, reloadNotes]); - const blocked = !a.view ? "reading the assistant's route…" : (a.view.route?.why ?? (!a.view.route ? "the assistant needs the editor" : null)); + const [filter, setFilter] = useState<Filter>("open"); + const [opened, setOpened] = useState<Record<string, boolean>>({}); + const blocked = !a.view ? "Reading how the assistant is routed…" : a.view.route?.why ? `${a.view.route.why}.` : !a.view.route ? "The assistant needs the editor, and it did not answer." : null; const running = !!a.job && !a.job.ended; const asking = running ? (a.job?.note ?? "all") : null; const p = a.view?.proposals ?? null; const open = mine.filter((n) => n.status === "open"); + const resolved = mine.filter((n) => n.status !== "open"); + const shown = filter === "open" ? open : filter === "resolved" ? resolved : mine; const all = cutNotesRequest(mine, { take }); const apply = async (ids: string[] | null, at?: string) => { const ok = await a.apply(ids, at ?? p?.at); if (ok) onApplied(); return ok; }; - const where = (n: Note) => { - const an = n.anchor as Extract<Anchor, { kind: "cut" }>; + const askOf = (n: Note) => (n.anchor as CutAnchor).ask; + const head = (n: Note) => { + const an = n.anchor as CutAnchor; + const ask = ASKS.find((x) => x.id === an.ask); return ( - <button type="button" data-play-note-seek={an.t} onClick={() => onSeek(n)} className="num shrink-0 font-mono text-[11px] ink-link" title="play from here"> - {clockText(an.t)} - {an.entry ? ` · ${an.entry}` : ""} - </button> + <> + <button type="button" data-play-note-seek={an.t} onClick={() => onSeek(n)} className="shrink-0 font-mono text-[11.5px] text-signal-text hover:underline" title="play from here"> + {timecode(an.t)} + </button> + {an.entry && <span className="shrink-0 font-mono text-[11px] text-muted">{an.entry}</span>} + {ask && ( + <span className="shrink-0 rounded-[2px] border border-seam-2 px-1 text-[10.5px] leading-[15px] text-text-2" data-play-note-ask={ask.id}> + {ask.label.toLowerCase()} + </span> + )} + </> ); }; + const count = (f: Filter) => (f === "open" ? open.length : f === "resolved" ? resolved.length : mine.length); + return ( - <section data-play-notes={mine.length} className="space-y-1.5"> - <h3 className="micro m-0"> - Notes{take ? ` on take ${take}` : " on the cut"} - {mine.length ? ` — ${open.length} open` : ""} - </h3> - {drafting && ( - <NoteComposer - testId="play-note-input" - busy={notes.busy} - placeholder="what to change here — Enter to save" - head={ - <span className="num font-mono text-[11px] text-text-2" data-play-note-at={drafting.t}> - at {clockText(drafting.t)} - {drafting.entry ? ` · ${drafting.entry}` : ""} - </span> - } - onCancel={onCancel} - onAdd={(text) => - void notes.write({ op: "add", text, anchor: drafting }).then((n) => { - if (n) onAdded(); - }) - } - /> - )} - {!drafting && !mine.length && <p className="m-0 text-[11.5px] text-muted">Press m (or Note at playhead) while it plays.</p>} - {mine.map((n) => ( - <div key={n.id} data-play-note={n.id}> - <NoteThread - note={n} - write={notes.write} - busy={notes.busy} - head={where(n)} - actions={ - n.status === "open" ? ( - <button - type="button" - data-play-send={n.id} - disabled={notes.busy || a.busy || !!blocked || running} - title={blocked ?? "the assistant reads this note (with where it was taken) and replies here; what it proposes waits for your Apply"} - onClick={() => void a.ask({ note: n.id, scope: "all" })} - className="ink-link disabled:opacity-40" - > - {asking === n.id ? "Asking…" : "Send to the assistant"} - </button> - ) : null - } - afterReply={(r) => <AssistReplyApply reply={r} proposals={p} busy={a.busy} apply={apply} onApplied={() => void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" })} />} - /> + <section data-play-notes={mine.length} className="flex min-h-0 flex-1 flex-col"> + <div className="space-y-2 border-b border-seam p-3"> + {drafting ? ( + <Composer anchor={drafting} busy={notes.busy} onCancel={onClose} onSave={async (text, ask) => { + const n = await notes.write({ op: "add", text, anchor: { ...drafting, ...(ask ? { ask } : {}) } }); + if (n) onClose(); + }} /> + ) : ( + <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5"> + <button type="button" data-play-note-add="" onClick={onNote} className={cn(buttonVariants({ variant: "outline", size: "sm" }), "font-mono")} title="note this moment (M)"> + Note at {nowLabel} + </button> + <label className="inline-flex items-center gap-1.5 text-[11.5px] text-text-2"> + <input type="checkbox" data-play-pause-writing="" checked={pauseWhileWriting} onChange={(e) => onPauseWhileWriting(e.target.checked)} /> + Pause while I write + </label> + </div> + )} + </div> + + <div className="flex items-center gap-2 px-3 pt-2.5"> + <h2 className="micro m-0">Notes{take ? ` · ${take}` : ""}</h2> + <div role="tablist" aria-label="Which notes" className="ml-auto flex rounded-[3px] border border-seam-2 p-0.5 text-[11.5px]"> + {(["open", "all", "resolved"] as Filter[]).map((f) => ( + <button + key={f} + type="button" + role="tab" + aria-selected={filter === f} + data-play-note-filter={f} + onClick={() => setFilter(f)} + className={cn("rounded-[2px] px-1.5 py-px capitalize", filter === f ? "bg-panel-2 text-text" : "text-muted-2 hover:text-text")} + > + {f} <span className="font-mono">{count(f)}</span> + </button> + ))} </div> - ))} - <div className="space-y-1 border-t border-seam pt-1.5" data-play-assist={a.view?.route?.route ?? "none"}> + </div> + + <ol className="m-0 min-h-0 flex-1 list-none space-y-2.5 overflow-auto p-3" data-play-note-list=""> + {!mine.length && <li className="text-[12px] text-muted">Press M while it plays to note this moment.</li>} + {mine.length > 0 && !shown.length && <li className="text-[12px] text-muted">{filter === "open" ? "No open notes." : "Nothing resolved yet."}</li>} + {shown.map((n) => { + const collapsed = n.status !== "open" && filter === "all" && !opened[n.id]; + if (collapsed) { + return ( + <li key={n.id} data-play-note={n.id} data-play-note-collapsed=""> + <button type="button" onClick={() => setOpened((o) => ({ ...o, [n.id]: true }))} className="flex w-full items-baseline gap-1.5 text-left text-[11.5px] text-muted hover:text-text"> + <span className="font-mono">{timecode((n.anchor as CutAnchor).t)}</span> + <span>✓</span> + <span className="min-w-0 truncate">{n.text.split("\n")[0]}</span> + </button> + </li> + ); + } + return ( + <li key={n.id} data-play-note={n.id}> + <NoteThread + note={n} + write={notes.write} + busy={notes.busy} + head={head(n)} + actions={ + n.status === "open" ? ( + <button + type="button" + data-play-send={n.id} + disabled={notes.busy || a.busy || !!blocked || running} + title={blocked ?? "the assistant reads this note (where it was taken, what it asks for) and replies here; what it proposes waits for your Apply"} + onClick={() => void a.ask({ note: n.id, scope: askOf(n) === "look" ? "look" : "all" })} + className="ink-link disabled:opacity-40" + > + {asking === n.id ? "Asking…" : "Send to the assistant"} + </button> + ) : null + } + afterReply={(r) => ( + <AssistReplyApply reply={r} proposals={p} busy={a.busy} apply={apply} variant="outline" onApplied={() => void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" })} /> + )} + /> + </li> + ); + })} + </ol> + + <div className="space-y-1.5 border-t border-seam p-3" data-play-assist={a.view?.route?.route ?? "none"}> <div className="flex flex-wrap items-center gap-2"> <button type="button" data-play-send-all="" disabled={!all || !!blocked || running || a.busy} - title={blocked ?? "every open note here, in cut order, as one request; its proposals come back below"} + title={blocked ?? "every open note here, in reel order, as one request; its proposals come back below"} onClick={() => all && void a.ask({ request: all, scope: "all" })} - className={buttonVariants({ size: "sm" })} + className={buttonVariants({ variant: "outline", size: "sm" })} > - {asking === "all" ? "Asking…" : `Send all open notes${open.length ? ` (${open.length})` : ""}`} + {asking === "all" ? "Asking…" : `Send ${open.length} open note${open.length === 1 ? "" : "s"} to the assistant`} </button> {running && ( <button type="button" onClick={() => void a.cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}> @@ -793,13 +1106,19 @@ function PlayNotes({ </button> )} </div> - {a.view && ( - <p className="m-0 text-[11px] text-muted" data-play-assist-status=""> - {routeLine(a.view)} + {blocked ? ( + <p className="m-0 text-[11px] text-muted" data-play-assist-blocked=""> + {blocked} </p> + ) : ( + a.view && ( + <p className="m-0 text-[11px] text-muted" data-play-assist-status=""> + {routeLine(a.view)} + </p> + ) )} <p className="m-0 text-[11px] text-muted"> - For Claude Code: <code className="font-mono">umtool notes {project}</code> prints these with where each was taken. + Claude Code reads these with <code className="font-mono text-text-2">umtool notes {project}</code>. </p> {a.job && ( <p className="m-0 text-[11.5px] text-text-2" data-play-assist-job={a.job.status}> @@ -816,3 +1135,68 @@ function PlayNotes({ </section> ); } + +/** The note being written: where, its words, what it asks for, Save note. */ +function Composer({ anchor, busy, onCancel, onSave }: { anchor: CutAnchor; busy: boolean; onCancel: () => void; onSave: (text: string, ask: CutAsk | null) => void | Promise<void> }) { + const [text, setText] = useState(""); + const [ask, setAsk] = useState<CutAsk | null>(null); + const save = () => { + if (text.trim()) void onSave(text, ask); + }; + return ( + <div className="space-y-1.5" data-play-composer=""> + <p className="m-0 font-mono text-[12px] text-text" data-play-note-at={anchor.t}> + Note at {timecode(anchor.t)} + {anchor.entry ? <span className="text-muted"> · {anchor.entry}</span> : null} + </p> + <textarea + autoFocus + rows={2} + value={text} + data-testid="play-note-input" + onChange={(e) => setText(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + onCancel(); + } else if (e.key === "Enter" && !e.shiftKey && !e.altKey) { + e.preventDefault(); + save(); + } else if (e.altKey) { + const k = ASKS.find((x) => x.key === e.key.toLowerCase() || e.code === `Key${x.key.toUpperCase()}`); + if (k) { + e.preventDefault(); + setAsk((cur) => (cur === k.id ? null : k.id)); + } + } + }} + placeholder="What to change here" + className="block w-full resize-y rounded-[3px] border border-seam-2 bg-ground px-2 py-1.5 text-[13px] text-text outline-none focus:border-signal" + /> + <div className="flex flex-wrap gap-1" role="group" aria-label="What it asks for"> + {ASKS.map((k) => ( + <button + key={k.id} + type="button" + aria-pressed={ask === k.id} + data-play-ask={k.id} + title={`Alt+${k.key.toUpperCase()}`} + onClick={() => setAsk((cur) => (cur === k.id ? null : k.id))} + className={cn("rounded-[2px] border px-1.5 py-px text-[11.5px]", ask === k.id ? "border-text-2 bg-panel-2 text-text" : "border-seam-2 text-muted-2 hover:text-text")} + > + {k.label} + </button> + ))} + </div> + <div className="flex items-center gap-2"> + <button type="button" data-play-note-save="" disabled={busy || !text.trim()} onClick={save} className={buttonVariants({ variant: "go", size: "sm" })}> + Save note + </button> + <button type="button" onClick={onCancel} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Cancel + </button> + <span className="ml-auto text-[11px] text-muted">Enter saves · Esc closes</span> + </div> + </div> + ); +} diff --git a/umtool/components/projects/review/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx @@ -0,0 +1,255 @@ +"use client"; + +import { useMemo, useRef, useState } from "react"; +import { cn } from "@/lib/utils"; +import { counterAt, dateRamp, playPlan, rulerTicks, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; + +type PlayItem = ReturnType<typeof playPlan>["items"][number]; + +// --------------------------------------------------------------------------- +// THE REEL STRIP (the Play view's signature): the whole cut as a strip of +// film. One cell per entry, as wide as the page shows it; a clip's cell +// tinted by its recording's date (older recedes toward the ground); a clip +// with no media hatched; the sections' seams as hairlines with the section's +// first date above; the deck's counter plotted across it as a staircase in +// METER, its total at the right end and at the playhead; the notes as SIGNAL +// pins at their cut second; the playhead a 1px SIGNAL line. Click or drag +// anywhere to scrub; a cell's Enter jumps to its start; the ruler under it +// counts the minutes. +// --------------------------------------------------------------------------- + +export type StripEntry = { id: string; type: string; heading: string; dateKey?: number | null; dateLabel?: string | null; media?: unknown }; +export type StripCounter = { id: string; label: string; steps: Array<{ t: number; n: number }> }; +export type StripPin = { id: string; t: number; text: string; open: boolean }; +export type StripSeam = { before: string; index: number; date: string | null; label: string | null }; + +const CELLS_H = 56; +const pctOf = (t: number, total: number) => `${total > 0 ? Math.max(0, Math.min(100, (t / total) * 100)) : 0}%`; + +export default function ReelStrip({ + items, + total, + entries, + t, + cur, + seams, + counters, + pins, + failed, + timecode, + onSeek, + onSeekItem, +}: { + items: PlayItem[]; + total: number; + entries: Map<string, StripEntry>; + t: number; + cur: number; + seams: StripSeam[]; + counters: StripCounter[]; + pins: StripPin[]; + failed: Record<string, string>; + timecode: (t: number) => string; + onSeek: (t: number) => void; + onSeekItem: (i: number) => void; +}) { + const cells = useRef<HTMLDivElement | null>(null); + const [hover, setHover] = useState<number | null>(null); + const scrubbing = useRef(false); + const ramp = useMemo(() => dateRamp([...entries.values()]), [entries]); + const max = Math.max(1, ...counters.map((c) => c.steps[c.steps.length - 1]?.n ?? 0)); + const { ticks } = useMemo(() => rulerTicks(total), [total]); + const tAt = (clientX: number) => { + const r = cells.current?.getBoundingClientRect(); + if (!r || r.width <= 0) return 0; + return Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * total; + }; + const counterNow = counters.map((c) => ({ ...c, now: counterAt(c.steps, t), end: c.steps[c.steps.length - 1]?.n ?? 0 })); + const hovered = hover !== null ? items[hover] : null; + const he = hovered ? entries.get(hovered.id) : null; + const noMedia = (it: PlayItem) => !!it.clip && (!entries.get(it.id)?.media || !!failed[it.id]); + + return ( + <section data-play-strip="" aria-label="The cut as a reel" className="select-none"> + {/* the seams' dates, the counter's total at the right end */} + <div className="relative h-4 font-mono text-[10px] leading-4 text-muted"> + {seams.map((s) => { + const it = items[s.index]; + if (!it) return null; + return ( + <span key={s.before} data-play-seam-date={s.before} className="absolute top-0 -translate-x-px whitespace-nowrap pl-1" style={{ left: pctOf(it.from, total) }} title={s.label ?? undefined}> + {s.date ?? s.label ?? ""} + </span> + ); + })} + {counterNow.length > 0 && ( + <span className="absolute right-0 top-0 whitespace-nowrap bg-ground pl-1.5 text-meter" data-play-counter-end={counterNow.map((c) => `${c.id}:${c.end}`).join(",")}> + {counterNow.map((c) => `${c.label} ${c.end}`).join(" · ")} + </span> + )} + </div> + + {/* a hovered cell, named above it */} + <div className="relative h-0"> + {hovered && ( + <span + data-play-strip-hover={hovered.id} + className="pointer-events-none absolute -top-4 z-10 whitespace-nowrap rounded-[2px] border border-seam-2 bg-panel px-1.5 font-mono text-[10.5px] leading-4 text-text-2" + style={{ + left: pctOf((hovered.from + hovered.to) / 2, total), + transform: `translateX(${(hovered.from + hovered.to) / 2 / Math.max(total, 1e-9) > 0.75 ? "-100%" : (hovered.from + hovered.to) / 2 / Math.max(total, 1e-9) < 0.25 ? "0" : "-50%"})`, + }} + > + {hovered.id} + {he?.dateLabel ? ` · ${he.dateLabel}` : hovered.clip ? "" : ` · ${hovered.type}`} · {shownSeconds(hovered).toFixed(1)} s + {noMedia(hovered) ? " · no media — fetch it" : ""} + </span> + )} + </div> + + {/* the notes' pins */} + <div className="relative h-3"> + {pins.map((p) => ( + <button + key={p.id} + type="button" + data-play-pin={p.id} + title={`${timecode(p.t)} — ${p.text.split("\n")[0]}`} + aria-label={`note at ${timecode(p.t)}: ${p.text.split("\n")[0]}`} + onClick={() => onSeek(p.t)} + className={cn("absolute top-0 h-3 w-2 -translate-x-1/2 p-0", p.open ? "opacity-100" : "opacity-45")} + style={{ left: pctOf(p.t, total) }} + > + <span className="absolute left-1/2 top-0 h-2 w-2 -translate-x-1/2 rotate-45 bg-signal" /> + <span className="absolute left-1/2 top-1.5 h-1.5 w-px -translate-x-1/2 bg-signal" /> + </button> + ))} + </div> + + {/* the cells: click or drag to scrub */} + <div + ref={cells} + data-play-cells="" + className="relative cursor-col-resize overflow-hidden rounded-[2px] border border-seam bg-ground touch-none" + style={{ height: CELLS_H }} + onPointerDown={(e) => { + if (e.button !== 0) return; + scrubbing.current = true; + e.currentTarget.setPointerCapture(e.pointerId); + onSeek(tAt(e.clientX)); + }} + onPointerMove={(e) => { + const r = cells.current?.getBoundingClientRect(); + if (r) { + const x = tAt(e.clientX); + const i = items.findIndex((it) => x >= it.from && x < it.to); + setHover(i >= 0 ? i : null); + } + if (scrubbing.current) onSeek(tAt(e.clientX)); + }} + onPointerUp={() => { + scrubbing.current = false; + }} + onPointerLeave={() => setHover(null)} + > + {items.map((it, i) => { + const e = entries.get(it.id); + const f = ramp.get(it.id); + const missing = noMedia(it); + const base = it.clip + ? `color-mix(in srgb, var(--seam-2) ${Math.round(30 + 60 * (f ?? 0.5))}%, var(--ground))` + : "var(--panel)"; + return ( + <button + key={it.id} + type="button" + tabIndex={0} + data-play-row={it.id} + aria-current={i === cur ? "true" : undefined} + aria-label={`${it.id}${e?.dateLabel ? `, ${e.dateLabel}` : ""}, ${shownSeconds(it).toFixed(1)} seconds${missing ? ", no media" : ""}`} + title={missing ? `${it.id}: no media — fetch it` : undefined} + data-play-row-missing={missing ? "" : undefined} + onClick={(ev) => { + // A pointer's click scrubbed on pointerdown; a key's (Enter) jumps to the entry's start. + if (ev.detail === 0) onSeekItem(i); + }} + className={cn( + "absolute top-0 h-full overflow-hidden border-r border-ground px-1 pt-0.5 text-left font-mono text-[10px] leading-3", + it.clip ? "text-text-2" : "text-muted", + i === cur && "shadow-[inset_0_-2px_0_var(--signal)]", + )} + style={{ + left: pctOf(it.from, total), + width: pctOf(it.to - it.from, total), + background: missing + ? `repeating-linear-gradient(135deg, var(--seam-2) 0 1px, transparent 1px 6px), ${base}` + : base, + }} + > + <span className="block whitespace-nowrap">{it.id}</span> + {!it.clip && <span className="block whitespace-nowrap text-[9px] uppercase tracking-wide opacity-80">{it.type}</span>} + </button> + ); + })} + + {/* the sections' seams */} + {seams.map((s) => { + const it = items[s.index]; + return it ? <span key={s.before} aria-hidden className="pointer-events-none absolute top-0 h-full w-px bg-text-2 opacity-60" style={{ left: pctOf(it.from, total) }} /> : null; + })} + + {/* the counter's staircase */} + {counters.length > 0 && total > 0 && ( + <svg aria-hidden className="pointer-events-none absolute inset-0 h-full w-full" viewBox="0 0 1000 100" preserveAspectRatio="none" data-play-staircase=""> + {counters.map((c, k) => { + const y = (n: number) => 94 - (n / max) * 78; + let d = `M0,${y(0)}`; + for (const s of c.steps) d += ` H${(s.t / total) * 1000} V${y(s.n)}`; + d += " H1000"; + return ( + <path + key={c.id} + d={d} + fill="none" + stroke={k === 0 ? "var(--meter)" : k === 1 ? "var(--m3)" : "var(--m5)"} + strokeWidth={1.5} + vectorEffect="non-scaling-stroke" + strokeLinejoin="miter" + /> + ); + })} + </svg> + )} + + {/* the playhead */} + <span aria-hidden data-play-playhead="" className="pointer-events-none absolute top-0 h-full w-px bg-signal" style={{ left: pctOf(t, total) }} /> + </div> + + {/* the playhead's timecode and the counter at it; a hovered cell's line */} + <div className="relative h-4 font-mono text-[10.5px] leading-4"> + <span + className="absolute top-0 whitespace-nowrap text-signal-text" + style={{ left: pctOf(t, total), transform: `translateX(${t / Math.max(total, 1e-9) > 0.8 ? "-100%" : t / Math.max(total, 1e-9) > 0.2 ? "-50%" : "0"})` }} + data-play-strip-at="" + > + {timecode(t)} + {counterNow.map((c) => ( + <span key={c.id} className="text-meter"> + {" "} + · {c.label} {c.now} + </span> + ))} + </span> + </div> + {/* the ruler */} + <div className="relative h-4 border-t border-seam font-mono text-[10px] leading-4 text-muted" aria-hidden data-play-ruler=""> + {ticks.map((s) => ( + <span key={s} className="absolute top-0" style={{ left: pctOf(s, total) }}> + <span className="absolute -top-px left-0 h-1.5 w-px bg-seam-2" /> + {s > 0 && s < total - total * 0.04 && <span className="absolute left-0 top-0.5 -translate-x-1/2 whitespace-nowrap">{runningTime(s)}</span>} + </span> + ))} + </div> + </section> + ); +} diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -190,10 +190,12 @@ take plays its blurred clips as recorded. | | In umtool | Keys | |---|---|---| -| play / pause, ±5 s, previous / next entry, speed (the voice keeps its pitch) | the transport under the picture | Space, ← →, P N | -| jump to an entry; which clips are not fetched | the list beside the picture (id, date, length) | — | -| a note at the playhead: the cut second, the clip on screen and its source second, the take (anchor `cut`) | **Note at playhead**, Enter to save; a note's time seeks there | M | -| the assistant on a note (its reply lands on the note, its edits wait for **Apply all**), or on every open note at once | a note's **Send to the assistant**; **Send all open notes** | — | +| play / pause, back (tap again: further), pause, play (tap again: 1.5×, 2×, …; the voice keeps its pitch), ±5 s, previous / next clip | the transport under the picture, the speed menu | Space, J K L, ← →, P N | +| the whole cut at a glance: a cell per entry as wide as it plays, tinted by its recording's date (older is darker), hatched when its media is not fetched; the sections' seams with their first date; the counter (the deck's tally) as a staircase with its total at the end and at the playhead; the notes as pins | the **reel strip** under the picture: click or drag to scrub, a cell's Enter jumps to its start, hover names it | — | +| what the clip on screen says, its spoken line lit as it plays, and what comes next | **Now**, under the strip | — | +| a note at the playhead: the cut second, the clip on screen and its source second, the take, and what it asks for (Trim, Cut, Move, Fact, Look, Other: the anchor's `ask`); playback pauses while you write (**Pause while I write**, on by default) and goes on when it is saved | **Note at 09:44**, the kind chips, **Save note**; the list in reel order (Open / All / Resolved); a note's timecode seeks there | M, Alt+T C M F L O, Enter, Esc, [ ] | +| the assistant on a note (its reply lands on the note, its edits wait for **Apply all**), or on every open note at once | a note's **Send to the assistant**; **Send N open notes to the assistant** | — | +| every key | **?** | ? | What it does not do (the line under the picture says so): each crossfade is a **hard cut at its middle** (where the deck hands its title over); cards, teasers and images are **placeholders** with their heading for their diff --git a/umtool/e2e/fixtures/play-cut-fixture.mjs b/umtool/e2e/fixtures/play-cut-fixture.mjs @@ -6,8 +6,9 @@ // made (takes/short/take.json, its own timeline: c04 then c01) and one only // a recipe names (quick-joins, a hard-cut look). // -// c01 vid1 1.0-3.0 c02 vid1 3.5-5.5 k01 card 1.5 s -// c03 nofetch 2-4 (no window on disk) c04 vid1 6.0-8.0 +// c01 vid1 1.0-3.0 c02 vid1 3.5-5.5 (k1 at 4.5) k01 card 1.5 s +// c03 nofetch 2-4 (no window on disk) c04 vid1 6.0-8.0 (k2, counts 2) +// sections 0 (c01, c02) and 1 (c03, c04); one counter, "Seizures" // // Synthetic, like every fixture. import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; @@ -20,14 +21,22 @@ export function makePlayCutFixture({ reports, deckManifest, cachedWindow }) { const dir = path.join(reports, "play-cut-fixture"); mkdirSync(dir, { recursive: true }); const timeline = [ - { type: "clip", id: "c01", video: "vid1", start: 1.0, end: 3.0, cite: 1, lock: true, quote: "This is a complete sentence.", onscreen: { title: "24 Oct 2020" } }, - { type: "clip", id: "c02", video: "vid1", start: 3.5, end: 5.5, cite: 4, lock: true, quote: "And this one runs on", onscreen: { title: "2 Dec 2024" } }, + { type: "clip", id: "c01", video: "vid1", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "This is a complete sentence.", onscreen: { title: "24 Oct 2020" } }, + { + type: "clip", id: "c02", video: "vid1", start: 3.5, end: 5.5, cite: 4, section: 0, lock: true, quote: "And this one runs on", onscreen: { title: "2 Dec 2024" }, + claim: { id: "k1", verdict: "CORROBORATED", at: 4.5 }, + }, { type: "card", id: "k01", style: "chapter", seconds: 1.5, heading: "Between the clips" }, - { type: "clip", id: "c03", video: "nofetch", start: 2.0, end: 4.0, cite: 2, lock: true, quote: "never fetched" }, - { type: "clip", id: "c04", video: "vid1", start: 6.0, end: 8.0, cite: 6, lock: true, quote: "of that it finishes here.", onscreen: { title: "27 Feb 2025" } }, + { type: "clip", id: "c03", video: "nofetch", start: 2.0, end: 4.0, cite: 2, section: 1, lock: true, quote: "never fetched" }, + { + type: "clip", id: "c04", video: "vid1", start: 6.0, end: 8.0, cite: 6, section: 1, lock: true, quote: "of that it finishes here.", onscreen: { title: "27 Feb 2025" }, + claim: { id: "k2", verdict: "CORROBORATED", count: 2 }, + }, ]; const m = deckManifest("play-cut-fixture", "The Play Cut Fixture", timeline); m.render.fetchPad = 0; + // One counter, as the Huck cut has: the reel strip's staircase steps 1 at c02, 2 more at c04. + m.render.chrome = { ...m.render.chrome, factcheck: { verdicts: { CORROBORATED: { label: "Seizures", color: "#6fa8dc" } }, stamp: { seconds: 1 } } }; writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4")); diff --git a/umtool/e2e/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts @@ -5,11 +5,14 @@ import { fileURLToPath } from "node:url"; import * as urls from "./urls"; // --------------------------------------------------------------------------- -// The Play view (umtool/docs/knobs.md, "Play the cut"): the whole cut played in the browser -// on one cut clock, no render -- clip 1 plays, the clock carries into clip 2, -// prev / next / the keys move between entries (a card and an unfetched clip -// play as placeholders), a note taken at the playhead lists and seeks, and a -// take plays its own timeline. Fixture: e2e/fixtures/play-cut-fixture.mjs. +// The Play view (umtool/docs/knobs.md, "Play the cut"): the whole cut played +// in the browser on one cut clock, no render -- clip 1 plays, the clock +// carries into clip 2, prev / next / the keys move between entries (a card +// and an unfetched clip play as placeholders), the reel strip scrubs and +// carries the counter's staircase, a note taken at the playhead (with its +// kind) lists, pins and seeks, and a take plays its own timeline. +// Screenshots at 1280 and 390 px land in test-results. Fixture: +// e2e/fixtures/play-cut-fixture.mjs. // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -25,15 +28,26 @@ test.beforeEach(() => { test.setTimeout(120_000); }); -test("the cut plays clip after clip on one clock; prev / next / keys; placeholders never stall", async ({ page }) => { +test("the cut plays clip after clip on one clock; prev / next / keys; the strip scrubs; placeholders never stall", async ({ page }) => { await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.playHref(PROJECT)); await expect(root(page)).toHaveAttribute("data-play-state", "paused"); await expect(rows(page)).toHaveCount(5); expect(await rows(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c01", "c02", "k01", "c03", "c04"]); - await expect(page.locator('[data-play-row="c03"] [data-play-row-missing]')).toBeVisible(); + await expect(page.locator('[data-play-row="c03"][data-play-row-missing]')).toHaveCount(1); await expect(page.locator('[data-play-row="c01"]')).toHaveAttribute("aria-current", "true"); await expect(page.locator("[data-play-approximate]")).toContainText("hard cut"); + // The strip: the section seam before c03 dated by its first dated clip, the counter's staircase and its total. + await expect(page.locator('[data-play-seam-date="c03"]')).toHaveText("27 Feb 2025"); + await expect(page.locator("[data-play-staircase] path")).toHaveCount(1); + await expect(page.locator("[data-play-counter-end]")).toHaveText("Seizures 3"); + await expect(page.locator("[data-play-strip-at]")).toContainText("Seizures 0"); + await expect(page.locator("[data-play-clock]")).toContainText("00:00 / 00:08"); + // Hovering a cell names it: the clip, its recording's date, how long it plays. + await page.locator('[data-play-row="c02"]').hover(); + await expect(page.locator('[data-play-strip-hover="c02"]')).toHaveText("c02 · 2 Dec 2024 · 1.8 s"); + await page.locator('[data-play-row="c03"]').hover(); + await expect(page.locator('[data-play-strip-hover="c03"]')).toContainText("no media — fetch it"); // Play: clip 1's media (the bench's raw route) plays, the clock moves. await page.locator("[data-play-toggle]").click(); @@ -46,7 +60,10 @@ test("the cut plays clip after clip on one clock; prev / next / keys; placeholde .poll(() => page.locator('video[data-play-slot-item="c02"]').evaluate((v: HTMLVideoElement) => !v.paused && v.readyState >= 2), { timeout: 15_000 }) .toBe(true); await expect.poll(() => tNow(page)).toBeGreaterThan(1.9); - await page.keyboard.press("Space"); + // NOW: c02 on the reader, the next entry named. + await expect(page.locator('[data-play-now="c02"]')).toBeVisible(); + await expect(page.locator("[data-play-next-up]")).toHaveAttribute("data-play-next-up", "k01"); + await page.keyboard.press("k"); await expect(root(page)).toHaveAttribute("data-play-state", "paused"); // Next: the card, shown as a placeholder from its first second. @@ -54,14 +71,17 @@ test("the cut plays clip after clip on one clock; prev / next / keys; placeholde await expect(root(page)).toHaveAttribute("data-play-item", "k01"); await expect(page.locator('[data-play-placeholder="card"]')).toContainText("Between the clips"); expect(await tNow(page)).toBeCloseTo(3.7, 1); + // The stamp on c02 (k1 at source 4.5) has landed by now: the counter at the playhead says so. + await expect(page.locator("[data-play-strip-at]")).toContainText("Seizures 1"); // n: the clip whose source was never fetched -- named, not waited on. await page.keyboard.press("n"); await expect(root(page)).toHaveAttribute("data-play-item", "c03"); - await expect(page.locator('[data-play-missing="c03"]')).toContainText("not fetched"); - // Playing through it: the wall clock carries on to c04. - await page.locator("[data-play-toggle]").click(); + await expect(page.locator('[data-play-missing="c03"]')).toContainText("No media for c03 — fetch it"); + // Playing through it (L): the wall clock carries on to c04. + await page.keyboard.press("l"); await expect(root(page)).toHaveAttribute("data-play-item", "c04", { timeout: 15_000 }); await page.keyboard.press("Space"); + await expect(root(page)).toHaveAttribute("data-play-state", "paused"); // p, prev: back an entry at a time. await page.keyboard.press("p"); await expect(root(page)).toHaveAttribute("data-play-item", "c03"); @@ -74,43 +94,90 @@ test("the cut plays clip after clip on one clock; prev / next / keys; placeholde await page.keyboard.press("ArrowRight"); await expect(root(page)).toHaveAttribute("data-play-item", "c03"); expect(await tNow(page)).toBeCloseTo(5, 1); - // A row is a jump. - await page.locator('[data-play-row="c02"]').click(); + // A cell's Enter jumps to its start; a click on the strip scrubs to that second. + await page.locator('[data-play-row="c02"]').press("Enter"); await expect(root(page)).toHaveAttribute("data-play-item", "c02"); expect(await tNow(page)).toBeCloseTo(1.9, 1); + const cells = page.locator("[data-play-cells]"); + const box = (await cells.boundingBox())!; + await page.mouse.click(box.x + box.width * 0.9, box.y + box.height / 2); + await expect(root(page)).toHaveAttribute("data-play-item", "c04"); + expect(Math.abs((await tNow(page)) - 0.9 * 8.7)).toBeLessThan(0.15); + + // ? lists the keys; Esc closes it. + await page.keyboard.press("?"); + await expect(page.locator("[data-play-keys]")).toContainText("previous / next note"); + await page.keyboard.press("Escape"); + await expect(page.locator("[data-play-keys]")).toHaveCount(0); }); -test("a note at the playhead: anchored to the cut second, the clip and its source second; listed; a click seeks", async ({ page }) => { +test("a note at the playhead: its kind, the cut second, the clip and its source second; listed, pinned, [ ] and a click seek", async ({ page }) => { await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.playHref(PROJECT)); await expect(root(page)).toHaveAttribute("data-play-state", "paused"); - await page.locator('[data-play-row="c02"]').click(); + await expect(page.locator("[data-play-note-list]")).toContainText("Press M while it plays to note this moment."); + await page.locator('[data-play-row="c02"]').press("Enter"); await page.keyboard.press("ArrowRight"); // 1.9 + 5 = 6.9: c04 await expect(root(page)).toHaveAttribute("data-play-item", "c04"); + await expect(page.locator("[data-play-note-add]")).toHaveText("Note at 00:06.9"); + // Paused, the clip's frame is in the picture (the fixture's window is dark green), not a black box. + await expect + .poll( + () => + page.locator("[data-play-footage]").evaluate((c: HTMLCanvasElement) => { + const [r, g, b] = c.getContext("2d")!.getImageData(Math.floor(c.width / 2), Math.floor(c.height / 2), 1, 1).data; + return g > 60 && r < 40 && b < 40; + }), + { timeout: 15_000 }, + ) + .toBe(true); await page.keyboard.press("m"); const input = page.getByTestId("play-note-input"); await expect(input).toBeFocused(); await expect(page.locator("[data-play-note-at]")).toHaveAttribute("data-play-note-at", "6.9"); await input.fill("start this one later"); + await input.press("Alt+t"); + await expect(page.locator('[data-play-ask="trim"]')).toHaveAttribute("aria-pressed", "true"); await input.press("Enter"); const note = page.locator("[data-play-note]"); await expect(note).toHaveCount(1); await expect(note).toContainText("start this one later"); - await expect(note.locator("[data-play-note-seek]")).toContainText("0:06.9 · c04"); - await expect(page.locator("[data-play-send-all]")).toContainText("(1)"); + await expect(note.locator("[data-play-note-seek]")).toHaveText("00:06.9"); + await expect(note.locator("[data-play-note-ask]")).toHaveText("trim"); + await expect(page.locator("[data-play-pin]")).toHaveCount(1); + await expect(page.locator("[data-play-send-all]")).toHaveText("Send 1 open note to the assistant"); - // Written through the notes store: the cut anchor, the clip, its source second (c04 starts at 6.7 on the clock: 6.0 + 0.2). + // Written through the notes store: the cut anchor, the clip, its source second (c04 starts at 6.7: 6.0 + 0.2), the kind. const doc = JSON.parse(readFileSync(path.join(DIR, "notes.json"), "utf8")); const n = doc.notes.find((x: { text: string }) => x.text === "start this one later"); - expect(n.anchor).toEqual({ kind: "cut", t: 6.9, entry: "c04", sourceT: 6.2 }); + expect(n.anchor).toEqual({ kind: "cut", t: 6.9, entry: "c04", sourceT: 6.2, ask: "trim" }); expect(n.author).toBe("operator"); - // Elsewhere, then the note's time: back where it was taken. - await page.locator('[data-play-row="c01"]').click(); + // Elsewhere, then ] (the next note) and the note's timecode: back where it was taken. + await page.locator('[data-play-row="c01"]').press("Enter"); await expect(root(page)).toHaveAttribute("data-play-item", "c01"); + await page.keyboard.press("]"); + await expect(root(page)).toHaveAttribute("data-play-item", "c04"); + expect(await tNow(page)).toBeCloseTo(6.9, 1); + await page.locator('[data-play-row="c01"]').press("Enter"); await note.locator("[data-play-note-seek]").click(); await expect(root(page)).toHaveAttribute("data-play-item", "c04"); expect(await tNow(page)).toBeCloseTo(6.9, 1); + + // How it looks: the desk at 1280, the stack at a phone's 390 (no sideways scroll). + await page.setViewportSize({ width: 1280, height: 860 }); + await page.screenshot({ path: test.info().outputPath("play-1280.png") }); + await page.setViewportSize({ width: 390, height: 844 }); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); + await page.screenshot({ path: test.info().outputPath("play-390.png") }); + await page.locator("[data-play-now]").scrollIntoViewIfNeeded(); + await page.screenshot({ path: test.info().outputPath("play-390-now.png") }); + await page.locator("[data-play-send-all]").scrollIntoViewIfNeeded(); + await page.screenshot({ path: test.info().outputPath("play-390-notes.png") }); + // And the dark base, at the desk's width. + await page.emulateMedia({ colorScheme: "dark" }); + await page.setViewportSize({ width: 1280, height: 860 }); + await page.screenshot({ path: test.info().outputPath("play-1280-dark.png") }); }); test("a take plays its own timeline (its patch over the project's manifest); a recipe's take plays unrendered", async ({ page }) => { @@ -122,6 +189,7 @@ test("a take plays its own timeline (its patch over the project's manifest); a r await page.goto(urls.playHref(PROJECT, { take: "short" })); await expect(root(page)).toHaveAttribute("data-play-cut", "short"); await expect(page.locator('[data-play-take="short"]')).toContainText("take “Short”"); + await expect(page.locator('[data-play-take-link="short"]')).toHaveAttribute("aria-current", "page"); await expect(rows(page)).toHaveCount(2); expect(await rows(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c04", "c01"]); await page.locator("[data-play-toggle]").click(); @@ -137,6 +205,6 @@ test("a take plays its own timeline (its patch over the project's manifest); a r await expect(page.locator('[data-play-take="quick-joins"]')).toContainText("not rendered yet"); await expect(rows(page)).toHaveCount(5); // A hard-cut look: each entry is its segment, so c02 starts at 2 s, not 1.9. - await page.locator('[data-play-row="c02"]').click(); + await page.locator('[data-play-row="c02"]').press("Enter"); expect(await tNow(page)).toBeCloseTo(2, 2); }); diff --git a/umtool/lib/annotations/cli.test.mjs b/umtool/lib/annotations/cli.test.mjs @@ -116,13 +116,13 @@ test("a note taken in the Play view: the CLI prints its cut second, its clip and }), ); const t = await projectTarget("ws/polemic-x", opts); - await writeNote(t, { op: "add", text: "Trim the start.", anchor: { kind: "cut", t: 2.5, entry: "e1", sourceT: 12.4 } }, { by: "operator" }); + await writeNote(t, { op: "add", text: "Trim the start.", anchor: { kind: "cut", t: 2.5, entry: "e1", sourceT: 12.4, ask: "trim" } }, { by: "operator" }); await writeNote(t, { op: "add", text: "Card too long.", anchor: { kind: "cut", t: 70.25, entry: "k9", take: "short-19" } }, { by: "operator" }); await writeNote(t, { op: "add", text: "Gone take.", anchor: { kind: "cut", t: 1, take: "gone" } }, { by: "operator" }); const d = await run(["ws/polemic-x"], opts); assert.equal(d.code, 0, d.text); assert.match(d.text, /\*\*On:\*\* 0:02\.5 of the cut, as the Play view plays it/); - assert.match(d.text, /entry `e1` \(clip\) “Denial”\n> I never said X\nsource ch\/v1@10-20, at source 12\.4 s/); + assert.match(d.text, /\*\*Asks for:\*\* a trim \(a clip's edges\)\nentry `e1` \(clip\) “Denial”\n> I never said X\nsource ch\/v1@10-20, at source 12\.4 s/); assert.match(d.text, /\*\*On:\*\* 1:10\.3 of take `short-19` “Short 19”/); assert.match(d.text, /entry `k9` \(card\) “The end”/); assert.match(d.text, /an edit for this take alone goes in its patch/); diff --git a/umtool/lib/annotations/digest.mjs b/umtool/lib/annotations/digest.mjs @@ -60,6 +60,16 @@ const clip = (s, n = 300) => { return t.length > n ? `${t.slice(0, n - 1)}…` : t; }; const quoteLine = (s) => `> ${clip(s, 400)}`; +/** What a Play-view note's `ask` means, for the agent. */ +const ASK_WORDS = { + trim: "a trim (a clip's edges)", + cut: "a cut (an entry out)", + move: "a move (an entry elsewhere in the order)", + fact: "a fact check (a claim, a stamp, a count)", + look: "a change of look (the chrome, the joins, the picture)", + other: "something else (read the note)", +}; + /** `m:ss.s` -- a cut second as the Play view's readout shows it. */ const cutClock = (t) => { const s = Math.max(0, Number(t) || 0); @@ -142,6 +152,7 @@ function anchorLines(a, ctx) { const lines = [ `**On:** ${cutClock(a.t)} of ${a.take ? `take \`${a.take}\`${t ? ` “${t.label}”` : ""}` : "the cut"}, as the Play view plays it (the estimated clock, cut seconds; nothing rendered)`, ]; + if (a.ask) lines.push(`**Asks for:** ${ASK_WORDS[a.ask] ?? a.ask}`); if (a.entry) { const e = (m?.timeline ?? []).find((x) => x.id === a.entry); if (!e) lines.push(`entry \`${a.entry}\` (no longer in the ${a.take ? "take's " : ""}manifest)`); diff --git a/umtool/lib/annotations/shape.mjs b/umtool/lib/annotations/shape.mjs @@ -17,6 +17,8 @@ export const NOTE_STATUSES = ["open", "resolved", "wontfix"]; export const NOTE_AUTHORS = ["operator", "agent"]; export const ANCHOR_KINDS = ["text", "cite", "section", "whole", "moment", "entry", "take", "edit", "cut"]; export const REPORT_BLOCKS = ["title", "subtitle", "summary", "method"]; +/** What a note taken in the Play view asks for (a `cut` anchor's `ask`): the dailies' kinds. */ +export const CUT_ASKS = ["trim", "cut", "move", "fact", "look", "other"]; const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; @@ -107,7 +109,8 @@ export function validateAnchor(raw) { case "cut": { // A moment of the CUT as the Play view plays it (no file: nothing is // rendered) -- the cut second on its clock, the clip on screen and its - // source second there, and the take when it was a take that played. + // source second there, the take when it was a take that played, and + // what the note asks for (`ask`, CUT_ASKS: a trim, a cut, a move, …). const t = Number(a.t); if (!Number.isFinite(t) || t < 0) return { error: "cut anchor needs t ≥ 0" }; const out = { kind: "cut", t: Number(t.toFixed(2)) }; @@ -124,6 +127,10 @@ export function validateAnchor(raw) { if (!isStr(a.take) || !TAKE_ID.test(a.take)) return { error: "cut take is not a take id" }; out.take = a.take; } + if (a.ask !== undefined) { + if (!CUT_ASKS.includes(/** @type {string} */ (a.ask))) return { error: `cut ask is one of ${CUT_ASKS.join(", ")}` }; + out.ask = a.ask; + } return { anchor: out }; } case "edit": { diff --git a/umtool/lib/annotations/store.test.mjs b/umtool/lib/annotations/store.test.mjs @@ -148,7 +148,8 @@ test("the cut anchor (the Play view): the cut second, the clip and its source se kind: "cut", t: 61.23, entry: "c04", sourceT: 194.26, take: "short-19", }); assert.deepEqual(validateAnchor({ kind: "cut", t: 0 }).anchor, { kind: "cut", t: 0 }); - for (const a of [{ kind: "cut" }, { kind: "cut", t: -1 }, { kind: "cut", t: 1, take: "Bad Id" }, { kind: "cut", t: 1, entry: "has space" }, { kind: "cut", t: 1, sourceT: -2 }]) { + assert.equal(validateAnchor({ kind: "cut", t: 1, ask: "trim" }).anchor.ask, "trim"); + for (const a of [{ kind: "cut" }, { kind: "cut", t: -1 }, { kind: "cut", t: 1, take: "Bad Id" }, { kind: "cut", t: 1, entry: "has space" }, { kind: "cut", t: 1, sourceT: -2 }, { kind: "cut", t: 1, ask: "please" }]) { assert.ok("error" in validateAnchor(a), JSON.stringify(a)); } }); diff --git a/umtool/lib/annotations/types.ts b/umtool/lib/annotations/types.ts @@ -7,6 +7,7 @@ // this file adds the types. export { ANCHOR_KINDS, + CUT_ASKS, NOTE_AUTHORS, NOTE_STATUSES, NOTE_TEXT_LIMIT, @@ -42,7 +43,10 @@ export type Anchor = | { kind: "take"; take: string } | { kind: "edit"; entry?: string; field: string; from: unknown; to: unknown } /** A moment of the cut as the Play view plays it: the cut second, the clip and its source second, the take. */ - | { kind: "cut"; t: number; entry?: string; sourceT?: number; take?: string }; + | { kind: "cut"; t: number; entry?: string; sourceT?: number; take?: string; ask?: CutAsk }; + +/** What a Play-view note asks for (shape.mjs CUT_ASKS). */ +export type CutAsk = "trim" | "cut" | "move" | "fact" | "look" | "other"; export type AnchorKind = Anchor["kind"]; diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs @@ -111,7 +111,7 @@ export const SEND_ALL_MAX = 2000; * taken (the cut second, the clip, the source second), cut to the request's * cap. null when there is nothing open. * - * @param {Array<{ status: string, text: string, anchor: { kind: string, t?: number, entry?: string, take?: string, sourceT?: number } }>} notes + * @param {Array<{ status: string, text: string, anchor: { kind: string, t?: number, entry?: string, take?: string, sourceT?: number, ask?: string } }>} notes * @param {{ take?: string | null, max?: number }} [opts] */ export function cutNotesRequest(notes, { take = null, max = SEND_ALL_MAX } = {}) { @@ -123,7 +123,8 @@ export function cutNotesRequest(notes, { take = null, max = SEND_ALL_MAX } = {}) const lines = [head]; let len = head.length; for (const [i, n] of open.entries()) { - const line = `${i + 1}. ${cutPlace(n.anchor)}: ${String(n.text).replace(/\s+/g, " ").trim()}`; + const ask = n.anchor.ask && n.anchor.ask !== "other" ? ` [${n.anchor.ask}]` : ""; + const line = `${i + 1}. ${cutPlace(n.anchor)}${ask}: ${String(n.text).replace(/\s+/g, " ").trim()}`; if (len + 1 + line.length > max) { const rest = `(${open.length - i} more not sent)`; if (len + 1 + rest.length <= max) lines.push(rest); @@ -141,3 +142,131 @@ export function cutPlace(a) { if (a?.entry) parts.push(`in clip ${a.entry}${fin(a.sourceT) ? ` (source ${Number(a.sourceT).toFixed(1)} s)` : ""}`); return parts.join(", "); } + +// --------------------------------------------------------------------------- +// THE REEL STRIP (PlayCut.tsx): the whole cut as a strip of film -- a cell +// per entry as wide as it is shown, tinted by its recording's date, the +// sections' seams, the counter's staircase, the time ruler. +// --------------------------------------------------------------------------- + +/** + * Each entry's place on the date ramp, 0 (the oldest recording) to 1 (the + * newest), by `dateKey` (YYYYMMDD); null for an entry with no date. One date + * throughout is 1 for every dated entry. + * + * @param {Array<{ id: string, dateKey?: number | null }>} entries + * @returns {Map<string, number | null>} + */ +export function dateRamp(entries) { + const days = (k) => { + const y = Math.floor(k / 10000); + const m = Math.floor((k % 10000) / 100); + const d = k % 100; + return Date.UTC(y, m - 1, d) / 86400000; + }; + const dated = (entries ?? []).filter((e) => fin(e.dateKey)).map((e) => days(/** @type {number} */ (e.dateKey))); + const lo = Math.min(...dated); + const hi = Math.max(...dated); + return new Map( + (entries ?? []).map((e) => [e.id, fin(e.dateKey) ? (hi > lo ? round((days(/** @type {number} */ (e.dateKey)) - lo) / (hi - lo)) : 1) : null]), + ); +} + +/** + * Where the cut changes section: before entry i when it is the first clip of + * a new `section` (sections.mjs's rule), or right after a deck marker's + * `after` clip. Each seam names the first date after it (the first dated + * clip from there on) and the marker's label when a marker made it. + * + * @param {Array<{ id: string, type: string, section?: unknown, dateLabel?: string | null }>} entries the cut's, in order + * @param {Array<{ after: string, label?: string }>} [markers] render.chrome.deck.markers + * @returns {Array<{ before: string, index: number, date: string | null, label: string | null }>} + */ +export function seamsOf(entries, markers = []) { + const list = entries ?? []; + /** @type {Map<number, string | null>} */ + const at = new Map(); + let prev; + list.forEach((e, i) => { + if (e.type !== "clip") return; + const s = e.section; + if (s !== undefined && s !== null && prev !== undefined && s !== prev && i > 0) at.set(i, null); + if (s !== undefined && s !== null) prev = s; + }); + for (const m of markers ?? []) { + const i = list.findIndex((e) => e.id === m?.after); + if (i >= 0 && i + 1 < list.length) at.set(i + 1, typeof m.label === "string" && m.label ? m.label : (at.get(i + 1) ?? null)); + } + return [...at.entries()] + .sort((a, b) => a[0] - b[0]) + .map(([i, label]) => ({ + before: list[i].id, + index: i, + date: list.slice(i).find((e) => e.type === "clip" && e.dateLabel)?.dateLabel ?? null, + label, + })); +} + +/** + * The counter as a staircase: for one verdict (or every one, `verdict` + * null), the running total after each stamp lands, in cut order -- + * `[{ t, n }]`, one point per step (stamps landing together are one step). + * + * @param {Array<{ landed: number, verdict: string, count?: number }>} stamps the schedule's factcheck stamps + * @param {string | null} [verdict] + */ +export function counterSteps(stamps, verdict = null) { + const mine = (stamps ?? []).filter((s) => fin(s.landed) && (verdict === null || s.verdict === verdict)).sort((a, b) => a.landed - b.landed); + /** @type {Array<{ t: number, n: number }>} */ + const out = []; + let n = 0; + for (const s of mine) { + n += fin(s.count) ? /** @type {number} */ (s.count) : 1; + const last = out[out.length - 1]; + if (last && last.t === round(s.landed)) last.n = n; + else out.push({ t: round(s.landed), n }); + } + return out; +} + +/** The counter's total at cut second t (the steps that landed by then). */ +export function counterAt(steps, t) { + let n = 0; + for (const s of steps ?? []) if (s.t <= t) n = s.n; + return n; +} + +/** + * The time ruler's ticks: a round step (seconds) that gives at most + * `maxTicks` ticks over the cut, and each tick's second. + * + * @param {number} total + * @param {number} [maxTicks] + */ +export function rulerTicks(total, maxTicks = 12) { + const steps = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600]; + const T = fin(total) && total > 0 ? total : 0; + const step = steps.find((s) => T / s <= maxTicks) ?? steps[steps.length - 1]; + const ticks = []; + for (let t = 0; t <= T + 1e-9; t += step) ticks.push(t); + return { step, ticks }; +} + +/** `m:ss` (or `h:mm:ss`): a ruler's or the running time's label. */ +export function runningTime(t) { + const s = Math.max(0, Math.floor(fin(t) ? t : 0)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const ss = String(s % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${String(m).padStart(2, "0")}:${ss}`; +} + +/** YYYYMMDD → "24 Oct 2020". */ +export function dateKeyLabel(k) { + if (!fin(k)) return null; + const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + const y = Math.floor(k / 10000); + const m = Math.floor((k % 10000) / 100); + const d = k % 100; + return m >= 1 && m <= 12 ? `${d} ${MON[m - 1]} ${y}` : null; +} diff --git a/umtool/lib/report/playCut.test.mjs b/umtool/lib/report/playCut.test.mjs @@ -9,7 +9,10 @@ import test from "node:test"; import { estimateSchedule } from "umtool-report-to-video/deck"; import { liveClock, cutTimeAt } from "./liveClock.mjs"; -import { cutAtSource, cutNotesRequest, cutPlace, inHold, itemIndexAt, playPlan, shownSeconds, sourceAt, startOf } from "./playCut.mjs"; +import { + counterAt, counterSteps, cutAtSource, cutNotesRequest, cutPlace, dateKeyLabel, dateRamp, inHold, itemIndexAt, playPlan, rulerTicks, + runningTime, seamsOf, shownSeconds, sourceAt, startOf, +} from "./playCut.mjs"; const manifest = (transition = 0.5) => ({ slug: "t", @@ -106,14 +109,14 @@ test("a carrying clip's hold: its last frame past its footage", () => { test("Send all open notes: the open notes on this cut (or take), in cut order, with where each was taken", () => { const notes = [ { status: "open", text: "too long here", anchor: { kind: "cut", t: 61.2, entry: "c04", sourceT: 194.2 } }, - { status: "open", text: "start sooner", anchor: { kind: "cut", t: 3.1, entry: "c01" } }, + { status: "open", text: "start sooner", anchor: { kind: "cut", t: 3.1, entry: "c01", ask: "trim" } }, { status: "resolved", text: "done", anchor: { kind: "cut", t: 5 } }, { status: "open", text: "on the take", anchor: { kind: "cut", t: 9, take: "short-19" } }, { status: "open", text: "whole", anchor: { kind: "whole" } }, ]; assert.equal( cutNotesRequest(notes), - "Notes taken while playing the cut, in order:\n1. at 0:03.1, in clip c01: start sooner\n2. at 1:01.2, in clip c04 (source 194.2 s): too long here", + "Notes taken while playing the cut, in order:\n1. at 0:03.1, in clip c01 [trim]: start sooner\n2. at 1:01.2, in clip c04 (source 194.2 s): too long here", ); assert.equal(cutNotesRequest(notes, { take: "short-19" }), "Notes taken while playing take short-19, in order:\n1. at 0:09.0: on the take"); assert.equal(cutNotesRequest(notes.slice(2, 3)), null); @@ -124,3 +127,50 @@ test("Send all open notes: the open notes on this cut (or take), in cut order, w assert.match(req, /more not sent\)$/); assert.equal(cutPlace({ t: 0 }), "at 0:00.0"); }); + +test("the reel strip: the date ramp, the seams, the counter's staircase, the ruler", () => { + const ramp = dateRamp([ + { id: "a", dateKey: 20201024 }, + { id: "b", dateKey: 20241202 }, + { id: "k" }, + { id: "c", dateKey: 20221113 }, + ]); + assert.equal(ramp.get("a"), 0); + assert.equal(ramp.get("b"), 1); + assert.equal(ramp.get("k"), null); + assert.ok(Number(ramp.get("c")) > 0.4 && Number(ramp.get("c")) < 0.6); + assert.equal(dateRamp([{ id: "x", dateKey: 20200101 }]).get("x"), 1); + + const entries = [ + { id: "a", type: "clip", section: 0, dateLabel: "24 Oct 2020" }, + { id: "b", type: "clip", section: 0, dateLabel: "1 Dec 2020" }, + { id: "k", type: "card" }, + { id: "c", type: "clip", section: 1, dateLabel: "13 Nov 2022" }, + { id: "d", type: "clip", section: 1, dateLabel: "2 Dec 2024" }, + ]; + assert.deepEqual(seamsOf(entries), [{ before: "c", index: 3, date: "13 Nov 2022", label: null }]); + assert.deepEqual(seamsOf(entries, [{ after: "a", label: "Rescue" }, { after: "d", label: "past the end" }]), [ + { before: "b", index: 1, date: "1 Dec 2020", label: "Rescue" }, + { before: "c", index: 3, date: "13 Nov 2022", label: null }, + ]); + + const stamps = [ + { landed: 5, verdict: "E", count: 2 }, + { landed: 1, verdict: "E" }, + { landed: 5, verdict: "G" }, + { landed: 9, verdict: "E" }, + ]; + assert.deepEqual(counterSteps(stamps, "E"), [{ t: 1, n: 1 }, { t: 5, n: 3 }, { t: 9, n: 4 }]); + assert.deepEqual(counterSteps(stamps), [{ t: 1, n: 1 }, { t: 5, n: 4 }, { t: 9, n: 5 }]); + assert.equal(counterAt(counterSteps(stamps, "E"), 4.9), 1); + assert.equal(counterAt(counterSteps(stamps, "E"), 5), 3); + assert.equal(counterAt([], 3), 0); + + assert.deepEqual(rulerTicks(8.7), { step: 1, ticks: [0, 1, 2, 3, 4, 5, 6, 7, 8] }); + assert.equal(rulerTicks(1142).step, 120); + assert.equal(rulerTicks(0).ticks.length, 1); + assert.equal(runningTime(581.4), "09:41"); + assert.equal(runningTime(3725), "1:02:05"); + assert.equal(dateKeyLabel(20250227), "27 Feb 2025"); + assert.equal(dateKeyLabel(null), null); +}); diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -9,8 +9,10 @@ // Nothing is fetched or cut here: a clip whose source window is not on disk // is listed with `media: null` and plays as a placeholder. import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video"; -import { deckOn, estimatedDuration, scheduleFrom, transitionOf } from "umtool-report-to-video/deck"; -import { readManifest } from "../projects/report.mjs"; +import { deckOn, estimatedDuration, estimateSchedule, scheduleFrom, transitionOf } from "umtool-report-to-video/deck"; +import { resolveFactcheck } from "umtool-report-to-video/factcheck"; +import { clipDateKey, readManifest } from "../projects/report.mjs"; +import { dateKeyLabel } from "./playCut.mjs"; import { pickWindow, projectCache, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; @@ -54,11 +56,18 @@ export async function playView(project, { take = null } = {}) { const cache = await projectCache(project, manifest); const entries = await Promise.all( timeline.map(async (e) => { - if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e) }; + if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null }; const win = pickWindow(await windowsFor(project, e, cache), null); + const dateKey = clipDateKey(e); + const onscreenDate = text(e.onscreen?.title); return { id: e.id, type: "clip", + // The recording's date (the on-screen date, else the upload date): the reel strip's tint. + dateKey, + dateLabel: dateKey === null ? null : /^\d{1,2}\s+[A-Za-z]{3}/.test(onscreenDate) ? onscreenDate : dateKeyLabel(dateKey), + section: e.section ?? null, + channel: typeof e.channel === "string" ? e.channel : null, heading: text(e.onscreen?.title) || text(e.title) || text(e.quote) || e.id, date: text(e.date) || text(e.onscreen?.title) || null, quote: text(e.quote) || null, @@ -73,8 +82,30 @@ export async function playView(project, { take = null } = {}) { }; }), ); + // The counter (the deck's tally): each stamp's landing second and count on + // the estimate's clock, and each verdict's word -- the reel strip's + // staircase before (or without) the chrome's own schedule. + let counter = { verdicts: /** @type {Array<{ id: string, label: string }>} */ ([]), stamps: /** @type {Array<{ landed: number, verdict: string, count: number }>} */ ([]) }; + try { + const est = estimateSchedule(selected); + const stamps = (est?.factcheck?.stamps ?? []).filter((x) => fin(x.landed)); + const words = /** @type {Record<string, { label: string }>} */ (resolveFactcheck(render).verdicts ?? {}); + const ids = [...new Set(stamps.map((x) => String(x.verdict)))]; + counter = { + verdicts: ids.map((id) => ({ id, label: words[id]?.label ?? id })), + stamps: stamps.map((x) => ({ landed: x.landed, verdict: String(x.verdict), count: fin(x.count) ? x.count : 1 })), + }; + } catch { + // A cut the deck cannot schedule counts nothing on the strip. + } + const markers = Array.isArray(render.chrome?.deck?.markers) + ? render.chrome.deck.markers.filter((m) => m && typeof m.after === "string").map((m) => ({ after: m.after, label: typeof m.label === "string" ? m.label : "" })) + : []; return { project: project.id, + title: text(manifest.title) || project.id, + counter, + markers, take: takeInfo, note, takes: await playableTakes(project.dir),