Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit baf8e1c6b16e61d3b67bf539395fa7bf1403e7ad
parent 4b1d6b76a69dda159842e39ee8920a881d2aab26
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 18:28:42 -0500

umtool: Play the cut plays a post item -- its card (the build's own page) and its attachments on the cut's clock

PostItemPlayer (components/projects/review): a post item in Play's footage box -- the
card drawn by GET /api/report/post-item (postCardHtml, the page the render screenshots,
at the footage box's size, scaled), its attachments laid over the card's slot where the
render lays them (postLayout, stepBoxes) on the item's plan: the first one's first frame
while the words are read, then a video playing with its sound, a GIF looped, an image
held (pushed in on when it asks), a video's transcript under it. Each element follows
Play's clock and is re-seeked past 0.3 s of drift. playView carries the entry and its
plan; the strip tints it by the post's day.

/api/report/post-item: the card's page (fonts from the cut's faces, a CSS url never
HTML-escaped), an attachment with byte ranges (only a file under the project's
posts-media/), a take's post item; POST op "set" is updatePostItem, op "transcribe"
asks the editor's transcribe op for a video attachment's words (a local file, a job,
its words written beside it) and GET ?job= sets them on the attachment when done.

Play's Edit on a post item is "Edit this post": its bench (postBenchHref), Back to the
cut lands on the same second.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/report/post-item/route.ts | 173+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 43++++++++++++++++++++++++++++++++++++-------
Aumtool/components/projects/review/PostItemPlayer.tsx | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 13+++++++++++++
Mumtool/lib/report/playView.mjs | 26++++++++++++++++++++++++++
Mumtool/report-to-video/post-item.mjs | 6++++--
6 files changed, 461 insertions(+), 9 deletions(-)

diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -0,0 +1,173 @@ +import { readFile, realpath, stat } from "node:fs/promises"; +import path from "node:path"; +import { postCardHtml } from "umtool-report-to-video/post-item"; +import { jobState, startJob } from "@/lib/research/case-editor"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs"; +import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; +import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// A POST ITEM's page, its files and its knobs (report-to-video/post-item.mjs; +// umtool/docs/knobs.md, "A post item"): what Play the cut and the post bench +// draw a post item with, and the bench's writer. +// +// GET ?project&id&w&h[&phase=read|media][&take] the card's page, the HTML the build +// screenshots, at w × h (the footage box) +// GET ?project&file=posts-media/… an attachment (byte ranges): only a file +// under the project's posts-media/ +// GET ?project&font=regular|bold the cut's faces, for the page +// GET ?project&id&media=<i>&job=<id> a transcription's state; once done, its +// words are set on the attachment +// POST {project, op: "set", id, patch, token} updatePostItem (hold, layout, redact, media.<i>.…) +// POST {project, op: "transcribe", id, media} the editor's transcribe op on the attachment +// (a local file, a job), its words beside it + +const noStore = { "cache-control": "no-store" }; + +type Entry = Record<string, unknown> & { id: string; type?: string; media?: Array<Record<string, unknown>> }; + +async function itemOf(project: { dir: string }, manifest: Record<string, unknown>, id: string, take: string | null) { + let m = manifest; + if (take) m = (await resolveTakeManifest(project.dir, take, { base: manifest })).manifest as Record<string, unknown>; + const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Entry[]; + return { item: tl.find((e) => e?.type === "post" && e.id === id) ?? null, manifest: m }; +} + +/** A project file under posts-media/, never outside it (its real path checked). */ +async function postsFile(projectDir: string, rel: string): Promise<string | null> { + if (!rel.startsWith("posts-media/") || rel.split("/").includes("..")) return null; + const abs = path.join(projectDir, ...rel.split("/")); + const [real, root] = await Promise.all([realpath(abs).catch(() => null), realpath(path.join(projectDir, "posts-media")).catch(() => null)]); + if (!real || !root || !(real === root || real.startsWith(root + path.sep))) return null; + return abs; +} + +const TYPES: Record<string, string> = { + ".mp4": "video/mp4", ".m4v": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".gif": "image/gif", + ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".json": "application/json", + ".ttf": "font/ttf", ".otf": "font/otf", ".woff2": "font/woff2", +}; + +const wordsRelOf = (src: string) => `${src.replace(/\.[^./]+$/, "")}.words.json`; + +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const r = await resolveReport(q.get("project") ?? ""); + if ("error" in r) return new Response(r.error, { status: r.status }); + const render = ((r.manifest as Record<string, unknown>).render ?? {}) as Record<string, unknown>; + + const font = q.get("font"); + if (font) { + const file = font === "bold" ? render.fontBold : font === "regular" ? render.fontRegular : null; + if (typeof file !== "string" || !file) return new Response("no such face", { status: 404 }); + const body = await readFile(file).catch(() => null); + if (!body) return new Response("the face is not on disk", { status: 404 }); + return new Response(new Uint8Array(body), { headers: { "content-type": TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream", "cache-control": "max-age=3600" } }); + } + + const rel = q.get("file"); + if (rel) { + const abs = await postsFile(r.project.dir, rel); + if (!abs) return new Response("not a post item's file", { status: 404 }); + const st = await stat(abs).catch(() => null); + if (!st?.isFile()) return new Response("gone", { status: 404 }); + const etag = `"${st.size.toString(16)}-${Math.round(st.mtimeMs).toString(16)}"`; + return rangeResponse(request, { + abs, size: st.size, etag, + headers: { "content-type": TYPES[path.extname(abs).toLowerCase()] ?? "application/octet-stream", "accept-ranges": "bytes", "cache-control": "no-cache" }, + }); + } + + const id = q.get("id") ?? ""; + let found; + try { + found = await itemOf(r.project, r.manifest as Record<string, unknown>, id, q.get("take") || null); + } catch (e) { + return new Response(e instanceof Error ? e.message : String(e), { status: 400 }); + } + if (!found.item) return new Response(`no post item ${id}`, { status: 404 }); + + const job = q.get("job"); + if (job) { + const i = Number(q.get("media")); + const m = found.item.media?.[i]; + if (!m || typeof m.src !== "string") return Response.json({ error: `no attachment ${q.get("media")}` }, { status: 404 }); + try { + const st = await jobState(job); + if (!st.done) return Response.json({ state: "transcribing", status: st.status }, { headers: noStore }); + if (st.status !== "done") return Response.json({ state: "failed", status: st.status, tail: st.tail.slice(-3) }, { headers: noStore }); + const words = wordsRelOf(m.src); + if (!(await stat(path.join(r.project.dir, ...words.split("/"))).catch(() => null))) { + return Response.json({ state: "failed", status: "done", error: "the job ended without its words file" }, { headers: noStore }); + } + if (m.words !== words) { + await withEditNotes(r.project, async () => updatePostItem(r.project.dir, id, { media: { [i]: { words } } }, { token: await manifestToken(r.project.dir) })); + } + return Response.json({ state: "done", words }, { headers: noStore }); + } catch (e) { + return Response.json({ state: "failed", error: e instanceof Error ? e.message : String(e) }, { status: 502 }); + } + } + + const w = Math.round(Number(q.get("w")) || 0); + const h = Math.round(Number(q.get("h")) || 0); + if (!(w >= 160 && w <= 3840 && h >= 90 && h <= 2160)) return new Response("w and h are the footage box, in px", { status: 400 }); + const base = `/api/report/post-item?project=${encodeURIComponent(r.project.id)}`; + const parentShot = typeof found.item.parentShot === "string" ? `${base}&file=${encodeURIComponent(found.item.parentShot)}` : null; + const html = postCardHtml(found.item, { + width: w, height: h, + palette: (render.palette ?? {}) as Record<string, string>, + fonts: { regular: `${base}&font=regular`, bold: `${base}&font=bold` }, + phase: q.get("phase") === "media" ? "media" : "read", + parentShotUrl: parentShot, + }); + return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/post-item"); + if (refused) return refused; + 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 ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const id = String(body.id ?? ""); + if (body.op === "set") { + try { + const { result, editNotes } = await withEditNotes(r.project, () => + updatePostItem(r.project.dir, id, (body.patch ?? {}) as Record<string, unknown>, { token: body.token === undefined || body.token === null ? null : String(body.token) }), + ); + return Response.json({ ok: true, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + } + if (body.op === "transcribe") { + const found = await itemOf(r.project, r.manifest as Record<string, unknown>, id, null); + const i = Number(body.media); + const m = found.item?.media?.[i]; + if (!m || typeof m.src !== "string") return Response.json({ error: `${id} has no attachment ${String(body.media)}` }, { status: 404 }); + if (m.kind !== "video") return Response.json({ error: "only a video attachment has words to transcribe" }, { status: 400 }); + const abs = await postsFile(r.project.dir, m.src); + if (!abs) return Response.json({ error: "the attachment is not in the project's posts-media/" }, { status: 404 }); + const out = path.join(r.project.dir, ...wordsRelOf(m.src).split("/")); + try { + // The editor's transcription door: a local file, on a local worker, as a job -- never ASR by hand. + const job = await startJob("/api/ops/transcribe", { path: abs, words: true, out }); + return Response.json({ ok: true, jobId: job }, { headers: noStore }); + } catch (e) { + const status = (e as { status?: number }).status ?? 502; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status }); + } + } + return Response.json({ error: "op is set or transcribe" }, { status: 400 }); +} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -6,7 +6,7 @@ import { buttonVariants } from "@/components/ui/button"; import { useSharedNotes } from "@/components/notes/NotesProvider"; import { NoteThread } from "@/components/notes/NoteThread"; import type { Anchor, CutAsk, Note } from "@/lib/annotations/types"; -import { clipBenchHref, takeClipHref } from "@/lib/hrefs"; +import { clipBenchHref, postBenchHref, takeClipHref } 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"; @@ -27,6 +27,7 @@ import WhatPlays, { type WorkingCut } from "./WhatPlays"; import { useCutApp } from "../cutApp/CutApp"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; import AddPost from "./AddPost"; +import PostItemPlayer, { type PostPlan } from "./PostItemPlayer"; // --------------------------------------------------------------------------- // THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The @@ -117,6 +118,9 @@ export type PlayEntry = { rejected?: { reason: string; label: string; fact: boolean; why: string } | null; /** The verdict's fields as written (Reject prefills from them; its keep-in-place Undo writes them back). */ review?: { verdict: string | null; reason: string | null; correction: string | null; rejectNote: string | null }; + /** A post item (report-to-video/post-item.mjs): the entry its card is drawn from, and what plays when. */ + post?: Record<string, unknown> & { id: string }; + postPlan?: PostPlan; }; export type PlayViewData = { @@ -218,7 +222,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 push or a wipe is drawn as a dissolve, the chrome is composed on the estimate's clock;", + "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;", `${edge};`, `${sound}${picture ? `; ${picture}` : ""}.`, silent.length ? `No sound decoded for ${silent.join(", ")}.` : "", @@ -579,6 +583,8 @@ export default function PlayCut({ const editHref = useCallback(() => { const e = now(); const it = planRef.current.items[e.cur]; + // A post item: its own bench (the post's attachments' trims, its hold and crop). + if (it?.type === "post") return postBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100 } }); if (!it?.clip) return null; const at = Math.round(Math.max(0, e.t - it.from) * 100) / 100; // A take with its own timeline: ITS bench, its patch (never the project's clip of the same id). @@ -606,7 +612,7 @@ export default function PlayCut({ setPlaying(false); // Where Back lands: this place, written now (the one push is the bench's). window.history.replaceState(window.history.state, "", placeHref()); - if (app) { + if (app && planRef.current.items[now().cur]?.clip) { // In place: Play stays as it is; on the way back the clip (and the source second) is found again. const e = now(); const it = planRef.current.items[e.cur]; @@ -798,7 +804,9 @@ export default function PlayCut({ const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, tc) : null; const missing = !!item?.clip && !entry?.media; const broken = !!item && !!failed[item.id]; - const placeholder = item && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null; + // 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; + const placeholder = item && !postNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null; const pct = (n: number, of: number) => `${(n / of) * 100}%`; // The reel strip's counter: the composed schedule's stamps when there is one, else the estimate's. @@ -814,6 +822,19 @@ 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} + /> + ) : null; const placeholderCard = placeholder ? ( <div data-play-placeholder={placeholder.kind} @@ -961,6 +982,11 @@ export default function PlayCut({ <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)} + {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 })} + </div> + )} {placeholderCard} {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} />} @@ -976,6 +1002,7 @@ export default function PlayCut({ ) : ( <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"> {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)} + {postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}</div>} {placeholderCard} </div> )} @@ -1029,7 +1056,7 @@ export default function PlayCut({ <button type="button" data-play-edit={take && view.take?.ownTimeline ? "take" : ""} - disabled={!item?.clip} + disabled={!item?.clip && !postNow} onClick={editHere} className={cn(buttonVariants({ variant: "outline", size: "sm" }))} title={ @@ -1039,10 +1066,12 @@ export default function PlayCut({ : take ? "edit this clip on the bench (E): the edit goes to the project's cut, not this take's render; Back plays the project's cut" : "edit this clip on the bench (E); Back to the cut returns here" - : "a card is not edited on the clip bench" + : postNow + ? "open this post item's bench (E): its attachments' trims, sound and crop, its hold; Back returns here" + : "a card is not edited on the clip bench" } > - Edit this clip + {postNow ? "Edit this post" : "Edit this clip"} </button> <span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px] text-muted" data-play-hud=""> {tally.length > 0 && <span className="sr-only" data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")} />} diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -0,0 +1,209 @@ +"use client"; + +import { useEffect, useMemo, useRef, useState } from "react"; +import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item"; + +// --------------------------------------------------------------------------- +// A POST ITEM PLAYED (report-to-video/post-item.mjs; knobs.md, "Play the cut"): +// the card drawn by the build's own page (/api/report/post-item, the HTML the +// render screenshots) at the footage box's size and scaled into it, and its +// attachments laid over the card's slot where the render lays them +// (postLayout, stepBoxes) on the item's plan (postItemPlan): the first one's +// first frame while the words are read, then each in turn -- a video playing +// with its sound, a GIF looped, an image held (pushed in on when it asks). +// The cut's clock is Play's own; each element follows it, re-seeked when it +// drifts. A video's words (its transcript) show at the slot's foot. +// --------------------------------------------------------------------------- + +export type PostPlan = { + reading: number; + total: number; + held: number; + steps: Array<{ + kind: string; + at: number; + seconds: number; + srcFrom?: number; + srcTo?: number; + loop: boolean; + sound: boolean; + items: Array<Record<string, unknown> & { i: number; src: string; kind: string; crop?: number[]; push?: boolean; words?: string }>; + }>; +}; + +type Box = { width: number; height: number }; +type Cue = { start: number; end: number; text: string }; + +const pct = (n: number, of: number) => `${(n / of) * 100}%`; +/** How far a playing element may drift from the cut's clock before it is re-seeked. */ +const DRIFT = 0.3; + +export function postFileUrl(project: string, rel: string) { + return `/api/report/post-item?project=${encodeURIComponent(project)}&file=${encodeURIComponent(rel)}`; +} + +function MediaEl({ + project, m, box, b, step, s, playing, inStep, +}: { + project: string; + m: PostPlan["steps"][number]["items"][number]; + box: Box; + b: { x: number; y: number; width: number; height: number }; + step: PostPlan["steps"][number]; + s: number; + playing: boolean; + inStep: boolean; +}) { + const ref = useRef<HTMLVideoElement | null>(null); + const crop = Array.isArray(m.crop) && m.crop.length === 4 ? m.crop : null; + const inner: React.CSSProperties = crop + ? { position: "absolute", width: `${100 / crop[2]}%`, height: `${100 / crop[3]}%`, left: `${(-crop[0] / crop[2]) * 100}%`, top: `${(-crop[1] / crop[3]) * 100}%`, maxWidth: "none" } + : { position: "absolute", inset: 0, width: "100%", height: "100%" }; + const timed = step.kind === "video" || step.kind === "gif"; + // Before its step: its first frame. In it: the source second the plan says. + const target = timed ? (inStep ? mediaTimeAt(step, s) : step.srcFrom ?? 0) : null; + const run = playing && inStep; + useEffect(() => { + const v = ref.current; + if (!v || target === null) return; + if (Math.abs(v.currentTime - target) > DRIFT || !run) { + try { + v.currentTime = target; + } catch { + // not seekable yet: the next tick tries again + } + } + if (run && v.paused) void v.play().catch(() => {}); + if (!run && !v.paused) v.pause(); + }, [target, run]); + const progress = inStep ? Math.min(1, Math.max(0, (s - step.at) / Math.max(0.1, step.seconds))) : 0; + return ( + <div + data-post-media={m.i} + data-post-media-kind={m.kind} + className="absolute overflow-hidden" + style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height) }} + > + {timed ? ( + <video + ref={ref} + src={postFileUrl(project, String(m.src))} + data-post-video={m.i} + data-post-video-playing={run ? "1" : "0"} + preload="auto" + playsInline + loop={step.loop} + muted={!(step.sound && run)} + style={{ ...inner, objectFit: "fill" }} + /> + ) : ( + // eslint-disable-next-line @next/next/no-img-element + <img + src={postFileUrl(project, String(m.src))} + alt="" + data-post-image={m.i} + style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center" }} + /> + )} + </div> + ); +} + +export default function PostItemPlayer({ + project, take = null, entry, plan, box, s, playing, +}: { + project: string; + take?: string | null; + entry: Record<string, unknown> & { id: string }; + plan: PostPlan; + box: Box; + /** The item's own second (0: its first frame). */ + s: number; + playing: boolean; +}) { + const wrap = useRef<HTMLDivElement | null>(null); + const [scale, setScale] = useState(0); + useEffect(() => { + const node = wrap.current; + if (!node) return; + const ro = new ResizeObserver(([e]) => setScale(e.contentRect.width / box.width)); + ro.observe(node); + return () => ro.disconnect(); + }, [box.width]); + const layout = useMemo(() => postLayout(entry, box), [entry, box]); + const pageUrl = (phase: "read" | "media") => + `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}`; + const reading = s < plan.reading || !plan.steps.length; + const current = stepAt(plan, s); + // Beside the card, the first attachment is up (its first frame) while the words are read. + const shown = current ?? (layout.mode === "side" && plan.steps.length ? plan.steps[0] : null); + const inStep = !!current && shown === current; + const mediaPhase = layout.mode === "stack" && !reading; + // A video's words, when it was transcribed (media[i].words): the cue at its source second. + const wordsRel = shown?.kind === "video" ? (shown.items[0]?.words as string | undefined) : undefined; + const [cues, setCues] = useState<Record<string, Cue[]>>({}); + useEffect(() => { + if (!wordsRel || cues[wordsRel]) return; + let gone = false; + fetch(postFileUrl(project, wordsRel)) + .then((r) => (r.ok ? r.json() : null)) + .then((doc) => { + if (gone || !doc) return; + const list = (Array.isArray(doc.cues) ? doc.cues : []) as Cue[]; + setCues((c) => ({ ...c, [wordsRel]: list })); + }) + .catch(() => {}); + return () => { + gone = true; + }; + }, [wordsRel, project, cues]); + const src = shown && inStep ? mediaTimeAt(shown, s) : null; + const cue = wordsRel && src !== null ? (cues[wordsRel] ?? []).find((c) => src >= c.start && src < c.end) ?? null : null; + return ( + <div + ref={wrap} + data-post-play={entry.id} + data-post-layout={layout.mode} + data-post-step={reading ? "read" : current?.kind ?? "held"} + data-post-s={String(Math.round(s * 100) / 100)} + className="pointer-events-none absolute inset-0 overflow-hidden" + > + {scale > 0 && ( + <div className="absolute left-0 top-0" style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }}> + <iframe + title={`post ${entry.id}`} + src={pageUrl("read")} + data-post-card-frame="read" + className="absolute inset-0 border-0" + style={{ width: box.width, height: box.height, visibility: mediaPhase ? "hidden" : "visible" }} + /> + {layout.mode === "stack" && ( + <iframe + title={`post ${entry.id} (media)`} + src={pageUrl("media")} + data-post-card-frame="media" + className="absolute inset-0 border-0" + style={{ width: box.width, height: box.height, visibility: mediaPhase ? "visible" : "hidden" }} + /> + )} + </div> + )} + {shown && layout.slot && (layout.mode === "side" || mediaPhase) && ( + <> + {stepBoxes(shown, layout.slot).map((b: { x: number; y: number; width: number; height: number }, j: number) => ( + <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} /> + ))} + {cue && ( + <div + data-post-caption="" + className="absolute -translate-x-1/2 rounded bg-black/65 px-2 py-0.5 text-center text-white" + style={{ left: pct(layout.slot.x + layout.slot.width / 2, box.width), top: pct(layout.slot.y + layout.slot.height * 0.86, box.height), fontSize: Math.max(10, 34 * scale * (box.height / 1080)) }} + > + {cue.text} + </div> + )} + </> + )} + </div> + ); +} diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -265,6 +265,19 @@ export function projectAtHref(id: string, q: NoteOpt = {}): string { } /** The clip bench, one timeline entry. */ +/** + * A POST ITEM's bench (report-to-video/post-item.mjs): its attachments' trims, + * sound and crop, its hold. From Play ("Edit this clip"): Back lands `at` + * seconds into the item. + */ +export function postBenchHref(project: string, id: string, q: { play?: { at?: number | null } | null } = {}): string { + const play = q.play; + return withQuery( + `/projects/${encodePath(project)}/post/${encodeURIComponent(id)}`, + play ? { from: "play", at: play.at != null && play.at > 0 ? play.at.toFixed(2) : null } : {}, + ); +} + export function clipBenchHref( project: string, clip: string, diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -14,6 +14,7 @@ import { resolveFactcheck } from "umtool-report-to-video/factcheck"; import { clipDateKey, readManifest } from "../projects/report.mjs"; import { rejectionOf } from "./rejectReasons.mjs"; import { dateKeyLabel } from "./playCut.mjs"; +import { postDay, postItemPlan } from "umtool-report-to-video/post-item"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; import { readWorkingCut } from "./workingCut.mjs"; @@ -30,6 +31,30 @@ export function headingOf(e) { } /** + * A POST ITEM as Play plays it (post-item.mjs): the entry itself (its card is + * drawn from it, by the same HTML the build screenshots), the plan of what + * plays when, and the day for the reel strip's tint. Its files are served by + * /api/report/post-item, which serves only what a post item names. + */ +export function postPlayEntry(e) { + const day = postDay(e.date); + const dateKey = day ? Number(day.replace(/-/g, "")) : null; + const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim(); + return { + id: e.id, + type: "post", + heading: `${e.author ?? (e.handle ? `@${e.handle}` : "a post")}: ${words.length > 80 ? `${words.slice(0, 77)}…` : words || "(no words)"}`, + section: e.section ?? null, + dateKey, + dateLabel: dateKeyLabel(dateKey), + date: day || null, + quote: words || null, + post: e, + postPlan: postItemPlan(e), + }; +} + +/** * WHAT PLAYS BY DEFAULT is the LATEST take (operator, 1 Nov 2026): with no * `take`, the newest working take (workingCut.mjs) -- the project's manifest * as it is now with that take's patch, so the look is the next draft's and @@ -80,6 +105,7 @@ export async function playView(project, { take = null, bare = false } = {}) { const cache = await projectCache(project, manifest); const entries = await Promise.all( timeline.map(async (e) => { + if (e.type === "post") return postPlayEntry(e); if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null }; const win = pickWindow(await windowsFor(project, e, cache), null); const dateKey = clipDateKey(e); diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -506,6 +506,8 @@ export function stepBoxes(step, slot, gap = 12) { }); } +/** A string inside a quoted CSS url(): a <style> is raw text, so HTML entities would be read literally. */ +const cssStr = (s) => String(s ?? "").replace(/[\\'"\n<>]/g, (c) => (c === "<" ? "\\3c " : c === ">" ? "\\3e " : `\\${c === "\n" ? "a " : c}`)); const esc = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;"); @@ -649,8 +651,8 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p return `<!doctype html> <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=${width}, height=${height}"> <style> -@font-face { font-family: 'PostSans'; src: url('${esc(fonts.regular ?? "")}'); } -@font-face { font-family: 'PostSansBold'; src: url('${esc(fonts.bold ?? "")}'); } +@font-face { font-family: 'PostSans'; src: url('${cssStr(fonts.regular ?? "")}'); } +@font-face { font-family: 'PostSansBold'; src: url('${cssStr(fonts.bold ?? "")}'); } * { margin: 0; padding: 0; box-sizing: border-box; } html, body { width: ${width}px; height: ${height}px; overflow: hidden; background: ${transparent ? "transparent" : pal.bg}; } body { position: relative; font-family: 'PostSans', sans-serif; color: ${pal.fg}; -webkit-font-smoothing: antialiased; font-synthesis: none; }