commit def73e20e13c4295683243c689e79cc6db4f0761
parent fb50334a05aaa4781a84df6dda2d1577c5ed9d19
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 16:17:48 -0500
Merge main (lane/word-zoom) into lane/post-redact: both features kept -- a redacted word is a bar in its own card-word slot (marks keep the text's spaces, so a word zoom's indices and occurrence are the original's); a zoom whose match is a redacted word is refused (the project's list in validatePostItems, the corpus's and the markup in the build); the zoom's shots and Play's "As published" draw the bars and the zoom together
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
27 files changed, 1854 insertions(+), 44 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts
@@ -4,7 +4,10 @@ import { postCardHtml } from "umtool-report-to-video/post-item";
import { avatarUrls } from "umtool-report-to-video/post-avatars";
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 { StaleToken, StructureRefused, manifestToken, updatePostFx, updatePostItem, updatePostNarration } from "@/lib/report/manifest.mjs";
+import { pickedTake } from "umtool-report-to-video/post-narration";
+import { scriptWordTimes } from "umtool-report-to-video/word-zoom";
+import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxCli.mjs";
import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs";
import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs";
import { refuseCaller } from "@/lib/report/caller";
@@ -28,6 +31,12 @@ export const dynamic = "force-dynamic";
// 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
+// POST {project, op: "fx", id, fx, token} updatePostFx: a word zoom added ({add}), changed
+// ({set, patch}), removed ({remove}) (word-zoom.mjs)
+// POST {project, op: "take-words", id, worker?} the picked take's WORD TIMINGS: the editor's transcribe
+// op on it (or each of its parts), jobs -> {jobs}
+// GET ?project&id&takeWords=<job>,<job>… those jobs' state; once all are done, the words heard
+// aligned to the script and kept on the take
const noStore = { "cache-control": "no-store" };
@@ -94,6 +103,34 @@ export async function GET(request: Request) {
}
if (!found.item) return new Response(`no post item ${id}`, { status: 404 });
+ const tw = q.get("takeWords");
+ if (tw) {
+ const jobs = tw.split(",").filter(Boolean);
+ const take = pickedTake(found.item) as (Record<string, unknown> & { file: string; index: number; script?: string; parts?: unknown[] }) | null;
+ if (!take) return Response.json({ state: "failed", error: `${id} has no take` }, { status: 404 });
+ try {
+ const states = await Promise.all(jobs.map((j) => jobState(j)));
+ if (states.some((st) => !st.done)) return Response.json({ state: "transcribing", done: states.filter((st) => st.done).length, of: jobs.length }, { headers: noStore });
+ const bad = states.find((st) => st.status !== "done");
+ if (bad) return Response.json({ state: "failed", status: bad.status, error: bad.tail.slice(-3).join(" / ") }, { headers: noStore });
+ const sources = await takeWordSources(r.project.dir, take);
+ const heard: Array<{ w: string; start: number; end: number }> = [];
+ for (const src of sources) {
+ const doc = JSON.parse(await readFile(path.join(r.project.dir, ...wordsFileOf(src.file).split("/")), "utf8"));
+ heard.push(...recognizedOf(doc, src.offset));
+ }
+ if (!heard.length) return Response.json({ state: "failed", error: "the editor's transcription came back with no word timings (a parakeet worker keeps them)" }, { headers: noStore });
+ const n = (found.item as { narration?: { script?: string } }).narration;
+ const script = typeof take.script === "string" && take.script.trim() ? take.script : String(n?.script ?? "");
+ const t = scriptWordTimes(script, heard);
+ const { result } = await withEditNotes(r.project, async () =>
+ updatePostNarration(r.project.dir, id, { takeWords: { take: take.index, words: t.words } }, { token: await manifestToken(r.project.dir) }));
+ return Response.json({ state: "done", heard: t.heard, of: t.of, entry: result.entry, token: result.token }, { headers: noStore });
+ } catch (e) {
+ return Response.json({ state: "failed", error: e instanceof Error ? e.message : String(e) }, { status: 502 });
+ }
+ }
+
const job = q.get("job");
if (job) {
const i = Number(q.get("media"));
@@ -164,6 +201,36 @@ export async function POST(request: Request) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
}
+ if (body.op === "fx") {
+ try {
+ const { result, editNotes } = await withEditNotes(r.project, () =>
+ updatePostFx(r.project.dir, id, (body.fx ?? {}) as Record<string, unknown>, { token: body.token === undefined || body.token === null ? null : String(body.token) }),
+ );
+ return Response.json({ ok: true, entry: result.entry, index: result.index, 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 === "take-words") {
+ const found = await itemOf(r.project, r.manifest as Record<string, unknown>, id, null);
+ const take = found.item ? (pickedTake(found.item) as (Record<string, unknown> & { file: string }) | null) : null;
+ if (!take) return Response.json({ error: `${id} has no take to time` }, { status: 404 });
+ try {
+ const sources = await takeWordSources(r.project.dir, take);
+ const worker = typeof body.worker === "string" && body.worker ? { workerId: body.worker } : {};
+ // The editor's transcription door, as for an attachment: a local file, a job -- never ASR here.
+ const jobs = [];
+ for (const src of sources) {
+ jobs.push(await startJob("/api/ops/transcribe", { path: path.join(r.project.dir, ...src.file.split("/")), words: true, out: path.join(r.project.dir, ...wordsFileOf(src.file).split("/")), ...worker }));
+ }
+ return Response.json({ ok: true, jobs }, { headers: noStore });
+ } catch (e) {
+ const status = (e as { status?: number }).status ?? 502;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
+ }
+ }
if (body.op === "transcribe") {
const found = await itemOf(r.project, r.manifest as Record<string, unknown>, id, null);
const i = Number(body.media);
@@ -182,5 +249,5 @@ export async function POST(request: Request) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
}
}
- return Response.json({ error: "op is set or transcribe" }, { status: 400 });
+ return Response.json({ error: "op is set, fx, take-words or transcribe" }, { status: 400 });
}
diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx
@@ -10,6 +10,8 @@ import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds
import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer";
import BlurBoxPad from "./BlurBoxPad";
import PostNarrationPanel from "./PostNarrationPanel";
+import PostZoomPanel from "./PostZoomPanel";
+import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
// THE POST BENCH, the client half (PostBenchPage.tsx): the item played on its
@@ -214,6 +216,13 @@ export default function PostBench({
return () => clearTimeout(t);
});
+ const zoomMarks = useMemo(
+ () =>
+ (wordZoomTimes(entry, render) as Array<{ i: number; t?: number }>)
+ .filter((z) => typeof z.t === "number")
+ .map((z) => ({ i: z.i, ...zoomSpan((entry.fx as Array<Record<string, unknown>>)[z.i], z.t as number) })),
+ [entry, render],
+ );
const stepOf = (i: number) => plan.steps.find((st) => st.items.some((m) => m.i === i)) ?? null;
const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
const reading = readingSeconds(entry);
@@ -270,8 +279,25 @@ export default function PostBench({
{st.kind} {st.seconds.toFixed(1)} s
</div>
))}
+ {/* Its word zooms (word-zoom.mjs): each from its lead-in to back out. */}
+ {zoomMarks.map((z) => (
+ <div key={z.i} className="absolute inset-y-0 border-x border-amber-400/80 bg-amber-400/25" style={{ left: `${(z.t0 / total) * 100}%`, width: `${((z.t3 - z.t0) / total) * 100}%` }} title={`word zoom ${z.i + 1}`} data-post-bench-zoom-mark={z.i} />
+ ))}
<div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} />
</div>
+ <PostZoomPanel
+ project={project}
+ entry={entry}
+ token={token}
+ render={render}
+ s={s}
+ setS={setS}
+ onEntry={(e, t) => {
+ setEntry(e as Entry);
+ setSaved(e as Entry);
+ setToken(t);
+ }}
+ />
<PostNarrationPanel
project={project}
entry={entry}
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -12,6 +12,7 @@ import { usePeaks } from "./bench/usePeaks";
import { useNotes } from "@/lib/annotations/useNotes";
import { MIC_KEY, ls, useMic } from "./useMic";
import type { PostPlan } from "./review/PostItemPlayer";
+import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
// A POST's NARRATION ON THE BENCH (report-to-video/post-narration.mjs;
@@ -283,6 +284,14 @@ export default function PostNarrationPanel({
const tMedia = useMemo(() => projectFileMedia({ project, path: picked?.file ?? "", seconds: picked?.seconds || 1 }), [project, picked?.file, picked?.seconds]);
const tPeaks = usePeaks(picked ? tMedia : { ...tMedia, peaksUrl: null });
const [showWhole, setShowWhole] = useState(false);
+ // The word zooms on the read (word-zoom.mjs): worked out once per change, not per frame.
+ const zoomSpans = useMemo(
+ () =>
+ wordZoomTimes(entry, render)
+ .filter((z) => typeof z.t === "number")
+ .map((z) => ({ i: z.i, ...zoomSpan((entry.fx as Array<Record<string, unknown>>)[z.i], z.t as number) })),
+ [entry, render],
+ );
const sch = plan.narration ?? null;
const total = plan.total;
const pct = (v: number) => `${(v / Math.max(0.1, total)) * 100}%`;
@@ -463,6 +472,10 @@ export default function PostNarrationPanel({
<span key={p.n} className="absolute inset-y-0 w-px bg-amber-200/70" style={{ left: `${(p.start / picked.seconds) * 100}%` }} title={`part ${p.n}`} />
))}
</div>
+ {/* The word zooms on the read: from the lead-in to back out (word-zoom.mjs). */}
+ {zoomSpans.map((sp) => (
+ <div key={`z${sp.i}`} className="pointer-events-none absolute inset-y-0 border-x-2 border-amber-300 bg-amber-300/10" style={{ left: pct(sp.t0), width: pct(sp.t3 - sp.t0) }} title={`word zoom ${sp.i + 1}`} data-post-lane-zoom={sp.i} />
+ ))}
<div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: pct(s) }} />
</div>
</div>
diff --git a/umtool/components/projects/PostZoomPanel.tsx b/umtool/components/projects/PostZoomPanel.tsx
@@ -0,0 +1,290 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
+import {
+ WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, WORD_ZOOM_LIMITS, cardTokens, normWord, readingEstimate, resolveWordZoom, targetTextOf, wordZoomTimes, zoomSpan,
+} from "umtool-report-to-video/word-zoom";
+
+// ---------------------------------------------------------------------------
+// A POST's WORD ZOOMS ON THE BENCH (report-to-video/word-zoom.mjs; knobs.md, "A
+// word zoom"): the card's words, each clickable (shift-click: a phrase) --
+// Zoom here adds the zoom on them (its match and occurrence filled) -- then each
+// zoom's knobs: scale, lead, hold, ease, highlight, and its moment: from the
+// take's word timings (Get word timings: the EDITOR's transcription, a job) or
+// `at`, nudged. Every change is one write (POST /api/report/post-item, op "fx").
+// ---------------------------------------------------------------------------
+
+type Entry = Record<string, unknown> & { id: string; fx?: Array<Record<string, unknown>> };
+type Sel = { target: string; from: number; to: number } | null;
+
+const r2 = (v: number) => Math.round(v * 100) / 100;
+
+/** The word as the card shows it, its edge punctuation off (what `match` is written as). */
+const bare = (tok: string) => tok.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "") || tok;
+
+export default function PostZoomPanel({
+ project, entry, token, render, s, setS, onEntry,
+}: {
+ project: string;
+ entry: Entry;
+ token: string | null;
+ render: Record<string, unknown>;
+ s: number;
+ setS: (s: number) => void;
+ onEntry: (e: Entry, token: string | null) => void;
+}) {
+ const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
+ const [error, setError] = useState<string | null>(null);
+ const [status, setStatus] = useState<string | null>(null);
+ const [sel, setSel] = useState<Sel>(null);
+ const targets = useMemo(() => {
+ const out: Array<{ target: string; label: string; text: string }> = [{ target: "post", label: "the post", text: String(targetTextOf(entry, "post") ?? "") }];
+ const parents = Array.isArray(entry.parents) ? entry.parents : [];
+ parents.slice(0, 2).forEach((_, i) => {
+ const t = targetTextOf(entry, `parent:${i}`);
+ if (t) out.push({ target: `parent:${i}`, label: i === 0 ? "the post it answers" : `the post ${i + 1} up`, text: t });
+ });
+ const q = targetTextOf(entry, "quoted");
+ if (q) out.push({ target: "quoted", label: "the post it quotes", text: q });
+ return out;
+ }, [entry]);
+ const [target, setTarget] = useState("post");
+ const text = targets.find((t) => t.target === target)?.text ?? "";
+ const tokens = useMemo(() => cardTokens(text).filter((t) => t.tok !== undefined) as Array<{ tok: string; i: number }>, [text]);
+ const list = Array.isArray(entry.fx) ? entry.fx : [];
+ const times = useMemo(() => wordZoomTimes(entry, render), [entry, render]);
+ const narrated = isNarrated(entry);
+ const take = pickedTake(entry) as (Record<string, unknown> & { words?: unknown[] }) | null;
+
+ const send = async (fx: Record<string, unknown>) => {
+ setError(null);
+ const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "fx", id: entry.id, fx, token }) });
+ const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[] };
+ if (!res.ok || !j.entry) {
+ setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`);
+ return null;
+ }
+ onEntry(j.entry, j.token ?? null);
+ return j.entry;
+ };
+
+ const zoomHere = async () => {
+ if (!sel) return;
+ const words = tokens.slice(sel.from, sel.to + 1).map((t) => t.tok);
+ const match = words.length === 1 ? bare(words[0]) : [bare(words[0]), ...words.slice(1, -1), bare(words[words.length - 1])].join(" ");
+ // Its occurrence: how many times the same run of words came before it, plus one.
+ const want = words.map(normWord);
+ let occurrence = 1;
+ for (let i = 0; i < sel.from; i += 1) if (want.every((w, k) => normWord(tokens[i + k]?.tok ?? "") === w)) occurrence += 1;
+ const add: Record<string, unknown> = { kind: "word-zoom", match, ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) };
+ // An un-narrated post has no read to time it by: the reading estimate, to nudge.
+ if (!narrated) add.at = readingEstimate(sel.from);
+ const e = await send({ add });
+ if (e) {
+ setStatus(`zoom added on "${match}"`);
+ setSel(null);
+ }
+ };
+
+ // Get word timings: the editor's transcription of the picked take, a job (or one per part), followed.
+ const [wordsJob, setWordsJob] = useState<{ jobs: string[]; state: string; error?: string } | null>(null);
+ const getWords = async () => {
+ setError(null);
+ const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "take-words", id: entry.id }) });
+ const j = (await res.json().catch(() => ({}))) as { jobs?: string[]; error?: string };
+ if (!res.ok || !j.jobs?.length) {
+ setWordsJob({ jobs: [], state: "failed", error: j.error ?? `HTTP ${res.status}` });
+ return;
+ }
+ setWordsJob({ jobs: j.jobs, state: "transcribing" });
+ };
+ useEffect(() => {
+ if (wordsJob?.state !== "transcribing") return;
+ const t = setTimeout(async () => {
+ const res = await fetch(`/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&takeWords=${encodeURIComponent(wordsJob.jobs.join(","))}`);
+ const j = (await res.json().catch(() => ({}))) as { state?: string; entry?: Entry; token?: string; error?: string; heard?: number; of?: number };
+ if (j.state === "done" && j.entry) {
+ onEntry(j.entry, j.token ?? null);
+ setStatus(`word timings: ${j.heard} of ${j.of} words heard`);
+ setWordsJob(null);
+ } else if (j.state !== "transcribing") setWordsJob({ ...wordsJob, state: "failed", error: j.error ?? "the transcription failed" });
+ else setWordsJob({ ...wordsJob });
+ }, 1500);
+ return () => clearTimeout(t);
+ }, [wordsJob, project, entry.id, onEntry]);
+
+ const knob = (i: number, key: "scale" | "lead" | "hold", step: number) => {
+ const fx = resolveWordZoom(list[i]);
+ const [lo, hi] = WORD_ZOOM_LIMITS[key];
+ return (
+ <label className="flex items-center gap-1" key={key}>
+ {key}
+ <input
+ type="number"
+ step={step}
+ min={lo}
+ max={hi}
+ defaultValue={Number(fx[key])}
+ key={`${entry.id}:${i}:${key}:${String(fx[key])}`}
+ onBlur={(ev) => {
+ const v = Number(ev.target.value);
+ if (Number.isFinite(v) && v !== Number(fx[key])) void send({ set: i, patch: { [key]: v === WORD_ZOOM_DEFAULTS[key] ? null : v } });
+ }}
+ className="w-14 rounded border border-seam bg-ground px-1 py-0.5"
+ data-post-zoom-knob={key}
+ />
+ </label>
+ );
+ };
+
+ return (
+ <section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12.5px]" data-post-zoom-panel={entry.id}>
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="micro m-0">word zoom</h2>
+ {targets.length > 1 && (
+ <select value={target} onChange={(e) => (setTarget(e.target.value), setSel(null))} data-post-zoom-target="">
+ {targets.map((t) => (
+ <option key={t.target} value={t.target}>
+ {t.label}
+ </option>
+ ))}
+ </select>
+ )}
+ {narrated && (
+ <span className="ml-auto flex items-center gap-2">
+ <span className="text-text-2" data-post-zoom-words-state="">
+ {take?.words?.length ? `the take is timed (${take.words.length} words)` : "the take has no word timings"}
+ </span>
+ {wordsJob?.state === "transcribing" ? (
+ <span data-post-zoom-words-running="">transcribing on the editor…</span>
+ ) : (
+ <button type="button" className={btn} onClick={() => void getWords()} data-post-zoom-get-words="">
+ Get word timings
+ </button>
+ )}
+ </span>
+ )}
+ </div>
+ {wordsJob?.state === "failed" && <p className="m-0 text-[var(--color-blocking,#c33)]">{wordsJob.error}</p>}
+ <p className="m-0 text-text-2">Click a word (shift-click another: a phrase), then Zoom here.</p>
+ <div className="max-h-40 overflow-y-auto rounded border border-seam bg-ground p-2 leading-7" data-post-zoom-words={target}>
+ {tokens.map((t) => {
+ const on = sel && sel.target === target && t.i >= sel.from && t.i <= sel.to;
+ return (
+ <button
+ key={t.i}
+ type="button"
+ className={cn("mr-1 rounded px-0.5", on ? "bg-amber-400/40 ring-1 ring-amber-400" : "hover:bg-white/10")}
+ onClick={(ev) => {
+ if (ev.shiftKey && sel && sel.target === target) setSel({ target, from: Math.min(sel.from, t.i), to: Math.max(sel.to, t.i) });
+ else setSel({ target, from: t.i, to: t.i });
+ }}
+ data-post-zoom-word={t.i}
+ >
+ {t.tok}
+ </button>
+ );
+ })}
+ </div>
+ <div className="flex items-center gap-2">
+ <button type="button" className={btn} disabled={!sel} onClick={() => void zoomHere()} data-post-zoom-here="">
+ Zoom here
+ </button>
+ {sel && (
+ <span className="text-text-2" data-post-zoom-sel="">
+ “{tokens.slice(sel.from, sel.to + 1).map((t) => t.tok).join(" ")}”
+ </span>
+ )}
+ </div>
+ {list.map((fx0, i) => {
+ const fx = resolveWordZoom(fx0);
+ const t = times[i] as { t?: number; source?: string; error?: string };
+ const at = typeof t?.t === "number" ? t.t : null;
+ const span = at !== null ? zoomSpan(fx0, at) : null;
+ const up = !!span && s >= span.t0 && s < span.t3;
+ return (
+ <div key={i} className={cn("space-y-1.5 rounded border p-2", up ? "border-amber-400/70" : "border-seam")} data-post-zoom-fx={i}>
+ <div className="flex flex-wrap items-center gap-2">
+ <b>
+ #{i + 1} “{fx.match}”
+ </b>
+ <span className="text-text-2">
+ {fx.target !== "post" ? `${fx.target} · ` : ""}
+ {fx.occurrence > 1 ? `its ${fx.occurrence}th time · ` : ""}
+ </span>
+ {at !== null ? (
+ <span data-post-zoom-at={String(at)}>
+ at {at.toFixed(2)} s {t.source === "words" ? "(the take's words)" : "(set by hand)"}
+ </span>
+ ) : (
+ <span className="text-[var(--color-blocking,#c33)]" data-post-zoom-no-time="">
+ {t?.error}
+ </span>
+ )}
+ <button type="button" className="ink-link ml-auto" onClick={() => setS(Math.max(0, (span?.t0 ?? 0) - 0.3))} disabled={!span} data-post-zoom-go={i}>
+ play it
+ </button>
+ <button type="button" className="ink-link" onClick={() => void send({ remove: i })} data-post-zoom-remove={i}>
+ remove
+ </button>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ at
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(Math.max(0, (at ?? 0) - 0.1)) } })} data-post-zoom-nudge="-">
+ −0.1
+ </button>
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2((at ?? 0) + 0.1) } })} data-post-zoom-nudge="+">
+ +0.1
+ </button>
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(s) } })} data-post-zoom-at-playhead="">
+ at playhead
+ </button>
+ {typeof fx0.at === "number" && narrated && (
+ <button type="button" className="ink-link" onClick={() => void send({ set: i, patch: { at: null } })} data-post-zoom-from-words="">
+ from the words
+ </button>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {knob(i, "scale", 0.1)}
+ {knob(i, "lead", 0.1)}
+ {knob(i, "hold", 0.1)}
+ <label className="flex items-center gap-1">
+ ease
+ <select value={fx.ease} onChange={(e) => void send({ set: i, patch: { ease: e.target.value === WORD_ZOOM_DEFAULTS.ease ? null : e.target.value } })} data-post-zoom-knob="ease">
+ {WORD_ZOOM_EASES.map((x) => (
+ <option key={x} value={x}>
+ {x}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="flex items-center gap-1">
+ <input type="checkbox" checked={fx.highlight !== false} onChange={(e) => void send({ set: i, patch: { highlight: e.target.checked ? null : false } })} data-post-zoom-knob="highlight" />
+ highlight
+ </label>
+ {fx.highlight !== false && (
+ <input
+ type="color"
+ defaultValue={String(fx.highlight).length === 7 ? String(fx.highlight) : WORD_ZOOM_DEFAULTS.highlight}
+ key={`${entry.id}:${i}:hl:${String(fx.highlight)}`}
+ onBlur={(e) => e.target.value !== String(fx.highlight) && void send({ set: i, patch: { highlight: e.target.value === WORD_ZOOM_DEFAULTS.highlight ? null : e.target.value } })}
+ data-post-zoom-knob="color"
+ />
+ )}
+ </div>
+ </div>
+ );
+ })}
+ {status && <p className="m-0 text-text-2" data-post-zoom-status="">{status}</p>}
+ {error && (
+ <p className="m-0 text-[var(--color-blocking,#c33)]" data-post-zoom-error="">
+ {error}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -1,9 +1,10 @@
"use client";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item";
import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration";
import { blurCqw, blurOf } from "umtool-report-to-video/post-censor";
+import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
// A POST ITEM PLAYED (report-to-video/post-item.mjs; knobs.md, "Play the cut"):
@@ -18,8 +19,54 @@ import { blurCqw, blurOf } from "umtool-report-to-video/post-censor";
// the pitch kept), so a fast-forward SPEEDS the item up rather than seeking
// it forward every few frames. The voice plays at that times the read's own
// `rate` (post-narration.mjs). A video's words show at the slot's foot.
+//
+// A WORD ZOOM (word-zoom.mjs) plays live on the same curve as the render's: the
+// card's contents scaled toward the word's box (measured in the card page: its
+// `data-w` spans) inside the card, which clips them, its highlight fading in
+// under the word -- the card page's own elements transformed, nothing redrawn.
// ---------------------------------------------------------------------------
+type Rect = { x: number; y: number; width: number; height: number };
+/** A zoom of the item, measured in its card page: its span on the item's clock, the card's region, the word's box. */
+type LiveZoom = { i: number; span: ReturnType<typeof zoomSpan>; scope: string; from: number; to: number; color: string | null; region: Rect; word: Rect };
+
+/** The card's children placed so the region shows `win` (zoomWindow) at z; their layout boxes measured before any transform. */
+function applyZoom(doc: Document, z: LiveZoom | null, zf: number, hl: number, boxes: Map<Element, Rect>) {
+ const card = doc.querySelector("[data-post-card]");
+ if (!card) return;
+ const kids = Array.from(card.children) as HTMLElement[];
+ if (!z || zf <= 1.0005) {
+ for (const k of kids) if (k.style.transform) k.style.transform = "";
+ } else {
+ const win = zoomWindow(z.region, z.word, z.span.scale, zf);
+ for (const k of kids) {
+ const c = boxes.get(k);
+ if (!c) continue;
+ // Window point P is drawn at R + (P - W)·z: a child's corner C moves by R - z·W + (z - 1)·C, scaled about it.
+ const tx = z.region.x - zf * win.x + (zf - 1) * c.x;
+ const ty = z.region.y - zf * win.y + (zf - 1) * c.y;
+ k.style.transformOrigin = "0 0";
+ k.style.transform = `translate(${tx}px, ${ty}px) scale(${zf})`;
+ }
+ }
+ doc.querySelectorAll("[data-w-live-hl]").forEach((el) => {
+ (el as HTMLElement).style.background = "";
+ (el as HTMLElement).style.boxShadow = "";
+ el.removeAttribute("data-w-live-hl");
+ });
+ if (z && z.color && hl > 0) {
+ const [r, g, b] = [1, 3, 5].map((o) => parseInt((z.color!.length === 4 ? z.color!.replace(/^#(.)(.)(.)$/, "#$1$1$2$2$3$3") : z.color!).slice(o, o + 2), 16));
+ for (let i = z.from; i <= z.to; i += 1) {
+ const el = doc.querySelector(`[data-w="${z.scope}:${i}"]`) as HTMLElement | null;
+ if (!el) continue;
+ el.setAttribute("data-w-live-hl", "");
+ el.style.background = `rgba(${r}, ${g}, ${b}, ${WORD_ZOOM_HIGHLIGHT_ALPHA * hl})`;
+ el.style.boxShadow = `inset 0 -0.12em 0 rgba(${r}, ${g}, ${b}, ${hl})`;
+ el.style.borderRadius = "0.16em";
+ }
+ }
+}
+
/** A narrated item's mix on its clock (post-narration.mjs narrationSchedule). */
export type NarrationSchedule = { at: number; seconds: number; takeSeconds?: number; rate?: number; voiceEnd: number; rampEnd: number; wet: number; lowpassHz: number; duck: boolean; attach?: string; lufs?: number };
@@ -291,6 +338,69 @@ export default function PostItemPlayer({
gone = true;
};
}, [wordsRel, project, cues]);
+ // ---- the word zooms, live: measured in the card page once it is drawn, applied on the item's clock ----
+ const readFrame = useRef<HTMLIFrameElement | null>(null);
+ const [zooms, setZooms] = useState<LiveZoom[]>([]);
+ const boxes = useRef<Map<Element, Rect>>(new Map());
+ const zoomTimes = useMemo(() => (Array.isArray(entry.fx) && entry.fx.length ? wordZoomTimes(entry, undefined, plan.narration as never) : []), [entry, plan.narration]);
+ const measure = useCallback(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return false;
+ const card = doc.querySelector("[data-post-card]") as HTMLElement | null;
+ const list = Array.isArray(entry.fx) ? (entry.fx as Array<Record<string, unknown>>) : [];
+ if (!card || !list.length) {
+ setZooms([]);
+ return true;
+ }
+ const rect = (el: Element): Rect => {
+ const b = el.getBoundingClientRect();
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
+ };
+ // Laid out untransformed first: the boxes every zoom is placed from.
+ for (const k of Array.from(card.children) as HTMLElement[]) k.style.transform = "";
+ boxes.current = new Map(Array.from(card.children).map((k) => [k, rect(k)]));
+ const c = rect(card);
+ const r = Math.round(18 * (box.height / 1080)) + 1;
+ const region = { x: c.x + r, y: c.y + r, width: c.width - 2 * r, height: c.height - 2 * r };
+ const out: LiveZoom[] = [];
+ list.forEach((fx0, i) => {
+ const t = zoomTimes[i] as { t?: number } | undefined;
+ if (typeof t?.t !== "number") return;
+ const fx = resolveWordZoom(fx0);
+ const m = findMatch(targetTextOf(entry, fx.target) ?? "", fx.match, fx.occurrence);
+ if (m.error) return;
+ const scope = targetScope(fx.target);
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (let w = m.from; w <= m.to; w += 1) {
+ const el = doc.querySelector(`[data-w="${scope}:${w}"]`);
+ if (!el) return;
+ const b = rect(el);
+ x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y); x1 = Math.max(x1, b.x + b.width); y1 = Math.max(y1, b.y + b.height);
+ }
+ out.push({ i, span: zoomSpan(fx0, t.t), scope, from: m.from, to: m.to, color: fx.highlight === false ? null : String(fx.highlight), region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } });
+ });
+ setZooms(out);
+ return true;
+ }, [entry, zoomTimes, box.height]);
+ const onFrameLoad = useCallback(() => {
+ let tries = 0;
+ const tick = () => {
+ if (measure() || tries++ > 50) return;
+ setTimeout(tick, 100);
+ };
+ tick();
+ }, [measure]);
+ useEffect(() => {
+ // The item changed under a loaded page (a knob, a zoom added): measure again.
+ onFrameLoad();
+ }, [onFrameLoad]);
+ const live = zooms.find((z) => s >= z.span.t0 && s < z.span.t3) ?? null;
+ const zf = live ? zoomAt(live.span, zoomProgressAt(live.span, s)) : 1;
+ const hl = live ? highlightAt(live.span, s) : 0;
+ useEffect(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (doc) applyZoom(doc, live, zf, hl, boxes.current);
+ }, [live, zf, hl]);
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 (
@@ -305,6 +415,9 @@ export default function PostItemPlayer({
data-post-wet={mix ? String(Math.round(wetGainAt(mix, s) * 100) / 100) : undefined}
data-post-dry={mix ? String(Math.round(dryGainAt(mix, s) * 100) / 100) : undefined}
data-post-narration-playing={mix ? (playing && speaking ? "1" : "0") : undefined}
+ data-post-zooms={zooms.length ? String(zooms.length) : undefined}
+ data-post-zoom={zooms.length ? String(Math.round(zf * 100) / 100) : undefined}
+ data-post-zoom-fx={live ? String(live.i) : undefined}
className="pointer-events-none absolute inset-0 overflow-hidden"
>
{mix && voiceTake && (
@@ -315,6 +428,8 @@ export default function PostItemPlayer({
<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}`}
+ ref={readFrame}
+ onLoad={onFrameLoad}
src={pageUrl("read")}
data-post-card-frame="read"
className="absolute inset-0 border-0"
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -84,6 +84,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` |
| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings) |
| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration`. Refused in the build's words (**exit 1**) |
+| `posts fx <project> <item> [ls]` · `add word-zoom --match "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--scale s] [--hold s] [--lead s] [--ease out\|inOut\|snap] [--highlight #rrggbb\|off]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]` | a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`) |
| `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is |
| `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one |
| `posts redact <project> ls \| add "<term>" [--substring] [--note "…"] \| remove <n> [--json]` | **REDACTED WORDS** ([knobs.md](knobs.md#redacted-words-blanked-from-what-is-published)): the project's list (`render.posts.redact`, `updatePostRedact`) of words or phrases blanked from everything the cut publishes -- a solid bar on the rendered card, left out of a synthesized read, a post's chapter line and an attachment's captions; matched without case, as whole words (`--substring`: inside words too), a phrase across any spaces or punctuation. The posts' words and the scripts are never rewritten. `ls` numbers the terms as `remove` takes them, and counts the corpus's (`transcripts/redactions.json`) and the posts marked up in the cut's channels (`posts-markup.json`). A term already listed is refused (**exit 1**) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -707,7 +707,11 @@ umtool's own views (the bench, Play, the recording page) show the words; Play's
and the recording teleprompter strikes through the words to leave out of your read. A term matches without regard
to case, as whole words unless `wholeWord: false`, the words of a phrase across any spaces or punctuation (or none,
as a handle runs them together), a possessive `'s` with it. A redaction file that is there and broken FAILS the build
-(a render that ignored it would publish what it was told to blank).
+(a render that ignored it would publish what it was told to blank). With a **word zoom** (below): the bars keep the
+redacted words' places (a phrase stays as many card words, so a zoom's `occurrence` is counted on the original words
+and lands on the same word), Play's **As published** shows the bars and the zoom together, and a zoom whose match
+is a redacted word is REFUSED -- the project's list at every write, the corpus's and a post's markup by the build: a
+published card never pushes in on a blank.
| Knob | In umtool | From a terminal | Route |
|---|---|---|---|
@@ -715,6 +719,22 @@ as a handle runs them together), a possessive `'s` with it. A redaction file tha
| the corpus's list — `transcripts/redactions.json`, the same shape (or `{terms: […]}`): blanked in every project | — | read by every build; the editor's to write | — |
| one post's markup — `transcripts/channels/<slug>/posts-markup.json`, `{"<postId>": {redact?: [{term, wholeWord?, scope?} \| {start, end, scope?, index?}], censor?: [{media, blur?}]}}`: a term in a `scope` (`text`, `parent`, `quoted`; absent, the whole post), or a span of the archived text in code units (`index`: which parent, nearest first); `censor` blurs the post's attachment `media` (its index; `blur` as `media[i].blur`'s keys, absent the whole frame) in every project | — | read by every build of a cut playing the post; the editor's to write | — |
+## A word zoom (a post item's card pushed in on a word as it is read)
+
+`fx: [{kind: "word-zoom", match, …}]` on a post item ([report-video.md](report-video.md#a-word-zoom): the shape, the
+time, the curve, the render). One writer, `updatePostFx` (`lib/report/manifest.mjs`), refused in the build's words
+(`validatePostFx`, `report-to-video/word-zoom.mjs`): unknown keys, a match not in the target's words, a knob out of
+its bounds. Its bench is the post bench's **word zoom** block; Play the cut zooms the card live on the same curve.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| a word zoom — `match` (the word or phrase as the card shows it; case and edge punctuation aside), `occurrence` (its n-th time, default 1), `target` (`post` default, `quoted`, `parent:<i>`) | post bench, **word zoom**: click a word (shift-click another: a phrase), **Zoom here** (match and occurrence filled) | `umtool posts fx <p> <item> add word-zoom --match "barbecue" [--occurrence n] [--target quoted]` | `POST /api/report/post-item {project, op: "fx", id, fx: {add: {kind: "word-zoom", match, …}}, token}` |
+| `at` — its moment, item seconds (0–600); absent: the matched word's start in the picked take's word timings, on the item's clock (lead + start ÷ the read's `rate`). An un-narrated post needs it (**Zoom here** and `add` fill the reading estimate: 1 s + 3 words a second) | the zoom's **−0.1** / **+0.1**, **at playhead**, **from the words** (clears it) | `umtool posts fx <p> <item> set <n> --at 4.2` (`--at default`: from the words) | `fx: {set: <i>, patch: {at}}` (`null` clears) |
+| `scale` 1.2–4 (default 2), `lead` 0–3 s in before the word (0.5), `hold` 0–10 s on it (1.2), `ease` `out`\|`inOut`\|`snap` (`inOut`), `highlight` a colour `#rrggbb` (`#ffd84d`, drawn at 42% under the words with a solid underline) or `false` | the zoom's **scale**, **lead**, **hold**, **ease**, **highlight** (and its colour); the way back out is 0.4 s on the same ease | `set <n> --scale 2.5 --lead 0.3 --hold 1.5 --ease snap --highlight off` (`default` clears one) | `fx: {set: <i>, patch: {…}}` |
+| remove one | the zoom's **remove** | `umtool posts fx <p> <item> remove <n>` (1 = the first, as `ls` shows) | `fx: {remove: <i>}` |
+| list them, each with its time and where it came from | the block's rows; the plan strip and the read lane mark each from its lead-in to back out | `umtool posts fx <p> <item> [ls] [--json]` | — |
+| `narration.takes[i].words` — the take's WORD TIMINGS, `[{w, start, end}]` per script word (take seconds): the editor's `transcribe` op (`words: true`; parakeet keeps word times) on the take -- or each of its parts' files, at their starts -- the words heard aligned to its script, fuzzy and in order (a typo read as the word it means still pairs; a word not heard is placed between its neighbours) | post bench, **Get word timings** (a job on the editor; the block says when the take is timed) | `umtool posts narrate <p> <item> --words [--worker <id>]` | `POST {op: "take-words", id, worker?}` → `{jobs}` · `GET ?project&id&takeWords=<job>,…` keeps them when done |
+
## The source backlog (Sources · Prioritize · Re-sweep when complete)
The Overview tab's **sources** line (`components/projects/report/SourceBacklog.tsx`, `lib/report/sourceBacklog.*`): for each
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -659,6 +659,56 @@ post's insert and `umtool posts avatars <p>`, or set by hand with `umtool posts
<p> <handle> <image>` (never replaced by the archive's). Every card that draws that
author unblurred shows it — the render, Play and the bench; a redacted author never.
+### A word zoom
+
+A post item's card may PUSH IN ON A WORD as it is read (`report-to-video/word-zoom.mjs`;
+operator, 3 Nov: "zoom in on the "barbecue" typo when it's being read out and make that
+effect a standard thing we can use and tune in the UI"), a highlight under it, then back
+out:
+
+```jsonc
+"fx": [{
+ "kind": "word-zoom",
+ "match": "barbecue", // the word or phrase as the card shows it (case and edge punctuation aside)
+ "target": "post", // whose words: "post" (default), "quoted", "parent:<i>" (a paraphrase's, when it has one)
+ "occurrence": 1, // its n-th time in that text
+ "at": 4.2, // item seconds; absent: from the take's word timings
+ "lead": 0.5, "hold": 1.2, // in over lead before the word, held on it (then 0.4 s back out)
+ "scale": 2, // 1.2–4
+ "ease": "inOut", // "out" | "inOut" | "snap"
+ "highlight": "#ffd84d" // or false
+}]
+```
+
+**When**: `at` when it is set (a nudge wins); else the matched word's start in the
+picked take, on the item's clock — the read's lead + start ÷ its `rate`. The take's
+WORD TIMINGS (`narration.takes[i].words`, `[{w, start, end}]` per script word) come
+from `umtool posts narrate <p> <item> --words` or the bench's **Get word timings**:
+the editor's `transcribe` op (`words: true`; parakeet keeps word times) on the take —
+or on each of its parts' files, offset by their starts — the words heard aligned to
+the script, fuzzy and in order, so a typo read as the word it means still pairs and
+a word not heard is placed between its neighbours. The card's words are aligned to
+the script the same way (the script drops handles and links). An un-narrated post
+has no read: its zoom needs `at`, and the build (and `--lint`) refuse a zoom with
+no time, naming the command that gives it one; two zooms of a post up at once, or
+one starting after the post ends, are refused too.
+
+**The curve** (one function for the render and Play): progress 0 → 1 over
+[t − lead, t] on the ease, 1 for `hold`, back to 0 over 0.4 s; the zoom is
+1 + (scale − 1)·progress, and the window is the card's region at 1/zoom of its size,
+moving so the word's box is centred (clamped inside the region) at full zoom.
+
+**The render**: the card page wraps every word in a span (`data-w="post:<i>"`); the
+build loads the page at 2–4× (crisp when pushed in), measures the card (inset by its
+corner: the REGION) and the words' box — refusing a word cut off the card — and
+shoots the region plain and with the highlight under the words. ffmpeg's `zoompan`
+crops and scales the region toward the word frame by frame on the item's second, the
+highlight fading in over the lead and out with the zoom, laid over the card's region
+only while it is up and before the attachments: the attachments are never covered.
+**Play** measures the same spans in its card page and transforms the card's contents
+about the same window; the post bench's **word zoom** block makes and tunes them
+([knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)).
+
## The on-screen deck (`render.chrome`)
Its knobs — the stamp's moment and count per clip, the stamp's look and words, the markers, a clip's sync and
diff --git a/umtool/e2e/fixtures/editor-stub-case-stages.mjs b/umtool/e2e/fixtures/editor-stub-case-stages.mjs
@@ -1,9 +1,12 @@
// The editor's side of a research case's verify, leads and evidence stages
// (release 38 lane C), stubbed:
//
-// POST /api/ops/transcribe {path, start, end, whilePaused?}
+// POST /api/ops/transcribe {path, start, end, whilePaused?, words?, out?}
// job "cs-<n>", done after 0.6 s, its log ending with the editor's
-// `@@transcribe-result {…}` -- the text the fixture's HEARD
+// `@@transcribe-result {…}` -- the text the fixture's HEARD; with `out`, the
+// result written there, and with `words` its words: `<path>.heard.json`
+// beside the file when a fixture put one there (a word zoom's take), else
+// HEARD's words, a third of a second each
// POST /api/ops/wayback-lookup {url}
// 403 {refusal: "excluded"} for the fixture's EXCLUDED_URL, else two captures
// POST /api/ops/fetch-posts {slug, …}
@@ -15,6 +18,7 @@
// worker, the Wayback Machine or a forum. Every request is recorded by the
// main stub's `record`.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { EXCLUDED_URL, HEARD } from "./case-stages-fixture.mjs";
@@ -64,6 +68,11 @@ export function caseStagesRoute(req, res, url, ctx) {
};
const id = job("transcribe-file", [`Transcribe ${path.basename(body.path)} [${body.start}, ${body.end})${body.whilePaused ? " while paused" : ""}`], (j) => {
j.log.push(`@@transcribe-result ${JSON.stringify(result)}`);
+ if (typeof body.out === "string" && path.isAbsolute(body.out)) {
+ const sidecar = `${body.path}.heard.json`;
+ const words = body.words !== true ? undefined : existsSync(sidecar) ? JSON.parse(readFileSync(sidecar, "utf8")) : HEARD.split(/\s+/).map((w, i) => ({ w, start: i / 3, end: i / 3 + 0.3 }));
+ writeFileSync(body.out, JSON.stringify({ ...result, ...(words ? { words } : {}) }));
+ }
});
json(res, 200, { ok: true, jobId: id });
})
diff --git a/umtool/e2e/fixtures/post-narration-fixture.mjs b/umtool/e2e/fixtures/post-narration-fixture.mjs
@@ -39,6 +39,8 @@ export function makePostNarrationFixture({ reports, deckManifest }) {
const takes = path.join(dir, "narration", "posts", "11");
mkdirSync(takes, { recursive: true });
ff(["-f", "lavfi", "-i", "sine=frequency=262:sample_rate=48000:duration=2", "-ac", "1", "-c:a", "pcm_s16le", path.join(takes, "take-1.orpheus-zac.wav")]);
+ // What the editor's stubbed transcription "hears" in that take (a word zoom's word timings; editor-stub-case-stages.mjs).
+ writeFileSync(path.join(takes, "take-1.orpheus-zac.wav.heard.json"), JSON.stringify([["The", 0.1, 0.3], ["video", 0.35, 0.7], ["speaks", 0.75, 1.1], ["for", 1.15, 1.3], ["itself.", 1.35, 1.8]].map(([w, start, end]) => ({ w, start, end }))));
const base = (id, text, o = {}) => ({
type: "post", id, post: `narrchan-x/${id.slice(2)}`, platform: "x", author: "Narr Subject", handle: "narrsubject",
date: "2026-10-30T10:00:00.000Z", text, url: `https://x.com/narrsubject/status/${id}`, engagement: { likes: 4 }, subjects: ["narrsubject"], ...o,
diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts
@@ -279,6 +279,52 @@ test.describe("the recording session", () => {
});
});
+test("A WORD ZOOM: Get word timings (the editor's transcription), click a word -> Zoom here -> saved; Play pushes the card in on it at its time", async ({ page }) => {
+ await page.setViewportSize({ width: 1500, height: 1100 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-11"));
+ const panel = page.locator('[data-post-zoom-panel="p-11"]');
+ await expect(panel.locator("[data-post-zoom-words-state]")).toHaveText(/no word timings/);
+ // The take's word timings: the editor's transcribe op (the stub "hears" the take), aligned to its script.
+ await panel.locator("[data-post-zoom-get-words]").click();
+ await expect(panel.locator("[data-post-zoom-words-state]")).toHaveText(/the take is timed \(5 words\)/, { timeout: 20_000 });
+ const t0 = (narr("p-11") as { takes: Array<Take & { words?: Array<{ w: string; start: number }> }> }).takes[0];
+ expect(t0.words?.[2]).toEqual({ w: "speaks", start: 0.75, end: 1.1 });
+ // Click "speaks" and zoom on it.
+ await panel.locator('[data-post-zoom-word="2"]').click();
+ await expect(panel.locator("[data-post-zoom-sel]")).toHaveText("“speaks”");
+ await panel.locator("[data-post-zoom-here]").click();
+ await expect(panel.locator('[data-post-zoom-fx="0"]')).toBeVisible();
+ expect((timeline().find((e) => e.id === "p-11") as { fx?: unknown[] }).fx).toEqual([{ kind: "word-zoom", match: "speaks" }]);
+ // Its time: the read's lead 0.4 + the word's 0.75 s in the take.
+ await expect(panel.locator("[data-post-zoom-at]")).toHaveAttribute("data-post-zoom-at", "1.15");
+ await expect(page.locator('[data-post-bench-zoom-mark="0"]')).toBeVisible();
+ await expect(page.locator('[data-post-lane-zoom="0"]')).toBeVisible();
+ // A knob: scale 3, one write.
+ const scale = panel.locator('[data-post-zoom-knob="scale"]');
+ await scale.fill("3");
+ await scale.blur();
+ await expect.poll(() => (timeline().find((e) => e.id === "p-11") as { fx?: Array<{ scale?: number }> }).fx?.[0]?.scale).toBe(3);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-word-zoom-bench.png") });
+
+ // Play the cut: at the word's time the card's contents are pushed in, on the render's curve.
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" }));
+ const player = page.locator('[data-post-play="p-11"]');
+ await expect(player).toHaveAttribute("data-post-zooms", "1", { timeout: 15_000 });
+ await expect(player).toHaveAttribute("data-post-zoom", "1");
+ await page.locator("[data-play-toggle]").click();
+ // Fully in from 1.15 s to 2.35 s: scale 3.
+ await expect(player).toHaveAttribute("data-post-zoom", "3", { timeout: 15_000 });
+ await expect(player).toHaveAttribute("data-post-zoom-fx", "0");
+ const transform = await page.frameLocator('[data-post-card-frame="read"]').locator("[data-post-words]").evaluate((el) => (el as HTMLElement).style.transform);
+ expect(transform).toMatch(/scale\(3\)/);
+ const lit = await page.frameLocator('[data-post-card-frame="read"]').locator('[data-w="post:2"]').evaluate((el) => (el as HTMLElement).style.background);
+ expect(lit).toMatch(/rgba\(255, 216, 77/);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-word-zoom-play.png") });
+ // And back out after it.
+ await expect(player).toHaveAttribute("data-post-zoom", "1", { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+});
+
test("THE RECORDING SESSION: part by part, a reload resumes, redo one, the last part makes the recorded take and picks it", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1200 });
await page.goto(urls.projectHref(PROJECT, { tab: "cut" }));
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -2530,7 +2530,7 @@ export function postNarrationIn(m, id, patch) {
const e = m.timeline[i];
if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
for (const k of Object.keys(patch)) {
- if (!POST_NARRATION_KNOBS.includes(k) && !["addTake", "dropTake", "keepPick"].includes(k)) throw new Error(`${k} is not a narration knob (${[...POST_NARRATION_KNOBS, "addTake", "dropTake"].join(", ")})`);
+ if (!POST_NARRATION_KNOBS.includes(k) && !["addTake", "dropTake", "keepPick", "takeWords"].includes(k)) throw new Error(`${k} is not a narration knob (${[...POST_NARRATION_KNOBS, "addTake", "dropTake", "takeWords"].join(", ")})`);
}
const before = isObj(e.narration) ? JSON.parse(JSON.stringify(e.narration)) : null;
const n = isObj(e.narration) ? e.narration : { takes: [] };
@@ -2545,6 +2545,14 @@ export function postNarrationIn(m, id, patch) {
n.takes.push(patch.addTake);
if (patch.keepPick !== true) n.pick = n.takes.length - 1;
}
+ // A take's word timings (posts narrate --words; word-zoom.mjs): `{ take: <index>, words: [{w, start, end}] | null }`.
+ if (patch.takeWords !== undefined && patch.takeWords !== null) {
+ const tw = patch.takeWords;
+ const t = isObj(tw) && Number.isInteger(tw.take) ? n.takes[tw.take] : null;
+ if (!t) throw new Error(`${id} has no take ${isObj(tw) ? tw.take : "?"} to time`);
+ if (tw.words === null) delete t.words;
+ else t.words = tw.words;
+ }
if (patch.dropTake !== undefined && patch.dropTake !== null) {
const d = Number(patch.dropTake);
if (!Number.isInteger(d) || !n.takes[d]) throw new Error(`${id} has no take ${patch.dropTake}`);
@@ -2566,6 +2574,66 @@ export function postNarrationIn(m, id, patch) {
}
/**
+ * A POST ITEM's EFFECTS (`fx`, word-zoom.mjs), in memory: `op` is `{ add: fx }`
+ * (appended), `{ set: <i>, patch }` (keys set; null clears one), `{ remove: <i> }`,
+ * or `{ list: [...] }` (all of them; [] none). Refused in the build's words.
+ *
+ * @param {Record<string, any>} m
+ * @param {string} id
+ * @param {Record<string, any>} op
+ */
+export function postFxIn(m, id, op) {
+ const i = entryIndex(m.timeline, id);
+ const e = m.timeline[i];
+ if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
+ if (!isObj(op)) throw new Error("an effects change is { add } | { set, patch } | { remove } | { list }");
+ const list = Array.isArray(e.fx) ? e.fx.map((x) => ({ ...x })) : [];
+ const at = (k) => {
+ const n = Number(k);
+ if (!Number.isInteger(n) || !list[n]) throw new Error(list.length ? `${id} has no effect ${k} (0–${list.length - 1})` : `${id} has no effects`);
+ return n;
+ };
+ const tidy = (fx) => {
+ const out = {};
+ for (const [k, v] of Object.entries(fx)) if (v !== null && v !== undefined) out[k] = typeof v === "number" && k !== "occurrence" ? round2(v) : v;
+ return out;
+ };
+ let index = null;
+ if (op.add !== undefined) {
+ if (!isObj(op.add)) throw new Error("add is an effect ({ kind: \"word-zoom\", match, … })");
+ list.push(tidy({ kind: "word-zoom", ...op.add }));
+ index = list.length - 1;
+ } else if (op.set !== undefined) {
+ index = at(op.set);
+ if (!isObj(op.patch)) throw new Error("set takes a patch of the effect's keys");
+ list[index] = tidy({ ...list[index], ...op.patch });
+ } else if (op.remove !== undefined) {
+ list.splice(at(op.remove), 1);
+ } else if (op.list !== undefined) {
+ if (!Array.isArray(op.list)) throw new Error("list is the whole list of effects");
+ list.splice(0, list.length, ...op.list.map((x) => (isObj(x) ? tidy(x) : x)));
+ } else throw new Error("an effects change is { add } | { set, patch } | { remove } | { list }");
+ if (list.length) e.fx = list;
+ else delete e.fx;
+ const errors = validatePostItem(e);
+ if (errors.length) throw new StructureRefused(errors);
+ return { id, at: i, entry: e, fx: e.fx ?? [], index };
+}
+
+/**
+ * CHANGE A POST ITEM's EFFECTS (`umtool posts fx`, the post bench's Zoom here):
+ * one structural write (one undo point). See postFxIn.
+ *
+ * @param {string} dir
+ * @param {string} id
+ * @param {Record<string, any>} op
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updatePostFx(dir, id, op, { token = null } = {}) {
+ return structural(dir, "post-fx", token, (m) => postFxIn(m, id, op));
+}
+
+/**
* SET A POST ITEM's NARRATION (`umtool posts narrate`, the post bench): one
* structural write (one undo point) -- the script, a take added or dropped,
* the pick, the approval, off, and the mix's knobs for this post.
diff --git a/umtool/lib/report/postFx.test.mjs b/umtool/lib/report/postFx.test.mjs
@@ -0,0 +1,90 @@
+// A post item's word zooms through the writer and the CLI (postFxCli.mjs,
+// manifest.mjs updatePostFx), and a take's word timings (`posts narrate --words`:
+// the editor's transcription, stood in for here, aligned to the script).
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { postsCommand } from "./postsCli.mjs";
+import { takeWords, takeWordSources } from "./postFxCli.mjs";
+import { updatePostFx } from "./manifest.mjs";
+import { wordZoomTimes } from "umtool-report-to-video/word-zoom";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-fx-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const REPORTS = path.join(ROOT, "reports");
+const TEXT = "stop me and save me from myself, barbecue if no one does, I'm going after him.";
+const item = (id, o = {}) => ({
+ type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-11-03T10:00:00.000Z", text: TEXT, ...o,
+});
+async function project(name, timeline) {
+ const dir = path.join(REPORTS, name);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2));
+ return { id: name, dir };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const cli = async (args) => {
+ const lines = [];
+ const errs = [];
+ const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) });
+ return { code, out: lines.join("\n"), err: errs.join("\n") };
+};
+
+test("posts fx: add (an un-narrated post gets the reading estimate), set, ls, remove -- refused in the build's words", async () => {
+ const p = await project("fx", [item("1")]);
+ let r = await cli(["fx", "fx", "p-1", "add", "word-zoom", "--match", "barbecue", "--scale", "2.5", "--hold", "1.5", "--ease", "snap", "--highlight", "off"]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /not narrated: at 3.33 s, the reading estimate/);
+ assert.match(r.out, /#1 word-zoom "barbecue" \(post, 1st\) at 3.33 s \(set by hand\) · 2.5× in 0.5 s, held 1.5 s, snap, highlight off/);
+ let fx = (await manifest(p)).timeline[0].fx;
+ assert.deepEqual(fx, [{ kind: "word-zoom", match: "barbecue", scale: 2.5, hold: 1.5, ease: "snap", highlight: false, at: 3.33 }]);
+ r = await cli(["fx", "fx", "p-1", "set", "1", "--at", "2.9", "--highlight", "default"]);
+ assert.equal(r.code, 0, r.err);
+ fx = (await manifest(p)).timeline[0].fx;
+ assert.equal(fx[0].at, 2.9);
+ assert.equal(fx[0].highlight, undefined);
+ // Not in the words: refused, nothing written.
+ r = await cli(["fx", "fx", "p-1", "add", "word-zoom", "--match", "because", "--at", "1"]);
+ assert.equal(r.code, 1);
+ assert.match(r.err, /fx\[1\]\.match "because" is not in the post's words/);
+ assert.equal((await manifest(p)).timeline[0].fx.length, 1);
+ r = await cli(["fx", "fx", "p-1", "ls", "--json"]);
+ assert.equal(JSON.parse(r.out).times[0].t, 2.9);
+ r = await cli(["fx", "fx", "p-1", "remove", "1"]);
+ assert.equal(r.code, 0, r.err);
+ assert.equal((await manifest(p)).timeline[0].fx, undefined);
+ assert.match(r.out, /no word zooms/);
+ await assert.rejects(updatePostFx(p.dir, "p-1", { remove: 0 }), /has no effects/);
+});
+
+test("posts narrate --words: the take transcribed by the editor (its parts, at their starts), aligned to the script, kept on the take", async () => {
+ const take = { file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 6, script: TEXT };
+ const p = await project("words", [item("1", { narration: { script: TEXT, takes: [take], lead: 0.5, rate: 1.25 }, fx: [{ kind: "word-zoom", match: "barbecue" }] })]);
+ // Before: no time.
+ assert.match(wordZoomTimes((await manifest(p)).timeline[0])[0].error, /no word timings yet/);
+ const asked = [];
+ // The editor stood in for: it "hears" the script with the typo read as the word it means.
+ const ask = async (route, body) => {
+ asked.push({ route, body });
+ const heard = TEXT.replace("barbecue", "barbeque").split(" ").map((w, i) => ({ w, start: i * 0.4, end: i * 0.4 + 0.3, conf: 0.9 }));
+ await mkdir(path.dirname(body.out), { recursive: true });
+ await writeFile(body.out, JSON.stringify({ path: body.path, cues: [], text: "", words: heard }));
+ return { jobId: "job-1", result: null };
+ };
+ const project1 = { id: "words", dir: p.dir };
+ const r = await takeWords(project1, (await manifest(p)).timeline[0], { ask, worker: "parakeet-cpu" });
+ assert.deepEqual(asked.map((a) => [a.route, a.body.words, a.body.workerId, path.relative(p.dir, a.body.out)]), [["/api/ops/transcribe", true, "parakeet-cpu", "narration/posts/1/take-1.orpheus-zac.words.json"]]);
+ assert.equal(r.heard, r.of);
+ const e = (await manifest(p)).timeline[0];
+ assert.deepEqual(e.narration.takes[0].words[7], { w: "barbecue", start: 2.8, end: 3.1 });
+ // Its time: lead 0.5 + 2.8 ÷ 1.25.
+ assert.equal(wordZoomTimes(e)[0].t, 2.74);
+ // A take read part by part: each part transcribed on its own file, at its start.
+ const parted = { ...take, parts: [{ n: 1, file: "narration/posts/1/take-1.parts/p01.wav", start: 0, seconds: 2 }, { n: 2, file: "narration/posts/1/take-1.parts/p02.wav", start: 2.6, seconds: 3 }] };
+ assert.deepEqual(await takeWordSources(p.dir, parted), [{ file: take.file, offset: 0 }]); // the parts' files are not there: the take's
+ await mkdir(path.join(p.dir, "narration/posts/1/take-1.parts"), { recursive: true });
+ for (const f of ["p01", "p02"]) await writeFile(path.join(p.dir, `narration/posts/1/take-1.parts/${f}.wav`), "");
+ assert.deepEqual(await takeWordSources(p.dir, parted), [{ file: parted.parts[0].file, offset: 0 }, { file: parted.parts[1].file, offset: 2.6 }]);
+});
diff --git a/umtool/lib/report/postFxCli.mjs b/umtool/lib/report/postFxCli.mjs
@@ -0,0 +1,195 @@
+// `umtool posts fx` and `umtool posts narrate <p> <item> --words`
+// (report-to-video/word-zoom.mjs; umtool/docs/report-video.md, "A word zoom"):
+// a post item's WORD ZOOMS -- the card pushed in on a word as it is read -- through
+// the writer (updatePostFx), and the word timings of its take, asked of the
+// EDITOR's transcription (never ASR here) and aligned to the script it read
+// (updatePostNarration's takeWords).
+//
+// umtool posts fx <p> <item> [ls]
+// umtool posts fx <p> <item> add word-zoom --match "…" [--target post|quoted|parent:<i>] [--occurrence n] [--at s]
+// [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off]
+// umtool posts fx <p> <item> set <n> [the same flags; a flag's value `default` clears it]
+// umtool posts fx <p> <item> remove <n>
+// umtool posts narrate <p> <item> --words [--worker <id>]
+//
+// Plain ESM: the CLI runs under bare node.
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
+import {
+ WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, findMatch, readingEstimate, resolveWordZoom, scriptWordTimes, targetTextOf, wordZoomTimes,
+} from "umtool-report-to-video/word-zoom";
+import { readManifest } from "../projects/report.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { manifestToken, updatePostFx, updatePostNarration } from "./manifest.mjs";
+import { findPostItem } from "./postNarrationCli.mjs";
+
+export const FX_USAGE = [
+ "usage: umtool posts fx <project> <item> [ls] [--json]",
+ " umtool posts fx <project> <item> add word-zoom --match \"…\" [--target post|quoted|parent:<i>] [--occurrence n]",
+ " [--at s] [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off] [--json]",
+ " umtool posts fx <project> <item> set <n> [those flags; `default` clears one] | remove <n>",
+ " A WORD ZOOM: the card pushed in on a word (or a phrase) as it is read, a highlight under it, then back out.",
+ " --match is the word as the card shows it (case and edge punctuation aside); --occurrence its n-th time in the",
+ " text (default 1); --target whose words: the post's own (default), the post it quotes, the posts it answers.",
+ " WHEN: --at (item seconds) when set; else the word's start in the picked take's word timings (lead + start ÷ the",
+ " read's rate) -- `umtool posts narrate <p> <item> --words` gets them from the editor's transcription. An",
+ " un-narrated post needs --at (add fills the reading estimate: 1 s + 3 words a second).",
+ ` --scale 1.2–4 (default ${WORD_ZOOM_DEFAULTS.scale}), --lead 0–3 s in before the word (${WORD_ZOOM_DEFAULTS.lead}), --hold 0–10 s on it (${WORD_ZOOM_DEFAULTS.hold}),`,
+ ` --ease ${WORD_ZOOM_EASES.join("|")} (${WORD_ZOOM_DEFAULTS.ease}), --highlight a colour or off (${WORD_ZOOM_DEFAULTS.highlight}). <n>: the zoom's number as ls shows it.`,
+].join("\n");
+
+export class FxError extends Error {}
+
+const NUM_KEYS = { "--at": "at", "--scale": "scale", "--hold": "hold", "--lead": "lead", "--occurrence": "occurrence" };
+
+/** The flags as an effect patch (null: back to the default). */
+export function fxPatchOf(str) {
+ const out = {};
+ const m = str("--match");
+ if (m !== null) out.match = m;
+ const t = str("--target");
+ if (t !== null) out.target = t === "default" ? null : t;
+ for (const [flag, key] of Object.entries(NUM_KEYS)) {
+ const v = str(flag);
+ if (v === null) continue;
+ if (v === "default" || v === "off" && key === "at") out[key] = null;
+ else {
+ const x = Number(v);
+ if (!Number.isFinite(x)) throw new FxError(`${flag} takes a number`);
+ out[key] = x;
+ }
+ }
+ const e = str("--ease");
+ if (e !== null) out.ease = e === "default" ? null : e;
+ const h = str("--highlight");
+ if (h !== null) out.highlight = h === "default" ? null : ["off", "none", "false", "no"].includes(h.toLowerCase()) ? false : h;
+ return out;
+}
+
+const nth = (n) => `${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"}`;
+
+/** One item's zooms as lines. */
+export function fxLines(e, render) {
+ const list = Array.isArray(e.fx) ? e.fx : [];
+ if (!list.length) return [`${e.id}: no word zooms (add one: umtool posts fx <p> ${e.id} add word-zoom --match "…")`];
+ const times = wordZoomTimes(e, render);
+ return [
+ `${e.id}: ${list.length} word zoom(s)${isNarrated(e) ? "" : " (not narrated: each needs at)"}`,
+ ...list.map((fx0, i) => {
+ const fx = resolveWordZoom(fx0);
+ const t = times[i];
+ const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s ${t.source === "at" ? "(set by hand)" : `(from the take's words: "${t.word.w}" at ${t.word.start} s)`}`;
+ return ` #${i + 1} word-zoom "${fx.match}" (${fx.target}, ${nth(fx.occurrence)}) ${when} · ${fx.scale}× in ${fx.lead} s, held ${fx.hold} s, ${fx.ease}, highlight ${fx.highlight === false ? "off" : fx.highlight}`;
+ }),
+ ];
+}
+
+/** `umtool posts fx …` (postsCli.mjs routes it here). */
+export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str }) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new FxError(`${project.id} has no manifest`);
+ const render = manifest.render ?? {};
+ const [ref, verb = "ls", arg] = words;
+ const e = findPostItem(manifest, ref);
+ if (!e) throw new FxError(`no post item ${ref} in ${project.id} (its id, or the post's id)`);
+ const write = async (op) => withEditNotes(project, async () => updatePostFx(project.dir, e.id, op, { token: await manifestToken(project.dir) }));
+ const say = (entry, extra = {}) => {
+ if (json) out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render), ...extra }, null, 2));
+ else out(fxLines(entry, render).join("\n"));
+ };
+ const index = () => {
+ const n = Number(arg);
+ if (!Number.isInteger(n) || n < 1) throw new FxError(`${verb} takes the zoom's number as ls shows it (1 = the first)`);
+ return n - 1;
+ };
+ if (verb === "ls") {
+ say(e);
+ return 0;
+ }
+ if (verb === "add") {
+ if (arg !== "word-zoom") throw new FxError("add names the effect: add word-zoom --match \"…\"");
+ const patch = Object.fromEntries(Object.entries(fxPatchOf(str)).filter(([, v]) => v !== null));
+ if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add word-zoom needs --match \"<the word, as the card shows it>\"");
+ let note = null;
+ if (patch.at === undefined && !isNarrated(e)) {
+ const m = findMatch(targetTextOf(e, patch.target ?? "post") ?? "", patch.match, patch.occurrence ?? 1);
+ if (!m.error) {
+ patch.at = readingEstimate(m.from);
+ note = `not narrated: at ${patch.at} s, the reading estimate (nudge it: set <n> --at s)`;
+ }
+ }
+ const { result } = await write({ add: { kind: "word-zoom", ...patch } });
+ if (note && !json) out(note);
+ say(result.entry, { index: result.index });
+ return 0;
+ }
+ if (verb === "set") {
+ const i = index();
+ const patch = fxPatchOf(str);
+ if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --scale, --hold, --lead, --ease, --highlight, --occurrence, --target");
+ const { result } = await write({ set: i, patch });
+ say(result.entry);
+ return 0;
+ }
+ if (verb === "remove") {
+ const { result } = await write({ remove: index() });
+ say(result.entry);
+ return 0;
+ }
+ throw new FxError(`${verb}: ls, add, set or remove`);
+}
+
+/**
+ * Where a take is transcribed from: its PARTS (a long post read part by part),
+ * each on its own file and offset by its start in the take, when every part's
+ * file is there; else the take's own file. `[{ file, offset }]`, project-relative.
+ */
+export async function takeWordSources(projectDir, take) {
+ const parts = Array.isArray(take?.parts) ? take.parts : [];
+ if (parts.length && parts.every((p) => typeof p?.file === "string" && Number.isFinite(p.start))) {
+ const here = await Promise.all(parts.map((p) => stat(path.join(projectDir, ...p.file.split("/"))).then((s) => s.isFile(), () => false)));
+ if (here.every(Boolean)) return parts.map((p) => ({ file: p.file, offset: p.start }));
+ }
+ return [{ file: take.file, offset: 0 }];
+}
+
+/** The words file the editor writes beside a sound file. */
+export const wordsFileOf = (rel) => String(rel).replace(/\.[^./]+$/, "") + ".words.json";
+
+/** The recognized words of a transcribe result (`{ words: [{w, start, end}] }`), moved by `offset`. */
+export function recognizedOf(doc, offset = 0) {
+ const list = Array.isArray(doc?.words) ? doc.words : [];
+ return list
+ .filter((x) => x && typeof x.w === "string" && Number.isFinite(x.start) && Number.isFinite(x.end))
+ .map((x) => ({ w: x.w, start: Math.round((x.start + offset) * 1000) / 1000, end: Math.round((x.end + offset) * 1000) / 1000 }));
+}
+
+/**
+ * THE TAKE's WORD TIMINGS: the picked take (or its parts) transcribed by the
+ * editor's transcribe op (`words: true`, a job; parakeet keeps word times), the
+ * words heard aligned to the script it read (scriptWordTimes), stored on the
+ * take (`takes[i].words`) by one write. `ask` (tests) stands in for askEditorOp.
+ */
+export async function takeWords(project, e, { worker = null, emit = () => {}, ask = null } = {}) {
+ const t = pickedTake(e);
+ if (!t) throw new FxError(`${e.id} has no take to time (umtool posts narrate <p> ${e.id} --take, or record one on the bench)`);
+ const script = typeof t.script === "string" && t.script.trim() ? t.script : String(e.narration?.script ?? "");
+ if (!script.trim()) throw new FxError(`${e.id}'s take has no script to align its words to`);
+ const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp;
+ const heard = [];
+ const sources = await takeWordSources(project.dir, t);
+ for (const src of sources) {
+ const abs = path.join(project.dir, ...src.file.split("/"));
+ const outFile = path.join(project.dir, ...wordsFileOf(src.file).split("/"));
+ emit("note", { message: `${e.id}: transcribing ${src.file} on the editor…` });
+ await askOp("/api/ops/transcribe", { path: abs, words: true, out: outFile, ...(worker ? { workerId: worker } : {}) }, { emit });
+ const doc = JSON.parse(await readFile(outFile, "utf8"));
+ heard.push(...recognizedOf(doc, src.offset));
+ }
+ if (!heard.length) throw new FxError(`the editor's transcription of ${t.file} came back with no word timings (a parakeet worker keeps them; name one with --worker)`);
+ const r = scriptWordTimes(script, heard);
+ const { result } = await withEditNotes(project, async () =>
+ updatePostNarration(project.dir, e.id, { takeWords: { take: t.index, words: r.words } }, { token: await manifestToken(project.dir) }));
+ return { take: t, heard: r.heard, of: r.of, recognized: heard.length, sources: sources.length, result };
+}
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -15,6 +15,7 @@
// umtool posts narrate <p> --all --draft-scripts [--force] scripts from the posts' words (verbatim)
// umtool posts narrate <p> --all --take [--limit N] every missing take, one at a time (resumable)
// umtool posts narrate <p> --cut k=v … the cut's mix (render.postNarration)
+// umtool posts narrate <p> <item> --words [--worker <id>] its take's word timings (the editor's transcription, aligned; postFxCli.mjs)
//
// Plain ESM: the CLI runs under bare node.
import { execFile } from "node:child_process";
@@ -57,6 +58,9 @@ export const NARRATE_USAGE = [
" once `umtool posts fit` has scanned it (else from its in point). clip=full plays the attachments whole.",
" rate=0.8–1.5 (default 1): the READ sped up (its pitch kept), the attachment untouched; the post's length, its",
" muffle and its parts follow the faster read (a 10 s take at rate=1.25 reads in 8 s).",
+ " --words [--worker <id>]: the picked take's WORD TIMINGS -- the editor's transcribe op (a job; parakeet keeps word times)",
+ " on the take (or each of its parts), the words heard aligned to its script, kept on the take: a word zoom's time",
+ " (umtool posts fx) is its word's start there.",
].join("\n");
export class NarrateError extends Error {}
@@ -394,6 +398,16 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
throw err;
}
}
+ if (flags.has("--words")) {
+ const { takeWords, fxLines } = await import("./postFxCli.mjs");
+ const r = await takeWords(project, e, { worker: str("--worker"), emit: (_ev, f) => !json && f?.message && out(f.message) });
+ if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take.file, heard: r.heard, of: r.of, recognized: r.recognized, words: r.result.entry.narration.takes[r.take.index].words, token: r.result.token }, null, 2));
+ else {
+ out(`${e.id}: take ${r.take.file} timed: ${r.heard} of its script's ${r.of} words heard (${r.recognized} recognized${r.sources > 1 ? `, over ${r.sources} parts` : ""}); the rest placed between them`);
+ if (Array.isArray(r.result.entry.fx) && r.result.entry.fx.length) out(fxLines(r.result.entry, render).join("\n"));
+ }
+ return 0;
+ }
if (flags.has("--take")) {
const speedRaw = str("--speed");
const r = await makeTake(project, e, {
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -73,6 +73,8 @@ export const POSTS_USAGE = [
" umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix",
" (umtool posts narrate --help)",
" umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
+ " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] [--scale s] … | set <n> … | remove <n>",
+ " a WORD ZOOM: the card pushed in on a word as it is read (umtool posts fx --help)",
" umtool posts avatar <project> [<handle> <image-file> | <handle> off] [--json]",
" an author's PICTURE on every card that draws them (postAvatars): the file copied into posts-media/_avatars/,",
" never replaced by the archive's; `off` clears it; no handle lists them. A blurred author never shows one.",
@@ -91,7 +93,7 @@ export const POSTS_USAGE = [
" none is listed with the call that reads it: pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…],\"contextOnly\":true}'.",
].join("\n");
-const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete"]);
+const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -372,6 +374,14 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
}
return await narrateCommand(await projectOf(projectArg, root), words.slice(2), flags, { json, dryRun, out, str });
}
+ if (verb === "fx") {
+ const { FX_USAGE, fxCommand } = await import("./postFxCli.mjs");
+ if (!projectArg || !ref || flags.has("--help")) {
+ err(FX_USAGE);
+ return 2;
+ }
+ return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str });
+ }
if (verb === "fit") {
const { FIT_USAGE, fitCommand } = await import("./postNarrationCli.mjs");
if (!projectArg || flags.has("--help") || (!flags.has("--all") && words.length < 3)) {
@@ -459,7 +469,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
return 1;
}
err(`umtool posts: ${e instanceof Error ? e.message : String(e)}`);
- return e instanceof CliError || e?.constructor?.name === "NarrateError" ? 2 : 1;
+ return e instanceof CliError || e?.constructor?.name === "NarrateError" || e?.constructor?.name === "FxError" ? 2 : 1;
}
}
diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs
@@ -298,6 +298,8 @@ export function validateFxEntries(manifest, { schedule = undefined } = {}) {
const render = manifest?.render ?? {};
for (const e of timeline) {
if (e?.fx === undefined) continue;
+ // A post item's `fx` is its own list of effects (a word zoom), post-item.mjs's to judge (word-zoom.mjs).
+ if (e.type === "post") continue;
const w = `timeline entry ${e.id ?? "?"}: fx`;
if (!isObj(e.fx)) { errors.push(`${w} must be an object`); continue; }
if (e.type !== "clip" && e.type !== "image") errors.push(`${w} is for a clip or an image`);
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -85,6 +85,7 @@ import { validateClipAudioEntries } from "./clip-audio.mjs";
import { validateClipBlurEntries } from "./clip-blur.mjs";
import { validateGapEntries } from "./gaps.mjs";
import { postItemFiles, validatePostItems } from "./post-item.mjs";
+import { wordZoomTimes } from "./word-zoom.mjs";
import { postAvatarFiles, validatePostAvatars } from "./post-avatars.mjs";
import { validatePostNarrationRender } from "./post-narration.mjs";
import { validateFinaleEntries } from "./finale.mjs";
@@ -325,6 +326,8 @@ export function validatorErrors(whole) {
...validateGapEntries(whole),
// A post as a timeline item (post-item.mjs): its archived words, its attachments, its hold.
...validatePostItems(whole),
+ // A post item's word zooms each need a time: `at`, or its take's word timings (the build refuses the same).
+ ...(whole.timeline ?? []).filter((e) => e?.type === "post" && Array.isArray(e.fx)).flatMap((e) => wordZoomTimes(e, whole.render).filter((t) => t.error).map((t) => String(t.error))),
...validatePostAvatars(whole),
// A narrated post item's mix (post-narration.mjs): the cut's knobs.
...validatePostNarrationRender(whole.render),
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -67,6 +67,7 @@
"./post-redact": "./post-redact.mjs",
"./post-redact-files": "./post-redact-files.mjs",
"./post-render": "./post-render.mjs",
+ "./word-zoom": "./word-zoom.mjs",
"./presets": "./presets.mjs",
"./prune-frames": "./prune-frames.mjs",
"./render-cards": "./render-cards.mjs",
diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -11,7 +11,10 @@
// media?: [{ src, kind: "image"|"video"|"gif", seconds?, width?, height?, audio?,
// start?, end?, mute?, crop?: [x, y, w, h], push?, words?,
// blur?: { on, strength?, boxes?, label? } }], (post-censor.mjs)
-// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen? }
+// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen?,
+// fx?: [{ kind: "word-zoom", match, target?, occurrence?, at?, lead?, hold?, scale?, ease?, highlight? }] }
+//
+// (`fx`: the card pushed in on a word as it is read -- word-zoom.mjs.)
//
// where a <ref> (a post it quotes, the posts it answers, nearest first) is
// `{ id?, author?, handle?, badge?, date?, text?, url?, paraphrase? }` --
@@ -29,8 +32,9 @@
import {
isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration,
} from "./post-narration.mjs";
-import { BAR_CSS, barsHtml, redactEntry, validatePostsRender } from "./post-redact.mjs";
+import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactionOn, validatePostsRender } from "./post-redact.mjs";
import { blurErrors } from "./post-censor.mjs";
+import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, cardWordsOf, findMatch, targetTextOf, validatePostFx } from "./word-zoom.mjs";
/** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */
export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]);
@@ -461,6 +465,8 @@ export function validatePostItem(e) {
}
// Its narration (post-narration.mjs): the script, the takes, the mix's knobs.
errors.push(...validatePostNarration(e));
+ // Its effects (word-zoom.mjs): a word zoomed on as it is read.
+ errors.push(...validatePostFx(e));
return errors;
}
@@ -500,6 +506,42 @@ export function validatePostItems(manifest) {
const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
for (const e of tl) if (e?.type === "post") errors.push(...validatePostItem(e));
errors.push(...validatePostsRender(manifest?.render));
+ // A word zoom on a word the project's list blanks (the corpus's and a post's markup are checked by the build).
+ const own = { terms: projectRedactOf(manifest?.render) };
+ for (const e of tl) if (e?.type === "post") errors.push(...fxRedactionErrors(e, own));
+ return errors;
+}
+
+/**
+ * Every word zoom of post item `entry` whose words are (or hold) a REDACTED
+ * word (post-redact.mjs): refused -- a published card never pushes in on a
+ * blank. The match is found on the ORIGINAL text (its `occurrence` as the
+ * manifest counts it); the redacted text keeps its spaces, so the same word
+ * indices name the same words on the published card.
+ *
+ * @param {Record<string, any>} entry
+ * @param {{ terms: any[], markup?: Record<string, any> } | null | undefined} red
+ */
+export function fxRedactionErrors(entry, red) {
+ if (!Array.isArray(entry?.fx) || !entry.fx.length || !redactionOn(red)) return [];
+ const shown = redactEntry(entry, red);
+ const errors = [];
+ entry.fx.forEach((fx, i) => {
+ if (!isObj(fx) || fx.kind !== "word-zoom" || typeof fx.match !== "string") return;
+ const target = fx.target ?? "post";
+ const text = targetTextOf(entry, target);
+ const published = targetTextOf(shown, target);
+ if (text === null || published === null) return;
+ const m = findMatch(text, fx.match, fx.occurrence ?? 1);
+ if (m.error) return;
+ const words = cardWordsOf(published);
+ for (let w = m.from; w <= m.to; w += 1) {
+ if (hasMarks(words[w])) {
+ errors.push(`timeline ${entry.id}.fx[${i}]: its match "${fx.match}" is a redacted word (render.posts.redact, the corpus's redactions.json or the post's markup) -- a published card never zooms on a blank; zoom on another word`);
+ break;
+ }
+ }
+ });
return errors;
}
@@ -681,13 +723,27 @@ export const hueOf = (s) => {
return h;
};
-/** The words with @mentions of the blurred authors blurred (their handle never in the page). */
-export function wordsHtml(text, blurred) {
+/**
+ * The words with @mentions of the blurred authors blurred (their handle never
+ * in the page). With `scope`, each word (cardTokens' runs of non-space) is a
+ * span `data-w="<scope>:<i>"` -- the build measures a word zoom's word by it,
+ * and Play zooms toward it; `hl` (`{ from, to }`) marks those words'
+ * spans `data-w-hl` (the zoom's highlight is drawn under them).
+ */
+export function wordsHtml(text, blurred, scope = null, hl = null) {
const set = new Set(blurred.map((h) => h.replace(/^@/, "").toLowerCase()));
- return esc(text)
- .replace(/@([A-Za-z0-9_]{1,30})/g, (m, h) => (set.has(h.toLowerCase()) ? `<span class="redact">@${"x".repeat(Math.max(4, Math.min(12, h.length)))}</span>` : `<span class="mention">${m}</span>`))
- .replace(/https?:\/\/\S+/g, (u) => `<span class="link">${u.length > 48 ? `${u.slice(0, 46)}…` : u}</span>`)
- .replace(/\n/g, "<br>");
+ const word = (t) =>
+ esc(t)
+ .replace(/@([A-Za-z0-9_]{1,30})/g, (m, h) => (set.has(h.toLowerCase()) ? `<span class="redact">@${"x".repeat(Math.max(4, Math.min(12, h.length)))}</span>` : `<span class="mention">${m}</span>`))
+ .replace(/https?:\/\/\S+/g, (u) => `<span class="link">${u.length > 48 ? `${u.slice(0, 46)}…` : u}</span>`);
+ if (!scope) return word(str(text)).replace(/\n/g, "<br>");
+ return cardTokens(text)
+ .map((t) => {
+ if (t.space !== undefined) return t.space.replace(/[^\n]+/g, " ").replace(/\n/g, "<br>");
+ const lit = hl && t.i >= hl.from && t.i <= hl.to;
+ return `<span data-w="${esc(scope)}:${t.i}"${lit ? " data-w-hl=\"\"" : ""}>${word(t.tok)}</span>`;
+ })
+ .join("");
}
/**
@@ -733,14 +789,20 @@ export function nameHtml(who, { redact, cls = "" }) {
* post it answers is not archived. `avatars`: `{ <handle>: url }`, the
* authors' pictures (the project's `postAvatars`, post-avatars.mjs); an
* author with none is drawn as the initial, a redacted one never shows one.
+ * Every word of the post's and its context's text is a span `data-w="<scope>:<i>"`
+ * (wordsHtml); `highlight` -- `{ scope, from, to, color }` -- draws a word
+ * zoom's marker under those words (word-zoom.mjs; the build's zoom shot).
*
* @param {Record<string, any>} entry
* @param {{ width: number, height: number, palette?: Record<string, string>, fonts?: { regular?: string, bold?: string },
* phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean, avatars?: Record<string, string>,
+ * highlight?: { scope: string, from: number, to: number, color: string } | null,
* redaction?: { terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, any> } | null }} o
*/
-export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, redaction = null }) {
- // AS PUBLISHED (post-redact.mjs): every redacted match drawn as a bar, its letters never in the page.
+export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null }) {
+ const hlOf = (scope) => (highlight && highlight.scope === scope ? highlight : null);
+ // AS PUBLISHED (post-redact.mjs): every redacted match drawn as a bar, its letters never in the page. The
+ // marks keep the text's length and its spaces, so the card's word indices (a word zoom's) are the original's.
entry = redactEntry(entry, redaction);
const pic = (who) => avatarUrlOf(avatars, who?.handle);
const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette };
@@ -770,7 +832,7 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
const r = red(`parents[${i}]`);
const subject = !r && subjectsOf(entry).some((h) => String(h).toLowerCase() === String(p.handle ?? "").replace(/^@/, "").toLowerCase());
ctx.push(
- `<div class="parent" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: Math.round(44 * k), accent: subject ? pal.accent : undefined, img: pic(p) })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span>${paraLabel(p)}</div><div class="ptext"${isParaphrased(p) ? ' data-post-paraphrase=""' : ""}>${wordsHtml(contextText(p) || (p.url ? "(not archived)" : ""), blurred)}</div></div></div>`,
+ `<div class="parent" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: Math.round(44 * k), accent: subject ? pal.accent : undefined, img: pic(p) })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span>${paraLabel(p)}</div><div class="ptext"${isParaphrased(p) ? ' data-post-paraphrase=""' : ""}>${wordsHtml(contextText(p) || (p.url ? "(not archived)" : ""), blurred, contextText(p) ? `parent:${i}` : null, hlOf(`parent:${i}`))}</div></div></div>`,
);
}
if (!parents.length && parentShotUrl) ctx.push(`<div class="pshot" data-post-parent-shot=""><img src="${esc(parentShotUrl)}" alt=""></div>`);
@@ -779,14 +841,14 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
}
const q = isObj(entry.quoted) ? entry.quoted : null;
const quoted = q
- ? `<div class="quoted" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(30 * k), img: pic(q) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span>${paraLabel(q)}</div><div class="qtext"${isParaphrased(q) ? ' data-post-paraphrase=""' : ""}>${wordsHtml(contextText(q), blurred)}</div></div>`
+ ? `<div class="quoted" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(30 * k), img: pic(q) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span>${paraLabel(q)}</div><div class="qtext"${isParaphrased(q) ? ' data-post-paraphrase=""' : ""}>${wordsHtml(contextText(q), blurred, "quoted", hlOf("quoted"))}</div></div>`
: "";
const repost = entry.repostedBy
? `<div class="repost" data-post-repost="">↻ ${esc(str(entry.repostedBy.author) || `@${entry.repostedBy.handle}`)} reposted</div>`
: "";
const head = `<div class="head"${ownRed ? ' data-redacted=""' : ""}>${avatarHtml(own, { redact: ownRed, size: Math.round(64 * k), accent: ownRed ? undefined : pal.accent, img: pic(own) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`;
// A card alone (text, or a stack's reading) is as tall as its words, centred in its box; beside the attachments, the box's height.
- const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;${L.mode === "side" ? `top:${box.y}px;height:${box.height}px` : `top:${box.y + box.height / 2}px;transform:translateY(-50%);max-height:${box.height}px`};width:${box.width}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words" data-post-words="" style="font-size:${size}px">${wordsHtml(cardText(entry), blurred)}</div>${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`;
+ const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;${L.mode === "side" ? `top:${box.y}px;height:${box.height}px` : `top:${box.y + box.height / 2}px;transform:translateY(-50%);max-height:${box.height}px`};width:${box.width}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words" data-post-words="" style="font-size:${size}px">${wordsHtml(cardText(entry), blurred, "post", hlOf("post"))}</div>${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`;
const stripHtml = L.strip
? `<div class="strip" data-post-strip="" style="left:${L.strip.x}px;top:${L.strip.y}px;width:${L.strip.width}px;height:${L.strip.height}px">${avatarHtml(own, { redact: ownRed, size: Math.round(56 * k), accent: ownRed ? undefined : pal.accent, img: pic(own) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="sline">${wordsHtml(cardText(entry).split("\n")[0].slice(0, 140) + (cardText(entry).length > 140 ? "…" : ""), blurred)}</div></div>`
: "";
@@ -835,7 +897,8 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; }
.counts b { color: ${pal.fg}; }
.redact { filter: blur(${Math.round(9 * k)}px); color: ${pal.muted}; }
.avatar.redact { background: ${rgbaOf(pal.muted, 0.6)} !important; }
-.slot { background: ${rgbaOf("#000000", 0.32)}; border-radius: ${Math.round(14 * k)}px; }
+.slot { background: ${rgbaOf("#000000", 0.32)}; border-radius: ${Math.round(14 * k)}px; }${highlight ? `
+[data-w-hl] { background: ${rgbaOf(highlight.color, WORD_ZOOM_HIGHLIGHT_ALPHA)}; box-shadow: inset 0 -0.12em 0 ${highlight.color}; border-radius: 0.16em; padding: 0 0.08em; margin: 0 -0.08em; -webkit-box-decoration-break: clone; box-decoration-break: clone; }` : ""}
${BAR_CSS(pal.fg)}
</style></head>
<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}">${barsHtml(body)}
diff --git a/umtool/report-to-video/post-item.test.mjs b/umtool/report-to-video/post-item.test.mjs
@@ -103,10 +103,12 @@ test("the privacy rule: another author is blurred unless the subject, gold/grey
const e = base({ text: "@KacamnGamesYT you are wrong", parents: [{ handle: "KacamnGamesYT", author: "Kacamn", text: "a question" }] });
assert.deepEqual(cardAuthors(e).map((a) => [a.where, a.redact]), [["parents[0]", true]]);
const html = postCardHtml(e, { width: 1440, height: 810 });
+ // The words as read (each word is its own span on the card: word-zoom.mjs).
+ const text = html.replace(/<[^>]+>/g, "");
// The parent's name and handle are never in the page, and the mention of them is blurred.
assert.ok(!html.includes("KacamnGamesYT"));
assert.ok(!html.includes("Kacamn"));
- assert.ok(html.includes("a question"));
+ assert.ok(text.includes("a question"));
assert.ok(html.includes('data-redacted=""'));
// A self-thread (his own parent) is drawn plainly.
const self = postCardHtml(base({ parents: [{ handle: "ObviousRises", author: "MR. OBVIOUS", text: "first" }] }), { width: 1440, height: 810 });
@@ -165,19 +167,21 @@ test("a context post's PARAPHRASE: validated, drawn in place of its words with a
assert.ok(readingSeconds(base({ quoted: short })) < readingSeconds(base({ quoted })));
// The card: the paraphrase and the label, never the original words.
const html = postCardHtml(base({ quoted: short, parents: [{ ...parent, paraphrase: "A parent asked a question." }] }), { width: 1920, height: 1080 });
- assert.ok(html.includes("He reviewed three videos."));
- assert.ok(html.includes("A parent asked a question."));
- assert.ok(!html.includes("spent all morning"), "the quoted post's original words are not on the card");
- assert.ok(!html.includes("the original parent words"), "the parent's original words are not on the card");
+ // The words as read (each word is its own span on the card: word-zoom.mjs).
+ const text = html.replace(/<[^>]+>/g, "");
+ assert.ok(text.includes("He reviewed three videos."));
+ assert.ok(text.includes("A parent asked a question."));
+ assert.ok(!text.includes("spent all morning"), "the quoted post's original words are not on the card");
+ assert.ok(!text.includes("the original parent words"), "the parent's original words are not on the card");
assert.equal(html.match(/data-post-paraphrased=""[^>]*>paraphrased</g)?.length, 2);
assert.equal(html.match(/data-post-paraphrase=""/g)?.length, 2);
// Unparaphrased: the original, and no label.
const plain = postCardHtml(base({ quoted }), { width: 1920, height: 1080 });
- assert.ok(plain.includes("spent all morning"));
+ assert.ok(plain.replace(/<[^>]+>/g, "").includes("spent all morning"));
assert.ok(!plain.includes("data-post-paraphrased"));
// The author stays under the blur rule: a private quoted author is blurred over a paraphrase too.
const priv = postCardHtml(base({ quoted: { ...short, badge: "blue", handle: "private_person" } }), { width: 1920, height: 1080 });
assert.ok(priv.includes('data-post-quoted="" data-redacted=""'));
assert.ok(!priv.includes("private_person"));
- assert.ok(priv.includes("He reviewed three videos."));
+ assert.ok(priv.replace(/<[^>]+>/g, "").includes("He reviewed three videos."));
});
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -10,7 +10,8 @@
// excerpt?: true, // drafted as an excerpt of a longer post
// engine?, voice?, speed?, // the next take's (default: render.postNarration's)
// takes: [{ file: "narration/posts/<postId>/take-<n>.<engine>-<voice>.wav",
-// engine, voice, seconds, script, at, note?, speed?, lufs?, jobId? }],
+// engine, voice, seconds, script, at, note?, speed?, lufs?, jobId?,
+// words?: [{ w, start, end }] }], // its script's words, timed (posts narrate --words; word-zoom.mjs)
// pick?: <index into takes>, // absent: the first
// approved?: true, // the picked take on this script, approved
// off?: true, // kept, but the item plays un-narrated
@@ -162,7 +163,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz",
// `attach` is one post's (it decides the card's layout, which is drawn from the entry alone).
const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice"]);
const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]);
-const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps"]);
+const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words"]);
const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]);
const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId"]);
const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/;
@@ -524,6 +525,13 @@ export function validatePostNarration(e) {
);
if (!ok) errors.push(`${tw}.source must be {kind: "tts", engine, voice}, {kind: "recorded", voice} or {kind: "take", from: <one of its takes' id>}`);
}
+ if (t.words !== undefined) {
+ // Its script's words, timed in take seconds (the editor's transcription, aligned: word-zoom.mjs scriptWordTimes).
+ const ws = t.words;
+ const bad = !Array.isArray(ws) || ws.length > 20000 ? -2 : ws.findIndex((x) => !isObj(x) || typeof x.w !== "string" || !fin(x.start) || !fin(x.end) || x.start < 0 || x.end < x.start || Object.keys(x).some((kk) => kk !== "w" && kk !== "start" && kk !== "end"));
+ if (bad === -2) errors.push(`${tw}.words must be a list of { w, start, end } (its words, timed; at most 20000)`);
+ else if (bad >= 0) errors.push(`${tw}.words[${bad}] must be { w, start, end } (take seconds, end ≥ start)`);
+ }
if (t.steps !== undefined) {
if (!Array.isArray(t.steps) || t.steps.length > 20) errors.push(`${tw}.steps must be a list (at most 20)`);
else t.steps.forEach((st, k) => {
diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs
@@ -73,8 +73,9 @@ export function redactPattern(terms) {
/**
* `text` with every match of `terms` (and every `spans` range, `{start, end}`
- * in code units) turned into REDACT_MARKs, one per code unit -- its length and
- * every offset kept, so a layout measured on it is the original's. Returns
+ * in code units) turned into REDACT_MARKs, one per code unit, its spaces kept
+ * -- its length, every offset and its words (runs of non-space) kept, so a
+ * layout measured on it and a word index counted on it are the original's. Returns
* `{ text, spans }`: the merged ranges, sorted.
*
* @param {string} text
@@ -102,7 +103,8 @@ export function redactText(text, terms, { spans: extra = [] } = {}) {
let out = "";
let at = 0;
for (const [a, b] of merged) {
- out += s.slice(at, a) + REDACT_MARK.repeat(b - a);
+ // Every code unit marked but the spaces: a phrase stays as many card words as it was (a word zoom's indices hold).
+ out += s.slice(at, a) + s.slice(a, b).replace(/\S/g, REDACT_MARK);
at = b;
}
return { text: out + s.slice(at), spans: merged.map(([start, end]) => ({ start, end })) };
@@ -118,7 +120,8 @@ export const hasMarks = (text) => str(text).includes(REDACT_MARK);
* at a sentence's start -- taken away. Only around a mark; the rest verbatim.
*/
export function dropMarks(marked) {
- const parts = str(marked).split(MARKS_RE);
+ // A phrase's marks with its spaces between them are one run to drop.
+ const parts = str(marked).split(/\uE000(?:[\s\uE000]*\uE000)?/);
if (parts.length === 1) return parts[0];
let out = parts[0];
for (let i = 1; i < parts.length; i += 1) {
diff --git a/umtool/report-to-video/post-redact.test.mjs b/umtool/report-to-video/post-redact.test.mjs
@@ -28,7 +28,8 @@ test("a phrase matches across any spaces or punctuation; its length and offsets
const r = redactText(s, NAME);
assert.equal(r.text.length, s.length);
assert.deepEqual(r.spans, [{ start: 8, end: 25 }]);
- assert.equal(r.text, `Signed, ${marks(17)} -- for real`);
+ // Its spaces kept: as many card words as before (a word zoom's indices hold).
+ assert.equal(r.text, `Signed, ${marks(8)}\n ${marks(7)} -- for real`);
assert.equal(redactText("Quentin alone", NAME).spans.length, 0, "a phrase is all its words");
assert.equal(redactText("@QuentinExample", NAME).text, `@${marks(14)}`);
// A span of the archived text (markup), merged with a match it overlaps.
@@ -63,7 +64,9 @@ test("the card AS PUBLISHED never holds a term: words, names, handles, context,
assert.ok((html.match(/data-post-blanked=""/g) ?? []).length >= 5, "the post, the parent, the paraphrase, the name and the handle");
assert.match(html, /\.rbar \{ display: inline-block/);
// Without a redaction, the card is the words.
- assert.match(postCardHtml(entry, { width: 1280, height: 720 }), /QUENTIN example/);
+ const plain = postCardHtml(entry, { width: 1280, height: 720 });
+ assert.match(plain, />QUENTIN</);
+ assert.match(plain, />example</);
// The entry itself is never rewritten.
assert.equal(entry.text, "Hi, I'm QUENTIN example and this is my channel");
assert.equal(redactEntry(entry, { terms: [] }), entry);
@@ -90,3 +93,20 @@ test("render.posts.redact is validated with the build's check", () => {
assert.equal(bad.length, 4, bad.join("; "));
assert.ok(validatePostItems({ timeline: [], render: { posts: { redact: "nope" } } }).some((e) => e.includes("render.posts.redact must be a list")));
});
+
+test("with a word zoom: the redacted text keeps its card words (the zoom's indices hold), a zoom on a redacted word is refused", async () => {
+ const { fxRedactionErrors, validatePostItems: vpi } = await import("./post-item.mjs");
+ const { cardWordsOf } = await import("./word-zoom.mjs");
+ const text = "So Quentin Example said barbecue twice, barbecue!";
+ assert.equal(cardWordsOf(redactText(text, NAME).text).length, cardWordsOf(text).length);
+ const e = { type: "post", id: "z1", post: "c-x/1", platform: "x", text, date: "2026-10-30T04:00:00Z", fx: [{ kind: "word-zoom", match: "barbecue", occurrence: 2, at: 1 }] };
+ assert.deepEqual(fxRedactionErrors(e, { terms: NAME }), []);
+ // The published card: the bars in the redacted words' slots, the zoom's word where it was.
+ const html = postCardHtml(e, { width: 1280, height: 720, redaction: { terms: NAME }, highlight: { scope: "post", from: 6, to: 6, color: "#ffd84d" } });
+ assert.match(html, /data-w="post:6" data-w-hl="">barbecue!/);
+ assert.match(html, /data-w="post:1"><span class="rbar"/);
+ const onName = { ...e, fx: [{ kind: "word-zoom", match: "Example", at: 1 }] };
+ assert.equal(fxRedactionErrors(onName, { terms: NAME }).length, 1);
+ assert.ok(vpi({ timeline: [onName], render: { posts: { redact: NAME } } }).some((x) => x.includes("is a redacted word")));
+ assert.deepEqual(vpi({ timeline: [onName], render: {} }), []);
+});
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -18,10 +18,11 @@ import { createHash } from "node:crypto";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
-import { POST_PICTURE_XFADE, POST_PUSH, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs";
+import { POST_PICTURE_XFADE, POST_PUSH, fxRedactionErrors, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs";
import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters } from "./post-narration.mjs";
import { redactEntry, redactionOn, spokenWithout, termsFor } from "./post-redact.mjs";
import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs";
+import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs";
const r3 = (v) => Math.round(v * 1000) / 1000;
const num = (v) => String(r3(v));
@@ -64,7 +65,7 @@ export function stepCaptions(step, cues) {
*
* @returns {string[]}
*/
-export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null }) {
+export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [] }) {
const fps = render.fps ?? 30;
const T = plan.total;
const inputs = [];
@@ -87,6 +88,30 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
parts.push(`[${mi}:v]scale=${box.width}:${box.height},setsar=1,fps=${fps}[mc]`);
lay("mc", 0, 0, plan.steps[0].at, T);
}
+ // WORD ZOOMS (word-zoom.mjs): the card's region, shot at k× (crisp when pushed in), zoomed toward the word on
+ // the curve -- frame by frame, zoompan on the item's second -- its highlight fading in under the word; laid over
+ // the card's region only while it is up, before the attachments (which it never covers).
+ zooms.forEach((zm, zi) => {
+ const { span, region, target, k } = zm;
+ const D = Math.max(1 / fps, span.t3 - span.t0);
+ const pi = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", zm.plain]);
+ parts.push(`[${pi}:v]scale=${region.width * k}:${region.height * k},setsar=1,format=rgba[wzp${zi}]`);
+ let src = `wzp${zi}`;
+ if (zm.hl) {
+ const hi = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", zm.hl]);
+ parts.push(
+ `[${hi}:v]scale=${region.width * k}:${region.height * k},setsar=1,format=rgba,fade=t=in:st=0:d=${num(Math.max(0.04, span.t1 - span.t0))}:alpha=1,` +
+ `fade=t=out:st=${num(span.t2 - span.t0)}:d=${num(Math.max(0.04, span.t3 - span.t2))}:alpha=1[wzh${zi}]`,
+ `[wzp${zi}][wzh${zi}]overlay=0:0:format=auto[wzc${zi}]`,
+ );
+ src = `wzc${zi}`;
+ }
+ const ex = zoompanExprs(span, target, k, `(${num(span.t0)}+on/${fps})`);
+ parts.push(`[${src}]zoompan=z='${ex.z}':x='${ex.x}':y='${ex.y}':d=1:s=${region.width}x${region.height}:fps=${fps},setsar=1,setpts=PTS-STARTPTS+${num(span.t0)}/TB[wz${zi}]`);
+ const next = `b${++n}`;
+ parts.push(`[${cur}][wz${zi}]overlay=x=${region.x}:y=${region.y}:eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`);
+ cur = next;
+ });
const audio = [];
const picture = (st) => !!st && (st.kind === "image" || st.kind === "grid" || st.kind === "gif");
plan.steps.forEach((step, si) => {
@@ -197,7 +222,7 @@ async function loadChromium() {
* stack layout. The page is a file beside them, so its faces and the parent
* shot load from disk (an about:blank page may not read file: urls).
*/
-export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, redaction = null }) {
+export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null }) {
await mkdir(dir, { recursive: true });
const fonts = {
regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
@@ -226,12 +251,109 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
out[phase] = png;
}
await ctx.close();
+ if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction });
} finally {
await browser.close();
}
return out;
}
+/** The device scale a word zoom's shots are taken at: crisp at its scale (2–4). */
+export const zoomShotScale = (zooms) => Math.min(4, Math.max(2, Math.ceil(Math.max(1, ...zooms.map((z) => z.scale ?? WORD_ZOOM_DEFAULTS.scale)))));
+
+/**
+ * Each WORD ZOOM's shots and geometry: the card's page at k× (zoomShotScale),
+ * its card's box inset by its corner (the REGION a zoom fills), the matched
+ * words' box (their spans' union, `data-w="<scope>:<i>"`) -- refused when a
+ * word is cut off the card (a clamped context post, a post shrunk to fit) --
+ * and the region shot plain and with the zoom's highlight under the words.
+ * `zooms`: `[{ i, scope, from, to, scale, highlight }]`.
+ */
+async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction = null }) {
+ const k = zoomShotScale(zooms);
+ const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: k, offline: true, serviceWorkers: "block" });
+ const page = await ctx.newPage();
+ const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href]));
+ const load = async (name, highlight) => {
+ const file = path.join(dir, `${name}.html`);
+ await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, redaction }), "utf8");
+ await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
+ await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
+ };
+ const out = [];
+ try {
+ await load("zoom", null);
+ const radius = Math.round(18 * (box.height / 1080)) + 1;
+ for (const z of zooms) {
+ const geo = await page.evaluate(({ scope, from, to, radius: r }) => {
+ const rect = (el) => {
+ const b = el.getBoundingClientRect();
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
+ };
+ const card = document.querySelector("[data-post-card]");
+ if (!card) return { error: "the card is not drawn" };
+ const c = rect(card);
+ const spans = [];
+ for (let i = from; i <= to; i += 1) {
+ const el = document.querySelector(`[data-w="${scope}:${i}"]`);
+ if (!el) return { error: `word ${i} is not on the card` };
+ spans.push(el);
+ }
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (const el of spans) {
+ const b = rect(el);
+ const clip = el.closest(".words, .ptext, .qtext");
+ const cb = clip ? clip.getBoundingClientRect() : card.getBoundingClientRect();
+ if (b.y + b.height > cb.bottom + 1 || b.y < cb.top - 1 || b.width === 0) return { error: "cut off the card (the text is longer than the card shows)" };
+ x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y); x1 = Math.max(x1, b.x + b.width); y1 = Math.max(y1, b.y + b.height);
+ }
+ const even = (v) => Math.max(2, Math.floor(v / 2) * 2);
+ const region = { x: Math.ceil(c.x + r), y: Math.ceil(c.y + r), width: even(c.width - 2 * r), height: even(c.height - 2 * r) };
+ return { region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } };
+ }, { scope: z.scope, from: z.from, to: z.to, radius });
+ if (geo.error) throw new Error(`${entry.id}: word zoom ${z.i + 1}: the word is ${geo.error}`);
+ out.push({ ...z, k, region: geo.region, word: geo.word });
+ }
+ const clip = (r) => ({ x: r.x, y: r.y, width: r.width, height: r.height });
+ for (const z of out) {
+ z.plain = path.join(dir, `zoom-${z.i}.png`);
+ await page.screenshot({ path: z.plain, clip: clip(z.region) });
+ }
+ for (const z of out) {
+ if (!z.highlight) continue;
+ await load(`zoom-hl-${z.i}`, { scope: z.scope, from: z.from, to: z.to, color: z.highlight });
+ z.hl = path.join(dir, `zoom-hl-${z.i}.png`);
+ await page.screenshot({ path: z.hl, clip: clip(z.region) });
+ }
+ } finally {
+ await ctx.close();
+ }
+ return out;
+}
+
+/**
+ * A post item's word zooms, resolved for the build: `[{ i, scope, from, to,
+ * scale, highlight, span }]`, each on its time (wordZoomTimes) -- refused in
+ * the build's words when one has no time, or two are up at once.
+ */
+export function postZoomPlan(entry, render, total = Infinity) {
+ const fx = Array.isArray(entry?.fx) ? entry.fx : [];
+ if (!fx.length) return [];
+ const times = wordZoomTimes(entry, render);
+ const bad = times.filter((t) => t.error);
+ if (bad.length) throw new Error(bad.map((t) => t.error).join("; "));
+ const zooms = fx.map((f0, i) => {
+ const f = resolveWordZoom(f0);
+ const m = findMatch(targetTextOf(entry, f.target), f.match, f.occurrence);
+ return { i, scope: targetScope(f.target), from: m.from, to: m.to, scale: f.scale, highlight: f.highlight === false ? null : f.highlight, t: times[i].t, source: times[i].source, span: zoomSpan(f0, times[i].t) };
+ });
+ const late = zooms.find((z) => z.span.t0 >= total - 0.05);
+ if (late) throw new Error(`${entry.id}: word zoom ${late.i + 1} ("${resolveWordZoom(fx[late.i]).match}") starts at ${late.span.t0} s, after the post's ${total} s (move its at)`);
+ const clash = overlappingZooms(zooms.map((z) => z.span));
+ if (clash) throw new Error(`${entry.id}: word zooms ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at, or shorten its hold)`);
+ return zooms;
+}
+
/**
* Build post item `entry`'s segment. `ctx`: `{ render, outDir, manifestDir,
* box, place, encode, exec, ffmpeg, emit, avatars }` -- the box it fills (the
@@ -244,6 +366,9 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null }) {
// A channel's markup may censor an attachment for every project (post-censor.mjs); the item's own blur wins.
entry = censorEntry(entry, redaction);
+ // A word zoom on a redacted word is refused in the build's words (the corpus's terms and the markup included).
+ const fxRed = fxRedactionErrors(entry, redaction);
+ if (fxRed.length) throw new Error(fxRed.join("; "));
const seg = path.join(outDir, "segments", `${entry.id}.mp4`);
const plan = postItemPlan(entry, render);
const layout = postLayout(entry, box);
@@ -271,7 +396,9 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
return seg;
}
const cardDir = path.join(outDir, "cards", `post-${entry.id}`);
- const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, redaction });
+ const zoomPlan = postZoomPlan(entry, render, plan.total);
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction });
+ const zooms = (cards.zooms ?? []).map((z) => ({ ...z, target: zoomTarget(z.region, { ...z.word }, z.span.scale) }));
// Its video attachments' words, when transcribed: one textfile per cue.
const captions = [];
for (const [si, step] of plan.steps.entries()) {
@@ -294,7 +421,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg });
narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs };
}
- const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration });
+ const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms });
try {
await exec(ffmpeg, argv, { maxBuffer: 1 << 24 });
} catch (err) {
@@ -302,12 +429,13 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
throw new Error(`${entry.id}: ffmpeg failed on the post item\n${detail}`);
}
await rename(tmp, seg);
- await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs } } : {}) }, null, 2) + "\n", "utf8");
+ await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs } } : {}) }, null, 2) + "\n", "utf8");
emit("note", {
message: narration
? `${entry.id}: post item ${plan.total.toFixed(1)} s, narrated (${take.file}: ${plan.narration.seconds.toFixed(1)} s from ${plan.narration.at} s, muffled to ${plan.narration.voiceEnd.toFixed(1)} s)`
: `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})`,
});
+ for (const z of zooms) emit("note", { message: `${entry.id}: word zoom ${z.i + 1} at ${z.t.toFixed(2)} s (${z.source === "at" ? "set by hand" : "from the take's words"}), ${z.span.scale}× over ${z.span.t0}–${z.span.t3} s` });
return seg;
}
diff --git a/umtool/report-to-video/word-zoom.mjs b/umtool/report-to-video/word-zoom.mjs
@@ -0,0 +1,414 @@
+// A POST ITEM's WORD ZOOM (umtool/docs/report-video.md, "A word zoom"; operator,
+// 3 Nov: "zoom in on the "barbecue" typo when it's being read out and make that
+// effect a standard thing we can use and tune in the UI"): the card pushed in on
+// one word (or a phrase) of its text as it is read, a highlight under it, then
+// back out.
+//
+// entry.fx = [{ kind: "word-zoom",
+// target?: "post" | "parent:<i>" | "quoted", // whose words (default: the post's own)
+// match: "<the word or phrase, as the card shows it>",
+// occurrence?: n, // its n-th time in that text (default 1)
+// at?: <item seconds>, // when; absent: from the take's word timings
+// lead?: s, hold?: s, scale?: 1.2–4, // in over lead before it, held, x scale
+// ease?: "out" | "inOut" | "snap",
+// highlight?: "#rrggbb" | false }] // the marker under it (default WORD_ZOOM_DEFAULTS)
+//
+// WHEN: `at` when it is set (the operator's nudge wins), else the matched
+// word's start in the picked take (`takes[i].words`, the editor's transcription
+// aligned to the script: `umtool posts narrate <p> <item> --words`) on the
+// item's clock -- the read's lead + start ÷ the read's rate. An un-narrated
+// post has no read to time it by: its zoom needs `at`.
+//
+// THE CURVE (one function, the render's ffmpeg expressions and Play's CSS read
+// it): progress p 0 → 1 over [t - lead, t] on the ease, 1 for `hold`, back to 0
+// over WORD_ZOOM_OUT on the same ease. The zoom is z = 1 + (scale - 1)·p; the
+// window is the card's region at 1/z of its size, moving toward the word so the
+// word's box is centred (clamped inside the region) when z = scale.
+//
+// PURE and dependency-free but for the post's text rules: the validator, the
+// card's word tokens (the card HTML wraps each in a span the build measures),
+// the match, the alignment of recognized words to a script, the time, the curve.
+
+import { cardText, contextText, parentsOf } from "./post-item.mjs";
+import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs";
+
+export const POST_FX_KINDS = Object.freeze(["word-zoom"]);
+export const POST_FX_MAX = 8;
+export const WORD_ZOOM_EASES = Object.freeze(["out", "inOut", "snap"]);
+export const WORD_ZOOM_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.5, hold: 1.2, scale: 2, ease: "inOut", highlight: "#ffd84d" });
+export const WORD_ZOOM_LIMITS = Object.freeze({ lead: [0, 3], hold: [0, 10], scale: [1.2, 4], at: [0, 600], occurrence: [1, 99] });
+/** The way back out, seconds, on the zoom's ease. */
+export const WORD_ZOOM_OUT = 0.4;
+/** The highlight's fill: the colour at this opacity, under the words (the card's text stays on top, readable). */
+export const WORD_ZOOM_HIGHLIGHT_ALPHA = 0.42;
+/** The longest match, in characters. */
+export const WORD_ZOOM_MATCH_MAX = 120;
+
+const KEYS = new Set(["kind", "target", "match", "occurrence", "at", "lead", "hold", "scale", "ease", "highlight"]);
+const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const numIn = (v, [lo, hi]) => fin(v) && v >= lo && v <= hi;
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const str = (v) => (typeof v === "string" ? v : "");
+
+// ---------------------------------------------------------------------------
+// The card's words.
+// ---------------------------------------------------------------------------
+
+/** The text's tokens as the card draws them: `[{ tok, i }]` for each run of non-space (i from 0), `{ space }` between. */
+export function cardTokens(text) {
+ const out = [];
+ let i = 0;
+ for (const part of str(text).split(/(\s+)/)) {
+ if (!part) continue;
+ if (/^\s+$/.test(part)) out.push({ space: part });
+ else out.push({ tok: part, i: i++ });
+ }
+ return out;
+}
+
+/** The card's words of `text` (cardTokens' words, in order). */
+export const cardWordsOf = (text) => cardTokens(text).filter((t) => t.tok !== undefined).map((t) => t.tok);
+
+/** A word reduced for matching: lower case, its leading and trailing punctuation gone ("Barbecue," -> "barbecue"). */
+export const normWord = (w) => str(w).toLowerCase().normalize("NFKC").replace(/[‘’]/g, "'").replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
+
+/** The text a target names on the card (the post's own words; a context post's: its paraphrase when it has one), or null. */
+export function targetTextOf(entry, target = "post") {
+ if (target === "post") return cardText(entry);
+ if (target === "quoted") return isObj(entry?.quoted) ? contextText(entry.quoted) : null;
+ const m = /^parent:(\d+)$/.exec(String(target));
+ if (m) {
+ const p = parentsOf(entry)[Number(m[1])];
+ return p ? contextText(p) : null;
+ }
+ return null;
+}
+
+/** The scope a target's word spans carry on the card (`data-w="<scope>:<i>"`). */
+export const targetScope = (target = "post") => String(target ?? "post");
+
+/**
+ * Where `match` is in `text`: its `occurrence`-th run of words (1-based), as
+ * `{ from, to, count }` card-word indices (inclusive), or `{ error, count }`
+ * (from and to -1).
+ * @param {string|null|undefined} text
+ * @param {string} match
+ * @param {number} [occurrence]
+ * @returns {{ from: number, to: number, count: number, error?: string }}
+ */
+export function findMatch(text, match, occurrence = 1) {
+ const want = str(match).split(/\s+/).map(normWord).filter(Boolean);
+ if (!want.length) return { error: "match names no word", count: 0, from: -1, to: -1 };
+ const words = cardWordsOf(text).map(normWord);
+ const hits = [];
+ for (let i = 0; i + want.length <= words.length; i += 1) {
+ if (want.every((w, k) => words[i + k] === w)) hits.push(i);
+ }
+ const n = Number.isInteger(occurrence) ? occurrence : 1;
+ if (!hits.length) return { error: "not in", count: 0, from: -1, to: -1 };
+ if (n > hits.length) return { error: "occurrence", count: hits.length, from: -1, to: -1 };
+ return { from: hits[n - 1], to: hits[n - 1] + want.length - 1, count: hits.length };
+}
+
+const TARGET_NAME = (t) => (t === "post" ? "the post's words" : t === "quoted" ? "the quoted post's words" : `the words of the post it answers (${t})`);
+
+// ---------------------------------------------------------------------------
+// The validator.
+// ---------------------------------------------------------------------------
+
+/**
+ * One zoom with every default filled in.
+ * @param {Record<string, any> | null | undefined} fx
+ * @returns {{ kind?: string, target: string, match: string, occurrence: number, at?: number, lead: number, hold: number, scale: number, ease: string, highlight: string | false }}
+ */
+export const resolveWordZoom = (fx) => ({ ...WORD_ZOOM_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) });
+
+/** Every reason post item `e`'s `fx` cannot be built, as sentences (empty: it can). Time is the build's to judge (wordZoomTimes). */
+export function validatePostFx(e) {
+ if (e?.fx === undefined) return [];
+ const w = `timeline ${e?.id ?? "?"}.fx`;
+ if (!Array.isArray(e.fx)) return [`${w} must be a list of the post's effects ([{ kind: "word-zoom", match, … }])`];
+ const errors = [];
+ if (e.fx.length > POST_FX_MAX) errors.push(`${w}: at most ${POST_FX_MAX} effects`);
+ e.fx.forEach((fx, i) => {
+ const fw = `${w}[${i}]`;
+ if (!isObj(fx)) return errors.push(`${fw} must be an object`);
+ if (!POST_FX_KINDS.includes(fx.kind)) return errors.push(`${fw}.kind must be one of ${POST_FX_KINDS.join(", ")}`);
+ for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a word-zoom key (${[...KEYS].join(", ")})`);
+ const target = fx.target ?? "post";
+ const text = typeof target === "string" ? targetTextOf(e, target) : null;
+ if (fx.target !== undefined && !(typeof fx.target === "string" && /^(post|quoted|parent:\d+)$/.test(fx.target))) errors.push(`${fw}.target must be "post", "quoted" or "parent:<i>"`);
+ else if (text === null) errors.push(`${fw}.target ${target}: the card draws no such post (${target === "quoted" ? "it quotes none" : "it answers no post there"})`);
+ if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase to zoom on, as the card shows it`);
+ else if (fx.match.length > WORD_ZOOM_MATCH_MAX) errors.push(`${fw}.match is longer than ${WORD_ZOOM_MATCH_MAX} characters`);
+ if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, WORD_ZOOM_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`);
+ if (typeof fx.match === "string" && fx.match.trim() && text !== null) {
+ const m = findMatch(text, fx.match, fx.occurrence ?? 1);
+ if (m.error === "not in") errors.push(`${fw}.match "${fx.match}" is not in ${TARGET_NAME(target)}`);
+ else if (m.error === "occurrence") errors.push(`${fw}.match "${fx.match}" is in ${TARGET_NAME(target)} ${m.count} time${m.count === 1 ? "" : "s"}: occurrence ${fx.occurrence} is not there`);
+ else if (m.error) errors.push(`${fw}.match: ${m.error}`);
+ }
+ for (const k of ["at", "lead", "hold", "scale"]) {
+ if (fx[k] !== undefined && !numIn(fx[k], WORD_ZOOM_LIMITS[k])) errors.push(`${fw}.${k} must be ${WORD_ZOOM_LIMITS[k][0]}–${WORD_ZOOM_LIMITS[k][1]}${k === "scale" ? " (times the card)" : " seconds"}`);
+ }
+ if (fx.ease !== undefined && !WORD_ZOOM_EASES.includes(fx.ease)) errors.push(`${fw}.ease must be one of ${WORD_ZOOM_EASES.join(", ")}`);
+ if (fx.highlight !== undefined && fx.highlight !== false && !(typeof fx.highlight === "string" && HEX_RE.test(fx.highlight))) errors.push(`${fw}.highlight must be a colour (#rrggbb) or false (none)`);
+ });
+ return errors;
+}
+
+// ---------------------------------------------------------------------------
+// Word timings: the editor's recognized words aligned to the script.
+// ---------------------------------------------------------------------------
+
+const NUMBERS = { 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 20: "twenty", 100: "hundred" };
+const spoken = (w) => {
+ const n = normWord(w).replace(/'/g, "");
+ return /^\d+$/.test(n) && NUMBERS[Number(n)] ? NUMBERS[Number(n)] : n;
+};
+
+function lev(a, b) {
+ if (a === b) return 0;
+ if (!a.length) return b.length;
+ if (!b.length) return a.length;
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
+ for (let i = 1; i <= a.length; i += 1) {
+ const cur = [i];
+ for (let j = 1; j <= b.length; j += 1) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
+ prev = cur;
+ }
+ return prev[b.length];
+}
+
+/** How alike two words are, 0–1: 1 the same, else 1 - edit distance ÷ the longer (a typo read as the word it means scores high). */
+export function wordSimilarity(a, b) {
+ const x = spoken(a);
+ const y = spoken(b);
+ if (!x || !y) return 0;
+ if (x === y) return 1;
+ const max = Math.max(x.length, y.length);
+ // The edit distance is at least the difference in length: past half the longer, no pair (skip the work).
+ if (Math.abs(x.length - y.length) > max * (1 - ALIGN_MIN)) return 0;
+ return Math.max(0, 1 - lev(x, y) / max);
+}
+
+/** Below this, two words are not the same word. */
+export const ALIGN_MIN = 0.5;
+
+/**
+ * THE ALIGNMENT, in order: each word of `a` paired with at most one of `b`,
+ * never crossing, maximising the summed similarity (pairs under ALIGN_MIN are
+ * not pairs). Returns `map[i]` = b's index for a's word i, or -1.
+ *
+ * @param {string[]} a
+ * @param {string[]} b
+ */
+export function alignWords(a, b) {
+ const n = a.length;
+ const m = b.length;
+ const map = new Array(n).fill(-1);
+ if (!n || !m) return map;
+ const W = m + 1;
+ const D = new Float32Array((n + 1) * W);
+ const sim = (i, j) => wordSimilarity(a[i], b[j]);
+ for (let i = 1; i <= n; i += 1) {
+ for (let j = 1; j <= m; j += 1) {
+ const s = sim(i - 1, j - 1);
+ const diag = s >= ALIGN_MIN ? D[(i - 1) * W + j - 1] + s : -1;
+ D[i * W + j] = Math.max(D[(i - 1) * W + j], D[i * W + j - 1], diag);
+ }
+ }
+ let i = n;
+ let j = m;
+ while (i > 0 && j > 0) {
+ const here = D[i * W + j];
+ if (here === D[(i - 1) * W + j]) i -= 1;
+ else if (here === D[i * W + j - 1]) j -= 1;
+ else {
+ map[i - 1] = j - 1;
+ i -= 1;
+ j -= 1;
+ }
+ }
+ return map;
+}
+
+/** A script's spoken words: its runs of non-space, Orpheus's tags (<sigh>) dropped. */
+export const scriptWordsOf = (script) => str(script).replace(/<[^<>]*>/g, " ").split(/\s+/).filter((w) => normWord(w));
+
+/**
+ * A TAKE's WORD TIMINGS from what the editor heard: `recognized` `[{ w, start,
+ * end }]` (take seconds, in order) aligned to the script's words; each script
+ * word gets the times of the word it was heard as, and a word not heard (or
+ * heard as something else) is spread evenly between its heard neighbours.
+ * Returns `[{ w, start, end }]`, one per script word, and how many were heard.
+ *
+ * @param {string} script
+ * @param {Array<{ w: string, start: number, end: number }>} recognized
+ */
+export function scriptWordTimes(script, recognized) {
+ const words = scriptWordsOf(script);
+ const heard = (Array.isArray(recognized) ? recognized : []).filter((r) => r && typeof r.w === "string" && fin(r.start) && fin(r.end) && normWord(r.w));
+ const map = alignWords(words, heard.map((r) => r.w));
+ const out = words.map((w, i) => (map[i] >= 0 ? { w, start: r3(heard[map[i]].start), end: r3(Math.max(heard[map[i]].start, heard[map[i]].end)) } : { w, start: null, end: null }));
+ const total = heard.length ? heard[heard.length - 1].end : 0;
+ for (let i = 0; i < out.length; ) {
+ if (out[i].start !== null) {
+ i += 1;
+ continue;
+ }
+ let k = i;
+ while (k < out.length && out[k].start === null) k += 1;
+ const from = i > 0 ? out[i - 1].end : heard[0]?.start ?? 0;
+ const to = k < out.length ? out[k].start : Math.max(from, total);
+ const step = (to - from) / (k - i);
+ for (let x = i; x < k; x += 1) out[x] = { w: out[x].w, start: r3(from + step * (x - i)), end: r3(from + step * (x - i + 1)) };
+ i = k;
+ }
+ return { words: out, heard: map.filter((x) => x >= 0).length, of: words.length };
+}
+
+// ---------------------------------------------------------------------------
+// WHEN: each zoom's second on the item's clock.
+// ---------------------------------------------------------------------------
+
+/**
+ * Each zoom's moment, `[{ i, t, source: "at"|"words", word? } | { i, error }]`:
+ * `at` when set; else the matched word in the picked take's words -- the card's
+ * words aligned to the script it read -- at lead + start ÷ rate.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {Record<string, any> | null} [schedule]
+ * @returns {Array<{ i: number, t?: number, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>}
+ */
+export function wordZoomTimes(entry, render = undefined, schedule = undefined) {
+ const list = Array.isArray(entry?.fx) ? entry.fx : [];
+ const narrated = isNarrated(entry);
+ const take = narrated ? pickedTake(entry) : null;
+ // `schedule`: the item's narration schedule when the caller has it (Play: the plan's), else worked out here.
+ const sch = narrated ? schedule ?? narrationSchedule(entry, render) : null;
+ return list.map((fx0, i) => {
+ if (!isObj(fx0) || fx0.kind !== "word-zoom") return { i, error: "not a word zoom" };
+ const fx = resolveWordZoom(fx0);
+ if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" };
+ const w = `${entry?.id ?? "?"}: word zoom ${i + 1} ("${fx.match}")`;
+ if (!narrated) return { i, error: `${w} has no time: the post is not narrated, so set its second (at, item seconds)` };
+ const words = Array.isArray(take?.words) ? take.words : null;
+ if (!words?.length) return { i, error: `${w} has no time: its take has no word timings yet (umtool posts narrate <p> ${entry.id} --words, or the bench's Get word timings) -- or set at` };
+ const text = targetTextOf(entry, fx.target);
+ const m = findMatch(text, fx.match, fx.occurrence);
+ if (m.error) return { i, error: `${w} is not on the card` };
+ const map = alignWords(cardWordsOf(text), words.map((x) => x.w));
+ let hit = -1;
+ for (let k = m.from; k <= m.to && hit < 0; k += 1) hit = map[k];
+ if (hit < 0) return { i, error: `${w} is not in the read (the script does not say it, or the take's words do not reach it) -- set at` };
+ return { i, t: r3(sch.at + words[hit].start / (sch.rate || 1)), source: "words", word: { ...words[hit], index: hit } };
+ });
+}
+
+/** The reading estimate for an un-narrated post's word (the CLI's and the bench's first `at`): 1 s to find it, then 3 words a second. */
+export const readingEstimate = (wordIndex) => Math.round((1 + Math.max(0, wordIndex) / 3) * 100) / 100;
+
+// ---------------------------------------------------------------------------
+// THE CURVE.
+// ---------------------------------------------------------------------------
+
+/** The ease, 0–1 → 0–1. */
+export function easeOf(name, x) {
+ const v = Math.min(1, Math.max(0, x));
+ if (name === "out") return 1 - (1 - v) ** 3;
+ if (name === "snap") return v >= 1 ? 1 : 1 - 2 ** (-10 * v);
+ return v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2;
+}
+
+/** One zoom's span on the item's clock: in from t0 to t1 (= t), held to t2, out by t3. */
+export function zoomSpan(fx0, t) {
+ const fx = resolveWordZoom(fx0);
+ const t1 = r3(t);
+ const t0 = r3(Math.max(0, t1 - fx.lead));
+ const t2 = r3(t1 + fx.hold);
+ return { t0, t1, t2, t3: r3(t2 + WORD_ZOOM_OUT), scale: fx.scale, ease: fx.ease };
+}
+
+/** The zoom's progress at item second `s` (0 none, 1 all the way in). */
+export function zoomProgressAt(span, s) {
+ if (!span || s < span.t0 || s >= span.t3) return 0;
+ if (s < span.t1) return span.t1 > span.t0 ? easeOf(span.ease, (s - span.t0) / (span.t1 - span.t0)) : 1;
+ if (s < span.t2) return 1;
+ return 1 - easeOf(span.ease, (s - span.t2) / (span.t3 - span.t2));
+}
+
+/** The highlight's opacity at item second `s`, 0–1: linear in over the lead, out over the way back (the render's alpha fades). */
+export function highlightAt(span, s) {
+ if (!span || s < span.t0 || s >= span.t3) return 0;
+ if (s < span.t1) return span.t1 > span.t0 ? (s - span.t0) / (span.t1 - span.t0) : 1;
+ if (s < span.t2) return 1;
+ return 1 - (s - span.t2) / (span.t3 - span.t2);
+}
+
+/** The zoom factor at progress p. */
+export const zoomAt = (span, p) => 1 + (span.scale - 1) * p;
+
+/**
+ * THE WINDOW at zoom z: the part of `region` (the card's box, px) shown
+ * filling it -- 1/z of its size, moving from the whole region (z = 1) to the
+ * one centred on `word` (its box, px; clamped inside the region) at z = scale.
+ * @returns {{ x: number, y: number, width: number, height: number }}
+ */
+export function zoomWindow(region, word, scale, z) {
+ const fw = region.width / scale;
+ const fh = region.height / scale;
+ const cx = word.x + word.width / 2;
+ const cy = word.y + word.height / 2;
+ const fx = Math.min(region.x + region.width - fw, Math.max(region.x, cx - fw / 2));
+ const fy = Math.min(region.y + region.height - fh, Math.max(region.y, cy - fh / 2));
+ // q runs 0 → 1 as z runs 1 → scale, so the window is exactly region / z.
+ const q = scale > 1 ? (1 - 1 / z) / (1 - 1 / scale) : 0;
+ return { x: region.x + (fx - region.x) * q, y: region.y + (fy - region.y) * q, width: region.width / z, height: region.height / z };
+}
+
+/** The final window's offset in the region (zoomWindow at z = scale, relative to the region's corner). */
+export function zoomTarget(region, word, scale) {
+ const f = zoomWindow(region, word, scale, scale);
+ return { x: f.x - region.x, y: f.y - region.y };
+}
+
+const f4 = (v) => {
+ const s = (Math.round(Number(v) * 1e4) / 1e4).toFixed(4).replace(/\.?0+$/, "");
+ return s === "-0" ? "0" : s;
+};
+
+/** The ease as an ffmpeg expression of `X` (an expression clipped 0–1 by the caller). */
+export function easeExpr(name, X) {
+ if (name === "out") return `(1-pow(1-${X},3))`;
+ if (name === "snap") return `if(gte(${X},1),1,1-pow(2,-10*${X}))`;
+ return `if(lt(${X},0.5),4*pow(${X},3),1-pow(-2*${X}+2,3)/2)`;
+}
+
+/** zoomProgressAt as an ffmpeg expression of `S` (the item second). */
+export function progressExpr(span, S) {
+ const { t0, t1, t2, t3 } = span;
+ const inX = t1 > t0 ? `clip((${S}-${f4(t0)})/${f4(t1 - t0)},0,1)` : "1";
+ const outX = `clip((${S}-${f4(t2)})/${f4(t3 - t2)},0,1)`;
+ return `if(lt(${S},${f4(t0)}),0,if(lt(${S},${f4(t1)}),${t1 > t0 ? easeExpr(span.ease, inX) : "1"},if(lt(${S},${f4(t2)}),1,if(lt(${S},${f4(t3)}),1-${easeExpr(span.ease, outX)},0))))`;
+}
+
+/**
+ * The zoompan expressions for one zoom over its region scaled by `k` (the
+ * hi-res card's device scale): `z` from the item second `S`, and `x`, `y` --
+ * the window's corner in the region's px × k -- from zoompan's own `zoom`.
+ */
+export function zoompanExprs(span, target, k, S) {
+ const p = progressExpr(span, S);
+ const q = span.scale > 1 ? `(1-1/zoom)/${f4(1 - 1 / span.scale)}` : "0";
+ return { z: `1+${f4(span.scale - 1)}*${p}`, x: `${f4(target.x * k)}*${q}`, y: `${f4(target.y * k)}*${q}` };
+}
+
+/** Two zooms of one post that are up at once (they would fight): their indices, or null. */
+export function overlappingZooms(spans) {
+ const s = spans.map((x, i) => ({ ...x, i })).filter((x) => x.t3 !== undefined).sort((a, b) => a.t0 - b.t0);
+ for (let k = 1; k < s.length; k += 1) if (s[k].t0 < s[k - 1].t3) return [s[k - 1].i, s[k].i];
+ return null;
+}
diff --git a/umtool/report-to-video/word-zoom.test.mjs b/umtool/report-to-video/word-zoom.test.mjs
@@ -0,0 +1,148 @@
+// word-zoom.mjs: a post item's word zoom -- the validator, the match, the
+// alignment of the words heard to the script, the time on the item's clock and
+// the curve (the render's expressions and Play's CSS read the same one).
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { postCardHtml, validatePostItem } from "./post-item.mjs";
+import { postSegmentArgs, postZoomPlan } from "./post-render.mjs";
+import { postItemPlan, postLayout } from "./post-item.mjs";
+import {
+ WORD_ZOOM_OUT, alignWords, cardWordsOf, easeOf, findMatch, overlappingZooms, progressExpr, scriptWordTimes, wordSimilarity, wordZoomTimes,
+ zoomAt, zoomProgressAt, zoomSpan, zoomWindow, zoompanExprs,
+} from "./word-zoom.mjs";
+
+const TEXT = "If no one does stop me and save me from myself, barbecue if no one does, I'm going after him.";
+const base = (o = {}) => ({
+ type: "post", id: "p1", post: "obvious-x/2117488972809330822", platform: "x", author: "MR. OBVIOUS", handle: "ObviousRises",
+ date: "2026-11-03T04:00:00.000Z", text: TEXT, ...o,
+});
+const zoom = (o = {}) => ({ kind: "word-zoom", match: "barbecue", ...o });
+const take = (o = {}) => ({ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 6, script: TEXT, ...o });
+
+test("the validator: unknown keys refused, the match must be in the target's words, the knobs in their bounds", () => {
+ assert.deepEqual(validatePostItem(base({ fx: [zoom()] })), []);
+ assert.deepEqual(validatePostItem(base({ fx: [zoom({ match: "Barbecue,", occurrence: 1, at: 2, lead: 0.3, hold: 1, scale: 3, ease: "snap", highlight: false })] })), []);
+ // "if no one does" is said twice: its second time is there, a third is not.
+ assert.deepEqual(validatePostItem(base({ fx: [zoom({ match: "if no one does", occurrence: 2 })] })), []);
+ const errs = (fx) => validatePostItem(base({ fx: [fx] })).join("\n");
+ assert.match(errs(zoom({ match: "if no one does", occurrence: 3 })), /is in the post's words 2 times: occurrence 3 is not there/);
+ assert.match(errs(zoom({ match: "because" })), /fx\[0\]\.match "because" is not in the post's words/);
+ assert.match(errs(zoom({ zoomy: 1 })), /fx\[0\]\.zoomy is not a word-zoom key/);
+ assert.match(errs(zoom({ scale: 9 })), /scale must be 1.2–4/);
+ assert.match(errs(zoom({ ease: "bounce" })), /ease must be one of out, inOut, snap/);
+ assert.match(errs(zoom({ highlight: "yellow" })), /highlight must be a colour/);
+ assert.match(errs(zoom({ target: "quoted" })), /target quoted: the card draws no such post \(it quotes none\)/);
+ assert.match(errs({ kind: "sparkle" }), /kind must be one of word-zoom/);
+ assert.match(validatePostItem(base({ fx: { kind: "word-zoom" } })).join(), /fx must be a list/);
+ // A context post's words: its paraphrase when it has one (what the card shows).
+ const q = { quoted: { handle: "someone", text: "the original words", paraphrase: "a short retelling" } };
+ assert.deepEqual(validatePostItem(base({ ...q, fx: [zoom({ target: "quoted", match: "retelling" })] })), []);
+ assert.match(validatePostItem(base({ ...q, fx: [zoom({ target: "quoted", match: "original" })] })).join(), /not in the quoted post's words/);
+});
+
+test("the match: the card's words, case and edge punctuation aside, the n-th run", () => {
+ assert.deepEqual(findMatch(TEXT, "BARBECUE"), { from: 11, to: 11, count: 1 });
+ assert.equal(cardWordsOf(TEXT)[11], "barbecue");
+ assert.deepEqual(findMatch(TEXT, "no one does", 2), { from: 13, to: 15, count: 2 });
+ assert.equal(findMatch(TEXT, "zzz").error, "not in");
+});
+
+test("the card: each word a span the build measures; the highlight marks the zoom's words", () => {
+ const html = postCardHtml(base(), { width: 1280, height: 720 });
+ assert.match(html, /<span data-w="post:11">barbecue<\/span>/);
+ const lit = postCardHtml(base(), { width: 1280, height: 720, highlight: { scope: "post", from: 11, to: 11, color: "#ffd84d" } });
+ assert.match(lit, /<span data-w="post:11" data-w-hl="">barbecue<\/span>/);
+ assert.match(lit, /\[data-w-hl\] \{ background: rgba\(255, 216, 77, 0.42\)/);
+});
+
+test("the alignment: in order, fuzzy -- a typo read as the word it means, a word misheard, a word not heard", () => {
+ assert.ok(wordSimilarity("barbecue", "barbeque") > 0.8);
+ assert.ok(wordSimilarity("barbecue,", "Barbecue") === 1);
+ assert.ok(wordSimilarity("2", "two") === 1);
+ assert.ok(wordSimilarity("because", "barbecue") < 0.5);
+ // The script has the typo; the voice said it, the transcription heard "barbeque"; "myself" was not heard.
+ const script = "save me from myself, barbecue if no one does";
+ const heard = [
+ ["save", 0.1, 0.4], ["me", 0.4, 0.5], ["from", 0.5, 0.7], ["barbeque", 1.6, 2.1], ["if", 2.2, 2.3], ["know", 2.3, 2.5], ["one", 2.5, 2.7], ["does", 2.7, 3.0],
+ ].map(([w, start, end]) => ({ w, start, end }));
+ const r = scriptWordTimes(script, heard);
+ assert.equal(r.of, 9);
+ assert.equal(r.heard, 8); // "no" was heard as "know": fuzzy (2 letters of 4 apart is half: a pair)
+ assert.deepEqual(r.words[4], { w: "barbecue", start: 1.6, end: 2.1 });
+ // "myself," not heard: placed between "from" (ends 0.7) and "barbecue" (starts 1.6).
+ assert.deepEqual(r.words[3], { w: "myself,", start: 0.7, end: 1.6 });
+ // Tags are not words; order holds (a word heard later never pairs with an earlier one).
+ assert.equal(scriptWordTimes("<sigh> fine then", [{ w: "fine", start: 0, end: 0.3 }, { w: "then", start: 0.3, end: 0.6 }]).of, 2);
+ assert.deepEqual(alignWords(["a", "b", "c"], ["c", "a", "b"]), [1, 2, -1]);
+});
+
+test("the time: at when set; else the word's start in the take ÷ the read's rate, after its lead", () => {
+ const words = scriptWordTimes(TEXT, cardWordsOf(TEXT).map((w, i) => ({ w, start: i * 0.3, end: i * 0.3 + 0.25 }))).words;
+ const narrated = base({ narration: { script: TEXT, takes: [take({ words })], lead: 0.4 }, fx: [zoom()] });
+ // "barbecue" is word 11: 3.3 s into the take, read from 0.4 s.
+ assert.deepEqual(wordZoomTimes(narrated)[0].t, 3.7);
+ assert.equal(wordZoomTimes(narrated)[0].source, "words");
+ // At rate 1.25 the take's 3.3 s are 2.64 s of the item.
+ const fast = base({ narration: { script: TEXT, takes: [take({ words })], lead: 0.4, rate: 1.25 }, fx: [zoom()] });
+ assert.equal(wordZoomTimes(fast)[0].t, 3.04);
+ // The cut's rate too.
+ assert.equal(wordZoomTimes(narrated, { postNarration: { rate: 1.5 } })[0].t, 2.6);
+ // at wins.
+ assert.deepEqual(wordZoomTimes(base({ ...narrated, fx: [zoom({ at: 1.25 })] }))[0], { i: 0, t: 1.25, source: "at" });
+ // No words yet, or not narrated: no time, said how to give it one.
+ assert.match(wordZoomTimes(base({ narration: { script: TEXT, takes: [take()] }, fx: [zoom()] }))[0].error, /no word timings yet \(umtool posts narrate <p> p1 --words/);
+ assert.match(wordZoomTimes(base({ fx: [zoom()] }))[0].error, /not narrated, so set its second \(at/);
+ assert.throws(() => postZoomPlan(base({ fx: [zoom()] })), /not narrated/);
+ assert.throws(() => postZoomPlan(base({ fx: [zoom({ at: 1, hold: 3 }), zoom({ match: "him", at: 2 })] })), /word zooms 1 and 2 are up at once/);
+ assert.throws(() => postZoomPlan(base({ fx: [zoom({ at: 9 })] }), undefined, 5), /starts at 8.5 s, after the post's 5 s/);
+});
+
+test("the curve: in over lead on the ease, held, out over WORD_ZOOM_OUT; the window is region ÷ z, landing on the word", () => {
+ const span = zoomSpan(zoom({ lead: 0.5, hold: 1, scale: 2.5 }), 3);
+ assert.deepEqual(span, { t0: 2.5, t1: 3, t2: 4, t3: 4 + WORD_ZOOM_OUT, scale: 2.5, ease: "inOut" });
+ assert.equal(zoomProgressAt(span, 2.4), 0);
+ assert.equal(zoomProgressAt(span, 2.75), 0.5); // inOut is half way at half time
+ assert.equal(zoomProgressAt(span, 3.5), 1);
+ assert.ok(zoomProgressAt(span, 4.2) > 0 && zoomProgressAt(span, 4.2) < 1);
+ assert.equal(zoomProgressAt(span, 4.4), 0);
+ assert.equal(easeOf("out", 0.5), 0.875);
+ assert.ok(easeOf("snap", 0.3) > 0.85);
+ const region = { x: 40, y: 40, width: 800, height: 600 };
+ const word = { x: 700, y: 500, width: 100, height: 40 };
+ assert.deepEqual(zoomWindow(region, word, 2.5, 1), region);
+ const full = zoomWindow(region, word, 2.5, 2.5);
+ assert.equal(full.width, 320);
+ assert.equal(full.height, 240);
+ // Centred on the word, clamped inside the region (the word is near its corner).
+ assert.equal(full.x, 40 + 800 - 320);
+ assert.equal(full.y, 40 + 600 - 240);
+ const mid = zoomWindow(region, word, 2.5, zoomAt(span, 0.5));
+ assert.ok(Math.abs(mid.width - 800 / 1.75) < 1e-9);
+ // The ffmpeg expression is the same curve: evaluated at a few seconds.
+ const S = (s) => progressExpr(span, String(s));
+ const evalExpr = (ex) => Function("lt", "gte", "clip", "pow", "if_", `return ${ex.replace(/\bif\(/g, "if_(")};`)(
+ (a, b) => (a < b ? 1 : 0), (a, b) => (a >= b ? 1 : 0), (v, lo, hi) => Math.min(hi, Math.max(lo, v)), Math.pow, (c, a, b) => (c ? a : b),
+ );
+ for (const s of [2, 2.6, 2.75, 2.9, 3.5, 4.1, 4.3, 5]) assert.ok(Math.abs(evalExpr(S(s)) - zoomProgressAt(span, s)) < 1e-3, `at ${s}`);
+ const ex = zoompanExprs(span, { x: 480, y: 360 }, 3, "S");
+ assert.match(ex.x, /^1440\*\(1-1\/zoom\)\/0\.6$/);
+ assert.deepEqual(overlappingZooms([zoomSpan({}, 1), zoomSpan({}, 1.5)]), [0, 1]);
+ assert.equal(overlappingZooms([zoomSpan({}, 1), zoomSpan({}, 5)]), null);
+});
+
+test("the render: the zoom's region shot zoomed on the curve, laid over the card before the attachments, only while up", () => {
+ const e = base({ fx: [zoom({ at: 1.5 })], media: [{ src: "m/i.jpg", kind: "image", width: 1000, height: 1000 }] });
+ const box = { width: 1440, height: 810 };
+ const span = zoomSpan(e.fx[0], 1.5);
+ const zooms = [{ i: 0, k: 2, span, region: { x: 30, y: 30, width: 500, height: 740 }, target: { x: 100, y: 200 }, plain: "/c/zoom-0.png", hl: "/c/zoom-hl-0.png", t: 1.5 }];
+ const argv = postSegmentArgs({ entry: e, box, plan: postItemPlan(e), layout: postLayout(e, box), cards: { read: "/c/read.png" }, files: ["/m/i.jpg"], render: { fps: 30 }, outPath: "/o.mp4", zooms });
+ const graph = argv[argv.indexOf("-filter_complex") + 1];
+ assert.ok(argv.includes("/c/zoom-0.png") && argv.includes("/c/zoom-hl-0.png"));
+ assert.match(graph, /\[1:v\]scale=1000:1480,setsar=1,format=rgba\[wzp0\]/);
+ assert.match(graph, /fade=t=in:st=0:d=0.5:alpha=1,fade=t=out:st=1.7:d=0.4:alpha=1\[wzh0\]/);
+ assert.match(graph, /zoompan=z='1\+1\*if\(lt\(\(1\+on\/30\),1\)/);
+ assert.match(graph, /d=1:s=500x740:fps=30,setsar=1,setpts=PTS-STARTPTS\+1\/TB\[wz0\]/);
+ assert.match(graph, /\[b0\]\[wz0\]overlay=x=30:y=30:eof_action=pass:enable='between\(t,1,3.1\)'\[b1\]/);
+ // The attachment is laid after it: on top.
+ assert.ok(graph.indexOf("[wz0]overlay") < graph.indexOf("[m0_0]"));
+});