"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { useSharedNotes } from "@/components/notes/NotesProvider";
import { NoteThread } from "@/components/notes/NoteThread";
import type { CutAsk, Note } from "@/lib/annotations/types";
import { reelPlayHref, reelWalkHref, takesHref, trailerHref } from "@/lib/hrefs";
import { cn } from "@/lib/utils";
import { SourceBanner } from "./ReelSource";
import { clock, itemAt, masterAt, masterOfSource, masterSrc, reelAtMaster, readReelView, reelItems, sourceClock, sourceOfMaster, type ReelRow, type ReelView } from "./reelTypes";
import { useReelPlayer } from "./useReelPlayer";
// ---------------------------------------------------------------------------
// A BEAT REEL'S PLAY VIEW (`/projects/
/trailer/play?reel=&take=`, lane
// beat-reels): the reel's beats played back to back from the chosen take's
// RENDERED MASTER -- the master's own frames, so the deck's chrome is the
// final render's and nothing is built (the preview is seeks). Each beat is the
// span `umtool trailer` cuts (lib/report/reelPlay.mjs, the trailer's own
// planTrailer, the edges as written), the trailer's crossfade dissolved in the
// browser (useReelPlayer.ts), the running clock against the platform limit.
//
// The Play view's keys: Space play/pause, K pause, N/P the next/previous beat,
// ←/→ two seconds, [ ] the previous/next note, M a note on the beat on screen,
// E walk this beat (the bench over it, on the master's frames), ? the keys.
// A note is anchored to the beat (kind "reel": the reel, the beat, the reel
// second, the master second, the clip and its source second, the take);
// `umtool notes ` prints it with the writer that acts on it.
// ---------------------------------------------------------------------------
const SKIP_S = 2;
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: "v" },
{ id: "fact", label: "Fact", key: "f" },
{ id: "look", label: "Look", key: "l" },
{ id: "other", label: "Other", key: "o" },
];
type ReelAnchor = { kind: "reel"; reel: string; beat: number; t: number; masterT?: number; entry?: string; sourceT?: number; take?: string; ask?: CutAsk };
export default function ReelPlay({ initial, initialBeat = null, initialNote = null }: { initial: ReelView; initialBeat?: number | null; initialNote?: string | null }) {
const router = useRouter();
const [view, setView] = useState(initial);
const [error, setError] = useState(null);
const project = view.project;
const reel = view.reel;
const take = view.take?.id ?? null;
const items = useMemo(() => reelItems(view), [view]);
const vids = useRef<(HTMLVideoElement | null)[]>([null, null]);
const player = useReelPlayer(items, view.xfade, vids);
const { t, cur, playing } = player;
const total = view.total ?? 0;
const item = items[cur] ?? null;
const row = item?.row ?? null;
const [videoSeconds, setVideoSeconds] = useState(null);
const reload = useCallback(async () => {
try {
setView(await readReelView(project, reel, take));
setError(null);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
}, [project, reel, take]);
// `?beat=n` (the walk's Back to the reel): start on that beat.
const started = useRef(false);
useEffect(() => {
if (started.current || !items.length) return;
started.current = true;
if (initialBeat) {
const it = items.find((x) => x.n === initialBeat);
if (it) player.seek(it.at + 0.001);
}
}, [items, initialBeat, player]);
const beatIndex = useCallback((d: 1 | -1) => {
const e = player.now();
const i = e.cur + d;
if (d < 0 && items[e.cur] && e.t - items[e.cur].at > 1) return e.cur;
return Math.max(0, Math.min(items.length - 1, i));
}, [items, player]);
const next = useCallback(() => {
const i = beatIndex(1);
if (items[i]) player.seek(items[i].at + (i > 0 && !items[i].seamless ? view.xfade : 0) + 0.001);
}, [beatIndex, items, player, view.xfade]);
const prev = useCallback(() => {
const i = beatIndex(-1);
if (items[i]) player.seek(items[i].at + 0.001);
}, [beatIndex, items, player]);
// ---- the notes ------------------------------------------------------------------
const notes = useSharedNotes({ project });
const mine = useMemo(
() => notes.notes.filter((n) => n.anchor.kind === "reel" && (n.anchor as ReelAnchor).reel === reel),
[notes.notes, reel],
);
/** A note's reel second now: by its clip and source second when a beat still holds it, else by its beat, else its t. */
const noteT = useCallback(
(a: ReelAnchor) => {
if (a.entry && a.sourceT !== undefined) {
const it = items.find((x) => {
const s = x.row?.id === a.entry ? x.row?.piece?.source : null;
return !!s && a.sourceT! >= s.start - 0.05 && a.sourceT! <= s.end + 0.05;
});
const m = it?.row ? masterOfSource(it.row, a.sourceT) : null;
if (it && m !== null) return reelAtMaster(it, m);
}
const byBeat = items.find((x) => x.n === a.beat);
if (byBeat && a.masterT !== undefined && a.masterT >= byBeat.mStart && a.masterT <= byBeat.mEnd) return reelAtMaster(byBeat, a.masterT);
return byBeat ? byBeat.at : a.t;
},
[items],
);
const sorted = useMemo(() => [...mine].sort((a, b) => noteT(a.anchor as ReelAnchor) - noteT(b.anchor as ReelAnchor)), [mine, noteT]);
const [drafting, setDrafting] = useState(null);
const resume = useRef(false);
const noteHere = useCallback(() => {
const e = player.now();
const it = items[e.cur];
if (!it?.row) return;
resume.current = e.playing;
if (e.playing) player.setPlaying(false);
const masterT = masterAt(it, e.t);
const src = sourceOfMaster(it.row, masterT);
setDrafting({
kind: "reel",
reel,
beat: it.n,
t: Math.round(e.t * 100) / 100,
masterT: Math.round(masterT * 100) / 100,
...(it.row.id ? { entry: it.row.id } : {}),
...(src !== null ? { sourceT: Math.round(src * 100) / 100 } : {}),
...(take ? { take } : {}),
});
}, [items, player, reel, take]);
const closeDraft = useCallback(() => {
setDrafting(null);
if (resume.current) {
resume.current = false;
player.setPlaying(true);
}
}, [player]);
const stepNote = useCallback(
(d: 1 | -1) => {
const now = player.now().t;
const ts = sorted.map((n) => noteT(n.anchor as ReelAnchor));
const to = d > 0 ? ts.find((x) => x > now + 0.05) : [...ts].reverse().find((x) => x < now - 0.05);
if (to !== undefined) player.seek(to);
},
[sorted, noteT, player],
);
const sought = useRef(false);
useEffect(() => {
if (sought.current || !initialNote) return;
const n = mine.find((x) => x.id === initialNote);
if (!n) return;
sought.current = true;
player.seek(noteT(n.anchor as ReelAnchor));
}, [initialNote, mine, noteT, player]);
// ---- walk this beat ---------------------------------------------------------------
const walkHere = useCallback(() => {
const it = items[player.now().cur];
if (!it?.row) return;
router.push(reelWalkHref(project, { reel, take, beat: it.n }));
}, [items, player, router, project, reel, take]);
// ---- the keys ----------------------------------------------------------------------
const [help, setHelp] = useState(false);
useEffect(() => {
const onKey = (ev: KeyboardEvent) => {
const tgt = ev.target as HTMLElement | null;
if (ev.key === "Escape") {
setHelp(false);
return;
}
if (tgt && (tgt.closest("input, textarea, select, [contenteditable=true]") || ev.metaKey || ev.ctrlKey || ev.altKey)) return;
const k = ev.key;
if (k === " ") player.setPlaying(!player.now().playing);
else if (k === "k" || k === "K") player.setPlaying(false);
else if (k === "n" || k === "N") next();
else if (k === "p" || k === "P") prev();
else if (k === "ArrowRight") player.seek(player.now().t + SKIP_S);
else if (k === "ArrowLeft") player.seek(player.now().t - SKIP_S);
else if (k === "[") stepNote(-1);
else if (k === "]") stepNote(1);
else if (k === "m" || k === "M") noteHere();
else if (k === "e" || k === "E") walkHere();
else if (k === "?") setHelp((h) => !h);
else return;
ev.preventDefault();
};
const onUp = (ev: KeyboardEvent) => {
const tgt = ev.target as HTMLElement | null;
if (ev.key === " " && !tgt?.closest("input, textarea, select, [contenteditable=true]")) ev.preventDefault();
};
window.addEventListener("keydown", onKey);
window.addEventListener("keyup", onUp);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("keyup", onUp);
};
}, [player, next, prev, stepNote, noteHere, walkHere]);
// ---- no master: said, and the render offered (never started from here) ----------
if (view.noMaster || !take) {
return (
{view.noMaster?.why ?? "no take to play"}
A reel is cut from a rendered take, so it plays only once one is rendered. Nothing renders from here:{" "}
render a take on the Takes page
{view.noMaster?.take ? (
<>
{" "}
({view.noMaster.take} is the newest), or umtool take {project} --id {view.noMaster.take} --rebuild
>
) : null}
, then come back.
{/* What the reel was cut against, and the beats this take changed (ReelSource.tsx). */}
{[0, 1].map((k) => (
{/* ---- the transport ---- */}
{clock(t)} / {clock(total)}
limit {clock(view.limit)} · {over ? over by {(total - view.limit).toFixed(1)} s : `${(view.limit - total).toFixed(1)} s to spare`} · crossfade {view.xfade} s
The master is {videoSeconds?.toFixed(2)} s but its build records describe {view.masterSeconds?.toFixed(2)} s: it is not the build these spans are from (rendered again since?).