commit 82aefea4e637c3899b4fea52045e01ebfe1c1418
parent 8a3024a4409cfd6000a713b6e6ebcf61488d8f6b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 22:35:58 -0500
umtool: Play the cut draws a teaser card as the build does -- its own page, seeked on the cut clock, the deck over a card that counts
Operator, 6 Nov: "play the cut needs to handle x posts". A `teaser` entry (here the
X posts quoted on text cards) played as a placeholder. Now POST
/api/report/chrome/teasers composes each teaser of the cut (or a take) with
compose-chrome's own `teaser` region into out/<variant>/chrome/teaser-preview-<id>/,
appends Play's seek to that preview copy only (the build's page and its render key
are untouched), and the files route serves it. Play lays it full frame where the
placeholder was -- under the deck's page, so a card that carries a mark keeps the
deck up and the count steps at its mark -- seeked to the seconds into the card.
With or without a deck. play-teaser.spec.ts and its fixture; unit tests for the
composer and the serving rule.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 424 insertions(+), 7 deletions(-)
diff --git a/umtool/app/api/report/chrome/teasers/route.ts b/umtool/app/api/report/chrome/teasers/route.ts
@@ -0,0 +1,64 @@
+import { composeTeaserPreviews } from "@/lib/report/onscreen.mjs";
+import { resolveReport, teaserPreviewSrc } from "@/lib/report/serve.mjs";
+import { selectVariant } from "umtool-report-to-video/build-video";
+import { teaserSeconds, transitionOf } from "umtool-report-to-video/deck";
+import { cachedTakeManifest, takePlayDir, writePlayManifest } from "@/lib/report/takeManifest.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE TEASERS' PAGES for Play the cut (lane leaflit-labels): every `teaser`
+// entry of the cut -- a text card, an X post quoted on one -- composed for
+// preview by the build's own page (compose-chrome's `teaser` region, under
+// out/<variant>/chrome/teaser-preview-<id>/, Play's seek appended:
+// onscreen.mjs composeTeaserPreviews), so Play draws the card as the render
+// does instead of a placeholder. No render. With or without a deck: a teaser is
+// full frame, the deck (when there is one, and the card counts) is laid over it
+// by the deck's own page.
+//
+// POST { project, take? } -> { teasers: [{ id, seconds, width, height, src } |
+// { id, error }] }. `seconds` is the card's length (deck.mjs teaserSeconds); the
+// page is seeked in seconds from its start. A take's pages are composed under
+// its own directory and served under `@take/<id>/`, as the deck's are.
+export async function POST(request: Request) {
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""), body.variant ? String(body.variant) : null);
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const take = body.take === undefined || body.take === null || body.take === "" ? null : String(body.take);
+ if (take !== null && !isTakeId(take)) return Response.json({ error: "take is a take id" }, { status: 400 });
+ let manifest = r.manifest;
+ let target: { dir: string; manifestFile?: string } = r.project;
+ if (take) {
+ try {
+ manifest = (await cachedTakeManifest(r.project.dir, take)).manifest;
+ target = { dir: takePlayDir(r.project.dir, take), manifestFile: await writePlayManifest(r.project.dir, take, manifest) };
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 404 });
+ }
+ }
+ const selected = selectVariant(manifest, r.variant);
+ const render = (selected.render ?? {}) as Record<string, unknown>;
+ const timeline = ((selected.timeline ?? []) as Record<string, unknown>[]).filter((e) => e && e.type === "teaser");
+ const composed = await composeTeaserPreviews(target, r.variant, timeline);
+ const D = transitionOf(render);
+ const fps = typeof render.fps === "number" ? render.fps : 30;
+ const width = typeof render.width === "number" ? render.width : 1920;
+ const height = typeof render.height === "number" ? render.height : 1080;
+ const stamp = Date.now();
+ return Response.json(
+ {
+ teasers: composed.map((c) => {
+ const e = timeline.find((x) => x.id === c.id)!;
+ return c.ok
+ ? { id: c.id, seconds: teaserSeconds(e, D, fps), width, height, src: `${teaserPreviewSrc(r.project.id, r.variant, c.id, take)}?v=${stamp}` }
+ : { id: c.id, error: c.error ?? "did not compose" };
+ }),
+ },
+ { headers: { "cache-control": "no-store" } },
+ );
+}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -34,6 +34,7 @@ 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 { videoStageAt, type VideoEntryPlay } from "@/lib/report/playVideo.mjs";
import ComboBadge, { type ComboInfo } from "./ComboBadge";
@@ -246,7 +247,7 @@ function approximateLine(edges: RenderCuts, info: EngineInfo | null) {
const picture = !info ? "" : info.picture === "webcodecs" ? "picture: WebCodecs" : info.picture === "mixed" ? "picture: WebCodecs, some clips on <video>" : "picture: <video>";
const silent = info ? Object.keys(info.silent) : [];
return [
- "Approximate: cards and teasers are placeholders (a post item plays its card and attachments, its sound from its own element), a push or a wipe is drawn as a dissolve, the chrome is composed on the estimate's clock;",
+ "Approximate: cards are placeholders (a teaser plays the build's own card, silent; a post item plays its card and attachments, its sound from its own element), a push or a wipe is drawn as a dissolve, the chrome is composed on the estimate's clock;",
`${edge};`,
`${sound}${picture ? `; ${picture}` : ""}.`,
silent.length ? `No sound decoded for ${silent.join(", ")}.` : "",
@@ -384,6 +385,35 @@ export default function PlayCut({
}, []);
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]);
+ 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.
@@ -893,7 +923,10 @@ export default function PlayCut({
// 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;
- const placeholder = item && !postNow && !videoNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : 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;
+ const placeholder = item && !postNow && !videoNow && !teaserNow && (!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(() => {
@@ -1012,6 +1045,8 @@ export default function PlayCut({
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;
const placeholderCard = placeholder ? (
<div
data-play-placeholder={placeholder.kind}
@@ -1023,7 +1058,9 @@ export default function PlayCut({
<>
<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="text-[11px] text-white/55">
+ {teaserPage && "error" in teaserPage ? `the card did not compose: ${teaserPage.error}` : placeholder.item.type === "teaser" ? "composing the card…" : "a placeholder: the build draws it"}
+ </span>
</>
) : (
<span className="rounded-[3px] bg-black/75 px-2.5 py-1 text-[12.5px] text-white">
@@ -1177,6 +1214,7 @@ export default function PlayCut({
{comboBadge({ width: box.width, height: box.height })}
</div>
)}
+ {teaserCard}
{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" />}
@@ -1195,6 +1233,7 @@ export default function PlayCut({
{footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
{postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>}
{videoUnder}
+ {teaserCard}
{placeholderCard}
{sideNow}
</div>
diff --git a/umtool/components/projects/review/TeaserCardPlayer.tsx b/umtool/components/projects/review/TeaserCardPlayer.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+
+// A TEASER on Play's stage (lane leaflit-labels): the card the build draws --
+// its own page (chrome-teaser.mjs, composed for preview by POST
+// /api/report/chrome/teasers) -- full frame, seeked to `s`, the seconds into
+// the card. The page says `teaser:ready` once its words are fitted; nothing is
+// sent before it. Laid where a placeholder would be: under the deck's page, so
+// a card that counts keeps the deck (and the count stepping at its mark) over it.
+
+export type TeaserPage = { id: string; seconds: number; width: number; height: number; src: string };
+
+export default function TeaserCardPlayer({ page, s }: { page: TeaserPage; s: number }) {
+ const box = useRef<HTMLDivElement | null>(null);
+ const el = useRef<HTMLIFrameElement | null>(null);
+ const [width, setWidth] = useState(0);
+ const [readySrc, setReadySrc] = useState<string | null>(null);
+ const src = `${page.src}${page.src.includes("?") ? "&" : "?"}preview=1`;
+
+ useEffect(() => {
+ const node = box.current;
+ if (!node) return;
+ const ro = new ResizeObserver(([e]) => setWidth(e.contentRect.width));
+ ro.observe(node);
+ return () => ro.disconnect();
+ }, []);
+
+ useEffect(() => {
+ const onMsg = (e: MessageEvent) => {
+ if (e.source !== el.current?.contentWindow || e.origin !== window.location.origin) return;
+ if ((e.data as { type?: string } | null)?.type === "teaser:ready") setReadySrc(src);
+ };
+ window.addEventListener("message", onMsg);
+ return () => window.removeEventListener("message", onMsg);
+ }, [src]);
+
+ const live = readySrc === src;
+ // Clamped into the card: a hard cut shows its middle, never past its last frame.
+ const at = Math.max(0, Math.min(page.seconds, s));
+ useEffect(() => {
+ if (live) el.current?.contentWindow?.postMessage({ type: "deck:seek", t: at }, window.location.origin);
+ }, [live, at]);
+
+ const scale = width > 0 ? width / page.width : 0;
+ return (
+ <div
+ ref={box}
+ data-play-teaser={page.id}
+ data-play-teaser-ready={live ? "1" : "0"}
+ data-play-teaser-at={at.toFixed(2)}
+ className="pointer-events-none absolute inset-0 overflow-hidden bg-black"
+ >
+ <iframe
+ ref={el}
+ key={src}
+ src={src}
+ title={`teaser ${page.id}`}
+ data-testid="play-teaser-iframe"
+ tabIndex={-1}
+ aria-hidden
+ style={{
+ position: "absolute",
+ left: 0,
+ top: 0,
+ width: page.width,
+ height: page.height,
+ border: 0,
+ transform: `scale(${scale})`,
+ transformOrigin: "0 0",
+ visibility: live ? "visible" : "hidden",
+ }}
+ />
+ </div>
+ );
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -2047,6 +2047,32 @@ pm.timeline = pm.timeline.map((e) => (e.id === "c03" ? { ...e, verdict: "incorre
writeFileSync(pmFile, JSON.stringify(pm, null, 2) + "\n");
}
+// A TEXT CARD in Play the cut (play-teaser.spec.ts, lane leaflit-labels): the Play cut
+// with its card k01 replaced by a teaser t01 -- an X post quoted on a card -- that
+// carries a mark (CORROBORATED, 1.0 s into the card), so the deck stays up over it
+// and the count steps on it. Play draws the build's own page, not a placeholder.
+{
+const { dir: playTeaserDir } = makePlayCutFixture({
+ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"),
+ name: "play-teaser-fixture", title: "The Play Teaser Fixture",
+ chrome: { factcheck: { verdicts: { CORROBORATED: { label: "Seizures", tallyLabel: "Seized", color: "#6fa8dc" } }, stamp: { seconds: 1 } } },
+});
+const ptFile = path.join(playTeaserDir, "video.manifest.json");
+const pt = JSON.parse(readFileSync(ptFile, "utf8"));
+pt.timeline = pt.timeline.map((e) => (e.id === "k01"
+ ? {
+ type: "teaser", id: "t01", seconds: 3,
+ lines: [
+ { text: "@someone on X · 1 Feb 2026", role: "overline" },
+ { text: "“I want to understand your perspective", role: "kicker" },
+ { text: "behind them as a moderate.”", role: "kicker" },
+ ],
+ claim: { id: "kx", verdict: "CORROBORATED", at: 1.0 },
+ }
+ : e));
+writeFileSync(ptFile, JSON.stringify(pt, null, 2) + "\n");
+}
+
// The measure's instruments (instruments.spec.ts): the Play cut with the dial, the odometer and
// the trail on, and a built schedule carrying a measure slice (instruments-fixture.mjs).
await makeInstrumentsFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture });
diff --git a/umtool/e2e/play-teaser.spec.ts b/umtool/e2e/play-teaser.spec.ts
@@ -0,0 +1,72 @@
+import { test, expect, type Page } from "@playwright/test";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// A TEXT CARD in Play the cut (lane leaflit-labels; operator, 6 Nov: "play the
+// cut needs to handle x posts"): a `teaser` entry -- an X post quoted on a card
+// -- plays as the build draws it, its own page (chrome-teaser.mjs, composed for
+// preview by POST /api/report/chrome/teasers) laid full frame and seeked on the
+// cut clock, not a placeholder. A card that carries a mark keeps the deck up
+// over it (deck.mjs teaserCounts) and the count steps at the mark.
+//
+// Fixture: e2e/fixtures/make-fixture.mjs, play-teaser-fixture -- the Play cut
+// with its card k01 replaced by t01 (3 s, three lines), marked CORROBORATED at
+// 1.0 s into the card; c02's mark (k1) lands before it, so the count is 1 on
+// the card's first second and 2 after its mark.
+// ---------------------------------------------------------------------------
+
+const PROJECT = "reports/play-teaser-fixture";
+
+const root = (page: Page) => page.locator("[data-play-cut]");
+const card = (page: Page) => page.locator('[data-play-teaser="t01"]');
+const frame = (page: Page) => page.frameLocator('[data-testid="play-teaser-iframe"]');
+/** A line's visibility inside the card's own page (the build's pixels, seeked by the parent). */
+const lineOpacity = (page: Page, i: number) =>
+ frame(page).locator(`[data-k="l${i}.o"]`).evaluate((el) => Number(getComputedStyle(el).opacity));
+const tally = (page: Page) => page.locator("[data-play-tally]");
+
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+});
+
+test("a teaser card that carries a mark plays as the build draws it: its lines, the deck over it, the count stepping at its mark", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ // Into the card, before its mark (1.0 s): seeked there from the URL.
+ await page.goto(urls.playHref(PROJECT, { clip: "t01", at: 0.6 }));
+ await expect(root(page)).toHaveAttribute("data-play-item", "t01", { timeout: 30_000 });
+ await expect(page.locator('[data-testid="play-deck"]')).toBeVisible({ timeout: 30_000 });
+ // The card's own page, not a placeholder.
+ await expect(card(page)).toHaveAttribute("data-play-teaser-ready", "1", { timeout: 30_000 });
+ await expect(page.locator("[data-play-placeholder]")).toHaveCount(0);
+ await expect(frame(page).locator('[data-k="l1.t"]')).toHaveText("“I want to understand your perspective");
+ await expect(frame(page).locator('[data-k="l2.t"]')).toHaveText("behind them as a moderate.”");
+ // Before the mark: c02's k1 has counted, the card's has not.
+ await expect(tally(page)).toHaveAttribute("data-play-tally", "CORROBORATED:1");
+ await page.screenshot({ path: test.info().outputPath("play-teaser-before-mark.png") });
+
+ // Seek through the card past its mark (→ is 5 s on, past the card: back with ← lands before it, so step by the URL).
+ await page.goto(urls.playHref(PROJECT, { clip: "t01", at: 2.6 }));
+ await expect(root(page)).toHaveAttribute("data-play-item", "t01", { timeout: 30_000 });
+ await expect(card(page)).toHaveAttribute("data-play-teaser-ready", "1", { timeout: 30_000 });
+ await expect(page.locator('[data-testid="play-deck"]')).toHaveAttribute("data-deck-ready", "1", { timeout: 30_000 });
+ // Every line is in by now: the card's last line too.
+ await expect.poll(() => lineOpacity(page, 2), { timeout: 10_000 }).toBeGreaterThan(0.9);
+ await expect.poll(() => lineOpacity(page, 1), { timeout: 10_000 }).toBeGreaterThan(0.9);
+ // After the mark: the count stepped on the card.
+ await expect(tally(page)).toHaveAttribute("data-play-tally", "CORROBORATED:2");
+ await page.screenshot({ path: test.info().outputPath("play-teaser-after-mark.png") });
+
+ // Playing across the mark from the card's start: the count steps while the card is on screen.
+ await page.goto(urls.playHref(PROJECT, { clip: "t01", at: 0.2 }));
+ await expect(card(page)).toHaveAttribute("data-play-teaser-ready", "1", { timeout: 30_000 });
+ await expect(tally(page)).toHaveAttribute("data-play-tally", "CORROBORATED:1");
+ await page.locator("[data-play-toggle]").click();
+ await expect(tally(page)).toHaveAttribute("data-play-tally", "CORROBORATED:2", { timeout: 15_000 });
+ await page.keyboard.press("k");
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+
+ // Out of it (c01): no card on screen.
+ await page.locator('[data-play-row="c01"]').press("Enter");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c01");
+ await expect(card(page)).toHaveCount(0);
+});
diff --git a/umtool/lib/report/livePreview.test.mjs b/umtool/lib/report/livePreview.test.mjs
@@ -13,8 +13,8 @@ import test from "node:test";
import { MANIFEST_NAME, StaleToken } from "./manifest.mjs";
import { clipEditorView, runClipEditorOp } from "./clipEditor.mjs";
import { clipRenderFile, clipRenderSteps, readClipRender, windowMoved } from "./clipRender.mjs";
-import { composeFinalePreview, renderSeconds, scheduleForPreview } from "./onscreen.mjs";
-import { finalePreviewDir, finalePreviewSrc, previewDirFor } from "./serve.mjs";
+import { composeFinalePreview, composeTeaserPreviews, renderSeconds, scheduleForPreview, TEASER_SEEK_SCRIPT, withTeaserSeek } from "./onscreen.mjs";
+import { finalePreviewDir, finalePreviewSrc, previewDirFor, teaserPreviewDir, teaserPreviewSrc } from "./serve.mjs";
import { PIPELINE_DIR, RENDER_BUDGET, buildSteps, buildTimeoutMs } from "./driver.mjs";
import { takeTimeoutMs } from "./takeMaker.mjs";
@@ -94,6 +94,52 @@ test("the finale's preview is served from finale-preview/ under the files route"
});
});
+test("composeTeaserPreviews: each teaser of the cut through compose-chrome's teaser region, into teaser-preview-<id>, Play's seek appended", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "teaser-preview-"));
+ try {
+ const calls = [];
+ const timeline = [
+ { type: "clip", id: "a" },
+ { type: "teaser", id: "x1", lines: ["One"] },
+ { type: "teaser", id: "x2", lines: ["Two"] },
+ ];
+ const r = await composeTeaserPreviews({ dir }, "sourced", timeline, {
+ compose: async (args) => {
+ calls.push(args);
+ if (args.segment === "x2") throw new Error("teaser x2: no lines");
+ const projDir = path.join(args.outDir, "chrome", `teaser-preview-${args.segment}`);
+ await mkdir(projDir, { recursive: true });
+ await writeFile(path.join(projDir, "index.html"), "<html><body><p>card</p></body></html>\n");
+ return { projDir };
+ },
+ });
+ assert.deepEqual(calls.map((c) => [c.region, c.segment, c.preview]), [["teaser", "x1", true], ["teaser", "x2", true]]);
+ assert.deepEqual(r, [{ id: "x1", ok: true }, { id: "x2", ok: false, error: "teaser x2: no lines" }]);
+ const html = await readFile(path.join(teaserPreviewDir(dir, "sourced", "x1"), "index.html"), "utf8");
+ assert.ok(html.includes(TEASER_SEEK_SCRIPT), "the preview copy answers Play's seek");
+ assert.ok(html.indexOf(TEASER_SEEK_SCRIPT) < html.indexOf("</body>"), "before </body>");
+ assert.ok(html.startsWith("<html><body><p>card</p>"), "the build's page otherwise");
+ // Refused when compose-chrome writes anywhere else.
+ const bad = await composeTeaserPreviews({ dir }, "sourced", [timeline[1]], { compose: async () => ({ projDir: "/elsewhere" }) });
+ assert.match(bad[0].error ?? "", /not .*teaser-preview-x1/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a teaser's preview is served from teaser-preview-<id>/ when <id> is an entry of the cut", () => {
+ assert.equal(teaserPreviewDir("/p", "sourced", "x-d28"), path.join("/p", "out", "sourced", "chrome", "teaser-preview-x-d28"));
+ assert.match(teaserPreviewSrc("reports/x", "sourced", "x-d28", "a-take"), /^\/api\/report\/chrome\/files\/[A-Za-z0-9_-]+\/sourced\/@take\/a-take\/teaser-preview-x-d28\/index\.html$/);
+ assert.deepEqual(previewDirFor("/p", "sourced", ["teaser-preview-x-d28", "assets", "gsap.min.js"], ["x-d28"]), {
+ dir: path.join("/p", "out", "sourced", "chrome", "teaser-preview-x-d28"),
+ rest: ["assets", "gsap.min.js"],
+ });
+ assert.equal(previewDirFor("/p", "sourced", ["teaser-preview-nope", "index.html"], ["x-d28"]), null);
+ assert.equal(previewDirFor("/p", "sourced", ["teaser-preview-..", "index.html"], [".."]), null);
+ // A page with no </body> still gets it, at its end.
+ assert.ok(withTeaserSeek("<p>x</p>").endsWith(TEASER_SEEK_SCRIPT));
+});
+
test("the editor's `onscreen` op: the clip's deck words through the On-screen writer; null is automatic; the view carries them", async () => {
const p = await project();
try {
diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -15,7 +15,7 @@
//
// The preview never renders and never touches the build's project or cache:
// compose-chrome's `preview: true` writes out/<variant>/chrome/deck-preview/.
-import { readFile, rm } from "node:fs/promises";
+import { readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { composeChrome } from "umtool-report-to-video/compose-chrome";
import { selectVariant } from "umtool-report-to-video/build-video";
@@ -50,7 +50,7 @@ import {
readCues,
} from "../projects/report.mjs";
import { normalizePostPatches, splitOnscreenRow } from "./manifest.mjs";
-import { deckPreviewDir, feedPreviewDir, finalePreviewDir, postsPreviewDir, stampPreviewDir } from "./serve.mjs";
+import { deckPreviewDir, feedPreviewDir, finalePreviewDir, postsPreviewDir, stampPreviewDir, teaserPreviewDir } from "./serve.mjs";
import { ensureWriteDir } from "./storage.mjs";
/** The schedule document deck.mjs defines, built or estimated. */
@@ -619,6 +619,76 @@ export async function composeStampPreview(project, variant, schedule, { compose
}
/**
+ * PLAY'S SEEK for a teaser's preview page: appended to the PREVIEW copy only
+ * (compose-chrome never renders a preview project, so the build's page and its
+ * render key are untouched). Under `?preview=1` the page answers the parent's
+ * `deck:seek` (seconds into the card) by seeking its own timeline, and posts
+ * `teaser:ready` once its words are fitted -- the build's page otherwise, byte
+ * for byte.
+ */
+export const TEASER_SEEK_SCRIPT = `<script data-play-seek="">
+ (function () {
+ if (new URLSearchParams(location.search).get("preview") === null) return;
+ var tl = window.__timelines && window.__timelines["teaser"];
+ if (!tl) return;
+ addEventListener("message", function (e) {
+ if (e.origin !== location.origin || !e.data || e.data.type !== "deck:seek") return;
+ tl.seek(Math.max(0, Number(e.data.t) || 0), false);
+ });
+ var tries = 0;
+ (function wait() {
+ if (document.documentElement.dataset.fit === "1" || tries++ > 200) parent.postMessage({ type: "teaser:ready" }, location.origin);
+ else setTimeout(wait, 25);
+ })();
+ })();
+</script>`;
+
+/** The page with Play's seek before its `</body>`. */
+export const withTeaserSeek = (html) => {
+ const at = html.lastIndexOf("</body>");
+ return at < 0 ? html + TEASER_SEEK_SCRIPT : `${html.slice(0, at)}${TEASER_SEEK_SCRIPT}\n ${html.slice(at)}`;
+};
+
+/**
+ * Compose the PREVIEW page of every TEASER in the cut (Play the cut, lane
+ * leaflit-labels: a text card -- an X post quoted on a card -- plays as the
+ * build draws it, not as a placeholder): compose-chrome's `teaser` region per
+ * entry, under out/<variant>/chrome/teaser-preview-<id>/, Play's seek
+ * appended. No render. A teaser that does not compose says why in its row; the
+ * others are composed either way.
+ *
+ * @param {{ dir: string, manifestFile?: string }} project
+ * @param {string} variant
+ * @param {Array<Record<string, any>>} timeline the cut's (the variant's) entries
+ * @param {{ compose?: (args: Record<string, unknown>) => Promise<any> }} [opts]
+ * @returns {Promise<Array<{ id: string, ok: boolean, error?: string }>>}
+ */
+export async function composeTeaserPreviews(project, variant, timeline, { compose = composeChrome } = {}) {
+ const outDir = path.join(project.dir, "out", variant);
+ const teasers = (timeline ?? []).filter((e) => e?.type === "teaser" && typeof e.id === "string");
+ const out = [];
+ for (const e of teasers) {
+ const want = teaserPreviewDir(project.dir, variant, e.id);
+ try {
+ await serialised(want, async () => {
+ /** @type {Record<string, unknown>} */
+ const args = { manifestPath: manifestOf(project), outDir, variant, region: "teaser", segment: e.id, preview: true };
+ const r = await compose(/** @type {any} */ (args));
+ if (r?.projDir && path.resolve(r.projDir) !== path.resolve(want)) {
+ throw new Error(`compose-chrome wrote the teaser preview to ${r.projDir}, not ${want}`);
+ }
+ const file = path.join(want, "index.html");
+ await writeFile(file, withTeaserSeek(await readFile(file, "utf8")), "utf8");
+ });
+ out.push({ id: e.id, ok: true });
+ } catch (err) {
+ out.push({ id: e.id, ok: false, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+ return out;
+}
+
+/**
* Compose the PREVIEW of the finale (a schedule with `finale`): compose-chrome's
* `finale` region, one project for its window under
* out/<variant>/chrome/finale-preview/. No render. The page is seeked in the
diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs
@@ -919,6 +919,22 @@ export const finalePreviewDir = (projectDir, variant) =>
export const finalePreviewSrc = (projectId, variant, take = null) =>
`${previewBase(projectId, variant, take)}/${FINALE_PREVIEW}/index.html`;
+// A TEASER's preview page (Play the cut, lane leaflit-labels): compose-chrome's
+// `teaser-preview-<id>/` for one teaser entry of the cut -- the build's own page
+// (chrome-teaser.mjs), with Play's seek appended (onscreen.mjs
+// composeTeaserPreviews) -- served one segment deeper, `teaser-preview-<id>/…`,
+// when `<id>` is one of the cut's entries.
+const TEASER_PREVIEW_PREFIX = "teaser-preview-";
+
+/** The preview project of one teaser entry. */
+export const teaserPreviewDir = (projectDir, variant, segment) =>
+ path.join(projectDir, "out", variant, "chrome", `${TEASER_PREVIEW_PREFIX}${segment}`);
+
+/** The iframe src for one teaser entry's preview page. */
+/** @type {(projectId: string, variant: string, segment: string, take?: string | null) => string} */
+export const teaserPreviewSrc = (projectId, variant, segment, take = null) =>
+ `${previewBase(projectId, variant, take)}/${TEASER_PREVIEW_PREFIX}${encodeURIComponent(segment)}/index.html`;
+
/** The preview project of the posts window on one segment. */
export const postsPreviewDir = (projectDir, variant, segment) =>
path.join(projectDir, "out", variant, "chrome", `${POSTS_PREVIEW_PREFIX}${segment}`);
@@ -935,6 +951,8 @@ export const postsPreviewSrc = (projectId, variant, segment, take = null) =>
* `feed-preview/…` is the posts feed's project (one per cut),
* `stamp-preview/…` the fact-check stamps' (one per cut) and
* `finale-preview/…` the finale's (one per cut).
+ * `teaser-preview-<segment>/…` is a teaser entry's page when `<segment>` is one
+ * of `segmentIds`, as a posts window's is.
* `posts-preview-<segment>/…` is a posts window's project when `<segment>` is
* one of `segmentIds` -- the cut's own entry ids, which the caller reads from
* the manifest, so a name the client made up is not a directory this serves.
@@ -960,6 +978,12 @@ export function previewDirFor(projectDir, variant, rest, segmentIds) {
if (head === FEED_PREVIEW) return { dir: feedPreviewDir(projectDir, variant), rest: rest.slice(1) };
if (head === STAMP_PREVIEW) return { dir: stampPreviewDir(projectDir, variant), rest: rest.slice(1) };
if (head === FINALE_PREVIEW) return { dir: finalePreviewDir(projectDir, variant), rest: rest.slice(1) };
+ if (typeof head === "string" && head.startsWith(TEASER_PREVIEW_PREFIX)) {
+ const seg = head.slice(TEASER_PREVIEW_PREFIX.length);
+ if (!seg || /[\/\\\0]/.test(seg) || seg === "." || seg === "..") return null;
+ if (!new Set(segmentIds).has(seg)) return null;
+ return { dir: teaserPreviewDir(projectDir, variant, seg), rest: rest.slice(1) };
+ }
if (typeof head === "string" && head.startsWith(POSTS_PREVIEW_PREFIX)) {
const seg = head.slice(POSTS_PREVIEW_PREFIX.length);
if (!seg || /[\/\\\0]/.test(seg) || seg === "." || seg === "..") return null;