Archilyzer · Source

archilyzer

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

commit 0c202936be657594085ee46aa10a61219d29df96
parent 47386ef525a5a7fbdac0d521f3339d99050e4157
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue,  3 Nov 2026 17:14:48 -0500

Merge lane/read-follow: the block being read lit, the rest dimmed, and a tall card panned to keep it in view -- blocks matched to the take's parts by words (comment, quoted post, paragraphs), timed by lead + part start / rate; deterministic in the render, live in Play, the block map in the post bench; posts narrate --cut follow=, posts set-item follow=

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 3+++
Mumtool/components/projects/PostBench.tsx | 4++++
Aumtool/components/projects/PostFollowPanel.tsx | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PostItemPlayer.tsx | 36+++++++++++++++++++++++++++++++++++-
Mumtool/docs/cli.md | 4++--
Mumtool/docs/knobs.md | 15+++++++++++++++
Mumtool/docs/report-video.md | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/post-narration.spec.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 31++++++++++++++++++++++++++-----
Mumtool/lib/report/postNarrationCli.mjs | 7+++++--
Mumtool/lib/report/postsCli.mjs | 11+++++++++--
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/post-item.mjs | 47+++++++++++++++++++++++++++++++++++------------
Mumtool/report-to-video/post-narration.mjs | 7+++++--
Mumtool/report-to-video/post-render.mjs | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Aumtool/report-to-video/read-follow.mjs | 513+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/read-follow.test.mjs | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
17 files changed, 1205 insertions(+), 36 deletions(-)

diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -7,6 +7,7 @@ import { withEditNotes } from "@/lib/report/guard"; 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"; @@ -172,6 +173,8 @@ export async function GET(request: Request) { 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 } }); diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -8,6 +8,7 @@ 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 PostZoomPanel from "./PostZoomPanel"; @@ -132,6 +133,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, @@ -298,6 +301,7 @@ export default function PostBench({ 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} 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&apos;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/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -3,6 +3,7 @@ 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"; @@ -24,6 +25,11 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar // 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 }; @@ -70,11 +76,21 @@ function applyZoom(doc: Document, z: LiveZoom | null, zf: number, hl: number, bo /** 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; @@ -343,10 +359,19 @@ export default function PostItemPlayer({ 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([]); @@ -370,6 +395,7 @@ export default function PostItemPlayer({ 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}"]`); @@ -381,7 +407,7 @@ export default function PostItemPlayer({ }); setZooms(out); return true; - }, [entry, zoomTimes, box.height]); + }, [entry, zoomTimes, box.height, follow]); const onFrameLoad = useCallback(() => { let tries = 0; const tick = () => { @@ -401,6 +427,11 @@ export default function PostItemPlayer({ 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 ( @@ -418,6 +449,9 @@ export default function PostItemPlayer({ 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 && ( diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -82,8 +82,8 @@ 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] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings) | -| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration`. Refused in the build's words (**exit 1**) | +| `posts 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 | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -735,6 +735,21 @@ its bounds. Its bench is the post bench's **word zoom** block; Play the cut zoom | 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 source backlog (Sources · Prioritize · Re-sweep when complete) The Overview tab's **sources** line (`components/projects/report/SourceBacklog.tsx`, `lib/report/sourceBacklog.*`): for each diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -709,6 +709,59 @@ only while it is up and before the attachments: the attachments are never covere 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 on-screen deck (`render.chrome`) Its knobs — the stamp's moment and count per clip, the stamp's look and words, the markers, a clip's sync and diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -325,6 +325,63 @@ test("A WORD ZOOM: Get word timings (the editor's transcription), click a word - 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 @@ -2351,7 +2351,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, 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. */ @@ -2359,7 +2359,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?, 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 @@ -2384,7 +2384,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)) { @@ -2737,7 +2749,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 @@ -2756,7 +2768,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 @@ -43,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.", @@ -227,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; 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]", " [media.<i>.blur=on|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"|off]", @@ -576,6 +576,12 @@ 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 if (/^media\.\d+\.blur(\.(strength|label|boxes))?$/.test(k)) { @@ -589,7 +595,7 @@ export function postItemPatchOf(pairs) { 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=, media.<i>.blur[.strength|.label|.boxes]=, 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); @@ -603,6 +609,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 @@ -68,6 +68,7 @@ "./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-item.mjs b/umtool/report-to-video/post-item.mjs @@ -35,6 +35,7 @@ import { 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"]); @@ -233,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); @@ -467,6 +470,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; } @@ -730,18 +735,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(""); } @@ -792,15 +801,22 @@ 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, - * redaction?: { terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, any> } | null }} o + * 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 = {}, highlight = null, redaction = null }) { +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); @@ -808,7 +824,9 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p 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; @@ -832,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, 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>`); @@ -841,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, "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="">&#x21bb; ${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> @@ -897,11 +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; }${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; }` : ""} ${BAR_CSS(pal.fg)} </style></head> -<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}">${barsHtml(body)} +<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-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, 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"; @@ -65,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, 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 = []; @@ -83,6 +84,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]`); @@ -222,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 = {}, zooms = [], redaction = null }) { +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 : "", @@ -240,6 +250,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", redaction, }); const file = path.join(dir, `${phase}.html`); @@ -249,15 +260,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, redaction }); + if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, 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))))); @@ -269,22 +332,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, redaction = null }) { +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 }), "utf8"); + 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(); @@ -317,11 +388,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) }); } @@ -387,7 +460,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box })); const key = createHash("sha256") // 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 } : {}) })) + .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); @@ -397,7 +470,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, redaction }); + 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 = []; @@ -421,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, 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) { @@ -429,12 +502,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\]/); +});