commit 2b956ee1abe5c17b402d2f9b84a80854a7ee0cfe
parent d0de22133672dbf7264bcfb3df1204d2804a2937
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 14:10:37 -0500
Merge lane/thread-scenes: a thread is one continuous scene even when its layout changes -- each item opens on the item before as it ended and morphs into its own layout (the join), whole threads read in date order (up to 8 ancestors, parent refs and their media set by hand), manual threads (thread.group, relation lines), context media (an image-only reply, a root's video, a linked post's tall screenshot scrolled as its transcript is read), wide attachments laid top/bottom, link visits (a pointer clicks the link, the linked post opens), the branch map, synthetic post items (timeline insert post-json:), posts set-item parent./media./link./panel= (operator, 4 Nov notes on mid-6: "especially ones that switch layout", "read the whole thread context", "a specific visual for changing thread branches"); fix: take --from reuses post segments (the record linked, nothing written through)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
34 files changed, 2786 insertions(+), 158 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";
@@ -119,7 +119,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);
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/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -857,6 +857,11 @@ export default function PlayCut({
published={asPublished}
uncensored={uncensored}
scene={postNow.entry.postScene ?? 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,8 +2,12 @@
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 { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom";
@@ -80,6 +84,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 +100,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 +240,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 +308,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 +358,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, joinFrom = null,
}: {
project: string;
take?: string | null;
@@ -368,6 +433,8 @@ 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;
+ /** 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 +471,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,6 +501,35 @@ 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 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]);
@@ -446,6 +544,17 @@ export default function PostItemPlayer({
// 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>>) : [];
@@ -503,10 +612,44 @@ 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]);
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;
@@ -515,6 +658,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}
@@ -549,6 +694,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 +722,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,9 +83,9 @@ Inbox cannot disagree about what is wrong with one.
| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) |
| `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` |
-| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [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 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`) |
@@ -99,6 +99,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
@@ -822,6 +822,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
@@ -911,6 +911,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/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);
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -14,7 +14,7 @@ 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 { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs";
import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs";
@@ -60,10 +60,10 @@ 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 }),
...(mediaScene ? { postScene: { key: mediaScene.key, n: mediaScene.n, of: mediaScene.of, ids: mediaScene.ids, anchor: mediaScene.anchor.id } } : {}),
};
}
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -182,7 +182,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 } : {}),
}));
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,6 +113,15 @@ 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",
@@ -227,6 +241,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`,
@@ -637,6 +652,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 +715,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 +797,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 +876,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 +947,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,7 @@ 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"]);
+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"]);
/**
* Before an entry's segment is rebuilt: each of its files in `segDir` that is
@@ -6403,7 +6412,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") {
@@ -6440,6 +6451,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,6 +73,9 @@
"./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",
"./read-follow": "./read-follow.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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
+
+/**
+ * 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-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, """)}" 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
@@ -262,14 +262,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,
@@ -644,7 +646,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
@@ -267,6 +267,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 +277,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 +326,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,17 @@ 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 { POST_PICTURE_XFADE, POST_PUSH, cardAuthors, fxRedactionErrors, mediaTimeAt, panelEntry, postCardHtml, postItemPlan, postLayout, stepAt, stepBoxes } from "./post-item.mjs";
import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, 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 { 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 +63,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 +85,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 }) {
const fps = render.fps ?? 30;
const T = plan.total;
const inputs = [];
@@ -170,6 +187,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 +199,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));
@@ -237,7 +317,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 }) {
await mkdir(dir, { recursive: true });
const fonts = {
regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
@@ -251,14 +331,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 +390,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);
@@ -309,7 +443,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 +454,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 +472,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)))));
@@ -419,10 +618,10 @@ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotU
* 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);
+ 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) => {
@@ -438,6 +637,47 @@ export function postZoomPlan(entry, render, total = Infinity) {
}
/**
+ * 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 }) {
+ 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 } } : {}),
+ ...(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 +691,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 +743,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 }));
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 +755,13 @@ 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);
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from });
// 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 +790,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 });
try {
await exec(ffmpeg, argv, { maxBuffer: 1 << 24 });
} catch (err) {
@@ -532,7 +800,9 @@ 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 })) } : {}), ...(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)`
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);