commit ca21d22b0dfe3e2d00294cfc3108e0326250eb17
parent 2b956ee1abe5c17b402d2f9b84a80854a7ee0cfe
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 14:34:40 -0500
Merge lane/post-captions: a caption chip explains a phrase as it is read, in free space only, never over a word (不動心 · fudōshin, the curse spelled backwards, Bajiquan); a clock on his posts runs forward between them and rewinds for a stinger; per-post pace (fast plays a burst back to back); a repeated post item (operator, 4 Nov: "show a clock advancing as we show the newest posts ... in bursts", "one sequence of 'You're gone' or 'You want to die?' replies"); the caption, clock and pace in the post segment's key, appended
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
24 files changed, 2307 insertions(+), 44 deletions(-)
diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx
@@ -17,6 +17,8 @@ import ComboBadge, { type ComboInfo } from "./review/ComboBadge";
import { liveCombo } from "umtool-report-to-video/post-combo";
import PostZoomPanel from "./PostZoomPanel";
import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
+import { captionTimes, resolveCaption } from "umtool-report-to-video/post-caption";
+import { clockPlan } from "umtool-report-to-video/post-clock";
import { sceneEntry } from "umtool-report-to-video/post-media-scene";
// ---------------------------------------------------------------------------
@@ -279,6 +281,16 @@ export default function PostBench({
.map((z) => ({ i: z.i, ...zoomSpan((entry.fx as Array<Record<string, unknown>>)[z.i], z.t as number) })),
[entry, render],
);
+ const captionMarks = useMemo(
+ () =>
+ (captionTimes(entry, render) as Array<{ i: number; t?: number }>)
+ .filter((c) => typeof c.t === "number")
+ .map((c) => {
+ const f = resolveCaption((entry.fx as Array<Record<string, unknown>>)[c.i]);
+ return { i: c.i, t0: Math.max(0, (c.t as number) - f.lead), t3: (c.t as number) + f.hold + 0.35 };
+ }),
+ [entry, render],
+ );
const stepOf = (i: number) => plan.steps.find((st) => st.items.some((m) => m.i === i)) ?? null;
const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
const reading = readingSeconds(entry);
@@ -305,7 +317,7 @@ export default function PostBench({
</span>
</div>
<div className="relative w-full overflow-hidden rounded border border-seam bg-black" style={{ aspectRatio: `${box.width} / ${box.height}` }}>
- <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} />
+ <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} clock={clockPlan(shown, render, before)} />
<ComboBadge project={project} entry={shown} plan={plan} combo={liveCombo(combo, render, entry) as ComboInfo | null} box={box} s={s} playing={playing} />
</div>
<div className="flex items-center gap-2 text-[12px]">
@@ -340,6 +352,10 @@ export default function PostBench({
{zoomMarks.map((z) => (
<div key={z.i} className="absolute inset-y-0 border-x border-amber-400/80 bg-amber-400/25" style={{ left: `${(z.t0 / total) * 100}%`, width: `${((z.t3 - z.t0) / total) * 100}%` }} title={`word zoom ${z.i + 1}`} data-post-bench-zoom-mark={z.i} />
))}
+ {/* Its captions (post-caption.mjs): each from its lead-in to gone (one waiting for a zoom is drawn later). */}
+ {captionMarks.map((c) => (
+ <div key={`c${c.i}`} className="absolute bottom-0 h-1/3 border-x border-sky-400/80 bg-sky-400/30" style={{ left: `${(c.t0 / total) * 100}%`, width: `${((c.t3 - c.t0) / total) * 100}%` }} title={`caption ${c.i + 1}`} data-post-bench-caption-mark={c.i} />
+ ))}
<div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} />
</div>
<PostZoomPanel
diff --git a/umtool/components/projects/PostZoomPanel.tsx b/umtool/components/projects/PostZoomPanel.tsx
@@ -7,6 +7,7 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
import {
WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, WORD_ZOOM_LIMITS, cardTokens, normWord, readingEstimate, resolveWordZoom, targetTextOf, wordZoomTimes, zoomSpan,
} from "umtool-report-to-video/word-zoom";
+import { CAPTION_DEFAULTS, CAPTION_LIMITS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption";
// ---------------------------------------------------------------------------
// A POST's WORD ZOOMS ON THE BENCH (report-to-video/word-zoom.mjs; knobs.md, "A
@@ -14,7 +15,9 @@ import {
// Zoom here adds the zoom on them (its match and occurrence filled) -- then each
// zoom's knobs: scale, lead, hold, ease, highlight, and its moment: from the
// take's word timings (Get word timings: the EDITOR's transcription, a job) or
-// `at`, nudged. Every change is one write (POST /api/report/post-item, op "fx").
+// `at`, nudged. A CAPTION (post-caption.mjs) is added on the same words (Caption
+// here, its text typed), then its text, place, lead, hold and moment set.
+// Every change is one write (POST /api/report/post-item, op "fx").
// ---------------------------------------------------------------------------
type Entry = Record<string, unknown> & { id: string; fx?: Array<Record<string, unknown>> };
@@ -56,6 +59,8 @@ export default function PostZoomPanel({
const tokens = useMemo(() => cardTokens(text).filter((t) => t.tok !== undefined) as Array<{ tok: string; i: number }>, [text]);
const list = Array.isArray(entry.fx) ? entry.fx : [];
const times = useMemo(() => wordZoomTimes(entry, render), [entry, render]);
+ const ctimes = useMemo(() => captionTimes(entry, render), [entry, render]);
+ const [capText, setCapText] = useState("");
const narrated = isNarrated(entry);
const take = pickedTake(entry) as (Record<string, unknown> & { words?: unknown[] }) | null;
@@ -71,21 +76,24 @@ export default function PostZoomPanel({
return j.entry;
};
- const zoomHere = async () => {
+ const zoomHere = async (kind: "word-zoom" | "caption" = "word-zoom") => {
if (!sel) return;
+ if (kind === "caption" && !capText.trim()) return setError("a caption needs its text");
const words = tokens.slice(sel.from, sel.to + 1).map((t) => t.tok);
const match = words.length === 1 ? bare(words[0]) : [bare(words[0]), ...words.slice(1, -1), bare(words[words.length - 1])].join(" ");
// Its occurrence: how many times the same run of words came before it, plus one.
const want = words.map(normWord);
let occurrence = 1;
for (let i = 0; i < sel.from; i += 1) if (want.every((w, k) => normWord(tokens[i + k]?.tok ?? "") === w)) occurrence += 1;
- const add: Record<string, unknown> = { kind: "word-zoom", match, ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) };
+ const add: Record<string, unknown> = { kind, match, ...(kind === "caption" ? { text: capText.trim() } : {}), ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) };
// An un-narrated post has no read to time it by: the reading estimate, to nudge.
- if (!narrated) add.at = readingEstimate(sel.from);
+ // (A caption is timed by the reading estimate itself when it has no at.)
+ if (!narrated && kind === "word-zoom") add.at = readingEstimate(sel.from);
const e = await send({ add });
if (e) {
- setStatus(`zoom added on "${match}"`);
+ setStatus(`${kind === "caption" ? "caption" : "zoom"} added on "${match}"`);
setSel(null);
+ if (kind === "caption") setCapText("");
}
};
@@ -143,7 +151,7 @@ export default function PostZoomPanel({
return (
<section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12.5px]" data-post-zoom-panel={entry.id}>
<div className="flex flex-wrap items-center gap-2">
- <h2 className="micro m-0">word zoom</h2>
+ <h2 className="micro m-0">word zoom · caption</h2>
{targets.length > 1 && (
<select value={target} onChange={(e) => (setTarget(e.target.value), setSel(null))} data-post-zoom-target="">
{targets.map((t) => (
@@ -193,6 +201,17 @@ export default function PostZoomPanel({
<button type="button" className={btn} disabled={!sel} onClick={() => void zoomHere()} data-post-zoom-here="">
Zoom here
</button>
+ <input
+ value={capText}
+ onChange={(e) => setCapText(e.target.value)}
+ placeholder="caption text"
+ className="min-w-0 flex-1 rounded border border-seam bg-ground px-1 py-0.5"
+ aria-label="caption text"
+ data-post-caption-text=""
+ />
+ <button type="button" className={btn} disabled={!sel || !capText.trim()} onClick={() => void zoomHere("caption")} data-post-caption-here="">
+ Caption here
+ </button>
{sel && (
<span className="text-text-2" data-post-zoom-sel="">
“{tokens.slice(sel.from, sel.to + 1).map((t) => t.tok).join(" ")}”
@@ -200,6 +219,114 @@ export default function PostZoomPanel({
)}
</div>
{list.map((fx0, i) => {
+ // Its clock (post-clock.mjs): a row of its own, its rewind knob.
+ if (fx0?.kind === "clock") {
+ return (
+ <div key={i} className="flex flex-wrap items-center gap-2 rounded border border-seam p-2" data-post-clock-fx={i}>
+ <b>#{i + 1} clock</b>
+ <span className="text-text-2">{fx0.on === false ? "off on this item" : "the post's own time, run from the item before"}</span>
+ {fx0.on !== false && (
+ <label className="flex items-center gap-1">
+ rewind
+ <select value={String(fx0.rewind ?? "auto")} onChange={(e) => void send({ set: i, patch: { rewind: e.target.value === "auto" ? null : e.target.value } })} data-post-clock-knob="rewind">
+ {["auto", "on", "off"].map((x) => (
+ <option key={x} value={x}>
+ {x}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ <button type="button" className="ink-link ml-auto" onClick={() => void send({ remove: i })} data-post-clock-remove={i}>
+ remove
+ </button>
+ </div>
+ );
+ }
+ if (fx0?.kind === "caption") {
+ const c = resolveCaption(fx0);
+ const t = ctimes[i] as { t?: number; source?: string; error?: string };
+ const at = typeof t?.t === "number" ? t.t : null;
+ const up = at !== null && s >= at - c.lead && s < at + c.hold + 0.35;
+ const capKnob = (key: "lead" | "hold") => (
+ <label className="flex items-center gap-1" key={key}>
+ {key}
+ <input
+ type="number"
+ step={0.1}
+ min={CAPTION_LIMITS[key][0]}
+ max={CAPTION_LIMITS[key][1]}
+ defaultValue={Number(c[key])}
+ key={`${entry.id}:${i}:${key}:${String(c[key])}`}
+ onBlur={(ev) => {
+ const v = Number(ev.target.value);
+ if (Number.isFinite(v) && v !== Number(c[key])) void send({ set: i, patch: { [key]: v === CAPTION_DEFAULTS[key] ? null : v } });
+ }}
+ className="w-14 rounded border border-seam bg-ground px-1 py-0.5"
+ data-post-caption-knob={key}
+ />
+ </label>
+ );
+ return (
+ <div key={i} className={cn("space-y-1.5 rounded border p-2", up ? "border-sky-400/70" : "border-seam")} data-post-caption-fx={i}>
+ <div className="flex flex-wrap items-center gap-2">
+ <b>
+ #{i + 1} caption on “{c.match}”
+ </b>
+ {at !== null ? (
+ <span data-post-caption-at={String(at)}>
+ at {at.toFixed(2)} s {t.source === "at" ? "(set by hand)" : t.source === "words" ? "(the take's words)" : "(the reading estimate)"}
+ </span>
+ ) : (
+ <span className="text-[var(--color-blocking,#c33)]">{t?.error}</span>
+ )}
+ <button type="button" className="ink-link ml-auto" onClick={() => setS(Math.max(0, (at ?? 0) - c.lead - 0.3))} disabled={at === null} data-post-caption-go={i}>
+ play it
+ </button>
+ <button type="button" className="ink-link" onClick={() => void send({ remove: i })} data-post-caption-remove={i}>
+ remove
+ </button>
+ </div>
+ <input
+ defaultValue={c.text}
+ key={`${entry.id}:${i}:text:${c.text}`}
+ onBlur={(ev) => ev.target.value.trim() && ev.target.value !== c.text && void send({ set: i, patch: { text: ev.target.value } })}
+ className="w-full rounded border border-seam bg-ground px-1 py-0.5"
+ aria-label={`caption ${i + 1} text`}
+ data-post-caption-knob="text"
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ at
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(Math.max(0, (at ?? 0) - 0.1)) } })} data-post-caption-nudge="-">
+ −0.1
+ </button>
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2((at ?? 0) + 0.1) } })} data-post-caption-nudge="+">
+ +0.1
+ </button>
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(s) } })} data-post-caption-at-playhead="">
+ at playhead
+ </button>
+ {typeof fx0.at === "number" && (
+ <button type="button" className="ink-link" onClick={() => void send({ set: i, patch: { at: null } })} data-post-caption-from-words="">
+ {narrated ? "from the read" : "the estimate"}
+ </button>
+ )}
+ {capKnob("lead")}
+ {capKnob("hold")}
+ <label className="flex items-center gap-1">
+ place
+ <select value={c.place} onChange={(e) => void send({ set: i, patch: { place: e.target.value === CAPTION_DEFAULTS.place ? null : e.target.value } })} data-post-caption-knob="place">
+ {CAPTION_PLACES.map((x) => (
+ <option key={x} value={x}>
+ {x}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+ </div>
+ );
+ }
const fx = resolveWordZoom(fx0);
const t = times[i] as { t?: number; source?: string; error?: string };
const at = typeof t?.t === "number" ? t.t : null;
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -122,6 +122,8 @@ export type PlayEntry = {
/** A post item (report-to-video/post-item.mjs): the entry its card is drawn from, and what plays when. */
post?: Record<string, unknown> & { id: string };
postPlan?: PostPlan;
+ /** Its clock (post-clock.mjs clockPlan), or null. */
+ postClock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null;
/** Its combo badge (post-combo.mjs): the attachment it repeats, its count, the knobs. */
postCombo?: ComboInfo;
/** Its media scene (post-media-scene.mjs): which, its place in it, its items, the anchor. */
@@ -857,6 +859,7 @@ export default function PlayCut({
published={asPublished}
uncensored={uncensored}
scene={postNow.entry.postScene ?? null}
+ clock={postNow.entry.postClock ?? null}
joinFrom={(() => {
// THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended.
const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null;
diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -9,6 +9,10 @@ import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-v
import { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow";
import { scrollAt, showOpacityAt } from "umtool-report-to-video/post-thread";
import { blurCqw, blurOf, labelBoxOf, pixelGrid } from "umtool-report-to-video/post-censor";
+import {
+ CAPTION_SLIDE, captionCss, captionInnerHtml, captionOpacityAt, captionPlan, captionSlideAt, measureCaptionWords, mountCaptions, paletteOfDoc, placeCaption, setCaptionState, slideDir,
+} from "umtool-report-to-video/post-caption";
+import { clockCss, clockFace, clockHtml, clockStateAt, measureClockPlace, mountClock, setClockState } from "umtool-report-to-video/post-clock";
import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
@@ -30,6 +34,15 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar
// `data-w` spans) inside the card, which clips them, its highlight fading in
// under the word -- the card page's own elements transformed, nothing redrawn.
//
+// A CAPTION (post-caption.mjs) plays live on the build's own markup: the chips
+// mounted in the card page (its CSS, in the page's palette), placed by the same
+// rule (placeCaption, the words read while it is up avoided), faded and slid in
+// on the same curve, and tracking the phrase as the card pans (measured each tick).
+//
+// THE CLOCK (post-clock.mjs) plays live from `clock` (clockPlan: the caller has
+// the item before it): the build's chip mounted in the card page, placed by the
+// same rule, set each tick to clockStateAt -- the run, the badge, the rewind.
+//
// READ-FOLLOW (read-follow.mjs) plays live on the plan's `follow`: the card
// page carries the read's blocks and its flow; the pan's path is worked out
// from the page's geometry once it is drawn, and each tick sets the state at
@@ -40,6 +53,8 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar
type Rect = { x: number; y: number; width: number; height: number };
/** A zoom of the item, measured in its card page: its span on the item's clock, the card's region, the word's box. */
+/** A caption of the item, placed in its card page: its span, its place, the phrase's box and lines when placed. */
+type LiveCaption = { i: number; span: { t0: number; t1: number; t2: number; t3: number }; scope: string; from: number; to: number; placed: NonNullable<ReturnType<typeof placeCaption>>; base: Rect; lines: Rect[] };
type LiveZoom = { i: number; span: ReturnType<typeof zoomSpan>; scope: string; from: number; to: number; color: string | null; region: Rect; word: Rect };
/** The card's children placed so the region shows `win` (zoomWindow) at z; their layout boxes measured before any transform. */
@@ -413,7 +428,7 @@ function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: A
}
export default function PostItemPlayer({
- project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, joinFrom = null,
+ project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null,
}: {
project: string;
take?: string | null;
@@ -433,6 +448,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;
+ /** Its clock (post-clock.mjs clockPlan, from the item before it), or none. */
+ clock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null;
/** THE JOIN (post-join.mjs): the item before (its entry and plan) -- this one opens on it as it ended. */
joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan } | null;
}) {
@@ -531,13 +548,21 @@ export default function PostItemPlayer({
tick();
}, [joinFrom, box]);
const [zooms, setZooms] = useState<LiveZoom[]>([]);
+ const [caps, setCaps] = useState<LiveCaption[]>([]);
+ // The clock's box (and its badge's) where it is placed: a caption covers neither.
+ const clockRect = useRef<Rect | null>(null);
const boxes = useRef<Map<Element, Rect>>(new Map());
const zoomTimes = useMemo(() => (Array.isArray(entry.fx) && entry.fx.length ? wordZoomTimes(entry, undefined, plan.narration as never) : []), [entry, plan.narration]);
// ---- read-follow, live: the page's geometry measured once it is drawn, the path from it ----
const follow = plan.follow ?? null;
const [followGeo, setFollowGeo] = useState<ReturnType<typeof measureFollow>>(null);
const followRoute = useMemo(() => (follow && followGeo ? followPath(follow, followGeo) : null), [follow, followGeo]);
+ // The plan, the layout and the clock as they are now, read by measure through a ref: its identity (and so a
+ // re-measure, which lays the card out untransformed) changes only with what it measured before (main's deps).
+ const live0 = useRef({ plan, layout, clock });
+ live0.current = { plan, layout, clock };
const measure = useCallback(() => {
+ const { plan, layout, clock } = live0.current;
const doc = readFrame.current?.contentDocument;
if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return false;
const card = doc.querySelector("[data-post-card]") as HTMLElement | null;
@@ -560,6 +585,8 @@ export default function PostItemPlayer({
const list = Array.isArray(entry.fx) ? (entry.fx as Array<Record<string, unknown>>) : [];
if (!card || !list.length) {
setZooms([]);
+ setCaps([]);
+ mountCaptions({ css: "", chips: [] }, doc);
return true;
}
const rect = (el: Element): Rect => {
@@ -591,16 +618,74 @@ export default function PostItemPlayer({
out.push({ i, span: zoomSpan(fx0, t.t), scope, from: m.from, to: m.to, color: fx.highlight === false ? null : String(fx.highlight), region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } });
});
setZooms(out);
+ // Its captions: planned as the build plans them (each waits for a zoom), mounted, placed as the card is at each one's peak.
+ let cplan: ReturnType<typeof captionPlan> = [];
+ try {
+ cplan = captionPlan(entry, undefined, { zooms: out.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration as never });
+ } catch {
+ cplan = [];
+ }
+ const k = box.height / 1080;
+ const sizes = mountCaptions({ css: captionCss({ height: box.height, palette: paletteOfDoc(doc) }), chips: cplan.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k }, doc);
+ const inset = Math.round(12 * k);
+ // Free space only (as the build places it): the whole box, never over a word, the card's furniture, an attachment or the clock.
+ const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset };
+ const fixed: Rect[] = [...(layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot) as Rect[]) : [])];
+ if (clock && clockRect.current) fixed.push(clockRect.current);
+ const placedCaps: LiveCaption[] = [];
+ type Geo = { error?: string; card: Rect; word: Rect; lines: Rect[]; avoid: Rect[]; obstacles: Rect[]; column: Rect | null };
+ for (const c of cplan) {
+ const looks: Geo[] = [];
+ for (const t of follow ? [c.span.t1, c.span.t0, c.span.t3 - 0.01] : [c.span.t1]) {
+ if (follow) applyFollowState(followStateAt(follow, route, t), doc);
+ looks.push(measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: c.avoid }, doc) as Geo);
+ }
+ if (follow) applyFollowState(followStateAt(follow, route, c.span.t1), doc);
+ const g = looks[0];
+ const size = sizes.find((x) => x.i === c.i);
+ if (g.error || !size) continue;
+ const placed = placeCaption({ word: g.word, sizes: size.sizes, bounds, card: g.card, column: g.column, place: c.place, obstacles: [...fixed, ...looks.flatMap((l) => l.obstacles ?? [])], gap: Math.round(10 * k) });
+ if (!placed) continue;
+ placedCaps.push({ i: c.i, span: c.span, scope: c.scope, from: c.from, to: c.to, placed, base: g.word, lines: g.lines });
+ }
+ setCaps(placedCaps);
return true;
}, [entry, zoomTimes, box.height, follow]);
+ // ---- the clock, live: mounted and placed once the page is drawn, set each tick ----
+ const [clockAt, setClockAt] = useState<{ x: number; y: number } | null>(null);
+ const placeClock = useCallback(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return;
+ if (!clock) {
+ mountClock(null, doc);
+ setClockAt(null);
+ return;
+ }
+ const face = clockFace(clock.to, clock.zone);
+ const size = mountClock({ css: clockCss({ height: box.height, palette: paletteOfDoc(doc) }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } }, doc);
+ // Placed as the build places it: as the card is at the read's end (a threaded card's own post in).
+ const route = follow && doc.querySelector("[data-post-flow]") ? followPath(follow, measureFollow(doc)) : null;
+ if (follow && route) applyFollowState(followStateAt(follow, route, plan.total), doc);
+ const at = size ? measureClockPlace({ size, inset: Math.round(22 * (box.height / 1080)) }, doc) : null;
+ clockRect.current = at && size ? { x: at.x - 240 * (box.height / 1080), y: at.y, width: size.width + 240 * (box.height / 1080), height: size.height } : null;
+ if (follow && route) applyFollowState(followStateAt(follow, route, 0), doc);
+ setClockAt(at ? { x: at.x, y: at.y } : null);
+ }, [clock, box.height, follow, plan.total]);
+ const placeClockRef = useRef(placeClock);
+ placeClockRef.current = placeClock;
const onFrameLoad = useCallback(() => {
let tries = 0;
const tick = () => {
+ placeClockRef.current();
if (measure() || tries++ > 50) return;
setTimeout(tick, 100);
};
tick();
}, [measure]);
+ // The clock placed again when it changes (another item before, a knob).
+ useEffect(() => {
+ placeClock();
+ }, [placeClock]);
useEffect(() => {
// The item changed under a loaded page (a knob, a zoom added): measure again.
onFrameLoad();
@@ -651,6 +736,33 @@ export default function PostItemPlayer({
const visits = (follow as { visits?: unknown[] } | null)?.visits;
if (doc && visits?.length) applyVisitState({ visits, st: followNow?.visit ?? null }, doc);
}, [follow, followNow, followGeo]);
+ // The captions up now, after the follow state of this tick: each tracking its phrase (measured live when the card pans).
+ const capsUp = caps.filter((c) => s >= c.span.t0 && s < c.span.t3);
+ useEffect(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (!doc) return;
+ const k = box.height / 1080;
+ const list = capsUp.flatMap((c) => {
+ // A pan moving its phrase ends it (as the build does): the chip never rides over words.
+ if (follow) {
+ const g = measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: [] }, doc) as { error?: string; word: Rect };
+ if (!g.error && (Math.abs(g.word.y - c.base.y) > 1 || Math.abs(g.word.x - c.base.x) > 1)) return [];
+ }
+ const left = captionSlideAt(c.span, s);
+ const rel = c.placed.y >= c.base.y + c.base.height ? "below" : c.placed.y + c.placed.height <= c.base.y ? "above" : c.placed.x >= c.base.x ? "side-right" : "side-left";
+ const d = slideDir(rel);
+ const opacity = captionOpacityAt(c.span, s);
+ return [{ i: c.i, x: c.placed.x, y: c.placed.y, max: c.placed.max, opacity, dx: d.x * CAPTION_SLIDE * k * left, dy: d.y * CAPTION_SLIDE * k * left, marks: c.lines, mark: opacity, leader: c.placed.leader }];
+ });
+ setCaptionState({ list, stroke: Math.max(2, Math.round(2.4 * k)) }, doc);
+ }, [capsUp, s, follow, followNow, box.height]);
+ const clockSt = useMemo(() => (clock ? clockStateAt(clock, s) : null), [clock, s]);
+ useEffect(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (!doc) return;
+ const until = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : Infinity;
+ setClockState(clockSt && clockAt && s < until ? { ...clockAt, st: clockSt } : null, doc);
+ }, [clockSt, clockAt, s, layout.mode, plan.steps]);
const src = shown && inStep ? mediaTimeAt(shown, s) : null;
const cue = wordsRel && src !== null ? (cues[wordsRel] ?? []).find((c) => src >= c.start && src < c.end) ?? null : null;
return (
@@ -670,6 +782,13 @@ export default function PostItemPlayer({
data-post-zooms={zooms.length ? String(zooms.length) : undefined}
data-post-zoom={zooms.length ? String(Math.round(zf * 100) / 100) : undefined}
data-post-zoom-fx={live ? String(live.i) : undefined}
+ data-post-captions={caps.length ? String(caps.length) : undefined}
+ data-post-clock={clockSt ? `${clockSt.time} ${clockSt.date}` : undefined}
+ data-post-clock-mode={clockSt ? clockSt.mode : undefined}
+ data-post-clock-gap={clockSt && clockSt.gapOpacity > 0 ? clockSt.gap : undefined}
+ data-post-caption-fx={capsUp.length ? capsUp.map((c) => String(c.i)).join(" ") : undefined}
+ data-post-caption-place={capsUp.length ? capsUp.map((c) => c.placed.place).join(" ") : undefined}
+ data-post-caption-covers={capsUp.length ? capsUp.map((c) => String(c.placed.covers)).join(" ") : undefined}
data-post-follow-block={followNow?.current !== null && followNow?.current !== undefined ? String(followNow.current) : undefined}
data-post-follow-offset={followNow && followRoute?.segments.length ? String(Math.round(followNow.offset)) : undefined}
data-post-follow-pans={followRoute ? String(followRoute.segments.length) : undefined}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -87,7 +87,9 @@ Inbox cannot disagree about what is wrong with one.
| `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, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) |
| `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) |
-| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) |
+| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) |
+| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) |
+| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times |
| `posts fx <project> <item> [ls]` · `add word-zoom --match "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--scale s] [--hold s] [--lead s] [--ease out\|inOut\|snap] [--highlight #rrggbb\|off]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]` | a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`) |
| `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is |
| `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -762,6 +762,41 @@ snapshot and every script keep their words.
| `render.posts.slurs.add` — the project's own words (always masked; a word, or `{word, forms?, mask?, say?}`) · `.except` — never masked here (a form, a slur's word or its id) | — | `umtool posts slurs <p> add <word>` · `except <word>` · `remove <word>` (one writer, `updatePostSlurs`) | — |
| what the cut masks | — | `umtool posts slurs <p> ls [--json]`: per slur (its mask, never the word) and per post, and each read that needs word timings | — |
+## A caption (a chip explaining a phrase as it is read)
+
+`fx: [{kind: "caption", match, text, …}]` on a post item ([report-video.md](report-video.md#a-caption): the shape,
+the time, the place, the render). One writer, `updatePostFx`, refused in the build's words (`captionErrors`,
+`report-to-video/post-caption.mjs`, through `validatePostFx`). Its bench is the post bench's **word zoom · caption**
+block; Play the cut and the bench draw the build's own chip, live.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| a caption -- `match` (the phrase as the card shows it), `text` (≤ 160 characters, any script: CJK is drawn in Noto Sans CJK; the part before " — " bold), `occurrence`, `target` (`post`, `quoted`, `parent:<i>`) | post bench: click a word (shift-click: a phrase), type the text, **Caption here**; a caption's text field | `umtool posts fx <p> <item> add caption --match "Fudōshin" --text '不動心 · fudōshin — "immovable mind"' [--target quoted] [--occurrence n]` | `POST /api/report/post-item {project, op: "fx", id, fx: {add: {kind: "caption", match, text, …}}, token}` |
+| `at` -- item seconds (0–600); absent: the matched word's start in the picked take's word timings, else the reading estimate (a narrated read spread over its script by characters; un-narrated, 1 s + 3 words a second) | the caption's **−0.1** / **+0.1**, **at playhead**, **from the read** (clears it) | `umtool posts fx <p> <item> set <n> --at 4.2` (`--at default`: back to the words / the estimate) | `fx: {set: <i>, patch: {at}}` |
+| `lead` 0–3 s in before the word (0.15), `hold` 0.5–10 s from it (2.5), `place` `below` \| `above` \| `side` (below) -- it never covers a word read while it is up (the next place that is clear wins); it waits for a word zoom it would be up with | the caption's **lead**, **hold**, **place** | `set <n> --lead 0.3 --hold 3 --place above` (`default` clears one) | `fx: {set: <i>, patch: {…}}` |
+| remove one | the caption's **remove** | `umtool posts fx <p> <item> remove <n>` | `fx: {remove: <i>}` |
+| list them, each with its time and where it came from | the block's rows; the plan strip marks each (blue) | `umtool posts fx <p> <item> [ls] [--json]` | — |
+
+## The clock (each post's own time on its card, run between items)
+
+`render.posts.clock` (the cut's default) and `fx: [{kind: "clock", on?, rewind?}]` on a post item
+([report-video.md](report-video.md#the-clock)): the item's own post time, "4:10 AM ET · Wed 4 Nov", run forward
+from the clock item before it in its first 0.8 s (the gap flashing), or rewound when it is earlier. Refused in the
+build's words (`clockErrors`, `validateClockRender`, `report-to-video/post-clock.mjs`).
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the cut's clock -- `on` (off by default), `zone` (an IANA zone; `America/New_York`) | — | `umtool posts clock <p> on\|off\|default [--zone America/New_York]` (`updatePostClock`); bare: which items show it | — |
+| one item's clock -- on (or `on: false`: not on this item though the cut's is) | post bench, the clock's row (**remove**) | `umtool posts fx <p> <item> add clock [--off]` · `remove <n>` | `fx: {add: {kind: "clock"}}` |
+| `rewind` `auto` (an earlier post rewinds) \| `on` (rewinds anyway) \| `off` (cuts straight to its time) | the clock's **rewind** | `umtool posts fx <p> <item> set <n> --rewind on\|off\|auto` | `fx: {set: <i>, patch: {rewind}}` |
+
+## The pace (a burst played back to back)
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| `narration.pace` -- `fast` (lead 0.1, tail 0.15, ramp 0.3, linger 0.45, unless the post sets one itself) \| `normal` (the cut's gaps); `render.postNarration.pace` the cut's. The schedule, the build, Play and the deck's estimate honour it | — | `umtool posts narrate <p> <item> pace=fast\|normal\|default` · `umtool posts narrate <p> --cut pace=fast` | — |
+| a REPEATED item (a stinger): a second copy of a post item, its narration and takes reused, its own knobs | — | `umtool timeline <p> duplicate <id>` then `timeline <p> move <id>-copy --to <n>` | — |
+
## A word zoom (a post item's card pushed in on a word as it is read)
`fx: [{kind: "word-zoom", match, …}]` on a post item ([report-video.md](report-video.md#a-word-zoom): the shape, the
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -659,6 +659,111 @@ post's insert and `umtool posts avatars <p>`, or set by hand with `umtool posts
<p> <handle> <image>` (never replaced by the archive's). Every card that draws that
author unblurred shows it — the render, Play and the bench; a redacted author never.
+### A caption
+
+A post item may carry a CAPTION: a small chip explaining a phrase, up as the phrase is
+read and held a beat (`report-to-video/post-caption.mjs`; operator, 4 Nov: `不動心 ·
+fudōshin — "immovable mind"` on "Fudōshin"). It sits beside a word zoom in `fx`:
+
+```jsonc
+"fx": [{
+ "kind": "caption",
+ "match": "Fudōshin", // the phrase as the card shows it (as a word zoom's)
+ "text": "不動心 · fudōshin — \"immovable mind\"", // ≤ 160 characters, any script; the part before " — " bold
+ "target": "post", "occurrence": 1, // whose words, its n-th time (as a word zoom's)
+ "at": 4.2, // item seconds; absent: the take's word timings, else the estimate
+ "lead": 0.15, "hold": 2.5, // in this long before the word; held this long from it
+ "place": "below" // "below" (default) | "above" | "side"
+}]
+```
+
+**When** -- a word zoom's rule: `at`, else the matched word's start in the picked take's
+word timings (lead + start ÷ rate), else the READING ESTIMATE: a narrated read spread over
+its script by characters (the card's words aligned to the script), an un-narrated post's
+1 s + 3 words a second. It fades and slides in over 0.3 s and out over 0.35 s. A caption
+that would be up while a word zoom is (its lead-in to back out) WAITS for the zoom to be
+out; two captions of a post up at once are refused, and one is gone by a stack card's media
+phase.
+
+**Where**: a chip by the phrase -- the card's palette (a panel of its background toward the
+accent, the accent's border), its faces, then the CJK faces (`Noto Sans CJK JP`, `Source
+Han Sans`, `WenQuanYi Zen Hei`) so 不動心 is drawn -- with a notch pointing at the phrase and
+an accent underline under it. It never covers a word read while it is up: `place` first,
+then below, above, side (each vertical place centred on the phrase, then its edges aligned);
+among the places clear of the read, the one hiding fewest of the card's other words; the
+build notes a WARNING when none is clear. It tracks the phrase while the card pans
+(read-follow), and it is drawn OVER the card, never in it -- no `data-w`, no
+`data-post-block` -- so `readInViewErrors` never counts it.
+
+**The render**: on the card page as drawn at the caption's peak, the phrase measured (a
+phrase cut off the card is refused), the chip placed, then shot alone on a clear page (the
+chip with its notch; the underline apart) and laid over the card (`postSegmentArgs`
+`captionFx`): fading, sliding in toward the phrase, riding the phrase's track. Play and the
+bench mount the same markup in the card frame (`mountCaptions`, `setCaptionState`) on the
+same curve. The post record (`<id>.post.json`) keeps each caption's time, span, place and box.
+
+### The clock
+
+A post item may show its CLOCK (`report-to-video/post-clock.mjs`; operator, 4 Nov: "show a
+clock advancing as we show the newest posts/replies chronologically and quickly to convey
+how much he's posting in bursts"; "the clock should probably just be for mr obvious'
+replies ... so it generally always goes forward unless there's a compelling reason to go
+back"): a small chip on the card, "4:10 AM ET · Wed 4 Nov" with an analogue face, in the
+cut's zone (`America/New_York`).
+
+```jsonc
+"render": { "posts": { "clock": { "on": true, "zone": "America/New_York" } } }, // the cut's default
+"fx": [{ "kind": "clock", "on": false, "rewind": "auto" }] // one item's ("on" default true)
+```
+
+It shows the ITEM's own post time (`entry.date`) -- never a parent's or a quote's -- and it
+does not move while they are read. Between two consecutive clock items, in the first 0.8 s
+of the second it RUNS from the earlier time to this one (`easeInOut`): the hands spin, the
+minutes roll, the date flips day by day, the gap flashes in a badge beside it ("+39 s",
+"+38 min", "+2 h 14 min", "+3 d 4 h") for 0.9 s, then fades over 0.4 s. When this post is
+EARLIER than the one before it REWINDS: the hands spin backwards, the face's ring dashes, and
+the badge says "⟲ rewind −12 h 6 min". `rewind: "off"` cuts straight to the time; `"on"`
+rewinds even forward (a repeat of the same post spins back a full turn to itself). An item
+after a non-clock entry shows its time without a run.
+
+It sits at the card's bottom-right corner, beside the counts row, else its top-right -- the
+first over no word of the card -- drawn over the card, never in it (`readInViewErrors`
+never counts it). The render shoots its frames alone on a clear page (each distinct state
+once: the run and the badge's fade) and lays them over the card from the first frame (a
+stack card's, until its media phase); Play and the bench mount the same chip
+(`mountClock`, `setClockState`) from `clockPlan`, which needs the item before it (`playView`
+`postClock`; the bench's `before`).
+
+### The pace
+
+`pace: "fast"` on a narrated post's narration (or `render.postNarration.pace`, the cut's)
+plays it BACK TO BACK (`POST_PACES`): lead 0.1, tail 0.15, ramp 0.3, linger 0.45 -- unless
+the post sets one of those itself (its own always wins); `"normal"` is the cut's gaps (on a
+post, it undoes a cut's `fast`). It rides the narration's knobs (`postNarrationKnobs`), so the
+schedule, the build, Play and the deck's estimate all honour it. An un-narrated post has no
+read gaps to shorten (its `hold` is its length).
+
+### Caching: the segment key
+
+A post segment is rebuilt only when its key changes (`<id>.post.json`'s `key`). The entry is in it -- a
+caption's text and knobs, the clock fx, the narration's `pace`, the item's id (a repeated item is its own
+segment) -- and `postFxKeyFields` (`post-render.mjs`) APPENDS what the entry does not carry: `captionV` and
+`clockV` (the chip's and the clock's drawing, bumped when their look changes), `clock` (the plan: this post's
+time, the time it runs from -- the item before's, when that one is a clock item -- the mode, a forced rewind,
+the zone) and `pace` (the gap knobs a cut-level pace resolved to). An item with none of these adds nothing, so
+its key is the one it had before they existed and a take `--from` an earlier one reuses its segment.
+A take `--from` another hard-links a post item's record (`.post.json`) and its combo pass's files (`.combo.json`,
+`.plain.mp4`) with its segment (`SEGMENT_FILE_SUFFIXES`), and a post item's files are no longer detached before
+its build: a matching key keeps the linked segment, and every write of a rebuilt one goes through a rename, so
+the other take's files are never written through (before, every post item was rebuilt in a `--from` take).
+
+### A repeated item
+
+`umtool timeline <p> duplicate <id>` copies a post item to just after itself under a fresh
+id (`<id>-copy`), its narration and takes REUSED (the same files), its knobs its own -- move
+it where the stinger goes (`timeline move <id>-copy --to <n>`) and give it its own pace,
+clock or captions. Two items of one post build two segments.
+
### A word zoom
A post item's card may PUSH IN ON A WORD as it is read (`report-to-video/word-zoom.mjs`;
diff --git a/umtool/e2e/post-captions.spec.ts b/umtool/e2e/post-captions.spec.ts
@@ -0,0 +1,127 @@
+import { test, expect, type Page } from "@playwright/test";
+import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// A POST ITEM's CAPTION and CLOCK (report-to-video/post-caption.mjs,
+// post-clock.mjs; knobs.md, "A caption", "The clock"). Fixture:
+// e2e/fixtures/post-narration-fixture.mjs -- p-11 "The video speaks for
+// itself." narrated by a 2 s take (no word timings: the reading estimate),
+// p-12 four pictures, p-13 words only; all dated 30 Oct 10:00 UTC.
+//
+// POST_CAPTIONS_SHOTS=<dir> screenshots there
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DIR = path.join(HERE, "..", ".e2e-song", "reports", "post-narration-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const PROJECT = "reports/post-narration-fixture";
+const SHOTS = process.env.POST_CAPTIONS_SHOTS ?? null;
+
+type Entry = { id: string; date?: string; fx?: Array<Record<string, unknown>> };
+const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[]; render: Record<string, unknown> };
+const timeline = () => manifest().timeline;
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+});
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+ rmSync(path.join(DIR, "notes.json"), { force: true });
+});
+
+type Box = { x: number; y: number; width: number; height: number };
+const overlap = (a: Box, b: Box) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
+/** In the card frame: the box of `sel` and of every card word. */
+const boxesIn = (page: Page, sel: string) =>
+ page.frameLocator('[data-post-card-frame="read"]').locator("body").evaluate((body, s) => {
+ const r = (el: Element) => {
+ const b = el.getBoundingClientRect();
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
+ };
+ const el = body.ownerDocument.querySelector(s);
+ return { el: el ? r(el) : null, words: Array.from(body.ownerDocument.querySelectorAll("[data-w]")).map((w) => ({ id: w.getAttribute("data-w"), ...r(w) })) };
+ }, sel);
+
+test("A CAPTION (operator, 4 Nov: 不動心 on \"Fudōshin\"): click a word -> type the text -> Caption here -> saved, timed by the reading estimate; Play shows the chip (CJK drawn) by the phrase as it is read, over no word read while it is up", async ({ page }) => {
+ await page.setViewportSize({ width: 1500, height: 1100 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-11"));
+ const panel = page.locator('[data-post-zoom-panel="p-11"]');
+ await panel.locator('[data-post-zoom-word="2"]').click();
+ await expect(panel.locator("[data-post-caption-here]")).toBeDisabled();
+ await panel.locator("[data-post-caption-text]").fill("不動心 · speaks — a test of the chip");
+ await panel.locator("[data-post-caption-here]").click();
+ await expect(panel.locator('[data-post-caption-fx="0"]')).toBeVisible();
+ expect(timeline().find((e) => e.id === "p-11")!.fx).toEqual([{ kind: "caption", match: "speaks", text: "不動心 · speaks — a test of the chip" }]);
+ // Its time: no word timings, so the read spread over its script by characters (0.4 + 10/29 of 2 s).
+ const at = Number(await panel.locator("[data-post-caption-at]").getAttribute("data-post-caption-at"));
+ expect(at).toBeGreaterThan(0.9);
+ expect(at).toBeLessThan(1.3);
+ await expect(panel.locator('[data-post-caption-fx="0"]')).toContainText("the reading estimate");
+ await expect(page.locator('[data-post-bench-caption-mark="0"]')).toBeVisible();
+ // A knob: place above, one write.
+ await panel.locator('[data-post-caption-knob="place"]').selectOption("above");
+ await expect.poll(() => timeline().find((e) => e.id === "p-11")!.fx?.[0]?.place).toBe("above");
+ // The bench's own player mounts the chip.
+ await expect(page.locator('[data-post-play="p-11"]')).toHaveAttribute("data-post-captions", "1", { timeout: 15_000 });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-caption-bench.png") });
+
+ // Play the cut: up from its lead-in, the chip in the card page, by the phrase.
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" }));
+ const player = page.locator('[data-post-play="p-11"]');
+ await expect(player).toHaveAttribute("data-post-captions", "1", { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+ await expect(player).toHaveAttribute("data-post-caption-fx", "0", { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+ const chip = page.frameLocator('[data-post-card-frame="read"]').locator('[data-post-fx-caption="0"]');
+ await expect(chip).toContainText("不動心");
+ await expect.poll(() => chip.evaluate((el) => Number((el as HTMLElement).style.opacity))).toBeGreaterThan(0);
+ // CJK is drawn by a face this machine has, not boxes.
+ expect(await chip.evaluate((el) => el.ownerDocument.fonts.check("27px 'Noto Sans CJK JP'", "不動心"))).toBe(true);
+ // Never over the words read while it is up ("for itself." after "speaks"); never in the card's words.
+ const { el, words } = await boxesIn(page, '[data-post-fx-caption="0"]');
+ expect(el).not.toBeNull();
+ for (const w of words.filter((x) => x.id === "post:3" || x.id === "post:4")) expect(overlap(el!, w)).toBe(0);
+ expect(await chip.evaluate((el) => el.closest("[data-post-card]") === null && !el.querySelector("[data-w], [data-post-block]"))).toBe(true);
+ // Its underline under the phrase.
+ await expect(page.frameLocator('[data-post-card-frame="read"]').locator('[data-post-fx-caption-mark="0"]')).toHaveCount(1);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-caption-play.png") });
+});
+
+test("THE CLOCK: each item's own time on its card, run FORWARD from the clock item before (the gap flashing) and REWOUND when the next is earlier; Play draws it over no word", async ({ page }) => {
+ const m = manifest();
+ const set = (id: string, o: Record<string, unknown>) => Object.assign(m.timeline.find((e) => e.id === id)!, o);
+ set("p-11", { fx: [{ kind: "clock" }] });
+ set("p-12", { date: "2026-10-30T10:38:00.000Z", fx: [{ kind: "clock" }] });
+ set("p-13", { date: "2026-10-28T09:00:00.000Z", fx: [{ kind: "clock" }] });
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+ await page.setViewportSize({ width: 1500, height: 1000 });
+
+ // Forward: p-12 after p-11, 38 minutes on (America/New_York: 6:00 AM -> 6:38 AM).
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-12" }));
+ const p12 = page.locator('[data-post-play="p-12"]');
+ await expect(p12).toHaveAttribute("data-post-clock-mode", "forward", { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+ await expect(p12).toHaveAttribute("data-post-clock-gap", "+38 min", { timeout: 15_000 });
+ await expect(p12).toHaveAttribute("data-post-clock", "6:38 AM Fri 30 Oct", { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+ const clock = page.frameLocator('[data-post-card-frame="read"]').locator("[data-post-clock]");
+ await expect(clock).toContainText("ET");
+ const { el, words } = await boxesIn(page, "[data-post-clock]");
+ for (const w of words) expect(overlap(el!, w)).toBe(0);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-clock-forward.png") });
+
+ // Rewind: p-13 is two days earlier than p-12.
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-13" }));
+ const p13 = page.locator('[data-post-play="p-13"]');
+ await expect(p13).toHaveAttribute("data-post-clock-mode", "rewind", { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+ await expect(p13).toHaveAttribute("data-post-clock-gap", /^⟲ rewind −2 d 1 h/, { timeout: 15_000 });
+ await expect(p13).toHaveAttribute("data-post-clock", "5:00 AM Wed 28 Oct", { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-clock-rewind.png") });
+});
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -2735,7 +2735,7 @@ export function handlesWithoutAvatar(m, handles) {
// ---- a post item's narration (report-to-video/post-narration.mjs) ----------
/** The narration keys a write may set on one post item (post-narration.mjs; knobs.md, "A narrated post item"). */
-export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "window"]);
+export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace", "window"]);
/**
* One post item's narration, changed in place (`m` the manifest inside a
@@ -3047,6 +3047,38 @@ export async function updatePostRedact(dir, change, { token = null } = {}) {
});
}
+// ---- the clock (post-clock.mjs; `umtool posts clock`) -----------------------
+
+/**
+ * SET THE CUT's CLOCK (`render.posts.clock`): `{ on?, zone? }` (a null: back to
+ * the default -- off, America/New_York). One item's own (`fx: [{kind: "clock"}]`)
+ * wins over it. Validated with the build's check.
+ *
+ * @param {string} dir
+ * @param {{ on?: boolean | null, zone?: string | null }} patch
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updatePostClock(dir, patch, { token = null } = {}) {
+ if (!isObj(patch) || !Object.keys(patch).length) throw new Error("say on, off or a zone");
+ return structural(dir, "post-clock", token, (m) => {
+ if (!isObj(m.render)) m.render = {};
+ const posts = isObj(m.render.posts) ? m.render.posts : {};
+ const c = isObj(posts.clock) ? { ...posts.clock } : {};
+ for (const [k, v] of Object.entries(patch)) {
+ if (!["on", "zone"].includes(k)) throw new StructureRefused([`render.posts.clock.${k} is not a clock knob (on, zone)`]);
+ if (v === null || v === undefined) delete c[k];
+ else c[k] = v;
+ }
+ if (Object.keys(c).length) posts.clock = c;
+ else delete posts.clock;
+ if (Object.keys(posts).length) m.render.posts = posts;
+ else delete m.render.posts;
+ const errors = validatePostsRender(m.render);
+ if (errors.length) throw new StructureRefused(errors);
+ return { clock: posts.clock ?? null };
+ });
+}
+
// ---- the slur filter (post-slurs.mjs; `umtool posts slurs`) ---------------
/**
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -16,6 +16,7 @@ import { rejectionOf } from "./rejectReasons.mjs";
import { dateKeyLabel } from "./playCut.mjs";
import { panelEntry, postDay, postItemPlan } from "umtool-report-to-video/post-item";
import { planContext } from "umtool-report-to-video/post-conversation";
+import { clockPlan } from "umtool-report-to-video/post-clock";
import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs";
import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs";
import { readWorkingCut } from "./workingCut.mjs";
@@ -64,6 +65,8 @@ export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = nu
// `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(panelEntry(sceneEntry(e, mediaScene), render), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene, join: ctx?.join ?? null }),
+ // Its clock (post-clock.mjs): its post's time, run from the clock item before it.
+ postClock: clockPlan(e, render, ctx?.prev ?? null),
...(mediaScene ? { postScene: { key: mediaScene.key, n: mediaScene.n, of: mediaScene.of, ids: mediaScene.ids, anchor: mediaScene.anchor.id } } : {}),
};
}
diff --git a/umtool/lib/report/postFx.test.mjs b/umtool/lib/report/postFx.test.mjs
@@ -55,7 +55,7 @@ test("posts fx: add (an un-narrated post gets the reading estimate), set, ls, re
r = await cli(["fx", "fx", "p-1", "remove", "1"]);
assert.equal(r.code, 0, r.err);
assert.equal((await manifest(p)).timeline[0].fx, undefined);
- assert.match(r.out, /no word zooms/);
+ assert.match(r.out, /no effects/);
await assert.rejects(updatePostFx(p.dir, "p-1", { remove: 0 }), /has no effects/);
});
@@ -88,3 +88,26 @@ test("posts narrate --words: the take transcribed by the editor (its parts, at t
for (const f of ["p01", "p02"]) await writeFile(path.join(p.dir, `narration/posts/1/take-1.parts/${f}.wav`), "");
assert.deepEqual(await takeWordSources(p.dir, parted), [{ file: parted.parts[0].file, offset: 0 }, { file: parted.parts[1].file, offset: 2.6 }]);
});
+
+test("posts fx add caption: the chip's text kept (CJK too), timed by the reading estimate, its knobs set -- a zoom's knobs refused", async () => {
+ const p = await project("cap", [item("1", { text: "I have achieved Fudōshin. Its amazing." })]);
+ let r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin", "--text", "不動心 · fudōshin — \"immovable mind\""]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /0 word zoom\(s\), 1 caption\(s\)/);
+ assert.match(r.out, /#1 caption "Fudōshin" \(post, 1st\) at 2.00 s \(the reading estimate\) · "不動心 · fudōshin — "immovable mind"" · in 0.15 s before, held 2.5 s, below/);
+ assert.deepEqual((await manifest(p)).timeline[0].fx, [{ kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"" }]);
+ r = await cli(["fx", "cap", "p-1", "set", "1", "--place", "above", "--hold", "3", "--at", "1.5"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual((await manifest(p)).timeline[0].fx[0], { kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"", place: "above", hold: 3, at: 1.5 });
+ r = await cli(["fx", "cap", "p-1", "set", "1", "--place", "left"]);
+ assert.equal(r.code, 1);
+ assert.match(r.err, /fx\[0\]\.place must be one of below, above, side/);
+ r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin"]);
+ assert.match(r.err, /add caption needs --text/);
+ r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin", "--text", "x", "--scale", "2"]);
+ assert.match(r.err, /--scale is a word zoom's knob/);
+ r = await cli(["fx", "cap", "p-1", "add", "word-zoom", "--match", "amazing", "--text", "x"]);
+ assert.match(r.err, /--text and --place are a caption's knobs/);
+ r = await cli(["fx", "cap", "p-1", "ls", "--json"]);
+ assert.deepEqual(JSON.parse(r.out).times, [{ i: 0, t: 1.5, source: "at" }]);
+});
diff --git a/umtool/lib/report/postFxCli.mjs b/umtool/lib/report/postFxCli.mjs
@@ -8,6 +8,8 @@
// umtool posts fx <p> <item> [ls]
// umtool posts fx <p> <item> add word-zoom --match "…" [--target post|quoted|parent:<i>] [--occurrence n] [--at s]
// [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off]
+// umtool posts fx <p> <item> add caption --match "…" --text "…" [--target …] [--occurrence n] [--at s]
+// [--lead s] [--hold s] [--place below|above|side] (post-caption.mjs)
// umtool posts fx <p> <item> set <n> [the same flags; a flag's value `default` clears it]
// umtool posts fx <p> <item> remove <n>
// umtool posts narrate <p> <item> --words [--worker <id>]
@@ -19,15 +21,20 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
import {
WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, findMatch, readingEstimate, resolveWordZoom, scriptWordTimes, targetTextOf, wordZoomTimes,
} from "umtool-report-to-video/word-zoom";
+import { CAPTION_DEFAULTS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption";
+import { CLOCK_REWINDS, CLOCK_ZONE, clockFace, clockOn, clockZoneOf } from "umtool-report-to-video/post-clock";
import { readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
-import { manifestToken, updatePostFx, updatePostNarration } from "./manifest.mjs";
+import { manifestToken, updatePostClock, updatePostFx, updatePostNarration } from "./manifest.mjs";
import { findPostItem } from "./postNarrationCli.mjs";
export const FX_USAGE = [
"usage: umtool posts fx <project> <item> [ls] [--json]",
" umtool posts fx <project> <item> add word-zoom --match \"…\" [--target post|quoted|parent:<i>] [--occurrence n]",
" [--at s] [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off] [--json]",
+ " umtool posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post|quoted|parent:<i>] [--occurrence n]",
+ " [--at s] [--lead s] [--hold s] [--place below|above|side] [--json]",
+ " umtool posts fx <project> <item> add clock [--rewind auto|on|off] [--off]",
" umtool posts fx <project> <item> set <n> [those flags; `default` clears one] | remove <n>",
" A WORD ZOOM: the card pushed in on a word (or a phrase) as it is read, a highlight under it, then back out.",
" --match is the word as the card shows it (case and edge punctuation aside); --occurrence its n-th time in the",
@@ -36,7 +43,16 @@ export const FX_USAGE = [
" read's rate) -- `umtool posts narrate <p> <item> --words` gets them from the editor's transcription. An",
" un-narrated post needs --at (add fills the reading estimate: 1 s + 3 words a second).",
` --scale 1.2–4 (default ${WORD_ZOOM_DEFAULTS.scale}), --lead 0–3 s in before the word (${WORD_ZOOM_DEFAULTS.lead}), --hold 0–10 s on it (${WORD_ZOOM_DEFAULTS.hold}),`,
- ` --ease ${WORD_ZOOM_EASES.join("|")} (${WORD_ZOOM_DEFAULTS.ease}), --highlight a colour or off (${WORD_ZOOM_DEFAULTS.highlight}). <n>: the zoom's number as ls shows it.`,
+ ` --ease ${WORD_ZOOM_EASES.join("|")} (${WORD_ZOOM_DEFAULTS.ease}), --highlight a colour or off (${WORD_ZOOM_DEFAULTS.highlight}). <n>: the effect's number as ls shows it.`,
+ " A CAPTION: a chip explaining a phrase (--text, any script: CJK is drawn), up as the phrase is read and held a beat,",
+ " by the phrase (--place; it never covers a word read while it is up) with a notch and an underline. WHEN: --at, else",
+ " the word's start in the take's word timings, else the reading estimate (a narrated read spread over its script).",
+ ` --lead 0–3 s in before the word (${CAPTION_DEFAULTS.lead}), --hold 0.5–10 s from it (${CAPTION_DEFAULTS.hold}), --place ${CAPTION_PLACES.join("|")} (${CAPTION_DEFAULTS.place}).`,
+ " A caption up while a word zoom is waits for the zoom to be out.",
+ " A CLOCK: the post's own time on its card (\"4:10 AM ET · Wed 4 Nov\", the cut's zone), run from the clock item",
+ " before it in its first 0.8 s -- forward with the gap flashing (\"+38 min\"), or REWOUND when this post is earlier",
+ " (⟲ rewind). --rewind off cuts straight to it, on rewinds anyway; --off: no clock on this item though the cut's is",
+ " on (umtool posts clock <p> on).",
].join("\n");
export class FxError extends Error {}
@@ -60,6 +76,12 @@ export function fxPatchOf(str) {
out[key] = x;
}
}
+ const rw = str("--rewind");
+ if (rw !== null) out.rewind = rw === "default" || rw === "auto" ? null : rw;
+ const tx = str("--text");
+ if (tx !== null) out.text = tx;
+ const pl = str("--place");
+ if (pl !== null) out.place = pl === "default" ? null : pl;
const e = str("--ease");
if (e !== null) out.ease = e === "default" ? null : e;
const h = str("--highlight");
@@ -69,14 +91,28 @@ export function fxPatchOf(str) {
const nth = (n) => `${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"}`;
-/** One item's zooms as lines. */
+/** One item's effects (word zooms, captions) as lines. */
export function fxLines(e, render) {
const list = Array.isArray(e.fx) ? e.fx : [];
- if (!list.length) return [`${e.id}: no word zooms (add one: umtool posts fx <p> ${e.id} add word-zoom --match "…")`];
+ if (!list.length) return [`${e.id}: no effects (add one: umtool posts fx <p> ${e.id} add word-zoom --match "…" | add caption --match "…" --text "…")`];
const times = wordZoomTimes(e, render);
+ const ctimes = captionTimes(e, render);
+ const nz = list.filter((f) => f?.kind === "word-zoom").length;
+ const nc = list.filter((f) => f?.kind === "caption").length;
+ const clk = list.some((f) => f?.kind === "clock");
return [
- `${e.id}: ${list.length} word zoom(s)${isNarrated(e) ? "" : " (not narrated: each needs at)"}`,
+ `${e.id}: ${nz} word zoom(s), ${nc} caption(s)${clk ? ", its clock" : ""}${isNarrated(e) || !nz ? "" : " (not narrated: a zoom needs at)"}`,
...list.map((fx0, i) => {
+ if (fx0?.kind === "clock") {
+ const on = fx0.on !== false;
+ return ` #${i + 1} clock ${on ? `on -- ${clockFace(Date.parse(e.date), clockZoneOf(render)).time} ${clockFace(Date.parse(e.date), clockZoneOf(render)).date}, rewind ${fx0.rewind ?? "auto"}` : "off (the cut's clock not shown here)"}`;
+ }
+ if (fx0?.kind === "caption") {
+ const c = resolveCaption(fx0);
+ const t = ctimes[i];
+ const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s (${t.source === "at" ? "set by hand" : t.source === "words" ? "from the take's words" : "the reading estimate"})`;
+ return ` #${i + 1} caption "${c.match}" (${c.target}, ${nth(c.occurrence)}) ${when} · "${c.text}" · in ${c.lead} s before, held ${c.hold} s, ${c.place}`;
+ }
const fx = resolveWordZoom(fx0);
const t = times[i];
const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s ${t.source === "at" ? "(set by hand)" : `(from the take's words: "${t.word.w}" at ${t.word.start} s)`}`;
@@ -86,7 +122,7 @@ export function fxLines(e, render) {
}
/** `umtool posts fx …` (postsCli.mjs routes it here). */
-export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str }) {
+export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str, off = false }) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new FxError(`${project.id} has no manifest`);
const render = manifest.render ?? {};
@@ -95,12 +131,15 @@ export async function fxCommand(project, words, { json = false, out = (s) => con
if (!e) throw new FxError(`no post item ${ref} in ${project.id} (its id, or the post's id)`);
const write = async (op) => withEditNotes(project, async () => updatePostFx(project.dir, e.id, op, { token: await manifestToken(project.dir) }));
const say = (entry, extra = {}) => {
- if (json) out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render), ...extra }, null, 2));
+ if (json) {
+ const ct = captionTimes(entry, render);
+ out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render).map((t, i) => (entry.fx?.[i]?.kind === "caption" ? ct[i] : t)), ...extra }, null, 2));
+ }
else out(fxLines(entry, render).join("\n"));
};
const index = () => {
const n = Number(arg);
- if (!Number.isInteger(n) || n < 1) throw new FxError(`${verb} takes the zoom's number as ls shows it (1 = the first)`);
+ if (!Number.isInteger(n) || n < 1) throw new FxError(`${verb} takes the effect's number as ls shows it (1 = the first)`);
return n - 1;
};
if (verb === "ls") {
@@ -108,8 +147,26 @@ export async function fxCommand(project, words, { json = false, out = (s) => con
return 0;
}
if (verb === "add") {
- if (arg !== "word-zoom") throw new FxError("add names the effect: add word-zoom --match \"…\"");
+ if (arg !== "word-zoom" && arg !== "caption" && arg !== "clock") throw new FxError("add names the effect: add word-zoom --match \"…\" | add caption --match \"…\" --text \"…\" | add clock");
const patch = Object.fromEntries(Object.entries(fxPatchOf(str)).filter(([, v]) => v !== null));
+ if (arg === "clock") {
+ const extra = Object.keys(patch).filter((k) => k !== "rewind");
+ if (extra.length) throw new FxError(`--${extra[0]} is not a clock's knob (--rewind ${CLOCK_REWINDS.join("|")}, --off)`);
+ if ((e.fx ?? []).some((f) => f?.kind === "clock")) throw new FxError(`${e.id} has its clock already (set <n> --rewind …, or remove <n>)`);
+ const { result } = await write({ add: { kind: "clock", ...patch, ...(off ? { on: false } : {}) } });
+ say(result.entry, { index: result.index });
+ return 0;
+ }
+ if ("rewind" in patch) throw new FxError("--rewind is a clock's knob (add clock …)");
+ if (arg === "caption") {
+ if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add caption needs --match \"<the phrase, as the card shows it>\"");
+ if (typeof patch.text !== "string" || !patch.text.trim()) throw new FxError("add caption needs --text \"<what the chip says>\"");
+ for (const k of ["scale", "ease", "highlight"]) if (k in patch) throw new FxError(`--${k} is a word zoom's knob, not a caption's`);
+ const { result } = await write({ add: { kind: "caption", ...patch } });
+ say(result.entry, { index: result.index });
+ return 0;
+ }
+ if ("text" in patch || "place" in patch) throw new FxError("--text and --place are a caption's knobs (add caption …)");
if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add word-zoom needs --match \"<the word, as the card shows it>\"");
let note = null;
if (patch.at === undefined && !isNarrated(e)) {
@@ -127,7 +184,7 @@ export async function fxCommand(project, words, { json = false, out = (s) => con
if (verb === "set") {
const i = index();
const patch = fxPatchOf(str);
- if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --scale, --hold, --lead, --ease, --highlight, --occurrence, --target");
+ if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --hold, --lead, --occurrence, --target; a zoom's --scale, --ease, --highlight; a caption's --text, --place");
const { result } = await write({ set: i, patch });
say(result.entry);
return 0;
@@ -140,6 +197,35 @@ export async function fxCommand(project, words, { json = false, out = (s) => con
throw new FxError(`${verb}: ls, add, set or remove`);
}
+export const CLOCK_USAGE = [
+ "usage: umtool posts clock <project> [on|off|default] [--zone <IANA zone>] [--json]",
+ " THE CUT's CLOCK (render.posts.clock): each post item's own time on its card (\"4:10 AM ET · Wed 4 Nov\"), run",
+ " forward between two clock items (the gap flashing), rewound when the next is earlier. on/off is the cut's",
+ ` default (an item's own: umtool posts fx <p> <item> add clock [--off]); --zone the clock's zone (${CLOCK_ZONE}).`,
+ " With no word: which items show it.",
+].join("\n");
+
+/** `umtool posts clock …` (postsCli.mjs routes it here). */
+export async function clockCommand(project, words, { json = false, out = (s) => console.log(s), str }) {
+ const [verb] = words;
+ const zone = str("--zone");
+ if (verb !== undefined && !["on", "off", "default", "ls"].includes(verb)) throw new FxError(`${verb}: on, off or default`);
+ if ((verb && verb !== "ls") || zone !== null) {
+ const patch = {};
+ if (verb === "on" || verb === "off") patch.on = verb === "on";
+ if (verb === "default") patch.on = null;
+ if (zone !== null) patch.zone = zone === "default" ? null : zone;
+ await withEditNotes(project, async () => updatePostClock(project.dir, patch, { token: await manifestToken(project.dir) }));
+ }
+ const manifest = await readManifest(project.dir);
+ const render = manifest?.render ?? {};
+ const items = (manifest?.timeline ?? []).filter((x) => x?.type === "post");
+ const shown = items.filter((x) => clockOn(x, render));
+ if (json) out(JSON.stringify({ ok: true, clock: render.posts?.clock ?? null, zone: clockZoneOf(render), items: shown.map((x) => x.id) }, null, 2));
+ else out([`clock: the cut's ${render.posts?.clock?.on ? "on" : "off"}, zone ${clockZoneOf(render)}; ${shown.length} of ${items.length} post item(s) show it`, ...shown.slice(0, 40).map((x) => ` ${x.id} ${clockFace(Date.parse(x.date), clockZoneOf(render)).time} ${clockFace(Date.parse(x.date), clockZoneOf(render)).date}`)].join("\n"));
+ return 0;
+}
+
/**
* Where a take is transcribed from: its PARTS (a long post read part by part),
* each on its own file and offset by its start in the take, when every part's
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -42,9 +42,9 @@ export const NARRATE_USAGE = [
" umtool posts narrate <project> --list [--json]",
" umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]",
" [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full",
- " wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=…] [--json]",
+ " wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]",
" umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]",
- " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… engine=… voice=… follow=on|off follow.dim=… follow.ease=…",
+ " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… pace=fast|normal engine=… voice=… follow=on|off follow.dim=… follow.ease=…",
" --cut thread.parent=auto|full|excerpt|context|carry|hidden thread.quoted=… thread.carry=auto|on|off thread.reveal=on|off thread.shrink=… thread.dim=… thread.seconds=… thread.pan=…",
" A NARRATED POST ITEM: its script read by a stock synthetic voice, its attachment playing under the read (muffled,",
" then clean). Takes are files of the project (narration/posts/<postId>/take-<n>.<engine>-<voice>.wav) the EDITOR",
@@ -57,6 +57,8 @@ export const NARRATE_USAGE = [
" --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op",
" (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.",
" A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,",
+ " pace=fast plays a post (or, with --cut, every post) back to back: lead 0.1, tail 0.15, ramp 0.3, linger 0.45 --",
+ " unless it sets one itself; pace=normal the cut's gaps.",
" once `umtool posts fit` has scanned it (else from its in point). clip=full plays the attachments whole.",
" rate=0.8–1.5 (default 1): the READ sped up (its pitch kept), the attachment untouched; the post's length, its",
" muffle and its parts follow the faster read (a 10 s take at rate=1.25 reads in 8 s).",
@@ -215,7 +217,7 @@ export function narrationLines(e, render) {
});
if (plan.narration) {
const k = postNarrationKnobs(e, render);
- lines.push(` mix: ${["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate"].map((x) => fmtKnob(x, k[x])).join(" ")}`);
+ lines.push(` mix: ${["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace"].map((x) => fmtKnob(x, k[x])).join(" ")}`);
if (n.window) lines.push(` window: attachment ${n.window.media + 1} ${n.window.start}–${n.window.end} s (score ${n.window.score}): ${n.window.reason}`);
lines.push(` plays: voice ${plan.narration.at}–${(plan.narration.at + plan.narration.seconds).toFixed(2)} s, muffled to ${plan.narration.voiceEnd} s, clean from ${plan.narration.rampEnd} s; attachments ${plan.steps.map((s) => `${s.kind} ${s.at}+${s.seconds}`).join(", ") || "none"}${plan.held ? `, held ${plan.held} s` : ""}`);
}
@@ -240,6 +242,8 @@ export function mixPatchOf(pairs, { cut = false } = {}) {
if (["lead", "tail", "ramp", "linger", "wet", "lufs", "rate"].includes(k)) out[k] = clear ? null : num();
else if (k === "clip") out.clip = clear ? null : v;
else if (k === "lowpass" || k === "lowpassHz") out.lowpassHz = clear ? null : num();
+ // The pace (post-narration.mjs POST_PACES): fast plays it back to back; normal (or default) the cut's gaps.
+ else if (k === "pace") out.pace = clear ? null : v;
else if (k === "duck") out.duck = clear ? null : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("duck= takes on or off"); })();
else if (k === "short") out.short = clear ? null : v;
else if (k === "attach" && !cut) out.attach = clear ? null : v;
@@ -265,7 +269,7 @@ export function mixPatchOf(pairs, { cut = false } = {}) {
if (!m) throw new NarrateError("fit= takes read or read:<linger seconds>");
out.linger = m[1] !== undefined ? Number(m[1]) : null;
out.clip = null;
- } else throw new NarrateError(`${pair}: not a narration knob (lead, tail, ramp, end, wet, lowpass, duck, short, ${cut ? "linger, clip, lufs, rate, engine, voice, follow, follow.dim, follow.ease, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan" : "linger, clip, attach, lufs, rate, fit"})`);
+ } else throw new NarrateError(`${pair}: not a narration knob (lead, tail, ramp, end, wet, lowpass, duck, short, ${cut ? "linger, clip, lufs, rate, pace, engine, voice, follow, follow.dim, follow.ease, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan" : "linger, clip, attach, lufs, rate, pace, fit"})`);
}
if (!Object.keys(out).length) throw new NarrateError("nothing to set");
return out;
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -127,8 +127,10 @@ export const POSTS_USAGE = [
" umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix",
" (umtool posts narrate --help)",
" umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
- " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] [--scale s] … | set <n> … | remove <n>",
- " a WORD ZOOM: the card pushed in on a word as it is read (umtool posts fx --help)",
+ " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] … | add caption --match \"…\" --text \"…\" | set <n> … | remove <n>",
+ " a WORD ZOOM (the card pushed in on a word) or a CAPTION (a chip explaining a phrase) as it is read,",
+ " or its CLOCK (add clock [--rewind auto|on|off] [--off]) (umtool posts fx --help)",
+ " umtool posts clock <project> [on|off|default] [--zone <IANA zone>] the cut's CLOCK default: each post's time on its card, run between items",
" umtool posts avatar <project> [<handle> <image-file> | <handle> off] [--json]",
" an author's PICTURE on every card that draws them (postAvatars): the file copied into posts-media/_avatars/,",
" never replaced by the archive's; `off` clears it; no handle lists them. A blurred author never shows one.",
@@ -152,7 +154,7 @@ export const POSTS_USAGE = [
" umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment",
].join("\n");
-const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts"]);
+const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -453,7 +455,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
err(FX_USAGE);
return 2;
}
- return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str });
+ return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str, off: flags.has("--off") });
+ }
+ if (verb === "clock") {
+ const { CLOCK_USAGE, clockCommand } = await import("./postFxCli.mjs");
+ if (!projectArg || flags.has("--help")) {
+ err(CLOCK_USAGE);
+ return 2;
+ }
+ return await clockCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str });
}
if (verb === "fit") {
const { FIT_USAGE, fitCommand } = await import("./postNarrationCli.mjs");
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -2484,7 +2484,10 @@ async function buildMontageWall({ M, entries, render, outDir, timeline, provenan
* started `--from` another keeps the intro's file, and the crossfade batch
* over it, instead of copying the intro in again).
*/
-export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".intro.json", ".quote.txt", ".attrib.txt", ".channel.txt", ".post.json", ".combo.json"]);
+// A post item's record (`.post.json`, its key: post-render.mjs) and its combo pass's (`.combo.json`, the badge-less
+// `.plain.mp4`) ride with its segment, so a take --from another reuses a post item whose key still matches (the plain one too:
+// without it a reused badged segment would be taken for a plain one and badged again).
+export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".intro.json", ".quote.txt", ".attrib.txt", ".channel.txt", ".post.json", ".combo.json", ".plain.mp4"]);
/**
* Before an entry's segment is rebuilt: each of its files in `segDir` that is
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -78,6 +78,8 @@
"./post-branch-map": "./post-branch-map.mjs",
"./post-render": "./post-render.mjs",
"./word-zoom": "./word-zoom.mjs",
+ "./post-caption": "./post-caption.mjs",
+ "./post-clock": "./post-clock.mjs",
"./read-follow": "./read-follow.mjs",
"./presets": "./presets.mjs",
"./prune-frames": "./prune-frames.mjs",
diff --git a/umtool/report-to-video/post-caption.mjs b/umtool/report-to-video/post-caption.mjs
@@ -0,0 +1,674 @@
+// A POST ITEM's CAPTION (umtool/docs/report-video.md, "A caption"; operator, 4 Nov:
+// a small explanatory chip tied to a phrase -- "不動心 · fudōshin — "immovable
+// mind"" on "Fudōshin" -- appearing as the phrase is read and held a beat).
+//
+// entry.fx = [{ kind: "caption",
+// target?: "post" | "parent:<i>" | "quoted", // whose words (default: the post's own)
+// match: "<the word or phrase, as the card shows it>",
+// occurrence?: n, // its n-th time in that text (default 1)
+// text: "<what the chip says>", // ≤ CAPTION_TEXT_MAX characters, any script (CJK too)
+// at?: <item seconds>, // when; absent: the take's word timings, else the estimate
+// lead?: s, hold?: s, // in this long before the word; held this long from it
+// place?: "below" | "above" | "side" }] // where it sits by the phrase (default below)
+//
+// WHEN -- word-zoom's rule: `at` when it is set, else the matched word's start in
+// the picked take's word timings (the read's lead + start ÷ rate), else the
+// READING ESTIMATE: a narrated post's read spread over its script by characters,
+// an un-narrated one's 1 s + 3 words a second (word-zoom.mjs readingEstimate).
+// A caption never fights a word zoom: one that would be up while a zoom is (its
+// lead-in to back out) WAITS for the zoom to be out, then comes in.
+//
+// WHERE: a chip by the phrase (`place`; below by default), with a notch pointing
+// at it and an underline under it, inside the card. It never covers a word read
+// while it is up: a place that would is passed over for the next (below, above,
+// side), and the chip tracks the phrase while the card pans (read-follow.mjs).
+// It is drawn OVER the card, never in it: the read-follow geometry
+// (measureFollow, readInViewErrors) is measured without it, and it carries no
+// `data-w` / `data-post-block` -- it never counts as text, read or covering.
+//
+// THE LOOK: the card's palette (a panel of its background toward its accent, the
+// accent's border and notch), its faces, then the CJK faces this machine has
+// (CAPTION_FONT_STACK) so 不動心 is drawn, not boxes. Text before " — " is bold.
+//
+// Pure but for the DOM functions (mountCaptions, measureCaptionWords,
+// setCaptionState), which are SELF-CONTAINED: the build passes them to a page
+// (page.evaluate), Play calls them on its card frame's document.
+
+import { alignWords, cardWordsOf, findMatch, readingEstimate, scriptWordsOf, targetScope, targetTextOf } from "./word-zoom.mjs";
+import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs";
+import { esc, mixHex, rgbaOf } from "./post-item.mjs";
+
+export const CAPTION_PLACES = Object.freeze(["below", "above", "side"]);
+export const CAPTION_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.15, hold: 2.5, place: "below" });
+export const CAPTION_LIMITS = Object.freeze({ at: [0, 600], lead: [0, 3], hold: [0.5, 10], occurrence: [1, 99] });
+export const CAPTION_TEXT_MAX = 160;
+/** Its fade (and slide) in, and its fade out, seconds. */
+export const CAPTION_IN = 0.3;
+export const CAPTION_OUT = 0.35;
+/** How far it slides in from, px at 1080. */
+export const CAPTION_SLIDE = 16;
+/** The faces a chip is drawn in: the card's, then the CJK faces (Noto Sans CJK on this machine), then any sans. */
+export const CAPTION_FONT_STACK = "'Noto Sans CJK JP', 'Noto Sans CJK SC', 'Source Han Sans JP', 'Source Han Sans CN', 'WenQuanYi Zen Hei', sans-serif";
+
+const KEYS = new Set(["kind", "target", "match", "occurrence", "text", "at", "lead", "hold", "place"]);
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const numIn = (v, [lo, hi]) => fin(v) && v >= lo && v <= hi;
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const MATCH_MAX = 120;
+
+/**
+ * One caption with every default filled in.
+ * @param {Record<string, any> | null | undefined} fx
+ * @returns {{ kind?: string, target: string, match: string, occurrence: number, text: string, at?: number, lead: number, hold: number, place: string }}
+ */
+export const resolveCaption = (fx) => ({ ...CAPTION_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) });
+
+const TARGET_NAME = (t) => (t === "post" ? "the post's words" : t === "quoted" ? "the quoted post's words" : `the words of the post it answers (${t})`);
+
+/** Every reason caption `fx` (entry `e`'s fx[i], named `fw`) cannot be built, as sentences. word-zoom.mjs validatePostFx calls it. */
+export function captionErrors(e, fx, fw) {
+ const errors = [];
+ for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a caption key (${[...KEYS].join(", ")})`);
+ const target = fx.target ?? "post";
+ const text = typeof target === "string" ? targetTextOf(e, target) : null;
+ if (fx.target !== undefined && !(typeof fx.target === "string" && /^(post|quoted|parent:\d+)$/.test(fx.target))) errors.push(`${fw}.target must be "post", "quoted" or "parent:<i>"`);
+ else if (text === null) errors.push(`${fw}.target ${target}: the card draws no such post (${target === "quoted" ? "it quotes none" : "it answers no post there"})`);
+ if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase the caption explains, as the card shows it`);
+ else if (fx.match.length > MATCH_MAX) errors.push(`${fw}.match is longer than ${MATCH_MAX} characters`);
+ if (typeof fx.text !== "string" || !fx.text.trim()) errors.push(`${fw}.text must be what the caption says`);
+ else if (fx.text.length > CAPTION_TEXT_MAX) errors.push(`${fw}.text is longer than ${CAPTION_TEXT_MAX} characters (a caption is a chip, not a paragraph)`);
+ if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, CAPTION_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`);
+ if (typeof fx.match === "string" && fx.match.trim() && text !== null) {
+ const m = findMatch(text, fx.match, fx.occurrence ?? 1);
+ if (m.error === "not in") errors.push(`${fw}.match "${fx.match}" is not in ${TARGET_NAME(target)}`);
+ else if (m.error === "occurrence") errors.push(`${fw}.match "${fx.match}" is in ${TARGET_NAME(target)} ${m.count} time${m.count === 1 ? "" : "s"}: occurrence ${fx.occurrence} is not there`);
+ else if (m.error) errors.push(`${fw}.match: ${m.error}`);
+ }
+ for (const k of ["at", "lead", "hold"]) if (fx[k] !== undefined && !numIn(fx[k], CAPTION_LIMITS[k])) errors.push(`${fw}.${k} must be ${CAPTION_LIMITS[k][0]}–${CAPTION_LIMITS[k][1]} seconds`);
+ if (fx.place !== undefined && !CAPTION_PLACES.includes(fx.place)) errors.push(`${fw}.place must be one of ${CAPTION_PLACES.join(", ")}`);
+ return errors;
+}
+
+// ---------------------------------------------------------------------------
+// WHEN.
+// ---------------------------------------------------------------------------
+
+/** Fill each null in `times` between its known neighbours (an end with none: the nearest known). */
+function fillTimes(times) {
+ const out = times.slice();
+ const known = out.map((v, i) => (v === null ? -1 : i)).filter((i) => i >= 0);
+ if (!known.length) return out;
+ for (let i = 0; i < out.length; i += 1) {
+ if (out[i] !== null) continue;
+ const a = [...known].reverse().find((k) => k < i);
+ const b = known.find((k) => k > i);
+ if (a === undefined) out[i] = out[b];
+ else if (b === undefined) out[i] = out[a];
+ else out[i] = r3(out[a] + ((out[b] - out[a]) * (i - a)) / (b - a));
+ }
+ return out;
+}
+
+/**
+ * When each card word of `target` is read, item seconds: `{ times, source }`
+ * -- "words" from the picked take's word timings, "estimate" otherwise (a
+ * narrated post: its script's characters spread over the read; an un-narrated
+ * one: readingEstimate). Null when the target draws no words.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {string} [target]
+ * @param {Record<string, any> | null} [schedule]
+ * @returns {{ times: Array<number | null>, source: "words" | "estimate" } | null}
+ */
+export function cardWordTimes(entry, render = undefined, target = "post", schedule = undefined) {
+ const text = targetTextOf(entry, target);
+ if (text === null) return null;
+ const words = cardWordsOf(text);
+ if (!isNarrated(entry)) return { times: words.map((_, i) => readingEstimate(i)), source: "estimate" };
+ const sch = schedule ?? narrationSchedule(entry, render);
+ const rate = sch.rate || 1;
+ const take = pickedTake(entry);
+ const timed = Array.isArray(take?.words) && take.words.length ? take.words : null;
+ if (timed) {
+ const map = alignWords(words, timed.map((x) => x.w));
+ return { times: fillTimes(map.map((k) => (k >= 0 && fin(timed[k].start) ? r3(sch.at + timed[k].start / rate) : null))), source: "words" };
+ }
+ const script = typeof take?.script === "string" && take.script.trim() ? take.script : String(entry?.narration?.script ?? "");
+ const sw = scriptWordsOf(script);
+ const map = alignWords(words, sw);
+ const before = [];
+ let n = 0;
+ for (const w of sw) {
+ before.push(n);
+ n += w.length + 1;
+ }
+ const secs = fin(sch.seconds) && sch.seconds > 0 ? sch.seconds : (n / 15);
+ return { times: fillTimes(map.map((k) => (k >= 0 && n > 0 ? r3(sch.at + (before[k] / n) * secs) : null))), source: "estimate" };
+}
+
+/**
+ * Each caption's moment, one per fx (a word zoom's row is `{ i, kind }`):
+ * `{ i, t, source: "at"|"words"|"estimate" }` or `{ i, error }`.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {Record<string, any> | null} [schedule]
+ * @returns {Array<{ i: number, t?: number, source?: string, error?: string, kind?: string | null }>}
+ */
+export function captionTimes(entry, render = undefined, schedule = undefined) {
+ const list = Array.isArray(entry?.fx) ? entry.fx : [];
+ const cache = new Map();
+ return list.map((fx0, i) => {
+ if (!isObj(fx0) || fx0.kind !== "caption") return { i, kind: fx0?.kind ?? null };
+ const fx = resolveCaption(fx0);
+ if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" };
+ const text = targetTextOf(entry, fx.target);
+ const m = findMatch(text, fx.match, fx.occurrence);
+ if (m.error) return { i, error: `${entry?.id ?? "?"}: caption ${i + 1} ("${fx.match}") is not on the card` };
+ if (!cache.has(fx.target)) cache.set(fx.target, cardWordTimes(entry, render, fx.target, schedule));
+ const wt = cache.get(fx.target);
+ const t = wt?.times?.[m.from];
+ if (!fin(t)) return { i, t: readingEstimate(m.from), source: "estimate" };
+ return { i, t: r3(t), source: wt.source };
+ });
+}
+
+/**
+ * One caption's span on the item's clock: in from t0 (its lead before the
+ * word) to t1, held to t2 (`hold` after the word), out by t3. It WAITS for a
+ * word zoom (`zooms`: their spans, word-zoom.mjs zoomSpan) it would be up
+ * with, and ends by `end` (the item's last second, or a stack card's media
+ * phase). `{ t0, t1, t2, t3, at, waited }` or `{ error }`.
+ * @param {Record<string, any>} fx0
+ * @param {number} t
+ * @param {{ zooms?: Array<Record<string, any>>, end?: number }} [o]
+ * @returns {{ t0: number, t1: number, t2: number, t3: number, at: number, waited: number | null, error?: undefined } | { error: string, t0?: undefined, t1?: undefined, t2?: undefined, t3?: undefined, at?: undefined, waited?: undefined }}
+ */
+export function captionSpan(fx0, t, { zooms = [], end = Infinity } = {}) {
+ const fx = resolveCaption(fx0);
+ let t0 = Math.max(0, t - fx.lead);
+ let dur = Math.max(CAPTION_IN, t + fx.hold - t0);
+ /** @type {number | null} */
+ let waited = null;
+ const sorted = zooms.map((z, k) => ({ ...z, k })).filter((z) => fin(z.t0) && fin(z.t3)).sort((a, b) => a.t0 - b.t0);
+ for (const z of sorted) {
+ if (t0 < z.t3 && t0 + dur + CAPTION_OUT > z.t0) {
+ t0 = z.t3;
+ waited = z.i ?? z.k;
+ }
+ }
+ if (t0 >= end - CAPTION_IN - 0.05) return { error: `starts at ${r3(t0)} s, at or after the item's ${r3(end)} s${waited !== null ? " (it waits for a word zoom)" : ""}` };
+ let t2 = t0 + dur;
+ if (t2 + CAPTION_OUT > end) t2 = Math.max(t0 + CAPTION_IN, end - CAPTION_OUT);
+ const t1 = Math.min(t2, t0 + CAPTION_IN);
+ return { t0: r3(t0), t1: r3(t1), t2: r3(t2), t3: r3(Math.min(end, t2 + CAPTION_OUT)), at: r3(t), waited };
+}
+
+const easeOut = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 3;
+
+/** The chip's opacity at item second `s` (0–1). */
+export function captionOpacityAt(span, s) {
+ if (!span || span.error || s < span.t0 || s >= span.t3) return 0;
+ if (s < span.t1) return span.t1 > span.t0 ? easeOut((s - span.t0) / (span.t1 - span.t0)) : 1;
+ if (s < span.t2) return 1;
+ return 1 - (s - span.t2) / (span.t3 - span.t2);
+}
+
+/** How much of its slide in is left at `s`, 1 → 0 (0 once in). */
+export function captionSlideAt(span, s) {
+ if (!span || span.error || s >= span.t1) return 0;
+ if (s < span.t0) return 1;
+ return 1 - easeOut((s - span.t0) / Math.max(1e-6, span.t1 - span.t0));
+}
+
+/** The direction a placed chip slides in from (toward the phrase): a unit `{ x, y }`. */
+export const slideDir = (place) => (place === "above" ? { x: 0, y: -1 } : place === "side-right" ? { x: 1, y: 0 } : place === "side-left" ? { x: -1, y: 0 } : { x: 0, y: 1 });
+
+/** Two captions of one post up at once: their indices, or null (one at a time). */
+export function overlappingCaptions(spans) {
+ const s = spans.filter((x) => x && fin(x.t0)).sort((a, b) => a.t0 - b.t0);
+ for (let k = 1; k < s.length; k += 1) if (s[k].t0 < s[k - 1].t3) return [s[k - 1].i, s[k].i];
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// WHERE.
+// ---------------------------------------------------------------------------
+
+/** @typedef {{ x: number, y: number, width: number, height: number }} Rect */
+/** @param {Rect} a @param {Rect} b */
+const area = (a, b) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
+/** @param {Rect} r @param {Rect} b */
+const inside = (r, b) => r.x >= b.x - 0.5 && r.y >= b.y - 0.5 && r.x + r.width <= b.x + b.width + 0.5 && r.y + r.height <= b.y + b.height + 0.5;
+/** @param {Rect} r @param {number} m */
+const grow = (r, m) => ({ x: r.x - m, y: r.y - m, width: r.width + 2 * m, height: r.height + 2 * m });
+/** Whether segment a→b crosses rect r (sampled every 3 px). @param {number[]} a @param {number[]} b @param {Rect} r */
+function crosses(a, b, r) {
+ const n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 3));
+ for (let k = 0; k <= n; k += 1) {
+ const x = a[0] + ((b[0] - a[0]) * k) / n;
+ const y = a[1] + ((b[1] - a[1]) * k) / n;
+ if (x > r.x && x < r.x + r.width && y > r.y && y < r.y + r.height) return true;
+ }
+ return false;
+}
+
+/**
+ * THE LEADER: a thin line from the phrase's underline to the chip, through free
+ * space only -- straight when nothing is in the way, else an elbow out along the
+ * underline (in the gap under the phrase's line) to the text column's gutter,
+ * along the gutter, then across to the chip. `[[x, y], …]` or null (none clear).
+ * @param {Rect} word @param {Rect} chip @param {Rect[]} obstacles @param {Rect | null} column
+ */
+export function leaderPath(word, chip, obstacles, column) {
+ const uy = word.y + word.height;
+ const cy = chip.y + chip.height / 2;
+ const cx = chip.x + chip.width / 2;
+ // The chip's edge facing the phrase.
+ const end = chip.y >= uy ? [Math.min(chip.x + chip.width - 8, Math.max(chip.x + 8, word.x + word.width / 2)), chip.y]
+ : chip.y + chip.height <= word.y ? [Math.min(chip.x + chip.width - 8, Math.max(chip.x + 8, word.x + word.width / 2)), chip.y + chip.height]
+ : chip.x >= word.x + word.width ? [chip.x, cy] : [chip.x + chip.width, cy];
+ const clear = (pts) => pts.slice(1).every((p, k) => obstacles.every((r) => !crosses(pts[k], p, grow(r, 1))));
+ const start = [Math.min(Math.max(end[0], word.x + 4), word.x + word.width - 4), uy];
+ const straight = [start, end];
+ if (clear(straight)) return straight;
+ const tries = [];
+ for (const side of [1, -1]) {
+ const gx = column ? (side > 0 ? column.x + column.width + 10 : column.x - 10) : side > 0 ? word.x + word.width + 10 : word.x - 10;
+ const s = [side > 0 ? word.x + word.width : word.x, uy];
+ const ey = chip.y <= uy && chip.y + chip.height >= uy ? uy : cy;
+ const ex = gx >= chip.x + chip.width ? chip.x + chip.width : gx <= chip.x ? chip.x : cx;
+ const pts = [s, [gx, uy], [gx, ey], [ex, ey]];
+ // The first leg runs in the gap under the phrase's line (not judged); the rest through free space.
+ if (clear(pts.slice(1))) tries.push({ pts, len: Math.abs(gx - s[0]) + Math.abs(ey - uy) + Math.abs(ex - gx) });
+ }
+ tries.sort((a, b) => a.len - b.len);
+ return tries[0]?.pts ?? null;
+}
+
+/**
+ * THE PLACE (operator, 4 Nov: "a caption chip never covers ANY of the card's
+ * words -- read, unread or already read"): the chip in FREE SPACE -- over no
+ * `obstacles` (every word drawn, the card's header and counts, the attachments,
+ * the clock), inside `bounds` (the footage box) -- as near the phrase as it can
+ * be, with a leader to it through free space. `sizes`: the chip laid out at
+ * each width it may take (`{ width, height, max }`, widest first); `place`
+ * (below | above | side) a preference, `card` the card's box (a place on the
+ * card beats one off it). Every candidate is a grid of spots around the phrase
+ * and down the box; the cheapest clear one wins (distance, plus a cost off the
+ * card, against the preferred side, and without a clear leader). `{ x, y,
+ * width, height, max, place, covers, leader }` -- `covers` 0 unless no spot is
+ * free (then the least-covering, which the build warns about).
+ * @param {{ word: Rect, sizes: Array<{ width: number, height: number, max?: number }>, bounds: Rect, card?: Rect | null, column?: Rect | null, place?: string, obstacles?: Rect[], gap?: number, step?: number }} o
+ */
+export function placeCaption({ word, sizes, bounds, card = null, column = null, place = "below", obstacles = [], gap = 10, step = 6 }) {
+ const cx = word.x + word.width / 2;
+ const cy = word.y + word.height / 2;
+ const blocked = obstacles.map((r) => grow(r, gap / 2)).concat([grow(word, gap / 2)]);
+ let best = null;
+ let least = null;
+ for (const [si, sz] of sizes.entries()) {
+ const xs = new Set();
+ for (const x of [cx - sz.width / 2, word.x, word.x + word.width - sz.width, card ? card.x + 14 : bounds.x, card ? card.x + card.width + gap : bounds.x, column ? column.x : bounds.x]) xs.add(Math.round(x));
+ for (let x = bounds.x; x + sz.width <= bounds.x + bounds.width; x += Math.max(24, step * 4)) xs.add(Math.round(x));
+ for (const x0 of xs) {
+ const x = Math.min(bounds.x + bounds.width - sz.width, Math.max(bounds.x, x0));
+ for (let y = bounds.y; y + sz.height <= bounds.y + bounds.height; y += step) {
+ const r = { x, y, width: sz.width, height: sz.height };
+ const covers = blocked.filter((b) => area(r, b) > 0).length;
+ const mx = r.x + r.width / 2;
+ const my = r.y + r.height / 2;
+ let cost = Math.hypot(mx - cx, my - cy) + si * 40;
+ const onCard = card && inside(r, card);
+ if (!onCard) cost += 160;
+ const below = r.y >= word.y + word.height;
+ const above = r.y + r.height <= word.y;
+ const side = !below && !above;
+ if ((place === "below" && !below) || (place === "above" && !above) || (place === "side" && !side)) cost += 60;
+ if (covers) {
+ if (!least || covers < least.covers || (covers === least.covers && cost < least.cost)) least = { ...r, max: sz.max, covers, cost };
+ continue;
+ }
+ if (best && cost >= best.cost) continue;
+ best = { ...r, max: sz.max, covers: 0, cost };
+ }
+ }
+ }
+ // Its leader, through free space; a spot with none is passed over for the next clear one when there is one.
+ const pick = best ?? least;
+ if (!pick) return null;
+ let leader = leaderPath(word, pick, obstacles, column);
+ let out = pick;
+ if (!leader && best) {
+ // Search again, the ones with a clear leader only (fewer: the cost already ranked them).
+ const ranked = [];
+ for (const sz of sizes) {
+ for (let y = bounds.y; y + sz.height <= bounds.y + bounds.height; y += step * 2) {
+ for (let x = bounds.x; x + sz.width <= bounds.x + bounds.width; x += step * 4) {
+ const r = { x, y, width: sz.width, height: sz.height };
+ if (blocked.some((b) => area(r, b) > 0)) continue;
+ ranked.push({ ...r, max: sz.max, covers: 0, cost: Math.hypot(x + sz.width / 2 - cx, y + sz.height / 2 - cy) + (card && inside(r, card) ? 0 : 160) });
+ }
+ }
+ ranked.sort((a, b) => a.cost - b.cost);
+ for (const r of ranked.slice(0, 200)) {
+ const l = leaderPath(word, r, obstacles, column);
+ if (l) {
+ out = r;
+ leader = l;
+ break;
+ }
+ }
+ if (leader) break;
+ }
+ }
+ const where = card && inside(out, card) ? "card" : "off-card";
+ const { cost, ...rest } = out;
+ return { ...rest, x: Math.round(rest.x), y: Math.round(rest.y), place: where, leader: leader ? leader.map(([x, y]) => [Math.round(x), Math.round(y)]) : null };
+}
+
+// ---------------------------------------------------------------------------
+// THE PLAN.
+// ---------------------------------------------------------------------------
+
+/**
+ * Post item `entry`'s captions, resolved: `[{ i, scope, from, to, text,
+ * place, t, source, span, avoid }]` -- `avoid` the target's word indices read
+ * while it is up (the chip covers none of them). `zooms`: the item's word
+ * zooms' spans (each a caption waits for); `end`: the last second a caption
+ * may be up. Throws in the build's words when one cannot be up, or two are up at once.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {{ zooms?: Array<Record<string, any>>, end?: number, schedule?: Record<string, any> }} [o]
+ * @returns {Array<{ i: number, scope: string, from: number, to: number, text: string, place: string, t: number, source: string, span: { t0: number, t1: number, t2: number, t3: number, at: number, waited: number | null, i: number }, avoid: number[] }>}
+ */
+export function captionPlan(entry, render = undefined, { zooms = [], end = Infinity, schedule = undefined } = {}) {
+ const list = Array.isArray(entry?.fx) ? entry.fx : [];
+ if (!list.some((f) => f?.kind === "caption")) return [];
+ const times = captionTimes(entry, render, schedule);
+ const bad = times.filter((t) => t.error);
+ if (bad.length) throw new Error(bad.map((t) => t.error).join("; "));
+ const wt = new Map();
+ /** @type {ReturnType<typeof captionPlan>} */
+ const out = [];
+ for (const [i, fx0] of list.entries()) {
+ if (fx0?.kind !== "caption") continue;
+ const fx = resolveCaption(fx0);
+ const m = findMatch(targetTextOf(entry, fx.target), fx.match, fx.occurrence);
+ const span = captionSpan(fx0, times[i].t, { zooms, end });
+ if (span.error !== undefined) throw new Error(`${entry?.id ?? "?"}: caption ${i + 1} ("${fx.match}") ${span.error} (move its at, or shorten the zoom)`);
+ if (!wt.has(fx.target)) wt.set(fx.target, cardWordTimes(entry, render, fx.target, schedule));
+ const read = wt.get(fx.target)?.times ?? [];
+ const avoid = read.map((s, k) => (fin(s) && s >= span.t0 - 0.25 && s <= span.t3 + 0.25 && (k < m.from || k > m.to) ? k : -1)).filter((k) => k >= 0);
+ out.push({ i, scope: targetScope(fx.target), from: m.from, to: m.to, text: fx.text, place: fx.place, t: Number(times[i].t), source: String(times[i].source), span: { ...span, i }, avoid });
+ }
+ const clash = overlappingCaptions(out.map((c) => c.span));
+ if (clash) throw new Error(`${entry?.id ?? "?"}: captions ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at, or shorten its hold)`);
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// THE LOOK.
+// ---------------------------------------------------------------------------
+
+/** The chip's inner HTML: the text, its part before " — " bold. */
+export function captionInnerHtml(text) {
+ const t = String(text ?? "");
+ const cut = t.indexOf(" — ");
+ return cut > 0 ? `<b>${esc(t.slice(0, cut))}</b><span class="pcap-rest"> — ${esc(t.slice(cut + 3))}</span>` : esc(t);
+}
+
+/**
+ * The chips' CSS, for a page `height` px tall (sizes at 1080), in the card's
+ * palette (`palette`, the deck's) and faces (the card's @font-face PostSans /
+ * PostSansBold, then CAPTION_FONT_STACK).
+ */
+/** @param {{ height?: number, palette?: Record<string, string> }} [o] */
+export function captionCss({ height = 1080, palette = {} } = {}) {
+ const k = height / 1080;
+ const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette };
+ const panel = mixHex(pal.bg, pal.accent, 0.16);
+ const n = Math.round(16 * k);
+ return `
+[data-post-fx-captions] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 60; }
+.pcap { position: absolute; left: 0; top: 0; max-width: ${Math.round(620 * k)}px; padding: ${Math.round(10 * k)}px ${Math.round(18 * k)}px ${Math.round(11 * k)}px; background: ${panel}; color: ${pal.fg};
+ border: ${Math.max(1, Math.round(2 * k))}px solid ${pal.accent}; border-radius: ${Math.round(12 * k)}px; box-shadow: 0 ${Math.round(8 * k)}px ${Math.round(26 * k)}px ${rgbaOf("#000000", 0.5)};
+ font-family: 'PostSans', ${CAPTION_FONT_STACK}; font-size: ${Math.round(27 * k)}px; line-height: 1.28; font-synthesis: none; opacity: 0; will-change: transform, opacity; overflow-wrap: anywhere; }
+.pcap b { font-family: 'PostSansBold', ${CAPTION_FONT_STACK}; font-weight: 700; color: ${pal.fg}; }
+.pcap .pcap-rest { color: ${mixHex(pal.fg, pal.muted, 0.25)}; }
+.pcap::before { content: ""; position: absolute; width: ${n}px; height: ${n}px; background: ${panel}; border: inherit; border-width: ${Math.max(1, Math.round(2 * k))}px; border-radius: ${Math.round(2 * k)}px; transform: rotate(45deg); }
+.pcap[data-place="below"]::before { top: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-right: none; border-bottom: none; }
+.pcap[data-place="above"]::before { bottom: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-left: none; border-top: none; }
+.pcap[data-place="side-right"]::before { left: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-right: none; border-top: none; }
+.pcap[data-place="side-left"]::before { right: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-left: none; border-bottom: none; }
+.pcap[data-place="free"]::before { display: none; }
+.pcap-leader-line { stroke: ${pal.accent}; }
+.pcap-leader-dot { fill: ${pal.accent}; }
+.pcap-mark { position: absolute; height: ${Math.max(2, Math.round(3 * k))}px; background: ${pal.accent}; border-radius: ${Math.max(1, Math.round(2 * k))}px; opacity: 0; }
+`;
+}
+
+// ---------------------------------------------------------------------------
+// THE DOM (self-contained: passed to page.evaluate by the build, called by Play).
+// ---------------------------------------------------------------------------
+
+/** The widths a chip is laid out at (px at 1080): the widest first; a narrower one fits a smaller space. */
+export const CAPTION_WIDTHS = Object.freeze([620, 480, 380, 300]);
+
+/**
+ * Mount the chips over the card page: `{ css, chips: [{ i, html }], k }`, each
+ * laid out unplaced and hidden at every width of CAPTION_WIDTHS (× `k`).
+ * Returns each one's sizes `[{ i, sizes: [{ width, height, max }] }]`.
+ * @param {{ css?: string, chips?: Array<{ i: number, html: string }>, k?: number, widths?: number[] } | null} arg
+ * @param {Document} [doc]
+ * @returns {Array<{ i: number, sizes: Array<{ width: number, height: number, max: number }> }>}
+ */
+export function mountCaptions(arg, doc = document) {
+ doc.querySelectorAll("[data-post-fx-captions], style[data-post-fx-captions-css]").forEach((el) => el.remove());
+ const chips = (arg && arg.chips) || [];
+ if (!chips.length) return [];
+ const style = doc.createElement("style");
+ style.setAttribute("data-post-fx-captions-css", "");
+ style.textContent = arg.css || "";
+ doc.head.appendChild(style);
+ const layer = doc.createElement("div");
+ layer.setAttribute("data-post-fx-captions", "");
+ doc.body.appendChild(layer);
+ const k = (arg && arg.k) || 1;
+ const widths = (arg && arg.widths) || [620, 480, 380, 300];
+ return chips.map((c) => {
+ const el = doc.createElement("div");
+ el.className = "pcap";
+ el.setAttribute("data-post-fx-caption", String(c.i));
+ el.innerHTML = c.html;
+ layer.appendChild(el);
+ const sizes = [];
+ for (const w of widths) {
+ const max = Math.round(w * k);
+ el.style.maxWidth = `${max}px`;
+ const b = el.getBoundingClientRect();
+ const s = { width: Math.ceil(b.width), height: Math.ceil(b.height), max };
+ if (!sizes.some((x) => x.width === s.width && x.height === s.height)) sizes.push(s);
+ }
+ el.style.maxWidth = "";
+ return { i: c.i, sizes };
+ });
+}
+
+/**
+ * The phrase's geometry as the card is drawn now: `{ scope, from, to, avoid:
+ * [indices] }` → `{ card, word, lines, avoid, obstacles, column }` -- px boxes:
+ * `lines` the phrase's box per line (its underline), `obstacles` everything
+ * drawn a chip may not cover (every word in view, the card's header, its
+ * counts, a quote's or a picture's frame -- the phrase itself apart), `column`
+ * the phrase's text column; or `{ error }` when a word is not drawn or is cut
+ * off the card.
+ * @param {{ scope: string, from: number, to: number, avoid?: number[] }} arg
+ * @param {Document} [doc]
+ * @returns {{ error: string } | { error?: undefined, card: Rect, word: Rect, lines: Rect[], avoid: Rect[], obstacles: Rect[], column: Rect | null }}
+ */
+export function measureCaptionWords(arg, doc = document) {
+ const rect = (el) => {
+ const b = el.getBoundingClientRect();
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
+ };
+ const card = doc.querySelector("[data-post-card]");
+ if (!card) return { error: "the card is not drawn" };
+ /** @type {Rect[]} */
+ const lines = [];
+ let column = null;
+ for (let i = arg.from; i <= arg.to; i += 1) {
+ const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`);
+ if (!el) return { error: `word ${i} is not on the card` };
+ const clip = el.closest(".words, .ptext, .qtext, .twords, .tt");
+ if (clip && !column) column = rect(clip);
+ const cb = (clip || card).getBoundingClientRect();
+ for (const r of Array.from(el.getClientRects())) {
+ if (r.width === 0) continue;
+ if (r.bottom > cb.bottom + 1 || r.top < cb.top - 1) return { error: "cut off the card (the text is longer than the card shows)" };
+ const same = lines.find((l) => Math.abs(l.y - r.top) < r.height / 2);
+ if (same) {
+ const x1 = Math.max(same.x + same.width, r.right);
+ same.x = Math.min(same.x, r.left);
+ same.width = x1 - same.x;
+ same.height = Math.max(same.height, r.height);
+ } else lines.push({ x: r.left, y: r.top, width: r.width, height: r.height });
+ }
+ }
+ if (!lines.length) return { error: "the words are not drawn" };
+ const x0 = Math.min(...lines.map((l) => l.x));
+ const y0 = Math.min(...lines.map((l) => l.y));
+ const x1 = Math.max(...lines.map((l) => l.x + l.width));
+ const y1 = Math.max(...lines.map((l) => l.y + l.height));
+ /** @type {Rect[]} */
+ const avoid = [];
+ for (const i of arg.avoid || []) {
+ const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`);
+ if (el) for (const r of Array.from(el.getClientRects())) if (r.width > 0) avoid.push({ x: r.left, y: r.top, width: r.width, height: r.height });
+ }
+ // Everything drawn a chip may not cover: each word in view (inside what clips it, not faded out), then the
+ // card's furniture -- names, dates, the platform mark, avatars, counts, labels, a context shot or quote frame.
+ /** @type {Rect[]} */
+ const obstacles = [];
+ const mine = new Set(Array.from({ length: arg.to - arg.from + 1 }, (_, k) => `${arg.scope}:${arg.from + k}`));
+ const view = doc.defaultView;
+ const shown = (el) => {
+ for (let n = el; n && n !== doc.body; n = n.parentElement) {
+ const st = view ? view.getComputedStyle(n) : null;
+ if (st && (st.visibility === "hidden" || st.display === "none" || Number(st.opacity) < 0.05)) return false;
+ }
+ return true;
+ };
+ for (const el of Array.from(doc.querySelectorAll("[data-w]"))) {
+ if (mine.has(el.getAttribute("data-w") || "")) continue;
+ const clip = el.closest(".words, .ptext, .qtext, .twords, .tt, [data-thread-tile]") || card;
+ const cb = clip.getBoundingClientRect();
+ for (const r of Array.from(el.getClientRects())) {
+ if (r.width <= 0 || r.bottom <= cb.top || r.top >= cb.bottom) continue;
+ obstacles.push({ x: r.left, y: Math.max(r.top, cb.top), width: r.width, height: Math.min(r.bottom, cb.bottom) - Math.max(r.top, cb.top) });
+ }
+ }
+ for (const el of Array.from(card.querySelectorAll(".avatar, .name, .handle, .date, .pdate, .mark, .plabel, .repost, .replying, .counts > *, .pshot img, .sline, .strip"))) {
+ if (!shown(el)) continue;
+ for (const r of Array.from(el.getClientRects())) if (r.width > 0 && r.height > 0) obstacles.push({ x: r.left, y: r.top, width: r.width, height: r.height });
+ }
+ return { card: rect(card), word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }, lines, avoid, obstacles, column };
+}
+
+/**
+ * Set the chips: `[{ i, x, y, max, opacity, dx, dy, marks, mark, leader }]`
+ * (`marks`: the underline's boxes under the phrase, `leader` its line to the
+ * chip, `mark` their opacity); a chip not listed is hidden. `only`: "chip" |
+ * "mark" draws just that layer (the build shoots them apart), absent both.
+ * @param {{ list?: Array<Record<string, any>>, only?: string, stroke?: number } | null} arg
+ * @param {Document} [doc]
+ */
+export function setCaptionState(arg, doc = document) {
+ const list = (arg && arg.list) || [];
+ const only = arg && arg.only;
+ const layer = doc.querySelector("[data-post-fx-captions]");
+ if (!layer) return;
+ layer.querySelectorAll(".pcap-mark, .pcap-leader").forEach((el) => el.remove());
+ for (const el of Array.from(layer.querySelectorAll(".pcap"))) {
+ const c = list.find((x) => String(x.i) === el.getAttribute("data-post-fx-caption"));
+ if (!c || only === "mark") {
+ el.style.opacity = "0";
+ continue;
+ }
+ el.setAttribute("data-place", "free");
+ if (c.max) el.style.maxWidth = `${c.max}px`;
+ el.style.transform = `translate(${Math.round(c.x + (c.dx || 0))}px, ${Math.round(c.y + (c.dy || 0))}px)`;
+ el.style.opacity = String(c.opacity);
+ }
+ if (only === "chip") return;
+ const sw = (arg && arg.stroke) || 2;
+ for (const c of list) {
+ for (const l of c.marks || []) {
+ const m = doc.createElement("div");
+ m.className = "pcap-mark";
+ m.setAttribute("data-post-fx-caption-mark", String(c.i));
+ const h = Math.max(2, Math.round(l.height * 0.07));
+ m.style.left = `${Math.round(l.x)}px`;
+ m.style.top = `${Math.round(l.y + l.height - h * 0.4)}px`;
+ m.style.width = `${Math.round(l.width)}px`;
+ m.style.opacity = String(c.mark ?? c.opacity);
+ layer.appendChild(m);
+ }
+ if (Array.isArray(c.leader) && c.leader.length > 1) {
+ const ns = "http://www.w3.org/2000/svg";
+ const svg = doc.createElementNS(ns, "svg");
+ svg.setAttribute("class", "pcap-leader");
+ svg.setAttribute("data-post-fx-caption-leader", String(c.i));
+ svg.setAttribute("width", "100%");
+ svg.setAttribute("height", "100%");
+ svg.style.position = "absolute";
+ svg.style.left = "0";
+ svg.style.top = "0";
+ svg.style.overflow = "visible";
+ svg.style.opacity = String(c.mark ?? c.opacity);
+ const pl = doc.createElementNS(ns, "polyline");
+ pl.setAttribute("points", c.leader.map((p) => `${p[0] + (c.ldx || 0)},${p[1] + (c.ldy || 0)}`).join(" "));
+ pl.setAttribute("fill", "none");
+ pl.setAttribute("stroke-width", String(sw));
+ pl.setAttribute("stroke-linejoin", "round");
+ pl.setAttribute("class", "pcap-leader-line");
+ svg.appendChild(pl);
+ const last = c.leader[c.leader.length - 1];
+ const dot = doc.createElementNS(ns, "circle");
+ dot.setAttribute("cx", String(last[0]));
+ dot.setAttribute("cy", String(last[1]));
+ dot.setAttribute("r", String(sw * 1.6));
+ dot.setAttribute("class", "pcap-leader-dot");
+ svg.appendChild(dot);
+ layer.appendChild(svg);
+ }
+ }
+}
+
+/**
+ * The card page's palette, read off its drawn styles (Play has the page, not the
+ * deck's render): `{ bg, fg, muted, accent }` as #rrggbb.
+ * @param {Document} [doc]
+ * @returns {Record<string, string>}
+ */
+export function paletteOfDoc(doc = document) {
+ const hex = (c) => {
+ const m = /rgba?\(([^)]+)\)/.exec(String(c || ""));
+ if (!m) return null;
+ const [r, g, b] = m[1].split(",").map((v) => Math.round(Number(v)));
+ return `#${[r, g, b].map((v) => Math.max(0, Math.min(255, v || 0)).toString(16).padStart(2, "0")).join("")}`;
+ };
+ const view = doc.defaultView;
+ if (!view || !doc.body) return {};
+ const probe = (cls) => {
+ const el = doc.createElement("span");
+ el.className = cls;
+ doc.body.appendChild(el);
+ const c = view.getComputedStyle(el).color;
+ el.remove();
+ return hex(c);
+ };
+ const st = view.getComputedStyle(doc.body);
+ const out = { bg: hex(st.backgroundColor), fg: hex(st.color), accent: probe("mention"), muted: probe("pdate") };
+ return Object.fromEntries(Object.entries(out).filter(([, v]) => v));
+}
diff --git a/umtool/report-to-video/post-caption.test.mjs b/umtool/report-to-video/post-caption.test.mjs
@@ -0,0 +1,141 @@
+// A post item's CAPTION (post-caption.mjs): its validation, its time (at, the
+// take's words, the reading estimate), its span (waiting for a word zoom), and
+// its place (never over a word read while it is up).
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ CAPTION_IN, CAPTION_OUT, captionInnerHtml, captionOpacityAt, captionPlan, captionSlideAt, captionSpan, captionTimes, cardWordTimes, placeCaption,
+} from "./post-caption.mjs";
+import { validatePostFx, wordZoomTimes } from "./word-zoom.mjs";
+
+const TEXT = "I'm ignoring my broken bones so my training can continue. I have achieved Fudōshin. Its amazing.";
+const base = (o = {}) => ({ type: "post", id: "p1", post: "s/1", platform: "x", author: "S", handle: "s", date: "2026-10-20T19:46:00.000Z", text: TEXT, ...o });
+const cap = (o = {}) => ({ kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"", ...o });
+const take = (o = {}) => ({ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 10, script: TEXT, ...o });
+
+test("validation: a caption's keys, its match, its text, its knobs -- in the build's words", () => {
+ assert.deepEqual(validatePostFx(base({ fx: [cap()] })), []);
+ const errs = validatePostFx(base({ fx: [cap({ match: "Fudoshinn", text: "", place: "left", hold: 0.1, scale: 2 })] }));
+ assert.ok(errs.some((e) => /fx\[0\]\.scale is not a caption key/.test(e)), errs.join("\n"));
+ assert.ok(errs.some((e) => /match "Fudoshinn" is not in the post's words/.test(e)));
+ assert.ok(errs.some((e) => /\.text must be what the caption says/.test(e)));
+ assert.ok(errs.some((e) => /\.place must be one of below, above, side/.test(e)));
+ assert.ok(errs.some((e) => /\.hold must be 0.5–10 seconds/.test(e)));
+ assert.ok(validatePostFx(base({ fx: [cap({ text: "x".repeat(161) })] })).some((e) => /longer than 160 characters/.test(e)));
+});
+
+test("a caption is not a word zoom: wordZoomTimes gives it no time and no error", () => {
+ assert.deepEqual(wordZoomTimes(base({ fx: [cap()] })), [{ i: 0, kind: "caption" }]);
+});
+
+test("WHEN: at wins; un-narrated, the reading estimate (1 s + 3 words a second)", () => {
+ assert.deepEqual(captionTimes(base({ fx: [cap({ at: 2.25 })] })), [{ i: 0, t: 2.25, source: "at" }]);
+ // "Fudōshin." is the card's 14th word (index 13): 1 + 13/3.
+ assert.deepEqual(captionTimes(base({ fx: [cap()] })), [{ i: 0, t: 5.33, source: "estimate" }]);
+});
+
+test("WHEN: narrated with no word timings -- the read spread over its script by characters, on the item's clock", () => {
+ const e = base({ narration: { script: TEXT, takes: [take()], lead: 0.5, rate: 1.25 }, fx: [cap()] });
+ const [t] = captionTimes(e);
+ assert.equal(t.source, "estimate");
+ // 72 characters of 101 before it, over 10 ÷ 1.25 = 8 s, from 0.5.
+ const before = TEXT.indexOf("Fudōshin");
+ const n = TEXT.split(/\s+/).reduce((a, w) => a + w.length + 1, 0);
+ assert.equal(t.t, Math.round((0.5 + (before / n) * 8) * 1000) / 1000);
+ // Each card word has a time, in order.
+ const wt = cardWordTimes(e);
+ assert.equal(wt.times.length, TEXT.split(/\s+/).length);
+ for (let k = 1; k < wt.times.length; k += 1) assert.ok(wt.times[k] >= wt.times[k - 1]);
+});
+
+test("WHEN: narrated and timed -- the matched word's start in the take (lead + start ÷ rate)", () => {
+ const words = TEXT.split(" ").map((w, i) => ({ w, start: i * 0.5, end: i * 0.5 + 0.4 }));
+ const e = base({ narration: { script: TEXT, takes: [take({ words })], lead: 0.4, rate: 1.25 }, fx: [cap()] });
+ assert.deepEqual(captionTimes(e), [{ i: 0, t: 5.6, source: "words" }]);
+});
+
+test("the span: in over its lead, held from the word, out; it waits for a word zoom it would be up with; it ends by the item's end", () => {
+ const s = captionSpan(cap(), 4, {});
+ assert.deepEqual(s, { t0: 3.85, t1: 3.85 + CAPTION_IN, t2: 6.5, t3: 6.5 + CAPTION_OUT, at: 4, waited: null });
+ const w = captionSpan(cap(), 4, { zooms: [{ i: 0, t0: 3.5, t1: 4, t2: 5.2, t3: 5.6 }] });
+ assert.equal(w.t0, 5.6);
+ assert.equal(w.waited, 0);
+ assert.equal(Math.round((w.t2 - w.t0) * 100) / 100, 2.65);
+ const short = captionSpan(cap(), 4, { end: 5 });
+ assert.equal(short.t3, 5);
+ assert.match(captionSpan(cap(), 4.9, { end: 5 }).error, /at or after the item's 5 s/);
+ assert.equal(captionOpacityAt(s, 3.8), 0);
+ assert.equal(captionOpacityAt(s, 5), 1);
+ assert.ok(captionOpacityAt(s, 6.6) > 0 && captionOpacityAt(s, 6.6) < 1);
+ assert.equal(captionSlideAt(s, 3.85), 1);
+ assert.equal(captionSlideAt(s, 4.5), 0);
+});
+
+test("the plan: the words read while it is up are what it must not cover; two up at once are refused", () => {
+ const plan = captionPlan(base({ fx: [cap({ at: 2 })] }));
+ assert.equal(plan.length, 1);
+ assert.deepEqual([plan[0].scope, plan[0].from, plan[0].to], ["post", 13, 13]);
+ // Up 1.85–4.85 s (± 0.25), the words read at 1 s + 3 a second: words 2..12 -- never the phrase itself.
+ assert.deepEqual(plan[0].avoid, [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
+ assert.throws(() => captionPlan(base({ fx: [cap({ at: 2 }), cap({ at: 3, match: "amazing." })] })), /captions 1 and 2 are up at once/);
+});
+
+const overlapArea = (a, b) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
+/** A card of text: `rows` lines of words, `[{x, y, width, height}]`, from (x0, y0). */
+const textBlock = (x0, y0, rows, { words = 8, w = 70, h = 40, gapX = 14, lineH = 52 } = {}) =>
+ Array.from({ length: rows }, (_, r) => Array.from({ length: words }, (_, c) => ({ x: x0 + c * (w + gapX), y: y0 + r * lineH, width: w, height: h }))).flat();
+
+test("THE PLACE (operator, 4 Nov: \"a caption chip never covers ANY of the card's words\"): free space only -- below the text, off the card, or in a band -- never over a word, read or not", () => {
+ const card = { x: 40, y: 40, width: 760, height: 1000 };
+ const bounds = { x: 12, y: 12, width: 1896, height: 1056 };
+ const words = textBlock(80, 300, 8); // y 300..704: a block of text mid-card
+ const phrase = words[3 * 8 + 3];
+ const obstacles = words.filter((w) => w !== phrase);
+ const sizes = [{ width: 480, height: 70, max: 480 }, { width: 340, height: 100, max: 340 }];
+ const p = placeCaption({ word: phrase, sizes, bounds, card, column: { x: 80, y: 300, width: 680, height: 410 }, obstacles });
+ assert.equal(p.covers, 0);
+ for (const w of words) assert.equal(overlapArea(p, w), 0, `over a word at ${w.x},${w.y}`);
+ assert.equal(p.place, "card", "the card's own free space beats the frame's");
+ assert.ok(p.y >= 704 || p.y + p.height <= 300, "above or below the block, not inside it");
+ assert.ok(Array.isArray(p.leader) && p.leader.length >= 2, "a leader to the phrase");
+ // Its leader runs through free space: past the first leg (in the gap under the phrase's line), it crosses no word.
+ const legs = p.leader.slice(p.leader.length > 2 ? 1 : 0);
+ for (let k = 1; k < legs.length; k += 1) {
+ for (let q = 0; q <= 20; q += 1) {
+ const x = legs[k - 1][0] + ((legs[k][0] - legs[k - 1][0]) * q) / 20;
+ const y = legs[k - 1][1] + ((legs[k][1] - legs[k - 1][1]) * q) / 20;
+ for (const w of obstacles) assert.ok(!(x > w.x + 1 && x < w.x + w.width - 1 && y > w.y + 1 && y < w.y + w.height - 1), `leader through a word at ${x},${y}`);
+ }
+ }
+ // A card full of text: off the card, still over nothing (the attachment's box an obstacle too).
+ const full = textBlock(60, 60, 18, { words: 8 });
+ const media = { x: 840, y: 240, width: 1060, height: 600 };
+ const q = placeCaption({ word: full[5 * 8 + 2], sizes, bounds, card, obstacles: [...full.filter((_, i) => i !== 5 * 8 + 2), media] });
+ assert.equal(q.covers, 0);
+ assert.equal(q.place, "off-card");
+ for (const w of [...full, media]) assert.equal(overlapArea(q, w), 0);
+ // Below by default when both are free; above when asked.
+ const lone = { x: 300, y: 500, width: 100, height: 40 };
+ const b = placeCaption({ word: lone, sizes, bounds, card });
+ assert.ok(b.y >= 540);
+ const a = placeCaption({ word: lone, sizes, bounds, card, place: "above" });
+ assert.ok(a.y + a.height <= 500);
+});
+
+test("THE PLACE, at random: over a hundred cards of words, the chip never overlaps a word box when the frame has room", () => {
+ let seed = 7;
+ const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
+ for (let n = 0; n < 120; n += 1) {
+ const rows = 2 + Math.floor(rnd() * 12);
+ const words = textBlock(60 + rnd() * 40, 60 + rnd() * 300, rows, { words: 4 + Math.floor(rnd() * 5) });
+ const k = Math.floor(rnd() * words.length);
+ const p = placeCaption({ word: words[k], sizes: [{ width: 300 + rnd() * 300, height: 60 + rnd() * 50 }], bounds: { x: 0, y: 0, width: 1920, height: 1080 }, card: { x: 40, y: 40, width: 800, height: 1000 }, obstacles: words.filter((_, i) => i !== k) });
+ assert.equal(p.covers, 0, `card ${n}`);
+ for (const w of words) assert.equal(overlapArea(p, w), 0, `card ${n}: over a word`);
+ }
+});
+
+test("the chip's markup: the part before the dash bold, every character escaped, CJK kept", () => {
+ assert.equal(captionInnerHtml("不動心 · fudōshin — \"immovable mind\""), "<b>不動心 · fudōshin</b><span class=\"pcap-rest\"> — "immovable mind"</span>");
+ assert.equal(captionInnerHtml("<b>x</b>"), "<b>x</b>");
+});
diff --git a/umtool/report-to-video/post-clock.mjs b/umtool/report-to-video/post-clock.mjs
@@ -0,0 +1,331 @@
+// A POST ITEM's CLOCK (umtool/docs/report-video.md, "The clock"; operator, 4 Nov:
+// "show a clock advancing as we show the newest posts/replies chronologically
+// and quickly to convey how much he's posting in bursts" -- "the clock should
+// probably just be for mr obvious' replies and ignore the messages he's replying
+// to so it generally always goes forward unless there's a compelling reason to
+// go back at some point (e.g. 'you want to die' combo)").
+//
+// A small clock-and-date chip on the card: "4:10 AM ET · Wed 4 Nov", in the
+// operator's zone (America/New_York; render.posts.clock.zone). It shows the
+// ITEM's own post time (entry.date) -- never a parent's or a quote's, and it
+// does not move while they are read. Between two consecutive clock items, in
+// the first CLOCK_TICK seconds of the second it RUNS from the earlier time to
+// this one: the hands spin, the minutes roll, the date flips, the gap flashes
+// ("+38 min", "+2 h 14 min", "+3 d 4 h"). When this post is EARLIER than the
+// one before (a stinger that jumps back), it REWINDS: the hands spin backwards,
+// a "⟲ rewind" badge with the gap, the date flipping back -- deliberate, never a
+// glitch. `rewind: "off"` cuts straight to the time; `"on"` rewinds even
+// forward (or across no gap: a repeated post spins back a full turn to itself).
+//
+// render.posts.clock = { on?: true, zone?: "America/New_York" } // the cut's default
+// entry.fx = [{ kind: "clock", on?: false, rewind?: "auto" | "on" | "off" }] // one item's
+//
+// WHERE: the card's bottom-right corner (beside the counts row, never read
+// text), else its top-right; the first place over no word of the card. Drawn
+// OVER the card, never in it (no data-w, no data-post-block): readInViewErrors
+// never counts it, and it covers no read text.
+//
+// Pure but for the DOM functions (mountClock, measureClockPlace, setClockState),
+// SELF-CONTAINED: the build passes them to a page, Play calls them on its frame.
+
+import { mixHex, rgbaOf } from "./post-item.mjs";
+
+export const CLOCK_ZONE = "America/New_York";
+/** How long the clock runs from the earlier time to this one, seconds. */
+export const CLOCK_TICK = 0.8;
+/** The gap's badge stays this long after the run, then fades over CLOCK_FLASH_OUT. */
+export const CLOCK_FLASH_HOLD = 0.9;
+export const CLOCK_FLASH_OUT = 0.4;
+export const CLOCK_REWINDS = Object.freeze(["auto", "on", "off"]);
+const CLOCK_KEYS = new Set(["kind", "on", "rewind"]);
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+
+/** A zone Intl knows. */
+export function validZone(zone) {
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: String(zone) });
+ return typeof zone === "string" && zone.length > 0;
+ } catch {
+ return false;
+ }
+}
+
+/** Every reason a clock fx (entry `e`'s fx[i], named `fw`) cannot be built. word-zoom.mjs validatePostFx calls it. */
+export function clockErrors(e, fx, fw) {
+ const errors = [];
+ for (const k of Object.keys(fx)) if (!CLOCK_KEYS.has(k)) errors.push(`${fw}.${k} is not a clock key (${[...CLOCK_KEYS].join(", ")})`);
+ if (fx.on !== undefined && typeof fx.on !== "boolean") errors.push(`${fw}.on must be true or false`);
+ if (fx.rewind !== undefined && !CLOCK_REWINDS.includes(fx.rewind)) errors.push(`${fw}.rewind must be one of ${CLOCK_REWINDS.join(", ")}`);
+ if ((Array.isArray(e?.fx) ? e.fx : []).filter((f) => f?.kind === "clock").length > 1) errors.push(`${fw}: one clock per item`);
+ if (fx.on !== false && !Number.isFinite(Date.parse(String(e?.date ?? "")))) errors.push(`${fw}: the post has no date to show (its date)`);
+ return errors;
+}
+
+/** Every reason `render.posts.clock` is refused (post-redact.mjs validatePostsRender calls it). */
+export function validateClockRender(c) {
+ if (c === undefined) return [];
+ if (!isObj(c)) return ["render.posts.clock must be { on?, zone? }"];
+ const errors = [];
+ for (const k of Object.keys(c)) if (!["on", "zone"].includes(k)) errors.push(`render.posts.clock.${k} is not a clock knob (on, zone)`);
+ if (c.on !== undefined && typeof c.on !== "boolean") errors.push("render.posts.clock.on must be true or false");
+ if (c.zone !== undefined && !validZone(c.zone)) errors.push(`render.posts.clock.zone ${JSON.stringify(c.zone)} is not a time zone (an IANA name: America/New_York)`);
+ return errors;
+}
+
+/** The item's clock fx, or null. */
+const clockFxOf = (entry) => (Array.isArray(entry?.fx) ? entry.fx.find((f) => isObj(f) && f.kind === "clock") ?? null : null);
+
+/** Whether post item `entry` shows the clock: its own fx (on unless `on: false`), else the cut's `render.posts.clock.on`. */
+export function clockOn(entry, render) {
+ if (entry?.type !== undefined && entry.type !== "post") return false;
+ if (!Number.isFinite(Date.parse(String(entry?.date ?? "")))) return false;
+ const fx = clockFxOf(entry);
+ if (fx) return fx.on !== false;
+ return render?.posts?.clock?.on === true;
+}
+
+/** The cut's zone. */
+export const clockZoneOf = (render) => (validZone(render?.posts?.clock?.zone) ? render.posts.clock.zone : CLOCK_ZONE);
+
+/**
+ * THE CLOCK's PLAN for post item `entry`: `{ to, from, mode, zone, gap }` --
+ * `to` its post's time (ms), `from` the time the clock showed on the item
+ * before it when that one is a clock item too (else null: no run), `mode`
+ * "forward" | "rewind" | "none", `gap` to - from (ms). Null when it shows no clock.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {Record<string, any> | null} [prev]
+ * @returns {{ to: number, from: number | null, mode: "forward" | "rewind" | "none", zone: string, gap: number, forced: boolean } | null}
+ */
+export function clockPlan(entry, render = undefined, prev = null) {
+ if (!clockOn(entry, render)) return null;
+ const to = Date.parse(entry.date);
+ const zone = clockZoneOf(render);
+ const rewind = clockFxOf(entry)?.rewind ?? "auto";
+ const from = prev && clockOn(prev, render) ? Date.parse(prev.date) : null;
+ if (from === null || rewind === "off") return { to, from: null, mode: "none", zone, gap: 0, forced: false };
+ if (rewind === "on") return { to, from: from > to ? from : to + 12 * 3600e3, mode: "rewind", zone, gap: to - from, forced: from <= to };
+ if (from === to) return { to, from: null, mode: "none", zone, gap: 0, forced: false };
+ return { to, from, mode: from > to ? "rewind" : "forward", zone, gap: to - from, forced: false };
+}
+
+/** A gap as the badge says it: "+38 min", "+2 h 14 min", "+3 d 4 h", "+45 s" (its sign kept). */
+export function gapLabel(ms) {
+ const sign = ms < 0 ? "−" : "+";
+ let s = Math.round(Math.abs(ms) / 1000);
+ if (s < 60) return `${sign}${s} s`;
+ const d = Math.floor(s / 86400);
+ s -= d * 86400;
+ const h = Math.floor(s / 3600);
+ s -= h * 3600;
+ const m = Math.floor(s / 60);
+ if (d) return `${sign}${d} d${h ? ` ${h} h` : ""}`;
+ if (h) return `${sign}${h} h${m ? ` ${m} min` : ""}`;
+ return `${sign}${m} min`;
+}
+
+const fmtCache = new Map();
+const fmt = (zone, o) => {
+ const k = `${zone}|${JSON.stringify(o)}`;
+ if (!fmtCache.has(k)) fmtCache.set(k, new Intl.DateTimeFormat(o.locale ?? "en-US", { timeZone: zone, ...o, locale: undefined }));
+ return fmtCache.get(k);
+};
+
+/** A moment's face in a zone: `{ time: "4:10 AM", zone: "ET", date: "Wed 4 Nov", h, m }` (h 0–23, m 0–59.99 its local clock). */
+export function clockFace(ms, zone = CLOCK_ZONE) {
+ const d = new Date(ms);
+ const time = fmt(zone, { hour: "numeric", minute: "2-digit" }).format(d);
+ const zn = (fmt(zone, { timeZoneName: "shortGeneric", hour: "numeric" }).formatToParts(d).find((p) => p.type === "timeZoneName")?.value ?? "").replace(/^GMT$/, "UTC");
+ const date = fmt(zone, { locale: "en-GB", weekday: "short", day: "numeric", month: "short" }).format(d).replace(",", "");
+ const parts = Object.fromEntries(fmt(zone, { hourCycle: "h23", hour: "2-digit", minute: "2-digit", second: "2-digit" }).formatToParts(d).map((p) => [p.type, p.value]));
+ return { time, zone: zn, date, h: Number(parts.hour) % 24, m: Number(parts.minute) + Number(parts.second) / 60 };
+}
+
+const easeInOut = (x) => {
+ const v = Math.min(1, Math.max(0, x));
+ return v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2;
+};
+
+/**
+ * THE CLOCK AT item second `s`: what the chip shows -- `{ time, zone, date,
+ * hour, minute (hand angles, degrees), gap, gapOpacity, mode, running }`. The
+ * hands' angles run continuously from the earlier time (a rewind: backwards).
+ * @param {ReturnType<typeof clockPlan>} plan
+ * @param {number} s
+ */
+export function clockStateAt(plan, s) {
+ if (!plan) return null;
+ const run = plan.from === null || plan.mode === "none" ? 1 : easeInOut(s / CLOCK_TICK);
+ const shown = plan.from === null ? plan.to : plan.from + (plan.to - plan.from) * run;
+ const face = clockFace(shown, plan.zone);
+ // The hands from the minutes elapsed (continuous across days: the hour hand turns once per 12 h, the minute hand per hour).
+ const end = clockFace(plan.to, plan.zone);
+ const endMin = end.h * 60 + end.m;
+ const minutes = endMin + (shown - plan.to) / 60000;
+ const ga = plan.mode === "none" ? 0 : s < CLOCK_TICK + CLOCK_FLASH_HOLD ? Math.min(1, s / 0.15) : Math.max(0, 1 - (s - CLOCK_TICK - CLOCK_FLASH_HOLD) / CLOCK_FLASH_OUT);
+ return {
+ time: face.time,
+ zone: face.zone,
+ date: face.date,
+ hour: ((minutes / 2) % 360 + 360) % 360,
+ minute: ((minutes * 6) % 360 + 360) % 360,
+ // Unwrapped (the DOM rotates by these, so a run spins rather than snapping back across 0).
+ hourTurn: minutes / 2,
+ minuteTurn: minutes * 6,
+ gap: plan.mode === "rewind" ? `⟲ rewind${plan.forced ? "" : ` ${gapLabel(plan.gap)}`}` : plan.mode === "forward" ? gapLabel(plan.gap) : "",
+ gapOpacity: Math.round(ga * 1000) / 1000,
+ mode: plan.mode,
+ running: plan.mode !== "none" && s < CLOCK_TICK,
+ };
+}
+
+/** The item seconds whose frames differ (the run and the badge's fade), at `fps`: `[0, 1/fps, …]` up to the last change. */
+export function clockFrameTimes(plan, fps = 30) {
+ if (!plan || plan.mode === "none") return [0];
+ const end = CLOCK_TICK + CLOCK_FLASH_HOLD + CLOCK_FLASH_OUT;
+ const out = [];
+ for (let f = 0; f / fps <= end + 1e-9; f += 1) out.push(f / fps);
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// THE LOOK, and the DOM (self-contained).
+// ---------------------------------------------------------------------------
+
+/** The chip's CSS for a page `height` px tall, in the card's palette. */
+export function clockCss({ height = 1080, palette = {} } = {}) {
+ const k = height / 1080;
+ const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette };
+ const panel = mixHex(pal.bg, pal.fg, 0.08);
+ const px = (v) => `${Math.round(v * k)}px`;
+ return `
+[data-post-clock-layer] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 61; }
+.pclock { position: absolute; left: 0; top: 0; display: flex; align-items: center; gap: ${px(12)}; padding: ${px(7)} ${px(16)} ${px(7)} ${px(9)};
+ background: ${panel}; color: ${pal.fg}; border: ${Math.max(1, Math.round(1.5 * k))}px solid ${rgbaOf(pal.fg, 0.18)}; border-radius: ${px(999)};
+ box-shadow: 0 ${px(4)} ${px(16)} ${rgbaOf("#000000", 0.4)}; font-family: 'PostSans', 'Noto Sans CJK JP', sans-serif; white-space: nowrap; font-synthesis: none; }
+.pclock-face { width: ${px(44)}; height: ${px(44)}; flex: none; }
+.pclock-face circle { fill: ${rgbaOf(pal.bg, 0.6)}; stroke: ${pal.accent}; stroke-width: 2.4; }
+.pclock-face .tk { stroke: ${rgbaOf(pal.fg, 0.45)}; stroke-width: 1.6; }
+.pclock-face .hh { stroke: ${pal.fg}; stroke-width: 3.2; stroke-linecap: round; }
+.pclock-face .mh { stroke: ${pal.accent}; stroke-width: 2.2; stroke-linecap: round; }
+.pclock-txt { display: flex; flex-direction: column; line-height: 1.12; }
+.pclock-time { font-family: 'PostSansBold', 'Noto Sans CJK JP', sans-serif; font-size: ${px(26)}; font-variant-numeric: tabular-nums; }
+.pclock-zone { font-family: 'PostSans', sans-serif; color: ${pal.muted}; font-size: ${px(18)}; margin-left: ${px(5)}; }
+.pclock-date { color: ${mixHex(pal.fg, pal.muted, 0.4)}; font-size: ${px(18)}; letter-spacing: 0.02em; }
+.pclock-gap { position: absolute; right: calc(100% + ${px(10)}); top: 50%; transform: translateY(-50%); padding: ${px(4)} ${px(12)}; border-radius: ${px(999)};
+ font-family: 'PostSansBold', sans-serif; font-size: ${px(22)}; background: ${pal.accent}; color: ${pal.bg}; opacity: 0; font-variant-numeric: tabular-nums; }
+.pclock[data-mode="rewind"] .pclock-gap { background: ${pal.fg}; color: ${pal.bg}; }
+.pclock[data-mode="rewind"][data-running="1"] .pclock-face circle { stroke: ${pal.fg}; stroke-dasharray: 4 3; }
+.pclock[data-running="1"] .pclock-date { color: ${pal.accent}; }
+`;
+}
+
+/** The chip's HTML (its face with 12 ticks; the text filled by setClockState). */
+export function clockHtml() {
+ const ticks = Array.from({ length: 12 }, (_, i) => {
+ const a = (i * Math.PI) / 6;
+ const r0 = i % 3 ? 15 : 13;
+ return `<line class="tk" x1="${(22 + r0 * Math.sin(a)).toFixed(2)}" y1="${(22 - r0 * Math.cos(a)).toFixed(2)}" x2="${(22 + 17.5 * Math.sin(a)).toFixed(2)}" y2="${(22 - 17.5 * Math.cos(a)).toFixed(2)}"/>`;
+ }).join("");
+ return `<span class="pclock-gap" data-clock-gap=""></span><svg class="pclock-face" viewBox="0 0 44 44"><circle cx="22" cy="22" r="19.5"/>${ticks}<line class="hh" data-clock-hh="" x1="22" y1="22" x2="22" y2="12"/><line class="mh" data-clock-mh="" x1="22" y1="22" x2="22" y2="6.5"/></svg><span class="pclock-txt"><span class="pclock-time"><span data-clock-time="">0:00 AM</span><span class="pclock-zone" data-clock-zone="">ET</span></span><span class="pclock-date" data-clock-date="">Mon 1 Jan</span></span>`;
+}
+
+/**
+ * Mount the clock over the card page (`{ css, html, widest }`: `widest` a state
+ * to lay it out at its widest), hidden. Returns its size `{ width, height }`.
+ * @param {{ css: string, html: string, widest?: Record<string, any> | null } | null} arg
+ * @param {Document} [doc]
+ */
+export function mountClock(arg, doc = document) {
+ doc.querySelectorAll("[data-post-clock-layer], style[data-post-clock-css]").forEach((el) => el.remove());
+ if (!arg || !arg.html) return null;
+ const style = doc.createElement("style");
+ style.setAttribute("data-post-clock-css", "");
+ style.textContent = arg.css || "";
+ doc.head.appendChild(style);
+ const layer = doc.createElement("div");
+ layer.setAttribute("data-post-clock-layer", "");
+ const el = doc.createElement("div");
+ el.className = "pclock";
+ el.setAttribute("data-post-clock", "");
+ el.style.opacity = "0";
+ el.innerHTML = arg.html;
+ layer.appendChild(el);
+ doc.body.appendChild(layer);
+ const w = arg.widest || {};
+ const set = (sel, v) => {
+ const n = el.querySelector(sel);
+ if (n && v !== undefined) n.textContent = v;
+ };
+ set("[data-clock-time]", w.time);
+ set("[data-clock-zone]", w.zone);
+ set("[data-clock-date]", w.date);
+ const b = el.getBoundingClientRect();
+ // Its width held at the widest (a running time never resizes it).
+ el.style.minWidth = `${Math.ceil(b.width)}px`;
+ return { width: Math.ceil(b.width), height: Math.ceil(b.height) };
+}
+
+/**
+ * Where the clock goes on the card as drawn: the bottom-right corner (beside
+ * the counts row), else the top-right, the first over no word of the card
+ * (`[data-w]`); `{ x, y, place, covers, tries }`. `size` its box, `inset` from
+ * the card's edge; `fixed`: the places to judge (an earlier call's `tries`),
+ * only counted here -- the build places it once and judges it over the read.
+ * @param {{ size: { width: number, height: number }, inset: number, fixed?: Array<{ x: number, y: number, place: string }> | null }} arg
+ * @param {Document} [doc]
+ */
+export function measureClockPlace(arg, doc = document) {
+ const card = doc.querySelector("[data-post-card]");
+ if (!card || !arg || !arg.size) return null;
+ const c = card.getBoundingClientRect();
+ const words = Array.from(doc.querySelectorAll("[data-w]")).flatMap((el) => Array.from(el.getClientRects())).filter((r) => r.width > 0);
+ const hit = (r) => words.filter((w) => Math.min(r.x + r.width, w.right) - Math.max(r.x, w.left) > 1 && Math.min(r.y + r.height, w.bottom) - Math.max(r.y, w.top) > 1).length;
+ // Its own post's counts row (a threaded card draws one per tile: the post's tile, else the last).
+ const all = Array.from(card.querySelectorAll(".counts"));
+ const counts = card.querySelector('[data-thread-tile="post"] .counts') || all[all.length - 1] || null;
+ const cb = counts ? counts.getBoundingClientRect() : null;
+ const x = Math.round(c.right - arg.inset - arg.size.width);
+ // Bottom: centred on the counts row when there is one, else in the card's foot.
+ const yb = cb && cb.height > 0 ? Math.round(cb.top + (cb.height - arg.size.height) / 2 + 4) : Math.round(c.bottom - arg.inset - arg.size.height);
+ const tries = (arg.fixed || [
+ { x, y: Math.min(yb, Math.round(c.bottom - arg.size.height - 4)), place: "bottom-right" },
+ { x, y: Math.round(c.top + arg.inset), place: "top-right" },
+ ]).map((t) => ({ ...t, covers: hit({ x: t.x - arg.size.width * 0.6, y: t.y, width: arg.size.width * 1.6, height: arg.size.height }) }));
+ const best = tries.find((t) => !t.covers) || tries.slice().sort((a, b) => a.covers - b.covers)[0];
+ return { ...best, tries };
+}
+
+/**
+ * Set the clock: `{ x, y, opacity, st }` (`st` clockStateAt's), or null to hide.
+ * @param {{ x: number, y: number, opacity?: number, st: Record<string, any> } | null} arg
+ * @param {Document} [doc]
+ */
+export function setClockState(arg, doc = document) {
+ const el = doc.querySelector("[data-post-clock]");
+ if (!el) return;
+ if (!arg || !arg.st) {
+ el.style.opacity = "0";
+ return;
+ }
+ const st = arg.st;
+ el.style.transform = `translate(${Math.round(arg.x)}px, ${Math.round(arg.y)}px)`;
+ el.style.opacity = String(arg.opacity === undefined ? 1 : arg.opacity);
+ el.setAttribute("data-mode", st.mode);
+ el.setAttribute("data-running", st.running ? "1" : "0");
+ const set = (sel, v) => {
+ const n = el.querySelector(sel);
+ if (n && n.textContent !== v) n.textContent = v;
+ };
+ set("[data-clock-time]", st.time);
+ set("[data-clock-zone]", st.zone);
+ set("[data-clock-date]", st.date);
+ set("[data-clock-gap]", st.gap);
+ const gap = el.querySelector("[data-clock-gap]");
+ if (gap) gap.style.opacity = st.gap ? String(st.gapOpacity) : "0";
+ const hh = el.querySelector("[data-clock-hh]");
+ const mh = el.querySelector("[data-clock-mh]");
+ if (hh) hh.setAttribute("transform", `rotate(${st.hourTurn.toFixed(2)} 22 22)`);
+ if (mh) mh.setAttribute("transform", `rotate(${st.minuteTurn.toFixed(2)} 22 22)`);
+}
diff --git a/umtool/report-to-video/post-clock.test.mjs b/umtool/report-to-video/post-clock.test.mjs
@@ -0,0 +1,132 @@
+// A post item's CLOCK (post-clock.mjs) and the PACE knob (post-narration.mjs
+// POST_PACES): which items show it, its plan from the item before (forward,
+// rewind, none), its face in the zone, the run's states, the validation.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { CLOCK_TICK, clockFace, clockFrameTimes, clockOn, clockPlan, clockStateAt, gapLabel, validateClockRender } from "./post-clock.mjs";
+import { validatePostFx } from "./word-zoom.mjs";
+import { narrationSchedule, postNarrationKnobs, validatePostNarration } from "./post-narration.mjs";
+import { validatePostsRender } from "./post-redact.mjs";
+
+const post = (id, date, o = {}) => ({ type: "post", id, post: `s/${id}`, platform: "x", author: "S", handle: "s", date, text: "do you want to die?", ...o });
+const CLK = { fx: [{ kind: "clock" }] };
+
+test("which items show it: an item's own clock fx, else the cut's render.posts.clock.on; never one without a date", () => {
+ assert.equal(clockOn(post("a", "2026-11-02T22:15:00Z"), {}), false);
+ assert.equal(clockOn(post("a", "2026-11-02T22:15:00Z", CLK), {}), true);
+ assert.equal(clockOn(post("a", "2026-11-02T22:15:00Z"), { posts: { clock: { on: true } } }), true);
+ assert.equal(clockOn(post("a", "2026-11-02T22:15:00Z", { fx: [{ kind: "clock", on: false }] }), { posts: { clock: { on: true } } }), false);
+ assert.equal(clockOn(post("a", "", CLK), {}), false);
+});
+
+test("its face: the post's time in the operator's zone (ET), the date as a day", () => {
+ assert.deepEqual(
+ (({ time, zone, date }) => ({ time, zone, date }))(clockFace(Date.parse("2026-11-04T09:10:00Z"))),
+ { time: "4:10 AM", zone: "ET", date: "Wed 4 Nov" },
+ );
+ assert.equal(clockFace(Date.parse("2026-11-04T09:10:00Z"), "Europe/London").time, "9:10 AM");
+});
+
+test("the plan: forward from the clock item before, a rewind when this one is earlier, none after a non-clock item", () => {
+ const a = post("a", "2026-11-02T22:15:00Z", CLK);
+ const b = post("b", "2026-11-02T22:15:39Z", CLK);
+ const fwd = clockPlan(b, {}, a);
+ assert.equal(fwd.mode, "forward");
+ assert.equal(fwd.gap, 39000);
+ const back = clockPlan(post("c", "2026-11-02T10:10:07Z", CLK), {}, b);
+ assert.equal(back.mode, "rewind");
+ assert.equal(clockPlan(b, {}, post("x", "2026-11-02T20:00:00Z")).mode, "none");
+ assert.equal(clockPlan(b, {}, null).mode, "none");
+ // Forced and suppressed.
+ assert.equal(clockPlan(post("c", "2026-11-02T10:10:07Z", { fx: [{ kind: "clock", rewind: "off" }] }), {}, b).mode, "none");
+ const forced = clockPlan(post("d", "2026-11-02T23:00:00Z", { fx: [{ kind: "clock", rewind: "on" }] }), {}, b);
+ assert.equal(forced.mode, "rewind");
+ assert.equal(forced.forced, true);
+ assert.ok(forced.from > forced.to);
+ // A repeat of the same post (the same time): nothing to run.
+ assert.equal(clockPlan(post("e", "2026-11-02T22:15:39Z", CLK), {}, b).mode, "none");
+ assert.equal(clockPlan(post("f", "2026-11-02T22:15:39Z"), {}, b), null);
+});
+
+test("the run: from the earlier time to this one over CLOCK_TICK, the gap flashing; a rewind spins the hands backwards", () => {
+ const a = post("a", "2026-11-02T13:30:00Z", CLK);
+ const b = post("b", "2026-11-02T14:08:00Z", CLK);
+ const p = clockPlan(b, {}, a);
+ const s0 = clockStateAt(p, 0);
+ const s1 = clockStateAt(p, CLOCK_TICK);
+ assert.equal(s0.time, "8:30 AM");
+ assert.equal(s1.time, "9:08 AM");
+ assert.equal(s0.gap, "+38 min");
+ assert.ok(s0.running && !s1.running);
+ assert.ok(s1.minuteTurn > s0.minuteTurn);
+ assert.equal(clockStateAt(p, 3).gapOpacity, 0);
+ const r = clockPlan(post("c", "2026-10-30T13:00:00Z", CLK), {}, b);
+ const r0 = clockStateAt(r, 0);
+ const r1 = clockStateAt(r, CLOCK_TICK);
+ assert.ok(r1.minuteTurn < r0.minuteTurn, "the hands run backwards");
+ assert.match(r0.gap, /^⟲ rewind −3 d 1 h/);
+ assert.equal(r0.date, "Mon 2 Nov");
+ assert.equal(r1.date, "Fri 30 Oct");
+ assert.equal(clockFrameTimes(clockPlan(b, {}, null)).length, 1);
+ assert.ok(clockFrameTimes(p, 30).length > 50);
+});
+
+test("gap labels", () => {
+ assert.equal(gapLabel(39000), "+39 s");
+ assert.equal(gapLabel(38 * 60000), "+38 min");
+ assert.equal(gapLabel((2 * 60 + 14) * 60000), "+2 h 14 min");
+ assert.equal(gapLabel(-(3 * 86400 + 4 * 3600) * 1000), "−3 d 4 h");
+});
+
+test("validation: the item's clock fx and the cut's render.posts.clock", () => {
+ assert.deepEqual(validatePostFx(post("a", "2026-11-02T22:15:00Z", { fx: [{ kind: "clock", rewind: "auto" }] })), []);
+ assert.match(validatePostFx(post("a", "2026-11-02T22:15:00Z", { fx: [{ kind: "clock", rewind: "back" }] })).join(), /rewind must be one of auto, on, off/);
+ assert.match(validatePostFx(post("a", "2026-11-02T22:15:00Z", { fx: [{ kind: "clock" }, { kind: "clock" }] })).join(), /one clock per item/);
+ assert.deepEqual(validateClockRender({ on: true, zone: "America/New_York" }), []);
+ assert.match(validatePostsRender({ posts: { clock: { zone: "Mars/Olympus" } } }).join(), /is not a time zone/);
+});
+
+test("THE PACE: fast plays a post back to back -- its gap knobs, unless it sets one; the cut's pace too; normal is the cut's", () => {
+ const take = { file: "n/t.wav", engine: "orpheus", voice: "zac", seconds: 5, script: "x" };
+ const e = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take], pace: "fast" } });
+ const k = postNarrationKnobs(e, {});
+ assert.deepEqual([k.lead, k.tail, k.ramp, k.linger], [0.1, 0.15, 0.3, 0.45]);
+ assert.equal(narrationSchedule(e, {}).at, 0.1);
+ const own = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take], pace: "fast", linger: 1 } });
+ assert.equal(postNarrationKnobs(own, {}).linger, 1);
+ const cut = { postNarration: { pace: "fast" } };
+ const plain = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take] } });
+ assert.equal(postNarrationKnobs(plain, cut).linger, 0.45);
+ const normal = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take], pace: "normal" } });
+ assert.equal(postNarrationKnobs(normal, cut).linger, 1.8);
+ assert.match(validatePostNarration(post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", pace: "slow" } })).join(), /pace must be fast or normal/);
+});
+
+test("THE SEGMENT KEY (post-render.mjs postFxKeyFields): nothing for a plain item (its old key, its segment reused); the caption, the clock (the time it runs from, the rewind, the zone) and the pace each change it", async () => {
+ const { postFxKeyFields } = await import("./post-render.mjs");
+ const take = { file: "n/t.wav", engine: "orpheus", voice: "zac", seconds: 5, script: "x" };
+ const plain = post("a", "2026-11-02T22:15:00Z", { narration: { script: "x", takes: [take] } });
+ assert.deepEqual(postFxKeyFields(plain, {}, post("z", "2026-11-02T22:00:00Z")), {});
+ assert.deepEqual(postFxKeyFields(plain, { postNarration: { rate: 1.08 } }, null), {});
+ // A caption: its drawing's version (the entry, in the key, carries its text and knobs).
+ assert.deepEqual(postFxKeyFields({ ...plain, fx: [{ kind: "caption", match: "x", text: "y" }] }, {}), { captionV: 2 });
+ // The clock: from the item before -- its time, its being a clock item, the zone, the rewind.
+ const clk = { ...plain, fx: [{ kind: "clock" }] };
+ const before = post("z", "2026-11-02T22:00:00Z", CLK);
+ const k1 = JSON.stringify(postFxKeyFields(clk, {}, before));
+ assert.match(k1, /"clockV":1/);
+ assert.notEqual(JSON.stringify(postFxKeyFields(clk, {}, { ...before, date: "2026-11-02T21:00:00Z" })), k1);
+ assert.notEqual(JSON.stringify(postFxKeyFields(clk, {}, { ...before, fx: [] })), k1);
+ assert.notEqual(JSON.stringify(postFxKeyFields(clk, { posts: { clock: { zone: "Europe/London" } } }, before)), k1);
+ assert.notEqual(JSON.stringify(postFxKeyFields({ ...clk, fx: [{ kind: "clock", rewind: "on" }] }, {}, before)), k1);
+ // The cut's clock on: every dated item keys its clock.
+ assert.ok(postFxKeyFields(plain, { posts: { clock: { on: true } } }, null).clock);
+ // The pace: the item's, or the cut's (which the entry does not carry).
+ assert.deepEqual(postFxKeyFields(plain, { postNarration: { pace: "fast" } }).pace, { pace: "fast", lead: 0.1, tail: 0.15, ramp: 0.3, linger: 0.45 });
+ assert.equal(postFxKeyFields({ ...plain, narration: { ...plain.narration, pace: "fast", linger: 1 } }, {}).pace.linger, 1);
+});
+
+test("a take --from another carries a post item's record (its key) and combo files with its segment, so a matching item is reused", async () => {
+ const { SEGMENT_FILE_SUFFIXES } = await import("./build-video.mjs");
+ for (const s of [".mp4", ".post.json", ".combo.json", ".plain.mp4"]) assert.ok(SEGMENT_FILE_SUFFIXES.includes(s), s);
+});
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -134,6 +134,8 @@ export const POST_NARRATION_DEFAULTS = Object.freeze({
rate: 1,
engine: "orpheus",
voice: "zac",
+ // The pace (POST_PACES): normal is the cut's gaps; fast plays each post back to back.
+ pace: "normal",
});
export const POST_NARRATION_LIMITS = Object.freeze({
@@ -164,7 +166,15 @@ export const POST_NARRATION_LIMIT = 0.95;
export const POST_NARRATION_CLIP = Object.freeze(["read", "full"]);
-const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate"];
+/**
+ * THE PACE (operator, 4 Nov: a burst "chronologically and quickly"): `pace:
+ * "fast"` on one post (or the cut) plays it back to back -- the read starts at
+ * once and the item ends just after the words. Its gap knobs, unless the post
+ * sets one itself (its own lead/linger always win); "normal" is the cut's.
+ */
+export const POST_PACES = Object.freeze({ fast: Object.freeze({ lead: 0.1, tail: 0.15, ramp: 0.3, linger: 0.45 }), normal: Object.freeze({}) });
+
+const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace"];
// `attach` is one post's (it decides the card's layout, which is drawn from the entry alone).
// `follow`: the cut's read-follow (read-follow.mjs) -- { on, dim, ease } -- kept here with the mix it rides on.
// `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim.
@@ -195,6 +205,9 @@ export function postNarrationKnobs(entry, render) {
const n = isObj(entry?.narration) ? entry.narration : {};
const out = { ...base, attach: POST_NARRATION_DEFAULTS.attach };
for (const k of [...MIX_KEYS, "engine", "voice"]) if (n[k] !== undefined && n[k] !== null) out[k] = n[k];
+ // Its pace (POST_PACES): the post's, else the cut's -- its gap knobs, unless the post sets one itself.
+ const pace = POST_PACES[out.pace] ? out.pace : "normal";
+ for (const [k, v] of Object.entries(POST_PACES[pace])) if (n[k] === undefined || n[k] === null) out[k] = v;
return out;
}
@@ -546,6 +559,7 @@ function mixErrors(o, where) {
if (o[k] !== undefined && !numIn(o[k], POST_NARRATION_LIMITS[k])) errors.push(`${where}.${k} must be ${POST_NARRATION_LIMITS[k][0]}–${POST_NARRATION_LIMITS[k][1]}`);
}
if (o.duck !== undefined && typeof o.duck !== "boolean") errors.push(`${where}.duck must be true or false`);
+ if (o.pace !== undefined && !Object.keys(POST_PACES).includes(o.pace)) errors.push(`${where}.pace must be ${Object.keys(POST_PACES).join(" or ")}`);
if (o.clip !== undefined && !POST_NARRATION_CLIP.includes(o.clip)) errors.push(`${where}.clip must be ${POST_NARRATION_CLIP.join(" or ")}`);
if (o.short !== undefined && !POST_NARRATION_SHORT.includes(o.short)) errors.push(`${where}.short must be ${POST_NARRATION_SHORT.join(" or ")}`);
if (o.attach !== undefined && !POST_NARRATION_ATTACH.includes(o.attach)) errors.push(`${where}.attach must be ${POST_NARRATION_ATTACH.join(" or ")}`);
diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs
@@ -30,6 +30,7 @@
// PURE (the build, the route, Play and the writers).
import { censorMarkupErrors } from "./post-censor.mjs";
import { BLACKOUT_MARK, SLUR_CSS, decodePlaceholder, hasSlurMarks, maskSlurs, placeholdersHtml, sayFor, slurMatches, slursOn, validateSlursRender } from "./post-slurs.mjs";
+import { validateClockRender } from "./post-clock.mjs";
/** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */
export const REDACT_MARK = "";
@@ -188,7 +189,8 @@ export function validatePostsRender(render) {
const p = render?.posts;
if (p === undefined) return [];
if (!isObj(p)) return ["render.posts must be an object ({redact, slurs})"];
- return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs)];
+ // Its clock (post-clock.mjs): the cut's default and zone.
+ return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs), ...validateClockRender(p.clock)];
}
/** Every reason a channel's posts-markup.json is refused. */
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -19,12 +19,14 @@ 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, cardAuthors, fxRedactionErrors, mediaTimeAt, panelEntry, postCardHtml, postItemPlan, postLayout, stepAt, stepBoxes } from "./post-item.mjs";
-import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, rootTakeOf } from "./post-narration.mjs";
+import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, postNarrationKnobs, rootTakeOf } from "./post-narration.mjs";
import { applyFollowState, followPath, followRuns, followStateAt, isDrawnState, measureFollow, readInViewErrors, shotStateAt } from "./read-follow.mjs";
import { redactEntry, redactionOn, shownLine, termsFor } from "./post-redact.mjs";
import { bleepFilters, slursOn, takeBleeps } from "./post-slurs.mjs";
import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs";
import { sceneEntry } from "./post-media-scene.mjs";
+import { CAPTION_OUT, CAPTION_SLIDE, captionCss, captionInnerHtml, captionPlan, measureCaptionWords, mountCaptions, placeCaption, setCaptionState, slideDir } from "./post-caption.mjs";
+import { clockCss, clockFace, clockFrameTimes, clockHtml, clockPlan, clockStateAt, measureClockPlace, mountClock, setClockState } from "./post-clock.mjs";
import { panelReadErrors } from "./post-thread.mjs";
import { applyJoinState, endMediaOf } from "./post-join.mjs";
import { applyVisitState } from "./post-link-visit.mjs";
@@ -85,7 +87,7 @@ export function scrollExpr(keys) {
*
* @returns {string[]}
*/
-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 }) {
+export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, panelFiles = [], join = null, map = null, captionFx = [], clock = null }) {
const fps = render.fps ?? 30;
const T = plan.total;
const inputs = [];
@@ -141,6 +143,39 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
parts.push(`[${cur}][wz${zi}]overlay=x=${region.x}:y=${region.y}:eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`);
cur = next;
});
+ // CAPTIONS (post-caption.mjs): each chip shot alone on a clear page, laid over the card while it is up -- fading
+ // and sliding in toward its phrase, the underline fading under the words, both tracking the words as the card
+ // pans -- after the zooms (a caption waits for one to be out), before the attachments (it stays on the card).
+ captionFx.forEach((c, ci) => {
+ const { span } = c;
+ const D = Math.max(1 / fps, span.t3 - span.t0);
+ // Static: a pan that moves its phrase ends it first (shootCaptions), so nothing rides over words.
+ const track = (axis) => trackExpr(c.track ?? [], axis);
+ const layer = (shot, label, slide) => {
+ const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", shot.file]);
+ parts.push(
+ `[${k}:v]format=rgba,fade=t=in:st=0:d=${num(Math.max(0.04, span.t1 - span.t0))}:alpha=1,` +
+ `fade=t=out:st=${num(span.t2 - span.t0)}:d=${num(Math.max(0.04, span.t3 - span.t2))}:alpha=1,setpts=PTS-STARTPTS+${num(span.t0)}/TB[${label}]`,
+ );
+ const left = span.t1 > span.t0 ? `pow(1-clip((t-${num(span.t0)})/${num(span.t1 - span.t0)},0,1),3)` : "0";
+ const sx = slide && slide.x ? `+${num(slide.x)}*${left}` : "";
+ const sy = slide && slide.y ? `+${num(slide.y)}*${left}` : "";
+ const next = `b${++n}`;
+ parts.push(`[${cur}][${label}]overlay=x='${shot.x}${track("dx")}${sx}':y='${shot.y}${track("dy")}${sy}':eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`);
+ cur = next;
+ };
+ if (c.mark) layer(c.mark, `cpm${ci}`, null);
+ layer(c.chip, `cpc${ci}`, c.slide);
+ });
+ // THE CLOCK (post-clock.mjs): its frames shot alone -- the run from the item before's time, then held -- laid
+ // over the card's corner from the first frame (a stack card's: until its media phase).
+ if (clock) {
+ const ci = add(["-f", "concat", "-safe", "0", "-i", clock.list]);
+ parts.push(`[${ci}:v]fps=${fps},format=rgba,setsar=1,setpts=PTS-STARTPTS[clk]`);
+ const next = `b${++n}`;
+ parts.push(`[${cur}][clk]overlay=x=${clock.x}:y=${clock.y}:eof_action=repeat${clock.until < T ? `:enable='lt(t,${num(clock.until)})'` : ""}[${next}]`);
+ cur = next;
+ }
const audio = [];
const picture = (st) => !!st && (st.kind === "image" || st.kind === "grid" || st.kind === "gif");
plan.steps.forEach((step, si) => {
@@ -300,6 +335,21 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
];
}
+/**
+ * A caption's track (`[{ t, dx, dy }]`: how far its phrase has moved from where
+ * it was placed, from item second t) as an ffmpeg term of `t` to add to its
+ * x or y ("" when it never moves).
+ */
+export function trackExpr(track, axis) {
+ const steps = [];
+ for (const p of track) if (!steps.length ? p[axis] !== 0 : p[axis] !== steps[steps.length - 1].v) steps.push({ t: p.t, v: p[axis] });
+ if (!steps.length) return "";
+ // Nested from the last change back: before each change, what held until it.
+ let e = String(steps[steps.length - 1].v);
+ for (let k = steps.length - 1; k >= 0; k -= 1) e = `if(lt(t,${num(steps[k].t)}),${k ? steps[k - 1].v : 0},${e})`;
+ return `+(${e})`;
+}
+
async function loadChromium() {
let mod;
try {
@@ -317,7 +367,7 @@ async function loadChromium() {
* stack layout. The page is a file beside them, so its faces and the parent
* shot load from disk (an about:blank page may not read file: urls).
*/
-export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, joinFrom = null }) {
+export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, joinFrom = null, captions = [], clock = null, obstacles = [] }) {
await mkdir(dir, { recursive: true });
const fonts = {
regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
@@ -413,6 +463,9 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
}
await ctx.close();
if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow });
+ if (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total });
+ // A caption covers none of the attachments (`obstacles`: their boxes) nor the clock.
+ if (captions.length) out.captions = await shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction, follow, obstacles: [...obstacles, ...(out.clock ? [out.clock.box] : [])] });
} finally {
await browser.close();
}
@@ -614,17 +667,193 @@ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotU
}
/**
+ * Each CAPTION's shots and place (post-caption.mjs): on the card page as it is
+ * drawn when the caption is fully in (read-follow's state at its t1), the
+ * phrase measured -- refused when it is cut off the card -- and the words read
+ * while it is up; the chip placed by them (placeCaption: never covering one),
+ * then shot alone on a clear page (the chip with its notch; the underline
+ * apart, as it does not slide). Following, the phrase is measured frame by
+ * frame over the caption's span: its `track`, which the chip rides.
+ * `captions`: captionPlan's. Returns `[{ ...caption, chip, mark, slide, track, placed }]`.
+ */
+export async function shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction = null, follow = null, obstacles: fixed = [] }) {
+ const fps = render.fps ?? 30;
+ const k = box.height / 1080;
+ const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" });
+ const page = await ctx.newPage();
+ const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href]));
+ const out = [];
+ try {
+ const file = path.join(dir, "caption.html");
+ await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null }), "utf8");
+ await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
+ await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
+ await page.evaluate(() => document.fonts.ready.then(() => true));
+ const sizes = await page.evaluate(mountCaptions, { css: captionCss({ height: box.height, palette: render.palette }), chips: captions.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k });
+ await page.evaluate(() => document.fonts.ready.then(() => true));
+ const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null;
+ const stateAt = async (s) => {
+ if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s));
+ };
+ const inset = Math.round(12 * k);
+ const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset };
+ for (const c0 of captions) {
+ let c = c0;
+ // A pan moving the phrase while it is up: the caption is gone before it moves (the chip never rides over words).
+ if (follow) {
+ let base = null;
+ for (let f = Math.floor(c.span.t0 * fps); f <= Math.ceil(c.span.t3 * fps); f += 1) {
+ await stateAt(f / fps);
+ const g = await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: [] });
+ if (g.error) continue;
+ base ??= g.word;
+ if (Math.abs(g.word.y - base.y) > 1 || Math.abs(g.word.x - base.x) > 1) {
+ const tm = r3(f / fps);
+ if (tm > c.span.t1 + 0.2) c = { ...c, span: { ...c.span, t2: r3(Math.max(c.span.t1, tm - CAPTION_OUT)), t3: tm }, cutByPan: tm };
+ break;
+ }
+ }
+ }
+ // Its place: judged where the card is as it comes in, while it is up and as it goes (a pan's other words too).
+ const looks = [];
+ for (const s of follow ? [c.span.t1, c.span.t0, c.span.t3 - 0.01] : [c.span.t1]) {
+ await stateAt(s);
+ looks.push(await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: c.avoid }));
+ }
+ await stateAt(c.span.t1);
+ const geo = looks[0];
+ if (geo.error) throw new Error(`${entry.id}: caption ${c.i + 1}: the phrase is ${geo.error}`);
+ const obstacles = [...fixed, ...looks.flatMap((l) => l.obstacles ?? [])];
+ const size = sizes.find((x) => x.i === c.i);
+ const placed = placeCaption({ word: geo.word, sizes: size.sizes, bounds, card: geo.card, column: geo.column, place: c.place, obstacles, gap: Math.round(10 * k) });
+ if (!placed) throw new Error(`${entry.id}: caption ${c.i + 1}: the chip fits nowhere in the frame`);
+ // Shot alone: the card hidden, the page clear.
+ await page.evaluate(() => {
+ const st = document.createElement("style");
+ st.setAttribute("data-pcap-solo", "");
+ st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-fx-captions]) { visibility: hidden !important; }";
+ document.head.appendChild(st);
+ });
+ const pad = Math.round(40 * k);
+ const clipOf = (r) => {
+ const x = Math.max(0, Math.floor(r.x - pad));
+ const y = Math.max(0, Math.floor(r.y - pad));
+ return { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width + pad) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height + pad) - y) };
+ };
+ const state = { i: c.i, x: placed.x, y: placed.y, max: placed.max, opacity: 1, marks: geo.lines, mark: 1, leader: placed.leader };
+ const stroke = Math.max(2, Math.round(2.4 * k));
+ await page.evaluate(setCaptionState, { list: [state], only: "chip", stroke });
+ const chipClip = clipOf(placed);
+ const chip = { file: path.join(dir, `caption-${c.i}.png`), x: chipClip.x, y: chipClip.y };
+ await page.screenshot({ path: chip.file, clip: chipClip, omitBackground: true });
+ await page.evaluate(setCaptionState, { list: [state], only: "mark", stroke });
+ // The underline and the leader (which does not slide): their union.
+ const pts = [...(placed.leader ?? []), [geo.word.x, geo.word.y + geo.word.height * 0.6], [geo.word.x + geo.word.width, geo.word.y + geo.word.height * 1.2]];
+ const mx0 = Math.min(...pts.map((p) => p[0]));
+ const my0 = Math.min(...pts.map((p) => p[1]));
+ const markClip = clipOf({ x: mx0, y: my0, width: Math.max(...pts.map((p) => p[0])) - mx0, height: Math.max(...pts.map((p) => p[1])) - my0 });
+ const mark = { file: path.join(dir, `caption-${c.i}-mark.png`), x: markClip.x, y: markClip.y };
+ await page.screenshot({ path: mark.file, clip: markClip, omitBackground: true });
+ await page.evaluate(setCaptionState, { list: [] });
+ await page.evaluate(() => document.querySelectorAll("style[data-pcap-solo]").forEach((el) => el.remove()));
+ const rel = placed.y >= geo.word.y + geo.word.height ? "below" : placed.y + placed.height <= geo.word.y ? "above" : placed.x >= geo.word.x ? "side-right" : "side-left";
+ const d = slideDir(rel);
+ // What it would cover of the words read, or of anything drawn: none, unless nothing in the frame is free.
+ out.push({ ...c, chip, mark, slide: { x: d.x * CAPTION_SLIDE * k, y: d.y * CAPTION_SLIDE * k }, track: [], placed: { ...placed, rel, word: geo.word } });
+ }
+ } finally {
+ await ctx.close();
+ }
+ return out;
+}
+
+/**
+ * THE CLOCK's FRAMES (post-clock.mjs): on the card page as drawn, the chip
+ * mounted at its widest and placed (measureClockPlace: the bottom-right corner
+ * by the counts row, else the top-right -- over no word), then shot alone on a
+ * clear page at each frame of its run and its badge's fade (each distinct one
+ * once) and a concat list holding each for its frames, the last to the end.
+ * `{ list, x, y, place, covers, shots }`.
+ */
+export async function shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction = null, follow = null, total = 0 }) {
+ const fps = render.fps ?? 30;
+ const k = box.height / 1080;
+ const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" });
+ const page = await ctx.newPage();
+ const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href]));
+ try {
+ const file = path.join(dir, "clock.html");
+ await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null }), "utf8");
+ await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
+ await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
+ const face = clockFace(clock.to, clock.zone);
+ const size = await page.evaluate(mountClock, { css: clockCss({ height: box.height, palette: render.palette }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } });
+ await page.evaluate(() => document.fonts.ready.then(() => true));
+ // Placed as the card is when its own post is in (the read's end: a threaded card's counts row is there), and
+ // judged over the read (its start, middle and end): the place covering fewest words over all three wins.
+ const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null;
+ const states = follow ? [total, 0, total / 2] : [0];
+ const looks = [];
+ for (const s of states) {
+ if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s));
+ looks.push(await page.evaluate(measureClockPlace, { size, inset: Math.round(22 * k), fixed: looks[0]?.tries ?? null }));
+ }
+ const at0 = looks[0];
+ const at = at0 ? at0.tries.map((t, i) => ({ ...t, covers: looks.reduce((a, l) => a + (l?.tries?.[i]?.covers ?? 0), 0) })).sort((a, b) => a.covers - b.covers)[0] : null;
+ if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, 0));
+ if (!at) throw new Error(`${entry.id}: the clock has no card to sit on`);
+ await page.evaluate(() => {
+ const st = document.createElement("style");
+ st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-clock-layer]) { visibility: hidden !important; }";
+ document.head.appendChild(st);
+ });
+ // The clip: the chip and its badge to its left.
+ const left = Math.round(300 * k);
+ const x = Math.max(0, at.x - left);
+ const y = Math.max(0, at.y - Math.round(10 * k));
+ const clip = { x, y, width: Math.min(box.width - x, at.x + size.width + Math.round(16 * k) - x), height: Math.min(box.height - y, size.height + Math.round(20 * k)) };
+ const fdir = path.join(dir, "clock");
+ await rm(fdir, { recursive: true, force: true });
+ await mkdir(fdir, { recursive: true });
+ const shots = new Map();
+ const runs = [];
+ for (const s of clockFrameTimes(clock, fps)) {
+ const st = clockStateAt(clock, s);
+ const key = JSON.stringify([st.time, st.date, st.gap, Math.round(st.gapOpacity * 50), Math.round(st.hourTurn * 2), Math.round(st.minuteTurn), st.running]);
+ if (!shots.has(key)) {
+ const f = path.join(fdir, `c-${String(shots.size).padStart(4, "0")}.png`);
+ await page.evaluate(setClockState, { x: at.x, y: at.y, st });
+ await page.screenshot({ path: f, clip, omitBackground: true });
+ shots.set(key, f);
+ }
+ if (runs.length && runs[runs.length - 1].key === key) runs[runs.length - 1].n += 1;
+ else runs.push({ key, n: 1 });
+ }
+ const q = (f) => `'${f.replace(/'/g, "'\\''")}'`;
+ const lines = ["ffconcat version 1.0"];
+ runs.forEach((r, i) => lines.push(`file ${q(shots.get(r.key))}`, `duration ${(r.n / fps).toFixed(6)}`));
+ lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`);
+ const list = path.join(fdir, "frames.ffconcat");
+ await writeFile(list, lines.join("\n") + "\n", "utf8");
+ return { list, x: clip.x, y: clip.y, place: at.place, covers: at.covers, shots: shots.size, box: { x: at.x - Math.round(240 * k), y: at.y, width: size.width + Math.round(240 * k), height: size.height } };
+ } finally {
+ await ctx.close();
+ }
+}
+
+/**
* A post item's word zooms, resolved for the build: `[{ i, scope, from, to,
* scale, highlight, span }]`, each on its time (wordZoomTimes) -- refused in
* the build's words when one has no time, or two are up at once.
*/
export function postZoomPlan(entry, render, total = Infinity, schedule = undefined) {
const fx = Array.isArray(entry?.fx) ? entry.fx : [];
- if (!fx.length) return [];
+ if (!fx.some((f) => f?.kind === "word-zoom")) return [];
const times = wordZoomTimes(entry, render, schedule);
const bad = times.filter((t) => t.error);
if (bad.length) throw new Error(bad.map((t) => t.error).join("; "));
- const zooms = fx.map((f0, i) => {
+ // Its captions (post-caption.mjs) are timed and drawn apart: only the word zooms here.
+ const zooms = fx.flatMap((f0, i) => (f0?.kind === "word-zoom" ? [[f0, i]] : [])).map(([f0, i]) => {
const f = resolveWordZoom(f0);
const m = findMatch(targetTextOf(entry, f.target), f.match, f.occurrence);
return { i, scope: targetScope(f.target), from: m.from, to: m.to, scale: f.scale, highlight: f.highlight === false ? null : f.highlight, t: times[i].t, source: times[i].source, span: zoomSpan(f0, times[i].t) };
@@ -637,6 +866,33 @@ export function postZoomPlan(entry, render, total = Infinity, schedule = undefin
}
/**
+ * THE SEGMENT KEY's fields for a caption, the clock and the pace (appended to
+ * the key, never restructuring it): `{}` for an item with none of them, so its
+ * key is the one it had before they existed and its segment is reused. The
+ * entry itself is in the key (its `fx` -- each caption's text, match, at,
+ * hold, place; its clock fx's on/rewind -- its `narration.pace`, its id: a
+ * repeated item is its own segment); what it does NOT carry is added here:
+ * captionV / clockV the chip's and the clock's drawing (bumped when their look changes)
+ * clock clockPlan -- this post's time, the time it runs from (the
+ * item before's, when that one is a clock item), the mode
+ * (forward / rewind / none, a forced rewind) and the zone
+ * pace the gap knobs the pace resolved to (lead, tail, ramp, linger:
+ * a cut-level pace changes them without touching the entry)
+ */
+export const POST_CAPTION_DRAW_V = 2;
+export const POST_CLOCK_DRAW_V = 1;
+export function postFxKeyFields(entry, render, prev = null) {
+ const out = {};
+ const fx = Array.isArray(entry?.fx) ? entry.fx : [];
+ if (fx.some((f) => f?.kind === "caption")) out.captionV = POST_CAPTION_DRAW_V;
+ const clk = clockPlan(entry, render, prev);
+ if (clk) Object.assign(out, { clockV: POST_CLOCK_DRAW_V, clock: clk });
+ const k = postNarrationKnobs(entry, render);
+ if (isNarrated(entry) && k.pace && k.pace !== "normal") out.pace = { pace: k.pace, lead: k.lead, tail: k.tail, ramp: k.ramp, linger: k.linger };
+ return out;
+}
+
+/**
* THE SEGMENT's CACHE KEY's fields, pure (a build whose key matches keeps the segment it has): the entry as drawn
* (and as published), the box and framing, the palette and faces, the encode, every file's stamp, the avatars, the
* narration and its mix, the plan's follow -- which carries the thread's tiles and their schedule, their relations,
@@ -653,7 +909,7 @@ export function postZoomPlan(entry, render, total = Infinity, schedule = undefin
* 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 }) {
+export function postSegmentKeyOf({ entry, redaction = null, box, place = [], render, encode = [], stamps = [], avatars = {}, take = null, plan, bleeps = null, layout = null, from = null, prev = null }) {
return {
v: 1, entry,
// A redaction that changes what the card draws changes the key; none leaves it as it was.
@@ -667,6 +923,8 @@ export function postSegmentKeyOf({ entry, redaction = null, box, place = [], ren
...(from ? { joinFrom: { entry: from.entry, follow: from.plan.follow ?? null, total: from.plan.total, media: from.media.map((x) => [x.m.src, x.t, x.box]), fadeIn: from.fadeIn } } : {}),
...(plan.panel ? { panel: plan.panel } : {}),
...(layout?.panel === "top" || layout?.panel === "bottom" ? { layout: { panel: layout.panel, card: layout.card, slot: layout.slot } } : {}),
+ // A caption, the clock, the pace (post-caption.mjs, post-clock.mjs): nothing for an item with none of them.
+ ...postFxKeyFields(entry, render, prev),
...(POST_SEGMENT_RV ? { rv: POST_SEGMENT_RV } : {}),
};
}
@@ -747,7 +1005,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
const st = await stat(f).catch(() => null);
return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`;
}));
- const key = postSegmentKey(postSegmentKeyOf({ entry, redaction, box, place, render, encode, stamps, avatars, take, plan, bleeps, layout, from }));
+ const key = postSegmentKey(postSegmentKeyOf({ entry, redaction, box, place, render, encode, stamps, avatars, take, plan, bleeps, layout, from, prev }));
const record = postRecordPath(seg);
const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null);
if (had?.key === key && (await stat(seg).catch(() => null))) {
@@ -756,7 +1014,11 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
}
const cardDir = path.join(outDir, "cards", `post-${entry.id}`);
const zoomPlan = postZoomPlan(entry, render, plan.total, 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 });
+ // Its captions (post-caption.mjs): each waits for a zoom it would be up with, and is gone by the media phase (a stack card).
+ const capPlan = captionPlan(entry, render, { zooms: zoomPlan.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration ?? undefined });
+ // Its clock (post-clock.mjs): the post's own time, run from the clock item before it.
+ const clk = clockPlan(entry, render, prev);
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [] });
// NO HIDDEN TEXT IS EVER NARRATED (operator, 4 Nov): a part whose words are not in view, whole and lit, while it
// is said -- or a context post drawn over its context size -- refuses the build (READ_IN_VIEW=warn: a note).
// A part read off a linked post's picture is on screen only while the panel shows it (post-thread.mjs panelReadErrors).
@@ -790,7 +1052,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg });
narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs, ...(bleeps ? { bleeps } : {}) };
}
- const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null, panelFiles, map: cards.map ?? null, join: from && cards.joinFrom ? { seconds: plan.follow.join.seconds, fadeIn: from.fadeIn, from: from.media } : null });
+ const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null, panelFiles, map: cards.map ?? null, join: from && cards.joinFrom ? { seconds: plan.follow.join.seconds, fadeIn: from.fadeIn, from: from.media } : null, captionFx: cards.captions ?? [], clock: cards.clock ? { ...cards.clock, until: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total } : null });
try {
await exec(ffmpeg, argv, { maxBuffer: 1 << 24 });
} catch (err) {
@@ -801,7 +1063,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
// 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 });
// 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 writeFile(`${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8");
await rename(`${record}.tmp`, record);
emit("note", {
message: narration
@@ -809,6 +1071,8 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
: `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})`,
});
if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` });
+ if (cards.clock) emit("note", { message: `${entry.id}: clock ${clockFace(clk.to, clk.zone).time} ${clockFace(clk.to, clk.zone).date} (${clk.mode === "none" ? "shown" : clk.mode === "rewind" ? "rewound" : "run forward"}${clk.mode === "none" ? "" : ` from the item before, ${clk.gap / 60000 | 0} min`}), ${cards.clock.place}${cards.clock.covers ? ` -- WARNING: over ${cards.clock.covers} word(s)` : ""}` });
+ for (const c of cards.captions ?? []) emit("note", { message: `${entry.id}: caption ${c.i + 1} "${c.text}" at ${c.t.toFixed(2)} s (${c.source === "at" ? "set by hand" : c.source === "words" ? "from the take's words" : "the reading estimate"}${c.span.waited !== null ? `, after word zoom ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.rel} the phrase ${c.placed.place === "card" ? "on the card" : "off the card"}${c.placed.leader ? ", a leader to it" : ""}${c.cutByPan ? ` (gone at ${c.cutByPan} s, before the card pans its phrase)` : ""}${c.placed.covers ? ` -- WARNING: no free space in the frame, it covers ${c.placed.covers} thing(s) drawn (shorten its text)` : ""}` });
for (const z of zooms) emit("note", { message: `${entry.id}: word zoom ${z.i + 1} at ${z.t.toFixed(2)} s (${z.source === "at" ? "set by hand" : "from the take's words"}), ${z.span.scale}× over ${z.span.t0}–${z.span.t3} s` });
return seg;
}
diff --git a/umtool/report-to-video/word-zoom.mjs b/umtool/report-to-video/word-zoom.mjs
@@ -31,8 +31,12 @@
import { cardText, contextText, parentsOf } from "./post-item.mjs";
import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs";
+import { captionErrors } from "./post-caption.mjs";
+import { clockErrors } from "./post-clock.mjs";
-export const POST_FX_KINDS = Object.freeze(["word-zoom"]);
+// A post's effects: a word zoom, a CAPTION (post-caption.mjs: a chip explaining a phrase as it is read), and its
+// CLOCK (post-clock.mjs: the post's time on the card, running from the item before's).
+export const POST_FX_KINDS = Object.freeze(["word-zoom", "caption", "clock"]);
export const POST_FX_MAX = 8;
export const WORD_ZOOM_EASES = Object.freeze(["out", "inOut", "snap"]);
export const WORD_ZOOM_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.5, hold: 1.2, scale: 2, ease: "inOut", highlight: "#ffd84d" });
@@ -136,6 +140,8 @@ export function validatePostFx(e) {
const fw = `${w}[${i}]`;
if (!isObj(fx)) return errors.push(`${fw} must be an object`);
if (!POST_FX_KINDS.includes(fx.kind)) return errors.push(`${fw}.kind must be one of ${POST_FX_KINDS.join(", ")}`);
+ if (fx.kind === "caption") return errors.push(...captionErrors(e, fx, fw));
+ if (fx.kind === "clock") return errors.push(...clockErrors(e, fx, fw));
for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a word-zoom key (${[...KEYS].join(", ")})`);
const target = fx.target ?? "post";
const text = typeof target === "string" ? targetTextOf(e, target) : null;
@@ -281,7 +287,7 @@ export function scriptWordTimes(script, recognized) {
* @param {Record<string, any>} entry
* @param {Record<string, any>} [render]
* @param {Record<string, any> | null} [schedule]
- * @returns {Array<{ i: number, t?: number, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>}
+ * @returns {Array<{ i: number, t?: number, kind?: string, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>}
*/
export function wordZoomTimes(entry, render = undefined, schedule = undefined) {
const list = Array.isArray(entry?.fx) ? entry.fx : [];
@@ -290,6 +296,8 @@ export function wordZoomTimes(entry, render = undefined, schedule = undefined) {
// `schedule`: the item's narration schedule when the caller has it (Play: the plan's), else worked out here.
const sch = narrated ? schedule ?? narrationSchedule(entry, render) : null;
return list.map((fx0, i) => {
+ // Another effect (a caption, post-caption.mjs) is timed by its own module: no time here, and no error.
+ if (isObj(fx0) && fx0.kind !== "word-zoom" && POST_FX_KINDS.includes(fx0.kind)) return { i, kind: fx0.kind };
if (!isObj(fx0) || fx0.kind !== "word-zoom") return { i, error: "not a word zoom" };
const fx = resolveWordZoom(fx0);
if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" };