commit c86b4e9c1fe54597483184de8e654b859d081797
parent d72e37ceafd05ff41f1cb8ed57341d2ac73e4770
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 16:47:12 -0500
umtool: READ-FOLLOW on a post item -- the block being read lit, the others dimmed a little, and a card taller than its box panned so that block stays in view (operator: "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")
read-follow.mjs (pure): the read's parts -- a take's `parts` (paragraphs, or a
long paragraph's <=60-word sentence runs; a parent read first as para 0, the
post as 100+), else the script's parts, else the card's own paragraphs --
matched to the card's words by a fitting alignment of normalized words, in
order (the script says "this slash that" and lower-cases a shout: never by
index); words no part reads join their neighbour up to a paragraph break. The
schedule is each block's start on the item's clock (lead + part start / rate;
un-narrated, the reading rule), carried as the plan's `follow`. The pan's path
comes from the page's geometry: a block not in view pans (0.7 s, eased,
0.4 s before its read) to sit a margin below the window's top; a block taller
than the window pans on through it; short cards never move. Fading edges say
there is more above/below.
The card page wraps the blocks (data-post-block) and puts the post's words in a
flow; following, they never shrink below 28 px @1080 to fit. The build shoots
the card's region once per distinct state (followStateAt per frame, deduped)
and lays a concat list of the shots over the card; word zooms are shot as the
card is at their peak. Knobs: render.postNarration.follow {on, dim 0.65,
ease 0.25} (posts narrate --cut follow=… follow.dim=… follow.ease=…) and
entry.follow false | {…} (posts set-item follow=on|off|auto follow.dim=…).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 902 insertions(+), 33 deletions(-)
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -2350,7 +2350,7 @@ 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"]);
+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. */
export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words"]);
/** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */
@@ -2358,7 +2358,7 @@ 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?,
+ * is `{ hold?, mediaLayout?, redact?, follow?: false | { on?, dim?, ease? }, media?: { <i>: { start?, end?, mute?,
* crop?, push?, words? } }, 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
@@ -2383,7 +2383,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)) {
@@ -2726,7 +2738,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
@@ -2745,7 +2757,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;
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -41,7 +41,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.",
@@ -225,13 +225,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;
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -56,7 +56,7 @@ 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]",
" [parent.<i>.paraphrase=\"…\"|off] [narration.rate=0.8–1.5|narration.<mix knob>=…] [--json]",
@@ -564,11 +564,17 @@ 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 {
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=, 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);
@@ -582,6 +588,7 @@ 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;
}
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -65,6 +65,7 @@
"./post-narration": "./post-narration.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-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -32,6 +32,7 @@ import {
isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration,
} from "./post-narration.mjs";
import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, 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"]);
@@ -230,7 +231,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);
@@ -464,6 +467,8 @@ export function validatePostItem(e) {
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;
}
@@ -689,18 +694,22 @@ export const hueOf = (s) => {
* 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) {
+export function wordsHtml(text, blurred, scope = null, hl = null, blocks = null) {
const set = new Set(blurred.map((h) => h.replace(/^@/, "").toLowerCase()));
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;
- return `<span data-w="${esc(scope)}:${t.i}"${lit ? " data-w-hl=\"\"" : ""}>${word(t.tok)}</span>`;
+ 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("");
}
@@ -751,19 +760,27 @@ export function nameHtml(who, { redact, cls = "" }) {
* 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>,
- * highlight?: { scope: string, from: number, to: number, color: string } | null }} o
+ * highlight?: { scope: string, from: number, to: number, color: string } | null, follow?: boolean }} o
*/
-export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null }) {
+export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = 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.
+ const fmap = follow ? followBlocks(entry) : null;
+ const blk = (scope) => (fmap ? scopeBlocks(fmap, scope) : null);
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;
@@ -787,7 +804,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, contextText(p) ? `parent:${i}` : null, hlOf(`parent:${i}`))}</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>`);
@@ -796,20 +813,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, "quoted", hlOf("quoted"))}</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, "post", hlOf("post"))}</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>
@@ -852,10 +869,15 @@ 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; }${highlight ? `
+.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; }` : ""}
</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}"` : ""}>${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-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -31,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). */
@@ -161,7 +163,8 @@ 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", "words"]);
const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]);
@@ -474,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). */
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -15,11 +15,12 @@
// 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 { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters } from "./post-narration.mjs";
+import { applyFollowState, followPath, followStateAt, followStateKey, measureFollow } from "./read-follow.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;
@@ -63,7 +64,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, zooms = [] }) {
+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 = [];
@@ -81,6 +82,15 @@ 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]`);
@@ -211,7 +221,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 = {}, zooms = [] }) {
+export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], follow = null, total = 0 }) {
await mkdir(dir, { recursive: true });
const fonts = {
regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
@@ -229,6 +239,7 @@ 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",
});
const file = path.join(dir, `${phase}.html`);
await writeFile(file, html, "utf8");
@@ -237,15 +248,67 @@ 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 });
+ if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, follow });
} finally {
await browser.close();
}
return out;
}
+/**
+ * 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)))));
@@ -257,22 +320,30 @@ export const zoomShotScale = (zooms) => Math.min(4, Math.max(2, Math.ceil(Math.m
* 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 }) {
+async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, 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 }), "utf8");
+ await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, 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();
@@ -305,11 +376,13 @@ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotU
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) });
}
@@ -367,7 +440,7 @@ 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 } : {}) }))
+ .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 } : {}), ...(plan.follow ? { follow: plan.follow } : {}) }))
.digest("hex");
const record = postRecordPath(seg);
const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null);
@@ -377,7 +450,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
}
const cardDir = path.join(outDir, "cards", `post-${entry.id}`);
const zoomPlan = postZoomPlan(entry, render, plan.total);
- const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan });
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, 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 = [];
@@ -398,7 +471,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, zooms });
+ 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) {
@@ -406,12 +479,15 @@ 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, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs } } : {}) }, null, 2) + "\n", "utf8");
+ // 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\]/);
+});