Archilyzer · Source

archilyzer

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

commit 2922a46d8eb4383527a72c680be35f920473df69
parent 0e791449b0417f1e305eb5282decc70e7b140c08
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 14:34:51 -0500

Merge main (thread-scenes, post-captions) into lane/fast-fix-render

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 21+++++++++++++++++----
Mumtool/components/projects/PostBench.tsx | 22+++++++++++++++++++---
Mumtool/components/projects/PostBenchPage.tsx | 4++--
Mumtool/components/projects/PostZoomPanel.tsx | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/review/PlayCut.tsx | 8++++++++
Mumtool/components/projects/review/PostItemPlayer.tsx | 300+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/docs/cli.md | 9++++++---
Mumtool/docs/knobs.md | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/post-captions.spec.ts | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/thread-scenes.spec.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/report/playView.mjs | 9++++++---
Mumtool/lib/report/postFx.test.mjs | 25++++++++++++++++++++++++-
Mumtool/lib/report/postFxCli.mjs | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/lib/report/postNarrationCli.mjs | 14+++++++++-----
Mumtool/lib/report/postReel.mjs | 6+++---
Mumtool/lib/report/postThreadCli.mjs | 4++--
Aumtool/lib/report/postThreadScenes.test.mjs | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 141++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/lib/report/timelineCli.mjs | 46++++++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/build-video.mjs | 22+++++++++++++++++++---
Mumtool/report-to-video/package.json | 5+++++
Aumtool/report-to-video/post-branch-map.mjs | 220+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-caption.mjs | 674+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-caption.test.mjs | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-clock.mjs | 331+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-clock.test.mjs | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-combo-render.mjs | 8+++++---
Mumtool/report-to-video/post-conversation.mjs | 57++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/report-to-video/post-item.mjs | 260++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/report-to-video/post-item.test.mjs | 3++-
Aumtool/report-to-video/post-join.mjs | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-link-visit.mjs | 220+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-media-scene.mjs | 2+-
Mumtool/report-to-video/post-narration.mjs | 26+++++++++++++++++++++-----
Mumtool/report-to-video/post-redact.mjs | 8+++++++-
Aumtool/report-to-video/post-render-key.test.mjs | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-render.mjs | 576++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Aumtool/report-to-video/post-thread-scenes.test.mjs | 325+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-thread.mjs | 349++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/read-follow.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/report-to-video/word-zoom.mjs | 12++++++++++--
43 files changed, 5084 insertions(+), 193 deletions(-)

diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -1,6 +1,6 @@ import { readFile, realpath, stat } from "node:fs/promises"; import path from "node:path"; -import { postCardHtml } from "umtool-report-to-video/post-item"; +import { cardWordsSize, panelEntry, postCardHtml, postItemPlan } from "umtool-report-to-video/post-item"; import { avatarUrls } from "umtool-report-to-video/post-avatars"; import { jobState, startJob } from "@/lib/research/case-editor"; import { withEditNotes } from "@/lib/report/guard"; @@ -57,8 +57,18 @@ async function itemOf(project: { dir: string }, manifest: Record<string, unknown const at = tl.findIndex((e) => e?.type === "post" && e.id === id); // `ctx`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in) and the scene its // run leaves on screen (post-conversation.mjs), as Play's plan has them. - const ctx = planContext(tl, at, (m.render ?? {}) as Record<string, unknown>) as { prev: Record<string, unknown> | null; scene: Record<string, unknown> | null }; - return { item: at >= 0 ? tl[at] : null, prev: ctx.prev, ctx, manifest: m }; + const ctx = planContext(tl, at, (m.render ?? {}) as Record<string, unknown>) as { prev: Record<string, unknown> | null; scene: Record<string, unknown> | null; join: { seconds: number } | null }; + // THE JOIN (post-join.mjs): the item before's own context, so its post's size is known (the carried post drawn alike). + const prevCtx = at > 0 && ctx.join ? (planContext(tl, at - 1, (m.render ?? {}) as Record<string, unknown>) as Record<string, unknown>) : null; + return { item: at >= 0 ? tl[at] : null, prev: ctx.prev, ctx, prevCtx, manifest: m }; +} + +/** The size the item before draws its post's words at (post-item.mjs cardWordsSize; threaded when its plan is). */ +function joinWordsSize(prev: Entry, prevCtx: Record<string, unknown> | null, render: Record<string, unknown>, box: { width: number; height: number }) { + const pe = panelEntry(prev, render) as Entry; + const follow = followKnobs(pe, render).on; + const plan = postItemPlan(pe, render, (prevCtx ?? {}) as never) as { follow?: { thread?: unknown } }; + return cardWordsSize(pe, box, { follow, threaded: follow && !!plan.follow?.thread }); } /** A project file under posts-media/, never outside it (its real path checked). */ @@ -191,7 +201,8 @@ export async function GET(request: Request) { ? ((await projectCombos(r.project.dir, found.manifest, { channelsDir: channelsDirFor(r.project.dir, found.manifest) }).catch(() => ({ groups: [] }))).groups as unknown[]) : []; const media = groups.length ? mediaSceneById(tl, found.item.id, groups as never, cutRender) : null; - const item = sceneEntry(found.item, media) as Entry; + // A WIDE attachment at full width above the card (post-item.mjs panelEntry: the cut's rule laid on). + const item = panelEntry(sceneEntry(found.item, media), cutRender) as Entry; // THE THREAD SCENE WINS (post-media-scene.mjs's header): with the conversation's scene (post-conversation.mjs) the // media scene keeps only the attachment (sceneEntry above), never the card. const scene = found.ctx.scene ? null : media; @@ -209,6 +220,8 @@ export async function GET(request: Request) { // read is its base; un-narrated, none). thread: followOn ? (scene ? sceneLayout(isNarrated(item) ? tlayout : null, item, scene) ?? tlayout : tlayout) : null, redaction, + // THE JOIN (post-join.mjs): the post the item before ended on drawn as it drew its post (Play lays the morph). + join: followOn && found.ctx.join && found.prev?.type === "post" ? { size: joinWordsSize(found.prev as Entry, found.prevCtx, cutRender, { width: w, height: h }) } : null, }); 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 @@ -6,7 +6,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { postBenchHref } from "@/lib/hrefs"; -import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds, postItemPlan, readingSeconds, ruleSeconds } from "umtool-report-to-video/post-item"; +import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds, postItemPlan, readingSeconds, ruleSeconds, panelEntry } from "umtool-report-to-video/post-item"; import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; import PostThreadPanel from "./PostThreadPanel"; @@ -17,6 +17,8 @@ import ComboBadge, { type ComboInfo } from "./review/ComboBadge"; import { liveCombo } from "umtool-report-to-video/post-combo"; import PostZoomPanel from "./PostZoomPanel"; import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; +import { captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; +import { clockPlan } from "umtool-report-to-video/post-clock"; import { sceneEntry } from "umtool-report-to-video/post-media-scene"; // --------------------------------------------------------------------------- @@ -119,7 +121,7 @@ export default function PostBench({ : savedScene, [entry, savedScene], ); - const shown = useMemo(() => sceneEntry(entry, scene) as Entry, [entry, scene]); + const shown = useMemo(() => panelEntry(sceneEntry(entry, scene), render) as Entry, [entry, scene, render]); const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(shown, render, { prev: before, scene: conversation, mediaScene: conversation ? null : scene }) as PostPlan)), [entry, shown, initial, initialPlan, render, before, scene, conversation]); const total = plan.total; const [s, setS] = useState(0); @@ -279,6 +281,16 @@ export default function PostBench({ .map((z) => ({ i: z.i, ...zoomSpan((entry.fx as Array<Record<string, unknown>>)[z.i], z.t as number) })), [entry, render], ); + const captionMarks = useMemo( + () => + (captionTimes(entry, render) as Array<{ i: number; t?: number }>) + .filter((c) => typeof c.t === "number") + .map((c) => { + const f = resolveCaption((entry.fx as Array<Record<string, unknown>>)[c.i]); + return { i: c.i, t0: Math.max(0, (c.t as number) - f.lead), t3: (c.t as number) + f.hold + 0.35 }; + }), + [entry, render], + ); const stepOf = (i: number) => plan.steps.find((st) => st.items.some((m) => m.i === i)) ?? null; const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); const reading = readingSeconds(entry); @@ -305,7 +317,7 @@ export default function PostBench({ </span> </div> <div className="relative w-full overflow-hidden rounded border border-seam bg-black" style={{ aspectRatio: `${box.width} / ${box.height}` }}> - <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} /> + <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} clock={clockPlan(shown, render, before)} /> <ComboBadge project={project} entry={shown} plan={plan} combo={liveCombo(combo, render, entry) as ComboInfo | null} box={box} s={s} playing={playing} /> </div> <div className="flex items-center gap-2 text-[12px]"> @@ -340,6 +352,10 @@ export default function PostBench({ {zoomMarks.map((z) => ( <div key={z.i} className="absolute inset-y-0 border-x border-amber-400/80 bg-amber-400/25" style={{ left: `${(z.t0 / total) * 100}%`, width: `${((z.t3 - z.t0) / total) * 100}%` }} title={`word zoom ${z.i + 1}`} data-post-bench-zoom-mark={z.i} /> ))} + {/* Its captions (post-caption.mjs): each from its lead-in to gone (one waiting for a zoom is drawn later). */} + {captionMarks.map((c) => ( + <div key={`c${c.i}`} className="absolute bottom-0 h-1/3 border-x border-sky-400/80 bg-sky-400/30" style={{ left: `${(c.t0 / total) * 100}%`, width: `${((c.t3 - c.t0) / total) * 100}%` }} title={`caption ${c.i + 1}`} data-post-bench-caption-mark={c.i} /> + ))} <div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} /> </div> <PostZoomPanel diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -5,7 +5,7 @@ import { channelsDirFor, readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { projectHref, playHref } from "@/lib/hrefs"; import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; -import { postItemPlan } from "umtool-report-to-video/post-item"; +import { postItemPlan, panelEntry } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; @@ -56,7 +56,7 @@ 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(sceneEntry(entry, scene), render, { ...ctx, mediaScene: ctx.scene ? null : scene }) as unknown as PostPlan} + plan={postItemPlan(panelEntry(sceneEntry(entry, scene), render), render, { ...ctx, mediaScene: ctx.scene ? null : scene }) as unknown as PostPlan} scene={scene} render={render} before={ctx.prev} diff --git a/umtool/components/projects/PostZoomPanel.tsx b/umtool/components/projects/PostZoomPanel.tsx @@ -7,6 +7,7 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, WORD_ZOOM_LIMITS, cardTokens, normWord, readingEstimate, resolveWordZoom, targetTextOf, wordZoomTimes, zoomSpan, } from "umtool-report-to-video/word-zoom"; +import { CAPTION_DEFAULTS, CAPTION_LIMITS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; // --------------------------------------------------------------------------- // A POST's WORD ZOOMS ON THE BENCH (report-to-video/word-zoom.mjs; knobs.md, "A @@ -14,7 +15,9 @@ import { // Zoom here adds the zoom on them (its match and occurrence filled) -- then each // zoom's knobs: scale, lead, hold, ease, highlight, and its moment: from the // take's word timings (Get word timings: the EDITOR's transcription, a job) or -// `at`, nudged. Every change is one write (POST /api/report/post-item, op "fx"). +// `at`, nudged. A CAPTION (post-caption.mjs) is added on the same words (Caption +// here, its text typed), then its text, place, lead, hold and moment set. +// Every change is one write (POST /api/report/post-item, op "fx"). // --------------------------------------------------------------------------- type Entry = Record<string, unknown> & { id: string; fx?: Array<Record<string, unknown>> }; @@ -56,6 +59,8 @@ export default function PostZoomPanel({ const tokens = useMemo(() => cardTokens(text).filter((t) => t.tok !== undefined) as Array<{ tok: string; i: number }>, [text]); const list = Array.isArray(entry.fx) ? entry.fx : []; const times = useMemo(() => wordZoomTimes(entry, render), [entry, render]); + const ctimes = useMemo(() => captionTimes(entry, render), [entry, render]); + const [capText, setCapText] = useState(""); const narrated = isNarrated(entry); const take = pickedTake(entry) as (Record<string, unknown> & { words?: unknown[] }) | null; @@ -71,21 +76,24 @@ export default function PostZoomPanel({ return j.entry; }; - const zoomHere = async () => { + const zoomHere = async (kind: "word-zoom" | "caption" = "word-zoom") => { if (!sel) return; + if (kind === "caption" && !capText.trim()) return setError("a caption needs its text"); const words = tokens.slice(sel.from, sel.to + 1).map((t) => t.tok); const match = words.length === 1 ? bare(words[0]) : [bare(words[0]), ...words.slice(1, -1), bare(words[words.length - 1])].join(" "); // Its occurrence: how many times the same run of words came before it, plus one. const want = words.map(normWord); let occurrence = 1; for (let i = 0; i < sel.from; i += 1) if (want.every((w, k) => normWord(tokens[i + k]?.tok ?? "") === w)) occurrence += 1; - const add: Record<string, unknown> = { kind: "word-zoom", match, ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) }; + const add: Record<string, unknown> = { kind, match, ...(kind === "caption" ? { text: capText.trim() } : {}), ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) }; // An un-narrated post has no read to time it by: the reading estimate, to nudge. - if (!narrated) add.at = readingEstimate(sel.from); + // (A caption is timed by the reading estimate itself when it has no at.) + if (!narrated && kind === "word-zoom") add.at = readingEstimate(sel.from); const e = await send({ add }); if (e) { - setStatus(`zoom added on "${match}"`); + setStatus(`${kind === "caption" ? "caption" : "zoom"} added on "${match}"`); setSel(null); + if (kind === "caption") setCapText(""); } }; @@ -143,7 +151,7 @@ export default function PostZoomPanel({ return ( <section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12.5px]" data-post-zoom-panel={entry.id}> <div className="flex flex-wrap items-center gap-2"> - <h2 className="micro m-0">word zoom</h2> + <h2 className="micro m-0">word zoom · caption</h2> {targets.length > 1 && ( <select value={target} onChange={(e) => (setTarget(e.target.value), setSel(null))} data-post-zoom-target=""> {targets.map((t) => ( @@ -193,6 +201,17 @@ export default function PostZoomPanel({ <button type="button" className={btn} disabled={!sel} onClick={() => void zoomHere()} data-post-zoom-here=""> Zoom here </button> + <input + value={capText} + onChange={(e) => setCapText(e.target.value)} + placeholder="caption text" + className="min-w-0 flex-1 rounded border border-seam bg-ground px-1 py-0.5" + aria-label="caption text" + data-post-caption-text="" + /> + <button type="button" className={btn} disabled={!sel || !capText.trim()} onClick={() => void zoomHere("caption")} data-post-caption-here=""> + Caption here + </button> {sel && ( <span className="text-text-2" data-post-zoom-sel=""> “{tokens.slice(sel.from, sel.to + 1).map((t) => t.tok).join(" ")}” @@ -200,6 +219,114 @@ export default function PostZoomPanel({ )} </div> {list.map((fx0, i) => { + // Its clock (post-clock.mjs): a row of its own, its rewind knob. + if (fx0?.kind === "clock") { + return ( + <div key={i} className="flex flex-wrap items-center gap-2 rounded border border-seam p-2" data-post-clock-fx={i}> + <b>#{i + 1} clock</b> + <span className="text-text-2">{fx0.on === false ? "off on this item" : "the post's own time, run from the item before"}</span> + {fx0.on !== false && ( + <label className="flex items-center gap-1"> + rewind + <select value={String(fx0.rewind ?? "auto")} onChange={(e) => void send({ set: i, patch: { rewind: e.target.value === "auto" ? null : e.target.value } })} data-post-clock-knob="rewind"> + {["auto", "on", "off"].map((x) => ( + <option key={x} value={x}> + {x} + </option> + ))} + </select> + </label> + )} + <button type="button" className="ink-link ml-auto" onClick={() => void send({ remove: i })} data-post-clock-remove={i}> + remove + </button> + </div> + ); + } + if (fx0?.kind === "caption") { + const c = resolveCaption(fx0); + const t = ctimes[i] as { t?: number; source?: string; error?: string }; + const at = typeof t?.t === "number" ? t.t : null; + const up = at !== null && s >= at - c.lead && s < at + c.hold + 0.35; + const capKnob = (key: "lead" | "hold") => ( + <label className="flex items-center gap-1" key={key}> + {key} + <input + type="number" + step={0.1} + min={CAPTION_LIMITS[key][0]} + max={CAPTION_LIMITS[key][1]} + defaultValue={Number(c[key])} + key={`${entry.id}:${i}:${key}:${String(c[key])}`} + onBlur={(ev) => { + const v = Number(ev.target.value); + if (Number.isFinite(v) && v !== Number(c[key])) void send({ set: i, patch: { [key]: v === CAPTION_DEFAULTS[key] ? null : v } }); + }} + className="w-14 rounded border border-seam bg-ground px-1 py-0.5" + data-post-caption-knob={key} + /> + </label> + ); + return ( + <div key={i} className={cn("space-y-1.5 rounded border p-2", up ? "border-sky-400/70" : "border-seam")} data-post-caption-fx={i}> + <div className="flex flex-wrap items-center gap-2"> + <b> + #{i + 1} caption on “{c.match}” + </b> + {at !== null ? ( + <span data-post-caption-at={String(at)}> + at {at.toFixed(2)} s {t.source === "at" ? "(set by hand)" : t.source === "words" ? "(the take's words)" : "(the reading estimate)"} + </span> + ) : ( + <span className="text-[var(--color-blocking,#c33)]">{t?.error}</span> + )} + <button type="button" className="ink-link ml-auto" onClick={() => setS(Math.max(0, (at ?? 0) - c.lead - 0.3))} disabled={at === null} data-post-caption-go={i}> + play it + </button> + <button type="button" className="ink-link" onClick={() => void send({ remove: i })} data-post-caption-remove={i}> + remove + </button> + </div> + <input + defaultValue={c.text} + key={`${entry.id}:${i}:text:${c.text}`} + onBlur={(ev) => ev.target.value.trim() && ev.target.value !== c.text && void send({ set: i, patch: { text: ev.target.value } })} + className="w-full rounded border border-seam bg-ground px-1 py-0.5" + aria-label={`caption ${i + 1} text`} + data-post-caption-knob="text" + /> + <div className="flex flex-wrap items-center gap-2"> + at + <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(Math.max(0, (at ?? 0) - 0.1)) } })} data-post-caption-nudge="-"> + −0.1 + </button> + <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2((at ?? 0) + 0.1) } })} data-post-caption-nudge="+"> + +0.1 + </button> + <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(s) } })} data-post-caption-at-playhead=""> + at playhead + </button> + {typeof fx0.at === "number" && ( + <button type="button" className="ink-link" onClick={() => void send({ set: i, patch: { at: null } })} data-post-caption-from-words=""> + {narrated ? "from the read" : "the estimate"} + </button> + )} + {capKnob("lead")} + {capKnob("hold")} + <label className="flex items-center gap-1"> + place + <select value={c.place} onChange={(e) => void send({ set: i, patch: { place: e.target.value === CAPTION_DEFAULTS.place ? null : e.target.value } })} data-post-caption-knob="place"> + {CAPTION_PLACES.map((x) => ( + <option key={x} value={x}> + {x} + </option> + ))} + </select> + </label> + </div> + </div> + ); + } const fx = resolveWordZoom(fx0); const t = times[i] as { t?: number; source?: string; error?: string }; const at = typeof t?.t === "number" ? t.t : null; diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -122,6 +122,8 @@ export type PlayEntry = { /** A post item (report-to-video/post-item.mjs): the entry its card is drawn from, and what plays when. */ post?: Record<string, unknown> & { id: string }; postPlan?: PostPlan; + /** Its clock (post-clock.mjs clockPlan), or null. */ + postClock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null; /** Its combo badge (post-combo.mjs): the attachment it repeats, its count, the knobs. */ postCombo?: ComboInfo; /** Its media scene (post-media-scene.mjs): which, its place in it, its items, the anchor. */ @@ -857,6 +859,12 @@ export default function PlayCut({ published={asPublished} uncensored={uncensored} scene={postNow.entry.postScene ?? null} + clock={postNow.entry.postClock ?? null} + joinFrom={(() => { + // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended. + const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null; + return postNow.entry.postPlan?.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan } : null; + })()} /> ) : null; // A post item that repeats an earlier one's attachment: its combo badge, beside the player. diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -2,9 +2,17 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item"; +import { applyJoinState, endMediaOf, joinFrameAt } from "umtool-report-to-video/post-join"; +import { applyVisitState } from "umtool-report-to-video/post-link-visit"; +import { applyMapState, mapHtml, mapPlace, mapSize } from "umtool-report-to-video/post-branch-map"; import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration"; import { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow"; +import { scrollAt, showOpacityAt } from "umtool-report-to-video/post-thread"; import { blurCqw, blurOf, labelBoxOf, pixelGrid } from "umtool-report-to-video/post-censor"; +import { + CAPTION_SLIDE, captionCss, captionInnerHtml, captionOpacityAt, captionPlan, captionSlideAt, measureCaptionWords, mountCaptions, paletteOfDoc, placeCaption, setCaptionState, slideDir, +} from "umtool-report-to-video/post-caption"; +import { clockCss, clockFace, clockHtml, clockStateAt, measureClockPlace, mountClock, setClockState } from "umtool-report-to-video/post-clock"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom"; // --------------------------------------------------------------------------- @@ -26,6 +34,15 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar // `data-w` spans) inside the card, which clips them, its highlight fading in // under the word -- the card page's own elements transformed, nothing redrawn. // +// A CAPTION (post-caption.mjs) plays live on the build's own markup: the chips +// mounted in the card page (its CSS, in the page's palette), placed by the same +// rule (placeCaption, the words read while it is up avoided), faded and slid in +// on the same curve, and tracking the phrase as the card pans (measured each tick). +// +// THE CLOCK (post-clock.mjs) plays live from `clock` (clockPlan: the caller has +// the item before it): the build's chip mounted in the card page, placed by the +// same rule, set each tick to clockStateAt -- the run, the badge, the rewind. +// // READ-FOLLOW (read-follow.mjs) plays live on the plan's `follow`: the card // page carries the read's blocks and its flow; the pan's path is worked out // from the page's geometry once it is drawn, and each tick sets the state at @@ -36,6 +53,8 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar type Rect = { x: number; y: number; width: number; height: number }; /** A zoom of the item, measured in its card page: its span on the item's clock, the card's region, the word's box. */ +/** A caption of the item, placed in its card page: its span, its place, the phrase's box and lines when placed. */ +type LiveCaption = { i: number; span: { t0: number; t1: number; t2: number; t3: number }; scope: string; from: number; to: number; placed: NonNullable<ReturnType<typeof placeCaption>>; base: Rect; lines: Rect[] }; type LiveZoom = { i: number; span: ReturnType<typeof zoomSpan>; scope: string; from: number; to: number; color: string | null; region: Rect; word: Rect }; /** The card's children placed so the region shows `win` (zoomWindow) at z; their layout boxes measured before any transform. */ @@ -80,6 +99,7 @@ export type NarrationSchedule = { at: number; seconds: number; takeSeconds?: num /** The plan's read-follow (read-follow.mjs followSchedule). */ export type FollowPlan = { + join?: { seconds: number }; dim: number; ease: number; readEnd: number; @@ -95,7 +115,11 @@ export type FollowPlan = { }; }; +/** A context post's attachment over the slot (post-thread.mjs panelSchedule). */ +export type PanelShow = { scope: string; media: Array<Record<string, unknown> & { src: string; kind: string; width?: number; height?: number }>; t0: number; t1: number; scroll?: number[][] }; + export type PostPlan = { + panel?: { fade: number; shows: PanelShow[] }; reading: number; total: number; held: number; @@ -231,8 +255,10 @@ function PixelLayer({ source, crop, censor }: { source: React.RefObject<HTMLVide } function MediaEl({ - project, m, box, b, step, s, playing, inStep, mix = null, speed = 1, + project, m, box, b, step, s, playing, inStep, mix = null, speed = 1, joinOp = 1, }: { + /** THE JOIN (post-join.mjs): its strength while it fades in over the attachment the item before ended on. */ + joinOp?: number; project: string; m: PostPlan["steps"][number]["items"][number]; box: Box; @@ -297,7 +323,7 @@ function MediaEl({ data-post-censor-style={blur ? blur.style : undefined} data-post-censor-band={blur?.band ? blur.band.join(",") : undefined} className="absolute overflow-hidden" - style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height), containerType: blur ? "size" : undefined }} + style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height), containerType: blur ? "size" : undefined, opacity: joinOp < 1 ? joinOp : undefined }} > {timed ? ( <video @@ -347,8 +373,62 @@ function MediaEl({ ); } +/** The panel's shows over the slot, as the build lays them: each crossfaded, a tall picture read through scrolled. */ +function PanelShows({ project, shows, fade, slot, box, s }: { project: string; shows: PanelShow[]; fade: number; slot: Rect; box: Box; s: number }) { + return ( + <> + {shows.map((sh, i) => { + const op = showOpacityAt(sh as never, s, fade); + if (op <= 0) return null; + const m = sh.media[0]; + const w = m.width ?? 16; + const h = m.height ?? 9; + const scroll = !!sh.scroll && m.kind === "image" && h / w > (slot.height / slot.width) * 1.4; + const fitS = Math.min(slot.width / w, slot.height / h); + const bw = scroll ? Math.min(slot.width, slot.height * 0.8) : w * fitS; + const bh = scroll ? slot.height : h * fitS; + const full = scroll ? (bw * h) / w : bh; + const y = scroll ? -(full - bh) * scrollAt(sh.scroll as never, s) : 0; + const left = slot.x + (slot.width - bw) / 2; + const top = slot.y + (scroll ? 0 : (slot.height - bh) / 2); + return ( + <div key={`${sh.scope}:${i}`} data-post-panel={sh.scope} className="absolute z-10 overflow-hidden" style={{ left: pct(left, box.width), top: pct(top, box.height), width: pct(bw, box.width), height: pct(bh, box.height), opacity: op }}> + {m.kind === "image" ? ( + // eslint-disable-next-line @next/next/no-img-element + <img alt="" src={postFileUrl(project, m.src)} style={{ position: "absolute", left: 0, top: `${(y / bh) * 100}%`, width: "100%", height: scroll ? `${(full / bh) * 100}%` : "100%", display: "block" }} /> + ) : ( + <video src={postFileUrl(project, m.src)} muted loop autoPlay playsInline style={{ width: "100%", height: "100%" }} /> + )} + </div> + ); + })} + </> + ); +} + +/** THE JOIN's outgoing attachments (post-join.mjs endMediaOf): the item before's last frame at its slot, fading out. */ +function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: Array<{ m: Record<string, unknown> & { src?: string; kind?: string }; t: number }>; layout: { slot: Rect | null }; box: Box; op: number }) { + if (!layout.slot || !ends.length || op <= 0) return null; + const boxes = stepBoxes({ items: ends.map((x, j) => ({ ...x.m, i: j })) } as never, layout.slot) as Rect[]; + return ( + <> + {ends.map((x, j) => { + const b = boxes[j]; + const src = postFileUrl(project, String(x.m.src ?? "")); + const style = { left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height), opacity: op, zIndex: 3 }; + return x.m.kind === "image" ? ( + // eslint-disable-next-line @next/next/no-img-element + <img key={j} alt="" src={src} data-post-join-end={j} className="absolute object-cover" style={style} /> + ) : ( + <video key={j} src={`${src}#t=${x.t}`} muted playsInline preload="auto" data-post-join-end={j} className="absolute object-cover" style={style} /> + ); + })} + </> + ); +} + export default function PostItemPlayer({ - project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, + project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, }: { project: string; take?: string | null; @@ -368,6 +448,10 @@ export default function PostItemPlayer({ uncensored?: boolean; /** Its media scene (post-media-scene.mjs): which, and its place in it. */ scene?: { key: string; n: number; of: number } | null; + /** Its clock (post-clock.mjs clockPlan, from the item before it), or none. */ + clock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null; + /** THE JOIN (post-join.mjs): the item before (its entry and plan) -- this one opens on it as it ended. */ + joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan } | null; }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); @@ -404,6 +488,8 @@ export default function PostItemPlayer({ return () => ro.disconnect(); }, [box.width]); const layout = useMemo(() => postLayout(entry, box), [entry, box]); + const pageUrlOf = (id: string, phase: "read" | "media") => + `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${published ? `&published=1${uncensored ? "&uncensored=1" : ""}` : ""}`; const pageUrl = (phase: "read" | "media") => `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}${published ? `&published=1${uncensored ? "&uncensored=1" : ""}` : ""}`; const reading = s < plan.reading || !plan.steps.length; @@ -432,25 +518,75 @@ export default function PostItemPlayer({ }, [wordsRel, project, cues]); // ---- the word zooms, live: measured in the card page once it is drawn, applied on the item's clock ---- const readFrame = useRef<HTMLIFrameElement | null>(null); + // ---- THE JOIN, live (post-join.mjs): the item before's page in a frame of its own, at its last frame's state ---- + const joinFrame = useRef<HTMLIFrameElement | null>(null); + const joinMeasure = useRef<{ A: Rect; anchor: number | null; slotA: Rect | null } | null>(null); + const [joinReady, setJoinReady] = useState(0); + const joinSecs = plan.follow?.join?.seconds ?? 0; + const joinOn = !!joinFrom && joinSecs > 0; + const onJoinLoad = useCallback(() => { + let tries = 0; + const tick = () => { + const doc = joinFrame.current?.contentDocument; + if (!doc || doc.body?.getAttribute("data-post-ready") !== "1" || !joinFrom) { + if (tries++ < 50) setTimeout(tick, 100); + return; + } + const pf = joinFrom.plan.follow ?? null; + if (pf && doc.querySelector("[data-post-flow]")) { + const g = measureFollow(doc); + applyFollowState(followStateAt(pf, g ? followPath(pf, g) : null, Math.max(0, joinFrom.plan.total - 1 / 30)), doc); + } + const card = doc.querySelector("[data-post-card]"); + if (!card) return; + const c = card.getBoundingClientRect(); + const post = doc.querySelector('[data-thread-slot="post"] .head') ?? card.querySelector(".head"); + const pl = postLayout(joinFrom.entry, box); + joinMeasure.current = { A: { x: c.left, y: c.top, width: c.width, height: c.height }, anchor: post ? post.getBoundingClientRect().top - c.top : null, slotA: pl.slot && pl.mode === "side" ? pl.slot : null }; + setJoinReady((n) => n + 1); + }; + tick(); + }, [joinFrom, box]); const [zooms, setZooms] = useState<LiveZoom[]>([]); + const [caps, setCaps] = useState<LiveCaption[]>([]); + // The clock's box (and its badge's) where it is placed: a caption covers neither. + const clockRect = useRef<Rect | null>(null); const boxes = useRef<Map<Element, Rect>>(new Map()); const zoomTimes = useMemo(() => (Array.isArray(entry.fx) && entry.fx.length ? wordZoomTimes(entry, undefined, plan.narration as never) : []), [entry, plan.narration]); // ---- read-follow, live: the page's geometry measured once it is drawn, the path from it ---- const follow = plan.follow ?? null; const [followGeo, setFollowGeo] = useState<ReturnType<typeof measureFollow>>(null); const followRoute = useMemo(() => (follow && followGeo ? followPath(follow, followGeo) : null), [follow, followGeo]); + // The plan, the layout and the clock as they are now, read by measure through a ref: its identity (and so a + // re-measure, which lays the card out untransformed) changes only with what it measured before (main's deps). + const live0 = useRef({ plan, layout, clock }); + live0.current = { plan, layout, clock }; const measure = useCallback(() => { + const { plan, layout, clock } = live0.current; const doc = readFrame.current?.contentDocument; if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return false; const card = doc.querySelector("[data-post-card]") as HTMLElement | null; // Laid out untransformed (no zoom), the follow geometry first; a zoom's word is measured as the card is at its peak. if (card) for (const k of Array.from(card.children) as HTMLElement[]) k.style.transform = ""; const geo = follow && doc.querySelector("[data-post-flow]") ? measureFollow(doc) : null; + // THE JOIN: the carried post opens where the item before's post sat (measured in its frame). + const jm = joinMeasure.current; + if (geo && jm && jm.anchor !== null) { + const c = card?.getBoundingClientRect(); + const w = doc.querySelector("[data-post-words]")?.getBoundingClientRect(); + const tile = doc.querySelector("[data-join-anchor]"); + const head = tile?.querySelector(".head")?.getBoundingClientRect(); + const slot = tile?.closest("[data-thread-slot]")?.getBoundingClientRect(); + const off = head && slot ? head.top - slot.top : 0; + if (c && w) (geo as Record<string, unknown>).joinAnchor = { y: Math.round((jm.anchor / (jm.A.width / c.width) - (w.top - c.top) - off) * 100) / 100 }; + } setFollowGeo(geo); const route = follow && geo ? followPath(follow, geo) : null; const list = Array.isArray(entry.fx) ? (entry.fx as Array<Record<string, unknown>>) : []; if (!card || !list.length) { setZooms([]); + setCaps([]); + mountCaptions({ css: "", chips: [] }, doc); return true; } const rect = (el: Element): Rect => { @@ -482,16 +618,74 @@ export default function PostItemPlayer({ out.push({ i, span: zoomSpan(fx0, t.t), scope, from: m.from, to: m.to, color: fx.highlight === false ? null : String(fx.highlight), region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } }); }); setZooms(out); + // Its captions: planned as the build plans them (each waits for a zoom), mounted, placed as the card is at each one's peak. + let cplan: ReturnType<typeof captionPlan> = []; + try { + cplan = captionPlan(entry, undefined, { zooms: out.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration as never }); + } catch { + cplan = []; + } + const k = box.height / 1080; + const sizes = mountCaptions({ css: captionCss({ height: box.height, palette: paletteOfDoc(doc) }), chips: cplan.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k }, doc); + const inset = Math.round(12 * k); + // Free space only (as the build places it): the whole box, never over a word, the card's furniture, an attachment or the clock. + const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset }; + const fixed: Rect[] = [...(layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot) as Rect[]) : [])]; + if (clock && clockRect.current) fixed.push(clockRect.current); + const placedCaps: LiveCaption[] = []; + type Geo = { error?: string; card: Rect; word: Rect; lines: Rect[]; avoid: Rect[]; obstacles: Rect[]; column: Rect | null }; + for (const c of cplan) { + const looks: Geo[] = []; + for (const t of follow ? [c.span.t1, c.span.t0, c.span.t3 - 0.01] : [c.span.t1]) { + if (follow) applyFollowState(followStateAt(follow, route, t), doc); + looks.push(measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: c.avoid }, doc) as Geo); + } + if (follow) applyFollowState(followStateAt(follow, route, c.span.t1), doc); + const g = looks[0]; + const size = sizes.find((x) => x.i === c.i); + if (g.error || !size) continue; + const placed = placeCaption({ word: g.word, sizes: size.sizes, bounds, card: g.card, column: g.column, place: c.place, obstacles: [...fixed, ...looks.flatMap((l) => l.obstacles ?? [])], gap: Math.round(10 * k) }); + if (!placed) continue; + placedCaps.push({ i: c.i, span: c.span, scope: c.scope, from: c.from, to: c.to, placed, base: g.word, lines: g.lines }); + } + setCaps(placedCaps); return true; }, [entry, zoomTimes, box.height, follow]); + // ---- the clock, live: mounted and placed once the page is drawn, set each tick ---- + const [clockAt, setClockAt] = useState<{ x: number; y: number } | null>(null); + const placeClock = useCallback(() => { + const doc = readFrame.current?.contentDocument; + if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return; + if (!clock) { + mountClock(null, doc); + setClockAt(null); + return; + } + const face = clockFace(clock.to, clock.zone); + const size = mountClock({ css: clockCss({ height: box.height, palette: paletteOfDoc(doc) }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } }, doc); + // Placed as the build places it: as the card is at the read's end (a threaded card's own post in). + const route = follow && doc.querySelector("[data-post-flow]") ? followPath(follow, measureFollow(doc)) : null; + if (follow && route) applyFollowState(followStateAt(follow, route, plan.total), doc); + const at = size ? measureClockPlace({ size, inset: Math.round(22 * (box.height / 1080)) }, doc) : null; + clockRect.current = at && size ? { x: at.x - 240 * (box.height / 1080), y: at.y, width: size.width + 240 * (box.height / 1080), height: size.height } : null; + if (follow && route) applyFollowState(followStateAt(follow, route, 0), doc); + setClockAt(at ? { x: at.x, y: at.y } : null); + }, [clock, box.height, follow, plan.total]); + const placeClockRef = useRef(placeClock); + placeClockRef.current = placeClock; const onFrameLoad = useCallback(() => { let tries = 0; const tick = () => { + placeClockRef.current(); if (measure() || tries++ > 50) return; setTimeout(tick, 100); }; tick(); }, [measure]); + // The clock placed again when it changes (another item before, a knob). + useEffect(() => { + placeClock(); + }, [placeClock]); useEffect(() => { // The item changed under a loaded page (a knob, a zoom added): measure again. onFrameLoad(); @@ -503,11 +697,72 @@ export default function PostItemPlayer({ const doc = readFrame.current?.contentDocument; if (doc) applyZoom(doc, live, zf, hl, boxes.current); }, [live, zf, hl]); + useEffect(() => { + if (joinReady) onFrameLoad(); + }, [joinReady, onFrameLoad]); const followNow = useMemo(() => (follow ? followStateAt(follow, followRoute, s) : null), [follow, followRoute, s]); + // The join's frame (post-join.mjs joinFrameAt): this card's box, the item before's card riding it, the slots. + const jp = joinOn && joinMeasure.current && s < joinSecs ? Math.max(0, s / joinSecs) : null; + const [ownBox, setOwnBox] = useState<Rect | null>(null); + useEffect(() => { + const doc = readFrame.current?.contentDocument; + const jm = joinMeasure.current; + if (!doc?.body || !jm) return; + if (!doc.body.getAttribute("data-join")) { + doc.body.setAttribute("data-join", JSON.stringify({ A: jm.A, slotA: jm.slotA, slotB: layout.slot && layout.mode === "side" ? layout.slot : null, same: false })); + const c = doc.querySelector("[data-post-card]")?.getBoundingClientRect(); + if (c) setOwnBox({ x: c.left, y: c.top, width: c.width, height: c.height }); + } + applyJoinState(jp, doc); + }, [jp, joinReady, layout]); + const jframe = jp !== null && joinMeasure.current && ownBox ? joinFrameAt({ A: joinMeasure.current.A, B: ownBox, slotA: joinMeasure.current.slotA, slotB: layout.slot && layout.mode === "side" ? layout.slot : null, same: false }, jp) : null; + // THE BRANCH MAP (post-branch-map.mjs): its own layer over the attachments, where the build lays it. + const branchMap = (follow?.thread as { map?: Record<string, unknown> } | undefined)?.map ?? null; + const mapRef = useRef<HTMLDivElement | null>(null); + const mapBox = useMemo(() => { + if (!branchMap) return null; + const k = box.height / 1080; + const size = mapSize(branchMap as never, k); + return { ...mapPlace(layout as never, box, size, k), ...size, html: mapHtml(branchMap as never, { k }) }; + }, [branchMap, box, layout]); + useEffect(() => { + if (mapRef.current) applyMapState((followNow?.map ?? null) as never, mapRef.current as unknown as Document); + }, [followNow, mapBox]); + const joinEnds = useMemo(() => (joinFrom ? endMediaOf(joinFrom.plan as never, { stepAt, mediaTimeAt }) : []), [joinFrom]); useEffect(() => { const doc = readFrame.current?.contentDocument; if (doc && follow && doc.querySelector("[data-post-follow]")) applyFollowState(followNow, doc); + // A LINK VISIT (post-link-visit.mjs): the pointer and its click, as the build draws them. + const visits = (follow as { visits?: unknown[] } | null)?.visits; + if (doc && visits?.length) applyVisitState({ visits, st: followNow?.visit ?? null }, doc); }, [follow, followNow, followGeo]); + // The captions up now, after the follow state of this tick: each tracking its phrase (measured live when the card pans). + const capsUp = caps.filter((c) => s >= c.span.t0 && s < c.span.t3); + useEffect(() => { + const doc = readFrame.current?.contentDocument; + if (!doc) return; + const k = box.height / 1080; + const list = capsUp.flatMap((c) => { + // A pan moving its phrase ends it (as the build does): the chip never rides over words. + if (follow) { + const g = measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: [] }, doc) as { error?: string; word: Rect }; + if (!g.error && (Math.abs(g.word.y - c.base.y) > 1 || Math.abs(g.word.x - c.base.x) > 1)) return []; + } + const left = captionSlideAt(c.span, s); + const rel = c.placed.y >= c.base.y + c.base.height ? "below" : c.placed.y + c.placed.height <= c.base.y ? "above" : c.placed.x >= c.base.x ? "side-right" : "side-left"; + const d = slideDir(rel); + const opacity = captionOpacityAt(c.span, s); + return [{ i: c.i, x: c.placed.x, y: c.placed.y, max: c.placed.max, opacity, dx: d.x * CAPTION_SLIDE * k * left, dy: d.y * CAPTION_SLIDE * k * left, marks: c.lines, mark: opacity, leader: c.placed.leader }]; + }); + setCaptionState({ list, stroke: Math.max(2, Math.round(2.4 * k)) }, doc); + }, [capsUp, s, follow, followNow, box.height]); + const clockSt = useMemo(() => (clock ? clockStateAt(clock, s) : null), [clock, s]); + useEffect(() => { + const doc = readFrame.current?.contentDocument; + if (!doc) return; + const until = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : Infinity; + setClockState(clockSt && clockAt && s < until ? { ...clockAt, st: clockSt } : null, doc); + }, [clockSt, clockAt, s, layout.mode, plan.steps]); const src = shown && inStep ? mediaTimeAt(shown, s) : null; const cue = wordsRel && src !== null ? (cues[wordsRel] ?? []).find((c) => src >= c.start && src < c.end) ?? null : null; return ( @@ -515,6 +770,8 @@ export default function PostItemPlayer({ ref={wrap} data-post-play={entry.id} data-post-layout={layout.mode} + data-post-panel={layout.panel ?? undefined} + data-post-join={joinOn ? (jp !== null ? String(Math.round(jp * 100) / 100) : "done") : undefined} data-post-step={reading ? "read" : current?.kind ?? "held"} data-post-s={String(Math.round(s * 100) / 100)} data-post-narrated={mix ? "1" : undefined} @@ -525,6 +782,13 @@ export default function PostItemPlayer({ data-post-zooms={zooms.length ? String(zooms.length) : undefined} data-post-zoom={zooms.length ? String(Math.round(zf * 100) / 100) : undefined} data-post-zoom-fx={live ? String(live.i) : undefined} + data-post-captions={caps.length ? String(caps.length) : undefined} + data-post-clock={clockSt ? `${clockSt.time} ${clockSt.date}` : undefined} + data-post-clock-mode={clockSt ? clockSt.mode : undefined} + data-post-clock-gap={clockSt && clockSt.gapOpacity > 0 ? clockSt.gap : undefined} + data-post-caption-fx={capsUp.length ? capsUp.map((c) => String(c.i)).join(" ") : undefined} + data-post-caption-place={capsUp.length ? capsUp.map((c) => c.placed.place).join(" ") : undefined} + data-post-caption-covers={capsUp.length ? capsUp.map((c) => String(c.placed.covers)).join(" ") : undefined} data-post-follow-block={followNow?.current !== null && followNow?.current !== undefined ? String(followNow.current) : undefined} data-post-follow-offset={followNow && followRoute?.segments.length ? String(Math.round(followNow.offset)) : undefined} data-post-follow-pans={followRoute ? String(followRoute.segments.length) : undefined} @@ -549,6 +813,23 @@ export default function PostItemPlayer({ className="absolute inset-0 border-0" style={{ width: box.width, height: box.height, visibility: mediaPhase ? "hidden" : "visible" }} /> + {joinOn && s < joinSecs + 0.2 && ( + // THE JOIN: the item before's card as it ended, riding the container (the build: its shot) and fading out. + <iframe + title={`post ${joinFrom!.entry.id} (as it ended)`} + ref={joinFrame} + onLoad={onJoinLoad} + src={pageUrlOf(joinFrom!.entry.id, "read")} + data-post-join-frame={joinFrom!.entry.id} + className="absolute left-0 top-0 border-0" + style={{ + width: box.width, height: box.height, transformOrigin: "0 0", zIndex: 2, + opacity: jframe ? jframe.from.op : 0, + transform: jframe ? `translate(${jframe.R.x - joinMeasure.current!.A.x * jframe.from.s}px, ${jframe.R.y - joinMeasure.current!.A.y * jframe.from.s}px) scale(${jframe.from.s})` : "none", + clipPath: jframe ? `inset(${joinMeasure.current!.A.y}px ${box.width - joinMeasure.current!.A.x - joinMeasure.current!.A.width}px ${Math.max(0, box.height - joinMeasure.current!.A.y - Math.min(joinMeasure.current!.A.height, jframe.R.height / jframe.from.s))}px ${joinMeasure.current!.A.x}px)` : "none", + }} + /> + )} {layout.mode === "stack" && ( <iframe title={`post ${entry.id} (media)`} @@ -560,10 +841,21 @@ export default function PostItemPlayer({ )} </div> )} + {plan.panel && layout.slot && ( + // THE PANEL (post-thread.mjs panelSchedule): a context post's attachment over the slot while it is on screen. + <PanelShows project={project} shows={plan.panel.shows} fade={plan.panel.fade} slot={layout.slot} box={box} s={s} /> + )} + {mapBox && ( + <div ref={mapRef} data-post-branch-map="" className="pointer-events-none absolute z-20" style={{ left: pct(mapBox.x, box.width), top: pct(mapBox.y, box.height), transform: `scale(${scale || 1})`, transformOrigin: "0 0" }} dangerouslySetInnerHTML={{ __html: mapBox.html }} /> + )} + {jframe && joinFrom && ( + // THE JOIN: what the item before ended on in its slot, fading out (the same attachment is held, not drawn twice). + <JoinEnds project={project} ends={joinEnds} layout={postLayout(joinFrom.entry, box)} box={box} op={jframe.slotFrom < 1 || !shown || joinEnds[0]?.m?.src !== shown.items[0]?.src ? 1 - jframe.e : 0} /> + )} {shown && layout.slot && (layout.mode === "side" || mediaPhase) && ( <> {stepBoxes(shown, layout.slot).map((b: { x: number; y: number; width: number; height: number }, j: number) => ( - <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} mix={mix} speed={speed} /> + <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} joinOp={jframe && !(joinEnds.length === 1 && joinEnds[0].m.src === shown.items[j]?.src) ? Math.min(1, Math.max(0, (jframe.e - 0.35) / 0.65)) : 1} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} mix={mix} speed={speed} /> ))} {cue && ( <div diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -83,11 +83,13 @@ Inbox cannot disagree about what is wrong with one. | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | | `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) | | `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | -| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings) | +| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [thread.group=<name>\|off] [thread.map=auto\|on\|off\|map\|label\|both] [panel=auto\|side\|top\|bottom] [media.add=<file>] [media.<i>=off] [parent.<i>=<json ref>\|@<file>\|off] [parent.<i>.media=<file>[,…]\|off] [link.add=<json ref>] [link.<i>=<json ref>\|off] [link.<i>.media=<file>\|off] [link.<i>.transcript="…"\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings). THREAD SCENES ([knobs.md](knobs.md#thread-scenes-the-join-whole-threads-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)): `parent.<i>=` an ancestor added / replaced / dropped (a whole-thread read), `parent.<i>.media=` its attachments, `media.add=` / `media.<i>=off` an attachment from a project file (measured), `link.add=` a post its words link to (a link visit) with its picture and transcript, `thread.group=` a manual thread, `thread.map=` the branch map, `panel=` where its attachments sit | | `posts reread <project> <item> [--without parent:0\|parent:1\|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]` | a narrated read **re-joined without a piece**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the picked take's kept parts cut out of its own file (ffmpeg) and joined with the read's pauses, measured, added as a derived take (`steps: [{op: "rejoin", drop}]`, its parts re-timed with their roles, its word timings moved, its slurs state kept) and picked — ONE write (one undo point). `--without` drops the parts that read the post it answers (`parent:0`), its parent (`parent:1`) or the quoted post; `--drop-parts` by number; `--drop-urls` the parts that are nothing but a link. Nothing to drop, every part dropped or a take read in one go: **exit 1**. `posts set-item … thread.parent.<i>=context\|hidden` (or `thread.quoted=…`) on a piece the take reads runs it first (`--no-reread`: refused, as before) | -| `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item) at its first item's place in TREE order — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) | +| `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) | | `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) | -| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) | +| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) | +| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) | +| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times | | `posts fx <project> <item> [ls]` · `add word-zoom --match "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--scale s] [--hold s] [--lead s] [--ease out\|inOut\|snap] [--highlight #rrggbb\|off]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]` | a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`) | | `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is | | `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one | @@ -99,6 +101,7 @@ Inbox cannot disagree about what is wrong with one. | `posts combo <project> [on=on\|off] [label=L] [position=top-right\|top-left\|bottom-right\|bottom-left\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\|hit\|coin] [minCount=2-20] [match=id\|file\|audio] [--json]` · `posts combo <project> <item> off\|on\|auto\|label=…\|position=…\|color=…\|scale=…\|sfx=… [--json]` | the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**) | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one | +| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post-json:<json>\|post-json:@<file> [--id ID]` | **a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>` | | `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) | | `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project>` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build ([knobs.md](knobs.md#look-presets)) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -762,6 +762,41 @@ snapshot and every script keep their words. | `render.posts.slurs.add` — the project's own words (always masked; a word, or `{word, forms?, mask?, say?}`) · `.except` — never masked here (a form, a slur's word or its id) | — | `umtool posts slurs <p> add <word>` · `except <word>` · `remove <word>` (one writer, `updatePostSlurs`) | — | | what the cut masks | — | `umtool posts slurs <p> ls [--json]`: per slur (its mask, never the word) and per post, and each read that needs word timings | — | +## A caption (a chip explaining a phrase as it is read) + +`fx: [{kind: "caption", match, text, …}]` on a post item ([report-video.md](report-video.md#a-caption): the shape, +the time, the place, the render). One writer, `updatePostFx`, refused in the build's words (`captionErrors`, +`report-to-video/post-caption.mjs`, through `validatePostFx`). Its bench is the post bench's **word zoom · caption** +block; Play the cut and the bench draw the build's own chip, live. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| a caption -- `match` (the phrase as the card shows it), `text` (≤ 160 characters, any script: CJK is drawn in Noto Sans CJK; the part before " — " bold), `occurrence`, `target` (`post`, `quoted`, `parent:<i>`) | post bench: click a word (shift-click: a phrase), type the text, **Caption here**; a caption's text field | `umtool posts fx <p> <item> add caption --match "Fudōshin" --text '不動心 · fudōshin — "immovable mind"' [--target quoted] [--occurrence n]` | `POST /api/report/post-item {project, op: "fx", id, fx: {add: {kind: "caption", match, text, …}}, token}` | +| `at` -- item seconds (0–600); absent: the matched word's start in the picked take's word timings, else the reading estimate (a narrated read spread over its script by characters; un-narrated, 1 s + 3 words a second) | the caption's **−0.1** / **+0.1**, **at playhead**, **from the read** (clears it) | `umtool posts fx <p> <item> set <n> --at 4.2` (`--at default`: back to the words / the estimate) | `fx: {set: <i>, patch: {at}}` | +| `lead` 0–3 s in before the word (0.15), `hold` 0.5–10 s from it (2.5), `place` `below` \| `above` \| `side` (below) -- it never covers a word read while it is up (the next place that is clear wins); it waits for a word zoom it would be up with | the caption's **lead**, **hold**, **place** | `set <n> --lead 0.3 --hold 3 --place above` (`default` clears one) | `fx: {set: <i>, patch: {…}}` | +| remove one | the caption's **remove** | `umtool posts fx <p> <item> remove <n>` | `fx: {remove: <i>}` | +| list them, each with its time and where it came from | the block's rows; the plan strip marks each (blue) | `umtool posts fx <p> <item> [ls] [--json]` | — | + +## The clock (each post's own time on its card, run between items) + +`render.posts.clock` (the cut's default) and `fx: [{kind: "clock", on?, rewind?}]` on a post item +([report-video.md](report-video.md#the-clock)): the item's own post time, "4:10 AM ET · Wed 4 Nov", run forward +from the clock item before it in its first 0.8 s (the gap flashing), or rewound when it is earlier. Refused in the +build's words (`clockErrors`, `validateClockRender`, `report-to-video/post-clock.mjs`). + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| the cut's clock -- `on` (off by default), `zone` (an IANA zone; `America/New_York`) | — | `umtool posts clock <p> on\|off\|default [--zone America/New_York]` (`updatePostClock`); bare: which items show it | — | +| one item's clock -- on (or `on: false`: not on this item though the cut's is) | post bench, the clock's row (**remove**) | `umtool posts fx <p> <item> add clock [--off]` · `remove <n>` | `fx: {add: {kind: "clock"}}` | +| `rewind` `auto` (an earlier post rewinds) \| `on` (rewinds anyway) \| `off` (cuts straight to its time) | the clock's **rewind** | `umtool posts fx <p> <item> set <n> --rewind on\|off\|auto` | `fx: {set: <i>, patch: {rewind}}` | + +## The pace (a burst played back to back) + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `narration.pace` -- `fast` (lead 0.1, tail 0.15, ramp 0.3, linger 0.45, unless the post sets one itself) \| `normal` (the cut's gaps); `render.postNarration.pace` the cut's. The schedule, the build, Play and the deck's estimate honour it | — | `umtool posts narrate <p> <item> pace=fast\|normal\|default` · `umtool posts narrate <p> --cut pace=fast` | — | +| a REPEATED item (a stinger): a second copy of a post item, its narration and takes reused, its own knobs | — | `umtool timeline <p> duplicate <id>` then `timeline <p> move <id>-copy --to <n>` | — | + ## A word zoom (a post item's card pushed in on a word as it is read) `fx: [{kind: "word-zoom", match, …}]` on a post item ([report-video.md](report-video.md#a-word-zoom): the shape, the @@ -822,6 +857,27 @@ gathers them). | the cut's conversations — one run is one scene; `threads --write` gathers each in tree order (a post after what it answers, sibling branches by date, never across a section) | — | `umtool timeline <p> threads [--json]` · `threads --write [--conversation <id>]` (one undo point) | — (`orderEntries`) | | a post item's `conversation` (the archive row's threadId) and `quoted.via: "link"` (a status link resolved to an archived post) | — | `umtool posts context <p> [--dry-run]` | — (`setPostItemsContext`) | +## Thread scenes (the join, whole threads, manual threads, wide attachments, context media, link visits, the branch map) + +What each is: [report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map). +The item knobs go through `updatePostItem` (`posts set-item`), each refused in the build's words; Play the cut, the +card route and the build draw the same states. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `render.posts.join` — the join between items of one run: `{on, seconds}` (default on, 0.6 s, 0.2–2); the read starts after it | — | (the manifest's `render.posts.join`) | — | +| `join` on a post item — `false`: a cut; `{seconds}` its own | — | (the manifest) | `POST /api/report/post-item {op: "set", patch}` | +| `parents[i]` — an ancestor added (i = the next index), replaced or dropped, nearest first, up to 8: `{id, author, handle, date, text, media?, paraphrase?}` | — | `umtool posts set-item <p> <item> 'parent.1={"id":"…","handle":"…","author":"…","date":"…","text":"…"}'` · `parent.1=@ref.json` · `parent.1=off` | `POST /api/report/post-item {op: "set", patch: {parents: {"1": {ref}}}}` | +| `parents[i].media` — a context post's attachments, shown in the slot while it is on screen (project files, measured) | — | `umtool posts set-item <p> <item> parent.0.media=posts-media/…/1.mp4[,…]` · `=off` | same, `{parents: {"0": {media: [...]}}}` | +| `media` from a project file — added (kind, size, length measured) or removed | — | `umtool posts set-item <p> <item> media.add=posts-media/…` · `media.1=off` | same, `{mediaAdd: [...]}` · `{media: {"1": null}}` | +| `links[]` — a post its words link to that the card draws (a link visit), its picture and the words read off it (`transcript`, role `linked:<i>`) | — | `umtool posts set-item <p> <item> 'link.add={…}'` · `link.0.media=<file>` · `link.0.transcript="…"` · `link.0=off` | same, `{linksAdd: [...]}` · `{links: {"0": {...}}}` | +| `thread.group` — a MANUAL THREAD: consecutive items of one group are one scene, in timeline order | — | `umtool posts set-item <p> <item> thread.group=jiggle` (`off`) · `umtool timeline <p> threads --write --conversation jiggle` (gathered in date order) | same, `{thread: {group}}` | +| `render.posts.panel` — a wide attachment's layout: `{wide, place}` (default 2.0, `top`; `bottom`; `side`: never) | — | (the manifest) | — | +| `panel` on a post item — `side`, `top`, `bottom` (absent: the cut's rule) | — | `umtool posts set-item <p> <item> panel=top` (`auto`) | same, `{panel}` | +| `render.posts.linkVisit` — `{on, hold}` (default on, 1.4 s: a post read earlier lit again that long) · `linkVisit: false` on an item | — | (the manifest) | — | +| `render.posts.threadMap` — the branch map: `{on, style}` (default on, `both`; `map`, `label`) · `thread.map` on an item: `false`, `true`, a style | — | `umtool posts set-item <p> <item> thread.map=off` (`label`, `map`, `both`, `auto`) | same, `{thread: {map}}` | +| a post item made by hand (no archive holds it) | — | `umtool timeline <p> insert --after <id> 'post-json:{"post":"<chan>/<id>","author":…,"handle":…,"date":…,"text":…,"media":["posts-media/…"]}'` (or `post-json:@file.json`) | — | + ## The combo counter A post item that plays an attachment an earlier post item of the cut already played gets a fighting-game badge, diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -659,6 +659,111 @@ post's insert and `umtool posts avatars <p>`, or set by hand with `umtool posts <p> <handle> <image>` (never replaced by the archive's). Every card that draws that author unblurred shows it — the render, Play and the bench; a redacted author never. +### A caption + +A post item may carry a CAPTION: a small chip explaining a phrase, up as the phrase is +read and held a beat (`report-to-video/post-caption.mjs`; operator, 4 Nov: `不動心 · +fudōshin — "immovable mind"` on "Fudōshin"). It sits beside a word zoom in `fx`: + +```jsonc +"fx": [{ + "kind": "caption", + "match": "Fudōshin", // the phrase as the card shows it (as a word zoom's) + "text": "不動心 · fudōshin — \"immovable mind\"", // ≤ 160 characters, any script; the part before " — " bold + "target": "post", "occurrence": 1, // whose words, its n-th time (as a word zoom's) + "at": 4.2, // item seconds; absent: the take's word timings, else the estimate + "lead": 0.15, "hold": 2.5, // in this long before the word; held this long from it + "place": "below" // "below" (default) | "above" | "side" +}] +``` + +**When** -- a word zoom's rule: `at`, else the matched word's start in the picked take's +word timings (lead + start ÷ rate), else the READING ESTIMATE: a narrated read spread over +its script by characters (the card's words aligned to the script), an un-narrated post's +1 s + 3 words a second. It fades and slides in over 0.3 s and out over 0.35 s. A caption +that would be up while a word zoom is (its lead-in to back out) WAITS for the zoom to be +out; two captions of a post up at once are refused, and one is gone by a stack card's media +phase. + +**Where**: a chip by the phrase -- the card's palette (a panel of its background toward the +accent, the accent's border), its faces, then the CJK faces (`Noto Sans CJK JP`, `Source +Han Sans`, `WenQuanYi Zen Hei`) so 不動心 is drawn -- with a notch pointing at the phrase and +an accent underline under it. It never covers a word read while it is up: `place` first, +then below, above, side (each vertical place centred on the phrase, then its edges aligned); +among the places clear of the read, the one hiding fewest of the card's other words; the +build notes a WARNING when none is clear. It tracks the phrase while the card pans +(read-follow), and it is drawn OVER the card, never in it -- no `data-w`, no +`data-post-block` -- so `readInViewErrors` never counts it. + +**The render**: on the card page as drawn at the caption's peak, the phrase measured (a +phrase cut off the card is refused), the chip placed, then shot alone on a clear page (the +chip with its notch; the underline apart) and laid over the card (`postSegmentArgs` +`captionFx`): fading, sliding in toward the phrase, riding the phrase's track. Play and the +bench mount the same markup in the card frame (`mountCaptions`, `setCaptionState`) on the +same curve. The post record (`<id>.post.json`) keeps each caption's time, span, place and box. + +### The clock + +A post item may show its CLOCK (`report-to-video/post-clock.mjs`; operator, 4 Nov: "show a +clock advancing as we show the newest posts/replies chronologically and quickly to convey +how much he's posting in bursts"; "the clock should probably just be for mr obvious' +replies ... so it generally always goes forward unless there's a compelling reason to go +back"): a small chip on the card, "4:10 AM ET · Wed 4 Nov" with an analogue face, in the +cut's zone (`America/New_York`). + +```jsonc +"render": { "posts": { "clock": { "on": true, "zone": "America/New_York" } } }, // the cut's default +"fx": [{ "kind": "clock", "on": false, "rewind": "auto" }] // one item's ("on" default true) +``` + +It shows the ITEM's own post time (`entry.date`) -- never a parent's or a quote's -- and it +does not move while they are read. Between two consecutive clock items, in the first 0.8 s +of the second it RUNS from the earlier time to this one (`easeInOut`): the hands spin, the +minutes roll, the date flips day by day, the gap flashes in a badge beside it ("+39 s", +"+38 min", "+2 h 14 min", "+3 d 4 h") for 0.9 s, then fades over 0.4 s. When this post is +EARLIER than the one before it REWINDS: the hands spin backwards, the face's ring dashes, and +the badge says "⟲ rewind −12 h 6 min". `rewind: "off"` cuts straight to the time; `"on"` +rewinds even forward (a repeat of the same post spins back a full turn to itself). An item +after a non-clock entry shows its time without a run. + +It sits at the card's bottom-right corner, beside the counts row, else its top-right -- the +first over no word of the card -- drawn over the card, never in it (`readInViewErrors` +never counts it). The render shoots its frames alone on a clear page (each distinct state +once: the run and the badge's fade) and lays them over the card from the first frame (a +stack card's, until its media phase); Play and the bench mount the same chip +(`mountClock`, `setClockState`) from `clockPlan`, which needs the item before it (`playView` +`postClock`; the bench's `before`). + +### The pace + +`pace: "fast"` on a narrated post's narration (or `render.postNarration.pace`, the cut's) +plays it BACK TO BACK (`POST_PACES`): lead 0.1, tail 0.15, ramp 0.3, linger 0.45 -- unless +the post sets one of those itself (its own always wins); `"normal"` is the cut's gaps (on a +post, it undoes a cut's `fast`). It rides the narration's knobs (`postNarrationKnobs`), so the +schedule, the build, Play and the deck's estimate all honour it. An un-narrated post has no +read gaps to shorten (its `hold` is its length). + +### Caching: the segment key + +A post segment is rebuilt only when its key changes (`<id>.post.json`'s `key`). The entry is in it -- a +caption's text and knobs, the clock fx, the narration's `pace`, the item's id (a repeated item is its own +segment) -- and `postFxKeyFields` (`post-render.mjs`) APPENDS what the entry does not carry: `captionV` and +`clockV` (the chip's and the clock's drawing, bumped when their look changes), `clock` (the plan: this post's +time, the time it runs from -- the item before's, when that one is a clock item -- the mode, a forced rewind, +the zone) and `pace` (the gap knobs a cut-level pace resolved to). An item with none of these adds nothing, so +its key is the one it had before they existed and a take `--from` an earlier one reuses its segment. +A take `--from` another hard-links a post item's record (`.post.json`) and its combo pass's files (`.combo.json`, +`.plain.mp4`) with its segment (`SEGMENT_FILE_SUFFIXES`), and a post item's files are no longer detached before +its build: a matching key keeps the linked segment, and every write of a rebuilt one goes through a rename, so +the other take's files are never written through (before, every post item was rebuilt in a `--from` take). + +### A repeated item + +`umtool timeline <p> duplicate <id>` copies a post item to just after itself under a fresh +id (`<id>-copy`), its narration and takes REUSED (the same files), its knobs its own -- move +it where the stinger goes (`timeline move <id>-copy --to <n>`) and give it its own pace, +clock or captions. Two items of one post build two segments. + ### A word zoom A post item's card may PUSH IN ON A WORD as it is read (`report-to-video/word-zoom.mjs`; @@ -911,6 +1016,85 @@ the scene its run leaves on screen (`planContext`: the build, Play, the bench, t writers' guard and the lint all pass it). Not narrated, or with no context post drawn, the card is as it was. +### Thread scenes: whole threads, the join, manual threads, wide attachments, context media, link visits, the branch map + +lane/thread-scenes (operator, 4 Nov, after mid-6 of the Mr. Obvious cut: "We'll almost certainly need code changes to +how we handle threads, especially ones that switch layout currently. It's fine if implementing all my requests +lengthens the video a bit"). The standing rule holds throughout: no hidden text is ever narrated, and every read +piece is shown in full and lit while it is read. + +**A whole thread, in date order.** An item may carry up to 8 ancestors (`parents`, nearest first; `POST_PARENTS_MAX` +-- a reel and `posts context` still fill two from the archive, `POST_PARENTS_FILL`); `posts set-item <p> <item> +parent.<i>=<json ref>|@<file>|off` adds one (i = the next index), replaces one or drops one. A take that reads every +ancestor the run has not read, oldest first, maps its parts to `parent:N` … `parent:1`, `parent:0`, `post` (the +roles), and each ancestor is a tile in full and lit while it is read, then shrunk and dimmed. THE READ IS IN DATE +ORDER (operator: "include the whole thread chronologically"): role inference ranks the texts by their posts' dates +(`roleOrderOf`; by kind when one has none), and the tiles follow the take's read (`orderByRead`) -- a quoted take +older than the post he answers is read first and drawn first, above it (p-2115519823090479417: his take 16:00, +Kirsche 17:45, his reply 19:03). A tile that does not answer the one drawn just above it says what it answers +("replying to @X"; in a manual thread every reply does, "replying to the post above"), from the real parents. + +**The join** (`report-to-video/post-join.mjs`; "I'd like a thread-like smooth transition here rather than a cut"). +An item of a conversation run (or a manual thread) opens on the item before AS IT ENDED and morphs into its own +layout over its first `seconds` (0.6; the same content at the same width -- a carried post drawn alike -- switches +at the first frame, never a double image) -- a card beside an attachment to a card alone, another attachment, another +width: the card's container eases from that item's box to its own (the words scaled with it, never re-flowed), that +item's card -- shot at its last frame in the build, its page in a second frame in Play -- rides the container and +fades as this one's comes in, the post it ended on (carried in, or the scene's) is drawn as that item drew its post +(its head, its words at their size) and framed where it sat (the anchor measured on both pages), the slot's well +fades in or out, and the attachment it ended on (its last frame) cross-fades into this one's -- the same one (a media +scene) is held. The read starts AFTER the join (`narrationSchedule`'s `pre`): an item in a run is the join longer. +`render.posts.join = { on, seconds }`; an item's `join: false` cuts. The build shoots the whole box while it joins +(the card and the slot's well move); `readInViewErrors` checks every read from its settle, after the join. + +**A manual thread** (`thread.group`; "basically do all of them chronologically as if a thread, maybe subtly indicate +the original relations"). Consecutive items with the same `thread.group` are one run even when X does not link them +(an un-narrated item may open it: shown, not read); every earlier post stays on screen, stacked oldest first, small +and dim (none collapses); each tile says what it answers. `timeline <p> threads --write [--conversation <group>]` +gathers a group at its first item's place in DATE order, the other entries after it in their order. It sits with a +media scene: the group's attachment may change from item to item (a join cross-fades it), same-attachment items +still hold it. + +**Wide attachments** (`postLayout`'s `panel`; "for these super wide images a top-bottom layout would be better"). An +attachment of width ÷ height ≥ `render.posts.panel.wide` (2.0; its crop counted) is laid at full width ABOVE the card +(`place: "top"`, or `"bottom"`), at most 42 % of the box, the card under it (at most 1500 px of a 1080 frame wide); +`panel=side|top|bottom` on an item overrides (`panelEntry` lays the cut's rule on in the build, Play, the route and the +bench). The join morphs to and from it like any other layout. + +**Context media** (`panelSchedule`, the plan's `panel`). A parent, a quoted post or a linked post may carry `media` +(project files; `parent.<i>.media=<file>`, measured as they go in): while that piece is on screen its attachment shows +in the slot over the item's own (cross-faded, 0.3 s) -- from its read (one not read, an image-only reply: from when its +tile is on screen, at least 1.2 s) until the next piece with media or his own words; with none of his own, the last +one is held. A slot is laid out for it when he carries none. A linked post's tall picture whose words are read (its +`transcript`, role `linked:<i>`) SCROLLS top to foot in step with its parts (the build: its crop's y on t; Play: the +same keyframes); `panelReadErrors` refuses a part read off a picture the panel is not showing. A tall picture shown, +not read, is laid at a readable width from its top (drifting down a little), and one shown while his own words are +read is a look at it (2.4 s), then his own attachment again. For a batch re-voicing a whole thread, +`chronoPieces(entry, { skip })` (post-thread.mjs) lists the pieces to read in date order. + +**Link visits** (`report-to-video/post-link-visit.mjs`; "can we have our transition visit it with a mouse click +visual?"). A status link in a drawn post's words to a post the card draws (the quote -- matched by its author when the +archive kept no id --, a linked post, a post it answers): a pointer glides to the link, clicks (a ripple), and the +post opens as it comes in (its reveal) -- or, read earlier (a thread read in date order), is lit again at full size +with an accent ring for `hold` s (1.4; the item holds it). A linked post shown, not read, is hidden until its click. +`links[]` holds posts its words link to that no archive gave (`posts set-item … link.add=<json ref>`, `link.<i>.media=`, +`link.<i>.transcript=`). `render.posts.linkVisit = { on, hold }`; an item's `linkVisit: false`. + +**The branch map** (`report-to-video/post-branch-map.mjs`; "a specific visual for changing thread branches that makes +the context obvious"). When the scene moves to another branch -- a sibling reply, a reply to an earlier post, a jump +back up -- a small map draws the posts on screen as a tree -- its own layer, laid over the attachments' slot (its +top-left corner), or beside a card alone, never over words being read (the build shoots it on a transparent page and +lays it over the attachments; Play lays the same markup) -- (a line for each reply, his posts in +his colour), the light travelling from the post the item before ended on up to the post the two branches share and +down to the new one, labelled ("another reply to his post", "back to @X's post"; a blurred author is "a stranger's"). +It comes in as the scene changes (the first piece, after the join), travels 1.1 s, holds, fades. `render.posts.threadMap += { on, style: "map" | "label" | "both" }`; an item's `thread.map` (`false`, `true` or a style). + +**A post item by hand** (`timeline <p> insert … post-json:<json>|@<file>`): a post no archive holds (Kirsche's reply, +kept only as a picture) -- `post`, `author`, `handle`, `date`, `text`, `media` (project files, measured), `parents`…; +its avatar `posts avatar <p> <handle> <file>`; refused as the build would. **An attachment from a file**: +`posts set-item … media.add=<file>` (kind and size measured), `media.<i>=off`. + ### The combo counter When a post item's attachment is one an EARLIER post item of the cut already played — diff --git a/umtool/e2e/post-captions.spec.ts b/umtool/e2e/post-captions.spec.ts @@ -0,0 +1,127 @@ +import { test, expect, type Page } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// A POST ITEM's CAPTION and CLOCK (report-to-video/post-caption.mjs, +// post-clock.mjs; knobs.md, "A caption", "The clock"). Fixture: +// e2e/fixtures/post-narration-fixture.mjs -- p-11 "The video speaks for +// itself." narrated by a 2 s take (no word timings: the reading estimate), +// p-12 four pictures, p-13 words only; all dated 30 Oct 10:00 UTC. +// +// POST_CAPTIONS_SHOTS=<dir> screenshots there +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "post-narration-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-narration-fixture"; +const SHOTS = process.env.POST_CAPTIONS_SHOTS ?? null; + +type Entry = { id: string; date?: string; fx?: Array<Record<string, unknown>> }; +const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[]; render: Record<string, unknown> }; +const timeline = () => manifest().timeline; + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + rmSync(path.join(DIR, "notes.json"), { force: true }); +}); + +type Box = { x: number; y: number; width: number; height: number }; +const overlap = (a: Box, b: Box) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); +/** In the card frame: the box of `sel` and of every card word. */ +const boxesIn = (page: Page, sel: string) => + page.frameLocator('[data-post-card-frame="read"]').locator("body").evaluate((body, s) => { + const r = (el: Element) => { + const b = el.getBoundingClientRect(); + return { x: b.left, y: b.top, width: b.width, height: b.height }; + }; + const el = body.ownerDocument.querySelector(s); + return { el: el ? r(el) : null, words: Array.from(body.ownerDocument.querySelectorAll("[data-w]")).map((w) => ({ id: w.getAttribute("data-w"), ...r(w) })) }; + }, sel); + +test("A CAPTION (operator, 4 Nov: 不動心 on \"Fudōshin\"): click a word -> type the text -> Caption here -> saved, timed by the reading estimate; Play shows the chip (CJK drawn) by the phrase as it is read, over no word read while it is up", async ({ page }) => { + await page.setViewportSize({ width: 1500, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const panel = page.locator('[data-post-zoom-panel="p-11"]'); + await panel.locator('[data-post-zoom-word="2"]').click(); + await expect(panel.locator("[data-post-caption-here]")).toBeDisabled(); + await panel.locator("[data-post-caption-text]").fill("不動心 · speaks — a test of the chip"); + await panel.locator("[data-post-caption-here]").click(); + await expect(panel.locator('[data-post-caption-fx="0"]')).toBeVisible(); + expect(timeline().find((e) => e.id === "p-11")!.fx).toEqual([{ kind: "caption", match: "speaks", text: "不動心 · speaks — a test of the chip" }]); + // Its time: no word timings, so the read spread over its script by characters (0.4 + 10/29 of 2 s). + const at = Number(await panel.locator("[data-post-caption-at]").getAttribute("data-post-caption-at")); + expect(at).toBeGreaterThan(0.9); + expect(at).toBeLessThan(1.3); + await expect(panel.locator('[data-post-caption-fx="0"]')).toContainText("the reading estimate"); + await expect(page.locator('[data-post-bench-caption-mark="0"]')).toBeVisible(); + // A knob: place above, one write. + await panel.locator('[data-post-caption-knob="place"]').selectOption("above"); + await expect.poll(() => timeline().find((e) => e.id === "p-11")!.fx?.[0]?.place).toBe("above"); + // The bench's own player mounts the chip. + await expect(page.locator('[data-post-play="p-11"]')).toHaveAttribute("data-post-captions", "1", { timeout: 15_000 }); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-caption-bench.png") }); + + // Play the cut: up from its lead-in, the chip in the card page, by the phrase. + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); + const player = page.locator('[data-post-play="p-11"]'); + await expect(player).toHaveAttribute("data-post-captions", "1", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + await expect(player).toHaveAttribute("data-post-caption-fx", "0", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + const chip = page.frameLocator('[data-post-card-frame="read"]').locator('[data-post-fx-caption="0"]'); + await expect(chip).toContainText("不動心"); + await expect.poll(() => chip.evaluate((el) => Number((el as HTMLElement).style.opacity))).toBeGreaterThan(0); + // CJK is drawn by a face this machine has, not boxes. + expect(await chip.evaluate((el) => el.ownerDocument.fonts.check("27px 'Noto Sans CJK JP'", "不動心"))).toBe(true); + // Never over the words read while it is up ("for itself." after "speaks"); never in the card's words. + const { el, words } = await boxesIn(page, '[data-post-fx-caption="0"]'); + expect(el).not.toBeNull(); + for (const w of words.filter((x) => x.id === "post:3" || x.id === "post:4")) expect(overlap(el!, w)).toBe(0); + expect(await chip.evaluate((el) => el.closest("[data-post-card]") === null && !el.querySelector("[data-w], [data-post-block]"))).toBe(true); + // Its underline under the phrase. + await expect(page.frameLocator('[data-post-card-frame="read"]').locator('[data-post-fx-caption-mark="0"]')).toHaveCount(1); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-caption-play.png") }); +}); + +test("THE CLOCK: each item's own time on its card, run FORWARD from the clock item before (the gap flashing) and REWOUND when the next is earlier; Play draws it over no word", async ({ page }) => { + const m = manifest(); + const set = (id: string, o: Record<string, unknown>) => Object.assign(m.timeline.find((e) => e.id === id)!, o); + set("p-11", { fx: [{ kind: "clock" }] }); + set("p-12", { date: "2026-10-30T10:38:00.000Z", fx: [{ kind: "clock" }] }); + set("p-13", { date: "2026-10-28T09:00:00.000Z", fx: [{ kind: "clock" }] }); + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); + await page.setViewportSize({ width: 1500, height: 1000 }); + + // Forward: p-12 after p-11, 38 minutes on (America/New_York: 6:00 AM -> 6:38 AM). + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-12" })); + const p12 = page.locator('[data-post-play="p-12"]'); + await expect(p12).toHaveAttribute("data-post-clock-mode", "forward", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + await expect(p12).toHaveAttribute("data-post-clock-gap", "+38 min", { timeout: 15_000 }); + await expect(p12).toHaveAttribute("data-post-clock", "6:38 AM Fri 30 Oct", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + const clock = page.frameLocator('[data-post-card-frame="read"]').locator("[data-post-clock]"); + await expect(clock).toContainText("ET"); + const { el, words } = await boxesIn(page, "[data-post-clock]"); + for (const w of words) expect(overlap(el!, w)).toBe(0); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-clock-forward.png") }); + + // Rewind: p-13 is two days earlier than p-12. + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-13" })); + const p13 = page.locator('[data-post-play="p-13"]'); + await expect(p13).toHaveAttribute("data-post-clock-mode", "rewind", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + await expect(p13).toHaveAttribute("data-post-clock-gap", /^⟲ rewind −2 d 1 h/, { timeout: 15_000 }); + await expect(p13).toHaveAttribute("data-post-clock", "5:00 AM Wed 28 Oct", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-clock-rewind.png") }); +}); diff --git a/umtool/e2e/thread-scenes.spec.ts b/umtool/e2e/thread-scenes.spec.ts @@ -0,0 +1,125 @@ +import { test, expect, type Page } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// THREAD SCENES (report-to-video/post-join.mjs, post-conversation.mjs, post-item.mjs postLayout; knobs.md, "The join", +// "Manual threads", "Wide attachments"; operator, 4 Nov, mid-6: "I'd like a thread-like smooth transition here rather +// than a cut", "do all of them chronologically as if a thread", "for these super wide images a top-bottom layout"): +// - a run whose items switch layout (a card beside a video, then a card alone) JOINS in Play: the item before's card +// as it ended in a frame of its own riding the morph, this card's box eased into its own; +// - a manual thread (thread.group) stacks unlinked posts as one scene, each reply saying what it answers; +// - a wide attachment is laid at full width above the card. +// Fixture: e2e/fixtures/post-narration-fixture.mjs's items, rewritten here. +// +// THREAD_SCENES_SHOTS=<dir> screenshots there +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const REPORTS = path.join(HERE, "..", ".e2e-song", "reports"); +const DIR = path.join(REPORTS, "post-narration-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-narration-fixture"; +const SHOTS = process.env.THREAD_SCENES_SHOTS ?? null; + +const ROOT_TEXT = "Many have questioned my methods in dealing with the whole mess, and I will say it once more for everyone."; +const REPLY = "I can't help but feel like I've failed everyone, they all got exactly what they wanted out of it."; +const ROOT = { id: "11", author: "Narr Subject", handle: "narrsubject", date: "2026-10-30T06:00:00.000Z", text: ROOT_TEXT }; + +function takeOf(pieces: string[]) { + let at = 0; + const parts = pieces.map((text, pi) => { + const seconds = Math.round((text.split(/\s+/).length / 3) * 100) / 100; + if (pi) at += 0.6; + const p = { n: pi + 1, para: pi * 100, text, start: Math.round(at * 100) / 100, seconds }; + at += seconds; + return p; + }); + return { file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "leo+zac", seconds: Math.round(at * 100) / 100, script: pieces.join("\n\n"), parts }; +} + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + rmSync(path.join(DIR, "notes.json"), { force: true }); + const m = JSON.parse(readFileSync(MANIFEST, "utf8")); + const byId = (id: string) => m.timeline.find((x: { id: string }) => x.id === id); + const narr = (e: Record<string, unknown>, text: string, pieces: string[]) => Object.assign(e, { text, narration: { script: text, takes: [takeOf(pieces)], pick: 0 } }); + // A run that switches layout: his root beside its video, then his reply under it, a card alone. + const root = narr(byId("p-11"), ROOT_TEXT, [ROOT_TEXT]); + root.date = ROOT.date; + const reply = narr(byId("p-12"), REPLY, [REPLY]); + delete reply.media; + reply.date = "2026-10-30T07:00:00.000Z"; + reply.parents = [ROOT]; + // A manual thread: a post he answered (shown), then two of his, unlinked on X. + const opener: Record<string, unknown> = { ...structuredClone(reply), id: "p-21", post: "othchan-x/21", author: "Movail", handle: "movail_two", text: "Ready for more lessons?", date: "2026-10-30T08:00:00.000Z", thread: { group: "lessons" } }; + delete opener.parents; + delete opener.narration; + const g1: Record<string, unknown> = narr({ ...structuredClone(reply), id: "p-22", post: "narrchan-x/22", date: "2026-10-30T09:00:00.000Z", thread: { group: "lessons" } }, "It wobbles, oh my word.", ["It wobbles, oh my word."]); + delete g1.parents; + const g2 = narr({ ...structuredClone(reply), id: "p-23", post: "narrchan-x/23", date: "2026-10-30T09:05:00.000Z", thread: { group: "lessons" }, parents: [{ id: "21", author: "Movail", handle: "movail_two", date: "2026-10-30T08:00:00.000Z", text: "Ready for more lessons?" }] }, "It wobbles, I cannot even.", ["It wobbles, I cannot even."]); + // A wide attachment. + const wide = narr({ ...structuredClone(byId("p-13")), id: "p-31", post: "narrchan-x/31", parents: undefined, media: [{ src: "posts-media/narrchan-x/12/12_1.png", kind: "image", width: 692, height: 141 }] }, "If anything happens I am holding them accountable.", ["If anything happens I am holding them accountable."]); + delete wide.parents; + m.timeline = [root, reply, opener, g1, g2, wide]; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); +}); + +async function playAt(page: Page, id: string, at: number) { + await page.goto(urls.playHref(PROJECT, { bare: true, clip: id, at })); + const player = page.locator(`[data-post-play="${id}"]`); + await expect(player).toBeVisible({ timeout: 15_000 }); + const frame = page.frameLocator('[data-post-card-frame="read"]'); + await expect(frame.locator("body")).toHaveAttribute("data-post-ready", "1", { timeout: 15_000 }); + await expect.poll(async () => Math.abs(Number(await player.getAttribute("data-post-s")) - at)).toBeLessThan(0.3); + return { player, frame }; +} + +test("THE JOIN in Play: his reply (a card alone) opens on his root as it ended beside its video -- the item before's card in a frame of its own riding the morph, this card's box eased from that one's -- and is its own once the join is over", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + { + const { player, frame } = await playAt(page, "p-12", 0.25); + await expect(page.locator('[data-post-join-frame="p-11"]')).toHaveCount(1); + await expect.poll(async () => player.getAttribute("data-post-join")).toMatch(/^0\.\d+$/); + // The page knows where the item before's card was; its own card moved and scaled toward its own box. + await expect(frame.locator("body")).toHaveAttribute("data-join", /"A":\{/); + await expect.poll(async () => frame.locator("[data-post-card]").evaluate((el) => (el as HTMLElement).style.transform)).toMatch(/translate\(.*scale\(/); + // The carried root is drawn as his post was (head and words), the join's anchor. + await expect(frame.locator('[data-thread-tile="parent:0"]')).toHaveAttribute("data-join-anchor", ""); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "join-mid.png") }); + } + { + const { player, frame } = await playAt(page, "p-12", 1.5); + await expect.poll(async () => player.getAttribute("data-post-join")).toBe("done"); + await expect.poll(async () => frame.locator("[data-post-card]").evaluate((el) => (el as HTMLElement).style.transform)).not.toMatch(/scale\(/); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "join-after.png") }); + } +}); + +test("A MANUAL THREAD (thread.group): the post he answered, then two of his unlinked on X, one scene -- every earlier post kept on screen, each reply saying what it answers", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + const { frame } = await playAt(page, "p-23", 2.5); + await expect(frame.locator('[data-thread-slot="conv:22"]')).toHaveAttribute("data-thread-scene", "keep"); + await expect(frame.locator('[data-thread-slot="parent:0"]')).toHaveCount(1); + // His last reply answers the post three tiles up: "replying to @movail_two" (blurred: a private account). + await expect(frame.locator('[data-thread-slot="post"] [data-thread-rel="branch"]')).toContainText("replying to"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "group.png") }); +}); + +test("A WIDE ATTACHMENT (692×141) is laid at full width above the card, never a side panel", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + const { player, frame } = await playAt(page, "p-31", 1); + await expect(player).toHaveAttribute("data-post-panel", "top"); + const slot = await frame.locator("[data-post-slot]").boundingBox(); + const card = await frame.locator("[data-post-card]").boundingBox(); + expect(slot && card && slot.y + slot.height <= card.y + 1).toBe(true); + expect(slot && card && slot.width > card.width).toBe(true); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "wide.png") }); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2356,11 +2356,13 @@ 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", "thread", "scene"]); +export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene"]); /** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */ export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ -export const POST_CONTEXT_KNOBS = Object.freeze(["paraphrase"]); +export const POST_CONTEXT_KNOBS = Object.freeze(["paraphrase", "ref", "media", "transcript"]); +/** The fields a context post (a parent, a linked post) is given by hand (`parent.<i>=<ref>`, post-item.mjs refErrors). */ +const POST_REF_FIELDS = Object.freeze(["id", "author", "handle", "badge", "date", "text", "url", "media", "paraphrase", "transcript", "via"]); /** * SET A POST ITEM's KNOBS (the post bench, `umtool posts set-item`): `patch` @@ -2380,7 +2382,7 @@ export const POST_CONTEXT_KNOBS = Object.freeze(["paraphrase"]); export async function updatePostItem(dir, id, patch, { token = null } = {}) { if (!isObj(patch)) throw new Error("a post item's patch is an object"); for (const k of Object.keys(patch)) { - if (!["media", "quoted", "parents"].includes(k) && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media", "quoted", "parents"].join(", ")})`); + if (!["media", "mediaAdd", "quoted", "parents", "links", "linksAdd"].includes(k) && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media", "mediaAdd", "quoted", "parents", "links", "linksAdd"].join(", ")})`); } return structural(dir, "post-item", token, (m) => { const i = entryIndex(m.timeline, id); @@ -2418,6 +2420,7 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { for (const [key, mp] of Object.entries(patch.media)) { const n = Number(key); if (!Number.isInteger(n) || !media[n]) throw new Error(`${id} has no attachment ${key} (0–${media.length - 1})`); + if (mp === null) continue; // removed below, once every index has been read if (!isObj(mp)) throw new Error(`media.${key} is an object of knobs`); for (const k of Object.keys(mp)) if (!POST_MEDIA_KNOBS.includes(k)) throw new Error(`media.${key}.${k} is not an attachment knob (${POST_MEDIA_KNOBS.join(", ")})`); for (const k of POST_MEDIA_KNOBS) { @@ -2440,7 +2443,20 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { if (Number.isFinite(media[n].seconds) && Number.isFinite(media[n].end) && Math.abs(media[n].end - media[n].seconds) < 0.02) delete media[n].end; } } - // A context post's paraphrase (`quoted`, `parents[i]`): its text is never touched. + // Attachments removed (`media.<i>=off`) and added from project files (`media.add=`, measured by the caller). + if (isObj(patch.media)) { + const drop = new Set(Object.entries(patch.media).filter(([, v]) => v === null).map(([k2]) => Number(k2))); + if (drop.size) { + e.media = (e.media ?? []).filter((_, n) => !drop.has(n)); + if (!e.media.length) delete e.media; + } + } + if (patch.mediaAdd !== undefined) { + if (!Array.isArray(patch.mediaAdd)) throw new Error("mediaAdd is a list of attachments"); + e.media = [...(Array.isArray(e.media) ? e.media : []), ...patch.mediaAdd]; + } + // A context post's paraphrase (`quoted`, `parents[i]`): its text is never touched. A hand-made ref (`ref`), its + // attachments (`media`) and the words read off its picture (`transcript`) are set here too. const setContext = (ref, cp, what) => { if (!isObj(cp)) throw new Error(`${what} is an object of knobs`); for (const k of Object.keys(cp)) if (!POST_CONTEXT_KNOBS.includes(k)) throw new Error(`${what}.${k} is not a context knob (${POST_CONTEXT_KNOBS.join(", ")})`); @@ -2449,25 +2465,63 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { if (v !== null && v !== undefined && typeof v !== "string") throw new Error(`${what}.paraphrase is a string (or null: its own words)`); set(ref, "paraphrase", typeof v === "string" && v.trim() ? v.trim() : null); } + if ("media" in cp) { + if (cp.media !== null && !Array.isArray(cp.media)) throw new Error(`${what}.media is a list of attachments (or null: none)`); + set(ref, "media", cp.media?.length ? cp.media : null); + } + if ("transcript" in cp) { + if (cp.transcript !== null && typeof cp.transcript !== "string") throw new Error(`${what}.transcript is the words read off its picture (or null)`); + set(ref, "transcript", typeof cp.transcript === "string" && cp.transcript.trim() ? cp.transcript.trim() : null); + } + }; + const cleanRef = (r, what) => { + if (!isObj(r)) throw new Error(`${what} is a post ({ id, author, handle, date, text, … })`); + const bad = Object.keys(r).filter((k) => !POST_REF_FIELDS.includes(k)); + if (bad.length) throw new Error(`${what}: ${bad.join(", ")} not a post's field (${POST_REF_FIELDS.join(", ")})`); + return JSON.parse(JSON.stringify(r)); + }; + // A list of refs (`parents`, `links`) patched by index: `ref` replaces (the next index appends) or (null) drops one. + const patchRefs = (field, rp) => { + if (!isObj(rp)) throw new Error(`${field} is an object of { <i>: knobs }`); + let list = Array.isArray(e[field]) ? e[field] : []; + const drop = new Set(); + for (const [key, cp] of Object.entries(rp).sort((a, b) => Number(a[0]) - Number(b[0]))) { + const n = Number(key); + if (!isObj(cp)) throw new Error(`${field}.${key} is an object of knobs`); + if ("ref" in cp) { + if (cp.ref === null) { + if (!isObj(list[n])) throw new Error(`${id} has no ${field === "parents" ? "parent" : "linked post"} ${key}`); + drop.add(n); + continue; + } + if (!Number.isInteger(n) || n < 0 || n > list.length) throw new Error(`${field}.${key}: the next one is ${list.length} (nearest first)`); + list[n] = cleanRef(cp.ref, `${field}.${key}`); + } + if (!Number.isInteger(n) || !isObj(list[n])) throw new Error(list.length ? `${id} has no ${field === "parents" ? "parent" : "linked post"} ${key} (0–${list.length - 1}${field === "parents" ? ", nearest first" : ""})` : `${id} ${field === "parents" ? "answers no post it carries" : "links no post"}`); + const { ref: _r, ...rest } = cp; + void _r; + if (Object.keys(rest).length) setContext(list[n], rest, `${field}.${key}`); + } + list = list.filter((_, n) => !drop.has(n)); + if (list.length) e[field] = list; + else delete e[field]; }; if (patch.quoted !== undefined) { if (!isObj(e.quoted)) throw new Error(`${id} quotes no post`); setContext(e.quoted, patch.quoted, "quoted"); } - if (patch.parents !== undefined) { - if (!isObj(patch.parents)) throw new Error("parents is an object of { <i>: knobs }"); - const parents = Array.isArray(e.parents) ? e.parents : []; - for (const [key, cp] of Object.entries(patch.parents)) { - const n = Number(key); - if (!Number.isInteger(n) || !isObj(parents[n])) throw new Error(parents.length ? `${id} has no parent ${key} (0–${parents.length - 1}, nearest first)` : `${id} answers no post it carries`); - setContext(parents[n], cp, `parents.${key}`); - } + if (patch.parents !== undefined) patchRefs("parents", patch.parents); + // Added first, so `link.add=… link.<n>.transcript=…` in one call names the one just added. + if (patch.linksAdd !== undefined) { + if (!Array.isArray(patch.linksAdd)) throw new Error("linksAdd is a list of posts"); + e.links = [...(Array.isArray(e.links) ? e.links : []), ...patch.linksAdd.map((r, n) => cleanRef(r, `linksAdd[${n}]`))]; } + if (patch.links !== undefined) patchRefs("links", patch.links); 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) { + if ("thread" in patch || "follow" in patch || "parents" in patch || "links" in patch || "linksAdd" in patch) { // With the item before it and the scene its run leaves on screen (post-conversation.mjs; a fresh list, so never // a context worked out before this write). const ctx = planContext(m.timeline.slice(), i, m.render); @@ -2681,7 +2735,7 @@ export function handlesWithoutAvatar(m, handles) { // ---- a post item's narration (report-to-video/post-narration.mjs) ---------- /** The narration keys a write may set on one post item (post-narration.mjs; knobs.md, "A narrated post item"). */ -export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "window"]); +export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace", "window"]); /** * One post item's narration, changed in place (`m` the manifest inside a @@ -2993,6 +3047,38 @@ export async function updatePostRedact(dir, change, { token = null } = {}) { }); } +// ---- the clock (post-clock.mjs; `umtool posts clock`) ----------------------- + +/** + * SET THE CUT's CLOCK (`render.posts.clock`): `{ on?, zone? }` (a null: back to + * the default -- off, America/New_York). One item's own (`fx: [{kind: "clock"}]`) + * wins over it. Validated with the build's check. + * + * @param {string} dir + * @param {{ on?: boolean | null, zone?: string | null }} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostClock(dir, patch, { token = null } = {}) { + if (!isObj(patch) || !Object.keys(patch).length) throw new Error("say on, off or a zone"); + return structural(dir, "post-clock", token, (m) => { + if (!isObj(m.render)) m.render = {}; + const posts = isObj(m.render.posts) ? m.render.posts : {}; + const c = isObj(posts.clock) ? { ...posts.clock } : {}; + for (const [k, v] of Object.entries(patch)) { + if (!["on", "zone"].includes(k)) throw new StructureRefused([`render.posts.clock.${k} is not a clock knob (on, zone)`]); + if (v === null || v === undefined) delete c[k]; + else c[k] = v; + } + if (Object.keys(c).length) posts.clock = c; + else delete posts.clock; + if (Object.keys(posts).length) m.render.posts = posts; + else delete m.render.posts; + const errors = validatePostsRender(m.render); + if (errors.length) throw new StructureRefused(errors); + return { clock: posts.clock ?? null }; + }); +} + // ---- the slur filter (post-slurs.mjs; `umtool posts slurs`) --------------- /** diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -14,8 +14,9 @@ import { resolveFactcheck } from "umtool-report-to-video/factcheck"; import { channelsDirFor, clipDateKey, readManifest } from "../projects/report.mjs"; import { rejectionOf } from "./rejectReasons.mjs"; import { dateKeyLabel } from "./playCut.mjs"; -import { postDay, postItemPlan } from "umtool-report-to-video/post-item"; +import { panelEntry, postDay, postItemPlan } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; +import { clockPlan } from "umtool-report-to-video/post-clock"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; import { readWorkingCut } from "./workingCut.mjs"; @@ -60,10 +61,12 @@ export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = nu dateLabel: dateKeyLabel(dateKey), date: day || null, quote: words || null, - post: sceneEntry(e, mediaScene), + post: panelEntry(sceneEntry(e, mediaScene), render), // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in); `scene`: the // posts its run left on screen (post-conversation.mjs: one conversation played as one scene) -- it wins the card. - postPlan: postItemPlan(sceneEntry(e, mediaScene), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene }), + postPlan: postItemPlan(panelEntry(sceneEntry(e, mediaScene), render), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene, join: ctx?.join ?? null }), + // Its clock (post-clock.mjs): its post's time, run from the clock item before it. + postClock: clockPlan(e, render, ctx?.prev ?? null), ...(mediaScene ? { postScene: { key: mediaScene.key, n: mediaScene.n, of: mediaScene.of, ids: mediaScene.ids, anchor: mediaScene.anchor.id } } : {}), }; } diff --git a/umtool/lib/report/postFx.test.mjs b/umtool/lib/report/postFx.test.mjs @@ -55,7 +55,7 @@ test("posts fx: add (an un-narrated post gets the reading estimate), set, ls, re r = await cli(["fx", "fx", "p-1", "remove", "1"]); assert.equal(r.code, 0, r.err); assert.equal((await manifest(p)).timeline[0].fx, undefined); - assert.match(r.out, /no word zooms/); + assert.match(r.out, /no effects/); await assert.rejects(updatePostFx(p.dir, "p-1", { remove: 0 }), /has no effects/); }); @@ -88,3 +88,26 @@ test("posts narrate --words: the take transcribed by the editor (its parts, at t for (const f of ["p01", "p02"]) await writeFile(path.join(p.dir, `narration/posts/1/take-1.parts/${f}.wav`), ""); assert.deepEqual(await takeWordSources(p.dir, parted), [{ file: parted.parts[0].file, offset: 0 }, { file: parted.parts[1].file, offset: 2.6 }]); }); + +test("posts fx add caption: the chip's text kept (CJK too), timed by the reading estimate, its knobs set -- a zoom's knobs refused", async () => { + const p = await project("cap", [item("1", { text: "I have achieved Fudōshin. Its amazing." })]); + let r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin", "--text", "不動心 · fudōshin — \"immovable mind\""]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /0 word zoom\(s\), 1 caption\(s\)/); + assert.match(r.out, /#1 caption "Fudōshin" \(post, 1st\) at 2.00 s \(the reading estimate\) · "不動心 · fudōshin — "immovable mind"" · in 0.15 s before, held 2.5 s, below/); + assert.deepEqual((await manifest(p)).timeline[0].fx, [{ kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"" }]); + r = await cli(["fx", "cap", "p-1", "set", "1", "--place", "above", "--hold", "3", "--at", "1.5"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual((await manifest(p)).timeline[0].fx[0], { kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"", place: "above", hold: 3, at: 1.5 }); + r = await cli(["fx", "cap", "p-1", "set", "1", "--place", "left"]); + assert.equal(r.code, 1); + assert.match(r.err, /fx\[0\]\.place must be one of below, above, side/); + r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin"]); + assert.match(r.err, /add caption needs --text/); + r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin", "--text", "x", "--scale", "2"]); + assert.match(r.err, /--scale is a word zoom's knob/); + r = await cli(["fx", "cap", "p-1", "add", "word-zoom", "--match", "amazing", "--text", "x"]); + assert.match(r.err, /--text and --place are a caption's knobs/); + r = await cli(["fx", "cap", "p-1", "ls", "--json"]); + assert.deepEqual(JSON.parse(r.out).times, [{ i: 0, t: 1.5, source: "at" }]); +}); diff --git a/umtool/lib/report/postFxCli.mjs b/umtool/lib/report/postFxCli.mjs @@ -8,6 +8,8 @@ // umtool posts fx <p> <item> [ls] // umtool posts fx <p> <item> add word-zoom --match "…" [--target post|quoted|parent:<i>] [--occurrence n] [--at s] // [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off] +// umtool posts fx <p> <item> add caption --match "…" --text "…" [--target …] [--occurrence n] [--at s] +// [--lead s] [--hold s] [--place below|above|side] (post-caption.mjs) // umtool posts fx <p> <item> set <n> [the same flags; a flag's value `default` clears it] // umtool posts fx <p> <item> remove <n> // umtool posts narrate <p> <item> --words [--worker <id>] @@ -19,15 +21,20 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, findMatch, readingEstimate, resolveWordZoom, scriptWordTimes, targetTextOf, wordZoomTimes, } from "umtool-report-to-video/word-zoom"; +import { CAPTION_DEFAULTS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; +import { CLOCK_REWINDS, CLOCK_ZONE, clockFace, clockOn, clockZoneOf } from "umtool-report-to-video/post-clock"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; -import { manifestToken, updatePostFx, updatePostNarration } from "./manifest.mjs"; +import { manifestToken, updatePostClock, updatePostFx, updatePostNarration } from "./manifest.mjs"; import { findPostItem } from "./postNarrationCli.mjs"; export const FX_USAGE = [ "usage: umtool posts fx <project> <item> [ls] [--json]", " umtool posts fx <project> <item> add word-zoom --match \"…\" [--target post|quoted|parent:<i>] [--occurrence n]", " [--at s] [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off] [--json]", + " umtool posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post|quoted|parent:<i>] [--occurrence n]", + " [--at s] [--lead s] [--hold s] [--place below|above|side] [--json]", + " umtool posts fx <project> <item> add clock [--rewind auto|on|off] [--off]", " umtool posts fx <project> <item> set <n> [those flags; `default` clears one] | remove <n>", " A WORD ZOOM: the card pushed in on a word (or a phrase) as it is read, a highlight under it, then back out.", " --match is the word as the card shows it (case and edge punctuation aside); --occurrence its n-th time in the", @@ -36,7 +43,16 @@ export const FX_USAGE = [ " read's rate) -- `umtool posts narrate <p> <item> --words` gets them from the editor's transcription. An", " un-narrated post needs --at (add fills the reading estimate: 1 s + 3 words a second).", ` --scale 1.2–4 (default ${WORD_ZOOM_DEFAULTS.scale}), --lead 0–3 s in before the word (${WORD_ZOOM_DEFAULTS.lead}), --hold 0–10 s on it (${WORD_ZOOM_DEFAULTS.hold}),`, - ` --ease ${WORD_ZOOM_EASES.join("|")} (${WORD_ZOOM_DEFAULTS.ease}), --highlight a colour or off (${WORD_ZOOM_DEFAULTS.highlight}). <n>: the zoom's number as ls shows it.`, + ` --ease ${WORD_ZOOM_EASES.join("|")} (${WORD_ZOOM_DEFAULTS.ease}), --highlight a colour or off (${WORD_ZOOM_DEFAULTS.highlight}). <n>: the effect's number as ls shows it.`, + " A CAPTION: a chip explaining a phrase (--text, any script: CJK is drawn), up as the phrase is read and held a beat,", + " by the phrase (--place; it never covers a word read while it is up) with a notch and an underline. WHEN: --at, else", + " the word's start in the take's word timings, else the reading estimate (a narrated read spread over its script).", + ` --lead 0–3 s in before the word (${CAPTION_DEFAULTS.lead}), --hold 0.5–10 s from it (${CAPTION_DEFAULTS.hold}), --place ${CAPTION_PLACES.join("|")} (${CAPTION_DEFAULTS.place}).`, + " A caption up while a word zoom is waits for the zoom to be out.", + " A CLOCK: the post's own time on its card (\"4:10 AM ET · Wed 4 Nov\", the cut's zone), run from the clock item", + " before it in its first 0.8 s -- forward with the gap flashing (\"+38 min\"), or REWOUND when this post is earlier", + " (⟲ rewind). --rewind off cuts straight to it, on rewinds anyway; --off: no clock on this item though the cut's is", + " on (umtool posts clock <p> on).", ].join("\n"); export class FxError extends Error {} @@ -60,6 +76,12 @@ export function fxPatchOf(str) { out[key] = x; } } + const rw = str("--rewind"); + if (rw !== null) out.rewind = rw === "default" || rw === "auto" ? null : rw; + const tx = str("--text"); + if (tx !== null) out.text = tx; + const pl = str("--place"); + if (pl !== null) out.place = pl === "default" ? null : pl; const e = str("--ease"); if (e !== null) out.ease = e === "default" ? null : e; const h = str("--highlight"); @@ -69,14 +91,28 @@ export function fxPatchOf(str) { const nth = (n) => `${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"}`; -/** One item's zooms as lines. */ +/** One item's effects (word zooms, captions) as lines. */ export function fxLines(e, render) { const list = Array.isArray(e.fx) ? e.fx : []; - if (!list.length) return [`${e.id}: no word zooms (add one: umtool posts fx <p> ${e.id} add word-zoom --match "…")`]; + if (!list.length) return [`${e.id}: no effects (add one: umtool posts fx <p> ${e.id} add word-zoom --match "…" | add caption --match "…" --text "…")`]; const times = wordZoomTimes(e, render); + const ctimes = captionTimes(e, render); + const nz = list.filter((f) => f?.kind === "word-zoom").length; + const nc = list.filter((f) => f?.kind === "caption").length; + const clk = list.some((f) => f?.kind === "clock"); return [ - `${e.id}: ${list.length} word zoom(s)${isNarrated(e) ? "" : " (not narrated: each needs at)"}`, + `${e.id}: ${nz} word zoom(s), ${nc} caption(s)${clk ? ", its clock" : ""}${isNarrated(e) || !nz ? "" : " (not narrated: a zoom needs at)"}`, ...list.map((fx0, i) => { + if (fx0?.kind === "clock") { + const on = fx0.on !== false; + return ` #${i + 1} clock ${on ? `on -- ${clockFace(Date.parse(e.date), clockZoneOf(render)).time} ${clockFace(Date.parse(e.date), clockZoneOf(render)).date}, rewind ${fx0.rewind ?? "auto"}` : "off (the cut's clock not shown here)"}`; + } + if (fx0?.kind === "caption") { + const c = resolveCaption(fx0); + const t = ctimes[i]; + const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s (${t.source === "at" ? "set by hand" : t.source === "words" ? "from the take's words" : "the reading estimate"})`; + return ` #${i + 1} caption "${c.match}" (${c.target}, ${nth(c.occurrence)}) ${when} · "${c.text}" · in ${c.lead} s before, held ${c.hold} s, ${c.place}`; + } const fx = resolveWordZoom(fx0); const t = times[i]; const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s ${t.source === "at" ? "(set by hand)" : `(from the take's words: "${t.word.w}" at ${t.word.start} s)`}`; @@ -86,7 +122,7 @@ export function fxLines(e, render) { } /** `umtool posts fx …` (postsCli.mjs routes it here). */ -export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str }) { +export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str, off = false }) { const manifest = await readManifest(project.dir); if (!manifest) throw new FxError(`${project.id} has no manifest`); const render = manifest.render ?? {}; @@ -95,12 +131,15 @@ export async function fxCommand(project, words, { json = false, out = (s) => con if (!e) throw new FxError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); const write = async (op) => withEditNotes(project, async () => updatePostFx(project.dir, e.id, op, { token: await manifestToken(project.dir) })); const say = (entry, extra = {}) => { - if (json) out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render), ...extra }, null, 2)); + if (json) { + const ct = captionTimes(entry, render); + out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render).map((t, i) => (entry.fx?.[i]?.kind === "caption" ? ct[i] : t)), ...extra }, null, 2)); + } else out(fxLines(entry, render).join("\n")); }; const index = () => { const n = Number(arg); - if (!Number.isInteger(n) || n < 1) throw new FxError(`${verb} takes the zoom's number as ls shows it (1 = the first)`); + if (!Number.isInteger(n) || n < 1) throw new FxError(`${verb} takes the effect's number as ls shows it (1 = the first)`); return n - 1; }; if (verb === "ls") { @@ -108,8 +147,26 @@ export async function fxCommand(project, words, { json = false, out = (s) => con return 0; } if (verb === "add") { - if (arg !== "word-zoom") throw new FxError("add names the effect: add word-zoom --match \"…\""); + if (arg !== "word-zoom" && arg !== "caption" && arg !== "clock") throw new FxError("add names the effect: add word-zoom --match \"…\" | add caption --match \"…\" --text \"…\" | add clock"); const patch = Object.fromEntries(Object.entries(fxPatchOf(str)).filter(([, v]) => v !== null)); + if (arg === "clock") { + const extra = Object.keys(patch).filter((k) => k !== "rewind"); + if (extra.length) throw new FxError(`--${extra[0]} is not a clock's knob (--rewind ${CLOCK_REWINDS.join("|")}, --off)`); + if ((e.fx ?? []).some((f) => f?.kind === "clock")) throw new FxError(`${e.id} has its clock already (set <n> --rewind …, or remove <n>)`); + const { result } = await write({ add: { kind: "clock", ...patch, ...(off ? { on: false } : {}) } }); + say(result.entry, { index: result.index }); + return 0; + } + if ("rewind" in patch) throw new FxError("--rewind is a clock's knob (add clock …)"); + if (arg === "caption") { + if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add caption needs --match \"<the phrase, as the card shows it>\""); + if (typeof patch.text !== "string" || !patch.text.trim()) throw new FxError("add caption needs --text \"<what the chip says>\""); + for (const k of ["scale", "ease", "highlight"]) if (k in patch) throw new FxError(`--${k} is a word zoom's knob, not a caption's`); + const { result } = await write({ add: { kind: "caption", ...patch } }); + say(result.entry, { index: result.index }); + return 0; + } + if ("text" in patch || "place" in patch) throw new FxError("--text and --place are a caption's knobs (add caption …)"); if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add word-zoom needs --match \"<the word, as the card shows it>\""); let note = null; if (patch.at === undefined && !isNarrated(e)) { @@ -127,7 +184,7 @@ export async function fxCommand(project, words, { json = false, out = (s) => con if (verb === "set") { const i = index(); const patch = fxPatchOf(str); - if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --scale, --hold, --lead, --ease, --highlight, --occurrence, --target"); + if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --hold, --lead, --occurrence, --target; a zoom's --scale, --ease, --highlight; a caption's --text, --place"); const { result } = await write({ set: i, patch }); say(result.entry); return 0; @@ -140,6 +197,35 @@ export async function fxCommand(project, words, { json = false, out = (s) => con throw new FxError(`${verb}: ls, add, set or remove`); } +export const CLOCK_USAGE = [ + "usage: umtool posts clock <project> [on|off|default] [--zone <IANA zone>] [--json]", + " THE CUT's CLOCK (render.posts.clock): each post item's own time on its card (\"4:10 AM ET · Wed 4 Nov\"), run", + " forward between two clock items (the gap flashing), rewound when the next is earlier. on/off is the cut's", + ` default (an item's own: umtool posts fx <p> <item> add clock [--off]); --zone the clock's zone (${CLOCK_ZONE}).`, + " With no word: which items show it.", +].join("\n"); + +/** `umtool posts clock …` (postsCli.mjs routes it here). */ +export async function clockCommand(project, words, { json = false, out = (s) => console.log(s), str }) { + const [verb] = words; + const zone = str("--zone"); + if (verb !== undefined && !["on", "off", "default", "ls"].includes(verb)) throw new FxError(`${verb}: on, off or default`); + if ((verb && verb !== "ls") || zone !== null) { + const patch = {}; + if (verb === "on" || verb === "off") patch.on = verb === "on"; + if (verb === "default") patch.on = null; + if (zone !== null) patch.zone = zone === "default" ? null : zone; + await withEditNotes(project, async () => updatePostClock(project.dir, patch, { token: await manifestToken(project.dir) })); + } + const manifest = await readManifest(project.dir); + const render = manifest?.render ?? {}; + const items = (manifest?.timeline ?? []).filter((x) => x?.type === "post"); + const shown = items.filter((x) => clockOn(x, render)); + if (json) out(JSON.stringify({ ok: true, clock: render.posts?.clock ?? null, zone: clockZoneOf(render), items: shown.map((x) => x.id) }, null, 2)); + else out([`clock: the cut's ${render.posts?.clock?.on ? "on" : "off"}, zone ${clockZoneOf(render)}; ${shown.length} of ${items.length} post item(s) show it`, ...shown.slice(0, 40).map((x) => ` ${x.id} ${clockFace(Date.parse(x.date), clockZoneOf(render)).time} ${clockFace(Date.parse(x.date), clockZoneOf(render)).date}`)].join("\n")); + return 0; +} + /** * Where a take is transcribed from: its PARTS (a long post read part by part), * each on its own file and offset by its start in the take, when every part's diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -42,9 +42,9 @@ export const NARRATE_USAGE = [ " umtool posts narrate <project> --list [--json]", " umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", " [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full", - " wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=…] [--json]", + " wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--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=…", + " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… pace=fast|normal 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", @@ -57,6 +57,8 @@ export const NARRATE_USAGE = [ " --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op", " (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.", " A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,", + " pace=fast plays a post (or, with --cut, every post) back to back: lead 0.1, tail 0.15, ramp 0.3, linger 0.45 --", + " unless it sets one itself; pace=normal the cut's gaps.", " once `umtool posts fit` has scanned it (else from its in point). clip=full plays the attachments whole.", " rate=0.8–1.5 (default 1): the READ sped up (its pitch kept), the attachment untouched; the post's length, its", " muffle and its parts follow the faster read (a 10 s take at rate=1.25 reads in 8 s).", @@ -182,7 +184,7 @@ export function normalizeParts(raw) { 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.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\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 } : {}), })); @@ -215,7 +217,7 @@ export function narrationLines(e, render) { }); if (plan.narration) { const k = postNarrationKnobs(e, render); - lines.push(` mix: ${["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate"].map((x) => fmtKnob(x, k[x])).join(" ")}`); + lines.push(` mix: ${["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace"].map((x) => fmtKnob(x, k[x])).join(" ")}`); if (n.window) lines.push(` window: attachment ${n.window.media + 1} ${n.window.start}–${n.window.end} s (score ${n.window.score}): ${n.window.reason}`); lines.push(` plays: voice ${plan.narration.at}–${(plan.narration.at + plan.narration.seconds).toFixed(2)} s, muffled to ${plan.narration.voiceEnd} s, clean from ${plan.narration.rampEnd} s; attachments ${plan.steps.map((s) => `${s.kind} ${s.at}+${s.seconds}`).join(", ") || "none"}${plan.held ? `, held ${plan.held} s` : ""}`); } @@ -240,6 +242,8 @@ export function mixPatchOf(pairs, { cut = false } = {}) { if (["lead", "tail", "ramp", "linger", "wet", "lufs", "rate"].includes(k)) out[k] = clear ? null : num(); else if (k === "clip") out.clip = clear ? null : v; else if (k === "lowpass" || k === "lowpassHz") out.lowpassHz = clear ? null : num(); + // The pace (post-narration.mjs POST_PACES): fast plays it back to back; normal (or default) the cut's gaps. + else if (k === "pace") out.pace = clear ? null : v; else if (k === "duck") out.duck = clear ? null : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("duck= takes on or off"); })(); else if (k === "short") out.short = clear ? null : v; else if (k === "attach" && !cut) out.attach = clear ? null : v; @@ -265,7 +269,7 @@ export function mixPatchOf(pairs, { cut = false } = {}) { 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, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan" : "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, pace, engine, voice, follow, follow.dim, follow.ease, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan" : "linger, clip, attach, lufs, rate, pace, fit"})`); } if (!Object.keys(out).length) throw new NarrateError("nothing to set"); return out; diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs @@ -20,7 +20,7 @@ // words, author, date, link and counts snapshotted from the archive row; a // repost drawn as the post it reposts, "reposted by" its reposter; a reply // with the posts it answers (from the archive, nearest first, up to -// POST_PARENTS_MAX) -- else the capture's `shot-thread.png` -- else a +// POST_PARENTS_FILL) -- else the capture's `shot-thread.png` -- else a // "replying to" line; its attachments COPIED into the project // (`posts-media/<slug>/<postId>/`, never a link out of it) and measured (a // video's length and whether it has sound; X serves a GIF as a silent mp4 @@ -37,7 +37,7 @@ import { execFile } from "node:child_process"; import { copyFile, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; -import { POST_MEDIA_MAX, POST_PARENTS_MAX, authorRedaction, cardAuthors, subjectsOf } from "umtool-report-to-video/post-item"; +import { POST_MEDIA_MAX, POST_PARENTS_FILL, authorRedaction, cardAuthors, subjectsOf } from "umtool-report-to-video/post-item"; import { ARCHIVE_AVATARS_DIR, ARCHIVE_AVATARS_FILE, AVATARS_DIR, AVATAR_EXT_RE, avatarEntryOf, handleKey } from "umtool-report-to-video/post-avatars"; import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -265,7 +265,7 @@ export async function postEntryFrom(row, { index, io, subjects = [] }) { if (shown.isReply === true && replyTo?.id) { const parents = []; let at = replyTo; - while (at?.id && parents.length < POST_PARENTS_MAX) { + while (at?.id && parents.length < POST_PARENTS_FILL) { const p = index.get(String(at.id)); if (!p) break; parents.push(refOf(p)); diff --git a/umtool/lib/report/postThreadCli.mjs b/umtool/lib/report/postThreadCli.mjs @@ -37,7 +37,7 @@ export class RolesError extends Error { } } -const ROLE_RE = /^(post|quoted|parent:\d|media:\d)$/; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; /** * A narrated item's read, piece by piece: `{ id, take, pieces: [{ role, parts, source, mode }], errors, threaded }`. @@ -83,7 +83,7 @@ export async function rolesCommand(project, ids, { write = false, set = null, js 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)`); + if (role !== "off" && !ROLE_RE.test(role)) throw new RolesError(`--set ${pair}: a role is post, quoted, parent:<i>, linked:<i>, media:<i> (or off: inferred)`); roles[n - 1] = role === "off" ? null : role; } const take = (Number.isInteger(t.index) ? t.index : e.narration.pick ?? 0); diff --git a/umtool/lib/report/postThreadScenes.test.mjs b/umtool/lib/report/postThreadScenes.test.mjs @@ -0,0 +1,96 @@ +// lane/thread-scenes, the writers: `posts set-item` parent.<i>=<ref> (a whole thread, by hand), parent.<i>.media, +// media.add / media.<i>=off (an attachment from a project file, measured), link.add (a linked post), thread.group +// (a manual thread), panel=, thread.map=; and `timeline threads --write` gathering a group in date order. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { postItemPatchOf, postsCommand } from "./postsCli.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-thread-scenes-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const item = (id, o = {}) => ({ type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: `Words of post ${id}.`, ...o }); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "" }, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const cli = async (args) => { + const lines = []; + const errs = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + return { code, out: lines.join("\n"), err: errs.join("\n") }; +}; +let ffmpeg = true; +try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); +} catch { + ffmpeg = false; +} + +test("set-item parent.<i>=<ref>: an ancestor added at the next index, replaced, dropped; parent.<i>.media and media.add measured from project files", { skip: !ffmpeg && "no ffmpeg" }, async () => { + const p = await project("chain", [item("1", { parents: [{ id: "900", handle: "grok", author: "Grok", date: "2026-10-30T09:00:00.000Z", text: "An answer." }] })]); + await mkdir(path.join(p.dir, "posts-media", "x", "1"), { recursive: true }); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=692x141", "-frames:v", "1", path.join(p.dir, "posts-media/x/1/wide.png")]); + const justin = JSON.stringify({ id: "800", handle: "@JustinInYT1", author: "Justin", date: "2026-10-30T08:00:00.000Z", text: "@grok is that a threat?" }); + assert.deepEqual(postItemPatchOf([`parent.1=${justin}`]).parents["1"].ref.handle, "JustinInYT1"); + const add = await cli(["set-item", "chain", "p-1", `parent.1=${justin}`, "parent.1.media=posts-media/x/1/wide.png", "media.add=posts-media/x/1/wide.png", "panel=top", "thread.group=grok", "thread.map=both"]); + assert.equal(add.code, 0, add.err); + let e = (await manifest(p)).timeline[0]; + assert.deepEqual(e.parents.map((x) => x.id), ["900", "800"]); + assert.deepEqual(e.parents[1].media, [{ src: "posts-media/x/1/wide.png", kind: "image", width: 692, height: 141 }]); + assert.deepEqual(e.media, [{ src: "posts-media/x/1/wide.png", kind: "image", width: 692, height: 141 }]); + assert.equal(e.panel, "top"); + assert.deepEqual(e.thread, { group: "grok", map: "both" }); + // Past the next index: refused; a field a post has not: refused; a file not there: refused. + assert.match((await cli(["set-item", "chain", "p-1", `parent.5=${justin}`])).err, /the next one is 2/); + assert.match((await cli(["set-item", "chain", "p-1", 'parent.2={"id":"7","likes":3}'])).err, /likes is not a post's field/); + assert.match((await cli(["set-item", "chain", "p-1", "media.add=posts-media/none.png"])).err, /not in the project/); + // Replaced, then dropped; the attachment removed. + assert.equal((await cli(["set-item", "chain", "p-1", 'parent.0={"id":"901","handle":"grok","text":"Another answer.","date":"2026-10-30T09:30:00.000Z"}', "media.0=off", "thread.group=off"])).code, 0); + e = (await manifest(p)).timeline[0]; + assert.deepEqual(e.parents.map((x) => [x.id, x.text]), [["901", "Another answer."], ["800", "@grok is that a threat?"]]); + assert.equal(e.media, undefined); + assert.deepEqual(e.thread, { map: "both" }); + assert.equal((await cli(["set-item", "chain", "p-1", "parent.1=off"])).code, 0); + assert.deepEqual((await manifest(p)).timeline[0].parents.map((x) => x.id), ["901"]); +}); + +test("set-item link.add: a post its words link to, with a picture and the words read off it; link.<i>=off drops it", { skip: !ffmpeg && "no ffmpeg" }, async () => { + const p = await project("links", [item("2", { text: "this you? https://x.com/Infinity_Virus_/status/2116805001309823299" })]); + await mkdir(path.join(p.dir, "posts-media", "iv"), { recursive: true }); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=blue:s=600x4029", "-frames:v", "1", path.join(p.dir, "posts-media/iv/1.jpg")]); + const ref = JSON.stringify({ id: "2116805001309823299", handle: "Infinity_Virus_", author: "Infinity", date: "2026-11-01T08:10:15.000Z", text: "Ya try to be civil and they go insane", media: ["posts-media/iv/1.jpg"] }); + const r = await cli(["set-item", "links", "p-2", `link.add=${ref}`, "link.0.transcript=Line one of the messages.\n\nLine two of them."]); + assert.equal(r.code, 0, r.err); + const e = (await manifest(p)).timeline[0]; + assert.equal(e.links[0].media[0].height, 4029); + assert.equal(e.links[0].transcript, "Line one of the messages.\n\nLine two of them."); + assert.equal((await cli(["set-item", "links", "p-2", "link.0=off"])).code, 0); + assert.equal((await manifest(p)).timeline[0].links, undefined); +}); + +test("timeline insert post-json: a post no archive holds (Kirsche's reply kept only as a picture) -- its author, handle, date, words and its picture, measured; refused as the build would", { skip: !ffmpeg && "no ffmpeg" }, async () => { + const { timelineCommand } = await import("./timelineCli.mjs"); + const p = await project("synthetic", [item("1")]); + await mkdir(path.join(p.dir, "posts-media", "KirscheVerstahl-x", "2115523442074087838"), { recursive: true }); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=1127x500", "-frames:v", "1", path.join(p.dir, "posts-media/KirscheVerstahl-x/2115523442074087838/2115523442074087838_1.jpg")]); + const json = JSON.stringify({ post: "KirscheVerstahl-x/2115523442074087838", author: "Kirsche", handle: "@KirscheVerstahl", date: "2026-10-28T19:17:00.000Z", text: "@ObviousRises", media: ["posts-media/KirscheVerstahl-x/2115523442074087838/2115523442074087838_1.jpg"] }); + const lines = []; + const errs = []; + const code = await timelineCommand(["synthetic", "insert", "--after", "p-1", `post-json:${json}`], { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + assert.equal(code, 0, errs.join("\n")); + const e = (await manifest(p)).timeline[1]; + assert.equal(e.id, "p-2115523442074087838"); + assert.equal(e.handle, "KirscheVerstahl"); + assert.deepEqual(e.media, [{ src: "posts-media/KirscheVerstahl-x/2115523442074087838/2115523442074087838_1.jpg", kind: "image", width: 1127, height: 500 }]); + const bad = await timelineCommand(["synthetic", "insert", "--after", "p-1", 'post-json:{"post":"x","text":"a"}'], { root: REPORTS, out: () => {}, err: (s) => errs.push(s) }); + assert.notEqual(bad, 0); + assert.match(errs.join("\n"), /post must be <channel>\/<postId>/); +}); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -28,6 +28,7 @@ // replaced (its attachTo kept unless --attach says otherwise). // // Plain ESM: the CLI runs under bare node. +import { readFileSync } from "node:fs"; import { copyFile, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; @@ -90,7 +91,11 @@ export const POSTS_USAGE = [ " [media.<i>.blur=on|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"|off]", " [media.<i>.blur.boxes=x,y,w,h;…|off] [media.<i>.blur.band=below:<f>|above:<f>|between:<a>,<b>[:left:<f>|:right:<f>]|off]", " [media.<i>.blur.style=blur|black|pixelate|off] [media.<i>.censor=<edge>:<f>[:<style>][:<strength>]|off]", - " [parent.<i>.paraphrase=\"…\"|off] [narration.rate=0.8–1.5|narration.<mix knob>=…] [--json]", + " [parent.<i>.paraphrase=\"…\"|off] [narration.rate=0.8–1.5|narration.<mix knob>=…]", + " [panel=auto|side|top|bottom] [media.add=<posts-media/…file>] [media.<i>=off]", + " [parent.<i>=<json ref>|@<file.json>|off] [parent.<i>.media=<file>[,<file>…]|off]", + " [link.add=<json ref>|@<file.json>] [link.<i>=<json ref>|off] [link.<i>.media=<file>|off] [link.<i>.transcript=\"…\"|off]", + " [thread.group=<name>|off] [thread.map=auto|on|off|map|label|both] [--json]", " a post item's knobs (the post bench's writer, updatePostItem): its hold, its images' grid, the blur of other authors,", " an attachment's trim, sound, crop (fractions of its picture) and push-in; fit=read[:linger] (a narrated post: its", " video cut to its best part for the read, `posts fit`). quoted.paraphrase / parent.<i>.paraphrase (nearest first):", @@ -108,13 +113,24 @@ export const POSTS_USAGE = [ " 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).", + " parent.<i>=<ref>: a WHOLE-THREAD read -- an ancestor added (i = the next one) or replaced, nearest first, as JSON", + " {\"id\",\"handle\",\"author\",\"date\",\"text\",\"media\":[\"posts-media/…\"]} (or @<file>.json); off drops it. parent.<i>.media=", + " the attachments a context post carries (shown in the slot while it is on screen; measured as they go in).", + " media.add=<file>: an attachment from a project file (kind and size measured); media.<i>=off removes one.", + " link.add=<ref>: a post its words link to (a LINK VISIT: the pointer clicks the link, the post opens); its", + " transcript (words read off its picture, in his voice) scrolls its picture as it is read (role linked:<i>).", + " thread.group=<name>: a MANUAL THREAD -- consecutive items of one group are one scene (timeline threads --write", + " gathers them in date order). thread.map: the BRANCH MAP drawn when the scene changes branch (post-branch-map.mjs).", + " panel=: where the attachments sit -- beside the card, or at full width above (top) or below it (a wide one: auto).", ...ROLES_LINES, ...REREAD_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", - " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] [--scale s] … | set <n> … | remove <n>", - " a WORD ZOOM: the card pushed in on a word as it is read (umtool posts fx --help)", + " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] … | add caption --match \"…\" --text \"…\" | set <n> … | remove <n>", + " a WORD ZOOM (the card pushed in on a word) or a CAPTION (a chip explaining a phrase) as it is read,", + " or its CLOCK (add clock [--rewind auto|on|off] [--off]) (umtool posts fx --help)", + " umtool posts clock <project> [on|off|default] [--zone <IANA zone>] the cut's CLOCK default: each post's time on its card, run between items", " umtool posts avatar <project> [<handle> <image-file> | <handle> off] [--json]", " an author's PICTURE on every card that draws them (postAvatars): the file copied into posts-media/_avatars/,", " never replaced by the archive's; `off` clears it; no handle lists them. A blurred author never shows one.", @@ -138,7 +154,7 @@ export const POSTS_USAGE = [ " umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment", ].join("\n"); -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", "--without", "--drop-parts"]); +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", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -227,6 +243,7 @@ export function postEntryOf(row, { slug, postId, manifest = null, attach = null, const ON = new Set(["on", "true", "yes", "1"]); const OFF = new Set(["off", "false", "no", "0"]); +const readFileSyncText = (f) => readFileSync(f, "utf8"); /** * `posts set`'s words as the Posts table's patch: `thread=on|off`, @@ -438,7 +455,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con err(FX_USAGE); return 2; } - return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str }); + return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str, off: flags.has("--off") }); + } + if (verb === "clock") { + const { CLOCK_USAGE, clockCommand } = await import("./postFxCli.mjs"); + if (!projectArg || flags.has("--help")) { + err(CLOCK_USAGE); + return 2; + } + return await clockCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str }); } if (verb === "fit") { const { FIT_USAGE, fitCommand } = await import("./postNarrationCli.mjs"); @@ -637,6 +662,33 @@ const onOff = (v, k) => { }; /** A paraphrase's words, or null for `off` / empty (its own words again). */ +/** A project file named by a knob (`posts-media/…`): kept as a marker the command measures (attachmentOf). */ +const fileArg = (raw, k) => { + const f = String(raw).trim(); + if (!f || f.startsWith("/") || f.split(/[\\/]/).includes("..")) throw new CliError(`${k}= takes a file of the project (posts-media/…), not ${raw}`); + return { file: f }; +}; + +/** The ref keys a context post may carry (post-item.mjs refErrors). */ +const REF_KEYS = ["id", "author", "handle", "badge", "date", "text", "url", "media", "paraphrase", "transcript", "via"]; + +/** A context post given on the command line: JSON, or `@<file>.json`. Its `media` may name project files. */ +const refArg = (raw, k) => { + let j; + try { + j = JSON.parse(raw.trim().startsWith("@") ? readFileSyncText(raw.trim().slice(1)) : raw); + } catch (e) { + throw new CliError(`${k}= takes a post as JSON ({"id","handle","author","date","text"}) or @<file>.json -- ${e.message}`); + } + if (!j || typeof j !== "object" || Array.isArray(j)) throw new CliError(`${k}= takes a post as a JSON object`); + const bad = Object.keys(j).filter((x) => !REF_KEYS.includes(x)); + if (bad.length) throw new CliError(`${k}: ${bad.join(", ")} ${bad.length === 1 ? "is" : "are"} not a post's field (${REF_KEYS.join(", ")})`); + if (j.id !== undefined) j.id = String(j.id); + if (typeof j.handle === "string") j.handle = j.handle.replace(/^@/, ""); + if (Array.isArray(j.media)) j.media = j.media.map((m) => (typeof m === "string" ? fileArg(m, `${k}.media`) : m)); + return j; +}; + const paraphraseOf = (raw) => (raw.trim() === "" || raw.trim().toLowerCase() === "off" ? null : raw); /** @@ -673,26 +725,58 @@ export function postItemPatchOf(pairs) { 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)) { + } else if (k === "thread.group") { + // A MANUAL THREAD (post-conversation.mjs): consecutive items of one group play as one scene, in date order. + if (out.thread === null) throw new CliError("thread=auto goes alone"); + const t = (out.thread ??= {}); + t.group = OFF.has(v) || v === "" || v === "auto" ? null : raw.trim(); + } else if (/^thread\.(parent(\.\d)?|quoted|carry|reveal|shrink|dim|seconds|pan|map)$/.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"); + const clear = v === "default" || v === "" || (v === "auto" && knob !== "parent" && knob !== "quoted" && knob !== "carry" && knob !== "map"); 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"]; + const list = Array.isArray(t.parent) ? t.parent : typeof t.parent === "string" ? Array.from({ length: i + 1 }, () => t.parent) : Array.from({ length: i + 1 }, () => "auto"); + while (list.length < i + 1) list.push("auto"); list[i] = clear ? "auto" : v; - t.parent = list.slice(0, Math.max(1, i + 1, list.length)).slice(0, 2); + t.parent = list.slice(0, Math.max(1, i + 1, list.length)).slice(0, 8); } 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 if (knob === "map") { + // The branch map (post-branch-map.mjs): on|off, or its style map|label|both; auto: the cut's. + if (v === "auto" || clear) t.map = null; + else if (["map", "label", "both"].includes(v)) t.map = v; + else t.map = 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`); } } + // Where the attachments sit (post-item.mjs postLayout): auto (beside the card; a wide one above it), side, top, bottom. + else if (k === "panel") { + if (!["auto", "side", "top", "bottom", ""].includes(v)) throw new CliError("panel= takes auto, side, top or bottom"); + out.panel = v === "auto" || v === "" ? null : v; + } + // AN ATTACHMENT FROM A PROJECT FILE (operator, 4 Nov: "this needs to include the cat video"): measured when it goes in. + else if (k === "media.add") (out.mediaAdd ??= []).push(fileArg(raw, k)); + else if (/^media\.\d+$/.test(k)) { + if (!OFF.has(v)) throw new CliError(`${k}= takes off (the attachment removed)`); + ((out.media ??= {})[k.split(".")[1]] = null); + } + // AN ANCESTOR, ADDED OR REPLACED (a whole-thread read): parent.<i>=<json ref>|@<file.json>|off, nearest first. + else if (/^parents?\.\d+$/.test(k)) (((out.parents ??= {})[k.split(".")[1]] ??= {}).ref = OFF.has(v) ? null : refArg(raw, k)); + else if (/^parents?\.\d+\.media$/.test(k)) (((out.parents ??= {})[k.split(".")[1]] ??= {}).media = OFF.has(v) || v === "" ? null : raw.split(",").map((f) => fileArg(f, k))); + // A POST ITS WORDS LINK TO (a link visit): link.add=<json ref>, link.<i>=<json>|off, link.<i>.media=<file>|off, + // link.<i>.transcript=<words read off its picture>|off. + else if (k === "link.add") (out.linksAdd ??= []).push(refArg(raw, k)); + else if (/^links?\.\d+$/.test(k)) (((out.links ??= {})[k.split(".")[1]] ??= {}).ref = OFF.has(v) ? null : refArg(raw, k)); + else if (/^links?\.\d+\.media$/.test(k)) (((out.links ??= {})[k.split(".")[1]] ??= {}).media = OFF.has(v) || v === "" ? null : raw.split(",").map((f) => fileArg(f, k))); + else if (/^links?\.\d+\.transcript$/.test(k)) (((out.links ??= {})[k.split(".")[1]] ??= {}).transcript = OFF.has(v) || raw.trim() === "" ? null : raw); else if (k === "quoted.paraphrase") out.quoted = { paraphrase: paraphraseOf(raw) }; - else if (/^parents?\.\d+\.paraphrase$/.test(k)) (out.parents ??= {})[k.split(".")[1]] = { paraphrase: paraphraseOf(raw) }; + else if (/^parents?\.\d+\.paraphrase$/.test(k)) ((out.parents ??= {})[k.split(".")[1]] ??= {}).paraphrase = paraphraseOf(raw); else if (/^media\.\d+\.blur(\.(strength|label|boxes|band|style))?$/.test(k)) { // The censoring blur (post-censor.mjs): on|off, its strength, its label (off: none), its boxes (x,y,w,h;…|off), // its band (below:0.38, between:0.2,0.6, left:0.5 … |off), its style (blur|black|pixelate|off: blur). @@ -723,7 +807,7 @@ export function postItemPatchOf(pairs) { } } 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=, scene=, 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|.band|.style]=, media.<i>.censor=, quoted.paraphrase=, parent.<i>.paraphrase=)`); + if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, panel=, redact=, scene=, follow=, follow.dim|ease=, thread=, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan|group|map=, media.add=, media.<i>=off, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes|.band|.style]=, media.<i>.censor=, quoted.paraphrase=, parent.<i>=<ref>|off, parent.<i>.media=, parent.<i>.paraphrase=, link.add=, link.<i>=<ref>|off, link.<i>.media=, link.<i>.transcript=)`); 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); @@ -802,6 +886,40 @@ async function contextCommand(projectArg, { root, json, dryRun, out }) { return 0; } +/** + * An attachment from a PROJECT FILE (`posts-media/…`), measured as `posts reel` measures one: `{ src, kind, + * width?, height?, seconds?, audio? }` -- refused when it is not there or a timed one cannot be measured. + */ +export async function attachmentOf(dir, rel) { + const file = path.join(dir, rel); + if (!(await stat(file).catch(() => null))) throw new CliError(`${rel} is not in the project (${file})`); + const { probeMediaFile, mediaKindOf } = await import("./postReel.mjs"); + const probe = await probeMediaFile(file); + const kind = mediaKindOf(path.basename(rel), "", probe); + if (kind !== "image" && !Number.isFinite(probe.seconds)) throw new CliError(`${rel}: its length could not be measured (ffprobe)`); + return { + src: rel.split(path.sep).join("/"), + kind, + ...(probe.width ? { width: probe.width } : {}), + ...(probe.height ? { height: probe.height } : {}), + ...(kind !== "image" ? { seconds: probe.seconds } : {}), + ...(kind === "video" ? { audio: probe.audio === true } : {}), + }; +} + +/** Every `{ file }` marker of a set-item patch measured into an attachment (attachmentOf), in place. */ +async function resolveAttachments(patch, dir) { + const fix = async (list) => (Array.isArray(list) ? Promise.all(list.map((m) => (m && typeof m === "object" && typeof m.file === "string" && Object.keys(m).length === 1 ? attachmentOf(dir, m.file) : m))) : list); + if (patch.mediaAdd) patch.mediaAdd = await fix(patch.mediaAdd); + for (const group of [patch.parents, patch.links]) { + for (const v of Object.values(group ?? {})) { + if (Array.isArray(v.media)) v.media = await fix(v.media); + if (v.ref && Array.isArray(v.ref.media)) v.ref.media = await fix(v.ref.media); + } + } + for (const r of patch.linksAdd ?? []) if (Array.isArray(r.media)) r.media = await fix(r.media); +} + /** `posts set-item`: a post item's knobs, through updatePostItem (`fit=read[:linger]`: posts fit, on this item). */ async function setItemCommand(projectArg, ref, pairs, { root, json, out, reread = true }) { const fitPair = pairs.find((p) => /^fit=/.test(p)); @@ -839,6 +957,7 @@ async function setItemCommand(projectArg, ref, pairs, { root, json, out, reread } const patch = postItemPatchOf(pairs); const project = await projectOf(projectArg, root); + await resolveAttachments(patch, project.dir); const manifest = await readManifest(project.dir); const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; const hit = tl.find((e) => e?.type === "post" && (e.id === ref || String(e.post ?? "").split("/")[1] === ref)); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -105,6 +105,9 @@ export const TIMELINE_USAGE = [ " are dates gets --date as one too. The section is <id>'s unless --section says", " umtool timeline <project> insert (--after <id|-> | --to-section N | --group G) post:<channel>/<postId> [--id ID]", " a POST ITEM from the posts archive (its card and attachments; umtool posts reel makes many)", + " umtool timeline <project> insert (--after <id|-> | --to-section N | --group G) post-json:<json>|post-json:@<file> [--id ID]", + " a POST ITEM BY HAND (one no archive holds): {post: \"<channel>/<postId>\", author, handle, date, text,", + " media: [\"posts-media/…\"], parents?, quoted?, subjects?} -- its media measured; its avatar: umtool posts avatar", " umtool timeline <project> insert (--to-section N | --group G) <channel>/<video>@<start>-<end> [same flags]", " at the END of section N, or after group G's last clip and one of its clips (the run stays", " together): one write, the marker after that clip re-anchored after the new one; the", @@ -203,6 +206,29 @@ export function splitTimelineArgs(args) { } /** A JSON argument, or `@file` for one read from disk. */ +/** + * A POST ITEM made by hand (`insert post-json:…`): the fields as given -- `post` "<channel>/<postId>", `author`, + * `handle`, `date`, `text`, optional `url`, `parents`, `quoted`, `subjects`, `engagement` -- its `media` named as + * project files and measured (postsCli.mjs attachmentOf); its `id` p-<postId> unless --id; refused as the build would. + */ +async function handPostItem(project, manifest, raw, { id = null } = {}) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new CliError("post-json takes a post item as a JSON object"); + const { attachmentOf } = await import("./postsCli.mjs"); + const { validatePostItem } = await import("umtool-report-to-video/post-item"); + const postId = String(raw.post ?? "").split("/")[1] ?? ""; + const media = []; + for (const m of Array.isArray(raw.media) ? raw.media : []) media.push(typeof m === "string" ? await attachmentOf(project.dir, m) : m); + const { media: _m, id: _i, type: _t, ...rest } = raw; + void _m; + void _i; + void _t; + const entry = { type: "post", id: id ?? (typeof raw.id === "string" ? raw.id : `p-${postId}`), platform: "x", ...rest, ...(typeof rest.handle === "string" ? { handle: rest.handle.replace(/^@/, "") } : {}), ...(media.length ? { media } : {}) }; + if ((manifest.timeline ?? []).some((e) => e?.id === entry.id)) throw new CliError(`${entry.id} is already in the cut (--id another)`); + const errors = validatePostItem(entry); + if (errors.length) throw new CliError(`post-json: ${errors.join("; ")}`); + return entry; +} + async function jsonArg(raw, what) { if (raw === undefined || raw === "") throw new CliError(`${what} needs a JSON value (or @file)`); const text = raw.startsWith("@") ? await readFile(path.resolve(raw.slice(1)), "utf8") : raw; @@ -545,7 +571,19 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => if (flags.has("--after") && (toSection !== null || group !== null)) throw new CliError("insert takes --after, or --to-section / --group, not both"); const afterArg = flags.has("--after") ? String(flags.get("--after")) : ""; const after = afterArg === "-" || afterArg === "" ? null : afterArg; - const spec = need(rest[0], "a clip: <channel>/<video>@<start>-<end> (or a post item: post:<channel>/<postId>)"); + const spec = need(rest[0], "a clip: <channel>/<video>@<start>-<end> (or a post item: post:<channel>/<postId>, or post-json:<json>|@<file>)"); + // A POST ITEM BY HAND (a post no archive holds: one kept only as a screenshot): post-json:<json> or + // post-json:@<file> -- { post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], … }. + if (/^post-json:/.test(spec)) { + const raw = await jsonArg(spec.slice("post-json:".length), "post-json"); + const entry = await handPostItem(project, manifest, raw, { id: flags.has("--id") ? String(flags.get("--id")) : null }); + if (toSection !== null || group !== null) { + ({ result, editNotes } = await write((token) => insertInto(project.dir, entry, toSection !== null ? { section: toSection } : { group }, { token }))); + } else { + ({ result, editNotes } = await write((token) => insertEntry(project.dir, after, entry, { token, at }))); + } + break; + } // A POST ITEM (post-item.mjs): `post:<channel>/<postId>` from the posts archive, as `posts reel` makes it. if (/^post:/.test(spec)) { const m = /^post:([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9_-]+)$/.exec(spec); @@ -875,7 +913,7 @@ export async function threadsCommand(project, manifest, { write = false, only = const { conversations, gatheredOrder } = await import("umtool-report-to-video/post-conversation"); const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; const convs = conversations(tl, manifest.render); - if (only && !convs.some((c) => c.root === only || c.items.some((it) => it.id === only || it.post === only || it.chain.includes(only)))) { + if (only && !convs.some((c) => c.root === only || c.group === only || c.items.some((it) => it.id === only || it.post === only || it.chain.includes(only)))) { throw new CliError(`no conversation of two post items or more holds ${only} in ${project.id}`); } if (!write) { @@ -885,10 +923,10 @@ export async function threadsCommand(project, manifest, { write = false, only = } out(`${project.id}: ${convs.length} conversation(s) of two post items or more`); for (const c of convs) { - out(` root ${c.root ?? "?"} ${c.items.length} items ${c.split ? `SPLIT into ${c.runs} runs` : "one run"}`); + out(` ${c.group ? `group ${c.group} (a manual thread, in date order) ` : ""}root ${c.root ?? "?"} ${c.items.length} items ${c.split ? `SPLIT into ${c.runs} runs` : "one run"}`); out(` in the cut: ${c.items.map((it) => `${it.id}@${it.at}`).join(" ")}`); const inOrder = c.items.map((it) => it.id).join(" ") === c.order.join(" "); - if (!inOrder) out(` tree order: ${c.order.join(" ")} (umtool timeline ${project.id} threads --write --conversation ${c.root ?? c.items[0].id})`); + if (!inOrder) out(` tree order: ${c.order.join(" ")} (umtool timeline ${project.id} threads --write --conversation ${c.group ?? c.root ?? c.items[0].id})`); for (const m of c.misplaced) out(` MISPLACED: ${m.id} (at ${m.at}) answers ${m.answers}, placed after it (at ${m.answersAt})`); for (const r of c.rereads) out(` RE-READ: ${r.id} reads ${r.scope} (${r.post}), which ${r.by} already read -- ${r.fix.replace("<p>", project.id)}`); } diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -216,7 +216,16 @@ import { // The snap itself (a montage's window snaps with it too), re-exported for the tests. import { snap } from "./snap.mjs"; import { buildPostSegment } from "./post-render.mjs"; -import { planContextOf } from "./post-conversation.mjs"; +import { planContext, planContextOf } from "./post-conversation.mjs"; + +/** The item before post item `id` with its own context (post-join.mjs: what the item opens on), or null. */ +function postJoinFrom(timeline, id, render, groups) { + const tl = Array.isArray(timeline) ? timeline : []; + const i = tl.findIndex((e) => e?.id === id); + const prev = i > 0 ? tl[i - 1] : null; + if (prev?.type !== "post") return null; + return { entry: prev, ...planContext(tl, i - 1, render), mediaScene: mediaSceneById(tl, prev.id, groups, render) }; +} import { readPostRedaction } from "./post-redact-files.mjs"; import { dropMarks, redactEntry } from "./post-redact.mjs"; import { avatarUrls } from "./post-avatars.mjs"; @@ -2475,7 +2484,10 @@ async function buildMontageWall({ M, entries, render, outDir, timeline, provenan * started `--from` another keeps the intro's file, and the crossfade batch * over it, instead of copying the intro in again). */ -export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".intro.json", ".quote.txt", ".attrib.txt", ".channel.txt"]); +// A post item's record (`.post.json`, its key: post-render.mjs) and its combo pass's (`.combo.json`, the badge-less +// `.plain.mp4`) ride with its segment, so a take --from another reuses a post item whose key still matches (the plain one too: +// without it a reused badged segment would be taken for a plain one and badged again). +export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".intro.json", ".quote.txt", ".attrib.txt", ".channel.txt", ".post.json", ".combo.json", ".plain.mp4"]); /** * Before an entry's segment is rebuilt: each of its files in `segDir` that is @@ -6577,7 +6589,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly render, encode: encodeArgs(render), outDir, manifestDir, workers: CHROME_WORKERS, emit: (ev, f) => EMIT(ev, f), }); } - if (entry.type !== "teaser" && entry.type !== "clip") { + // A post item (post-render.mjs) keeps a segment `--from` linked in when its key matches (its record, `.post.json`, + // linked beside it) and writes every file of its own through a rename -- never through the link -- when it does not. + if (entry.type !== "teaser" && entry.type !== "clip" && entry.type !== "post") { await detachSegmentFiles(path.join(outDir, "segments"), entry.id); } if (entry.type === "card") { @@ -6614,6 +6628,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // Its media scene (post-media-scene.mjs): neighbours with the same attachment, over the WHOLE cut's groups -- // its attachment always, its card only when the conversation has no scene (read-follow.mjs: that one wins). mediaScene: mediaSceneById(manifest.timeline, entry.id, postGroups, render), + // THE JOIN (post-join.mjs): the item before and its context, so this one opens on it as it ended. + joinFrom: postJoinFrom(manifest.timeline, entry.id, render, postGroups), }); 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/package.json b/umtool/report-to-video/package.json @@ -73,8 +73,13 @@ "./post-slurs": "./post-slurs.mjs", "./post-thread": "./post-thread.mjs", "./post-conversation": "./post-conversation.mjs", + "./post-join": "./post-join.mjs", + "./post-link-visit": "./post-link-visit.mjs", + "./post-branch-map": "./post-branch-map.mjs", "./post-render": "./post-render.mjs", "./word-zoom": "./word-zoom.mjs", + "./post-caption": "./post-caption.mjs", + "./post-clock": "./post-clock.mjs", "./read-follow": "./read-follow.mjs", "./presets": "./presets.mjs", "./prune-frames": "./prune-frames.mjs", diff --git a/umtool/report-to-video/post-branch-map.mjs b/umtool/report-to-video/post-branch-map.mjs @@ -0,0 +1,220 @@ +// THE BRANCH MAP (umtool/docs/report-video.md, "The branch map"; operator, 4 Nov: "we need a specific visual for +// changing thread branches that makes the context obvious"): when a scene moves from one branch of a conversation +// to another -- a sibling reply, a new reply to an earlier post, a jump back up the tree -- a small map in the card's +// corner shows where we are going: a node for each post on screen, a line for each reply, the post the item before +// ended on lit, the light travelling up to the post the two branches share and down the new branch to the post being +// read; a label under it says it ("another reply to @X's post"; "back to @X's post"). A manual thread +// (`thread.group`) draws its posts' real relations (a post that answers none stands alone). +// +// render.posts.threadMap = { on?: true, style?: "both" } the cut's: "map" | "label" | "both" +// timeline[i].thread.map = false | true | "map" | "label" | "both" +// +// When: the item's scene changes branch (a post the run had on screen collapses away, post-conversation.mjs) or, in a +// manual thread, the post he answers is not the one just above. It shows from the join's end, travels with the +// branch's change (its collapse), holds, and fades (MAP_TIMES). +// +// PURE but the page function (applyMapState, self-contained): threadLayout carries `map` (its nodes, its edges, the +// path), threadSchedule its times, the state at a second its progress; the card page draws it (mapHtml). + +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; + +export const MAP_DEFAULTS = Object.freeze({ on: true, style: "both" }); +export const MAP_STYLES = Object.freeze(["map", "label", "both"]); +/** The map's fade in (s), the light's travel (s), the hold after it (s), the fade out (s). */ +export const MAP_TIMES = Object.freeze({ in: 0.3, travel: 1.1, hold: 2.2, out: 0.5 }); + +/** The cut's and an item's map knobs: `{ on, style }`. */ +export function mapKnobs(entry, render = undefined) { + const r = isObj(render?.posts?.threadMap) ? render.posts.threadMap : {}; + const k = { ...MAP_DEFAULTS, ...(typeof r.on === "boolean" ? { on: r.on } : {}), ...(MAP_STYLES.includes(r.style) ? { style: r.style } : {}) }; + const v = entry?.thread?.map; + if (v === false) return { ...k, on: false }; + if (v === true) return { ...k, on: true }; + if (MAP_STYLES.includes(v)) return { on: true, style: v }; + return k; +} + +/** Every reason `render.posts.threadMap` cannot be built. */ +export function validatePostMapRender(render) { + const v = render?.posts?.threadMap; + if (v === undefined) return []; + if (!isObj(v)) return ["render.posts.threadMap must be { on?, style? } (the branch map)"]; + const errors = Object.keys(v).filter((k) => !(k in MAP_DEFAULTS)).map((k) => `render.posts.threadMap.${k} is not a branch-map knob (on, style)`); + if (v.on !== undefined && typeof v.on !== "boolean") errors.push("render.posts.threadMap.on must be true or false"); + if (v.style !== undefined && !MAP_STYLES.includes(v.style)) errors.push(`render.posts.threadMap.style must be one of ${MAP_STYLES.join(", ")}`); + return errors; +} + +/** + * THE MAP of a card, pure: `{ style, nodes: [{ id, scope, handle, him, x, y }], edges: [[from, to]], path: [ids], + * label, from, to }` -- or null when the scene does not change branch. `tiles`: threadLayout's (each with its `id`, + * its parent's `parent`, its author's `handle`); `subject`: his handle; `prevId`: the post the item before ended on; + * `nowId`: the post being read first (the new branch's). Laid out as a tree: depth across, the tiles' order down. + */ +export function branchMapOf(tiles, { prevId, nowId, subject = "", style = "both", group = false } = {}) { + const list = (tiles ?? []).filter((t) => str(t.id)); + if (!prevId || !nowId || prevId === nowId || !list.some((t) => t.id === prevId) || !list.some((t) => t.id === nowId)) return null; + const byId = new Map(list.map((t) => [t.id, t])); + const parentOf = (id) => { + const p = str(byId.get(id)?.parent); + return p && byId.has(p) && p !== id ? p : null; + }; + const up = (id) => { + const out = [id]; + for (let p = parentOf(id), n = 0; p && n < 20; p = parentOf(p), n += 1) out.push(p); + return out; + }; + const a = up(prevId); + const b = up(nowId); + const shared = a.find((id) => b.includes(id)) ?? null; + // The new post answers the one before it directly (no branch change): no map. + if (shared === prevId) return null; + // No post shared: through the post the new one answers when it is on screen (a manual thread's reply up the stack). + const via = !shared && parentOf(nowId) && parentOf(nowId) !== prevId ? parentOf(nowId) : null; + const path = shared ? [...a.slice(0, a.indexOf(shared) + 1), ...b.slice(0, b.indexOf(shared)).reverse()] : via ? [prevId, via, nowId] : [prevId, nowId]; + const depth = new Map(); + const depthOf = (id) => { + if (depth.has(id)) return depth.get(id); + depth.set(id, 0); + const p = parentOf(id); + const d = p ? depthOf(p) + 1 : 0; + depth.set(id, d); + return d; + }; + const nodes = list.map((t, row) => ({ id: t.id, scope: t.scope, handle: str(t.handle), him: !!subject && str(t.handle).toLowerCase() === subject.toLowerCase(), x: depthOf(t.id), y: row })); + const edges = list.map((t) => [parentOf(t.id), t.id]).filter((e) => e[0]); + const sh = shared ? byId.get(shared) : via ? byId.get(via) : null; + const isHim = (t) => !!subject && str(t?.handle).toLowerCase() === subject.toLowerCase(); + const who = sh ? (isHim(sh) ? "his" : sh.handle ? `@${sh.handle}'s` : "the") : null; + // Back up the stack to a post on screen (the post he answers, read again): "back to"; else a sibling's. + const nowT = byId.get(nowId); + const back = !sh && nowT && nowT.scope !== "post" ? (isHim(nowT) ? "his" : nowT.handle ? `@${nowT.handle}'s` : "the") : null; + const label = back ? `back to ${back} post` : !sh ? "a new thread" : shared === nowId ? `back to ${who} post` : `another reply to ${who} post`; + return { style, nodes, edges, path, label, from: prevId, to: nowId, shared }; +} + +/** The map's times on the item's clock: in at `t0`, the light travelling from `travel`, out by `t3`. */ +export function mapTimes(at) { + const t0 = r3(Math.max(0, at)); + const travel = r3(t0 + MAP_TIMES.in); + const t2 = r3(travel + MAP_TIMES.travel + MAP_TIMES.hold); + return { t0, travel, t2, t3: r3(t2 + MAP_TIMES.out) }; +} + +/** The map's state at item second `s`: `{ op, p }` (p: the light's place along its path, 0..1), or null. */ +export function mapStateAt(map, s) { + if (!map?.times) return null; + const { t0, travel, t2, t3 } = map.times; + if (s < t0 || s > t3) return null; + const op = s < travel ? (s - t0) / Math.max(1e-6, travel - t0) : s > t2 ? 1 - (s - t2) / Math.max(1e-6, t3 - t2) : 1; + const x = Math.min(1, Math.max(0, (s - travel) / MAP_TIMES.travel)); + const p = x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2; + return { op: r3(Math.max(0, Math.min(1, op))), p: r3(p) }; +} + +const esc = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); + +/** + * The map's markup (the card page's): an SVG of the nodes and lines in the card's top-right corner, the light (a + * ring that travels), the label under it -- hidden until applyMapState shows it. `k`: the page's scale (height ÷ + * 1080); `blurred`: handles the card blurs (a label never names one); `accent`: his colour. + */ +export function mapHtml(map, { k = 1, accent = "#c8752a", fg = "#f6f1e6", muted = "#a2957f", blurred = [] } = {}) { + if (!map) return ""; + const cell = Math.round(26 * k); + const r = Math.round(6 * k); + const cols = Math.max(...map.nodes.map((n) => n.x)) + 1; + const rows = map.nodes.length; + const w = cols * cell + 2 * r + 4; + const h = rows * cell + 2 * r; + const at = (n) => [r + 2 + n.x * cell + r, r + n.y * cell + r]; + const pos = new Map(map.nodes.map((n) => [n.id, at(n)])); + const lines = map.edges.map(([a, b]) => { + const [x1, y1] = pos.get(a); + const [x2, y2] = pos.get(b); + return `<path d="M${x1} ${y1} V${y2} H${x2}" fill="none" stroke="${muted}" stroke-width="${Math.max(1.5, 2 * k)}" stroke-opacity="0.7"/>`; + }); + const onPath = new Set(map.path); + const dots = map.nodes.map((n) => { + const [x, y] = pos.get(n.id); + return `<circle data-map-node="${esc(n.id)}" cx="${x}" cy="${y}" r="${r}" fill="${n.him ? accent : fg}" fill-opacity="${onPath.has(n.id) ? 0.95 : 0.45}"/>`; + }); + const pts = map.path.map((id) => pos.get(id)); + const blur = new Set(blurred.map((h) => String(h).replace(/^@/, "").toLowerCase())); + const label = /@([A-Za-z0-9_]+)'s/.exec(map.label)?.[1]; + const text = label && blur.has(label.toLowerCase()) ? map.label.replace(`@${label}'s`, "a stranger's") : map.label; + const showMap = map.style !== "label"; + const showLabel = map.style !== "map"; + return `<div data-thread-map="${esc(map.style)}" data-map-path='${esc(JSON.stringify(pts))}' style="position:absolute;z-index:6;display:none;left:0;top:0;padding:${Math.round(10 * k)}px;border-radius:${Math.round(12 * k)}px;background:rgba(0,0,0,0.55);pointer-events:none;text-align:right">${showMap ? `<svg width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" style="display:block;margin-left:auto">${lines.join("")}${dots.join("")}<circle data-map-light="" cx="${pts[0][0]}" cy="${pts[0][1]}" r="${r + Math.round(4 * k)}" fill="none" stroke="#ffcf33" stroke-width="${Math.max(2, 3 * k)}"/></svg>` : ""}${showLabel ? `<div data-map-label="" style="margin-top:${showMap ? Math.round(6 * k) : 0}px;color:${fg};font-size:${Math.round(19 * k)}px;white-space:nowrap">${esc(text)}</div>` : ""}</div>`; +} + +/** IN THE PAGE (self-contained): the map shown at strength `st.op`, its light `st.p` along its path (null: hidden). */ +export function applyMapState(st, doc = document) { + const el = doc.querySelector("[data-thread-map]"); + if (!el) return; + if (!st) { + el.style.display = "none"; + return; + } + el.style.display = "block"; + el.style.opacity = String(st.op); + const light = el.querySelector("[data-map-light]"); + const pts = JSON.parse(el.getAttribute("data-map-path") || "[]"); + if (!light || pts.length < 1) return; + // Along the path's legs (each an elbow: down, then across), by length. + const legs = []; + for (let i = 1; i < pts.length; i += 1) { + const [a, b] = [pts[i - 1], pts[i]]; + const mid = [a[0], b[1]]; + legs.push([a, mid], [mid, b]); + } + const len = legs.map(([a, b]) => Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1])); + const total = len.reduce((x, y) => x + y, 0) || 1; + let d = st.p * total; + let at = pts[0]; + for (let i = 0; i < legs.length; i += 1) { + if (d <= len[i] || i === legs.length - 1) { + const f = len[i] ? Math.min(1, d / len[i]) : 1; + at = [legs[i][0][0] + (legs[i][1][0] - legs[i][0][0]) * f, legs[i][0][1] + (legs[i][1][1] - legs[i][0][1]) * f]; + break; + } + d -= len[i]; + } + light.setAttribute("cx", String(at[0])); + light.setAttribute("cy", String(at[1])); +} + +/** The map's box (px), as mapHtml draws it: its tree, its label under it, its padding. */ +export function mapSize(map, k = 1) { + if (!map) return { width: 0, height: 0 }; + const cell = Math.round(26 * k); + const r = Math.round(6 * k); + const cols = Math.max(...map.nodes.map((n) => n.x)) + 1; + const svgW = map.style === "label" ? 0 : cols * cell + 2 * r + 4; + const svgH = map.style === "label" ? 0 : map.nodes.length * cell + 2 * r; + const labelW = map.style === "map" ? 0 : Math.round(String(map.label).length * 19 * k * 0.52); + const labelH = map.style === "map" ? 0 : Math.round(19 * k * 1.3) + (map.style === "both" ? Math.round(6 * k) : 0); + const pad = Math.round(10 * k); + return { width: Math.max(svgW, labelW) + 2 * pad, height: svgH + labelH + 2 * pad }; +} + +/** + * WHERE THE MAP SITS in the item's box -- never over words being read: over the attachments' slot (its top-left + * corner) when there is one, else beside a card alone (right of it, when the box has room), else the card's top-right + * corner. `L`: post-item.mjs postLayout's; `size`: mapSize's. + */ +export function mapPlace(L, box, size, k = 1) { + const m = Math.round(16 * k); + if (L?.slot && L.mode === "side") return { x: L.slot.x + m, y: L.slot.y + m }; + if (L?.card && L.card.x + L.card.width + m + size.width <= box.width - m) return { x: L.card.x + L.card.width + 2 * m, y: L.card.y + m }; + return { x: Math.max(0, (L?.card?.x ?? 0) + (L?.card?.width ?? box.width) - size.width - m), y: (L?.card?.y ?? 0) + m }; +} + +/** The map alone on a transparent page (the build shoots its states and lays them over the attachments). */ +export function mapPageHtml(map, { width, height, k = 1, accent, fg, muted, blurred = [], fonts = {} }) { + const css = (s) => String(s ?? "").replace(/[\\'"\n<>]/g, ""); + return `<!doctype html><html><head><meta charset="utf-8"><style>@font-face { font-family: 'PostSans'; src: url('${css(fonts.regular)}'); } html, body { margin: 0; width: ${width}px; height: ${height}px; background: transparent; font-family: 'PostSans', sans-serif; }</style></head><body>${mapHtml(map, { k, accent, fg, muted, blurred })}</body></html>`; +} diff --git a/umtool/report-to-video/post-caption.mjs b/umtool/report-to-video/post-caption.mjs @@ -0,0 +1,674 @@ +// A POST ITEM's CAPTION (umtool/docs/report-video.md, "A caption"; operator, 4 Nov: +// a small explanatory chip tied to a phrase -- "不動心 · fudōshin — "immovable +// mind"" on "Fudōshin" -- appearing as the phrase is read and held a beat). +// +// entry.fx = [{ kind: "caption", +// target?: "post" | "parent:<i>" | "quoted", // whose words (default: the post's own) +// match: "<the word or phrase, as the card shows it>", +// occurrence?: n, // its n-th time in that text (default 1) +// text: "<what the chip says>", // ≤ CAPTION_TEXT_MAX characters, any script (CJK too) +// at?: <item seconds>, // when; absent: the take's word timings, else the estimate +// lead?: s, hold?: s, // in this long before the word; held this long from it +// place?: "below" | "above" | "side" }] // where it sits by the phrase (default below) +// +// WHEN -- word-zoom's rule: `at` when it is set, else the matched word's start in +// the picked take's word timings (the read's lead + start ÷ rate), else the +// READING ESTIMATE: a narrated post's read spread over its script by characters, +// an un-narrated one's 1 s + 3 words a second (word-zoom.mjs readingEstimate). +// A caption never fights a word zoom: one that would be up while a zoom is (its +// lead-in to back out) WAITS for the zoom to be out, then comes in. +// +// WHERE: a chip by the phrase (`place`; below by default), with a notch pointing +// at it and an underline under it, inside the card. It never covers a word read +// while it is up: a place that would is passed over for the next (below, above, +// side), and the chip tracks the phrase while the card pans (read-follow.mjs). +// It is drawn OVER the card, never in it: the read-follow geometry +// (measureFollow, readInViewErrors) is measured without it, and it carries no +// `data-w` / `data-post-block` -- it never counts as text, read or covering. +// +// THE LOOK: the card's palette (a panel of its background toward its accent, the +// accent's border and notch), its faces, then the CJK faces this machine has +// (CAPTION_FONT_STACK) so 不動心 is drawn, not boxes. Text before " — " is bold. +// +// Pure but for the DOM functions (mountCaptions, measureCaptionWords, +// setCaptionState), which are SELF-CONTAINED: the build passes them to a page +// (page.evaluate), Play calls them on its card frame's document. + +import { alignWords, cardWordsOf, findMatch, readingEstimate, scriptWordsOf, targetScope, targetTextOf } from "./word-zoom.mjs"; +import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; +import { esc, mixHex, rgbaOf } from "./post-item.mjs"; + +export const CAPTION_PLACES = Object.freeze(["below", "above", "side"]); +export const CAPTION_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.15, hold: 2.5, place: "below" }); +export const CAPTION_LIMITS = Object.freeze({ at: [0, 600], lead: [0, 3], hold: [0.5, 10], occurrence: [1, 99] }); +export const CAPTION_TEXT_MAX = 160; +/** Its fade (and slide) in, and its fade out, seconds. */ +export const CAPTION_IN = 0.3; +export const CAPTION_OUT = 0.35; +/** How far it slides in from, px at 1080. */ +export const CAPTION_SLIDE = 16; +/** The faces a chip is drawn in: the card's, then the CJK faces (Noto Sans CJK on this machine), then any sans. */ +export const CAPTION_FONT_STACK = "'Noto Sans CJK JP', 'Noto Sans CJK SC', 'Source Han Sans JP', 'Source Han Sans CN', 'WenQuanYi Zen Hei', sans-serif"; + +const KEYS = new Set(["kind", "target", "match", "occurrence", "text", "at", "lead", "hold", "place"]); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const numIn = (v, [lo, hi]) => fin(v) && v >= lo && v <= hi; +const r3 = (v) => Math.round(v * 1000) / 1000; +const MATCH_MAX = 120; + +/** + * One caption with every default filled in. + * @param {Record<string, any> | null | undefined} fx + * @returns {{ kind?: string, target: string, match: string, occurrence: number, text: string, at?: number, lead: number, hold: number, place: string }} + */ +export const resolveCaption = (fx) => ({ ...CAPTION_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) }); + +const TARGET_NAME = (t) => (t === "post" ? "the post's words" : t === "quoted" ? "the quoted post's words" : `the words of the post it answers (${t})`); + +/** Every reason caption `fx` (entry `e`'s fx[i], named `fw`) cannot be built, as sentences. word-zoom.mjs validatePostFx calls it. */ +export function captionErrors(e, fx, fw) { + const errors = []; + for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a caption key (${[...KEYS].join(", ")})`); + const target = fx.target ?? "post"; + const text = typeof target === "string" ? targetTextOf(e, target) : null; + if (fx.target !== undefined && !(typeof fx.target === "string" && /^(post|quoted|parent:\d+)$/.test(fx.target))) errors.push(`${fw}.target must be "post", "quoted" or "parent:<i>"`); + else if (text === null) errors.push(`${fw}.target ${target}: the card draws no such post (${target === "quoted" ? "it quotes none" : "it answers no post there"})`); + if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase the caption explains, as the card shows it`); + else if (fx.match.length > MATCH_MAX) errors.push(`${fw}.match is longer than ${MATCH_MAX} characters`); + if (typeof fx.text !== "string" || !fx.text.trim()) errors.push(`${fw}.text must be what the caption says`); + else if (fx.text.length > CAPTION_TEXT_MAX) errors.push(`${fw}.text is longer than ${CAPTION_TEXT_MAX} characters (a caption is a chip, not a paragraph)`); + if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, CAPTION_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`); + if (typeof fx.match === "string" && fx.match.trim() && text !== null) { + const m = findMatch(text, fx.match, fx.occurrence ?? 1); + if (m.error === "not in") errors.push(`${fw}.match "${fx.match}" is not in ${TARGET_NAME(target)}`); + else if (m.error === "occurrence") errors.push(`${fw}.match "${fx.match}" is in ${TARGET_NAME(target)} ${m.count} time${m.count === 1 ? "" : "s"}: occurrence ${fx.occurrence} is not there`); + else if (m.error) errors.push(`${fw}.match: ${m.error}`); + } + for (const k of ["at", "lead", "hold"]) if (fx[k] !== undefined && !numIn(fx[k], CAPTION_LIMITS[k])) errors.push(`${fw}.${k} must be ${CAPTION_LIMITS[k][0]}–${CAPTION_LIMITS[k][1]} seconds`); + if (fx.place !== undefined && !CAPTION_PLACES.includes(fx.place)) errors.push(`${fw}.place must be one of ${CAPTION_PLACES.join(", ")}`); + return errors; +} + +// --------------------------------------------------------------------------- +// WHEN. +// --------------------------------------------------------------------------- + +/** Fill each null in `times` between its known neighbours (an end with none: the nearest known). */ +function fillTimes(times) { + const out = times.slice(); + const known = out.map((v, i) => (v === null ? -1 : i)).filter((i) => i >= 0); + if (!known.length) return out; + for (let i = 0; i < out.length; i += 1) { + if (out[i] !== null) continue; + const a = [...known].reverse().find((k) => k < i); + const b = known.find((k) => k > i); + if (a === undefined) out[i] = out[b]; + else if (b === undefined) out[i] = out[a]; + else out[i] = r3(out[a] + ((out[b] - out[a]) * (i - a)) / (b - a)); + } + return out; +} + +/** + * When each card word of `target` is read, item seconds: `{ times, source }` + * -- "words" from the picked take's word timings, "estimate" otherwise (a + * narrated post: its script's characters spread over the read; an un-narrated + * one: readingEstimate). Null when the target draws no words. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {string} [target] + * @param {Record<string, any> | null} [schedule] + * @returns {{ times: Array<number | null>, source: "words" | "estimate" } | null} + */ +export function cardWordTimes(entry, render = undefined, target = "post", schedule = undefined) { + const text = targetTextOf(entry, target); + if (text === null) return null; + const words = cardWordsOf(text); + if (!isNarrated(entry)) return { times: words.map((_, i) => readingEstimate(i)), source: "estimate" }; + const sch = schedule ?? narrationSchedule(entry, render); + const rate = sch.rate || 1; + const take = pickedTake(entry); + const timed = Array.isArray(take?.words) && take.words.length ? take.words : null; + if (timed) { + const map = alignWords(words, timed.map((x) => x.w)); + return { times: fillTimes(map.map((k) => (k >= 0 && fin(timed[k].start) ? r3(sch.at + timed[k].start / rate) : null))), source: "words" }; + } + const script = typeof take?.script === "string" && take.script.trim() ? take.script : String(entry?.narration?.script ?? ""); + const sw = scriptWordsOf(script); + const map = alignWords(words, sw); + const before = []; + let n = 0; + for (const w of sw) { + before.push(n); + n += w.length + 1; + } + const secs = fin(sch.seconds) && sch.seconds > 0 ? sch.seconds : (n / 15); + return { times: fillTimes(map.map((k) => (k >= 0 && n > 0 ? r3(sch.at + (before[k] / n) * secs) : null))), source: "estimate" }; +} + +/** + * Each caption's moment, one per fx (a word zoom's row is `{ i, kind }`): + * `{ i, t, source: "at"|"words"|"estimate" }` or `{ i, error }`. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {Record<string, any> | null} [schedule] + * @returns {Array<{ i: number, t?: number, source?: string, error?: string, kind?: string | null }>} + */ +export function captionTimes(entry, render = undefined, schedule = undefined) { + const list = Array.isArray(entry?.fx) ? entry.fx : []; + const cache = new Map(); + return list.map((fx0, i) => { + if (!isObj(fx0) || fx0.kind !== "caption") return { i, kind: fx0?.kind ?? null }; + const fx = resolveCaption(fx0); + if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" }; + const text = targetTextOf(entry, fx.target); + const m = findMatch(text, fx.match, fx.occurrence); + if (m.error) return { i, error: `${entry?.id ?? "?"}: caption ${i + 1} ("${fx.match}") is not on the card` }; + if (!cache.has(fx.target)) cache.set(fx.target, cardWordTimes(entry, render, fx.target, schedule)); + const wt = cache.get(fx.target); + const t = wt?.times?.[m.from]; + if (!fin(t)) return { i, t: readingEstimate(m.from), source: "estimate" }; + return { i, t: r3(t), source: wt.source }; + }); +} + +/** + * One caption's span on the item's clock: in from t0 (its lead before the + * word) to t1, held to t2 (`hold` after the word), out by t3. It WAITS for a + * word zoom (`zooms`: their spans, word-zoom.mjs zoomSpan) it would be up + * with, and ends by `end` (the item's last second, or a stack card's media + * phase). `{ t0, t1, t2, t3, at, waited }` or `{ error }`. + * @param {Record<string, any>} fx0 + * @param {number} t + * @param {{ zooms?: Array<Record<string, any>>, end?: number }} [o] + * @returns {{ t0: number, t1: number, t2: number, t3: number, at: number, waited: number | null, error?: undefined } | { error: string, t0?: undefined, t1?: undefined, t2?: undefined, t3?: undefined, at?: undefined, waited?: undefined }} + */ +export function captionSpan(fx0, t, { zooms = [], end = Infinity } = {}) { + const fx = resolveCaption(fx0); + let t0 = Math.max(0, t - fx.lead); + let dur = Math.max(CAPTION_IN, t + fx.hold - t0); + /** @type {number | null} */ + let waited = null; + const sorted = zooms.map((z, k) => ({ ...z, k })).filter((z) => fin(z.t0) && fin(z.t3)).sort((a, b) => a.t0 - b.t0); + for (const z of sorted) { + if (t0 < z.t3 && t0 + dur + CAPTION_OUT > z.t0) { + t0 = z.t3; + waited = z.i ?? z.k; + } + } + if (t0 >= end - CAPTION_IN - 0.05) return { error: `starts at ${r3(t0)} s, at or after the item's ${r3(end)} s${waited !== null ? " (it waits for a word zoom)" : ""}` }; + let t2 = t0 + dur; + if (t2 + CAPTION_OUT > end) t2 = Math.max(t0 + CAPTION_IN, end - CAPTION_OUT); + const t1 = Math.min(t2, t0 + CAPTION_IN); + return { t0: r3(t0), t1: r3(t1), t2: r3(t2), t3: r3(Math.min(end, t2 + CAPTION_OUT)), at: r3(t), waited }; +} + +const easeOut = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 3; + +/** The chip's opacity at item second `s` (0–1). */ +export function captionOpacityAt(span, s) { + if (!span || span.error || s < span.t0 || s >= span.t3) return 0; + if (s < span.t1) return span.t1 > span.t0 ? easeOut((s - span.t0) / (span.t1 - span.t0)) : 1; + if (s < span.t2) return 1; + return 1 - (s - span.t2) / (span.t3 - span.t2); +} + +/** How much of its slide in is left at `s`, 1 → 0 (0 once in). */ +export function captionSlideAt(span, s) { + if (!span || span.error || s >= span.t1) return 0; + if (s < span.t0) return 1; + return 1 - easeOut((s - span.t0) / Math.max(1e-6, span.t1 - span.t0)); +} + +/** The direction a placed chip slides in from (toward the phrase): a unit `{ x, y }`. */ +export const slideDir = (place) => (place === "above" ? { x: 0, y: -1 } : place === "side-right" ? { x: 1, y: 0 } : place === "side-left" ? { x: -1, y: 0 } : { x: 0, y: 1 }); + +/** Two captions of one post up at once: their indices, or null (one at a time). */ +export function overlappingCaptions(spans) { + const s = spans.filter((x) => x && fin(x.t0)).sort((a, b) => a.t0 - b.t0); + for (let k = 1; k < s.length; k += 1) if (s[k].t0 < s[k - 1].t3) return [s[k - 1].i, s[k].i]; + return null; +} + +// --------------------------------------------------------------------------- +// WHERE. +// --------------------------------------------------------------------------- + +/** @typedef {{ x: number, y: number, width: number, height: number }} Rect */ +/** @param {Rect} a @param {Rect} b */ +const area = (a, b) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); +/** @param {Rect} r @param {Rect} b */ +const inside = (r, b) => r.x >= b.x - 0.5 && r.y >= b.y - 0.5 && r.x + r.width <= b.x + b.width + 0.5 && r.y + r.height <= b.y + b.height + 0.5; +/** @param {Rect} r @param {number} m */ +const grow = (r, m) => ({ x: r.x - m, y: r.y - m, width: r.width + 2 * m, height: r.height + 2 * m }); +/** Whether segment a→b crosses rect r (sampled every 3 px). @param {number[]} a @param {number[]} b @param {Rect} r */ +function crosses(a, b, r) { + const n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 3)); + for (let k = 0; k <= n; k += 1) { + const x = a[0] + ((b[0] - a[0]) * k) / n; + const y = a[1] + ((b[1] - a[1]) * k) / n; + if (x > r.x && x < r.x + r.width && y > r.y && y < r.y + r.height) return true; + } + return false; +} + +/** + * THE LEADER: a thin line from the phrase's underline to the chip, through free + * space only -- straight when nothing is in the way, else an elbow out along the + * underline (in the gap under the phrase's line) to the text column's gutter, + * along the gutter, then across to the chip. `[[x, y], …]` or null (none clear). + * @param {Rect} word @param {Rect} chip @param {Rect[]} obstacles @param {Rect | null} column + */ +export function leaderPath(word, chip, obstacles, column) { + const uy = word.y + word.height; + const cy = chip.y + chip.height / 2; + const cx = chip.x + chip.width / 2; + // The chip's edge facing the phrase. + const end = chip.y >= uy ? [Math.min(chip.x + chip.width - 8, Math.max(chip.x + 8, word.x + word.width / 2)), chip.y] + : chip.y + chip.height <= word.y ? [Math.min(chip.x + chip.width - 8, Math.max(chip.x + 8, word.x + word.width / 2)), chip.y + chip.height] + : chip.x >= word.x + word.width ? [chip.x, cy] : [chip.x + chip.width, cy]; + const clear = (pts) => pts.slice(1).every((p, k) => obstacles.every((r) => !crosses(pts[k], p, grow(r, 1)))); + const start = [Math.min(Math.max(end[0], word.x + 4), word.x + word.width - 4), uy]; + const straight = [start, end]; + if (clear(straight)) return straight; + const tries = []; + for (const side of [1, -1]) { + const gx = column ? (side > 0 ? column.x + column.width + 10 : column.x - 10) : side > 0 ? word.x + word.width + 10 : word.x - 10; + const s = [side > 0 ? word.x + word.width : word.x, uy]; + const ey = chip.y <= uy && chip.y + chip.height >= uy ? uy : cy; + const ex = gx >= chip.x + chip.width ? chip.x + chip.width : gx <= chip.x ? chip.x : cx; + const pts = [s, [gx, uy], [gx, ey], [ex, ey]]; + // The first leg runs in the gap under the phrase's line (not judged); the rest through free space. + if (clear(pts.slice(1))) tries.push({ pts, len: Math.abs(gx - s[0]) + Math.abs(ey - uy) + Math.abs(ex - gx) }); + } + tries.sort((a, b) => a.len - b.len); + return tries[0]?.pts ?? null; +} + +/** + * THE PLACE (operator, 4 Nov: "a caption chip never covers ANY of the card's + * words -- read, unread or already read"): the chip in FREE SPACE -- over no + * `obstacles` (every word drawn, the card's header and counts, the attachments, + * the clock), inside `bounds` (the footage box) -- as near the phrase as it can + * be, with a leader to it through free space. `sizes`: the chip laid out at + * each width it may take (`{ width, height, max }`, widest first); `place` + * (below | above | side) a preference, `card` the card's box (a place on the + * card beats one off it). Every candidate is a grid of spots around the phrase + * and down the box; the cheapest clear one wins (distance, plus a cost off the + * card, against the preferred side, and without a clear leader). `{ x, y, + * width, height, max, place, covers, leader }` -- `covers` 0 unless no spot is + * free (then the least-covering, which the build warns about). + * @param {{ word: Rect, sizes: Array<{ width: number, height: number, max?: number }>, bounds: Rect, card?: Rect | null, column?: Rect | null, place?: string, obstacles?: Rect[], gap?: number, step?: number }} o + */ +export function placeCaption({ word, sizes, bounds, card = null, column = null, place = "below", obstacles = [], gap = 10, step = 6 }) { + const cx = word.x + word.width / 2; + const cy = word.y + word.height / 2; + const blocked = obstacles.map((r) => grow(r, gap / 2)).concat([grow(word, gap / 2)]); + let best = null; + let least = null; + for (const [si, sz] of sizes.entries()) { + const xs = new Set(); + for (const x of [cx - sz.width / 2, word.x, word.x + word.width - sz.width, card ? card.x + 14 : bounds.x, card ? card.x + card.width + gap : bounds.x, column ? column.x : bounds.x]) xs.add(Math.round(x)); + for (let x = bounds.x; x + sz.width <= bounds.x + bounds.width; x += Math.max(24, step * 4)) xs.add(Math.round(x)); + for (const x0 of xs) { + const x = Math.min(bounds.x + bounds.width - sz.width, Math.max(bounds.x, x0)); + for (let y = bounds.y; y + sz.height <= bounds.y + bounds.height; y += step) { + const r = { x, y, width: sz.width, height: sz.height }; + const covers = blocked.filter((b) => area(r, b) > 0).length; + const mx = r.x + r.width / 2; + const my = r.y + r.height / 2; + let cost = Math.hypot(mx - cx, my - cy) + si * 40; + const onCard = card && inside(r, card); + if (!onCard) cost += 160; + const below = r.y >= word.y + word.height; + const above = r.y + r.height <= word.y; + const side = !below && !above; + if ((place === "below" && !below) || (place === "above" && !above) || (place === "side" && !side)) cost += 60; + if (covers) { + if (!least || covers < least.covers || (covers === least.covers && cost < least.cost)) least = { ...r, max: sz.max, covers, cost }; + continue; + } + if (best && cost >= best.cost) continue; + best = { ...r, max: sz.max, covers: 0, cost }; + } + } + } + // Its leader, through free space; a spot with none is passed over for the next clear one when there is one. + const pick = best ?? least; + if (!pick) return null; + let leader = leaderPath(word, pick, obstacles, column); + let out = pick; + if (!leader && best) { + // Search again, the ones with a clear leader only (fewer: the cost already ranked them). + const ranked = []; + for (const sz of sizes) { + for (let y = bounds.y; y + sz.height <= bounds.y + bounds.height; y += step * 2) { + for (let x = bounds.x; x + sz.width <= bounds.x + bounds.width; x += step * 4) { + const r = { x, y, width: sz.width, height: sz.height }; + if (blocked.some((b) => area(r, b) > 0)) continue; + ranked.push({ ...r, max: sz.max, covers: 0, cost: Math.hypot(x + sz.width / 2 - cx, y + sz.height / 2 - cy) + (card && inside(r, card) ? 0 : 160) }); + } + } + ranked.sort((a, b) => a.cost - b.cost); + for (const r of ranked.slice(0, 200)) { + const l = leaderPath(word, r, obstacles, column); + if (l) { + out = r; + leader = l; + break; + } + } + if (leader) break; + } + } + const where = card && inside(out, card) ? "card" : "off-card"; + const { cost, ...rest } = out; + return { ...rest, x: Math.round(rest.x), y: Math.round(rest.y), place: where, leader: leader ? leader.map(([x, y]) => [Math.round(x), Math.round(y)]) : null }; +} + +// --------------------------------------------------------------------------- +// THE PLAN. +// --------------------------------------------------------------------------- + +/** + * Post item `entry`'s captions, resolved: `[{ i, scope, from, to, text, + * place, t, source, span, avoid }]` -- `avoid` the target's word indices read + * while it is up (the chip covers none of them). `zooms`: the item's word + * zooms' spans (each a caption waits for); `end`: the last second a caption + * may be up. Throws in the build's words when one cannot be up, or two are up at once. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {{ zooms?: Array<Record<string, any>>, end?: number, schedule?: Record<string, any> }} [o] + * @returns {Array<{ i: number, scope: string, from: number, to: number, text: string, place: string, t: number, source: string, span: { t0: number, t1: number, t2: number, t3: number, at: number, waited: number | null, i: number }, avoid: number[] }>} + */ +export function captionPlan(entry, render = undefined, { zooms = [], end = Infinity, schedule = undefined } = {}) { + const list = Array.isArray(entry?.fx) ? entry.fx : []; + if (!list.some((f) => f?.kind === "caption")) return []; + const times = captionTimes(entry, render, schedule); + const bad = times.filter((t) => t.error); + if (bad.length) throw new Error(bad.map((t) => t.error).join("; ")); + const wt = new Map(); + /** @type {ReturnType<typeof captionPlan>} */ + const out = []; + for (const [i, fx0] of list.entries()) { + if (fx0?.kind !== "caption") continue; + const fx = resolveCaption(fx0); + const m = findMatch(targetTextOf(entry, fx.target), fx.match, fx.occurrence); + const span = captionSpan(fx0, times[i].t, { zooms, end }); + if (span.error !== undefined) throw new Error(`${entry?.id ?? "?"}: caption ${i + 1} ("${fx.match}") ${span.error} (move its at, or shorten the zoom)`); + if (!wt.has(fx.target)) wt.set(fx.target, cardWordTimes(entry, render, fx.target, schedule)); + const read = wt.get(fx.target)?.times ?? []; + const avoid = read.map((s, k) => (fin(s) && s >= span.t0 - 0.25 && s <= span.t3 + 0.25 && (k < m.from || k > m.to) ? k : -1)).filter((k) => k >= 0); + out.push({ i, scope: targetScope(fx.target), from: m.from, to: m.to, text: fx.text, place: fx.place, t: Number(times[i].t), source: String(times[i].source), span: { ...span, i }, avoid }); + } + const clash = overlappingCaptions(out.map((c) => c.span)); + if (clash) throw new Error(`${entry?.id ?? "?"}: captions ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at, or shorten its hold)`); + return out; +} + +// --------------------------------------------------------------------------- +// THE LOOK. +// --------------------------------------------------------------------------- + +/** The chip's inner HTML: the text, its part before " — " bold. */ +export function captionInnerHtml(text) { + const t = String(text ?? ""); + const cut = t.indexOf(" — "); + return cut > 0 ? `<b>${esc(t.slice(0, cut))}</b><span class="pcap-rest"> — ${esc(t.slice(cut + 3))}</span>` : esc(t); +} + +/** + * The chips' CSS, for a page `height` px tall (sizes at 1080), in the card's + * palette (`palette`, the deck's) and faces (the card's @font-face PostSans / + * PostSansBold, then CAPTION_FONT_STACK). + */ +/** @param {{ height?: number, palette?: Record<string, string> }} [o] */ +export function captionCss({ height = 1080, palette = {} } = {}) { + const k = height / 1080; + const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; + const panel = mixHex(pal.bg, pal.accent, 0.16); + const n = Math.round(16 * k); + return ` +[data-post-fx-captions] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 60; } +.pcap { position: absolute; left: 0; top: 0; max-width: ${Math.round(620 * k)}px; padding: ${Math.round(10 * k)}px ${Math.round(18 * k)}px ${Math.round(11 * k)}px; background: ${panel}; color: ${pal.fg}; + border: ${Math.max(1, Math.round(2 * k))}px solid ${pal.accent}; border-radius: ${Math.round(12 * k)}px; box-shadow: 0 ${Math.round(8 * k)}px ${Math.round(26 * k)}px ${rgbaOf("#000000", 0.5)}; + font-family: 'PostSans', ${CAPTION_FONT_STACK}; font-size: ${Math.round(27 * k)}px; line-height: 1.28; font-synthesis: none; opacity: 0; will-change: transform, opacity; overflow-wrap: anywhere; } +.pcap b { font-family: 'PostSansBold', ${CAPTION_FONT_STACK}; font-weight: 700; color: ${pal.fg}; } +.pcap .pcap-rest { color: ${mixHex(pal.fg, pal.muted, 0.25)}; } +.pcap::before { content: ""; position: absolute; width: ${n}px; height: ${n}px; background: ${panel}; border: inherit; border-width: ${Math.max(1, Math.round(2 * k))}px; border-radius: ${Math.round(2 * k)}px; transform: rotate(45deg); } +.pcap[data-place="below"]::before { top: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-right: none; border-bottom: none; } +.pcap[data-place="above"]::before { bottom: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-left: none; border-top: none; } +.pcap[data-place="side-right"]::before { left: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-right: none; border-top: none; } +.pcap[data-place="side-left"]::before { right: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-left: none; border-bottom: none; } +.pcap[data-place="free"]::before { display: none; } +.pcap-leader-line { stroke: ${pal.accent}; } +.pcap-leader-dot { fill: ${pal.accent}; } +.pcap-mark { position: absolute; height: ${Math.max(2, Math.round(3 * k))}px; background: ${pal.accent}; border-radius: ${Math.max(1, Math.round(2 * k))}px; opacity: 0; } +`; +} + +// --------------------------------------------------------------------------- +// THE DOM (self-contained: passed to page.evaluate by the build, called by Play). +// --------------------------------------------------------------------------- + +/** The widths a chip is laid out at (px at 1080): the widest first; a narrower one fits a smaller space. */ +export const CAPTION_WIDTHS = Object.freeze([620, 480, 380, 300]); + +/** + * Mount the chips over the card page: `{ css, chips: [{ i, html }], k }`, each + * laid out unplaced and hidden at every width of CAPTION_WIDTHS (× `k`). + * Returns each one's sizes `[{ i, sizes: [{ width, height, max }] }]`. + * @param {{ css?: string, chips?: Array<{ i: number, html: string }>, k?: number, widths?: number[] } | null} arg + * @param {Document} [doc] + * @returns {Array<{ i: number, sizes: Array<{ width: number, height: number, max: number }> }>} + */ +export function mountCaptions(arg, doc = document) { + doc.querySelectorAll("[data-post-fx-captions], style[data-post-fx-captions-css]").forEach((el) => el.remove()); + const chips = (arg && arg.chips) || []; + if (!chips.length) return []; + const style = doc.createElement("style"); + style.setAttribute("data-post-fx-captions-css", ""); + style.textContent = arg.css || ""; + doc.head.appendChild(style); + const layer = doc.createElement("div"); + layer.setAttribute("data-post-fx-captions", ""); + doc.body.appendChild(layer); + const k = (arg && arg.k) || 1; + const widths = (arg && arg.widths) || [620, 480, 380, 300]; + return chips.map((c) => { + const el = doc.createElement("div"); + el.className = "pcap"; + el.setAttribute("data-post-fx-caption", String(c.i)); + el.innerHTML = c.html; + layer.appendChild(el); + const sizes = []; + for (const w of widths) { + const max = Math.round(w * k); + el.style.maxWidth = `${max}px`; + const b = el.getBoundingClientRect(); + const s = { width: Math.ceil(b.width), height: Math.ceil(b.height), max }; + if (!sizes.some((x) => x.width === s.width && x.height === s.height)) sizes.push(s); + } + el.style.maxWidth = ""; + return { i: c.i, sizes }; + }); +} + +/** + * The phrase's geometry as the card is drawn now: `{ scope, from, to, avoid: + * [indices] }` → `{ card, word, lines, avoid, obstacles, column }` -- px boxes: + * `lines` the phrase's box per line (its underline), `obstacles` everything + * drawn a chip may not cover (every word in view, the card's header, its + * counts, a quote's or a picture's frame -- the phrase itself apart), `column` + * the phrase's text column; or `{ error }` when a word is not drawn or is cut + * off the card. + * @param {{ scope: string, from: number, to: number, avoid?: number[] }} arg + * @param {Document} [doc] + * @returns {{ error: string } | { error?: undefined, card: Rect, word: Rect, lines: Rect[], avoid: Rect[], obstacles: Rect[], column: Rect | null }} + */ +export function measureCaptionWords(arg, doc = document) { + const rect = (el) => { + const b = el.getBoundingClientRect(); + return { x: b.left, y: b.top, width: b.width, height: b.height }; + }; + const card = doc.querySelector("[data-post-card]"); + if (!card) return { error: "the card is not drawn" }; + /** @type {Rect[]} */ + const lines = []; + let column = null; + for (let i = arg.from; i <= arg.to; i += 1) { + const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`); + if (!el) return { error: `word ${i} is not on the card` }; + const clip = el.closest(".words, .ptext, .qtext, .twords, .tt"); + if (clip && !column) column = rect(clip); + const cb = (clip || card).getBoundingClientRect(); + for (const r of Array.from(el.getClientRects())) { + if (r.width === 0) continue; + if (r.bottom > cb.bottom + 1 || r.top < cb.top - 1) return { error: "cut off the card (the text is longer than the card shows)" }; + const same = lines.find((l) => Math.abs(l.y - r.top) < r.height / 2); + if (same) { + const x1 = Math.max(same.x + same.width, r.right); + same.x = Math.min(same.x, r.left); + same.width = x1 - same.x; + same.height = Math.max(same.height, r.height); + } else lines.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + } + } + if (!lines.length) return { error: "the words are not drawn" }; + const x0 = Math.min(...lines.map((l) => l.x)); + const y0 = Math.min(...lines.map((l) => l.y)); + const x1 = Math.max(...lines.map((l) => l.x + l.width)); + const y1 = Math.max(...lines.map((l) => l.y + l.height)); + /** @type {Rect[]} */ + const avoid = []; + for (const i of arg.avoid || []) { + const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`); + if (el) for (const r of Array.from(el.getClientRects())) if (r.width > 0) avoid.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + } + // Everything drawn a chip may not cover: each word in view (inside what clips it, not faded out), then the + // card's furniture -- names, dates, the platform mark, avatars, counts, labels, a context shot or quote frame. + /** @type {Rect[]} */ + const obstacles = []; + const mine = new Set(Array.from({ length: arg.to - arg.from + 1 }, (_, k) => `${arg.scope}:${arg.from + k}`)); + const view = doc.defaultView; + const shown = (el) => { + for (let n = el; n && n !== doc.body; n = n.parentElement) { + const st = view ? view.getComputedStyle(n) : null; + if (st && (st.visibility === "hidden" || st.display === "none" || Number(st.opacity) < 0.05)) return false; + } + return true; + }; + for (const el of Array.from(doc.querySelectorAll("[data-w]"))) { + if (mine.has(el.getAttribute("data-w") || "")) continue; + const clip = el.closest(".words, .ptext, .qtext, .twords, .tt, [data-thread-tile]") || card; + const cb = clip.getBoundingClientRect(); + for (const r of Array.from(el.getClientRects())) { + if (r.width <= 0 || r.bottom <= cb.top || r.top >= cb.bottom) continue; + obstacles.push({ x: r.left, y: Math.max(r.top, cb.top), width: r.width, height: Math.min(r.bottom, cb.bottom) - Math.max(r.top, cb.top) }); + } + } + for (const el of Array.from(card.querySelectorAll(".avatar, .name, .handle, .date, .pdate, .mark, .plabel, .repost, .replying, .counts > *, .pshot img, .sline, .strip"))) { + if (!shown(el)) continue; + for (const r of Array.from(el.getClientRects())) if (r.width > 0 && r.height > 0) obstacles.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + } + return { card: rect(card), word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }, lines, avoid, obstacles, column }; +} + +/** + * Set the chips: `[{ i, x, y, max, opacity, dx, dy, marks, mark, leader }]` + * (`marks`: the underline's boxes under the phrase, `leader` its line to the + * chip, `mark` their opacity); a chip not listed is hidden. `only`: "chip" | + * "mark" draws just that layer (the build shoots them apart), absent both. + * @param {{ list?: Array<Record<string, any>>, only?: string, stroke?: number } | null} arg + * @param {Document} [doc] + */ +export function setCaptionState(arg, doc = document) { + const list = (arg && arg.list) || []; + const only = arg && arg.only; + const layer = doc.querySelector("[data-post-fx-captions]"); + if (!layer) return; + layer.querySelectorAll(".pcap-mark, .pcap-leader").forEach((el) => el.remove()); + for (const el of Array.from(layer.querySelectorAll(".pcap"))) { + const c = list.find((x) => String(x.i) === el.getAttribute("data-post-fx-caption")); + if (!c || only === "mark") { + el.style.opacity = "0"; + continue; + } + el.setAttribute("data-place", "free"); + if (c.max) el.style.maxWidth = `${c.max}px`; + el.style.transform = `translate(${Math.round(c.x + (c.dx || 0))}px, ${Math.round(c.y + (c.dy || 0))}px)`; + el.style.opacity = String(c.opacity); + } + if (only === "chip") return; + const sw = (arg && arg.stroke) || 2; + for (const c of list) { + for (const l of c.marks || []) { + const m = doc.createElement("div"); + m.className = "pcap-mark"; + m.setAttribute("data-post-fx-caption-mark", String(c.i)); + const h = Math.max(2, Math.round(l.height * 0.07)); + m.style.left = `${Math.round(l.x)}px`; + m.style.top = `${Math.round(l.y + l.height - h * 0.4)}px`; + m.style.width = `${Math.round(l.width)}px`; + m.style.opacity = String(c.mark ?? c.opacity); + layer.appendChild(m); + } + if (Array.isArray(c.leader) && c.leader.length > 1) { + const ns = "http://www.w3.org/2000/svg"; + const svg = doc.createElementNS(ns, "svg"); + svg.setAttribute("class", "pcap-leader"); + svg.setAttribute("data-post-fx-caption-leader", String(c.i)); + svg.setAttribute("width", "100%"); + svg.setAttribute("height", "100%"); + svg.style.position = "absolute"; + svg.style.left = "0"; + svg.style.top = "0"; + svg.style.overflow = "visible"; + svg.style.opacity = String(c.mark ?? c.opacity); + const pl = doc.createElementNS(ns, "polyline"); + pl.setAttribute("points", c.leader.map((p) => `${p[0] + (c.ldx || 0)},${p[1] + (c.ldy || 0)}`).join(" ")); + pl.setAttribute("fill", "none"); + pl.setAttribute("stroke-width", String(sw)); + pl.setAttribute("stroke-linejoin", "round"); + pl.setAttribute("class", "pcap-leader-line"); + svg.appendChild(pl); + const last = c.leader[c.leader.length - 1]; + const dot = doc.createElementNS(ns, "circle"); + dot.setAttribute("cx", String(last[0])); + dot.setAttribute("cy", String(last[1])); + dot.setAttribute("r", String(sw * 1.6)); + dot.setAttribute("class", "pcap-leader-dot"); + svg.appendChild(dot); + layer.appendChild(svg); + } + } +} + +/** + * The card page's palette, read off its drawn styles (Play has the page, not the + * deck's render): `{ bg, fg, muted, accent }` as #rrggbb. + * @param {Document} [doc] + * @returns {Record<string, string>} + */ +export function paletteOfDoc(doc = document) { + const hex = (c) => { + const m = /rgba?\(([^)]+)\)/.exec(String(c || "")); + if (!m) return null; + const [r, g, b] = m[1].split(",").map((v) => Math.round(Number(v))); + return `#${[r, g, b].map((v) => Math.max(0, Math.min(255, v || 0)).toString(16).padStart(2, "0")).join("")}`; + }; + const view = doc.defaultView; + if (!view || !doc.body) return {}; + const probe = (cls) => { + const el = doc.createElement("span"); + el.className = cls; + doc.body.appendChild(el); + const c = view.getComputedStyle(el).color; + el.remove(); + return hex(c); + }; + const st = view.getComputedStyle(doc.body); + const out = { bg: hex(st.backgroundColor), fg: hex(st.color), accent: probe("mention"), muted: probe("pdate") }; + return Object.fromEntries(Object.entries(out).filter(([, v]) => v)); +} diff --git a/umtool/report-to-video/post-caption.test.mjs b/umtool/report-to-video/post-caption.test.mjs @@ -0,0 +1,141 @@ +// A post item's CAPTION (post-caption.mjs): its validation, its time (at, the +// take's words, the reading estimate), its span (waiting for a word zoom), and +// its place (never over a word read while it is up). +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + CAPTION_IN, CAPTION_OUT, captionInnerHtml, captionOpacityAt, captionPlan, captionSlideAt, captionSpan, captionTimes, cardWordTimes, placeCaption, +} from "./post-caption.mjs"; +import { validatePostFx, wordZoomTimes } from "./word-zoom.mjs"; + +const TEXT = "I'm ignoring my broken bones so my training can continue. I have achieved Fudōshin. Its amazing."; +const base = (o = {}) => ({ type: "post", id: "p1", post: "s/1", platform: "x", author: "S", handle: "s", date: "2026-10-20T19:46:00.000Z", text: TEXT, ...o }); +const cap = (o = {}) => ({ kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"", ...o }); +const take = (o = {}) => ({ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 10, script: TEXT, ...o }); + +test("validation: a caption's keys, its match, its text, its knobs -- in the build's words", () => { + assert.deepEqual(validatePostFx(base({ fx: [cap()] })), []); + const errs = validatePostFx(base({ fx: [cap({ match: "Fudoshinn", text: "", place: "left", hold: 0.1, scale: 2 })] })); + assert.ok(errs.some((e) => /fx\[0\]\.scale is not a caption key/.test(e)), errs.join("\n")); + assert.ok(errs.some((e) => /match "Fudoshinn" is not in the post's words/.test(e))); + assert.ok(errs.some((e) => /\.text must be what the caption says/.test(e))); + assert.ok(errs.some((e) => /\.place must be one of below, above, side/.test(e))); + assert.ok(errs.some((e) => /\.hold must be 0.5–10 seconds/.test(e))); + assert.ok(validatePostFx(base({ fx: [cap({ text: "x".repeat(161) })] })).some((e) => /longer than 160 characters/.test(e))); +}); + +test("a caption is not a word zoom: wordZoomTimes gives it no time and no error", () => { + assert.deepEqual(wordZoomTimes(base({ fx: [cap()] })), [{ i: 0, kind: "caption" }]); +}); + +test("WHEN: at wins; un-narrated, the reading estimate (1 s + 3 words a second)", () => { + assert.deepEqual(captionTimes(base({ fx: [cap({ at: 2.25 })] })), [{ i: 0, t: 2.25, source: "at" }]); + // "Fudōshin." is the card's 14th word (index 13): 1 + 13/3. + assert.deepEqual(captionTimes(base({ fx: [cap()] })), [{ i: 0, t: 5.33, source: "estimate" }]); +}); + +test("WHEN: narrated with no word timings -- the read spread over its script by characters, on the item's clock", () => { + const e = base({ narration: { script: TEXT, takes: [take()], lead: 0.5, rate: 1.25 }, fx: [cap()] }); + const [t] = captionTimes(e); + assert.equal(t.source, "estimate"); + // 72 characters of 101 before it, over 10 ÷ 1.25 = 8 s, from 0.5. + const before = TEXT.indexOf("Fudōshin"); + const n = TEXT.split(/\s+/).reduce((a, w) => a + w.length + 1, 0); + assert.equal(t.t, Math.round((0.5 + (before / n) * 8) * 1000) / 1000); + // Each card word has a time, in order. + const wt = cardWordTimes(e); + assert.equal(wt.times.length, TEXT.split(/\s+/).length); + for (let k = 1; k < wt.times.length; k += 1) assert.ok(wt.times[k] >= wt.times[k - 1]); +}); + +test("WHEN: narrated and timed -- the matched word's start in the take (lead + start ÷ rate)", () => { + const words = TEXT.split(" ").map((w, i) => ({ w, start: i * 0.5, end: i * 0.5 + 0.4 })); + const e = base({ narration: { script: TEXT, takes: [take({ words })], lead: 0.4, rate: 1.25 }, fx: [cap()] }); + assert.deepEqual(captionTimes(e), [{ i: 0, t: 5.6, source: "words" }]); +}); + +test("the span: in over its lead, held from the word, out; it waits for a word zoom it would be up with; it ends by the item's end", () => { + const s = captionSpan(cap(), 4, {}); + assert.deepEqual(s, { t0: 3.85, t1: 3.85 + CAPTION_IN, t2: 6.5, t3: 6.5 + CAPTION_OUT, at: 4, waited: null }); + const w = captionSpan(cap(), 4, { zooms: [{ i: 0, t0: 3.5, t1: 4, t2: 5.2, t3: 5.6 }] }); + assert.equal(w.t0, 5.6); + assert.equal(w.waited, 0); + assert.equal(Math.round((w.t2 - w.t0) * 100) / 100, 2.65); + const short = captionSpan(cap(), 4, { end: 5 }); + assert.equal(short.t3, 5); + assert.match(captionSpan(cap(), 4.9, { end: 5 }).error, /at or after the item's 5 s/); + assert.equal(captionOpacityAt(s, 3.8), 0); + assert.equal(captionOpacityAt(s, 5), 1); + assert.ok(captionOpacityAt(s, 6.6) > 0 && captionOpacityAt(s, 6.6) < 1); + assert.equal(captionSlideAt(s, 3.85), 1); + assert.equal(captionSlideAt(s, 4.5), 0); +}); + +test("the plan: the words read while it is up are what it must not cover; two up at once are refused", () => { + const plan = captionPlan(base({ fx: [cap({ at: 2 })] })); + assert.equal(plan.length, 1); + assert.deepEqual([plan[0].scope, plan[0].from, plan[0].to], ["post", 13, 13]); + // Up 1.85–4.85 s (± 0.25), the words read at 1 s + 3 a second: words 2..12 -- never the phrase itself. + assert.deepEqual(plan[0].avoid, [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + assert.throws(() => captionPlan(base({ fx: [cap({ at: 2 }), cap({ at: 3, match: "amazing." })] })), /captions 1 and 2 are up at once/); +}); + +const overlapArea = (a, b) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); +/** A card of text: `rows` lines of words, `[{x, y, width, height}]`, from (x0, y0). */ +const textBlock = (x0, y0, rows, { words = 8, w = 70, h = 40, gapX = 14, lineH = 52 } = {}) => + Array.from({ length: rows }, (_, r) => Array.from({ length: words }, (_, c) => ({ x: x0 + c * (w + gapX), y: y0 + r * lineH, width: w, height: h }))).flat(); + +test("THE PLACE (operator, 4 Nov: \"a caption chip never covers ANY of the card's words\"): free space only -- below the text, off the card, or in a band -- never over a word, read or not", () => { + const card = { x: 40, y: 40, width: 760, height: 1000 }; + const bounds = { x: 12, y: 12, width: 1896, height: 1056 }; + const words = textBlock(80, 300, 8); // y 300..704: a block of text mid-card + const phrase = words[3 * 8 + 3]; + const obstacles = words.filter((w) => w !== phrase); + const sizes = [{ width: 480, height: 70, max: 480 }, { width: 340, height: 100, max: 340 }]; + const p = placeCaption({ word: phrase, sizes, bounds, card, column: { x: 80, y: 300, width: 680, height: 410 }, obstacles }); + assert.equal(p.covers, 0); + for (const w of words) assert.equal(overlapArea(p, w), 0, `over a word at ${w.x},${w.y}`); + assert.equal(p.place, "card", "the card's own free space beats the frame's"); + assert.ok(p.y >= 704 || p.y + p.height <= 300, "above or below the block, not inside it"); + assert.ok(Array.isArray(p.leader) && p.leader.length >= 2, "a leader to the phrase"); + // Its leader runs through free space: past the first leg (in the gap under the phrase's line), it crosses no word. + const legs = p.leader.slice(p.leader.length > 2 ? 1 : 0); + for (let k = 1; k < legs.length; k += 1) { + for (let q = 0; q <= 20; q += 1) { + const x = legs[k - 1][0] + ((legs[k][0] - legs[k - 1][0]) * q) / 20; + const y = legs[k - 1][1] + ((legs[k][1] - legs[k - 1][1]) * q) / 20; + for (const w of obstacles) assert.ok(!(x > w.x + 1 && x < w.x + w.width - 1 && y > w.y + 1 && y < w.y + w.height - 1), `leader through a word at ${x},${y}`); + } + } + // A card full of text: off the card, still over nothing (the attachment's box an obstacle too). + const full = textBlock(60, 60, 18, { words: 8 }); + const media = { x: 840, y: 240, width: 1060, height: 600 }; + const q = placeCaption({ word: full[5 * 8 + 2], sizes, bounds, card, obstacles: [...full.filter((_, i) => i !== 5 * 8 + 2), media] }); + assert.equal(q.covers, 0); + assert.equal(q.place, "off-card"); + for (const w of [...full, media]) assert.equal(overlapArea(q, w), 0); + // Below by default when both are free; above when asked. + const lone = { x: 300, y: 500, width: 100, height: 40 }; + const b = placeCaption({ word: lone, sizes, bounds, card }); + assert.ok(b.y >= 540); + const a = placeCaption({ word: lone, sizes, bounds, card, place: "above" }); + assert.ok(a.y + a.height <= 500); +}); + +test("THE PLACE, at random: over a hundred cards of words, the chip never overlaps a word box when the frame has room", () => { + let seed = 7; + const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648); + for (let n = 0; n < 120; n += 1) { + const rows = 2 + Math.floor(rnd() * 12); + const words = textBlock(60 + rnd() * 40, 60 + rnd() * 300, rows, { words: 4 + Math.floor(rnd() * 5) }); + const k = Math.floor(rnd() * words.length); + const p = placeCaption({ word: words[k], sizes: [{ width: 300 + rnd() * 300, height: 60 + rnd() * 50 }], bounds: { x: 0, y: 0, width: 1920, height: 1080 }, card: { x: 40, y: 40, width: 800, height: 1000 }, obstacles: words.filter((_, i) => i !== k) }); + assert.equal(p.covers, 0, `card ${n}`); + for (const w of words) assert.equal(overlapArea(p, w), 0, `card ${n}: over a word`); + } +}); + +test("the chip's markup: the part before the dash bold, every character escaped, CJK kept", () => { + assert.equal(captionInnerHtml("不動心 · fudōshin — \"immovable mind\""), "<b>不動心 · fudōshin</b><span class=\"pcap-rest\"> — &quot;immovable mind&quot;</span>"); + assert.equal(captionInnerHtml("<b>x</b>"), "&lt;b&gt;x&lt;/b&gt;"); +}); diff --git a/umtool/report-to-video/post-clock.mjs b/umtool/report-to-video/post-clock.mjs @@ -0,0 +1,331 @@ +// A POST ITEM's CLOCK (umtool/docs/report-video.md, "The clock"; operator, 4 Nov: +// "show a clock advancing as we show the newest posts/replies chronologically +// and quickly to convey how much he's posting in bursts" -- "the clock should +// probably just be for mr obvious' replies and ignore the messages he's replying +// to so it generally always goes forward unless there's a compelling reason to +// go back at some point (e.g. 'you want to die' combo)"). +// +// A small clock-and-date chip on the card: "4:10 AM ET · Wed 4 Nov", in the +// operator's zone (America/New_York; render.posts.clock.zone). It shows the +// ITEM's own post time (entry.date) -- never a parent's or a quote's, and it +// does not move while they are read. Between two consecutive clock items, in +// the first CLOCK_TICK seconds of the second it RUNS from the earlier time to +// this one: the hands spin, the minutes roll, the date flips, the gap flashes +// ("+38 min", "+2 h 14 min", "+3 d 4 h"). When this post is EARLIER than the +// one before (a stinger that jumps back), it REWINDS: the hands spin backwards, +// a "⟲ rewind" badge with the gap, the date flipping back -- deliberate, never a +// glitch. `rewind: "off"` cuts straight to the time; `"on"` rewinds even +// forward (or across no gap: a repeated post spins back a full turn to itself). +// +// render.posts.clock = { on?: true, zone?: "America/New_York" } // the cut's default +// entry.fx = [{ kind: "clock", on?: false, rewind?: "auto" | "on" | "off" }] // one item's +// +// WHERE: the card's bottom-right corner (beside the counts row, never read +// text), else its top-right; the first place over no word of the card. Drawn +// OVER the card, never in it (no data-w, no data-post-block): readInViewErrors +// never counts it, and it covers no read text. +// +// Pure but for the DOM functions (mountClock, measureClockPlace, setClockState), +// SELF-CONTAINED: the build passes them to a page, Play calls them on its frame. + +import { mixHex, rgbaOf } from "./post-item.mjs"; + +export const CLOCK_ZONE = "America/New_York"; +/** How long the clock runs from the earlier time to this one, seconds. */ +export const CLOCK_TICK = 0.8; +/** The gap's badge stays this long after the run, then fades over CLOCK_FLASH_OUT. */ +export const CLOCK_FLASH_HOLD = 0.9; +export const CLOCK_FLASH_OUT = 0.4; +export const CLOCK_REWINDS = Object.freeze(["auto", "on", "off"]); +const CLOCK_KEYS = new Set(["kind", "on", "rewind"]); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +/** A zone Intl knows. */ +export function validZone(zone) { + try { + new Intl.DateTimeFormat("en-US", { timeZone: String(zone) }); + return typeof zone === "string" && zone.length > 0; + } catch { + return false; + } +} + +/** Every reason a clock fx (entry `e`'s fx[i], named `fw`) cannot be built. word-zoom.mjs validatePostFx calls it. */ +export function clockErrors(e, fx, fw) { + const errors = []; + for (const k of Object.keys(fx)) if (!CLOCK_KEYS.has(k)) errors.push(`${fw}.${k} is not a clock key (${[...CLOCK_KEYS].join(", ")})`); + if (fx.on !== undefined && typeof fx.on !== "boolean") errors.push(`${fw}.on must be true or false`); + if (fx.rewind !== undefined && !CLOCK_REWINDS.includes(fx.rewind)) errors.push(`${fw}.rewind must be one of ${CLOCK_REWINDS.join(", ")}`); + if ((Array.isArray(e?.fx) ? e.fx : []).filter((f) => f?.kind === "clock").length > 1) errors.push(`${fw}: one clock per item`); + if (fx.on !== false && !Number.isFinite(Date.parse(String(e?.date ?? "")))) errors.push(`${fw}: the post has no date to show (its date)`); + return errors; +} + +/** Every reason `render.posts.clock` is refused (post-redact.mjs validatePostsRender calls it). */ +export function validateClockRender(c) { + if (c === undefined) return []; + if (!isObj(c)) return ["render.posts.clock must be { on?, zone? }"]; + const errors = []; + for (const k of Object.keys(c)) if (!["on", "zone"].includes(k)) errors.push(`render.posts.clock.${k} is not a clock knob (on, zone)`); + if (c.on !== undefined && typeof c.on !== "boolean") errors.push("render.posts.clock.on must be true or false"); + if (c.zone !== undefined && !validZone(c.zone)) errors.push(`render.posts.clock.zone ${JSON.stringify(c.zone)} is not a time zone (an IANA name: America/New_York)`); + return errors; +} + +/** The item's clock fx, or null. */ +const clockFxOf = (entry) => (Array.isArray(entry?.fx) ? entry.fx.find((f) => isObj(f) && f.kind === "clock") ?? null : null); + +/** Whether post item `entry` shows the clock: its own fx (on unless `on: false`), else the cut's `render.posts.clock.on`. */ +export function clockOn(entry, render) { + if (entry?.type !== undefined && entry.type !== "post") return false; + if (!Number.isFinite(Date.parse(String(entry?.date ?? "")))) return false; + const fx = clockFxOf(entry); + if (fx) return fx.on !== false; + return render?.posts?.clock?.on === true; +} + +/** The cut's zone. */ +export const clockZoneOf = (render) => (validZone(render?.posts?.clock?.zone) ? render.posts.clock.zone : CLOCK_ZONE); + +/** + * THE CLOCK's PLAN for post item `entry`: `{ to, from, mode, zone, gap }` -- + * `to` its post's time (ms), `from` the time the clock showed on the item + * before it when that one is a clock item too (else null: no run), `mode` + * "forward" | "rewind" | "none", `gap` to - from (ms). Null when it shows no clock. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {Record<string, any> | null} [prev] + * @returns {{ to: number, from: number | null, mode: "forward" | "rewind" | "none", zone: string, gap: number, forced: boolean } | null} + */ +export function clockPlan(entry, render = undefined, prev = null) { + if (!clockOn(entry, render)) return null; + const to = Date.parse(entry.date); + const zone = clockZoneOf(render); + const rewind = clockFxOf(entry)?.rewind ?? "auto"; + const from = prev && clockOn(prev, render) ? Date.parse(prev.date) : null; + if (from === null || rewind === "off") return { to, from: null, mode: "none", zone, gap: 0, forced: false }; + if (rewind === "on") return { to, from: from > to ? from : to + 12 * 3600e3, mode: "rewind", zone, gap: to - from, forced: from <= to }; + if (from === to) return { to, from: null, mode: "none", zone, gap: 0, forced: false }; + return { to, from, mode: from > to ? "rewind" : "forward", zone, gap: to - from, forced: false }; +} + +/** A gap as the badge says it: "+38 min", "+2 h 14 min", "+3 d 4 h", "+45 s" (its sign kept). */ +export function gapLabel(ms) { + const sign = ms < 0 ? "−" : "+"; + let s = Math.round(Math.abs(ms) / 1000); + if (s < 60) return `${sign}${s} s`; + const d = Math.floor(s / 86400); + s -= d * 86400; + const h = Math.floor(s / 3600); + s -= h * 3600; + const m = Math.floor(s / 60); + if (d) return `${sign}${d} d${h ? ` ${h} h` : ""}`; + if (h) return `${sign}${h} h${m ? ` ${m} min` : ""}`; + return `${sign}${m} min`; +} + +const fmtCache = new Map(); +const fmt = (zone, o) => { + const k = `${zone}|${JSON.stringify(o)}`; + if (!fmtCache.has(k)) fmtCache.set(k, new Intl.DateTimeFormat(o.locale ?? "en-US", { timeZone: zone, ...o, locale: undefined })); + return fmtCache.get(k); +}; + +/** A moment's face in a zone: `{ time: "4:10 AM", zone: "ET", date: "Wed 4 Nov", h, m }` (h 0–23, m 0–59.99 its local clock). */ +export function clockFace(ms, zone = CLOCK_ZONE) { + const d = new Date(ms); + const time = fmt(zone, { hour: "numeric", minute: "2-digit" }).format(d); + const zn = (fmt(zone, { timeZoneName: "shortGeneric", hour: "numeric" }).formatToParts(d).find((p) => p.type === "timeZoneName")?.value ?? "").replace(/^GMT$/, "UTC"); + const date = fmt(zone, { locale: "en-GB", weekday: "short", day: "numeric", month: "short" }).format(d).replace(",", ""); + const parts = Object.fromEntries(fmt(zone, { hourCycle: "h23", hour: "2-digit", minute: "2-digit", second: "2-digit" }).formatToParts(d).map((p) => [p.type, p.value])); + return { time, zone: zn, date, h: Number(parts.hour) % 24, m: Number(parts.minute) + Number(parts.second) / 60 }; +} + +const easeInOut = (x) => { + const v = Math.min(1, Math.max(0, x)); + return v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2; +}; + +/** + * THE CLOCK AT item second `s`: what the chip shows -- `{ time, zone, date, + * hour, minute (hand angles, degrees), gap, gapOpacity, mode, running }`. The + * hands' angles run continuously from the earlier time (a rewind: backwards). + * @param {ReturnType<typeof clockPlan>} plan + * @param {number} s + */ +export function clockStateAt(plan, s) { + if (!plan) return null; + const run = plan.from === null || plan.mode === "none" ? 1 : easeInOut(s / CLOCK_TICK); + const shown = plan.from === null ? plan.to : plan.from + (plan.to - plan.from) * run; + const face = clockFace(shown, plan.zone); + // The hands from the minutes elapsed (continuous across days: the hour hand turns once per 12 h, the minute hand per hour). + const end = clockFace(plan.to, plan.zone); + const endMin = end.h * 60 + end.m; + const minutes = endMin + (shown - plan.to) / 60000; + const ga = plan.mode === "none" ? 0 : s < CLOCK_TICK + CLOCK_FLASH_HOLD ? Math.min(1, s / 0.15) : Math.max(0, 1 - (s - CLOCK_TICK - CLOCK_FLASH_HOLD) / CLOCK_FLASH_OUT); + return { + time: face.time, + zone: face.zone, + date: face.date, + hour: ((minutes / 2) % 360 + 360) % 360, + minute: ((minutes * 6) % 360 + 360) % 360, + // Unwrapped (the DOM rotates by these, so a run spins rather than snapping back across 0). + hourTurn: minutes / 2, + minuteTurn: minutes * 6, + gap: plan.mode === "rewind" ? `⟲ rewind${plan.forced ? "" : ` ${gapLabel(plan.gap)}`}` : plan.mode === "forward" ? gapLabel(plan.gap) : "", + gapOpacity: Math.round(ga * 1000) / 1000, + mode: plan.mode, + running: plan.mode !== "none" && s < CLOCK_TICK, + }; +} + +/** The item seconds whose frames differ (the run and the badge's fade), at `fps`: `[0, 1/fps, …]` up to the last change. */ +export function clockFrameTimes(plan, fps = 30) { + if (!plan || plan.mode === "none") return [0]; + const end = CLOCK_TICK + CLOCK_FLASH_HOLD + CLOCK_FLASH_OUT; + const out = []; + for (let f = 0; f / fps <= end + 1e-9; f += 1) out.push(f / fps); + return out; +} + +// --------------------------------------------------------------------------- +// THE LOOK, and the DOM (self-contained). +// --------------------------------------------------------------------------- + +/** The chip's CSS for a page `height` px tall, in the card's palette. */ +export function clockCss({ height = 1080, palette = {} } = {}) { + const k = height / 1080; + const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; + const panel = mixHex(pal.bg, pal.fg, 0.08); + const px = (v) => `${Math.round(v * k)}px`; + return ` +[data-post-clock-layer] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 61; } +.pclock { position: absolute; left: 0; top: 0; display: flex; align-items: center; gap: ${px(12)}; padding: ${px(7)} ${px(16)} ${px(7)} ${px(9)}; + background: ${panel}; color: ${pal.fg}; border: ${Math.max(1, Math.round(1.5 * k))}px solid ${rgbaOf(pal.fg, 0.18)}; border-radius: ${px(999)}; + box-shadow: 0 ${px(4)} ${px(16)} ${rgbaOf("#000000", 0.4)}; font-family: 'PostSans', 'Noto Sans CJK JP', sans-serif; white-space: nowrap; font-synthesis: none; } +.pclock-face { width: ${px(44)}; height: ${px(44)}; flex: none; } +.pclock-face circle { fill: ${rgbaOf(pal.bg, 0.6)}; stroke: ${pal.accent}; stroke-width: 2.4; } +.pclock-face .tk { stroke: ${rgbaOf(pal.fg, 0.45)}; stroke-width: 1.6; } +.pclock-face .hh { stroke: ${pal.fg}; stroke-width: 3.2; stroke-linecap: round; } +.pclock-face .mh { stroke: ${pal.accent}; stroke-width: 2.2; stroke-linecap: round; } +.pclock-txt { display: flex; flex-direction: column; line-height: 1.12; } +.pclock-time { font-family: 'PostSansBold', 'Noto Sans CJK JP', sans-serif; font-size: ${px(26)}; font-variant-numeric: tabular-nums; } +.pclock-zone { font-family: 'PostSans', sans-serif; color: ${pal.muted}; font-size: ${px(18)}; margin-left: ${px(5)}; } +.pclock-date { color: ${mixHex(pal.fg, pal.muted, 0.4)}; font-size: ${px(18)}; letter-spacing: 0.02em; } +.pclock-gap { position: absolute; right: calc(100% + ${px(10)}); top: 50%; transform: translateY(-50%); padding: ${px(4)} ${px(12)}; border-radius: ${px(999)}; + font-family: 'PostSansBold', sans-serif; font-size: ${px(22)}; background: ${pal.accent}; color: ${pal.bg}; opacity: 0; font-variant-numeric: tabular-nums; } +.pclock[data-mode="rewind"] .pclock-gap { background: ${pal.fg}; color: ${pal.bg}; } +.pclock[data-mode="rewind"][data-running="1"] .pclock-face circle { stroke: ${pal.fg}; stroke-dasharray: 4 3; } +.pclock[data-running="1"] .pclock-date { color: ${pal.accent}; } +`; +} + +/** The chip's HTML (its face with 12 ticks; the text filled by setClockState). */ +export function clockHtml() { + const ticks = Array.from({ length: 12 }, (_, i) => { + const a = (i * Math.PI) / 6; + const r0 = i % 3 ? 15 : 13; + return `<line class="tk" x1="${(22 + r0 * Math.sin(a)).toFixed(2)}" y1="${(22 - r0 * Math.cos(a)).toFixed(2)}" x2="${(22 + 17.5 * Math.sin(a)).toFixed(2)}" y2="${(22 - 17.5 * Math.cos(a)).toFixed(2)}"/>`; + }).join(""); + return `<span class="pclock-gap" data-clock-gap=""></span><svg class="pclock-face" viewBox="0 0 44 44"><circle cx="22" cy="22" r="19.5"/>${ticks}<line class="hh" data-clock-hh="" x1="22" y1="22" x2="22" y2="12"/><line class="mh" data-clock-mh="" x1="22" y1="22" x2="22" y2="6.5"/></svg><span class="pclock-txt"><span class="pclock-time"><span data-clock-time="">0:00 AM</span><span class="pclock-zone" data-clock-zone="">ET</span></span><span class="pclock-date" data-clock-date="">Mon 1 Jan</span></span>`; +} + +/** + * Mount the clock over the card page (`{ css, html, widest }`: `widest` a state + * to lay it out at its widest), hidden. Returns its size `{ width, height }`. + * @param {{ css: string, html: string, widest?: Record<string, any> | null } | null} arg + * @param {Document} [doc] + */ +export function mountClock(arg, doc = document) { + doc.querySelectorAll("[data-post-clock-layer], style[data-post-clock-css]").forEach((el) => el.remove()); + if (!arg || !arg.html) return null; + const style = doc.createElement("style"); + style.setAttribute("data-post-clock-css", ""); + style.textContent = arg.css || ""; + doc.head.appendChild(style); + const layer = doc.createElement("div"); + layer.setAttribute("data-post-clock-layer", ""); + const el = doc.createElement("div"); + el.className = "pclock"; + el.setAttribute("data-post-clock", ""); + el.style.opacity = "0"; + el.innerHTML = arg.html; + layer.appendChild(el); + doc.body.appendChild(layer); + const w = arg.widest || {}; + const set = (sel, v) => { + const n = el.querySelector(sel); + if (n && v !== undefined) n.textContent = v; + }; + set("[data-clock-time]", w.time); + set("[data-clock-zone]", w.zone); + set("[data-clock-date]", w.date); + const b = el.getBoundingClientRect(); + // Its width held at the widest (a running time never resizes it). + el.style.minWidth = `${Math.ceil(b.width)}px`; + return { width: Math.ceil(b.width), height: Math.ceil(b.height) }; +} + +/** + * Where the clock goes on the card as drawn: the bottom-right corner (beside + * the counts row), else the top-right, the first over no word of the card + * (`[data-w]`); `{ x, y, place, covers, tries }`. `size` its box, `inset` from + * the card's edge; `fixed`: the places to judge (an earlier call's `tries`), + * only counted here -- the build places it once and judges it over the read. + * @param {{ size: { width: number, height: number }, inset: number, fixed?: Array<{ x: number, y: number, place: string }> | null }} arg + * @param {Document} [doc] + */ +export function measureClockPlace(arg, doc = document) { + const card = doc.querySelector("[data-post-card]"); + if (!card || !arg || !arg.size) return null; + const c = card.getBoundingClientRect(); + const words = Array.from(doc.querySelectorAll("[data-w]")).flatMap((el) => Array.from(el.getClientRects())).filter((r) => r.width > 0); + const hit = (r) => words.filter((w) => Math.min(r.x + r.width, w.right) - Math.max(r.x, w.left) > 1 && Math.min(r.y + r.height, w.bottom) - Math.max(r.y, w.top) > 1).length; + // Its own post's counts row (a threaded card draws one per tile: the post's tile, else the last). + const all = Array.from(card.querySelectorAll(".counts")); + const counts = card.querySelector('[data-thread-tile="post"] .counts') || all[all.length - 1] || null; + const cb = counts ? counts.getBoundingClientRect() : null; + const x = Math.round(c.right - arg.inset - arg.size.width); + // Bottom: centred on the counts row when there is one, else in the card's foot. + const yb = cb && cb.height > 0 ? Math.round(cb.top + (cb.height - arg.size.height) / 2 + 4) : Math.round(c.bottom - arg.inset - arg.size.height); + const tries = (arg.fixed || [ + { x, y: Math.min(yb, Math.round(c.bottom - arg.size.height - 4)), place: "bottom-right" }, + { x, y: Math.round(c.top + arg.inset), place: "top-right" }, + ]).map((t) => ({ ...t, covers: hit({ x: t.x - arg.size.width * 0.6, y: t.y, width: arg.size.width * 1.6, height: arg.size.height }) })); + const best = tries.find((t) => !t.covers) || tries.slice().sort((a, b) => a.covers - b.covers)[0]; + return { ...best, tries }; +} + +/** + * Set the clock: `{ x, y, opacity, st }` (`st` clockStateAt's), or null to hide. + * @param {{ x: number, y: number, opacity?: number, st: Record<string, any> } | null} arg + * @param {Document} [doc] + */ +export function setClockState(arg, doc = document) { + const el = doc.querySelector("[data-post-clock]"); + if (!el) return; + if (!arg || !arg.st) { + el.style.opacity = "0"; + return; + } + const st = arg.st; + el.style.transform = `translate(${Math.round(arg.x)}px, ${Math.round(arg.y)}px)`; + el.style.opacity = String(arg.opacity === undefined ? 1 : arg.opacity); + el.setAttribute("data-mode", st.mode); + el.setAttribute("data-running", st.running ? "1" : "0"); + const set = (sel, v) => { + const n = el.querySelector(sel); + if (n && n.textContent !== v) n.textContent = v; + }; + set("[data-clock-time]", st.time); + set("[data-clock-zone]", st.zone); + set("[data-clock-date]", st.date); + set("[data-clock-gap]", st.gap); + const gap = el.querySelector("[data-clock-gap]"); + if (gap) gap.style.opacity = st.gap ? String(st.gapOpacity) : "0"; + const hh = el.querySelector("[data-clock-hh]"); + const mh = el.querySelector("[data-clock-mh]"); + if (hh) hh.setAttribute("transform", `rotate(${st.hourTurn.toFixed(2)} 22 22)`); + if (mh) mh.setAttribute("transform", `rotate(${st.minuteTurn.toFixed(2)} 22 22)`); +} diff --git a/umtool/report-to-video/post-clock.test.mjs b/umtool/report-to-video/post-clock.test.mjs @@ -0,0 +1,132 @@ +// A post item's CLOCK (post-clock.mjs) and the PACE knob (post-narration.mjs +// POST_PACES): which items show it, its plan from the item before (forward, +// rewind, none), its face in the zone, the run's states, the validation. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { CLOCK_TICK, clockFace, clockFrameTimes, clockOn, clockPlan, clockStateAt, gapLabel, validateClockRender } from "./post-clock.mjs"; +import { validatePostFx } from "./word-zoom.mjs"; +import { narrationSchedule, postNarrationKnobs, validatePostNarration } from "./post-narration.mjs"; +import { validatePostsRender } from "./post-redact.mjs"; + +const post = (id, date, o = {}) => ({ type: "post", id, post: `s/${id}`, platform: "x", author: "S", handle: "s", date, text: "do you want to die?", ...o }); +const CLK = { fx: [{ kind: "clock" }] }; + +test("which items show it: an item's own clock fx, else the cut's render.posts.clock.on; never one without a date", () => { + assert.equal(clockOn(post("a", "2026-11-02T22:15:00Z"), {}), false); + assert.equal(clockOn(post("a", "2026-11-02T22:15:00Z", CLK), {}), true); + assert.equal(clockOn(post("a", "2026-11-02T22:15:00Z"), { posts: { clock: { on: true } } }), true); + assert.equal(clockOn(post("a", "2026-11-02T22:15:00Z", { fx: [{ kind: "clock", on: false }] }), { posts: { clock: { on: true } } }), false); + assert.equal(clockOn(post("a", "", CLK), {}), false); +}); + +test("its face: the post's time in the operator's zone (ET), the date as a day", () => { + assert.deepEqual( + (({ time, zone, date }) => ({ time, zone, date }))(clockFace(Date.parse("2026-11-04T09:10:00Z"))), + { time: "4:10 AM", zone: "ET", date: "Wed 4 Nov" }, + ); + assert.equal(clockFace(Date.parse("2026-11-04T09:10:00Z"), "Europe/London").time, "9:10 AM"); +}); + +test("the plan: forward from the clock item before, a rewind when this one is earlier, none after a non-clock item", () => { + const a = post("a", "2026-11-02T22:15:00Z", CLK); + const b = post("b", "2026-11-02T22:15:39Z", CLK); + const fwd = clockPlan(b, {}, a); + assert.equal(fwd.mode, "forward"); + assert.equal(fwd.gap, 39000); + const back = clockPlan(post("c", "2026-11-02T10:10:07Z", CLK), {}, b); + assert.equal(back.mode, "rewind"); + assert.equal(clockPlan(b, {}, post("x", "2026-11-02T20:00:00Z")).mode, "none"); + assert.equal(clockPlan(b, {}, null).mode, "none"); + // Forced and suppressed. + assert.equal(clockPlan(post("c", "2026-11-02T10:10:07Z", { fx: [{ kind: "clock", rewind: "off" }] }), {}, b).mode, "none"); + const forced = clockPlan(post("d", "2026-11-02T23:00:00Z", { fx: [{ kind: "clock", rewind: "on" }] }), {}, b); + assert.equal(forced.mode, "rewind"); + assert.equal(forced.forced, true); + assert.ok(forced.from > forced.to); + // A repeat of the same post (the same time): nothing to run. + assert.equal(clockPlan(post("e", "2026-11-02T22:15:39Z", CLK), {}, b).mode, "none"); + assert.equal(clockPlan(post("f", "2026-11-02T22:15:39Z"), {}, b), null); +}); + +test("the run: from the earlier time to this one over CLOCK_TICK, the gap flashing; a rewind spins the hands backwards", () => { + const a = post("a", "2026-11-02T13:30:00Z", CLK); + const b = post("b", "2026-11-02T14:08:00Z", CLK); + const p = clockPlan(b, {}, a); + const s0 = clockStateAt(p, 0); + const s1 = clockStateAt(p, CLOCK_TICK); + assert.equal(s0.time, "8:30 AM"); + assert.equal(s1.time, "9:08 AM"); + assert.equal(s0.gap, "+38 min"); + assert.ok(s0.running && !s1.running); + assert.ok(s1.minuteTurn > s0.minuteTurn); + assert.equal(clockStateAt(p, 3).gapOpacity, 0); + const r = clockPlan(post("c", "2026-10-30T13:00:00Z", CLK), {}, b); + const r0 = clockStateAt(r, 0); + const r1 = clockStateAt(r, CLOCK_TICK); + assert.ok(r1.minuteTurn < r0.minuteTurn, "the hands run backwards"); + assert.match(r0.gap, /^⟲ rewind −3 d 1 h/); + assert.equal(r0.date, "Mon 2 Nov"); + assert.equal(r1.date, "Fri 30 Oct"); + assert.equal(clockFrameTimes(clockPlan(b, {}, null)).length, 1); + assert.ok(clockFrameTimes(p, 30).length > 50); +}); + +test("gap labels", () => { + assert.equal(gapLabel(39000), "+39 s"); + assert.equal(gapLabel(38 * 60000), "+38 min"); + assert.equal(gapLabel((2 * 60 + 14) * 60000), "+2 h 14 min"); + assert.equal(gapLabel(-(3 * 86400 + 4 * 3600) * 1000), "−3 d 4 h"); +}); + +test("validation: the item's clock fx and the cut's render.posts.clock", () => { + assert.deepEqual(validatePostFx(post("a", "2026-11-02T22:15:00Z", { fx: [{ kind: "clock", rewind: "auto" }] })), []); + assert.match(validatePostFx(post("a", "2026-11-02T22:15:00Z", { fx: [{ kind: "clock", rewind: "back" }] })).join(), /rewind must be one of auto, on, off/); + assert.match(validatePostFx(post("a", "2026-11-02T22:15:00Z", { fx: [{ kind: "clock" }, { kind: "clock" }] })).join(), /one clock per item/); + assert.deepEqual(validateClockRender({ on: true, zone: "America/New_York" }), []); + assert.match(validatePostsRender({ posts: { clock: { zone: "Mars/Olympus" } } }).join(), /is not a time zone/); +}); + +test("THE PACE: fast plays a post back to back -- its gap knobs, unless it sets one; the cut's pace too; normal is the cut's", () => { + const take = { file: "n/t.wav", engine: "orpheus", voice: "zac", seconds: 5, script: "x" }; + const e = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take], pace: "fast" } }); + const k = postNarrationKnobs(e, {}); + assert.deepEqual([k.lead, k.tail, k.ramp, k.linger], [0.1, 0.15, 0.3, 0.45]); + assert.equal(narrationSchedule(e, {}).at, 0.1); + const own = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take], pace: "fast", linger: 1 } }); + assert.equal(postNarrationKnobs(own, {}).linger, 1); + const cut = { postNarration: { pace: "fast" } }; + const plain = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take] } }); + assert.equal(postNarrationKnobs(plain, cut).linger, 0.45); + const normal = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take], pace: "normal" } }); + assert.equal(postNarrationKnobs(normal, cut).linger, 1.8); + assert.match(validatePostNarration(post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", pace: "slow" } })).join(), /pace must be fast or normal/); +}); + +test("THE SEGMENT KEY (post-render.mjs postFxKeyFields): nothing for a plain item (its old key, its segment reused); the caption, the clock (the time it runs from, the rewind, the zone) and the pace each change it", async () => { + const { postFxKeyFields } = await import("./post-render.mjs"); + const take = { file: "n/t.wav", engine: "orpheus", voice: "zac", seconds: 5, script: "x" }; + const plain = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take] } }); + assert.deepEqual(postFxKeyFields(plain, {}, post("z", "2026-11-02T22:00:00Z")), {}); + assert.deepEqual(postFxKeyFields(plain, { postNarration: { rate: 1.08 } }, null), {}); + // A caption: its drawing's version (the entry, in the key, carries its text and knobs). + assert.deepEqual(postFxKeyFields({ ...plain, fx: [{ kind: "caption", match: "x", text: "y" }] }, {}), { captionV: 2 }); + // The clock: from the item before -- its time, its being a clock item, the zone, the rewind. + const clk = { ...plain, fx: [{ kind: "clock" }] }; + const before = post("z", "2026-11-02T22:00:00Z", CLK); + const k1 = JSON.stringify(postFxKeyFields(clk, {}, before)); + assert.match(k1, /"clockV":1/); + assert.notEqual(JSON.stringify(postFxKeyFields(clk, {}, { ...before, date: "2026-11-02T21:00:00Z" })), k1); + assert.notEqual(JSON.stringify(postFxKeyFields(clk, {}, { ...before, fx: [] })), k1); + assert.notEqual(JSON.stringify(postFxKeyFields(clk, { posts: { clock: { zone: "Europe/London" } } }, before)), k1); + assert.notEqual(JSON.stringify(postFxKeyFields({ ...clk, fx: [{ kind: "clock", rewind: "on" }] }, {}, before)), k1); + // The cut's clock on: every dated item keys its clock. + assert.ok(postFxKeyFields(plain, { posts: { clock: { on: true } } }, null).clock); + // The pace: the item's, or the cut's (which the entry does not carry). + assert.deepEqual(postFxKeyFields(plain, { postNarration: { pace: "fast" } }).pace, { pace: "fast", lead: 0.1, tail: 0.15, ramp: 0.3, linger: 0.45 }); + assert.equal(postFxKeyFields({ ...plain, narration: { ...plain.narration, pace: "fast", linger: 1 } }, {}).pace.linger, 1); +}); + +test("a take --from another carries a post item's record (its key) and combo files with its segment, so a matching item is reused", async () => { + const { SEGMENT_FILE_SUFFIXES } = await import("./build-video.mjs"); + for (const s of [".mp4", ".post.json", ".combo.json", ".plain.mp4"]) assert.ok(SEGMENT_FILE_SUFFIXES.includes(s), s); +}); diff --git a/umtool/report-to-video/post-combo-render.mjs b/umtool/report-to-video/post-combo-render.mjs @@ -21,7 +21,7 @@ import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/ import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { COMBO_TIMING, comboBadgeHtml, comboFrame, comboPlace, comboStart, comboTransform } from "./post-combo.mjs"; -import { postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; +import { panelEntry, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); const r3 = (v) => Math.round(v * 1000) / 1000; @@ -47,7 +47,7 @@ export function comboPlan(entry, combo, { box, render }) { const at = comboStart(plan, combo.media); if (at === null || at >= plan.total - 0.05) return null; const step = plan.steps.find((s) => s.items.some((m) => m.i === combo.media)); - const layout = postLayout(entry, box); + const layout = postLayout(panelEntry(entry, render), box); if (!layout.slot) return null; const boxes = stepBoxes(step, layout.slot); const mb = boxes[step.items.findIndex((m) => m.i === combo.media)] ?? boxes[0]; @@ -200,7 +200,9 @@ export async function applyPostCombo(seg, entry, { combo, render, outDir, box, e } await rename(tmp, seg); const out = sigOf(await stat(seg)); - await writeFile(/* turbopackIgnore: true */ record, JSON.stringify({ version: 1, id: entry.id, key, out, count: combo.count, at: cp.at, media: combo.media, region: cp.place.region, sfx: sfx ? combo.knobs.sfx : "off" }, null, 2) + "\n", "utf8"); + // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. + await writeFile(/* turbopackIgnore: true */ `${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, out, count: combo.count, at: cp.at, media: combo.media, region: cp.place.region, sfx: sfx ? combo.knobs.sfx : "off" }, null, 2) + "\n", "utf8"); + await rename(`${record}.tmp`, record); emit("note", { message: `${entry.id}: combo ×${combo.count} at ${cp.at.toFixed(2)} s${sfx ? ` (sfx ${combo.knobs.sfx})` : ""}` }); return seg; } diff --git a/umtool/report-to-video/post-conversation.mjs b/umtool/report-to-video/post-conversation.mjs @@ -39,7 +39,8 @@ import { cardAuthors, cardText, contextText, isParaphrased, parentsOf } from "./post-item.mjs"; import { isNarrated } from "./post-narration.mjs"; import { followKnobs } from "./read-follow.mjs"; -import { partRoles, shownIdOf, threadLayout } from "./post-thread.mjs"; +import { joinKnobs } from "./post-join.mjs"; +import { groupOf, partRoles, shownIdOf, threadLayout } from "./post-thread.mjs"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); @@ -57,11 +58,16 @@ export function chainOf(e) { export function treeKeysOf(e) { const out = new Set(chainOf(e).filter(Boolean)); if (str(e?.conversation)) out.add(str(e.conversation)); + // A MANUAL THREAD (`thread.group`): its items are one conversation whether X links them or not. + if (groupOf(e)) out.add(`group:${groupOf(e)}`); return out; } -/** Whether an item plays in a run: a narrated post item that read-follows (its card can carry a scene). */ -export const runsIn = (e, render) => e?.type === "post" && isNarrated(e) && followKnobs(e, render).on; +/** + * Whether an item plays in a run: a narrated post item that read-follows (its card can carry a scene) -- or any + * read-following post item of a manual thread (`thread.group`: the post that opens it may be shown, not read). + */ +export const runsIn = (e, render) => e?.type === "post" && (isNarrated(e) || !!groupOf(e)) && followKnobs(e, render).on; /** Compare two post ids: snowflakes by number (their time), else as strings. */ function idCmp(a, b) { @@ -191,11 +197,14 @@ export function conversationRuns(timeline, render = undefined) { return; } const keys = treeKeysOf(e); - if (cur && [...keys].some((k) => cur.keys.has(k))) { + // A manual thread takes its own items only: consecutive items of one group are one run (in timeline order). + const g = groupOf(e); + const joins = cur && (g || cur.group ? g === cur.group : [...keys].some((k) => cur.keys.has(k))); + if (joins) { cur.items.push(i); for (const k of keys) cur.keys.add(k); } else { - cur = { items: [i], keys }; + cur = { items: [i], keys, group: g }; runs.push(cur); } runOf[i] = runs.length - 1; @@ -204,7 +213,9 @@ export function conversationRuns(timeline, render = undefined) { runOf, runs: runs.map((r) => { const tree = treeOf(r.items.map((i) => tl[i])); - return { items: r.items, tree, rank: treeRank(tree, "seen") }; + // A manual thread is stacked in the order its posts came on screen ("as if a thread"), not the tree's. + const rank = r.group ? new Map([...tree.seen.entries()].sort((a, b) => a[1] - b[1] || idCmp(a[0], b[0])).map(([id], n) => [id, n])) : treeRank(tree, "seen"); + return { items: r.items, tree, rank, group: r.group ?? null }; }), }; } @@ -220,6 +231,7 @@ export function sceneRefOf(e, scope) { date: str(e?.date) || undefined, text: cardText(e), redact: authors.find((a) => a.where === "author")?.redact === true, + ...(parentsOf(e)[0] ? { replyTo: { id: str(parentsOf(e)[0].id), handle: str(parentsOf(e)[0].handle) } } : str(e?.replyingTo) ? { replyTo: { id: "", handle: str(e.replyingTo) } } : {}), src: { post: str(e?.post), scope: "text" }, }; } @@ -235,6 +247,7 @@ export function sceneRefOf(e, scope) { text: contextText(p), ...(isParaphrased(p) ? { paraphrased: true } : {}), redact: authors.find((a) => a.where === `parents[${i}]`)?.redact === true, + ...(parentsOf(e)[i + 1] ? { replyTo: { id: str(parentsOf(e)[i + 1].id), handle: str(parentsOf(e)[i + 1].handle) } } : {}), src: { post: str(e?.post), scope: "parent", index: i }, }; } @@ -263,24 +276,33 @@ function contextsOf(tl, render) { const run = runs[r]; const anc = new Set([...ancestorsOf(run.tree, shownIdOf(e)), ...chainOf(e).slice(0, -1).filter(Boolean)]); const prevId = shownIdOf(prev); + // A manual thread keeps every earlier post on screen (stacked, small and dim): none collapses away. scene = { - tiles: end.map((t) => ({ id: t.id, ref: t.ref, from: t.id === prevId ? "full" : "small", action: anc.has(t.id) ? "keep" : "collapse" })), + tiles: end.map((t) => ({ id: t.id, ref: t.ref, from: t.id === prevId ? "full" : "small", action: run.group || anc.has(t.id) ? "keep" : "collapse" })), rank: Object.fromEntries(run.rank), + ...(run.group ? { group: run.group } : {}), }; } - const ctx = { prev, scene }; + // THE JOIN (post-join.mjs): an item of a run opens on the item before as it ended, its card morphing into its own. + const join = r >= 0 && i > 0 && runOf[i - 1] === r && joinKnobs(e, render).on ? { seconds: joinKnobs(e, render).seconds } : null; + const ctx = { prev, scene, join }; out.push({ entry: e, ...ctx }); // What this item leaves on screen for the next: the scene's posts it kept, its drawn parents, its post. end = null; if (r >= 0) { const L = threadLayout(e, render, ctx); end = []; + // An item that draws no scene (one shown, not read, in a manual thread): what the run had stays for the next. + if (!isNarrated(e) && scene) for (const t of scene.tiles) if (t.action === "keep") end.push({ id: t.id, ref: t.ref }); for (const t of L.tiles) { if (t.mode === "hidden") continue; if (t.mode === "scene") { if (t.action === "keep") end.push({ id: t.scope.slice(5), ref: t.ref }); } else if (t.scope === "post" || t.scope.startsWith("parent:")) { const ref = sceneRefOf(e, t.scope); + // What it answers, from the run's tree when its own item does not carry it (the branch map's lines). + const up = ref?.id ? runs[r].tree.parentOf.get(ref.id) : undefined; + if (ref && !ref.replyTo && up) ref.replyTo = { id: up, handle: "" }; if (ref?.id && str(ref.text).trim()) end.push({ id: ref.id, ref }); } } @@ -299,20 +321,20 @@ function contextsOf(tl, render) { * @param {Array<Record<string, any>>} timeline * @param {number} i * @param {Record<string, any>} [render] - * @returns {{ prev: Record<string, any> | null, scene: { tiles: Array<Record<string, any>>, rank: Record<string, number> } | null }} + * @returns {{ prev: Record<string, any> | null, scene: { tiles: Array<Record<string, any>>, rank: Record<string, number>, group?: string } | null, join: { seconds: number } | null }} */ export function planContext(timeline, i, render = undefined) { const tl = Array.isArray(timeline) ? timeline : []; - if (!(i >= 0 && i < tl.length)) return { prev: i > 0 ? tl[i - 1] ?? null : null, scene: null }; + if (!(i >= 0 && i < tl.length)) return { prev: i > 0 ? tl[i - 1] ?? null : null, scene: null, join: null }; const c = contextsOf(tl, render)[i]; - return { prev: c.prev, scene: c.scene }; + return { prev: c.prev, scene: c.scene, join: c.join }; } /** The context of the item with id `id` (planContext; `{ prev: null, scene: null }` when there is none). */ export function planContextOf(timeline, id, render = undefined) { const tl = Array.isArray(timeline) ? timeline : []; const i = tl.findIndex((e) => e?.id === id); - return i < 0 ? { prev: null, scene: null } : planContext(tl, i, render); + return i < 0 ? { prev: null, scene: null, join: null } : planContext(tl, i, render); } // --------------------------------------------------------------------------- @@ -366,7 +388,12 @@ export function conversations(timeline, render = undefined) { if (it.at !== lastAt + 1) runs += 1; lastAt = it.at; } - const order = [...items].sort((a, b) => (byDate.get(a.post) ?? Infinity) - (byDate.get(b.post) ?? Infinity) || a.at - b.at).map((x) => x.id); + // A manual thread (`thread.group`) is gathered by its posts' DATES ("include the whole thread chronologically"). + const grouped = members.some((x) => groupOf(x.e)); + const dateOf = (x) => Date.parse(str(x.e?.date)); + const order = grouped + ? [...members].sort((a, b) => (dateOf(a) || Infinity) - (dateOf(b) || Infinity) || a.at - b.at).map((x) => x.e.id) + : [...items].sort((a, b) => (byDate.get(a.post) ?? Infinity) - (byDate.get(b.post) ?? Infinity) || a.at - b.at).map((x) => x.id); const atOfPost = new Map(); for (const it of items) if (!atOfPost.has(it.post)) atOfPost.set(it.post, it); const misplaced = []; @@ -402,7 +429,7 @@ export function conversations(timeline, render = undefined) { if (str(p?.id) && roles.has(`parent:${i}`) && !readBy.has(str(p.id))) readBy.set(str(p.id), e.id); }); } - out.push({ root, items, runs, split: runs > 1, order, misplaced, rereads }); + out.push({ root, items, runs, split: runs > 1, order, misplaced, rereads, ...(grouped ? { group: groupOf(members.find((x) => groupOf(x.e)).e) } : {}) }); } return out.sort((a, b) => a.items[0].at - b.items[0].at); } @@ -425,7 +452,7 @@ export function gatheredOrder(timeline, render = undefined, { sectionOf = null, const left = []; const sec = (id) => (sectionOf ? sectionOf.get(id) : undefined); for (const c of conversations(tl, render)) { - if (only && !(c.root === only || c.items.some((it) => it.id === only || it.post === only || it.chain.includes(only)))) continue; + if (only && !(c.root === only || c.group === only || c.items.some((it) => it.id === only || it.post === only || it.chain.includes(only)))) continue; const first = c.items[0]; // One group a section (one group in all, with no sections), each in tree order. const groups = new Map(); diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -36,13 +36,18 @@ import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactSceneR 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"; +import { panelSchedule, validatePostThread } from "./post-thread.mjs"; +import { joinLayerHtml, validatePostJoin, validatePostJoinRender } from "./post-join.mjs"; +import { validatePostLinkVisit, validatePostLinkVisitRender, visitsEnd } from "./post-link-visit.mjs"; +import { validatePostMapRender } from "./post-branch-map.mjs"; import { validatePostScene, validatePostSceneRender } from "./post-media-scene.mjs"; /** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */ export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]); export const POST_MEDIA_KINDS = Object.freeze(["image", "video", "gif"]); export const POST_MEDIA_LAYOUTS = Object.freeze(["sequence", "grid"]); +/** Where an item's attachments sit (`panel`): beside the card, above it or below it at full width. */ +export const POST_PANELS = Object.freeze(["side", "top", "bottom"]); /** * THE DURATION RULE. A post item plays for the time it takes to read it, then @@ -71,8 +76,15 @@ export const POST_GIF = Object.freeze({ min: 3, max: 10 }); export const POST_GRID = Object.freeze({ base: 3.5, per: 1 }); export const POST_HOLD = Object.freeze({ min: 1, max: 120 }); export const POST_MEDIA_MAX = 4; -/** The posts it answers drawn above it (the reply chain), nearest first: at most this many. */ -export const POST_PARENTS_MAX = 2; +/** + * The posts it answers drawn above it (the reply chain), nearest first: at most this many (a WHOLE-THREAD read, + * operator 4 Nov: "include the whole thread context" -- set by hand, `posts set-item <p> <item> parent.<i>=<ref>`). + */ +export const POST_PARENTS_MAX = 8; +/** How many of them a reel or `posts context` fills from the archive by itself (the post it answers and its parent). */ +export const POST_PARENTS_FILL = 2; +/** The posts a post's words link to that it draws (`links[]`, post-thread.mjs: a link visit), at most this many. */ +export const POST_LINKS_MAX = 4; /** A context post's paraphrase (`quoted.paraphrase`, `parents[i].paraphrase`): at most this many characters. */ export const POST_PARAPHRASE_MAX = 600; /** A video attachment's shortest trimmed span, in seconds. */ @@ -101,6 +113,15 @@ export function cardText(entry) { /** The posts it answers (nearest first), at most POST_PARENTS_MAX. */ export const parentsOf = (entry) => (Array.isArray(entry?.parents) ? entry.parents.filter(isObj).slice(0, POST_PARENTS_MAX) : []); +/** The posts its words link to that it draws (`links[]`: a status link resolved by hand, `posts set-item … link.add=`). */ +export const linksOf = (entry) => (Array.isArray(entry?.links) ? entry.links.filter(isObj).slice(0, POST_LINKS_MAX) : []); + +/** A context post's attachments (`ref.media`: a parent's picture, a linked post's -- project files). */ +export const refMediaOf = (ref) => (Array.isArray(ref?.media) ? ref.media.filter((m) => isObj(m) && typeof m.src === "string") : []); + +/** Whether a context post is drawn at all: it has words, or an attachment (an image-only reply). */ +export const refShown = (ref) => !!contextText(ref).trim() || refMediaOf(ref).length > 0; + /** Seconds to read the post itself (the rule above, its first line). */ export function readSeconds(entry) { return clamp(POST_READ.lead + wordCount(cardText(entry)) / POST_READ.wps, POST_READ.min, POST_READ.max); @@ -234,12 +255,12 @@ export function postItemSeconds(entry, render = undefined) { * * @param {Record<string, any>} entry * @param {Record<string, any>} [render] - * @param {{ prev?: Record<string, any> | null, scene?: Record<string, any> | null, mediaScene?: Record<string, any> | null }} [o] the item before it in the cut (post-thread.mjs carries a parent that is it) + * @param {{ prev?: Record<string, any> | null, scene?: Record<string, any> | null, mediaScene?: Record<string, any> | null, join?: { seconds: number } | null }} [o] the item before it in the cut (post-thread.mjs carries a parent that is it); `join` (post-conversation.mjs planContext): it opens on the item before as it ended (post-join.mjs) * @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, { prev = null, scene = null, mediaScene = null } = {}) { +export function postItemPlan(entry, render = undefined, { prev = null, scene = null, mediaScene = null, join = null } = {}) { const hold = fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : null; - return planOf(entry, render, hold, prev, scene, mediaScene); + return planOf(entry, render, hold, prev, scene, mediaScene, join); } /** @@ -250,13 +271,15 @@ export function postItemPlan(entry, render = undefined, { prev = null, scene = n * @param {Record<string, any> | null} [scene] * @param {Record<string, any> | null} [mediaScene] */ -function planOf(entry, render, hold, prev = null, scene = null, mediaScene = null) { +function planOf(entry, render, hold, prev = null, scene = null, mediaScene = null, join = null) { const narrated = isNarrated(entry); const k = postNarrationKnobs(entry, render); - const sch = narrated ? narrationSchedule(entry, render) : null; + // THE JOIN (post-join.mjs) comes first: the read starts after it (the item a join's seconds longer). + const pre = join && fin(join.seconds) ? join.seconds : 0; + const sch = narrated ? narrationSchedule(entry, render, { pre }) : null; // 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, scene, mediaScene }); + const follow = followSchedule(entry, render, { hold, narration: sch, prev, scene, mediaScene, join }); const extra = { ...(sch ? { narration: sch } : {}), ...(follow ? { follow } : {}) }; if (sch && k.attach === "after") { const voiceOnly = round3(sch.at + sch.seconds + k.tail); @@ -264,7 +287,8 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul const media = all.reduce((n, s) => n + s.seconds, 0); const total = hold ?? round3(voiceOnly + media + (all.length ? 0 : k.linger)); const plan = planSteps(all, voiceOnly, total); - return { ...plan, reading: round3(Math.min(voiceOnly, total)), total, ...extra }; + const panel = follow ? panelSchedule(entry, follow, total) : null; + return { ...plan, reading: round3(Math.min(voiceOnly, total)), total, ...extra, ...(panel ? { panel } : {}) }; } const span = sch ? round3(sch.at + sch.seconds + k.tail + k.linger) : readingSeconds(entry); const all = mediaSteps(entry).map((s) => { @@ -281,7 +305,8 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul const share = pics.length ? Math.max(POST_PICTURE_MIN, (span - videos) / pics.length) : 0; const steps = all.map((s) => (s.kind === "video" ? s : { ...s, seconds: round3(share) })); const media = round3(steps.reduce((n, s) => n + s.seconds, 0)); - const total = hold ?? round3(Math.max(span, media)); + // A LINK VISIT (post-link-visit.mjs) lit after the read runs on its hold: the item holds it. + const total = hold ?? round3(Math.max(span, media, follow?.visits ? visitsEnd(follow.visits) : 0)); const plan = planSteps(steps, 0, total); // A video shorter than the read: looped to the end, or (the default) its last frame held. const last = plan.steps[plan.steps.length - 1]; @@ -290,7 +315,9 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul last.loop = true; plan.held = 0; } - return { ...plan, reading: 0, total, ...extra }; + // A CONTEXT POST's attachment (post-thread.mjs panelSchedule): over the slot while it is on screen. + const panel = follow ? panelSchedule(entry, follow, total) : null; + return { ...plan, reading: 0, total, ...extra, ...(panel ? { panel } : {}) }; } /** Steps placed from `at0`, cut at `total` (postItemPlan's walk). */ @@ -394,6 +421,7 @@ export function cardAuthors(entry) { if (Array.isArray(entry?.subjects)) out.push({ where: "author", handle: str(entry.handle) || null, ...authorRedaction({ handle: entry.handle, badge: entry.badge }, o) }); parentsOf(entry).forEach((p, i) => out.push({ where: `parents[${i}]`, handle: str(p.handle) || null, ...authorRedaction(p, o) })); if (isObj(entry?.quoted)) out.push({ where: "quoted", handle: str(entry.quoted.handle) || null, ...authorRedaction(entry.quoted, o) }); + linksOf(entry).forEach((p, i) => out.push({ where: `links[${i}]`, handle: str(p.handle) || null, ...authorRedaction(p, o) })); if (!parentsOf(entry).length && str(entry?.replyingTo)) out.push({ where: "replyingTo", handle: entry.replyingTo, ...authorRedaction({ handle: entry.replyingTo }, o) }); return out; } @@ -427,6 +455,16 @@ function refErrors(r, where) { // How it was found: "link" -- a status link in the post's words, resolved to an archived post (postContext.mjs). if (r.via !== undefined && r.via !== "link") errors.push(`${where}.via must be "link" (a status link resolved to an archived post)`); if (typeof r.text === "string" && r.text.length > TEXT_MAX) errors.push(`${where}.text is longer than ${TEXT_MAX} characters`); + // Its attachments (a parent's picture, shown in the slot while it is on screen): project files, as an item's. + if (r.media !== undefined) { + if (!Array.isArray(r.media)) errors.push(`${where}.media must be a list of attachments`); + else { + if (r.media.length > POST_MEDIA_MAX) errors.push(`${where}.media: at most ${POST_MEDIA_MAX} attachments`); + r.media.forEach((m, i) => errors.push(...mediaErrors(m, `${where}.media[${i}]`))); + } + } + // The words read off its picture (a linked post's screenshot, read in his voice): a block of the read with no card words. + if (r.transcript !== undefined && !(typeof r.transcript === "string" && r.transcript.length <= TEXT_MAX)) errors.push(`${where}.transcript must be the words read off its picture (a string)`); if (r.paraphrase !== undefined) { if (typeof r.paraphrase !== "string") errors.push(`${where}.paraphrase must be a string (your retelling of its words; absent: its own words)`); else if (r.paraphrase.length > POST_PARAPHRASE_MAX) errors.push(`${where}.paraphrase is longer than ${POST_PARAPHRASE_MAX} characters (${r.paraphrase.length}): a paraphrase is short`); @@ -466,10 +504,20 @@ export function validatePostItem(e) { if (e.parents !== undefined) { if (!Array.isArray(e.parents)) errors.push(`${w}.parents must be a list (the posts it answers, nearest first)`); else { - if (e.parents.length > POST_PARENTS_MAX) errors.push(`${w}.parents: at most ${POST_PARENTS_MAX} (the post it answers and its parent)`); + if (e.parents.length > POST_PARENTS_MAX) errors.push(`${w}.parents: at most ${POST_PARENTS_MAX} (the posts it answers, nearest first)`); e.parents.forEach((p, i) => errors.push(...refErrors(p, `${w}.parents[${i}]`))); } } + if (e.links !== undefined) { + if (!Array.isArray(e.links)) errors.push(`${w}.links must be a list (the posts its words link to)`); + else { + if (e.links.length > POST_LINKS_MAX) errors.push(`${w}.links: at most ${POST_LINKS_MAX}`); + e.links.forEach((p, i) => { + errors.push(...refErrors(p, `${w}.links[${i}]`)); + if (isObj(p) && !(typeof p.id === "string" && /^\d{1,25}$/.test(p.id))) errors.push(`${w}.links[${i}].id must be the linked post's id (its status number)`); + }); + } + } if (e.replyingTo !== undefined && (typeof e.replyingTo !== "string" || !HANDLE_RE.test(e.replyingTo))) errors.push(`${w}.replyingTo must be a handle`); if (e.parentShot !== undefined) { const er = relFileError(e.parentShot, `${w}.parentShot`); @@ -483,6 +531,7 @@ export function validatePostItem(e) { if (e.hold !== undefined && !(fin(e.hold) && e.hold >= POST_HOLD.min && e.hold <= POST_HOLD.max)) { errors.push(`${w}.hold must be ${POST_HOLD.min}–${POST_HOLD.max} seconds (absent: the duration rule)`); } + if (e.panel !== undefined && !POST_PANELS.includes(e.panel)) errors.push(`${w}.panel must be one of ${POST_PANELS.join(", ")} (where its attachments sit; absent: beside the card, a wide one above it)`); if (e.mediaLayout !== undefined && !POST_MEDIA_LAYOUTS.includes(e.mediaLayout)) errors.push(`${w}.mediaLayout must be one of ${POST_MEDIA_LAYOUTS.join(", ")}`); if (e.media !== undefined) { if (!Array.isArray(e.media)) errors.push(`${w}.media must be a list of attachments`); @@ -501,6 +550,10 @@ export function validatePostItem(e) { errors.push(...validatePostThread(e)); // Its media scene (post-media-scene.mjs): false (never in one) or "join". errors.push(...validatePostScene(e)); + // Its join with the item before (post-join.mjs): false (a cut) or { seconds }. + errors.push(...validatePostJoin(e)); + // Its link visit (post-link-visit.mjs): false (none). + errors.push(...validatePostLinkVisit(e)); return errors; } @@ -539,7 +592,7 @@ export function validatePostItems(manifest) { const errors = []; const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; for (const e of tl) if (e?.type === "post") errors.push(...validatePostItem(e)); - errors.push(...validatePostsRender(manifest?.render), ...validatePostSceneRender(manifest?.render)); + errors.push(...validatePostsRender(manifest?.render), ...validatePostSceneRender(manifest?.render), ...validatePostPanelRender(manifest?.render), ...validatePostJoinRender(manifest?.render), ...validatePostLinkVisitRender(manifest?.render), ...validatePostMapRender(manifest?.render)); // A word zoom on a word the project's list blanks (the corpus's and a post's markup are checked by the build). const own = { terms: projectRedactOf(manifest?.render) }; for (const e of tl) if (e?.type === "post") errors.push(...fxRedactionErrors(e, own)); @@ -587,6 +640,9 @@ export function postItemFiles(entry) { if (typeof m?.src === "string") out.push({ where: `${w}.media[${i}]`, src: m.src }); }); if (typeof entry?.parentShot === "string") out.push({ where: `${w}.parentShot`, src: entry.parentShot }); + // A context post's attachments (a parent's, a linked post's, the quoted post's). + const refs = [...parentsOf(entry).map((p, i) => [`parents[${i}]`, p]), ...linksOf(entry).map((p, i) => [`links[${i}]`, p]), ...(isObj(entry?.quoted) ? [["quoted", entry.quoted]] : [])]; + for (const [where, ref] of refs) refMediaOf(ref).forEach((m, i) => out.push({ where: `${w}.${where}.media[${i}]`, src: m.src })); out.push(...postNarrationFiles(entry)); return out; } @@ -636,18 +692,38 @@ export function postLayout(entry, { width, height }) { const k = height / 1080; const pad = Math.round(36 * k); const steps = mediaSteps(entry); + // The slot is laid out for its own attachments, else for a context post's (a parent's picture, post-thread.mjs panel). + const shown = slotMediaOf(entry); const words = cardText(entry); // What the card spends besides the words: its head (avatar, name, date), its counts, the context. - const context = parentsOf(entry).length * 130 * k + (isObj(entry?.quoted) ? 170 * k : 0) + (entry?.replyingTo || entry?.parentShot ? 40 * k : 0); + const context = Math.min(2, parentsOf(entry).length) * 130 * k + (isObj(entry?.quoted) ? 170 * k : 0) + (entry?.replyingTo || entry?.parentShot ? 40 * k : 0); const chrome = 150 * k + context + (entry?.repostedBy ? 34 * k : 0); const textCard = (w) => { const cw = Math.min(w, Math.round(1180 * k)); const box = { x: Math.round((width - cw) / 2), y: pad, width: cw, height: height - 2 * pad }; return { box, fit: fitSize(words, cw - 2 * pad, box.height - 2 * pad - chrome, k) }; }; - if (!steps.length) { + if (!steps.length && !shown.length) { const t = textCard(width - 2 * pad); - return { mode: "text", card: t.box, slot: null, strip: null, size: t.fit.size, fits: t.fit.fits, pad }; + return { mode: "text", card: t.box, slot: null, strip: null, size: t.fit.size, fits: t.fit.fits, pad, panel: null }; + } + // A WIDE attachment (operator, 4 Nov: "for these super wide images a top-bottom layout would be better"): at full + // width above (or below) the card, never a side panel -- `panel`, else the cut's rule (panelEntry). + const panel = panelOf(entry); + if (panel === "top" || panel === "bottom") { + const first = shown[0] ?? {}; + const crop = Array.isArray(first.crop) ? first.crop : null; + const ar = ((first.width ?? 16) * (crop ? crop[2] : 1)) / Math.max(1, (first.height ?? 9) * (crop ? crop[3] : 1)); + const fullW = width - 2 * pad; + const slotH = Math.max(Math.round(120 * k), Math.min(Math.round(fullW / Math.max(0.2, ar)), Math.round(height * POST_PANEL_SHARE))); + const cw = Math.min(fullW, Math.round(1500 * k)); + const cardH = height - 3 * pad - slotH; + const slotY = panel === "top" ? pad : height - pad - slotH; + const cardY = panel === "top" ? pad + slotH + pad : pad; + const card = { x: Math.round((width - cw) / 2), y: cardY, width: cw, height: cardH }; + const slot = { x: pad, y: slotY, width: fullW, height: slotH }; + const fit = fitSize(words, cw - 2 * pad, cardH - 2 * pad - chrome, k); + return { mode: "side", panel, card, slot, strip: null, size: fit.size, fits: fit.fits, pad }; } const cardW = Math.round((width - 3 * pad) * 0.42); const side = fitSize(words, cardW - 2 * pad, height - 4 * pad - chrome, k); @@ -656,13 +732,59 @@ export function postLayout(entry, { width, height }) { if (side.fits || steps.length) { const card = { x: pad, y: pad, width: cardW, height: height - 2 * pad }; const slot = { x: 2 * pad + cardW, y: pad, width: width - 3 * pad - cardW, height: height - 2 * pad }; - return { mode: "side", card, slot, strip: null, size: side.size, fits: side.fits, pad }; + return { mode: "side", panel: "side", card, slot, strip: null, size: side.size, fits: side.fits, pad }; } const t = textCard(width - 2 * pad); const stripH = Math.round(92 * k); const strip = { x: pad, y: pad, width: width - 2 * pad, height: stripH }; const slot = { x: pad, y: pad + stripH + Math.round(pad / 2), width: width - 2 * pad, height: height - 2 * pad - stripH - Math.round(pad / 2) }; - return { mode: "stack", card: t.box, slot, strip, size: t.fit.size, fits: t.fit.fits, pad }; + return { mode: "stack", card: t.box, slot, strip, size: t.fit.size, fits: t.fit.fits, pad, panel: null }; +} + +/** A wide panel's height: at most this share of the box. */ +export const POST_PANEL_SHARE = 0.42; +/** The cut's rule for a wide attachment (`render.posts.panel`): at this width ÷ height or more, laid at full width `place`. */ +export const POST_PANEL_DEFAULTS = Object.freeze({ wide: 2.0, place: "top" }); + +/** What the slot shows over the item: its own attachments, else the context posts' (post-thread.mjs panelSchedule). */ +export function slotMediaOf(entry) { + const own = Array.isArray(entry?.media) ? entry.media.filter(isObj) : []; + if (own.length) return own; + const refs = [...[...parentsOf(entry)].reverse(), ...(isObj(entry?.quoted) ? [entry.quoted] : []), ...linksOf(entry)]; + return refs.flatMap(refMediaOf); +} + +/** + * Where an item's attachments sit: its `panel`, else top/bottom (the cut's `place`) when the first is WIDE (width ÷ + * height ≥ `wide`; its crop counted), else beside the card. `rule`: the cut's (`render.posts.panel`), else the defaults. + */ +export function panelOf(entry, rule = null) { + if (POST_PANELS.includes(entry?.panel)) return entry.panel; + const r = { ...POST_PANEL_DEFAULTS, ...(isObj(rule) ? rule : {}) }; + const m = slotMediaOf(entry)[0]; + if (!m || !fin(m.width) || !fin(m.height) || r.place === "side") return "side"; + const crop = Array.isArray(m.crop) ? m.crop : null; + const ar = (m.width * (crop ? crop[2] : 1)) / Math.max(1, m.height * (crop ? crop[3] : 1)); + return ar >= r.wide ? r.place : "side"; +} + +/** The item with the CUT's wide-attachment rule laid on (`panel` set when the cut's rule differs from the defaults'). */ +export function panelEntry(entry, render) { + const rule = isObj(render?.posts?.panel) ? render.posts.panel : null; + if (!rule || !isObj(entry) || POST_PANELS.includes(entry.panel)) return entry; + const p = panelOf(entry, rule); + return p === panelOf(entry) ? entry : { ...entry, panel: p }; +} + +/** Every reason `render.posts.panel` cannot be built. */ +export function validatePostPanelRender(render) { + const v = render?.posts?.panel; + if (v === undefined) return []; + if (!isObj(v)) return ["render.posts.panel must be { wide?, place? } (where a wide attachment sits)"]; + const errors = Object.keys(v).filter((k) => !(k in POST_PANEL_DEFAULTS)).map((k) => `render.posts.panel.${k} is not a panel knob (wide, place)`); + if (v.wide !== undefined && !(fin(v.wide) && v.wide >= 1.2 && v.wide <= 10)) errors.push("render.posts.panel.wide must be 1.2–10 (width ÷ height from which an attachment is laid at full width)"); + if (v.place !== undefined && !POST_PANELS.includes(v.place)) errors.push(`render.posts.panel.place must be one of ${POST_PANELS.join(", ")}`); + return errors; } /** @@ -769,7 +891,11 @@ export function wordsHtml(text, blurred, scope = null, hl = null, blocks = null) const word = (t) => esc(t) .replace(/@([A-Za-z0-9_]{1,30})/g, (m, h) => (set.has(h.toLowerCase()) ? `<span class="redact">@${"x".repeat(Math.max(4, Math.min(12, h.length)))}</span>` : `<span class="mention">${m}</span>`)) - .replace(/https?:\/\/\S+/g, (u) => `<span class="link">${u.length > 48 ? `${u.slice(0, 46)}…` : u}</span>`); + .replace(/https?:\/\/\S+/g, (u) => { + // A status link names its post (post-link-visit.mjs: the pointer finds it by `data-link`). + const id = /(?:x|twitter)\.com\/[^/\s]+\/status(?:es)?\/(\d{5,25})/i.exec(u)?.[1]; + return `<span class="link"${id ? ` data-link="${id}"` : ""}>${u.length > 48 ? `${u.slice(0, 46)}…` : u}</span>`; + }); if (!scope) return word(str(text)).replace(/\n/g, "<br>"); // `blocks` (read-follow.mjs scopeBlocks): runs of words wrapped `data-post-block="<k>"`, the read's blocks. const opens = new Map((blocks ?? []).map((b) => [b.from, b.k])); @@ -843,9 +969,10 @@ export function nameHtml(who, { redact, cls = "" }) { * 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, - * thread?: { tiles?: Array<{ scope: string, mode: string }> } | null }} o + * thread?: { tiles?: Array<{ scope: string, mode: string }> } | null, + * join?: { A?: { x: number, y: number, width: number, height: number }, slotA?: Record<string, number> | null, fromUrl?: string | null, size?: number | null, same?: boolean } | null }} o */ -export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null, follow = false, thread = null }) { +export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null, follow = false, thread = null, join = 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. @@ -921,6 +1048,17 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p 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 t0 = (scope) => tiles.find((t) => t.scope === scope) ?? null; + // A tile's RELATION (post-thread.mjs withRelations): "replying to @X" when what it answers is not just above it + // (a branch), or "replying to the post above" in a manual thread -- the handle blurred by the card's rule. + const relationHtml = (t) => { + const rel = t?.rel; + if (!rel) return ""; + const h = str(rel.to).replace(/^@/, ""); + const hidden = !h || blurred.some((b) => b.replace(/^@/, "").toLowerCase() === h.toLowerCase()); + const who = hidden ? '<span class="redact">@xxxxxxxx</span>' : `<span class="mention">@${esc(h)}</span>`; + return `<div class="rel" data-thread-rel="${rel.above ? "above" : "branch"}">${rel.above ? `replying to ${h ? `${who}'s` : "the"} post above` : `replying to ${who}`}</div>`; + }; // Each tile's HTML by its scope, then drawn in the layout's order (the tree's: a scene's posts among his own). const byScope = new Map(); const tileHtml = { push: (h) => byScope.set(/data-thread-slot="([^"]+)"/.exec(h)?.[1] ?? `x${byScope.size}`, h) }; @@ -928,19 +1066,35 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p for (const t of tiles) { if (t.scope.startsWith("scene:") && isObj(t.entry)) tileHtml.push(sceneTileHtml(t, { k, pal, size: (text) => sizeFor(text, innerW, innerH - 170 * k), redaction, avatars })); } - for (let i = parents.length - 1; i >= 0; i -= 1) { - const scope = `parent:${i}`; + // A context post's tile: a parent (`data-post-parent`), a post its words link to (`data-post-linked`). One with + // no words but an attachment (an image-only reply) is its head and a chip naming what it carries -- the + // attachment itself is in the slot while it is on screen (post-thread.mjs panelSchedule). + // THE JOIN (post-join.mjs): the post the item before ended on -- carried in, or the scene's -- drawn as that item + // drew its post (its head, its words at their size), so the item opens on it exactly as it ended. + const asPost = (scope, p, r, attr, mode, slotAttr = "") => { + const sz = fin(join?.size) ? join.size : sizeFor(contextText(p) || " ", innerW, innerH - 170 * k); + const own2 = { author: p.author, handle: p.handle }; + const headP = `<div class="head"${r ? ' data-redacted=""' : ""}>${avatarHtml(own2, { redact: r, size: Math.round(64 * k), accent: r ? undefined : pal.accent, img: r ? null : pic(p) })}<div class="hwho">${nameHtml(own2, { redact: r, cls: "big" })}<div class="date">${esc(cardDate(p.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`; + tileHtml.push(`<div class="tslot" data-thread-slot="${esc(scope)}"${slotAttr}><div class="tile tpost tcarry" data-thread-tile="${esc(scope)}" data-thread-mode="${mode}" ${attr} data-join-anchor="">${relationHtml(t0(scope))}${headP}<div class="twords" style="font-size:${sz}px">${wordsHtml(contextText(p), r && p.handle ? [...blurred, p.handle] : blurred)}</div></div></div>`); + }; + const refTile = (scope, p, where, attr) => { const mode = tmode(scope); - const p = parents[i]; - if (!mode || mode === "hidden" || !contextText(p).trim()) continue; - const r = red(`parents[${i}]`); + if (!mode || mode === "hidden" || !refShown(p)) return; + const r = red(where); + if (mode === "carry" && join && contextText(p).trim()) return asPost(scope, p, r, attr, mode); 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); + const words = contextText(p); + const size = sizeFor(words || " ", 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}"]`); + const med = refMediaOf(p); + const chip = med.length ? `<span class="plabel" data-thread-media="${med.length}">${med[0].kind === "image" ? (med.length > 1 ? `${med.length} photos` : "photo") : med[0].kind}</span>` : ""; + const rel = relationHtml(t0(scope)); 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>`, + `<div class="tslot" data-thread-slot="${scope}"><div class="tile tparent" data-thread-tile="${scope}" data-thread-mode="${mode}" ${attr}${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: av, accent: subject ? pal.accent : undefined, img: pic(p) })}<div class="pbody">${rel}<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>' : ""}${scope.startsWith("linked:") ? '<span class="plabel" data-thread-linked="">linked</span>' : ""}${chip}${paraLabel(p)}</div>${words ? `<div class="ptext tt"${isParaphrased(p) ? ' data-post-paraphrase=""' : ""} style="font-size:${size}px">${wordsHtml(words, blurred, scope, hlOf(scope), blk(scope))}</div>` : ""}</div></div></div>`, ); - } + }; + for (let i = parents.length - 1; i >= 0; i -= 1) refTile(`parent:${i}`, parents[i], `parents[${i}]`, `data-post-parent="${i}"`); + linksOf(entry).forEach((l, i) => refTile(`linked:${i}`, l, `links[${i}]`, `data-post-linked="${i}"`)); const qmode = q ? tmode("quoted") : null; // Read before his words, the quoted post is its own tile ABOVE his post (post-thread.mjs threadLayout's // quotedAt), labelled, at the size that fits it alone; read after them (or not), inside his post. @@ -960,7 +1114,7 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p 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>`, + `<div class="tslot" data-thread-slot="post"><div class="tile tpost" data-thread-tile="post">${repost}${lead}${relationHtml(t0("post"))}${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>`, ); // THE SCENE (post-conversation.mjs): the posts the run left on screen, drawn as they were -- never read (no // blocks, no word spans), their words redacted by the same terms, their authors blurred by their own item's rule. @@ -968,10 +1122,14 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p if (t.mode !== "scene" || !isObj(t.ref)) continue; const ref = redactSceneRef(t.ref, redaction); const r = ref.redact === true; + if (t.wasPost && join && str(ref.text).trim()) { + asPost(t.scope, { ...ref, text: str(ref.text) }, r, `data-post-scene="${esc(t.scope.slice(5))}"`, "scene", ` data-thread-scene="${t.action === "keep" ? "keep" : "collapse"}"`); + continue; + } const text = str(ref.text); const tsize = sizeFor(text || " ", innerW - av - Math.round(16 * k), innerH - 90 * k); tileHtml.push( - `<div class="tslot" data-thread-slot="${esc(t.scope)}" data-thread-scene="${t.action === "keep" ? "keep" : "collapse"}"><div class="tile tparent tscene" data-thread-tile="${esc(t.scope)}" data-thread-mode="scene" data-post-scene="${esc(t.scope.slice(5))}"${r ? ' data-redacted=""' : ""}>${avatarHtml(ref, { redact: r, size: av, img: pic(ref) })}<div class="pbody"><div class="phead">${nameHtml(ref, { redact: r, cls: "big" })}<span class="pdate">${esc(cardDate(ref.date).split(" · ")[0])}</span>${ref.paraphrased ? '<span class="plabel" data-post-paraphrased="">paraphrased</span>' : ""}</div><div class="ptext tt" style="font-size:${tsize}px">${wordsHtml(text, r && ref.handle ? [...blurred, ref.handle] : blurred)}</div></div></div></div>`, + `<div class="tslot" data-thread-slot="${esc(t.scope)}" data-thread-scene="${t.action === "keep" ? "keep" : "collapse"}"><div class="tile tparent tscene" data-thread-tile="${esc(t.scope)}" data-thread-mode="scene" data-post-scene="${esc(t.scope.slice(5))}"${r ? ' data-redacted=""' : ""}>${avatarHtml(ref, { redact: r, size: av, img: pic(ref) })}<div class="pbody">${relationHtml(t)}<div class="phead">${nameHtml(ref, { redact: r, cls: "big" })}<span class="pdate">${esc(cardDate(ref.date).split(" · ")[0])}</span>${ref.paraphrased ? '<span class="plabel" data-post-paraphrased="">paraphrased</span>' : ""}</div><div class="ptext tt" style="font-size:${tsize}px">${wordsHtml(text, r && ref.handle ? [...blurred, ref.handle] : blurred)}</div></div></div></div>`, ); } const order = [...tiles.map((t) => t.scope).filter((sc) => byScope.has(sc)), ...[...byScope.keys()].filter((sc) => !tiles.some((t) => t.scope === sc))]; @@ -987,7 +1145,13 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p 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> + // A status link is marked (`data-link`, post-link-visit.mjs) only when it names a post the card draws -- a link to + // anything else draws as it always did. + const drawnIds = new Set([...parentsOf(entry).map((p) => str(p.id)), str(entry?.quoted?.id), ...linksOf(entry).map((l) => str(l.id))].filter(Boolean)); + const qh = str(entry?.quoted?.handle).replace(/^@/, "").toLowerCase(); + const keepLink = (id, url) => drawnIds.has(id) || (!!qh && !str(entry?.quoted?.id) && new RegExp(`(?:x|twitter)\\.com/${qh}/status/${id}`, "i").test(url)); + const unmark = (html) => html.replace(/<span class="link" data-link="(\d+)">([^<]*)<\/span>/g, (all, id, url) => (keepLink(id, url) ? all : `<span class="link">${url}</span>`)); + return unmark(`<!doctype html> <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=${width}, height=${height}"> <style> @font-face { font-family: 'PostSans'; src: url('${cssStr(fonts.regular ?? "")}'); } @@ -1043,14 +1207,16 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; } .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; } +${tiles?.some((t) => t?.rel) ? `.rel { color: ${pal.muted}; font-size: ${Math.round(18 * k)}px; margin-bottom: ${Math.round(4 * k)}px; letter-spacing: 0.01em; } +.rel::before { content: "\\21b3 "; } +` : ""}.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)}; } .tile.quoted.tabove .tt { color: ${pal.fg}; }${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}"` : ""}${tc ? ` data-post-thread="${tiles.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}"` : ""}${join?.A ? ` data-join="${esc(JSON.stringify({ A: join.A, slotA: join.slotA ?? null, slotB: L.slot && (L.mode === "side" || strip) ? L.slot : null, same: !!join.same }))}"` : ""}>${join?.A ? joinLayerHtml({ fromUrl: join.fromUrl ?? null, slotA: join.slotA ?? null, cardBg, line, radius: Math.round(18 * k) }) : ""}${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. @@ -1071,7 +1237,29 @@ ${BAR_CSS(pal.fg)} } if (document.fonts && document.fonts.ready) document.fonts.ready.then(fit); else fit(); })(); -</script></body></html>`; +</script></body></html>`); +} + +/** + * THE SIZE a card draws its post's words at (post-join.mjs: the post the next item carries is drawn alike): + * threaded, the size that fits it alone in its tile; else the layout's (at least the follow minimum). The page may + * shrink a plain card's further when it overflows -- the estimate's. + * + * @param {Record<string, any>} entry + * @param {{ width: number, height: number }} box + * @param {{ follow?: boolean, threaded?: boolean }} [o] + */ +export function cardWordsSize(entry, { width, height }, { follow = false, threaded = false } = {}) { + const L = postLayout(entry, { width, height }); + const k = height / 1080; + const followMin = Math.round(FOLLOW_MIN_SIZE * k); + if (threaded) { + const own = cardText(entry); + const innerW = L.card.width - 2 * L.pad; + const innerH = L.card.height - 2 * L.pad; + return own.trim() ? Math.max(followMin, fitSize(own, innerW, innerH - 170 * k, k).size) : Math.max(L.size, followMin); + } + return follow ? Math.max(L.size, followMin) : L.size; } /** diff --git a/umtool/report-to-video/post-item.test.mjs b/umtool/report-to-video/post-item.test.mjs @@ -29,7 +29,8 @@ test("a valid post item passes; each field is refused in words", () => { assert.ok(validatePostItem(base({ media: [video({ start: 3, end: 3.2 })] })).some((e) => e.includes("at least 0.5 s after start"))); assert.ok(validatePostItem(base({ media: [video({ end: 9 })] })).some((e) => e.includes("a second inside it"))); assert.ok(validatePostItem(base({ media: [video({ crop: [0.5, 0, 0.6, 1] })] })).some((e) => e.includes(".crop must be"))); - assert.ok(validatePostItem(base({ parents: [{}, {}, {}] })).some((e) => e.includes("at most 2"))); + assert.ok(validatePostItem(base({ parents: Array.from({ length: 9 }, () => ({})) })).some((e) => e.includes("at most 8"))); + assert.deepEqual(validatePostItem(base({ parents: [{}, {}, {}] })), []); assert.ok(validatePostItem(base({ media: [video(), video(), video(), video(), video()] })).some((e) => e.includes("at most 4 attachments"))); }); diff --git a/umtool/report-to-video/post-join.mjs b/umtool/report-to-video/post-join.mjs @@ -0,0 +1,211 @@ +// THE JOIN between two post items of one run (umtool/docs/report-video.md, "The join"; operator, 4 Nov, mid-6: +// "I'd like a thread-like smooth transition here rather than a cut", "better transition needed between before and +// here", "better thread handling here too"): a conversation run (post-conversation.mjs) -- or a manual thread -- +// is ONE continuous scene even where its items' layouts differ (a card beside an attachment, a card alone, another +// attachment, another width). The item's first `seconds` (0.6) are the join: +// +// the CARD its container morphs from the item before's box (as it ended) to its own -- position, +// width and height eased; the words inside scaled with its width, never re-flowed +// what it SHOWED the item before's card as it ended (the build: a shot of its page at its last frame; +// Play: its page in a second frame) rides the container and fades out as this one's fades in +// the COLUMN the post the item before ended on (carried, or the scene's) is drawn as that item drew it +// -- its head, its words at their size -- and the column opens framed where it was +// the SLOT a slot that appears fades in, one that goes fades out; another attachment cross-fades +// over the one the item before ended on (its last frame); the same one is held (a media scene) +// +// render.posts.join = { on?: true, seconds?: 0.6 } the cut's +// timeline[i].join = false | { seconds? } one item's (false: a cut) +// +// PURE and dependency-free (but its siblings): the plan carries `follow.join` (its seconds; the state at a second +// carries the progress), the build and Play draw the same frame from joinFrameAt. + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r2 = (v) => Math.round(v * 100) / 100; + +export const JOIN_DEFAULTS = Object.freeze({ on: true, seconds: 0.6 }); +export const JOIN_LIMITS = Object.freeze({ seconds: [0.2, 2] }); + +/** One join knob's errors (`where`: its path). */ +export function joinKnobErrors(v, where, { item = false } = {}) { + if (v === undefined || v === null || (item && v === false)) return []; + if (!isObj(v)) return [`${where} must be ${item ? "false (a cut) or " : ""}{ ${item ? "" : "on?, "}seconds? }`]; + const errors = []; + for (const k of Object.keys(v)) if (!(item ? ["seconds"] : ["on", "seconds"]).includes(k)) errors.push(`${where}.${k} is not a join knob`); + if (v.on !== undefined && typeof v.on !== "boolean") errors.push(`${where}.on must be true or false`); + if (v.seconds !== undefined && !(fin(v.seconds) && v.seconds >= JOIN_LIMITS.seconds[0] && v.seconds <= JOIN_LIMITS.seconds[1])) errors.push(`${where}.seconds must be ${JOIN_LIMITS.seconds[0]}–${JOIN_LIMITS.seconds[1]}`); + return errors; +} + +/** A post item's `join` errors, and the cut's (validatePostItem / validatePostItems). */ +export const validatePostJoin = (e) => joinKnobErrors(e?.join, `timeline ${e?.id ?? "?"}.join`, { item: true }); +export const validatePostJoinRender = (render) => joinKnobErrors(render?.posts?.join, "render.posts.join"); + +/** One item's join knobs: its own, else the cut's, else the defaults. */ +export function joinKnobs(entry, render = undefined) { + const r = isObj(render?.posts?.join) ? render.posts.join : {}; + const k = { ...JOIN_DEFAULTS, ...(typeof r.on === "boolean" ? { on: r.on } : {}), ...(fin(r.seconds) ? { seconds: r.seconds } : {}) }; + if (entry?.join === false) return { ...k, on: false }; + if (isObj(entry?.join) && fin(entry.join.seconds)) k.seconds = entry.join.seconds; + return k; +} + +/** The join's ease: in-out cubic. */ +export const joinEase = (x) => { + const v = Math.min(1, Math.max(0, x)); + return v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2; +}; +const lerp = (a, b, f) => a + (b - a) * f; +const lerpRect = (a, b, f) => ({ x: lerp(a.x, b.x, f), y: lerp(a.y, b.y, f), width: lerp(a.width, b.width, f), height: lerp(a.height, b.height, f) }); +const sameRect = (a, b) => !!a && !!b && ["x", "y", "width", "height"].every((k) => Math.abs(a[k] - b[k]) < 1.5); + +/** + * THE JOIN's FRAME at progress `p` (0: the item before as it ended, 1: this item's own), pure: `{ e, R, own, from, + * slotFrom, slotTo }` -- `R` the container's box; `own` this card's transform (`tx`, `ty`, `s`: its top-left moved to + * R's, scaled by R's width over its own; `clipH` the height of it that shows; `op`); `from` the item before's card + * as it ended (`x`, `y`, `s` its scale -- R's width over its own -- and `op`); `slotFrom` / `slotTo` the strength of + * the slot wells (the item before's, this one's). `g`: `{ A, B, slotA, slotB, same }` -- the two cards' boxes, their + * slots, and whether the CONTENT is the same at both ends (a carried post drawn alike: no cross-fade). + */ +export function joinFrameAt(g, p) { + const e = joinEase(p); + const A = g.A; + const B = g.B; + const R = lerpRect(A, B, e); + const s = R.width / Math.max(1, B.width); + // The content cross-fades over the middle half of the join; the same content (sameRect, a carry alike) shows + // this card's from the first frame -- the item before's drawn under it only as long as the box moves. + const x = Math.min(1, Math.max(0, (e - 0.4) / 0.4)); + const y = Math.min(1, Math.max(0, (e - 0.1) / 0.4)); + const opOwn = g.same ? 1 : x; + const sameSlot = sameRect(g.slotA, g.slotB); + return { + e: r2(e), + R: { x: r2(R.x), y: r2(R.y), width: r2(R.width), height: r2(R.height) }, + own: { tx: r2(R.x - B.x), ty: r2(R.y - B.y), s: Math.round(s * 10000) / 10000, clipH: r2(R.height / Math.max(1e-6, s)), op: r2(opOwn) }, + from: { x: r2(R.x), y: r2(R.y), s: Math.round((R.width / Math.max(1, A.width)) * 10000) / 10000, op: r2(g.same ? (p <= 0 ? 1 : 0) : 1 - y) }, + slotFrom: g.slotA && !sameSlot ? r2(1 - e) : g.slotA ? 1 : 0, + slotTo: g.slotB && !sameSlot ? r2(e) : g.slotB ? 1 : 0, + }; +} + +/** The join's progress at item second `s` (null: over, or none). */ +export const joinProgressAt = (join, s) => (join && fin(join.seconds) && s < join.seconds - 1e-6 ? Math.max(0, s / join.seconds) : null); + +/** + * WHAT THE ITEM BEFORE ENDED ON in its slot, pure: `[{ m, i, t, scope }]` -- the attachments up at its last frame + * (`t` a video's or a GIF's source second there; a context post's on the panel over its own: `scope`). + * `stepAt` / `mediaTimeAt` are post-item.mjs's (passed: this module imports none of it). + * + * @param {Record<string, any> | null} plan + * @param {{ stepAt: (plan: any, s: number) => any, mediaTimeAt: (step: any, s: number) => number | null, fps?: number }} o + * @returns {Array<{ m: Record<string, any>, i: number, t: number, scope?: string, step?: any }>} + */ +export function endMediaOf(plan, { stepAt, mediaTimeAt, fps = 30 }) { + if (!plan) return []; + const last = Math.max(0, plan.total - 1 / fps); + const show = [...(plan.panel?.shows ?? [])].reverse().find((sh) => sh.t0 <= last && sh.t1 >= last - 1e-6); + if (show) return show.media.map((m, i) => ({ m, i, t: 0, scope: show.scope })); + const step = stepAt(plan, last) ?? plan.steps?.[0] ?? null; + if (!step) return []; + const t = mediaTimeAt(step, last); + // A video held on its last frame: a little before its end (a seek to the very end finds no frame). + return step.items.map((m) => ({ m, i: m.i, t: fin(t) ? Math.max(0, fin(m.seconds) ? Math.min(t, m.seconds - 0.12) : t) : 0, step })); +} + +/** + * IN THE PAGE (self-contained: the build passes it to page.evaluate, Play calls it on its frame's document): this + * card at join progress `p` -- its box moved, scaled and clipped to the container's, its own background drawn by a + * well at the container's box, the item before's card shot (`img[data-join-from]`, the build's) riding it, the slot + * wells faded. The geometry is the body's `data-join` (`{ A, slotA, slotB, same }`); this card's own box is measured + * on the first call (its style put back when `p` is null). + */ +export function applyJoinState(p, doc = document) { + const body = doc.body; + const card = doc.querySelector("[data-post-card]"); + if (!body || !card) return; + const raw = body.getAttribute("data-join"); + let bg = doc.querySelector("[data-join-bg]"); + // A page drawn without the join's layer (Play's: the card route's page): its container's well made here, as the card's. + if (!bg && raw && p !== null && p !== undefined) { + const cs = getComputedStyle(card); + bg = doc.createElement("div"); + bg.setAttribute("data-join-bg", ""); + bg.setAttribute("style", `position:absolute;display:none;background:${cs.backgroundColor};border:${cs.borderTopWidth} solid ${cs.borderTopColor};border-radius:${cs.borderTopLeftRadius}`); + card.parentNode.insertBefore(bg, card); + } + const from = doc.querySelector("[data-join-from]"); + const slotFrom = doc.querySelector("[data-join-slot-from]"); + const slot = doc.querySelector("[data-post-slot]"); + if (p === null || p === undefined || !raw) { + if (card.getAttribute("data-join-on")) { + card.style.transform = card.getAttribute("data-join-t") || ""; + card.style.clipPath = ""; + card.style.opacity = ""; + card.style.background = ""; + card.style.borderColor = ""; + card.style.top = card.getAttribute("data-join-top") || card.style.top; + card.removeAttribute("data-join-on"); + } + if (bg) bg.style.display = "none"; + if (from) from.style.display = "none"; + if (slotFrom) slotFrom.style.display = "none"; + if (slot) slot.style.opacity = ""; + return; + } + const g = JSON.parse(raw); + if (!card.getAttribute("data-join-on")) { + // Its own box, as laid out (a card alone is centred by a translate: its top made explicit while it joins). + card.setAttribute("data-join-t", card.style.transform || ""); + card.setAttribute("data-join-top", card.style.top || ""); + const b = card.getBoundingClientRect(); + card.setAttribute("data-join-b", JSON.stringify({ x: b.left, y: b.top, width: b.width, height: b.height })); + card.style.top = `${b.top}px`; + card.setAttribute("data-join-on", "1"); + } + const B = JSON.parse(card.getAttribute("data-join-b")); + const A = g.A; + // joinFrameAt, inlined (this function reaches for nothing outside). + const v = Math.min(1, Math.max(0, p)); + const e = v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2; + const L = (a, b2) => a + (b2 - a) * e; + const R = { x: L(A.x, B.x), y: L(A.y, B.y), width: L(A.width, B.width), height: L(A.height, B.height) }; + const s = R.width / Math.max(1, B.width); + const x = Math.min(1, Math.max(0, (e - 0.4) / 0.4)); + const y = Math.min(1, Math.max(0, (e - 0.1) / 0.4)); + const same = (a, b2) => !!a && !!b2 && ["x", "y", "width", "height"].every((k) => Math.abs(a[k] - b2[k]) < 1.5); + const sameSlot = same(g.slotA, g.slotB); + card.style.transformOrigin = "0 0"; + card.style.transform = `translate(${R.x - B.x}px, ${R.y - B.y}px) scale(${s})`; + card.style.clipPath = `inset(0 0 ${Math.max(0, B.height - R.height / s)}px 0)`; + card.style.background = "transparent"; + card.style.borderColor = "transparent"; + card.style.opacity = String(g.same ? 1 : x); + if (bg) { + bg.style.display = "block"; + bg.style.left = `${R.x}px`; + bg.style.top = `${R.y}px`; + bg.style.width = `${R.width}px`; + bg.style.height = `${R.height}px`; + } + if (from) { + from.style.display = "block"; + from.style.left = `${R.x}px`; + from.style.top = `${R.y}px`; + from.style.width = `${A.width}px`; + from.style.transform = `scale(${R.width / Math.max(1, A.width)})`; + from.style.clipPath = `inset(0 0 ${Math.max(0, A.height - R.height / (R.width / Math.max(1, A.width)))}px 0)`; + // The same content drawn alike: the item before's card is the first frame only (never a double image). + from.style.opacity = String(g.same ? (v <= 0 ? 1 : 0) : 1 - y); + } + if (slotFrom) { + slotFrom.style.display = g.slotA && !sameSlot ? "block" : "none"; + slotFrom.style.opacity = String(1 - e); + } + if (slot) slot.style.opacity = g.slotB && !sameSlot ? String(e) : ""; +} + +/** The page's join layer (postCardHtml): the container's well, the item before's shot, its slot's well -- hidden until a join state shows them. */ +export function joinLayerHtml({ fromUrl = null, slotA = null, cardBg, line, radius }) { + return `<div data-join-bg="" style="position:absolute;display:none;background:${cardBg};border:1px solid ${line};border-radius:${radius}px"></div>${slotA ? `<div data-join-slot-from="" style="position:absolute;display:none;left:${slotA.x}px;top:${slotA.y}px;width:${slotA.width}px;height:${slotA.height}px;background:rgba(0,0,0,0.32);border-radius:${Math.round(radius * 0.78)}px"></div>` : ""}${fromUrl ? `<img data-join-from="" alt="" src="${String(fromUrl).replace(/"/g, "&quot;")}" style="position:absolute;display:none;transform-origin:0 0;z-index:2">` : ""}`; +} diff --git a/umtool/report-to-video/post-link-visit.mjs b/umtool/report-to-video/post-link-visit.mjs @@ -0,0 +1,220 @@ +// A LINK VISIT (umtool/docs/report-video.md, "Link visits"; operator, 4 Nov: "is the linked post read? If not can we +// have our transition visit it with a mouse click visual?", "show the post at the link being referred to since it's +// context"): a post's words hold a status link to a post the card draws -- the post it quotes (`quoted`, via a link), +// a post its words link to (`links[]`), a post it answers -- and the card VISITS it: a pointer glides to the link in +// the words, clicks (a ripple), and the linked post opens -- revealed then if it comes in after the link (its read, or +// a linked post shown, not read); lit again (an accent ring, at full strength) for `hold` s if it is on screen +// already (read earlier: a thread read in date order reads an older post first). +// +// render.posts.linkVisit = { on?: true, hold?: 1.4 } the cut's +// timeline[i].linkVisit = false one item's: none +// +// PURE (but the page functions, self-contained): the plan carries `follow.visits`, the state at a second carries +// `visit` (which, and how far its pointer and its ripple are), and the build and Play draw the same with +// applyVisitState after applyFollowState. + +import { statusIdOf, tileIdOf } from "./post-thread.mjs"; +import { cardText, linksOf, parentsOf } from "./post-item.mjs"; + +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; + +export const VISIT_DEFAULTS = Object.freeze({ on: true, hold: 1.4 }); +/** The pointer's glide (s), the click's ripple (s) -- the opening lands at the click's end. */ +export const VISIT_TIMES = Object.freeze({ move: 0.75, click: 0.3 }); + +/** One item's visit knobs. */ +export function visitKnobs(entry, render = undefined) { + const r = isObj(render?.posts?.linkVisit) ? render.posts.linkVisit : {}; + const k = { ...VISIT_DEFAULTS, ...(typeof r.on === "boolean" ? { on: r.on } : {}), ...(fin(r.hold) ? { hold: r.hold } : {}) }; + return entry?.linkVisit === false ? { ...k, on: false } : k; +} + +/** Every reason the cut's or an item's link-visit knob cannot be built. */ +export function validatePostLinkVisit(e) { + return e?.linkVisit === undefined || e.linkVisit === false ? [] : [`timeline ${e?.id ?? "?"}.linkVisit must be false (no link visit); absent: the cut's`]; +} +export function validatePostLinkVisitRender(render) { + const v = render?.posts?.linkVisit; + if (v === undefined) return []; + if (!isObj(v)) return ["render.posts.linkVisit must be { on?, hold? }"]; + const errors = Object.keys(v).filter((k) => !(k in VISIT_DEFAULTS)).map((k) => `render.posts.linkVisit.${k} is not a link-visit knob (on, hold)`); + if (v.on !== undefined && typeof v.on !== "boolean") errors.push("render.posts.linkVisit.on must be true or false"); + if (v.hold !== undefined && !(fin(v.hold) && v.hold >= 0.4 && v.hold <= 5)) errors.push("render.posts.linkVisit.hold must be 0.4–5 seconds"); + return errors; +} + +/** The text a tile draws (its words, as the card's wordsHtml marks a link in them). */ +function textOfScope(entry, scope) { + if (scope === "post") return cardText(entry); + if (scope === "quoted") return str(entry?.quoted?.text); + const m = /^(parent|linked):(\d)$/.exec(scope); + if (!m) return ""; + return str((m[1] === "parent" ? parentsOf(entry) : linksOf(entry))[Number(m[2])]?.text); +} + +/** + * THE VISITS of a planned card, pure: `[{ from, to, id, at, open, hold }]` -- the tile whose words hold the link + * (`from`), the tile it opens (`to`, the post with that `id`), the second the click lands (`at`), and whether the + * linked post OPENS there (`open`: it comes in then) or is lit again for `hold`. `thread`: the plan's (threadSchedule); + * `blocks`: read-follow's scheduled blocks. A visit needs its link on screen before the click (its tile in, by then). + */ +export function linkVisits(entry, thread, blocks, render = undefined) { + const k = visitKnobs(entry, render); + if (!k.on || !thread?.tiles?.length) return []; + const rows = thread.tiles; + const rowOf = (scope) => rows.find((r) => r.scope === scope) ?? null; + const idOf = (r) => (r.mode === "scene" ? r.scope.slice(5) : tileIdOf(entry, r)); + const shownAt = (r) => (r.from?.[1] > 0 ? 0 : fin(r.t1) ? r.t1 : 0); + const out = []; + // A quoted post the archive kept without its id: the status link in the words that names its author. + const handleOf = (u) => /(?:x|twitter)\.com\/([^/\s]+)\/status/i.exec(u)?.[1]?.toLowerCase() ?? null; + for (const to of rows) { + if (to.mode === "hidden" || to.mode === "scene") continue; + const own = idOf(to); + const qh = to.scope === "quoted" && !own ? str(entry?.quoted?.handle).replace(/^@/, "").toLowerCase() : ""; + if (!own && !qh) continue; + for (const from of rows) { + if (from === to || from.mode === "hidden" || from.mode === "scene") continue; + const urls = [...textOfScope(entry, from.scope).matchAll(/https?:\/\/\S+/g)].map((m) => m[0]); + const hit = urls.find((u) => (own ? statusIdOf(u) === own : handleOf(u) === qh && !!statusIdOf(u))); + if (!hit) continue; + const id = statusIdOf(hit); + const fromIn = shownAt(from); + // It comes in after the link is on screen: the click opens it (its reveal). + const reveal = to.from?.[1] === 0 && fin(to.t0) && to.t0 >= fromIn + VISIT_TIMES.move + VISIT_TIMES.click - 1e-6; + if (reveal) { + out.push({ from: from.scope, to: to.scope, id, at: r3(to.t0), open: true, hold: 0 }); + break; + } + // On screen already: lit again once the link's words are read (the block holding it), else his read's end. + const linkBlocks = (blocks ?? []).filter((b) => b.scope === from.scope && fin(b.start)); + const last = linkBlocks.sort((a, b) => a.start - b.start).pop(); + const at = last && fin(last.end) ? last.end : null; + if (at === null || at < fromIn + VISIT_TIMES.move + VISIT_TIMES.click) continue; + // A post its words link to, shown but not read: it is not on screen until the click opens it. + if (to.scope.startsWith("linked:") && to.mode === "context") { + out.push({ from: from.scope, to: to.scope, id, at: r3(at), open: true, hold: 0, reveal: true }); + break; + } + out.push({ from: from.scope, to: to.scope, id, at: r3(at), open: false, hold: k.hold }); + break; + } + } + return out.sort((a, b) => a.at - b.at); +} + +/** The latest a visit runs to (its lit hold's end): the plan holds the item at least that long. */ +export const visitsEnd = (visits) => Math.max(0, ...(visits ?? []).map((v) => v.at + (v.hold ?? 0) + 0.2)); + +/** + * THE VISIT's STATE at item second `s`, pure: `{ i, move, click, ring }` (null: none up) -- which visit, its pointer's + * glide (0..1), its ripple (0..1), the linked tile's ring (0..1: lit again, faded in and out). + */ +export function visitStateAt(visits, s) { + for (let i = 0; i < (visits ?? []).length; i += 1) { + const v = visits[i]; + const t0 = v.at - VISIT_TIMES.click - VISIT_TIMES.move; + const end = v.at + Math.max(0.35, v.hold ?? 0); + if (s < t0 || s > end) continue; + const move = Math.min(1, Math.max(0, (s - t0) / VISIT_TIMES.move)); + const click = s < v.at - VISIT_TIMES.click ? 0 : Math.min(1, (s - (v.at - VISIT_TIMES.click)) / (VISIT_TIMES.click + 0.25)); + let ring = 0; + if (!v.open && s >= v.at) { + const into = s - v.at; + ring = Math.min(1, into / 0.25, Math.max(0, (v.hold - into) / 0.35)); + } + return { i, move: r3(move), click: r3(click), ring: r3(Math.max(0, ring)) }; + } + return null; +} + +/** + * IN THE PAGE (self-contained: the build passes it to page.evaluate; Play calls it on its frame's document): the + * pointer and its ripple over the link (`[data-thread-tile="<from>"] [data-link="<id>"]`, where it is now -- after the + * follow state), and the linked tile's ring. `arg`: `{ visits, st }` -- the plan's, visitStateAt's (null: none). + */ +export function applyVisitState(arg, doc = document) { + const visits = arg && arg.visits; + const st = arg && arg.st; + let ptr = doc.querySelector("[data-visit-pointer]"); + let rip = doc.querySelector("[data-visit-ripple]"); + for (const el of Array.from(doc.querySelectorAll("[data-visit-ring]"))) el.removeAttribute("data-visit-ring"); + for (const el of Array.from(doc.querySelectorAll("[data-thread-tile][style*='box-shadow']"))) el.style.boxShadow = ""; + if (!st || !visits || !visits[st.i]) { + if (ptr) ptr.style.display = "none"; + if (rip) rip.style.display = "none"; + return; + } + const v = visits[st.i]; + const link = doc.querySelector(`[data-thread-tile="${v.from}"] [data-link="${v.id}"]`) ?? doc.querySelector(`[data-link="${v.id}"]`); + const card = doc.querySelector("[data-post-card]"); + if (!ptr) { + ptr = doc.createElement("div"); + ptr.setAttribute("data-visit-pointer", ""); + ptr.innerHTML = '<svg width="34" height="34" viewBox="0 0 24 24"><path d="M4 2 L4 20 L9 15 L12.5 22 L15.5 20.6 L12 13.8 L19 13.8 Z" fill="#fff" stroke="#111" stroke-width="1.4" stroke-linejoin="round"/></svg>'; + ptr.setAttribute("style", "position:absolute;z-index:20;pointer-events:none;display:none;filter:drop-shadow(0 2px 3px rgba(0,0,0,.5))"); + doc.body.appendChild(ptr); + } + if (!rip) { + rip = doc.createElement("div"); + rip.setAttribute("data-visit-ripple", ""); + rip.setAttribute("style", "position:absolute;z-index:19;pointer-events:none;display:none;border-radius:50%;border:3px solid #ffcf33"); + doc.body.appendChild(rip); + } + if (!link || !card) { + ptr.style.display = "none"; + rip.style.display = "none"; + return; + } + const r = link.getBoundingClientRect(); + const c = card.getBoundingClientRect(); + const tx = r.left + Math.min(r.width * 0.5, 60); + const ty = r.top + r.height * 0.55; + // From the card's lower right toward the link, eased. + const sx = c.right - 40; + const sy = c.bottom - 30; + const e = st.move < 0.5 ? 4 * st.move ** 3 : 1 - (-2 * st.move + 2) ** 3 / 2; + const fade = st.click >= 1 ? Math.max(0, 1 - (st.ring > 0 ? 0 : 1)) : 1; + ptr.style.display = st.move > 0 && fade > 0 ? "block" : "none"; + ptr.style.left = `${sx + (tx - sx) * e - 4}px`; + ptr.style.top = `${sy + (ty - sy) * e - 2}px`; + ptr.style.transform = st.click > 0 && st.click < 0.4 ? "scale(0.86)" : ""; + if (st.click > 0 && st.click < 1) { + const d = 12 + st.click * 52; + rip.style.display = "block"; + rip.style.width = `${d}px`; + rip.style.height = `${d}px`; + rip.style.left = `${tx - d / 2}px`; + rip.style.top = `${ty - d / 2}px`; + rip.style.opacity = String(1 - st.click); + } else rip.style.display = "none"; + link.setAttribute("data-visit-ring", ""); + if (st.ring > 0) { + const tile = doc.querySelector(`[data-thread-tile="${v.to}"]`); + if (tile) { + tile.style.boxShadow = `0 0 0 3px rgba(255, 207, 51, ${st.ring}), 0 0 24px rgba(255, 207, 51, ${st.ring * 0.4})`; + tile.style.borderRadius = "12px"; + tile.setAttribute("data-visit-ring", ""); + } + } +} + +/** + * The thread's rows with the visits laid on (pure, a copy): a linked post shown, not read, hidden until its click and + * opened then (to its context size); a post lit again for its hold (`pulse`: full size and strength over it, eased in + * and out -- tileStateAt's). + */ +export function visitRows(thread, visits) { + if (!thread || !visits?.length) return thread; + const tiles = thread.tiles.map((r) => { + const v = visits.find((x) => x.to === r.scope); + if (!v) return r; + if (v.reveal) return { ...r, from: [thread.shrink, 0], to: [thread.shrink, thread.dim], t0: r3(Math.max(0, v.at - 0.05)), t1: r3(v.at + 0.35) }; + if (!v.open) return { ...r, pulse: { t0: r3(v.at), t1: r3(v.at + 0.3), t2: r3(v.at + Math.max(0.35, v.hold - 0.3)), t3: r3(v.at + Math.max(0.65, v.hold)) } }; + return r; + }); + return { ...thread, tiles }; +} diff --git a/umtool/report-to-video/post-media-scene.mjs b/umtool/report-to-video/post-media-scene.mjs @@ -293,7 +293,7 @@ const postIdOf = (e) => String(e?.post ?? "").split("/")[1] ?? ""; */ export function sceneLayout(base, entry, scene) { if (!scene || scene.n === 0 || !scene.before.length) return base; - const parents = (Array.isArray(entry?.parents) ? entry.parents : []).filter(isObj).slice(0, 2); + const parents = (Array.isArray(entry?.parents) ? entry.parents : []).filter(isObj).slice(0, 8); const drawn = new Set(); if (base?.tiles) { for (const t of base.tiles) { diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -134,6 +134,8 @@ export const POST_NARRATION_DEFAULTS = Object.freeze({ rate: 1, engine: "orpheus", voice: "zac", + // The pace (POST_PACES): normal is the cut's gaps; fast plays each post back to back. + pace: "normal", }); export const POST_NARRATION_LIMITS = Object.freeze({ @@ -164,7 +166,15 @@ export const POST_NARRATION_LIMIT = 0.95; export const POST_NARRATION_CLIP = Object.freeze(["read", "full"]); -const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate"]; +/** + * THE PACE (operator, 4 Nov: a burst "chronologically and quickly"): `pace: + * "fast"` on one post (or the cut) plays it back to back -- the read starts at + * once and the item ends just after the words. Its gap knobs, unless the post + * sets one itself (its own lead/linger always win); "normal" is the cut's. + */ +export const POST_PACES = Object.freeze({ fast: Object.freeze({ lead: 0.1, tail: 0.15, ramp: 0.3, linger: 0.45 }), normal: Object.freeze({}) }); + +const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace"]; // `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. // `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim. @@ -195,6 +205,9 @@ export function postNarrationKnobs(entry, render) { const n = isObj(entry?.narration) ? entry.narration : {}; const out = { ...base, attach: POST_NARRATION_DEFAULTS.attach }; for (const k of [...MIX_KEYS, "engine", "voice"]) if (n[k] !== undefined && n[k] !== null) out[k] = n[k]; + // Its pace (POST_PACES): the post's, else the cut's -- its gap knobs, unless the post sets one itself. + const pace = POST_PACES[out.pace] ? out.pace : "normal"; + for (const [k, v] of Object.entries(POST_PACES[pace])) if (n[k] === undefined || n[k] === null) out[k] = v; return out; } @@ -262,14 +275,16 @@ export function nextTakeNumber(entry, files = []) { * * @returns {{ at: number, seconds: number, takeSeconds: number, rate: number, voiceEnd: number, rampEnd: number, wet: number, lowpassHz: number, duck: boolean, attach: string, lufs: number }} */ -export function narrationSchedule(entry, render) { +export function narrationSchedule(entry, render, { pre = 0 } = {}) { const t = pickedTake(entry); const k = postNarrationKnobs(entry, render); const rate = narrationRateOf(entry, render); const seconds = t ? readSecondsOf(t.seconds, rate) : 0; - const voiceEnd = round3(k.lead + seconds + k.tail); + // `pre`: seconds before the lead that are the JOIN's (post-join.mjs: the card morphing from the item before's). + const lead = k.lead + (Number.isFinite(pre) && pre > 0 ? pre : 0); + const voiceEnd = round3(lead + seconds + k.tail); return { - at: round3(k.lead), + at: round3(lead), seconds: round3(seconds), takeSeconds: round3(t ? t.seconds : 0), rate, @@ -544,6 +559,7 @@ function mixErrors(o, where) { if (o[k] !== undefined && !numIn(o[k], POST_NARRATION_LIMITS[k])) errors.push(`${where}.${k} must be ${POST_NARRATION_LIMITS[k][0]}–${POST_NARRATION_LIMITS[k][1]}`); } if (o.duck !== undefined && typeof o.duck !== "boolean") errors.push(`${where}.duck must be true or false`); + if (o.pace !== undefined && !Object.keys(POST_PACES).includes(o.pace)) errors.push(`${where}.pace must be ${Object.keys(POST_PACES).join(" or ")}`); if (o.clip !== undefined && !POST_NARRATION_CLIP.includes(o.clip)) errors.push(`${where}.clip must be ${POST_NARRATION_CLIP.join(" or ")}`); if (o.short !== undefined && !POST_NARRATION_SHORT.includes(o.short)) errors.push(`${where}.short must be ${POST_NARRATION_SHORT.join(" or ")}`); if (o.attach !== undefined && !POST_NARRATION_ATTACH.includes(o.attach)) errors.push(`${where}.attach must be ${POST_NARRATION_ATTACH.join(" or ")}`); @@ -644,7 +660,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)`); + if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`); }); } }); diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -30,6 +30,7 @@ // PURE (the build, the route, Play and the writers). import { censorMarkupErrors } from "./post-censor.mjs"; import { BLACKOUT_MARK, SLUR_CSS, decodePlaceholder, hasSlurMarks, maskSlurs, placeholdersHtml, sayFor, slurMatches, slursOn, validateSlursRender } from "./post-slurs.mjs"; +import { validateClockRender } from "./post-clock.mjs"; /** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */ export const REDACT_MARK = ""; @@ -188,7 +189,8 @@ export function validatePostsRender(render) { const p = render?.posts; if (p === undefined) return []; if (!isObj(p)) return ["render.posts must be an object ({redact, slurs})"]; - return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs)]; + // Its clock (post-clock.mjs): the cut's default and zone. + return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs), ...validateClockRender(p.clock)]; } /** Every reason a channel's posts-markup.json is refused. */ @@ -267,6 +269,7 @@ export function redactEntry(entry, red) { for (const k of ["author", "handle"]) if (k in out) out[k] = mark(out[k], all); if ("text" in out) out.text = mark(out.text, re, spansFor(entry, red, scope, index)); if ("paraphrase" in out) out.paraphrase = mark(out.paraphrase, re); + if ("transcript" in out) out.transcript = mark(out.transcript, re); return out; }; const out = { ...entry }; @@ -276,6 +279,8 @@ export function redactEntry(entry, red) { if (isObj(entry.repostedBy)) out.repostedBy = { ...entry.repostedBy, author: mark(entry.repostedBy.author, all), handle: mark(entry.repostedBy.handle, all) }; if (Array.isArray(entry.parents)) out.parents = entry.parents.map((p, i) => ref(p, "parent", i)); if (isObj(entry.quoted)) out.quoted = ref(entry.quoted, "quoted"); + // A post its words link to (post-thread.mjs): marked by the project's terms, as a quoted post is. + if (Array.isArray(entry.links)) out.links = entry.links.map((p) => ref(p, "quoted")); return slurEntry(out, red?.slurs); } @@ -323,6 +328,7 @@ export function slurEntry(entry, slurs) { if (isObj(entry.repostedBy)) out.repostedBy = { ...entry.repostedBy, author: m(entry.repostedBy.author) }; if (Array.isArray(entry.parents)) out.parents = entry.parents.map(ref); if (isObj(entry.quoted)) out.quoted = ref(entry.quoted); + if (Array.isArray(entry.links)) out.links = entry.links.map((r) => (isObj(r) && "transcript" in r ? { ...ref(r), transcript: m(r.transcript) } : ref(r))); return out; } diff --git a/umtool/report-to-video/post-render-key.test.mjs b/umtool/report-to-video/post-render-key.test.mjs @@ -0,0 +1,72 @@ +// THE SEGMENT CACHE KEY (post-render.mjs postSegmentKeyOf; operator, 4 Nov: "make sure you handle caching well, we may +// have a couple rerenders before shipping"): every thread-scenes input that changes a post segment's pixels or timing +// changes its key; an item none of them touch keeps the key it had on main (645dafb7), so `umtool take --from` reuses it. +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { test } from "node:test"; +import { postItemPlan, postLayout } from "./post-item.mjs"; +import { planContext } from "./post-conversation.mjs"; +import { POST_SEGMENT_RV, postSegmentKey, postSegmentKeyOf } from "./post-render.mjs"; + +const render = { fps: 30, palette: { bg: "#111111" }, fontRegular: "/f/r.ttf", fontBold: "/f/b.ttf", postNarration: { lead: 0.25 } }; +const box = { width: 1610, height: 906 }; +const at = (h) => `2026-11-02T${String(h).padStart(2, "0")}:00:00.000Z`; +const take = (text, role) => ({ file: "narration/posts/1/take-1.wav", engine: "orpheus", voice: "zac", seconds: 4, script: text, parts: [{ n: 1, para: 0, text, start: 0, seconds: 3.5, ...(role ? { role } : {}) }] }); +const post = (id, text, o = {}) => ({ type: "post", id: `p-${id}`, post: `acct-x/${id}`, platform: "x", author: "Subject", handle: "subject", date: at(10), text, ...o }); +const narrated = (e, pieces) => ({ ...e, narration: { script: e.text, takes: [{ ...take(e.text), parts: pieces.map(([t, role], k) => ({ n: k + 1, para: k * 100, text: t, start: k * 4, seconds: 3.5, role })), seconds: pieces.length * 4 }], pick: 0 } }); + +/** Main's key, verbatim (645dafb7 post-render.mjs buildPostSegment), for an item with no redaction, bleeps or slurs. */ +function mainKey({ entry, plan, take: tk, stamps = [] }) { + return createHash("sha256") + .update(JSON.stringify({ v: 1, entry, box, place: [], palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode: [], stamps, ...(tk ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}), ...(plan.follow ? { follow: plan.follow } : {}) })) + .digest("hex"); +} +const keyOf = (entry, ctx = {}, extra = {}) => { + const plan = postItemPlan(entry, render, ctx); + return { plan, key: postSegmentKey(postSegmentKeyOf({ entry, box, render, plan, take: entry.narration ? entry.narration.takes[0] : null, layout: postLayout(entry, box), ...extra })) }; +}; + +test("a PLAIN item (no thread, no join, no wide attachment) keeps main's key: --from reuses its segment", () => { + assert.equal(POST_SEGMENT_RV, null, "no renderer salt: unchanged plans draw what they drew"); + for (const e of [ + post("1", "Just a post with words."), + narrated(post("2", "A narrated post read on its own."), [["A narrated post read on its own.", "post"]]), + post("3", "A post with its picture.", { media: [{ src: "posts-media/a/3.png", kind: "image", width: 800, height: 600 }] }), + ]) { + const { plan, key } = keyOf(e); + assert.equal(key, mainKey({ entry: e, plan, take: e.narration ? e.narration.takes[0] : null }), e.id); + } +}); + +test("every thread-scenes input changes the key: the join, context media, a wide layout, a manual thread and its relations, the branch map, link visits and linked posts, whole-thread pieces", () => { + const root = narrated(post("10", "You all have low testosterone, I become bestial.", { date: at(10) }), [["You all have low testosterone, I become bestial.", "post"]]); + const reply = narrated(post("11", "We high T guys have to watch ourselves.", { date: at(12), parents: [{ id: "5", handle: "ryobi", author: "Ryobi", date: at(11), text: "Three days is enough." }, { id: "10", handle: "subject", author: "Subject", date: at(10), text: root.text }] }), [["Three days is enough.", "parent:0"], ["We high T guys have to watch ourselves.", "post"]]); + const tl = [root, reply]; + const base = keyOf(reply, { ...planContext(tl, 1, render), join: null }).key; + const keys = new Map(); + // The join: its seconds in the plan (follow.join), the item before's end in joinFrom. + const j = keyOf(reply, planContext(tl, 1, render)); + keys.set("join (plan)", j.key); + keys.set("join (the item before's end)", keyOf(reply, planContext(tl, 1, render), { from: { entry: root, plan: postItemPlan(root, render), media: [], fadeIn: false } }).key); + // A context post's media (the plan's panel, the entry's ref media). + const withMedia = { ...reply, parents: [{ ...reply.parents[0], media: [{ src: "posts-media/r/5.jpg", kind: "image", width: 600, height: 800 }] }, reply.parents[1]] }; + keys.set("context media", keyOf(withMedia, { ...planContext([root, withMedia], 1, render), join: null }).key); + // A wide attachment: the top layout. + keys.set("wide", keyOf({ ...reply, media: [{ src: "posts-media/w/1.png", kind: "image", width: 692, height: 141 }] }, { ...planContext(tl, 1, render), join: null }).key); + // A manual thread: its group's stack and relations. + const g = (e) => ({ ...e, thread: { group: "g" } }); + const lone = narrated(post("20", "Ready for more lessons?", { handle: "movail", date: at(9) }), [["Ready for more lessons?", "post"]]); + const gtl = [g(lone), g(reply)]; + keys.set("manual thread", keyOf(gtl[1], { ...planContext(gtl, 1, render), join: null }).key); + // The branch map off. + keys.set("branch map knob", keyOf({ ...reply, thread: { map: false } }, { ...planContext(tl, 1, render), join: null }).key); + // A linked post (a link visit) and its transcript. + const linked = { ...reply, links: [{ id: "77", handle: "iv", author: "IV", date: at(8), text: "Ya try to be civil" }] }; + keys.set("linked post", keyOf(linked, { ...planContext([root, linked], 1, render), join: null }).key); + keys.set("linked transcript", keyOf({ ...linked, links: [{ ...linked.links[0], transcript: "the messages" }] }, { ...planContext([root, linked], 1, render), join: null }).key); + // A whole-thread read: a third ancestor. + const deeper = { ...reply, parents: [...reply.parents, { id: "3", handle: "x", author: "X", date: at(9), text: "An older post." }] }; + keys.set("whole thread", keyOf(deeper, { ...planContext([root, deeper], 1, render), join: null }).key); + for (const [what, k] of keys) assert.notEqual(k, base, what); + assert.equal(new Set(keys.values()).size, keys.size, "each input its own key"); +}); diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -18,13 +18,19 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; -import { POST_PICTURE_XFADE, POST_PUSH, fxRedactionErrors, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; -import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, rootTakeOf } from "./post-narration.mjs"; +import { POST_PICTURE_XFADE, POST_PUSH, cardAuthors, fxRedactionErrors, mediaTimeAt, panelEntry, postCardHtml, postItemPlan, postLayout, stepAt, stepBoxes } from "./post-item.mjs"; +import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, postNarrationKnobs, rootTakeOf } from "./post-narration.mjs"; import { applyFollowState, followPath, followRuns, followStateAt, isDrawnState, measureFollow, readInViewErrors, shotStateAt } from "./read-follow.mjs"; import { redactEntry, redactionOn, shownLine, termsFor } from "./post-redact.mjs"; import { bleepFilters, slursOn, takeBleeps } from "./post-slurs.mjs"; import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs"; import { sceneEntry } from "./post-media-scene.mjs"; +import { CAPTION_OUT, CAPTION_SLIDE, captionCss, captionInnerHtml, captionPlan, measureCaptionWords, mountCaptions, placeCaption, setCaptionState, slideDir } from "./post-caption.mjs"; +import { clockCss, clockFace, clockFrameTimes, clockHtml, clockPlan, clockStateAt, measureClockPlace, mountClock, setClockState } from "./post-clock.mjs"; +import { panelReadErrors } from "./post-thread.mjs"; +import { applyJoinState, endMediaOf } from "./post-join.mjs"; +import { applyVisitState } from "./post-link-visit.mjs"; +import { applyMapState, mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; @@ -59,6 +65,19 @@ export function stepCaptions(step, cues) { .filter((c) => c.to - c.from > 0.05); } +/** A scroll's keyframes (post-thread.mjs panelSchedule) as an ffmpeg expression of t: 0..1, linear between them. */ +export function scrollExpr(keys) { + if (!Array.isArray(keys) || !keys.length) return "0"; + let e = num(keys[keys.length - 1][1]); + for (let i = keys.length - 1; i >= 1; i -= 1) { + const [t1, f1] = keys[i]; + const [t0, f0] = keys[i - 1]; + const seg = t1 > t0 ? `${num(f0)}+(${num(f1 - f0)})*(t-${num(t0)})/${num(t1 - t0)}` : num(f1); + e = `if(lt(t,${num(t1)}),${seg},${e})`; + } + return `if(lt(t,${num(keys[0][0])}),${num(keys[0][1])},${e})`; +} + /** * The encode, pure. `cards`: the read-phase PNG and (a stack layout) the * media-phase one; `files[i]`: attachment i's absolute path; `captions`: @@ -68,7 +87,7 @@ export function stepCaptions(step, cues) { * * @returns {string[]} */ -export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null }) { +export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, panelFiles = [], join = null, map = null, captionFx = [], clock = null }) { const fps = render.fps ?? 30; const T = plan.total; const inputs = []; @@ -124,6 +143,39 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render parts.push(`[${cur}][wz${zi}]overlay=x=${region.x}:y=${region.y}:eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`); cur = next; }); + // CAPTIONS (post-caption.mjs): each chip shot alone on a clear page, laid over the card while it is up -- fading + // and sliding in toward its phrase, the underline fading under the words, both tracking the words as the card + // pans -- after the zooms (a caption waits for one to be out), before the attachments (it stays on the card). + captionFx.forEach((c, ci) => { + const { span } = c; + const D = Math.max(1 / fps, span.t3 - span.t0); + // Static: a pan that moves its phrase ends it first (shootCaptions), so nothing rides over words. + const track = (axis) => trackExpr(c.track ?? [], axis); + const layer = (shot, label, slide) => { + const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", shot.file]); + parts.push( + `[${k}:v]format=rgba,fade=t=in:st=0:d=${num(Math.max(0.04, span.t1 - span.t0))}:alpha=1,` + + `fade=t=out:st=${num(span.t2 - span.t0)}:d=${num(Math.max(0.04, span.t3 - span.t2))}:alpha=1,setpts=PTS-STARTPTS+${num(span.t0)}/TB[${label}]`, + ); + const left = span.t1 > span.t0 ? `pow(1-clip((t-${num(span.t0)})/${num(span.t1 - span.t0)},0,1),3)` : "0"; + const sx = slide && slide.x ? `+${num(slide.x)}*${left}` : ""; + const sy = slide && slide.y ? `+${num(slide.y)}*${left}` : ""; + const next = `b${++n}`; + parts.push(`[${cur}][${label}]overlay=x='${shot.x}${track("dx")}${sx}':y='${shot.y}${track("dy")}${sy}':eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`); + cur = next; + }; + if (c.mark) layer(c.mark, `cpm${ci}`, null); + layer(c.chip, `cpc${ci}`, c.slide); + }); + // THE CLOCK (post-clock.mjs): its frames shot alone -- the run from the item before's time, then held -- laid + // over the card's corner from the first frame (a stack card's: until its media phase). + if (clock) { + const ci = add(["-f", "concat", "-safe", "0", "-i", clock.list]); + parts.push(`[${ci}:v]fps=${fps},format=rgba,setsar=1,setpts=PTS-STARTPTS[clk]`); + const next = `b${++n}`; + parts.push(`[${cur}][clk]overlay=x=${clock.x}:y=${clock.y}:eof_action=repeat${clock.until < T ? `:enable='lt(t,${num(clock.until)})'` : ""}[${next}]`); + cur = next; + } const audio = []; const picture = (st) => !!st && (st.kind === "image" || st.kind === "grid" || st.kind === "gif"); plan.steps.forEach((step, si) => { @@ -170,6 +222,8 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render audio.push({ label: `a${si}`, chain: `[${k}:a]aresample=${render.audioRate ?? 48000},aformat=channel_layouts=stereo,asetpts=PTS-STARTPTS,atrim=0:${num(dur)},afade=t=in:d=0.04,afade=t=out:st=${num(Math.max(0, dur - 0.06))}:d=0.06,adelay=${ms}|${ms}[a${si}]` }); } } + // THE JOIN (post-join.mjs): another attachment than the one the item before ended on fades in over it. + if (si === 0 && join?.fadeIn) parts[parts.length - 1] = parts[parts.length - 1].replace(new RegExp(`\\[${raw}\\]$`), `,format=rgba,fade=t=in:st=${num(join.seconds * 0.35)}:d=${num(join.seconds * 0.65)}:alpha=1[${raw}]`); if (raw !== label) parts.push(...blurFilters(raw, label, m, b)); lay(label, b.x, b.y, shownFrom, until); // Its label ("Censored") on the frame, at the attachment's corner, while it is up. @@ -180,6 +234,67 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render } }); }); + // THE PANEL (post-thread.mjs panelSchedule): a context post's attachment over the slot while it is on screen -- + // crossfaded in and out over the item's own; a tall picture read through scrolled top to foot (its crop's y on t). + if (plan.panel && layout.slot) { + const fade = plan.panel.fade ?? 0.3; + plan.panel.shows.forEach((show, pi) => { + const items = show.media.map((m, j) => ({ ...m, i: j })); + const boxes = stepBoxes({ items }, layout.slot); + const until = Math.min(T, show.t1 + fade); + items.forEach((m, j) => { + const file = panelFiles[pi]?.[j]; + if (!file) return; + const label = `pn${pi}_${j}`; + const raw = blurOn(m) ? `${label}r` : label; + const fades = `format=rgba${show.t0 > 0.001 ? `,fade=t=in:st=${num(show.t0)}:d=${num(fade)}:alpha=1` : ""}${until < T - 0.001 ? `,fade=t=out:st=${num(show.t1)}:d=${num(fade)}:alpha=1` : ""}`; + let b = boxes[j]; + if (show.scroll && j === 0 && m.kind === "image" && (m.height ?? 0) / Math.max(1, m.width ?? 1) > (layout.slot.height / layout.slot.width) * 1.4) { + // Scrolled: the picture at a readable width, a window of the slot's height panned down it as it is read. + const w = Math.max(2, Math.floor(Math.min(layout.slot.width, layout.slot.height * 0.8) / 2) * 2); + const fullH = Math.max(2, Math.floor((w * (m.height ?? 1)) / Math.max(1, m.width ?? 1) / 2) * 2); + const h = Math.max(2, Math.floor(layout.slot.height / 2) * 2); + const range = Math.max(0, fullH - h); + b = { x: Math.round(layout.slot.x + (layout.slot.width - w) / 2), y: layout.slot.y, width: w, height: h }; + const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]); + parts.push(`[${k}:v]scale=${w}:${fullH},setsar=1,fps=${fps},crop=${w}:${h}:0:'${num(range)}*(${scrollExpr(show.scroll)})',${fades}[${raw}]`); + } else if (m.kind === "image") { + const crop = Array.isArray(m.crop) ? `crop=iw*${num(m.crop[2])}:ih*${num(m.crop[3])}:iw*${num(m.crop[0])}:ih*${num(m.crop[1])},` : ""; + const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]); + parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},${fades}[${raw}]`); + } else { + // A video or a GIF of a context post: looped, silent, from its first frame as it comes up. + const k = add(["-stream_loop", "-1", "-t", num(Math.max(0.1, until - show.t0)), "-i", file]); + parts.push(`[${k}:v]scale=${b.width}:${b.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,tpad=start_duration=${num(show.t0)}:start_mode=clone,${fades}[${raw}]`); + } + if (raw !== label) parts.push(...blurFilters(raw, label, m, b)); + lay(label, b.x, b.y, show.t0, until); + }); + }); + } + // THE JOIN (post-join.mjs): what the item before ended on in its slot, fading out over the join (a video playing on). + if (join?.from?.length) { + const J = join.seconds; + join.from.forEach((f, ji) => { + const label = `jf${ji}`; + const raw = blurOn(f.m) ? `${label}r` : label; + const crop = Array.isArray(f.m.crop) ? `crop=iw*${num(f.m.crop[2])}:ih*${num(f.m.crop[3])}:iw*${num(f.m.crop[0])}:ih*${num(f.m.crop[1])},` : ""; + const k = f.m.kind === "image" + ? add(["-loop", "1", "-framerate", String(fps), "-t", num(J), "-i", f.file]) + : add([...(f.m.kind === "gif" ? ["-stream_loop", "-1"] : []), "-ss", num(f.t), "-t", num(J + 0.1), "-i", f.file]); + parts.push(`[${k}:v]${crop}scale=${f.box.width}:${f.box.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,tpad=stop_mode=clone:stop_duration=${num(J)},format=rgba,fade=t=out:st=0:d=${num(J)}:alpha=1[${raw}]`); + if (raw !== label) parts.push(...blurFilters(raw, label, f.m, f.box)); + lay(label, f.box.x, f.box.y, 0, J); + }); + } + // THE BRANCH MAP (post-branch-map.mjs): over everything, where mapPlace put it, while it is up. + if (map) { + const mi = add(["-f", "concat", "-safe", "0", "-i", map.list]); + parts.push(`[${mi}:v]fps=${fps},format=rgba,setpts=PTS-STARTPTS+${num(map.t0)}/TB[bmap]`); + const next = `b${++n}`; + parts.push(`[${cur}][bmap]overlay=x=${map.x}:y=${map.y}:eof_action=pass:enable='between(t,${num(map.t0)},${num(map.t3)})'[${next}]`); + cur = next; + } // A video attachment's words (its transcript), at the slot's foot. if (captions.length && fontfile && layout.slot) { const size = Math.round(34 * (box.height / 1080)); @@ -220,6 +335,21 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render ]; } +/** + * A caption's track (`[{ t, dx, dy }]`: how far its phrase has moved from where + * it was placed, from item second t) as an ffmpeg term of `t` to add to its + * x or y ("" when it never moves). + */ +export function trackExpr(track, axis) { + const steps = []; + for (const p of track) if (!steps.length ? p[axis] !== 0 : p[axis] !== steps[steps.length - 1].v) steps.push({ t: p.t, v: p[axis] }); + if (!steps.length) return ""; + // Nested from the last change back: before each change, what held until it. + let e = String(steps[steps.length - 1].v); + for (let k = steps.length - 1; k >= 0; k -= 1) e = `if(lt(t,${num(steps[k].t)}),${k ? steps[k - 1].v : 0},${e})`; + return `+(${e})`; +} + async function loadChromium() { let mod; try { @@ -237,7 +367,7 @@ async function loadChromium() { * stack layout. The page is a file beside them, so its faces and the parent * shot load from disk (an about:blank page may not read file: urls). */ -export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0 }) { +export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, joinFrom = null, captions = [], clock = null, obstacles = [] }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", @@ -251,14 +381,54 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la try { const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); + const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); + // THE JOIN (post-join.mjs): the item before's card as it ENDED -- its page drawn, its last frame's state set, its + // card shot -- and where its post's words sat; this card opens on it and morphs into its own. + let join = null; + if (follow?.join && joinFrom?.entry) { + const fps = render.fps ?? 30; + const pe = joinFrom.entry; + const pf = joinFrom.plan?.follow ?? null; + const ph = postCardHtml(pe, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", avatars: av, follow: !!pf, thread: pf?.thread ?? null, redaction }); + const pfile = path.join(dir, "join-from.html"); + await writeFile(pfile, ph, "utf8"); + await page.goto(pathToFileURL(pfile).href, { waitUntil: "load" }); + await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); + if (pf) { + const pgeo = await page.evaluate(measureFollow); + await page.evaluate(applyFollowState, followStateAt(pf, followPath(pf, pgeo), Math.max(0, joinFrom.plan.total - 1 / fps))); + } + const m = await page.evaluate(() => { + const card = document.querySelector("[data-post-card]"); + if (!card) return null; + const c = card.getBoundingClientRect(); + // His post's head where the item before drew it (a threaded card's post tile; a plain card's head), and its words' size. + // Its HEAD (name and date): where the carried post's head goes (a relation line above it moves its tile, not it). + const post = document.querySelector('[data-thread-slot="post"] .head') ?? card.querySelector(".head"); + const words = document.querySelector('[data-thread-slot="post"] .twords') ?? document.querySelector("[data-post-words]"); + const pr = post ? post.getBoundingClientRect() : null; + return { A: { x: c.left, y: c.top, width: c.width, height: c.height }, anchor: pr ? pr.top - c.top : null, size: words ? parseFloat(getComputedStyle(words).fontSize) : null }; + }); + if (m) { + const png = path.join(dir, "join-from.png"); + const x = Math.max(0, Math.floor(m.A.x)); + const y = Math.max(0, Math.floor(m.A.y)); + await page.screenshot({ path: png, clip: { x, y, width: Math.min(box.width - x, Math.ceil(m.A.width)), height: Math.min(box.height - y, Math.ceil(m.A.height)) } }); + const pl = postLayout(pe, box); + const same = Math.abs(m.A.width - layout.card.width) < 2 && !!(follow.thread?.tiles ?? []).some((t) => t.mode === "carry" || (t.mode === "scene" && t.wasPost)); + join = { A: { x, y, width: Math.ceil(m.A.width), height: Math.ceil(m.A.height) }, slotA: pl.slot && pl.mode === "side" ? pl.slot : null, fromUrl: pathToFileURL(png).href, size: m.size, same, anchor: m.anchor }; + out.joinFrom = { A: join.A, layout: pl }; + } + } for (const phase of phases) { const html = postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl, - avatars: Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])), + avatars: av, follow: !!follow && phase === "read", // A threaded card (post-thread.mjs): the plan's tiles. thread: follow?.thread ?? null, redaction, + ...(join && phase === "read" ? { join } : {}), }); const file = path.join(dir, `${phase}.html`); await writeFile(file, html, "utf8"); @@ -270,7 +440,21 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la if (phase === "read" && follow) { const fps = render.fps ?? 30; const geo = await page.evaluate(measureFollow); + // THE JOIN: the carried post opens where the item before's post sat (its top this far down the window). + if (join && geo && join.anchor !== null) { + const own = await page.evaluate(() => { + const c = document.querySelector("[data-post-card]")?.getBoundingClientRect(); + const w = document.querySelector("[data-post-words]")?.getBoundingClientRect(); + const tile = document.querySelector("[data-join-anchor]"); + const head = tile?.querySelector(".head")?.getBoundingClientRect(); + const slot = tile?.closest("[data-thread-slot]")?.getBoundingClientRect(); + return c && w ? { win: w.top - c.top, width: c.width, head: head && slot ? head.top - slot.top : 0 } : null; + }); + if (own) geo.joinAnchor = { y: Math.round((join.anchor / (join.A.width / own.width) - own.win - own.head) * 100) / 100 }; + } out.follow = await shootFollow(page, { follow, total, fps, box, dir, geo }); + // THE BRANCH MAP (post-branch-map.mjs): its own layer, shot on a transparent page, laid over the attachments. + if (follow.thread?.map) out.map = await shootMap(ctx, { map: follow.thread.map, layout, box, fps, dir, render, fonts, entry }); // THE INVARIANT (read-follow.mjs readInViewErrors): what each part reads is in view, whole and lit, in the // frames as they are shot -- or, with none shot, in the page as drawn. const fpath = out.follow?.path ?? followPath(follow, geo); @@ -279,6 +463,9 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la } await ctx.close(); if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow }); + if (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total }); + // A caption covers none of the attachments (`obstacles`: their boxes) nor the clock. + if (captions.length) out.captions = await shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction, follow, obstacles: [...obstacles, ...(out.clock ? [out.clock.box] : [])] }); } finally { await browser.close(); } @@ -309,7 +496,9 @@ export async function shootFollow(page, { follow, total, fps, box, dir, geo = nu if (!r) return null; const x = Math.max(0, Math.floor(r.x)); const y = Math.max(0, Math.floor(r.y)); - const clip = { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height) - y) }; + // A JOIN (post-join.mjs) moves the card and the slot's well: the whole box is shot. + const joined = !!follow.join && (await page.evaluate(() => !!document.body.getAttribute("data-join"))); + const clip = joined ? { x: 0, y: 0, width: box.width, height: box.height } : { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height) - y) }; const fdir = path.join(dir, "follow"); await rm(fdir, { recursive: true, force: true }); await mkdir(fdir, { recursive: true }); @@ -318,10 +507,15 @@ export async function shootFollow(page, { follow, total, fps, box, dir, geo = nu if (shots.has(run.key)) continue; const file = path.join(fdir, `f-${String(shots.size).padStart(5, "0")}.png`); await page.evaluate(applyFollowState, run.st); + if (joined) await page.evaluate(applyJoinState, run.st.join ?? null); + // A LINK VISIT (post-link-visit.mjs): the pointer and its click over the link where the state puts it. + if (follow.visits?.length) await page.evaluate(applyVisitState, { visits: follow.visits, st: run.st.visit ?? null }); await page.screenshot({ path: file, clip }); shots.set(run.key, file); } await page.evaluate(applyFollowState, null); + if (joined) await page.evaluate(applyJoinState, null); + if (follow.visits?.length) await page.evaluate(applyVisitState, { visits: follow.visits, st: null }); const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, `duration ${(run.n / fps).toFixed(6)}`); @@ -331,6 +525,64 @@ export async function shootFollow(page, { follow, total, fps, box, dir, geo = nu return { list, clip, shots: shots.size, frames, geo, path: path0 }; } +/** + * THE BRANCH MAP's FRAMES (post-branch-map.mjs): the map alone on a transparent page, each distinct state (its + * strength, its light's place) shot once over its span, a concat list holding each for its frames; `{ list, x, y, + * t0, t3 }` -- where it is laid (mapPlace: over the slot, or beside a card alone) and when. + */ +async function shootMap(ctx, { map, layout, box, fps, dir, render, fonts, entry }) { + const k = box.height / 1080; + const size = mapSize(map, k); + const at = mapPlace(layout, box, size, k); + const pal = { fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...(render.palette ?? {}) }; + const blurred = cardAuthors(entry).filter((a) => a.redact && a.handle).map((a) => a.handle); + const page = await ctx.newPage(); + try { + await page.setViewportSize({ width: Math.max(2, size.width + 4), height: Math.max(2, size.height + 4) }); + const file = path.join(dir, "map.html"); + await writeFile(file, mapPageHtml(map, { width: size.width + 4, height: size.height + 4, k, accent: pal.accent, fg: pal.fg, muted: pal.muted, blurred, fonts }), "utf8"); + await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); + const el = await page.evaluate(() => { + const m = document.querySelector("[data-thread-map]"); + if (!m) return null; + m.style.display = "block"; + const r = m.getBoundingClientRect(); + return { width: Math.ceil(r.width), height: Math.ceil(r.height) }; + }); + if (!el) return null; + const mdir = path.join(dir, "map"); + await rm(mdir, { recursive: true, force: true }); + await mkdir(mdir, { recursive: true }); + const { t0, t3 } = map.times; + const frames = Math.max(1, Math.round((t3 - t0) * fps)); + const runs = []; + for (let i = 0; i < frames; i += 1) { + const st = mapStateAt(map, t0 + i / fps) ?? { op: 0, p: 0 }; + const key = JSON.stringify(st); + const last = runs[runs.length - 1]; + if (last && last.key === key) last.n += 1; + else runs.push({ key, st, n: 1 }); + } + const shots = new Map(); + for (const run of runs) { + if (shots.has(run.key)) continue; + const png = path.join(mdir, `m-${String(shots.size).padStart(4, "0")}.png`); + await page.evaluate(applyMapState, run.st); + await page.screenshot({ path: png, clip: { x: 0, y: 0, width: el.width, height: el.height }, omitBackground: true }); + shots.set(run.key, png); + } + const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; + const lines = ["ffconcat version 1.0"]; + for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, `duration ${(run.n / fps).toFixed(6)}`); + lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`); + const list = path.join(mdir, "frames.ffconcat"); + await writeFile(list, lines.join("\n") + "\n", "utf8"); + return { list, x: Math.round(at.x), y: Math.round(at.y), t0, t3 }; + } finally { + await page.close(); + } +} + /** The device scale a word zoom's shots are taken at: crisp at its scale (2–4). */ export const zoomShotScale = (zooms) => Math.min(4, Math.max(2, Math.ceil(Math.max(1, ...zooms.map((z) => z.scale ?? WORD_ZOOM_DEFAULTS.scale))))); @@ -415,17 +667,193 @@ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotU } /** + * Each CAPTION's shots and place (post-caption.mjs): on the card page as it is + * drawn when the caption is fully in (read-follow's state at its t1), the + * phrase measured -- refused when it is cut off the card -- and the words read + * while it is up; the chip placed by them (placeCaption: never covering one), + * then shot alone on a clear page (the chip with its notch; the underline + * apart, as it does not slide). Following, the phrase is measured frame by + * frame over the caption's span: its `track`, which the chip rides. + * `captions`: captionPlan's. Returns `[{ ...caption, chip, mark, slide, track, placed }]`. + */ +export async function shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction = null, follow = null, obstacles: fixed = [] }) { + const fps = render.fps ?? 30; + const k = box.height / 1080; + const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); + const page = await ctx.newPage(); + const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); + const out = []; + try { + const file = path.join(dir, "caption.html"); + await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, 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 }); + await page.evaluate(() => document.fonts.ready.then(() => true)); + const sizes = await page.evaluate(mountCaptions, { css: captionCss({ height: box.height, palette: render.palette }), chips: captions.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k }); + await page.evaluate(() => document.fonts.ready.then(() => true)); + const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; + const stateAt = async (s) => { + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); + }; + const inset = Math.round(12 * k); + const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset }; + for (const c0 of captions) { + let c = c0; + // A pan moving the phrase while it is up: the caption is gone before it moves (the chip never rides over words). + if (follow) { + let base = null; + for (let f = Math.floor(c.span.t0 * fps); f <= Math.ceil(c.span.t3 * fps); f += 1) { + await stateAt(f / fps); + const g = await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: [] }); + if (g.error) continue; + base ??= g.word; + if (Math.abs(g.word.y - base.y) > 1 || Math.abs(g.word.x - base.x) > 1) { + const tm = r3(f / fps); + if (tm > c.span.t1 + 0.2) c = { ...c, span: { ...c.span, t2: r3(Math.max(c.span.t1, tm - CAPTION_OUT)), t3: tm }, cutByPan: tm }; + break; + } + } + } + // Its place: judged where the card is as it comes in, while it is up and as it goes (a pan's other words too). + const looks = []; + for (const s of follow ? [c.span.t1, c.span.t0, c.span.t3 - 0.01] : [c.span.t1]) { + await stateAt(s); + looks.push(await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: c.avoid })); + } + await stateAt(c.span.t1); + const geo = looks[0]; + if (geo.error) throw new Error(`${entry.id}: caption ${c.i + 1}: the phrase is ${geo.error}`); + const obstacles = [...fixed, ...looks.flatMap((l) => l.obstacles ?? [])]; + const size = sizes.find((x) => x.i === c.i); + const placed = placeCaption({ word: geo.word, sizes: size.sizes, bounds, card: geo.card, column: geo.column, place: c.place, obstacles, gap: Math.round(10 * k) }); + if (!placed) throw new Error(`${entry.id}: caption ${c.i + 1}: the chip fits nowhere in the frame`); + // Shot alone: the card hidden, the page clear. + await page.evaluate(() => { + const st = document.createElement("style"); + st.setAttribute("data-pcap-solo", ""); + st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-fx-captions]) { visibility: hidden !important; }"; + document.head.appendChild(st); + }); + const pad = Math.round(40 * k); + const clipOf = (r) => { + const x = Math.max(0, Math.floor(r.x - pad)); + const y = Math.max(0, Math.floor(r.y - pad)); + return { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width + pad) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height + pad) - y) }; + }; + const state = { i: c.i, x: placed.x, y: placed.y, max: placed.max, opacity: 1, marks: geo.lines, mark: 1, leader: placed.leader }; + const stroke = Math.max(2, Math.round(2.4 * k)); + await page.evaluate(setCaptionState, { list: [state], only: "chip", stroke }); + const chipClip = clipOf(placed); + const chip = { file: path.join(dir, `caption-${c.i}.png`), x: chipClip.x, y: chipClip.y }; + await page.screenshot({ path: chip.file, clip: chipClip, omitBackground: true }); + await page.evaluate(setCaptionState, { list: [state], only: "mark", stroke }); + // The underline and the leader (which does not slide): their union. + const pts = [...(placed.leader ?? []), [geo.word.x, geo.word.y + geo.word.height * 0.6], [geo.word.x + geo.word.width, geo.word.y + geo.word.height * 1.2]]; + const mx0 = Math.min(...pts.map((p) => p[0])); + const my0 = Math.min(...pts.map((p) => p[1])); + const markClip = clipOf({ x: mx0, y: my0, width: Math.max(...pts.map((p) => p[0])) - mx0, height: Math.max(...pts.map((p) => p[1])) - my0 }); + const mark = { file: path.join(dir, `caption-${c.i}-mark.png`), x: markClip.x, y: markClip.y }; + await page.screenshot({ path: mark.file, clip: markClip, omitBackground: true }); + await page.evaluate(setCaptionState, { list: [] }); + await page.evaluate(() => document.querySelectorAll("style[data-pcap-solo]").forEach((el) => el.remove())); + const rel = placed.y >= geo.word.y + geo.word.height ? "below" : placed.y + placed.height <= geo.word.y ? "above" : placed.x >= geo.word.x ? "side-right" : "side-left"; + const d = slideDir(rel); + // What it would cover of the words read, or of anything drawn: none, unless nothing in the frame is free. + out.push({ ...c, chip, mark, slide: { x: d.x * CAPTION_SLIDE * k, y: d.y * CAPTION_SLIDE * k }, track: [], placed: { ...placed, rel, word: geo.word } }); + } + } finally { + await ctx.close(); + } + return out; +} + +/** + * THE CLOCK's FRAMES (post-clock.mjs): on the card page as drawn, the chip + * mounted at its widest and placed (measureClockPlace: the bottom-right corner + * by the counts row, else the top-right -- over no word), then shot alone on a + * clear page at each frame of its run and its badge's fade (each distinct one + * once) and a concat list holding each for its frames, the last to the end. + * `{ list, x, y, place, covers, shots }`. + */ +export async function shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction = null, follow = null, total = 0 }) { + const fps = render.fps ?? 30; + const k = box.height / 1080; + const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); + const page = await ctx.newPage(); + const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); + try { + const file = path.join(dir, "clock.html"); + await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, 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 }); + const face = clockFace(clock.to, clock.zone); + const size = await page.evaluate(mountClock, { css: clockCss({ height: box.height, palette: render.palette }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } }); + await page.evaluate(() => document.fonts.ready.then(() => true)); + // Placed as the card is when its own post is in (the read's end: a threaded card's counts row is there), and + // judged over the read (its start, middle and end): the place covering fewest words over all three wins. + const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; + const states = follow ? [total, 0, total / 2] : [0]; + const looks = []; + for (const s of states) { + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); + looks.push(await page.evaluate(measureClockPlace, { size, inset: Math.round(22 * k), fixed: looks[0]?.tries ?? null })); + } + const at0 = looks[0]; + const at = at0 ? at0.tries.map((t, i) => ({ ...t, covers: looks.reduce((a, l) => a + (l?.tries?.[i]?.covers ?? 0), 0) })).sort((a, b) => a.covers - b.covers)[0] : null; + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, 0)); + if (!at) throw new Error(`${entry.id}: the clock has no card to sit on`); + await page.evaluate(() => { + const st = document.createElement("style"); + st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-clock-layer]) { visibility: hidden !important; }"; + document.head.appendChild(st); + }); + // The clip: the chip and its badge to its left. + const left = Math.round(300 * k); + const x = Math.max(0, at.x - left); + const y = Math.max(0, at.y - Math.round(10 * k)); + const clip = { x, y, width: Math.min(box.width - x, at.x + size.width + Math.round(16 * k) - x), height: Math.min(box.height - y, size.height + Math.round(20 * k)) }; + const fdir = path.join(dir, "clock"); + await rm(fdir, { recursive: true, force: true }); + await mkdir(fdir, { recursive: true }); + const shots = new Map(); + const runs = []; + for (const s of clockFrameTimes(clock, fps)) { + const st = clockStateAt(clock, s); + const key = JSON.stringify([st.time, st.date, st.gap, Math.round(st.gapOpacity * 50), Math.round(st.hourTurn * 2), Math.round(st.minuteTurn), st.running]); + if (!shots.has(key)) { + const f = path.join(fdir, `c-${String(shots.size).padStart(4, "0")}.png`); + await page.evaluate(setClockState, { x: at.x, y: at.y, st }); + await page.screenshot({ path: f, clip, omitBackground: true }); + shots.set(key, f); + } + if (runs.length && runs[runs.length - 1].key === key) runs[runs.length - 1].n += 1; + else runs.push({ key, n: 1 }); + } + const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; + const lines = ["ffconcat version 1.0"]; + runs.forEach((r, i) => lines.push(`file ${q(shots.get(r.key))}`, `duration ${(r.n / fps).toFixed(6)}`)); + lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`); + const list = path.join(fdir, "frames.ffconcat"); + await writeFile(list, lines.join("\n") + "\n", "utf8"); + return { list, x: clip.x, y: clip.y, place: at.place, covers: at.covers, shots: shots.size, box: { x: at.x - Math.round(240 * k), y: at.y, width: size.width + Math.round(240 * k), height: size.height } }; + } finally { + await ctx.close(); + } +} + +/** * A post item's word zooms, resolved for the build: `[{ i, scope, from, to, * scale, highlight, span }]`, each on its time (wordZoomTimes) -- refused in * the build's words when one has no time, or two are up at once. */ -export function postZoomPlan(entry, render, total = Infinity) { +export function postZoomPlan(entry, render, total = Infinity, schedule = undefined) { const fx = Array.isArray(entry?.fx) ? entry.fx : []; - if (!fx.length) return []; - const times = wordZoomTimes(entry, render); + if (!fx.some((f) => f?.kind === "word-zoom")) return []; + const times = wordZoomTimes(entry, render, schedule); const bad = times.filter((t) => t.error); if (bad.length) throw new Error(bad.map((t) => t.error).join("; ")); - const zooms = fx.map((f0, i) => { + // Its captions (post-caption.mjs) are timed and drawn apart: only the word zooms here. + const zooms = fx.flatMap((f0, i) => (f0?.kind === "word-zoom" ? [[f0, i]] : [])).map(([f0, i]) => { const f = resolveWordZoom(f0); const m = findMatch(targetTextOf(entry, f.target), f.match, f.occurrence); return { i, scope: targetScope(f.target), from: m.from, to: m.to, scale: f.scale, highlight: f.highlight === false ? null : f.highlight, t: times[i].t, source: times[i].source, span: zoomSpan(f0, times[i].t) }; @@ -438,6 +866,76 @@ export function postZoomPlan(entry, render, total = Infinity) { } /** + * THE SEGMENT KEY's fields for a caption, the clock and the pace (appended to + * the key, never restructuring it): `{}` for an item with none of them, so its + * key is the one it had before they existed and its segment is reused. The + * entry itself is in the key (its `fx` -- each caption's text, match, at, + * hold, place; its clock fx's on/rewind -- its `narration.pace`, its id: a + * repeated item is its own segment); what it does NOT carry is added here: + * captionV / clockV the chip's and the clock's drawing (bumped when their look changes) + * clock clockPlan -- this post's time, the time it runs from (the + * item before's, when that one is a clock item), the mode + * (forward / rewind / none, a forced rewind) and the zone + * pace the gap knobs the pace resolved to (lead, tail, ramp, linger: + * a cut-level pace changes them without touching the entry) + */ +export const POST_CAPTION_DRAW_V = 2; +export const POST_CLOCK_DRAW_V = 1; +export function postFxKeyFields(entry, render, prev = null) { + const out = {}; + const fx = Array.isArray(entry?.fx) ? entry.fx : []; + if (fx.some((f) => f?.kind === "caption")) out.captionV = POST_CAPTION_DRAW_V; + const clk = clockPlan(entry, render, prev); + if (clk) Object.assign(out, { clockV: POST_CLOCK_DRAW_V, clock: clk }); + const k = postNarrationKnobs(entry, render); + if (isNarrated(entry) && k.pace && k.pace !== "normal") out.pace = { pace: k.pace, lead: k.lead, tail: k.tail, ramp: k.ramp, linger: k.linger }; + return out; +} + +/** + * THE SEGMENT's CACHE KEY's fields, pure (a build whose key matches keeps the segment it has): the entry as drawn + * (and as published), the box and framing, the palette and faces, the encode, every file's stamp, the avatars, the + * narration and its mix, the plan's follow -- which carries the thread's tiles and their schedule, their relations, + * the scene, a manual thread's stack, the branch map, the link visits and the join's seconds -- the slurs; and, only + * when an item has them (an item none of them touch keeps the key it had before them): + * + * joinFrom the join (post-join.mjs): the item before as its segment draws it, its follow, its length, what its slot + * ended on -- its card and box are drawn from these + * panel the plan's context media shows (post-thread.mjs panelSchedule) + * layout a wide attachment's top/bottom layout (postLayout's `panel`), and its boxes + * rv a renderer salt (POST_SEGMENT_RV), only when it is set: bump it (a string) when a card draws + * differently from an UNCHANGED plan, so a segment built before is rebuilt, never reused. Unset: every + * thread-scenes change to what a card draws rides on its plan (its follow: the tiles' relations, the + * scene, the map, the visits, the join) or on the fields above -- checked over the whole of mid-6 + * (post-render-key.test.mjs; an item with an unchanged key draws the same page as main's) + */ +export function postSegmentKeyOf({ entry, redaction = null, box, place = [], render, encode = [], stamps = [], avatars = {}, take = null, plan, bleeps = null, layout = null, from = null, prev = null }) { + return { + v: 1, entry, + // A redaction that changes what the card draws changes the key; none leaves it as it was. + ...(redactionOn(redaction) ? { published: redactEntry(entry, redaction), blank: termsFor(entry, redaction) } : {}), + box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, + ...(Object.keys(avatars).length ? { avatars } : {}), + ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}), + ...(plan.follow ? { follow: plan.follow } : {}), + ...(bleeps ? { bleeps } : {}), + ...(slursOn(redaction?.slurs) ? { slurs: redaction.slurs } : {}), + ...(from ? { joinFrom: { entry: from.entry, follow: from.plan.follow ?? null, total: from.plan.total, media: from.media.map((x) => [x.m.src, x.t, x.box]), fadeIn: from.fadeIn } } : {}), + ...(plan.panel ? { panel: plan.panel } : {}), + ...(layout?.panel === "top" || layout?.panel === "bottom" ? { layout: { panel: layout.panel, card: layout.card, slot: layout.slot } } : {}), + // A caption, the clock, the pace (post-caption.mjs, post-clock.mjs): nothing for an item with none of them. + ...postFxKeyFields(entry, render, prev), + ...(POST_SEGMENT_RV ? { rv: POST_SEGMENT_RV } : {}), + }; +} + +/** The renderer's salt (postSegmentKeyOf `rv`): null keeps every key as it was; a string rebuilds every post segment. */ +export const POST_SEGMENT_RV = null; + +/** The key of postSegmentKeyOf's fields. */ +export const postSegmentKey = (fields) => createHash("sha256").update(JSON.stringify(fields)).digest("hex"); + +/** * Build post item `entry`'s segment. `ctx`: `{ render, outDir, manifestDir, * box, place, encode, exec, ffmpeg, emit, avatars }` -- the box it fills (the * deck's footage box, or the frame), the deck's framing after it, @@ -451,23 +949,51 @@ export function postZoomPlan(entry, render, total = Infinity) { * attachment the anchor's, the scene's earlier messages above its card -- not * drawn when `scene` is). Returns the segment's path. */ -export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null, prev = null, scene = null, mediaScene = null }) { +export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null, prev = null, scene = null, mediaScene = null, join = null, joinFrom = 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); // In a media scene (post-media-scene.mjs) the shared attachment is the anchor's -- its markup laid on too. entry = sceneEntry(entry, mediaScene, { censor: (e) => censorEntry(e, redaction) }); + // A WIDE attachment at full width above (or below) the card: the cut's rule laid on (post-item.mjs panelEntry). + entry = panelEntry(entry, render); // 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`); // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in); `scene`: what // its run left on screen (post-conversation.mjs) -- in plan.follow, so in the segment's key; a media scene too. - const plan = postItemPlan(entry, render, { prev, scene, mediaScene }); + const plan = postItemPlan(entry, render, { prev, scene, mediaScene, join }); const layout = postLayout(entry, box); + // THE JOIN (post-join.mjs): the item before as ITS segment draws it (its markup, its media scene, the cut's panel + // rule), its plan -- what this item opens on. `joinFrom`: its entry and its context (planContext's, mediaSceneOf's). + let from = null; + if (plan.follow?.join && joinFrom?.entry?.type === "post") { + let pe = censorEntry(joinFrom.entry, redaction); + pe = panelEntry(sceneEntry(pe, joinFrom.mediaScene ?? null, { censor: (e) => censorEntry(e, redaction) }), render); + const pp = postItemPlan(pe, render, { prev: joinFrom.prev ?? null, scene: joinFrom.scene ?? null, mediaScene: joinFrom.scene ? null : joinFrom.mediaScene ?? null, join: joinFrom.join ?? null }); + const pl = postLayout(pe, box); + const ends = pl.slot && pl.mode === "side" ? endMediaOf(pp, { stepAt, mediaTimeAt, fps: render.fps ?? 30 }) : []; + const boxesOf = (list) => (list.length ? stepBoxes({ items: list.map((x, j) => ({ ...x.m, i: j })) }, pl.slot) : []); + const eb = boxesOf(ends); + const firstOwn = plan.steps[0]?.items?.[0] ?? null; + const ownBox = firstOwn && layout.slot && layout.mode === "side" ? stepBoxes(plan.steps[0], layout.slot)[0] : null; + // The same attachment in the same box (a media scene): held, neither faded. + const held = !!firstOwn && ends.length === 1 && ends[0].m.src === firstOwn.src && !!ownBox && Math.abs(ownBox.x - eb[0].x) < 2 && Math.abs(ownBox.y - eb[0].y) < 2 && Math.abs(ownBox.width - eb[0].width) < 2; + from = { + entry: pe, plan: pp, + media: held ? [] : ends.map((x, j) => ({ file: path.resolve(manifestDir, x.m.src), m: x.m, t: x.t, box: eb[j] })), + fadeIn: !held && !!firstOwn, + }; + } const files = (entry.media ?? []).map((m) => path.resolve(manifestDir, m.src)); for (const [i, f] of files.entries()) { if (!(await stat(f).catch(() => null))) throw new Error(`${entry.id}: media[${i}] is not on disk: ${f} (src: ${entry.media[i].src})`); } + // A context post's attachments (post-thread.mjs panelSchedule): files of the project, as the item's own are. + const panelFiles = (plan.panel?.shows ?? []).map((sh) => sh.media.map((m) => path.resolve(manifestDir, m.src))); + for (const [i, f] of panelFiles.flat().entries()) { + if (!(await stat(f).catch(() => null))) throw new Error(`${entry.id}: a context post's attachment is not on disk: ${f} (${i})`); + } const wordFiles = (entry.media ?? []).map((m) => (typeof m.words === "string" ? path.resolve(manifestDir, m.words) : null)); // Its narration's picked take (post-narration.mjs): a file of the project, levelled by its measured loudness. const take = isNarrated(entry) ? pickedTake(entry) : null; @@ -475,14 +1001,11 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box if (takeFile && !(await stat(takeFile).catch(() => null))) throw new Error(`${entry.id}: its narration take is not on disk: ${takeFile} (${take.file})`); // The slurs its take SAYS, covered (post-slurs.mjs): a public render never plays one -- without word timings it is refused. const bleeps = take ? takeSlurBleeps(entry, take, redaction) : null; - const stamps = await Promise.all([...files, ...wordFiles.filter(Boolean), ...Object.values(avatars), ...(takeFile ? [takeFile] : []), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : [])].map(async (f) => { + const stamps = await Promise.all([...files, ...panelFiles.flat(), ...(from?.media ?? []).map((x) => x.file), ...wordFiles.filter(Boolean), ...Object.values(avatars), ...(takeFile ? [takeFile] : []), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : [])].map(async (f) => { const st = await stat(f).catch(() => null); return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`; })); - const key = createHash("sha256") - // A redaction that changes what the card draws changes the key; none leaves it as it was. - .update(JSON.stringify({ v: 1, entry, ...(redactionOn(redaction) ? { published: redactEntry(entry, redaction), blank: termsFor(entry, redaction) } : {}), box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}), ...(plan.follow ? { follow: plan.follow } : {}), ...(bleeps ? { bleeps } : {}), ...(slursOn(redaction?.slurs) ? { slurs: redaction.slurs } : {}) })) - .digest("hex"); + const key = postSegmentKey(postSegmentKeyOf({ entry, redaction, box, place, render, encode, stamps, avatars, take, plan, bleeps, layout, from, prev })); const record = postRecordPath(seg); const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null); if (had?.key === key && (await stat(seg).catch(() => null))) { @@ -490,10 +1013,17 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box return seg; } const cardDir = path.join(outDir, "cards", `post-${entry.id}`); - const zoomPlan = postZoomPlan(entry, render, plan.total); - const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total }); + const zoomPlan = postZoomPlan(entry, render, plan.total, plan.narration); + // Its captions (post-caption.mjs): each waits for a zoom it would be up with, and is gone by the media phase (a stack card). + const capPlan = captionPlan(entry, render, { zooms: zoomPlan.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration ?? undefined }); + // Its clock (post-clock.mjs): the post's own time, run from the clock item before it. + const clk = clockPlan(entry, render, prev); + const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [] }); // NO HIDDEN TEXT IS EVER NARRATED (operator, 4 Nov): a part whose words are not in view, whole and lit, while it // is said -- or a context post drawn over its context size -- refuses the build (READ_IN_VIEW=warn: a note). + // A part read off a linked post's picture is on screen only while the panel shows it (post-thread.mjs panelReadErrors). + const panelErr = panelReadErrors(plan.follow, plan.panel, { id: entry.id }); + if (panelErr.length) cards.inView = [...(cards.inView ?? []), ...panelErr]; if (cards.inView?.length) { const msg = `${entry.id}: the read is not on screen while it is said (read-follow.mjs readInViewErrors):\n ${cards.inView.join("\n ")}`; if (process.env.READ_IN_VIEW === "warn") emit("note", { message: `warning: ${msg}` }); @@ -522,7 +1052,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg }); narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs, ...(bleeps ? { bleeps } : {}) }; } - const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null }); + const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null, panelFiles, map: cards.map ?? null, join: from && cards.joinFrom ? { seconds: plan.follow.join.seconds, fadeIn: from.fadeIn, from: from.media } : null, captionFx: cards.captions ?? [], clock: cards.clock ? { ...cards.clock, until: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total } : null }); try { await exec(ffmpeg, argv, { maxBuffer: 1 << 24 }); } catch (err) { @@ -532,13 +1062,17 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box await rename(tmp, seg); // The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides). if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true }); - await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8"); + // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. + await writeFile(`${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8"); + await rename(`${record}.tmp`, record); emit("note", { message: narration ? `${entry.id}: post item ${plan.total.toFixed(1)} s, narrated (${take.file}: ${plan.narration.seconds.toFixed(1)} s from ${plan.narration.at} s, muffled to ${plan.narration.voiceEnd.toFixed(1)} s)` : `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})`, }); if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` }); + if (cards.clock) emit("note", { message: `${entry.id}: clock ${clockFace(clk.to, clk.zone).time} ${clockFace(clk.to, clk.zone).date} (${clk.mode === "none" ? "shown" : clk.mode === "rewind" ? "rewound" : "run forward"}${clk.mode === "none" ? "" : ` from the item before, ${clk.gap / 60000 | 0} min`}), ${cards.clock.place}${cards.clock.covers ? ` -- WARNING: over ${cards.clock.covers} word(s)` : ""}` }); + for (const c of cards.captions ?? []) emit("note", { message: `${entry.id}: caption ${c.i + 1} "${c.text}" at ${c.t.toFixed(2)} s (${c.source === "at" ? "set by hand" : c.source === "words" ? "from the take's words" : "the reading estimate"}${c.span.waited !== null ? `, after word zoom ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.rel} the phrase ${c.placed.place === "card" ? "on the card" : "off the card"}${c.placed.leader ? ", a leader to it" : ""}${c.cutByPan ? ` (gone at ${c.cutByPan} s, before the card pans its phrase)` : ""}${c.placed.covers ? ` -- WARNING: no free space in the frame, it covers ${c.placed.covers} thing(s) drawn (shorten its text)` : ""}` }); for (const z of zooms) emit("note", { message: `${entry.id}: word zoom ${z.i + 1} at ${z.t.toFixed(2)} s (${z.source === "at" ? "set by hand" : "from the take's words"}), ${z.span.scale}× over ${z.span.t0}–${z.span.t3} s` }); return seg; } diff --git a/umtool/report-to-video/post-thread-scenes.test.mjs b/umtool/report-to-video/post-thread-scenes.test.mjs @@ -0,0 +1,325 @@ +// lane/thread-scenes: whole-thread reads (every ancestor read, oldest first), the read in DATE order, context +// posts with attachments, manual threads (`thread.group`), the join between items, the branch map, link visits. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { postCardHtml, postItemPlan, validatePostItem } from "./post-item.mjs"; +import { followPath, readInViewErrors, shotStateAt } from "./read-follow.mjs"; +import { partRoles, roleOrderOf, threadLayout, threadReadErrors } from "./post-thread.mjs"; + +const at = (h) => `2026-11-02T${String(h).padStart(2, "0")}:00:00.000Z`; +const ref = (id, handle, text, h, o = {}) => ({ id, author: handle, handle, date: at(h), text, ...o }); +const base = (o = {}) => ({ type: "post", id: "p-1", post: "acct-x/1001", platform: "x", author: "Subject", handle: "subject", date: at(20), text: "I was simply offering advice to everyone in the community today.", ...o }); +/** A take of pieces in order (para = piece * 100 + paragraph), each paragraph a part. */ +export function take(pieces, { roles = false } = {}) { + const parts = []; + let t = 0; + pieces.forEach(([text, role], pi) => { + text.split(/\n\n/).forEach((para, k) => { + const seconds = Math.round((para.split(/\s+/).length / 3) * 100) / 100; + t += parts.length ? (k === 0 ? 0.8 : 0.6) : 0; + parts.push({ n: parts.length + 1, para: pi * 100 + k, text: para, start: Math.round(t * 100) / 100, seconds, ...(roles && role ? { role } : {}) }); + t += seconds; + }); + }); + return { file: "narration/posts/1001/take-1.wav", engine: "orpheus", voice: "leo+zac", seconds: Math.round(t * 100) / 100, script: pieces.map((p) => p[0]).join("\n\n"), parts }; +} +export const narrate = (e, pieces, o) => ({ ...e, narration: { script: e.text, takes: [take(pieces, o)], pick: 0 } }); + +export function fakeGeo(plan, { H = 520, line = 44 } = {}) { + const blocks = {}; + const tiles = {}; + let y = 0; + for (const scope of plan.follow.thread.tiles.map((t) => t.scope)) { + const top = y; + y += 70; + for (const b of plan.follow.blocks.filter((x) => x.scope === scope)) { + const h = Math.max(1, Math.ceil((b.to - b.from + 1) / 6)) * line; + blocks[b.k] = { top: y, bottom: y + h }; + y += h + line; + } + tiles[scope] = { top, height: y - top }; + y += 22; + } + return { H, C: y, blocks, tiles }; +} + +const ROOT = "I was hit by my own brother and it hurt. I am real close to going atomic."; +const Q = "Lol what? You playing games with all of us again tonight?"; +const G = "Yes, that phrasing can be viewed as a threat under the law in most places."; + +test("WHOLE-THREAD READ: three ancestors read oldest first, then his words -- roles parent:2, parent:1, parent:0, post; each tile in full while read, then shrunk; the invariant holds", () => { + const parents = [ref("3", "grok", G, 19), ref("2", "asker", Q, 18), ref("1", "subject", ROOT, 17)]; + const e = narrate(base({ parents }), [[ROOT], [Q], [G], [base().text]]); + assert.deepEqual(partRoles(e).map((r) => r.role), ["parent:2", "parent:1", "parent:0", "post"]); + assert.deepEqual(validatePostItem(e), []); + const L = threadLayout(e); + assert.deepEqual(L.tiles.map((t) => [t.scope, t.mode]), [["parent:2", "full"], ["parent:1", "full"], ["parent:0", "full"], ["post", "full"]]); + assert.deepEqual(threadReadErrors(e), []); + const plan = postItemPlan(e, { postNarration: { lead: 0.4 } }); + const th = plan.follow.thread; + // The oldest opens the card; each later one revealed as its piece starts, each earlier one shrunk as the next starts. + const row = (sc) => th.tiles.find((t) => t.scope === sc); + assert.deepEqual(row("parent:2").from, [1, 1]); + assert.deepEqual(row("parent:1").from, [1, 0]); + assert.ok(row("parent:1").then, "parent:1 shrinks once parent:0 is read"); + const geo = fakeGeo(plan, { H: 400 }); + const path = followPath(plan.follow, geo); + assert.deepEqual(readInViewErrors(plan.follow, geo, shotStateAt(plan.follow, path, 30), { total: plan.total, id: e.id }), []); +}); + +test("THE READ IN DATE ORDER (operator, 4 Nov: D): a quoted take older than the post he answers is read first and drawn first -- the quote, the parent, his words", () => { + const take0 = "Here is my take on the whole situation, in two points."; + const kirsche = "I hate watching people defend the very tactics that lead to that happening."; + const e0 = base({ date: at(19), quoted: { author: "Subject", handle: "subject", date: at(16), text: take0 }, parents: [ref("2115500212617703691", "kirsche", kirsche, 17)] }); + assert.deepEqual(["quoted", "parent:0", "post"].map(roleOrderOf(e0)), [1, 2, 3]); + const e = narrate(e0, [[take0], [kirsche], [e0.text]]); + assert.deepEqual(partRoles(e).map((r) => r.role), ["quoted", "parent:0", "post"]); + const L = threadLayout(e); + assert.deepEqual(L.tiles.map((t) => t.scope), ["quoted", "parent:0", "post"]); + assert.equal(L.quotedAt, "above"); + const plan = postItemPlan(e, { postNarration: { lead: 0.4 } }); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(html.indexOf('data-thread-slot="quoted"') < html.indexOf('data-thread-slot="parent:0"'), "the quote drawn above the parent"); + const geo = fakeGeo(plan, { H: 400 }); + assert.deepEqual(readInViewErrors(plan.follow, geo, shotStateAt(plan.follow, followPath(plan.follow, geo), 30), { total: plan.total, id: e.id }), []); +}); + +test("AN IMAGE-ONLY REPLY is a tile (its head and a chip), never read; a parent's attachment is a file the lint checks", () => { + const e = narrate(base({ parents: [ref("9", "furri", "", 19, { media: [{ src: "posts-media/f/9/9_1.jpg", kind: "image", width: 600, height: 800 }] }), ref("1", "subject", ROOT, 17)] }), [[base().text]]); + assert.deepEqual(validatePostItem(e), []); + const L = threadLayout(e); + assert.deepEqual(L.tiles.map((t) => [t.scope, t.mode]), [["parent:1", "context"], ["parent:0", "context"], ["post", "full"]]); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: L }); + assert.match(html, /data-post-parent="0"[^>]*>.*data-thread-media="1">photo</s); + assert.deepEqual(validatePostItem({ ...e, parents: [{ media: [{ src: "/abs.jpg", kind: "image" }] }] }).length > 0, true); +}); + +import { conversationRuns, gatheredOrder, planContext } from "./post-conversation.mjs"; + +const said = (id, text, h, o = {}) => narrate(base({ id: `p-${id}`, post: `subj-x/${id}`, text, date: at(h), ...o }), [[text]]); + +test("A MANUAL THREAD (thread.group): consecutive items of one group are one run -- the opening post shown (not read) and three of his, unlinked on X -- every earlier post kept on screen, oldest first, each reply saying what it answers", () => { + const g = { group: "jiggle" }; + const movail = base({ id: "p-m", post: "mov-x/2117295478345998503", author: "Movail", handle: "Movail2", text: "Ready for more lessons?", date: at(16), thread: g }); + const tl = [ + { type: "clip", id: "c-0" }, + movail, + said("6841", "Phat ass jiggle, oh my god.", 22, { thread: g, post: "subj-x/2117379977360326841" }), + said("4063", "It jiggle.", 22, { thread: g, parents: [ref("2117379977360326841", "subject", "Phat ass jiggle, oh my god.", 22)] }), + said("0390", "it jiggle, oh my god, i literally cannot, hypnotism", 23, { thread: g, parents: [ref("2117295478345998503", "Movail2", "Ready for more lessons?", 16)] }), + said("9999", "Something else entirely.", 23), + ]; + const { runOf } = conversationRuns(tl); + assert.deepEqual(runOf, [-1, 0, 0, 0, 0, 1]); + const last = planContext(tl, 4); + assert.equal(last.scene.group, "jiggle"); + assert.deepEqual(last.scene.tiles.map((t) => [t.id, t.action]), [["2117295478345998503", "keep"], ["2117379977360326841", "keep"], ["4063", "keep"]]); + // His last message draws the stack: Movail2's post (its own parent:0 -- one tile), the two before, his words. + const L = threadLayout(tl[4], undefined, last); + assert.deepEqual(L.tiles.map((t) => t.scope), ["parent:0", "conv:2117379977360326841", "conv:4063", "post"]); + // The relations: "It jiggle." answers the post above; his last answers Movail2's post, three tiles up. + const L3 = threadLayout(tl[3], undefined, planContext(tl, 3)); + assert.deepEqual(L3.tiles.find((t) => t.scope === "post").rel, { to: "subject", above: true, id: "2117379977360326841" }); + assert.deepEqual(L.tiles.find((t) => t.scope === "post").rel, { to: "Movail2", above: false, id: "2117295478345998503" }); + const html = postCardHtml(tl[4], { width: 1600, height: 900, follow: true, thread: postItemPlan(tl[4], undefined, last).follow.thread }); + assert.match(html, /data-thread-rel="branch">replying to <span class="redact">@xxxxxxxx<\/span>/); +}); + +test("A MANUAL THREAD is gathered in DATE order (timeline threads --write): the group at its first item's place, the other conversations after it in their order", () => { + const g = { group: "grok" }; + const tl = [ + said("72", "She better watch her back.", 10, { thread: g }), + said("73", "I meant it as advice.", 12, { thread: g }), + said("74", "Another conversation.", 11), + said("75", "And another one.", 13), + said("78", "I was simply offering advice.", 14, { thread: g }), + said("80", "Last word.", 16, { thread: g }), + said("79", "Do you agree?", 15, { thread: g }), + ]; + const { ids } = gatheredOrder(tl); + assert.deepEqual(ids, ["p-72", "p-73", "p-78", "p-79", "p-80", "p-74", "p-75"]); +}); + +import { panelEntry, panelOf, postLayout, validatePostItems } from "./post-item.mjs"; + +test("A WIDE ATTACHMENT (operator, 4 Nov: \"a top-bottom layout would be better\"): 692×141 is laid at full width above the card; the cut's rule (wide, place) and the item's panel override", () => { + const wide = base({ media: [{ src: "posts-media/a/1.png", kind: "image", width: 692, height: 141 }] }); + const box = { width: 1920, height: 1080 }; + assert.equal(panelOf(wide), "top"); + const L = postLayout(wide, box); + assert.equal(L.mode, "side"); + assert.equal(L.panel, "top"); + assert.ok(L.slot.width > 1800 && L.slot.y < L.card.y, "the picture across the top, the card under it"); + assert.ok(L.slot.height <= Math.round(1080 * 0.42) && L.card.y + L.card.height <= 1080); + // A picture that is not wide stays beside the card; `panel` overrides either way. + assert.equal(panelOf(base({ media: [{ src: "a.png", kind: "image", width: 800, height: 600 }] })), "side"); + assert.equal(postLayout({ ...wide, panel: "side" }, box).panel, "side"); + assert.equal(postLayout({ ...wide, panel: "bottom" }, box).slot.y > 500, true); + // The cut's rule: a stricter threshold keeps it beside; place bottom. + assert.equal(postLayout(panelEntry(wide, { posts: { panel: { wide: 6 } } }), box).panel, "side"); + assert.equal(postLayout(panelEntry(wide, { posts: { panel: { place: "bottom" } } }), box).panel, "bottom"); + assert.match(validatePostItems({ render: { posts: { panel: { wide: 0.5 } } }, timeline: [] }).join(" "), /panel\.wide must be/); + // The card is drawn in its box under the picture. + const html = postCardHtml(wide, { width: 1920, height: 1080 }); + assert.match(html, new RegExp(`data-post-slot="" style="left:${L.slot.x}px;top:${L.slot.y}px;width:${L.slot.width}px`)); +}); + +import { panelReadErrors, panelSchedule, scrollAt, showOpacityAt } from "./post-thread.mjs"; +import { postSegmentArgs, scrollExpr } from "./post-render.mjs"; + +test("THE PANEL: a context post's picture over the slot while it is read; an image-only reply shown at least a beat; with no attachment of his own the last one held; a slot laid out for it", () => { + const pic = { src: "posts-media/b/1/baby.mp4", kind: "video", width: 720, height: 1280, seconds: 9 }; + const root = ref("1", "subject", "a video of my baby girl, pretty sure she's trying to eat me", 17, { media: [pic] }); + const e = narrate(base({ parents: [ref("2", "panda", "There is an acceptable level of crazy cat behaviour and this is it.", 18), root] }), [[root.text], ["There is an acceptable level of crazy cat behaviour and this is it."], [base().text]]); + const L = postLayout(e, { width: 1920, height: 1080 }); + assert.equal(L.mode, "side", "his reply has no attachment: the slot is for the root's video"); + const plan = postItemPlan(e, { postNarration: { lead: 0.4 } }); + assert.equal(plan.panel.shows.length, 1); + const sh = plan.panel.shows[0]; + assert.equal(sh.scope, "parent:1"); + assert.equal(sh.t0, 0); + assert.equal(sh.t1, plan.total, "held to the end: he carries none"); + assert.equal(showOpacityAt(sh, 0.1), 1); + // Over his own attachment: from its piece until his words come. + const own = { ...e, media: [{ src: "posts-media/b/2/own.jpg", kind: "image", width: 800, height: 800 }] }; + const p2 = postItemPlan(own, { postNarration: { lead: 0.4 } }); + const post = p2.follow.blocks.find((b) => b.scope === "post"); + assert.ok(Math.abs(p2.panel.shows[0].t1 - (post.start - 0.4)) < 0.01); + // The build lays it over the slot, crossfaded out. + const argv = postSegmentArgs({ entry: own, box: { width: 1920, height: 1080 }, plan: p2, layout: postLayout(own, { width: 1920, height: 1080 }), cards: { read: "r.png" }, files: ["own.jpg"], render: { fps: 30 }, outPath: "o.mp4", panelFiles: [["baby.mp4"]] }); + const fc = argv[argv.indexOf("-filter_complex") + 1]; + assert.match(fc, /fade=t=out:st=[\d.]+:d=0\.3:alpha=1\[pn0_0\]/); + assert.ok(argv.includes("baby.mp4")); +}); + +test("A LINKED POST's PICTURE READ THROUGH (H): its transcript's parts are picture blocks; the tall screenshot scrolls top to foot as they are read; the guard names a part read while the panel is elsewhere", () => { + const dm = "first line of the messages he sent\n\nsecond line of the messages he sent\n\nthird and last line of them"; + const link = { id: "2116805001309823299", handle: "Infinity_Virus_", author: "Infinity", date: at(8), text: "Ya try to be civil and they go insane", transcript: dm, media: [{ src: "posts-media/iv/1.jpg", kind: "image", width: 600, height: 4029 }] }; + const saber = ref("5", "SaberXVeritas", "this you? https://x.com/Infinity_Virus_/status/2116805001309823299", 9); + const e = narrate(base({ parents: [saber], links: [link] }), [["this you?", "parent:0"], ["Ya try to be civil and they go insane", "linked:0"], [dm, "linked:0"], [base().text, "post"]], { roles: true }); + assert.deepEqual(validatePostItem(e), []); + const plan = postItemPlan(e, { postNarration: { lead: 0.4 } }); + const pics = plan.follow.blocks.filter((b) => b.pic); + assert.equal(pics.length, 3); + const sh = plan.panel.shows.find((x) => x.scope === "linked:0"); + assert.ok(sh.scroll.length >= 4); + assert.equal(scrollAt(sh.scroll, sh.t0), 0); + assert.equal(scrollAt(sh.scroll, plan.total), 1); + assert.ok(scrollAt(sh.scroll, pics[1].start + 0.5) > 0.2 && scrollAt(sh.scroll, pics[1].start + 0.5) < 0.8); + assert.match(scrollExpr(sh.scroll), /^if\(lt\(t,/); + assert.deepEqual(panelReadErrors(plan.follow, plan.panel, { id: e.id }), []); + assert.match(panelReadErrors(plan.follow, { shows: [] }, { id: e.id }).join(" "), /reads the picture of linked:0/); +}); + +import { joinFrameAt, joinKnobs, endMediaOf } from "./post-join.mjs"; +import { followStateAt, isDrawnState } from "./read-follow.mjs"; +import { mediaTimeAt, stepAt } from "./post-item.mjs"; + +test("THE JOIN (operator, 4 Nov: \"a thread-like smooth transition here rather than a cut\"): an item of a run opens on the item before as it ended -- its read after the join's seconds, the card morphing from that item's box, the post it ended on carried in drawn as it was", () => { + const root = said("1", "You all have low testosterone, if I go an entire week I become bestial.", 10); + const ryobi = ref("2", "Ryobi_404", "Three days is enough to make me feel like a completely different person.", 11); + const reply = narrate(base({ id: "p-2", post: "subj-x/2", date: at(12), parents: [ryobi, ref("1", "subject", root.text, 10)] }), [[ryobi.text], [base().text]]); + const tl = [root, reply]; + const ctx = planContext(tl, 1, { postNarration: { lead: 0.25 } }); + assert.deepEqual(ctx.join, { seconds: 0.6 }); + assert.equal(planContext(tl, 0).join, null, "the first of a run cuts in"); + const plain = postItemPlan(reply, { postNarration: { lead: 0.25 } }, { ...ctx, join: null }); + const plan = postItemPlan(reply, { postNarration: { lead: 0.25 } }, ctx); + assert.equal(plan.narration.at, 0.85, "the read starts after the join"); + assert.ok(Math.abs(plan.total - plain.total - 0.6) < 0.01, "the item a join longer"); + assert.equal(plan.follow.join.seconds, 0.6); + assert.equal(followStateAt(plan.follow, null, 0.3).join, 0.5); + assert.equal(followStateAt(plan.follow, null, 0.7).join, undefined); + assert.equal(isDrawnState({ op: {}, offset: 0, join: 0 }), false); + // The carried post is drawn as his post was (head and words), marked as the join's anchor. + const html = postCardHtml(reply, { width: 1600, height: 900, follow: true, thread: plan.follow.thread, join: { A: { x: 10, y: 10, width: 800, height: 500 }, size: 40 } }); + assert.match(html, /class="tile tpost tcarry" data-thread-tile="parent:1" data-thread-mode="carry" data-post-parent="1" data-join-anchor="">/); + assert.match(html, /data-join="\{/); + // The frame: at 0 the item before's box and its card; at 1 its own; the content cross-fades. + const g = { A: { x: 0, y: 100, width: 800, height: 400 }, B: { x: 400, y: 0, width: 1200, height: 900 }, slotA: { x: 900, y: 0, width: 900, height: 900 }, slotB: null }; + const f0 = joinFrameAt(g, 0); + assert.deepEqual([f0.R, f0.from.op, f0.own.op, f0.slotFrom], [g.A, 1, 0, 1]); + const f1 = joinFrameAt(g, 1); + assert.deepEqual([f1.R, f1.from.op, f1.own.op, f1.own.s, f1.slotFrom], [g.B, 0, 1, 1, 0]); + assert.equal(joinKnobs({ join: false }).on, false); + assert.equal(joinKnobs({}, { posts: { join: { seconds: 1 } } }).seconds, 1); + // What the item before ended on: a video held on its last frame, sought a little before its end. + const vplan = { total: 10, steps: [{ kind: "video", at: 0, seconds: 9.6, srcFrom: 0, srcTo: 9.6, items: [{ i: 0, src: "v.mp4", kind: "video", seconds: 9.6 }] }] }; + assert.deepEqual(endMediaOf(vplan, { stepAt, mediaTimeAt }).map((x) => [x.m.src, x.t]), [["v.mp4", 9.48]]); +}); + +import { linkVisits, visitStateAt } from "./post-link-visit.mjs"; + +test("A LINK VISIT: his reply ends \"Here's my take on it. <link>\" to his own take, read first (in date order) -- once the link is read the pointer clicks it and the take is lit again, full, for its hold; the item holds it", () => { + const takeText = "Here is my take on the whole situation, in two points."; + const kirsche = "I hate watching people defend the very tactics that lead to that happening."; + const words = "Kirsche you're wrong on this one, strawb seems like a traitor.\n\nHere's my take on it.\n\nhttps://x.com/subject/status/2115473673671020640"; + const e = narrate(base({ date: at(19), text: words, quoted: { author: "Subject", handle: "subject", date: at(16), text: takeText }, parents: [ref("2115500212617703691", "kirsche", kirsche, 17)] }), [[takeText], [kirsche], ["Kirsche you're wrong on this one, strawb seems like a traitor.\n\nHere's my take on it."]]); + const plan = postItemPlan(e, { postNarration: { lead: 0.4 } }); + assert.deepEqual(plan.follow.visits.map((v) => [v.from, v.to, v.id, v.open]), [["post", "quoted", "2115473673671020640", false]]); + const v = plan.follow.visits[0]; + assert.ok(plan.total >= v.at + v.hold, "the item holds the visit"); + const st = visitStateAt(plan.follow.visits, v.at + 0.6); + assert.equal(st.ring, 1); + const row = plan.follow.thread.tiles.find((t) => t.scope === "quoted"); + assert.deepEqual(followStateAt(plan.follow, null, v.at + 0.6).tiles.quoted.slice(0, 2), [1, 1]); + assert.ok(row.pulse); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.match(html, /<span class="link" data-link="2115473673671020640">/); + const geo = fakeGeo(plan, { H: 400 }); + assert.deepEqual(readInViewErrors(plan.follow, geo, shotStateAt(plan.follow, followPath(plan.follow, geo), 30), { total: plan.total, id: e.id }), []); +}); + +test("A LINK VISIT that OPENS: SaberXVeritas's \"this you? <link>\", then the linked post read -- the click lands as it comes in", () => { + const link = { id: "2116805001309823299", handle: "Infinity_Virus_", author: "Infinity", date: at(8), text: "Ya try to be civil and they go insane" }; + const saber = ref("5", "SaberXVeritas", "this you? https://x.com/Infinity_Virus_/status/2116805001309823299", 9); + const e = narrate(base({ parents: [saber], links: [link] }), [["this you?", "parent:0"], ["Ya try to be civil and they go insane", "linked:0"], [base().text, "post"]], { roles: true }); + const plan = postItemPlan(e, { postNarration: { lead: 0.4 } }); + assert.deepEqual(plan.follow.visits.map((v) => [v.from, v.to, v.open]), [["parent:0", "linked:0", true]]); + const row = plan.follow.thread.tiles.find((t) => t.scope === "linked:0"); + assert.equal(plan.follow.visits[0].at, row.t0); +}); + +import { mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs"; + +test("THE BRANCH MAP (operator, 4 Nov: \"a specific visual for changing thread branches\"): the sibling swap draws the run's posts as a tree, the light travelling from the post the item before ended on up to his root and down to the new reply; the label says it", () => { + const ROOTP = ref("771", "subject", "Many have questioned my methods in dealing with the whole mess.", 6); + const FOX = ref("834", "fox_one", "Far as people should be concerned you are no better than them.", 7); + const DRAC = ref("775", "drac_two", "Oh please, you were never going to change anything here.", 6); + const p11 = narrate(base({ id: "p-11", post: "subj-x/11", date: at(10), text: "I feel like I've failed everyone.", parents: [ROOTP] }), [["I feel like I've failed everyone."]]); + const p12 = narrate(base({ id: "p-12", post: "subj-x/12", date: at(11), text: "You are nobody at all.", parents: [FOX, ref("11", "subject", p11.text, 10)] }), [[FOX.text], ["You are nobody at all."]]); + const p13 = narrate(base({ id: "p-13", post: "subj-x/13", date: at(12), text: "Who are you to tell me.", parents: [DRAC, ROOTP] }), [[DRAC.text], ["Who are you to tell me."]]); + const tl = [p11, p12, p13]; + const L = threadLayout(p13, undefined, planContext(tl, 2)); + assert.deepEqual(L.map.path, ["12", "834", "11", "771", "775"]); + assert.equal(L.map.label, "another reply to his post"); + // No map where the scene does not change branch (p-12 reads the reply to the post the item before ended on). + assert.equal(threadLayout(p12, undefined, planContext(tl, 1)).map, undefined); + const plan = postItemPlan(p13, undefined, planContext(tl, 2)); + const m = plan.follow.thread.map; + assert.ok(m.times.t0 >= 0.6 - 1e-6, "after the join"); + assert.deepEqual(mapStateAt(m, m.times.travel), { op: 1, p: 0 }); + assert.equal(mapStateAt(m, m.times.travel + 1.1).p, 1); + assert.equal(followStateAt(plan.follow, null, m.times.travel + 0.5).map.op, 1); + // Its own layer, never over words being read: over the slot, else beside a card alone. + const html = mapPageHtml(m, { width: 300, height: 200 }); + assert.match(html, /data-thread-map="both"/); + assert.match(html, /another reply to his post/); + assert.doesNotMatch(postCardHtml(p13, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }), /data-thread-map/); + const size = mapSize(m); + const side = { mode: "side", card: { x: 36, y: 36, width: 700, height: 1008 }, slot: { x: 772, y: 36, width: 1112, height: 1008 } }; + assert.deepEqual(mapPlace(side, { width: 1920, height: 1080 }, size), { x: 788, y: 52 }); + const alone = { mode: "text", card: { x: 370, y: 36, width: 1180, height: 1008 }, slot: null }; + assert.equal(mapPlace(alone, { width: 1920, height: 1080 }, size).x, 370 + 1180 + 32); + // Off for the item, or a label only. + assert.equal(threadLayout({ ...p13, thread: { map: false } }, undefined, planContext(tl, 2)).map, undefined); + assert.equal(threadLayout({ ...p13, thread: { map: "label" } }, undefined, planContext(tl, 2)).map.style, "label"); +}); + +import { chronoPieces } from "./post-thread.mjs"; + +test("chronoPieces: what a batch reads, oldest first -- his take (16:00), Kirsche (17:45), his reply (19:03); a carried post skipped", () => { + const e = base({ date: at(19), text: "Kirsche you're wrong on this one.", quoted: { author: "Subject", handle: "subject", date: at(16), text: "Here is my take." }, parents: [ref("2", "kirsche", "I hate watching it.", 17)] }); + assert.deepEqual(chronoPieces(e).map((p) => p.role), ["quoted", "parent:0", "post"]); + assert.deepEqual(chronoPieces(e, { skip: ["parent:0"] }).map((p) => p.role), ["quoted", "post"]); +}); diff --git a/umtool/report-to-video/post-thread.mjs b/umtool/report-to-video/post-thread.mjs @@ -48,11 +48,12 @@ // 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 { POST_PARENTS_MAX, cardText, contextText, linksOf, parentsOf, refMediaOf, refShown } from "./post-item.mjs"; import { draftScript, isNarrated, isOnlyUrls, joinSplitLinks, pickedTake, scriptParts, spokenUrls } from "./post-narration.mjs"; import { normWord, scriptWordsOf } from "./word-zoom.mjs"; import { followKnobs } from "./read-follow.mjs"; import { planContext } from "./post-conversation.mjs"; +import { branchMapOf, mapKnobs, mapTimes } from "./post-branch-map.mjs"; /** What a context tile may be. */ export const THREAD_MODES = Object.freeze(["auto", "full", "excerpt", "context", "carry", "hidden"]); @@ -63,12 +64,16 @@ 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)); +/** `thread.group` (one item's): a MANUAL THREAD -- consecutive items of one group play as one scene (post-conversation.mjs). */ +export const THREAD_GROUP_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/; +/** `thread.map`: the branch map (post-branch-map.mjs) -- on, off, or its style. */ +export const THREAD_MAP_VALUES = Object.freeze([true, false, "map", "label", "both"]); +const KEYS = new Set([...Object.keys(THREAD_DEFAULTS), "group", "map"]); 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)$/; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; // --------------------------------------------------------------------------- // The knobs. @@ -79,16 +84,18 @@ const modeOk = (v, carryOk) => typeof v === "string" && THREAD_MODES.includes(v) /** 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? }`]; + if (!isObj(v)) return [`${where} must be { parent?, quoted?, carry?, reveal?, shrink?, dim?, seconds?, pan?, group? }`]; 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 (!list.length || list.length > POST_PARENTS_MAX || !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`); + if (v.map !== undefined && !THREAD_MAP_VALUES.includes(v.map)) errors.push(`${where}.map must be true, false, "map", "label" or "both" (the branch map)`); + if (v.group !== undefined && !(typeof v.group === "string" && THREAD_GROUP_RE.test(v.group))) errors.push(`${where}.group must be a name (letters, digits, . _ -): the manual thread the item plays in`); 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"}`); @@ -110,9 +117,14 @@ const pick = (o) => (isObj(o) ? Object.fromEntries(Object.entries(o).filter(([k, */ 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) }); + const { group: _g, ...cut } = pick(r); + void _g; + return /** @type {any} */ ({ ...THREAD_DEFAULTS, ...cut, ...pick(entry?.thread) }); } +/** An item's manual thread (`thread.group`), or null. */ +export const groupOf = (e) => (typeof e?.thread?.group === "string" && THREAD_GROUP_RE.test(e.thread.group) ? e.thread.group : null); + /** 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"; @@ -134,22 +146,29 @@ const pairsOf = (keys) => keys.slice(1).map((k, i) => `${keys[i]} ${k}`); export function readTexts(entry) { const out = []; const spoken = (t) => (str(t).trim() ? draftScript(t).script : ""); - const add = (role, forms) => { + const add = (role, forms, pic = false) => { 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)) }); + out.push({ role, keys: new Set(lists.flat()), pairs: new Set(lists.flatMap(pairsOf)), ...(pic ? { pic: true } : {}) }); }; 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)]); } + // A post its words link to (`links[]`): read in place when the take reads it. + linksOf(entry).forEach((l, i) => { + add(`linked:${i}`, [contextText(l), str(l.text), spoken(contextText(l)), spoken(l.text)]); + // The words read off its picture: matched by their word pairs only (a two-word part is never a picture's). + add(`linked:${i}`, [str(l.transcript), spoken(l.transcript)], true); + }); 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 (text.pic && keys.length < 3) return 0; if (keys.length >= 3) { const pairs = pairsOf(keys); return pairs.filter((p) => text.pairs.has(p)).length / pairs.length; @@ -157,8 +176,25 @@ function shareOf(keys, text) { 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 read's order of the roles by KIND (a parent, oldest first, before the quoted post before his words). */ +const kindOrder = (role) => (role.startsWith("parent:") ? 2 - Number(role.slice(7)) / 10 : role === "quoted" ? 3 : role.startsWith("linked:") ? 3.5 : role === "post" ? 4 : 5); + +/** + * THE READ's ORDER of the roles (operator, 4 Nov: "include the whole thread chronologically"): by the DATE of + * the post each reads when every text has one -- the chain oldest first, a quoted post at its own date, his words + * at theirs -- else by kind (kindOrder). An attachment's words come last. Ranks from 1. + */ +export function roleOrderOf(entry) { + const dates = new Map(); + parentsOf(entry).forEach((p, i) => dates.set(`parent:${i}`, Date.parse(str(p?.date)))); + if (isObj(entry?.quoted)) dates.set("quoted", Date.parse(str(entry.quoted.date))); + linksOf(entry).forEach((l, i) => dates.set(`linked:${i}`, Date.parse(str(l?.date)))); + dates.set("post", Date.parse(str(entry?.date))); + if (![...dates.values()].every(Number.isFinite)) return kindOrder; + const ranked = [...dates.keys()].sort((a, b) => dates.get(a) - dates.get(b) || kindOrder(a) - kindOrder(b)); + const rank = new Map(ranked.map((r, i) => [r, i + 1])); + return (role) => rank.get(role) ?? ranked.length + 1; +} /** * THE ROLES of the picked take's parts, pure: `[{ role, source }]` (one a @@ -178,6 +214,7 @@ export function partRoles(entry, take = undefined) { } if (!parts.length) return []; const texts = readTexts(entry); + const orderOf = roleOrderOf(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); @@ -267,7 +304,8 @@ export function threadLayout(entry, render = undefined, { prev = null, scene = n const parents = parentsOf(entry); for (let i = parents.length - 1; i >= 0; i -= 1) { const scope = `parent:${i}`; - if (!contextText(parents[i]).trim()) continue; + // An image-only reply (no words, a picture) is drawn too: its head and its attachment in the slot. + if (!refShown(parents[i])) continue; let mode = parentKnob(k, i); const isRead = read.has(scope); if (mode === "auto") { @@ -290,20 +328,78 @@ export function threadLayout(entry, render = undefined, { prev = null, scene = n if (q.above) tiles.push(q, post); else tiles.push(post, q); } else tiles.push(post); + // THE POSTS ITS WORDS LINK TO (`links[]`, a link visit): each a tile after the one whose words link it (else after his). + linksOf(entry).forEach((l, i) => { + if (!refShown(l)) return; + const scope = `linked:${i}`; + const isRead = read.has(scope); + const from = linkedFrom(entry, l); + const at = tiles.findIndex((t) => t.scope === (from ?? "post")); + tiles.splice(at < 0 ? tiles.length : at + 1, 0, { scope, mode: isRead ? "full" : "context", read: isRead, ...(from ? { linkedFrom: from } : {}) }); + }); + // THE READ's ORDER (operator, 4 Nov: "read the whole thread chronologically"): the tiles in the order the take + // reads them -- a quote read before the post it answers sits above it -- one not read where it stood before the next. + orderByRead(tiles, roles); const quotedAtOut = tiles.some((t) => t.above) ? "above" : "inside"; // THE SCENE (post-conversation.mjs): what the run had on screen, in the tree's order with this item's own tiles. - const scened = isNarrated(entry) ? sceneTiles(entry, tiles, scene, k) : tiles; + const scened = withRelations(entry, isNarrated(entry) ? sceneTiles(entry, tiles, scene, k) : tiles, { group: !!scene?.group || !!groupOf(entry) }); const on = isNarrated(entry) && scened.some((t) => t.scope !== "post" && t.mode !== "hidden"); - return { on, tiles: scened, roles, quotedAt: quotedAtOut }; + // THE BRANCH MAP (post-branch-map.mjs): where the scene goes when it changes branch. + const map = on && scene && prev ? layoutMap(entry, scened, roles, { prevId: prevId, group: !!scene?.group || !!groupOf(entry), knobs: mapKnobs(entry, render) }) : null; + return { on, tiles: scened, roles, quotedAt: quotedAtOut, ...(map ? { map } : {}) }; } -/** The id a tile of `entry` draws (a parent's, his post's; null: a quoted post, a scene tile's own). */ -function tileIdOf(entry, t) { +/** The id a tile of `entry` draws (a parent's, his post's, a quoted or linked post's; null: none known). */ +export function tileIdOf(entry, t) { if (t.scope === "post") return shownIdOf(entry) || null; + if (t.scope === "quoted") return str(entry?.quoted?.id) || statusIdOf(entry?.quoted?.url) || null; + const l = /^linked:(\d)$/.exec(t.scope); + if (l) return str(linksOf(entry)[Number(l[1])]?.id) || null; const m = /^parent:(\d)$/.exec(t.scope); return m ? str(parentsOf(entry)[Number(m[1])]?.id) || null : null; } +/** The status id an x.com / twitter.com link names (null: none). */ +export function statusIdOf(url) { + const m = /(?:x|twitter)\.com\/[^/\s]+\/status(?:es)?\/(\d{5,25})/i.exec(str(url)); + return m ? m[1] : null; +} + +/** The tile whose words link to post `ref` (a status link naming its id): "post", "parent:<i>", "quoted" -- null: none. */ +export function linkedFrom(entry, ref) { + const id = str(ref?.id) || statusIdOf(ref?.url); + if (!id) return null; + const holds = (t) => [...str(t).matchAll(/https?:\/\/\S+/g)].some((m) => statusIdOf(m[0]) === id); + if (holds(cardText(entry))) return "post"; + const ps = parentsOf(entry); + for (let i = 0; i < ps.length; i += 1) if (holds(ps[i]?.text)) return `parent:${i}`; + if (isObj(entry?.quoted) && holds(entry.quoted.text)) return "quoted"; + return null; +} + +/** + * The tiles in place in THE READ's ORDER: each read tile by its first part; a tile not read (and a quoted post + * inside his) keeps its place before the next tile it stood before. Stable when the read is in the drawn order. + */ +function orderByRead(tiles, roles) { + const first = new Map(); + roles.forEach((r, k) => { + if (r?.role && !first.has(r.role)) first.set(r.role, k); + }); + const own = (t) => t.scope !== "quoted" || !!t.above; + const keyed = tiles.map((t, i) => ({ t, i, k: own(t) && first.has(t.scope) ? first.get(t.scope) : null })); + // A tile not read takes the key of the next read tile after it (it stands before it), less a little. + for (let i = keyed.length - 1, next = Infinity; i >= 0; i -= 1) { + if (keyed[i].k !== null) next = keyed[i].k; + else keyed[i].k = next - 0.5 + i / 1000; + } + // A quoted post inside his post rides with it. + const post = keyed.find((x) => x.t.scope === "post"); + for (const x of keyed) if (x.t.scope === "quoted" && !x.t.above && post) x.k = post.k + 0.0001; + keyed.sort((a, b) => a.k - b.k || a.i - b.i); + tiles.splice(0, tiles.length, ...keyed.map((x) => x.t)); +} + /** * The layout's tiles with the SCENE's (planContext's `scene.tiles`: `{ id, * ref, from: "full"|"small", action: "keep"|"collapse" }`) merged in, in the @@ -314,6 +410,12 @@ function sceneTiles(entry, tiles, scene, k) { const list = Array.isArray(scene?.tiles) ? scene.tiles : []; if (!list.length) return tiles; const own = new Set(tiles.filter((t) => t.mode !== "hidden").map((t) => tileIdOf(entry, t)).filter(Boolean)); + // A post of his own card the run already had on screen grows from where it was (small), never pops in from nothing. + const was = new Map(list.filter((t) => isObj(t) && str(t.id)).map((t) => [str(t.id), t.from === "full" ? [1, 1] : [k.shrink, k.dim]])); + for (const t of tiles) { + const id = tileIdOf(entry, t); + if (id && was.has(id) && t.mode !== "hidden") t.fromScene = was.get(id); + } const extra = list .filter((t) => isObj(t) && str(t.id) && isObj(t.ref) && !own.has(str(t.id))) .map((t) => ({ @@ -344,6 +446,57 @@ function sceneTiles(entry, tiles, scene, k) { return [...mine, ...theirs].map((x, i) => ({ ...x, i })).sort((a, b) => a.r - b.r || a.i - b.i).map((x) => x.t); } +/** + * Each tile's RELATION to what it answers (operator, 4 Nov: "subtly indicate the original relations"): `rel` -- + * `{ to: <handle> | null, above: boolean, id }` -- when the post it answers is NOT the tile drawn just above it + * (a branch: "replying to @X"), and, in a manual thread (`group`), on every reply ("replying to the post above"). + * From the real parents: his post answers parents[0], parents[i] answers parents[i + 1], a scene post its own. + */ +function withRelations(entry, tiles, { group = false } = {}) { + const parents = parentsOf(entry); + const answers = (t) => { + if (t.scope === "post") return parents[0] ? { id: str(parents[0].id), handle: str(parents[0].handle) } : str(entry?.replyingTo) ? { id: "", handle: str(entry.replyingTo) } : null; + const m = /^parent:(\d)$/.exec(t.scope); + if (m) { + const p = parents[Number(m[1]) + 1]; + return p ? { id: str(p.id), handle: str(p.handle) } : null; + } + if (t.mode === "scene" && isObj(t.ref?.replyTo)) return { id: str(t.ref.replyTo.id), handle: str(t.ref.replyTo.handle) }; + return null; + }; + const idOf = (t) => (t.mode === "scene" ? t.scope.slice(5) : tileIdOf(entry, t)); + const drawn = tiles.filter((t) => t.mode !== "hidden" && (t.scope !== "quoted" || t.above)); + return tiles.map((t) => { + if (t.mode === "hidden" || (t.scope === "quoted" && !t.above) || t.scope.startsWith("linked:")) return t; + const a = answers(t); + if (!a) return t; + const at = drawn.indexOf(t); + const above = at > 0 ? idOf(drawn[at - 1]) : null; + const isAbove = !!a.id && above === a.id; + if (isAbove && !group) return t; + return { ...t, rel: { to: a.handle || null, above: isAbove, id: a.id || null } }; + }); +} + +/** The branch map of a laid-out card (post-branch-map.mjs branchMapOf), from its tiles' ids, parents and authors. */ +function layoutMap(entry, tiles, roles, { prevId, group, knobs }) { + if (!knobs.on) return null; + const parents = parentsOf(entry); + const node = (t) => { + if (t.mode === "hidden") return null; + if (t.mode === "scene") return { scope: t.scope, id: t.scope.slice(5), parent: str(t.ref?.replyTo?.id), handle: str(t.ref?.handle) }; + if (t.scope === "post") return { scope: t.scope, id: shownIdOf(entry), parent: str(parents[0]?.id), handle: str(entry?.handle) }; + const m = /^parent:(\d)$/.exec(t.scope); + if (m) return { scope: t.scope, id: str(parents[Number(m[1])]?.id), parent: str(parents[Number(m[1]) + 1]?.id), handle: str(parents[Number(m[1])]?.handle) }; + return null; + }; + const nodes = tiles.map(node).filter((n) => n && n.id); + // The post read first is where the scene goes (his own when he is read first). + const first = roles.find((r) => r.role && (r.role === "post" || r.role.startsWith("parent:")))?.role ?? "post"; + const now = nodes.find((n) => n.scope === first)?.id ?? shownIdOf(entry); + return branchMapOf(nodes, { prevId, nowId: now, subject: str(entry?.handle), style: knobs.style, group }); +} + /** 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; @@ -351,7 +504,7 @@ export const tileModeOf = (layout, scope) => layout?.tiles?.find((t) => t.scope // 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}`); +const ROLE_NAME = (r) => (r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r.startsWith("linked:") ? "the post its words link to" : 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, @@ -383,7 +536,7 @@ export function threadReadErrors(entry, render = undefined, { prev = null, scene 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"; + const knob = r.role === "quoted" ? "thread.quoted" : r.role.startsWith("linked:") ? "thread.linked" : "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}`); } }); @@ -475,8 +628,8 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4 }) { // A quoted post above his: a top-level tile like a parent (revealed, shrunk); inside his: it only dims. const own = t.scope !== "quoted" || !!t.above; if (own && revealed(t.scope, T0)) { - // Revealed when its read comes (an older post read before it). - row.from = [1, 0]; + // Revealed when its read comes (an older post read before it) -- from where the run had it, when it had it. + row.from = t.fromScene ?? [1, 0]; row.to = [1, 1]; Object.assign(row, win(T0)); if (T !== null) row.then = { to: small, ...win(T) }; @@ -486,9 +639,13 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4 }) { } } if (t.above) row.above = true; + if (t.rel) row.rel = t.rel; + if (t.linkedFrom) row.linkedFrom = t.linkedFrom; tiles.push(row); } - return { shrink: k.shrink, dim: k.dim, seconds: k.seconds, pan: k.pan, contextRoom: THREAD_CONTEXT_ROOM, quotedAt: above ? "above" : "inside", tiles }; + // THE BRANCH MAP (post-branch-map.mjs): in as the scene changes branch (its first piece, less the pan's lead). + const map = layout.map ? { ...layout.map, times: mapTimes(first ? Math.max(0, first.start - lead) : lead) } : null; + return { shrink: k.shrink, dim: k.dim, seconds: k.seconds, pan: k.pan, contextRoom: THREAD_CONTEXT_ROOM, quotedAt: above ? "above" : "inside", tiles, ...(map ? { map } : {}) }; } /** inOut cubic over [0, 1]. */ @@ -508,6 +665,12 @@ export function tileStateAt(row, s) { }; 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); + // A LINK VISIT (post-link-visit.mjs): lit again -- full size and strength over its hold, eased in and out. + const p = row.pulse; + if (p && s > p.t0 && s < p.t3) { + const w = s < p.t1 ? ease((s - p.t0) / Math.max(1e-6, p.t1 - p.t0)) : s > p.t2 ? 1 - ease((s - p.t2) / Math.max(1e-6, p.t3 - p.t2)) : 1; + v = [mix(v[0], 1, w), mix(v[1], 1, w)]; + } return [Math.round(v[0] * 1000) / 1000, Math.round(v[1] * 1000) / 1000]; } @@ -524,6 +687,7 @@ export function threadTimes(thread) { 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); + if (row.pulse) out.add(row.pulse.t0).add(row.pulse.t1).add(row.pulse.t2).add(row.pulse.t3); } return [...out].sort((a, b) => a - b); } @@ -638,3 +802,148 @@ export function validateThreadReads(manifest) { }); return errors; } + +// --------------------------------------------------------------------------- +// THE PANEL: a context post's attachment in the slot while it is on screen +// (operator, 4 Nov: "a parent or ancestor that carries media shows it while +// that piece is on screen"; furrimessiah's image-only reply, his "video of my +// baby girl"; Infinity_Virus_'s screenshot scrolled as its words are read). +// --------------------------------------------------------------------------- + +/** The panel's crossfade (s) and the least a context post's picture that is not read stays up (s). */ +export const PANEL = Object.freeze({ fade: 0.3, minUnread: 1.2 }); + +/** The context post a tile draws (a parent, the quoted post, a linked post), or null. */ +export function refOfScope(entry, scope) { + const m = /^(parent|linked):(\d)$/.exec(String(scope)); + if (m) return (m[1] === "parent" ? parentsOf(entry) : linksOf(entry))[Number(m[2])] ?? null; + return scope === "quoted" && isObj(entry?.quoted) ? entry.quoted : null; +} + +/** + * THE PANEL SCHEDULE, pure: `{ fade, shows: [{ scope, media, t0, t1, scroll? }] }` -- each context post with + * attachments shown over the slot from when its piece is read (its first block's start, less the pan's lead; one + * not read: from when its tile is on screen, at least PANEL.minUnread) until the next one's (his own words, when he + * carries attachments: they are under it, playing on their plan); the last one held to the end when he carries + * none. A tall picture whose words are read (a linked post's `transcript`) SCROLLS: `scroll` the keyframes + * `[[t, f]]` (f: 0 the picture's top in view, 1 its foot) through its parts, by their words. Null: none. + * + * @param {Record<string, any>} entry + * @param {Record<string, any> | null} follow the plan's (followSchedule) + * @param {number} total + */ +export function panelSchedule(entry, follow, total, { lead = 0.4 } = {}) { + const th = follow?.thread; + if (!th) return null; + const own = Array.isArray(entry?.media) && entry.media.length > 0; + const startOf = (scope) => { + const ts = (follow.blocks ?? []).filter((b) => b.scope === scope && fin(b.start)).map((b) => b.start); + return ts.length ? Math.min(...ts) : null; + }; + const cand = []; + for (const row of th.tiles ?? []) { + const media = refMediaOf(refOfScope(entry, row.scope)); + if (!media.length) continue; + const s = startOf(row.scope); + const on = row.read && s !== null ? s - lead : row.from?.[1] > 0 ? 0 : row.t0; + cand.push({ scope: row.scope, media, on: r3(Math.max(0, on)), read: !!row.read && s !== null }); + } + if (!cand.length) return null; + const postAt = startOf("post"); + if (own) cand.push({ scope: "own", on: r3(Math.max(0, (postAt ?? 0) - lead)), read: true }); + cand.sort((a, b) => a.on - b.on); + const shows = []; + cand.forEach((c, i) => { + if (c.scope === "own") return; + const next = cand[i + 1]; + // A context post's picture shown (not read) while his own words are read: a look at it, then his own attachment again. + const ownAt = cand.find((x) => x.scope === "own")?.on ?? null; + const end = next ? next.on : !c.read && ownAt !== null && c.on >= ownAt ? Math.min(total, c.on + 2 * PANEL.minUnread) : total; + const t1 = r3(Math.min(total, Math.max(end, c.read ? end : c.on + PANEL.minUnread))); + if (t1 <= c.on + 0.05) return; + const show = { scope: c.scope, media: c.media, t0: c.on, t1 }; + // A picture read through (its transcript's parts, read-follow.mjs pic blocks): scrolled top to foot as it is read. + const pics = (follow.blocks ?? []).filter((b) => b.scope === c.scope && b.pic && fin(b.start)).sort((a, b) => a.start - b.start); + if (pics.length) { + const words = pics.reduce((n, b) => n + (b.words ?? 1), 0) || 1; + const keys = [[c.on, 0]]; + let w = 0; + for (const b of pics) { + keys.push([r3(b.start), r3(w / words)]); + w += b.words ?? 1; + keys.push([r3(Math.max(b.start + 0.1, fin(b.end) ? b.end : b.start + 1)), r3(w / words)]); + } + show.scroll = keys; + } else { + // A TALL picture shown, not read (a screenshot of a long chat): its top at a readable width, drifting down a + // little -- never the whole of it shrunk to a sliver. + const m0 = c.media[0]; + if (m0?.kind === "image" && fin(m0.width) && fin(m0.height) && m0.height / Math.max(1, m0.width) > 2) show.scroll = [[c.on, 0], [t1, 0.12]]; + } + shows.push(show); + }); + return shows.length ? { fade: PANEL.fade, shows } : null; +} + +/** A scroll's place at item second `s` (0: the top in view, 1: the foot), linear between keyframes. */ +export function scrollAt(keys, s) { + if (!Array.isArray(keys) || !keys.length) return 0; + if (s <= keys[0][0]) return keys[0][1]; + for (let i = 1; i < keys.length; i += 1) { + const [t1, f1] = keys[i]; + const [t0, f0] = keys[i - 1]; + if (s <= t1) return t1 > t0 ? f0 + ((f1 - f0) * (s - t0)) / (t1 - t0) : f1; + } + return keys[keys.length - 1][1]; +} + +/** + * A panel show's strength at item second `s` (its crossfade in and out). + * @param {{ t0: number, t1: number }} show + * @param {number} s + * @param {number} [fade] + */ +export function showOpacityAt(show, s, fade = 0.3) { + if (s < show.t0 || s > show.t1 + fade) return 0; + const up = show.t0 <= 0.001 ? 1 : Math.min(1, (s - show.t0) / fade); + const down = s <= show.t1 ? 1 : 1 - (s - show.t1) / fade; + return Math.round(Math.max(0, Math.min(up, down)) * 1000) / 1000; +} + +/** + * THE PANEL's GUARD, pure: a part read off a linked post's PICTURE is on screen only while the panel shows that + * picture -- every such part whose read (less the settle) falls outside its show is named. + */ +export function panelReadErrors(follow, panel, { id = "?", settle = 0.35 } = {}) { + const errors = []; + for (const b of (follow?.blocks ?? []).filter((x) => x.pic && fin(x.start))) { + const show = (panel?.shows ?? []).find((sh) => sh.scope === b.scope); + const a = b.start + settle; + const z = Math.max(a, (fin(b.end) ? b.end : b.start) - 0.4); + if (!show || show.t0 > a + 1e-6 || show.t1 < z - 1e-6) errors.push(`${id}: part ${b.part + 1} reads the picture of ${b.scope}, which the panel does not show while it is said (${r3(b.start)}–${r3(fin(b.end) ? b.end : b.start)} s)`); + } + return errors; +} + +/** + * THE READ's PIECES IN DATE ORDER (operator, 4 Nov: "include the whole thread chronologically"), pure: what a + * narration batch reads, in the order to read it -- `[{ role, date, author, handle, text }]`, every context post + * the card draws with words (the parents, the quoted post, the linked posts; a linked post's `transcript` as its own + * words) and his post, oldest first (roleOrderOf). `skip`: roles the run has read already (a carried post). + * + * @param {Record<string, any>} entry + * @param {{ skip?: string[] }} [o] + */ +export function chronoPieces(entry, { skip = [] } = {}) { + const order = roleOrderOf(entry); + const out = []; + const add = (role, ref, text) => { + if (!str(text).trim() || skip.includes(role)) return; + out.push({ role, date: str(ref?.date) || null, author: str(ref?.author) || null, handle: str(ref?.handle) || null, text: str(text) }); + }; + parentsOf(entry).forEach((p, i) => add(`parent:${i}`, p, contextText(p))); + if (isObj(entry?.quoted)) add("quoted", entry.quoted, contextText(entry.quoted)); + linksOf(entry).forEach((l, i) => add(`linked:${i}`, l, [contextText(l), str(l.transcript)].filter((t) => t.trim()).join("\n\n"))); + add("post", entry, cardText(entry)); + return out.sort((a, b) => order(a.role) - order(b.role)); +} diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs @@ -43,11 +43,13 @@ // sets it on the page -- in the build per frame before a screenshot // (post-render.mjs), in Play per tick (PostItemPlayer). -import { cardText, contextReadSeconds, contextText, parentsOf, readSeconds } from "./post-item.mjs"; +import { cardText, contextReadSeconds, contextText, linksOf, 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, threadKnobs, threadLayout, threadSchedule, threadStateAt } from "./post-thread.mjs"; import { sceneLayout, sceneRows, sceneSchedule } from "./post-media-scene.mjs"; +import { linkVisits, visitRows, visitStateAt } from "./post-link-visit.mjs"; +import { mapStateAt } from "./post-branch-map.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] }); @@ -119,6 +121,10 @@ export function cardScopes(entry) { } out.push({ scope: "post", text: cardText(entry), ref: null }); if (isObj(entry?.quoted) && contextText(entry.quoted).trim()) out.push({ scope: "quoted", text: contextText(entry.quoted), ref: entry.quoted }); + // The posts its words link to (post-thread.mjs: a link visit; read in place when the take reads them). + linksOf(entry).forEach((l, i) => { + if (contextText(l).trim()) out.push({ scope: `linked:${i}`, text: contextText(l), ref: l }); + }); return out; } @@ -230,6 +236,18 @@ export function followBlocks(entry) { } const keys = partKeys(p.text); if (!keys.length) return; + // A part read off a LINKED post's picture (its `transcript`, post-thread.mjs: the picture scrolls as it is read): + // a block with no card words, its words counted for the scroll. + if (typeof p.scope === "string" && p.scope.startsWith("linked:")) { + const l = linksOf(entry)[Number(p.scope.slice(7))]; + const onCard = new Set(partKeys(contextText(l))); + const inPic = new Set(partKeys(l?.transcript ?? "")); + const share = (set) => keys.filter((x) => set.has(x)).length / keys.length; + if (inPic.size && share(inPic) > share(onCard)) { + media.push({ scope: p.scope, from: null, to: null, part: pi, pic: true, words: keys.length }); + return; + } + } // Which of the card's texts it reads: its own scope (the card's parts), else the one most of its words are in. let target = p.scope ? byScope.get(p.scope) : null; if (!target) { @@ -320,9 +338,9 @@ const wordsIn = (t) => scriptWordsOf(t).length; * run left on screen. A conversation scene WINS the card: with one, the media * scene is not drawn (it keeps only the attachment, sceneEntry). * - * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null, scene?: Record<string, any> | null, mediaScene?: Record<string, any> | null }} [o] + * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null, scene?: Record<string, any> | null, mediaScene?: Record<string, any> | null, join?: { seconds: number } | null }} [o] */ -export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null, scene = null, mediaScene = null } = {}) { +export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null, scene = null, mediaScene = null, join = null } = {}) { const k = followKnobs(entry, render); if (!k.on) return null; const map = followBlocks(entry); @@ -350,7 +368,8 @@ export function followSchedule(entry, render = undefined, { hold = null, narrati for (const sc of cardScopes(entry)) spans.set(sc.scope, sc.ref ? contextReadSeconds(sc.ref) : readSeconds(entry)); const reading = [...spans.values()].reduce((n, v) => n + v, 0); const f = fin(hold) && hold > reading + 1 ? (hold - 1) / reading : 1; - let t = 0; + // THE JOIN (post-join.mjs) comes first: the reading after it. + let t = join && fin(join.seconds) ? join.seconds : 0; for (const sc of cardScopes(entry)) { const mine = parts.map((p, i) => ({ p, i })).filter((x) => x.p.scope === sc.scope); const words = mine.reduce((n, x) => n + Math.max(1, wordsIn(x.p.text)), 0) || 1; @@ -378,8 +397,12 @@ export function followSchedule(entry, render = undefined, { hold = null, narrati // item's on its thread read's schedule, an un-narrated one's on the scene's. const layout = ms ? sceneLayout(base, entry, ms) : base; const own = !layout?.on ? null : base ? threadSchedule(entry, render, { layout, blocks, lead: FOLLOW_PAN.lead }) : sceneSchedule(threadKnobs(entry, render), { layout, blocks, lead: FOLLOW_PAN.lead }); - const thread = ms ? sceneRows(own, layout) : own; - return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks, ...(thread ? { thread } : {}) }; + const thread0 = ms ? sceneRows(own, layout) : own; + // LINK VISITS (post-link-visit.mjs): a link in the words visited -- the pointer, the click, the post opened. + const visits = thread0 && isNarrated(entry) ? linkVisits(entry, thread0, blocks, render) : []; + const thread = visits.length ? visitRows(thread0, visits) : thread0; + // THE JOIN (post-join.mjs): its first seconds morph from the item before as it ended. + return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks, ...(thread ? { thread } : {}), ...(visits.length ? { visits } : {}), ...(join && fin(join.seconds) ? { join: { seconds: join.seconds } } : {}) }; } /** The block being read at item second `s` (its k), or null (before the read's first block, or none). */ @@ -441,7 +464,7 @@ export function followPath(follow, geo) { } /** 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); +const tileScopeOf = (scope) => (scope === "quoted" || scope === "post" || String(scope).startsWith("parent:") || String(scope).startsWith("linked:") ? scope : null); /** * A THREADED card's PAN (post-thread.mjs), pure: `{ thread: true, start, @@ -475,7 +498,11 @@ export function threadPath(follow, geo) { const carry = (th.tiles ?? []).find((t) => t.mode === "carry") ?? (th.tiles ?? []).find((t) => t.mode === "scene" && t.wasPost); const g0 = at(0); let off; - if (carry && g0.tiles[carry.scope] && th.scene) { + if (carry && g0.tiles[carry.scope] && geo?.joinAnchor && fin(geo.joinAnchor.y)) { + // THE JOIN (post-join.mjs): the post the item before ended on, framed where that item left it (the anchor + // measured on both pages: its top this far down the window). + off = Math.round((g0.tiles[carry.scope].top - geo.joinAnchor.y) * 100) / 100; + } else if (carry && g0.tiles[carry.scope] && th.scene) { // A MEDIA SCENE (post-media-scene.mjs): framed as the item before ended -- what is on screen (the column down // to the carried message) centred, or its foot a margin above the window's when it runs past. const vis = g0.tiles[carry.scope].bottom; @@ -560,6 +587,12 @@ const ramp = (s, a, d) => (d <= 0 ? (s >= a ? 1 : 0) : easeOf("inOut", (s - a) / * end every block rises back to full. A map of fewer than two read blocks is * never dimmed. `path`: followPath's (null: no pan). */ +/** + * @param {Record<string, any> | null} follow + * @param {Record<string, any> | null} path + * @param {number} s + * @returns {{ op: Record<string, number>, offset: number, fadeTop: number, fadeBottom: number, current: any, tiles?: Record<string, number[]>, join?: number, visit?: { i: number, move: number, click: number, ring: number }, map?: { op: number, p: number } }} + */ export function followStateAt(follow, path, s) { const op = {}; if (!follow) return { op, offset: 0, fadeTop: 0, fadeBottom: 0, current: null }; @@ -582,6 +615,15 @@ export function followStateAt(follow, path, s) { const max = path?.max ?? 0; const edge = 24; const current = read.length ? followBlockAt(follow, s) ?? read[0].k : null; + // THE JOIN (post-join.mjs): its progress while the card morphs from the item before's. + /** @type {Record<string, any>} */ + const jp = follow.join && fin(follow.join.seconds) && s < follow.join.seconds - 1e-6 ? { join: Math.round((Math.max(0, s) / follow.join.seconds) * 1000) / 1000 } : {}; + // A LINK VISIT (post-link-visit.mjs): the pointer, its click, the linked post's ring. + const vs = follow.visits?.length ? visitStateAt(follow.visits, s) : null; + if (vs) jp.visit = vs; + // THE BRANCH MAP (post-branch-map.mjs): shown as the scene changes branch, its light travelling. + const ms = follow.thread?.map ? mapStateAt(follow.thread.map, s) : null; + if (ms) jp.map = ms; 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); @@ -604,6 +646,7 @@ export function followStateAt(follow, path, s) { fadeBottom: path?.H && below > 0.5 ? Math.round(clamp(below / edge, 0, 1) * 100) / 100 : 0, current, tiles, + ...jp, }; } return { @@ -612,11 +655,12 @@ export function followStateAt(follow, path, s) { 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, + ...jp, }; } /** 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, ...(st.tiles ? [st.tiles] : [])]); +export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom, ...(st.tiles ? [st.tiles] : []), ...(st.join !== undefined ? [st.join] : []), ...(st.visit ? [st.visit] : []), ...(st.map ? [st.map] : [])]); /** * Whether a state draws the card PAGE AS DRAWN (no state applied): nothing @@ -629,6 +673,7 @@ export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeT */ export function isDrawnState(st) { if (!st) return true; + if (fin(st.join) || st.visit || st.map) return false; if (Object.values(st.op ?? {}).some((o) => fin(o) && o < 0.9995)) return false; if (fin(st.offset) && Math.abs(st.offset) >= 0.5) return false; if ((st.fadeTop ?? 0) > 0 || (st.fadeBottom ?? 0) > 0) return false; @@ -650,7 +695,7 @@ export function isDrawnState(st) { export const READ_IN_VIEW = Object.freeze({ tol: 2, slack: 0.25, share: 0.5, step: 0.05, size: 0.005 }); const pct = (v) => `${Math.round(v * 100)}%`; -const tileName = (scope) => (scope === "post" ? "his post" : scope === "quoted" ? "the quoted post" : String(scope).startsWith("parent:") ? `the post it answers (${scope})` : String(scope)); +const tileName = (scope) => (scope === "post" ? "his post" : scope === "quoted" ? "the quoted post" : String(scope).startsWith("parent:") ? `the post it answers (${scope})` : String(scope).startsWith("linked:") ? `the post it links (${scope})` : String(scope)); /** * THE READ IN VIEW, pure: every reason the words being read are not on screen, @@ -753,6 +798,8 @@ export function readInViewErrors(follow, geo, stateAt, { total = null, id = "?" const lim = ctxMode ? (row.scope === "quoted" && th.quotedAt !== "above" ? [1, th.dim] : [th.shrink, th.dim]) : row.to; const from = ctxMode ? 0 : row.t1 + 0.05; for (let s = from; s <= end + 1e-9; s += 0.1) { + // Lit again by a link visit (post-link-visit.mjs): its hold is the visit's, not a read's. + if (row.pulse && s > row.pulse.t0 - 1e-6 && s < row.pulse.t3 + 1e-6) continue; const v = look(r3(s)); const sc = v.scaleOf(row.scope); const op = v.opOf(row.scope); diff --git a/umtool/report-to-video/word-zoom.mjs b/umtool/report-to-video/word-zoom.mjs @@ -31,8 +31,12 @@ import { cardText, contextText, parentsOf } from "./post-item.mjs"; import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; +import { captionErrors } from "./post-caption.mjs"; +import { clockErrors } from "./post-clock.mjs"; -export const POST_FX_KINDS = Object.freeze(["word-zoom"]); +// A post's effects: a word zoom, a CAPTION (post-caption.mjs: a chip explaining a phrase as it is read), and its +// CLOCK (post-clock.mjs: the post's time on the card, running from the item before's). +export const POST_FX_KINDS = Object.freeze(["word-zoom", "caption", "clock"]); export const POST_FX_MAX = 8; export const WORD_ZOOM_EASES = Object.freeze(["out", "inOut", "snap"]); export const WORD_ZOOM_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.5, hold: 1.2, scale: 2, ease: "inOut", highlight: "#ffd84d" }); @@ -136,6 +140,8 @@ export function validatePostFx(e) { const fw = `${w}[${i}]`; if (!isObj(fx)) return errors.push(`${fw} must be an object`); if (!POST_FX_KINDS.includes(fx.kind)) return errors.push(`${fw}.kind must be one of ${POST_FX_KINDS.join(", ")}`); + if (fx.kind === "caption") return errors.push(...captionErrors(e, fx, fw)); + if (fx.kind === "clock") return errors.push(...clockErrors(e, fx, fw)); for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a word-zoom key (${[...KEYS].join(", ")})`); const target = fx.target ?? "post"; const text = typeof target === "string" ? targetTextOf(e, target) : null; @@ -281,7 +287,7 @@ export function scriptWordTimes(script, recognized) { * @param {Record<string, any>} entry * @param {Record<string, any>} [render] * @param {Record<string, any> | null} [schedule] - * @returns {Array<{ i: number, t?: number, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>} + * @returns {Array<{ i: number, t?: number, kind?: string, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>} */ export function wordZoomTimes(entry, render = undefined, schedule = undefined) { const list = Array.isArray(entry?.fx) ? entry.fx : []; @@ -290,6 +296,8 @@ export function wordZoomTimes(entry, render = undefined, schedule = undefined) { // `schedule`: the item's narration schedule when the caller has it (Play: the plan's), else worked out here. const sch = narrated ? schedule ?? narrationSchedule(entry, render) : null; return list.map((fx0, i) => { + // Another effect (a caption, post-caption.mjs) is timed by its own module: no time here, and no error. + if (isObj(fx0) && fx0.kind !== "word-zoom" && POST_FX_KINDS.includes(fx0.kind)) return { i, kind: fx0.kind }; if (!isObj(fx0) || fx0.kind !== "word-zoom") return { i, error: "not a word zoom" }; const fx = resolveWordZoom(fx0); if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" };