commit ab20ff53f622c5379e4b5c60afafbfd57548f8c9
parent 1ee27dc0f8053fd27a0eacf98ba80bf6abd76cc7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 01:28:30 -0500
Merge lane/thread-reads: a read never narrates hidden text -- a take that reads the post it answers or quotes draws the card as the conversation, oldest first; the post being read shown in full and lit, then shrunk and dimmed as the next fades in below (operator: "show the parent in full then transition in the reply as the parent shrinks and goes dim"); part roles (posts roles), thread knobs per cut and item (set-item thread.*, the bench's thread read panel), the build's guard; fix: the combo validator no longer refuses render.posts.redact
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
27 files changed, 1848 insertions(+), 60 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts
@@ -8,6 +8,7 @@ import { StaleToken, StructureRefused, manifestToken, updatePostFx, updatePostIt
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 { threadLayout } from "umtool-report-to-video/post-thread";
import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxCli.mjs";
import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs";
import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs";
@@ -49,7 +50,9 @@ async function itemOf(project: { dir: string }, manifest: Record<string, unknown
let m = manifest;
if (take) m = (await resolveTakeManifest(project.dir, take, { base: manifest })).manifest as Record<string, unknown>;
const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Entry[];
- return { item: tl.find((e) => e?.type === "post" && e.id === id) ?? null, manifest: m };
+ const at = tl.findIndex((e) => e?.type === "post" && e.id === id);
+ // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in).
+ return { item: at >= 0 ? tl[at] : null, prev: at > 0 ? tl[at - 1] : null, manifest: m };
}
/** A project file under posts-media/, never outside it (its real path checked). */
@@ -170,6 +173,7 @@ export async function GET(request: Request) {
} catch (e) {
return new Response(e instanceof Error ? e.message : String(e), { status: 500 });
}
+ const followOn = q.get("phase") !== "media" && followKnobs(found.item, (found.manifest.render ?? render) as Record<string, unknown>).on;
const html = postCardHtml(found.item, {
width: w, height: h, avatars,
palette: (render.palette ?? {}) as Record<string, string>,
@@ -177,7 +181,9 @@ export async function GET(request: Request) {
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,
+ follow: followOn,
+ // A threaded card (post-thread.mjs): its tiles, as the plan's follow.thread has them.
+ thread: followOn ? threadLayout(found.item, (found.manifest.render ?? render) as Record<string, unknown>, { prev: found.prev }) : null,
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
@@ -9,6 +9,7 @@ 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 PostThreadPanel from "./PostThreadPanel";
import BlurBoxPad from "./BlurBoxPad";
import PostNarrationPanel from "./PostNarrationPanel";
import PostComboPanel from "./PostComboPanel";
@@ -30,6 +31,8 @@ import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
// its sound, a crop of any attachment, an image's push-in,
// and a video's words: Transcribe asks the EDITOR's
// transcription (a job on a local worker), never ASR here
+// thread a read of the post it answers or quotes: what each is on
+// screen while it is read and after (PostThreadPanel)
// context the post it quotes, the posts it answers: a paraphrase of
// a long one, drawn in place of its words with a
// "paraphrased" label (its own text kept, shown beside)
@@ -56,7 +59,7 @@ const CROPS: Array<{ label: string; crop: number[] | null }> = [
];
export default function PostBench({
- project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null,
+ project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null,
}: {
project: string;
entry: Entry;
@@ -71,6 +74,8 @@ export default function PostBench({
render?: Record<string, unknown>;
/** Its combo (post-combo.mjs): the attachment the cut plays again here, its count, its group. */
combo?: ComboInfo | null;
+ /** The timeline entry before it in the cut (post-thread.mjs: a parent that is that item is carried in). */
+ before?: Record<string, unknown> | null;
}) {
const router = useRouter();
const [entry, setEntry] = useState<Entry>(initial);
@@ -78,7 +83,7 @@ export default function PostBench({
const [token, setToken] = useState(initialToken);
const [status, setStatus] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
- const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry, render) as PostPlan)), [entry, initial, initialPlan, render]);
+ const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry, render, { prev: before }) as PostPlan)), [entry, initial, initialPlan, render, before]);
const total = plan.total;
const [s, setS] = useState(0);
const [playing, setPlaying] = useState(false);
@@ -140,6 +145,8 @@ export default function PostBench({
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,
+ // Its thread read (post-thread.mjs): its knobs, each null when it is the cut's.
+ thread: e.thread && typeof e.thread === "object" ? { parent: null, quoted: null, carry: null, reveal: null, shrink: null, dim: null, seconds: null, pan: null, ...(e.thread as Record<string, unknown>) } : null,
media: Object.fromEntries(
(e.media ?? []).map((m, i) => [
i,
@@ -308,6 +315,7 @@ export default function PostBench({
}}
/>
<PostFollowPanel entry={entry} plan={plan} render={render} s={s} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} />
+ <PostThreadPanel entry={entry} plan={plan} render={render} before={before} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} />
<PostNarrationPanel
project={project}
entry={entry}
diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx
@@ -49,8 +49,9 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj
entry={entry}
token={await manifestToken(project.dir)}
box={{ width: box.width, height: box.height }}
- plan={postItemPlan(entry, render) as unknown as PostPlan}
+ plan={postItemPlan(entry, render, { prev: at > 0 ? tl[at - 1] : null }) as unknown as PostPlan}
render={render}
+ before={at > 0 ? tl[at - 1] : null}
combo={combo}
back={{ href: back, label: fromPlay ? "‹ Back to the cut" : "‹ The Cut tab" }}
prev={k > 0 ? neighbours[k - 1] : null}
diff --git a/umtool/components/projects/PostFollowPanel.tsx b/umtool/components/projects/PostFollowPanel.tsx
@@ -17,7 +17,7 @@ import type { PostPlan } from "./review/PostItemPlayer";
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 "));
+const SCOPE_NAME = (s: string) => (s === "post" ? "post" : s === "quoted" ? "quoted" : s.startsWith("media:") ? "attachment" : s.replace("parent:", "parent "));
export default function PostFollowPanel({
entry, plan, render, s, setS, setEntry,
@@ -105,7 +105,8 @@ export default function PostFollowPanel({
<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(" ");
+ // A part read off an attachment (post-thread.mjs: a screenshot's words) has no words on the card.
+ const head = b.from === null || b.to === null ? "(read off the attachment)" : 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
@@ -119,7 +120,7 @@ export default function PostFollowPanel({
<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 ? "…" : ""}
+ {b.from !== null && b.to !== null && b.to + 1 - b.from > 8 ? "…" : ""}
</span>
</button>
</li>
diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx
@@ -0,0 +1,169 @@
+"use client";
+
+import { useMemo } from "react";
+import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread";
+import { followKnobs } from "umtool-report-to-video/read-follow";
+import { pickedTake } from "umtool-report-to-video/post-narration";
+import type { PostPlan } from "./review/PostItemPlayer";
+
+// ---------------------------------------------------------------------------
+// A POST's THREAD READ ON THE BENCH (report-to-video/post-thread.mjs;
+// knobs.md, "Thread reads"; operator, 4 Nov: "you're never narrating hidden
+// text ... show the parent in full then transition in the reply as the parent
+// shrinks and goes dim"): its read PIECE BY PIECE -- the text each piece reads
+// (the post it answers, the post it quotes, his words, an attachment's), when
+// it starts (click: the playhead there) -- and what each context post is on
+// screen (full, excerpt, context, carry, hidden), the shrink, the dim and their
+// seconds, the pan's. A setting that would narrate a post the card hides is
+// shown here, and refused by Save (the writer's guard). The knobs are the
+// bench's draft (its Save writes them, as hold and follow).
+// ---------------------------------------------------------------------------
+
+type Entry = Record<string, unknown> & { id: string; parents?: Array<Record<string, unknown>>; quoted?: Record<string, unknown> };
+type Thread = Partial<{ parent: string | string[]; quoted: string; carry: "auto" | boolean; reveal: boolean; shrink: number; dim: number; seconds: number; pan: number }>;
+
+const ROLE_NAME = (r: string | null) =>
+ r === null ? "no text on the card" : r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r === "parent:0" ? "the post it answers" : r.startsWith("parent:") ? "the post that answers" : `attachment ${Number(r.slice(6)) + 1}'s words`;
+
+export default function PostThreadPanel({
+ entry, plan, render, before, setS, setEntry,
+}: {
+ entry: Entry;
+ plan: PostPlan;
+ render: Record<string, unknown>;
+ before: Record<string, unknown> | null;
+ setS: (s: number) => void;
+ setEntry: (f: (e: Entry) => Entry) => void;
+}) {
+ const own = (entry.thread ?? undefined) as Thread | undefined;
+ const k = threadKnobs(entry, render) as Required<Thread>;
+ const layout = useMemo(() => threadLayout(entry, render, { prev: before }), [entry, render, before]);
+ const roles = useMemo(() => partRoles(entry) as Array<{ role: string | null; source: string }>, [entry]);
+ const pieces = useMemo(() => readPieces(entry, roles) as Array<{ role: string | null; parts: number[] }>, [entry, roles]);
+ const errors = useMemo(() => threadReadErrors(entry, render, { prev: before, followOn: (followKnobs(entry, render) as { on: boolean }).on }) as string[], [entry, render, before]);
+ const take = pickedTake(entry) as { parts?: Array<{ start: number; text?: string }> } | null;
+ const startOf = (part: number) => plan.follow?.blocks.find((b) => b.part === part)?.start ?? null;
+ const setOwn = (patch: Thread) =>
+ setEntry((e) => {
+ const next: Record<string, unknown> = { ...((e.thread as Thread | undefined) ?? {}), ...patch };
+ for (const [kk, v] of Object.entries(next)) if (v === undefined || v === null || v === "") delete next[kk];
+ const out = { ...e };
+ if (Object.keys(next).length) out.thread = next;
+ else delete out.thread;
+ return out;
+ });
+ const parents = Array.isArray(entry.parents) ? entry.parents : [];
+ const parentMode = (i: number) => {
+ const p = own?.parent;
+ return Array.isArray(p) ? p[i] ?? "" : typeof p === "string" ? p : "";
+ };
+ const setParent = (i: number, v: string) => {
+ const list = parents.map((_, j) => parentMode(j) || "auto");
+ list[i] = v || "auto";
+ setOwn({ parent: list.every((m) => m === "auto") ? undefined : list.length === 1 ? list[0] : list });
+ };
+ const modeShown = (scope: string) => layout.tiles.find((t: { scope: string; mode: string }) => t.scope === scope)?.mode ?? "—";
+ const num = (key: "shrink" | "dim" | "seconds" | "pan", label: string, step: number) => (
+ <label className="flex items-center gap-1">
+ {label}
+ <input
+ type="number"
+ min={THREAD_LIMITS[key][0]}
+ max={THREAD_LIMITS[key][1]}
+ step={step}
+ className="w-16"
+ value={typeof own?.[key] === "number" ? (own[key] as number) : ""}
+ placeholder={String(k[key] ?? THREAD_DEFAULTS[key])}
+ onChange={(e) => setOwn({ [key]: e.target.value === "" ? undefined : Number(e.target.value) })}
+ data-post-thread-knob={key}
+ />
+ </label>
+ );
+ if (!parents.length && !entry.quoted) return null;
+ return (
+ <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]" data-post-thread-panel="" data-threaded={layout.on ? "1" : "0"}>
+ <div className="mb-2 flex flex-wrap items-center gap-2">
+ <h2 className="micro m-0">thread read</h2>
+ <span className="text-text-2" data-post-thread-summary="">
+ {layout.on ? "the card draws the conversation: each post read is shown in full, then shrinks and dims as the next comes in" : roles.length ? "his words only: the posts it answers are context" : "not narrated: the card as it is"}
+ </span>
+ </div>
+ {pieces.length > 0 && (
+ <ol className="m-0 mb-2 list-none space-y-0.5 p-0" data-post-thread-pieces="">
+ {pieces.map((p, i) => {
+ const at = startOf(p.parts[0]);
+ const words = p.parts.map((n) => take?.parts?.[n]?.text ?? "").join(" ").trim();
+ return (
+ <li key={i} data-post-thread-piece={p.role ?? "none"} data-source={roles[p.parts[0]]?.source}>
+ <button type="button" disabled={at === null} className="flex w-full gap-2 px-1 text-left disabled:opacity-60" onClick={() => at !== null && setS(at)} title={`parts ${p.parts.map((n) => n + 1).join(", ")}`}>
+ <span className="w-12 shrink-0 font-mono tabular-nums">{at === null ? "—" : `${at.toFixed(1)}s`}</span>
+ <span className="w-32 shrink-0 text-text-2">
+ {ROLE_NAME(p.role)}
+ {roles[p.parts[0]]?.source === "stored" ? "" : " ·"}
+ </span>
+ <span className="min-w-0 truncate">{words.split(/\s+/).slice(0, 10).join(" ")}…</span>
+ </button>
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ {parents.map((_, i) => (
+ <label key={i} className="flex items-center gap-1">
+ {i === 0 ? "the post it answers" : "its parent"}
+ <select value={parentMode(i)} onChange={(e) => setParent(i, e.target.value)} data-post-thread-mode={`parent:${i}`} aria-label={`what parent ${i} is on screen`}>
+ <option value="">the cut's ({modeShown(`parent:${i}`)})</option>
+ {THREAD_MODES.filter((m: string) => m !== "auto").map((m: string) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ </label>
+ ))}
+ {entry.quoted && (
+ <label className="flex items-center gap-1">
+ the quoted post
+ <select value={typeof own?.quoted === "string" ? own.quoted : ""} onChange={(e) => setOwn({ quoted: e.target.value || undefined })} data-post-thread-mode="quoted" aria-label="what the quoted post is on screen">
+ <option value="">the cut's ({modeShown("quoted")})</option>
+ {THREAD_MODES.filter((m: string) => m !== "auto" && m !== "carry").map((m: string) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ <label className="flex items-center gap-1">
+ carry
+ <select
+ value={own?.carry === undefined ? "" : String(own.carry)}
+ onChange={(e) => setOwn({ carry: e.target.value === "" ? undefined : e.target.value === "auto" ? "auto" : e.target.value === "true" })}
+ data-post-thread-carry=""
+ aria-label="carry the item before in"
+ >
+ <option value="">the cut's ({String(k.carry)})</option>
+ <option value="auto">auto</option>
+ <option value="true">on</option>
+ <option value="false">off</option>
+ </select>
+ </label>
+ {num("shrink", "shrink", 0.02)}
+ {num("dim", "dim", 0.05)}
+ {num("seconds", "over", 0.1)}
+ {num("pan", "pan", 0.1)}
+ </div>
+ <p className="m-0 mt-1 text-text-2">
+ full: in full while read · excerpt: only what is read · context: small and dim · carry: the item before, giving way · hidden: not drawn (never read). Hidden and excerpt redraw the card once saved.
+ </p>
+ {errors.length > 0 && (
+ <ul className="m-0 mt-1 list-disc pl-4 text-[var(--color-bad,#e5484d)]" data-post-thread-errors="">
+ {errors.map((er, i) => (
+ <li key={i}>{er}</li>
+ ))}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -30,6 +30,8 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar
// 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).
+// A THREADED card (post-thread.mjs) is the same: its tiles' sizes and
+// strengths are part of the state (the page's slots and tiles set by it).
// ---------------------------------------------------------------------------
type Rect = { x: number; y: number; width: number; height: number };
@@ -82,7 +84,15 @@ export type FollowPlan = {
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 }>;
+ blocks: Array<{ k: number; scope: string; from: number | null; to: number | null; part: number | null; start: number | null; end: number | null }>;
+ /** A threaded card (post-thread.mjs threadSchedule): each tile's size and strength on the item's clock. */
+ thread?: {
+ shrink: number;
+ dim: number;
+ seconds: number;
+ pan: number;
+ tiles: Array<{ scope: string; mode: string; read: boolean; from: number[]; to: number[]; t0: number; t1: number }>;
+ };
};
export type PostPlan = {
@@ -454,6 +464,8 @@ export default function PostItemPlayer({
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}
+ data-post-thread={follow?.thread ? String(follow.thread.tiles.length) : undefined}
+ data-post-thread-tiles={followNow?.tiles ? Object.entries(followNow.tiles).map(([sc, v]) => `${sc}=${v[0]}/${v[1]}`).join(" ") : undefined}
className="pointer-events-none absolute inset-0 overflow-hidden"
>
{mix && voiceTake && (
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -83,8 +83,9 @@ 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] [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 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>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [--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. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `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 roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) |
+| `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=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). 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
@@ -792,6 +792,24 @@ the card live on the same states the build shoots.
| `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`) | — |
+## Thread reads (every part of a read on screen while it is said)
+
+A narrated post item that reads the post it answers or quotes draws the conversation
+([report-video.md](report-video.md#thread-reads): the roles, the modes, the motion, the guard;
+`report-to-video/post-thread.mjs`). The cut's knobs ride on `render.postNarration.thread`
+(`updatePostNarrationRender`), one post's on the item (`updatePostItem`), each refused in the
+build's words (`threadKnobErrors`); a `thread`/`follow` change that would narrate a post the card
+hides is refused with the fix. Its bench is the post bench's **thread read** block; Play the cut
+draws the same states the build shoots.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| `render.postNarration.thread.parent` / `.quoted` — what a context post is on screen: `auto` (default: full when read, carried in when it is the item before, else context), `full`, `excerpt`, `context`, `carry` (parents), `hidden` | — | `umtool posts narrate <p> --cut thread.parent=full thread.quoted=context` (`default` clears one) | — |
+| `render.postNarration.thread.carry` — carry a parent that is the item before: `auto` (default), `true`, `false` · `.reveal` — the post read next fades in under the one before (default true) | — | `umtool posts narrate <p> --cut thread.carry=off thread.reveal=off` | — |
+| `render.postNarration.thread.shrink` — a context post's size, 0.3–1 (default 0.62) · `.dim` — its opacity, 0.15–1 (default 0.5) · `.seconds` — the change, 0–3 s (default 0.7) · `.pan` — the column's move, 0.1–3 s (default 0.7) | — | `umtool posts narrate <p> --cut thread.shrink=0.55 thread.dim=0.4 thread.seconds=0.9 thread.pan=1` | — |
+| `thread` on a post item — `{parent?, quoted?, carry?, reveal?, shrink?, dim?, seconds?, pan?}` over the cut's (`parent` one mode, or a list, nearest parent first) | post bench, **thread read**: the post it answers / its parent / the quoted post (the cut's, or a mode), **carry**, **shrink**, **dim**, **over**, **pan**; the guard's refusals listed before Save | `umtool posts set-item <p> <item> thread.parent=excerpt` · `thread.parent.1=hidden` · `thread.quoted=context` · `thread.carry=off` · `thread.shrink=0.5` … · `thread=auto` (the cut's) | `POST /api/report/post-item {project, op: "set", id, patch: {thread}, token}` (an object merges; `null` clears) |
+| a part's role — the text it reads: `parent:<i>`, `quoted`, `post`, `media:<i>` (stored, else inferred) | post bench, **thread read**: the read piece by piece (click one: the playhead at its start; `·` marks an inferred role) | `umtool posts roles <p> [<item> …]` (list, with the guard's verdict) · `--write` (store the inferred roles) · `<item> --set 3=parent:0,4=post` (`off`: inferred again) | — (`updatePostNarration {partRoles: {take, roles}}`) |
+
## The combo counter
A post item that plays an attachment an earlier post item of the cut already played gets a fighting-game badge,
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -762,6 +762,78 @@ at their peak). **Play** sets the same states on its card page each tick; the po
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)).
+### Thread reads
+
+A narrated post item whose read reads the POST IT ANSWERS or THE POST IT QUOTES is drawn as
+the conversation, and every part of the read is on screen, legible and lit while it is said
+(`report-to-video/post-thread.mjs`; operator, 3–4 Nov: "when narrating a reply parent you're
+just narrating hidden text. Rework the thread system so you're never narrating hidden text"
+— "If it's a big reply that we're reading, show the parent in full then transition in the
+reply as the parent shrinks and goes dim"; and earlier "start with the first post in the
+chain, then reveal the rest of the thread as we read through, pushing older posts up top").
+Before it, a parent was drawn 22 px high and clamped to four lines while a voice read all of
+it, and read-follow only knew the post's own words.
+
+**The pieces and their roles.** The narration batch assembles a read as PIECES — [the post it
+answers (voice `leo`, his own `zac`)] + [the post it quotes] + [his words] (a parent that is
+the item just before in the cut is left out) — each split into parts, `para` = piece × 100 +
+paragraph. Each part has a ROLE, the text it reads: `parent:<i>` (nearest first), `quoted`,
+`post`, or `media:<i>` (words read off an attachment — the screenshot of a reply he answers).
+A part's role is its own (`parts[k].role`: the import stores the inferred role of every new
+take's parts; `umtool posts roles <p> --write` stores them on the takes before it; `--set n=role`
+sets one by hand), else INFERRED: the parts grouped by piece, each piece matched to the text it
+reads by its WORD PAIRS (a bag of words matched a short parent to a 700-word post), against
+every form of each text (as written, its paraphrase, as a voice says it — draftScript), a new
+piece taking the next text along; a piece no text holds is an attachment's when the post has a
+picture, else no text's. Checked over the three Mr. Obvious cuts (395 reads): every read's
+pieces in the batch's order, his words last.
+
+**The card.** Narrated, following (read-follow on), with a context post drawn, the card is a
+column of TILES in one flow — the parents oldest first, his post, the quoted post inside it —
+each tile's words at the size that fits it alone in the card (at least 28 px of a 1080 frame),
+whole: no line clamp. read-follow's blocks span every tile (the parts matched to their roles'
+texts), and its pan moves the whole column. What each context post is on screen is its MODE:
+
+| mode | on screen |
+|---|---|
+| `full` | in full, the frame's focus while it is read (a long one panned paragraph by paragraph) |
+| `excerpt` | as full, its paragraphs no part reads left out (labelled "excerpt") |
+| `context` | small and dim the whole item; never read |
+| `carry` | a parent the read skips because it is the item just before: it opens as that item ended — in full — and gives way as the read begins (no cold cut) |
+| `hidden` | not drawn; never read |
+| `auto` (default) | `full` when the read reads it, `carry` when it is the item before (`carry: "auto"`), else `context` |
+
+**The motion.** A tile read is in full while it is read; when the next piece starts it SHRINKS
+(`shrink`, 0.62) about its corner and DIMS (`dim`, 0.5) over `seconds` (0.7), starting 0.4 s
+before that piece, while the tile read next is REVEALED under it (`reveal`) — his reply
+fades in as the parent gives way; older up top. A quoted post is never shrunk: it dims once
+read. The column pans (`pan` s, eased, from the same moment) so a new piece sits under a strip
+(30 % of the window) of the post it answers, its first block whole in view; a later block
+running past the window's foot is brought up just far enough; a block taller than the window
+pans on through it. A conversation shorter than the window is centred in it. A part read off
+an attachment lights no block (all dim: the picture is the thing being read).
+
+```jsonc
+"render": { "postNarration": { "thread": { "parent": "auto", "quoted": "auto", "carry": "auto", "reveal": true,
+ "shrink": 0.62, "dim": 0.5, "seconds": 0.7, "pan": 0.7 } } }, // the cut's
+"thread": { "parent": ["full", "context"], "shrink": 0.5 } // one post's, over the cut's (parent: one mode, or one per parent, nearest first)
+```
+
+**The guard.** NEVER NARRATE HIDDEN TEXT: the build's lint (`validateThreadReads`) refuses a
+post item whose take reads a part of a post drawn `hidden` or `context`, a part no text on the
+card holds, or a threaded read with read-follow off — each with the fix (show it, set the
+part's role, or re-make the read without it). The item writer refuses a `thread`/`follow`
+change that would do it (`updatePostItem`: the post bench's Save, `posts set-item`), and the
+post bench's **thread read** block shows the refusal before Save.
+
+**The render and Play** are read-follow's: the state at a second carries each tile's scale and
+opacity (`tiles`), the page's slots are closed up to match (`data-thread-slot`,
+`data-thread-tile`), the geometry is measured once at full size and worked out under the scales
+(threadGeoAt), and the build shoots each distinct state once. The plan's `follow.thread` is
+the tiles' schedule; `postItemPlan(entry, render, { prev })` takes the item before it (the
+build, Play, the bench and the card route pass it). Not narrated, or with no context post
+drawn, the card is as it was.
+
### The combo counter
When a post item's attachment is one an EARLIER post item of the cut already played —
diff --git a/umtool/e2e/thread-reads.spec.ts b/umtool/e2e/thread-reads.spec.ts
@@ -0,0 +1,160 @@
+import { test, expect, type FrameLocator, type Page } from "@playwright/test";
+import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// THREAD READS (report-to-video/post-thread.mjs; knobs.md, "Thread reads";
+// operator, 4 Nov: "when narrating a reply parent you're just narrating hidden
+// text ... show the parent in full then transition in the reply as the parent
+// shrinks and goes dim"). Fixture: e2e/fixtures/post-narration-fixture.mjs's
+// p-13, made a reply here: the post it answers read first (three parts), then
+// his reply (two parts) -- as the narration batch assembles a read.
+//
+// THREAD_READS_SHOTS=<dir> screenshots there
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DIR = path.join(HERE, "..", ".e2e-song", "reports", "post-narration-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const PROJECT = "reports/post-narration-fixture";
+const SHOTS = process.env.THREAD_READS_SHOTS ?? null;
+
+const say = (i: number) => `Paragraph ${i} of the neighbour's post goes on about the noise from the street, ${"and the lights in the hall that keep going out without any warning at all, ".repeat(2)}until it stops at mark ${i}.`;
+const PARENT = [1, 2, 3].map(say).join("\n\n");
+const REPLY = "That is exactly what I was saying yesterday morning to everyone.\n\nWe should have bought the generator back in the spring.";
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+});
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+ rmSync(path.join(DIR, "notes.json"), { force: true });
+ // p-13 a reply, read [the post it answers] + [his words], part by part (3 s a part, the batch's pauses).
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ const e = m.timeline.find((x: { id: string }) => x.id === "p-13");
+ e.text = REPLY;
+ e.parents = [{ id: "900", author: "Some Neighbour", handle: "neighbour_one", date: "2026-10-29T10:00:00.000Z", text: PARENT }];
+ const paras = [...PARENT.split("\n\n").map((t, k) => ({ para: k, text: t })), ...REPLY.split("\n\n").map((t, k) => ({ para: 100 + k, text: t }))];
+ const starts = [0, 3.6, 7.2, 11, 14.6];
+ e.narration = {
+ script: REPLY,
+ takes: [{ file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "leo+zac", seconds: 17.6, script: `${PARENT}\n\n${REPLY}`, parts: paras.map((p, i) => ({ n: i + 1, ...p, start: starts[i], seconds: 3 })) }],
+ pick: 0,
+ };
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+});
+
+/** A block's box against the card's window (the words' window), in the card page. */
+const inWindow = (frame: FrameLocator, k: string) =>
+ frame.locator("[data-post-words]").evaluate((w, k) => {
+ const r = w.getBoundingClientRect();
+ const b = (w.querySelector(`[data-post-block="${k}"]`) as HTMLElement).getBoundingClientRect();
+ return { top: b.top - r.top, bottom: b.bottom - r.top, height: r.height, op: (w.querySelector(`[data-post-block="${k}"]`) as HTMLElement).style.opacity };
+ }, k);
+const tileOf = (frame: FrameLocator, scope: string) =>
+ frame.locator(`[data-thread-slot="${scope}"]`).evaluate((el) => {
+ const t = el.querySelector("[data-thread-tile]") as HTMLElement;
+ const w = document.querySelector("[data-post-words]")!.getBoundingClientRect();
+ const r = el.getBoundingClientRect();
+ return { state: el.getAttribute("data-thread-state"), transform: t.style.transform, opacity: t.style.opacity, top: r.top - w.top, bottom: r.bottom - w.top };
+ });
+
+/** Play opened paused `at` seconds into p-13. */
+async function playAt(page: Page, at: number) {
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-13", at }));
+ const player = page.locator('[data-post-play="p-13"]');
+ await expect(player).toHaveAttribute("data-post-thread", "2", { timeout: 15_000 });
+ const frame = page.frameLocator('[data-post-card-frame="read"]');
+ await expect(frame.locator("body")).toHaveAttribute("data-post-thread", "2", { timeout: 15_000 });
+ // Play opens there (give or take its first tick).
+ await expect.poll(async () => Math.abs(Number(await player.getAttribute("data-post-s")) - at)).toBeLessThan(0.3);
+ return { player, frame };
+}
+
+test("NEVER NARRATE HIDDEN TEXT, in Play: the post it answers in full and lit while its parts play -- in the window, panned to -- his reply hidden under it", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ for (const [at, part] of [[1.5, 0], [5.5, 1], [9.2, 2]] as const) {
+ const { player, frame } = await playAt(page, at);
+ // The block being read is the parent's, part by part.
+ const k = await player.getAttribute("data-post-follow-block");
+ await expect(frame.locator(`[data-thread-tile="parent:0"] [data-post-block="${k}"]`)).toHaveCount(1);
+ const blocks = await frame.locator('[data-thread-tile="parent:0"] [data-post-block]').evaluateAll((els) => els.map((el) => el.getAttribute("data-post-block")));
+ expect(blocks[part]).toBe(k);
+ await expect(player).toHaveAttribute("data-post-thread-tiles", /parent:0=1\/1 post=1\/0/);
+ await expect.poll(async () => (await tileOf(frame, "post")).opacity).toBe("0");
+ const t = await tileOf(frame, "parent:0");
+ expect(t.state).toBe("focus");
+ expect(t.transform).toBe("");
+ // Lit (full strength) and inside the window.
+ await expect.poll(async () => (await inWindow(frame, k!)).op).toBe("");
+ const b = await inWindow(frame, k!);
+ expect(b.top).toBeGreaterThanOrEqual(-1);
+ expect(b.bottom).toBeLessThanOrEqual(b.height + 1);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `thread-parent-part-${part + 1}.png`) });
+ }
+});
+
+test("THE REPLY COMES IN: as his first part starts the parent shrinks and dims (it stays above), his reply is revealed, lit and in the window", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ // Mid-change (his part at 0.4 + 11 = 11.4 s; the change from 11.0 s over 0.7 s).
+ {
+ const { player, frame } = await playAt(page, 11.35);
+ const tiles = (await player.getAttribute("data-post-thread-tiles"))!;
+ const [, sc, op] = /parent:0=([\d.]+)\/([\d.]+)/.exec(tiles)!;
+ expect(Number(sc)).toBeGreaterThan(0.62);
+ expect(Number(sc)).toBeLessThan(1);
+ expect(Number(op)).toBeLessThan(1);
+ await expect.poll(async () => (await tileOf(frame, "parent:0")).transform).toMatch(/^scale\(0\.\d+\)$/);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "thread-transition.png") });
+ }
+ for (const [at, part] of [[12.5, 0], [16, 1]] as const) {
+ const { player, frame } = await playAt(page, at);
+ await expect(player).toHaveAttribute("data-post-thread-tiles", "parent:0=0.62/0.5 post=1/1");
+ const k = await player.getAttribute("data-post-follow-block");
+ const mine = await frame.locator('[data-thread-tile="post"] [data-post-block]').evaluateAll((els) => els.map((el) => el.getAttribute("data-post-block")));
+ expect(mine[part]).toBe(k);
+ // The page set to the state Play is at (each tick applies it).
+ await expect.poll(async () => (await tileOf(frame, "parent:0")).transform).toBe("scale(0.62)");
+ const parent = await tileOf(frame, "parent:0");
+ expect(parent.state).toBe("context");
+ expect(parent.opacity).toBe("0.5");
+ await expect.poll(async () => (await inWindow(frame, k!)).op).toBe("");
+ const b = await inWindow(frame, k!);
+ expect(b.top).toBeGreaterThanOrEqual(-1);
+ expect(b.bottom).toBeLessThanOrEqual(b.height + 1);
+ // Older up top: the parent's foot is still in the window, above his post.
+ const post = await tileOf(frame, "post");
+ expect(parent.bottom).toBeGreaterThan(0);
+ expect(parent.bottom).toBeLessThanOrEqual(post.top + 1);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `thread-reply-part-${part + 1}.png`) });
+ }
+});
+
+test("the bench: the read piece by piece, what each post is on screen; hiding the post it reads is shown and refused by Save", async ({ page }) => {
+ await page.setViewportSize({ width: 1500, height: 1100 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-13"));
+ const panel = page.locator("[data-post-thread-panel]");
+ await expect(panel).toHaveAttribute("data-threaded", "1");
+ await expect(panel.locator("[data-post-thread-piece]")).toHaveCount(2);
+ await expect(panel.locator('[data-post-thread-piece="parent:0"]')).toContainText("the post it answers");
+ await expect(panel.locator('[data-post-thread-piece="post"]')).toContainText("his words");
+ // A piece's row puts the playhead at its start (his first part: 0.4 + 11).
+ await panel.locator('[data-post-thread-piece="post"] button').click();
+ await expect(page.locator("[data-post-bench-clock]")).toHaveText(/^11\.4 \//);
+ // Hide the post it reads: the guard says so here, and Save is refused.
+ await panel.locator('[data-post-thread-mode="parent:0"]').selectOption("hidden");
+ await expect(panel.locator("[data-post-thread-errors]")).toContainText("drawn hidden");
+ await page.locator("[data-post-bench-save]").click();
+ await expect(page.locator("[data-post-bench-error]")).toContainText("drawn hidden");
+ expect(JSON.parse(readFileSync(MANIFEST, "utf8")).timeline.find((x: { id: string }) => x.id === "p-13").thread).toBeUndefined();
+ // A shrink of its own saves.
+ await panel.locator('[data-post-thread-mode="parent:0"]').selectOption("");
+ await panel.locator('[data-post-thread-knob="shrink"]').fill("0.5");
+ await page.locator("[data-post-bench-save]").click();
+ await expect.poll(() => JSON.parse(readFileSync(MANIFEST, "utf8")).timeline.find((x: { id: string }) => x.id === "p-13").thread).toEqual({ shrink: 0.5 });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "thread-bench.png") });
+});
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -58,6 +58,8 @@ import {
} from "./knobs.mjs";
import { validateNarration } from "umtool-report-to-video/narration";
import { validatePostItem, validatePostItems } from "umtool-report-to-video/post-item";
+import { threadReadErrors } from "umtool-report-to-video/post-thread";
+import { followKnobs } from "umtool-report-to-video/read-follow";
import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umtool-report-to-video/post-avatars";
import { POST_NARRATION_DEFAULTS, validatePostNarrationRender } from "umtool-report-to-video/post-narration";
import { termWords, validatePostsRender } from "umtool-report-to-video/post-redact";
@@ -2352,7 +2354,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", "follow"]);
+export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact", "follow", "thread"]);
/** 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. */
@@ -2360,7 +2362,8 @@ 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?, follow?: false | { on?, dim?, ease? }, media?: { <i>: { start?, end?, mute?,
+ * is `{ hold?, mediaLayout?, redact?, follow?: false | { on?, dim?, ease? }, thread?: { parent?, quoted?, carry?,
+ * reveal?, shrink?, dim?, seconds?, pan? }, 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
@@ -2381,6 +2384,7 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
const i = entryIndex(m.timeline, id);
const e = m.timeline[i];
if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
+ const was = JSON.parse(JSON.stringify(e));
const set = (o, k, v) => {
if (v === null || v === undefined) delete o[k];
else o[k] = typeof v === "number" ? round2(v) : v;
@@ -2396,6 +2400,15 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
}
if (Object.keys(f).length) e.follow = f;
else delete e.follow;
+ } else if (k === "thread" && isObj(patch.thread)) {
+ // Its thread read (post-thread.mjs): the knobs merge (a null one back to the cut's).
+ const f = isObj(e.thread) ? e.thread : {};
+ for (const [fk, fv] of Object.entries(patch.thread)) {
+ if (fv === null || fv === undefined) delete f[fk];
+ else f[fk] = typeof fv === "number" ? round2(fv) : fv;
+ }
+ if (Object.keys(f).length) e.thread = f;
+ else delete e.thread;
} else set(e, k, patch[k]);
}
if (isObj(patch.media)) {
@@ -2450,6 +2463,14 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
}
const errors = validatePostItem(e);
if (errors.length) throw new StructureRefused(errors);
+ // NEVER NARRATE HIDDEN TEXT (post-thread.mjs): a change to what the card shows that leaves a part of its read
+ // off the screen is refused, with the fix (one it had before is the guard's, not this write's).
+ if ("thread" in patch || "follow" in patch) {
+ const guard = (x) => threadReadErrors(x, m.render, { prev: m.timeline[i - 1] ?? null, followOn: followKnobs(x, m.render).on });
+ const had = new Set(guard(was));
+ const now = guard(e).filter((x) => !had.has(x));
+ if (now.length) throw new StructureRefused(now);
+ }
return { id, at: i, entry: e };
});
}
@@ -2639,7 +2660,7 @@ export function postNarrationIn(m, id, patch) {
const e = m.timeline[i];
if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
for (const k of Object.keys(patch)) {
- if (!POST_NARRATION_KNOBS.includes(k) && !["addTake", "dropTake", "keepPick", "takeWords"].includes(k)) throw new Error(`${k} is not a narration knob (${[...POST_NARRATION_KNOBS, "addTake", "dropTake", "takeWords"].join(", ")})`);
+ if (!POST_NARRATION_KNOBS.includes(k) && !["addTake", "dropTake", "keepPick", "takeWords", "partRoles"].includes(k)) throw new Error(`${k} is not a narration knob (${[...POST_NARRATION_KNOBS, "addTake", "dropTake", "takeWords", "partRoles"].join(", ")})`);
}
const before = isObj(e.narration) ? JSON.parse(JSON.stringify(e.narration)) : null;
const n = isObj(e.narration) ? e.narration : { takes: [] };
@@ -2662,6 +2683,18 @@ export function postNarrationIn(m, id, patch) {
if (tw.words === null) delete t.words;
else t.words = tw.words;
}
+ // Its parts' ROLES (post-thread.mjs; posts roles --write/--set): `{ take: <index>, roles: [<role> | null, …] }`,
+ // one a part (null: none stored -- inferred again).
+ if (patch.partRoles !== undefined && patch.partRoles !== null) {
+ const pr = patch.partRoles;
+ const t = isObj(pr) && Number.isInteger(pr.take) ? n.takes[pr.take] : null;
+ if (!t || !Array.isArray(t.parts) || !t.parts.length) throw new Error(`${id} has no take ${isObj(pr) ? pr.take : "?"} with parts`);
+ if (!Array.isArray(pr.roles) || pr.roles.length !== t.parts.length) throw new Error(`${id}: partRoles.roles is one role a part (${t.parts.length})`);
+ t.parts.forEach((p, k) => {
+ if (pr.roles[k] === null || pr.roles[k] === undefined) delete p.role;
+ else p.role = pr.roles[k];
+ });
+ }
if (patch.dropTake !== undefined && patch.dropTake !== null) {
const d = Number(patch.dropTake);
if (!Number.isInteger(d) || !n.takes[d]) throw new Error(`${id} has no take ${patch.dropTake}`);
@@ -2846,7 +2879,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"), "follow"]);
+export const POST_NARRATION_RENDER_KNOBS = Object.freeze([...Object.keys(POST_NARRATION_DEFAULTS).filter((k) => k !== "attach"), "follow", "thread"]);
/**
* SET THE CUT's NARRATION MIX (`render.postNarration`; `umtool posts narrate
@@ -2865,15 +2898,15 @@ 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 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 : {};
+ else if ((k === "follow" || k === "thread") && isObj(v)) {
+ // The read-follow's knobs ({ on, dim, ease }) and the thread read's (post-thread.mjs) merge; a null one back to its default.
+ const f = isObj(r[k]) ? r[k] : {};
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;
+ if (Object.keys(f).length) r[k] = f;
+ else delete r[k];
} else r[k] = typeof v === "number" ? round2(v) : v;
}
if (Object.keys(r).length) m.render.postNarration = r;
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -36,8 +36,12 @@ export function headingOf(e) {
* drawn from it, by the same HTML the build screenshots), the plan of what
* plays when, and the day for the reel strip's tint. Its files are served by
* /api/report/post-item, which serves only what a post item names.
+ *
+ * @param {Record<string, any>} e
+ * @param {Record<string, any>} [render]
+ * @param {Record<string, any> | null} [prev] the item before it in the cut
*/
-export function postPlayEntry(e, render = undefined) {
+export function postPlayEntry(e, render = undefined, prev = null) {
const day = postDay(e.date);
const dateKey = day ? Number(day.replace(/-/g, "")) : null;
const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim();
@@ -51,7 +55,8 @@ export function postPlayEntry(e, render = undefined) {
date: day || null,
quote: words || null,
post: e,
- postPlan: postItemPlan(e, render),
+ // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in).
+ postPlan: postItemPlan(e, render, { prev }),
};
}
@@ -105,8 +110,8 @@ export async function playView(project, { take = null, bare = false } = {}) {
const segments = timeline.map((e, i) => ({ id: e.id, start: Math.round(starts[i] * 1000) / 1000, duration: Math.round(durs[i] * 1000) / 1000 }));
const cache = await projectCache(project, manifest);
const entries = await Promise.all(
- timeline.map(async (e) => {
- if (e.type === "post") return postPlayEntry(e, render);
+ timeline.map(async (e, i) => {
+ if (e.type === "post") return postPlayEntry(e, render, timeline[i - 1] ?? null);
if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null };
const win = pickWindow(await windowsFor(project, e, cache), null);
const dateKey = clipDateKey(e);
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -26,6 +26,7 @@ import {
NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf,
} from "umtool-report-to-video/post-narration";
import { postItemPlan } from "umtool-report-to-video/post-item";
+import { partRoles } from "umtool-report-to-video/post-thread";
import { spokenRead } from "umtool-report-to-video/post-redact";
import { projectRedaction } from "./postRedaction.mjs";
import { readManifest } from "../projects/report.mjs";
@@ -44,6 +45,7 @@ export const NARRATE_USAGE = [
" 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=… follow=on|off follow.dim=… follow.ease=…",
+ " --cut thread.parent=auto|full|excerpt|context|carry|hidden thread.quoted=… thread.carry=auto|on|off thread.reveal=on|off thread.shrink=… thread.dim=… thread.seconds=… thread.pan=…",
" 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.",
@@ -134,9 +136,10 @@ export async function importPatches(manifest, rows, measure) {
...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}),
...(typeof t.note === "string" ? { note: t.note } : {}),
// A take composed of parts (a long post, paragraph by paragraph): the row's, else take-<n>.parts.json beside it.
+ // Each part's ROLE stored as it comes in (post-thread.mjs): the text it reads, its own or inferred.
...(() => {
const parts = normalizeParts(Array.isArray(t.parts) ? t.parts : m.parts);
- return parts ? { parts } : {};
+ return parts ? { parts: withPartRoles(e, parts) } : {};
})(),
});
files.add(t.file);
@@ -178,9 +181,23 @@ export function normalizeParts(raw) {
start: r3(p.start),
seconds: r3(p.seconds),
...(Number.isFinite(Number(p.gapBefore)) ? { gapBefore: r3(p.gapBefore) } : {}),
+ // The text it reads (post-thread.mjs), the voice and the piece the batch read it in.
+ ...(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d)$/.test(p.role) ? { role: p.role } : {}),
+ ...(typeof p.voice === "string" && /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/.test(p.voice) ? { voice: p.voice } : {}),
+ ...(Number.isInteger(p.piece) && p.piece >= 0 ? { piece: p.piece } : {}),
}));
}
+/**
+ * A take's parts with each one's ROLE (post-thread.mjs partRoles): the text
+ * it reads -- its own role kept, else the one inferred from its words and its
+ * piece (`para` div 100); a part no text on the card holds is left without.
+ */
+export function withPartRoles(entry, parts) {
+ const roles = partRoles(entry, { parts });
+ return parts.map((p, k) => (p.role || !roles[k]?.role ? p : { ...p, role: roles[k].role }));
+}
+
/** `take-<n>.parts.json` for a take file `narration/posts/<id>/take-<n>.<engine>-<voice>.wav`. */
export const partsFileOf = (rel) => String(rel).replace(/(take-\d+)(?:-[a-z]+)?\.[^/]*\.wav$/, "$1.parts.json");
@@ -230,13 +247,25 @@ export function mixPatchOf(pairs, { cut = false } = {}) {
// 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() };
+ // The cut's thread reads (post-thread.mjs): thread.parent|quoted=<mode>, thread.carry=auto|on|off, thread.reveal=on|off,
+ // thread.shrink|dim|seconds|pan=<n>.
+ else if (/^thread\.(parent|quoted|carry|reveal|shrink|dim|seconds|pan)$/.test(k) && cut) {
+ const knob = k.slice(7);
+ let val;
+ if (clear) val = null;
+ else if (knob === "parent" || knob === "quoted") val = v;
+ else if (knob === "carry") val = v === "auto" ? "auto" : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("thread.carry= takes auto, on or off"); })();
+ else if (knob === "reveal") val = ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("thread.reveal= takes on or off"); })();
+ else val = num();
+ out.thread = { ...(out.thread ?? {}), [knob]: val };
+ }
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, follow, follow.dim, follow.ease" : "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, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan" : "linger, clip, attach, lufs, rate, fit"})`);
}
if (!Object.keys(out).length) throw new NarrateError("nothing to set");
return out;
@@ -321,8 +350,8 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
if (!manifest) throw new NarrateError(`${project.id} has no manifest`);
const render = manifest.render ?? {};
const tl = (manifest.timeline ?? []).filter((e) => e?.type === "post");
- const pairs = words.filter((w) => /^[A-Za-z]+=/.test(w));
- const ref = words.find((w) => !/^[A-Za-z]+=/.test(w)) ?? null;
+ const pairs = words.filter((w) => /^[A-Za-z][A-Za-z.]*=/.test(w));
+ const ref = words.find((w) => !/^[A-Za-z][A-Za-z.]*=/.test(w)) ?? null;
const write = async (fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir)));
if (flags.has("--import")) {
diff --git a/umtool/lib/report/postThread.test.mjs b/umtool/lib/report/postThread.test.mjs
@@ -0,0 +1,101 @@
+// A THREAD READ's writers and CLI (post-thread.mjs; postThreadCli.mjs,
+// postsCli.mjs set-item thread.*, posts narrate --cut thread.*, the import's
+// roles, manifest.mjs updatePostItem's guard): the roles stored, what each
+// context post is on screen set, and a setting that would narrate hidden text
+// refused with the fix.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { postsCommand } from "./postsCli.mjs";
+import { postItemPatchOf } from "./postsCli.mjs";
+import { mixPatchOf } from "./postNarrationCli.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-thread-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const REPORTS = path.join(ROOT, "reports");
+const PARENT = "The first thing anyone notices is the noise from the street.\n\nThen the lights in the hall go out without warning.";
+const REPLY = "That is exactly what I was saying yesterday morning.";
+
+const parts = () => [
+ { n: 1, para: 0, text: "The first thing anyone notices is the noise from the street.", start: 0, seconds: 3.6 },
+ { n: 2, para: 1, text: "Then the lights in the hall go out without warning.", start: 4.2, seconds: 3.2 },
+ { n: 3, para: 100, text: REPLY, start: 8.2, seconds: 3.1 },
+];
+const item = (id, o = {}) => ({
+ type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: REPLY,
+ parents: [{ id: "900", author: "Neighbour", handle: "neighbour_one", date: "2026-10-29T10:00:00.000Z", text: PARENT }],
+ ...o,
+});
+const narrated = (id, o = {}) => item(id, { narration: { script: REPLY, takes: [{ file: `narration/posts/${id}/take-1.orpheus-thread.wav`, engine: "orpheus", voice: "leo+zac", seconds: 11.3, parts: parts() }], pick: 0 }, ...o });
+
+async function project(name, timeline) {
+ const dir = path.join(REPORTS, name);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "" }, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2));
+ return { id: name, dir };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const cli = async (args) => {
+ const lines = [];
+ const errs = [];
+ const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) });
+ return { code, out: lines.join("\n"), err: errs.join("\n") };
+};
+
+test("posts roles: the read piece by piece (inferred), --write stores them, --set sets one by hand", async () => {
+ const p = await project("roles", [narrated("1")]);
+ const ls = await cli(["roles", "roles"]);
+ assert.equal(ls.code, 0, ls.err);
+ assert.match(ls.out, /1 narrated item\(s\) read in parts, 1 threaded, 0 refused/);
+ assert.match(ls.out, /parts 1,2 {2}parent:0 {2}inferred {2}shown full/);
+ assert.match(ls.out, /parts 3 {2}post {2}inferred {2}shown full/);
+ const w = await cli(["roles", "roles", "--write"]);
+ assert.match(w.out, /stored the roles of 1 read/);
+ assert.deepEqual((await manifest(p)).timeline[0].narration.takes[0].parts.map((x) => x.role), ["parent:0", "parent:0", "post"]);
+ assert.match((await cli(["roles", "roles", "--write"])).out, /stored already/);
+ const set = await cli(["roles", "roles", "p-1", "--set", "2=post"]);
+ assert.equal(set.code, 0, set.err);
+ assert.deepEqual((await manifest(p)).timeline[0].narration.takes[0].parts.map((x) => x.role), ["parent:0", "post", "post"]);
+ assert.match((await cli(["roles", "roles", "p-1", "--set", "9=post"])).err, /parts 1-3/);
+ assert.match((await cli(["roles", "roles", "p-1", "--set", "1=somewhere"])).err, /a role is post, quoted/);
+});
+
+test("set-item thread.*: the knobs merge; hiding a parent the read reads is REFUSED with the fix; context for an unread one is fine", async () => {
+ const p = await project("knobs", [narrated("1"), item("2", { narration: { script: REPLY, takes: [{ file: "narration/posts/2/take-1.orpheus-zac.wav", seconds: 3.1, parts: [{ n: 1, para: 0, text: REPLY, start: 0, seconds: 3.1 }] }], pick: 0 } })]);
+ assert.deepEqual(postItemPatchOf(["thread.shrink=0.5", "thread.parent.1=hidden", "thread.carry=off", "thread.reveal=on"]).thread, { shrink: 0.5, parent: ["auto", "hidden"], carry: false, reveal: true });
+ assert.deepEqual(postItemPatchOf(["thread=auto"]), { thread: null });
+ const ok = await cli(["set-item", "knobs", "p-1", "thread.shrink=0.5", "thread.dim=0.4"]);
+ assert.equal(ok.code, 0, ok.err);
+ assert.deepEqual((await manifest(p)).timeline[0].thread, { shrink: 0.5, dim: 0.4 });
+ const bad = await cli(["set-item", "knobs", "p-1", "thread.parent=hidden"]);
+ assert.notEqual(bad.code, 0);
+ assert.match(bad.err, /part 1 reads the post it answers, which is drawn hidden.*thread\.parent=full/);
+ assert.equal((await manifest(p)).timeline[0].thread.parent, undefined);
+ // Follow off with a read parent: refused too.
+ assert.match((await cli(["set-item", "knobs", "p-1", "follow=off"])).err, /read-follow is off/);
+ // p-2 reads only his words: its parent may be context or hidden.
+ assert.equal((await cli(["set-item", "knobs", "p-2", "thread.parent=hidden"])).code, 0);
+ assert.equal((await manifest(p)).timeline[1].thread.parent, "hidden");
+ assert.equal((await cli(["set-item", "knobs", "p-1", "thread=auto"])).code, 0);
+ assert.equal((await manifest(p)).timeline[0].thread, undefined);
+});
+
+test("the cut's thread knobs (posts narrate --cut thread.*), and the import stores each part's role", async () => {
+ assert.deepEqual(mixPatchOf(["thread.shrink=0.55", "thread.parent=excerpt", "thread.carry=auto", "thread.reveal=off"], { cut: true }).thread, { shrink: 0.55, parent: "excerpt", carry: "auto", reveal: false });
+ const p = await project("cut", [item("1")]);
+ const r = await cli(["narrate", "cut", "--cut", "thread.shrink=0.55", "thread.pan=1.2"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual((await manifest(p)).render.postNarration.thread, { shrink: 0.55, pan: 1.2 });
+ assert.notEqual((await cli(["narrate", "cut", "--cut", "thread.shrink=9"])).code, 0);
+ // The import: a batch's take with its parts (no roles) comes in with each part's role stored.
+ await mkdir(path.join(p.dir, "narration", "posts", "1"), { recursive: true });
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=f=220:d=11.3", "-ar", "48000", "-ac", "1", path.join(p.dir, "narration", "posts", "1", "take-1.orpheus-thread.wav")]);
+ await writeFile(path.join(p.dir, "narration", "posts", "index.json"), JSON.stringify([{ id: "1", entry: "p-1", script: REPLY, takes: [{ file: "narration/posts/1/take-1.orpheus-thread.wav", engine: "orpheus", voice: "leo+zac", seconds: 11.3, parts: parts().map((x, i) => ({ ...x, voice: i < 2 ? "leo" : "zac" })) }], pick: 0 }]));
+ const imp = await cli(["narrate", "cut", "--import"]);
+ assert.equal(imp.code, 0, imp.err);
+ const got = (await manifest(p)).timeline[0].narration.takes[0].parts;
+ assert.deepEqual(got.map((x) => [x.role, x.voice]), [["parent:0", "leo"], ["parent:0", "leo"], ["post", "zac"]]);
+});
diff --git a/umtool/lib/report/postThreadCli.mjs b/umtool/lib/report/postThreadCli.mjs
@@ -0,0 +1,129 @@
+// `umtool posts roles` -- A POST ITEM's READ, PIECE BY PIECE
+// (umtool-report-to-video/post-thread.mjs; umtool/docs/knobs.md, "Thread
+// reads"): the text each part of its read reads -- the post it answers, the
+// post it quotes, his words, an attachment's -- its own (stored) or inferred,
+// what the card shows for each, and whether anything read is not on screen.
+//
+// umtool posts roles <p> [<item> …] the read's pieces and the guard's verdict, per narrated item
+// umtool posts roles <p> [<item> …] --write the inferred roles stored on each picked take's parts
+// umtool posts roles <p> <item> --set 3=parent:0,4=post one part's role set by hand (n as `ls` shows it)
+//
+// Every write goes through updatePostNarration (`partRoles`), one undo point a
+// run (updatePostNarrations).
+//
+// Plain ESM: the CLI runs under bare node.
+import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
+import { partRoles, readPieces, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread";
+import { followKnobs } from "umtool-report-to-video/read-follow";
+import { readManifest } from "../projects/report.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { manifestToken, updatePostNarrations } from "./manifest.mjs";
+
+export const ROLES_USAGE = [
+ " umtool posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]",
+ " A READ's PIECES (post-thread.mjs): the text each part of a narrated item's read reads -- parent:<i> (the post it",
+ " answers, nearest first), quoted, post (his words), media:<i> (an attachment's words, a screenshot) -- its own",
+ " role, else INFERRED (its piece, para div 100, matched by its word pairs), what the card shows for each (full,",
+ " excerpt, context, carry, hidden: thread.parent / thread.quoted) and the build's guard: a part read off a text the",
+ " card does not show is refused. --write stores the inferred roles on the picked takes' parts (the import stores",
+ " them for every new take); --set n=role sets one part's by hand (n from 1, as listed; role off: inferred again).",
+].join("\n");
+
+export class RolesError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "RolesError";
+ }
+}
+
+const ROLE_RE = /^(post|quoted|parent:\d|media:\d)$/;
+
+/** A narrated item's read, piece by piece: `{ id, take, pieces: [{ role, parts, source, mode }], errors, threaded }`. */
+export function readListing(e, render, prev) {
+ const t = pickedTake(e);
+ const roles = partRoles(e);
+ const L = threadLayout(e, render, { prev });
+ const mode = (role) => (!role ? null : role.startsWith("media:") ? "attachment" : L.tiles.find((x) => x.scope === role)?.mode ?? "absent");
+ const pieces = readPieces(e, roles).map((p) => ({
+ role: p.role,
+ parts: p.parts.map((k) => k + 1),
+ source: p.parts.every((k) => roles[k].source === "stored") ? "stored" : p.parts.some((k) => roles[k].source === "stored") ? "mixed" : "inferred",
+ mode: mode(p.role),
+ words: p.parts.map((k) => String(t.parts[k]?.text ?? "")).join(" ").split(/\s+/).filter(Boolean).length,
+ }));
+ const tiles = L.tiles.filter((x) => !x.read && x.scope !== "post").map((x) => ({ scope: x.scope, mode: x.mode }));
+ return { id: e.id, take: t?.file ?? null, parts: t?.parts?.length ?? 0, pieces, unread: tiles, threaded: L.on && followKnobs(e, render).on, errors: threadReadErrors(e, render, { prev, followOn: followKnobs(e, render).on }) };
+}
+
+/**
+ * `umtool posts roles <p> [<item> …] [--write] [--set n=role,…]`.
+ * @param {{ id: string, dir: string }} project
+ * @param {string[]} ids
+ */
+export async function rolesCommand(project, ids, { write = false, set = null, json = false, out = (s) => console.log(s) } = {}) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new RolesError(`${project.id} has no manifest`);
+ const tl = Array.isArray(manifest.timeline) ? manifest.timeline : [];
+ const want = new Set(ids);
+ const hit = (e) => !want.size || want.has(e.id) || want.has(String(e.post ?? "").split("/")[1]);
+ const items = tl.map((e, i) => ({ e, prev: tl[i - 1] ?? null })).filter(({ e }) => e?.type === "post" && isNarrated(e) && hit(e) && pickedTake(e)?.parts?.length);
+ for (const id of want) if (!tl.some((e) => e?.type === "post" && (e.id === id || String(e.post ?? "").split("/")[1] === id))) throw new RolesError(`no post item ${id} in ${project.id}`);
+ if (set !== null) {
+ if (items.length !== 1) throw new RolesError("--set names one item's parts: give exactly one narrated item with parts");
+ const { e } = items[0];
+ const t = pickedTake(e);
+ const roles = t.parts.map((p) => (typeof p.role === "string" ? p.role : null));
+ for (const pair of String(set).split(",").map((x) => x.trim()).filter(Boolean)) {
+ const m = /^(\d+)=(.+)$/.exec(pair);
+ if (!m) throw new RolesError(`--set ${pair}: n=role (n from 1, role post|quoted|parent:<i>|media:<i>|off)`);
+ const n = Number(m[1]);
+ if (!(n >= 1 && n <= t.parts.length)) throw new RolesError(`--set ${pair}: ${e.id}'s take has parts 1-${t.parts.length}`);
+ const role = m[2].trim();
+ if (role !== "off" && !ROLE_RE.test(role)) throw new RolesError(`--set ${pair}: a role is post, quoted, parent:<i>, media:<i> (or off: inferred)`);
+ roles[n - 1] = role === "off" ? null : role;
+ }
+ const take = (Number.isInteger(t.index) ? t.index : e.narration.pick ?? 0);
+ const { result } = await withEditNotes(project, async () => updatePostNarrations(project.dir, [{ id: e.id, patch: { partRoles: { take, roles } } }], { token: await manifestToken(project.dir) }));
+ const now = await readManifest(project.dir);
+ const after = (now?.timeline ?? []).find((x) => x?.id === e.id) ?? e;
+ const row = readListing(after, now?.render ?? manifest.render, items[0].prev);
+ out(json ? JSON.stringify({ ok: true, item: row, token: result.token }, null, 2) : lines([row]).join("\n"));
+ return 0;
+ }
+ if (write) {
+ const patches = [];
+ for (const { e } of items) {
+ const t = pickedTake(e);
+ const inferred = partRoles(e);
+ const roles = t.parts.map((p, k) => (typeof p.role === "string" ? p.role : inferred[k]?.role ?? null));
+ if (roles.every((r, k) => r === (t.parts[k].role ?? null))) continue;
+ patches.push({ id: e.id, patch: { partRoles: { take: (Number.isInteger(t.index) ? t.index : e.narration.pick ?? 0), roles } } });
+ }
+ if (!patches.length) {
+ out(json ? JSON.stringify({ ok: true, written: 0 }, null, 2) : `every read's roles are stored already (${items.length} item(s))`);
+ return 0;
+ }
+ const { result } = await withEditNotes(project, async () => updatePostNarrations(project.dir, patches, { token: await manifestToken(project.dir) }));
+ out(json ? JSON.stringify({ ok: true, written: patches.length, token: result.token }, null, 2) : `stored the roles of ${patches.length} read(s) in ${project.id}`);
+ return 0;
+ }
+ const rows = items.map(({ e, prev }) => readListing(e, manifest.render, prev));
+ if (json) {
+ out(JSON.stringify({ ok: true, items: rows, refused: rows.filter((r) => r.errors.length).length }, null, 2));
+ return 0;
+ }
+ out(`${project.id}: ${rows.length} narrated item(s) read in parts, ${rows.filter((r) => r.threaded).length} threaded, ${rows.filter((r) => r.errors.length).length} refused`);
+ out(lines(rows).join("\n"));
+ return 0;
+}
+
+function lines(rows) {
+ const out = [];
+ for (const r of rows) {
+ out.push(` ${r.id} ${r.parts} part(s)${r.threaded ? " threaded" : ""}`);
+ for (const p of r.pieces) out.push(` parts ${p.parts.join(",")} ${p.role ?? "(no text on the card)"} ${p.source}${p.mode ? ` shown ${p.mode}` : ""} ${p.words} words`);
+ for (const u of r.unread) out.push(` not read: ${u.scope} shown ${u.mode}`);
+ for (const er of r.errors) out.push(` REFUSED: ${er}`);
+ }
+ return out;
+}
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -36,6 +36,13 @@ import { withEditNotes } from "./edit-guard.mjs";
import { PostsRefused, StaleToken, StructureRefused, addArchiveAvatars, manifestToken, setPostAvatar, updatePostItem, updatePostRedact, updatePosts, upsertPost } from "./manifest.mjs";
import { postWarnings } from "./postCards.mjs";
+// `umtool posts roles` (postThreadCli.mjs ROLES_USAGE): its lines, kept here so the usage is one block.
+const ROLES_LINES = [
+ " umtool posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]",
+ " a READ's PIECES: the text each part of a narrated item's read reads (the post it answers, the quoted post, his",
+ " words, an attachment's), stored or inferred, what the card shows for each, and the guard (umtool posts roles --help).",
+];
+
// `umtool posts slurs` (postSlursCli.mjs SLURS_USAGE): its lines, kept here so the usage is one block.
const SLURS_USAGE_LINES = [
" umtool posts slurs <project> [ls] | on | off | level strong|all | visual blackout|placeholder",
@@ -66,6 +73,9 @@ export const POSTS_USAGE = [
" 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] [follow=on|off|auto] [follow.dim=<0.2-1>] [follow.ease=<s>]",
+ " [thread.parent[.<i>]=auto|full|excerpt|context|carry|hidden] [thread.quoted=auto|full|excerpt|context|hidden]",
+ " [thread.carry=auto|on|off] [thread.reveal=on|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>]",
+ " [thread.seconds=<0-3>] [thread.pan=<0.1-3>] [thread=auto]",
" [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]",
@@ -79,6 +89,11 @@ export const POSTS_USAGE = [
" media.<i>.blur=on: the attachment CENSORED in the render -- a real blur (strength 1-10, default 7) of the whole",
" frame, or of its boxes (fractions of the picture as shown: x,y,w,h;…), labelled \"Censored\" (label=… or off);",
" its file is never touched. Play and the bench preview it; the bench draws boxes on a paused frame.",
+ " thread.*: a THREAD READ (post-thread.mjs) -- a narrated item that reads the post it answers or quotes is drawn as",
+ " the conversation, each post read shown in full and shrunk/dimmed as the next comes in: what each context post is",
+ " on screen (auto: full when read, carried in when it is the item before, else context), the shrink, dim and their",
+ " seconds, the pan's seconds. A setting that would narrate a post the card hides is refused (umtool posts roles).",
+ ...ROLES_LINES,
" umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix",
" (umtool posts narrate --help)",
" umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
@@ -106,7 +121,7 @@ export const POSTS_USAGE = [
" umtool posts attach <project> [<item> … | --all] [--dry-run] a capture's media onto items that carry none",
].join("\n");
-const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker"]);
+const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -406,6 +421,17 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (lingerRaw !== null && !(Number.isFinite(linger) && linger >= 0 && linger <= 30)) throw new CliError("--linger takes seconds, 0-30");
return await fitCommand(await projectOf(projectArg, root), words.slice(2), { all: flags.has("--all"), linger, json, dryRun, out });
}
+ if (verb === "roles") {
+ // A read's pieces (postThreadCli.mjs): the text each part reads, what the card shows, the guard.
+ const { ROLES_USAGE, rolesCommand } = await import("./postThreadCli.mjs");
+ if (!projectArg || flags.has("--help")) {
+ err(ROLES_USAGE);
+ return 2;
+ }
+ return await rolesCommand(await projectOf(projectArg, root), words.slice(2), { write: flags.has("--write"), set: flags.has("--set") ? str("--set") : null, json, out }).catch((e) => {
+ throw e?.name === "RolesError" ? new CliError(e.message) : e;
+ });
+ }
if (verb === "redact" && projectArg && !flags.has("--help")) return await redactCommand(projectArg, words.slice(2), { root, json, out, flags, str });
if (verb === "slurs") {
// The slur filter (postSlursCli.mjs): its own words refused as a usage error.
@@ -608,6 +634,28 @@ export function postItemPatchOf(pairs) {
if (out.follow === false) throw new CliError("follow=off goes alone");
out.follow = { ...(out.follow ?? {}), [k.slice(7)]: v === "default" || v === "" ? null : Number(raw) };
}
+ // Its thread read (post-thread.mjs): thread=auto clears every knob (the cut's); thread.<knob>=… one of them.
+ else if (k === "thread") {
+ if (!(v === "auto" || v === "default" || v === "")) throw new CliError("thread= takes auto (the cut's knobs); set one with thread.<knob>=");
+ out.thread = null;
+ } else if (/^thread\.(parent(\.\d)?|quoted|carry|reveal|shrink|dim|seconds|pan)$/.test(k)) {
+ if (out.thread === null) throw new CliError("thread=auto goes alone");
+ const t = (out.thread ??= {});
+ const knob = k.split(".")[1];
+ const clear = v === "default" || v === "" || (v === "auto" && knob !== "parent" && knob !== "quoted" && knob !== "carry");
+ if (knob === "parent" && k.split(".").length === 3) {
+ const i = Number(k.split(".")[2]);
+ const list = Array.isArray(t.parent) ? t.parent : typeof t.parent === "string" ? [t.parent, t.parent] : ["auto", "auto"];
+ list[i] = clear ? "auto" : v;
+ t.parent = list.slice(0, Math.max(1, i + 1, list.length)).slice(0, 2);
+ } else if (knob === "parent" || knob === "quoted") t[knob] = clear ? null : v;
+ else if (knob === "carry") t.carry = clear ? null : v === "auto" ? "auto" : onOff(v, k);
+ else if (knob === "reveal") t.reveal = clear ? null : onOff(v, k);
+ else {
+ t[knob] = clear ? null : Number(raw);
+ if (typeof t[knob] === "number" && !Number.isFinite(t[knob])) throw new CliError(`${k}= takes a number`);
+ }
+ }
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)) {
@@ -621,7 +669,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=, follow=, follow.dim|ease=, 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=, thread=, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan=, 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);
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -6432,6 +6432,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// The authors' pictures (post-avatars.mjs), as files of the project.
avatars: avatarUrls(manifest, (src) => path.resolve(manifestDir, src)),
redaction: POST_REDACTION,
+ // The item before it in the cut (post-thread.mjs: a parent that is that item is carried in, not cut to).
+ prev: manifest.timeline[manifest.timeline.findIndex((x) => x?.id === entry.id) - 1] ?? null,
});
if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr });
// Its combo badge (post-combo-render.mjs): a pass over the segment when its attachment repeats an earlier one's.
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -89,6 +89,7 @@ import { wordZoomTimes } from "./word-zoom.mjs";
import { postAvatarFiles, validatePostAvatars } from "./post-avatars.mjs";
import { validatePostNarrationRender } from "./post-narration.mjs";
import { validatePostCombos } from "./post-combo.mjs";
+import { validateThreadReads } from "./post-thread.mjs";
import { validateFinaleEntries } from "./finale.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
@@ -332,6 +333,8 @@ export function validatorErrors(whole) {
...validatePostAvatars(whole),
// A narrated post item's mix (post-narration.mjs): the cut's knobs.
...validatePostNarrationRender(whole.render),
+ // Never narrate hidden text (post-thread.mjs): every part of a read is of a text its card shows.
+ ...validateThreadReads(whole),
// The combo counter (post-combo.mjs): render.posts.combo and each post item's `combo`.
...validatePostCombos(whole),
];
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -70,6 +70,7 @@
"./post-redact": "./post-redact.mjs",
"./post-redact-files": "./post-redact-files.mjs",
"./post-slurs": "./post-slurs.mjs",
+ "./post-thread": "./post-thread.mjs",
"./post-render": "./post-render.mjs",
"./word-zoom": "./word-zoom.mjs",
"./read-follow": "./read-follow.mjs",
diff --git a/umtool/report-to-video/post-combo.mjs b/umtool/report-to-video/post-combo.mjs
@@ -418,7 +418,8 @@ export function validatePostComboRender(render) {
const p = render?.posts;
if (p === undefined || p === null) return [];
if (!isObj(p)) return ["render.posts must be an object (its `combo` knobs)"];
- const errors = Object.keys(p).filter((k) => k !== "combo").map((k) => `render.posts.${k} is not a knob (combo)`);
+ // render.posts is shared: `redact` and `slurs` are post-redact.mjs's (validatePostsRender checks them).
+ const errors = Object.keys(p).filter((k) => !["combo", "redact", "slurs"].includes(k)).map((k) => `render.posts.${k} is not a knob (combo, redact, slurs)`);
if (p.combo === undefined) return errors;
if (!isObj(p.combo)) return [...errors, "render.posts.combo must be an object of knobs"];
return [...errors, ...knobErrors(p.combo, "render.posts.combo", Object.keys(COMBO_DEFAULTS))];
diff --git a/umtool/report-to-video/post-combo.test.mjs b/umtool/report-to-video/post-combo.test.mjs
@@ -249,3 +249,8 @@ test("the sound's print: the same clip re-encoded matches, another sound does no
p.done();
}
});
+
+test("render.posts is shared: the combo validator leaves redact and slurs to post-redact.mjs (a cut with redacted words built again)", () => {
+ assert.deepEqual(validatePostComboRender({ posts: { redact: [{ term: "Someone" }], slurs: { on: true }, combo: { on: true } } }), []);
+ assert.match(validatePostComboRender({ posts: { comb: {} } }).join(" "), /render\.posts\.comb is not a knob/);
+});
diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -36,6 +36,7 @@ import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactionOn,
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";
+import { validatePostThread } from "./post-thread.mjs";
/** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */
export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]);
@@ -223,19 +224,27 @@ export function postItemSeconds(entry, render = undefined) {
*
* @param {Record<string, any>} entry
* @param {Record<string, any>} [render]
- * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number, narration?: Record<string, any> }}
+ * @param {{ prev?: Record<string, any> | null }} [o] the item before it in the cut (post-thread.mjs carries a parent that is it)
+ * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number, narration?: Record<string, any>, follow?: Record<string, any> }}
*/
-export function postItemPlan(entry, render = undefined) {
+export function postItemPlan(entry, render = undefined, { prev = null } = {}) {
const hold = fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : null;
- return planOf(entry, render, hold);
+ return planOf(entry, render, hold, prev);
}
-function planOf(entry, render, hold) {
+/**
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any> | undefined} render
+ * @param {number | null} hold
+ * @param {Record<string, any> | null} [prev]
+ */
+function planOf(entry, render, hold, prev = null) {
const narrated = isNarrated(entry);
const k = postNarrationKnobs(entry, render);
const sch = narrated ? narrationSchedule(entry, render) : null;
- // 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 });
+ // Its read-follow (read-follow.mjs): each block's start on the item's clock -- null when it is off. `prev`: the
+ // item before it in the cut (post-thread.mjs: a parent that is that item is carried in, not cut to).
+ const follow = followSchedule(entry, render, { hold, narration: sch, prev });
const extra = { ...(sch ? { narration: sch } : {}), ...(follow ? { follow } : {}) };
if (sch && k.attach === "after") {
const voiceOnly = round3(sch.at + sch.seconds + k.tail);
@@ -472,6 +481,8 @@ export function validatePostItem(e) {
errors.push(...validatePostFx(e));
// Its read-follow's knobs (read-follow.mjs): false, or { on, dim, ease }.
errors.push(...validatePostFollow(e));
+ // Its thread read's knobs (post-thread.mjs): what each context post is on screen, the shrink and dim.
+ errors.push(...validatePostThread(e));
return errors;
}
@@ -803,16 +814,26 @@ export function nameHtml(who, { redact, cls = "" }) {
* 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.
+ * below FOLLOW_MIN_SIZE -- the build and Play light and pan them. `thread`
+ * (post-thread.mjs threadLayout, or the plan's follow.thread): a narrated read
+ * of the post it answers or quotes draws the card as the conversation -- a
+ * column of tiles (`data-thread-slot` / `data-thread-tile`), each post at the
+ * size that fits it alone, scaled and dimmed by the follow state.
*
* @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, follow?: boolean }} o
+ * redaction?: { terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, any> } | null, follow?: boolean,
+ * thread?: { tiles?: Array<{ scope: string, mode: string }> } | null }} o
*/
-export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null, follow = false }) {
+export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null, follow = false, thread = null }) {
const hlOf = (scope) => (highlight && highlight.scope === scope ? highlight : null);
+ // THREADED (post-thread.mjs): the conversation as a column of tiles -- `thread` the layout's tiles
+ // (threadLayout, or the plan's follow.thread), each `{ scope, mode }`; a hidden one is not drawn.
+ const tiles = follow && Array.isArray(thread?.tiles) ? thread.tiles.filter((t) => t && t.mode !== "hidden") : null;
+ const threaded = !!tiles && tiles.some((t) => t.scope !== "post") && phase === "read";
+ const tmode = (scope) => tiles?.find((t) => t.scope === scope)?.mode ?? (threaded ? "hidden" : 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;
@@ -847,6 +868,7 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
const parents = parentsOf(entry);
for (let i = parents.length - 1; i >= 0; i -= 1) {
const p = parents[i];
+ if (thread && Array.isArray(thread.tiles) && thread.tiles.some((t) => t.scope === `parent:${i}` && t.mode === "hidden")) continue;
const r = red(`parents[${i}]`);
const subject = !r && subjectsOf(entry).some((h) => String(h).toLowerCase() === String(p.handle ?? "").replace(/^@/, "").toLowerCase());
ctx.push(
@@ -871,8 +893,51 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
? `<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 = follow ? followMin : Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k);
+ // THE THREADED CARD (post-thread.mjs): the posts it answers (oldest first) and his post -- the quoted post inside
+ // it -- as tiles in one column the read pans; each tile's words at the size that fits it alone in the card, so a
+ // post being read is large; a tile is scaled down about its corner (its slot closed up) as context.
+ const threadCard = (box) => {
+ const innerW = box.width - 2 * L.pad;
+ const innerH = box.height - 2 * L.pad;
+ const sizeFor = (text, w, h) => Math.max(followMin, fitSize(text, w, h, k).size);
+ const av = Math.round(56 * k);
+ const cut = (scope) => (tmode(scope) === "excerpt" && fmap ? new Set(fmap.blocks.filter((b) => b.scope === scope && b.part === null).map((b) => b.k)) : null);
+ const cutCss = [];
+ const tileHtml = [];
+ for (let i = parents.length - 1; i >= 0; i -= 1) {
+ const scope = `parent:${i}`;
+ const mode = tmode(scope);
+ const p = parents[i];
+ if (!mode || mode === "hidden" || !contextText(p).trim()) continue;
+ const r = red(`parents[${i}]`);
+ const subject = !r && subjectsOf(entry).some((h) => String(h).toLowerCase() === String(p.handle ?? "").replace(/^@/, "").toLowerCase());
+ const size = sizeFor(contextText(p), innerW - av - Math.round(16 * k), innerH - 90 * k);
+ for (const kk of cut(scope) ?? []) cutCss.push(`[data-thread-tile="${scope}"] [data-post-block="${kk}"]`);
+ tileHtml.push(
+ `<div class="tslot" data-thread-slot="${scope}"><div class="tile tparent" data-thread-tile="${scope}" data-thread-mode="${mode}" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: av, accent: subject ? pal.accent : undefined, img: pic(p) })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r, cls: "big" })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span>${mode === "excerpt" ? '<span class="plabel" data-thread-excerpt="">excerpt</span>' : ""}${paraLabel(p)}</div><div class="ptext tt"${isParaphrased(p) ? ' data-post-paraphrase=""' : ""} style="font-size:${size}px">${wordsHtml(contextText(p), blurred, scope, hlOf(scope), blk(scope))}</div></div></div></div>`,
+ );
+ }
+ const qmode = q ? tmode("quoted") : null;
+ let quotedTile = "";
+ if (q && qmode && qmode !== "hidden") {
+ const qsize = sizeFor(contextText(q), innerW - Math.round(36 * k), innerH - 140 * k);
+ for (const kk of cut("quoted") ?? []) cutCss.push(`[data-thread-tile="quoted"] [data-post-block="${kk}"]`);
+ quotedTile = `<div class="tslot" data-thread-slot="quoted"><div class="tile quoted" data-thread-tile="quoted" data-thread-mode="${qmode}" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(36 * k), img: pic(q) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span>${qmode === "excerpt" ? '<span class="plabel" data-thread-excerpt="">excerpt</span>' : ""}${paraLabel(q)}</div><div class="qtext tt"${isParaphrased(q) ? ' data-post-paraphrase=""' : ""} style="font-size:${Math.round(qsize * 0.9)}px">${wordsHtml(contextText(q), blurred, "quoted", hlOf("quoted"), blk("quoted"))}</div></div></div>`;
+ }
+ const own = cardText(entry);
+ const psize = own.trim() ? sizeFor(own, innerW, innerH - 170 * k) : size;
+ const lead = !parents.length && (parentShotUrl || entry.replyingTo) ? ctx.join("") : "";
+ tileHtml.push(
+ `<div class="tslot" data-thread-slot="post"><div class="tile tpost" data-thread-tile="post">${repost}${lead}${head}<div class="twords" style="font-size:${psize}px">${wordsHtml(own, blurred, "post", hlOf("post"), blk("post"))}</div>${quotedTile}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div></div>`,
+ );
+ return {
+ html: `<div class="card thread" data-post-card="${esc(entry.id)}" data-post-thread="${tiles.length}"${L.mode === "text" ? ' data-thread-fit=""' : ""} style="left:${box.x}px;top:${box.y}px;height:${box.height}px;width:${box.width}px"><div class="words" data-post-words="" style="font-size:${size}px"><div class="wflow" data-post-flow="">${tileHtml.join("")}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div></div></div>`,
+ css: cutCss.length ? `\n${cutCss.join(", ")} { display: none; }` : "",
+ };
+ };
+ const tc = threaded ? threadCard(L.card) : null;
+ const body = strip ? `${stripHtml}${slot}` : `${tc ? tc.html : card(L.card)}${slot}`;
+ const minSize = tc ? size : 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>
@@ -920,11 +985,22 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; }
.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 ? `
+.wfade[data-post-fade="bottom"] { bottom: 0; background: linear-gradient(${rgbaOf(cardBg, 0)}, ${cardBg}); }` : ""}${tc ? `
+.card.thread { justify-content: flex-start; }
+.card.thread .words { flex: 1 1 auto; height: 100%; }
+.tslot { position: relative; }
+.tslot + .tslot { margin-top: ${Math.round(22 * k)}px; }
+.tile { transform-origin: 0 0; }
+.tparent { display: flex; gap: ${Math.round(16 * k)}px; position: relative; }
+.tparent::after { content: ""; position: absolute; left: ${Math.round(27 * k)}px; top: ${Math.round(64 * k)}px; bottom: -${Math.round(20 * k)}px; width: 2px; background: ${line}; }
+.tpost { display: flex; flex-direction: column; gap: ${Math.round(16 * k)}px; }
+.tile .tt { display: block; -webkit-line-clamp: none; overflow: visible; line-height: ${LINE}; color: ${pal.fg}; margin-top: ${Math.round(6 * k)}px; }
+.twords { line-height: ${LINE}; overflow-wrap: anywhere; }
+.tile.quoted .tt { color: ${mixHex(pal.fg, pal.bg, 0.08)}; }${tc.css}` : ""}${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"}"${fmap ? ` data-post-follow="${fmap.blocks.length}"` : ""}>${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}"` : ""}${tc ? ` data-post-thread="${tiles.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.
@@ -933,6 +1009,14 @@ ${BAR_CSS(pal.fg)}
var min = ${minSize};
function fit() {
if (w) { var s = parseFloat(w.style.fontSize); while (w.scrollHeight > w.clientHeight + 1 && s > min) { s -= 1; w.style.fontSize = s + 'px'; } }
+ // A threaded card alone (no attachments): as tall as its conversation at full size, centred -- never taller than its box.
+ var c = document.querySelector('.card.thread[data-thread-fit]');
+ if (c && w) {
+ var f = c.querySelector('.wflow');
+ var h0 = c.offsetHeight;
+ var h = Math.min(h0, Math.ceil(f.scrollHeight + (h0 - w.clientHeight)));
+ if (h < h0) { c.style.top = (parseFloat(c.style.top) + Math.floor((h0 - h) / 2)) + 'px'; c.style.height = h + 'px'; }
+ }
document.body.setAttribute('data-post-ready', '1');
}
if (document.fonts && document.fonts.ready) document.fonts.ready.then(fit); else fit();
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -32,6 +32,7 @@
// (postItemPlan's narrated branch), which reads these.
import { followKnobErrors } from "./read-follow.mjs";
+import { threadKnobErrors } from "./post-thread.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"]);
@@ -164,11 +165,13 @@ 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).
// `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"]);
+// `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim.
+const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]);
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", "slurs"]);
const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]);
-const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId"]);
+// `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's.
+const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece"]);
const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/;
/** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */
const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"];
@@ -477,7 +480,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"), ...followKnobErrors(r.follow, "render.postNarration.follow")];
+ return [...errors, ...mixErrors(r, "render.postNarration"), ...followKnobErrors(r.follow, "render.postNarration.follow"), ...threadKnobErrors(r.thread, "render.postNarration.thread")];
}
/** Every reason one post item's `narration` cannot be built (empty: it can). */
@@ -558,6 +561,7 @@ export function validatePostNarration(e) {
if (!(fin(p.start) && p.start >= 0)) errors.push(`${pw}.start must be where it starts in the take, seconds`);
if (!(fin(p.seconds) && p.seconds > 0)) errors.push(`${pw}.seconds must be its length`);
if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`);
+ if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i> or media:<i> (the text it reads)`);
});
}
});
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -255,6 +255,8 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
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",
+ // A threaded card (post-thread.mjs): the plan's tiles.
+ thread: follow?.thread ?? null,
redaction,
});
const file = path.join(dir, `${phase}.html`);
@@ -343,7 +345,7 @@ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotU
const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href]));
const load = async (name, highlight) => {
const file = path.join(dir, `${name}.html`);
- await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, redaction, follow: !!follow }), "utf8");
+ await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, redaction, follow: !!follow, thread: follow?.thread ?? null }), "utf8");
await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
};
@@ -438,16 +440,19 @@ export function postZoomPlan(entry, render, total = Infinity) {
* build-video's encode args and ffmpeg runner, the authors' pictures
* (`{ <handle>: absolute file }`, post-avatars.mjs), the redaction it is
* published with (`{ terms, markup }`, post-redact-files.mjs: its matches
- * drawn as bars, dropped from its captions). Returns the segment's path.
+ * drawn as bars, dropped from its captions), and `prev` the timeline entry
+ * before it (post-thread.mjs carries a parent that is it). Returns the
+ * segment's path.
*/
-export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null }) {
+export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null, prev = null }) {
// A channel's markup may censor an attachment for every project (post-censor.mjs); the item's own blur wins.
entry = censorEntry(entry, redaction);
// A word zoom on a redacted word is refused in the build's words (the corpus's terms and the markup included).
const fxRed = fxRedactionErrors(entry, redaction);
if (fxRed.length) throw new Error(fxRed.join("; "));
const seg = path.join(outDir, "segments", `${entry.id}.mp4`);
- const plan = postItemPlan(entry, render);
+ // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in).
+ const plan = postItemPlan(entry, render, { prev });
const layout = postLayout(entry, box);
const files = (entry.media ?? []).map((m) => path.resolve(manifestDir, m.src));
for (const [i, f] of files.entries()) {
diff --git a/umtool/report-to-video/post-thread.mjs b/umtool/report-to-video/post-thread.mjs
@@ -0,0 +1,494 @@
+// A POST ITEM's THREAD READ (umtool/docs/report-video.md, "Thread reads";
+// operator, 3-4 Nov 2026: "when narrating a reply parent you're just narrating
+// hidden text. Rework the thread system so you're never narrating hidden
+// text" -- "If it's a big reply that we're reading, show the parent in full
+// then transition in the reply as the parent shrinks and goes dim"; and,
+// earlier, "start with the first post in the chain, then reveal the rest of
+// the thread as we read through, pushing older posts up top").
+//
+// THE INVARIANT: every narrated part is on screen, legible and highlighted
+// while it is said. A post item's read is assembled in PIECES -- the post it
+// answers, the post it quotes, his words (and, by hand, words read off an
+// attachment) -- and each piece has a ROLE, the text it reads:
+//
+// "parent:<i>" parents[i] (nearest first) "quoted" the post it quotes
+// "post" his own words "media:<i>" an attachment's words (a screenshot)
+//
+// A part's role is its own (`parts[k].role`, stored by the import and by
+// `umtool posts roles --write`), else INFERRED: the parts grouped into their
+// pieces (`para` div 100), each piece matched by its words to the text it
+// reads (the context post's words as written and as a voice says them,
+// draftScript; his card text and his script), in the read's order.
+//
+// THE CARD, threaded: a narrated, following post item with a context post
+// drawn becomes a column of TILES (oldest first: the parents, then his post,
+// the quoted post inside it) panned by read-follow. A tile's MODE is what is
+// on screen for it (render.postNarration.thread / entry.thread):
+//
+// full the post in full, at the words' size, the frame's focus while it is read
+// excerpt as full, but only the paragraphs the read reads ("…" for the rest)
+// context small and dim the whole item -- never read
+// carry (a parent the read skips because it is the item just before in
+// the cut) it opens as that item ended -- in full -- and shrinks
+// and dims as the reply comes in, instead of a cold cut
+// hidden not drawn at all -- never read
+// auto (the default) full when the read reads it; else carry when it
+// is the item before (carry: auto), else context
+//
+// THE MOTION: a read tile is shown in full while it is read; when the next
+// piece starts, it SHRINKS (`shrink`) and DIMS (`dim`) over `seconds`, and the
+// tile being read next is revealed (`reveal`) under it -- older up top -- the
+// column panned (`pan` s, eased) so the new piece sits under a strip of what it
+// answers. A quoted post is never shrunk: it dims once it has been read.
+//
+// THE GUARD (threadReadErrors; the build's lint): a part whose role is a tile
+// that is hidden or context, a part no text on the card reads, or a threaded
+// read with read-follow off is refused, with the fix.
+//
+// PURE and dependency-free (but its siblings): the plan, the build, Play, the
+// bench, the writers and the lint all read the same rules from here.
+
+import { cardText, contextText, parentsOf } from "./post-item.mjs";
+import { draftScript, isNarrated, pickedTake, scriptParts } from "./post-narration.mjs";
+import { normWord, scriptWordsOf } from "./word-zoom.mjs";
+import { followKnobs } from "./read-follow.mjs";
+
+/** What a context tile may be. */
+export const THREAD_MODES = Object.freeze(["auto", "full", "excerpt", "context", "carry", "hidden"]);
+export const THREAD_DEFAULTS = Object.freeze({ parent: "auto", quoted: "auto", carry: "auto", reveal: true, shrink: 0.62, dim: 0.5, seconds: 0.7, pan: 0.7 });
+export const THREAD_LIMITS = Object.freeze({ shrink: [0.3, 1], dim: [0.15, 1], seconds: [0, 3], pan: [0.1, 3] });
+/** The share of a piece's words the text it reads must hold (else it is matched to no text). */
+const ROLE_MIN = 0.5;
+/** The share of the window kept for the post a new piece answers (its foot above the new piece). */
+export const THREAD_CONTEXT_ROOM = 0.3;
+
+const KEYS = new Set(Object.keys(THREAD_DEFAULTS));
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const str = (v) => (typeof v === "string" ? v : "");
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const ROLE_RE = /^(post|quoted|parent:\d|media:\d)$/;
+
+// ---------------------------------------------------------------------------
+// The knobs.
+// ---------------------------------------------------------------------------
+
+const modeOk = (v, carryOk) => typeof v === "string" && THREAD_MODES.includes(v) && (carryOk || v !== "carry");
+
+/** One thread knob's errors (`where`: its path in the manifest). */
+export function threadKnobErrors(v, where) {
+ if (v === undefined || v === null) return [];
+ if (!isObj(v)) return [`${where} must be { parent?, quoted?, carry?, reveal?, shrink?, dim?, seconds?, pan? }`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!KEYS.has(k)) errors.push(`${where}.${k} is not a thread knob (${[...KEYS].join(", ")})`);
+ if (v.parent !== undefined) {
+ const list = Array.isArray(v.parent) ? v.parent : [v.parent];
+ if (!list.length || list.length > 2 || !list.every((m) => modeOk(m, true))) errors.push(`${where}.parent must be one of ${THREAD_MODES.join(", ")} (or a list of them, nearest parent first)`);
+ }
+ if (v.quoted !== undefined && !modeOk(v.quoted, false)) errors.push(`${where}.quoted must be one of ${THREAD_MODES.filter((m) => m !== "carry").join(", ")}`);
+ if (v.carry !== undefined && !(v.carry === "auto" || typeof v.carry === "boolean")) errors.push(`${where}.carry must be auto, true or false`);
+ if (v.reveal !== undefined && typeof v.reveal !== "boolean") errors.push(`${where}.reveal must be true or false`);
+ for (const k of ["shrink", "dim", "seconds", "pan"]) {
+ if (v[k] !== undefined && !(fin(v[k]) && v[k] >= THREAD_LIMITS[k][0] && v[k] <= THREAD_LIMITS[k][1])) {
+ errors.push(`${where}.${k} must be ${THREAD_LIMITS[k][0]}–${THREAD_LIMITS[k][1]}${k === "shrink" ? " (a context post's size)" : k === "dim" ? " (a context post's opacity)" : " seconds"}`);
+ }
+ }
+ return errors;
+}
+
+/** A post item's `thread` errors (validatePostItem). */
+export const validatePostThread = (e) => threadKnobErrors(e?.thread, `timeline ${e?.id ?? "?"}.thread`);
+
+const pick = (o) => (isObj(o) ? Object.fromEntries(Object.entries(o).filter(([k, v]) => KEYS.has(k) && v !== undefined && v !== null)) : {});
+
+/**
+ * One post's thread knobs: its own, else the cut's (`render.postNarration.thread`), else the defaults.
+ * @param {Record<string, any> | null | undefined} entry
+ * @param {Record<string, any>} [render]
+ * @returns {{ parent: string | string[], quoted: string, carry: "auto"|boolean, reveal: boolean, shrink: number, dim: number, seconds: number, pan: number }}
+ */
+export function threadKnobs(entry, render = undefined) {
+ const r = isObj(render?.postNarration) ? render.postNarration.thread : undefined;
+ return /** @type {any} */ ({ ...THREAD_DEFAULTS, ...pick(r), ...pick(entry?.thread) });
+}
+
+/** Parent `i`'s mode as the knobs set it (before `auto` is resolved). */
+const parentKnob = (k, i) => (Array.isArray(k.parent) ? k.parent[i] ?? k.parent[k.parent.length - 1] : k.parent) ?? "auto";
+
+// ---------------------------------------------------------------------------
+// THE ROLES: which text each part of the read reads.
+// ---------------------------------------------------------------------------
+
+const keyOf = (w) => normWord(w).replace(/'/g, "");
+/** A text's words as matching sees them: normalized, a "this/that" split at its slash, the voice's "slash" dropped. */
+const keysOf = (t) => scriptWordsOf(t).flatMap((w) => w.split("/")).map(keyOf).filter((k) => k && k !== "slash");
+const pairsOf = (keys) => keys.slice(1).map((k, i) => `${keys[i]} ${k}`);
+
+/**
+ * The texts a read may read, in the order the read reads them: the parents
+ * (nearest first), the quoted post, his words -- each as its words and its
+ * word PAIRS, over every form it may be read in (as written, its paraphrase,
+ * as a voice says it).
+ */
+export function readTexts(entry) {
+ const out = [];
+ const spoken = (t) => (str(t).trim() ? draftScript(t).script : "");
+ const add = (role, forms) => {
+ const lists = forms.filter((t) => str(t).trim()).map(keysOf);
+ if (!lists.some((l) => l.length)) return;
+ out.push({ role, keys: new Set(lists.flat()), pairs: new Set(lists.flatMap(pairsOf)) });
+ };
+ parentsOf(entry).forEach((p, i) => add(`parent:${i}`, [contextText(p), str(p.text), spoken(contextText(p)), spoken(p.text)]));
+ if (isObj(entry?.quoted)) {
+ const q = entry.quoted;
+ add("quoted", [contextText(q), str(q.text), spoken(contextText(q)), spoken(q.text)]);
+ }
+ add("post", [cardText(entry), str(entry?.narration?.script), spoken(cardText(entry))]);
+ return out;
+}
+
+/** The share of a piece's words a text holds: by word pairs, in order (one word a pair: by words). */
+function shareOf(keys, text) {
+ if (keys.length >= 3) {
+ const pairs = pairsOf(keys);
+ return pairs.filter((p) => text.pairs.has(p)).length / pairs.length;
+ }
+ return keys.filter((w) => text.keys.has(w)).length / keys.length;
+}
+
+/** The read's order of the roles (a parent before the quoted post before his words). */
+const orderOf = (role) => (role.startsWith("parent:") ? 2 - Number(role.slice(7)) / 10 : role === "quoted" ? 3 : role === "post" ? 4 : 5);
+
+/**
+ * THE ROLES of the picked take's parts, pure: `[{ role, source }]` (one a
+ * part; `role` null: no text on the card reads it; `source` "stored" or
+ * "inferred"). Empty when the item has no take with parts.
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any> | null} [take] a take other than the picked one
+ */
+export function partRoles(entry, take = undefined) {
+ const t = take === undefined ? pickedTake(entry) : take;
+ let parts = Array.isArray(t?.parts) ? t.parts : [];
+ // A take read in one go (no parts): its script's parts, as read-follow times them -- each paragraph a piece.
+ if (!parts.length && t) {
+ const script = str(t.script).trim() ? t.script : str(entry?.narration?.script);
+ parts = scriptParts(script).map((p) => ({ text: p.text, para: p.para * 100 }));
+ }
+ if (!parts.length) return [];
+ const texts = readTexts(entry);
+ const images = (Array.isArray(entry?.media) ? entry.media : []).map((m, i) => ({ m, i })).filter((x) => x.m?.kind === "image");
+ // The pieces: consecutive parts of one `para` div 100 (a take of one piece: all of it).
+ const pieceOf = (p) => (Number.isInteger(p?.para) ? Math.floor(p.para / 100) : 0);
+ const groups = [];
+ parts.forEach((p, k) => {
+ const g = groups[groups.length - 1];
+ if (g && g.piece === pieceOf(p)) g.parts.push(k);
+ else groups.push({ piece: pieceOf(p), parts: [k] });
+ });
+ const out = parts.map((p) => (typeof p?.role === "string" && ROLE_RE.test(p.role) ? { role: p.role, source: "stored" } : null));
+ let floor = 0;
+ for (const g of groups) {
+ const stored = g.parts.map((k) => out[k]).filter(Boolean);
+ if (stored.length === g.parts.length) {
+ floor = Math.max(floor, orderOf(stored[stored.length - 1].role));
+ continue;
+ }
+ const keys = keysOf(g.parts.map((k) => str(parts[k].text)).join(" "));
+ let role = null;
+ if (keys.length) {
+ const scored = texts.map((x) => ({ role: x.role, share: shareOf(keys, x) }));
+ const best = Math.max(...scored.map((x) => x.share));
+ if (best >= ROLE_MIN) {
+ // Among the near-best, the one the read's order expects (never back up the thread).
+ // A new piece reads another text than the one before it: among the near-best, the next one along.
+ const near = scored.filter((x) => x.share >= best - 0.05);
+ const ahead = near.filter((x) => orderOf(x.role) > floor);
+ const fwd = near.filter((x) => orderOf(x.role) >= floor);
+ role = (ahead.length && floor > 0 ? ahead : fwd.length ? fwd : near).sort((a, b) => b.share - a.share || orderOf(a.role) - orderOf(b.role))[0].role;
+ }
+ }
+ // Words no text holds, on an item with a picture: read off the picture (a screenshot).
+ if (!role && images.length) role = `media:${images[0].i}`;
+ if (role) floor = Math.max(floor, orderOf(role));
+ for (const k of g.parts) out[k] ??= { role, source: "inferred" };
+ }
+ return out;
+}
+
+/**
+ * The read's PIECES in order: `[{ role, parts: [k…] }]` -- runs of parts of one role.
+ * @param {Record<string, any>} entry
+ * @param {Array<{ role: string | null, source?: string }>} [roles]
+ */
+export function readPieces(entry, roles = partRoles(entry)) {
+ const out = [];
+ roles.forEach((r, k) => {
+ const last = out[out.length - 1];
+ if (last && last.role === r.role) last.parts.push(k);
+ else out.push({ role: r.role, parts: [k] });
+ });
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// THE TILES: what each context post is on screen.
+// ---------------------------------------------------------------------------
+
+/** The archive id of an item's post (`<channel>/<postId>` → `<postId>`). */
+const postIdOf = (e) => String(e?.post ?? "").split("/")[1] ?? "";
+
+/**
+ * THE THREAD LAYOUT, pure: `{ on, tiles: [{ scope, mode, read }], roles }` --
+ * the tiles top to bottom (the parents oldest first, "post", then "quoted"
+ * inside it), each with its resolved mode (never "auto") and whether the read
+ * reads it. `on`: the card is threaded (a narrated item with a context tile
+ * drawn; read-follow on is the caller's to require). `prev`: the item before
+ * it in the cut (a parent that is that item is carried).
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {{ prev?: Record<string, any> | null }} [o]
+ */
+export function threadLayout(entry, render = undefined, { prev = null } = {}) {
+ const k = threadKnobs(entry, render);
+ const roles = isNarrated(entry) ? partRoles(entry) : [];
+ const read = new Set(roles.map((r) => r.role).filter(Boolean));
+ const prevId = prev ? postIdOf(prev) : "";
+ const tiles = [];
+ const parents = parentsOf(entry);
+ for (let i = parents.length - 1; i >= 0; i -= 1) {
+ const scope = `parent:${i}`;
+ if (!contextText(parents[i]).trim()) continue;
+ let mode = parentKnob(k, i);
+ const isRead = read.has(scope);
+ if (mode === "auto") {
+ const carry = k.carry === true || (k.carry === "auto" && !!prevId && String(parents[i].id ?? "") === prevId);
+ mode = isRead ? "full" : carry ? "carry" : "context";
+ }
+ if (mode === "carry" && isRead) mode = "full";
+ tiles.push({ scope, mode, read: isRead });
+ }
+ tiles.push({ scope: "post", mode: "full", read: read.has("post") });
+ if (isObj(entry?.quoted) && contextText(entry.quoted).trim()) {
+ const m = k.quoted === "auto" ? (read.has("quoted") ? "full" : "context") : k.quoted;
+ tiles.push({ scope: "quoted", mode: m, read: read.has("quoted") });
+ }
+ const on = isNarrated(entry) && tiles.some((t) => t.scope !== "post" && t.mode !== "hidden");
+ return { on, tiles, roles };
+}
+
+/** A tile's mode in a layout (null: no such tile). */
+export const tileModeOf = (layout, scope) => layout?.tiles?.find((t) => t.scope === scope)?.mode ?? null;
+
+// ---------------------------------------------------------------------------
+// THE GUARD: never narrate hidden text.
+// ---------------------------------------------------------------------------
+
+const ROLE_NAME = (r) => (r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r.startsWith("parent:") ? (r === "parent:0" ? "the post it answers" : "the post that one answers") : `the words on attachment ${Number(r.slice(6)) + 1}`);
+
+/**
+ * Every reason post item `entry`'s read narrates text the card does not show,
+ * as sentences with the fix (empty: every part is on screen while it is said).
+ * `followOn`: its read-follow (read-follow.mjs followKnobs(...).on).
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {{ prev?: Record<string, any> | null, followOn?: boolean }} [o]
+ */
+export function threadReadErrors(entry, render = undefined, { prev = null, followOn = true } = {}) {
+ if (!isNarrated(entry)) return [];
+ const w = `timeline ${entry?.id ?? "?"}`;
+ const L = threadLayout(entry, render, { prev });
+ const errors = [];
+ const fix = `umtool posts set-item <p> ${entry?.id ?? "<item>"}`;
+ const remake = `or re-make the read without it (umtool posts narrate <p> ${entry?.id ?? "<item>"} --take, a script that leaves it out)`;
+ L.roles.forEach((r, k) => {
+ const n = k + 1;
+ if (!r.role) {
+ errors.push(`${w}: its take's part ${n} reads words the card does not show (no text on it holds them) -- set its role (umtool posts roles <p> ${entry?.id ?? "<item>"} --set ${n}=post|quoted|parent:0|media:0) ${remake}`);
+ return;
+ }
+ if (r.role.startsWith("media:")) {
+ const m = (entry?.media ?? [])[Number(r.role.slice(6))];
+ if (!m) errors.push(`${w}: its take's part ${n} reads attachment ${Number(r.role.slice(6)) + 1}, which it does not have -- set its role (umtool posts roles)`);
+ return;
+ }
+ const mode = tileModeOf(L, r.role);
+ if (mode === null) errors.push(`${w}: its take's part ${n} reads ${ROLE_NAME(r.role)}, which the item does not carry -- set its role (umtool posts roles) ${remake}`);
+ else if (mode === "hidden" || mode === "context") {
+ const knob = r.role === "quoted" ? "thread.quoted" : "thread.parent";
+ errors.push(`${w}: its take's part ${n} reads ${ROLE_NAME(r.role)}, which is drawn ${mode === "hidden" ? "hidden (not at all)" : "as context (small and dim)"} -- show it (${fix} ${knob}=full) ${remake}`);
+ }
+ });
+ if (L.on && !followOn && L.roles.some((r) => r.role && r.role !== "post" && !r.role.startsWith("media:"))) {
+ errors.push(`${w}: its read reads the post it answers or quotes, and its read-follow is off -- the card can only show a context post in full while it is read with it on (${fix} follow=on) ${remake}`);
+ }
+ return [...new Set(errors)];
+}
+
+// ---------------------------------------------------------------------------
+// THE SCHEDULE: each tile's size and strength on the item's clock.
+// ---------------------------------------------------------------------------
+
+/**
+ * THE THREAD SCHEDULE, pure (read-follow's plan carries it, `follow.thread`):
+ * `{ shrink, dim, seconds, pan, tiles: [{ scope, mode, read, from: [s, op],
+ * to: [s, op], t0, t1 }] }` -- a tile at `from` until t0, eased to `to` by t1
+ * (s its scale, op its opacity). `blocks`: read-follow's scheduled blocks
+ * (each `{ scope, part, start }`); `roles`: the parts' roles; `layout`:
+ * threadLayout's. Null when the card is not threaded.
+ */
+export function threadSchedule(entry, render, { layout, blocks, lead = 0.4 }) {
+ if (!layout?.on) return null;
+ const k = threadKnobs(entry, render);
+ const roles = layout.roles;
+ // Each read piece's start on the item's clock: its first block's start.
+ const startOfPart = new Map();
+ for (const b of blocks) if (b.part !== null && b.start !== null && !startOfPart.has(b.part)) startOfPart.set(b.part, b.start);
+ const pieces = readPieces(entry, roles).map((p) => {
+ const ts = p.parts.map((n) => startOfPart.get(n)).filter(fin);
+ return { ...p, start: ts.length ? Math.min(...ts) : null };
+ }).filter((p) => p.start !== null && p.role);
+ // A tile's pieces (the quoted post reads inside his post's tile: the post tile shows for both).
+ const tileOf = (role) => (role === "quoted" ? "quoted" : role);
+ const firstRead = (scope) => pieces.find((p) => tileOf(p.role) === scope || (scope === "post" && p.role === "quoted"))?.start ?? null;
+ /** The start of the first piece after the last piece of `scope` that is of another tile. */
+ const after = (scope) => {
+ let last = -1;
+ pieces.forEach((p, i) => {
+ if (p.role === scope) last = i;
+ });
+ if (last < 0) return null;
+ const next = pieces.slice(last + 1).find((p) => p.role !== scope);
+ return next ? next.start : null;
+ };
+ const first = pieces[0] ?? null;
+ const win = (T) => {
+ const t0 = r3(Math.max(0, T - lead));
+ return { t0, t1: r3(t0 + k.seconds) };
+ };
+ const small = [k.shrink, k.dim];
+ // A carried parent opens the item alone: what the read reads first comes in under it as it gives way.
+ const carried = layout.tiles.some((t) => t.mode === "carry");
+ const revealed = (scope, T0) => !!k.reveal && !!first && T0 !== null && (first.start < T0 - 1e-6 ? first.role !== scope : carried) && !first.role.startsWith("media:");
+ const tiles = [];
+ for (const t of layout.tiles) {
+ if (t.mode === "hidden") continue;
+ const row = { scope: t.scope, mode: t.mode, read: t.read, from: [1, 1], to: [1, 1], t0: 0, t1: 0 };
+ if (t.scope === "post") {
+ // His post: revealed when its first piece (or the quoted post inside it) starts, when something else is read first.
+ const T = firstRead("post");
+ if (revealed("post", T) && (carried || first.role !== "quoted")) {
+ row.from = [1, 0];
+ Object.assign(row, win(T));
+ }
+ } else if (t.mode === "context") {
+ row.from = t.scope === "quoted" ? [1, k.dim] : small;
+ row.to = row.from;
+ } else if (t.mode === "carry") {
+ // It opens as the item before ended, and gives way as the read begins.
+ if (first) {
+ row.to = small;
+ Object.assign(row, win(first.start));
+ }
+ } else if (t.read) {
+ // Read: in full while it is read, then small and dim (a quoted post only dims) as the next piece starts.
+ const T = after(t.scope);
+ const T0 = firstRead(t.scope);
+ if (t.scope !== "quoted" && revealed(t.scope, T0)) {
+ // Revealed when its read comes (an older post read before it).
+ row.from = [1, 0];
+ row.to = [1, 1];
+ Object.assign(row, win(T0));
+ if (T !== null) row.then = { to: small, ...win(T) };
+ } else if (T !== null) {
+ row.to = t.scope === "quoted" ? [1, k.dim] : small;
+ Object.assign(row, win(T));
+ }
+ }
+ tiles.push(row);
+ }
+ return { shrink: k.shrink, dim: k.dim, seconds: k.seconds, pan: k.pan, contextRoom: THREAD_CONTEXT_ROOM, tiles };
+}
+
+/** inOut cubic over [0, 1]. */
+const ease = (x) => {
+ const v = Math.min(1, Math.max(0, x));
+ return v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2;
+};
+const mix = (a, b, f) => a + (b - a) * f;
+
+/** One tile's `[scale, opacity]` at item second `s` (seek-safe). */
+export function tileStateAt(row, s) {
+ const step = (from, to, t0, t1) => {
+ if (s <= t0) return from;
+ if (s >= t1) return to;
+ const f = ease((s - t0) / Math.max(1e-6, t1 - t0));
+ return [mix(from[0], to[0], f), mix(from[1], to[1], f)];
+ };
+ let v = step(row.from, row.to, row.t0, row.t1);
+ if (row.then && s > row.then.t0) v = step(row.to, row.then.to, row.then.t0, row.then.t1);
+ return [Math.round(v[0] * 1000) / 1000, Math.round(v[1] * 1000) / 1000];
+}
+
+/** Every tile's state at `s`: `{ <scope>: [scale, opacity] }`. */
+export function threadStateAt(thread, s) {
+ const out = {};
+ for (const row of thread?.tiles ?? []) out[row.scope] = tileStateAt(row, s);
+ return out;
+}
+
+/** The times a tile's state changes (the starts and ends of its transitions). */
+export function threadTimes(thread) {
+ const out = new Set();
+ for (const row of thread?.tiles ?? []) {
+ if (row.t1 > row.t0) out.add(row.t0).add(row.t1);
+ if (row.then) out.add(row.then.t0).add(row.then.t1);
+ }
+ return [...out].sort((a, b) => a - b);
+}
+
+// ---------------------------------------------------------------------------
+// THE GEOMETRY under the tiles' scales (pure: the pan's path is worked out
+// from the page measured once, at every tile's full size).
+// ---------------------------------------------------------------------------
+
+/**
+ * Where the flow's things are with the tiles at `scales` (`{ <scope>: s }`):
+ * `{ C, top(y), blocks: { <k>: { top, bottom } } }`. `geo` is measureFollow's
+ * (its `tiles`: `{ <scope>: { top, height } }` at full size, `blockTile`: the
+ * tile each block is in). A tile shrinks about its top-left corner and the
+ * flow below it closes up.
+ */
+export function threadGeoAt(geo, scales) {
+ const tiles = Object.entries(geo?.tiles ?? {}).map(([scope, t]) => ({ scope, ...t, s: fin(scales?.[scope]) ? scales[scope] : 1 })).sort((a, b) => a.top - b.top);
+ const shift = (y) => {
+ let d = 0;
+ for (const t of tiles) {
+ if (t.s >= 0.9995) continue;
+ if (y >= t.top + t.height - 0.5) d += (1 - t.s) * t.height;
+ else if (y > t.top) d += (1 - t.s) * (y - t.top);
+ }
+ return y - d;
+ };
+ const blocks = {};
+ for (const [k, b] of Object.entries(geo?.blocks ?? {})) blocks[k] = { top: shift(b.top), bottom: shift(b.bottom) };
+ const tileTops = {};
+ for (const t of tiles) tileTops[t.scope] = { top: shift(t.top), bottom: shift(t.top + t.height) };
+ return { C: shift(geo?.C ?? 0), blocks, tiles: tileTops };
+}
+
+/**
+ * THE GUARD over a cut (the build's lint): every post item's read against
+ * what its card shows (threadReadErrors), each with the item before it.
+ */
+export function validateThreadReads(manifest) {
+ const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ const errors = [];
+ tl.forEach((e, i) => {
+ if (e?.type !== "post") return;
+ errors.push(...threadReadErrors(e, manifest?.render, { prev: tl[i - 1] ?? null, followOn: followKnobs(e, manifest?.render).on }));
+ });
+ return errors;
+}
diff --git a/umtool/report-to-video/post-thread.test.mjs b/umtool/report-to-video/post-thread.test.mjs
@@ -0,0 +1,222 @@
+// post-thread.mjs: a post item's THREAD READ -- each part's role (the text it
+// reads: the post it answers, the post it quotes, his words, an attachment's),
+// what the card shows for each, the guard that refuses narrating hidden text,
+// and THE INVARIANT: every part's time span lies inside its block's on-screen,
+// highlighted interval -- its tile in full, its block lit, in the window.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { postCardHtml, postItemPlan, validatePostItem } from "./post-item.mjs";
+import { validatePostNarrationRender } from "./post-narration.mjs";
+import { followPath, followStateAt, followStateKey } from "./read-follow.mjs";
+import {
+ THREAD_DEFAULTS, partRoles, readPieces, threadGeoAt, threadKnobs, threadLayout, threadReadErrors, threadStateAt, tileStateAt, validateThreadReads,
+} from "./post-thread.mjs";
+
+const PARENT = "The first thing anyone notices is the noise from the street.\n\nThen the lights in the hall go out without warning.\n\nNobody had planned for any of this at all.";
+const REPLY = "That is exactly what I was saying yesterday morning.\n\nWe should have bought the generator in the spring.";
+const QUOTED = "Here is the plan for the weekend repairs on the roof.";
+const parentRef = (o = {}) => ({ id: "900", author: "Neighbour", handle: "neighbour_one", date: "2026-10-26T19:09:24.000Z", text: PARENT, ...o });
+const base = (o = {}) => ({
+ type: "post", id: "p-1", post: "acct-x/1001", platform: "x", author: "Subject", handle: "subject", date: "2026-10-27T02:41:55.000Z", text: REPLY, ...o,
+});
+/** A take as the batch assembles one: pieces in order (para = piece * 100 + paragraph), each paragraph a part. */
+function take(pieces, { roles = false } = {}) {
+ const parts = [];
+ let at = 0;
+ pieces.forEach(([text, role], pi) => {
+ text.split(/\n\n/).forEach((para, k) => {
+ const seconds = Math.round((para.split(/\s+/).length / 3) * 100) / 100;
+ at += parts.length ? (k === 0 ? 0.8 : 0.6) : 0;
+ parts.push({ n: parts.length + 1, para: pi * 100 + k, text: para, start: Math.round(at * 100) / 100, seconds, ...(roles ? { role } : {}) });
+ at += seconds;
+ });
+ });
+ return { file: "narration/posts/1001/take-1.orpheus-thread.wav", engine: "orpheus", voice: "leo+zac", seconds: Math.round(at * 100) / 100, script: pieces.map((p) => p[0]).join("\n\n"), parts };
+}
+const narrate = (e, pieces, o) => ({ ...e, narration: { script: e.text, takes: [take(pieces, o)], pick: 0 } });
+
+test("roles: the parent read first (para 0..), his words after (100..), matched by word pairs -- not by a bag of common words", () => {
+ const e = narrate(base({ parents: [parentRef()] }), [[PARENT, "parent:0"], [REPLY, "post"]]);
+ assert.deepEqual(partRoles(e).map((r) => r.role), ["parent:0", "parent:0", "parent:0", "post", "post"]);
+ assert.ok(partRoles(e).every((r) => r.source === "inferred"));
+ assert.deepEqual(readPieces(e).map((p) => [p.role, p.parts]), [["parent:0", [0, 1, 2]], ["post", [3, 4]]]);
+ // A quoted post read first, then his words.
+ const q = narrate(base({ quoted: { author: "Other", handle: "other", text: QUOTED } }), [[QUOTED], [REPLY]]);
+ assert.deepEqual(partRoles(q).map((r) => r.role), ["quoted", "post", "post"]);
+ // A stored role wins.
+ const s = narrate(base({ parents: [parentRef()] }), [[PARENT, "quoted"], [REPLY, "post"]], { roles: true });
+ assert.equal(partRoles(s)[0].role, "quoted");
+ assert.equal(partRoles(s)[0].source, "stored");
+});
+
+test("roles: words no text holds are an attachment's when the post has a picture (a screenshot read first), else no text's; a two-word reply that repeats its parent's words still reads his", () => {
+ const shot = "Someone wrote a long thing about the council meeting going sideways again.";
+ const withPic = narrate(base({ media: [{ src: "posts-media/a/1.png", kind: "image", width: 600, height: 700 }] }), [[shot], [REPLY]]);
+ assert.deepEqual(partRoles(withPic).map((r) => r.role), ["media:0", "post", "post"]);
+ const without = narrate(base(), [[shot], [REPLY]]);
+ assert.equal(partRoles(without)[0].role, null);
+ // His two words are in the parent too: a new piece reads the next text along.
+ const tiny = narrate(base({ text: "It wobbles.", parents: [parentRef({ text: "Look how it wobbles, oh my word." })] }), [["Look how it wobbles, oh my word."], ["It wobbles."]]);
+ assert.deepEqual(partRoles(tiny).map((r) => r.role), ["parent:0", "post"]);
+});
+
+test("the layout: a read parent full, an unread one context -- carried when it is the item before; hidden and excerpt are knobs", () => {
+ const e = narrate(base({ parents: [parentRef()] }), [[PARENT], [REPLY]]);
+ const L = threadLayout(e);
+ assert.equal(L.on, true);
+ assert.deepEqual(L.tiles.map((t) => [t.scope, t.mode, t.read]), [["parent:0", "full", true], ["post", "full", true]]);
+ // His own reply only: the parent unread -- context, or carried when it is the item before.
+ const own = narrate(base({ parents: [parentRef()] }), [[REPLY]]);
+ assert.equal(threadLayout(own).tiles[0].mode, "context");
+ assert.equal(threadLayout(own, undefined, { prev: { type: "post", id: "p-0", post: "acct-x/900" } }).tiles[0].mode, "carry");
+ assert.equal(threadLayout({ ...own, thread: { carry: false } }, undefined, { prev: { post: "acct-x/900" } }).tiles[0].mode, "context");
+ assert.equal(threadLayout({ ...own, thread: { parent: "hidden" } }).tiles[0].mode, "hidden");
+ // Un-narrated: never threaded (the card as it was).
+ assert.equal(threadLayout(base({ parents: [parentRef()] })).on, false);
+ // The cut's default, the post's own over it.
+ assert.equal(threadKnobs({}, { postNarration: { thread: { shrink: 0.5 } } }).shrink, 0.5);
+ assert.equal(threadKnobs({ thread: { shrink: 0.7 } }, { postNarration: { thread: { shrink: 0.5 } } }).shrink, 0.7);
+ assert.equal(threadKnobs({}).dim, THREAD_DEFAULTS.dim);
+});
+
+test("THE GUARD: a part read off a hidden or context post, off no text on the card, or a threaded read with follow off is refused, with the fix", () => {
+ const e = narrate(base({ parents: [parentRef()] }), [[PARENT], [REPLY]]);
+ assert.deepEqual(threadReadErrors(e), []);
+ const hidden = threadReadErrors({ ...e, thread: { parent: "hidden" } });
+ assert.equal(hidden.length, 3);
+ assert.match(hidden[0], /part 1 reads the post it answers, which is drawn hidden.*thread\.parent=full.*re-make the read without it/);
+ assert.match(threadReadErrors({ ...e, thread: { parent: "context" } })[0], /drawn as context/);
+ assert.match(threadReadErrors(e, undefined, { followOn: false }).join(" "), /read-follow is off.*follow=on/);
+ const lost = narrate(base(), [["Words from somewhere nobody can see on the card."], [REPLY]]);
+ assert.match(threadReadErrors(lost)[0], /part 1 reads words the card does not show.*umtool posts roles/);
+ // Over a cut: each item with the one before it.
+ const m = { render: {}, timeline: [base({ id: "p-0", post: "acct-x/900", text: PARENT }), narrate(base({ parents: [parentRef()] }), [[REPLY]])] };
+ assert.deepEqual(validateThreadReads(m), []);
+ // The knobs' own errors.
+ assert.match(validatePostItem({ ...e, thread: { parent: "huge", shrink: 2 } }).join(" "), /thread\.parent must be one of.*thread\.shrink must be 0\.3–1/);
+ assert.match(validatePostNarrationRender({ postNarration: { thread: { quoted: "carry" } } }).join(" "), /render\.postNarration\.thread\.quoted/);
+});
+
+test("the schedule: the parent in full while it is read, shrunk and dimmed as his reply comes in -- revealed under it; a carried parent gives way as the read starts", () => {
+ const e = narrate(base({ parents: [parentRef()] }), [[PARENT], [REPLY]]);
+ const plan = postItemPlan(e, { postNarration: { lead: 0.4 } });
+ const th = plan.follow.thread;
+ const [par, post] = th.tiles;
+ assert.deepEqual([par.scope, par.from, par.to], ["parent:0", [1, 1], [THREAD_DEFAULTS.shrink, THREAD_DEFAULTS.dim]]);
+ assert.deepEqual([post.scope, post.from, post.to], ["post", [1, 0], [1, 1]]);
+ // His first part starts at lead + its start in the take; the change begins FOLLOW_PAN.lead before it.
+ const replyStart = plan.follow.blocks.find((b) => b.scope === "post" && b.part === 3).start;
+ assert.equal(par.t0, Math.round((replyStart - 0.4) * 1000) / 1000);
+ assert.equal(par.t1, Math.round((par.t0 + THREAD_DEFAULTS.seconds) * 1000) / 1000);
+ assert.deepEqual(tileStateAt(par, 1), [1, 1]);
+ assert.deepEqual(tileStateAt(par, par.t1 + 0.01), [THREAD_DEFAULTS.shrink, THREAD_DEFAULTS.dim]);
+ assert.deepEqual(threadStateAt(th, 1).post, [1, 0]);
+ // Carried: in full at the first frame, small and dim once the read is under way, his reply revealed.
+ const own = narrate(base({ parents: [parentRef()] }), [[REPLY]]);
+ const cp = postItemPlan(own, {}, { prev: { post: "acct-x/900" } });
+ const carry = cp.follow.thread.tiles.find((t) => t.scope === "parent:0");
+ assert.equal(carry.mode, "carry");
+ assert.deepEqual(tileStateAt(carry, 0), [1, 1]);
+ assert.deepEqual(tileStateAt(carry, 2), [THREAD_DEFAULTS.shrink, THREAD_DEFAULTS.dim]);
+ assert.deepEqual(threadStateAt(cp.follow.thread, 0).post, [1, 0]);
+ assert.deepEqual(threadStateAt(cp.follow.thread, 2).post, [1, 1]);
+});
+
+test("the geometry: a tile shrunk about its corner closes the flow up under it", () => {
+ const geo = { H: 500, C: 1000, tiles: { "parent:0": { top: 0, height: 400 }, post: { top: 420, height: 580 } }, blocks: { 0: { top: 100, bottom: 200 }, 1: { top: 500, bottom: 600 } } };
+ const g = threadGeoAt(geo, { "parent:0": 0.5 });
+ assert.deepEqual(g.blocks[0], { top: 50, bottom: 100 });
+ assert.deepEqual(g.blocks[1], { top: 300, bottom: 400 });
+ assert.equal(g.C, 800);
+ assert.deepEqual(g.tiles.post, { top: 220, bottom: 800 });
+});
+
+/**
+ * A page's geometry for an entry, as measureFollow reports it: each tile's blocks stacked at `line` px a
+ * paragraph's line (a block's words / 6 lines), a head over each tile, the window `H` tall.
+ */
+function fakeGeo(plan, { H = 520, line = 44 } = {}) {
+ const blocks = {};
+ const tiles = {};
+ let y = 0;
+ const order = plan.follow.thread.tiles.map((t) => t.scope);
+ for (const scope of order) {
+ const top = y;
+ y += 70;
+ for (const b of plan.follow.blocks.filter((x) => x.scope === scope)) {
+ const h = Math.max(1, Math.ceil((b.to - b.from + 1) / 6)) * line;
+ blocks[b.k] = { top: y, bottom: y + h };
+ y += h + line;
+ }
+ tiles[scope] = { top, height: y - top };
+ y += 22;
+ }
+ return { H, C: y, blocks, tiles };
+}
+
+test("THE INVARIANT: every part's time span lies inside its block's on-screen, highlighted interval -- its tile in full, its block lit, inside the window", () => {
+ const cases = [
+ ["a parent read first", narrate(base({ parents: [parentRef()] }), [[PARENT], [REPLY]]), null],
+ ["a quoted post read first", narrate(base({ quoted: { author: "Other", handle: "other", text: `${QUOTED}\n\n${PARENT}` } }), [[`${QUOTED}\n\n${PARENT}`], [REPLY]]), null],
+ ["two parents, then him", narrate(base({ parents: [parentRef({ id: "901", handle: "second_one", text: "Is anyone else hearing the street noise again tonight?" }), parentRef()] }), [[PARENT], ["Is anyone else hearing the street noise again tonight?"], [REPLY]]), null],
+ ["a carried parent", narrate(base({ parents: [parentRef()] }), [[REPLY]]), { post: "acct-x/900" }],
+ ];
+ for (const [what, e, prev] of cases) {
+ const render = { postNarration: { lead: 0.4 } };
+ const plan = postItemPlan(e, render, { prev });
+ assert.ok(plan.follow?.thread, `${what}: threaded`);
+ const geo = fakeGeo(plan);
+ const path = followPath(plan.follow, geo);
+ const t = e.narration.takes[0];
+ const settle = 0.4 + Math.max(THREAD_DEFAULTS.pan, THREAD_DEFAULTS.seconds) - 0.4 + plan.follow.ease / 2 + 0.02;
+ t.parts.forEach((p, k) => {
+ const blk = plan.follow.blocks.find((b) => b.part === k);
+ assert.ok(blk, `${what}: part ${k + 1} has a block`);
+ const from = blk.start + settle;
+ const to = (t.parts[k + 1] ? plan.follow.blocks.find((b) => b.part === k + 1).start : plan.follow.readEnd) - 0.45;
+ for (let s = from; s <= to; s += 0.1) {
+ const st = followStateAt(plan.follow, path, s);
+ const [sc, op] = st.tiles[blk.scope];
+ assert.equal(sc, 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its tile (${blk.scope}) in full`);
+ if (blk.scope !== "quoted") assert.equal(op, 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its tile at full strength`);
+ else assert.equal(st.tiles.post[1], 1, `${what}: the post the quoted post is in, shown`);
+ assert.equal(st.op[blk.k] ?? 1, 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its block lit`);
+ assert.equal(st.current, blk.k, `${what}: part ${k + 1} is the block being read`);
+ const g = threadGeoAt(geo, Object.fromEntries(Object.entries(st.tiles).map(([x, v]) => [x, v[0]])));
+ const bb = g.blocks[blk.k];
+ assert.ok(bb.top - st.offset >= -1 && bb.bottom - st.offset <= geo.H + 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its block in the window (${(bb.top - st.offset).toFixed(0)}–${(bb.bottom - st.offset).toFixed(0)} of ${geo.H})`);
+ }
+ });
+ // A transition draws a different card every frame; a still read, one.
+ assert.notEqual(followStateKey(followStateAt(plan.follow, path, 0.5)), followStateKey(followStateAt(plan.follow, path, plan.follow.readEnd + 1)));
+ }
+});
+
+test("the card page: a threaded read draws the conversation as tiles in one flow -- each post whole (no clamp), a hidden one not at all, an excerpt without its unread paragraphs", () => {
+ const e = narrate(base({ parents: [parentRef()], quoted: { author: "Other", handle: "other", text: QUOTED } }), [[PARENT], [REPLY]]);
+ const plan = postItemPlan(e, {});
+ const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread });
+ assert.match(html, /data-post-thread="3"/);
+ for (const scope of ["parent:0", "post", "quoted"]) assert.ok(html.includes(`data-thread-slot="${scope}"`), scope);
+ assert.match(html, /data-w="parent:0:\d+">all\.<\/span>/, "the parent's last word is on the page");
+ assert.match(html, /\.tile \.tt \{ display: block; -webkit-line-clamp: none;/);
+ const hid = postItemPlan({ ...e, thread: { quoted: "hidden" } }, {});
+ assert.ok(!postCardHtml(e, { width: 1600, height: 900, follow: true, thread: hid.follow.thread }).includes('data-thread-slot="quoted"'));
+ // An excerpt: the parent read only in part -- its unread paragraph not drawn.
+ const part = narrate(base({ parents: [parentRef()] }), [["The first thing anyone notices is the noise from the street."], [REPLY]]);
+ const ex = postItemPlan({ ...part, thread: { parent: "excerpt" } }, {});
+ const exHtml = postCardHtml({ ...part, thread: { parent: "excerpt" } }, { width: 1600, height: 900, follow: true, thread: ex.follow.thread });
+ assert.match(exHtml, /data-thread-excerpt/);
+ assert.match(exHtml, /\[data-thread-tile="parent:0"\] \[data-post-block="\d+"\][^{]*\{ display: none; \}/);
+ // Not narrated: the card as it was (no tiles).
+ assert.ok(!postCardHtml(base({ parents: [parentRef()] }), { width: 1600, height: 900, follow: true, thread: null }).includes("data-thread-slot"));
+});
+
+test("a take read in one go (no parts): its script's paragraphs carry the roles -- the parent it reads is shown in full while the words share the read", () => {
+ const e = base({ parents: [parentRef()], narration: { script: REPLY, takes: [{ file: "narration/posts/1001/take-1.orpheus-zac.wav", seconds: 20, script: `${PARENT}\n\n${REPLY}` }], pick: 0 } });
+ assert.deepEqual(partRoles(e).map((r) => r.role), ["parent:0", "parent:0", "parent:0", "post", "post"]);
+ const plan = postItemPlan(e, {});
+ assert.equal(plan.follow.source, "script");
+ assert.deepEqual(plan.follow.thread.tiles.map((t) => [t.scope, t.mode]), [["parent:0", "full"], ["post", "full"]]);
+ assert.deepEqual(threadReadErrors(e), []);
+});
diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs
@@ -46,6 +46,7 @@
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";
+import { partRoles, threadGeoAt, threadLayout, threadSchedule, threadStateAt } from "./post-thread.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] });
@@ -194,9 +195,14 @@ function fitMatch(a, b, lo, hi) {
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 })) };
+ if (Array.isArray(t?.parts) && t.parts.length) {
+ // Each part's ROLE (post-thread.mjs): the text it reads -- a context post, his words, an attachment's.
+ const roles = partRoles(entry);
+ return { source: "take", parts: t.parts.map((p, k) => ({ text: str(p.text), start: fin(p.start) ? p.start : null, ...(roles[k]?.role ? { scope: roles[k].role } : {}) })) };
+ }
const script = str(t?.script).trim() ? t.script : str(entry?.narration?.script);
- return { source: "script", parts: scriptParts(script).map((p) => ({ text: p.text })) };
+ const roles = partRoles(entry);
+ return { source: "script", parts: scriptParts(script).map((p, k) => ({ text: p.text, ...(roles[k]?.role ? { scope: roles[k].role } : {}) })) };
}
const parts = [];
for (const sc of cardScopes(entry)) for (const p of scriptParts(sc.text)) parts.push({ text: p.text, scope: sc.scope });
@@ -214,7 +220,13 @@ 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 }]));
+ // A part read off an attachment (a screenshot's words, post-thread.mjs): a block with no words on the card.
+ const media = [];
parts.forEach((p, pi) => {
+ if (typeof p.scope === "string" && p.scope.startsWith("media:")) {
+ media.push({ scope: p.scope, from: null, to: null, part: pi });
+ return;
+ }
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.
@@ -278,6 +290,7 @@ export function followBlocks(entry) {
segs.sort((a, b) => a.from - b.from);
blocks.push(...segs);
}
+ blocks.push(...media);
return { source, parts: parts.length, blocks: blocks.map((b, k) => ({ k, ...b })) };
}
@@ -300,9 +313,9 @@ const wordsIn = (t) => scriptWordsOf(t).length;
*
* @param {Record<string, any>} entry
* @param {Record<string, any>} [render]
- * @param {{ hold?: number | null, narration?: Record<string, any> | null }} [o]
+ * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null }} [o]
*/
-export function followSchedule(entry, render = undefined, { hold = null, narration = undefined } = {}) {
+export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null } = {}) {
const k = followKnobs(entry, render);
if (!k.on) return null;
const map = followBlocks(entry);
@@ -348,7 +361,11 @@ export function followSchedule(entry, render = undefined, { hold = null, narrati
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 };
+ // THREADED (post-thread.mjs): a narrated read of the post it answers or quotes -- the card a column of tiles,
+ // each shown in full while it is read, then shrunk and dimmed as the next piece comes in.
+ const layout = isNarrated(entry) ? threadLayout(entry, render, { prev }) : null;
+ const thread = layout?.on ? threadSchedule(entry, render, { layout, blocks, lead: FOLLOW_PAN.lead }) : null;
+ return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks, ...(thread ? { thread } : {}) };
}
/** The block being read at item second `s` (its k), or null (before the read's first block, or none). */
@@ -369,6 +386,7 @@ export function followBlockAt(follow, s) {
* block's `{ top, bottom }` in the flow. No overflow: no segments.
*/
export function followPath(follow, geo) {
+ if (follow?.thread) return threadPath(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);
@@ -408,9 +426,96 @@ export function followPath(follow, geo) {
return { max, segments };
}
+/** The tile a block's scope is drawn in (a quoted post is a tile inside his post's). */
+const tileScopeOf = (scope) => (scope === "quoted" || scope === "post" || String(scope).startsWith("parent:") ? scope : null);
+
+/**
+ * A THREADED card's PAN (post-thread.mjs), pure: `{ thread: true, start,
+ * segments, H, C, tiles, max }` -- the column's offset at the first frame
+ * (`start`; negative: a column shorter than the window, centred in it) and
+ * its moves. The geometry is the page measured at every tile's full size
+ * (measureFollow), worked out under the tiles' scales at each move's end
+ * (threadGeoAt): the first block of each piece is brought in under a strip
+ * (THREAD_CONTEXT_ROOM of the window) of the post it answers, eased over the
+ * thread's `pan` seconds from the same moment the tile before it starts to
+ * shrink; a later block not in view pans as read-follow pans a post's own.
+ */
+export function threadPath(follow, geo) {
+ const th = follow.thread;
+ const H = fin(geo?.H) ? geo.H : 0;
+ const base = { thread: true, start: 0, segments: [], H, C: fin(geo?.C) ? geo.C : 0, tiles: geo?.tiles ?? {} };
+ if (!H) return { ...base, max: 0 };
+ const m = Math.round(H * FOLLOW_PAN.margin);
+ const lead = FOLLOW_PAN.lead;
+ const span = Math.max(th.seconds, th.pan);
+ const scalesAt = (t) => Object.fromEntries(Object.entries(threadStateAt(th, t)).map(([sc, v]) => [sc, v[0]]));
+ const at = (t) => threadGeoAt(geo, scalesAt(t));
+ const placed = (g, want) => {
+ const max = g.C - H;
+ if (max < 1) return Math.round((max / 2) * 100) / 100;
+ return Math.round(clamp(want, 0, max) * 100) / 100;
+ };
+ const read = (follow.blocks ?? []).filter((b) => b.start !== null && geo.blocks?.[b.k]).sort((a, b) => a.start - b.start || a.k - b.k);
+ // The opening frame: a carried post framed as the item before left it; else the first block's place.
+ const carry = (th.tiles ?? []).find((t) => t.mode === "carry");
+ const g0 = at(0);
+ let off;
+ if (carry && g0.tiles[carry.scope]) off = placed(g0, g0.tiles[carry.scope].top - m);
+ else if (read.length) {
+ const g = at(read[0].start - lead + span);
+ off = placed(g, g.blocks[read[0].k].top - m);
+ } else off = placed(g0, 0);
+ const start = off;
+ const segments = [];
+ let free = 0;
+ let maxSeen = Math.max(0, g0.C - H);
+ const moveTo = (to, t0w, seconds) => {
+ if (Math.abs(to - off) < 1) return;
+ const t0 = r3(Math.max(0, t0w, free));
+ const t1 = r3(t0 + seconds);
+ segments.push({ t0, t1, from: off, to });
+ off = to;
+ free = t1;
+ };
+ let prevScope = carry ? carry.scope : null;
+ read.forEach((b, i) => {
+ const first = b.scope !== prevScope;
+ prevScope = b.scope;
+ if (i === 0 && !carry) return;
+ const g = at(b.start - lead + span);
+ maxSeen = Math.max(maxSeen, g.C - H);
+ const bb = g.blocks[b.k];
+ if (first) {
+ // A new piece: its tile under a strip of the one it answers, the block itself in view.
+ const tile = g.tiles[tileScopeOf(b.scope)];
+ const top = tile ? tile.top : bb.top;
+ let want = top - Math.min(H * (th.contextRoom ?? 0.3), top);
+ // Its first block whole in view, as much of what it answers kept above as that leaves.
+ if (bb.bottom > want + H - m) want = Math.min(bb.top - m, bb.bottom - H + m);
+ moveTo(placed(g, want), b.start - lead, th.pan);
+ } else if (bb.top < off - 0.5) moveTo(placed(g, bb.top - m), b.start - lead, th.pan);
+ // Running past the window's foot: up just enough to show it whole (what it follows kept in view above).
+ else if (bb.bottom > off + H - m / 2 + 0.5) moveTo(placed(g, Math.min(bb.top - m, bb.bottom - H + m)), b.start - lead, th.pan);
+ // A block taller than the window pans on through it as it is read.
+ const h = bb.bottom - bb.top;
+ const room = H - 2 * m;
+ if (h > room && room > 0 && g.C - H >= 1) {
+ const over = h - room;
+ const n = Math.ceil(over / (0.6 * room));
+ const len = Math.max(0.1, (b.end ?? b.start) - b.start);
+ for (let j = 1; j <= n; j += 1) {
+ const target = bb.top - m + (over * j) / n;
+ const line = target - (bb.top - m) + room * 0.6;
+ moveTo(placed(g, target), Math.min((b.end ?? b.start) - th.pan, b.start + (len * line) / h), th.pan);
+ }
+ }
+ });
+ return { ...base, start, segments, max: Math.round(maxSeen * 100) / 100 };
+}
+
/** The flow's offset at item second `s` on the path. */
export function followOffsetAt(path, s) {
- let off = 0;
+ let off = fin(path?.start) ? path.start : 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));
@@ -451,30 +556,67 @@ export function followStateAt(follow, path, s) {
const offset = Math.round(followOffsetAt(path, s) * 4) / 4;
const max = path?.max ?? 0;
const edge = 24;
+ const current = read.length ? followBlockAt(follow, s) ?? read[0].k : null;
+ if (follow.thread) {
+ // THREADED (post-thread.mjs): each tile's scale and opacity, with its full height (the page sets its slot's).
+ const ts = threadStateAt(follow.thread, s);
+ const tiles = {};
+ let C = fin(path?.C) ? path.C : 0;
+ for (const [scope, [sc, o]] of Object.entries(ts)) {
+ const h = path?.tiles?.[scope]?.height ?? 0;
+ tiles[scope] = [sc, o, Math.round(h * 100) / 100];
+ if (sc < 0.9995 && scope !== "quoted") C -= (1 - sc) * h;
+ }
+ const below = C - (path?.H ?? 0) - offset;
+ return {
+ op,
+ offset,
+ fadeTop: offset > 0.5 ? Math.round(clamp(offset / edge, 0, 1) * 100) / 100 : 0,
+ fadeBottom: path?.H && below > 0.5 ? Math.round(clamp(below / edge, 0, 1) * 100) / 100 : 0,
+ current,
+ tiles,
+ };
+ }
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,
+ current,
};
}
/** 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]);
+export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom, ...(st.tiles ? [st.tiles] : [])]);
// ---------------------------------------------------------------------------
// 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. */
+/**
+ * The page's geometry for the pan: the window's height, the flow's, each
+ * block's top and bottom in the flow -- and, a threaded card (post-thread.mjs),
+ * each tile's top and height, all measured at every tile's full size.
+ */
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";
+ // A threaded card's tiles at full size while it is measured (their state put back after).
+ const slots = Array.from(flow.querySelectorAll("[data-thread-slot]"));
+ const kept = slots.map((el) => {
+ const tile = el.querySelector("[data-thread-tile]");
+ const k = { el, tile, h: el.style.height, t: tile ? tile.style.transform : "", o: tile ? tile.style.opacity : "" };
+ el.style.height = "";
+ if (tile) {
+ tile.style.transform = "";
+ tile.style.opacity = "";
+ }
+ return k;
+ });
const fr = flow.getBoundingClientRect();
const blocks = {};
for (const el of Array.from(flow.querySelectorAll("[data-post-block]"))) {
@@ -488,6 +630,21 @@ export function measureFollow(doc = document) {
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 };
+ if (slots.length) {
+ const tiles = {};
+ for (const el of slots) {
+ const r = el.getBoundingClientRect();
+ tiles[el.getAttribute("data-thread-slot")] = { top: Math.round((r.top - fr.top) * 100) / 100, height: Math.round(r.height * 100) / 100 };
+ }
+ out.tiles = tiles;
+ }
+ for (const k of kept) {
+ k.el.style.height = k.h;
+ if (k.tile) {
+ k.tile.style.transform = k.t;
+ k.tile.style.opacity = k.o;
+ }
+ }
flow.style.transform = had;
return out;
}
@@ -500,6 +657,23 @@ export function applyFollowState(state, doc = document) {
const v = typeof o === "number" && o < 0.9995 ? String(o) : "";
if (el.style.opacity !== v) el.style.opacity = v;
}
+ // A threaded card's tiles (post-thread.mjs): each scaled about its corner, its slot closed up to match, its strength.
+ const tiles = (state && state.tiles) || {};
+ for (const el of Array.from(doc.querySelectorAll("[data-thread-slot]"))) {
+ const v = tiles[el.getAttribute("data-thread-slot")];
+ const tile = el.querySelector("[data-thread-tile]");
+ const sc = v && typeof v[0] === "number" ? v[0] : 1;
+ const o = v && typeof v[1] === "number" ? v[1] : 1;
+ const h = sc < 0.9995 && v && v[2] > 0 ? `${Math.round(v[2] * sc * 100) / 100}px` : "";
+ if (el.style.height !== h) el.style.height = h;
+ if (tile) {
+ const tf = sc < 0.9995 ? `scale(${sc})` : "";
+ if (tile.style.transform !== tf) tile.style.transform = tf;
+ const ov = o < 0.9995 ? String(o) : "";
+ if (tile.style.opacity !== ov) tile.style.opacity = ov;
+ }
+ el.setAttribute("data-thread-state", sc < 0.9995 || o < 0.9995 ? (o < 0.02 ? "hidden" : "context") : "focus");
+ }
const flow = doc.querySelector("[data-post-flow]");
if (flow) {
const t = state && state.offset ? `translateY(${-state.offset}px)` : "";