commit a0e15e72fc9a85b3e796917d17f558e8a2d787e4
parent 6729ed86d3ed4ca452049385317cd87afa133750
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 10 Nov 2026 09:25:47 -0500
umtool: Play's player core extracted (playCore.tsx: usePlayCore + PlayStage) -- one player for Play and the workspace
The composition, the plan, the teasers' and the intro's pages, the engine and its gate, the post items fetched
ahead and what is on screen now move out of PlayCut into usePlayCore; the picture (the two <video> slots, the
deck or the plain frame, every card's player, the overlays) into <PlayStage core/>. PlayCut keeps everything a
page adds: the transport, the notes, the reel strip, the keys, the place in the URL. No behaviour change, but one:
a cut switched to Basic under the page drops the deck it composed (the workspace's Look switch).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
2 files changed, 535 insertions(+), 447 deletions(-)
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -9,18 +9,13 @@ import { NoteThread } from "@/components/notes/NoteThread";
import type { Anchor, CutAsk, Note } from "@/lib/annotations/types";
import { clipBenchHref, ingredientHref, openInDraftHref, postBenchHref } 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 {
- chromeTime, counterSteps, cutAtSource, cutNotesRequest, playPlan, playTimeOfChrome, runningTime, seamsOf, skipEntries, sourceAt, startOf,
+ counterSteps, cutAtSource, cutNotesRequest, playPlan, playTimeOfChrome, runningTime, seamsOf, sourceAt, startOf,
} from "@/lib/report/playCut.mjs";
-import { tallyCellsFrom, VERDICTS } from "umtool-report-to-video/factcheck";
import { AssistReplyApply, ProposalList, routeLine, jobLine, useAssist } from "../report/AssistBox";
-import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
-import { usePlayEngine } from "./playEngine/usePlayEngine";
-import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts";
-import type { EngineInfo, ItemGate, MediaRef } from "./playEngine/engine";
-import { postPreload } from "./playEngine/postPreload";
+import type { RenderCuts } from "./playEngine/useRenderCuts";
+import type { EngineInfo, MediaRef } from "./playEngine/engine";
+import { PlayStage, usePlayCore } from "./playCore";
import ReelStrip, { type StripCounter, type StripEdit } from "./ReelStrip";
import { useWaveZoom, ZoomControls } from "../bench/GapsZoom";
import { followVis, itemSections } from "@/lib/report/stripDrag.mjs";
@@ -32,14 +27,9 @@ import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExpor
import AddPost from "./AddPost";
import { AddClipToggle } from "../AddClip";
import { Options, PanelSlot } from "@/components/ui/disclosure";
-import PostItemPlayer, { postItemAssets, type PostPlan } from "./PostItemPlayer";
-import SidePostOverlay from "./SidePostOverlay";
-import VideoEntryPlayer from "./VideoEntryPlayer";
-import TeaserCardPlayer, { type TeaserPage } from "./TeaserCardPlayer";
-import IntroCardPlayer from "./IntroCardPlayer";
-import { useIntroPage } from "./useIntroPage";
-import { videoStageAt, type VideoEntryPlay } from "@/lib/report/playVideo.mjs";
-import ComboBadge, { type ComboInfo } from "./ComboBadge";
+import type { PostPlan } from "./PostItemPlayer";
+import type { VideoEntryPlay } from "@/lib/report/playVideo.mjs";
+import type { ComboInfo } from "./ComboBadge";
import CopyShareLine from "../CopyShareLine";
import { StillButton } from "../inspector/StillInspector";
@@ -179,13 +169,6 @@ export type PlayViewData = {
entries: PlayEntry[];
};
-type LiveDoc = DeckPreviewDoc & {
- leadIn?: number;
- verdictLabels?: Record<string, string>;
- tallyOrder?: string[];
- tallyAlways?: string[];
- 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" }>;
@@ -200,10 +183,6 @@ const PAUSE_KEY = "umtool.play.pauseWhileWriting";
/** "on": play the clips the walk rejected too (for re-review); absent or "off": skip them. */
// The key keeps its old name: a browser that chose "show" before rejections had reasons still has.
const SHOW_REJECTED_KEY = "umtool.play.showIncorrect";
-/** Play's "As published": post cards drawn with their redacted words as bars (post-redact.mjs). Per browser. */
-const AS_PUBLISHED_KEY = "umtool.play.asPublished";
-/** And which cut: censored (the slur filter on, post-slurs.mjs) or the uncensored one. Per browser. */
-const UNCENSORED_KEY = "umtool.play.uncensored";
/** 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 }[] = [
@@ -264,16 +243,6 @@ function approximateLine(edges: RenderCuts, info: EngineInfo | null) {
].filter(Boolean).join(" ");
}
-/**
- * POST ITEMS FETCHED AHEAD (postPreload.ts; operator, 4 Nov: "the rapid sections ... don't load fast enough"):
- * the post items whose start is within this many cut seconds after the one on screen -- at least PRELOAD_MIN of
- * them, at most PRELOAD_MAX -- so a burst of short items has many ahead, a slow stretch a few.
- */
-const PRELOAD_AHEAD_S = 20;
-const PRELOAD_MIN = 3;
-const PRELOAD_MAX = 24;
-/** The clock never waits longer than this on one item (a page that never says it is ready). */
-const GATE_MAX_MS = 15_000;
/** The pinned player as a strip, once the transport is under it (a phone). */
const STRIP_H = 120;
@@ -328,102 +297,11 @@ export default function PlayCut({
// Export clip (ClipExport.tsx): the clip at the playhead -- or the one a note points at -- clean, into exports/.
const clipExport = useClipExport(project, take);
- // ---- the composition (the live preview's) ---------------------------------
- const [doc, setDoc] = useState<LiveDoc | null>(null);
- const [composeState, setComposeState] = useState<"composing" | "ready" | "no-deck" | "error">(view.deckOn ? "composing" : "no-deck");
- const [composeError, setComposeError] = useState<string | null>(null);
- const seq = useRef(0);
- const compose = useCallback(async () => {
- const mine = ++seq.current;
- setComposeState("composing");
- try {
- const r = await fetch("/api/report/chrome/preview", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ project, estimate: true, ...(take ? { take } : {}) }),
- });
- const j = (await r.json().catch(() => ({}))) as LiveDoc & { error?: string; deckOn?: boolean };
- if (mine !== seq.current) return;
- if (!r.ok) {
- setDoc(null);
- setComposeState(j.deckOn === false ? "no-deck" : "error");
- setComposeError(j.deckOn === false ? null : String(j.error ?? `HTTP ${r.status}`));
- } else {
- setDoc(j);
- setComposeState("ready");
- setComposeError(null);
- }
- } catch (e) {
- if (mine === seq.current) {
- setComposeState("error");
- setComposeError(e instanceof Error ? e.message : String(e));
- }
- }
- }, [project, take]);
- useEffect(() => {
- if (view.deckOn) void compose();
- }, [compose, view.deckOn]);
-
- // ---- the plan ----------------------------------------------------------------
- // The composed schedule, while it is the cut's ORDER: a reorder (the strip's drop) re-reads the
- // view at once, and until the deck is composed again its segments would play the old order --
- // so the estimate's (the view's own, in the new order) stand in meanwhile.
- const composedOrder = doc?.schedule?.segments?.map((x) => x.id).join("\n") ?? null;
- const viewOrder = useMemo(() => view.segments.map((x) => x.id).join("\n"), [view.segments]);
- const scheduleNow = composedOrder !== null && composedOrder === viewOrder;
- const schedule = scheduleNow ? (doc?.schedule ?? null) : null;
- const segments = schedule?.segments ?? view.segments;
- const leadIn = doc?.leadIn ?? view.leadIn;
- // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change.
- const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd, e.gaps ?? null])), [view.entries]);
- const edges = useRenderCuts(project, take, edgesKey);
+ // ---- the player core (playCore.tsx: the composition, the plan, the engine, what is on screen) ----
// Clips the walk REJECTED (a fact error, or irrelevant, weak, …) are SKIPPED
// unless asked for: the cut the operator means to ship does not hold them
// (umtool check blocks on a fact error and lists the rest). Remembered per browser.
const [showRejected, setShowRejected] = useState(false);
- const [asPublished, setAsPublished] = useState(false);
- const [uncensored, setUncensored] = useState(false);
- useEffect(() => {
- try {
- if (window.localStorage.getItem(AS_PUBLISHED_KEY) === "on") setAsPublished(true);
- if (window.localStorage.getItem(UNCENSORED_KEY) === "on") setUncensored(true);
- } catch {
- // A preference, not state.
- }
- }, []);
- const hasPosts = useMemo(() => view.entries.some((e) => e.type === "post"), [view.entries]);
- const hasVideoEntries = useMemo(() => view.entries.some((e) => e.type === "video" && !!e.videoEntry), [view.entries]);
- // THE TEASERS (lane leaflit-labels): each text card's own page, composed for preview (POST
- // /api/report/chrome/teasers) and laid full frame while it is on screen -- the build's card, not a placeholder.
- // Composed again whenever the manifest moved (its token), with or without a deck.
- const teaserKey = useMemo(() => view.entries.filter((e) => e.type === "teaser").map((e) => e.id).join("\n"), [view.entries]);
- // THE INTRO (lane intro-play): its page composed for preview (POST /api/report/chrome/intro), again when the manifest moved.
- const introPage = useIntroPage(project, take, view.entries.some((e) => e.type === "intro"), view.token);
- const [teaserPages, setTeaserPages] = useState<Record<string, TeaserPage | { id: string; error: string }>>({});
- useEffect(() => {
- if (!teaserKey) {
- setTeaserPages({});
- return;
- }
- let live = true;
- void (async () => {
- try {
- const r = await fetch("/api/report/chrome/teasers", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ project, ...(take ? { take } : {}) }),
- });
- const j = (await r.json().catch(() => ({}))) as { teasers?: (TeaserPage | { id: string; error: string })[]; error?: string };
- if (!live) return;
- setTeaserPages(Object.fromEntries((j.teasers ?? []).map((x) => [x.id, x])));
- } catch {
- if (live) setTeaserPages({});
- }
- })();
- return () => {
- live = false;
- };
- }, [project, take, teaserKey, view.token]);
useEffect(() => {
try {
// The URL first (Back from the bench lands on the URL Play left), then this browser's choice.
@@ -435,65 +313,9 @@ export default function PlayCut({
// No storage: skipped, the default.
}
}, []);
- const rejected = useMemo(() => view.entries.filter((e) => e.rejected), [view.entries]);
- const skipIds = useMemo(() => new Set(showRejected ? [] : rejected.map((e) => e.id)), [showRejected, rejected]);
- const plan = useMemo(
- () => skipEntries(playPlan(segments, view.entries, { leadIn, cuts: edges.cuts }), skipIds),
- [segments, view.entries, leadIn, edges.cuts, skipIds],
- );
- const entryOf = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
- const planRef = useRef(plan);
- planRef.current = plan;
-
- // ---- the engine (playEngine/: the sound on one Web Audio clock, the picture slaved to it) ----
- const bg = doc?.background ?? "#000";
- // `v` (the version of the window's bytes, playView): a window refetched under its old name is a new URL.
- const srcOf = useCallback(
- (id: string, m: MediaRef) =>
- `/api/report/raw?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file: m.name, ...(m.v ? { v: m.v } : {}) }).toString()}`,
- [project, take],
- );
- const audioOf = useCallback(
- (id: string, m: MediaRef, from: number, to: number) =>
- `/api/report/audio?${new URLSearchParams({
- project, clip: id, ...(take ? { take } : {}), file: m.name, from: String(from), to: String(to), ...(m.v ? { v: m.v } : {}),
- }).toString()}`,
- [project, take],
- );
- // THE GATE (engine.ts): a post item plays once its player is ready -- its card drawn, its voice and its first
- // attachment able to play -- and the clock waits on it, never cutting it short (a buffer stall's wait). Fetched
- // ahead (postPreload.ts), its player is ready the frame its card is drawn; the clock holds on the item before
- // while it is still fetching. `postReady`: what the MOUNTED player said (one at a time; "gone" as it unmounts).
- // `started`: the item on screen once it has played -- a player mounted again under it (the deck composed) is not
- // waited for (the clock runs on, as it always did).
- const entryOfRef = useRef(entryOf);
- entryOfRef.current = entryOf;
- const postReady = useRef<string | null>(null);
- const started = useRef<string | null>(null);
- const gateAsked = useRef(new Map<string, number>());
- const gate = useCallback<ItemGate>((id, next) => {
- const e = entryOfRef.current.get(id);
- if (!(e?.type === "post" && e.post && e.postPlan)) return "ready";
- const now = performance.now();
- const key = `${next ? "next" : "on"}:${id}`;
- let since = gateAsked.current.get(key);
- if (since === undefined) gateAsked.current.set(key, (since = now));
- if (now - since > GATE_MAX_MS) return "ready";
- if (next) return postPreload.itemState(id) === "loading" ? "fetching" : "ready";
- if (started.current === id) return "ready";
- if (postReady.current !== id) return "wait";
- started.current = id;
- return "ready";
- }, []);
- const onPostReady = useCallback((id: string, state: "ready" | "gone") => {
- if (state !== "gone") postReady.current = id;
- else if (postReady.current === id) postReady.current = null;
- }, []);
- const engine = usePlayEngine({
- plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring", gate,
- });
+ const core = usePlayCore(view, { showRejected });
+ const { doc, composeState, composeError, compose, schedule, edges, plan, planRef, entryOf, rejected, skipIds, hasPosts, engine, asPublished, setAsPublished, uncensored, setUncensored } = core;
const { ui, rate, failed, now } = engine;
- const setDuck = engine.setDuck;
const setRate = engine.setRate;
// `?clip=&at=` (back from the clip bench): that clip, that far in -- the
@@ -588,14 +410,6 @@ export default function PlayCut({
setPlaying(false);
void reloadView();
}, [reloadView, setPlaying]);
- // The deck is composed again whenever the manifest moved (its token): a Reject, a reorder, an
- // Apply, the bench's save seen on the way back -- once, however the view came to be re-read.
- const composedFor = useRef(view.token);
- useEffect(() => {
- if (view.token === composedFor.current) return;
- composedFor.current = view.token;
- if (view.deckOn) void compose();
- }, [view.token, view.deckOn, compose]);
// Hidden under the bench (the one app), Play does not play on; shown again, it finds the clip it
// left by its id and the source second (an edit on the bench may have moved it in the cut).
const leftAt = useRef<{ clip: string; at: number; t: number } | null>(null);
@@ -918,86 +732,8 @@ export default function PlayCut({
};
}, [back, help, lPlay, next, prev, skip, stepNote, noteHere, editHere, setPlaying, now, zoom, curSpan]);
- // ---- what is on screen -------------------------------------------------------------
- const t = ui.t;
- // The chrome was composed on the estimate's clock: seeked by the source second playing.
- const tc = chromeTime(plan, t);
- const item = plan.items[ui.cur] ?? null;
- const entry = item ? entryOf.get(item.id) : null;
- const g = doc?.geometry ?? null;
- const box: Rect | null = g ? (doc?.feed?.footage ?? g.footage) : null;
- const move = schedule ? footageAt(schedule, tc) : null;
- const rect: Rect | null = move?.rect ?? box;
- const order = useMemo(
- () => (schedule?.factcheck ? tallyCellsFrom(schedule.factcheck.stamps, doc?.tallyOrder ?? VERDICTS, doc?.tallyAlways ?? []) : []),
- [schedule, doc?.tallyOrder, doc?.tallyAlways],
- );
- const tally = schedule?.factcheck ? tallyAt(schedule, tc, order) : [];
- const stamp = schedule ? stampAt(schedule, tc) : null;
- const finaleNow = !!schedule && finaleUp(schedule, tc);
- const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, tc) : null;
- const missing = !!item?.clip && !entry?.media;
- const broken = !!item && !!failed[item.id];
- // A post item plays its card and attachments (PostItemPlayer), not a placeholder.
- const postNow = item && entry?.type === "post" && entry.post && entry.postPlan ? { item, entry } : null;
- // A VIDEO entry (lib/report/playVideo.mjs): its file, the whole frame -- and the item before it darkening into it.
- const vstage = hasVideoEntries ? videoStageAt(plan, entryOf, t) : null;
- const videoNow = vstage?.video ? { ...vstage, video: vstage.video } : null;
- // A teaser plays its own page (TeaserCardPlayer), once composed; until then -- or if it did not compose -- a placeholder.
- const teaserPage = item && entry?.type === "teaser" ? teaserPages[item.id] : undefined;
- const teaserNow = item && teaserPage && "src" in teaserPage ? { item, page: teaserPage } : null;
- // THE INTRO (lane intro-play): the build's own page and its sound (IntroCardPlayer), once composed; until then -- or if
- // it did not compose -- a placeholder that says so.
- const introNow = item && entry?.type === "intro" && introPage && "src" in introPage ? { item, page: introPage } : null;
- const placeholder = item && !postNow && !videoNow && !teaserNow && !introNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
- // The clips' sound fades with the picture into a video entry and is off over it (its element plays its own).
- const duck = vstage ? vstage.duck : 1;
- useEffect(() => {
- if (hasVideoEntries) setDuck(duck);
- }, [hasVideoEntries, duck, setDuck]);
- const pct = (n: number, of: number) => `${(n / of) * 100}%`;
- // A clip's side post (lane vertical): its card over the clip for the side's span (SidePostOverlay).
- const sideEntry = item && entry?.type === "clip" ? (entry as { side?: { from: number; to: number; place?: string | null } }).side : undefined;
- const sideNow = item && sideEntry ? <SidePostOverlay project={project} take={take} clipId={item.id} side={sideEntry} s={Math.max(0, t - item.start)} published={asPublished} /> : null;
-
- // ---- post items fetched ahead (postPreload.ts): from the one on screen, ~20 s on --------------------------
- const postBox = box ? { width: box.width, height: box.height } : { width: 1920, height: 1080 };
- const postBoxKey = `${Math.round(postBox.width)}x${Math.round(postBox.height)}`;
- useEffect(() => {
- // A new item on screen: its gate is asked afresh (a revisit waits as the first visit did).
- gateAsked.current.clear();
- }, [ui.cur, plan]);
- // Another item on screen: the one before is no longer "started" (a revisit waits as the first visit did).
- const curId = plan.items[ui.cur]?.id ?? null;
- useEffect(() => {
- if (started.current !== curId) started.current = null;
- }, [curId]);
- useEffect(() => {
- // Not while the deck composes: its pages would be fetched at the plain frame's size (the deck's box is
- // another URL), and the requests would queue ahead of the composition itself.
- if (composeState === "composing") return;
- const items = plan.items;
- const i = ui.cur;
- const [w, h] = postBoxKey.split("x").map(Number);
- const assetsOf = (k: number) => {
- const it = items[k];
- const e = it ? entryOf.get(it.id) : null;
- if (!e || e.type !== "post" || !e.post || !e.postPlan) return null;
- const before = k > 0 ? entryOf.get(items[k - 1]?.id ?? "") : null;
- const joinFrom = e.postPlan.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan } : null;
- return postItemAssets({ project, take, entry: e.post, plan: e.postPlan, box: { width: w, height: h }, published: asPublished, uncensored, joinFrom });
- };
- const keep = [i - 1, i].map(assetsOf).filter((x): x is NonNullable<typeof x> => !!x);
- const ahead: NonNullable<ReturnType<typeof assetsOf>>[] = [];
- const from = items[i]?.to ?? 0;
- for (let k = i + 1, n = 0; k < items.length && ahead.length < PRELOAD_MAX; k += 1, n += 1) {
- if (items[k].from - from > PRELOAD_AHEAD_S && n >= PRELOAD_MIN) break;
- const a = assetsOf(k);
- if (a) ahead.push(a);
- }
- postPreload.want(ahead, keep);
- }, [ui.cur, plan, entryOf, project, take, asPublished, uncensored, postBoxKey, composeState]);
- useEffect(() => () => postPreload.clear(), []);
+ // ---- what is on screen (the core's) ----------------------------------------------
+ const { t, item, entry, tally, stamp, finaleNow, broken, postNow, videoNow } = core;
// The reel strip's counter: the composed schedule's stamps when there is one, else the estimate's.
const counters = useMemo<StripCounter[]>(() => {
@@ -1012,99 +748,6 @@ export default function PlayCut({
const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: noteT(n.anchor as CutAnchor), text: n.text, open: n.status === "open" })), [mine, noteT, plan]);
const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
- const postPlayer = (box2: { width: number; height: number }) =>
- postNow ? (
- <PostItemPlayer
- key={postNow.item.id}
- project={project}
- take={take}
- entry={postNow.entry.post!}
- plan={postNow.entry.postPlan!}
- box={box2}
- s={Math.max(0, t - postNow.item.start)}
- playing={ui.playing && !ui.waiting}
- speed={rate}
- published={asPublished}
- uncensored={uncensored}
- scene={postNow.entry.postScene ?? null}
- clock={postNow.entry.postClock ?? null}
- onReady={onPostReady}
- progress={postNow.entry.postProgress ?? null}
- joinFrom={(() => {
- // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended.
- const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null;
- return postNow.entry.postPlan?.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan, clock: before.postClock ?? null } : null;
- })()}
- />
- ) : null;
- // A post item that repeats an earlier one's attachment: its combo badge, beside the player.
- const comboBadge = (box2: { width: number; height: number }) =>
- postNow?.entry.postCombo ? (
- <ComboBadge
- key={`combo-${postNow.item.id}`}
- project={project}
- entry={postNow.entry.post!}
- plan={postNow.entry.postPlan!}
- combo={postNow.entry.postCombo}
- box={box2}
- s={Math.max(0, t - postNow.item.start)}
- playing={ui.playing && !ui.waiting}
- />
- ) : null;
- // The video on screen: over EVERYTHING when the chrome is off over it (the default), else as the footage under it.
- const videoPlayer = videoNow ? (
- <VideoEntryPlayer
- key={videoNow.id}
- project={project}
- id={videoNow.id}
- video={videoNow.video}
- src={videoNow.src ?? videoNow.video.from}
- opacity={videoNow.opacity}
- run={ui.playing && !ui.waiting && videoNow.playing}
- speed={rate}
- />
- ) : null;
- const videoOver = videoNow?.video.noChrome ? <div className="pointer-events-none absolute inset-0 z-30">{videoPlayer}</div> : null;
- const videoUnder = videoNow && !videoNow.video.noChrome ? videoPlayer : null;
- // The item before a video entry, darkening into it: the whole stage, its chrome with it.
- const dipVeil = vstage && vstage.dark > 0 ? <div data-play-dip={vstage.id} className="pointer-events-none absolute inset-0 z-30 bg-black" style={{ opacity: vstage.dark }} /> : null;
- // A teaser on screen: its page, seeked to the seconds into the card (the item's own clock, as a post item's).
- const teaserCard = teaserNow ? <TeaserCardPlayer key={teaserNow.item.id} page={teaserNow.page} s={t - teaserNow.item.start} /> : null;
- // The intro on screen: its page seeked to the seconds into it, its sound on Play's clock.
- const introCard = introNow ? <IntroCardPlayer key={introNow.page.src} page={introNow.page} s={t - introNow.item.start} playing={ui.playing && !ui.waiting} speed={rate} /> : null;
- 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.5 p-6 text-center"
- style={{ background: placeholder.kind === "card" ? bg : "transparent" }}
- >
- {placeholder.kind === "card" ? (
- <>
- <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">
- {teaserPage && "error" in teaserPage
- ? `the card did not compose: ${teaserPage.error}`
- : placeholder.item.type === "teaser"
- ? "composing the card…"
- : placeholder.item.type === "intro"
- ? introPage && "error" in introPage
- ? `the intro did not compose: ${introPage.error}`
- : "composing the intro…"
- : "a placeholder: the build draws it"}
- </span>
- </>
- ) : (
- <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>
- ) : null;
// ---- the phone: the pinned player --------------------------------------------------
// Pinned at full width; a strip (the picture left, where it is right) once
@@ -1152,9 +795,6 @@ export default function PlayCut({
}, [isPhone]);
const dockBtn = cn(buttonVariants({ variant: "outline", size: "md" }), "h-12 min-w-0 px-1 text-[13px]");
- const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => (
- <canvas ref={engine.canvasRef} 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 (
@@ -1240,63 +880,7 @@ export default function PlayCut({
: { maxWidth: PLAYER_MAX_W }
}
>
- <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
- <video ref={engine.slotRef0} data-play-slot="0" preload="auto" playsInline muted onError={() => engine.onMediaError(0)} className="absolute inset-0 h-full w-full" />
- <video ref={engine.slotRef1} data-play-slot="1" preload="auto" playsInline muted onError={() => engine.onMediaError(1)} className="absolute inset-0 h-full w-full" />
- </div>
- <div className="relative">
- {doc && g && box ? (
- <DeckFrame preview={doc} t={tc} 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)}
- {videoUnder}
- {postNow && rect && (
- <div className="absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H), background: bg }}>
- {postPlayer({ width: box.width, height: box.height })}
- {comboBadge({ width: box.width, height: box.height })}
- </div>
- )}
- {teaserCard}
- {introCard}
- {placeholderCard}
- {sideNow && rect && <div className="pointer-events-none absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) }}>{sideNow}</div>}
- {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={tc} testid="play-feed" />}
- {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />}
- {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={tc} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />}
- {/* Every module that declares `play` (chapters, then and now, the status ledger …), by z. */}
- <ModuleLayers layers={doc.layers} frame={g} t={tc} testid="play-layer" />
- {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={tc} ready="finale:ready" testid="play-finale" name="finale" />
- </div>
- )}
- </DeckFrame>
- ) : (
- <div
- className="relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0"
- style={{ aspectRatio: "16 / 9" }}
- data-testid="play-plain"
- // A basic cut: the bare footage, as the basic render cuts it -- no card, no side post, nothing over it.
- data-play-bare={view.basic ? "" : undefined}
- >
- {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
- {!view.basic && postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>}
- {!view.basic && videoUnder}
- {!view.basic && teaserCard}
- {!view.basic && introCard}
- {!view.basic && placeholderCard}
- {!view.basic && sideNow}
- </div>
- )}
- {dipVeil}
- {videoOver}
- {ui.playing && ui.waiting && (
- // The clock held (engine.ts): a clip's sound decoding, a post item loading -- it plays in full once here.
- <span data-play-loading="" className="pointer-events-none absolute right-2 top-2 z-40 rounded-full bg-black/70 px-2 py-0.5 text-[11px] text-white">
- loading…
- </span>
- )}
- </div>
+ <PlayStage core={core} basic={!!view.basic} />
{/* The strip's right side (a phone): where you are. */}
{compact && (
<div data-play-strip-side="" className="absolute left-full top-0 flex h-full w-[calc(100vw-213px)] flex-col justify-center gap-0.5 bg-ground px-3 md:hidden">
@@ -1342,15 +926,7 @@ export default function PlayCut({
type="checkbox"
data-play-as-published=""
checked={asPublished}
- onChange={(ev) => {
- const on = ev.target.checked;
- setAsPublished(on);
- try {
- window.localStorage.setItem(AS_PUBLISHED_KEY, on ? "on" : "off");
- } catch {
- // A preference, not state.
- }
- }}
+ onChange={(ev) => setAsPublished(ev.target.checked)}
/>
{asPublished ? (uncensored ? "As published (uncensored)" : "As published (censored)") : "As published"}
</label>
@@ -1361,15 +937,7 @@ export default function PlayCut({
type="checkbox"
data-play-uncensored=""
checked={uncensored}
- onChange={(ev) => {
- const on = ev.target.checked;
- setUncensored(on);
- try {
- window.localStorage.setItem(UNCENSORED_KEY, on ? "on" : "off");
- } catch {
- // A preference, not state.
- }
- }}
+ onChange={(ev) => setUncensored(ev.target.checked)}
/>
Uncensored
</label>
diff --git a/umtool/components/projects/review/playCore.tsx b/umtool/components/projects/review/playCore.tsx
@@ -0,0 +1,520 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { footageAt } from "@/lib/report/footage-move.mjs";
+import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
+import { chromeTime, playPlan, skipEntries } from "@/lib/report/playCut.mjs";
+import { tallyCellsFrom, VERDICTS } from "umtool-report-to-video/factcheck";
+import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
+import { usePlayEngine } from "./playEngine/usePlayEngine";
+import { useRenderCuts } from "./playEngine/useRenderCuts";
+import type { ItemGate, MediaRef } from "./playEngine/engine";
+import { postPreload } from "./playEngine/postPreload";
+import PostItemPlayer, { postItemAssets } from "./PostItemPlayer";
+import SidePostOverlay from "./SidePostOverlay";
+import VideoEntryPlayer from "./VideoEntryPlayer";
+import TeaserCardPlayer, { type TeaserPage } from "./TeaserCardPlayer";
+import IntroCardPlayer from "./IntroCardPlayer";
+import { useIntroPage } from "./useIntroPage";
+import { videoStageAt } from "@/lib/report/playVideo.mjs";
+import ComboBadge from "./ComboBadge";
+import type { PlayEntry, PlayViewData } from "./PlayCut";
+
+// ---------------------------------------------------------------------------
+// THE PLAYER CORE, extracted from PlayCut (umtool redesign L7a): what plays the
+// draft -- or a version -- in the browser in its final look, with no render,
+// and nothing else. Play (PlayCut.tsx) and the workspace (workspace/Workspace.tsx)
+// both draw it; neither forks it.
+//
+// usePlayCore(view) the composition (the live preview's deck, POST
+// /api/report/chrome/preview), the plan (the estimate's
+// segments re-timed by the render's edges), the teasers'
+// and the intro's pages, the engine (one Web Audio clock,
+// the picture slaved to it), the post items' gate and
+// their fetching ahead -- and what is on screen now.
+// <PlayStage core/> the picture: the two <video> slots under the frame, the
+// deck (or the plain 16:9 frame), every card's player,
+// the overlays, the dip into a video entry.
+//
+// Everything a caller adds -- the transport, the notes, the strip, the keys,
+// the place in the URL -- is the caller's: the core does not know which page it
+// is on. PlayCut's own header comment is still the design of what plays.
+// ---------------------------------------------------------------------------
+
+export type LiveDoc = DeckPreviewDoc & {
+ leadIn?: number;
+ verdictLabels?: Record<string, string>;
+ tallyOrder?: string[];
+ tallyAlways?: string[];
+ schedule: DeckPreviewDoc["schedule"] & { finale?: { from: number; to: number } };
+};
+
+/** Play's "As published": post cards drawn with their redacted words as bars (post-redact.mjs). Per browser. */
+const AS_PUBLISHED_KEY = "umtool.play.asPublished";
+/** And which cut: censored (the slur filter on, post-slurs.mjs) or the uncensored one. Per browser. */
+const UNCENSORED_KEY = "umtool.play.uncensored";
+
+/**
+ * POST ITEMS FETCHED AHEAD (postPreload.ts; operator, 4 Nov: "the rapid sections ... don't load fast enough"):
+ * the post items whose start is within this many cut seconds after the one on screen -- at least PRELOAD_MIN of
+ * them, at most PRELOAD_MAX -- so a burst of short items has many ahead, a slow stretch a few.
+ */
+const PRELOAD_AHEAD_S = 20;
+const PRELOAD_MIN = 3;
+const PRELOAD_MAX = 24;
+/** The clock never waits longer than this on one item (a page that never says it is ready). */
+const GATE_MAX_MS = 15_000;
+
+const remember = (key: string, on: boolean) => {
+ try {
+ window.localStorage.setItem(key, on ? "on" : "off");
+ } catch {
+ // A preference, not state.
+ }
+};
+
+export function usePlayCore(view: PlayViewData, { showRejected = false }: { showRejected?: boolean } = {}) {
+ const project = view.project;
+ const take = view.take?.id ?? null;
+
+ // ---- the composition (the live preview's) ---------------------------------
+ const [doc, setDoc] = useState<LiveDoc | null>(null);
+ const [composeState, setComposeState] = useState<"composing" | "ready" | "no-deck" | "error">(view.deckOn ? "composing" : "no-deck");
+ const [composeError, setComposeError] = useState<string | null>(null);
+ const seq = useRef(0);
+ const compose = useCallback(async () => {
+ const mine = ++seq.current;
+ setComposeState("composing");
+ try {
+ const r = await fetch("/api/report/chrome/preview", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, estimate: true, ...(take ? { take } : {}) }),
+ });
+ const j = (await r.json().catch(() => ({}))) as LiveDoc & { error?: string; deckOn?: boolean };
+ if (mine !== seq.current) return;
+ if (!r.ok) {
+ setDoc(null);
+ setComposeState(j.deckOn === false ? "no-deck" : "error");
+ setComposeError(j.deckOn === false ? null : String(j.error ?? `HTTP ${r.status}`));
+ } else {
+ setDoc(j);
+ setComposeState("ready");
+ setComposeError(null);
+ }
+ } catch (e) {
+ if (mine === seq.current) {
+ setComposeState("error");
+ setComposeError(e instanceof Error ? e.message : String(e));
+ }
+ }
+ }, [project, take]);
+ useEffect(() => {
+ if (view.deckOn) void compose();
+ }, [compose, view.deckOn]);
+ // The deck is composed again whenever the manifest moved (its token): a Reject, a reorder, an
+ // Apply, the bench's save seen on the way back -- once, however the view came to be re-read.
+ const composedFor = useRef(view.token);
+ useEffect(() => {
+ if (view.token === composedFor.current) return;
+ composedFor.current = view.token;
+ if (view.deckOn) void compose();
+ }, [view.token, view.deckOn, compose]);
+ // A cut switched to Basic (or back) under the page: nothing composed for the deck that is no longer there.
+ useEffect(() => {
+ if (!view.deckOn) {
+ setDoc(null);
+ setComposeState("no-deck");
+ }
+ }, [view.deckOn]);
+
+ // ---- the plan ----------------------------------------------------------------
+ // The composed schedule, while it is the cut's ORDER: a reorder (the strip's drop) re-reads the
+ // view at once, and until the deck is composed again its segments would play the old order --
+ // so the estimate's (the view's own, in the new order) stand in meanwhile.
+ const composedOrder = doc?.schedule?.segments?.map((x) => x.id).join("\n") ?? null;
+ const viewOrder = useMemo(() => view.segments.map((x) => x.id).join("\n"), [view.segments]);
+ const scheduleNow = composedOrder !== null && composedOrder === viewOrder;
+ const schedule = scheduleNow ? (doc?.schedule ?? null) : null;
+ const segments = schedule?.segments ?? view.segments;
+ const leadIn = doc?.leadIn ?? view.leadIn;
+ // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change.
+ const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd, e.gaps ?? null])), [view.entries]);
+ const edges = useRenderCuts(project, take, edgesKey);
+ const [asPublished, setAsPublishedState] = useState(false);
+ const [uncensored, setUncensoredState] = useState(false);
+ useEffect(() => {
+ try {
+ if (window.localStorage.getItem(AS_PUBLISHED_KEY) === "on") setAsPublishedState(true);
+ if (window.localStorage.getItem(UNCENSORED_KEY) === "on") setUncensoredState(true);
+ } catch {
+ // A preference, not state.
+ }
+ }, []);
+ const setAsPublished = useCallback((on: boolean) => {
+ setAsPublishedState(on);
+ remember(AS_PUBLISHED_KEY, on);
+ }, []);
+ const setUncensored = useCallback((on: boolean) => {
+ setUncensoredState(on);
+ remember(UNCENSORED_KEY, on);
+ }, []);
+ const hasPosts = useMemo(() => view.entries.some((e) => e.type === "post"), [view.entries]);
+ const hasVideoEntries = useMemo(() => view.entries.some((e) => e.type === "video" && !!e.videoEntry), [view.entries]);
+ // THE TEASERS (lane leaflit-labels): each text card's own page, composed for preview (POST
+ // /api/report/chrome/teasers) and laid full frame while it is on screen -- the build's card, not a placeholder.
+ // Composed again whenever the manifest moved (its token), with or without a deck.
+ const teaserKey = useMemo(() => view.entries.filter((e) => e.type === "teaser").map((e) => e.id).join("\n"), [view.entries]);
+ // THE INTRO (lane intro-play): its page composed for preview (POST /api/report/chrome/intro), again when the manifest moved.
+ const introPage = useIntroPage(project, take, view.entries.some((e) => e.type === "intro"), view.token);
+ const [teaserPages, setTeaserPages] = useState<Record<string, TeaserPage | { id: string; error: string }>>({});
+ useEffect(() => {
+ if (!teaserKey) {
+ setTeaserPages({});
+ return;
+ }
+ let live = true;
+ void (async () => {
+ try {
+ const r = await fetch("/api/report/chrome/teasers", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, ...(take ? { take } : {}) }),
+ });
+ const j = (await r.json().catch(() => ({}))) as { teasers?: (TeaserPage | { id: string; error: string })[]; error?: string };
+ if (!live) return;
+ setTeaserPages(Object.fromEntries((j.teasers ?? []).map((x) => [x.id, x])));
+ } catch {
+ if (live) setTeaserPages({});
+ }
+ })();
+ return () => {
+ live = false;
+ };
+ }, [project, take, teaserKey, view.token]);
+ // Clips the walk REJECTED (a fact error, or irrelevant, weak, …) are SKIPPED unless the caller shows them.
+ const rejected = useMemo(() => view.entries.filter((e) => e.rejected), [view.entries]);
+ const skipIds = useMemo(() => new Set(showRejected ? [] : rejected.map((e) => e.id)), [showRejected, rejected]);
+ const plan = useMemo(
+ () => skipEntries(playPlan(segments, view.entries, { leadIn, cuts: edges.cuts }), skipIds),
+ [segments, view.entries, leadIn, edges.cuts, skipIds],
+ );
+ const entryOf = useMemo(() => new Map<string, PlayEntry>(view.entries.map((e) => [e.id, e])), [view.entries]);
+ const planRef = useRef(plan);
+ planRef.current = plan;
+
+ // ---- the engine (playEngine/: the sound on one Web Audio clock, the picture slaved to it) ----
+ const bg = doc?.background ?? "#000";
+ // `v` (the version of the window's bytes, playView): a window refetched under its old name is a new URL.
+ const srcOf = useCallback(
+ (id: string, m: MediaRef) =>
+ `/api/report/raw?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file: m.name, ...(m.v ? { v: m.v } : {}) }).toString()}`,
+ [project, take],
+ );
+ const audioOf = useCallback(
+ (id: string, m: MediaRef, from: number, to: number) =>
+ `/api/report/audio?${new URLSearchParams({
+ project, clip: id, ...(take ? { take } : {}), file: m.name, from: String(from), to: String(to), ...(m.v ? { v: m.v } : {}),
+ }).toString()}`,
+ [project, take],
+ );
+ // THE GATE (engine.ts): a post item plays once its player is ready -- its card drawn, its voice and its first
+ // attachment able to play -- and the clock waits on it, never cutting it short (a buffer stall's wait). Fetched
+ // ahead (postPreload.ts), its player is ready the frame its card is drawn; the clock holds on the item before
+ // while it is still fetching. `postReady`: what the MOUNTED player said (one at a time; "gone" as it unmounts).
+ // `started`: the item on screen once it has played -- a player mounted again under it (the deck composed) is not
+ // waited for (the clock runs on, as it always did).
+ const entryOfRef = useRef(entryOf);
+ entryOfRef.current = entryOf;
+ const postReady = useRef<string | null>(null);
+ const started = useRef<string | null>(null);
+ const gateAsked = useRef(new Map<string, number>());
+ const gate = useCallback<ItemGate>((id, next) => {
+ const e = entryOfRef.current.get(id);
+ if (!(e?.type === "post" && e.post && e.postPlan)) return "ready";
+ const now = performance.now();
+ const key = `${next ? "next" : "on"}:${id}`;
+ let since = gateAsked.current.get(key);
+ if (since === undefined) gateAsked.current.set(key, (since = now));
+ if (now - since > GATE_MAX_MS) return "ready";
+ if (next) return postPreload.itemState(id) === "loading" ? "fetching" : "ready";
+ if (started.current === id) return "ready";
+ if (postReady.current !== id) return "wait";
+ started.current = id;
+ return "ready";
+ }, []);
+ const onPostReady = useCallback((id: string, state: "ready" | "gone") => {
+ if (state !== "gone") postReady.current = id;
+ else if (postReady.current === id) postReady.current = null;
+ }, []);
+ const engine = usePlayEngine({
+ plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring", gate,
+ });
+ const { ui, failed } = engine;
+ const setDuck = engine.setDuck;
+
+ // ---- what is on screen -------------------------------------------------------------
+ const t = ui.t;
+ // The chrome was composed on the estimate's clock: seeked by the source second playing.
+ const tc = chromeTime(plan, t);
+ const item = plan.items[ui.cur] ?? null;
+ const entry = item ? (entryOf.get(item.id) ?? null) : null;
+ const g = doc?.geometry ?? null;
+ const box: Rect | null = g ? (doc?.feed?.footage ?? g.footage) : null;
+ const move = schedule ? footageAt(schedule, tc) : null;
+ const rect: Rect | null = move?.rect ?? box;
+ const order = useMemo(
+ () => (schedule?.factcheck ? tallyCellsFrom(schedule.factcheck.stamps, doc?.tallyOrder ?? VERDICTS, doc?.tallyAlways ?? []) : []),
+ [schedule, doc?.tallyOrder, doc?.tallyAlways],
+ );
+ const tally = schedule?.factcheck ? tallyAt(schedule, tc, order) : [];
+ const stamp = schedule ? stampAt(schedule, tc) : null;
+ const finaleNow = !!schedule && finaleUp(schedule, tc);
+ const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, tc) : null;
+ const missing = !!item?.clip && !entry?.media;
+ const broken = !!item && !!failed[item.id];
+ // A post item plays its card and attachments (PostItemPlayer), not a placeholder.
+ const postNow = item && entry?.type === "post" && entry.post && entry.postPlan ? { item, entry } : null;
+ // A VIDEO entry (lib/report/playVideo.mjs): its file, the whole frame -- and the item before it darkening into it.
+ const vstage = hasVideoEntries ? videoStageAt(plan, entryOf, t) : null;
+ const videoNow = vstage?.video ? { ...vstage, video: vstage.video } : null;
+ // A teaser plays its own page (TeaserCardPlayer), once composed; until then -- or if it did not compose -- a placeholder.
+ const teaserPage = item && entry?.type === "teaser" ? teaserPages[item.id] : undefined;
+ const teaserNow = item && teaserPage && "src" in teaserPage ? { item, page: teaserPage } : null;
+ // THE INTRO (lane intro-play): the build's own page and its sound (IntroCardPlayer), once composed; until then -- or if
+ // it did not compose -- a placeholder that says so.
+ const introNow = item && entry?.type === "intro" && introPage && "src" in introPage ? { item, page: introPage } : null;
+ const placeholder = item && !postNow && !videoNow && !teaserNow && !introNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
+ // The clips' sound fades with the picture into a video entry and is off over it (its element plays its own).
+ const duck = vstage ? vstage.duck : 1;
+ useEffect(() => {
+ if (hasVideoEntries) setDuck(duck);
+ }, [hasVideoEntries, duck, setDuck]);
+ // A clip's side post (lane vertical): its card over the clip for the side's span (SidePostOverlay).
+ const sideEntry = item && entry?.type === "clip" ? (entry as { side?: { from: number; to: number; place?: string | null } }).side : undefined;
+
+ // ---- post items fetched ahead (postPreload.ts): from the one on screen, ~20 s on --------------------------
+ const postBox = box ? { width: box.width, height: box.height } : { width: 1920, height: 1080 };
+ const postBoxKey = `${Math.round(postBox.width)}x${Math.round(postBox.height)}`;
+ useEffect(() => {
+ // A new item on screen: its gate is asked afresh (a revisit waits as the first visit did).
+ gateAsked.current.clear();
+ }, [ui.cur, plan]);
+ // Another item on screen: the one before is no longer "started" (a revisit waits as the first visit did).
+ const curId = plan.items[ui.cur]?.id ?? null;
+ useEffect(() => {
+ if (started.current !== curId) started.current = null;
+ }, [curId]);
+ useEffect(() => {
+ // Not while the deck composes: its pages would be fetched at the plain frame's size (the deck's box is
+ // another URL), and the requests would queue ahead of the composition itself.
+ if (composeState === "composing") return;
+ const items = plan.items;
+ const i = ui.cur;
+ const [w, h] = postBoxKey.split("x").map(Number);
+ const assetsOf = (k: number) => {
+ const it = items[k];
+ const e = it ? entryOf.get(it.id) : null;
+ if (!e || e.type !== "post" || !e.post || !e.postPlan) return null;
+ const before = k > 0 ? entryOf.get(items[k - 1]?.id ?? "") : null;
+ const joinFrom = e.postPlan.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan } : null;
+ return postItemAssets({ project, take, entry: e.post, plan: e.postPlan, box: { width: w, height: h }, published: asPublished, uncensored, joinFrom });
+ };
+ const keep = [i - 1, i].map(assetsOf).filter((x): x is NonNullable<typeof x> => !!x);
+ const ahead: NonNullable<ReturnType<typeof assetsOf>>[] = [];
+ const from = items[i]?.to ?? 0;
+ for (let k = i + 1, n = 0; k < items.length && ahead.length < PRELOAD_MAX; k += 1, n += 1) {
+ if (items[k].from - from > PRELOAD_AHEAD_S && n >= PRELOAD_MIN) break;
+ const a = assetsOf(k);
+ if (a) ahead.push(a);
+ }
+ postPreload.want(ahead, keep);
+ }, [ui.cur, plan, entryOf, project, take, asPublished, uncensored, postBoxKey, composeState]);
+ useEffect(() => () => postPreload.clear(), []);
+
+ return {
+ view, project, take,
+ doc, composeState, composeError, compose,
+ schedule, edges, plan, planRef, entryOf, rejected, skipIds, hasPosts, hasVideoEntries,
+ teaserPages, introPage, engine, onPostReady, bg,
+ asPublished, setAsPublished, uncensored, setUncensored,
+ // what is on screen
+ t, tc, item, entry, g, box, move, rect, tally, stamp, finaleNow, postsWin, missing, broken,
+ postNow, vstage, videoNow, teaserPage, teaserNow, introNow, placeholder, sideEntry,
+ };
+}
+
+export type PlayCore = ReturnType<typeof usePlayCore>;
+
+const pct = (n: number, of: number) => `${(n / of) * 100}%`;
+
+/**
+ * THE PICTURE. 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.
+ * `basic`: a basic cut -- the bare footage, as the basic render cuts it.
+ */
+export function PlayStage({ core, basic = false, plainClassName }: { core: PlayCore; basic?: boolean; plainClassName?: string }) {
+ const { project, take, doc, g, box, rect, move, tc, t, bg, engine, postNow, entryOf, plan, videoNow, vstage, teaserNow, introNow, placeholder, teaserPage, introPage, sideEntry, item, postsWin, finaleNow, asPublished, uncensored, onPostReady } = core;
+ const { ui, rate, failed } = engine;
+ const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => (
+ <canvas ref={engine.canvasRef} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} />
+ );
+ const sideNow = item && sideEntry ? <SidePostOverlay project={project} take={take} clipId={item.id} side={sideEntry} s={Math.max(0, t - item.start)} published={asPublished} /> : null;
+ const postPlayer = (box2: { width: number; height: number }) =>
+ postNow ? (
+ <PostItemPlayer
+ key={postNow.item.id}
+ project={project}
+ take={take}
+ entry={postNow.entry.post!}
+ plan={postNow.entry.postPlan!}
+ box={box2}
+ s={Math.max(0, t - postNow.item.start)}
+ playing={ui.playing && !ui.waiting}
+ speed={rate}
+ published={asPublished}
+ uncensored={uncensored}
+ scene={postNow.entry.postScene ?? null}
+ clock={postNow.entry.postClock ?? null}
+ onReady={onPostReady}
+ progress={postNow.entry.postProgress ?? null}
+ joinFrom={(() => {
+ // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended.
+ const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null;
+ return postNow.entry.postPlan?.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan, clock: before.postClock ?? null } : null;
+ })()}
+ />
+ ) : null;
+ // A post item that repeats an earlier one's attachment: its combo badge, beside the player.
+ const comboBadge = (box2: { width: number; height: number }) =>
+ postNow?.entry.postCombo ? (
+ <ComboBadge
+ key={`combo-${postNow.item.id}`}
+ project={project}
+ entry={postNow.entry.post!}
+ plan={postNow.entry.postPlan!}
+ combo={postNow.entry.postCombo}
+ box={box2}
+ s={Math.max(0, t - postNow.item.start)}
+ playing={ui.playing && !ui.waiting}
+ />
+ ) : null;
+ // The video on screen: over EVERYTHING when the chrome is off over it (the default), else as the footage under it.
+ const videoPlayer = videoNow ? (
+ <VideoEntryPlayer
+ key={videoNow.id}
+ project={project}
+ id={videoNow.id}
+ video={videoNow.video}
+ src={videoNow.src ?? videoNow.video.from}
+ opacity={videoNow.opacity}
+ run={ui.playing && !ui.waiting && videoNow.playing}
+ speed={rate}
+ />
+ ) : null;
+ const videoOver = videoNow?.video.noChrome ? <div className="pointer-events-none absolute inset-0 z-30">{videoPlayer}</div> : null;
+ const videoUnder = videoNow && !videoNow.video.noChrome ? videoPlayer : null;
+ // The item before a video entry, darkening into it: the whole stage, its chrome with it.
+ const dipVeil = vstage && vstage.dark > 0 ? <div data-play-dip={vstage.id} className="pointer-events-none absolute inset-0 z-30 bg-black" style={{ opacity: vstage.dark }} /> : null;
+ // A teaser on screen: its page, seeked to the seconds into the card (the item's own clock, as a post item's).
+ const teaserCard = teaserNow ? <TeaserCardPlayer key={teaserNow.item.id} page={teaserNow.page} s={t - teaserNow.item.start} /> : null;
+ // The intro on screen: its page seeked to the seconds into it, its sound on Play's clock.
+ const introCard = introNow ? <IntroCardPlayer key={introNow.page.src} page={introNow.page} s={t - introNow.item.start} playing={ui.playing && !ui.waiting} speed={rate} /> : null;
+ 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.5 p-6 text-center"
+ style={{ background: placeholder.kind === "card" ? bg : "transparent" }}
+ >
+ {placeholder.kind === "card" ? (
+ <>
+ <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">
+ {teaserPage && "error" in teaserPage
+ ? `the card did not compose: ${teaserPage.error}`
+ : placeholder.item.type === "teaser"
+ ? "composing the card…"
+ : placeholder.item.type === "intro"
+ ? introPage && "error" in introPage
+ ? `the intro did not compose: ${introPage.error}`
+ : "composing the intro…"
+ : "a placeholder: the build draws it"}
+ </span>
+ </>
+ ) : (
+ <span className="rounded-[3px] bg-black/75 px-2.5 py-1 text-[12.5px] text-white">
+ {core.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>
+ ) : null;
+
+ return (
+ <>
+ <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
+ <video ref={engine.slotRef0} data-play-slot="0" preload="auto" playsInline muted onError={() => engine.onMediaError(0)} className="absolute inset-0 h-full w-full" />
+ <video ref={engine.slotRef1} data-play-slot="1" preload="auto" playsInline muted onError={() => engine.onMediaError(1)} className="absolute inset-0 h-full w-full" />
+ </div>
+ <div className="relative">
+ {doc && g && box ? (
+ <DeckFrame preview={doc} t={tc} 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)}
+ {videoUnder}
+ {postNow && rect && (
+ <div className="absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H), background: bg }}>
+ {postPlayer({ width: box.width, height: box.height })}
+ {comboBadge({ width: box.width, height: box.height })}
+ </div>
+ )}
+ {teaserCard}
+ {introCard}
+ {placeholderCard}
+ {sideNow && rect && <div className="pointer-events-none absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) }}>{sideNow}</div>}
+ {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={tc} testid="play-feed" />}
+ {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />}
+ {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={tc} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />}
+ {/* Every module that declares `play` (chapters, then and now, the status ledger …), by z. */}
+ <ModuleLayers layers={doc.layers} frame={g} t={tc} testid="play-layer" />
+ {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={tc} ready="finale:ready" testid="play-finale" name="finale" />
+ </div>
+ )}
+ </DeckFrame>
+ ) : (
+ <div
+ className={plainClassName ?? "relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0"}
+ style={{ aspectRatio: "16 / 9" }}
+ data-testid="play-plain"
+ // A basic cut: the bare footage, as the basic render cuts it -- no card, no side post, nothing over it.
+ data-play-bare={basic ? "" : undefined}
+ >
+ {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
+ {!basic && postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>}
+ {!basic && videoUnder}
+ {!basic && teaserCard}
+ {!basic && introCard}
+ {!basic && placeholderCard}
+ {!basic && sideNow}
+ </div>
+ )}
+ {dipVeil}
+ {videoOver}
+ {ui.playing && ui.waiting && (
+ // The clock held (engine.ts): a clip's sound decoding, a post item loading -- it plays in full once here.
+ <span data-play-loading="" className="pointer-events-none absolute right-2 top-2 z-40 rounded-full bg-black/70 px-2 py-0.5 text-[11px] text-white">
+ loading…
+ </span>
+ )}
+ </div>
+ </>
+ );
+}