Archilyzer · Source

archilyzer

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

commit ba28b7f6ece3b6aedc6e4e1ab8ebdb63159fb65f
parent 1ee27dc0f8053fd27a0eacf98ba80bf6abd76cc7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 00:36:59 -0500

umtool: thread reads -- never narrate hidden text. A narrated read's parts each carry a ROLE (the post it answers, the post it quotes, his words, an attachment's), stored or inferred from its piece and word pairs; a read of a context post draws the card as the conversation, a column of tiles read-follow pans: the post being read in full at the size that fits it, shrunk and dimmed as the next piece comes in (the reply revealed under it), a parent that is the item before carried in; the build's lint refuses a part read off a text the card hides; posts roles, set-item thread.*, --cut thread.*

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 10++++++++--
Mumtool/components/projects/PostBench.tsx | 6++++--
Mumtool/components/projects/PostBenchPage.tsx | 3++-
Mumtool/lib/report/manifest.mjs | 51++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/lib/report/playView.mjs | 13+++++++++----
Mumtool/lib/report/postNarrationCli.mjs | 33+++++++++++++++++++++++++++++++--
Aumtool/lib/report/postThreadCli.mjs | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 52++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/build-video.mjs | 2++
Mumtool/report-to-video/lint.mjs | 3+++
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/post-item.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/report-to-video/post-narration.mjs | 10+++++++---
Mumtool/report-to-video/post-render.mjs | 13+++++++++----
Aumtool/report-to-video/post-thread.mjs | 483+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/read-follow.mjs | 189+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
16 files changed, 1050 insertions(+), 50 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 @@ -56,7 +56,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 +71,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 +80,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); 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/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; 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 = e.narration.takes.indexOf(t); + 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: e.narration.takes.indexOf(t), 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-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}" 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. 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,483 @@ +// 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 } 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. + * @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; + const parts = Array.isArray(t?.parts) ? t.parts : []; + 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. */ +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/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,7 +195,11 @@ 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 })) }; } @@ -214,7 +219,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 +289,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 +312,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 +360,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 +385,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 +425,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 +555,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 +629,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 +656,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)` : "";