commit ae296c98706d0d91e5f6de6e5e3a95d347b09dfc
parent 4af3f830f8328f88db76bb6db23aeb0aa730d842
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 17:17:58 -0500
Merge main (word-zoom, post-redact, read-follow) into lane/combo-counter: every feature kept -- the combo badge is a pass over the finished post segment, so it lands over the read-follow card, the word zoom and a censored attachment's blur; Play and the bench draw it beside PostItemPlayer; posts' VALUED flags main's (its --match serves both verbs); docs: the combo sections after redaction, word zoom and read-follow
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
43 files changed, 4335 insertions(+), 81 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts
@@ -4,10 +4,15 @@ 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 { followKnobs } from "umtool-report-to-video/read-follow";
+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";
+import { projectRedaction } from "@/lib/report/postRedaction.mjs";
export const dynamic = "force-dynamic";
@@ -15,8 +20,10 @@ export const dynamic = "force-dynamic";
// umtool/docs/knobs.md, "A post item"): what Play the cut and the post bench
// draw a post item with, and the bench's writer.
//
-// GET ?project&id&w&h[&phase=read|media][&take] the card's page, the HTML the build
-// screenshots, at w × h (the footage box)
+// GET ?project&id&w&h[&phase=read|media][&take][&published=1] the card's page, the HTML the
+// build screenshots, at w × h (the footage box);
+// published=1 AS PUBLISHED: its redacted words bars
+// (post-redact.mjs), never in the page
// GET ?project&file=posts-media/… an attachment (byte ranges): only a file
// under the project's posts-media/
// GET ?project&font=regular|bold the cut's faces, for the page
@@ -25,6 +32,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" };
@@ -91,6 +104,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"));
@@ -120,12 +161,21 @@ export async function GET(request: Request) {
const parentShot = typeof found.item.parentShot === "string" ? `${base}&file=${encodeURIComponent(found.item.parentShot)}` : null;
// The authors' pictures (post-avatars.mjs), served as the project's files.
const avatars = avatarUrls(found.manifest, (src: string) => `${base}&file=${encodeURIComponent(src)}`) as Record<string, string>;
+ let redaction = null;
+ try {
+ if (q.get("published") === "1") redaction = await projectRedaction(r.project.dir, found.manifest);
+ } catch (e) {
+ return new Response(e instanceof Error ? e.message : String(e), { status: 500 });
+ }
const html = postCardHtml(found.item, {
width: w, height: h, avatars,
palette: (render.palette ?? {}) as Record<string, string>,
fonts: { regular: `${base}&font=regular`, bold: `${base}&font=bold` },
phase: q.get("phase") === "media" ? "media" : "read",
parentShotUrl: parentShot,
+ // Its read-follow (read-follow.mjs): the blocks and the flow Play lights and pans, as the build's page has them.
+ follow: q.get("phase") !== "media" && followKnobs(found.item, (found.manifest.render ?? render) as Record<string, unknown>).on,
+ redaction,
});
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } });
}
@@ -154,6 +204,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);
@@ -172,5 +252,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/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -13,6 +13,8 @@ import { refuseCaller } from "@/lib/report/caller";
import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs";
import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs";
import { fitPostItem } from "@/lib/report/postFit.mjs";
+import { projectRedaction } from "@/lib/report/postRedaction.mjs";
+import { spokenWithout, termsFor } from "umtool-report-to-video/post-redact";
export const dynamic = "force-dynamic";
@@ -167,7 +169,9 @@ export async function POST(request: Request) {
await mkdir(dir, { recursive: true });
const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice);
const speed = body.speed === undefined || body.speed === null || engine === "orpheus" ? undefined : Number(body.speed);
- const jobId = await startJob("/api/ops/tts", { text: script, engine, voice, out: path.join(r.project.dir, ...rel.split("/")), ...(speed ? { speed } : {}) });
+ // What the voice SAYS: the script with every redacted term left out (post-redact.mjs); the script is kept as written.
+ const spoken = spokenWithout(script, termsFor(e, await projectRedaction(r.project.dir, m)));
+ const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out: path.join(r.project.dir, ...rel.split("/")), ...(speed ? { speed } : {}) });
return Response.json({ ok: true, jobId, file: rel, engine, voice, script }, { headers: noStore });
}
if (body.op === "derive") {
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -115,6 +115,7 @@
// narrate <project> [<item>] --import | --take | --script | --pick | --approve | k=v | --all … narration
// fit <project> --all | <item>… narrated posts' videos cut to their best part
// avatar <project> <handle> <image> | avatars <project> the authors' pictures
+// redact <project> ls | add "<term>" [--substring] | remove <n> words blanked from what is published
// repeats <project> [--match id|file|audio] · combo <project> [<item>] k=v|off the combo counter
// umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel
import process from "node:process";
@@ -1037,6 +1038,8 @@ function usage() {
" | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)",
" umtool posts fit <project> [--all | <item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
" umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards",
+ " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> words blanked from",
+ " what is published (a bar on the card, left out of a synthesized read); the data never rewritten",
" umtool posts repeats <project> [--match id|file|audio] [--json] the attachments played more than once (the combo counter)",
" umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (the cut's, one item's)",
" umtool candidates <project> [ls] [--all] [--json] | import <sweep.md> [--dry-run] | add <json|@file>",
diff --git a/umtool/components/projects/BlurBoxPad.tsx b/umtool/components/projects/BlurBoxPad.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+
+// THE CENSOR BOXES, DRAWN (post-censor.mjs; knobs.md, "A post item"): the
+// attachment on a still frame -- a picture as it is, a video paused at the
+// bench's playhead (or its in point) -- shown as the cut shows it (its crop),
+// each box over it; drag to draw a new one, × to take one away. The boxes are
+// fractions of the picture as shown, which is what the render blurs.
+
+type Box = number[];
+type Props = {
+ project: string;
+ media: { src: string; kind: string; width?: number; height?: number; crop?: number[] };
+ /** The video's source second to hold still. */
+ at: number;
+ boxes: Box[];
+ onChange: (boxes: Box[]) => void;
+ index: number;
+};
+
+const r4 = (v: number) => Math.round(v * 10000) / 10000;
+const clamp = (v: number) => Math.min(1, Math.max(0, v));
+
+export default function BlurBoxPad({ project, media, at, boxes, onChange, index }: Props) {
+ const pad = useRef<HTMLDivElement | null>(null);
+ const video = useRef<HTMLVideoElement | null>(null);
+ const [drag, setDrag] = useState<{ x: number; y: number; x2: number; y2: number } | null>(null);
+ const crop = Array.isArray(media.crop) && media.crop.length === 4 ? media.crop : [0, 0, 1, 1];
+ const aspect = media.width && media.height ? (media.width * crop[2]) / (media.height * crop[3]) : 16 / 9;
+ const src = `/api/report/post-item?project=${encodeURIComponent(project)}&file=${encodeURIComponent(media.src)}`;
+ const inner: React.CSSProperties = {
+ position: "absolute", width: `${100 / crop[2]}%`, height: `${100 / crop[3]}%`, left: `${(-crop[0] / crop[2]) * 100}%`, top: `${(-crop[1] / crop[3]) * 100}%`, maxWidth: "none", objectFit: "fill",
+ };
+ useEffect(() => {
+ const v = video.current;
+ if (!v) return;
+ try {
+ v.currentTime = at;
+ } catch {
+ // not seekable yet
+ }
+ }, [at]);
+ const where = (ev: React.PointerEvent) => {
+ const r = pad.current!.getBoundingClientRect();
+ return { x: clamp((ev.clientX - r.left) / r.width), y: clamp((ev.clientY - r.top) / r.height) };
+ };
+ const box = (d: { x: number; y: number; x2: number; y2: number }): Box => {
+ const x = Math.min(d.x, d.x2);
+ const y = Math.min(d.y, d.y2);
+ return [r4(x), r4(y), r4(Math.abs(d.x2 - d.x)), r4(Math.abs(d.y2 - d.y))];
+ };
+ return (
+ <div className="space-y-1">
+ <div
+ ref={pad}
+ className="relative w-full cursor-crosshair touch-none select-none overflow-hidden rounded border border-seam bg-black"
+ style={{ aspectRatio: String(aspect) }}
+ data-post-bench-blur-pad={index}
+ onPointerDown={(ev) => {
+ if ((ev.target as HTMLElement).closest("button")) return;
+ (ev.currentTarget as HTMLDivElement).setPointerCapture(ev.pointerId);
+ const p = where(ev);
+ setDrag({ x: p.x, y: p.y, x2: p.x, y2: p.y });
+ }}
+ onPointerMove={(ev) => {
+ if (!drag) return;
+ const p = where(ev);
+ setDrag({ ...drag, x2: p.x, y2: p.y });
+ }}
+ onPointerUp={() => {
+ if (!drag) return;
+ const b = box(drag);
+ setDrag(null);
+ if (b[2] >= 0.01 && b[3] >= 0.01 && boxes.length < 8) onChange([...boxes, b]);
+ }}
+ >
+ {media.kind === "image" ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={src} alt="" draggable={false} style={inner} />
+ ) : (
+ <video ref={video} src={src} muted playsInline preload="auto" style={inner} />
+ )}
+ {[...boxes, ...(drag ? [box(drag)] : [])].map((b, j) => (
+ <div
+ key={j}
+ data-post-bench-blur-box={j < boxes.length ? j : "new"}
+ className="absolute border-2 border-amber-400 bg-amber-400/15"
+ style={{ left: `${b[0] * 100}%`, top: `${b[1] * 100}%`, width: `${b[2] * 100}%`, height: `${b[3] * 100}%` }}
+ >
+ {j < boxes.length && (
+ <button
+ type="button"
+ className="absolute right-0 top-0 bg-black/70 px-1 text-[11px] leading-none text-white"
+ onClick={() => onChange(boxes.filter((_, k) => k !== j))}
+ aria-label={`remove box ${j + 1}`}
+ data-post-bench-blur-box-remove={j}
+ >
+ ×
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ <p className="m-0 text-[11.5px] text-text-2">
+ drag on the frame to blur a region; no box blurs the whole frame{boxes.length ? ` · ${boxes.length} box${boxes.length === 1 ? "" : "es"}` : ""}
+ </p>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx
@@ -8,10 +8,14 @@ import { cn } from "@/lib/utils";
import { postBenchHref } from "@/lib/hrefs";
import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds, postItemPlan, readingSeconds, ruleSeconds } from "umtool-report-to-video/post-item";
import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer";
+import PostFollowPanel from "./PostFollowPanel";
+import BlurBoxPad from "./BlurBoxPad";
import PostNarrationPanel from "./PostNarrationPanel";
import PostComboPanel from "./PostComboPanel";
import ComboBadge, { type ComboInfo } from "./review/ComboBadge";
import { liveCombo } from "umtool-report-to-video/post-combo";
+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
@@ -31,7 +35,8 @@ import { liveCombo } from "umtool-report-to-video/post-combo";
// "paraphrased" label (its own text kept, shown beside)
// ---------------------------------------------------------------------------
-type Media = Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number; mute?: boolean; crop?: number[]; push?: boolean; words?: string; audio?: boolean; width?: number; height?: number };
+type Blur = { on: boolean; strength?: number; boxes?: number[][]; label?: string | false };
+type Media = Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number; mute?: boolean; crop?: number[]; push?: boolean; words?: string; audio?: boolean; width?: number; height?: number; blur?: Blur };
type Ref = Record<string, unknown> & { author?: string; handle?: string; text?: string; paraphrase?: string };
type Entry = Record<string, unknown> & { id: string; media?: Media[]; hold?: number; mediaLayout?: string; redact?: boolean; quoted?: Ref; parents?: Ref[] };
@@ -133,6 +138,8 @@ export default function PostBench({
hold: typeof e.hold === "number" ? e.hold : null,
mediaLayout: e.mediaLayout ?? null,
redact: typeof e.redact === "boolean" ? e.redact : null,
+ // Its read-follow (read-follow.mjs): false is off; its knobs, each null when it is the cut's.
+ follow: e.follow === false ? false : e.follow && typeof e.follow === "object" ? { on: null, dim: null, ease: null, ...(e.follow as Record<string, unknown>) } : null,
media: Object.fromEntries(
(e.media ?? []).map((m, i) => [
i,
@@ -142,6 +149,10 @@ export default function PostBench({
mute: m.mute === true ? true : null,
crop: Array.isArray(m.crop) ? m.crop : null,
push: m.push === true ? true : null,
+ // The censoring blur (post-censor.mjs), every key as it stands (null: cleared).
+ blur: m.blur
+ ? { on: m.blur.on === true, strength: m.blur.strength ?? null, boxes: m.blur.boxes?.length ? m.blur.boxes : null, label: m.blur.label === undefined ? null : m.blur.label }
+ : null,
},
]),
),
@@ -213,6 +224,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 +288,26 @@ 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);
+ }}
+ />
+ <PostFollowPanel entry={entry} plan={plan} render={render} s={s} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} />
<PostNarrationPanel
project={project}
entry={entry}
@@ -454,6 +490,61 @@ export default function PostBench({
</button>
))}
</div>
+ <div className="mt-2 space-y-1.5 text-[12px]" data-post-bench-censor={i}>
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={m.blur?.on === true}
+ onChange={(e) => setMedia(i, { blur: { ...(m.blur ?? {}), on: e.target.checked } })}
+ data-post-bench-blur={i}
+ />
+ censor it (blurred in the video; the file is untouched)
+ </label>
+ {m.blur?.on === true && (
+ <>
+ <div className="flex flex-wrap items-center gap-2">
+ strength
+ <input
+ type="range"
+ min={1}
+ max={10}
+ step={1}
+ value={m.blur.strength ?? 7}
+ onChange={(e) => setMedia(i, { blur: { ...m.blur!, strength: Number(e.target.value) === 7 ? undefined : Number(e.target.value) } })}
+ data-post-bench-blur-strength={i}
+ />
+ <span className="font-mono">{m.blur.strength ?? 7}</span>
+ label
+ <input
+ type="text"
+ value={m.blur.label === false ? "" : (m.blur.label ?? "")}
+ placeholder={m.blur.label === false ? "(none)" : "Censored"}
+ disabled={m.blur.label === false}
+ onChange={(e) => setMedia(i, { blur: { ...m.blur!, label: e.target.value.trim() ? e.target.value : undefined } })}
+ className="w-28 rounded border border-seam bg-ground px-1.5 py-0.5"
+ data-post-bench-blur-label={i}
+ />
+ <label className="flex items-center gap-1">
+ <input type="checkbox" checked={m.blur.label === false} onChange={(e) => setMedia(i, { blur: { ...m.blur!, label: e.target.checked ? false : undefined } })} />
+ no label
+ </label>
+ {!!m.blur.boxes?.length && (
+ <button type="button" className={btn} onClick={() => setMedia(i, { blur: { ...m.blur!, boxes: undefined } })} data-post-bench-blur-whole={i}>
+ Whole frame
+ </button>
+ )}
+ </div>
+ <BlurBoxPad
+ project={project}
+ media={m}
+ index={i}
+ at={timed ? (srcNow ?? m.start ?? 0) : 0}
+ boxes={m.blur.boxes ?? []}
+ onChange={(boxes) => setMedia(i, { blur: { ...m.blur!, boxes: boxes.length ? boxes : undefined } })}
+ />
+ </>
+ )}
+ </div>
{m.kind === "video" && m.audio !== false && (
<div className="mt-2 text-[12px]">
{m.words ? (
diff --git a/umtool/components/projects/PostFollowPanel.tsx b/umtool/components/projects/PostFollowPanel.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import { useMemo } from "react";
+import { FOLLOW_DEFAULTS, FOLLOW_LIMITS, cardScopes, followBlockAt, followKnobs } from "umtool-report-to-video/read-follow";
+import { cardWordsOf } from "umtool-report-to-video/word-zoom";
+import type { PostPlan } from "./review/PostItemPlayer";
+
+// ---------------------------------------------------------------------------
+// A POST's READ-FOLLOW ON THE BENCH (report-to-video/read-follow.mjs; knobs.md,
+// "Read-follow"): the BLOCK MAP -- each block of the card's words, which text
+// it is in, the part of the read that reads it and when (click: the playhead
+// there), the one being read marked -- and this post's knobs: follow on, off or
+// the cut's, the other blocks' dim, the ease. The knobs are the bench's draft
+// (its Save writes them, as hold and redact).
+// ---------------------------------------------------------------------------
+
+type Entry = Record<string, unknown> & { id: string };
+type Follow = false | { on?: boolean; dim?: number; ease?: number } | undefined;
+
+const SCOPE_NAME = (s: string) => (s === "post" ? "post" : s === "quoted" ? "quoted" : s.replace("parent:", "parent "));
+
+export default function PostFollowPanel({
+ entry, plan, render, s, setS, setEntry,
+}: {
+ entry: Entry;
+ plan: PostPlan;
+ render: Record<string, unknown>;
+ s: number;
+ setS: (s: number) => void;
+ setEntry: (f: (e: Entry) => Entry) => void;
+}) {
+ const follow = plan.follow ?? null;
+ const own = entry.follow as Follow;
+ const k = followKnobs(entry, render) as { on: boolean; dim: number; ease: number };
+ const cutOn = (followKnobs({}, render) as { on: boolean }).on;
+ const mode = own === false ? "off" : own && typeof own === "object" && own.on === true ? "on" : "auto";
+ const texts = useMemo(() => new Map(cardScopes(entry).map((sc: { scope: string; text: string }) => [sc.scope, cardWordsOf(sc.text)])), [entry]);
+ const cur = follow ? followBlockAt(follow, s) : null;
+ const setOwn = (next: Follow) =>
+ setEntry((e) => {
+ const out = { ...e };
+ if (next === undefined || (typeof next === "object" && !Object.keys(next).length)) delete out.follow;
+ else out.follow = next;
+ return out;
+ });
+ const knob = (key: "dim" | "ease", v: string) => {
+ const base = own && typeof own === "object" ? { ...own } : {};
+ if (v === "") delete base[key];
+ else base[key] = Number(v);
+ setOwn(base);
+ };
+ const read = follow ? follow.blocks.filter((b) => b.start !== null).length : 0;
+ return (
+ <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]" data-post-follow-panel="">
+ <div className="mb-2 flex flex-wrap items-center gap-2">
+ <h2 className="micro m-0">read-follow</h2>
+ <select
+ value={mode}
+ onChange={(e) => setOwn(e.target.value === "off" ? false : e.target.value === "on" ? { ...(own && typeof own === "object" ? own : {}), on: true } : own && typeof own === "object" ? (({ on: _on, ...rest }) => rest)(own) : undefined)}
+ data-post-follow-mode=""
+ aria-label="read-follow on this post"
+ >
+ <option value="auto">the cut's ({cutOn ? "on" : "off"})</option>
+ <option value="on">on</option>
+ <option value="off">off</option>
+ </select>
+ <label className="flex items-center gap-1">
+ dim
+ <input
+ type="number"
+ min={FOLLOW_LIMITS.dim[0]}
+ max={FOLLOW_LIMITS.dim[1]}
+ step={0.05}
+ className="w-16"
+ value={own && typeof own === "object" && typeof own.dim === "number" ? own.dim : ""}
+ placeholder={String(k.dim ?? FOLLOW_DEFAULTS.dim)}
+ onChange={(e) => knob("dim", e.target.value)}
+ data-post-follow-dim=""
+ />
+ </label>
+ <label className="flex items-center gap-1">
+ ease
+ <input
+ type="number"
+ min={FOLLOW_LIMITS.ease[0]}
+ max={FOLLOW_LIMITS.ease[1]}
+ step={0.05}
+ className="w-16"
+ value={own && typeof own === "object" && typeof own.ease === "number" ? own.ease : ""}
+ placeholder={String(k.ease ?? FOLLOW_DEFAULTS.ease)}
+ onChange={(e) => knob("ease", e.target.value)}
+ data-post-follow-ease=""
+ />
+ s
+ </label>
+ </div>
+ {!follow ? (
+ <p className="m-0 text-text-2">off: the card shows its words as they are, shrunk to fit.</p>
+ ) : (
+ <>
+ <p className="m-0 mb-1 text-text-2" data-post-follow-summary="">
+ {follow.blocks.length} block{follow.blocks.length === 1 ? "" : "s"}, {read} read
+ {follow.source === "take" ? " (the take's parts)" : follow.source === "script" ? " (the script's parts, timed by words)" : " (the reading rule)"}; the read ends at {follow.readEnd.toFixed(1)} s
+ </p>
+ <ol className="m-0 max-h-56 list-none space-y-0.5 overflow-auto p-0" data-post-follow-map="">
+ {follow.blocks.map((b) => {
+ const words = texts.get(b.scope) ?? [];
+ const head = words.slice(b.from, Math.min(b.to + 1, b.from + 8)).join(" ");
+ return (
+ <li key={b.k} data-post-follow-row={b.k} data-current={cur === b.k ? "1" : undefined} className={cur === b.k ? "rounded bg-white/10" : ""}>
+ <button
+ type="button"
+ disabled={b.start === null}
+ className="flex w-full gap-2 px-1 text-left disabled:opacity-60"
+ onClick={() => b.start !== null && setS(b.start)}
+ title={b.start === null ? "no part reads it: dimmed while the read runs" : `part ${b.part! + 1}`}
+ >
+ <span className="w-12 shrink-0 font-mono tabular-nums">{b.start === null ? "—" : `${b.start.toFixed(1)}s`}</span>
+ <span className="w-14 shrink-0 text-text-2">{SCOPE_NAME(b.scope)}</span>
+ <span className="min-w-0 truncate">
+ {head}
+ {b.to + 1 - b.from > 8 ? "…" : ""}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ol>
+ </>
+ )}
+ </section>
+ );
+}
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/RecordPage.tsx b/umtool/components/projects/RecordPage.tsx
@@ -10,6 +10,8 @@ import { draftScript, pickedTake, takeSourceOf } from "umtool-report-to-video/po
import { normalizeParts, partsFileOf } from "@/lib/report/postNarrationCli.mjs";
import { avatarEntryOf } from "umtool-report-to-video/post-avatars";
import type { ProjectRef } from "@/lib/project-types";
+import { projectRedaction } from "@/lib/report/postRedaction.mjs";
+import { termsFor } from "umtool-report-to-video/post-redact";
// THE RECORDING SESSION (operator, 3 Nov: "I need to do a dramatic reading of
// this starting tomorrow"): /projects/<p>/narration/record walks the cut's
@@ -29,6 +31,8 @@ export default async function RecordPage({ project, search = {} }: { project: Pr
const posts = ((Array.isArray(m.timeline) ? m.timeline : []) as Entry[]).filter((e) => e?.type === "post");
if (!posts.length) notFound();
const items: RecordItem[] = [];
+ // The words to leave out of the read (post-redact.mjs): marked on the teleprompter, never removed from the script.
+ const redaction = await projectRedaction(project.dir, m);
for (const [i, e] of posts.entries()) {
const takes = e.narration?.takes ?? [];
const picked = pickedTake(e) as (Take & { index: number }) | null;
@@ -49,6 +53,7 @@ export default async function RecordPage({ project, search = {} }: { project: Pr
placeholder: placeholder ? { file: placeholder.file, seconds: placeholder.seconds, parts: (parts ?? []).map((p) => ({ n: p.n, para: p.para ?? 0, text: p.text ?? "", start: p.start, seconds: p.seconds, ...(p.file ? { file: p.file } : {}) })) } : null,
media: (e.media ?? []).slice(0, 1).map((x) => ({ src: x.src, kind: x.kind }))[0] ?? null,
avatar: av ? String((av[1] as { src?: string }).src ?? "") || null : null,
+ skip: termsFor(e, redaction) as RecordItem["skip"],
});
}
const box = deckOn(render) ? deckGeometry(render).footage : { width: Number(render.width ?? 1920), height: Number(render.height ?? 1080) };
diff --git a/umtool/components/projects/RecordSession.tsx b/umtool/components/projects/RecordSession.tsx
@@ -1,10 +1,11 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { postBenchHref } from "@/lib/hrefs";
import { scriptParts } from "umtool-report-to-video/post-narration";
+import { redactText } from "umtool-report-to-video/post-redact";
import { MIC_KEY, ls, useMic } from "./useMic";
// ---------------------------------------------------------------------------
@@ -38,7 +39,28 @@ export type RecordItem = {
placeholder: { file: string; seconds: number; parts: Part[] } | null;
media: { src: string; kind: string } | null;
avatar: string | null;
+ /** Redacted terms (post-redact.mjs): marked on the teleprompter as words to leave out of the read. */
+ skip?: Array<{ term: string; wholeWord?: boolean }>;
};
+
+/** A part's words with each redacted term struck through: say everything but those. */
+function SkipMarked({ text, skip }: { text: string; skip?: RecordItem["skip"] }) {
+ const { spans } = redactText(text, skip ?? []) as { spans: Array<{ start: number; end: number }> };
+ if (!spans.length) return <>{text}</>;
+ const out: ReactNode[] = [];
+ let at = 0;
+ for (const sp of spans) {
+ out.push(text.slice(at, sp.start));
+ out.push(
+ <s key={sp.start} className="text-muted-2" title="redacted: leave this out of the read" data-record-skip="">
+ {text.slice(sp.start, sp.end)}
+ </s>,
+ );
+ at = sp.end;
+ }
+ out.push(text.slice(at));
+ return <>{out}</>;
+}
type Session = { count: number | null; parts: Record<string, { file: string; text: string; at: string }> };
const COUNT_KEY = "umtool.record.count-in";
@@ -339,7 +361,7 @@ export default function RecordSession({ project, items: initial, start, box }: {
data-record-prompt-kept={kept(p.n) ? "1" : undefined}
>
{parts.length > 1 && <span className="micro mr-2 align-middle">{p.n}/{parts.length}</span>}
- {p.text}
+ <SkipMarked text={p.text} skip={item.skip} />
{i === cur && (
<span className="mt-1 flex flex-wrap gap-1.5 text-[12px]">
{kept(p.n) && (
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -172,6 +172,8 @@ const PAUSE_KEY = "umtool.play.pauseWhileWriting";
/** "on": play the clips the walk rejected too (for re-review); absent or "off": skip them. */
// The key keeps its old name: a browser that chose "show" before rejections had reasons still has.
const SHOW_REJECTED_KEY = "umtool.play.showIncorrect";
+/** Play's "As published": post cards drawn with their redacted words as bars (post-redact.mjs). Per browser. */
+const AS_PUBLISHED_KEY = "umtool.play.asPublished";
/** The dailies' kinds of note: what it asks for, and its key (with Alt, in the composer). */
const ASKS: { id: CutAsk; label: string; key: string }[] = [
@@ -340,6 +342,15 @@ export default function PlayCut({
// unless asked for: the cut the operator means to ship does not hold them
// (umtool check blocks on a fact error and lists the rest). Remembered per browser.
const [showRejected, setShowRejected] = useState(false);
+ const [asPublished, setAsPublished] = useState(false);
+ useEffect(() => {
+ try {
+ if (window.localStorage.getItem(AS_PUBLISHED_KEY) === "on") setAsPublished(true);
+ } catch {
+ // A preference, not state.
+ }
+ }, []);
+ const hasPosts = useMemo(() => view.entries.some((e) => e.type === "post"), [view.entries]);
useEffect(() => {
try {
// The URL first (Back from the bench lands on the URL Play left), then this browser's choice.
@@ -837,6 +848,7 @@ export default function PlayCut({
s={Math.max(0, t - postNow.item.start)}
playing={ui.playing && !ui.waiting}
speed={rate}
+ published={asPublished}
/>
) : null;
// A post item that repeats an earlier one's attachment: its combo badge, beside the player.
@@ -1065,6 +1077,25 @@ export default function PlayCut({
))}
</select>
</label>
+ {hasPosts && (
+ <label className="inline-flex items-center gap-1.5 text-[11.5px] text-text-2" title="the post cards as the video draws them: every redacted word a blank bar (umtool posts redact)">
+ <input
+ type="checkbox"
+ data-play-as-published=""
+ checked={asPublished}
+ onChange={(ev) => {
+ const on = ev.target.checked;
+ setAsPublished(on);
+ try {
+ window.localStorage.setItem(AS_PUBLISHED_KEY, on ? "on" : "off");
+ } catch {
+ // A preference, not state.
+ }
+ }}
+ />
+ As published
+ </label>
+ )}
{item && (
<span className="min-w-0 truncate font-mono text-[11.5px] text-muted" data-play-readout="">
{ui.cur + 1}/{plan.items.length} · {item.id}
diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -1,8 +1,11 @@
"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 { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow";
+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"):
@@ -17,16 +20,77 @@ import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-v
// 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.
+//
+// READ-FOLLOW (read-follow.mjs) plays live on the plan's `follow`: the card
+// page carries the read's blocks and its flow; the pan's path is worked out
+// from the page's geometry once it is drawn, and each tick sets the state at
+// the item's second (followStateAt -- the build's frames are the same states).
// ---------------------------------------------------------------------------
+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 };
+/** The plan's read-follow (read-follow.mjs followSchedule). */
+export type FollowPlan = {
+ dim: number;
+ ease: number;
+ readEnd: number;
+ source: string;
+ blocks: Array<{ k: number; scope: string; from: number; to: number; part: number | null; start: number | null; end: number | null }>;
+};
+
export type PostPlan = {
reading: number;
total: number;
held: number;
narration?: NarrationSchedule;
+ follow?: FollowPlan;
steps: Array<{
kind: string;
at: number;
@@ -161,12 +225,16 @@ function MediaEl({
if (!run && !v.paused) v.pause();
}, [target, run, speed]);
const progress = inStep ? Math.min(1, Math.max(0, (s - step.at) / Math.max(0.1, step.seconds))) : 0;
+ // CENSORED (post-censor.mjs): the whole frame blurred, or its boxes -- as the render blurs it.
+ const blur = blurOf(m) as { strength: number; boxes: number[][]; label: string | null } | null;
+ const blurCss = blur ? `blur(${blurCqw(blur.strength)}cqw)` : undefined;
return (
<div
data-post-media={m.i}
data-post-media-kind={m.kind}
+ data-post-blurred={blur ? (blur.boxes.length ? "boxes" : "frame") : undefined}
className="absolute overflow-hidden"
- style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height) }}
+ style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height), containerType: blur ? "size" : undefined }}
>
{timed ? (
<video
@@ -179,7 +247,7 @@ function MediaEl({
playsInline
loop={step.loop}
muted={!(step.sound && run)}
- style={{ ...inner, objectFit: "fill" }}
+ style={{ ...inner, objectFit: "fill", filter: blur && !blur.boxes.length ? blurCss : undefined }}
/>
) : (
// eslint-disable-next-line @next/next/no-img-element
@@ -187,15 +255,28 @@ function MediaEl({
src={postFileUrl(project, String(m.src))}
alt=""
data-post-image={m.i}
- style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center" }}
+ style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center", filter: blur && !blur.boxes.length ? blurCss : undefined }}
/>
)}
+ {blur?.boxes.map((bx, j) => (
+ <div
+ key={j}
+ data-post-blur-box={j}
+ className="pointer-events-none absolute"
+ style={{ left: `${bx[0] * 100}%`, top: `${bx[1] * 100}%`, width: `${bx[2] * 100}%`, height: `${bx[3] * 100}%`, backdropFilter: blurCss, WebkitBackdropFilter: blurCss }}
+ />
+ ))}
+ {blur?.label && (
+ <span data-post-blur-label="" className="pointer-events-none absolute left-[2%] top-[2%] rounded-[3px] bg-black/70 px-[1.2cqw] py-[0.4cqw] text-[2.4cqw] leading-none text-white">
+ {blur.label}
+ </span>
+ )}
</div>
);
}
export default function PostItemPlayer({
- project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1,
+ project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false,
}: {
project: string;
take?: string | null;
@@ -209,6 +290,8 @@ export default function PostItemPlayer({
cardKey?: string | null;
/** The clock's speed (Play's 0.75-3x): the attachments and the voice play at it, not seeked along. */
speed?: number;
+ /** AS PUBLISHED (Play's toggle): the card with its redacted words as bars, as the build draws it. */
+ published?: boolean;
}) {
const wrap = useRef<HTMLDivElement | null>(null);
const [scale, setScale] = useState(0);
@@ -246,7 +329,7 @@ export default function PostItemPlayer({
}, [box.width]);
const layout = useMemo(() => postLayout(entry, box), [entry, box]);
const pageUrl = (phase: "read" | "media") =>
- `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}`;
+ `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}${published ? "&published=1" : ""}`;
const reading = s < plan.reading || !plan.steps.length;
const current = stepAt(plan, s);
// Beside the card, the first attachment is up (its first frame) while the words are read.
@@ -271,6 +354,84 @@ 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]);
+ // ---- read-follow, live: the page's geometry measured once it is drawn, the path from it ----
+ const follow = plan.follow ?? null;
+ const [followGeo, setFollowGeo] = useState<ReturnType<typeof measureFollow>>(null);
+ const followRoute = useMemo(() => (follow && followGeo ? followPath(follow, followGeo) : null), [follow, followGeo]);
+ 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;
+ // Laid out untransformed (no zoom), the follow geometry first; a zoom's word is measured as the card is at its peak.
+ if (card) for (const k of Array.from(card.children) as HTMLElement[]) k.style.transform = "";
+ const geo = follow && doc.querySelector("[data-post-flow]") ? measureFollow(doc) : null;
+ setFollowGeo(geo);
+ const route = follow && geo ? followPath(follow, geo) : 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);
+ if (follow) applyFollowState(followStateAt(follow, route, zoomSpan(fx0, t.t).t1), doc);
+ 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, follow]);
+ 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 followNow = useMemo(() => (follow ? followStateAt(follow, followRoute, s) : null), [follow, followRoute, s]);
+ useEffect(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (doc && follow && doc.querySelector("[data-post-follow]")) applyFollowState(followNow, doc);
+ }, [follow, followNow, followGeo]);
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 (
@@ -285,6 +446,12 @@ 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}
+ data-post-follow-block={followNow?.current !== null && followNow?.current !== undefined ? String(followNow.current) : undefined}
+ data-post-follow-offset={followNow && followRoute?.segments.length ? String(Math.round(followNow.offset)) : undefined}
+ data-post-follow-pans={followRoute ? String(followRoute.segments.length) : undefined}
className="pointer-events-none absolute inset-0 overflow-hidden"
>
{mix && voiceTake && (
@@ -295,6 +462,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
@@ -82,10 +82,12 @@ Inbox cannot disagree about what is wrong with one.
| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) |
| `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] [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 |
-| `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 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] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [--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. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's `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` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`). 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**) |
| `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) |
| `posts repeats <project> [--match id\|file\|audio] [--json]` | the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `timeline remove` + `insert post:<channel>/<postId>` that makes it again from the archive (the entry's own edits not kept). Reads only |
| `posts combo <project> [on=on\|off] [label=L] [position=top-right\|top-left\|bottom-right\|bottom-left\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\|hit\|coin] [minCount=2-20] [match=id\|file\|audio] [--json]` · `posts combo <project> <item> off\|on\|auto\|label=…\|position=…\|color=…\|scale=…\|sfx=… [--json]` | the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -652,6 +652,7 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused
| `media[i].mute` — `true`: the video plays silent | post bench, **its sound** | `media.0.mute=on` (`=off`) | same |
| `media[i].crop` — `[x, y, w, h]`, fractions of the picture: what of it is shown | post bench, **crop** (none, centre 80%, top half, bottom half) | `media.0.crop=0,0.1,1,0.8` (`=off`) | same |
| `media[i].push` — an image's slow push-in (6% over its span) | post bench, **slow push-in** | `media.0.push=on` | same |
+| `media[i].blur` — the attachment CENSORED (`post-censor.mjs`): `{on, strength?: 1–10 (7), boxes?: [[x, y, w, h], …], label?: "…" \| false}`. The render blurs it for real (ffmpeg `gblur`, its sigma grown with the strength and the picture's width) -- the whole frame, or only its boxes (fractions of the picture as shown, after its crop, held still over the clip) -- and draws the label ("Censored"; `false`: none) at its corner. The file is never touched; `on: false` keeps the settings. A channel's `posts-markup.json` may censor it for every project (`censor`, below); the item's own `blur` wins | post bench, **censor it**, **strength**, **label** / **no label**, the boxes drawn on a still frame (drag; × removes; **Whole frame**); Play and the bench preview it | `media.0.blur=on` · `media.0.blur.strength=5` · `media.0.blur.label="Censored"` (`=off`: none) · `media.0.blur.boxes=0.2,0.3,0.4,0.4;…` (`=off`) · `media.0.blur=off` | same, `patch: {media: {"0": {blur: {on, strength, boxes, label}}}}` (merged; a null key cleared) |
| `media[i].words` — a video's transcript (`{cues: [{start, end, text}]}` beside it), its words shown under it in Play and the render | post bench, **Transcribe its words (the editor)**: the editor's `transcribe` op on the file (a job on a local worker), set when it is done | `pnpm ops transcribe --json '{"path": "<project>/posts-media/…_1.mp4", "words": true, "out": "<project>/posts-media/…_1.words.json"}'`, then set `words` by the bench | `POST {op: "transcribe", id, media}` → `{jobId}` · `GET ?project&id&media&job=` |
| | In umtool | From a terminal | Route |
@@ -693,6 +694,62 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n
none, approved) and links the next post to record; **N** / **P** walk the cut's posts, **Space** plays the item as the
render will (the take over the muffled attachment).
+## Redacted words (blanked from what is published)
+
+A word or a phrase -- a private person's name -- left out of everything a cut PUBLISHES, never out of the data
+(`report-to-video/post-redact.mjs`). The archive's rows, the manifest's snapshot of each post and every narration
+script keep their words; the redaction is applied where public output is made: the **rendered card** draws each
+match as a solid bar of the word's width (no letters in the page or the frame, not a blur that can be undone) in the
+post's words, the posts it answers and quotes, a paraphrase, an author's name and handle and the repost line; a
+**synthesized read** (`--take`, the bench's re-take) is sent to the editor with the match left out, its spaces and
+dangling punctuation tidied; a post's **chapter line** and a video attachment's **burnt-in captions** drop it.
+umtool's own views (the bench, Play, the recording page) show the words; Play's **As published** shows the bars,
+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). 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 |
+|---|---|---|---|
+| `render.posts.redact` — the project's list, `[{term, wholeWord?, note?}]` (at most 200; one writer, `updatePostRedact`, refused in the build's words) | Play the cut, **As published** (the cards as the video draws them) | `umtool posts redact <p> ls` · `add "<term>" [--substring] [--note "…"]` · `remove <n>` (n as `ls` numbers them) | `GET /api/report/post-item?…&published=1` (the card's page, as published) |
+| 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 |
+
+## Read-follow (the block being read lit, the card panned to it)
+
+A post item's card follows its read ([report-video.md](report-video.md#read-follow): the blocks, the schedule, the
+pan, the render). On by default; the cut's knobs ride on `render.postNarration` (`updatePostNarrationRender`), one
+post's on the item (`updatePostItem`), each refused in the build's words (`followKnobErrors`,
+`report-to-video/read-follow.mjs`). Its bench is the post bench's **read-follow** block; Play the cut lights and pans
+the card live on the same states the build shoots.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| `render.postNarration.follow.on` — the cut's read-follow on (default) or off | — | `umtool posts narrate <p> --cut follow=off` (`follow=on`, `follow=default`) | — |
+| `render.postNarration.follow.dim` — the other blocks' opacity, 0.2–1 (default 0.65) · `.ease` — the light moving from one block to the next, 0–2 s (default 0.25) | — | `umtool posts narrate <p> --cut follow.dim=0.6 follow.ease=0.3` (`default` clears one) | — |
+| `follow` on a post item — `false` (off on this post), or `{on, dim, ease}` over the cut's | post bench, **read-follow**: the cut's / on / off, **dim**, **ease** (saved with the bench's other knobs) | `umtool posts set-item <p> <item> follow=off` (`follow=on`, `follow=auto`: the cut's) · `follow.dim=0.7 follow.ease=0.4` | `POST /api/report/post-item {project, op: "set", id, patch: {follow}, token}` (an object merges; `null` clears) |
+| the block map — each block of the card's words, its text, the part that reads it, its start on the item's clock | post bench, **read-follow**: the map's rows (click one: the playhead at its start; the one being read is marked) | — (`postItemPlan(entry, render).follow`) | — |
+
## The combo counter
A post item that plays an attachment an earlier post item of the cut already played gets a fighting-game badge,
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -659,6 +659,109 @@ 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)).
+
+### Read-follow
+
+A post item's card FOLLOWS ITS READ (`report-to-video/read-follow.mjs`; operator, 3 Nov:
+"'I'm someone who has never watched Ember' goes on beyond the text but the text doesn't
+scroll? That needs to be an effect, something like highlight the current paragraph and
+panning down as needed" — and "a subtle effect of highlighting the block currently being
+read by making it brighter"): the card's words are laid out in BLOCKS that match the read's
+parts, the block being read is drawn at full strength and the others dimmed a little, and
+a card whose words are taller than their box pans so the block being read stays in view.
+It is on by default, for narrated and un-narrated posts alike:
+
+```jsonc
+"render": { "postNarration": { "follow": { "on": true, "dim": 0.65, "ease": 0.25 } } }, // the cut's
+"follow": false // one post's: off; or { on?, dim?, ease? } over the cut's
+```
+
+**The blocks** (from the entry alone): the read's parts — the picked take's `parts` (its
+paragraphs, or a long paragraph's ≤60-word sentence runs; a take that reads the post it
+answers first numbers that piece's paragraphs 0…, the post's 100…), else the script's
+parts (scriptParts), else, un-narrated, the card's own paragraphs and sentence runs. Each
+part is matched BY ITS WORDS to the run of the card's words it reads, in whichever of the
+card's texts it is (a parent's, the post's, the quoted post's): the script is the post as a
+voice says it ("this slash that", a shout lower-cased), so the match is a fitting alignment
+of normalized words, in order — never by index. Words no part reads join the block before
+them up to a paragraph break; a paragraph no part reads (a bare link, a quoted post that is
+not read aloud) is a block that is never lit.
+
+**When**: a block starts at its part's start in the take on the item's clock — lead +
+start ÷ the read's `rate` (partStartOnItem); a take without parts shares the read's seconds
+by words; un-narrated, the reading rule's seconds (each context post's context read, the
+post's reading time shared by words; a `hold` longer than the reading spreads it, less a
+second). The block being read rises to full over `ease` (centred on its start) while the
+one before falls back to `dim`; before the first block's start the first is lit, and after
+the read's end every block rises back to full. A post with one block read is never dimmed.
+
+**The pan**: following, the post's words never shrink below 28 px of a 1080 frame to fit
+(they used to shrink to 18 and cut the rest); when they are still taller than their box,
+they sit in a window that pans. A block about to be read that is not in view pans
+(0.7 s, eased, starting 0.4 s before its read) to sit a margin (a tenth of the window)
+below the window's top; a block taller than the window pans on through it as it is read.
+A short card never moves. A fading edge at the window's foot (and top) says there is more.
+
+**The render**: the card page wraps each block (`data-post-block="<k>"`) and puts the
+post's words in a flow (`data-post-flow`); the build measures the page (the window, the
+flow, each block's top and bottom), works out the pan's path, and for every frame the
+state at its second (followStateAt — pure, seek-safe); each DISTINCT state is applied to
+the page and the card's region shot once, and a concat list holds each shot for its frames,
+laid over the card before the attachments and the word zooms (which are shot as the card is
+at their peak). **Play** sets the same states on its card page each tick; the post bench's
+**read-follow** block shows the block map — each block, its text, the part that reads it and
+when (click: the playhead there), the one being read marked — and the post's knobs
+([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)).
+
### The combo counter
When a post item's attachment is one an EARLIER post item of the cut already played —
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-items.spec.ts b/umtool/e2e/post-items.spec.ts
@@ -104,6 +104,50 @@ test("Play plays a post item: its card, the private parent blurred, its video pl
await expect(root(page)).toHaveAttribute("data-play-item", "p-vid");
});
+test("a redacted term: Play shows the words; As published draws blank bars and the term is nowhere in the card's DOM", async ({ page }) => {
+ // A made-up term on the fixture's words (post-redact.mjs; knobs.md, "Redacted words").
+ umtool(["posts", "redact", PROJECT, "add", "here is"]);
+ expect(umtool(["posts", "redact", PROJECT, "ls"])).toContain("1. here is");
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-vid" }));
+ await page.evaluate(() => window.localStorage.removeItem("umtool.play.asPublished"));
+ await page.reload();
+ await expect(root(page)).toHaveAttribute("data-play-item", "p-vid");
+ const card = page.frameLocator('[data-post-card-frame="read"]');
+ // umtool's own view: the words as posted.
+ await expect(card.locator("[data-post-words]")).toContainText("Yes, and here is the video.");
+ await expect(card.locator("[data-post-blanked]")).toHaveCount(0);
+ await page.locator("[data-play-as-published]").check();
+ // A bar per word of the phrase, each in its own word's slot (a word zoom's indices hold).
+ await expect(card.locator("[data-post-blanked]")).toHaveCount(2);
+ await expect(card.locator("[data-post-words]")).toContainText("Yes, and");
+ await expect(card.locator("[data-post-words]")).toContainText("the video.");
+ const dom = await card.locator("html").evaluate((el) => el.outerHTML);
+ expect(dom.toLowerCase()).not.toContain("here is");
+ expect(await card.locator("[data-post-blanked]").evaluateAll((els) => els.map((el) => el.textContent).join(""))).toBe("");
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-as-published.png") });
+ // The snapshot is never rewritten.
+ expect(JSON.stringify(timeline())).toContain("here is the video");
+});
+
+test("a censored attachment: set-item blurs it, Play previews the blur and its label, the bench toggles it off and saves", async ({ page }) => {
+ umtool(["posts", "set-item", PROJECT, "p-vid", "media.0.blur=on"]);
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-vid" }));
+ await expect(page.locator('[data-post-media="0"]')).toHaveAttribute("data-post-blurred", "frame");
+ await expect(page.locator('[data-post-media="0"] [data-post-blur-label]')).toHaveText("Censored");
+ expect(await page.locator('[data-post-video="0"]').evaluate((v) => getComputedStyle(v).filter)).toMatch(/blur\(/);
+ await page.goto(urls.postBenchHref(PROJECT, "p-vid"));
+ await expect(page.locator('[data-post-bench-blur="0"]')).toBeChecked();
+ await expect(page.locator('[data-post-bench-blur-pad="0"]')).toBeVisible();
+ await page.locator('[data-post-bench-blur="0"]').uncheck();
+ await page.locator("[data-post-bench-save]").click();
+ await expect(page.locator("[data-post-bench-status]")).toBeVisible();
+ const vid = timeline().find((e) => e.id === "p-vid") as Entry & { media: Array<{ blur?: { on: boolean }; src: string }> };
+ expect(vid.media[0].blur?.on).toBe(false);
+ expect(vid.media[0].src).toMatch(/\.mp4$/);
+});
+
test("the post bench trims the video attachment and saves it; the cut's seconds follow", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1000 });
await page.goto(urls.postBenchHref(PROJECT, "p-vid"));
diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts
@@ -279,6 +279,109 @@ 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("READ-FOLLOW (operator, 3 Nov: \"highlight the current paragraph and panning down as needed\"): a long post read part by part -- the second block brightens at its part's start, the others dim, and the card pans so a late block is in view; the bench shows the block map", async ({ page }) => {
+ // p-13 made long: ten paragraphs, a take read paragraph by paragraph (a part every 2 s of the take).
+ const para = (i: number) => `Paragraph ${i + 1} begins here and it goes on for a while, ${"saying the same kind of thing again and again, ".repeat(3)}until it ends with mark ${i + 1}.`;
+ const paras = Array.from({ length: 10 }, (_, i) => para(i));
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ const e = m.timeline.find((x: { id: string }) => x.id === "p-13");
+ e.text = paras.join("\n\n");
+ e.narration = {
+ script: e.text,
+ takes: [{ file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 20, script: e.text, parts: paras.map((text, i) => ({ n: i + 1, para: i, text, start: i * 2, seconds: 1.8 })) }],
+ pick: 0,
+ };
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+ await page.setViewportSize({ width: 1500, height: 1100 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-13"));
+ const panel = page.locator("[data-post-follow-panel]");
+ await expect(panel.locator("[data-post-follow-summary]")).toHaveText(/10 blocks, 10 read \(the take's parts\)/);
+ await expect(panel.locator("[data-post-follow-row]")).toHaveCount(10);
+ const player = page.locator('[data-post-play="p-13"]');
+ const frame = page.frameLocator('[data-post-card-frame="read"]');
+ await expect(frame.locator("body")).toHaveAttribute("data-post-follow", "10", { timeout: 15_000 });
+ const op = (k: number) => frame.locator(`[data-post-block="${k}"]`).evaluate((el) => (el as HTMLElement).style.opacity);
+ const scrub = page.locator("[data-post-bench-scrub]");
+ // Before the second part: the first block lit, the second dimmed.
+ await scrub.fill("1");
+ await expect(player).toHaveAttribute("data-post-follow-block", "0");
+ await expect.poll(() => op(0)).toBe("");
+ await expect.poll(() => op(1)).toBe("0.65");
+ // The second part starts at lead 0.4 + 2 s: past its ease (0.125 s) it is lit and the first is dimmed.
+ await scrub.fill("2.6");
+ await expect(player).toHaveAttribute("data-post-follow-block", "1");
+ await expect.poll(() => op(1)).toBe("");
+ await expect.poll(() => op(0)).toBe("0.65");
+ await expect(panel.locator('[data-post-follow-row="1"]')).toHaveAttribute("data-current", "1");
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-follow-second-block.png") });
+ // The words are taller than the card: a late block is panned into view.
+ await expect(player).toHaveAttribute("data-post-follow-pans", /^[1-9]/);
+ await scrub.fill("17.2");
+ await expect(player).toHaveAttribute("data-post-follow-block", "8");
+ await expect.poll(async () => Number(await player.getAttribute("data-post-follow-offset"))).toBeGreaterThan(0);
+ const view = await frame.locator("[data-post-words]").evaluate((w) => {
+ const r = w.getBoundingClientRect();
+ const b = (w.querySelector('[data-post-block="8"]') as HTMLElement).getBoundingClientRect();
+ return { top: r.top, bottom: r.bottom, bTop: b.top, bBottom: b.bottom, flow: (w.querySelector("[data-post-flow]") as HTMLElement).style.transform };
+ });
+ expect(view.flow).toMatch(/translateY\(-\d/);
+ expect(view.bTop).toBeGreaterThanOrEqual(view.top - 1);
+ expect(view.bBottom).toBeLessThanOrEqual(view.bottom + 1);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-follow-panned.png") });
+ // A row of the map puts the playhead at its block's start.
+ await panel.locator('[data-post-follow-row="3"] button').click();
+ await expect(page.locator("[data-post-bench-clock]")).toHaveText(/^6\.4 \//);
+ // Off on this post: the card shows its words as they are (no blocks lit, no pan).
+ await panel.locator("[data-post-follow-mode]").selectOption("off");
+ await expect(panel).toContainText("off: the card shows its words as they are");
+});
+
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
@@ -60,6 +60,7 @@ import { validateNarration } from "umtool-report-to-video/narration";
import { validatePostItem, validatePostItems } from "umtool-report-to-video/post-item";
import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umtool-report-to-video/post-avatars";
import { POST_NARRATION_DEFAULTS, validatePostNarrationRender } from "umtool-report-to-video/post-narration";
+import { termWords, validatePostsRender } from "umtool-report-to-video/post-redact";
import { parseMuteFrom } from "./playback.mjs";
import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs";
import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources";
@@ -2351,16 +2352,16 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i
}
/** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */
-export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact"]);
-/** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript. */
-export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words"]);
+export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact", "follow"]);
+/** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */
+export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur"]);
/** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */
export const POST_CONTEXT_KNOBS = Object.freeze(["paraphrase"]);
/**
* SET A POST ITEM's KNOBS (the post bench, `umtool posts set-item`): `patch`
- * is `{ hold?, mediaLayout?, redact?, media?: { <i>: { start?, end?, mute?,
- * crop?, push?, words? } }, quoted?: { paraphrase? }, parents?: { <i>:
+ * is `{ hold?, mediaLayout?, redact?, follow?: false | { on?, dim?, ease? }, media?: { <i>: { start?, end?, mute?,
+ * crop?, push?, words?, blur? } }, quoted?: { paraphrase? }, parents?: { <i>:
* { paraphrase? } } }`; a null clears a knob (the default again), and so
* does an empty paraphrase (the context's own words again; its `text` is
* never touched). One structural write, refused in the build's words
@@ -2384,7 +2385,19 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
if (v === null || v === undefined) delete o[k];
else o[k] = typeof v === "number" ? round2(v) : v;
};
- for (const k of POST_ITEM_KNOBS) if (k in patch) set(e, k, patch[k]);
+ for (const k of POST_ITEM_KNOBS) {
+ if (!(k in patch)) continue;
+ // Its read-follow (read-follow.mjs): false is off; an object's knobs merge into the one it has (null: the default).
+ if (k === "follow" && isObj(patch.follow)) {
+ const f = isObj(e.follow) ? e.follow : {};
+ for (const [fk, fv] of Object.entries(patch.follow)) {
+ if (fv === null || fv === undefined) delete f[fk];
+ else f[fk] = typeof fv === "number" ? round2(fv) : fv;
+ }
+ if (Object.keys(f).length) e.follow = f;
+ else delete e.follow;
+ } else set(e, k, patch[k]);
+ }
if (isObj(patch.media)) {
const media = Array.isArray(e.media) ? e.media : [];
for (const [key, mp] of Object.entries(patch.media)) {
@@ -2395,7 +2408,17 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
for (const k of POST_MEDIA_KNOBS) {
if (!(k in mp)) continue;
if (k === "crop" && Array.isArray(mp.crop)) media[n].crop = mp.crop.map((v) => Math.round(Number(v) * 10000) / 10000);
- else set(media[n], k, mp[k]);
+ else if (k === "blur" && isObj(mp.blur)) {
+ // The censoring blur (post-censor.mjs) MERGES: each key set, a null one cleared; nothing left, none.
+ const b = isObj(media[n].blur) ? { ...media[n].blur } : {};
+ for (const [bk, bv] of Object.entries(mp.blur)) {
+ if (bv === null || bv === undefined) delete b[bk];
+ else if (bk === "boxes" && Array.isArray(bv)) b.boxes = bv.map((box) => (Array.isArray(box) ? box.map((v) => Math.round(Number(v) * 10000) / 10000) : box));
+ else b[bk] = bv;
+ }
+ if (Object.keys(b).length) media[n].blur = b;
+ else delete media[n].blur;
+ } else set(media[n], k, mp[k]);
}
// A trim back to the whole file is no trim.
if (media[n].start === 0) delete media[n].start;
@@ -2588,7 +2611,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: [] };
@@ -2603,6 +2626,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}`);
@@ -2624,6 +2655,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.
@@ -2727,7 +2818,7 @@ export async function setPostItemsContext(dir, patches, { token = null } = {}) {
}
/** The cut's mix knobs a write may set (`render.postNarration`). */
-export const POST_NARRATION_RENDER_KNOBS = Object.freeze(Object.keys(POST_NARRATION_DEFAULTS).filter((k) => k !== "attach"));
+export const POST_NARRATION_RENDER_KNOBS = Object.freeze([...Object.keys(POST_NARRATION_DEFAULTS).filter((k) => k !== "attach"), "follow"]);
/**
* SET THE CUT's NARRATION MIX (`render.postNarration`; `umtool posts narrate
@@ -2746,7 +2837,16 @@ export async function updatePostNarrationRender(dir, patch, { token = null } = {
const r = isObj(m.render.postNarration) ? m.render.postNarration : {};
for (const [k, v] of Object.entries(patch)) {
if (v === null || v === undefined) delete r[k];
- else r[k] = typeof v === "number" ? round2(v) : v;
+ else if (k === "follow" && isObj(v)) {
+ // The read-follow's knobs merge ({ on, dim, ease }; a null one back to its default).
+ const f = isObj(r.follow) ? r.follow : {};
+ for (const [fk, fv] of Object.entries(v)) {
+ if (fv === null || fv === undefined) delete f[fk];
+ else f[fk] = typeof fv === "number" ? round2(fv) : fv;
+ }
+ if (Object.keys(f).length) r.follow = f;
+ else delete r.follow;
+ } else r[k] = typeof v === "number" ? round2(v) : v;
}
if (Object.keys(r).length) m.render.postNarration = r;
else delete m.render.postNarration;
@@ -2756,6 +2856,45 @@ export async function updatePostNarrationRender(dir, patch, { token = null } = {
});
}
+// ---- the redaction list (post-redact.mjs; `umtool posts redact`) ---------
+
+/**
+ * CHANGE THE PROJECT's REDACTION LIST (`render.posts.redact`): `{ add: {term,
+ * wholeWord?, note?} }` appends a term (one already there, the same words
+ * and the same wholeWord, is refused), `{ remove: <index> }` takes one out.
+ * The words of the posts are never touched: the list is applied where a
+ * public output is made. Validated with the build's check.
+ *
+ * @param {string} dir
+ * @param {{ add?: {term: string, wholeWord?: boolean, note?: string}, remove?: number }} change
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updatePostRedact(dir, change, { token = null } = {}) {
+ if (!isObj(change) || (change.add === undefined) === (change.remove === undefined)) throw new Error("say add or remove");
+ return structural(dir, "post-redact", token, (m) => {
+ if (!isObj(m.render)) m.render = {};
+ const posts = isObj(m.render.posts) ? m.render.posts : {};
+ const list = Array.isArray(posts.redact) ? [...posts.redact] : [];
+ if (change.add !== undefined) {
+ const t = change.add;
+ const key = (x) => `${termWords(x?.term).join(" ").toLowerCase()}|${x?.wholeWord !== false}`;
+ if (list.some((x) => key(x) === key(t))) throw new Error("that term is already on the list");
+ list.push({ term: String(t?.term ?? "").trim(), ...(t?.wholeWord === false ? { wholeWord: false } : {}), ...(typeof t?.note === "string" && t.note ? { note: t.note } : {}) });
+ } else {
+ const i = change.remove;
+ if (!Number.isInteger(i) || i < 0 || i >= list.length) throw new Error(`no term ${typeof i === "number" ? i + 1 : i} on the list (it holds ${list.length})`);
+ list.splice(i, 1);
+ }
+ if (list.length) posts.redact = list;
+ else delete posts.redact;
+ if (Object.keys(posts).length) m.render.posts = posts;
+ else delete m.render.posts;
+ const errors = validatePostsRender(m.render);
+ if (errors.length) throw new StructureRefused(errors);
+ return { redact: list };
+ });
+}
+
// ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) -----------
/**
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";
@@ -25,6 +26,8 @@ import {
NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf,
} from "umtool-report-to-video/post-narration";
import { postItemPlan } from "umtool-report-to-video/post-item";
+import { spokenWithout, termsFor } from "umtool-report-to-video/post-redact";
+import { projectRedaction } from "./postRedaction.mjs";
import { readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { manifestToken, updatePostNarration, updatePostNarrationRender, updatePostNarrations } from "./manifest.mjs";
@@ -40,7 +43,7 @@ export const NARRATE_USAGE = [
" [--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=… rate=…] [--json]",
" umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]",
- " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… engine=… voice=…",
+ " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… engine=… voice=… follow=on|off follow.dim=… follow.ease=…",
" A NARRATED POST ITEM: its script read by a stock synthetic voice, its attachment playing under the read (muffled,",
" then clean). Takes are files of the project (narration/posts/<postId>/take-<n>.<engine>-<voice>.wav) the EDITOR",
" writes (`pnpm ops tts`, a job on its tts queue; ARCHILYZER_EDITOR_URL + WORKER_TOKEN) -- umtool never synthesizes.",
@@ -55,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 {}
@@ -221,13 +227,16 @@ export function mixPatchOf(pairs, { cut = false } = {}) {
else if (k === "short") out.short = clear ? null : v;
else if (k === "attach" && !cut) out.attach = clear ? null : v;
else if ((k === "engine" || k === "voice") && cut) out[k] = clear ? null : raw;
+ // The cut's read-follow (read-follow.mjs): follow=on|off, follow.dim=<0.2-1>, follow.ease=<s>.
+ else if (k === "follow" && cut) out.follow = { ...(out.follow ?? {}), on: clear ? null : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("follow= takes on or off"); })() };
+ else if ((k === "follow.dim" || k === "follow.ease") && cut) out.follow = { ...(out.follow ?? {}), [k.slice(7)]: clear ? null : num() };
else if (k === "fit" && !cut) {
// fit=read[:linger]: the item ends `linger` after the words (posts fit picks the clip's best part for it).
const m = /^read(?::([\d.]+))?$/.exec(v);
if (!m) throw new NarrateError("fit= takes read or read:<linger seconds>");
out.linger = m[1] !== undefined ? Number(m[1]) : null;
out.clip = null;
- } else throw new NarrateError(`${pair}: not a narration knob (lead, tail, ramp, end, wet, lowpass, duck, short, ${cut ? "linger, clip, lufs, rate, engine, voice" : "linger, clip, attach, lufs, rate, fit"})`);
+ } else throw new NarrateError(`${pair}: not a narration knob (lead, tail, ramp, end, wet, lowpass, duck, short, ${cut ? "linger, clip, lufs, rate, engine, voice, follow, follow.dim, follow.ease" : "linger, clip, attach, lufs, rate, fit"})`);
}
if (!Object.keys(out).length) throw new NarrateError("nothing to set");
return out;
@@ -238,7 +247,7 @@ export function mixPatchOf(pairs, { cut = false } = {}) {
* the project, measured, appended (and picked) through the writer. Returns
* the take and the write's result.
*/
-export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null } = {}) {
+export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null, redaction = undefined } = {}) {
const k = postNarrationKnobs(e, render);
const words = String(script ?? e.narration?.script ?? "").trim();
if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`);
@@ -253,7 +262,9 @@ export async function makeTake(project, e, { script = null, note = null, engine
const rel = takeFileOf(pid, n, eng, vox);
const out = path.join(project.dir, ...rel.split("/"));
const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts;
- const body = { text: words, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) };
+ // What the voice SAYS: the script with every redacted term left out (post-redact.mjs) -- the script itself is kept as written.
+ const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {});
+ const body = { text: spokenWithout(words, termsFor(e, red)), engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) };
const { jobId, result } = await askTts(body, { ...(editor ? { editor } : {}), emit });
if (!(await stat(out).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there (its result names ${result?.wav ?? "no file"})`);
const m = await measureTake(out);
@@ -390,6 +401,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/postRedaction.mjs b/umtool/lib/report/postRedaction.mjs
@@ -0,0 +1,15 @@
+// A PROJECT's REDACTION (umtool-report-to-video/post-redact.mjs): the corpus's
+// terms, its channels' post markup and the project's own `render.posts.redact`,
+// read from the channels tree the project's clip bench reads. What a take's
+// synthesized read, Play's "As published" and the post item route blank.
+import { readPostRedaction } from "umtool-report-to-video/post-redact-files";
+import { channelsDirFor, hasShadowChannels } from "../projects/report.mjs";
+
+/**
+ * @param {string} dir the project's folder
+ * @param {Record<string, any>} manifest
+ */
+export async function projectRedaction(dir, manifest) {
+ const channelsDir = channelsDirFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) });
+ return readPostRedaction(channelsDir, manifest);
+}
diff --git a/umtool/lib/report/postRedaction.test.mjs b/umtool/lib/report/postRedaction.test.mjs
@@ -0,0 +1,108 @@
+// The redaction list's writer and CLI (`umtool posts redact`), the corpus's
+// files read beside it (post-redact-files.mjs), and a take's synthesized read
+// with the terms left out while its script is kept. Made-up terms only.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+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 { makeTake } from "./postNarrationCli.mjs";
+import { projectRedaction } from "./postRedaction.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-redact-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const REPORTS = path.join(ROOT, "reports");
+const CH = path.join(ROOT, "channels");
+const wav = (f, secs) => execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `sine=f=220:d=${secs}`, "-ar", "48000", "-ac", "1", f]);
+
+const item = (id, o = {}) => ({
+ type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z",
+ text: `post ${id}`, ...o,
+});
+async function project(name, timeline, render = {}) {
+ 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, provenance: { siteOrigin: "", channelSlug: "subj-x", channelsDir: CH },
+ render: { width: 1920, height: 1080, fps: 30, ...render }, 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 redact: add, ls (numbered, as remove takes them), remove -- the posts' words untouched", async () => {
+ const p = await project("r", [item("1", { text: "I am Quentin Example" })]);
+ let r = await cli(["redact", "r", "add", "Quentin Example", "--note", "a made-up name"]);
+ assert.equal(r.code, 0, r.err);
+ r = await cli(["redact", "r", "add", "Exam", "--substring"]);
+ assert.equal(r.code, 0, r.err);
+ const m = await manifest(p);
+ assert.deepEqual(m.render.posts.redact, [{ term: "Quentin Example", note: "a made-up name" }, { term: "Exam", wholeWord: false }]);
+ assert.equal(m.timeline[0].text, "I am Quentin Example", "the snapshot is never rewritten");
+ r = await cli(["redact", "r", "ls"]);
+ assert.match(r.out, /r: 2 term\(s\) of its own; 0 from the corpus, 0 post\(s\) marked up/);
+ assert.match(r.out, /1\. Quentin Example {2}-- a made-up name/);
+ assert.match(r.out, /2\. Exam {2}\(inside words too\)/);
+ // The same term twice is refused.
+ r = await cli(["redact", "r", "add", "quentin example"]);
+ assert.equal(r.code, 1);
+ r = await cli(["redact", "r", "remove", "1"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual((await manifest(p)).render.posts.redact, [{ term: "Exam", wholeWord: false }]);
+ assert.equal((await cli(["redact", "r", "remove", "5"])).code, 1);
+ await cli(["redact", "r", "remove", "1"]);
+ assert.equal((await manifest(p)).render.posts, undefined, "an empty list leaves no key");
+});
+
+test("the corpus's terms and a channel's markup are read with the project's list; a broken file fails the read", async () => {
+ const p = await project("c", [item("1")], { posts: { redact: [{ term: "Zed" }] } });
+ await mkdir(path.join(CH, "subj-x"), { recursive: true });
+ await writeFile(path.join(ROOT, "redactions.json"), JSON.stringify([{ term: "Quentin Example", note: "everywhere" }]));
+ await writeFile(path.join(CH, "subj-x", "posts-markup.json"), JSON.stringify({ "1": { redact: [{ start: 0, end: 4 }] } }));
+ const red = await projectRedaction(p.dir, await manifest(p));
+ assert.deepEqual(red.terms.map((t) => t.term), ["Quentin Example", "Zed"]);
+ assert.deepEqual(Object.keys(red.markup), ["subj-x/1"]);
+ assert.match((await cli(["redact", "c", "ls"])).out, /1 term\(s\) of its own; 1 from the corpus, 1 post\(s\) marked up/);
+ await writeFile(path.join(ROOT, "redactions.json"), "{ not json");
+ await assert.rejects(projectRedaction(p.dir, await manifest(p)), /does not parse/);
+ await rm(path.join(ROOT, "redactions.json"));
+ await rm(path.join(CH, "subj-x", "posts-markup.json"));
+});
+
+test("a take's synthesized read leaves the term out; the script and the take's record keep it", async () => {
+ const p = await project("t", [item("1", { narration: { script: "Hello, I am Quentin Example. Welcome." } })], { posts: { redact: [{ term: "Quentin Example" }] } });
+ const asked = [];
+ const ask = async (body) => {
+ asked.push(body);
+ wav(body.out, 1);
+ return { jobId: "job-1", result: { wav: body.out, engine: body.engine, voice: body.voice, seconds: 1 } };
+ };
+ const r = await makeTake(p, (await manifest(p)).timeline[0], { ask });
+ assert.equal(asked[0].text, "Hello, I am. Welcome.");
+ assert.doesNotMatch(asked[0].text, /quentin/i);
+ assert.equal(r.take.script, "Hello, I am Quentin Example. Welcome.");
+ assert.equal((await manifest(p)).timeline[0].narration.script, "Hello, I am Quentin Example. Welcome.");
+});
+
+test("posts set-item media.<i>.blur: on, strength, label, boxes -- merged; off keeps the settings; the file's entry otherwise untouched", async () => {
+ const p = await project("b", [item("1", { media: [{ src: "posts-media/subj-x/1/1.mp4", kind: "video", seconds: 3, width: 320, height: 180 }] })]);
+ let r = await cli(["set-item", "b", "p-1", "media.0.blur=on", "media.0.blur.strength=4", "media.0.blur.boxes=0,0,0.5,0.5;0.5,0.5,0.25,0.25"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual((await manifest(p)).timeline[0].media[0].blur, { on: true, strength: 4, boxes: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.25, 0.25]] });
+ r = await cli(["set-item", "b", "p-1", "media.0.blur.label=off", "media.0.blur.boxes=off"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual((await manifest(p)).timeline[0].media[0].blur, { on: true, strength: 4, label: false });
+ r = await cli(["set-item", "b", "p-1", "media.0.blur=off"]);
+ assert.deepEqual((await manifest(p)).timeline[0].media[0].blur, { on: false, strength: 4, label: false });
+ r = await cli(["set-item", "b", "p-1", "media.0.blur.strength=40"]);
+ assert.equal(r.code, 1, "refused in the build's words");
+ assert.equal((await manifest(p)).timeline[0].media[0].src, "posts-media/subj-x/1/1.mp4");
+});
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -33,7 +33,7 @@ import path from "node:path";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { channelsDirFor, readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
-import { PostsRefused, StaleToken, StructureRefused, addArchiveAvatars, manifestToken, setPostAvatar, updatePostItem, updatePosts, upsertPost } from "./manifest.mjs";
+import { PostsRefused, StaleToken, StructureRefused, addArchiveAvatars, manifestToken, setPostAvatar, updatePostItem, updatePostRedact, updatePosts, upsertPost } from "./manifest.mjs";
import { postWarnings } from "./postCards.mjs";
export const POSTS_USAGE = [
@@ -56,24 +56,37 @@ export const POSTS_USAGE = [
" POST ITEMS: each archived post as an entry of the cut, its card and its attachments (report-video.md, \"Post items\"):",
" the channels merged in time order, de-duplicated by post id; a post already in the cut is skipped, so a re-run",
" adds only what is new -- in ONE write (one undo point), at the end unless --after.",
- " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto]",
+ " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [follow=on|off|auto] [follow.dim=<0.2-1>] [follow.ease=<s>]",
" [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]",
" [media.<i>.push=on|off] [media.<i>.trim=off] [quoted.paraphrase=\"…\"|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]",
" [parent.<i>.paraphrase=\"…\"|off] [narration.rate=0.8–1.5|narration.<mix knob>=…] [--json]",
" a post item's knobs (the post bench's writer, updatePostItem): its hold, its images' grid, the blur of other authors,",
" an attachment's trim, sound, crop (fractions of its picture) and push-in; fit=read[:linger] (a narrated post: its",
" video cut to its best part for the read, `posts fit`). quoted.paraphrase / parent.<i>.paraphrase (nearest first):",
" your retelling of a long context post (at most 600 characters), drawn in place of its words and labelled",
" \"paraphrased\"; its own text is kept; off (or empty) shows its words again.",
+ " media.<i>.blur=on: the attachment CENSORED in the render -- a real blur (strength 1-10, default 7) of the whole",
+ " frame, or of its boxes (fractions of the picture as shown: x,y,w,h;…), labelled \"Censored\" (label=… or off);",
+ " its file is never touched. Play and the bench preview it; the bench draws boxes on a paused frame.",
" 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.",
" umtool posts avatars <project> [--dry-run] [--json]",
" every author the cut's cards draw unblurred, their picture from the archive's store (the channels' posts-media/",
" _avatars/, capture-posts') copied in where the cut has none; a manual one is never replaced.",
+ " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> [--json]",
+ " REDACTED WORDS (render.posts.redact): a word or phrase blanked from everything PUBLISHED -- a solid bar on the",
+ " rendered card, left out of a synthesized read, a 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 are",
+ " never rewritten; Play's \"As published\" shows the bars. `ls` lists the project's terms (n as `remove` takes it)",
+ " and counts the corpus's (transcripts/redactions.json, channels/<slug>/posts-markup.json).",
" umtool posts context <project> [--dry-run] [--json]",
" every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as",
" its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read",
@@ -82,7 +95,7 @@ export const POSTS_USAGE = [
" umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (umtool posts repeats --help)",
].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", "--match"]);
+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}$/;
@@ -363,6 +376,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)) {
@@ -374,6 +395,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (lingerRaw !== null && !(Number.isFinite(linger) && linger >= 0 && linger <= 30)) throw new CliError("--linger takes seconds, 0-30");
return await fitCommand(await projectOf(projectArg, root), words.slice(2), { all: flags.has("--all"), linger, json, dryRun, out });
}
+ if (verb === "redact" && projectArg && !flags.has("--help")) return await redactCommand(projectArg, words.slice(2), { root, json, out, flags, str });
if (verb === "avatar" && projectArg && !flags.has("--help")) return await avatarCommand(projectArg, words.slice(2), { root, json, out });
if (verb === "avatars" && projectArg && !flags.has("--help")) return await avatarsCommand(projectArg, { root, json, dryRun, out });
if (verb === "context" && projectArg && !flags.has("--help")) return await contextCommand(projectArg, { root, json, dryRun, out });
@@ -451,7 +473,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;
}
}
@@ -558,11 +580,26 @@ export function postItemPatchOf(pairs) {
if (k === "hold") out.hold = OFF.has(v) || v === "" ? null : Number(raw);
else if (k === "layout") out.mediaLayout = v === "sequence" ? null : v;
else if (k === "redact") out.redact = v === "auto" || v === "" ? null : onOff(v, k);
+ // Its read-follow (read-follow.mjs): follow=on|off|auto, follow.dim=<0.2-1>, follow.ease=<s> (auto/default: the cut's).
+ else if (k === "follow") out.follow = v === "auto" || v === "default" || v === "" ? null : onOff(v, k) ? { on: true } : false;
+ else if (k === "follow.dim" || k === "follow.ease") {
+ if (out.follow === false) throw new CliError("follow=off goes alone");
+ out.follow = { ...(out.follow ?? {}), [k.slice(7)]: v === "default" || v === "" ? null : Number(raw) };
+ }
else if (k === "quoted.paraphrase") out.quoted = { paraphrase: paraphraseOf(raw) };
else if (/^parents?\.\d+\.paraphrase$/.test(k)) (out.parents ??= {})[k.split(".")[1]] = { paraphrase: paraphraseOf(raw) };
- else {
+ else if (/^media\.\d+\.blur(\.(strength|label|boxes))?$/.test(k)) {
+ // The censoring blur (post-censor.mjs): on|off, its strength, its label (off: none), its boxes (x,y,w,h;…|off).
+ const [, i, , sub] = /^media\.(\d+)\.blur(\.(strength|label|boxes))?$/.exec(k) ?? [];
+ const blur = (((out.media ??= {})[i] ??= {}).blur ??= {});
+ if (!sub) blur.on = onOff(v, k);
+ else if (sub === "strength") blur.strength = OFF.has(v) || v === "" ? null : Number(raw);
+ else if (sub === "label") blur.label = v === "off" ? false : raw.trim() === "" ? null : raw;
+ else blur.boxes = OFF.has(v) || v === "" ? null : raw.split(";").map((b) => b.split(",").map(Number));
+ if (typeof blur.strength === "number" && !Number.isFinite(blur.strength)) throw new CliError(`${k}= takes a number (1-10)`);
+ } else {
const m = /^media\.(\d+)\.(start|end|mute|crop|push|trim)$/.exec(k);
- if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, media.<i>.start|end|mute|crop|push|trim=, quoted.paraphrase=, parent.<i>.paraphrase=)`);
+ if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, follow=, follow.dim|ease=, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes]=, quoted.paraphrase=, parent.<i>.paraphrase=)`);
const media = (out.media ??= {});
const one = (media[m[1]] ??= {});
if (m[2] === "start" || m[2] === "end") one[m[2]] = OFF.has(v) || v === "" ? null : Number(raw);
@@ -576,9 +613,46 @@ export function postItemPatchOf(pairs) {
}
if (!Object.keys(out).length) throw new CliError("nothing to set");
for (const [k, v] of Object.entries(out)) if (typeof v === "number" && !Number.isFinite(v)) throw new CliError(`${k}= takes a number`);
+ for (const [fk, fv] of Object.entries(out.follow && typeof out.follow === "object" ? out.follow : {})) if (typeof fv === "number" && !Number.isFinite(fv)) throw new CliError(`follow.${fk}= takes a number`);
return out;
}
+/** `umtool posts redact <p> ls | add "<term>" [--substring] [--note …] | remove <n>`: the project's redaction list. */
+async function redactCommand(projectArg, rest, { root, json, out, flags, str }) {
+ const project = await projectOf(projectArg, root);
+ const [sub, arg] = rest;
+ const write = async (change) => withEditNotes(project, async () => updatePostRedact(project.dir, change, { token: await manifestToken(project.dir) }));
+ const line = (t, i) => ` ${i + 1}. ${t.term}${t.wholeWord === false ? " (inside words too)" : ""}${t.note ? ` -- ${t.note}` : ""}`;
+ if (sub === "add") {
+ if (!arg || !String(arg).trim()) throw new CliError('posts redact add takes the term: add "<word or phrase>"');
+ const { result } = await write({ add: { term: arg, ...(flags.has("--substring") ? { wholeWord: false } : {}), ...(str("--note") ? { note: str("--note") } : {}) } });
+ out(json ? JSON.stringify({ ok: true, redact: result.redact, token: result.token }, null, 2) : `added; ${project.id} blanks ${result.redact.length} term(s) from what it publishes`);
+ return 0;
+ }
+ if (sub === "remove") {
+ const n = Number(arg);
+ if (!Number.isInteger(n) || n < 1) throw new CliError("posts redact remove takes the term's number, as `ls` shows it");
+ const { result } = await write({ remove: n - 1 });
+ out(json ? JSON.stringify({ ok: true, redact: result.redact, token: result.token }, null, 2) : `removed term ${n}; ${project.id} blanks ${result.redact.length} term(s)`);
+ return 0;
+ }
+ if (sub !== "ls" && sub !== undefined) throw new CliError(`posts redact: ls, add "<term>" or remove <n> (not ${sub})`);
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ const list = Array.isArray(manifest.render?.posts?.redact) ? manifest.render.posts.redact : [];
+ const { projectRedaction } = await import("./postRedaction.mjs");
+ const all = await projectRedaction(project.dir, manifest);
+ const corpus = all.terms.length - list.length;
+ const marked = Object.keys(all.markup ?? {}).length;
+ if (json) {
+ out(JSON.stringify({ ok: true, redact: list, corpusTerms: corpus, markedPosts: marked }, null, 2));
+ return 0;
+ }
+ out(`${project.id}: ${list.length} term(s) of its own${list.length ? "" : " (umtool posts redact <p> add \"<term>\")"}; ${corpus} from the corpus, ${marked} post(s) marked up in its channels`);
+ list.forEach((t, i) => out(line(t, i)));
+ return 0;
+}
+
/** `posts context`: every post item's context from its capture (postContext.mjs postsContext). */
async function contextCommand(projectArg, { root, json, dryRun, out }) {
const project = await projectOf(projectArg, root);
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -212,6 +212,8 @@ import {
// The snap itself (a montage's window snaps with it too), re-exported for the tests.
import { snap } from "./snap.mjs";
import { buildPostSegment } from "./post-render.mjs";
+import { readPostRedaction } from "./post-redact-files.mjs";
+import { dropMarks, redactEntry } from "./post-redact.mjs";
import { avatarUrls } from "./post-avatars.mjs";
import { applyPostCombo } from "./post-combo-render.mjs";
import { projectCombos } from "./post-combo-prints.mjs";
@@ -287,6 +289,8 @@ let LOCAL = null;
// The channels tree the build reads local media from (sources.mjs
// channelsDirFor), for the effects' words: set by buildVideo() beside CUES.
let FX_CHANNELS_DIR = null;
+// What this build blanks from its post items (post-redact.mjs): the corpus's terms, the channels' markup, the project's list.
+let POST_REDACTION = null;
const exists = (p) => access(p).then(() => true, () => false);
@@ -5529,6 +5533,13 @@ export async function chapterTitle(entry, index, provenance, { deck = false } =
}
// A post item: who posted it, and the first words.
if (entry.type === "post") {
+ // As published: a redacted term is left out of the chapter line (post-redact.mjs).
+ const shown = redactEntry(entry, POST_REDACTION);
+ if (shown !== entry) {
+ const words = dropMarks(String(shown.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "")).replace(/\s+/g, " ").trim();
+ const who = dropMarks(String(shown.author ?? "")) || (dropMarks(String(shown.handle ?? "")) ? `@${dropMarks(String(shown.handle))}` : "Post");
+ return `${who}: ${words.length > 60 ? `${words.slice(0, 57)}…` : words || "(no words)"}`;
+ }
const words = String(entry.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim();
return `${entry.author ?? (entry.handle ? `@${entry.handle}` : "Post")}: ${words.length > 60 ? `${words.slice(0, 57)}…` : words || "(no words)"}`;
}
@@ -6141,6 +6152,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe,
});
FX_CHANNELS_DIR = channelsDir;
+ // Read only for a cut that plays post items: a cut without them publishes nothing it could blank.
+ POST_REDACTION = (manifest.timeline ?? []).some((e) => e?.type === "post") ? await readPostRedaction(channelsDir, manifest) : null;
// Speaker captions read the project's reactions.json and words beside the
// manifest (readLookSources); a short is framed by its clip's crop.
if (captionsOn(render)) dirs.look = await readLookSources(manifestDir);
@@ -6409,6 +6422,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
encode: encodeArgs(render), exec: execFileP, ffmpeg: FFMPEG, emit: (ev, f) => EMIT(ev, f),
// The authors' pictures (post-avatars.mjs), as files of the project.
avatars: avatarUrls(manifest, (src) => path.resolve(manifestDir, src)),
+ redaction: POST_REDACTION,
});
if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr });
// Its combo badge (post-combo-render.mjs): a pass over the segment when its attachment repeats an earlier one's.
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 { validatePostCombos } from "./post-combo.mjs";
@@ -326,6 +327,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
@@ -66,7 +66,12 @@
"./post-combo-render": "./post-combo-render.mjs",
"./post-item": "./post-item.mjs",
"./post-narration": "./post-narration.mjs",
+ "./post-censor": "./post-censor.mjs",
+ "./post-redact": "./post-redact.mjs",
+ "./post-redact-files": "./post-redact-files.mjs",
"./post-render": "./post-render.mjs",
+ "./word-zoom": "./word-zoom.mjs",
+ "./read-follow": "./read-follow.mjs",
"./presets": "./presets.mjs",
"./prune-frames": "./prune-frames.mjs",
"./render-cards": "./render-cards.mjs",
diff --git a/umtool/report-to-video/post-censor.mjs b/umtool/report-to-video/post-censor.mjs
@@ -0,0 +1,144 @@
+// A CENSORED ATTACHMENT (operator, 3 Nov: "'it jiggle' will need to be
+// censored but I do want to include it"): a post item's picture or video
+// played BLURRED -- the whole frame, or only some regions of it -- with a
+// small label saying so. umtool/docs/knobs.md, "A post item".
+//
+// media[i].blur = { on: true, strength?: 1–10 (7), boxes?: [[x, y, w, h], …], label?: "…" | false }
+//
+// `boxes` are fractions of the picture AS SHOWN (after its crop), held still
+// over the clip; none blurs the whole frame. `label` is the caption drawn on
+// it ("Censored" by default; false: none). A post's channel markup may censor
+// one of its attachments for every project (posts-markup.json's `censor`,
+// post-redact.mjs); the item's own `blur` wins.
+//
+// NOTHING IS REWRITTEN: the attachment's file stays as it was captured. The
+// blur is a real one (ffmpeg gblur, sigma grown with the strength and the
+// picture's size), drawn where public output is made -- the render. Play and
+// the post bench preview it (a CSS blur, the boxes as backdrop blurs).
+//
+// PURE and dependency-free.
+
+export const POST_BLUR_DEFAULTS = Object.freeze({ strength: 7, label: "Censored" });
+export const POST_BLUR_BOXES_MAX = 8;
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r3 = (v) => Math.round(v * 1000) / 1000;
+
+/** Is attachment `m` blurred? */
+export const blurOn = (m) => isObj(m?.blur) && m.blur.on === true;
+
+/** Its blur with the defaults filled: `{ strength, boxes, label }` (label null: none), or null when it is not blurred. */
+export function blurOf(m) {
+ if (!blurOn(m)) return null;
+ const b = m.blur;
+ return {
+ strength: fin(b.strength) ? Math.min(10, Math.max(1, b.strength)) : POST_BLUR_DEFAULTS.strength,
+ boxes: Array.isArray(b.boxes) ? b.boxes.filter((x) => Array.isArray(x) && x.length === 4) : [],
+ label: b.label === false ? null : typeof b.label === "string" && b.label.trim() ? b.label.trim() : POST_BLUR_DEFAULTS.label,
+ };
+}
+
+/** The blur's sigma on a picture `width` px wide: 0.4% of the width per step of strength (at 7, ~2.8%). */
+export const blurSigma = (strength, width) => Math.max(2, Math.round(width * strength * 0.004 * 10) / 10);
+/** The same as a share of the width, for a preview (CSS `cqw`). */
+export const blurCqw = (strength) => r3(strength * 0.4);
+
+/** Is `b` a box of fractions inside the picture? */
+export const boxOk = (b) =>
+ Array.isArray(b) && b.length === 4 && b.every((v) => fin(v) && v >= 0 && v <= 1) && b[2] >= 0.01 && b[3] >= 0.01 && b[0] + b[2] <= 1.0001 && b[1] + b[3] <= 1.0001;
+
+/** Every reason `media[i].blur` is refused. */
+export function blurErrors(blur, where) {
+ if (blur === undefined) return [];
+ if (!isObj(blur)) return [`${where} must be {on, strength?, boxes?, label?}`];
+ const errors = [];
+ for (const k of Object.keys(blur)) if (!["on", "strength", "boxes", "label"].includes(k)) errors.push(`${where}.${k} is not a blur knob (on, strength, boxes, label)`);
+ if (typeof blur.on !== "boolean") errors.push(`${where}.on must be true or false`);
+ if (blur.strength !== undefined && !(fin(blur.strength) && blur.strength >= 1 && blur.strength <= 10)) errors.push(`${where}.strength must be 1–10`);
+ if (blur.boxes !== undefined) {
+ if (!Array.isArray(blur.boxes) || blur.boxes.length > POST_BLUR_BOXES_MAX) errors.push(`${where}.boxes must be a list of at most ${POST_BLUR_BOXES_MAX} [x, y, w, h]`);
+ else blur.boxes.forEach((b, j) => !boxOk(b) && errors.push(`${where}.boxes[${j}] must be [x, y, w, h] as fractions of the picture (each 0–1, inside it)`));
+ }
+ if (blur.label !== undefined && blur.label !== false && !(typeof blur.label === "string" && blur.label.length <= 40)) errors.push(`${where}.label must be words (at most 40 characters) or false`);
+ return errors;
+}
+
+/** A label's words as ffmpeg drawtext's `text=` takes them, inside single quotes. */
+const dtText = (s) => String(s).replace(/\\/g, "\\\\").replace(/'/g, "\u2019").replace(/:/g, "\\:").replace(/%/g, "\\%");
+
+/**
+ * The filters that blur attachment `m`, drawn `w` × `h` px: `[inLabel]` →
+ * `[outLabel]`. The whole frame, or each box: split, cropped, blurred and laid
+ * back over. A label is drawn by labelFilter, on the composed frame.
+ */
+export function blurFilters(inLabel, outLabel, m, { width, height }) {
+ const b = blurOf(m);
+ if (!b) return [`[${inLabel}]null[${outLabel}]`];
+ const sigma = blurSigma(b.strength, width);
+ if (!b.boxes.length) return [`[${inLabel}]gblur=sigma=${sigma}:steps=3[${outLabel}]`];
+ const out = [];
+ let cur = inLabel;
+ b.boxes.forEach((box, j) => {
+ const x = Math.round(box[0] * width);
+ const y = Math.round(box[1] * height);
+ const w = Math.max(2, Math.min(width - x, Math.round(box[2] * width)));
+ const h = Math.max(2, Math.min(height - y, Math.round(box[3] * height)));
+ const base = `${outLabel}_k${j}`;
+ out.push(`[${cur}]split[${base}a][${base}b]`);
+ out.push(`[${base}b]crop=${w}:${h}:${x}:${y},gblur=sigma=${sigma}:steps=3[${base}c]`);
+ const next = j === b.boxes.length - 1 ? outLabel : `${base}o`;
+ out.push(`[${base}a][${base}c]overlay=x=${x}:y=${y}[${next}]`);
+ cur = next;
+ });
+ return out;
+}
+
+/**
+ * The label's drawtext on the frame `[inLabel]` → `[outLabel]`: the words at
+ * the attachment's top-left corner (its box `b` on the frame) while it is up,
+ * or null when it has none (or there is no face to draw it in).
+ */
+export function labelFilter(inLabel, outLabel, m, b, { from, to, fontfile, scale = 1 }) {
+ const bl = blurOf(m);
+ if (!bl?.label || !fontfile) return null;
+ const size = Math.max(12, Math.round(26 * scale));
+ const pad = Math.round(size * 0.5);
+ return (
+ `[${inLabel}]drawtext=fontfile='${fontfile}':text='${dtText(bl.label)}':fontsize=${size}:fontcolor=white:box=1:boxcolor=black@0.7:boxborderw=${Math.round(size * 0.35)}:` +
+ `x=${b.x + pad}:y=${b.y + pad}:enable='between(t,${r3(from)},${r3(to)})'[${outLabel}]`
+ );
+}
+
+/** Every reason a markup's `censor` list is refused (posts-markup.json). */
+export function censorMarkupErrors(list, where) {
+ if (list === undefined) return [];
+ if (!Array.isArray(list)) return [`${where} must be a list of {media, blur}`];
+ const errors = [];
+ list.forEach((c, i) => {
+ if (!isObj(c) || !(Number.isInteger(c.media) && c.media >= 0 && c.media < 8)) errors.push(`${where}[${i}].media must be the attachment's index (0–7)`);
+ if (isObj(c) && c.blur !== undefined) errors.push(...blurErrors({ on: true, ...(isObj(c.blur) ? c.blur : { bad: c.blur }) }, `${where}[${i}].blur`));
+ });
+ return errors;
+}
+
+/**
+ * Post item `entry` with its channel markup's censoring laid on (`censor:
+ * [{media, blur?}]` in the post's markup; `blur` absent: the whole frame, the
+ * defaults): an attachment with a `blur` of its own keeps it. Returns the
+ * entry itself when nothing changes.
+ *
+ * @param {Record<string, any>} entry
+ * @param {{ markup?: Record<string, {censor?: Array<{media: number, blur?: Record<string, any>}>}> } | null | undefined} red
+ */
+export function censorEntry(entry, red) {
+ const list = red?.markup?.[String(entry?.post ?? "")]?.censor;
+ if (!Array.isArray(list) || !list.length || !Array.isArray(entry?.media)) return entry;
+ let changed = false;
+ const media = entry.media.map((m, i) => {
+ const c = list.find((x) => x?.media === i);
+ if (!c || !isObj(m) || m.blur !== undefined) return m;
+ changed = true;
+ return { ...m, blur: { on: true, ...(isObj(c.blur) ? c.blur : {}) } };
+ });
+ return changed ? { ...entry, media } : entry;
+}
diff --git a/umtool/report-to-video/post-censor.test.mjs b/umtool/report-to-video/post-censor.test.mjs
@@ -0,0 +1,83 @@
+// post-censor.mjs: a censored attachment -- the knob's check, the blur in the
+// encode (the whole frame, or its boxes), the label, a channel's markup.
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { blurErrors, blurFilters, blurOf, blurSigma, censorEntry } from "./post-censor.mjs";
+import { postItemPlan, postLayout, validatePostItem } from "./post-item.mjs";
+import { postSegmentArgs } from "./post-render.mjs";
+import { validatePostsMarkup } from "./post-redact.mjs";
+
+const box = { width: 1440, height: 810 };
+const entry = (blur) => ({
+ type: "post", id: "p1", post: "c-x/1", platform: "x", author: "A", handle: "a", date: "2026-10-30T04:00:00Z", text: "it does a thing",
+ media: [{ src: "m/v.mp4", kind: "video", seconds: 3, width: 320, height: 180, audio: false, ...(blur ? { blur } : {}) }],
+});
+const graphOf = (e, fontfile = null) => {
+ const argv = postSegmentArgs({ entry: e, box, plan: postItemPlan(e), layout: postLayout(e, box), cards: { read: "/c/read.png" }, files: ["/m/v.mp4"], render: { fps: 30 }, outPath: "/o.mp4", fontfile });
+ return argv[argv.indexOf("-filter_complex") + 1];
+};
+
+test("the knob: on, a strength 1-10, boxes of fractions, a label or false; validated with the item", () => {
+ assert.deepEqual(blurErrors({ on: true, strength: 4, boxes: [[0.1, 0.1, 0.5, 0.5]], label: false }, "b"), []);
+ const bad = blurErrors({ on: "yes", strength: 11, boxes: [[0.8, 0, 0.5, 0.5]], label: 3, extra: 1 }, "b");
+ assert.equal(bad.length, 5, bad.join("; "));
+ assert.ok(validatePostItem(entry({ on: true, strength: 0 })).some((e) => e.includes("media[0].blur.strength must be 1–10")));
+ assert.deepEqual(blurOf({ blur: { on: true } }), { strength: 7, boxes: [], label: "Censored" });
+ assert.equal(blurOf({ blur: { on: false, strength: 3 } }), null, "off keeps its settings and blurs nothing");
+});
+
+test("the encode: the whole frame gblurred, or each box split, cropped, blurred and laid back; the label drawn on the frame", () => {
+ const plain = graphOf(entry(null));
+ assert.doesNotMatch(plain, /gblur/);
+ const whole = graphOf(entry({ on: true }), "/f/bold.ttf");
+ assert.match(whole, /\[m0_0r\]gblur=sigma=[\d.]+:steps=3\[m0_0\]/);
+ assert.match(whole, /drawtext=fontfile='\/f\/bold.ttf':text='Censored'/);
+ const boxes = graphOf(entry({ on: true, strength: 5, boxes: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]], label: "It: 100%" }), "/f/bold.ttf");
+ assert.equal((boxes.match(/gblur/g) ?? []).length, 2);
+ assert.match(boxes, /\[m0_0r\]split/);
+ assert.match(boxes, /text='It\\: 100\\%'/);
+ assert.doesNotMatch(graphOf(entry({ on: true, label: false }), "/f/bold.ttf"), /drawtext/);
+ assert.equal(blurSigma(7, 1000), 28);
+ assert.deepEqual(blurFilters("a", "b", { blur: { on: false } }, { width: 10, height: 10 }), ["[a]null[b]"]);
+});
+
+test("a channel's markup censors an attachment in every project; the item's own blur wins", () => {
+ const red = { terms: [], markup: { "c-x/1": { censor: [{ media: 0 }] } } };
+ const e = entry(null);
+ const out = censorEntry(e, red);
+ assert.deepEqual(out.media[0].blur, { on: true });
+ assert.equal(e.media[0].blur, undefined, "the entry is never rewritten");
+ const own = entry({ on: false });
+ assert.equal(censorEntry(own, red), own);
+ assert.equal(censorEntry(e, { terms: [] }), e);
+ assert.deepEqual(validatePostsMarkup({ "1": { censor: [{ media: 0, blur: { strength: 3 } }] } }), []);
+ assert.equal(validatePostsMarkup({ "1": { censor: [{ media: 9 }, { media: 0, blur: { strength: 30 } }] } }).length, 2);
+});
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "post-censor-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+test("the encode runs: a blurred frame is smoother than the clean one (ffmpeg)", () => {
+ const src = path.join(ROOT, "v.mp4");
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=s=320x180:d=3:r=30", "-c:v", "libx264", "-pix_fmt", "yuv420p", src]);
+ const png = path.join(ROOT, "card.png");
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=black:s=1440x810", "-frames:v", "1", png]);
+ const detail = (blur) => {
+ const e = entry(blur);
+ const out = path.join(ROOT, `o-${blur ? "b" : "c"}.mp4`);
+ const argv = postSegmentArgs({ entry: e, box, plan: postItemPlan(e), layout: postLayout(e, box), cards: { read: png }, files: [src], render: { fps: 30 }, outPath: out, encode: ["-c:v", "libx264", "-preset", "ultrafast"] });
+ execFileSync("ffmpeg", argv);
+ // The frame's edge energy: a blur takes most of it away.
+ const r = spawnSync("ffmpeg", ["-v", "info", "-ss", "1", "-i", out, "-frames:v", "1", "-vf", "edgedetect,signalstats,metadata=print:key=lavfi.signalstats.YAVG", "-f", "null", "-"], { encoding: "utf8" });
+ return `${r.stdout}${r.stderr}`;
+ };
+ const yavg = (s) => Number(/YAVG=([\d.]+)/.exec(s)?.[1] ?? NaN);
+ const clean = yavg(detail(null));
+ const blurred = yavg(detail({ on: true, label: false }));
+ assert.ok(Number.isFinite(clean) && Number.isFinite(blurred), `${clean} ${blurred}`);
+ assert.ok(blurred < clean * 0.6, `edges: clean ${clean}, blurred ${blurred}`);
+});
diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -9,8 +9,12 @@
// repostedBy?: { author, handle }, quoted?: <ref>, parents?: [<ref>, …],
// replyingTo?: "<handle>", parentShot?: "<file>",
// media?: [{ src, kind: "image"|"video"|"gif", seconds?, width?, height?, audio?,
-// start?, end?, mute?, crop?: [x, y, w, h], push?, words? }],
-// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen? }
+// start?, end?, mute?, crop?: [x, y, w, h], push?, words?,
+// blur?: { on, strength?, boxes?, label? } }], (post-censor.mjs)
+// 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? }` --
@@ -28,6 +32,10 @@
import {
isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration,
} from "./post-narration.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";
+import { FOLLOW_MIN_SIZE, followBlocks, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs";
/** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */
export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]);
@@ -226,7 +234,9 @@ function planOf(entry, render, hold) {
const narrated = isNarrated(entry);
const k = postNarrationKnobs(entry, render);
const sch = narrated ? narrationSchedule(entry, render) : null;
- const extra = sch ? { narration: sch } : {};
+ // Its read-follow (read-follow.mjs): each block's start on the item's clock -- null when it is off.
+ const follow = followSchedule(entry, render, { hold, narration: sch });
+ const extra = { ...(sch ? { narration: sch } : {}), ...(follow ? { follow } : {}) };
if (sch && k.attach === "after") {
const voiceOnly = round3(sch.at + sch.seconds + k.tail);
const all = mediaSteps(entry);
@@ -458,6 +468,10 @@ 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));
+ // Its read-follow's knobs (read-follow.mjs): false, or { on, dim, ease }.
+ errors.push(...validatePostFollow(e));
return errors;
}
@@ -487,6 +501,7 @@ function mediaErrors(m, where) {
const er2 = relFileError(m.words, `${where}.words`);
if (er2) errors.push(er2);
}
+ errors.push(...blurErrors(m.blur, `${where}.blur`));
return errors;
}
@@ -495,6 +510,43 @@ export function validatePostItems(manifest) {
const errors = [];
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;
}
@@ -676,13 +728,31 @@ 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, blocks = 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>");
+ // `blocks` (read-follow.mjs scopeBlocks): runs of words wrapped `data-post-block="<k>"`, the read's blocks.
+ const opens = new Map((blocks ?? []).map((b) => [b.from, b.k]));
+ const closes = new Set((blocks ?? []).map((b) => b.to));
+ 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;
+ const open = opens.has(t.i) ? `<span class="fblock" data-post-block="${opens.get(t.i)}">` : "";
+ return `${open}<span data-w="${esc(scope)}:${t.i}"${lit ? " data-w-hl=\"\"" : ""}>${word(t.tok)}</span>${closes.has(t.i) ? "</span>" : ""}`;
+ })
+ .join("");
}
/**
@@ -728,17 +798,35 @@ 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).
+ * `follow` (read-follow.mjs): the read's blocks wrapped `data-post-block`, the
+ * post's words in a flow (`data-post-flow`) with fading edges, never shrunk
+ * below FOLLOW_MIN_SIZE -- the build and Play light and pan them.
*
* @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> }} o
+ * 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, follow?: boolean }} o
*/
-export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {} }) {
+export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null, follow = false }) {
+ const hlOf = (scope) => (highlight && highlight.scope === scope ? highlight : null);
+ // READ-FOLLOW (read-follow.mjs): the read's blocks wrapped on the card, the post's words in a flow that pans --
+ // mapped on the words as written (the plan's are), whose indices the redaction's bars keep.
+ const fmap = follow ? followBlocks(entry) : null;
+ const blk = (scope) => (fmap ? scopeBlocks(fmap, scope) : 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 };
const L = postLayout(entry, { width, height });
const k = height / 1080;
- const size = L.size;
+ // Following, the words never shrink below a readable size to fit: the card pans them instead.
+ const followMin = Math.round(FOLLOW_MIN_SIZE * k);
+ const size = follow ? Math.max(L.size, followMin) : L.size;
const authors = cardAuthors(entry);
const blurred = authors.filter((a) => a.redact && a.handle).map((a) => a.handle);
const red = (where) => authors.find((a) => a.where === where)?.redact ?? false;
@@ -762,7 +850,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}`), blk(`parent:${i}`))}</div></div></div>`,
);
}
if (!parents.length && parentShotUrl) ctx.push(`<div class="pshot" data-post-parent-shot=""><img src="${esc(parentShotUrl)}" alt=""></div>`);
@@ -771,20 +859,20 @@ 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"), blk("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">${follow ? `<div class="wflow" data-post-flow="">${wordsHtml(cardText(entry), blurred, "post", hlOf("post"), blk("post"))}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div>` : 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>`
: "";
const slot = L.slot && (L.mode === "side" || strip) ? `<div class="slot" data-post-slot="" style="left:${L.slot.x}px;top:${L.slot.y}px;width:${L.slot.width}px;height:${L.slot.height}px"></div>` : "";
const body = strip ? `${stripHtml}${slot}` : `${card(L.card)}${slot}`;
- const minSize = Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k);
+ const minSize = follow ? followMin : Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k);
return `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=${width}, height=${height}">
<style>
@@ -827,9 +915,16 @@ 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; }${follow ? `
+.words { position: relative; }
+.wflow { will-change: transform; }
+.wfade { position: absolute; left: 0; right: 0; height: 1.5em; pointer-events: none; opacity: 0; }
+.wfade[data-post-fade="top"] { top: 0; background: linear-gradient(${cardBg}, ${rgbaOf(cardBg, 0)}); }
+.wfade[data-post-fade="bottom"] { bottom: 0; background: linear-gradient(${rgbaOf(cardBg, 0)}, ${cardBg}); }` : ""}${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"}">${body}
+<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}"${fmap ? ` data-post-follow="${fmap.blocks.length}"` : ""}>${barsHtml(body)}
<script>
// The words at the layout's size, shrunk while they overflow (the browser
// knows how they wrap; the layout only estimated it). Then say so.
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
@@ -30,6 +31,8 @@
// from the post's words. The plan of what plays when is post-item.mjs's
// (postItemPlan's narrated branch), which reads these.
+import { followKnobErrors } from "./read-follow.mjs";
+
/** The engines a post's narration may name (the editor's tts op). */
export const POST_NARRATION_ENGINES = Object.freeze(["orpheus", "kokoro", "espeak-ng"]);
/** A take's engine: one of those, or `recorded` -- a person's own voice, recorded on the post bench (never synthesized). */
@@ -160,9 +163,10 @@ export const POST_NARRATION_CLIP = Object.freeze(["read", "full"]);
const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate"];
// `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"]);
+// `follow`: the cut's read-follow (read-follow.mjs) -- { on, dim, ease } -- kept here with the mix it rides on.
+const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow"]);
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}$/;
@@ -473,7 +477,7 @@ export function validatePostNarrationRender(render) {
if (!isObj(r)) return ["render.postNarration must be an object of the mix's knobs"];
const errors = [];
for (const k of Object.keys(r)) if (!RENDER_KEYS.has(k)) errors.push(`render.postNarration.${k} is not a knob (${[...RENDER_KEYS].join(", ")})`);
- return [...errors, ...mixErrors(r, "render.postNarration")];
+ return [...errors, ...mixErrors(r, "render.postNarration"), ...followKnobErrors(r.follow, "render.postNarration.follow")];
}
/** Every reason one post item's `narration` cannot be built (empty: it can). */
@@ -524,6 +528,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-files.mjs b/umtool/report-to-video/post-redact-files.mjs
@@ -0,0 +1,71 @@
+// THE REDACTION A BUILD PUBLISHES WITH (post-redact.mjs): the corpus's terms,
+// each post's channel markup and the project's own list, read together. Read
+// only -- the corpus's two files are the editor's to write.
+//
+// <transcripts>/redactions.json [{ term, wholeWord?, note? }] (or { terms: […] })
+// <transcripts>/channels/<slug>/posts-markup.json { "<postId>": { redact: […] } }
+//
+// A file that is there and does not parse, or is refused by its validator,
+// FAILS the read: a public render that silently ignored its redaction would
+// publish what it was told to blank. A file that is not there is nothing.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { normalizeTerms, projectRedactOf, validatePostsMarkup, validateRedactTerms } from "./post-redact.mjs";
+
+export const CORPUS_REDACTIONS_FILE = "redactions.json";
+export const POSTS_MARKUP_FILE = "posts-markup.json";
+
+/** The corpus's terms file beside a channels dir. */
+export const corpusRedactionsPath = (channelsDir) => path.join(path.dirname(path.resolve(channelsDir)), CORPUS_REDACTIONS_FILE);
+/** A channel's markup file. */
+export const postsMarkupPath = (channelsDir, slug) => path.join(path.resolve(channelsDir), slug, POSTS_MARKUP_FILE);
+
+async function readJson(file) {
+ let text;
+ try {
+ text = await readFile(file, "utf8");
+ } catch (e) {
+ if (e?.code === "ENOENT" || e?.code === "ENOTDIR") return undefined;
+ throw e;
+ }
+ try {
+ return JSON.parse(text);
+ } catch (e) {
+ throw new Error(`${file} does not parse (${e instanceof Error ? e.message : e}) -- a public render does not run without its redaction`);
+ }
+}
+
+/**
+ * The redaction for `manifest`'s post items: `{ terms, markup }`. `channelsDir`
+ * null reads only the project's list (no corpus at hand).
+ *
+ * @param {string|null} channelsDir
+ * @param {Record<string, any>} manifest
+ */
+export async function readPostRedaction(channelsDir, manifest) {
+ const project = projectRedactOf(manifest?.render);
+ const terms = [];
+ const markup = {};
+ if (channelsDir) {
+ const file = corpusRedactionsPath(channelsDir);
+ const doc = await readJson(file);
+ if (doc !== undefined) {
+ const list = Array.isArray(doc) ? doc : doc?.terms;
+ const errors = validateRedactTerms(list, CORPUS_REDACTIONS_FILE);
+ if (errors.length) throw new Error(`${file} is refused: ${errors.join("; ")}`);
+ terms.push(...normalizeTerms(list));
+ }
+ const posts = (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => e?.type === "post" && typeof e.post === "string");
+ const slugs = [...new Set(posts.map((e) => e.post.split("/")[0]).filter((s) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(s)))];
+ for (const slug of slugs) {
+ const mf = postsMarkupPath(channelsDir, slug);
+ const doc2 = await readJson(mf);
+ if (doc2 === undefined) continue;
+ const errors = validatePostsMarkup(doc2, `${slug}/${POSTS_MARKUP_FILE}`);
+ if (errors.length) throw new Error(`${mf} is refused: ${errors.join("; ")}`);
+ for (const [id, m] of Object.entries(doc2)) markup[`${slug}/${id}`] = m;
+ }
+ }
+ terms.push(...normalizeTerms(project));
+ return { terms, markup };
+}
diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs
@@ -0,0 +1,275 @@
+// WORDS BLANKED FROM WHAT IS PUBLISHED (operator, 3 Nov: "Leave out his real
+// name since we don't really need it, even if he says it himself blank and
+// skip it"; "don't manipulate original data, just don't show it in the
+// public views"). umtool/docs/knobs.md, "Redacted words".
+//
+// A REDACTION is a list of terms -- a word or a phrase -- matched without
+// regard to case, as whole words unless `wholeWord: false`, the words of a
+// phrase across any run of spaces or punctuation ("Quentin Example" matches
+// "quentin, EXAMPLE", and "QuentinExample" as a handle runs them together), a
+// possessive 's taken with it. Its sources, merged by
+// the reader (post-redact-files.mjs):
+//
+// render.posts.redact [{ term, wholeWord?, note? }] the project's own list
+// <transcripts>/redactions.json the same shape every project's (the corpus's)
+// channels/<slug>/posts-markup.json one post's MARKUP:
+// { "<postId>": { redact?: [{ term, wholeWord?, scope? } | { start, end, scope?, index? }],
+// censor?: [{ media: <i>, blur?: {strength?, boxes?, label?} }] } }
+// a term (in `scope` -- "text", "parent", "quoted" -- or the whole post), or a span of the
+// archived text, in code units (`index`: which parent, nearest first); `censor` blurs an
+// attachment of the post in every project (post-censor.mjs)
+//
+// NOTHING IS REWRITTEN: the archive's rows, the manifest's snapshot and a
+// narration's script keep their words. Redaction happens only where PUBLIC
+// output is made -- the rendered card (each match a solid bar of the word's
+// width: no letters, not a blur), the read a voice synthesizes (the match
+// dropped, its spaces and dangling punctuation tidied), a video's chapter
+// line and an attachment's burnt-in captions. umtool's own views show the
+// words; Play's "As published" shows the bars.
+//
+// PURE (the build, the route, Play and the writers).
+import { censorMarkupErrors } from "./post-censor.mjs";
+
+/** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */
+export const REDACT_MARK = "";
+const MARKS_RE = /+/g;
+export const POST_REDACT_MAX = 200;
+export const POST_REDACT_TERM_MAX = 120;
+export const POST_MARKUP_SCOPES = Object.freeze(["text", "parent", "quoted"]);
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const str = (v) => (typeof v === "string" ? v : "");
+const WORD = "[\\p{L}\\p{N}]";
+const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
+
+/** A term's words (letters and digits): what it matches, across any punctuation. */
+export const termWords = (term) => str(term).split(/[^\p{L}\p{N}]+/u).filter(Boolean);
+
+/** A list's terms as `{ term, wholeWord }`, a bare string read as a term. */
+export function normalizeTerms(list) {
+ return (Array.isArray(list) ? list : [])
+ .map((t) => (typeof t === "string" ? { term: t } : t))
+ .filter((t) => isObj(t) && termWords(t.term).length)
+ .map((t) => ({ term: t.term, wholeWord: t.wholeWord !== false }));
+}
+
+/** One term's pattern source, or null when it has no word to match. */
+export function termPattern(t) {
+ const words = termWords(t?.term);
+ if (!words.length) return null;
+ // Between a phrase's words, any run of spaces or punctuation -- or none, as a handle writes it ("QuentinExample").
+ const body = `${words.map(escRe).join("[^\\p{L}\\p{N}]*")}(?:['’]s)?`;
+ return t?.wholeWord === false ? body : `(?<!${WORD})${body}(?!${WORD})`;
+}
+
+/** The terms' one pattern (longest first, so a phrase wins over a word inside it), or null. */
+export function redactPattern(terms) {
+ const src = normalizeTerms(terms)
+ .sort((a, b) => b.term.length - a.term.length)
+ .map(termPattern)
+ .filter(Boolean);
+ return src.length ? new RegExp(src.join("|"), "giu") : null;
+}
+
+/**
+ * `text` with every match of `terms` (and every `spans` range, `{start, end}`
+ * 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
+ * @param {Array<string|{term: string, wholeWord?: boolean}>|RegExp|null} terms
+ * @param {{ spans?: Array<{start: number, end: number}> }} [o]
+ */
+export function redactText(text, terms, { spans: extra = [] } = {}) {
+ const s = str(text);
+ const re = terms instanceof RegExp ? new RegExp(terms.source, terms.flags) : redactPattern(terms);
+ const ranges = [];
+ if (re && s) for (const m of s.matchAll(re)) if (m[0]) ranges.push([m.index, m.index + m[0].length]);
+ for (const sp of Array.isArray(extra) ? extra : []) {
+ const a = Math.max(0, Math.floor(Number(sp?.start)));
+ const b = Math.min(s.length, Math.floor(Number(sp?.end)));
+ if (Number.isFinite(a) && Number.isFinite(b) && b > a) ranges.push([a, b]);
+ }
+ if (!ranges.length) return { text: s, spans: [] };
+ ranges.sort((x, y) => x[0] - y[0]);
+ const merged = [];
+ for (const r of ranges) {
+ const last = merged[merged.length - 1];
+ if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]);
+ else merged.push([...r]);
+ }
+ let out = "";
+ let at = 0;
+ for (const [a, b] of merged) {
+ // 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 })) };
+}
+
+/** Does `text` hold a redacted match? */
+export const hasMarks = (text) => str(text).includes(REDACT_MARK);
+
+/**
+ * Marked text with the marks DROPPED, as a read or a line of text says it:
+ * the spaces either side collapsed to one, a bracket left empty removed, and
+ * punctuation left dangling -- a comma before a full stop, a clause's comma
+ * at a sentence's start -- taken away. Only around a mark; the rest verbatim.
+ */
+export function dropMarks(marked) {
+ // 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) {
+ let L = out.replace(/[ \t]+$/, "");
+ let R = parts[i].replace(/^[ \t]+/, "");
+ if (/[(\[]$/.test(L) && /^[)\]]/.test(R)) {
+ L = L.slice(0, -1).replace(/[ \t]+$/, "");
+ R = R.slice(1).replace(/^[ \t]+/, "");
+ }
+ if ((L === "" || /[.!?…\n,;:(\[]$/.test(L)) && /^[,;:]/.test(R)) R = R.replace(/^[,;:][ \t]*/, "");
+ if (/[,;:]$/.test(L) && /^[.!?…,;:]/.test(R)) L = L.slice(0, -1);
+ const glue = L === "" || /\n$/.test(L) || R === "" || /^[\n,.!?;:…)\]]/.test(R) ? "" : " ";
+ out = L + glue + R;
+ }
+ return out.trim();
+}
+
+/** `text` as SAID with `terms` left out (a synthesized read; a chapter line). */
+export const spokenWithout = (text, terms) => {
+ const r = redactText(text, terms);
+ return r.spans.length ? dropMarks(r.text) : str(text);
+};
+
+/** The width a run of `n` marks is drawn at, in em (a sans face's average letter). */
+export const barEm = (n) => Math.round(n * 0.52 * 100) / 100;
+
+/** HTML (already escaped) with each run of marks drawn as a solid bar of its width -- no letters inside. */
+export const barsHtml = (html) =>
+ str(html).replace(MARKS_RE, (m) => `<span class="rbar" data-post-blanked="" style="width:${barEm(m.length)}em"></span>`);
+
+/** The bar's CSS, for a page that draws them. */
+export const BAR_CSS = (fg) => `.rbar { display: inline-block; height: 0.92em; vertical-align: -0.12em; background: ${fg}; border-radius: 0.12em; }`;
+
+// ---------------------------------------------------------------------------
+// The project's list and a post's markup.
+// ---------------------------------------------------------------------------
+
+/** The project's own list (`render.posts.redact`). */
+export const projectRedactOf = (render) => (Array.isArray(render?.posts?.redact) ? render.posts.redact : []);
+
+/** Every reason a list of terms (the project's, or the corpus's file) is refused. */
+export function validateRedactTerms(list, where = "render.posts.redact") {
+ if (list === undefined) return [];
+ if (!Array.isArray(list)) return [`${where} must be a list of {term, wholeWord?}`];
+ const errors = [];
+ if (list.length > POST_REDACT_MAX) errors.push(`${where} holds at most ${POST_REDACT_MAX} terms`);
+ list.forEach((t, i) => {
+ const w = `${where}[${i}]`;
+ if (!isObj(t)) return errors.push(`${w} must be {term, wholeWord?}`);
+ for (const k of Object.keys(t)) if (!["term", "wholeWord", "note"].includes(k)) errors.push(`${w}.${k} is not a key of a term (term, wholeWord, note)`);
+ if (typeof t.term !== "string" || !termWords(t.term).length) errors.push(`${w}.term must hold a word (letters or digits)`);
+ else if (t.term.length > POST_REDACT_TERM_MAX) errors.push(`${w}.term is longer than ${POST_REDACT_TERM_MAX} characters`);
+ if (t.wholeWord !== undefined && typeof t.wholeWord !== "boolean") errors.push(`${w}.wholeWord must be true or false`);
+ if (t.note !== undefined && typeof t.note !== "string") errors.push(`${w}.note must be words`);
+ });
+ return errors;
+}
+
+/** Every reason `render.posts` cannot be built (its `redact` list). */
+export function validatePostsRender(render) {
+ const p = render?.posts;
+ if (p === undefined) return [];
+ if (!isObj(p)) return ["render.posts must be an object ({redact})"];
+ return validateRedactTerms(p.redact);
+}
+
+/** Every reason a channel's posts-markup.json is refused. */
+export function validatePostsMarkup(doc, where = "posts-markup.json") {
+ if (!isObj(doc)) return [`${where} must be {"<postId>": {redact?: […], censor?: […]}}`];
+ const errors = [];
+ for (const [id, m] of Object.entries(doc)) {
+ const w = `${where} ${id}`;
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) errors.push(`${w}: not a post id`);
+ if (!isObj(m) || (m.redact !== undefined && !Array.isArray(m.redact)) || Object.keys(m).some((k) => !["redact", "censor", "note"].includes(k))) {
+ errors.push(`${w} must be {redact?: […], censor?: […]}`);
+ continue;
+ }
+ errors.push(...censorMarkupErrors(m.censor, `${w}.censor`));
+ (m.redact ?? []).forEach((r, i) => {
+ const wi = `${w}.redact[${i}]`;
+ if (!isObj(r)) return errors.push(`${wi} must be {term} or {start, end}`);
+ if (r.scope !== undefined && !POST_MARKUP_SCOPES.includes(r.scope)) errors.push(`${wi}.scope must be one of ${POST_MARKUP_SCOPES.join(", ")}`);
+ if (r.index !== undefined && !(Number.isInteger(r.index) && r.index >= 0 && r.index < 2)) errors.push(`${wi}.index must be 0 or 1 (a parent, nearest first)`);
+ if (r.term !== undefined) {
+ if (typeof r.term !== "string" || !termWords(r.term).length) errors.push(`${wi}.term must hold a word`);
+ if (r.wholeWord !== undefined && typeof r.wholeWord !== "boolean") errors.push(`${wi}.wholeWord must be true or false`);
+ } else if (!(Number.isInteger(r.start) && Number.isInteger(r.end) && r.start >= 0 && r.end > r.start)) {
+ errors.push(`${wi} must name a term, or a span {start, end} of the text (code units, end after start)`);
+ }
+ });
+ }
+ return errors;
+}
+
+/**
+ * A REDACTION as the readers resolve it: `{ terms, markup }` -- every term
+ * that applies everywhere (the corpus's and the project's) and each post's
+ * markup by `<channel>/<postId>` (the entry's `post`).
+ *
+ * @typedef {{ terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, {redact: any[]}> }} Redaction
+ */
+
+/** Is there anything to blank? */
+export const redactionOn = (red) => !!red && (normalizeTerms(red.terms).length > 0 || Object.keys(red.markup ?? {}).length > 0);
+
+/** The terms that apply to post item `entry` in `scope` (everywhere, then its markup's). */
+export function termsFor(entry, red, scope = null) {
+ const mine = red?.markup?.[str(entry?.post)]?.redact ?? [];
+ const local = mine.filter((r) => isObj(r) && typeof r.term === "string" && (!scope || !r.scope || r.scope === scope));
+ return [...normalizeTerms(red?.terms), ...normalizeTerms(local)];
+}
+
+const spansFor = (entry, red, scope, index = 0) =>
+ (red?.markup?.[str(entry?.post)]?.redact ?? []).filter(
+ (r) => isObj(r) && r.term === undefined && (r.scope ?? "text") === scope && (scope !== "parent" || (r.index ?? 0) === index),
+ );
+
+/**
+ * Post item `entry` AS PUBLISHED: a copy with every match marked (redactText)
+ * in what its card draws -- its words, its author's name and handle, the
+ * posts it answers and quotes (their words, a paraphrase, their names), the
+ * repost line, a "replying to" handle and the subjects the authors' rule
+ * reads (so a subject marked is still the subject). The entry itself is
+ * never touched; with nothing to blank, it is returned as it is.
+ *
+ * @param {Record<string, any>} entry
+ * @param {Redaction|null|undefined} red
+ */
+export function redactEntry(entry, red) {
+ if (!redactionOn(red) || !isObj(entry)) return entry;
+ const all = redactPattern(termsFor(entry, red));
+ const scoped = (scope) => redactPattern(termsFor(entry, red, scope));
+ const mark = (v, re, spans = []) => (typeof v === "string" ? redactText(v, re, { spans }).text : v);
+ const ref = (r, scope, index = 0) => {
+ if (!isObj(r)) return r;
+ const re = scoped(scope);
+ const out = { ...r };
+ for (const k of ["author", "handle"]) if (k in out) out[k] = mark(out[k], all);
+ if ("text" in out) out.text = mark(out.text, re, spansFor(entry, red, scope, index));
+ if ("paraphrase" in out) out.paraphrase = mark(out.paraphrase, re);
+ return out;
+ };
+ const out = { ...entry };
+ for (const k of ["author", "handle", "replyingTo"]) if (k in out) out[k] = mark(out[k], all);
+ out.text = mark(entry.text, scoped("text"), spansFor(entry, red, "text"));
+ if (Array.isArray(entry.subjects)) out.subjects = entry.subjects.map((h) => mark(h, all));
+ if (isObj(entry.repostedBy)) out.repostedBy = { ...entry.repostedBy, author: mark(entry.repostedBy.author, all), handle: mark(entry.repostedBy.handle, all) };
+ if (Array.isArray(entry.parents)) out.parents = entry.parents.map((p, i) => ref(p, "parent", i));
+ if (isObj(entry.quoted)) out.quoted = ref(entry.quoted, "quoted");
+ return out;
+}
diff --git a/umtool/report-to-video/post-redact.test.mjs b/umtool/report-to-video/post-redact.test.mjs
@@ -0,0 +1,112 @@
+// post-redact.mjs: words blanked from what is published -- the matcher, the
+// marks, the read without them, the card that never holds them. Made-up
+// terms only ("Quentin Example").
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ REDACT_MARK, barsHtml, dropMarks, redactEntry, redactPattern, redactText, spokenWithout, termsFor, validatePostsMarkup, validatePostsRender,
+} from "./post-redact.mjs";
+import { postCardHtml, validatePostItems } from "./post-item.mjs";
+
+const NAME = [{ term: "Quentin Example" }];
+const marks = (n) => REDACT_MARK.repeat(n);
+
+test("a term matches without case, as whole words; --substring inside words too", () => {
+ assert.equal(redactText("quentin is here", [{ term: "Quentin" }]).text, `${marks(7)} is here`);
+ // Whole word: not inside another word.
+ assert.equal(redactText("Quentinesque", [{ term: "Quentin" }]).text, "Quentinesque");
+ assert.equal(redactText("Quentinesque", [{ term: "Quentin", wholeWord: false }]).text, `${marks(7)}esque`);
+ // A possessive goes with it.
+ assert.equal(redactText("QUENTIN's mic", [{ term: "Quentin" }]).text, `${marks(9)} mic`);
+ // A bare string is a term.
+ assert.equal(redactText("hi Quentin", ["quentin"]).spans.length, 1);
+ assert.equal(redactPattern([]), null);
+});
+
+test("a phrase matches across any spaces or punctuation; its length and offsets are kept", () => {
+ const s = "Signed, quentin.\n EXAMPLE -- for real";
+ const r = redactText(s, NAME);
+ assert.equal(r.text.length, s.length);
+ assert.deepEqual(r.spans, [{ start: 8, end: 25 }]);
+ // 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.
+ assert.deepEqual(redactText("ab Quentin Example cd", NAME, { spans: [{ start: 0, end: 2 }, { start: 10, end: 20 }] }).spans, [{ start: 0, end: 2 }, { start: 3, end: 20 }]);
+});
+
+test("the read drops the match: spaces collapsed, dangling punctuation and an empty bracket taken away", () => {
+ assert.equal(spokenWithout("My name is Quentin Example.", NAME), "My name is.");
+ assert.equal(spokenWithout("Quentin Example, the author, said so", NAME), "the author, said so");
+ assert.equal(spokenWithout("Thanks, Quentin Example!", NAME), "Thanks!");
+ assert.equal(spokenWithout("hello (Quentin Example) there", NAME), "hello there");
+ assert.equal(spokenWithout("I, Quentin Example, swear", NAME), "I, swear");
+ // Paragraphs kept; nothing else touched.
+ assert.equal(spokenWithout("One , two.\n\nQuentin Example: three", NAME), "One , two.\n\nthree");
+ assert.equal(spokenWithout("no match , here", NAME), "no match , here");
+ assert.equal(dropMarks(`a ${marks(3)} b`), "a b");
+});
+
+test("the card AS PUBLISHED never holds a term: words, names, handles, context, paraphrase -- solid bars instead", () => {
+ const entry = {
+ type: "post", id: "p1", post: "subj-x/1", platform: "x", author: "Quentin Example", handle: "QuentinExample", date: "2026-10-30T04:00:00.000Z",
+ text: "Hi, I'm QUENTIN example and this is my channel", url: "https://x.com/s/status/1",
+ parents: [{ author: "Fan", handle: "fan", badge: "gold", text: "is that quentin, example?", date: "2026-10-30T03:00:00.000Z" }],
+ quoted: { author: "Other", handle: "other", badge: "gold", text: "long words", paraphrase: "He said Quentin Example out loud" },
+ redact: false,
+ };
+ // The phrase alone covers the handle that runs its words together.
+ const red = { terms: NAME };
+ const html = postCardHtml(entry, { width: 1280, height: 720, redaction: red });
+ assert.doesNotMatch(html, /quentin/i, "not even hidden");
+ assert.doesNotMatch(html, new RegExp(REDACT_MARK));
+ 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.
+ 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);
+ assert.equal(barsHtml(`x${marks(4)}y`), `x<span class="rbar" data-post-blanked="" style="width:2.08em"></span>y`);
+});
+
+test("a post's markup: a term in one scope, or a span of its archived text", () => {
+ const entry = { type: "post", id: "p1", post: "subj-x/7", text: "abc Zed def", parents: [{ text: "Zed in a parent" }], quoted: { text: "Zed quoted" } };
+ const red = { terms: [], markup: { "subj-x/7": { redact: [{ term: "Zed", scope: "parent" }, { start: 8, end: 11, scope: "text" }] } } };
+ const out = redactEntry(entry, red);
+ assert.equal(out.text, `abc Zed ${marks(3)}`);
+ assert.equal(out.parents[0].text, `${marks(3)} in a parent`);
+ assert.equal(out.quoted.text, "Zed quoted");
+ assert.deepEqual(termsFor(entry, red).map((t) => t.term), ["Zed"]);
+ assert.deepEqual(termsFor({ post: "other/1" }, red), []);
+ assert.deepEqual(validatePostsMarkup({ "7": { redact: [{ term: "Zed" }, { start: 1, end: 3, scope: "quoted" }] } }), []);
+ const bad = validatePostsMarkup({ "7": { redact: [{ start: 3, end: 1 }, { term: "Zed", scope: "elsewhere" }] }, "a/b": {}, "8": { other: 1 } });
+ assert.equal(bad.length, 4, bad.join("; "));
+});
+
+test("render.posts.redact is validated with the build's check", () => {
+ assert.deepEqual(validatePostsRender({ posts: { redact: [{ term: "Quentin Example" }, { term: "Q", wholeWord: false, note: "a note" }] } }), []);
+ const bad = validatePostsRender({ posts: { redact: [{ term: " !! " }, { term: "x", wholeWord: "yes" }, { term: "y", extra: 1 }, "bare"] } });
+ 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
@@ -15,11 +15,15 @@
// attachment's size and mtime), and a build whose key matches keeps the
// segment it has.
import { createHash } from "node:crypto";
-import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import { mkdir, readFile, rename, rm, 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 { applyFollowState, followPath, followStateAt, followStateKey, measureFollow } from "./read-follow.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));
@@ -62,7 +66,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 = [], follow = null }) {
const fps = render.fps ?? 30;
const T = plan.total;
const inputs = [];
@@ -80,11 +84,44 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
parts.push(`[${cur}][${label}]overlay=x=${x}:y=${y}:enable='between(t,${num(a)},${num(b)})'[${next}]`);
cur = next;
};
+ // READ-FOLLOW (read-follow.mjs): the card's region as the browser drew it frame by frame -- the block being read
+ // lit, the words panned -- one shot per distinct state, held for its frames (a concat list), over the card.
+ if (follow) {
+ const fi = add(["-f", "concat", "-safe", "0", "-i", follow.list]);
+ parts.push(`[${fi}:v]fps=${fps},setsar=1,setpts=PTS-STARTPTS[rf]`);
+ const next = `b${++n}`;
+ parts.push(`[${cur}][rf]overlay=x=${follow.clip.x}:y=${follow.clip.y}:eof_action=repeat[${next}]`);
+ cur = next;
+ }
if (layout.mode === "stack" && cards.media && plan.steps.length) {
const mi = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", cards.media]);
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) => {
@@ -102,6 +139,8 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
const file = files[m.i];
const crop = Array.isArray(m.crop) ? `crop=iw*${num(m.crop[2])}:ih*${num(m.crop[3])}:iw*${num(m.crop[0])}:ih*${num(m.crop[1])},` : "";
const label = `m${si}_${j}`;
+ // A censored attachment (post-censor.mjs): its chain ends in a raw label, blurred into `label`.
+ const raw = blurOn(m) ? `${label}r` : label;
if (step.kind === "image" || step.kind === "grid") {
if (m.push === true) {
const frames = Math.max(1, Math.round((until - shownFrom) * fps));
@@ -109,11 +148,11 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
parts.push(
`[${k}:v]${crop}scale=${b.width * 2}:${b.height * 2},setsar=1,` +
`zoompan=z='1+${POST_PUSH}*on/${frames}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${b.width}x${b.height}:fps=${fps},` +
- `setpts=PTS-STARTPTS+${num(shownFrom)}/TB${fadeIn(shownFrom)}[${label}]`,
+ `setpts=PTS-STARTPTS+${num(shownFrom)}/TB${fadeIn(shownFrom)}[${raw}]`,
);
} else {
const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]);
- parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}${fadeIn(shownFrom)}[${label}]`);
+ parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}${fadeIn(shownFrom)}[${raw}]`);
}
} else {
// A video or a GIF: its span from srcFrom, its first frame held from the item's start until it plays.
@@ -121,7 +160,7 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(len), "-i", file]);
parts.push(
`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,` +
- `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}[${label}]`,
+ `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}[${raw}]`,
);
if (step.sound) {
const ms = Math.round(step.at * 1000);
@@ -129,7 +168,14 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
audio.push({ label: `a${si}`, chain: `[${k}:a]aresample=${render.audioRate ?? 48000},aformat=channel_layouts=stereo,asetpts=PTS-STARTPTS,atrim=0:${num(dur)},afade=t=in:d=0.04,afade=t=out:st=${num(Math.max(0, dur - 0.06))}:d=0.06,adelay=${ms}|${ms}[a${si}]` });
}
}
+ if (raw !== label) parts.push(...blurFilters(raw, label, m, b));
lay(label, b.x, b.y, shownFrom, until);
+ // Its label ("Censored") on the frame, at the attachment's corner, while it is up.
+ const lf = blurOn(m) ? labelFilter(cur, `b${n + 1}`, m, b, { from: shownFrom, to: until, fontfile, scale: box.height / 1080 }) : null;
+ if (lf) {
+ parts.push(lf);
+ cur = `b${++n}`;
+ }
});
});
// A video attachment's words (its transcript), at the slot's foot.
@@ -186,7 +232,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 = {} }) {
+export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0 }) {
await mkdir(dir, { recursive: true });
const fonts = {
regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
@@ -204,6 +250,8 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
const html = postCardHtml(entry, {
width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl,
avatars: Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])),
+ follow: !!follow && phase === "read",
+ redaction,
});
const file = path.join(dir, `${phase}.html`);
await writeFile(file, html, "utf8");
@@ -212,8 +260,10 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
const png = path.join(dir, `${phase}.png`);
await page.screenshot({ path: png, clip: { x: 0, y: 0, width: box.width, height: box.height } });
out[phase] = png;
+ if (phase === "read" && follow) out.follow = await shootFollow(page, { follow, total, fps: render.fps ?? 30, box, dir });
}
await ctx.close();
+ if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow });
} finally {
await browser.close();
}
@@ -221,13 +271,177 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
}
/**
+ * READ-FOLLOW's FRAMES (read-follow.mjs): on the drawn card page, the pan's
+ * path from its geometry, then every frame's state (followStateAt at frame
+ * i / fps); each distinct state applied and the card's region shot once, and
+ * a concat list holding each shot for its frames. Null when nothing would
+ * move (fewer than two blocks read and no pan). `{ list, clip, shots, frames,
+ * geo, path }`.
+ */
+export async function shootFollow(page, { follow, total, fps, box, dir }) {
+ const geo = await page.evaluate(measureFollow);
+ const path0 = followPath(follow, geo);
+ const read = follow.blocks.filter((b) => b.start !== null).length;
+ if (read < 2 && !path0.segments.length) return null;
+ const r = await page.evaluate(() => {
+ const b = document.querySelector("[data-post-card]")?.getBoundingClientRect();
+ return b ? { x: b.left, y: b.top, width: b.width, height: b.height } : null;
+ });
+ if (!r) return null;
+ const x = Math.max(0, Math.floor(r.x));
+ const y = Math.max(0, Math.floor(r.y));
+ const clip = { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height) - y) };
+ const fdir = path.join(dir, "follow");
+ await rm(fdir, { recursive: true, force: true });
+ await mkdir(fdir, { recursive: true });
+ const frames = Math.max(1, Math.round(total * fps));
+ const runs = [];
+ for (let i = 0; i < frames; i += 1) {
+ const st = followStateAt(follow, path0, i / fps);
+ const key = followStateKey(st);
+ const last = runs[runs.length - 1];
+ if (last && last.key === key) last.n += 1;
+ else runs.push({ key, st, n: 1 });
+ }
+ const shots = new Map();
+ for (const run of runs) {
+ if (shots.has(run.key)) continue;
+ const file = path.join(fdir, `f-${String(shots.size).padStart(5, "0")}.png`);
+ await page.evaluate(applyFollowState, run.st);
+ await page.screenshot({ path: file, clip });
+ shots.set(run.key, file);
+ }
+ await page.evaluate(applyFollowState, null);
+ const q = (f) => `'${f.replace(/'/g, "'\\''")}'`;
+ const lines = ["ffconcat version 1.0"];
+ for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, `duration ${(run.n / fps).toFixed(6)}`);
+ lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`);
+ const list = path.join(fdir, "frames.ffconcat");
+ await writeFile(list, lines.join("\n") + "\n", "utf8");
+ return { list, clip, shots: shots.size, frames, geo, path: path0 };
+}
+
+/** 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, follow = 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, follow: !!follow }), "utf8");
+ await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
+ await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
+ };
+ // Following (read-follow.mjs): each zoom is shot as the card is at its peak -- that block lit, the words panned there.
+ let fpath = null;
+ const atZoom = async (z) => {
+ if (!follow) return;
+ fpath ??= followPath(follow, await page.evaluate(measureFollow));
+ await page.evaluate(applyFollowState, followStateAt(follow, fpath, z.span.t1));
+ };
+ const out = [];
+ try {
+ await load("zoom", null);
+ const radius = Math.round(18 * (box.height / 1080)) + 1;
+ for (const z of zooms) {
+ await atZoom(z);
+ 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 atZoom(z);
+ 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 });
+ await atZoom(z);
+ 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
* deck's footage box, or the frame), the deck's framing after it,
* build-video's encode args and ffmpeg runner, the authors' pictures
- * (`{ <handle>: absolute file }`, post-avatars.mjs). Returns the segment's path.
+ * (`{ <handle>: absolute file }`, post-avatars.mjs), the redaction it is
+ * published with (`{ terms, markup }`, post-redact-files.mjs: its matches
+ * drawn as bars, dropped from its captions). Returns the segment's path.
*/
-export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {} }) {
+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);
@@ -245,7 +459,8 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`;
}));
const key = createHash("sha256")
- .update(JSON.stringify({ v: 1, entry, box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}) }))
+ // A redaction that changes what the card draws changes the key; none leaves it as it was.
+ .update(JSON.stringify({ v: 1, entry, ...(redactionOn(redaction) ? { published: redactEntry(entry, redaction), blank: termsFor(entry, redaction) } : {}), box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}), ...(plan.follow ? { follow: plan.follow } : {}) }))
.digest("hex");
const record = postRecordPath(seg);
const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null);
@@ -254,7 +469,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 });
+ const zoomPlan = postZoomPlan(entry, render, plan.total);
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total });
+ 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()) {
@@ -262,7 +479,10 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
const m = step.items[0];
const wf = wordFiles[m.i];
if (!wf) continue;
- for (const [ci, c] of stepCaptions(step, await readMediaCues(wf)).entries()) {
+ for (const [ci, c0] of stepCaptions(step, await readMediaCues(wf)).entries()) {
+ // A redacted term is left out of the burnt-in words, as it is left out of a read.
+ const c = { ...c0, text: spokenWithout(c0.text, termsFor(entry, redaction)) };
+ if (!c.text.trim()) continue;
const textfile = path.join(cardDir, `cue-${si}-${ci}.txt`);
await writeFile(textfile, c.text, "utf8");
captions.push({ ...c, textfile });
@@ -274,7 +494,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, follow: cards.follow ?? null });
try {
await exec(ffmpeg, argv, { maxBuffer: 1 << 24 });
} catch (err) {
@@ -282,12 +502,16 @@ 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");
+ // The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides).
+ if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true });
+ 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 } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, 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)` : ""})`,
});
+ if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` });
+ 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/read-follow.mjs b/umtool/report-to-video/read-follow.mjs
@@ -0,0 +1,513 @@
+// A POST ITEM's READ-FOLLOW (umtool/docs/report-video.md, "Read-follow"; operator,
+// 3 Nov: "'I'm someone who has never watched Ember' goes on beyond the text but
+// the text doesn't scroll? That needs to be an effect, something like highlight
+// the current paragraph and panning down as needed" -- and "a subtle effect of
+// highlighting the block currently being read by making it brighter may be
+// good"): the card's words laid out in BLOCKS that match the read's parts, the
+// block being read drawn at full strength and the others dimmed a little, and a
+// card whose words are taller than their box PANNED so the block being read
+// stays in view -- where it used to shrink its words to 18 px and cut the rest.
+//
+// render.postNarration.follow = { on?: true, dim?: 0.65, ease?: 0.25 } the cut's
+// entry.follow = false | { on?, dim?, ease? } one post's (false: off)
+//
+// THE BLOCKS (followBlocks, from the entry alone): the read's parts -- a
+// narrated take's `parts` (its paragraphs, or a long paragraph's <=60-word
+// sentence runs; `para` = piece*100 + paragraph when a take reads the post it
+// answers first), else the script's parts, else (un-narrated) the card's own
+// paragraphs and sentence runs -- each matched BY ITS WORDS to the run of the
+// card's words it reads, in whichever of the card's texts it is (a parent's,
+// the post's, the quoted post's). The script is the post as a voice says it
+// ("this slash that", a shout lower-cased), so the match is by normalized
+// words, in order (a windowed longest common subsequence), never by index.
+// Words no part reads join the block before them up to a paragraph break; a
+// whole paragraph no part reads is a block that is never lit.
+//
+// THE SCHEDULE (followSchedule, the plan's `follow`): each block's start on the
+// item's clock -- a part's start in the take at the read's rate (lead + start ÷
+// rate, post-narration.mjs partStartOnItem); without parts, the read's seconds
+// shared by words; un-narrated, the reading rule's seconds (post-item.mjs
+// readSeconds, contextReadSeconds) -- and the read's end, after which every
+// block is back at full strength.
+//
+// THE PAN (followPath, from the card page's geometry, measureFollow): the post's
+// words in a window of the card (`.words`); when a block to be read is not in
+// view, the words pan (eased, FOLLOW_PAN.seconds, starting FOLLOW_PAN.lead
+// before its read) so it sits a margin below the window's top; a block taller
+// than the window pans on through it as it is read. Short posts never move.
+// A fading edge says there is more text above or below.
+//
+// The build and Play draw the same thing: the card page carries the blocks
+// (`data-post-block`), its flow (`data-post-flow`) and fades; followStateAt(t)
+// is a pure function of the item's second (seek-safe), and applyFollowState
+// sets it on the page -- in the build per frame before a screenshot
+// (post-render.mjs), in Play per tick (PostItemPlayer).
+
+import { cardText, contextReadSeconds, contextText, parentsOf, readSeconds } from "./post-item.mjs";
+import { isNarrated, narrationSchedule, partStartOnItem, pickedTake, scriptParts } from "./post-narration.mjs";
+import { cardTokens, easeOf, normWord, scriptWordsOf } from "./word-zoom.mjs";
+
+export const FOLLOW_DEFAULTS = Object.freeze({ on: true, dim: 0.65, ease: 0.25 });
+export const FOLLOW_LIMITS = Object.freeze({ dim: [0.2, 1], ease: [0, 2] });
+/** The pan: it starts `lead` s before the block's read and takes `seconds`, eased; the block sits `margin` (of the window) below its top. */
+export const FOLLOW_PAN = Object.freeze({ lead: 0.4, seconds: 0.7, margin: 0.1 });
+/** While follow is on, the words never shrink below this (px of a 1080-high frame) to fit: the card pans instead. */
+export const FOLLOW_MIN_SIZE = 28;
+/** A block's words are matched if at least this share of a part's words are found. */
+const MATCH_MIN = 0.35;
+
+const KEYS = new Set(["on", "dim", "ease"]);
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
+const str = (v) => (typeof v === "string" ? v : "");
+
+// ---------------------------------------------------------------------------
+// The knobs.
+// ---------------------------------------------------------------------------
+
+/** One follow knob's errors (`where`: its path in the manifest). `false` is off. */
+export function followKnobErrors(v, where) {
+ if (v === undefined || v === null || v === false) return [];
+ if (!isObj(v)) return [`${where} must be false (off) or { on?, dim?, ease? }`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!KEYS.has(k)) errors.push(`${where}.${k} is not a follow knob (on, dim, ease)`);
+ if (v.on !== undefined && typeof v.on !== "boolean") errors.push(`${where}.on must be true or false`);
+ for (const k of ["dim", "ease"]) {
+ if (v[k] !== undefined && !(fin(v[k]) && v[k] >= FOLLOW_LIMITS[k][0] && v[k] <= FOLLOW_LIMITS[k][1])) {
+ errors.push(`${where}.${k} must be ${FOLLOW_LIMITS[k][0]}–${FOLLOW_LIMITS[k][1]}${k === "dim" ? " (the other blocks' opacity)" : " seconds"}`);
+ }
+ }
+ return errors;
+}
+
+/** A post item's `follow` errors (validatePostItem). */
+export const validatePostFollow = (e) => followKnobErrors(e?.follow, `timeline ${e?.id ?? "?"}.follow`);
+
+const pick = (o) => (isObj(o) ? Object.fromEntries(Object.entries(o).filter(([k, v]) => KEYS.has(k) && v !== undefined && v !== null)) : {});
+
+/**
+ * One post's follow knobs: its own, else the cut's (`render.postNarration.follow`), else the defaults.
+ * @param {Record<string, any> | null | undefined} entry
+ * @param {Record<string, any>} [render]
+ * @returns {{ on: boolean, dim: number, ease: number }}
+ */
+export function followKnobs(entry, render = undefined) {
+ const r = isObj(render?.postNarration) ? render.postNarration.follow : undefined;
+ const e = entry?.follow;
+ return {
+ ...FOLLOW_DEFAULTS,
+ ...(r === false ? { on: false } : pick(r)),
+ ...(e === false ? { on: false } : pick(e)),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// THE BLOCKS: the read's parts matched to the card's words.
+// ---------------------------------------------------------------------------
+
+/** The card's texts in the order they are drawn: the posts it answers (oldest first), the post, the quoted post. */
+export function cardScopes(entry) {
+ const out = [];
+ const parents = parentsOf(entry);
+ for (let i = parents.length - 1; i >= 0; i -= 1) {
+ const t = contextText(parents[i]);
+ if (t.trim()) out.push({ scope: `parent:${i}`, text: t, ref: parents[i] });
+ }
+ out.push({ scope: "post", text: cardText(entry), ref: null });
+ if (isObj(entry?.quoted) && contextText(entry.quoted).trim()) out.push({ scope: "quoted", text: contextText(entry.quoted), ref: entry.quoted });
+ return out;
+}
+
+/** A word as matching sees it: normalized, apostrophes gone. */
+const keyOf = (w) => normWord(w).replace(/'/g, "");
+
+/** A card text's match keys: `[{ key, ci }]` (ci its card word), a "this/that" word split at its slashes. */
+function cardKeys(text) {
+ const out = [];
+ for (const t of cardTokens(text)) {
+ if (t.tok === undefined) continue;
+ for (const sub of t.tok.split("/")) {
+ const key = keyOf(sub);
+ if (key) out.push({ key, ci: t.i });
+ }
+ }
+ return out;
+}
+
+/** A part's words as keys ("slash" is the voice's reading of a "/": the card has none). */
+const partKeys = (text) => scriptWordsOf(text).map(keyOf).filter((k) => k && k !== "slash");
+
+/** The paragraph starts of a card text: the card word indices that begin a paragraph (after a blank line). */
+function paragraphStarts(text) {
+ const starts = new Set([0]);
+ let seenWord = false;
+ let next = 0;
+ for (const t of cardTokens(text)) {
+ if (t.tok !== undefined) {
+ seenWord = true;
+ next = t.i + 1;
+ } else if (seenWord && /\n\s*\n/.test(t.space)) starts.add(next);
+ }
+ return starts;
+}
+
+/**
+ * A FITTING ALIGNMENT of `a` (a part's keys) inside `b` (a card text's keys,
+ * from `lo` to `hi`): all of `a`, a compact run of `b` -- a word in common
+ * +2, a word skipped on either side -1, free before and after the run (so
+ * a common word far away never stretches the span). Returns the matched b
+ * indices, in order.
+ */
+function fitMatch(a, b, lo, hi) {
+ const n = a.length;
+ const m = hi - lo;
+ if (!n || m <= 0) return [];
+ const W = m + 1;
+ const S = new Int32Array((n + 1) * W);
+ for (let i = 1; i <= n; i += 1) S[i * W] = -i;
+ for (let i = 1; i <= n; i += 1) {
+ for (let j = 1; j <= m; j += 1) {
+ const diag = S[(i - 1) * W + j - 1] + (a[i - 1] === b[lo + j - 1].key ? 2 : -1);
+ S[i * W + j] = Math.max(diag, S[(i - 1) * W + j] - 1, S[i * W + j - 1] - 1);
+ }
+ }
+ let j = 0;
+ for (let x = 1; x <= m; x += 1) if (S[n * W + x] > S[n * W + j]) j = x;
+ const hits = [];
+ let i = n;
+ while (i > 0 && j > 0) {
+ const here = S[i * W + j];
+ const eq = a[i - 1] === b[lo + j - 1].key;
+ if (here === S[(i - 1) * W + j - 1] + (eq ? 2 : -1)) {
+ if (eq) hits.push(lo + j - 1);
+ i -= 1;
+ j -= 1;
+ } else if (here === S[(i - 1) * W + j] - 1) i -= 1;
+ else j -= 1;
+ }
+ return hits.reverse();
+}
+
+/** The parts a block map is made from: `[{ text, scope? }]` -- the take's, the script's, or (un-narrated) the card's own. */
+export function followParts(entry) {
+ if (isNarrated(entry)) {
+ const t = pickedTake(entry);
+ if (Array.isArray(t?.parts) && t.parts.length) return { source: "take", parts: t.parts.map((p) => ({ text: str(p.text), start: fin(p.start) ? p.start : null })) };
+ const script = str(t?.script).trim() ? t.script : str(entry?.narration?.script);
+ return { source: "script", parts: scriptParts(script).map((p) => ({ text: p.text })) };
+ }
+ const parts = [];
+ for (const sc of cardScopes(entry)) for (const p of scriptParts(sc.text)) parts.push({ text: p.text, scope: sc.scope });
+ return { source: "card", parts };
+}
+
+/**
+ * THE BLOCK MAP, pure, from the entry alone: `{ source, blocks: [{ k, scope,
+ * from, to, part }], parts }` -- each block a run of one card text's words
+ * (card word indices, inclusive), `part` the index of the part that reads it
+ * (null: a paragraph no part reads). Blocks are in the card's order within a
+ * scope; `k` is their id on the page (`data-post-block`).
+ */
+export function followBlocks(entry) {
+ const { source, parts } = followParts(entry);
+ const scopes = cardScopes(entry).map((sc) => ({ ...sc, keys: cardKeys(sc.text), starts: paragraphStarts(sc.text), words: cardTokens(sc.text).filter((t) => t.tok !== undefined).length }));
+ const byScope = new Map(scopes.map((sc) => [sc.scope, { sc, spans: [], cursor: 0 }]));
+ parts.forEach((p, pi) => {
+ const keys = partKeys(p.text);
+ if (!keys.length) return;
+ // Which of the card's texts it reads: its own scope (the card's parts), else the one most of its words are in.
+ let target = p.scope ? byScope.get(p.scope) : null;
+ if (!target) {
+ let best = 0;
+ for (const s of byScope.values()) {
+ const set = new Set(s.sc.keys.map((x) => x.key));
+ const share = keys.filter((k) => set.has(k)).length / keys.length;
+ if (share > best + 1e-9 || (Math.abs(share - best) < 1e-9 && s.sc.scope === "post" && share > 0)) {
+ best = share;
+ target = s;
+ }
+ }
+ if (best < 0.5) target = null;
+ }
+ if (!target) return;
+ const ck = target.sc.keys;
+ // In order: a window from where the last part ended, then (a part read out of order) the whole text.
+ let hits = fitMatch(keys, ck, target.cursor, Math.min(ck.length, target.cursor + 2 * keys.length + 40));
+ if (hits.length < Math.max(1, Math.ceil(MATCH_MIN * keys.length))) hits = fitMatch(keys, ck, 0, ck.length);
+ if (hits.length < Math.max(1, Math.ceil(MATCH_MIN * keys.length))) return;
+ target.cursor = hits[hits.length - 1] + 1;
+ target.spans.push({ part: pi, from: ck[hits[0]].ci, to: ck[hits[hits.length - 1]].ci });
+ });
+ const blocks = [];
+ for (const { sc, spans } of byScope.values()) {
+ if (!sc.words) continue;
+ // Overlaps (a part re-read) are clipped to what the earlier part did not cover.
+ const sorted = [...spans].sort((a, b) => a.from - b.from || a.part - b.part);
+ const clean = [];
+ for (const s of sorted) {
+ const last = clean[clean.length - 1];
+ const from = last ? Math.max(s.from, last.to + 1) : s.from;
+ if (from <= s.to) clean.push({ ...s, from });
+ }
+ const segs = [];
+ const gap = (from, to, prev, nextSpan) => {
+ if (from > to) return;
+ // The gap split at its paragraph starts: its first piece joins the block before (no break between),
+ // its last piece the block after; a piece between breaks is a paragraph no part reads.
+ const cuts = [from];
+ for (let i = from + 1; i <= to; i += 1) if (sc.starts.has(i)) cuts.push(i);
+ const pieces = cuts.map((c, j) => ({ from: c, to: j + 1 < cuts.length ? cuts[j + 1] - 1 : to }));
+ pieces.forEach((pc, j) => {
+ if (j === 0 && prev && !sc.starts.has(pc.from)) prev.to = pc.to;
+ else if (j === pieces.length - 1 && nextSpan && !sc.starts.has(to + 1)) nextSpan.from = pc.from;
+ else segs.push({ scope: sc.scope, from: pc.from, to: pc.to, part: null });
+ });
+ };
+ let pos = 0;
+ let prev = null;
+ for (const s of clean) {
+ const span = { scope: sc.scope, from: s.from, to: s.to, part: s.part };
+ gap(pos, s.from - 1, prev, span);
+ segs.push(span);
+ prev = span;
+ pos = s.to + 1;
+ }
+ gap(pos, sc.words - 1, prev, null);
+ segs.sort((a, b) => a.from - b.from);
+ blocks.push(...segs);
+ }
+ return { source, parts: parts.length, blocks: blocks.map((b, k) => ({ k, ...b })) };
+}
+
+/** A block map's runs for one scope, as wordsHtml wraps them: `[{ from, to, k }]`. */
+export const scopeBlocks = (map, scope) => (map?.blocks ?? []).filter((b) => b.scope === scope).map((b) => ({ from: b.from, to: b.to, k: b.k }));
+
+// ---------------------------------------------------------------------------
+// THE SCHEDULE: each block's start on the item's clock.
+// ---------------------------------------------------------------------------
+
+const wordsIn = (t) => scriptWordsOf(t).length;
+
+/**
+ * THE FOLLOW SCHEDULE, pure (the plan's `follow`): `{ dim, ease, readEnd,
+ * blocks: [{ k, scope, from, to, part, start, end }] }` -- `start` the
+ * block's read on the item's clock (null: never read), `end` the next
+ * block's start (the read's end for the last). Null when follow is off.
+ * `o.total`/`o.hold`: the item's length, its hold (an un-narrated post with a
+ * hold longer than its reading spreads the reading over it, less a second).
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {{ hold?: number | null, narration?: Record<string, any> | null }} [o]
+ */
+export function followSchedule(entry, render = undefined, { hold = null, narration = undefined } = {}) {
+ const k = followKnobs(entry, render);
+ if (!k.on) return null;
+ const map = followBlocks(entry);
+ const { parts } = followParts(entry);
+ const starts = new Array(parts.length).fill(null);
+ let readEnd;
+ if (isNarrated(entry)) {
+ const sch = narration ?? narrationSchedule(entry, render);
+ readEnd = r3(sch.at + sch.seconds);
+ const take = pickedTake(entry);
+ const timed = map.source === "take" && parts.every((p) => fin(p.start));
+ if (timed) take.parts.forEach((p, i) => (starts[i] = partStartOnItem(sch, p)));
+ else {
+ // No parts: the read's seconds shared by words.
+ const total = parts.reduce((n, p) => n + wordsIn(p.text), 0) || 1;
+ let w = 0;
+ parts.forEach((p, i) => {
+ starts[i] = r3(sch.at + (sch.seconds * w) / total);
+ w += wordsIn(p.text);
+ });
+ }
+ } else {
+ // The reading rule: each context post its context seconds, the post its reading seconds, shared by words.
+ const spans = new Map();
+ for (const sc of cardScopes(entry)) spans.set(sc.scope, sc.ref ? contextReadSeconds(sc.ref) : readSeconds(entry));
+ const reading = [...spans.values()].reduce((n, v) => n + v, 0);
+ const f = fin(hold) && hold > reading + 1 ? (hold - 1) / reading : 1;
+ let t = 0;
+ for (const sc of cardScopes(entry)) {
+ const mine = parts.map((p, i) => ({ p, i })).filter((x) => x.p.scope === sc.scope);
+ const words = mine.reduce((n, x) => n + Math.max(1, wordsIn(x.p.text)), 0) || 1;
+ const secs = spans.get(sc.scope) * f;
+ for (const x of mine) {
+ starts[x.i] = r3(t);
+ t += (secs * Math.max(1, wordsIn(x.p.text))) / words;
+ }
+ if (!mine.length) t += secs;
+ }
+ readEnd = r3(t);
+ }
+ const blocks = map.blocks.map((b) => ({ ...b, start: b.part === null ? null : starts[b.part] }));
+ // In the order they are read; each ends where the next starts.
+ const lit = blocks.filter((b) => b.start !== null).sort((a, b) => a.start - b.start || a.k - b.k);
+ lit.forEach((b, i) => (b.end = i + 1 < lit.length ? lit[i + 1].start : Math.max(b.start, readEnd)));
+ for (const b of blocks) if (b.start === null) b.end = null;
+ return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks };
+}
+
+/** The block being read at item second `s` (its k), or null (before the read's first block, or none). */
+export function followBlockAt(follow, s) {
+ let cur = null;
+ for (const b of follow?.blocks ?? []) if (b.start !== null && s >= b.start - 0.05 && (cur === null || b.start >= cur.start)) cur = b;
+ return cur ? cur.k : null;
+}
+
+// ---------------------------------------------------------------------------
+// THE PAN: the window over the post's words, from the page's geometry.
+// ---------------------------------------------------------------------------
+
+/**
+ * THE PAN's PATH, pure: `{ max, segments: [{ t0, t1, from, to }] }` -- the
+ * flow's offset (px, down) eased from `from` to `to` over each segment. `geo`
+ * is measureFollow's: the window's height `H`, the flow's `C`, each post
+ * block's `{ top, bottom }` in the flow. No overflow: no segments.
+ */
+export function followPath(follow, geo) {
+ const H = fin(geo?.H) ? geo.H : 0;
+ const C = fin(geo?.C) ? geo.C : 0;
+ const max = Math.max(0, Math.round((C - H) * 100) / 100);
+ if (!follow || max < 1 || H <= 0) return { max, segments: [] };
+ const m = Math.round(H * FOLLOW_PAN.margin);
+ const segments = [];
+ let off = 0;
+ let free = 0;
+ const moveTo = (target, at) => {
+ const to = Math.round(clamp(target, 0, max) * 100) / 100;
+ if (Math.abs(to - off) < 1) return;
+ const t0 = r3(Math.max(0, at, free));
+ const t1 = r3(t0 + FOLLOW_PAN.seconds);
+ segments.push({ t0, t1, from: off, to });
+ off = to;
+ free = t1;
+ };
+ const read = (follow.blocks ?? []).filter((b) => b.scope === "post" && b.start !== null && geo.blocks?.[b.k]).sort((a, b) => a.start - b.start);
+ for (const b of read) {
+ const { top, bottom } = geo.blocks[b.k];
+ const h = bottom - top;
+ // Not in view (above the window, or running past its foot): it pans to sit a margin below the top.
+ if (top < off - 0.5 || bottom > off + H - m / 2 + 0.5) moveTo(top - m, b.start - FOLLOW_PAN.lead);
+ // Taller than the window: on through it as it is read (the reading line taken as even through its words).
+ const room = H - 2 * m;
+ if (h > room && room > 0) {
+ const over = h - room;
+ const n = Math.ceil(over / (0.6 * room));
+ const span = Math.max(0.1, b.end - b.start);
+ for (let i = 1; i <= n; i += 1) {
+ const target = top - m + (over * i) / n;
+ const line = target - (top - m) + room * 0.6;
+ moveTo(target, Math.min(b.end - FOLLOW_PAN.seconds, b.start + (span * line) / h));
+ }
+ }
+ }
+ return { max, segments };
+}
+
+/** The flow's offset at item second `s` on the path. */
+export function followOffsetAt(path, s) {
+ let off = 0;
+ for (const g of path?.segments ?? []) {
+ if (s >= g.t1) off = g.to;
+ else if (s >= g.t0) return g.from + (g.to - g.from) * easeOf("inOut", (s - g.t0) / Math.max(1e-6, g.t1 - g.t0));
+ else break;
+ }
+ return off;
+}
+
+/** An eased ramp 0 -> 1 over [a, a + d]. */
+const ramp = (s, a, d) => (d <= 0 ? (s >= a ? 1 : 0) : easeOf("inOut", (s - a) / d));
+
+/**
+ * THE STATE at item second `s`, pure and seek-safe: `{ op: { <k>: opacity },
+ * offset, fadeTop, fadeBottom, current }`. The block being read rises to full
+ * over `ease` (centred on its start) while the one before falls back to
+ * `dim`; before the first block's start the first is lit; after the read's
+ * end every block rises back to full. A map of fewer than two read blocks is
+ * never dimmed. `path`: followPath's (null: no pan).
+ */
+export function followStateAt(follow, path, s) {
+ const op = {};
+ if (!follow) return { op, offset: 0, fadeTop: 0, fadeBottom: 0, current: null };
+ const read = follow.blocks.filter((b) => b.start !== null).sort((a, b) => a.start - b.start);
+ const e = follow.ease;
+ const after = ramp(s, follow.readEnd, e);
+ if (read.length >= 2) {
+ const lit = new Map();
+ read.forEach((b, i) => {
+ const up = i === 0 ? 1 : ramp(s, b.start - e / 2, e);
+ const down = i + 1 < read.length ? ramp(s, read[i + 1].start - e / 2, e) : 0;
+ lit.set(b.k, Math.min(up, 1 - down));
+ });
+ for (const b of follow.blocks) {
+ const l = Math.max(lit.get(b.k) ?? 0, after);
+ op[b.k] = Math.round((follow.dim + (1 - follow.dim) * l) * 1000) / 1000;
+ }
+ }
+ const offset = Math.round(followOffsetAt(path, s) * 4) / 4;
+ const max = path?.max ?? 0;
+ const edge = 24;
+ return {
+ op,
+ offset,
+ fadeTop: max >= 1 ? Math.round(clamp(offset / edge, 0, 1) * 100) / 100 : 0,
+ fadeBottom: max >= 1 ? Math.round(clamp((max - offset) / edge, 0, 1) * 100) / 100 : 0,
+ current: read.length ? followBlockAt(follow, s) ?? read[0].k : null,
+ };
+}
+
+/** A state's key: two frames with the same key draw the same card (the build shoots each key once). */
+export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom]);
+
+// ---------------------------------------------------------------------------
+// In the page: self-contained (the build passes them to page.evaluate; Play
+// calls them on its frame's document). They reach for nothing outside.
+// ---------------------------------------------------------------------------
+
+/** The page's geometry for the pan: the window's height, the flow's, each post block's top and bottom in the flow. */
+export function measureFollow(doc = document) {
+ const words = doc.querySelector("[data-post-words]");
+ const flow = doc.querySelector("[data-post-flow]");
+ if (!words || !flow) return null;
+ const had = flow.style.transform;
+ flow.style.transform = "none";
+ const fr = flow.getBoundingClientRect();
+ const blocks = {};
+ for (const el of Array.from(flow.querySelectorAll("[data-post-block]"))) {
+ let top = Infinity;
+ let bottom = -Infinity;
+ for (const r of Array.from(el.getClientRects())) {
+ if (r.width === 0 && r.height === 0) continue;
+ top = Math.min(top, r.top);
+ bottom = Math.max(bottom, r.bottom);
+ }
+ if (top < bottom) blocks[el.getAttribute("data-post-block")] = { top: Math.round((top - fr.top) * 100) / 100, bottom: Math.round((bottom - fr.top) * 100) / 100 };
+ }
+ const out = { H: words.clientHeight, C: Math.round(fr.height * 100) / 100, blocks };
+ flow.style.transform = had;
+ return out;
+}
+
+/** Set a follow state on the page: each block's opacity, the flow's offset, the fading edges. */
+export function applyFollowState(state, doc = document) {
+ const op = (state && state.op) || {};
+ for (const el of Array.from(doc.querySelectorAll("[data-post-block]"))) {
+ const o = op[el.getAttribute("data-post-block")];
+ const v = typeof o === "number" && o < 0.9995 ? String(o) : "";
+ if (el.style.opacity !== v) el.style.opacity = v;
+ }
+ const flow = doc.querySelector("[data-post-flow]");
+ if (flow) {
+ const t = state && state.offset ? `translateY(${-state.offset}px)` : "";
+ if (flow.style.transform !== t) flow.style.transform = t;
+ }
+ for (const [side, v] of [["top", state ? state.fadeTop : 0], ["bottom", state ? state.fadeBottom : 0]]) {
+ const el = doc.querySelector(`[data-post-fade="${side}"]`);
+ if (el) el.style.opacity = String(v || 0);
+ }
+ if (doc.body) doc.body.setAttribute("data-post-follow-block", state && state.current !== null && state.current !== undefined ? String(state.current) : "");
+}
diff --git a/umtool/report-to-video/read-follow.test.mjs b/umtool/report-to-video/read-follow.test.mjs
@@ -0,0 +1,223 @@
+// read-follow.mjs: a post item's read-follow -- the read's parts matched to the
+// card's words (a long paragraph split into parts, a script that reads "this
+// slash that" and lower-cases a shout), the schedule on the item's clock (a
+// take's part starts divided by the read's rate; un-narrated, the reading
+// rule), the pan that keeps the block being read in view, and the card page.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { postCardHtml, postItemPlan, validatePostItem } from "./post-item.mjs";
+import { postSegmentArgs } from "./post-render.mjs";
+import { speakableText, validatePostNarrationRender } from "./post-narration.mjs";
+import {
+ FOLLOW_DEFAULTS, FOLLOW_PAN, followBlockAt, followBlocks, followKnobs, followOffsetAt, followPath, followSchedule, followStateAt, followStateKey,
+} from "./read-follow.mjs";
+import { cardWordsOf } from "./word-zoom.mjs";
+
+const LONG_PARA =
+ "Believe it or not, two people can read the same thing and come to a different conclusion. That doesn't make me a leftist, nor does it mean I'm pretending not to get it. " +
+ "At first I didn't have much context but looking into things, Strawb appears to be a malicious actor and Maria appears to be malicious as well. " +
+ "I think the entire thing was blown WAY out of proportion and a lot of people are being really obtuse/vindictive about it. " +
+ "For example Ember did not infiltrate this group chat, it was actually Strawb who was invited later to the chat, and Ember was one of the three original members.";
+const TEXT = `Normally I don't respond to stuff like this.\n\nKirsche you have lost the plot.\n\n${LONG_PARA}\n\nThat is all.`;
+const base = (o = {}) => ({
+ type: "post", id: "p1", post: "obvious-x/2115851166383063324", platform: "x", author: "MR. OBVIOUS", handle: "ObviousRises",
+ date: "2026-10-29T17:00:03.000Z", text: TEXT, ...o,
+});
+/** A take read part by part, as the orchestrator's generator makes one: the script's parts, each timed. */
+function narrated(entry, { rate } = {}) {
+ const script = speakableText(entry.text);
+ const paras = script.split(/\n\n/);
+ const parts = [];
+ let at = 0;
+ paras.forEach((p, para) => {
+ // The long paragraph read in two runs of sentences (as scriptParts splits one over 60 words).
+ const runs = p.split(/ (?=At first|For example)/);
+ for (const text of runs) {
+ const seconds = text.split(/\s+/).length / 3;
+ parts.push({ n: parts.length + 1, para, text, start: Math.round(at * 100) / 100, seconds: Math.round(seconds * 100) / 100 });
+ at += seconds + 0.5;
+ }
+ });
+ return {
+ ...entry,
+ narration: { script, takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: Math.round(at * 100) / 100, script, parts }], ...(rate ? { rate } : {}) },
+ };
+}
+const wordsOf = (entry, b) => cardWordsOf(entry.text).slice(b.from, b.to + 1).join(" ");
+
+test("the knobs: on by default, dim 0.65, ease 0.25; the cut's, then the post's; false is off", () => {
+ assert.deepEqual(followKnobs(base()), FOLLOW_DEFAULTS);
+ assert.deepEqual(followKnobs(base(), { postNarration: { follow: { dim: 0.5 } } }), { on: true, dim: 0.5, ease: 0.25 });
+ assert.equal(followKnobs(base({ follow: false }), { postNarration: { follow: { dim: 0.5 } } }).on, false);
+ assert.equal(followKnobs(base({ follow: { on: true } }), { postNarration: { follow: { on: false } } }).on, true);
+ assert.deepEqual(validatePostItem(base({ follow: { dim: 0.1 } })), ["timeline p1.follow.dim must be 0.2–1 (the other blocks' opacity)"]);
+ assert.deepEqual(validatePostItem(base({ follow: "yes" })), ["timeline p1.follow must be false (off) or { on?, dim?, ease? }"]);
+ assert.deepEqual(validatePostItem(base({ follow: false })), []);
+ assert.deepEqual(validatePostNarrationRender({ postNarration: { follow: { ease: 0.4, dim: 0.7 } } }), []);
+ assert.match(validatePostNarrationRender({ postNarration: { follow: { pan: 1 } } }).join(), /follow.pan is not a follow knob/);
+ assert.equal(postItemPlan(base({ follow: false })).follow, undefined);
+});
+
+test("parts -> blocks: each part's words found on the card in order, a long paragraph split where its parts split", () => {
+ const e = narrated(base());
+ const { blocks, source } = followBlocks(e);
+ assert.equal(source, "take");
+ assert.equal(blocks.length, 6);
+ assert.deepEqual(blocks.map((b) => b.part), [0, 1, 2, 3, 4, 5]);
+ assert.equal(wordsOf(e, blocks[0]), "Normally I don't respond to stuff like this.");
+ assert.equal(wordsOf(e, blocks[1]), "Kirsche you have lost the plot.");
+ // The long paragraph: three blocks, each a run of its sentences, covering it without a gap.
+ assert.match(wordsOf(e, blocks[2]), /^Believe it or not, .* pretending not to get it\.$/);
+ assert.match(wordsOf(e, blocks[3]), /^At first .* malicious as well\. I think .*obtuse\/vindictive about it\.$/);
+ assert.match(wordsOf(e, blocks[4]), /^For example .* original members\.$/);
+ assert.equal(blocks[3].from, blocks[2].to + 1);
+ assert.equal(blocks[4].from, blocks[3].to + 1);
+ assert.equal(wordsOf(e, blocks[5]), "That is all.");
+ assert.equal(blocks[5].to, cardWordsOf(e.text).length - 1);
+});
+
+test("parts -> blocks: a parent read first (para 0) then the post (para 100+), matched by words, not by index; an unread quote is a block never lit", () => {
+ const parent = { handle: "someone", text: "I think she's just super paranoid" };
+ const e = base({ text: "And that's fair.\n\nJUST keep in mind this/that is a lot.", parents: [parent], quoted: { handle: "q", text: "A quoted post nobody reads aloud." } });
+ e.narration = {
+ script: "x",
+ takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 9, parts: [
+ { n: 1, para: 0, text: "I think she's just super paranoid", start: 0, seconds: 2 },
+ { n: 2, para: 100, text: "And that's fair.", start: 2.6, seconds: 1.5 },
+ { n: 3, para: 101, text: "just keep in mind this slash that is a lot!", start: 4.7, seconds: 3 },
+ ] }],
+ };
+ const { blocks } = followBlocks(e);
+ const by = (scope) => blocks.filter((b) => b.scope === scope);
+ assert.deepEqual(by("parent:0").map((b) => [b.from, b.to, b.part]), [[0, 5, 0]]);
+ assert.deepEqual(by("post").map((b) => [b.part, b.from, b.to]), [[1, 0, 2], [2, 3, 10]]);
+ assert.deepEqual(by("quoted").map((b) => b.part), [null]);
+ const sch = followSchedule(e);
+ assert.deepEqual(sch.blocks.filter((b) => b.start !== null).map((b) => b.start), [0.4, 3, 5.1]);
+ assert.equal(sch.blocks.find((b) => b.scope === "quoted").start, null);
+});
+
+test("the schedule: a part starts at lead + its start in the take ÷ the read's rate", () => {
+ const e = narrated(base(), { rate: 1.25 });
+ const plan = postItemPlan(e);
+ const parts = e.narration.takes[0].parts;
+ const f = plan.follow;
+ assert.equal(f.blocks.length, parts.length);
+ parts.forEach((p, i) => assert.equal(f.blocks[i].start, Math.round((0.4 + p.start / 1.25) * 1000) / 1000));
+ assert.equal(f.readEnd, Math.round((0.4 + e.narration.takes[0].seconds / 1.25) * 1000) / 1000);
+ // Each block ends where the next starts, the last at the read's end.
+ assert.equal(f.blocks[0].end, f.blocks[1].start);
+ assert.equal(f.blocks[5].end, f.readEnd);
+ // The cut's rate does the same.
+ const g = postItemPlan(narrated(base()), { postNarration: { rate: 1.25 } }).follow;
+ assert.deepEqual(g.blocks.map((b) => b.start), f.blocks.map((b) => b.start));
+ assert.equal(followBlockAt(f, f.blocks[3].start + 0.01), 3);
+ assert.equal(followBlockAt(f, f.blocks[3].start - 0.2), 2);
+});
+
+test("un-narrated: the card's own paragraphs and sentence runs, paced by the reading rule", () => {
+ const e = base();
+ const f = postItemPlan(e).follow;
+ assert.equal(f.source, "card");
+ assert.ok(f.blocks.length >= 4);
+ assert.equal(f.blocks[0].start, 0);
+ // The post's reading time (clamped 3-15 s) is shared by words; the read ends there.
+ assert.equal(f.readEnd, 15);
+ for (let i = 1; i < f.blocks.length; i += 1) assert.ok(f.blocks[i].start > f.blocks[i - 1].start);
+ // A hold longer than the reading spreads it, less a second.
+ assert.equal(postItemPlan(base({ hold: 61 })).follow.readEnd, 60);
+});
+
+test("the state: the block being read at full, the others dimmed, eased; back to full after the read", () => {
+ const f = postItemPlan(narrated(base())).follow;
+ const at = (s) => followStateAt(f, null, s);
+ const s3 = f.blocks[3].start;
+ const mid = at((s3 + f.blocks[4].start) / 2);
+ assert.equal(mid.current, 3);
+ assert.equal(mid.op[3], 1);
+ assert.equal(mid.op[2], 0.65);
+ assert.equal(mid.op[0], 0.65);
+ // Halfway through the ease, the two meet.
+ const half = at(s3);
+ assert.ok(half.op[3] > 0.65 && half.op[3] < 1 && half.op[2] > 0.65 && half.op[2] < 1);
+ assert.equal(at(s3 + f.ease / 2 + 0.001).op[3], 1);
+ // Before the first block's start the first is lit; after the read everything is back.
+ assert.equal(at(0).op[0], 1);
+ assert.equal(at(0).op[1], 0.65);
+ const after = at(f.readEnd + f.ease + 0.01);
+ assert.ok(Object.values(after.op).every((v) => v === 1));
+ // Seek-safe: the same second gives the same state, whichever came before.
+ assert.equal(followStateKey(at(s3 + 0.1)), followStateKey(at(s3 + 0.1)));
+ // One block read: nothing dims.
+ const one = postItemPlan(base({ text: "Just one short line." })).follow;
+ assert.deepEqual(followStateAt(one, null, 1).op, {});
+});
+
+test("the pan: short cards never move; a tall one keeps the block being read in view, starting before its read", () => {
+ const f = postItemPlan(narrated(base())).follow;
+ // Six blocks stacked 200 px apart in a flow of 1200 px.
+ const blocks = Object.fromEntries(f.blocks.map((b, i) => [b.k, { top: i * 200, bottom: i * 200 + 180 }]));
+ assert.deepEqual(followPath(f, { H: 1300, C: 1200, blocks }).segments, []);
+ const geo = { H: 500, C: 1200, blocks };
+ const path = followPath(f, geo);
+ assert.equal(path.max, 700);
+ assert.ok(path.segments.length >= 2);
+ const m = Math.round(500 * FOLLOW_PAN.margin);
+ for (const b of f.blocks) {
+ // Once its read is under way (past the pan), the block is inside the window.
+ const s = Math.min(b.end - 0.01, b.start + FOLLOW_PAN.seconds);
+ const off = followOffsetAt(path, s);
+ const { top, bottom } = blocks[b.k];
+ assert.ok(top >= off - 0.5 && bottom <= off + 500 + 0.5, `block ${b.k} in view at ${s}: ${top}-${bottom} in ${off}-${off + 500}`);
+ }
+ // A pan starts before the block it brings into view is read.
+ const first = path.segments[0];
+ const target = f.blocks.find((b) => blocks[b.k].bottom > 500 - m / 2);
+ assert.ok(first.t0 < target.start && first.t0 >= target.start - FOLLOW_PAN.lead - 0.001);
+ // Never past the end of the words.
+ assert.ok(path.segments.every((g) => g.to <= 700 && g.to >= 0));
+ // The fading edges: more below at the start, more above at the end.
+ const s0 = followStateAt(f, path, 0);
+ assert.equal(s0.fadeTop, 0);
+ assert.equal(s0.fadeBottom, 1);
+ const end = followStateAt(f, path, f.readEnd + 1);
+ assert.equal(end.offset, 700);
+ assert.equal(end.fadeBottom, 0);
+ assert.equal(end.fadeTop, 1);
+});
+
+test("the pan: a block taller than the window pans on through it while it is read", () => {
+ const f = postItemPlan(narrated(base())).follow;
+ const blocks = Object.fromEntries(f.blocks.map((b, i) => [b.k, i === 2 ? { top: 100, bottom: 1300 } : i < 2 ? { top: i * 50, bottom: i * 50 + 40 } : { top: 1300 + (i - 2) * 50, bottom: 1340 + (i - 2) * 50 }]));
+ const path = followPath(f, { H: 400, C: 1550, blocks });
+ const b = f.blocks[2];
+ const inside = path.segments.filter((g) => g.t0 >= b.start - FOLLOW_PAN.lead - 0.001 && g.t1 <= b.end + 0.001);
+ assert.ok(inside.length >= 3, `${inside.length} pans through the tall block`);
+ assert.ok(followOffsetAt(path, b.end - 0.01) >= 1300 - 400);
+});
+
+test("the card page: the blocks wrapped on the card, the post's words in a flow that pans, never shrunk below the readable size", () => {
+ const e = narrated(base({ text: `${TEXT}\n\n${LONG_PARA}\n\n${LONG_PARA}` }));
+ const html = postCardHtml(e, { width: 1600, height: 900, follow: true });
+ assert.match(html, /data-post-flow=""/);
+ assert.match(html, /data-post-fade="bottom"/);
+ assert.match(html, /<span class="fblock" data-post-block="0"><span data-w="post:0">Normally<\/span>/);
+ assert.match(html, /data-post-follow="\d+"/);
+ // The fit script's floor: FOLLOW_MIN_SIZE (28) at 900/1080, not the old 18.
+ assert.match(html, /var min = 23;/);
+ const off = postCardHtml(e, { width: 1600, height: 900 });
+ assert.doesNotMatch(off, /data-post-block|data-post-flow/);
+ assert.match(off, /var min = 15;/);
+});
+
+test("the encode: the follow frames are a concat list laid over the card's region, before the attachments", () => {
+ const e = base({ text: "Hello there." });
+ const plan = postItemPlan(e);
+ const argv = postSegmentArgs({
+ entry: e, box: { width: 1600, height: 900 }, plan, layout: { mode: "text", card: { x: 0, y: 0, width: 100, height: 100 }, slot: null }, cards: { read: "/c/read.png" },
+ files: [], render: { fps: 30 }, outPath: "/o.mp4", follow: { list: "/c/follow/frames.ffconcat", clip: { x: 210, y: 40, width: 1180, height: 820 } },
+ });
+ const fc = argv[argv.indexOf("-filter_complex") + 1];
+ assert.ok(argv.join(" ").includes("-f concat -safe 0 -i /c/follow/frames.ffconcat"));
+ assert.match(fc, /\[1:v\]fps=30,setsar=1,setpts=PTS-STARTPTS\[rf\];\[b0\]\[rf\]overlay=x=210:y=40:eof_action=repeat\[b1\]/);
+});
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]"));
+});