commit 59805728981e85986864608f60e228f2683e8ee9
parent 6601f3aa56ca83afed17c791dc38d95f23d4c6d3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 29 Oct 2026 10:32:41 -0400
Merge lane/video-modules-ui: the video-modules registry, the story modules, look presets, module-config apply and the generic module panel
Conflicts:
- chrome-feed.mjs: the lane's `const html = (` (items for the frame keys),
with reply-parent's `whole` (data-thread) line before it.
- compose-chrome.mjs: the lane's imports plus threadShotOf from deck.mjs;
regionHtml is the module dispatch, its `shots` helper taking reply-parent's
`threads` Set: (posts, key = "shot", threads = null) => copyShots(...).
- deck.mjs: reply-parent's POST_KEYS (with `thread`); POST_LAYOUTS/POST_LINKS
now live in modules/settings.mjs (posts[].thread is still validated in
deck.mjs validatePosts).
- umtool/docs/cli.md: reply-parent's `posts set` and `posts add --thread`
rows, then the lane's `modules` and `preset` rows.
modules/feed.mjs page() collects the thread shots and passes
threadShots to feedHtml, so a reply's thread shot still renders whole
through the feed module (a test in chrome-feed.test.mjs).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
87 files changed, 7661 insertions(+), 887 deletions(-)
diff --git a/common/lib/report/intro.d.mts b/common/lib/report/intro.d.mts
@@ -13,6 +13,8 @@ export type IntroSite = "auto" | "none" | string | IntroSiteObject;
export type Intro = {
style: string; ground: IntroGround; mark: IntroMark; sound: string | false | undefined; seconds: number;
site?: IntroSite; swap?: IntroSwap; url?: IntroUrlMode; urlPlace?: IntroUrlPlace;
+ /** The brand (release 39): the kit it draws, the suffix a site's name keeps, the project URL the swap writes. */
+ brand?: string; suffix?: string; projectUrl?: string | false;
};
export const INTRO_STYLES: readonly string[];
@@ -32,9 +34,11 @@ export const INTRO_URLS: readonly Exclude<IntroUrlMode, "none">[];
export const INTRO_URL_PLACES: readonly IntroUrlPlace[];
export const INTRO_SITE_DEFAULTS: Readonly<{ swap: IntroSwap; url: IntroUrlMode; urlPlace: IntroUrlPlace }>;
export const INTRO_SUFFIX: string;
+export const INTRO_BRAND_DEFAULT: string;
+export const INTRO_PROJECT_URL: string;
export function introUrlMode(v: unknown): IntroUrlMode;
export function introUrlText(u: unknown): string;
-export function introSitePrefix(name: unknown): string;
+export function introSitePrefix(name: unknown, suffix?: string): string;
export function introSiteErrors(site: unknown): string[];
export const INTRO_SECONDS: number;
export const INTRO_SECONDS_MIN: number;
diff --git a/common/lib/report/intro.mjs b/common/lib/report/intro.mjs
@@ -110,9 +110,15 @@ export const INTRO_URL_PLACES = Object.freeze(["under", "replace"]);
/** The swap's defaults: the operator's pick. */
export const INTRO_SITE_DEFAULTS = Object.freeze({ swap: "swipe-down", url: "both", urlPlace: "under" });
-/** The family's shared suffix: what a site's name keeps of "Archilyzer". */
+/** The family's shared suffix: what a site's name keeps of "Archilyzer". `render.intro.suffix` sets another brand's. */
export const INTRO_SUFFIX = "lyzer";
+/** The brand kit the intro draws (report-to-video brands/<id>.json) unless `render.intro.brand` names another. */
+export const INTRO_BRAND_DEFAULT = "archilyzer-media";
+
+/** The project's URL as the swap writes it, unless `render.intro.projectUrl` sets another (or false: none). */
+export const INTRO_PROJECT_URL = "archilyzer.pages.dev";
+
/** The intro's timeline id (its segment is segments/<id>.mp4). */
export const INTRO_ID = "brand-intro";
@@ -135,6 +141,11 @@ export function introOf(render) {
mark: INTRO_MARKS.includes(o.mark) ? o.mark : (INTRO_STYLE_MARK[style] ?? "none"),
sound: o.sound === false || typeof o.sound === "string" ? o.sound : undefined,
seconds: Number.isFinite(o.seconds) ? o.seconds : INTRO_SECONDS,
+ // The brand's knobs only when set: an intro without them reads exactly
+ // as it did before they existed (the Archilyzer kit, "lyzer", its URL).
+ ...(typeof o.brand === "string" && o.brand ? { brand: o.brand } : {}),
+ ...(typeof o.suffix === "string" && o.suffix ? { suffix: o.suffix } : {}),
+ ...(o.projectUrl === false || (typeof o.projectUrl === "string" && o.projectUrl) ? { projectUrl: o.projectUrl } : {}),
// The site's knobs only when there is a site: an intro without one reads
// exactly as it did before the key existed.
...(site
@@ -168,9 +179,9 @@ export const introUrlText = (u) => String(u ?? "").trim().replace(/^[a-z][a-z0-9
* wordmark that changes; `lead` (the site's wordmarkLead) only says which of
* its letters are heavy.
*/
-export function introSitePrefix(name) {
+export function introSitePrefix(name, suffix = INTRO_SUFFIX) {
const n = String(name ?? "");
- return n.length > INTRO_SUFFIX.length && n.endsWith(INTRO_SUFFIX) ? n.slice(0, -INTRO_SUFFIX.length) : n;
+ return n.length > suffix.length && n.endsWith(suffix) ? n.slice(0, -suffix.length) : n;
}
/** Every reason `site` (a `render.intro.site`) cannot be drawn, as sentences naming the key. */
@@ -197,7 +208,7 @@ export function introSiteErrors(site) {
return errors;
}
-const KEYS = ["style", "ground", "mark", "sound", "seconds", "site", "swap", "url", "urlPlace"];
+const KEYS = ["style", "ground", "mark", "sound", "seconds", "site", "swap", "url", "urlPlace", "brand", "suffix", "projectUrl"];
/** Every reason `value` (a `render.intro`) cannot be built, as sentences naming the key. */
export function introErrors(value) {
@@ -231,6 +242,17 @@ export function introErrors(value) {
if (o.urlPlace !== undefined && !INTRO_URL_PLACES.includes(o.urlPlace)) {
errors.push(`render.intro.urlPlace must be ${INTRO_URL_PLACES.join(" or ")}, got ${JSON.stringify(o.urlPlace)}`);
}
+ // The brand (release 39): which kit it draws, the suffix a site's name
+ // keeps of it, the project URL the swap writes.
+ if (o.brand !== undefined && !(typeof o.brand === "string" && /^[a-z0-9][a-z0-9-]{0,39}$/.test(o.brand))) {
+ errors.push(`render.intro.brand must be a brand kit's id (e.g. "${INTRO_BRAND_DEFAULT}"), got ${JSON.stringify(o.brand)}`);
+ }
+ if (o.suffix !== undefined && !(typeof o.suffix === "string" && /^[A-Za-z]{1,16}$/.test(o.suffix))) {
+ errors.push(`render.intro.suffix must be the letters a site's name keeps of the brand's (e.g. "${INTRO_SUFFIX}"), 1 to 16, got ${JSON.stringify(o.suffix)}`);
+ }
+ if (o.projectUrl !== undefined && o.projectUrl !== false && !(typeof o.projectUrl === "string" && introUrlText(o.projectUrl))) {
+ errors.push(`render.intro.projectUrl must be the project's URL (e.g. "${INTRO_PROJECT_URL}") or false (none)`);
+ }
return errors;
}
diff --git a/package.json b/package.json
@@ -24,7 +24,7 @@
"wt": "node scripts/worktree.mjs",
"e2e:sharded": "node scripts/run-sharded-e2e.mjs",
"e2e:all": "node scripts/e2e-all.mjs",
- "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs",
+ "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs",
"test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]",
"typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit",
"lint": "pnpm --filter export run lint",
diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts
@@ -1,6 +1,7 @@
import {
composeDeckPreview,
composeFeedPreview,
+ composeLayerPreviews,
composeFinalePreview,
composePostsPreviews,
composeStampPreview,
@@ -11,7 +12,7 @@ import {
segmentBoxes,
} from "@/lib/report/onscreen.mjs";
import {
- deckPreviewSrc, feedPreviewSrc, finalePreviewSrc, postsPreviewSrc, resolveReport, stampPreviewSrc,
+ deckPreviewSrc, feedPreviewSrc, finalePreviewSrc, layerPreviewSrc, postsPreviewSrc, resolveReport, stampPreviewSrc,
} from "@/lib/report/serve.mjs";
import {
deckGeometry, deckLayout, deckOn, feedGeometry, postsGeometry, stampGeometry, validateChrome,
@@ -73,6 +74,10 @@ export const dynamic = "force-dynamic";
// composed under takes/<id>/out/<variant>/chrome/, served under
// `<project>/<variant>/@take/<id>/` -- never over the project's own preview.
//
+// `layers: [<module id>, …]` composes only those modules, each alone through
+// its own page (modules/<id>.mjs) -- the module panel's single-layer preview:
+// `{ layers: [{ id, region, geometry, src | windows | off | error }] }`.
+//
// The client sends a project id, a variant, a take id and the drafts. Never a path.
export async function POST(request: Request) {
let body: Record<string, unknown>;
@@ -132,6 +137,49 @@ export async function POST(request: Request) {
return Response.json({ error: `render.chrome: ${errors.join("; ")}`, errors }, { status: 400 });
}
+ // `layers: [<module id>, …]` (release 39, the module panel): only those
+ // modules, each composed alone through its own page -- a part of the deck
+ // (the subtitle, the counter …) is the deck's page.
+ if (Array.isArray(body.layers)) {
+ const ids = body.layers.map(String).slice(0, 12);
+ const stamp = Date.now();
+ const layers = await composeLayerPreviews(target, r.variant, schedule, ids, render);
+ let deckSrc: string | null = null;
+ let deckError: string | null = null;
+ if (layers.some((l) => l.region === "deck")) {
+ try {
+ await composeDeckPreview(target, r.variant, schedule);
+ deckSrc = `${deckPreviewSrc(r.project.id, r.variant, take)}?v=${stamp}`;
+ } catch (e) {
+ deckError = e instanceof Error ? e.message : String(e);
+ }
+ }
+ const g = deckGeometry(render);
+ return Response.json(
+ {
+ variant: r.variant,
+ geometry: g,
+ schedule,
+ layers: layers.map((l) => {
+ if (l.region === "deck") {
+ return { ...l, geometry: g.deck, ...(deckSrc ? { src: deckSrc } : { error: deckError }) };
+ }
+ if (l.name) return { ...l, src: `${layerPreviewSrc(r.project.id, r.variant, l.name, take)}?v=${stamp}` };
+ if (Array.isArray(l.windows)) {
+ return {
+ ...l,
+ windows: l.windows.map((w: Record<string, unknown>) => (w.name
+ ? { ...w, src: l.region === "finale" ? `${finalePreviewSrc(r.project.id, r.variant, take)}?v=${stamp}` : `${layerPreviewSrc(r.project.id, r.variant, String(w.name), take)}?v=${stamp}` }
+ : w)),
+ };
+ }
+ return l;
+ }),
+ },
+ { headers: { "cache-control": "no-store" } },
+ );
+ }
+
try {
await composeDeckPreview(target, r.variant, schedule);
} catch (e) {
diff --git a/umtool/app/api/report/modules/route.ts b/umtool/app/api/report/modules/route.ts
@@ -0,0 +1,89 @@
+import { withEditNotes } from "@/lib/report/guard";
+import {
+ ChromeRefused, RenderRefused, StaleToken, effectiveManifest, manifestToken, updateChrome, updatePreset, updateRender,
+} from "@/lib/report/manifest.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { moduleProblems } from "umtool-report-to-video/modules";
+import { panelState, panelWrite } from "umtool-report-to-video/modules/panel";
+import { listPresets } from "umtool-report-to-video/presets";
+
+export const dynamic = "force-dynamic";
+
+// THE MODULE PANEL (release 39): every video module with a `ui` descriptor,
+// as umtool's Media tab draws it -- its fields as the manifest holds them and
+// as the build reads them (over the cut's look preset), whether it is on, and
+// its validator's sentences -- and the cut's preset.
+//
+// PUT { project, token, module, fields?, enabled? } writes one module through
+// the writers: a key under render.chrome by updateChrome (validated whole,
+// over the preset), a look key (the intro, the blur) by updateRender.
+// `fields` are the module's ui keys (dotted, null removes); `enabled` false
+// removes its object, true writes its starting value.
+// PUT { project, token, preset: <name> | null } names the cut's look preset
+// (updatePreset). The client never sends a path.
+
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const manifest = r.manifest as Record<string, unknown>;
+ let seen: Record<string, unknown> = manifest;
+ let presetError: string | null = null;
+ try {
+ seen = effectiveManifest(manifest);
+ } catch (e) {
+ presetError = e instanceof Error ? e.message : String(e);
+ }
+ return Response.json(
+ {
+ preset: typeof manifest.preset === "string" ? manifest.preset : null,
+ presetError,
+ presets: listPresets(),
+ modules: panelState(manifest, seen, moduleProblems(seen) as Record<string, string[]>),
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function PUT(request: Request) {
+ const refused = refuseCaller(request, "/api/report/modules");
+ if (refused) return refused;
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const token = typeof body.token === "string" ? body.token : null;
+ try {
+ if ("preset" in body) {
+ const name = body.preset === null || body.preset === "" ? null : String(body.preset);
+ const { result, editNotes } = await withEditNotes(r.project, () => updatePreset(r.project.dir, name, { token }));
+ return Response.json({ ok: true, ...result, editNotes }, { headers: noStore });
+ }
+ const id = String(body.module ?? "");
+ const fields = (body.fields ?? {}) as Record<string, unknown>;
+ if (typeof fields !== "object" || Array.isArray(fields)) return Response.json({ error: "fields is an object of the module's keys" }, { status: 400 });
+ const enabled = typeof body.enabled === "boolean" ? body.enabled : undefined;
+ const write = panelWrite(r.manifest as Record<string, unknown>, id, { fields, enabled });
+ const { result, editNotes } = await withEditNotes(r.project, async () => {
+ if ("chrome" in write) return updateChrome(r.project.dir, write.chrome ?? null, { token });
+ return updateRender(r.project.dir, write.render ?? {}, { token });
+ });
+ return Response.json({ ok: true, token: (result as { token: string | null }).token, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) {
+ return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 });
+ }
+ if (e instanceof ChromeRefused || e instanceof RenderRefused) {
+ return Response.json({ error: e.message, errors: (e as { errors: string[] }).errors }, { status: 400 });
+ }
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -56,6 +56,10 @@
// umtool notes [<site>/<report> | <project> | --all] [--open|--resolved|--all-status] [--json]
// umtool notes reply <id> "<text>" [--resolve] | resolve | wontfix | reopen <id>
// the operator's notes, and the agent's answers
+// umtool modules list | apply <project> [--config F] [--dry-run | --take <id> [--at S --dur S | --full] …]
+// the video modules; a module-config.json onto the cut, or as a take's patch
+// umtool preset list | show <name> | save <name> --from <project> | apply <name|none> <project>
+// the look presets: a render block the manifest stands on (preset → manifest → style → patch)
// umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …]
// [--at S --dur S | --full] [--force] [--from TAKE] [--keep-frames] | --id <id> --rebuild make one take
// [--draft] record it without rendering (walk it first) · --id <id> --promote [--anyway] make it the cut
@@ -743,6 +747,8 @@ function usage() {
" umtool look <project> key=value … the cut's knobs: factcheck.stamp.scale|motion|opacity|seconds,",
" factcheck.verdicts.<V>.stampLabel|label|color, deck.markers=<json>, deck.markerLayout,",
" variants=<json>, and the look's keys (transition=0.3, …)",
+ " umtool migrate <project> [--dry-run] [--json] move the manifest into the video modules' homes",
+ " (the fact-check verdicts and tally become deck.counter's series); renders the same",
" umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder of a build (render.variants);",
" --list: what was made, and the build's sync report (each clip's lag, past a frame flagged)",
" umtool corrections <project> what the report got wrong + the walk's coverage",
@@ -782,6 +788,10 @@ function usage() {
" umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)",
" umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)",
" umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>",
+ " umtool modules list | apply <project> [--config F] [--dry-run | --take <id> [--at S --dur S | --full] …]",
+ " a module-config.json onto the cut (writers), or as a take's patch",
+ " umtool preset list | show <name> | save <name> --from <project> | apply <name|none> <project>",
+ " the look presets (preset → manifest → style → take patch)",
" umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]",
" one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force;",
" --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)",
@@ -867,6 +877,10 @@ const COMMANDS = {
// The video knobs (plans/video-knobs-ui.md): lib/report/knobsCli.mjs.
set: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).setCommand(argv.slice(argv.indexOf("set") + 1))),
look: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).lookCommand(argv.slice(argv.indexOf("look") + 1))),
+ // The video modules' homes (release 39): lib/report/migrateCli.mjs.
+ modules: async () => process.exit(await (await import("../lib/report/modulesCli.mjs")).modulesCommand(argv.slice(argv.indexOf("modules") + 1))),
+ preset: async () => process.exit(await (await import("../lib/report/modulesCli.mjs")).presetCommand(argv.slice(argv.indexOf("preset") + 1))),
+ migrate: async () => process.exit(await (await import("../lib/report/migrateCli.mjs")).migrateCommand(argv.slice(argv.indexOf("migrate") + 1))),
variants: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).variantsCommand(argv.slice(argv.indexOf("variants") + 1))),
corrections: cmdCorrections,
build: cmdBuild,
diff --git a/umtool/components/projects/ModulesPanel.tsx b/umtool/components/projects/ModulesPanel.tsx
@@ -0,0 +1,414 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+
+// THE MODULE PANEL (release 39, the video modules): every video module with
+// a `ui` descriptor (report-to-video/modules/<id>.mjs), drawn from that
+// descriptor -- its fields, on/off for a module that is an object of its own,
+// its validator's sentences, a save through the writers (PUT
+// /api/report/modules) and a preview of the module ALONE (POST
+// /api/report/chrome/preview { layers: [id] }). The bespoke editors above
+// (the deck's settings, the markers, the claim checks) stay; this covers
+// every module, the ones without one first -- the story modules, the
+// finale's contents, the intro's brand and site. And the cut's look preset.
+
+type Field = {
+ key: string;
+ type: string;
+ label: string;
+ options?: unknown[];
+ min?: number;
+ max?: number;
+ step?: number;
+ default?: unknown;
+ item?: Field[];
+ when?: Record<string, unknown>;
+};
+type ModuleRow = {
+ id: string;
+ title: string;
+ summary: string;
+ kind: string;
+ slot: string;
+ z: number;
+ configKey: string;
+ base: string;
+ ui: Field[];
+ toggle: boolean;
+ enabled: boolean;
+ fields: Record<string, unknown>;
+ effective: Record<string, unknown>;
+ preview: boolean;
+ problems: string[];
+};
+type Preset = { name: string; description: string; error?: string };
+type State = { preset: string | null; presetError: string | null; presets: Preset[]; modules: ModuleRow[]; token: string | null };
+type Layer = {
+ id: string;
+ region?: string | null;
+ geometry?: { x: number; y: number; width: number; height: number } | null;
+ src?: string;
+ off?: string;
+ error?: string;
+ windows?: { segment: string | null; from: number; to?: number; src?: string; error?: string }[];
+};
+
+const input =
+ "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]";
+
+// The panel lists the modules without a bespoke editor first.
+const FIRST = ["pair", "chapter", "status", "finale", "intro", "counter"];
+const LIST_TYPES = new Set(["list", "series", "stats", "markers"]);
+// The rows of a list type whose descriptor names no item fields.
+const ITEMS: Record<string, Field[]> = {
+ stats: [
+ { key: "label", type: "text", label: "Label" },
+ { key: "value", type: "text", label: "Value" },
+ { key: "note", type: "text", label: "Note" },
+ { key: "color", type: "color", label: "Colour" },
+ ],
+ markers: [
+ { key: "after", type: "clip", label: "After" },
+ { key: "label", type: "text", label: "Label" },
+ { key: "color", type: "text", label: "Colour" },
+ { key: "align", type: "enum", label: "Align", options: ["auto", "left", "right", "center"] },
+ ],
+};
+
+const textOf = (v: unknown) => (v === undefined || v === null ? "" : typeof v === "object" ? JSON.stringify(v) : String(v));
+
+function getPath(obj: unknown, dotted: string): unknown {
+ return dotted.split(".").reduce<unknown>((o, k) => (o && typeof o === "object" && !Array.isArray(o) ? (o as Record<string, unknown>)[k] : undefined), obj);
+}
+function setPath(obj: Record<string, unknown>, dotted: string, value: unknown): Record<string, unknown> {
+ const out = structuredClone(obj);
+ const keys = dotted.split(".");
+ let cur: Record<string, unknown> = out;
+ for (const k of keys.slice(0, -1)) {
+ if (!cur[k] || typeof cur[k] !== "object" || Array.isArray(cur[k])) cur[k] = {};
+ cur = cur[k] as Record<string, unknown>;
+ }
+ const last = keys[keys.length - 1];
+ if (value === "" || value === undefined || value === null) delete cur[last];
+ else cur[last] = value;
+ return out;
+}
+
+/** One scalar field's input. */
+function Scalar({ f, value, placeholder, onChange, clips, testid }: {
+ f: Field; value: unknown; placeholder: unknown; onChange: (v: unknown) => void; clips: string[]; testid: string;
+}) {
+ if (f.type === "boolean") {
+ const v = value === undefined ? "" : String(value);
+ return (
+ <select className={input} data-testid={testid} value={v} onChange={(e) => onChange(e.target.value === "" ? null : e.target.value === "true")}>
+ <option value="">{`default (${textOf(placeholder ?? f.default) || "—"})`}</option>
+ <option value="true">on</option>
+ <option value="false">off</option>
+ </select>
+ );
+ }
+ if (f.type === "enum") {
+ const opts = (f.options ?? []).map((o) => String(o));
+ return (
+ <select className={input} data-testid={testid} value={value === undefined ? "" : String(value)} onChange={(e) => {
+ const raw = e.target.value;
+ onChange(raw === "" ? null : raw === "false" ? false : raw);
+ }}>
+ <option value="">{`default (${textOf(placeholder ?? f.default) || "—"})`}</option>
+ {opts.map((o) => <option key={o} value={o}>{o}</option>)}
+ </select>
+ );
+ }
+ if (f.type === "number") {
+ return (
+ <input className={`${input} w-24`} data-testid={testid} type="number" min={f.min} max={f.max} step={f.step ?? "any"}
+ value={value === undefined ? "" : String(value)} placeholder={textOf(placeholder ?? f.default)}
+ onChange={(e) => onChange(e.target.value === "" ? null : Number(e.target.value))} />
+ );
+ }
+ if (f.type === "color") {
+ return <input className={`${input} w-24`} data-testid={testid} value={textOf(value)} placeholder={textOf(placeholder ?? "#rrggbb")} onChange={(e) => onChange(e.target.value)} />;
+ }
+ if (f.type === "clip") {
+ return <input className={`${input} w-32`} data-testid={testid} list="module-panel-clips" value={textOf(value)} placeholder={clips[0] ?? "clip id"} onChange={(e) => onChange(e.target.value)} />;
+ }
+ if (f.type === "date") {
+ return <input className={`${input} w-28`} data-testid={testid} value={textOf(value)} placeholder="YYYY-MM-DD" onChange={(e) => onChange(e.target.value)} />;
+ }
+ if (f.type === "text") {
+ return <input className={`${input} min-w-0 flex-1`} data-testid={testid} value={textOf(value)} placeholder={textOf(placeholder ?? f.default)} onChange={(e) => onChange(e.target.value)} />;
+ }
+ // Anything else (a list of tokens, the stats cards, markers, an object): its JSON.
+ return <JsonField value={value} placeholder={placeholder} onChange={onChange} testid={testid} />;
+}
+
+function JsonField({ value, placeholder, onChange, testid }: { value: unknown; placeholder: unknown; onChange: (v: unknown) => void; testid: string }) {
+ const [text, setText] = useState(() => (value === undefined ? "" : JSON.stringify(value)));
+ const [bad, setBad] = useState(false);
+ return (
+ <textarea className={`${input} min-h-[2.2rem] flex-1 font-mono`} data-testid={testid} value={text}
+ placeholder={placeholder === undefined ? "JSON" : JSON.stringify(placeholder)}
+ style={bad ? { borderColor: "var(--color-bad, #e5534b)" } : undefined}
+ onChange={(e) => {
+ setText(e.target.value);
+ if (!e.target.value.trim()) { setBad(false); onChange(null); return; }
+ try {
+ onChange(JSON.parse(e.target.value));
+ setBad(false);
+ } catch {
+ setBad(true);
+ }
+ }} />
+ );
+}
+
+/** A list field: rows of its item's fields, added and removed. */
+function ListField({ f, value, onChange, clips, testid }: { f: Field; value: unknown; onChange: (v: unknown) => void; clips: string[]; testid: string }) {
+ const rows = Array.isArray(value) ? (value as Record<string, unknown>[]) : [];
+ if (!f.item && ITEMS[f.type]) f = { ...f, item: ITEMS[f.type] };
+ if (!f.item) return <JsonField value={value} placeholder={f.default} onChange={onChange} testid={testid} />;
+ const set = (i: number, key: string, v: unknown) => onChange(rows.map((r, j) => (j === i ? setPath(r ?? {}, key, v) : r)));
+ return (
+ <div className="flex w-full flex-col gap-1" data-testid={testid}>
+ {rows.map((r, i) => (
+ <div key={i} className="flex flex-wrap items-center gap-1 rounded border border-[var(--color-line)] p-1" data-testid={`${testid}-row-${i}`}>
+ {f.item!.map((it) => (
+ <label key={it.key} className="flex items-center gap-1 text-[10px] text-[var(--color-dim)]">
+ {it.label}
+ <Scalar f={it} value={getPath(r, it.key)} placeholder={undefined} clips={clips} testid={`${testid}-${i}-${it.key}`} onChange={(v) => set(i, it.key, v)} />
+ </label>
+ ))}
+ <button type="button" className={buttonVariants({ variant: "ghost", size: "sm" })} data-testid={`${testid}-remove-${i}`}
+ onClick={() => onChange(rows.filter((_, j) => j !== i))}>remove</button>
+ </div>
+ ))}
+ <button type="button" className={`${buttonVariants({ variant: "outline", size: "sm" })} self-start`} data-testid={`${testid}-add`}
+ onClick={() => onChange([...rows, {}])}>add</button>
+ </div>
+ );
+}
+
+/** A module's preview: its layer alone, over a scaled frame, scrubbed. */
+function LayerPreview({ layers, frame, total }: { layers: Layer[]; frame: { W: number; H: number }; total: number }) {
+ const [t, setT] = useState(0);
+ const boxRef = useRef<HTMLDivElement | null>(null);
+ const [scale, setScale] = useState(0.3);
+ useEffect(() => {
+ const el = boxRef.current;
+ if (!el) return;
+ const fit = () => setScale(el.clientWidth / frame.W);
+ fit();
+ const ro = new ResizeObserver(fit);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [frame.W]);
+ const first = layers.flatMap((l) => l.windows ?? []).find((w) => w.src);
+ useEffect(() => {
+ if (first) {
+ setT(first.from + 0.8);
+ for (const f of boxRef.current?.querySelectorAll("iframe") ?? []) f.contentWindow?.postMessage({ type: "deck:seek", t: first.from + 0.8 }, "*");
+ }
+ }, [first?.src]); // eslint-disable-line react-hooks/exhaustive-deps
+ // The pages are loaded once; a scrub seeks them by message (never a new src).
+ const tRef = useRef(t);
+ tRef.current = t;
+ const seek = useCallback((v: number) => {
+ setT(v);
+ for (const f of boxRef.current?.querySelectorAll("iframe") ?? []) f.contentWindow?.postMessage({ type: "deck:seek", t: v }, "*");
+ }, []);
+ const frames = layers.flatMap((l) => {
+ if (!l.geometry) return [];
+ if (l.src) return [{ key: l.id, src: l.src, g: l.geometry, show: true }];
+ return (l.windows ?? []).filter((w) => w.src).map((w) => ({
+ key: `${l.id}-${w.segment}`, src: w.src!, g: l.geometry!, show: t >= w.from && t <= (w.to ?? w.from + 10),
+ }));
+ });
+ return (
+ <div className="flex flex-col gap-1">
+ <div ref={boxRef} className="relative w-full overflow-hidden rounded bg-[#222]" style={{ aspectRatio: `${frame.W} / ${frame.H}` }} data-testid="module-preview-frame">
+ <div style={{ position: "absolute", left: 0, top: 0, width: frame.W, height: frame.H, transform: `scale(${scale})`, transformOrigin: "0 0" }}>
+ {frames.map((f) => (
+ <iframe key={f.key} title={f.key} src={`${f.src}${f.src.includes("?") ? "&" : "?"}preview=1`} data-testid="module-preview-iframe"
+ onLoad={(e) => e.currentTarget.contentWindow?.postMessage({ type: "deck:seek", t: tRef.current }, "*")}
+ style={{ position: "absolute", left: f.g.x, top: f.g.y, width: f.g.width, height: f.g.height, border: 0, background: "transparent", visibility: f.show ? "visible" : "hidden" }} />
+ ))}
+ </div>
+ </div>
+ <input type="range" min={0} max={Math.max(1, total)} step={0.1} value={t} onChange={(e) => seek(Number(e.target.value))} data-testid="module-preview-scrub" />
+ <div className="text-[10px] text-[var(--color-dim)]">{t.toFixed(1)} s</div>
+ {layers.map((l) => (l.off || l.error ? (
+ <div key={l.id} className="text-[11px] text-[var(--color-dim)]" data-testid="module-preview-note">{l.id}: {l.off ?? l.error}</div>
+ ) : null))}
+ </div>
+ );
+}
+
+function ModuleCard({ project, m, token, setToken, reload, clips }: {
+ project: string; m: ModuleRow; token: string | null; setToken: (t: string | null) => void; reload: () => Promise<void>; clips: string[];
+}) {
+ const [draft, setDraft] = useState<Record<string, unknown>>(m.fields);
+ const [busy, setBusy] = useState(false);
+ const [msg, setMsg] = useState<string | null>(null);
+ const [errors, setErrors] = useState<string[]>([]);
+ const [preview, setPreview] = useState<{ layers: Layer[]; frame: { W: number; H: number }; total: number } | null>(null);
+ const savedKey = JSON.stringify(m.fields);
+ useEffect(() => setDraft(m.fields), [savedKey]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const changed = useMemo(() => {
+ const out: Record<string, unknown> = {};
+ for (const f of m.ui) {
+ const a = JSON.stringify(draft[f.key] ?? null);
+ const b = JSON.stringify(m.fields[f.key] ?? null);
+ if (a !== b) out[f.key] = draft[f.key] ?? null;
+ }
+ return out;
+ }, [draft, m.fields, m.ui]);
+
+ const put = async (body: Record<string, unknown>) => {
+ setBusy(true);
+ setMsg(null);
+ setErrors([]);
+ try {
+ const res = await fetch("/api/report/modules", {
+ method: "PUT", headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, token, module: m.id, ...body }),
+ });
+ const j = await res.json();
+ if (!res.ok) {
+ setErrors(j.errors ?? [j.error ?? `HTTP ${res.status}`]);
+ setMsg(j.stale ? "the manifest changed under you — reloaded" : "refused");
+ if (j.stale) await reload();
+ return;
+ }
+ setToken(j.token ?? null);
+ setMsg("saved");
+ await reload();
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const doPreview = async () => {
+ setBusy(true);
+ setMsg(null);
+ try {
+ const res = await fetch("/api/report/chrome/preview", {
+ method: "POST", headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, layers: [m.id] }),
+ });
+ const j = await res.json();
+ if (!res.ok) { setMsg(j.error ?? `HTTP ${res.status}`); return; }
+ setPreview({ layers: j.layers ?? [], frame: { W: j.geometry?.W ?? 1920, H: j.geometry?.H ?? 1080 }, total: Number(j.schedule?.total ?? 60) });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const visible = m.ui.filter((f) => !f.when || Object.entries(f.when).every(([k, v]) => (draft[k] ?? m.effective[k]) === v));
+ return (
+ <details className="rounded border border-[var(--color-line)] p-2" data-testid={`module-${m.id}`}>
+ <summary className="flex cursor-pointer flex-wrap items-center gap-2 text-[12px]">
+ <span className="font-semibold text-[var(--color-text)]">{m.title}</span>
+ <span className="text-[10px] text-[var(--color-dim)]">{m.id} · {m.kind} · {m.slot}</span>
+ {m.toggle ? (
+ <span className={`text-[10px] ${m.enabled ? "text-[var(--color-ok,#5fa8d3)]" : "text-[var(--color-dim)]"}`} data-testid={`module-state-${m.id}`}>{m.enabled ? "on" : "off"}</span>
+ ) : null}
+ {m.problems.length ? <span className="text-[10px] text-[#e5534b]" data-testid={`module-problems-${m.id}`}>{m.problems.length} problem(s)</span> : null}
+ </summary>
+ <div className="mt-2 flex flex-col gap-2">
+ <p className="text-[11px] text-[var(--color-dim)]">{m.summary} <code>{m.base}</code></p>
+ {m.toggle ? (
+ <label className="flex items-center gap-2 text-[11px]">
+ <input type="checkbox" checked={m.enabled} disabled={busy} data-testid={`module-toggle-${m.id}`}
+ onChange={(e) => void put({ enabled: e.target.checked })} />
+ draw it in this cut
+ </label>
+ ) : null}
+ {m.problems.map((p) => <div key={p} className="text-[11px] text-[#e5534b]">{p}</div>)}
+ {visible.map((f) => (
+ <label key={f.key} className={`flex ${LIST_TYPES.has(f.type) ? "flex-col items-start" : "items-center"} gap-2 text-[11px] text-[var(--color-dim)]`}>
+ <span className="min-w-[9rem]">{f.label}</span>
+ {LIST_TYPES.has(f.type) ? (
+ <ListField f={f} value={draft[f.key] ?? m.effective[f.key]} clips={clips} testid={`module-field-${m.id}-${f.key}`}
+ onChange={(v) => setDraft((d) => ({ ...d, [f.key]: v }))} />
+ ) : (
+ <Scalar f={f} value={draft[f.key]} placeholder={m.effective[f.key]} clips={clips} testid={`module-field-${m.id}-${f.key}`}
+ onChange={(v) => setDraft((d) => ({ ...d, [f.key]: v === "" ? undefined : v }))} />
+ )}
+ </label>
+ ))}
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" className={buttonVariants({ size: "sm" })} disabled={busy || !Object.keys(changed).length}
+ data-testid={`module-save-${m.id}`} onClick={() => void put({ fields: changed })}>Save</button>
+ <button type="button" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={busy}
+ data-testid={`module-reset-${m.id}`} onClick={() => setDraft(m.fields)}>Reset</button>
+ {m.preview ? (
+ <button type="button" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={busy}
+ data-testid={`module-preview-${m.id}`} onClick={() => void doPreview()}>Preview alone</button>
+ ) : null}
+ {msg ? <span className="text-[11px] text-[var(--color-dim)]" data-testid={`module-status-${m.id}`}>{msg}</span> : null}
+ </div>
+ {errors.length ? (
+ <ul className="text-[11px] text-[#e5534b]" data-testid={`module-errors-${m.id}`}>{errors.map((e) => <li key={e}>{e}</li>)}</ul>
+ ) : null}
+ {preview ? <LayerPreview layers={preview.layers} frame={preview.frame} total={preview.total} /> : null}
+ </div>
+ </details>
+ );
+}
+
+export default function ModulesPanel({ project, clips }: { project: string; clips: string[] }) {
+ const [state, setState] = useState<State | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [presetMsg, setPresetMsg] = useState<string | null>(null);
+ const load = useCallback(async () => {
+ const res = await fetch(`/api/report/modules?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = await res.json();
+ if (!res.ok) { setError(j.error ?? `HTTP ${res.status}`); return; }
+ setState(j);
+ setError(null);
+ }, [project]);
+ useEffect(() => { void load(); }, [load]);
+ const setToken = (token: string | null) => setState((s) => (s ? { ...s, token } : s));
+
+ const putPreset = async (name: string | null) => {
+ setPresetMsg(null);
+ const res = await fetch("/api/report/modules", {
+ method: "PUT", headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, token: state?.token ?? null, preset: name }),
+ });
+ const j = await res.json();
+ if (!res.ok) { setPresetMsg((j.errors ?? [j.error]).join("; ")); return; }
+ setPresetMsg(name ? `the cut stands on ${name}` : "no preset");
+ await load();
+ };
+
+ if (error) return <section className="mt-4 text-[12px] text-[#e5534b]" data-testid="modules-panel">{error}</section>;
+ if (!state) return <section className="mt-4 text-[12px] text-[var(--color-dim)]" data-testid="modules-panel">Loading the modules…</section>;
+ const order = (id: string) => (FIRST.includes(id) ? FIRST.indexOf(id) : FIRST.length);
+ const mods = [...state.modules].sort((a, b) => order(a.id) - order(b.id) || a.z - b.z);
+ return (
+ <section className="mt-6 flex flex-col gap-2" data-testid="modules-panel">
+ <h3 className="text-[13px] font-semibold text-[var(--color-text)]">Video modules</h3>
+ <p className="text-[11px] text-[var(--color-dim)]">
+ Every module of the cut from its own descriptor: on or off, its settings, its checks, and a preview of it alone.
+ The look preset is the layer under the manifest (preset → manifest → style → take patch).
+ </p>
+ <label className="flex items-center gap-2 text-[11px] text-[var(--color-dim)]">
+ Look preset
+ <select className={input} data-testid="modules-preset" value={state.preset ?? ""} onChange={(e) => void putPreset(e.target.value || null)}>
+ <option value="">none</option>
+ {state.presets.map((p) => <option key={p.name} value={p.name} title={p.description}>{p.name}</option>)}
+ </select>
+ {presetMsg ? <span data-testid="modules-preset-status">{presetMsg}</span> : null}
+ {state.presetError ? <span className="text-[#e5534b]">{state.presetError}</span> : null}
+ </label>
+ <datalist id="module-panel-clips">{clips.map((c) => <option key={c} value={c} />)}</datalist>
+ {mods.map((m) => (
+ <ModuleCard key={m.id} project={project} m={m} token={state.token} setToken={setToken} reload={load} clips={clips} />
+ ))}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/report/MediaTab.tsx b/umtool/components/projects/report/MediaTab.tsx
@@ -5,6 +5,7 @@ import { manifestToken } from "@/lib/report/manifest.mjs";
import { draftRowsOf, draftRuns, projectIteration } from "@/lib/articles/projectDraft";
import MediaDrafts, { type FieldProvenance } from "../MediaDrafts";
import OnscreenSection from "../OnscreenSection";
+import ModulesPanel from "../ModulesPanel";
import YoutubeSection from "../YoutubeSection";
import SocialPostSection from "../SocialPostSection";
import HandFill, { type HandFillView } from "../HandFill";
@@ -57,6 +58,12 @@ export default async function MediaTab({ project, detail }: ReportTabProps) {
built={!!build.built}
/>
+ {/* --- every video module from its own descriptor (release 39) ----- */}
+ {/* The generic module panel: on/off, settings, checks, a preview of
+ each module alone, and the cut's look preset. The bespoke editors
+ above stay; this covers the modules without one. */}
+ <ModulesPanel project={project.id} clips={entries.map((e) => e.id)} />
+
{/* --- the upload's text (out/youtube.txt, or its preview) --------- */}
<YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} />
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -64,6 +64,8 @@ Inbox cannot disagree about what is wrong with one.
| `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) |
| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key. Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run) |
+| `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) |
+| `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project>` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build ([knobs.md](knobs.md#look-presets)) |
A project argument is an exact id, a directory, or a **unique** basename. Two
projects answering to one name is reported, never resolved by picking one.
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -132,6 +132,10 @@ that mentions the seizure in question and one before it. The Marks box is on eve
| `render.intro.site` — on the chime, "Archi" becomes the cited site's name ("Jera"), "lyzer" stays, the colours go to its accent: `auto` (the site whose `siteUrl` is `provenance.siteOrigin`; none found, no swap), a site id, `{name, lead?, accent?, url?}`, or `none`/absent (the plain intro, byte for byte). `render.intro.swap` `swipe-down` (default) \| `roll` \| `wipe`; `render.intro.url` `both` (default: the site's, then archilyzer.pages.dev) \| `site` \| `project` \| `false`; `render.intro.urlPlace` `under` (default: one row under MEDIA) \| `replace` (MEDIA's place) | — (manifest or a take) | a take: `umtool take <p> --id intro-jera --set render.intro.style=boot-dark --set render.intro.mark=chime --set render.intro.site=auto` (`--set render.intro.swap=roll`, `--set render.intro.url=false`, `--set render.intro.urlPlace=replace`) · standalone: `node umtool/report-to-video/intro.mjs render --style boot-dark --mark chime --site auto --site-origin https://jeralyzer.pages.dev --swap wipe --out x.mp4` | `PUT /api/report/render {project, token, patch: {intro: {…, site}}}` |
| `render.variants` — the ladder **Make variants** encodes: `{name, height?, crf?, maxMiB?, preset?}` (at most 12; a `maxMiB` rung takes no crf, a height there caps it); `master` is the build itself | Deliver, **Variants and sync**: Edit, Save ladder, Use the default | `umtool look <p> variants='[{"name":"master"},{"name":"720p","height":720,"crf":23}]'` | `PUT /api/report/render {project, token, variants}` |
+The `factcheck.verdicts` and `factcheck.tally` knobs are the deck's counter as the fact-check's five verdicts; a cut may
+count its own named series instead (`deck.counter`, [Counter](#counter)), and `umtool migrate <p>` moves the verdicts there,
+the render unchanged. The two are not set together: on a migrated cut the series' words are set in `deck.counter`.
+
The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets
the look's keys (`transition=0.3`, …: [report-video.md](report-video.md#the-look-captions-loudness-shorts-release-36)).
@@ -303,3 +307,268 @@ negative lag, needs a positive offset), then a build.
`umtool show <p>` prints a **knobs** block — each clip's claim knobs, audio and blur (which clip stamps), the stamp's
knobs and words, the markers and their layout, the ladder — and `umtool show <p> --json` carries it as `knobs`.
+
+## Look presets
+
+A **look preset** is a render block a manifest stands on: `"preset": "<name>"` at the manifest's TOP level (not
+`render.preset`, which is the x264 encoder preset) names `umtool/presets/<name>.json` — `{ name, description,
+render }` — and its `render` is laid UNDER the manifest's. The order, each an RFC 7386 merge patch over the one
+before:
+
+ preset → manifest → style → take patch
+
+So a manifest names only what it changes from its preset; a take's montage style and its own patch change it again
+(either may name a `preset` of its own — the last one named is the one laid); a `null` anywhere above removes the
+key it names from everything below, the preset's value included. It is resolved where every reader of a cut goes
+through (`selectVariant`), where a take merges its patches (`makeTake`, `resolveTakeManifest`) and where a writer
+checks the chrome (`updateChrome` validates the chrome over the preset). A resolved manifest says
+`presetApplied: <name>`.
+
+| | In umtool | From a terminal |
+|---|---|---|
+| the presets | Media, **Video modules**, Look preset | `umtool preset list` · `umtool preset show <name>` |
+| stand the cut on one (or none) | the same list | `umtool preset apply <name\|none> <p>` |
+| save a project's look as one (its content — claim checks, markers, counter series, finale stats, the story modules' lists, an intro's named site — left out) | | `umtool preset save <name> --from <p> [--description D]` |
+| a take on one | | `umtool take <p> --id <id> --set preset=<name>` |
+
+Built in: `huck-deck` (quartering-huck/polemic-huck's look: the feed, verdict-coloured pips, the finale beside the
+clip), `plain-deck` (the Trisha final's: every subtitle part, the boot-dark intro, no feed), `archive-catalog` (a
+then-and-now archive look: dated subtitles, a pitched rail, the pair strip at the foot of the footage).
+
+## A module-config.json
+
+A project's `module-config.json` names the modules its video wants in the design's vocabulary (`{ preset, modules:
+{ shell, subtitle, qr, counter, stamp, rail, chapter, pair, status, feed, intro, finale } }`). `umtool modules apply
+<p>` maps it into the manifest's homes (report-to-video `modules/config-loader.mjs`) and lists, by path, every field
+that has none — a cut-wide deck title, a rail node over a year of clips, a marker past the deck's twelve, a citation
+URL a status row does not draw, a feed post (posts join through `umtool posts add`). `--take <id>` makes it a take's
+patch instead. A finale stat `value: "counter.totals.<series>"` is counted from the config's marks at apply time.
+
+<!-- modules:begin (generated by report-to-video/modules/docs.mjs -- edit the modules, not this) -->
+## Modules
+
+A report video's chrome is a set of MODULES (`umtool/report-to-video/modules/`), each with its home in the manifest, its
+defaults, its validator and its frame-key rules; the build, the composer and umtool loop over the one registry
+(`modules/index.mjs`). The deck's parts are drawn in its one page; every other module is its own layer, segment or
+filter. A knob absent is its default, and a module whose knobs are all absent draws what it always drew.
+
+| Module | What it is | Its home |
+|---|---|---|
+| [Deck (the shell)](#deck-the-shell) `shell` | The panel at the foot of the frame: each clip's title, and the band the subtitle, QR, rail and counter draw in. (a page over the whole cut) | `render.chrome.deck` |
+| [Subtitle](#subtitle) `subtitle` | Each clip's source line under its title: the channel, the source's title, the date, the clock. (drawn in the deck's page) | `render.chrome.deck.subtitle` |
+| [QR](#qr) `qr` | Each clip's code in the deck, to the archive at the clip or to the record itself. (drawn in the deck's page) | `render.chrome.deck.qr` |
+| [Rail](#rail) `rail` | The deck's pip track: a pip per clip, the marker, the fuse, and the markers' flags. (drawn in the deck's page) | `render.chrome.deck.pip` |
+| [Counter](#counter) `counter` | A running tally of named series in the deck, each cell stepping as a mark's stamp lands. (drawn in the deck's page) | `render.chrome.deck.counter` |
+| [Claim checks](#claim-checks) `claims` | His explicit claims against the record on the rail: a count over a window, a goalpost moved. (drawn in the deck's page) | `render.chrome.deck.claims` |
+| [Teaser](#teaser) `teaser` | A full-frame card of lines popping in on the beat, inserted as its own segment. (a segment cut into the timeline) | -- |
+| [Intro](#intro) `intro` | The brand sting the cut opens with, a site's name swapped in on the chime. (a segment cut into the timeline) | `render.intro` |
+| [Blur](#blur) `blur` | A clip's picture blurred at its encode, a caption on it, the sound as recorded. (a filter on the footage) | `render.blur` |
+| [Posts feed](#posts-feed) `feed` | The cut's posts in a column beside the footage, each ticking in as its clip starts. (a page over the whole cut) | `render.chrome.deck.posts` |
+| [Popup posts](#popup-posts) `popup-posts` | A clip's posts as cards over the footage, each window its own short page at its own second. (pages at their own seconds) | `render.chrome.deck.posts` |
+| [Stamps](#stamps) `stamp` | Each counted mark's word, stamped over the footage as it lands. (a page over the whole cut) | `render.chrome.factcheck.stamp` |
+| [Stats](#stats) `stats` | A frame scan's running numbers over the clips that declare them. (a page over the whole cut) | `render.chrome.stats` |
+| [Then and now (pair)](#then-and-now-pair) `pair` | Two clips on one subject, each with its date: a then \| now strip (or a then→now card) with the pair's caption. (a page over the whole cut) | `render.chrome.pair` |
+| [Status ledger](#status-ledger) `status` | A row per item -- announced, then followed up or not -- filling a column as the cut plays. (a page over the whole cut) | `render.chrome.status` |
+| [Effects](#effects) `fx` | Overlays on the picture: receipts, a zoom, a scrubber, captions. (a page over the whole cut) | `render.chrome.fx` |
+| [Thread rail](#thread-rail) `threads` | A card per thread beside the footage, lit as its clips play. (a page over the whole cut) | `render.chrome.threads` |
+| [Flips](#flips) `flips` | Pairs of what was said then and now, in the side panel. (a page over the whole cut) | `render.chrome.flips` |
+| [Chapters](#chapters) `chapter` | A section bumper over the first seconds of the clip it opens: title, subtitle, date. (pages at their own seconds) | `render.chrome.chapter` |
+| [Finale](#finale) `finale` | The cut's last clips under the rail redrawn large, the final totals and stats cards. (pages at their own seconds) | `render.chrome.deck.finale` |
+
+### Deck (the shell)
+
+The panel at the foot of the frame and each clip's title (`render.chrome.deck`); its parts -- the subtitle, the QR, the rail, the counter, the claim checks -- are their own modules below.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.height` | 120–400 px · default 190 | `umtool look <p> deck.height=210` |
+| `deck.footageScale` | 0.5–1 (the footage must fit above the deck) · default 0.82 | `umtool look <p> deck.footageScale=0.8` |
+| `deck.background` | `panel` · `flush` · default `panel` | `umtool look <p> deck.background=flush` |
+| `deck.overCards` | `hide` (the deck slides away over a card) · `show` · default `hide` | `umtool look <p> deck.overCards=show` |
+| `deck.title` | `{size 24–96, maxChars 10–120}` · default 54, 48 | `umtool look <p> deck.title='{"size":60}'` |
+| `deck.motion` | `{out 0–2, in 0–2, pip 0–3}` s · default 0.3, 0.45, 0.7 | `umtool look <p> deck.motion='{"in":0.6}'` |
+
+### Subtitle
+
+The source line under each clip's title, in the deck.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.subtitle.parts` | `auto` · a list of distinct `channel` `title` `date` `clock` · default `auto` | `umtool look <p> deck.subtitle='{"parts":["channel","date","clock"]}'` |
+| `deck.subtitle.dateFormat` | `long` (24 Oct 2020) · `iso` · default `long` | `umtool look <p> deck.subtitle='{"dateFormat":"iso"}'` |
+
+### QR
+
+Each clip's QR in the deck's source cell. An entry's `citeUrl` wins either way.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.qr.show` | bool · default `true` | `umtool look <p> deck.qr='{"show":false}'` |
+| `deck.qr.size` | 80–380 px, at most the deck's height less 20 · default 150 | `umtool look <p> deck.qr='{"size":130}'` |
+| `deck.qr.links` | `site` (the archive at the clip's start) · `original` (YouTube at the second, a Rumble page, an X post) · default `site` | `umtool look <p> deck.qr='{"links":"original"}'` |
+
+### Rail
+
+The pip track along the top of the deck; the markers' flags stand over it ([markers](#the-cut)).
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.pip.spacing` | `even` · `time` (each pip at its clip's middle) · `pitch` (each `pip.pitch` px after the last, from the left; the pips not yet reached are not drawn, so an insert keeps the frames before it) · default `even` | `umtool look <p> deck.pip='{"spacing":"pitch","pitch":24}'` |
+| `deck.pip.pitch` | 8–200 px · default 28 (only with `spacing: "pitch"`; a cut with more pips than the track holds at it is laid at the pitch that fits) | same |
+| `deck.pip.size`, `deck.pip.activeSize` | 2–24 · 2–40 px, the marker at least the pip · default 6, 12 | `umtool look <p> deck.pip='{"size":8}'` |
+| `deck.pip.color` | `accent` · `verdict` (a counted clip's pip takes its series' colour and shape) · default `accent` | `umtool look <p> deck.pip='{"color":"verdict"}'` |
+
+### Counter
+
+The deck's tally as named series (`render.chrome.deck.counter`). A clip's mark names the series it counts (`claim.verdict`, or its alias `claim.counter`); a deck claim's `tally` names one by id or label. Without `counter` the series are the fact-check verdicts with `factcheck.verdicts`' relabels and `factcheck.tally`'s settings, as ever; `umtool migrate <p>` writes those as a `counter` (the render is the same) and the two are not set together.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.counter.series[]` | 1–8 `{id, label, color?, stampLabel?, tallyLabel?, showAt?, shape?, unit?}` -- an `id` a letter then letters, digits, `_` `-`; a verdict's id (`CORROBORATED` …) takes its default label, colour and shape; `label` ≤ 24 and fitting the cell, as the verdicts' are | `umtool look <p> deck.counter='{"series":[{"id":"seizures","label":"Seizures","color":"#e5534b","stampLabel":"Seizure"}]}'` |
+| `deck.counter.series[].shape` | `circle` `diamond` `square` `triangle` `ring` · default by place (a verdict's own) | same |
+| `deck.counter.series[].unit` | ≤ 24 · the noun a count claim's number reads (default its label, lower-cased) | same |
+| `deck.counter.show`, `.position`, `.showAt` | bool · `right` `left` · `always` `first` (a series' own `showAt` wins) · defaults `true`, `right`, `always` | same |
+| a mark's series | `claim.verdict` (or `claim.counter`): one of the series' ids | `umtool set <p> <clip> mark.add=seizures@190.2` |
+
+### Claim checks
+
+The full reference is [Claim checks on the rail](#claim-checks-on-the-rail). A count claim's `tally` names a counter series by id or label.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.claims[]` | at most 6, each a `count` or a `goalpost` | `umtool look <p> deck.claims='[…]'` (`deck.claims=` none) |
+
+### Teaser
+
+A timeline entry `{ type: "teaser", lines, … }`: a full-frame card whose lines pop in on the beat, cut in as its own segment (deck.mjs `validateTeaser`; [report-video.md](report-video.md)).
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| a `teaser` entry | `lines` (each `{text, role?, hold?, …}`), `tail?`, `dip?` | `umtool timeline <p> insert …` |
+
+### Intro
+
+The brand sting (`render.intro`); the style, mark and site knobs are in [The cut](#the-cut). The brand it draws is configurable; unset, it is the Archilyzer intro, byte for byte.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `render.intro.brand` | a brand kit id (archilyzer-media) · default `archilyzer-media` | `umtool look <p> intro='{"style":"boot","brand":"archilyzer-media"}'` |
+| `render.intro.suffix` | the letters a site's name keeps of the brand's, 1–16 · default `lyzer` (Jeralyzer swaps "Archi" for "Jera") | a take: `--set render.intro.suffix=lyzer` |
+| `render.intro.projectUrl` | the project URL the swap writes beside the site's · `false` none · default `archilyzer.pages.dev` | a take: `--set render.intro.projectUrl=false` |
+
+### Blur
+
+The full reference is [A clip's picture, blurred](#a-clips-picture-blurred).
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `render.blur` | `on` · `off` (the uncensored variant) · default `on` | `umtool look <p> blur=off` |
+| a clip's `blur` | `{on, caption?, strength?, from?, to?}` -- caption ≤ 120, strength 2–15 (default 5) | `umtool set <p> <clip> blur.on=true` |
+
+### Posts feed
+
+`deck.posts.layout: "feed"` with posts to draw: a column for the whole cut, each post ticking in as its clip starts; no hold, no footage move. Shares `deck.posts` with the popup posts.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.posts.layout` | `popup` · `feed` · default `popup` | `umtool look <p> deck.posts='{"layout":"feed"}'` |
+| `deck.posts.width`, `.inset` | 320–900 · 0–80 px · default 600, 24 (the column's width; the footage keeps the inset clear) | same |
+| `deck.posts.links`, `.qr` | `archive` · `original`; bool · default `archive`, `true` | same |
+
+### Popup posts
+
+A clip's posts as cards over the footage (`deck.posts`, the `popup` layout), each window its own short page.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.posts.at` | `end` (the clip's last `seconds` each) · `start` (from the clip's start, sharing it) · default `end` | `umtool look <p> deck.posts='{"at":"start"}'` |
+| `deck.posts.seconds`, `.hold` | 0.5–10 · 0–10 s · default 4, 2.5 (the last frame held so the last card can be read) | same |
+| `deck.posts.position` | `top-right` · `top-left` · default `top-right` | same |
+| `deck.posts.shift` | `false` · `{scale 0.5–1, seconds 0–3}` · default 0.86, 0.6 (the footage moves aside while they are up) | same |
+| `deck.posts.shotMaxHeight` | null · 120–1080 px · default null (a full card of words) | same |
+
+### Stamps
+
+Each counted mark's word stamped over the footage as it lands (`render.chrome.factcheck.stamp`); the word is the mark's `label`, else its series' `stampLabel`, else its label.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `factcheck.stamp.show` | bool · default `true` (`false`: nothing drawn, the counter still counts) | `umtool look <p> factcheck.stamp.show=false` |
+| `factcheck.stamp.seconds` | 1–10 s · default 3 | `umtool look <p> factcheck.stamp.seconds=4` |
+| `factcheck.stamp.position` | `top-left` `top-right` `bottom-left` `bottom-right` `center` · default `top-left` | `umtool look <p> factcheck.stamp.position=center` |
+| `factcheck.stamp.scale`, `.motion`, `.opacity` | 0.5–2 · `slam` `pop` `fade` `none` · 0.3–1 · default 1, `slam`, 1 | `umtool look <p> factcheck.stamp.motion=pop` |
+
+### Stats
+
+A frame scan’s running numbers over the clips that declare them, in a panel in the footage (`render.chrome.stats`, stats.mjs).
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `render.chrome.stats.position` | `top-left` `top-right` `bottom-left` `bottom-right` · default `bottom-left` | manifest |
+| `render.chrome.stats.fields`, `.name` | a list of `stack` `stackBB` `playersLeft` `level`; bool · default all, `true` | manifest |
+
+### Then and now (pair)
+
+Two clips on one subject, each with its date (`render.chrome.pair`, chrome-story.mjs). The footage is not split -- two clips never play at once: "split" is a strip in the footage box, THEN on one side and NOW on the other, the side playing lit, up while either clip plays; "then→now" a card with both dates over the pair's first `seconds`. A pair whose clips the cut does not play is not drawn.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `chrome.pair.pairs[]` | 1–60 `{then: {clip, date?, label?}, now: {clip, date?, label?}, caption? ≤200, topic? ≤60, style?, also?: [{clip, side, date?}]}` -- a date YYYY, YYYY-MM or YYYY-MM-DD; `also` more clips on a side (≤4) | `umtool modules apply <p> --config module-config.json` · `umtool look <p> pair='{…}'` |
+| `chrome.pair.style` | `split` · `then→now` · default `split` (a pair's own `style` wins) | `umtool look <p> pair.style=then→now` |
+| `chrome.pair.position`, `.dateFormat`, `.seconds` | `bottom` `top` · `long` `year` `iso` · 1–10 s · default `bottom`, `long`, 4 | `umtool look <p> pair.position=top` |
+| `chrome.pair.labels` | `{then, now}` ≤16 each · default Then, Now | `umtool look <p> pair.labels='{"then":"2012"}'` |
+
+### Status ledger
+
+A ledger of items, each announced and then followed up -- or not (`render.chrome.status`, chrome-story.mjs): a column in a corner of the footage box that fills as the cut plays. A row comes in on its first clip (its announcement's, else its first evidence clip); its outcome is written on the outcome's clip, else at the end of its last clip. `fill` keeps the last `rows` rows up from the first on; `each` shows a row alone over its own clips.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `chrome.status.items[]` | 1–30 `{item ≤140, announced: words | {clip?, date?, text?}, outcome?: words | {clip?, date?, text?}, evidence?: [clip…]}` -- at least one clip named | `umtool modules apply <p> --config module-config.json` · `umtool look <p> status='{…}'` |
+| `chrome.status.mode` | `fill` · `each` · default `fill` | `umtool look <p> status.mode=each` |
+| `chrome.status.position`, `.rows`, `.width`, `.title` | a corner of the footage box · 1–8 · 360–900 px · ≤40 · default `top-right`, 4, 640, "On the record" | `umtool look <p> status.position=bottom-left` |
+
+### Effects
+
+Overlays on the picture -- receipts, a zoom, the scrubber, a kinetic quote, punch-ins, whip cuts -- (`render.chrome.fx`, fx.mjs); `umtool takes effects <p>` lists the presets.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `render.chrome.fx.<effect>` | scrubber · receipts · zoom · kineticQuote · redact · odometer · punchIn · thenNow · whip · glitch | a take: `umtool take <p> --effect <name>` |
+
+### Thread rail
+
+A card per thread in the side panel beside the footage, lit as its clips play; a thread’s outcome stamped on its last clip (`render.chrome.threads`, threads.mjs).
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `render.chrome.threads.list[]` | `{id, label, outcome?: {verdict, label?}}`; a clip names its thread with `thread` | `umtool look <p> chrome.threads=…` (manifest) |
+
+### Flips
+
+Then-and-now pairs in the side panel (`render.chrome.flips`, flips.mjs); the thread rail and the flips share the panel: one or the other.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `render.chrome.flips` | see flips.mjs | manifest |
+
+### Chapters
+
+A section bumper -- per dog, per crisis, per lawsuit -- over the first `seconds` of the clip it opens (`render.chrome.chapter`, chrome-story.mjs): a window of the cut laid at its own second, over the footage box (the deck stays). It does not insert time: the clip's sound plays under it.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `chrome.chapter.list[]` | 1–40 `{at, title ≤48, subtitle? ≤90, date?}` -- `at` the clip it opens, once each | `umtool modules apply <p> --config module-config.json` · `umtool look <p> chapter='{…}'` |
+| `chrome.chapter.style` | `card` (the footage box covered) · `lower` (a band at its foot) · default `card` | `umtool look <p> chapter.style=lower` |
+| `chrome.chapter.seconds` | 1–8 s, never past the clip · default 3 | `umtool look <p> chapter.seconds=2.5` |
+
+### Finale
+
+The full reference is [The finale](#the-finale-the-timeline-in-primary-view). It reads the counter's totals (`counter.totals`) and the rail's layout (`rail.layout`); the counter reads its window (`finale.window`): a mark that would stamp inside it counts as it opens.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| `deck.finale` | `{video, motion, totals, stats, statsTitle, railLabels, pips, timelineShare, claims}` | `umtool look <p> deck.finale='{…}'` |
+| a clip's `layout` | `finale` on one run of clips at the end | `umtool set <p> <clip> layout=finale` |
+
+<!-- modules:end -->
diff --git a/umtool/docs/quirks.md b/umtool/docs/quirks.md
@@ -389,7 +389,11 @@ compose-chrome, and the posts windows' frame arithmetic it needs
not a wall around the page modules: umtool's preview helper
(`lib/report/onscreen.mjs`) imports compose-chrome statically, as it did before
posts, and its routes build. A capped umtool build is the gate that catches it — the unit
-tests run in plain Node and pass either way.
+tests run in plain Node and pass either way. Since release 39 the module registry
+(`modules/index.mjs`, which build-video imports) brings every page module into that chain, so
+the deck's GSAP and the effects' mono face go through `assetFile` (chrome-deck.mjs): the
+bundler's asset URL is kept as its string where `fileURLToPath` refuses it, instead of failing
+the module load.
**A teaser's page module is reached by a dynamic import from compose-chrome
too.** `chrome-teaser.mjs` carries the display face as `new URL(…,
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -951,6 +951,17 @@ pruning them, where a `--from` twin finds them. The blur is in the segments' pic
twin rebuilds the blurred clips, their crossfade batches and the final overlay pass, and reuses
the rest.
+A layer whose page changed reuses its frames FRAME BY FRAME (report-to-video `frame-keys.mjs`, each
+module's `frameKeys`: the deck, the stamps, the feed, the finale, the thread rail, the flips, the
+stats, the effects and a teaser): every frame's key is the page's static part and what is on screen
+at that frame, and only the frames with a new key are captured. Since the video modules (release 39)
+the static part is minimal: an asset counts by its bytes, not by the `qrNN`/`shotNN` name its place
+gives it, and a page's ITEMS -- each clip's deck text, each pip, each feed card -- count only in the
+frames that show them. So a changed subtitle recaptures the frames its clip's text is up, a post
+changed or added recaptures from its moment on, and with the rail at a fixed pitch
+(`deck.pip.spacing: "pitch"`) a clip appended keeps every frame before the marker reaches the clip
+before it. A render keyed before then (frame-key version 1) is captured once more, then reused.
+
`--quick` (a recipe's or a take's `quick: true`) is that quick render. A take that exists is skipped unless forced (**make it again if it exists**, `--force`).
**Rebuild** on a card (`--rebuild`) makes it again from its own take.json against the project's
manifest as it is now. A recipe is `{ group, window, quick?, takes: [{ id, label, style?, patch?,
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -40,6 +40,7 @@ import { makeRunTraceFixture } from "./run-trace-fixture.mjs";
import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs";
import { makeVideoAssistFixture } from "./video-assist-fixture.mjs";
import { makeKnobsFixture } from "./knobs-fixture.mjs";
+import { makeModulesFixture } from "./modules-fixture.mjs";
import { makeMarksFixture } from "./marks-fixture.mjs";
import { makeLivePreviewFixture } from "./live-preview-fixture.mjs";
import { makePlayCutFixture } from "./play-cut-fixture.mjs";
@@ -1856,6 +1857,8 @@ makeClipsSuggestFixture({ reports, manifest, cachedWindow: path.join(REPORT, "ou
makeVideoAssistFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
// Video knobs (plans/video-knobs-ui.md): Count & stamp, Audio, Make variants, Sync and the Markers editor (knobs.spec.ts).
makeKnobsFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// Release 39, the video modules: the generic module panel, the single-layer preview, the look presets (modules.spec.ts).
+makeModulesFixture({ reports, manifest, deckManifest });
// Marks (plans/clip-marks.md): the clip editor's Marks box -- add at the playhead, verdict, Shift+S/M, remove (marks.spec.ts).
makeMarksFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
// The clip editor's live preview and Render this clip (plans/live-preview.md, live-preview.spec.ts).
diff --git a/umtool/e2e/fixtures/modules-fixture.mjs b/umtool/e2e/fixtures/modules-fixture.mjs
@@ -0,0 +1,49 @@
+// What modules.spec.ts edits (release 39, the video modules):
+//
+// modules-fixture the deck on (make-fixture.mjs deckManifest), three
+// clips, a then-and-now pair (c01 → c02) and a status
+// ledger row -- the generic module panel: on/off,
+// a list editor, a refused save, the single-layer
+// preview (pair, chapter)
+// modules-preset-fixture NO chrome of its own, a module-config.json beside
+// it -- the look preset (the panel's list and
+// `umtool preset apply`) and `umtool modules apply`
+//
+// Synthetic, like every fixture.
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const clip = (id, start) => ({ type: "clip", id, video: "vid1", start, end: start + 3, cite: start, section: 0, lock: true, quote: "and because" });
+
+/** @param {{ reports: string, manifest: Function, deckManifest: Function }} o */
+export function makeModulesFixture({ reports, manifest, deckManifest }) {
+ const dir = path.join(reports, "modules-fixture");
+ mkdirSync(dir, { recursive: true });
+ const m = deckManifest("modules-fixture", "The Modules Fixture", [clip("c01", 3), clip("c02", 9), clip("c03", 0)]);
+ m.render.chrome = {
+ ...m.render.chrome,
+ pair: { pairs: [{ topic: "The opening", then: { clip: "c01", date: "2012-09-29" }, now: { clip: "c02", date: "2026-02-27" }, caption: "The same opening, renamed." }] },
+ status: { items: [{ item: "The lawsuit", announced: { clip: "c01", date: "2019-06-01" }, outcome: "no follow-up found", evidence: ["c01", "c03"] }] },
+ };
+ writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+
+ const pdir = path.join(reports, "modules-preset-fixture");
+ mkdirSync(pdir, { recursive: true });
+ const p = manifest("modules-preset-fixture", "The Modules Preset Fixture", { siteOrigin: "https://archive.example" }, [clip("c01", 3), clip("c02", 9)]);
+ // A deck's size, as deckManifest gives it, but no chrome: the preset brings the deck.
+ p.render = { ...p.render, width: 1920, height: 1080 };
+ delete p.render.headerHeight;
+ writeFileSync(path.join(pdir, "video.manifest.json"), JSON.stringify(p, null, 2) + "\n");
+ writeFileSync(
+ path.join(pdir, "module-config.json"),
+ JSON.stringify({
+ preset: "plain-deck",
+ modules: {
+ shell: { title: "Not mapped" },
+ chapter: [{ atClip: "c02", title: "Part two", subtitle: "the second clip" }],
+ pair: [{ then: { clip: "c01", date: "2012" }, now: { clip: "c02", date: "2026-02" }, caption: "then and now" }],
+ },
+ }, null, 2) + "\n",
+ );
+ return { dir, pdir };
+}
diff --git a/umtool/e2e/modules.spec.ts b/umtool/e2e/modules.spec.ts
@@ -0,0 +1,219 @@
+import { test, expect, type APIRequestContext, type Page } from "@playwright/test";
+import { execFileSync, spawnSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// THE VIDEO MODULES (release 39): the generic module panel in the Media tab
+// (components/projects/ModulesPanel.tsx), drawn from each module's `ui`
+// descriptor and writing through the writers (PUT /api/report/modules); the
+// single-layer preview (POST /api/report/chrome/preview { layers }); the look
+// presets (the panel's list, `umtool preset apply`) and `umtool modules
+// apply` (a module-config.json onto the cut).
+//
+// modules-fixture the deck on, three clips, a pair and a status row
+// modules-preset-fixture no chrome of its own, a module-config.json beside it
+//
+// The deck refuses to draw without its faces: the preview test skips on a
+// machine make-fixture.mjs found no font on, as onscreen.spec.ts does.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const UMTOOL = path.join(HERE, "..");
+const FIXTURE = path.join(UMTOOL, ".e2e-song");
+const PROJECT = "reports/modules-fixture";
+const DIR = path.join(FIXTURE, "reports", "modules-fixture");
+const PRESET_PROJECT = "reports/modules-preset-fixture";
+const PRESET_DIR = path.join(FIXTURE, "reports", "modules-preset-fixture");
+const enc = encodeURIComponent;
+
+const cliEnv = {
+ ...process.env,
+ SONG_REPORTS_DIR: path.join(FIXTURE, "reports"),
+ SONG_DIR: path.join(FIXTURE, "data"),
+ CHANNELS_DIR: path.join(FIXTURE, "channels"),
+ UMTOOL_CACHE_DIR: path.join(FIXTURE, "cache"),
+ UMTOOL_MEDIA_DIR: "",
+};
+const umtool = (args: string[]) => spawnSync("node", ["bin/umtool.mjs", ...args], { cwd: UMTOOL, encoding: "utf8", env: cliEnv });
+
+type Manifest = { preset?: string; render: Record<string, any>; timeline: { id: string; claim?: unknown }[] };
+const readManifest = (dir = DIR): Manifest => JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8"));
+
+async function modulesState(request: APIRequestContext, project = PROJECT) {
+ const r = await request.get(`/api/report/modules?project=${enc(project)}`);
+ expect(r.ok(), await r.text()).toBeTruthy();
+ return (await r.json()) as { token: string; preset: string | null; presets: { name: string }[]; modules: { id: string; enabled: boolean; fields: Record<string, unknown>; effective: Record<string, unknown>; problems: string[] }[] };
+}
+
+async function putModule(request: APIRequestContext, body: Record<string, unknown>, project = PROJECT) {
+ const { token } = await modulesState(request, project);
+ return request.put("/api/report/modules", { data: { project, token, ...body } });
+}
+
+async function openPanel(page: Page, project = PROJECT) {
+ await page.goto(urls.section(project, "onscreen"));
+ const panel = page.getByTestId("modules-panel");
+ await expect(panel.getByTestId("module-pair")).toBeAttached({ timeout: 60_000 });
+ return panel;
+}
+
+async function openModule(page: Page, id: string) {
+ const card = page.getByTestId(`module-${id}`);
+ await card.locator("summary").click();
+ await expect(card).toHaveAttribute("open", "");
+ return card;
+}
+
+// workers: 1, not fully parallel (playwright.config.ts): the tests run in
+// file order, and the later ones start from the state the earlier leave.
+
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+});
+
+test("the panel draws every module from its descriptor, and a module is switched on, filled and off through the writers", async ({ page, request }) => {
+ // From a known state: no chapters.
+ expect((await putModule(request, { module: "chapter", enabled: false })).ok() || true).toBeTruthy();
+ const panel = await openPanel(page);
+ for (const id of ["pair", "chapter", "status", "finale", "intro", "counter", "shell", "rail", "stamp"]) {
+ await expect(panel.getByTestId(`module-${id}`)).toBeAttached();
+ }
+ await expect(panel.getByTestId("module-state-chapter")).toHaveText("off");
+ await expect(panel.getByTestId("module-state-pair")).toHaveText("on");
+
+ const card = await openModule(page, "chapter");
+ // A controlled box: it turns when the write lands and the panel re-reads, so click, then wait.
+ await card.getByTestId("module-toggle-chapter").click();
+ await expect(panel.getByTestId("module-state-chapter")).toHaveText("on");
+ await expect.poll(() => readManifest().render.chrome.chapter).toEqual({ list: [] });
+
+ // A row of the list editor, its clip from the cut's clips, saved.
+ await card.getByTestId("module-field-chapter-list-add").click();
+ await card.getByTestId("module-field-chapter-list-0-at").fill("c02");
+ await card.getByTestId("module-field-chapter-list-0-title").fill("Part two");
+ await card.getByTestId("module-field-chapter-list-0-date").fill("2020-10");
+ await card.getByTestId("module-save-chapter").click();
+ await expect(card.getByTestId("module-status-chapter")).toHaveText("saved");
+ await expect.poll(() => readManifest().render.chrome.chapter).toEqual({ list: [{ at: "c02", title: "Part two", date: "2020-10" }] });
+
+ // A scalar field: the pair strip to the top.
+ const pair = await openModule(page, "pair");
+ await pair.getByTestId("module-field-pair-position").selectOption("top");
+ await pair.getByTestId("module-save-pair").click();
+ await expect(pair.getByTestId("module-status-pair")).toHaveText("saved");
+ await expect.poll(() => readManifest().render.chrome.pair.position).toBe("top");
+ // The rest of the pair as it was.
+ expect(readManifest().render.chrome.pair.pairs[0].then.clip).toBe("c01");
+
+ // Off: the object removed, nothing else of the deck moved.
+ await card.getByTestId("module-toggle-chapter").click();
+ await expect(panel.getByTestId("module-state-chapter")).toHaveText("off");
+ await expect.poll(() => "chapter" in readManifest().render.chrome).toBe(false);
+ expect(readManifest().render.chrome.layout).toBe("deck");
+});
+
+test("a save the build would refuse is refused with the build's sentence, and the manifest is untouched", async ({ page }) => {
+ const before = JSON.stringify(readManifest().render.chrome.status);
+ await openPanel(page);
+ const card = await openModule(page, "status");
+ await card.getByTestId("module-field-status-rows").fill("12");
+ await card.getByTestId("module-save-status").click();
+ await expect(card.getByTestId("module-errors-status")).toContainText("render.chrome.status.rows");
+ expect(JSON.stringify(readManifest().render.chrome.status)).toBe(before);
+});
+
+test("a chapter at a clip the cut does not hold is refused by the writer", async ({ request }) => {
+ const r = await putModule(request, { module: "chapter", fields: { list: [{ at: "nope", title: "Gone" }] } });
+ expect(r.status()).toBe(400);
+ expect(JSON.stringify(await r.json())).toContain("no timeline entry is nope");
+ const off = await putModule(request, { module: "chapter", enabled: false });
+ expect(off.ok() || off.status() === 400).toBeTruthy();
+});
+
+test("Preview alone composes one module's page by itself; the files route serves it", async ({ page, request }) => {
+ test.skip(!readManifest().render.fontRegular, "the deck refuses to draw without its faces, and make-fixture.mjs found no font on this machine");
+ // The route: a whole-cut layer (pair) and a window layer (chapter), alone.
+ expect((await putModule(request, { module: "chapter", enabled: true, fields: { list: [{ at: "c02", title: "Part two" }] } })).ok()).toBeTruthy();
+ const res = await request.post("/api/report/chrome/preview", { data: { project: PROJECT, layers: ["pair", "chapter", "subtitle", "threads"] } });
+ expect(res.ok(), await res.text()).toBeTruthy();
+ const j = (await res.json()) as { layers: { id: string; region?: string; src?: string; off?: string; windows?: { segment: string; src?: string }[] }[] };
+ const by = Object.fromEntries(j.layers.map((l) => [l.id, l]));
+ expect(by.pair.src).toContain("pair-preview/index.html");
+ expect(by.chapter.windows?.[0]?.segment).toBe("c02");
+ expect(by.chapter.windows?.[0]?.src).toContain("chapter-preview-c02/index.html");
+ expect(by.subtitle.region).toBe("deck");
+ expect(by.threads.off).toBeTruthy();
+ const html = await (await request.get(by.pair.src!)).text();
+ expect(html).toContain('id="pair-data"');
+ expect(html).toContain("The same opening, renamed.");
+ expect(html).not.toContain('id="deck-data"');
+ // A window page another cut's entry names is not served.
+ expect((await request.get(by.pair.src!.replace("pair-preview/", "chapter-preview-zz/"))).status()).toBe(404);
+
+ // The panel's button: the module's own iframe over a scaled frame.
+ await openPanel(page);
+ const card = await openModule(page, "pair");
+ await card.getByTestId("module-preview-pair").click();
+ await expect(card.getByTestId("module-preview-iframe")).toHaveAttribute("src", /pair-preview\/index\.html/);
+ await expect(card.getByTestId("module-preview-scrub")).toBeVisible();
+ await putModule(request, { module: "chapter", enabled: false });
+});
+
+test("a look preset is the layer under the manifest: named from the panel, read through, removed from a terminal", async ({ page, request }) => {
+ const r0 = umtool(["preset", "apply", "none", PRESET_PROJECT]);
+ expect(r0.status, r0.stderr).toBe(0);
+ const s0 = await modulesState(request, PRESET_PROJECT);
+ expect(s0.presets.map((p) => p.name)).toEqual(expect.arrayContaining(["huck-deck", "plain-deck", "archive-catalog"]));
+ expect(s0.modules.find((m) => m.id === "intro")!.enabled).toBe(false);
+
+ await openPanel(page, PRESET_PROJECT);
+ await page.getByTestId("modules-preset").selectOption("plain-deck");
+ await expect(page.getByTestId("modules-preset-status")).toContainText("plain-deck");
+ await expect.poll(() => readManifest(PRESET_DIR).preset).toBe("plain-deck");
+ // Nothing of the preset copied in: the manifest's render is as it was.
+ expect(readManifest(PRESET_DIR).render.chrome).toBeUndefined();
+ // Read through: the intro and the deck are the preset's, as the build reads them.
+ const s1 = await modulesState(request, PRESET_PROJECT);
+ expect(s1.modules.find((m) => m.id === "intro")!.enabled).toBe(true);
+ expect(s1.modules.find((m) => m.id === "intro")!.effective.style).toBe("boot-dark");
+ expect(s1.modules.find((m) => m.id === "subtitle")!.effective.parts).toEqual(["channel", "title", "date", "clock"]);
+ // A chrome save over the preset is whole: the writer reads the deck from it.
+ expect((await putModule(request, { module: "pair", enabled: true }, PRESET_PROJECT)).ok()).toBeTruthy();
+ expect(readManifest(PRESET_DIR).render.chrome).toEqual({ pair: { pairs: [] } });
+
+ const r1 = umtool(["preset", "list", "--json"]);
+ expect(JSON.parse(r1.stdout).map((p: { name: string }) => p.name)).toContain("archive-catalog");
+ const bad = umtool(["preset", "apply", "no-such-preset", PRESET_PROJECT]);
+ expect(bad.status).toBe(1);
+ expect(bad.stderr).toContain('no preset "no-such-preset"');
+ // Removed: the chrome named only what it changed from the preset, so the cut
+ // over no preset would not build -- refused, the preset kept.
+ const r2 = umtool(["preset", "apply", "none", PRESET_PROJECT]);
+ expect(r2.status).toBe(1);
+ expect(readManifest(PRESET_DIR).preset).toBe("plain-deck");
+ expect((await putModule(request, { module: "pair", enabled: false }, PRESET_PROJECT)).ok()).toBeTruthy();
+ const r3 = umtool(["preset", "apply", "none", PRESET_PROJECT]);
+ expect(r3.status, r3.stderr).toBe(0);
+ expect(readManifest(PRESET_DIR).preset).toBeUndefined();
+});
+
+test("umtool modules apply maps a module-config.json onto the cut, listing what has no home", async () => {
+ const dry = umtool(["modules", "apply", PRESET_PROJECT, "--dry-run", "--json"]);
+ expect(dry.status, dry.stderr).toBe(0);
+ const plan = JSON.parse(dry.stdout);
+ expect(plan.patch.preset).toBe("plain-deck");
+ expect(plan.patch.render.chrome.chapter.list[0]).toEqual({ at: "c02", title: "Part two", subtitle: "the second clip" });
+ expect(plan.unmapped.some((u: string) => u.startsWith("modules.shell.title"))).toBe(true);
+ expect(readManifest(PRESET_DIR).preset).toBeUndefined();
+
+ const run = umtool(["modules", "apply", PRESET_PROJECT]);
+ expect(run.status, run.stderr).toBe(0);
+ const m = readManifest(PRESET_DIR);
+ expect(m.preset).toBe("plain-deck");
+ expect(m.render.chrome.pair.pairs[0].now).toEqual({ clip: "c02", date: "2026-02" });
+ // Back as it was, through the same writers.
+ execFileSync("node", ["bin/umtool.mjs", "preset", "apply", "plain-deck", PRESET_PROJECT], { cwd: UMTOOL, env: cliEnv });
+});
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -210,7 +210,9 @@ function knobDefaultsOf(render) {
const given = isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {};
const labels = {};
for (const [v, x] of Object.entries(fc.verdicts)) {
- const own = isObj(given[v]) && typeof given[v].stampLabel === "string" && given[v].stampLabel.trim() ? given[v].stampLabel.trim() : null;
+ // A counter series carries its stamp word itself (report-to-video counter.mjs).
+ const own = isObj(given[v]) && typeof given[v].stampLabel === "string" && given[v].stampLabel.trim() ? given[v].stampLabel.trim()
+ : typeof x.stampLabel === "string" && x.stampLabel.trim() ? x.stampLabel.trim() : null;
labels[v] = own ?? x.label;
}
return { hold: fc.stamp.seconds, stampShown: fc.stamp.show !== false, count: CLAIM_KNOB_DEFAULTS.count, labels };
diff --git a/umtool/lib/report/knobs.mjs b/umtool/lib/report/knobs.mjs
@@ -20,6 +20,7 @@
import {
CLAIM_KEYS, CLAIM_LIMITS, CLAIM_MARKS_MAX, FACTCHECK_DEFAULTS, FACTCHECK_LIMITS, STAMP_MOTIONS, VERDICTS, rawMarksOf, resolveFactcheck,
} from "umtool-report-to-video/factcheck";
+import { resolveCounter } from "umtool-report-to-video/counter";
import { MARKER_ALIGNS, MARKER_LAYOUTS } from "umtool-report-to-video/deck";
import { isIsoDate } from "umtool-report-to-video/claims";
import { DEFAULT_VARIANTS, validateVariants, variantsOf } from "umtool-report-to-video/variants";
@@ -217,16 +218,22 @@ export function freshMarkId(manifest, entryId) {
*/
export function verdictOfInput(v, render) {
const s = typeof v === "string" ? v.trim() : "";
+ // The counter's series (report-to-video counter.mjs): the verdicts with
+ // their relabels, or a `deck.counter`'s named series -- by id or by word.
+ const counter = resolveCounter(render);
+ const ids = counter.order;
+ if (ids.includes(s)) return s;
const upper = s.toUpperCase().replace(/[\s-]+/g, "_");
- if (VERDICTS.includes(upper)) return upper;
- const fc = resolveFactcheck(render);
- const given = isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {};
- for (const V of VERDICTS) {
- const words = [fc.verdicts[V]?.label, isObj(given[V]) ? given[V].stampLabel : null].filter((x) => typeof x === "string");
+ if (ids.includes(upper)) return upper;
+ const byLower = ids.find((id) => id.toLowerCase() === s.toLowerCase());
+ if (byLower) return byLower;
+ for (const V of ids) {
+ const x = counter.byId[V] ?? {};
+ const words = [x.label, x.stampLabel].filter((w) => typeof w === "string");
if (words.some((w) => w.trim().toLowerCase() === s.toLowerCase())) return V;
}
- const names = VERDICTS.map((V) => (fc.verdicts[V]?.label && fc.verdicts[V].label !== V ? `${V} (${fc.verdicts[V].label})` : V));
- throw new Error(`${q(v)} is not a verdict: ${names.join(", ")}`);
+ const names = ids.map((V) => (counter.byId[V]?.label && counter.byId[V].label !== V ? `${V} (${counter.byId[V].label})` : V));
+ throw new Error(`${q(v)} is not a ${counter.custom ? "counter series" : "verdict"}: ${names.join(", ")}`);
}
/**
@@ -238,15 +245,17 @@ export function verdictOfInput(v, render) {
*/
export function markVerdictsOf(manifest) {
const render = manifest?.render;
- const fc = resolveFactcheck(render);
- const given = isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {};
+ const counter = resolveCounter(render);
+ // A counter's series are all the cut's own; the verdicts', the relabelled.
+ const given = counter.custom ? counter.byId : isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {};
const used = new Set();
for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
for (const m of rawMarksOf(e)) if (isObj(m) && typeof m.verdict === "string") used.add(m.verdict);
}
- const all = VERDICTS.map((V) => {
+ const all = counter.order.map((V) => {
const own = isObj(given[V]) && typeof given[V].stampLabel === "string" && given[V].stampLabel.trim() ? given[V].stampLabel.trim() : null;
- return { verdict: V, label: fc.verdicts[V].label, stampLabel: own ?? fc.verdicts[V].label, color: fc.verdicts[V].color, stock: V in given || used.has(V) };
+ const x = counter.byId[V];
+ return { verdict: V, label: x.label, stampLabel: own ?? x.label, color: x.color, stock: V in given || used.has(V) };
});
return [...all.filter((x) => x.stock), ...all.filter((x) => !x.stock)];
}
diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs
@@ -28,6 +28,7 @@ import {
LOOK_KEYS,
manifestToken,
updateClaimKnobs,
+ updateChrome,
updateClip,
updateDeckKeys,
updateFactcheck,
@@ -74,6 +75,8 @@ export const LOOK_USAGE = [
" factcheck.tally.showAt.<VERDICT>=first for one cell) .show .position (right|left)",
" deck.markers='[{\"after\":\"c01\",\"label\":\"Arrival\",\"align\":\"left\"}]' deck.markerLayout=stagger|truncate",
" deck.<key>=<json>: any of the deck's own keys (deck.finale='{…}', deck.pip='{…}', …), checked by the build's rules",
+ " pair=<json> | pair.<key>=…, chapter=<json> | chapter.<key>=…, status=<json> | status.<key>=…: the story modules",
+ " (render.chrome.pair / .chapter / .status, docs/knobs.md \"Modules\"), checked by the build's rules",
" variants='[{\"name\":\"master\"},{\"name\":\"720p\",\"height\":720,\"crf\":23},{\"name\":\"fit24\",\"maxMiB\":24}]'",
` the look: ${LOOK_KEYS.join(", ")} (a JSON value each)`,
" `key=` clears it (the default).",
@@ -310,7 +313,11 @@ export async function lookCommand(args, { root = REPORTS_ROOT, out = (s) => cons
const deck = pairs.filter(([k]) => k.startsWith("deck."));
const variants = pairs.filter(([k]) => k === "variants");
const look = pairs.filter(([k]) => LOOK_KEYS.includes(k));
- const unknown = pairs.filter(([k]) => !k.startsWith("factcheck.") && !k.startsWith("deck.") && k !== "variants" && !LOOK_KEYS.includes(k));
+ // The story modules (release 39): `pair=<json>`, `pair.style=…`, likewise chapter and status.
+ const STORY = ["pair", "chapter", "status"];
+ const isStory = (k) => STORY.includes(k.split(".")[0]);
+ const story = pairs.filter(([k]) => isStory(k));
+ const unknown = pairs.filter(([k]) => !k.startsWith("factcheck.") && !k.startsWith("deck.") && k !== "variants" && !LOOK_KEYS.includes(k) && !isStory(k));
if (unknown.length) throw new CliError(`not a knob here: ${unknown.map(([k]) => k).join(", ")}\n\n${LOOK_USAGE}`);
for (const [k] of deck) if (k.split(".").length !== 2 || !k.split(".")[1]) throw new CliError(`${k}: name one of the deck's own keys (deck.<key>=<json>)`);
const done = {};
@@ -334,6 +341,13 @@ export async function lookCommand(args, { root = REPORTS_ROOT, out = (s) => cons
const r = await write((token) => updateDeckKeys(project.dir, patch, { token }));
for (const k of Object.keys(patch)) done[`deck.${k}`] = r.deck[k] ?? null;
}
+ if (story.length) {
+ const m = await readManifest(project.dir);
+ let chrome = m?.render?.chrome ?? {};
+ for (const [k, v] of story) chrome = setPath(chrome, k.split("."), v);
+ const r = await write((token) => updateChrome(project.dir, chrome, { token }));
+ for (const k of new Set(story.map(([k]) => k.split(".")[0]))) done[k] = r.chrome?.[k] ?? null;
+ }
if (variants.length) {
const r = await write((token) => updateVariants(project.dir, variants[0][1], { token }));
done.variants = r.variants;
diff --git a/umtool/lib/report/layerPreview.test.mjs b/umtool/lib/report/layerPreview.test.mjs
@@ -0,0 +1,53 @@
+// The module panel's single-layer preview: composeLayerPreviews (onscreen.mjs)
+// and the files route's layer names (serve.mjs layerPreviewOf).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import path from "node:path";
+
+import { composeLayerPreviews } from "./onscreen.mjs";
+import { layerPreviewOf, layerPreviewSrc, previewDirFor } from "./serve.mjs";
+
+const palette = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#ff0000" };
+const render = {
+ width: 1920, height: 1080, fps: 30, palette,
+ chrome: {
+ engine: "hyperframes", layout: "deck",
+ pair: { pairs: [{ then: { clip: "a", date: "2012" }, now: { clip: "b", date: "2026" } }] },
+ chapter: { list: [{ at: "b", title: "Two" }] },
+ },
+};
+const schedule = {
+ kind: "deck", fps: 30, total: 20, transition: 0.5,
+ segments: [["a", 0, 10], ["b", 10, 20]].map(([id, start, end]) => ({ id, type: "clip", start, end, duration: end - start })),
+};
+
+test("each layer composed alone: a whole page once, a window page per window, a part as the deck's, an absent one off", async () => {
+ const calls = [];
+ const compose = async (args) => {
+ calls.push(args);
+ const name = args.region === "chapter" ? `chapter-preview-${args.segment}` : `${args.region}-preview`;
+ return { projDir: path.join("/p/out/sourced/chrome", name) };
+ };
+ const out = await composeLayerPreviews({ dir: "/p", manifestFile: "/p/video.manifest.json" }, "sourced", schedule, ["pair", "chapter", "counter", "status", "nope"], render, { compose });
+ const by = Object.fromEntries(out.map((l) => [l.id, l]));
+ assert.equal(by.pair.name, "pair-preview");
+ assert.equal(by.pair.geometry.width > 0, true);
+ assert.deepEqual(by.chapter.windows.map((w) => [w.segment, w.from, w.name]), [["b", 10, "chapter-preview-b"]]);
+ assert.equal(by.counter.region, "deck");
+ assert.match(by.status.off, /status/);
+ assert.match(by.nope.error, /no module/);
+ assert.deepEqual(calls.map((c) => [c.region, c.preview, c.segment ?? null]), [["pair", true, null], ["chapter", true, "b"]]);
+ assert.ok(calls.every((c) => c.schedule === schedule && c.manifestPath === "/p/video.manifest.json"));
+});
+
+test("the files route serves a layer's project by its name, a window's only for the cut's own entry", () => {
+ assert.equal(layerPreviewOf("pair-preview"), "pair-preview");
+ assert.equal(layerPreviewOf("chapter-preview-b", ["a", "b"]), "chapter-preview-b");
+ assert.equal(layerPreviewOf("chapter-preview-zz", ["a", "b"]), null);
+ assert.equal(layerPreviewOf("chapter-preview-..", [".."]), null);
+ assert.equal(layerPreviewOf("deck-preview"), null);
+ assert.deepEqual(previewDirFor("/p", "sourced", ["status-preview", "index.html"], []), { dir: "/p/out/sourced/chrome/status-preview", rest: ["index.html"] });
+ // The deck's own preview, as it always was.
+ assert.equal(previewDirFor("/p", "sourced", ["index.html"], []).dir, "/p/out/sourced/chrome/deck-preview");
+ assert.equal(layerPreviewSrc("reports/x", "sourced", "pair-preview"), "/api/report/chrome/files/" + layerPreviewSrc("reports/x", "sourced", "pair-preview").split("/api/report/chrome/files/")[1]);
+});
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -41,6 +41,10 @@ import { validateRoom } from "umtool-report-to-video/room";
import { applySectionEnter } from "./sections.mjs";
import { parseClipSpec } from "./clipEditorModel.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
+import { migrateManifest } from "umtool-report-to-video/modules/migrate";
+import { loadPreset, resolvePresetLayers } from "umtool-report-to-video/presets";
+import { storyClipErrors } from "umtool-report-to-video/modules/story-settings";
+import { counterOrder } from "umtool-report-to-video/counter";
import { validateFinaleEntries } from "umtool-report-to-video/finale";
import { validateClipAudio } from "umtool-report-to-video/clip-audio";
import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH, validateClipBlur, validateClipBlurEntries } from "umtool-report-to-video/clip-blur";
@@ -914,7 +918,7 @@ function setOnscreen(entry, value) {
* @param {unknown} row
* @returns {{ onscreen: { title?: string, subtitle?: string } | null, claim?: Claim | null }}
*/
-export function splitOnscreenRow(row) {
+export function splitOnscreenRow(row, { series = null } = {}) {
if (row === null || row === undefined || typeof row !== "object" || Array.isArray(row) || !("claim" in row)) {
return { onscreen: normalizeOnscreen(row) };
}
@@ -932,10 +936,10 @@ export function splitOnscreenRow(row) {
delete base[k];
if (v !== null && !(k === "stamp" && v === true) && !(k === "count" && v === 1)) knobs[k] = v;
}
- const c = normalizeClaim(base);
+ const c = normalizeClaim(base, { series });
return { onscreen: normalizeOnscreen(text), claim: c ? { ...c, ...knobs } : c, knobs: true };
}
- return { onscreen: normalizeOnscreen(text), claim: normalizeClaim(claim) };
+ return { onscreen: normalizeOnscreen(text), claim: normalizeClaim(claim, { series }) };
}
/**
@@ -968,7 +972,9 @@ export async function updateOnscreen(dir, onscreen, { token = null } = {}) {
const ids = Object.keys(onscreen);
if (!ids.length) throw new Error("nothing to change");
// Normalised BEFORE the lock: a bad value is the caller's error whatever the
- // file says, and refusing it needs no read.
+ // file says. The one thing it reads is the counter's series (a mark names
+ // one of them: the verdicts, unless the cut counts its own).
+ const series = counterOrder(await readFile(manifestFile(dir), "utf8").then((t) => JSON.parse(t).render, () => null));
/** @type {Record<string, { title?: string, subtitle?: string } | null>} */
const next = {};
/** @type {Record<string, Claim | null>} */
@@ -977,7 +983,7 @@ export async function updateOnscreen(dir, onscreen, { token = null } = {}) {
const withKnobs = new Set();
for (const id of ids) {
try {
- const row = splitOnscreenRow(onscreen[id]);
+ const row = splitOnscreenRow(onscreen[id], { series });
next[id] = row.onscreen;
if (row.claim !== undefined) claims[id] = row.claim;
if (row.knobs) withKnobs.add(id);
@@ -1053,12 +1059,18 @@ export async function updateChrome(dir, chrome, { token = null } = {}) {
if (chrome === null) {
if (manifest.render) delete manifest.render.chrome;
} else {
- const errors = validateChrome(chrome, renderWithoutChrome);
- if (errors.length) throw new ChromeRefused(errors);
manifest.render = { ...(manifest.render ?? {}), chrome };
+ // Checked as the build will read it: over its look preset when it
+ // names one (presets.mjs), so a chrome that names only what it
+ // changes from the preset is whole.
+ const seen = effectiveManifest(manifest);
+ const { chrome: seenChrome, ...seenRest } = seen.render ?? {};
+ const errors = validateChrome(seenChrome, seenRest);
+ if (errors.length) throw new ChromeRefused(errors);
// The deck's markers against the timeline: each follows a clip in it.
- // Its claim checks likewise: each is said in a clip in it.
- const markers = [...validateDeckMarkers(manifest), ...validateDeckClaims(manifest)];
+ // Its claim checks likewise: each is said in a clip in it. The story
+ // modules' clips (pair, chapter, status) likewise.
+ const markers = [...validateDeckMarkers(seen), ...validateDeckClaims(seen), ...storyClipErrors(seen)];
if (markers.length) throw new ChromeRefused(markers);
}
@@ -1067,6 +1079,41 @@ export async function updateChrome(dir, chrome, { token = null } = {}) {
});
}
+/** The manifest as the build reads it: its look preset laid under it (presets.mjs), or itself. */
+export function effectiveManifest(manifest) {
+ return manifest?.preset ? resolvePresetLayers(manifest) : manifest;
+}
+
+/**
+ * Name, change or remove the cut's look preset (`preset`, presets.mjs): the
+ * base layer the build lays under its render block. `null` removes it. The
+ * preset must exist, and the cut over it must build: its chrome checked as
+ * updateChrome checks it. Nothing of the preset is copied into the manifest.
+ *
+ * @param {string} dir
+ * @param {string | null} name
+ * @param {{ token?: string | null }} [opts]
+ * @returns {Promise<{ preset: string | null, token: string | null }>}
+ */
+export async function updatePreset(dir, name, { token = null } = {}) {
+ if (name !== null) loadPreset(name);
+ return withManifestLock(async () => {
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ if (name === null) delete manifest.preset;
+ else manifest.preset = name;
+ const seen = effectiveManifest(manifest);
+ const { chrome, ...rest } = seen.render ?? {};
+ if (chrome !== undefined && chrome !== null) {
+ const errors = [...validateChrome(chrome, rest), ...validateDeckMarkers(seen), ...validateDeckClaims(seen), ...storyClipErrors(seen)];
+ if (errors.length) throw new ChromeRefused(errors);
+ }
+ const nextToken = await writeManifestAtomic(dir, manifest);
+ return { preset: manifest.preset ?? null, token: nextToken };
+ });
+}
+
/**
* Put `chrome` (the minimal deck) on a cut that has NO `render.chrome`, and
* leave a cut that has one as it is (release 29 G1: Draft everything's deck
@@ -2006,7 +2053,7 @@ export async function updateMarks(dir, entryId, change, { token = null } = {}) {
const given = Object.fromEntries(CLAIM_KNOBS.filter((k) => a[k] !== undefined && a[k] !== null && a[k] !== "").map((k) => [k, a[k]]));
const knobs = Object.keys(given).length ? normalizeClaimKnobPatch(given) : {};
for (const [k, v] of Object.entries(knobs)) if (v !== null) mark[k] = v;
- marks.push(normalizeClaim(mark));
+ marks.push(normalizeClaim(mark, { series: counterOrder(manifest.render) }));
added = id;
break;
}
@@ -2066,7 +2113,7 @@ function normalizeMarksInput(list, render) {
if (v !== null) mark[k2] = v;
}
try {
- return normalizeClaim(mark);
+ return normalizeClaim(mark, { series: counterOrder(render) });
} catch (e) {
throw new Error(String(e instanceof Error ? e.message : e).replace(/^claim\b/, `claims[${k}]`));
}
@@ -2219,6 +2266,39 @@ export async function replaceManifest(dir, manifest, { token = null, op = "repla
}
/**
+ * Migrate the manifest into the video modules' homes (release 39,
+ * report-to-video modules/migrate.mjs `migrateManifest`): the fact-check
+ * verdicts and tally become the counter's named series, and the cut renders
+ * as it did. The same path as a structural edit -- the lock, the token, the
+ * auto snapshot (`auto-before-migrate`, so "Undo last edit" takes it back),
+ * the atomic write -- refused when the result carries a problem the
+ * renderer's validators name that the manifest did not. `dryRun` writes
+ * nothing. Nothing to migrate: nothing written, `changes` empty.
+ *
+ * @param {string} dir
+ * @param {{ token?: string | null, dryRun?: boolean }} [opts]
+ * @returns {Promise<{ changes: string[], manifest: Record<string, any>, token?: string | null, snapshot?: unknown }>}
+ */
+export async function migrateManifestFile(dir, { token = null, dryRun = false } = {}) {
+ const problems = (m) => {
+ const { chrome, ...rest } = m.render ?? {};
+ return [...validateChrome(chrome, rest), ...validateClaims(m)];
+ };
+ const current = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ const planned = migrateManifest(current);
+ if (dryRun || !planned.changes.length) return { changes: planned.changes, manifest: planned.manifest };
+ return structural(dir, "migrate", token, (m) => {
+ const { manifest: next, changes } = migrateManifest(m);
+ const already = new Set(problems(m));
+ const errors = problems(next).filter((e) => !already.has(e));
+ if (errors.length) throw new StructureRefused(errors);
+ for (const k of Object.keys(m)) delete m[k];
+ Object.assign(m, next);
+ return { changes, manifest: next };
+ });
+}
+
+/**
* Take back the newest structural edit: restore the newest `auto-before-<op>`
* snapshot, byte for byte. The manifest as it is now is kept first
* (`undo-saved`), and the restored snapshot is renamed `undone-<op>` so the
diff --git a/umtool/lib/report/migrateCli.mjs b/umtool/lib/report/migrateCli.mjs
@@ -0,0 +1,60 @@
+// `umtool migrate` (release 39, the video-modules toolkit): a project's
+// manifest moved into the modules' homes -- the fact-check verdicts and tally
+// become the counter's named series (report-to-video modules/migrate.mjs) --
+// through the one writer (manifest.mjs `migrateManifestFile`: the lock, the
+// token, an `auto-before-migrate` snapshot, refused on a problem the
+// renderer's validators would name). The cut renders as it did.
+//
+// umtool migrate <project> [--dry-run] [--json]
+//
+// Plain ESM: the CLI runs under bare node.
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { manifestToken, migrateManifestFile } from "./manifest.mjs";
+
+export const MIGRATE_USAGE = [
+ "usage: umtool migrate <project> [--dry-run] [--json]",
+ "",
+ "Moves the manifest's settings into the video modules' homes (report-to-video/modules/migrate.mjs):",
+ "the fact-check verdicts and tally become render.chrome.deck.counter's named series, a deck claim's",
+ "tally names its series by id. The render is the same, frame for frame. --dry-run prints the moves",
+ "and writes nothing; a manifest already migrated is left as it is.",
+].join("\n");
+
+/**
+ * @param {string[]} args
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [io]
+ * @returns {Promise<number>}
+ */
+export async function migrateCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ const words = args.filter((a) => !a.startsWith("--"));
+ const dryRun = args.includes("--dry-run");
+ const json = args.includes("--json");
+ if (!words[0] || args.includes("--help")) {
+ err(MIGRATE_USAGE);
+ return 2;
+ }
+ const r = await resolveProject(words[0], root);
+ if (r.ambiguous) {
+ err(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ return 1;
+ }
+ if (!r.project) {
+ err(`no project matches "${words[0]}"`);
+ return 1;
+ }
+ try {
+ const token = await manifestToken(r.project.dir);
+ const res = await migrateManifestFile(r.project.dir, { token, dryRun });
+ if (json) out(JSON.stringify({ project: r.project.id, dryRun, changes: res.changes, ...(res.token ? { token: res.token } : {}) }));
+ else if (!res.changes.length) out(`${r.project.id}: nothing to migrate`);
+ else {
+ out(`${r.project.id}: ${dryRun ? "would migrate" : "migrated"}`);
+ for (const c of res.changes) out(` ${c}`);
+ }
+ return 0;
+ } catch (e) {
+ const errors = /** @type {any} */ (e)?.errors;
+ err(Array.isArray(errors) ? `refused:\n ${errors.join("\n ")}` : String(/** @type {any} */ (e)?.message ?? e));
+ return 1;
+ }
+}
diff --git a/umtool/lib/report/modulesCli.mjs b/umtool/lib/report/modulesCli.mjs
@@ -0,0 +1,262 @@
+// `umtool modules` and `umtool preset` (release 39, the video modules): the
+// module registry, a project's module-config.json applied, and the look
+// presets -- from a terminal, through the same writers the app uses.
+//
+// umtool modules list [--json] every module: id, kind, slot, where its settings live
+// umtool modules apply <project> [--config F] [--dry-run] [--json]
+// module-config.json onto the project's manifest
+// umtool modules apply <project> [--config F] --take <id> [--label L] [--at S --dur S | --full]
+// [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out F]
+// … as a take's patch instead: the project is not touched
+// umtool preset list [--json]
+// umtool preset show <name> [--json]
+// umtool preset save <name> --from <project> [--description D] [--force]
+// umtool preset apply <name> <project> the cut stands on the preset (`preset`); `none` removes it
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { MODULES } from "umtool-report-to-video/modules";
+import { moduleConfigToManifest } from "umtool-report-to-video/modules/config-loader";
+import { storyClipErrors } from "umtool-report-to-video/modules/story-settings";
+import { validateIntroSettings } from "umtool-report-to-video/modules/intro";
+import { listPresets, loadPreset, presetFromManifest, presetsDir, resolvePresetLayers, PRESET_NAME_RE } from "umtool-report-to-video/presets";
+import { validateChrome } from "umtool-report-to-video/deck";
+import { validateClaims } from "umtool-report-to-video/factcheck";
+import { mergePatch } from "umtool-report-to-video/montage-styles";
+import { manifestToken, replaceManifest, updatePreset } from "./manifest.mjs";
+
+export const MODULES_USAGE = [
+ "usage: umtool modules list [--json]",
+ " umtool modules apply <project> [--config FILE] [--dry-run] [--json]",
+ " umtool modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S | --full]",
+ " [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]",
+ "",
+ "apply reads the project's module-config.json (or --config): the modules a video wants, in the",
+ "design's vocabulary, mapped into the manifest's homes (modules/config-loader.mjs) -- the preset, the",
+ "deck's subtitle, QR, counter series and rail markers, each clip's marks, the stamps, the chapters, the",
+ "pairs, the status ledger, the intro and the finale. Everything with no home is listed, with its path.",
+ "Without --take the project's manifest is rewritten (a snapshot first; Undo last edit takes it back);",
+ "with --take the mapping is that take's patch (written to takes/<id>.modules-patch.json, or --patch-out)",
+ "and the take is made from it as `umtool take` makes one -- the project's manifest is not touched.",
+].join("\n");
+
+export const PRESET_USAGE = [
+ "usage: umtool preset list [--json]",
+ " umtool preset show <name> [--json]",
+ " umtool preset save <name> --from <project> [--description D] [--force]",
+ " umtool preset apply <name|none> <project>",
+ "",
+ "A look preset (umtool/presets/<name>.json) is a render block a manifest stands on: `\"preset\": \"<name>\"`",
+ "at the manifest's top level lays it UNDER the manifest -- preset → manifest → style → take patch, each",
+ "a JSON merge patch over the one before. save keeps a project's look and leaves its content out (its",
+ "claim checks, markers, counter series, finale stats, the story modules' lists); apply names the preset",
+ "on the cut (nothing of it is copied in), refused when the cut over it would not build.",
+].join("\n");
+
+class CliError extends Error {}
+
+function parse(args, valued) {
+ const flags = {};
+ const positional = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a.startsWith("--")) {
+ if (valued.includes(a)) {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ (flags[a] ??= []).push(args[++i]);
+ } else (flags[a] ??= []).push("");
+ } else positional.push(a);
+ }
+ return { flags, positional, one: (n) => flags[n]?.[flags[n].length - 1], has: (n) => n in flags };
+}
+
+async function pickProject(arg, root) {
+ if (!arg) throw new CliError("which project? pass an id, a name, or a directory");
+ const r = await resolveProject(arg, root);
+ if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${arg}"`);
+ return r.project;
+}
+
+const readJson = async (file, what) => {
+ try {
+ return JSON.parse(await readFile(file, "utf8"));
+ } catch (e) {
+ throw new CliError(`${what} ${file}: ${e instanceof Error ? e.message : e}`);
+ }
+};
+
+/** Every reason the manifest a module config makes would not build (the writers' and the build's checks). */
+export function appliedProblems(manifest) {
+ const seen = resolvePresetLayers(manifest);
+ const { chrome, ...rest } = seen.render ?? {};
+ return [
+ ...(chrome !== undefined && chrome !== null ? validateChrome(chrome, rest) : []),
+ ...storyClipErrors(seen),
+ ...validateClaims(seen),
+ ...(seen.render?.intro !== undefined ? validateIntroSettings(seen.render.intro) : []),
+ ];
+}
+
+/**
+ * `umtool modules …`
+ * @param {string[]} args everything after `modules`
+ * @returns {Promise<number>}
+ */
+export async function modulesCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, take = null } = {}) {
+ try {
+ const p = parse(args, ["--config", "--take", "--label", "--at", "--dur", "--from", "--patch-out", "--group"]);
+ const [sub, projectArg] = p.positional;
+ const json = p.has("--json");
+ if (!sub || p.has("--help")) {
+ log(MODULES_USAGE);
+ return sub ? 0 : 2;
+ }
+ if (sub === "list") {
+ const rows = MODULES.map((m) => ({
+ id: m.id, title: m.title, kind: m.kind, slot: m.slot, z: m.z, configKey: m.configKey ?? null,
+ ...(m.host ? { host: m.host } : {}), ui: Array.isArray(m.ui), preview: typeof m.preview === "function",
+ }));
+ if (json) log(JSON.stringify(rows, null, 2));
+ else for (const r of rows) log(`${r.id.padEnd(12)} ${r.kind.padEnd(15)} ${r.slot.padEnd(8)} z${String(r.z).padEnd(4)} ${r.configKey ?? "—"}`);
+ return 0;
+ }
+ if (sub !== "apply") throw new CliError(`unknown modules command "${sub}" — list or apply`);
+ const project = await pickProject(projectArg, reportsRoot);
+ const configFile = path.resolve(p.one("--config") ?? path.join(project.dir, "module-config.json"));
+ const config = await readJson(configFile, "--config");
+ const manifestPath = path.join(project.dir, "video.manifest.json");
+ const manifest = await readJson(manifestPath, "the manifest");
+ const token = await manifestToken(project.dir);
+ const { patch, unmapped, notes } = moduleConfigToManifest(config, manifest);
+ if (typeof patch.preset === "string") {
+ try {
+ loadPreset(patch.preset);
+ } catch (e) {
+ throw new CliError(`the config's preset: ${e instanceof Error ? e.message : e}`);
+ }
+ }
+ const next = mergePatch(manifest, patch);
+ const problems = appliedProblems(next);
+ const takeId = p.one("--take");
+ const report = { project: project.id, config: configFile, take: takeId ?? null, patch, unmapped, notes, problems };
+ const say = () => {
+ if (json) return log(JSON.stringify(report, null, 2));
+ log(`${project.id}: ${Object.keys(patch).length ? `sets ${describe(patch)}` : "nothing to set"}`);
+ if (unmapped.length) log(`not mapped (${unmapped.length}):\n ${unmapped.join("\n ")}`);
+ if (notes.length) log(`notes:\n ${notes.join("\n ")}`);
+ if (problems.length) log(`refused -- the cut would not build:\n ${problems.join("\n ")}`);
+ };
+ if (problems.length) {
+ say();
+ return 1;
+ }
+ if (p.has("--dry-run")) {
+ say();
+ return 0;
+ }
+ if (!takeId) {
+ const r = await replaceManifest(project.dir, next, { token, op: "modules" });
+ report.token = r.token;
+ say();
+ if (!json) log(`written: ${manifestPath} (snapshot ${r.snapshot?.id ?? r.snapshot?.file ?? "taken"})`);
+ return 0;
+ }
+ const patchFile = path.resolve(p.one("--patch-out") ?? path.join(project.dir, "takes", `${takeId}.modules-patch.json`));
+ await mkdir(path.dirname(patchFile), { recursive: true });
+ await writeFile(patchFile, JSON.stringify(patch, null, 2) + "\n", "utf8");
+ say();
+ if (!json) log(`the take's patch: ${patchFile}`);
+ const pass = ["--at", "--dur", "--from", "--group"].flatMap((f) => (p.has(f) ? [f, p.one(f)] : []));
+ const bare = ["--full", "--quick", "--force", "--keep-frames"].filter((f) => p.has(f));
+ const takeArgs = [project.dir, "--id", takeId, "--label", p.one("--label") ?? `modules (${path.basename(configFile)})`, "--patch", patchFile, ...pass, ...bare];
+ const run = take ?? (await import("./takeCli.mjs")).takeCommand;
+ return await run(takeArgs, { reportsRoot, log, err });
+ } catch (e) {
+ if (e instanceof CliError) {
+ err(e.message);
+ return 2;
+ }
+ err(e instanceof Error ? e.message : String(e));
+ return 1;
+ }
+}
+
+/** A patch's top-level homes, in words. */
+function describe(patch) {
+ const parts = [];
+ if (patch.preset) parts.push(`preset ${patch.preset}`);
+ const c = patch.render?.chrome ?? {};
+ for (const k of Object.keys(c)) {
+ if (k === "deck") parts.push(`deck.{${Object.keys(c.deck).join(", ")}}`);
+ else parts.push(`chrome.${k}`);
+ }
+ if (patch.render?.intro) parts.push("intro");
+ if (patch.timeline) parts.push("the timeline's marks and finale run");
+ return parts.join(", ");
+}
+
+/**
+ * `umtool preset …`
+ * @param {string[]} args everything after `preset`
+ * @returns {Promise<number>}
+ */
+export async function presetCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) {
+ try {
+ const p = parse(args, ["--from", "--description"]);
+ const [sub, a, b] = p.positional;
+ const json = p.has("--json");
+ if (!sub || p.has("--help")) {
+ log(PRESET_USAGE);
+ return sub ? 0 : 2;
+ }
+ if (sub === "list") {
+ const rows = listPresets();
+ if (json) log(JSON.stringify(rows, null, 2));
+ else if (!rows.length) log(`no presets in ${presetsDir()}`);
+ else for (const r of rows) log(`${r.name.padEnd(18)} ${r.error ? `(unreadable: ${r.error})` : r.description}`);
+ return 0;
+ }
+ if (sub === "show") {
+ if (!a) throw new CliError("which preset?");
+ const doc = loadPreset(a);
+ log(json ? JSON.stringify(doc, null, 2) : `${doc.name}: ${doc.description ?? ""}\n${JSON.stringify(doc.render, null, 2)}`);
+ return 0;
+ }
+ if (sub === "save") {
+ if (!a || !PRESET_NAME_RE.test(a)) throw new CliError("preset save <name>: lower-case letters, digits and dashes");
+ if (!p.has("--from")) throw new CliError("preset save <name> --from <project>");
+ const project = await pickProject(p.one("--from"), reportsRoot);
+ const manifest = await readJson(path.join(project.dir, "video.manifest.json"), "the manifest");
+ const file = path.join(presetsDir(), `${a}.json`);
+ const exists = await readFile(file, "utf8").then(() => true, () => false);
+ if (exists && !p.has("--force")) throw new CliError(`${file} exists — pass --force to replace it`);
+ const { preset, dropped } = presetFromManifest(manifest, { name: a, description: p.one("--description") ?? `The look of ${project.id}.`, from: project.id });
+ await mkdir(presetsDir(), { recursive: true });
+ await writeFile(file, JSON.stringify(preset, null, 2) + "\n", "utf8");
+ if (json) log(JSON.stringify({ file, preset, dropped }, null, 2));
+ else {
+ log(`saved ${file} (${Object.keys(preset.render).length} render keys, from ${project.id})`);
+ if (dropped.length) log(`left out (the cut's content, not its look):\n ${dropped.join("\n ")}`);
+ }
+ return 0;
+ }
+ if (sub === "apply") {
+ if (!a || !b) throw new CliError("preset apply <name|none> <project>");
+ const project = await pickProject(b, reportsRoot);
+ const r = await updatePreset(project.dir, a === "none" ? null : a);
+ if (json) log(JSON.stringify({ project: project.id, ...r }, null, 2));
+ else log(r.preset ? `${project.id} stands on the preset ${r.preset}` : `${project.id} stands on no preset`);
+ return 0;
+ }
+ throw new CliError(`unknown preset command "${sub}" — list, show, save or apply`);
+ } catch (e) {
+ if (e instanceof CliError) {
+ err(e.message);
+ return 2;
+ }
+ err(e instanceof Error ? (e.errors ? `${e.message}` : e.message) : String(e));
+ return 1;
+ }
+}
diff --git a/umtool/lib/report/modulesCli.test.mjs b/umtool/lib/report/modulesCli.test.mjs
@@ -0,0 +1,105 @@
+// `umtool modules` and `umtool preset` (modulesCli.mjs) over a temp tree.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { modulesCommand, presetCommand } from "./modulesCli.mjs";
+
+const clip = (id, start) => ({ type: "clip", id, channel: "c", video: "v", start, end: start + 3 });
+
+function tree() {
+ const root = mkdtempSync(path.join(os.tmpdir(), "modules-cli-"));
+ const dir = path.join(root, "proj");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: "proj", title: "Proj", provenance: {},
+ render: { width: 1920, height: 1080, fps: 30 }, timeline: [clip("a", 0), clip("b", 10)],
+ }));
+ writeFileSync(path.join(dir, "module-config.json"), JSON.stringify({
+ preset: "plain-deck",
+ modules: { chapter: [{ atClip: "b", title: "Two" }], shell: { title: "x" } },
+ }));
+ return { root, dir };
+}
+const sink = () => {
+ const lines = [];
+ return { lines, log: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) };
+};
+
+test("modules apply --dry-run says the patch and what has no home, and writes nothing", async () => {
+ const { root, dir } = tree();
+ const before = readFileSync(path.join(dir, "video.manifest.json"), "utf8");
+ const s = sink();
+ assert.equal(await modulesCommand(["apply", dir, "--dry-run", "--json"], { reportsRoot: root, ...s }), 0, s.lines.join("\n"));
+ const r = JSON.parse(s.lines[0]);
+ assert.equal(r.patch.preset, "plain-deck");
+ assert.deepEqual(r.patch.render.chrome.chapter, { list: [{ at: "b", title: "Two" }] });
+ assert.ok(r.unmapped.some((u) => u.startsWith("modules.shell.title")));
+ assert.equal(readFileSync(path.join(dir, "video.manifest.json"), "utf8"), before);
+});
+
+test("modules apply --take writes the take's patch and makes the take from it; the manifest untouched", async () => {
+ const { root, dir } = tree();
+ const before = readFileSync(path.join(dir, "video.manifest.json"), "utf8");
+ const s = sink();
+ let got = null;
+ const take = async (args) => { got = args; return 0; };
+ assert.equal(await modulesCommand(["apply", dir, "--take", "modules-1", "--at", "0", "--dur", "20", "--quick"], { reportsRoot: root, ...s, take }), 0, s.lines.join("\n"));
+ const patchFile = path.join(dir, "takes", "modules-1.modules-patch.json");
+ assert.deepEqual(got.slice(1, 3), ["--id", "modules-1"]);
+ assert.ok(got.includes("--patch") && got[got.indexOf("--patch") + 1] === patchFile);
+ assert.ok(got.includes("--quick") && got.includes("--at"));
+ assert.equal(JSON.parse(readFileSync(patchFile, "utf8")).preset, "plain-deck");
+ assert.equal(readFileSync(path.join(dir, "video.manifest.json"), "utf8"), before);
+});
+
+test("modules apply writes the manifest through the writer; preset apply none is refused while the chrome needs it", async () => {
+ const { root, dir } = tree();
+ const s = sink();
+ assert.equal(await modulesCommand(["apply", dir], { reportsRoot: root, ...s }), 0, s.lines.join("\n"));
+ const m = JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8"));
+ assert.equal(m.preset, "plain-deck");
+ assert.deepEqual(m.render.chrome, { chapter: { list: [{ at: "b", title: "Two" }] } });
+ const t = sink();
+ assert.equal(await presetCommand(["apply", "none", dir], { reportsRoot: root, ...t }), 1);
+ assert.match(t.lines.join("\n"), /render\.chrome\.engine/);
+ assert.equal(await presetCommand(["apply", "archive-catalog", dir], { reportsRoot: root, ...sink() }), 0);
+ assert.equal(JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8")).preset, "archive-catalog");
+});
+
+test("a config the cut could not build is refused, naming why", async () => {
+ const { root, dir } = tree();
+ writeFileSync(path.join(dir, "module-config.json"), JSON.stringify({ modules: { chapter: [{ atClip: "b", title: "Two" }] } }));
+ const s = sink();
+ // No preset and no deck: the chapter has no deck to stand in.
+ assert.equal(await modulesCommand(["apply", dir, "--dry-run"], { reportsRoot: root, ...s }), 1);
+ assert.match(s.lines.join("\n"), /refused/);
+});
+
+test("modules list and preset list", async () => {
+ const s = sink();
+ assert.equal(await modulesCommand(["list", "--json"], s), 0);
+ const ids = JSON.parse(s.lines[0]).map((m) => m.id);
+ for (const id of ["pair", "chapter", "status", "finale", "intro"]) assert.ok(ids.includes(id), id);
+ const t = sink();
+ assert.equal(await presetCommand(["list", "--json"], t), 0);
+ assert.deepEqual(JSON.parse(t.lines[0]).map((p) => p.name).sort(), ["archive-catalog", "huck-deck", "plain-deck"]);
+});
+
+test("umtool look takes the story modules' keys, through updateChrome", async () => {
+ const { lookCommand } = await import("./knobsCli.mjs");
+ const { root, dir } = tree();
+ assert.equal(await modulesCommand(["apply", dir], { reportsRoot: root, ...sink() }), 0);
+ const s = sink();
+ const code = await lookCommand([dir, "chapter.style=lower", "pair={\"style\":\"split\"}"], { root, out: s.log, err: s.err });
+ assert.equal(code, 0, s.lines.join("\n"));
+ const m = JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8"));
+ assert.equal(m.render.chrome.chapter.style, "lower");
+ assert.deepEqual(m.render.chrome.chapter.list, [{ at: "b", title: "Two" }]);
+ assert.deepEqual(m.render.chrome.pair, { style: "split" });
+ const bad = sink();
+ assert.equal(await lookCommand([dir, "status.rows=40"], { root, out: bad.log, err: bad.err }), 1);
+ assert.match(bad.lines.join("\n"), /status\.rows/);
+});
diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -759,3 +759,71 @@ export function stillTimeOf(schedule, id) {
const s = (schedule.segments ?? []).find((x) => x.id === id);
return s ? Math.round((s.start + s.duration / 2) * 1000) / 1000 : null;
}
+
+/**
+ * SINGLE-LAYER PREVIEWS (release 39, the module panel): each named module
+ * composed ALONE over the preview schedule -- its page, no render -- and
+ * where to load it. A part (the subtitle, the counter …) is its host's page,
+ * the deck's: composed by composeDeckPreview, so it is answered as `deck`.
+ * A whole-cut module is one project (`<region>-preview`); a window module
+ * one per window (`<region>-preview-<segment>`), the finale's one. A module
+ * this cut does not draw answers `{ off: <why> }`.
+ *
+ * @param {{ dir: string, manifestFile?: string }} project
+ * @param {string} variant
+ * @param {Record<string, any>} schedule
+ * @param {string[]} ids module ids
+ * @param {Record<string, any>} render the variant's render block
+ * @returns {Promise<Array<Record<string, any>>>}
+ */
+export async function composeLayerPreviews(project, variant, schedule, ids, render, { compose = composeChrome } = {}) {
+ const { moduleById } = await import("umtool-report-to-video/modules");
+ const outDir = path.join(project.dir, "out", variant);
+ const out = [];
+ for (const id of ids) {
+ const mod = moduleById(id);
+ if (!mod) { out.push({ id, error: `no module ${id}` }); continue; }
+ const m = mod.host ? moduleById(mod.host) : mod;
+ if (m.id === "shell") { out.push({ id, region: "deck", host: mod.host ?? null }); continue; }
+ if (!m.region || !["overlay-whole", "overlay-window"].includes(m.kind)) {
+ out.push({ id, region: m.region ?? null, off: `${m.title} is not an overlay: it has no live preview` });
+ continue;
+ }
+ if (!m.on(schedule, render)) {
+ out.push({ id, region: m.region, off: (m.check && m.check(schedule, render)) ?? `${m.title} draws nothing in this cut` });
+ continue;
+ }
+ const manifestPathOf = manifestOf(project);
+ if (m.kind === "overlay-whole") {
+ const name = `${m.region}-preview`;
+ const geometry = m.regions(schedule, { render, outDir })[0];
+ try {
+ await serialised(path.join(outDir, "chrome", name), () => compose(/** @type {any} */ ({
+ manifestPath: manifestPathOf, outDir, variant, region: m.region, schedule, preview: true,
+ })));
+ out.push({ id, region: m.region, kind: m.kind, name, geometry: pick(geometry) });
+ } catch (e) {
+ out.push({ id, region: m.region, kind: m.kind, geometry: pick(geometry), error: e instanceof Error ? e.message : String(e) });
+ }
+ continue;
+ }
+ const windows = [];
+ for (const r of m.regions(schedule, { render, outDir })) {
+ const w = r.window ?? null;
+ try {
+ const res = await serialised(`${outDir}:${m.region}:${r.segment ?? ""}`, () => compose(/** @type {any} */ ({
+ manifestPath: manifestPathOf, outDir, variant, region: m.region, schedule, preview: true,
+ ...(r.segment !== undefined ? { window: w, segment: r.segment } : {}),
+ })));
+ windows.push({ segment: r.segment ?? null, from: r.offset, to: r.offset + r.frameCount / Number(schedule.fps ?? render.fps ?? 30), name: path.basename(res.projDir) });
+ } catch (e) {
+ windows.push({ segment: r.segment ?? null, from: r.offset, error: e instanceof Error ? e.message : String(e) });
+ }
+ }
+ const g = m.regions(schedule, { render, outDir })[0];
+ out.push({ id, region: m.region, kind: m.kind, geometry: g ? pick(g) : null, windows });
+ }
+ return out;
+}
+
+const pick = (g) => (g ? { x: g.x, y: g.y, width: g.width, height: g.height } : null);
diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs
@@ -652,6 +652,11 @@ export const postsPreviewSrc = (projectId, variant, segment, take = null) =>
export function previewDirFor(projectDir, variant, rest, segmentIds) {
if (!Array.isArray(rest) || !rest.length) return null;
const head = rest[0];
+ // A single layer's preview (release 39, the module panel): a module's own
+ // project, `<region>-preview` (a whole-cut page) or
+ // `<region>-preview-<segment>` (a window page on one of the cut's entries).
+ const layer = layerPreviewOf(head, segmentIds);
+ if (layer) return { dir: path.join(projectDir, "out", variant, "chrome", layer), rest: rest.slice(1) };
if (head === FEED_PREVIEW) return { dir: feedPreviewDir(projectDir, variant), rest: rest.slice(1) };
if (head === STAMP_PREVIEW) return { dir: stampPreviewDir(projectDir, variant), rest: rest.slice(1) };
if (head === FINALE_PREVIEW) return { dir: finalePreviewDir(projectDir, variant), rest: rest.slice(1) };
@@ -663,3 +668,37 @@ export function previewDirFor(projectDir, variant, rest, segmentIds) {
}
return { dir: deckPreviewDir(projectDir, variant), rest };
}
+
+// ---------------------------------------------------------------------------
+// SINGLE-LAYER PREVIEWS (release 39, the module panel): a module composed
+// alone, `POST /api/report/chrome/preview { layers: [...] }`. Its project is
+// compose-chrome's preview name -- `<region>-preview` for a whole-cut page,
+// `<region>-preview-<segment>` for a window -- and is served here by that name
+// when the region is one of the LAYER_REGIONS (never the deck's own, the
+// posts' or the feed's, which have their own names above).
+// ---------------------------------------------------------------------------
+
+/** The regions whose pages the panel previews alone. */
+export const LAYER_REGIONS = Object.freeze(["pair", "status", "chapter", "stats", "threads", "flips", "fx"]);
+
+/** The project name a layer preview is served under, or null when `head` is not one. */
+export function layerPreviewOf(head, segmentIds = []) {
+ if (typeof head !== "string") return null;
+ for (const region of LAYER_REGIONS) {
+ if (head === `${region}-preview`) return head;
+ const prefix = `${region}-preview-`;
+ if (head.startsWith(prefix)) {
+ const seg = head.slice(prefix.length);
+ if (!seg || /[\/\\\0]/.test(seg) || seg === "." || seg === "..") return null;
+ return new Set(segmentIds).has(seg) ? head : null;
+ }
+ }
+ return null;
+}
+
+/**
+ * The iframe src of a layer's preview project (`name` as compose-chrome named it).
+ * @type {(projectId: string, variant: string, name: string, take?: string | null) => string}
+ */
+export const layerPreviewSrc = (projectId, variant, name, take = null) =>
+ `${previewBase(projectId, variant, take)}/${encodeURIComponent(name)}/index.html`;
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -42,6 +42,7 @@
//
// Plain ESM: the CLI (`umtool take`) runs it with bare node, and the app's
// pages import the parts they show (the styles, the staleness check).
+import { resolvePresetLayers } from "umtool-report-to-video/presets";
import { createHash } from "node:crypto";
import { link, lstat, mkdir, readFile, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
@@ -541,9 +542,11 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
}
}
const patches = [stylePatch, spec.patch].filter(Boolean);
- const manifest = /** @type {Record<string, any>} */ (patches.reduce((m, p) => mergePatch(m, p), base));
+ // preset → manifest → style → take patch (presets.mjs): a preset named by
+ // the manifest or by a patch is the base layer under them all.
+ const manifest = /** @type {Record<string, any>} */ (resolvePresetLayers(base, patches));
if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error("the patched manifest has no timeline");
- const changes = changeLines(base, manifest, patches);
+ const changes = changeLines(resolvePresetLayers(base), manifest, patches);
const kind = changes.length === 0 ? "reference" : (spec.kind ?? "different");
// The clip deck's rulings (report-to-video/montage-rulings.mjs), applied to
diff --git a/umtool/lib/report/takeManifest.mjs b/umtool/lib/report/takeManifest.mjs
@@ -16,6 +16,7 @@
// (so a relative asset in it resolves as the project's do), what the chrome
// preview composes a take's pages from -- a scratch file, rewritten on every
// compose, never read by a build.
+import { resolvePresetLayers } from "umtool-report-to-video/presets";
import { readFile, stat, writeFile, rename } from "node:fs/promises";
import path from "node:path";
import { ALL_STYLES_RECIPE, MANIFEST, RECIPE_FILE, loadMontageStyles, mergePatch, parseRecipe } from "./takeMaker.mjs";
@@ -124,7 +125,8 @@ export async function resolveTakeManifest(projectDir, id, { styles = null, base
return { manifest: frozen, take, note: `the style "${take.style}" is not installed: playing the manifest the take was rendered from` };
}
}
- const manifest = [stylePatch, take.patch].filter(Boolean).reduce((m, p) => mergePatch(m, p), project);
+ // preset → manifest → style → take patch (presets.mjs).
+ const manifest = resolvePresetLayers(project, [stylePatch, take.patch]);
if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error(`take ${id}: the patched manifest has no timeline`);
return { manifest: /** @type {Record<string, any>} */ (manifest), take, note };
}
diff --git a/umtool/presets/archive-catalog.json b/umtool/presets/archive-catalog.json
@@ -0,0 +1,45 @@
+{
+ "name": "archive-catalog",
+ "description": "A then-and-now archive look: the deck with every subtitle part and the full date, the rail laid at a fixed pitch so a dated pair reads in order, the pair module's split strip at the foot of the footage, QR to the original, a cool archive palette.",
+ "render": {
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "audioRate": 48000,
+ "audioChannels": 2,
+ "maxHeightSource": 720,
+ "fontRegular": "/usr/share/fonts/TTF/FiraSans-Regular.ttf",
+ "fontBold": "/usr/share/fonts/TTF/FiraSans-Bold.ttf",
+ "palette": {
+ "bg": "#0e1416",
+ "fg": "#eef2ee",
+ "muted": "#93a3a4",
+ "accent": "#4fb3bf",
+ "amber": "#e8c46a"
+ },
+ "transition": 0.5,
+ "fetchPad": 1,
+ "snapWindow": 0.6,
+ "silenceMinDur": 0.3,
+ "silenceRelDb": 8,
+ "headerHeight": 56,
+ "footerHeight": 0,
+ "crf": 21,
+ "preset": "slow",
+ "audioBitrate": "160k",
+ "qr": { "scale": 3, "quiet": 3, "ecc": "M", "margin": 28 },
+ "endFade": 1,
+ "intro": { "style": "boot-dark", "site": "auto" },
+ "chrome": {
+ "engine": "hyperframes",
+ "layout": "deck",
+ "deck": {
+ "qr": { "links": "original" },
+ "subtitle": { "parts": ["channel", "title", "date", "clock"], "dateFormat": "long" },
+ "pip": { "spacing": "pitch", "pitch": 28 },
+ "markerLayout": "stagger"
+ },
+ "pair": { "style": "split", "position": "bottom", "dateFormat": "long" }
+ }
+ }
+}
diff --git a/umtool/presets/huck-deck.json b/umtool/presets/huck-deck.json
@@ -0,0 +1,72 @@
+{
+ "name": "huck-deck",
+ "description": "The Huck video's look (quartering-huck/polemic-huck): the deck with the posts feed, verdict-coloured pips, the finale beside the clip, stamps top-left, the red accent on near-black.",
+ "render": {
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "audioRate": 48000,
+ "audioChannels": 2,
+ "maxHeightSource": 720,
+ "fontRegular": "/usr/share/fonts/TTF/FiraSans-Regular.ttf",
+ "fontBold": "/usr/share/fonts/TTF/FiraSans-Bold.ttf",
+ "palette": {
+ "bg": "#101219",
+ "fg": "#f2f0ea",
+ "muted": "#979caa",
+ "accent": "#e5534b",
+ "amber": "#ffc860"
+ },
+ "transition": 0.5,
+ "fetchPad": 1,
+ "snapWindow": 0.6,
+ "silenceMinDur": 0.3,
+ "silenceRelDb": 8,
+ "snapLead": 0.45,
+ "snapTail": 0.55,
+ "footerHeight": 100,
+ "headerHeight": 56,
+ "slideSeconds": 0.9,
+ "crf": 21,
+ "preset": "slow",
+ "audioBitrate": "160k",
+ "qr": {
+ "scale": 3,
+ "quiet": 3,
+ "ecc": "M",
+ "margin": 28
+ },
+ "endFade": 1,
+ "chrome": {
+ "engine": "hyperframes",
+ "layout": "deck",
+ "deck": {
+ "qr": {
+ "links": "original"
+ },
+ "posts": {
+ "layout": "feed",
+ "links": "original",
+ "qr": false
+ },
+ "pip": {
+ "color": "verdict"
+ },
+ "finale": {
+ "video": "side",
+ "motion": "grow",
+ "totals": true,
+ "railLabels": "all"
+ }
+ },
+ "factcheck": {
+ "stamp": {
+ "seconds": 3,
+ "position": "top-left",
+ "show": true
+ }
+ }
+ }
+ },
+ "from": "quartering-huck/polemic-huck"
+}
diff --git a/umtool/presets/plain-deck.json b/umtool/presets/plain-deck.json
@@ -0,0 +1,60 @@
+{
+ "name": "plain-deck",
+ "description": "A plain deck (the Trisha final's look): the deck with every subtitle part, QR to the original, the boot-dark intro with the chime, warm amber on brown-black; no posts feed, no finale.",
+ "render": {
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "audioRate": 48000,
+ "audioChannels": 2,
+ "maxHeightSource": 1080,
+ "fontRegular": "/usr/share/fonts/TTF/FiraSans-Regular.ttf",
+ "fontBold": "/usr/share/fonts/TTF/FiraSans-Bold.ttf",
+ "palette": {
+ "bg": "#12100c",
+ "fg": "#f6f1e6",
+ "muted": "#a2957f",
+ "accent": "#c8752a",
+ "amber": "#ffc860"
+ },
+ "transition": 0.4,
+ "fetchPad": 3,
+ "snapWindow": 1.6,
+ "silenceMinDur": 0.09,
+ "silenceRelDb": 6,
+ "footerHeight": 0,
+ "headerHeight": 56,
+ "crf": 21,
+ "preset": "slow",
+ "qr": {
+ "scale": 4,
+ "quiet": 3,
+ "ecc": "M",
+ "margin": 28
+ },
+ "intro": {
+ "style": "boot-dark",
+ "mark": "chime",
+ "seconds": 4.75,
+ "site": "auto"
+ },
+ "chrome": {
+ "engine": "hyperframes",
+ "layout": "deck",
+ "deck": {
+ "qr": {
+ "links": "original"
+ },
+ "subtitle": {
+ "parts": [
+ "channel",
+ "title",
+ "date",
+ "clock"
+ ]
+ }
+ }
+ }
+ },
+ "from": "trisha-final patch"
+}
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -121,6 +121,7 @@
//
// Requires: yt-dlp, ffmpeg/ffprobe, ImageMagick with Pango.
+import { presetManifest } from "./presets.mjs";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { promisify } from "node:util";
@@ -165,6 +166,8 @@ import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
import { validateStatsEntries } from "./stats.mjs";
+import { deckOverlays, moduleById, placementOf } from "./modules/index.mjs";
+import { counterOrder } from "./counter.mjs";
// The upload's text (release 28 M6): composed by code, written beside the cut.
import { composeYoutubeText, youtubeChapters, youtubeSources, youtubeTextName } from "./youtube.mjs";
import { socialTexts } from "./social.mjs";
@@ -336,7 +339,9 @@ export function selectVariant(manifest, variant = DEFAULT_VARIANT) {
// the object as built above. So does the brand intro (`render.intro`,
// intro.mjs): prepended here, so every reader sees the same first segment;
// without the key, the same object again.
- return introManifest(brandManifest({ ...manifest, variant, timeline, ledger, ...(posts !== undefined ? { posts } : {}) }));
+ // A look preset (`preset`, presets.mjs) is the base layer under it all:
+ // laid first, so the brand and the intro read the render as it will be.
+ return introManifest(brandManifest(presetManifest({ ...manifest, variant, timeline, ledger, ...(posts !== undefined ? { posts } : {}) })));
}
/**
@@ -3307,9 +3312,11 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts
// The effects region (`name: "fx"`) likewise.
// The finale (`name: "finale"`, chrome-finale.mjs) is a window like a
// posts window's -- the whole frame, laid last.
- const deck = r.name === "deck" || r.name === "feed" || r.name === "stamp" || r.name === "threads" || r.name === "flips" ||
- r.name === "stats" || r.name === "fx";
- const posts = r.name === "posts" || r.name === "finale";
+ // How each region is laid is its module's (modules/index.mjs placementOf):
+ // a whole-cut sequence laid as the deck's is, or a window at its second.
+ const placement = placementOf(r.name);
+ const deck = placement === "whole";
+ const posts = placement === "window";
inputs.push(
...(deck || posts ? ["-reinit_filter", "0"] : []),
...(posts ? ["-itsoffset", offsetArg(r.offset)] : []),
@@ -3346,80 +3353,52 @@ const offsetArg = (v) => {
};
/**
- * The posts windows as overlay regions: one per clip that carries posts
- * (`postWindows`), snapped to the frame grid (`snapWindow`), at
- * `postsGeometry`. `offset` is the second the window's frame 1 lands on in the
- * BASE's clock -- the cut's, or a preview's that starts `shift` seconds in.
- * `clip` (`{at, dur}`) keeps only the windows that intersect it. No posts, no
+ * The posts windows as overlay regions (modules/popup-posts.mjs): one per
+ * clip that carries posts, snapped to the frame grid, at `postsGeometry`.
+ * `offset` is the second the window's frame 1 lands on in the BASE's clock
+ * -- the cut's, or a preview's that starts `shift` seconds in. `clip`
+ * (`{at, dur}`) keeps only the windows that intersect it. No posts, no
* regions: the deck's overlay is then exactly what it was.
*/
export function postsRegions(render, outDir, schedule, { shift = 0, clip = null } = {}) {
- const fps = Number(schedule.fps ?? render.fps);
- const g = postsGeometry(render);
- return postWindows(schedule)
- .map((w) => ({ w, s: snapWindow(w, { fps, total: schedule.total }) }))
- .filter(({ s }) => !clip || (s.from < clip.at + clip.dur && s.to > clip.at))
- .map(({ w, s }) => ({
- name: "posts",
- segment: s.segment,
- window: w,
- frames: path.join(outDir, "chrome", `posts-${s.segment}-frames`),
- x: g.x, y: g.y, width: g.width, height: g.height,
- offset: s.from - shift,
- frameCount: s.frames,
- }));
+ return moduleById("popup-posts").regions(schedule, { render, outDir, shift, clip });
}
/**
- * The finale's page (a schedule with `finale`, chrome-finale.mjs) as an
- * overlay region: the whole frame, its window snapped to the frame grid
- * (`snapWindow`) and laid at its own second like a posts window -- `offset`
- * in the BASE's clock (the cut's, or a preview's that starts `shift` in).
- * `clip` (`{at, dur}`) keeps it only when it intersects. No finale: none.
+ * The finale's page as an overlay region (modules/finale.mjs): the whole
+ * frame, its window snapped to the frame grid and laid at its own second like
+ * a posts window. No finale: none.
*
* @returns {Array<{ name: "finale", frames: string, x: number, y: number, width: number, height: number,
* offset: number, frameCount: number, window: object }>}
*/
export function finaleRegions(render, outDir, schedule, { shift = 0, clip = null } = {}) {
- const f = schedule?.finale;
- if (!f) return [];
- const fps = Number(schedule.fps ?? render.fps);
- const s = snapWindow({ segment: "finale", from: f.from, to: f.to }, { fps, total: schedule.total });
- if (clip && !(s.from < clip.at + clip.dur && s.to > clip.at)) return [];
- return [{
- name: "finale",
- frames: path.join(outDir, "chrome", "finale-frames"),
- x: 0, y: 0, width: render.width ?? 1920, height: render.height ?? 1080,
- offset: s.from - shift,
- frameCount: s.frames,
- window: s,
- }];
+ return moduleById("finale").regions(schedule, { render, outDir, shift, clip });
}
/** The posts feed as an overlay region: its frames at feedGeometry's column. */
export function feedRegion(render, frames) {
- return { name: "feed", frames, ...feedGeometry(render).column };
+ return moduleById("feed").regions(null, { render, frames })[0];
}
/** The thread rail as an overlay region: its frames at threadsGeometry's box. */
export function threadsRegion(render, frames, name = "threads") {
- const { cards: _c, ...box } = threadsGeometry(render);
- return { name, frames, ...box };
+ return moduleById(name === "flips" ? "flips" : "threads").regions(null, { render, frames })[0];
}
/** The fact-check stamps as an overlay region: their frames at stampGeometry's box. */
export function stampRegion(render, frames, schedule) {
- return { name: "stamp", frames, ...stampGeometry(render, { feed: schedule.layout === "feed" }) };
+ return moduleById("stamp").regions(schedule, { render, frames })[0];
}
/** The stats region as an overlay region: its frames at statsGeometry's panel. */
export function statsRegion(render, frames, schedule) {
- return { name: "stats", frames, ...statsGeometry(render, { feed: schedule.layout === "feed" }) };
+ return moduleById("stats").regions(schedule, { render, frames })[0];
}
/** The effects region as an overlay region: its frames over the footage box (fxGeometry). */
export function fxRegion(render, frames, schedule) {
- return { name: "fx", frames, ...fxGeometry(render, { feed: schedule.layout === "feed" }) };
+ return moduleById("fx").regions(schedule, { render, frames })[0];
}
/**
@@ -3435,21 +3414,7 @@ export function fxRegion(render, frames, schedule) {
* band's branch rather than joining it: the deck refuses `chromeEngine`.
*/
export function chromeRegions(render, outDir) {
- if (deckOn(render)) {
- const { deck } = deckGeometry(render);
- return [{ name: "deck", frames: path.join(outDir, "chrome", "deck-frames"), ...deck }];
- }
- const H = render.chart?.height ?? 200;
- return [
- {
- name: "chart",
- frames: path.join(outDir, "chrome", "chart-frames"),
- x: 0,
- y: render.height - H,
- width: contentWidth(render),
- height: H,
- },
- ];
+ return moduleById(deckOn(render) ? "shell" : "chart").regions(null, { render, outDir });
}
/**
@@ -4578,7 +4543,7 @@ const cutAudioEncodeArgs = (render) => [
];
/** Overlay regions laid like a posts window: a short sequence at its own second. */
-const WINDOW_REGIONS = new Set(["posts", "finale"]);
+const WINDOW_REGIONS = { has: (name) => placementOf(name) === "window" };
/**
* One chunk's ffmpeg argv (picture only), and the same argv in KEY form with
@@ -5077,218 +5042,75 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro
if (fields.phase !== "compose") layers.push({ region: fields.region ?? "deck", segment: fields.segment, phase: fields.phase,
frames: fields.frames, reused: fields.reused, captured: fields.captured, seconds: fields.seconds });
};
- EMIT("chrome", { phase: "compose", ...(duration != null ? { from, duration } : {}) });
- const t0 = Date.now();
- const r = await composeChrome({
- manifestPath, outDir, variant, region: "deck", doRender: true,
- fps: render.fps, workers: CHROME_WORKERS, quality: "high", format: "png-sequence",
- ...(duration != null ? { from, duration } : {}),
- });
const want = frameCount(duration ?? schedule.total, render.fps);
- if (r.frameCount !== want) {
- throw new Error(
- `the deck's sequence is ${r.frameCount} frames but the ${duration != null ? "window" : "cut"} ` +
- `is ${want} (${(duration ?? schedule.total).toFixed(3)}s at ${render.fps} fps)`,
- );
- }
- emitChrome({
- phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render",
- ...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}),
- frames: r.frameCount, key: r.key, dir: r.frames,
- seconds: Number(((Date.now() - t0) / 1000).toFixed(1)),
- });
- const regions = chromeRegions(render, outDir).map((g) => ({ ...g, frames: r.frames }));
-
- // The posts FEED (a schedule with `layout: "feed"`): one sequence for the
- // whole cut -- or the same window as the deck's -- at feedGeometry's column,
- // laid like the deck's. postWindows has none for a feed, so the loop below
- // adds nothing.
- if (schedule.layout === "feed") {
- EMIT("chrome", { phase: "compose", region: "feed", ...(duration != null ? { from, duration } : {}) });
- const t1 = Date.now();
- const f = await composeChrome({
- manifestPath, outDir, variant, region: "feed", doRender: true,
- fps: render.fps, workers: CHROME_WORKERS, quality: "high", format: "png-sequence",
- ...(duration != null ? { from, duration } : {}),
- });
- if (f.frameCount !== want) {
- throw new Error(`the feed's sequence is ${f.frameCount} frames but the deck's is ${want}`);
- }
- emitChrome({
- phase: f.cached ? "cached" : f.reused > 0 ? "reuse" : "render", region: "feed",
- ...(f.reused != null ? { reused: f.reused, captured: f.captured } : {}),
- frames: f.frameCount, key: f.key, dir: f.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
- });
- regions.push(feedRegion(render, f.frames));
- }
-
- // Then the posts: one short sequence per clip that carries them, each with
- // its own cache, laid over the deck at its own second. A preview window
- // (`duration` given) takes only the windows it intersects, shifted into its
- // own clock; their frames are the build's, so a preview renders nothing a
- // build would not.
+ const win = duration != null ? { from, duration } : {};
+ // A preview window (`duration` given) takes only the windows it
+ // intersects, shifted into its own clock; their frames are the build's, so
+ // a preview renders nothing a build would not.
const clip = duration != null ? { at: from, dur: duration } : null;
- for (const pr of postsRegions(render, outDir, schedule, { shift: clip ? clip.at : 0, clip })) {
- EMIT("chrome", { phase: "compose", region: "posts", segment: pr.segment });
- const t1 = Date.now();
- const p = await composeChrome({
- manifestPath, outDir, variant, region: "posts", window: pr.window, doRender: true,
- fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence",
- });
- if (p.frames !== pr.frames || p.frameCount !== pr.frameCount) {
- throw new Error(
- `the posts window for ${pr.segment} rendered ${p.frameCount} frames to ${p.frames}; ` +
- `the overlay expects ${pr.frameCount} at ${pr.frames}`,
- );
- }
- emitChrome({
- phase: p.cached ? "cached" : p.reused > 0 ? "reuse" : "render", region: "posts", segment: pr.segment,
- ...(p.reused != null ? { reused: p.reused, captured: p.captured } : {}),
- frames: p.frameCount, key: p.key, dir: p.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
- });
- const { window: _w, ...region } = pr;
- regions.push(region);
- }
-
- // The fact-check stamps (a schedule whose `factcheck` stamps a claim): one
- // sequence for the whole cut -- or the deck's window -- laid last, over the
- // posts, at stampGeometry's box in the footage. With `stamp.show: false`
- // none is composed or laid; the deck's tally still counts each claim.
- if (stampsDrawn(schedule, render)) {
- EMIT("chrome", { phase: "compose", region: "stamp", ...(duration != null ? { from, duration } : {}) });
- const t1 = Date.now();
- const st = await composeChrome({
- manifestPath, outDir, variant, region: "stamp", doRender: true,
- fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence",
- ...(duration != null ? { from, duration } : {}),
- });
- if (st.frameCount !== want) {
- throw new Error(`the stamps' sequence is ${st.frameCount} frames but the deck's is ${want}`);
- }
- emitChrome({
- phase: st.cached ? "cached" : st.reused > 0 ? "reuse" : "render", region: "stamp",
- ...(st.reused != null ? { reused: st.reused, captured: st.captured } : {}),
- frames: st.frameCount, key: st.key, dir: st.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
- });
- regions.push(stampRegion(render, st.frames, schedule));
- }
-
- // The stats region (a schedule whose `stats` draws a clip, stats.mjs): one
- // sequence for the whole cut -- or the deck's window -- in a corner of the
- // footage, laid like the stamps'.
- if (schedule.stats?.clips?.length) {
- EMIT("chrome", { phase: "compose", region: "stats", ...(duration != null ? { from, duration } : {}) });
- const t1 = Date.now();
- const sr = await composeChrome({
- manifestPath, outDir, variant, region: "stats", doRender: true,
- fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence",
- ...(duration != null ? { from, duration } : {}),
- });
- if (sr.frameCount !== want) {
- throw new Error(`the stats region's sequence is ${sr.frameCount} frames but the deck's is ${want}`);
- }
- emitChrome({
- phase: sr.cached ? "cached" : sr.reused > 0 ? "reuse" : "render", region: "stats",
- ...(sr.reused != null ? { reused: sr.reused, captured: sr.captured } : {}),
- frames: sr.frameCount, key: sr.key, dir: sr.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
- });
- regions.push(statsRegion(render, sr.frames, schedule));
- }
-
- // The effects (a schedule with `fx`, fx.mjs): one sequence for the whole cut
- // -- or the deck's window -- exactly over the footage box, laid over the
- // stats.
- if (schedule.fx) {
- EMIT("chrome", { phase: "compose", region: "fx", ...(duration != null ? { from, duration } : {}) });
- const t1 = Date.now();
- const fr = await composeChrome({
- manifestPath, outDir, variant, region: "fx", doRender: true,
- fps: render.fps, workers: CHROME_WORKERS, quality: "high", format: "png-sequence",
- ...(duration != null ? { from, duration } : {}),
- });
- if (fr.frameCount !== want) {
- throw new Error(`the effects' sequence is ${fr.frameCount} frames but the deck's is ${want}`);
- }
- emitChrome({
- phase: fr.cached ? "cached" : fr.reused > 0 ? "reuse" : "render", region: "fx",
- ...(fr.reused != null ? { reused: fr.reused, captured: fr.captured } : {}),
- frames: fr.frameCount, key: fr.key, dir: fr.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
- });
- regions.push(fxRegion(render, fr.frames, schedule));
- }
-
- // The thread rail (a schedule with `threads`): one sequence for the whole
- // cut -- or the deck's window -- beside the footage, laid like the deck's.
- if (schedule.threads?.threads?.length) {
- EMIT("chrome", { phase: "compose", region: "threads", ...(duration != null ? { from, duration } : {}) });
- const t1 = Date.now();
- const th = await composeChrome({
- manifestPath, outDir, variant, region: "threads", doRender: true,
- fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence",
- ...(duration != null ? { from, duration } : {}),
- });
- if (th.frameCount !== want) {
- throw new Error(`the thread rail's sequence is ${th.frameCount} frames but the deck's is ${want}`);
- }
- emitChrome({
- phase: th.cached ? "cached" : th.reused > 0 ? "reuse" : "render", region: "threads",
- ...(th.reused != null ? { reused: th.reused, captured: th.captured } : {}),
- frames: th.frameCount, key: th.key, dir: th.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
- });
- regions.push(threadsRegion(render, th.frames));
- }
-
- // The flips panel (a schedule with `flips`): the same region as the rail.
- if (schedule.flips?.pairs?.length) {
- EMIT("chrome", { phase: "compose", region: "flips", ...(duration != null ? { from, duration } : {}) });
- const t1 = Date.now();
- const fl = await composeChrome({
- manifestPath, outDir, variant, region: "flips", doRender: true,
- fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence",
- ...(duration != null ? { from, duration } : {}),
- });
- if (fl.frameCount !== want) {
- throw new Error(`the flips panel's sequence is ${fl.frameCount} frames but the deck's is ${want}`);
+ const regions = [];
+ // Every overlay module the schedule draws, in z order (modules/index.mjs):
+ // the deck's shell first, then the feed, each posts window, the stamps, the
+ // stats, the effects, the side panel, and the finale LAST -- its ground
+ // covers every region under it while it is up. A whole-cut module is one
+ // sequence for the whole cut -- or the deck's window -- laid from frame 1;
+ // a window module is a short sequence per window, laid at its own second.
+ for (const mod of deckOverlays()) {
+ if (!mod.on(schedule, render)) continue;
+ const workers = mod.workers === "wide" ? CHROME_WORKERS : CHROME_WORKERS_SMALL;
+ // The shell's events name no region (the deck's, as they always have).
+ const named = mod.region === "deck" ? {} : { region: mod.region };
+ if (mod.kind === "overlay-whole") {
+ EMIT("chrome", { phase: "compose", ...named, ...win });
+ const t1 = Date.now();
+ const r = await composeChrome({
+ manifestPath, outDir, variant, region: mod.region, doRender: true,
+ fps: render.fps, workers, quality: "high", format: "png-sequence", ...win,
+ });
+ if (r.frameCount !== want) {
+ throw new Error(
+ mod.region === "deck"
+ ? `the deck's sequence is ${r.frameCount} frames but the ${duration != null ? "window" : "cut"} ` +
+ `is ${want} (${(duration ?? schedule.total).toFixed(3)}s at ${render.fps} fps)`
+ : `${mod.noun} sequence is ${r.frameCount} frames but the deck's is ${want}`,
+ );
+ }
+ emitChrome({
+ phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render", ...named,
+ ...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}),
+ frames: r.frameCount, key: r.key, dir: r.frames,
+ seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
+ });
+ regions.push(...mod.regions(schedule, { render, outDir, frames: r.frames }));
+ continue;
}
- emitChrome({
- phase: fl.cached ? "cached" : fl.reused > 0 ? "reuse" : "render", region: "flips",
- ...(fl.reused != null ? { reused: fl.reused, captured: fl.captured } : {}),
- frames: fl.frameCount, key: fl.key, dir: fl.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
- });
- regions.push(threadsRegion(render, fl.frames, "flips"));
- }
-
- // The finale (a schedule with `finale`, chrome-finale.mjs): one full-frame
- // window over the run's seconds, laid LAST -- its ground covers every
- // region under it while it is up. A preview window takes it only when it
- // intersects; its frames are the build's, as the posts windows' are.
- for (const fr of finaleRegions(render, outDir, schedule, { shift: clip ? clip.at : 0, clip })) {
- EMIT("chrome", { phase: "compose", region: "finale" });
- const t1 = Date.now();
- const p = await composeChrome({
- manifestPath, outDir, variant, region: "finale", doRender: true,
- fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence",
- });
- if (p.frames !== fr.frames || p.frameCount !== fr.frameCount) {
- throw new Error(`the finale rendered ${p.frameCount} frames to ${p.frames}; the overlay expects ${fr.frameCount} at ${fr.frames}`);
+ for (const pr of mod.regions(schedule, { render, outDir, shift: clip ? clip.at : 0, clip })) {
+ EMIT("chrome", { phase: "compose", region: mod.region, ...(pr.segment !== undefined ? { segment: pr.segment } : {}) });
+ const t1 = Date.now();
+ const p = await composeChrome({
+ manifestPath, outDir, variant, region: mod.region, ...(pr.segment !== undefined ? { window: pr.window } : {}), doRender: true,
+ fps: render.fps, workers, quality: "high", format: "png-sequence",
+ });
+ if (p.frames !== pr.frames || p.frameCount !== pr.frameCount) {
+ throw new Error(
+ pr.segment !== undefined
+ ? `the posts window for ${pr.segment} rendered ${p.frameCount} frames to ${p.frames}; ` +
+ `the overlay expects ${pr.frameCount} at ${pr.frames}`
+ : `the ${mod.region} rendered ${p.frameCount} frames to ${p.frames}; the overlay expects ${pr.frameCount} at ${pr.frames}`,
+ );
+ }
+ emitChrome({
+ phase: p.cached ? "cached" : p.reused > 0 ? "reuse" : "render", region: mod.region,
+ ...(pr.segment !== undefined ? { segment: pr.segment } : {}),
+ ...(p.reused != null ? { reused: p.reused, captured: p.captured } : {}),
+ frames: p.frameCount, key: p.key, dir: p.frames,
+ seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
+ });
+ const { window: _w, ...region } = pr;
+ regions.push(region);
}
- emitChrome({
- phase: p.cached ? "cached" : p.reused > 0 ? "reuse" : "render", region: "finale",
- ...(p.reused != null ? { reused: p.reused, captured: p.captured } : {}),
- frames: p.frameCount, key: p.key, dir: p.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
- });
- const { window: _w, ...region } = fr;
- regions.push(region);
}
- if (duration == null && layers.length) await logRebuild(outDir, { phase: "chrome", layers });
+ if (duration == null && layers.length) await logRebuild(outDir, { phase: "chrome", layers });
return { regions, outLabel: "[hfout]" };
}
@@ -5427,7 +5249,9 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du
let clipClock = null;
// So is a clip a deck claim check is said in (`deck.claims`, claims.mjs).
const claimClips = deckClaimClips(render);
- const timedMarks = (e) => marksOf(e).some((c) => c.at !== undefined) || claimClips.has(e.id);
+ // A mark names one of the counter's series (counter.mjs): read with them.
+ const series = counterOrder(render);
+ const timedMarks = (e) => marksOf(e, series).some((c) => c.at !== undefined) || claimClips.has(e.id);
if (entries.some(timedMarks)) {
clipClock = new Map();
for (let i = 0; i < entries.length; i += 1) {
diff --git a/umtool/report-to-video/chrome-cues.mjs b/umtool/report-to-video/chrome-cues.mjs
@@ -0,0 +1,228 @@
+// THE CUE PAGE (release 39, the video modules): the one shape a small chrome
+// page takes -- markup whose every element starts hidden, and a list of cues
+// each stating its FROM, played by a paused GSAP timeline a renderer seeks
+// frame by frame. chrome-stats.mjs is the pattern; the pair, chapter and
+// status modules write their pages through this file so they do not each
+// carry a copy of the interpreter (and the frame-key model reads all three
+// the same way: frame-keys.mjs, `frameKeys` on each module).
+//
+// Two placements:
+// - WHOLE: a page as long as the cut (or a window of it, `from`/`duration`),
+// its data `{ total, window, ids, init, cues }`.
+// - WINDOW: a page for one window of the cut, its data `{ from, dur, init,
+// cues }`, the cues in the cut's clock (the frame keys' `offset: "from"`).
+//
+// PURE: data in, an HTML string out.
+import { pageDuration } from "./deck.mjs";
+
+/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
+export const INSTANT = 0.001;
+
+export const r4 = (v) => Math.round(v * 10000) / 10000;
+
+export const esc = (s) =>
+ String(s ?? "")
+ .replace(/&/g, "&")
+ .replace(/</g, "<")
+ .replace(/>/g, ">")
+ .replace(/"/g, """);
+
+/**
+ * Events -> cues: ordered by time, clamped so a cue never starts before the
+ * last on its element ends, every FROM stated (the last TO on its element,
+ * or its init). `events` are `{ k, at, dur, to, ease }`.
+ *
+ * @returns {{ init: Record<string, object>, cues: Array<{ k: string, at: number, dur: number, from: object, to: object, ease: string }> }}
+ */
+export function compileCues(init, events) {
+ const ev = events.map((e, n) => ({ ...e, at: r4(e.at), dur: r4(Math.max(INSTANT, e.dur)), n }));
+ ev.sort((a, b) => a.at - b.at || a.n - b.n);
+ const state = Object.fromEntries(Object.entries(init).map(([k, v]) => [k, { ...v }]));
+ const freeAt = new Map();
+ const cues = [];
+ for (const e of ev) {
+ let { at, dur } = e;
+ const free = freeAt.get(e.k) ?? 0;
+ if (at < free) {
+ const end = at + dur;
+ at = r4(free);
+ dur = r4(Math.max(INSTANT, end - at));
+ }
+ const cur = state[e.k] ?? (state[e.k] = {});
+ const from = {};
+ for (const p of Object.keys(e.to)) from[p] = cur[p];
+ Object.assign(cur, e.to);
+ freeAt.set(e.k, r4(at + dur));
+ cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
+ }
+ return { init, cues };
+}
+
+/**
+ * Show `k` over [a, b]: in over `fadeIn`, out over `fadeOut` before b (each
+ * at most half the span). The events compileCues takes.
+ */
+export function spanEvents(k, a, b, { fadeIn = 0.35, fadeOut = 0.3, prop = "autoAlpha" } = {}) {
+ const len = Math.max(0, b - a);
+ if (!(len > 0)) return [];
+ return [
+ { k, at: a, dur: Math.min(fadeIn, len / 2), to: { [prop]: 1 }, ease: "power2.out" },
+ { k, at: Math.max(a, b - fadeOut), dur: Math.min(fadeOut, len / 2), to: { [prop]: 0 }, ease: "power1.in" },
+ ];
+}
+
+/** Spans `{in, out}` with the ones that touch (or overlap) joined. */
+export function joinSpans(spans, gap = 1e-6) {
+ const out = [];
+ for (const s of [...spans].sort((x, y) => x.in - y.in)) {
+ const last = out[out.length - 1];
+ if (last && s.in - last.out <= gap) last.out = Math.max(last.out, s.out);
+ else out.push({ in: s.in, out: s.out });
+ }
+ return out;
+}
+
+/** The deck's two faces, under the deck's private names (docs/quirks.md). */
+function fontFaces(fonts) {
+ return `@font-face { font-family: 'DeckSans'; font-weight: 400; font-style: normal; src: url('${esc(fonts.regular ?? "")}'); }
+ @font-face { font-family: 'DeckSansBold'; font-weight: 400; font-style: normal; src: url('${esc(fonts.bold ?? "")}'); }`;
+}
+
+/**
+ * A cue page's HTML.
+ *
+ * @param {{ id: string, W: number, H: number, fps: number, fonts?: {regular?: string, bold?: string},
+ * gsapSrc?: string, css: string, body: string, init: object, cues: object[],
+ * whole?: { total: number, from?: number, duration?: number | null, ids?: string[] },
+ * window?: { from: number, dur: number } }} p
+ */
+export function cuePageHtml(p) {
+ const { id, W, H, fps, css, body, init, cues } = p;
+ const fonts = p.fonts ?? {};
+ const gsapSrc = p.gsapSrc ?? "assets/gsap.min.js";
+ let data;
+ let dur;
+ if (p.window) {
+ dur = r4(p.window.dur);
+ data = { from: r4(p.window.from), dur, init, cues };
+ } else {
+ const total = p.whole.total;
+ const from = Number(p.whole.from ?? 0);
+ dur = p.whole.duration != null ? r4(Number(p.whole.duration)) : r4(total - from);
+ if (!(dur > 0)) throw new Error(`${id}: nothing to render from ${from}s of a ${total}s cut`);
+ const windowed = from > 0 || Math.abs(dur - total) > 1e-6;
+ data = { total: r4(total), window: windowed ? { from: r4(from), dur } : null, ids: p.whole.ids ?? [], init, cues };
+ }
+ const json = JSON.stringify(data).replace(/</g, "\\u003c");
+ const D = pageDuration(dur, fps);
+ // The window's timeline plays the cut's [from, from + dur]; a whole page's
+ // its own [0, total], or the window of it it was asked for.
+ const play = p.window
+ ? `const tl = gsap.timeline({ paused: true });
+ tl.add(inner.tweenFromTo(S.from, S.from + S.dur, { duration: S.dur, ease: "none" }), 0);
+ const local = (t) => Math.max(0, Math.min(S.dur, (Number(t) || 0) - S.from));`
+ : `inner.set({}, {}, S.total);
+ let tl = inner;
+ if (S.window) {
+ tl = gsap.timeline({ paused: true });
+ tl.add(inner.tweenFromTo(S.window.from, S.window.from + S.window.dur, { duration: S.window.dur, ease: "none" }), 0);
+ }
+ const local = (t) => {
+ const v = Number(t) || 0;
+ return S.window ? Math.max(0, Math.min(S.window.dur, v - S.window.from)) : Math.max(0, v);
+ };`;
+ return `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=${W}, height=${H}" />
+ <script src="${esc(gsapSrc)}"></script>
+ <style>
+ ${fontFaces(fonts)}
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ html, body { width: ${W}px; height: ${H}px; overflow: hidden; background: transparent; }
+ body { font-family: 'DeckSans', sans-serif; font-synthesis: none;
+ -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; }
+ #root { position: relative; width: ${W}px; height: ${H}px; overflow: hidden; }
+ #${id}-clip { position: absolute; left: 0; top: 0; width: ${W}px; height: ${H}px; }
+ ${css}
+ </style>
+ </head>
+ <body>
+ <div id="root" data-composition-id="${id}" data-start="0" data-duration="${D}"
+ data-width="${W}" data-height="${H}">
+ <div id="${id}-clip" class="clip" data-start="0" data-duration="${D}" data-track-index="1">
+ ${body}
+ </div>
+ </div>
+
+ <script id="${id}-data" type="application/json">${json}</script>
+ <script>
+ const S = JSON.parse(document.getElementById("${id}-data").textContent);
+ const byK = {};
+ for (const el of document.querySelectorAll("[data-k]")) byK[el.dataset.k] = el;
+ // t = 0, then the cues. Every cue states its from, so a seek from
+ // anywhere to anywhere lands on the same pixels.
+ for (const k of Object.keys(S.init)) if (byK[k]) gsap.set(byK[k], S.init[k]);
+ const inner = gsap.timeline({ paused: true });
+ for (const c of S.cues) {
+ const el = byK[c.k];
+ if (!el) continue;
+ inner.fromTo(el, c.from, { ...c.to, duration: c.dur, ease: c.ease, immediateRender: false }, c.at);
+ }
+ ${play}
+ window.__timelines = window.__timelines || {};
+ window.__timelines["${id}"] = tl;
+
+ const ready = document.fonts.ready.catch(() => {}).then(() => { document.documentElement.dataset.fit = "1"; });
+ const params = new URLSearchParams(location.search);
+ const still = params.get("still");
+ if (still !== null) {
+ tl.seek(local(still), false);
+ ready.then(() => tl.seek(local(still), false));
+ }
+ // umtool's live preview: the parent seeks in cut seconds, as it seeks the deck.
+ if (params.get("preview") === "1") {
+ window.addEventListener("message", (e) => {
+ const m = e.data || {};
+ if (m.type === "deck:seek") tl.seek(local(m.t), false);
+ });
+ ready.then(() => {
+ if (window.parent !== window) window.parent.postMessage({ type: "${id}:ready", ids: S.ids || [] }, "*");
+ });
+ }
+ </script>
+ </body>
+</html>
+`;
+}
+
+/**
+ * Each segment's span in the cut, by id: `{ in, out }` -- its start to its
+ * end less the dissolve into the next (the frame a viewer reads it on).
+ */
+export function segmentSpans(schedule) {
+ const out = new Map();
+ for (const s of schedule?.segments ?? []) out.set(s.id, { in: s.start, out: s.end });
+ return out;
+}
+
+/**
+ * A date as the cut writes it: "2012" | "Sep 2012" | "29 Sep 2012" from
+ * YYYY, YYYY-MM or YYYY-MM-DD (`format` "iso" keeps it; "year" the year).
+ * Anything else is written as given.
+ */
+export function dateText(d, format = "long") {
+ if (d === undefined || d === null || d === "") return "";
+ const s = String(d);
+ const m = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/.exec(s);
+ if (!m || format === "iso") return s;
+ if (format === "year") return m[1];
+ const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ if (!m[2]) return m[1];
+ const mon = MON[Number(m[2]) - 1] ?? m[2];
+ return m[3] ? `${Number(m[3])} ${mon} ${m[1]}` : `${mon} ${m[1]}`;
+}
+
+/** A YYYY / YYYY-MM / YYYY-MM-DD date (what pair, chapter and status take). */
+export const DATE_RE = /^\d{4}(?:-(?:0[1-9]|1[0-2])(?:-(?:0[1-9]|[12]\d|3[01]))?)?$/;
diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs
@@ -38,10 +38,11 @@
import { fileURLToPath } from "node:url";
import {
- claimsLayout, cueTime, cueTimeAfter, stampsOnFrames, deckChoreography, deckLayout, deckMarkers, MARKER_LABEL_SIZE, MARKER_ROW, pageDuration, pipSegments, pipXs, resolveDeck,
+ claimsLayout, cueTime, cueTimeAfter, PIP_PITCH_DEFAULT, stampsOnFrames, deckChoreography, deckLayout, deckMarkers, MARKER_LABEL_SIZE, MARKER_ROW, pageDuration, pipSegments, pipXs, resolveDeck,
} from "./deck.mjs";
import { claimsCues, claimsMarkup } from "./chrome-claims.mjs";
-import { resolveFactcheck, tallyCues, tallyFinals, tallyKey, tallyLabelOf, tallyOf, tallyPopIns, VERDICT_SHAPES } from "./factcheck.mjs";
+import { resolveFactcheck, tallyCues, tallyFinals, tallyKey, tallyLabelOf, tallyOf, tallyPopIns } from "./factcheck.mjs";
+import { resolveCounter } from "./counter.mjs";
/**
* GSAP, vendored, for every chrome region.
@@ -56,7 +57,28 @@ import { resolveFactcheck, tallyCues, tallyFinals, tallyKey, tallyLabelOf, tally
* import.meta in the module that does the fs work would mark every path that
* module joins (scripts/next-build-trace.test.mjs).
*/
-export const GSAP_FILE = fileURLToPath(new URL("./assets/gsap.min.js", import.meta.url));
+export const GSAP_FILE = assetFile(new URL("./assets/gsap.min.js", import.meta.url));
+
+/**
+ * A module's asset URL as a file path. In plain Node it is fileURLToPath's;
+ * in a server bundle Turbopack hands an asset URL object of its own that
+ * fileURLToPath refuses at module load ("Received an instance of URL"),
+ * which failed `next build` while it collected page data once the module
+ * registry (modules/index.mjs) brought the page modules into build-video's
+ * static import chain (docs/quirks.md). There the bundler's own string is
+ * kept: nothing a page bundle evaluates reads the file, and a route that
+ * does gets a real URL, as before.
+ *
+ * @param {URL} url
+ * @returns {string}
+ */
+export function assetFile(url) {
+ try {
+ return fileURLToPath(url);
+ } catch {
+ return String(url);
+ }
+}
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
const INSTANT = 0.001;
@@ -153,9 +175,10 @@ export function deckCues(schedule, render) {
const segs = schedule.segments;
const ch = deckChoreography(schedule, render);
const pipped = pipSegments(schedule);
+ const pitched = deck.pip.spacing === "pitch";
const xs = pipXs(
pipped.length, lay.pipTrack.x0, lay.pipTrack.x1, deck.pip.spacing,
- deck.pip.spacing === "time" ? { total: schedule.total, segments: pipped } : null,
+ deck.pip.spacing === "time" ? { total: schedule.total, segments: pipped } : null, deck.pip.pitch ?? PIP_PITCH_DEFAULT,
);
// `pip.color: "verdict"`: a claimed clip's pip carries its verdict (drawn
// in its colour and shape once lit). Only then, so the pips are as they
@@ -164,7 +187,9 @@ export function deckCues(schedule, render) {
const pips = pipped.map((s, k) => ({ id: s.id, x: r4(xs[k]), ...(byVerdict && s.claim?.verdict ? { verdict: s.claim.verdict } : {}) }));
const pipOf = new Map(pipped.map((s, k) => [s.id, k]));
const fuseX0 = xs[0] ?? 0;
- const fuseW = xs.length > 1 ? xs[xs.length - 1] - xs[0] : 0;
+ // At a fixed pitch the fuse is measured against the whole track, so its
+ // progress to a pip does not depend on how many come after it.
+ const fuseW = xs.length > 1 ? (pitched ? lay.pipTrack.x1 - xs[0] : xs[xs.length - 1] - xs[0]) : 0;
const frac = (k) => (fuseW > 0 ? r4((xs[k] - fuseX0) / fuseW) : 0);
const lift = Math.round(lay.text.titleSize * 0.16);
const slideY = lay.height + 12;
@@ -177,6 +202,10 @@ export function deckCues(schedule, render) {
put("marker", { x: r4(xs[0] ?? lay.pipTrack.x0) });
if (fuseW > 0) put("fuse", { scaleX: 0, transformOrigin: "0% 50%" });
pips.forEach((_, k) => put(`pip${k}`, { opacity: 0 }));
+ // At a fixed pitch a pip is not drawn until the fuse sets off toward it
+ // (the marker reaches the pip before): the rail is the record so far, so a
+ // clip inserted later changes nothing drawn before it.
+ if (pitched) pips.forEach((_, k) => { if (k > 0) put(`pb${k}`, { opacity: 0 }); });
segs.forEach((s, i) => {
const st = i === 0 && !s.hideDeck ? SEG_STATE.shown() : SEG_STATE.before(lift);
put(keyOf(i, "seg"), st.seg);
@@ -279,6 +308,14 @@ export function deckCues(schedule, render) {
for (const e of t.events) add(e.k, e.at, e.dur, e.to, e.ease, e.why);
}
+ // At a fixed pitch, each pip after the first comes in as the marker reaches the one before it.
+ if (pitched) {
+ for (let k = 1; k < pips.length; k += 1) {
+ const a = arrive.get(k - 1);
+ if (a !== undefined) add(`pb${k}`, a, INSTANT, { opacity: 1 }, "none", `pip ${pips[k].id} ahead`);
+ }
+ }
+
// The fuse: from pip k to pip k+1 over the time the marker rests on k.
if (fuseW > 0) {
for (let k = 0; k < pips.length - 1; k += 1) {
@@ -384,6 +421,7 @@ export function subtitleMarkup(text) {
*/
export function deckHtml(schedule, render, opts = {}) {
const deck = resolveDeck(render);
+ const pitched = deck.pip.spacing === "pitch";
const tally = tallyOf(schedule, render);
const lay = deckLayout(render, { tally, schedule });
const pal = render.palette;
@@ -406,6 +444,9 @@ export function deckHtml(schedule, render, opts = {}) {
// The verdicts' colours as the tally draws them (relabels and recolours
// included), so a claimed pip and its tally cell are the same colour.
const verdictColors = resolveFactcheck(render).verdicts;
+ // The counter's series (counter.mjs): their order and each one's shape.
+ const counter = resolveCounter(render);
+ const shapes = counter.shapes;
const byVerdict = pip.color === "verdict";
// The lift: a few percent toward the foreground, so the deck reads as a
@@ -420,10 +461,15 @@ export function deckHtml(schedule, render, opts = {}) {
const plateX = qr ? qr.x - 46 : W;
const ink = panel ? mix(pal.bg, pal.fg, 0.085) : pal.bg; // what the marker's ring cuts back to
+ // The page's ITEMS (frame-keys.mjs): each segment's text, each pip -- the
+ // markup a frame draws only while its gate is visible, collected when the
+ // caller asks (`opts.items`, an array) so a frame's key holds the items it
+ // shows and not every other's. The page is the same either way.
+ const items = Array.isArray(opts.items) ? opts.items : null;
const segHtml = schedule.segments
.map((s, i) => {
const src = qrSrcs[s.id];
- return (
+ const html = (
`<div class="seg${s.title ? "" : " untitled"}" data-seg="${esc(s.id)}" data-k="s${i}">` +
`<div class="tc" data-k="s${i}.tc"><div class="ti" data-k="s${i}.ti">` +
`<div class="deck-title">${esc(s.title)}</div></div>` +
@@ -439,6 +485,8 @@ export function deckHtml(schedule, render, opts = {}) {
: `<div class="deck-qr empty" data-k="s${i}.qr"></div>`) +
`</div>`
);
+ if (items) items.push({ key: `s${i}`, gate: [`s${i}`, "autoAlpha"], html });
+ return html;
})
.join("\n ");
@@ -447,15 +495,19 @@ export function deckHtml(schedule, render, opts = {}) {
const vSize = Math.max(pip.size, Math.round((pip.size * 5) / 3));
const pipHtml = pips
.map((p, k) => {
- const base = `<div class="pip" style="left:${r4(p.x - pip.size / 2)}px"></div>`;
- if (!p.verdict) return base + `<div class="pip lit" data-k="pip${k}" style="left:${r4(p.x - pip.size / 2)}px"></div>`;
- const color = verdictColors[p.verdict]?.color ?? pal.accent;
- return (
- base +
- `<div class="pip lit vpip" data-k="pip${k}" data-verdict="${esc(p.verdict)}" data-shape="${VERDICT_SHAPES[p.verdict]}" ` +
- `style="left:${r4(p.x - vSize / 2)}px; top:${r4(-vSize / 2)}px; width:${vSize}px; height:${vSize}px; ` +
- `${shapeCss(VERDICT_SHAPES[p.verdict], vSize, esc(color))}"></div>`
- );
+ const base = `<div class="pip"${pitched && k > 0 ? ` data-k="pb${k}"` : ""} style="left:${r4(p.x - pip.size / 2)}px"></div>`;
+ const color = p.verdict ? verdictColors[p.verdict]?.color ?? pal.accent : null;
+ const lit = !p.verdict
+ ? `<div class="pip lit" data-k="pip${k}" style="left:${r4(p.x - pip.size / 2)}px"></div>`
+ : `<div class="pip lit vpip" data-k="pip${k}" data-verdict="${esc(p.verdict)}" data-shape="${shapes[p.verdict]}" ` +
+ `style="left:${r4(p.x - vSize / 2)}px; top:${r4(-vSize / 2)}px; width:${vSize}px; height:${vSize}px; ` +
+ `${shapeCss(shapes[p.verdict], vSize, esc(color))}"></div>`;
+ if (items) {
+ // A pip at a fixed pitch is drawn only once the fuse sets off for it.
+ if (pitched && k > 0) items.push({ key: `pb${k}`, gate: [`pb${k}`, "opacity"], html: base });
+ items.push({ key: `pip${k}`, gate: [`pip${k}`, "opacity"], html: lit });
+ }
+ return base + lit;
})
.join("");
// The markers: a flag on the track and its label in the band above it.
@@ -487,7 +539,7 @@ export function deckHtml(schedule, render, opts = {}) {
? `<div class="tally">` +
tally
.map((v, j) => {
- const finals = tallyFinals(schedule.factcheck.stamps)[v];
+ const finals = tallyFinals(schedule.factcheck.stamps, counter.order)[v];
const color = verdictSet[v].color;
const nums = Array.from({ length: finals + 1 }, (_, k) =>
`<div class="tn" data-k="${tallyKey(v, `n${k}`)}">${k}</div>`).join("");
@@ -500,7 +552,7 @@ export function deckHtml(schedule, render, opts = {}) {
// top corner (the label keeps its width): the key a viewer who
// cannot tell the colours apart reads the rail by.
(byVerdict
- ? `<div class="tshape" data-shape="${VERDICT_SHAPES[v]}" style="${shapeCss(VERDICT_SHAPES[v], 12, esc(color))}"></div>`
+ ? `<div class="tshape" data-shape="${shapes[v]}" style="${shapeCss(shapes[v], 12, esc(color))}"></div>`
: "") +
// tallyLabelOf: the cell's own short word, else the label (or its
// last words) that fits -- never an ellipsis.
@@ -523,7 +575,7 @@ export function deckHtml(schedule, render, opts = {}) {
: null;
const fuseLeft = pips[0]?.x ?? tr.x0;
- const fuseWidth = pips.length > 1 ? pips[pips.length - 1].x - fuseLeft : 0;
+ const fuseWidth = pips.length > 1 ? (pitched ? tr.x1 - fuseLeft : pips[pips.length - 1].x - fuseLeft) : 0;
const data = {
total,
diff --git a/umtool/report-to-video/chrome-feed.mjs b/umtool/report-to-video/chrome-feed.mjs
@@ -356,6 +356,9 @@ export function feedHtml(schedule, render, opts = {}) {
const cardTop = mix(mix(pal.bg, pal.fg, 0.14), pal.accent, 0.06);
const cardBottom = mix(mix(pal.bg, pal.fg, 0.11), pal.accent, 0.03);
+ // The page's ITEMS (frame-keys.mjs): each card, drawn only from its post's
+ // event on -- collected when the caller asks (`opts.items`).
+ const items = Array.isArray(opts.items) ? opts.items : null;
const cardHtml = posts
.map((p, j) => {
const { name, platform } = postWho(p);
@@ -363,7 +366,7 @@ export function feedHtml(schedule, render, opts = {}) {
const shot = shotSrcs[p.id];
// A thread shot is marked, so the page gives it the column (feedShotLone `whole`).
const whole = threadShots.has(p.id) ? ` data-thread="1"` : "";
- return (
+ const html = (
`<article class="post${shot ? " has-shot" : ""}" data-post="${esc(p.id)}" data-k="c${j}">` +
(shot
? `<div class="body shot-body"><img class="shot" src="${esc(shot)}"${whole} alt=""></div>`
@@ -383,6 +386,8 @@ export function feedHtml(schedule, render, opts = {}) {
`<div class="hl" data-k="h${j}"></div>` +
`</article>`
);
+ if (items) items.push({ key: `c${j}`, event: j, html });
+ return html;
})
.join("\n ");
diff --git a/umtool/report-to-video/chrome-feed.test.mjs b/umtool/report-to-video/chrome-feed.test.mjs
@@ -560,3 +560,25 @@ test("the page: a thread shot is marked and carries feedShotWhole; the .shot rul
const plain = page(posts, { shotSrcs: { b: "assets/shot00.png" } }).html;
assert.doesNotMatch(plain, /feedShotWhole|data-thread/);
});
+
+test("the feed module: a thread shot the composer drew in place of a post's shot reaches the page marked", async () => {
+ const { default: feedModule } = await import("./modules/feed.mjs");
+ const s = sched(FEED, [POST("a", "2024-10-19"), POST("b", "2024-11-27")]);
+ const asked = [];
+ const ctx = {
+ render: FEED, schedule: s, from: 0, duration: undefined,
+ fonts: async () => FONTS,
+ qrs: async (urls) => new Map(urls.map((u, i) => [u, `assets/qr0${i}.png`])),
+ // compose-chrome's helper: adds to `threads` the posts whose thread shot it copied.
+ shots: async (posts, key = "shot", threads = null) => {
+ asked.push(key);
+ if (key !== "shot") return {};
+ threads?.add("b");
+ return { b: "assets/shot00.png" };
+ },
+ };
+ const { html } = await feedModule.page(ctx);
+ assert.deepEqual(asked, ["shot"]);
+ assert.ok(html.includes('<img class="shot" src="assets/shot00.png" data-thread="1" alt="">'));
+ assert.match(html, /feedShotWhole/);
+});
diff --git a/umtool/report-to-video/chrome-finale.mjs b/umtool/report-to-video/chrome-finale.mjs
@@ -25,7 +25,8 @@
import { cueTime, cueTimeAfter, finaleRail, pageDuration, resolveDeck } from "./deck.mjs";
import { finaleClaimsMarkup } from "./chrome-claims.mjs";
import { mix, rgba, shapeCss, subtitleMarkup } from "./chrome-deck.mjs";
-import { resolveFactcheck, tallyFinals, tallyOf, tallyVerdicts, VERDICT_SHAPES } from "./factcheck.mjs";
+import { resolveFactcheck, tallyFinals, tallyOf, tallyVerdicts } from "./factcheck.mjs";
+import { resolveCounter } from "./counter.mjs";
import { aboveTop, FINALE_CLAIMS, FINALE_MOTION, finaleGeometry, resolveFinale } from "./finale.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
@@ -61,7 +62,8 @@ export function finaleLayout(schedule, render) {
const fc = resolveFactcheck(render);
const pal = render.palette;
const stamps = schedule.factcheck?.stamps ?? [];
- const verdicts = f.totals && stamps.length ? tallyVerdicts(stamps) : [];
+ const counter = resolveCounter(render);
+ const verdicts = f.totals && stamps.length ? tallyVerdicts(stamps, counter.order) : [];
// The large rail (deck.mjs finaleRail): in the room the schedule gave it.
const R = finaleRail(schedule, render, { railBottom: fin.railBottom ?? finaleGeometry(render).rail.bottom, textScale: fin.textScale ?? 1 });
const { geo, x0, labels, marks, claims, lay, fxs, footSize } = R;
@@ -74,13 +76,13 @@ export function finaleLayout(schedule, render) {
const tally = tallyOf(schedule, render);
// The totals: the tally's verdicts, each at its final count.
- const finals = tallyFinals(stamps);
+ const finals = tallyFinals(stamps, counter.order);
const tb = lay.tally ?? null;
const T = geo.totals;
const totals = T
? verdicts.map((v, j) => ({
verdict: v, count: finals[v], label: verdictColors[v]?.label ?? v, color: verdictColors[v]?.color ?? pal.accent,
- shape: VERDICT_SHAPES[v], x: T.x + j * (T.cell + T.gap), y: T.y, width: T.cell, height: T.height,
+ shape: counter.shapes[v], x: T.x + j * (T.cell + T.gap), y: T.y, width: T.cell, height: T.height,
...(tb && tally?.[j] === v ? { foot: { x: tb.x + j * (tb.cell + tb.gap), y: deckY + tb.y, width: tb.cell, height: tb.height } } : {}),
}))
: [];
diff --git a/umtool/report-to-video/chrome-fx.mjs b/umtool/report-to-video/chrome-fx.mjs
@@ -16,10 +16,9 @@
// the page: every size is in the data (a screenshot's pixels are read by
// compose-chrome before the page is written). The glitch's noise is a seeded
// generator's (fxRandom), so frame 412 is the same tear on every worker.
-import { fileURLToPath } from "node:url";
import { fxGeometry, pageDuration } from "./deck.mjs";
-import { mix, rgba } from "./chrome-deck.mjs";
+import { assetFile, mix, rgba } from "./chrome-deck.mjs";
import { FX_MOTION, INSTANT, compileCues, fxRandom, noNegZero } from "./fx.mjs";
const esc = (s) =>
@@ -34,7 +33,8 @@ const r2 = (v) => Math.round(v * 100) / 100 || 0;
const r4 = (v) => Math.round(v * 10000) / 10000 || 0;
/** The VHS stamp's mono, vendored beside the brand's faces; copied in as `assets/FxMono.ttf`. */
-export const FX_MONO_FILE = fileURLToPath(new URL("./fonts/IBMPlexMono-Bold.ttf", import.meta.url));
+// Through assetFile (chrome-deck.mjs): a server bundle's asset URL is not fileURLToPath's.
+export const FX_MONO_FILE = assetFile(new URL("./fonts/IBMPlexMono-Bold.ttf", import.meta.url));
/** THEN's colour when the palette names none (`palette.then`), as the flips panel's. */
export const FX_THEN_COLOR = "#6fa8dc";
diff --git a/umtool/report-to-video/chrome-intro.mjs b/umtool/report-to-video/chrome-intro.mjs
@@ -17,7 +17,9 @@
// a render is a seek per frame, from parallel workers, in any order). Every
// cue is a fromTo whose FROM is stated; the page is a dumb interpreter of
// `introCues`, so the tests read every time it uses.
-import { INTRO_BEATS, INTRO_SITE_DEFAULTS, INTRO_STYLE_MARK, introSitePrefix } from "yt-dlp-transcript-common/lib/report/intro.mjs";
+import {
+ INTRO_BEATS, INTRO_PROJECT_URL, INTRO_SITE_DEFAULTS, INTRO_STYLE_MARK, INTRO_SUFFIX, introSitePrefix, introUrlText,
+} from "yt-dlp-transcript-common/lib/report/intro.mjs";
import { pageDuration } from "./deck.mjs";
import { INTRO_GLYPHS, INTRO_GLYPH_CAP, INTRO_GLYPH_UPEM } from "./intro-glyphs.mjs";
@@ -147,8 +149,12 @@ export function lockupParts(kit) {
// The site swap (`render.intro.site`).
// ---------------------------------------------------------------------------
-/** The project's own URL, as the intro writes it: common/lib/project.ts PROJECT_URL without its scheme. */
-export const PROJECT_URL_TEXT = "archilyzer.pages.dev";
+/**
+ * The project's own URL, as the intro writes it: common/lib/project.ts
+ * PROJECT_URL without its scheme -- the default; `render.intro.projectUrl`
+ * sets another brand's (or false: none).
+ */
+export const PROJECT_URL_TEXT = INTRO_PROJECT_URL;
/** The weights the swap draws in (intro-glyphs.mjs): the wordmark's lead and suffix, and the URLs. */
const W_LEAD = 720;
@@ -241,12 +247,15 @@ export function setRun(text, { size, track = 0, weightOf = () => W_URL, x = 0, b
* it. A lead that runs into "lyzer" (Bonnell|yzer) takes those letters too; a
* name not ending in "lyzer" swaps the whole word.
*/
-export function swapPlan({ parts, site, url = INTRO_SITE_DEFAULTS.url, urlPlace = INTRO_SITE_DEFAULTS.urlPlace, markX = null }) {
+export function swapPlan({
+ parts, site, url = INTRO_SITE_DEFAULTS.url, urlPlace = INTRO_SITE_DEFAULTS.urlPlace, markX = null,
+ suffix = INTRO_SUFFIX, projectUrl = PROJECT_URL_TEXT,
+}) {
const word = parts.letters.filter((l) => l.role !== "media");
const media = parts.letters.filter((l) => l.role === "media");
const nW = word.length;
const name = String(site.name);
- let prefix = introSitePrefix(name);
+ let prefix = introSitePrefix(name, suffix);
const lead = typeof site.lead === "string" && name.startsWith(site.lead) && site.lead.length < name.length ? site.lead : null;
if (lead && lead.length > prefix.length) prefix = name.slice(0, lead.length);
const keep = name.length - prefix.length;
@@ -309,7 +318,8 @@ export function swapPlan({ parts, site, url = INTRO_SITE_DEFAULTS.url, urlPlace
const siteUrl = typeof site.url === "string" && site.url ? site.url : null;
const texts = [];
if ((url === "both" || url === "site") && siteUrl) texts.push({ text: siteUrl, tone: "site" });
- if (url === "both" || url === "project") texts.push({ text: PROJECT_URL_TEXT, tone: "project" });
+ const project = projectUrl === false ? null : introUrlText(projectUrl) || null;
+ if ((url === "both" || url === "project") && project) texts.push({ text: project, tone: "project" });
const urls = [];
const cap = INTRO_GLYPH_CAP / INTRO_GLYPH_UPEM;
let bottom = parts.bottom;
@@ -711,6 +721,7 @@ function markShapes(mark) {
export function introHtml({
style, ground, mark = INTRO_STYLE_MARK[style] ?? "none", seconds, width = 1920, height = 1080, fps = 30, kit, gsapSrc = "assets/gsap.min.js",
site = null, swap = INTRO_SITE_DEFAULTS.swap, url = INTRO_SITE_DEFAULTS.url, urlPlace = INTRO_SITE_DEFAULTS.urlPlace,
+ suffix = INTRO_SUFFIX, projectUrl = PROJECT_URL_TEXT,
}) {
const W = width;
const H = height;
@@ -734,7 +745,7 @@ export function introHtml({
// centring -- so on the chime it only ever moves sideways, never a vertical
// lift (operator, 2026-10-26).
const oy = r3(H / 2 - ((y0 + y1) / 2) * k);
- const plan = site ? swapPlan({ parts, site, url, urlPlace, markX: withMark ? parts.mark.x : null }) : null;
+ const plan = site ? swapPlan({ parts, site, url, urlPlace, markX: withMark ? parts.mark.x : null, suffix, projectUrl }) : null;
const accent = site ? introAccent(site.accent, ground, palette) : null;
const lift = 0;
const { init, cues } = introCues({
diff --git a/umtool/report-to-video/chrome-story.mjs b/umtool/report-to-video/chrome-story.mjs
@@ -0,0 +1,386 @@
+// THE STORY PAGES (release 39): the pages of the `pair`, `chapter` and
+// `status` modules (modules/pair.mjs, chapter.mjs, status.mjs), each a cue
+// page (chrome-cues.mjs). PURE: a schedule and a render block in, the slice
+// a module draws and its HTML out.
+//
+// - PAIR: then and now -- two clips on one subject, each with its date. As
+// "split" a strip in the footage box, THEN on one side and NOW on the
+// other, the side playing lit, the caption under them, up while either
+// clip plays; as "then→now" a card with both dates and an arrow over the
+// first `seconds` of the pair. The footage itself is not split: two clips
+// never play at once.
+// - CHAPTER: a section bumper over the first `seconds` of the clip it opens
+// (a window of the cut, laid at its own second): title, subtitle, date.
+// - STATUS: a ledger, a row per item -- "announced <date> → <outcome>" --
+// that fills as the cut plays: a row comes in on its first clip, its
+// outcome on the outcome's clip (else the end of its last evidence clip).
+// Each STATE of the ledger is its own block, shown over exactly its span.
+import { deckGeometry, feedGeometry } from "./deck.mjs";
+import { rgba } from "./chrome-deck.mjs";
+import { compileCues, cuePageHtml, dateText, esc, joinSpans, r4, segmentSpans, spanEvents, INSTANT } from "./chrome-cues.mjs";
+import { CHAPTER_DEFAULTS, PAIR_DEFAULTS, STATUS_DEFAULTS } from "./modules/story-settings.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** The footage box this cut's clips play in (the feed's when it is one). */
+export function footageBox(render, { feed = false } = {}) {
+ const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage;
+ return { x: f.x, y: f.y, width: f.width, height: f.height };
+}
+
+const scaleOf = (render) => (render?.width ?? 1920) / 1920;
+const pxOf = (render) => (v) => Math.max(1, Math.round(v * scaleOf(render)));
+const even = (v) => 2 * Math.round(v / 2);
+
+// ---------------------------------------------------------------------------
+// PAIR
+// ---------------------------------------------------------------------------
+
+export function resolvePair(render) {
+ const v = isObj(render?.chrome?.pair) ? render.chrome.pair : {};
+ return {
+ ...PAIR_DEFAULTS, ...v,
+ labels: { ...PAIR_DEFAULTS.labels, ...(isObj(v.labels) ? v.labels : {}) },
+ pairs: Array.isArray(v.pairs) ? v.pairs : [],
+ };
+}
+
+/** The pair strip's region: a band across the footage box, at its foot (or top). */
+export function pairGeometry(render, { feed = false } = {}) {
+ const f = footageBox(render, { feed });
+ const px = pxOf(render);
+ const P = resolvePair(render);
+ const height = even(px(P.style === "then→now" ? 200 : 132));
+ const inset = px(18);
+ const width = even(f.width - 2 * inset);
+ return {
+ x: f.x + inset,
+ y: P.position === "top" ? f.y + inset : f.y + f.height - inset - height,
+ width, height,
+ };
+}
+
+/**
+ * The pairs this cut plays, in the cut's clock: each `{ i, style, then, now,
+ * caption, topic, spans: [{in, out}], phases: [{side, in, out}] }` -- a pair
+ * none of whose clips is in the cut is left out.
+ */
+export function pairSchedule(schedule, render) {
+ const P = resolvePair(render);
+ const at = segmentSpans(schedule);
+ const out = [];
+ P.pairs.forEach((p, i) => {
+ if (!isObj(p?.then) || !isObj(p?.now)) return;
+ const sides = [
+ { side: "then", clip: p.then.clip },
+ { side: "now", clip: p.now.clip },
+ ...(Array.isArray(p.also) ? p.also.map((a) => ({ side: a.side, clip: a.clip })) : []),
+ ];
+ const phases = [];
+ for (const s of sides) {
+ const sp = at.get(s.clip);
+ if (!sp) continue;
+ const same = p.then.clip === p.now.clip;
+ phases.push({ side: same ? "both" : s.side, in: sp.in, out: sp.out });
+ }
+ if (!phases.length) return;
+ // One phase per span: a clip named twice (then and now the same clip) once.
+ const seen = new Set();
+ const uniq = phases.filter((ph) => (seen.has(ph.in) ? false : (seen.add(ph.in), true))).sort((a, b) => a.in - b.in);
+ out.push({
+ i, style: p.style ?? P.style, then: p.then, now: p.now, caption: p.caption ?? "", topic: p.topic ?? "",
+ phases: uniq, spans: joinSpans(uniq.map((ph) => ({ in: ph.in, out: ph.out })), 0.75),
+ });
+ });
+ return out;
+}
+
+/** The pair page's cues: a pair's block `p<i>` in over its spans; `p<i>.t` / `p<i>.n` lit by phase. */
+export function pairCues(pairs, P) {
+ const init = {};
+ const ev = [];
+ for (const p of pairs) {
+ const k = `p${p.i}`;
+ init[k] = { autoAlpha: 0 };
+ if (p.style === "then→now") {
+ const a = p.spans[0].in;
+ const b = Math.min(p.spans[0].out, a + P.seconds);
+ ev.push(...spanEvents(k, a, b, { fadeIn: 0.4, fadeOut: 0.4 }));
+ continue;
+ }
+ for (const sp of p.spans) ev.push(...spanEvents(k, sp.in, sp.out));
+ for (const side of ["t", "n"]) init[`${k}.${side}`] = { opacity: 0.35 };
+ for (const ph of p.phases) {
+ const lit = ph.side === "both" ? ["t", "n"] : [ph.side === "then" ? "t" : "n"];
+ for (const s of lit) {
+ ev.push({ k: `${k}.${s}`, at: ph.in, dur: 0.3, to: { opacity: 1 }, ease: "power1.out" });
+ ev.push({ k: `${k}.${s}`, at: Math.max(ph.in + 0.3, ph.out - 0.3), dur: 0.3, to: { opacity: 0.35 }, ease: "power1.in" });
+ }
+ }
+ }
+ return compileCues(init, ev);
+}
+
+/**
+ * The pair page: `{ html, items }` (each pair's block an item, gated by its
+ * own autoAlpha -- a changed caption recaptures only the frames it is up).
+ */
+export function pairHtml(schedule, render, opts = {}) {
+ const P = resolvePair(render);
+ const pairs = pairSchedule(schedule, render);
+ if (!pairs.length) throw new Error("pair: the cut plays none of the pairs' clips");
+ const geo = pairGeometry(render, { feed: schedule.layout === "feed" });
+ const pal = render.palette;
+ const px = pxOf(render);
+ const fps = schedule.fps ?? render.fps ?? 30;
+ const { init, cues } = pairCues(pairs, P);
+ const items = [];
+ const blocks = pairs.map((p) => {
+ const k = `p${p.i}`;
+ const d = (s) => esc(dateText(s?.date, P.dateFormat));
+ const label = (side) => esc(p[side]?.label ?? P.labels[side]);
+ let html;
+ if (p.style === "then→now") {
+ html = `<div class="pair card" data-k="${k}"><div class="row"><div class="side"><div class="lab">${label("then")}</div><div class="date">${d(p.then)}</div></div><div class="arrow">→</div><div class="side"><div class="lab">${label("now")}</div><div class="date">${d(p.now)}</div></div></div>${p.caption ? `<div class="cap">${esc(p.caption)}</div>` : ""}</div>`;
+ } else {
+ html = `<div class="pair split" data-k="${k}"><div class="row"><div class="side t" data-k="${k}.t"><span class="lab">${label("then")}</span><span class="date">${d(p.then)}</span></div><div class="mid">${p.topic ? esc(p.topic) : "→"}</div><div class="side n" data-k="${k}.n"><span class="lab">${label("now")}</span><span class="date">${d(p.now)}</span></div></div>${p.caption ? `<div class="cap">${esc(p.caption)}</div>` : ""}</div>`;
+ }
+ items.push({ key: k, gate: [k, "autoAlpha"], html });
+ return html;
+ });
+ const css = `
+ .pair { position: absolute; inset: 0; visibility: hidden; opacity: 0; border-radius: ${px(10)}px;
+ background: ${rgba(pal.bg, 0.94)}; box-shadow: 0 ${px(8)}px ${px(26)}px rgba(0, 0, 0, 0.4);
+ padding: ${px(12)}px ${px(22)}px; display: flex; flex-direction: column; justify-content: center; gap: ${px(6)}px; }
+ .row { display: flex; align-items: center; justify-content: space-between; gap: ${px(18)}px; }
+ .side { display: flex; align-items: baseline; gap: ${px(12)}px; white-space: nowrap; }
+ .split .side.n { justify-content: flex-end; }
+ .lab { font-family: 'DeckSansBold', sans-serif; font-size: ${px(22)}px; letter-spacing: 0.12em; text-transform: uppercase; color: ${pal.accent}; }
+ .date { font-family: 'DeckSansBold', sans-serif; font-size: ${px(34)}px; color: ${pal.fg}; font-variant-numeric: tabular-nums; }
+ .mid { flex: 1 1 auto; min-width: 0; text-align: center; font-size: ${px(24)}px; color: ${pal.muted};
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .cap { font-size: ${px(24)}px; line-height: ${px(30)}px; color: ${pal.fg}; text-align: center;
+ display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
+ .card .row { justify-content: center; gap: ${px(40)}px; }
+ .card .side { flex-direction: column; align-items: center; gap: ${px(4)}px; }
+ .card .date { font-size: ${px(46)}px; }
+ .arrow { font-family: 'DeckSansBold', sans-serif; font-size: ${px(56)}px; color: ${pal.accent}; }`;
+ const html = cuePageHtml({
+ id: "pair", W: geo.width, H: geo.height, fps, fonts: opts.fonts, gsapSrc: opts.gsap, css,
+ body: blocks.join("\n "), init, cues,
+ whole: { total: schedule.total, from: opts.from, duration: opts.duration, ids: pairs.map((p) => `p${p.i}`) },
+ });
+ return { html, items };
+}
+
+// ---------------------------------------------------------------------------
+// CHAPTER
+// ---------------------------------------------------------------------------
+
+export function resolveChapter(render) {
+ const v = isObj(render?.chrome?.chapter) ? render.chrome.chapter : {};
+ return { ...CHAPTER_DEFAULTS, ...v, list: Array.isArray(v.list) ? v.list : [] };
+}
+
+/**
+ * The chapters this cut plays, each its window: `{ segment, from, to, n,
+ * title, subtitle, date }` -- `segment` the clip it opens, the window its
+ * first `seconds` (never past the clip).
+ */
+export function chapterWindows(schedule, render) {
+ const C = resolveChapter(render);
+ const at = segmentSpans(schedule);
+ const out = [];
+ C.list.forEach((c, n) => {
+ const sp = at.get(c?.at);
+ if (!sp) return;
+ const to = Math.min(sp.out, sp.in + C.seconds);
+ if (!(to - sp.in > 0.2)) return;
+ out.push({ segment: c.at, from: sp.in, to, n, title: c.title, subtitle: c.subtitle ?? "", date: c.date ?? null });
+ });
+ return out;
+}
+
+/** The chapter bumper's region: the footage box. */
+export function chapterGeometry(render, { feed = false } = {}) {
+ return footageBox(render, { feed });
+}
+
+/** One chapter window's page. `window` is the snapped `{ segment, from, to }`. */
+export function chapterHtml(schedule, render, window, opts = {}) {
+ const C = resolveChapter(render);
+ const ch = chapterWindows(schedule, render).find((w) => w.segment === window.segment);
+ if (!ch) throw new Error(`chapter: no chapter opens ${window.segment} in this cut`);
+ const geo = chapterGeometry(render, { feed: schedule.layout === "feed" });
+ const pal = render.palette;
+ const px = pxOf(render);
+ const fps = schedule.fps ?? render.fps ?? 30;
+ const from = r4(window.from);
+ const dur = r4(window.to - window.from);
+ const ev = [...spanEvents("ch", from, from + dur, { fadeIn: 0.25, fadeOut: 0.45 })];
+ ev.push({ k: "ch.t", at: from, dur: 0.5, to: { y: 0 }, ease: "power2.out" });
+ const { init, cues } = compileCues({ ch: { autoAlpha: 0 }, "ch.t": { y: px(18) } }, ev);
+ const lower = C.style === "lower";
+ const date = ch.date ? dateText(ch.date) : "";
+ const css = `
+ .chapter { position: absolute; visibility: hidden; opacity: 0; display: flex; flex-direction: column;
+ ${lower
+ ? `left: 0; right: 0; bottom: 0; height: ${px(220)}px; padding: ${px(26)}px ${px(48)}px; justify-content: center;
+ background: linear-gradient(to top, ${rgba(pal.bg, 0.94)}, ${rgba(pal.bg, 0.0)});`
+ : `inset: 0; align-items: center; justify-content: center; text-align: center; padding: ${px(60)}px;
+ background: ${rgba(pal.bg, 0.92)};`} }
+ .ct { display: flex; flex-direction: column; gap: ${px(12)}px; ${lower ? "" : "align-items: center;"} }
+ .rule { width: ${px(96)}px; height: ${px(6)}px; background: ${pal.accent}; border-radius: ${px(3)}px; }
+ .title { font-family: 'DeckSansBold', sans-serif; font-size: ${px(lower ? 54 : 84)}px; line-height: 1.08; color: ${pal.fg}; }
+ .sub { font-size: ${px(lower ? 28 : 36)}px; line-height: 1.25; color: ${pal.muted}; max-width: ${px(1300)}px; }
+ .date { font-family: 'DeckSansBold', sans-serif; font-size: ${px(26)}px; letter-spacing: 0.12em; text-transform: uppercase; color: ${pal.accent}; }`;
+ const body = `<div class="chapter" data-k="ch"><div class="ct" data-k="ch.t"><div class="rule"></div>${date ? `<div class="date">${esc(date)}</div>` : ""}<div class="title">${esc(ch.title)}</div>${ch.subtitle ? `<div class="sub">${esc(ch.subtitle)}</div>` : ""}</div></div>`;
+ return cuePageHtml({
+ id: "chapter", W: geo.width, H: geo.height, fps, fonts: opts.fonts, gsapSrc: opts.gsap, css, body, init, cues,
+ window: { from, dur },
+ });
+}
+
+// ---------------------------------------------------------------------------
+// STATUS
+// ---------------------------------------------------------------------------
+
+export function resolveStatus(render) {
+ const v = isObj(render?.chrome?.status) ? render.chrome.status : {};
+ return { ...STATUS_DEFAULTS, ...v, items: Array.isArray(v.items) ? v.items : [] };
+}
+
+const sideClip = (s) => (isObj(s) && typeof s.clip === "string" ? s.clip : null);
+const sideText = (s, fmt = "long") => {
+ if (typeof s === "string") return s;
+ if (!isObj(s)) return "";
+ const d = s.date ? dateText(s.date, fmt) : "";
+ return [d, s.text ?? ""].filter(Boolean).join(" · ");
+};
+
+/**
+ * The ledger's rows in the cut's clock: each `{ n, item, announced, outcome,
+ * in, done }` -- `in` the second it comes in (its first clip's start),
+ * `done` the second its outcome is filled (the outcome's clip, else the end
+ * of its last clip), null when no outcome is given. Rows none of whose clips
+ * the cut plays are left out.
+ */
+export function statusRows(schedule, render) {
+ const S = resolveStatus(render);
+ const at = segmentSpans(schedule);
+ const rows = [];
+ S.items.forEach((it, n) => {
+ const clips = [sideClip(it.announced), ...(Array.isArray(it.evidence) ? it.evidence : []), sideClip(it.outcome)].filter(Boolean);
+ const spans = clips.map((c) => at.get(c)).filter(Boolean);
+ if (!spans.length) return;
+ const first = Math.min(...spans.map((s) => s.in));
+ const last = Math.max(...spans.map((s) => s.out));
+ const oc = sideClip(it.outcome);
+ const hasOutcome = it.outcome !== undefined && sideText(it.outcome) !== "";
+ const done = !hasOutcome ? null : oc && at.get(oc) ? Math.max(first, at.get(oc).in) : last;
+ rows.push({
+ n, item: it.item, announced: sideText(it.announced), outcome: hasOutcome ? sideText(it.outcome) : "",
+ in: first, done: done == null ? null : Math.max(first, done), last,
+ });
+ });
+ return rows.sort((a, b) => a.in - b.in || a.n - b.n);
+}
+
+/**
+ * The ledger's states: between two events (a row in, an outcome filled) it
+ * reads the same. `fill`: from the first row on, the last `rows` rows; `each`:
+ * a row alone, over its own clips.
+ */
+export function statusStates(schedule, render) {
+ const S = resolveStatus(render);
+ const rows = statusRows(schedule, render);
+ const total = schedule.total;
+ if (S.mode === "each") {
+ return rows.flatMap((r) => {
+ const parts = [];
+ if (r.done != null && r.done > r.in + 0.05 && r.done < r.last) {
+ parts.push({ at: r.in, until: r.done, rows: [{ ...r, filled: false }] });
+ parts.push({ at: r.done, until: r.last, rows: [{ ...r, filled: true }] });
+ } else parts.push({ at: r.in, until: r.last, rows: [{ ...r, filled: r.done != null && r.done <= r.in + 0.05 }] });
+ return parts;
+ });
+ }
+ const events = [...new Set(rows.flatMap((r) => [r.in, ...(r.done != null ? [r.done] : [])]).map(r4))].sort((a, b) => a - b);
+ return events.map((t, j) => {
+ const shown = rows.filter((r) => r.in <= t + 1e-6).slice(-S.rows);
+ return { at: t, until: events[j + 1] ?? total, rows: shown.map((r) => ({ ...r, filled: r.done != null && r.done <= t + 1e-6 })) };
+ });
+}
+
+/** The ledger's region: a column in a corner of the footage box, as tall as `rows` rows. */
+export function statusGeometry(render, { feed = false } = {}) {
+ const f = footageBox(render, { feed });
+ const S = resolveStatus(render);
+ const px = pxOf(render);
+ const width = even(Math.min(px(S.width), f.width - 2 * px(18)));
+ const height = even(Math.min(f.height - 2 * px(18), px(58) + S.rows * px(92)));
+ const inset = px(18);
+ const right = S.position.endsWith("right");
+ const bottom = S.position.startsWith("bottom");
+ return {
+ x: right ? f.x + f.width - inset - width : f.x + inset,
+ y: bottom ? f.y + f.height - inset - height : f.y + inset,
+ width, height,
+ };
+}
+
+/** The status page: `{ html, items }`, each state an item gated by its own autoAlpha. */
+export function statusHtml(schedule, render, opts = {}) {
+ const S = resolveStatus(render);
+ const states = statusStates(schedule, render);
+ if (!states.length) throw new Error("status: the cut plays none of the ledger's clips");
+ const geo = statusGeometry(render, { feed: schedule.layout === "feed" });
+ const pal = render.palette;
+ const px = pxOf(render);
+ const fps = schedule.fps ?? render.fps ?? 30;
+ const bottom = S.position.startsWith("bottom");
+ const init = { lg: { autoAlpha: 0 } };
+ const ev = [];
+ const spans = joinSpans(states.map((s) => ({ in: s.at, out: s.until })), 1e-3);
+ for (const sp of spans) ev.push(...spanEvents("lg", sp.in, sp.out, { fadeIn: 0.35, fadeOut: 0.35 }));
+ const items = [];
+ const blocks = states.map((st, j) => {
+ const k = `s${j}`;
+ init[k] = { autoAlpha: 0 };
+ ev.push({ k, at: st.at, dur: INSTANT, to: { autoAlpha: 1 }, ease: "none" });
+ ev.push({ k, at: st.until, dur: INSTANT, to: { autoAlpha: 0 }, ease: "none" });
+ const rows = st.rows.map((r) => `<div class="r${r.filled ? " done" : ""}"><div class="it">${esc(r.item)}</div><div class="ln"><span class="an">${esc(r.announced || "announced")}</span><span class="ar">→</span><span class="oc">${r.filled ? esc(r.outcome) : "…"}</span></div></div>`).join("");
+ const html = `<div class="st" data-k="${k}"><div class="hd">${esc(S.title)}</div>${rows}</div>`;
+ items.push({ key: k, gate: [k, "autoAlpha"], html });
+ return html;
+ });
+ const { init: i2, cues } = compileCues(init, ev);
+ const css = `
+ #ledger { position: absolute; inset: 0; visibility: hidden; opacity: 0; }
+ /* Each state is its own card, as tall as its rows, from the corner it is anchored to. */
+ .st { position: absolute; left: 0; right: 0; ${bottom ? "bottom: 0;" : "top: 0;"} visibility: hidden; opacity: 0;
+ display: flex; flex-direction: column; gap: ${px(10)}px; padding: ${px(12)}px ${px(20)}px ${px(14)}px ${px(20)}px;
+ border-radius: ${px(10)}px; background: ${rgba(pal.bg, 0.94)}; border-left: ${px(5)}px solid ${pal.accent};
+ box-shadow: 0 ${px(8)}px ${px(26)}px rgba(0, 0, 0, 0.4); }
+ .hd { font-family: 'DeckSansBold', sans-serif; font-size: ${px(20)}px; line-height: ${px(26)}px; letter-spacing: 0.12em;
+ text-transform: uppercase; color: ${pal.muted}; }
+ .r { display: flex; flex-direction: column; gap: ${px(2)}px; }
+ .it { font-family: 'DeckSansBold', sans-serif; font-size: ${px(24)}px; line-height: ${px(30)}px; color: ${pal.fg};
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .ln { display: flex; gap: ${px(10)}px; font-size: ${px(21)}px; line-height: ${px(28)}px; color: ${pal.muted}; white-space: nowrap; min-width: 0; }
+ .an { flex: 0 1 auto; overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 45%; }
+ .ar { flex: none; color: ${pal.accent}; font-family: 'DeckSansBold', sans-serif; }
+ .oc { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
+ /* Before its outcome a row's announcement takes the line. */
+ .r:not(.done) .an { max-width: none; }
+ .r:not(.done) .oc { flex: 0 0 auto; }
+ .done .oc { color: ${pal.amber ?? pal.fg}; }`;
+ const body = `<div id="ledger" data-k="lg">
+ ${blocks.join("\n ")}
+ </div>`;
+ const html = cuePageHtml({
+ id: "status", W: geo.width, H: geo.height, fps, fonts: opts.fonts, gsapSrc: opts.gsap, css, body, init: i2, cues,
+ whole: { total: schedule.total, from: opts.from, duration: opts.duration, ids: states.map((_, j) => `s${j}`) },
+ });
+ return { html, items };
+}
diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs
@@ -36,24 +36,14 @@ import { execFile, spawn } from "node:child_process";
import { promisify } from "node:util";
import path from "node:path";
-import { ledgerTotals, dateKey } from "./ledger-totals.mjs";
+import { dateKey } from "./ledger-totals.mjs";
import { selectVariant } from "./build-video.mjs";
import { ensureWriteDir } from "../lib/report/storage.mjs";
-import {
- chromeCacheKey, deckLayout, frameCount, pageDuration, hyperframesCommand, postWindows, resolveDeck, sha256, teaserSeconds, transitionOf,
- validateTeaser,
-} from "./deck.mjs";
-import { deckHtml, GSAP_FILE } from "./chrome-deck.mjs";
-import { postsHtml, snapWindow, windowPosts } from "./chrome-posts.mjs";
-import { feedHtml } from "./chrome-feed.mjs";
-import { stampHtml } from "./chrome-stamp.mjs";
-import { stampsDrawn } from "./factcheck.mjs";
-import { threadsHtml } from "./chrome-threads.mjs";
-import { flipsHtml } from "./chrome-flips.mjs";
-import { statsHtml } from "./chrome-stats.mjs";
-import { finaleHtml, finaleLayout } from "./chrome-finale.mjs";
+import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, sha256, transitionOf } from "./deck.mjs";
+import { GSAP_FILE } from "./chrome-deck.mjs";
import { fxGeometry, threadShotOf } from "./deck.mjs";
import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs";
+import { regionCaching, regionModule } from "./modules/index.mjs";
const run = promisify(execFile);
@@ -742,117 +732,27 @@ export async function fxThumbs(schedule, base, render, assetsDir) {
/**
* Which HTML each chrome region is, with the assets it needs written into
- * `projDir/assets`. The chart's branch is the band as it shipped; only where
- * its GSAP comes from has changed.
+ * `projDir/assets`: the region's MODULE writes it (modules/<id>.mjs `page`),
+ * handed what it may touch -- the faces, the QR maker, the shots -- as
+ * helpers, so a module never reaches into the file system itself.
*/
async function regionHtml(region, { manifest, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, teaser, transition }) {
- if (region === "fx") {
- // The effects (chrome-fx.mjs): the deck's faces, a mono, the screenshots
- // the receipts and the zoom show, and the scrubber's thumbnails.
- // A page module reached by a dynamic import, as the teaser's: it carries
- // its mono as an asset URL (docs/quirks.md).
- const { fxHtml, FX_MONO_FILE } = await import("./chrome-fx.mjs");
- const render = manifest.render;
- const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- await copyFile(FX_MONO_FILE, path.join(assetsDir, "FxMono.ttf"));
- fonts.mono = "assets/FxMono.ttf";
- const shots = await copyFxShots(schedule.fx, manifestDir, assetsDir);
- const thumbs = schedule.fx.scrubber?.thumbs ? await fxThumbs(schedule, base, render, assetsDir) : {};
- return fxHtml(schedule, render, { fonts, assets: { shots, thumbs }, from, duration });
- }
- if (region === "chart") {
- const sched = schedule ?? JSON.parse(await readFile(path.join(base, "schedule.json"), "utf8"));
- const fonts = await copyFonts(manifest.render, assetsDir, { regular: "regular", bold: "bold" }, { strict: false });
- const totals = ledgerTotals(manifest.ledger);
- return chartBandHtml(manifest, totals, sched, { fonts, ...(duration ? { duration } : {}) });
- }
- if (region === "deck") {
- const render = manifest.render;
- const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- // With the schedule: a staggered marker band moves the QR down and may shrink it.
- const lay = deckLayout(render, { schedule });
- const qrSrcs = {};
- if (lay.qr) {
- const byUrl = await qrPngsFor(schedule.segments.map((s) => s.qrUrl), render, lay.qr.size, assetsDir);
- for (const s of schedule.segments) if (s.qrUrl) qrSrcs[s.id] = byUrl.get(s.qrUrl);
- }
- return deckHtml(schedule, render, { fonts, qrSrcs, from, duration });
- }
- if (region === "posts") {
- // The deck's faces and the deck's QR maker: a card is part of the deck's
- // family, not a second design.
- const render = manifest.render;
- const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- const posts = windowPosts(schedule, window.segment);
- // `posts.qr: false`: no codes are made, and the page draws none.
- const byUrl = resolveDeck(render).posts.qr === false
- ? new Map()
- : await qrPngsFor(posts.map((p) => p.qrUrl), render, resolveDeck(render).posts.qrSize, assetsDir);
- const qrSrcs = {};
- for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl);
- const shotSrcs = await copyShots(posts, manifestDir, assetsDir);
- const logoSrcs = await copyShots(posts, manifestDir, assetsDir, "logo");
- return postsHtml(schedule, render, window, { fonts, qrSrcs, shotSrcs, logoSrcs });
- }
- if (region === "feed") {
- // The posts feed: the deck's faces and QR maker, one page for the whole cut.
- const render = manifest.render;
- const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- const posts = schedule.posts ?? [];
- // `posts.qr: false`: no codes are made, and the page draws none.
- const byUrl = resolveDeck(render).posts.qr === false
- ? new Map()
- : await qrPngsFor(posts.map((p) => p.qrUrl), render, resolveDeck(render).posts.qrSize, assetsDir);
- const qrSrcs = {};
- for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl);
- // A thread shot (a reply over the post it answers) is drawn whole: the
- // feed gives it the column rather than the room beside the card under it.
- const threads = new Set();
- const shotSrcs = await copyShots(posts, manifestDir, assetsDir, "shot", threads);
- return feedHtml(schedule, render, { fonts, qrSrcs, shotSrcs, threadShots: [...threads], from, duration });
- }
- if (region === "stamp") {
- // The fact-check stamps (chrome-stamp.mjs): the deck's faces, no QR.
- const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- return stampHtml(schedule, manifest.render, { fonts, from, duration });
- }
- if (region === "threads") {
- // The thread rail (chrome-threads.mjs): the deck's faces, no QR.
- const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- return threadsHtml(schedule, manifest.render, { fonts, from, duration });
- }
- if (region === "flips") {
- // The flips panel (chrome-flips.mjs): the deck's faces, no QR.
- const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- return flipsHtml(schedule, manifest.render, { fonts, from, duration });
- }
- if (region === "stats") {
- // The stats region (chrome-stats.mjs): the deck's faces, no QR.
- const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- return statsHtml(schedule, manifest.render, { fonts, from, duration });
- }
- if (region === "finale") {
- // The finale (chrome-finale.mjs): the deck's faces and QR maker, one page
- // for its window.
- const render = manifest.render;
- const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
- const L = finaleLayout(schedule, render);
- const qrSrcs = {};
- if (resolveDeck(render).qr.show) {
- const byUrl = await qrPngsFor(L.captions.map((c) => c.qrUrl), render, L.geo.qr.size, assetsDir);
- for (const c of L.captions) if (c.qrUrl) qrSrcs[c.id] = byUrl.get(c.qrUrl);
- }
- return finaleHtml(schedule, render, window, { fonts, qrSrcs });
- }
- if (region === "teaser") {
- // A page module reached by a dynamic import, so nothing that imports this
- // file -- umtool's preview helper, the build -- loads its face's URL
- // unless a teaser is being composed (docs/quirks.md).
- const { teaserHtml, TEASER_FONT_FILE, TEASER_FONT_ASSET } = await import("./chrome-teaser.mjs");
- await copyFile(TEASER_FONT_FILE, path.join(projDir, TEASER_FONT_ASSET));
- return teaserHtml(teaser, manifest.render, { font: TEASER_FONT_ASSET, transition });
- }
- throw new Error(`unknown chrome region: ${region}`);
+ const mod = regionModule(region);
+ const render = manifest.render;
+ return mod.page({
+ manifest, render, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, entry: teaser, transition,
+ fonts: (names, opts) => copyFonts(render, assetsDir, names, opts),
+ qrs: (urls, size) => qrPngsFor(urls, render, size, assetsDir),
+ // `threads`, a Set: the posts whose thread shot was drawn in place of their shot are added to it.
+ shots: (posts, key = "shot", threads = null) => copyShots(posts, manifestDir, assetsDir, key, threads),
+ fxShots: (fx) => copyFxShots(fx, manifestDir, assetsDir),
+ fxThumbs: (sched) => fxThumbs(sched, base, render, assetsDir),
+ asset: async (src, name) => {
+ await copyFile(src, path.join(assetsDir, name));
+ return `assets/${name}`;
+ },
+ projectFile: (src, rel) => copyFile(src, path.join(projDir, rel)),
+ });
}
/** The root's declared size and length, read back off the HTML rather than re-derived. */
@@ -979,22 +879,18 @@ export async function composeChrome({
await ensureWriteDir(base);
from = Number(from ?? 0);
- // The regions keyed by the render cache: the two drawn from the deck's
- // schedule, and a teaser, drawn from its own timeline entry.
- const keyed = region === "deck" || region === "feed" || region === "posts" || region === "teaser" || region === "stamp" ||
- region === "threads" || region === "flips" || region === "stats" || region === "fx" || region === "finale";
- // The regions drawn over the whole cut from its schedule, windowable alike.
- const wholeCut = region === "deck" || region === "feed" || region === "stamp" || region === "threads" || region === "flips" ||
- region === "stats" || region === "fx";
+ // The region's module (modules/index.mjs) says how it is cached and laid:
+ // keyed by the render cache (every page but the legacy chart band), and
+ // drawn over the whole cut from its schedule, windowable (`overlay-whole`).
+ const mod = regionModule(region);
+ const { keyed, wholeCut } = regionCaching(region);
let teaser = null;
- if (region === "teaser") {
- teaser = (manifest.timeline ?? []).find((e) => e.id === segment && e.type === "teaser") ?? null;
- if (!teaser) throw new Error(`no teaser entry ${segment ?? "(none named)"} in the ${variant} cut`);
- const errors = validateTeaser(teaser);
- if (errors.length) throw new Error(`teaser ${teaser.id}: ${errors.join("; ")}`);
+ if (mod.kind === "segment") {
+ teaser = mod.entry(manifest, segment);
+ if (!teaser) throw new Error(`no ${region} entry ${segment ?? "(none named)"} in the ${variant} cut`);
}
let sched = schedule;
- if ((wholeCut || region === "posts" || region === "finale") && !sched) {
+ if (keyed && mod.kind !== "segment" && !sched) {
const p = path.join(base, "schedule.json");
try {
sched = JSON.parse(await readFile(p, "utf8"));
@@ -1003,62 +899,23 @@ export async function composeChrome({
}
if (sched.kind !== "deck") throw new Error(`${p} is not a deck schedule (kind ${sched.kind ?? "missing"})`);
}
- if (region === "feed" && sched.layout !== "feed") {
- throw new Error("the feed region needs a feed's schedule (layout \"feed\": posts.layout \"feed\" and posts to draw)");
- }
- if (region === "flips" && !sched.flips?.pairs?.length) {
- throw new Error("the flips region needs a schedule with flip pairs (render.chrome.flips)");
- }
- if (region === "threads" && !sched.threads?.threads?.length) {
- throw new Error("the threads region needs a schedule with a thread rail (render.chrome.threads)");
- }
- if (region === "stats" && !sched.stats?.clips?.length) {
- throw new Error("the stats region needs a schedule with a clip that declares it (render.chrome.stats or a clip's stats, and frameScan.overlay points)");
- }
- if (region === "fx" && !sched.fx) {
- throw new Error("the fx region needs a schedule with an effect on (render.chrome.fx)");
- }
- if (region === "finale" && !sched.finale) {
- throw new Error("the finale region needs a schedule with a finale (a clip with layout \"finale\", render.chrome.deck.finale)");
- }
- if (region === "stamp" && !sched.factcheck?.stamps?.length) {
- throw new Error("the stamp region needs a schedule that stamps a claim (an entry with a `claim`)");
- }
- if (region === "stamp" && !stampsDrawn(sched, manifest.render)) {
- throw new Error("the stamps are off (render.chrome.factcheck.stamp.show: false): there is no stamp region to compose");
- }
+ const refused = mod.check ? mod.check(sched, manifest.render) : null;
+ if (refused) throw new Error(refused);
const D = transition ?? transitionOf(manifest.render);
const rate = Number(fps ?? sched?.fps ?? manifest.render.fps ?? 30);
- const total = teaser ? teaserSeconds(teaser, D, rate) : keyed ? sched.total : null;
+ const total = teaser ? mod.seconds(teaser, D, rate) : keyed ? sched.total : null;
const windowed =
wholeCut &&
(from > 0 || (duration != null && Math.abs(Number(duration) - total) > 1e-6));
const suffix = windowed ? `-from${fmtSeconds(from)}` : "";
- // A posts window: the one asked for, or the segment's from the schedule.
- let win = null;
- if (region === "posts") {
- const want = window ?? postWindows(sched).find((w) => w.segment === segment);
- if (!want) {
- throw new Error(
- segment ? `no post rides on ${segment} in this schedule` : "the posts region needs a window (or a segment)",
- );
- }
- if (!/^[A-Za-z0-9_-]+$/.test(String(want.segment))) throw new Error(`posts: ${want.segment} is not a segment id`);
- win = snapWindow(want, { fps: rate, total });
- }
- // The finale's window: the schedule's, snapped outward to the frame grid.
- if (region === "finale") win = snapWindow({ segment: "finale", from: sched.finale.from, to: sched.finale.to }, { fps: rate, total });
-
- const projName =
- region === "posts"
- ? `posts-${preview ? "preview-" : ""}${win.segment}`
- : region === "finale"
- ? `finale${preview ? "-preview" : ""}`
- : region === "teaser"
- ? `teaser-${preview ? "preview-" : ""}${teaser.id}`
- : wholeCut && preview ? `${region}-preview` : `${region}${suffix}`;
- const projDir = path.join(base, "chrome", projName);
+ // A window (a posts window, the finale's): the one asked for, snapped to the frame grid.
+ const win = mod.window ? mod.window(sched, { window, segment, fps: rate, total, render: manifest.render }) : null;
+
+ const names = mod.names
+ ? mod.names({ preview, window: win, entry: teaser, suffix })
+ : { project: wholeCut && preview ? `${region}-preview` : `${region}${suffix}`, stem: `${region}${suffix}` };
+ const projDir = path.join(base, "chrome", names.project);
const assetsDir = path.join(projDir, "assets");
// The deck's assets are rebuilt every time: a QR from a clip that has since
// left the cut must not sit in the directory the cache key hashes.
@@ -1066,10 +923,14 @@ export async function composeChrome({
await mkdir(assetsDir, { recursive: true });
await copyFile(GSAP_FILE, path.join(assetsDir, "gsap.min.js"));
- const html = await regionHtml(region, {
+ // A module's page is its HTML, or `{ html, items }`: the markup the frame
+ // keys hold only while it is shown (frame-keys.mjs).
+ const drawn = await regionHtml(region, {
manifest, manifestDir: path.dirname(path.resolve(manifestPath)), base, projDir, assetsDir, schedule: sched,
duration: duration != null ? Number(duration) : null, from, window: win, teaser, transition: D,
});
+ const html = typeof drawn === "string" ? drawn : drawn.html;
+ const pageItems = typeof drawn === "string" ? null : drawn.items ?? null;
await writeFile(path.join(projDir, "index.html"), html, "utf8");
await writeFile(path.join(projDir, "hyperframes.json"), HF_JSON + "\n", "utf8");
@@ -1109,7 +970,7 @@ export async function composeChrome({
// A sequence is a directory; every other format is a file.
const sequence = format === "png-sequence";
- const stem = region === "posts" ? `posts-${win.segment}` : region === "finale" ? "finale" : region === "teaser" ? `teaser-${teaser.id}` : `${region}${suffix}`;
+ const stem = names.stem;
const target = sequence
? path.join(base, "chrome", `${stem}-frames`)
: path.join(base, "chrome", `${stem}.${format}`);
@@ -1118,9 +979,19 @@ export async function composeChrome({
// Each frame's key (frame-keys.mjs), for a whole-cut page it models: a
// render that is not cached whole captures only the frames no render on
// disk has drawn.
- const fk = keyed && sequence && ((wholeCut && !windowed) || region === "finale") && !preview && FRAME_KEY_REGIONS[region]
- ? frameKeys({ html, region, assets, fps: rate, frames, version: hf.version })
- : null;
+ // Frame keys, for a page its module models (`frameKeys`): a whole-cut page
+ // over the whole cut, a window's, a segment's.
+ // A page the model cannot read (an ease it does not know, a cue it cannot
+ // place) renders whole, as a page without frame keys always has.
+ let fk = null;
+ if (keyed && sequence && ((wholeCut && !windowed) || mod.kind === "overlay-window" || mod.kind === "segment") && !preview && mod.frameKeys) {
+ try {
+ fk = frameKeys({ html, region, assets, fps: rate, frames, version: hf.version, items: pageItems });
+ } catch (e) {
+ process.stderr.write(`chrome ${region}: no frame keys (${e?.message ?? e}); rendering it whole\n`);
+ fk = null;
+ }
+ }
if (keyed && sequence) {
const onDisk = await readFile(keyFile, "utf8").then((s) => s.trim(), () => null);
if (onDisk === key && (await framesOnDisk(target)) === frames) {
@@ -1357,7 +1228,7 @@ if (import.meta.url === `file://${process.argv[1]}`) {
still: num("--still"),
png: flag("--png"),
// The deck renders four-wide by default; the band keeps the renderer's own default.
- workers: num("--workers") ?? (region === "deck" || region === "feed" || region === "teaser" || region === "fx" ? 4 : region === "posts" || region === "finale" || region === "stamp" || region === "stats" || region === "threads" || region === "flips" ? 2 : null),
+ workers: num("--workers") ?? ({ wide: 4, narrow: 2 }[regionModule(region).workers] ?? null),
quality: flag("--quality") ?? "high",
format: flag("--format") ?? "png-sequence",
fps: num("--fps"),
diff --git a/umtool/report-to-video/counter.mjs b/umtool/report-to-video/counter.mjs
@@ -0,0 +1,184 @@
+// THE COUNTER (release 39): the deck's running tally, generalised from the
+// fact-check verdicts to arbitrary NAMED SERIES.
+//
+// render.chrome.deck.counter: {
+// "series": [ { "id": "seizures", "label": "Seizures", "color": "#e5534b",
+// "stampLabel": "Seizure", "tallyLabel": "Fits", "showAt": "first",
+// "unit": "seizures", "shape": "diamond" }, … ],
+// "show": true, "position": "right", "showAt": "always"
+// }
+//
+// A clip's MARK names the series it counts by id (`claim.verdict`, or its
+// alias `claim.counter`), and the counter steps as its stamp lands
+// (factcheck.mjs `stampSchedule`, `tallySteps`). The series are the tally's
+// cells, in the order listed; a deck claim (`deck.claims[].tally`) names one
+// by id or label.
+//
+// BACK-COMPAT: without `counter`, the series are the fact-check verdicts
+// (common's VERDICTS, in that order) with `render.chrome.factcheck.verdicts`'s
+// relabels and `factcheck.tally`'s show/position/showAt -- exactly what the
+// tally always drew. `migrateManifest` (modules/migrate.mjs) writes that as
+// a `counter` the bytes of whose render are the same. A series whose id is a
+// verdict takes that verdict's default label, colour and shape.
+//
+// PURE: no fs. factcheck.mjs, deck.mjs and the pages read `resolveCounter`;
+// modules/counter.mjs validates and documents it.
+import { VERDICT_DEFAULTS, VERDICT_COLOR_RE, VERDICT_LABEL_MAX, VERDICTS } from "yt-dlp-transcript-common/lib/report/verdicts.mjs";
+
+/** A series' cell shape, so a viewer who cannot tell the colours apart can tell the series apart. */
+export const COUNTER_SHAPES = Object.freeze(["circle", "diamond", "square", "triangle", "ring"]);
+
+/** Each verdict's shape (VERDICTS order): what a verdict series takes by default. */
+export const VERDICT_SHAPES = Object.freeze(Object.fromEntries(VERDICTS.map((v, i) => [v, COUNTER_SHAPES[i] ?? "circle"])));
+
+/** When a cell is on screen: from the first frame (dim at 0), or from its first count. */
+export const COUNTER_SHOW_AT = Object.freeze(["always", "first"]);
+
+/** Which end of the deck's text column the counter takes. */
+export const COUNTER_POSITIONS = Object.freeze(["right", "left"]);
+
+/** The counter's limits: how many series, an id's and a unit's characters. */
+export const COUNTER_LIMITS = Object.freeze({ series: 8, id: 32, unit: 24, label: VERDICT_LABEL_MAX });
+
+/** A series id: what a mark names. A letter, then letters, digits, `_` or `-`. */
+export const SERIES_ID_RE = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
+
+/** A custom series' colour when it names none, by its place in the list. */
+export const SERIES_COLORS = Object.freeze(["#e5534b", "#e3b23c", "#3fbf7f", "#7d8fd6", "#c55f9c", "#22ab83", "#d2732f", "#8b93a7"]);
+
+/** The keys a series may carry. */
+export const SERIES_KEYS = Object.freeze(["id", "label", "color", "stampLabel", "tallyLabel", "showAt", "unit", "shape"]);
+
+/** The keys `deck.counter` may carry. */
+export const COUNTER_KEYS = Object.freeze(["series", "show", "position", "showAt"]);
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** Is `render` counting named series (`deck.counter`) rather than the fact-check verdicts? */
+export const counterOn = (render) => isObj(render?.chrome?.deck?.counter);
+
+/**
+ * The counter resolved: `series` (each `{ id, label, color, stampLabel?,
+ * tallyLabel?, showAt, shape, unit? }`, in the tally's order), `order` (their
+ * ids), `byId` (each `{ label, color, stampLabel?, tallyLabel? }` -- the shape
+ * `resolveVerdicts` has always given, so every reader of a verdict's label and
+ * colour reads a series' the same way), `shapes`, `showAt` (id → "always" |
+ * "first"), `show`, `position`, and `custom` (a `deck.counter` was given).
+ * A shape no validator would pass reads as what it can.
+ */
+export function resolveCounter(render) {
+ const c = render?.chrome?.deck?.counter;
+ const f = isObj(render?.chrome?.factcheck) ? render.chrome.factcheck : {};
+ const one = (v) => (COUNTER_SHOW_AT.includes(v) ? v : "always");
+ if (isObj(c)) {
+ const list = (Array.isArray(c.series) ? c.series : []).filter((s) => isObj(s) && typeof s.id === "string" && SERIES_ID_RE.test(s.id));
+ const series = list.map((s, i) => {
+ const { id, showAt, unit, shape, ...look } = s;
+ const base = VERDICT_DEFAULTS[id] ?? { label: id, color: SERIES_COLORS[i % SERIES_COLORS.length] };
+ return {
+ id,
+ ...base,
+ ...look,
+ showAt: one(showAt ?? c.showAt),
+ shape: COUNTER_SHAPES.includes(shape) ? shape : (VERDICT_SHAPES[id] ?? COUNTER_SHAPES[i % COUNTER_SHAPES.length]),
+ ...(typeof unit === "string" && unit.trim() ? { unit: unit.trim() } : {}),
+ };
+ });
+ return {
+ custom: true,
+ series,
+ order: series.map((s) => s.id),
+ byId: Object.fromEntries(series.map(({ id, showAt: _a, shape: _s, unit: _u, ...look }) => [id, look])),
+ shapes: Object.fromEntries(series.map((s) => [s.id, s.shape])),
+ showAt: Object.fromEntries(series.map((s) => [s.id, s.showAt])),
+ show: c.show !== false,
+ position: COUNTER_POSITIONS.includes(c.position) ? c.position : "right",
+ };
+ }
+ // The fact-check verdicts, as the tally always counted them.
+ const given = isObj(f.verdicts) ? f.verdicts : {};
+ const tally = isObj(f.tally) ? f.tally : {};
+ const byId = {};
+ for (const v of VERDICTS) byId[v] = { ...VERDICT_DEFAULTS[v], ...(isObj(given[v]) ? given[v] : {}) };
+ const w = tally.showAt;
+ const showAt = Object.fromEntries(VERDICTS.map((v) => [v, isObj(w) ? one(w[v]) : one(w)]));
+ return {
+ custom: false,
+ series: VERDICTS.map((id) => ({ id, ...byId[id], showAt: showAt[id], shape: VERDICT_SHAPES[id] })),
+ order: [...VERDICTS],
+ byId,
+ shapes: { ...VERDICT_SHAPES },
+ showAt,
+ show: tally.show !== false,
+ position: COUNTER_POSITIONS.includes(tally.position) ? tally.position : "right",
+ };
+}
+
+/** The series ids a mark may name: the counter's, else the verdicts. */
+export const counterOrder = (render) => resolveCounter(render).order;
+
+/**
+ * Every reason a `deck.counter` cannot be drawn, as sentences (empty: it can).
+ * Unknown keys are refused. `factcheck` is the cut's `render.chrome.factcheck`:
+ * a counter beside the legacy `verdicts` or `tally` is refused (one home for
+ * the series). `labelFits(series)` is the tally cell's fit check
+ * (factcheck.mjs `tallyLabelOf`), handed in so this file stays free of it.
+ *
+ * @returns {string[]}
+ */
+export function validateCounter(c, { factcheck = undefined, labelFits = null, where = "render.chrome.deck.counter" } = {}) {
+ if (c === undefined) return [];
+ if (!isObj(c)) return [`${where} must be an object { series, show?, position?, showAt? }`];
+ const errors = [];
+ for (const k of Object.keys(c)) if (!COUNTER_KEYS.includes(k)) errors.push(`${where}.${k} is not a counter setting (${COUNTER_KEYS.join(", ")})`);
+ if (isObj(factcheck) && (factcheck.verdicts !== undefined || factcheck.tally !== undefined)) {
+ errors.push(`${where} replaces render.chrome.factcheck.verdicts and .tally: set the series and the cells in one place`);
+ }
+ if (c.show !== undefined && typeof c.show !== "boolean") errors.push(`${where}.show must be true or false`);
+ if (c.position !== undefined && !COUNTER_POSITIONS.includes(c.position)) {
+ errors.push(`${where}.position must be ${COUNTER_POSITIONS.map((p) => `"${p}"`).join(" or ")}`);
+ }
+ if (c.showAt !== undefined && !COUNTER_SHOW_AT.includes(c.showAt)) {
+ errors.push(`${where}.showAt must be ${COUNTER_SHOW_AT.map((p) => `"${p}"`).join(" or ")}`);
+ }
+ if (!Array.isArray(c.series) || !c.series.length) {
+ errors.push(`${where}.series must list at least one series { id, label }`);
+ return errors;
+ }
+ if (c.series.length > COUNTER_LIMITS.series) errors.push(`${where}.series holds ${c.series.length} (at most ${COUNTER_LIMITS.series})`);
+ const seen = new Set();
+ c.series.forEach((s, i) => {
+ const w = `${where}.series[${i}]`;
+ if (!isObj(s)) { errors.push(`${w} must be { id, label, color? }`); return; }
+ for (const k of Object.keys(s)) if (!SERIES_KEYS.includes(k)) errors.push(`${w}.${k} is not a series setting (${SERIES_KEYS.join(", ")})`);
+ if (typeof s.id !== "string" || !SERIES_ID_RE.test(s.id)) {
+ errors.push(`${w}.id must be a letter then letters, digits, _ or - (at most ${COUNTER_LIMITS.id})`);
+ } else if (seen.has(s.id)) errors.push(`${w}.id ${s.id} is listed twice -- one series, one id`);
+ else seen.add(s.id);
+ if (!VERDICTS.includes(s.id) && s.label === undefined) errors.push(`${w}.label is needed: only a verdict series has a default label`);
+ for (const key of ["label", "stampLabel", "tallyLabel"]) {
+ const word = s[key];
+ if (word === undefined) continue;
+ if (typeof word !== "string" || !word.trim()) errors.push(`${w}.${key} must be words, not empty`);
+ else if (/[\r\n]/.test(word)) errors.push(`${w}.${key} must be one line`);
+ else if (word.trim().length > COUNTER_LIMITS.label) errors.push(`${w}.${key} is ${word.trim().length} characters (at most ${COUNTER_LIMITS.label})`);
+ }
+ if (s.color !== undefined && !(typeof s.color === "string" && VERDICT_COLOR_RE.test(s.color))) errors.push(`${w}.color must be a hex colour, #rgb or #rrggbb`);
+ if (s.showAt !== undefined && !COUNTER_SHOW_AT.includes(s.showAt)) errors.push(`${w}.showAt must be ${COUNTER_SHOW_AT.map((p) => `"${p}"`).join(" or ")}`);
+ if (s.shape !== undefined && !COUNTER_SHAPES.includes(s.shape)) errors.push(`${w}.shape must be one of ${COUNTER_SHAPES.join(", ")}`);
+ if (s.unit !== undefined && !(typeof s.unit === "string" && s.unit.trim() && s.unit.trim().length <= COUNTER_LIMITS.unit)) {
+ errors.push(`${w}.unit must be a word, 1 to ${COUNTER_LIMITS.unit} characters`);
+ }
+ if (labelFits && !errors.some((e) => e.startsWith(`${w}.`))) {
+ const problem = labelFits(s, w);
+ if (problem) errors.push(problem);
+ }
+ });
+ return errors;
+}
+
+/**
+ * The series a mark counts: its `counter`, else its `verdict` -- one name for
+ * the same thing, `counter` the toolkit's, `verdict` the fact-check's.
+ */
+export const markSeries = (m) => (isObj(m) ? (m.counter ?? m.verdict) : undefined);
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -20,9 +20,22 @@ import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs";
import { attributionParts, deckSubtitle } from "./attribution.mjs";
import {
- claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, tallyOf, tallyVerdicts, validateFactcheck,
- VERDICT_SHAPES,
+ claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, tallyOf, tallyVerdicts, validateFactcheck,
} from "./factcheck.mjs";
+import { resolveCounter } from "./counter.mjs";
+import { DECK_PAD_X, COUNTER_CELL } from "./modules/design.mjs";
+import {
+ DECK_DEFAULTS, MARKER_ALIGNS, MARKER_DEFAULT_COLOR, MARKER_LAYOUTS, MARKER_LIMITS, MARKER_PALETTE_KEYS, markerShapeErrors,
+ PIP_COLORS, PIP_PITCH_DEFAULT, PIP_SPACINGS, POST_AT, POST_LAYOUTS, POST_LINKS, QR_LINKS, SETTINGS, settingValue, SUBTITLE_TOKENS,
+} from "./modules/settings.mjs";
+
+// The deck's settings and their limits live with the modules' validators
+// (modules/settings.mjs, a leaf: this file imports it); here under the names
+// they always had.
+export {
+ DECK_DEFAULTS, MARKER_ALIGNS, MARKER_DEFAULT_COLOR, MARKER_LAYOUTS, MARKER_LIMITS, MARKER_PALETTE_KEYS, PIP_COLORS, PIP_PITCH_DEFAULT,
+ PIP_SPACINGS, POST_AT, POST_LAYOUTS, POST_LINKS, QR_LINKS, SUBTITLE_TOKENS,
+};
import { threadOf, threadSchedule, threadsOn, validateThreads } from "./threads.mjs";
import { flipSchedule, flipsOn, validateFlips } from "./flips.mjs";
import { overlayPointsOf, resolveStats, statsSchedule, statsWanted, validateStats } from "./stats.mjs";
@@ -43,86 +56,6 @@ export const railOn = (render) => threadsOn(render) || flipsOn(render);
export const HYPERFRAMES_PKG_DEFAULT = "hyperframes@0.8.24";
/**
- * Every deck setting and its default. A manifest names only what it changes;
- * `resolveDeck` fills the rest. Each default is a setting, not a constant --
- * the alternative in each comment is a supported value.
- */
-export const DECK_DEFAULTS = Object.freeze({
- height: 190,
- footageScale: 0.82,
- background: "panel", // | "flush"
- // spacing | "time". `color` "verdict": a claimed clip's pip, once lit, takes
- // its claim's verdict colour and shape (factcheck.mjs VERDICT_SHAPES).
- pip: Object.freeze({ spacing: "even", size: 6, activeSize: 12, color: "accent" }),
- title: Object.freeze({ size: 54, maxChars: 48 }),
- subtitle: Object.freeze({ parts: "auto", dateFormat: "long" }), // dateFormat | "iso"
- // `links` is where a clip's QR goes: "site" (the archive's page at the
- // clip's start) or "original" (the record's own page -- YouTube at the
- // second, a Rumble page, an X post). An entry's `citeUrl` wins either way.
- qr: Object.freeze({ show: true, size: 150, links: "site" }),
- overCards: "hide", // | "show"
- motion: Object.freeze({ out: 0.3, in: 0.45, pip: 0.7 }),
- // The manifest's `posts`, drawn as cards over the footage at the end of the
- // clip each one is attached to. position | "top-left".
- // `hold` freezes the last frame of a clip that carries posts for that long,
- // so the last of them can be read before the next clip; `shift` moves the
- // footage away from the posts column (scaled to `scale`, over `seconds`)
- // while they are up, or is `false`.
- // `layout` "popup" draws them as above; "feed" keeps them in a column of
- // their own beside the footage for the whole cut (feedGeometry), each one
- // ticking in as its clip starts -- no hold, no move.
- // `links` is where a post's QR goes: "archive" (the post's page on the
- // archive the manifest names, `provenance.siteOrigin`, which survives the
- // post or the platform going away, and links on to the original) or
- // "original" (the bsky.app / x.com link itself).
- // `at` is when a popup's posts come up: "end" (the last `seconds` of the
- // clip, as above) or "start" (from the clip's start, sharing the whole clip
- // in the order the manifest lists them -- the post beside the words it goes
- // with, so no hold is needed). `shotMaxHeight` caps a post's screenshot in
- // px; null keeps it to the height of a full card of words (`maxLines`).
- posts: Object.freeze({
- show: true, layout: "popup", seconds: 4, hold: 2.5, position: "top-right", width: 600, qrSize: 120, maxLines: 7,
- inset: 24, shift: Object.freeze({ scale: 0.86, seconds: 0.6 }), links: "archive", at: "end", shotMaxHeight: null,
- // `qr: false` draws no QR on any post card (popup or feed); the words
- // take the code's width. The clip's own deck QR (`qr`) is untouched.
- qr: true,
- }),
- // Flags on the pip track: `[{ after, label, color?, align? }]`, each between
- // the pip of the clip `after` names and the next, hidden until the fuse
- // reaches it (deckMarkers). An empty list is no flags, and the deck lays out
- // as it always did.
- markers: Object.freeze([]),
- // Crowded labels: "stagger" lays them in two rows when one would not fit in
- // a single row (the band grows by MARKER_ROW, the track moves down by it);
- // "truncate" keeps one row and ellipsizes. A single row that fits is laid
- // the same either way.
- markerLayout: "stagger",
-});
-
-/** The pip's colour when lit (`pip.color`): the deck's accent, or a claimed clip's verdict. */
-export const PIP_COLORS = Object.freeze(["accent", "verdict"]);
-
-/** A marker's limits: how many, and a label's characters. */
-export const MARKER_LIMITS = Object.freeze({ count: 12, label: 24 });
-
-/**
- * Where a marker's label sits against its flag: "auto" (centred when it has
- * the room, else the stretch it may take -- as it always was), "left" (it
- * starts at the flag and reads on to the right), "right" (it ends at the
- * flag), "center" (centred on it, always).
- */
-export const MARKER_ALIGNS = Object.freeze(["auto", "left", "right", "center"]);
-
-/** `deck.markerLayout`: crowded labels in two rows, or one row ellipsized. */
-export const MARKER_LAYOUTS = Object.freeze(["stagger", "truncate"]);
-
-/** The palette keys a marker's `color` may name (else a `#rgb` / `#rrggbb`). */
-export const MARKER_PALETTE_KEYS = Object.freeze(["fg", "muted", "accent", "amber", "dim"]);
-
-/** A marker with no `color` is drawn in this palette key. */
-export const MARKER_DEFAULT_COLOR = "amber";
-
-/**
* The deck's TUNABLE params (release 38): the settings the video assistant's
* `fx` op may set by name, each with the bounds validateChrome holds it to
* (declared in common lib/report/fxParams.mjs; fx-params.test.mjs keeps the
@@ -130,12 +63,6 @@ export const MARKER_DEFAULT_COLOR = "amber";
*/
export const DECK_PARAMS = COMPOSITION_PARAMS.deck;
-/** Where a clip's deck QR links (`qr.links`): the archive at the clip, or the original. */
-export const QR_LINKS = Object.freeze(["site", "original"]);
-
-/** Subtitle tokens a `subtitle.parts` array may name. "auto" picks from these. */
-export const SUBTITLE_TOKENS = Object.freeze(["channel", "title", "date", "clock"]);
-
/**
* Segment types the deck slides away over when `overCards: "hide"`. A
* `teaser` is one too, and the deck slides away over it whatever `overCards`
@@ -173,6 +100,7 @@ export function resolveDeck(render) {
// refuses with it, so a manifest umtool accepted is one the build accepts.
// ---------------------------------------------------------------------------
+const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
@@ -196,7 +124,7 @@ export function validateChrome(chrome, render = {}) {
const errors = [];
if (chrome === undefined || chrome === null) return errors;
if (!isObj(chrome)) return ["render.chrome must be an object"];
- unknownKeys(chrome, ["engine", "layout", "deck", "factcheck", "threads", "flips", "stats", "fx"], "render.chrome", errors);
+ unknownKeys(chrome, ["engine", "layout", "deck", "factcheck", "threads", "flips", "stats", "fx", "pair", "chapter", "status"], "render.chrome", errors);
if (chrome.engine !== "hyperframes") errors.push('render.chrome.engine must be "hyperframes"');
if (chrome.layout !== "deck") errors.push('render.chrome.layout must be "deck"');
if (render.rail) errors.push("render.chrome (the deck) and render.rail cannot both be set");
@@ -206,142 +134,27 @@ export function validateChrome(chrome, render = {}) {
// The end fade is a render key the deck's cut is finished with; checked
// here too, so a writer that validates the deck refuses a bad one.
errors.push(...validateEndFade(render));
- // The fact-check stamps and tally (factcheck.mjs): drawn only by the deck.
- errors.push(...validateFactcheck(chrome.factcheck, undefined, { fontBold: render.fontBold ?? null }));
- // The thread rail (threads.mjs): the deck's layout only, beside the footage.
- errors.push(...validateThreads(chrome.threads));
- // The flips panel (flips.mjs): the same region as the rail, so not both.
- errors.push(...validateFlips(chrome.flips));
- // The stats region (stats.mjs): a frame scan's running numbers over the footage.
- errors.push(...validateStats(chrome.stats));
- // The effects region (fx.mjs): overlays drawn over the footage box.
- errors.push(...validateFx(chrome.fx));
- if (threadsOn({ chrome }) && flipsOn({ chrome })) errors.push("render.chrome.threads and render.chrome.flips share the left panel: set one");
+ // Every module's own settings (modules/settings.mjs), in SETTINGS order:
+ // the fact-check's, the side panel's, the stats', the effects', then the
+ // deck's own keys -- the finale's, the claim checks', the counter's, the
+ // shell's, the rail's, the subtitle's, the QR's, the posts'.
const d = chrome.deck ?? {};
- if (!isObj(d)) return [...errors, "render.chrome.deck must be an object"];
const w = "render.chrome.deck";
- // `finale` (finale.mjs) is the deck's too, with no default to fill: absent,
- // nothing about the deck changes. So are `claims` (claims.mjs): his words
- // against the record, drawn on the rail.
- unknownKeys(d, [...Object.keys(DECK_DEFAULTS), "finale", "claims"], w, errors);
- errors.push(...validateFinaleSettings(d.finale, `${w}.finale`));
- errors.push(...deckClaimShapeErrors(d.claims, `${w}.claims`));
-
- if (d.height !== undefined && !(Number.isInteger(d.height) && numIn(d.height, 120, 400))) {
- errors.push(`${w}.height must be a whole number of pixels from 120 to 400`);
- }
- if (d.footageScale !== undefined && !numIn(d.footageScale, 0.5, 1)) {
- errors.push(`${w}.footageScale must be from 0.5 to 1`);
- }
- if (d.background !== undefined && !["panel", "flush"].includes(d.background)) {
- errors.push(`${w}.background must be "panel" or "flush"`);
- }
- if (d.overCards !== undefined && !["hide", "show"].includes(d.overCards)) {
- errors.push(`${w}.overCards must be "hide" or "show"`);
- }
-
- const sub = (key, allowed, check) => {
- if (d[key] === undefined) return;
- if (!isObj(d[key])) { errors.push(`${w}.${key} must be an object`); return; }
- unknownKeys(d[key], allowed, `${w}.${key}`, errors);
- check(d[key]);
- };
- sub("pip", ["spacing", "size", "activeSize", "color"], (p) => {
- if (p.spacing !== undefined && !["even", "time"].includes(p.spacing)) {
- errors.push(`${w}.pip.spacing must be "even" or "time"`);
- }
- if (p.color !== undefined && !PIP_COLORS.includes(p.color)) {
- errors.push(`${w}.pip.color must be ${PIP_COLORS.map((c) => `"${c}"`).join(" or ")}`);
- }
- if (p.size !== undefined && !numIn(p.size, 2, 24)) errors.push(`${w}.pip.size must be from 2 to 24`);
- if (p.activeSize !== undefined && !numIn(p.activeSize, 2, 40)) {
- errors.push(`${w}.pip.activeSize must be from 2 to 40`);
- }
- const size = p.size ?? DECK_DEFAULTS.pip.size;
- const active = p.activeSize ?? DECK_DEFAULTS.pip.activeSize;
- if (numIn(size, 2, 24) && numIn(active, 2, 40) && active < size) {
- errors.push(`${w}.pip.activeSize must be at least pip.size`);
- }
- });
- sub("title", ["size", "maxChars"], (t) => {
- if (t.size !== undefined && !numIn(t.size, 24, 96)) errors.push(`${w}.title.size must be from 24 to 96`);
- if (t.maxChars !== undefined && !(Number.isInteger(t.maxChars) && numIn(t.maxChars, 10, 120))) {
- errors.push(`${w}.title.maxChars must be a whole number from 10 to 120`);
- }
- });
- sub("subtitle", ["parts", "dateFormat"], (s) => {
- if (s.parts !== undefined && s.parts !== "auto") {
- const ok = Array.isArray(s.parts) && s.parts.length > 0 &&
- s.parts.every((p) => SUBTITLE_TOKENS.includes(p)) &&
- new Set(s.parts).size === s.parts.length;
- if (!ok) {
- errors.push(`${w}.subtitle.parts must be "auto" or a list of distinct ${SUBTITLE_TOKENS.join("/")}`);
- }
- }
- if (s.dateFormat !== undefined && !["long", "iso"].includes(s.dateFormat)) {
- errors.push(`${w}.subtitle.dateFormat must be "long" or "iso"`);
- }
- });
- sub("qr", ["show", "size", "links"], (q) => {
- if (q.show !== undefined && typeof q.show !== "boolean") errors.push(`${w}.qr.show must be true or false`);
- if (q.links !== undefined && !QR_LINKS.includes(q.links)) {
- errors.push(`${w}.qr.links must be ${QR_LINKS.map((l) => `"${l}"`).join(" or ")}`);
- }
- if (q.size !== undefined && !numIn(q.size, 80, 380)) errors.push(`${w}.qr.size must be from 80 to 380`);
- const h = d.height ?? DECK_DEFAULTS.height;
- const size = q.size ?? DECK_DEFAULTS.qr.size;
- if (numIn(size, 80, 380) && Number.isInteger(h) && size > h - 20) {
- errors.push(`${w}.qr.size ${size} does not fit a ${h}px deck (at most ${h - 20})`);
- }
- });
- sub("posts", ["show", "layout", "seconds", "hold", "position", "width", "qrSize", "maxLines", "inset", "shift", "links", "at", "shotMaxHeight", "qr"], (p) => {
- if (p.qr !== undefined && typeof p.qr !== "boolean") errors.push(`${w}.posts.qr must be true or false`);
- if (p.at !== undefined && !POST_AT.includes(p.at)) {
- errors.push(`${w}.posts.at must be ${POST_AT.map((a) => `"${a}"`).join(" or ")}`);
- }
- if (p.shotMaxHeight !== undefined && p.shotMaxHeight !== null &&
- !(Number.isInteger(p.shotMaxHeight) && numIn(p.shotMaxHeight, 120, 1080))) {
- errors.push(`${w}.posts.shotMaxHeight must be null or a whole number of pixels from 120 to 1080`);
- }
- if (p.layout !== undefined && !POST_LAYOUTS.includes(p.layout)) {
- errors.push(`${w}.posts.layout must be ${POST_LAYOUTS.map((l) => `"${l}"`).join(" or ")}`);
- }
- if (p.links !== undefined && !POST_LINKS.includes(p.links)) {
- errors.push(`${w}.posts.links must be ${POST_LINKS.map((l) => `"${l}"`).join(" or ")}`);
- }
- if (p.hold !== undefined && !numIn(p.hold, 0, 10)) errors.push(`${w}.posts.hold must be from 0 to 10 seconds`);
- if (p.shift !== undefined && p.shift !== false) {
- if (!isObj(p.shift)) errors.push(`${w}.posts.shift must be false or { scale, seconds }`);
- else {
- unknownKeys(p.shift, ["scale", "seconds"], `${w}.posts.shift`, errors);
- if (p.shift.scale !== undefined && !numIn(p.shift.scale, 0.5, 1)) errors.push(`${w}.posts.shift.scale must be from 0.5 to 1`);
- if (p.shift.seconds !== undefined && !numIn(p.shift.seconds, 0, 3)) errors.push(`${w}.posts.shift.seconds must be from 0 to 3`);
- }
- }
- if (p.show !== undefined && typeof p.show !== "boolean") errors.push(`${w}.posts.show must be true or false`);
- if (p.seconds !== undefined && !numIn(p.seconds, 0.5, 10)) errors.push(`${w}.posts.seconds must be from 0.5 to 10`);
- if (p.position !== undefined && !["top-right", "top-left"].includes(p.position)) {
- errors.push(`${w}.posts.position must be "top-right" or "top-left"`);
- }
- if (p.width !== undefined && !(Number.isInteger(p.width) && numIn(p.width, 320, 900))) {
- errors.push(`${w}.posts.width must be a whole number of pixels from 320 to 900`);
- }
- if (p.qrSize !== undefined && !numIn(p.qrSize, 80, 200)) errors.push(`${w}.posts.qrSize must be from 80 to 200`);
- if (p.maxLines !== undefined && !(Number.isInteger(p.maxLines) && numIn(p.maxLines, 2, 14))) {
- errors.push(`${w}.posts.maxLines must be a whole number from 2 to 14`);
- }
- if (p.inset !== undefined && !numIn(p.inset, 0, 80)) errors.push(`${w}.posts.inset must be from 0 to 80`);
- });
- errors.push(...markerShapeErrors(d.markers, `${w}.markers`));
- if (d.markerLayout !== undefined && !MARKER_LAYOUTS.includes(d.markerLayout)) {
- errors.push(`${w}.markerLayout must be ${MARKER_LAYOUTS.map((l) => `"${l}"`).join(" or ")}`);
+ let deckChecked = false;
+ for (const entry of SETTINGS) {
+ if (entry.deck && !deckChecked) {
+ // The thread rail and the flips share the left panel: one or the other.
+ if (threadsOn({ chrome }) && flipsOn({ chrome })) errors.push("render.chrome.threads and render.chrome.flips share the left panel: set one");
+ if (!isObj(d)) return [...errors, "render.chrome.deck must be an object"];
+ // `finale` (finale.mjs) is the deck's too, with no default to fill:
+ // absent, nothing about the deck changes. So are `claims` (claims.mjs:
+ // his words against the record, drawn on the rail) and `counter`
+ // (counter.mjs: the tally's named series).
+ unknownKeys(d, [...Object.keys(DECK_DEFAULTS), "finale", "claims", "counter"], w, errors);
+ deckChecked = true;
+ }
+ errors.push(...entry.validate(settingValue(chrome, entry), { render, chrome, deck: d, where: w }));
}
- sub("motion", ["out", "in", "pip"], (m) => {
- for (const k of ["out", "in"]) {
- if (m[k] !== undefined && !numIn(m[k], 0, 2)) errors.push(`${w}.motion.${k} must be from 0 to 2 seconds`);
- }
- if (m.pip !== undefined && !numIn(m.pip, 0, 3)) errors.push(`${w}.motion.pip must be from 0 to 3 seconds`);
- });
// The footage has to fit above the deck. Clamping the scale instead would
// make the setting lie about what was drawn.
@@ -371,43 +184,6 @@ export function validateChrome(chrome, render = {}) {
return errors;
}
-const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
-
-/**
- * Every reason a `deck.markers` list cannot be drawn, its shape alone (the
- * timeline is not in `render.chrome`: `validateDeckMarkers` checks `after`
- * against it). validateChrome calls this.
- *
- * @returns {string[]}
- */
-function markerShapeErrors(markers, where) {
- if (markers === undefined) return [];
- if (!Array.isArray(markers)) return [`${where} must be a list of { after, label, color? }`];
- const errors = [];
- if (markers.length > MARKER_LIMITS.count) errors.push(`${where} has ${markers.length} markers (at most ${MARKER_LIMITS.count})`);
- markers.forEach((m, i) => {
- const at = `${where}[${i}]`;
- if (!isObj(m)) { errors.push(`${at} must be { after, label, color? }`); return; }
- for (const k of Object.keys(m)) {
- if (!["after", "label", "color", "align"].includes(k)) errors.push(`${at}.${k} is not a marker setting (after, label, color, align)`);
- }
- if (m.align !== undefined && !MARKER_ALIGNS.includes(m.align)) {
- errors.push(`${at}.align must be ${MARKER_ALIGNS.map((a) => `"${a}"`).join(", ")}`);
- }
- if (typeof m.after !== "string" || !m.after.trim()) errors.push(`${at}.after must name a clip's id`);
- const label = typeof m.label === "string" ? m.label.trim() : "";
- if (!label) errors.push(`${at}.label must be a word or two`);
- else if (/[\r\n]/.test(label)) errors.push(`${at}.label must be one line`);
- else if ([...label].length > MARKER_LIMITS.label) {
- errors.push(`${at}.label is ${[...label].length} characters (at most ${MARKER_LIMITS.label})`);
- }
- if (m.color !== undefined && !(typeof m.color === "string" && (HEX_RE.test(m.color) || MARKER_PALETTE_KEYS.includes(m.color)))) {
- errors.push(`${at}.color must be a #hex colour or one of ${MARKER_PALETTE_KEYS.join(", ")}`);
- }
- });
- return errors;
-}
-
/**
* The deck's markers checked whole: their shape (as validateChrome checks
* it) and, against the WHOLE timeline, that each `after` names a clip in it.
@@ -654,7 +430,7 @@ export function threadsGeometry(render) {
export function deckLayout(render, { tally = null, schedule = null } = {}) {
const { W, deck: rect } = deckGeometry(render);
const d = resolveDeck(render);
- const padX = 48;
+ const padX = DECK_PAD_X;
// The markers' labels (`deck.markers`) stand in a band above the track: the
// track moves down by it, and only when there is a marker to label, so a
// deck without them lays out as it always did.
@@ -684,7 +460,7 @@ export function deckLayout(render, { tally = null, schedule = null } = {}) {
// A cell per verdict the cut uses: its count over its label. Beside the
// QR's cell (whose plate starts 46 px before the code) on the right, or
// ahead of the title on the left; 40 px of air to the text either way.
- const cell = 124, gap = 10;
+ const { cell, gap } = COUNTER_CELL;
const width = tally.length * cell + (tally.length - 1) * gap;
const height = Math.min(bodyH - 8, 118);
const y = Math.round(bodyTop + (bodyH - height) / 2);
@@ -813,7 +589,7 @@ export function markerRowsOf(schedule, render) {
const pipped = pipSegments(schedule);
const xs = pipXs(
pipped.length, lay.pipTrack.x0, lay.pipTrack.x1, d.pip.spacing,
- d.pip.spacing === "time" ? { total: schedule.total, segments: pipped } : null,
+ d.pip.spacing === "time" ? { total: schedule.total, segments: pipped } : null, d.pip.pitch ?? PIP_PITCH_DEFAULT,
);
return deckMarkers(schedule, render, xs, pipped, lay).some((m) => m.row === 1) ? 2 : 1;
}
@@ -925,8 +701,16 @@ export function deckMarkers(schedule, render, xs, pipped, lay = deckLayout(rende
* -- needs `schedule` (`{ total, segments: [{start, duration}] }`, the pipped
* segments only, in order).
*/
-export function pipXs(n, x0, x1, spacing = "even", schedule = null) {
+export function pipXs(n, x0, x1, spacing = "even", schedule = null, pitch = PIP_PITCH_DEFAULT) {
if (n <= 0) return [];
+ // "pitch" (rail.mjs): each pip `pitch` px after the one before, from the
+ // left end -- a pip's place depends on the pips before it alone -- unless
+ // the track cannot hold them all at it, when they are laid at the pitch
+ // that fits.
+ if (spacing === "pitch") {
+ const step = n > 1 ? Math.min(pitch, (x1 - x0) / (n - 1)) : pitch;
+ return Array.from({ length: n }, (_, i) => x0 + i * step);
+ }
if (spacing === "time") {
if (!schedule?.segments || schedule.segments.length !== n || !(schedule.total > 0)) {
throw new Error("pipXs: spacing \"time\" needs a schedule with one segment per pip");
@@ -1097,6 +881,8 @@ export function deckSchedule({
}) {
const deck = resolveDeck(render);
const fps = render.fps ?? 30;
+ // The series a mark may count (counter.mjs): the counter's, else the verdicts.
+ const series = resolveCounter(render).order;
// A clip that carries posts is held on its last frame for `posts.hold`: the
// hold is part of the segment's length in the cut, so every start, the total
// and the posts' timing below are measured with it. `durs` are the segments'
@@ -1129,7 +915,7 @@ export function deckSchedule({
// An entry's marks (`claims`, two or more) ride beside its first.
const stamped = stampSchedule({
segments: segs.map((s, i) => {
- const marks = marksOf(entries[i]);
+ const marks = marksOf(entries[i], series);
const claim = marks[0] ?? null;
const many = marks.length > 1 ? { claims: marks } : {};
if (!marks.some((c) => c.at !== undefined)) return { ...s, claim, ...many };
@@ -1143,11 +929,10 @@ export function deckSchedule({
// -- its totals are final -- and is not drawn: there is no footage box to
// stamp, and the clip before is not the claim's.
const finale = fin ? finaleSchedule({ entries, segs, fin, D, total, render, feed, metas, provenance, deck }) : null;
- const stamps = finale
- ? stamped.map((s) => (finIds.has(s.segment)
- ? { ...s, at: finale.start, landed: finale.start, out: [finale.start, finale.start], stamp: false, finale: true }
- : s))
- : stamped;
+ // The counter's stamps (factcheck.mjs `stampsWithFinale`): the finale's
+ // window is an output the counter reads (`finale.window`), and the finale
+ // reads the counter's totals -- neither writes the other's slice.
+ const stamps = stampsWithFinale(stamped, finale ? { start: finale.start, segments: finIds } : null);
const allMoves = finale ? [...moves, ...finale.moves] : moves;
const threads = threadsOn(render)
? threadSchedule({ segments: segs.map((s, i) => ({ ...s, thread: threadOf(entries[i]) })), D, total, render, moves })
@@ -1208,13 +993,13 @@ export function deckSchedule({
// Only on a teaser that dips, so a cut without one writes the schedule it always did.
...(dipOf(e, fps) ? { dip: dipOf(e, fps) } : {}),
// Only on an entry that carries a claim (factcheck.mjs), likewise.
- ...(claimOf(e) ? { claim: claimOf(e) } : {}),
+ ...(claimOf(e, series) ? { claim: claimOf(e, series) } : {}),
// Its marks, only when it carries two or more (`claim` is the first).
- ...(marksOf(e).length > 1 ? { claims: marksOf(e) } : {}),
+ ...(marksOf(e, series).length > 1 ? { claims: marksOf(e, series) } : {}),
// And on one stamped at a source second, the second its segment starts
// at -- what placed the stamp, kept for a preview to place it again.
// So does a clip a deck claim check is said in (`deck.claims`).
- ...(marksOf(e).some((c) => c.at !== undefined) || claimClips.has(e.id)
+ ...(marksOf(e, series).some((c) => c.at !== undefined) || claimClips.has(e.id)
? { sourceFrom: round(clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from) }
: {}),
// Only on a finale clip, likewise.
@@ -1282,6 +1067,7 @@ export function claimsSchedule({ entries, segments, D, total, metas = [], render
const list = render?.chrome?.deck?.claims;
if (!Array.isArray(list) || !list.length || deckClaimShapeErrors(list).length) return null;
const verdicts = resolveFactcheck(render).verdicts;
+ const unitOf = (id) => resolveCounter(render).series.find((s) => s.id === id)?.unit ?? null;
const idx = new Map(segments.map((s, i) => [s.id, i]));
const round = (v) => Math.round(v * 1000) / 1000;
const dates = {};
@@ -1319,7 +1105,8 @@ export function claimsSchedule({ entries, segments, D, total, metas = [], render
items.push({
kind: "count", n, segment: c.at, at: cutAt(c.at, c.t), until: untilOf(c.at), said: c.said.trim(),
window: { from: c.window.from, to: c.window.to }, verdict,
- noun: String(verdicts[verdict].label ?? verdict).trim().toLowerCase(),
+ // A counter series' `unit` (counter.mjs) when it names one, else its label.
+ noun: String(unitOf(verdict) ?? verdicts[verdict].label ?? verdict).trim().toLowerCase(),
total: sum,
stamps: inWindow.map(({ landed: _l, ...s }) => s),
...(c.per ? { per: c.per, spans } : {}),
@@ -1608,7 +1395,7 @@ function finaleRailAt(schedule, render, railBottom, textScale) {
const fc = resolveFactcheck(render);
const pal = render.palette ?? {};
const stamps = schedule.factcheck?.stamps ?? [];
- const verdicts = f.totals && stamps.length ? tallyVerdicts(stamps) : [];
+ const verdicts = f.totals && stamps.length ? tallyVerdicts(stamps, resolveCounter(render).order) : [];
const H = render?.height ?? 1080;
const kh = H / 1080;
const py = (v) => Math.round(v * kh);
@@ -1622,7 +1409,9 @@ function finaleRailAt(schedule, render, railBottom, textScale) {
const lay = deckLayout(render, { tally, schedule });
const pipped = pipSegments(schedule);
const time = deck.pip.spacing === "time" ? { total: schedule.total, segments: pipped } : null;
- const fxs = pipXs(pipped.length, lay.pipTrack.x0, lay.pipTrack.x1, deck.pip.spacing, time);
+ const fxs = pipXs(pipped.length, lay.pipTrack.x0, lay.pipTrack.x1, deck.pip.spacing, time, deck.pip.pitch ?? PIP_PITCH_DEFAULT);
+ // The large rail is the whole record at once: a footer at a fixed pitch is laid evenly across it.
+ const bigSpacing = deck.pip.spacing === "pitch" ? "even" : deck.pip.spacing;
const footSize = deck.pip.size;
const bigSize = Math.max(14, Math.round(footSize * 2.5));
const bigV = Math.round((bigSize * 5) / 3);
@@ -1633,7 +1422,7 @@ function finaleRailAt(schedule, render, railBottom, textScale) {
const dates = f.railLabels === "all";
const labelsAt = (xs, geo) => railLabelLayout(xs.map((x, k) => ({ x, ...info[k] })), geo, { dates });
let x0 = rail.x0;
- let xs = pipXs(pipped.length, x0, rail.x1, deck.pip.spacing, time);
+ let xs = pipXs(pipped.length, x0, rail.x1, bigSpacing, time);
let labels = labelsAt(xs, base);
if (labels.mode === "turned" && labels.groups.length) {
const g0 = labels.groups[0];
@@ -1641,7 +1430,7 @@ function finaleRailAt(schedule, render, railBottom, textScale) {
const need = Math.round(base.margin / 2 + w0 * Math.cos((labels.angle * Math.PI) / 180));
if (need > x0) {
x0 = Math.min(need, Math.round(base.W * 0.2));
- xs = pipXs(pipped.length, x0, rail.x1, deck.pip.spacing, time);
+ xs = pipXs(pipped.length, x0, rail.x1, bigSpacing, time);
labels = labelsAt(xs, base);
}
}
@@ -1651,7 +1440,7 @@ function finaleRailAt(schedule, render, railBottom, textScale) {
const v = byVerdict && s.claim?.verdict ? s.claim.verdict : null;
return {
id: s.id, x: r2(xs[k]), size: v ? bigV : bigSize,
- ...(v ? { verdict: v, shape: VERDICT_SHAPES[v], color: fc.verdicts[v]?.color ?? pal.accent } : {}),
+ ...(v ? { verdict: v, shape: resolveCounter(render).shapes[v], color: fc.verdicts[v]?.color ?? pal.accent } : {}),
...(finSet.has(s.id) ? { here: true } : {}),
};
});
@@ -1839,14 +1628,8 @@ export function pipSegments(schedule) {
// ---------------------------------------------------------------------------
export const POST_PLATFORMS = Object.freeze(["bluesky", "x", "web"]);
-/** When a popup's posts come up (`posts.at`): the end of their clip, or its start. */
-export const POST_AT = Object.freeze(["end", "start"]);
/** The cuts a post may be limited to (`posts[].variant`) -- build-video's VARIANTS. */
const POST_VARIANTS = Object.freeze(["sourced", "full"]);
-/** How posts are drawn (`posts.layout`): cards at the end of a clip, or a column for the whole cut. */
-export const POST_LAYOUTS = Object.freeze(["popup", "feed"]);
-/** Where a post's QR links (`posts.links`): its page on the archive, or the platform's own link. */
-export const POST_LINKS = Object.freeze(["archive", "original"]);
const POST_KEYS = ["id", "platform", "author", "handle", "date", "text", "url", "attachTo", "hide", "siteChannel", "siteUrl", "postId", "shot", "thread", "variant", "accent", "logo", "flag"];
/** A post's `flag`: at most this many characters. */
export const POST_FLAG_MAX = 60;
diff --git a/umtool/report-to-video/factcheck.mjs b/umtool/report-to-video/factcheck.mjs
@@ -35,6 +35,8 @@
// copy shared with report.json and the export site's report pages. This file
// re-exports the list and lays the stamp and tally settings beside the labels.
import { isIsoDate } from "./claims.mjs";
+import { resolveCounter, VERDICT_SHAPES } from "./counter.mjs";
+import { COUNTER_CELL } from "./modules/design.mjs";
import {
VERDICT_DEFAULTS,
VERDICT_LABEL_MAX,
@@ -95,7 +97,7 @@ export const FACTCHECK_LIMITS = Object.freeze({
export const CLAIM_LIMITS = Object.freeze({ hold: Object.freeze([0.5, 10]), count: Object.freeze([1, 99]), label: 20 });
/** The keys a `claim` may carry. */
-export const CLAIM_KEYS = Object.freeze(["id", "verdict", "at", "hold", "stamp", "count", "label", "eventDate"]);
+export const CLAIM_KEYS = Object.freeze(["id", "verdict", "counter", "at", "hold", "stamp", "count", "label", "eventDate"]);
/** The most marks (`claims`) one entry may carry. */
export const CLAIM_MARKS_MAX = 8;
@@ -130,7 +132,7 @@ function unknownKeys(obj, allowed, where, errors) {
* (deck.mjs deckLayout's 124 px cell). The page ellipsizes what overruns, so
* a label is fitted HERE, before the page is written.
*/
-export const TALLY_LABEL = Object.freeze({ size: 13, tracking: 0.08, width: 124 - 12 });
+export const TALLY_LABEL = Object.freeze({ size: 13, tracking: 0.08, width: COUNTER_CELL.cell - 2 * COUNTER_CELL.labelPad });
// Fira Sans Bold's advances (the deck's bold unless a brand sets one), per
// character a capitalised label can hold, in 1/1000 em, rounded UP --
@@ -183,13 +185,40 @@ export function tallyLabelOf(v, { fontBold = null } = {}) {
return null;
}
-/** The fact-check settings with every default filled in. */
+/**
+ * Why a counter series' words do not fit its tally cell (`deck.counter`,
+ * counter.mjs), as the verdicts' are held: its `tallyLabel` must fit, else
+ * its label or a run of its last words must. null when they fit.
+ */
+export function counterLabelProblem(s, w, { fontBold = null } = {}) {
+ const label = s.label ?? VERDICT_DEFAULTS[s.id]?.label ?? s.id;
+ if (typeof s.tallyLabel === "string") {
+ const px = tallyLabelWidth(s.tallyLabel.trim(), { fontBold });
+ return px > TALLY_LABEL.width
+ ? `${w}.tallyLabel "${s.tallyLabel.trim()}" is ${px} px wide in the tally's cell, which has ${TALLY_LABEL.width} px: shorten it`
+ : null;
+ }
+ if (tallyLabelOf({ label }, { fontBold }) !== null) return null;
+ const px = tallyLabelWidth(label, { fontBold });
+ return `${w}.label "${String(label).trim()}" is ${px} px wide in the tally's cell, which has ${TALLY_LABEL.width} px, and no run of its last words fits: set ${w}.tallyLabel to a shorter word`;
+}
+
+/**
+ * The fact-check settings with every default filled in. `verdicts` are the
+ * COUNTER's series (counter.mjs `resolveCounter`): the verdicts with their
+ * relabels, as ever, or a `deck.counter`'s named series -- each `{ label,
+ * color, stampLabel?, tallyLabel? }` by id either way -- and `tally` its
+ * cells' show, position and showAt.
+ */
export function resolveFactcheck(render) {
const f = isObj(render?.chrome?.factcheck) ? render.chrome.factcheck : {};
+ const counter = resolveCounter(render);
return {
- verdicts: resolveVerdicts(f.verdicts),
+ verdicts: counter.custom ? counter.byId : resolveVerdicts(f.verdicts),
stamp: { ...FACTCHECK_DEFAULTS.stamp, ...(isObj(f.stamp) ? f.stamp : {}) },
- tally: { ...FACTCHECK_DEFAULTS.tally, ...(isObj(f.tally) ? f.tally : {}) },
+ tally: counter.custom
+ ? { show: counter.show, position: counter.position, showAt: counter.showAt }
+ : { ...FACTCHECK_DEFAULTS.tally, ...(isObj(f.tally) ? f.tally : {}) },
};
}
@@ -299,7 +328,7 @@ export function validateFactcheck(f, where = "render.chrome.factcheck", { fontBo
* @returns {{ id: string, verdict: string, at?: number, hold?: number,
* stamp?: false, count?: number, label?: string, eventDate?: string } | null}
*/
-export function normalizeClaim(v) {
+export function normalizeClaim(v, { series = null } = {}) {
if (v === undefined || v === null) return null;
if (!isObj(v)) throw new Error("claim must be { id, verdict }");
for (const k of Object.keys(v)) {
@@ -307,8 +336,13 @@ export function normalizeClaim(v) {
}
const id = typeof v.id === "string" ? v.id.trim() : "";
if (!CLAIM_ID_RE.test(id)) throw new Error("claim.id must be letters, digits, dots, colons, dashes or underscores (at most 64)");
- if (!VERDICTS.includes(v.verdict)) throw new Error(`claim.verdict must be one of ${VERDICTS.join(", ")}`);
- const out = { id, verdict: v.verdict };
+ // The series it counts (counter.mjs): `verdict`, or its alias `counter` --
+ // one of the counter's series ids (`series`; the verdicts unless given).
+ if (v.counter !== undefined && v.verdict !== undefined) throw new Error("claim.counter and claim.verdict are one setting: set one");
+ const name = v.counter ?? v.verdict;
+ const allowed = series ?? VERDICTS;
+ if (!allowed.includes(name)) throw new Error(`claim.verdict must be one of ${allowed.join(", ")}`);
+ const out = { id, verdict: name };
if (v.at !== undefined) {
if (!numIn(v.at, 0, Number.MAX_SAFE_INTEGER)) throw new Error("claim.at must be a source second, 0 or more");
out.at = v.at;
@@ -369,7 +403,7 @@ export function rawMarksOf(entry) {
*
* @returns {Array<NonNullable<ReturnType<typeof normalizeClaim>>>}
*/
-export function normalizeMarks(v) {
+export function normalizeMarks(v, { series = null } = {}) {
if (!Array.isArray(v)) throw new Error("claims must be a list of marks [{ id, verdict, … }]");
if (!v.length) throw new Error("claims must name at least one mark (remove the key for none)");
if (v.length > CLAIM_MARKS_MAX) throw new Error(`claims holds ${v.length} marks (at most ${CLAIM_MARKS_MAX})`);
@@ -377,7 +411,7 @@ export function normalizeMarks(v) {
return v.map((m, k) => {
let c;
try {
- c = normalizeClaim(m);
+ c = normalizeClaim(m, { series });
} catch (err) {
throw new Error(String(err.message).replace(/^claim\b/, `claims[${k}]`));
}
@@ -393,11 +427,11 @@ export function normalizeMarks(v) {
* written. None on a teaser, or on a shape that does not normalise. Never
* throws.
*/
-export function marksOf(entry) {
+export function marksOf(entry, series = null) {
if (!isObj(entry) || entry.type === "teaser") return [];
try {
- if (Array.isArray(entry.claims)) return entry.claim === undefined || entry.claim === null ? normalizeMarks(entry.claims) : [];
- const c = normalizeClaim(entry.claim);
+ if (Array.isArray(entry.claims)) return entry.claim === undefined || entry.claim === null ? normalizeMarks(entry.claims, { series }) : [];
+ const c = normalizeClaim(entry.claim, { series });
return c ? [c] : [];
} catch {
return [];
@@ -408,8 +442,8 @@ export function marksOf(entry) {
* An entry's claim when it carries a sound one, else null: its FIRST mark --
* the one its pip and rail take their verdict's colour from. Never throws.
*/
-export function claimOf(entry) {
- return marksOf(entry)[0] ?? null;
+export function claimOf(entry, series = null) {
+ return marksOf(entry, series)[0] ?? null;
}
/**
@@ -422,6 +456,8 @@ export function claimOf(entry) {
*/
export function validateClaims(manifest) {
const errors = [];
+ // The series a mark may count: the counter's (counter.mjs), else the verdicts.
+ const series = resolveCounter(manifest?.render).order;
const verdictOf = new Map();
const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
// The last entry carrying each id: a mark stamps there, and only there.
@@ -439,7 +475,7 @@ export function validateClaims(manifest) {
if (e.type === "teaser") { errors.push(`${where}.${key}: a teaser is not evidence for a claim`); return; }
let marks;
try {
- marks = many ? normalizeMarks(e.claims) : [normalizeClaim(e.claim)];
+ marks = many ? normalizeMarks(e.claims, { series }) : [normalizeClaim(e.claim, { series })];
} catch (err) {
errors.push(`${where}.${err.message}`);
return;
@@ -601,6 +637,21 @@ export function stampSchedule({ segments, D, total, render }) {
});
}
+/**
+ * The counter's stamps given the finale's window (`finale.window`: its
+ * `start` and the `segments` it plays, or null for none): a stamp that would
+ * land on a finale clip counts as the finale opens instead -- its totals are
+ * final -- and is not drawn (there is no footage box to stamp, and the clip
+ * before is not the claim's). Every other stamp is as stamped.
+ */
+export function stampsWithFinale(stamps, finale) {
+ if (!finale) return stamps;
+ const at = finale.start;
+ return stamps.map((s) => (finale.segments.has(s.segment)
+ ? { ...s, at, landed: at, out: [at, at], stamp: false, finale: true }
+ : s));
+}
+
/** The stamps that are DRAWN: all but a claim's `stamp: false`. */
export const drawnStamps = (stamps = []) => stamps.filter((s) => s.stamp !== false);
@@ -617,10 +668,9 @@ export function stampsDrawn(schedule, render) {
* The shape a claimed clip's pip takes (`deck.pip.color: "verdict"`), one per
* verdict in VERDICTS order, so a viewer who cannot tell the colours apart
* can still tell the verdicts apart. The tally's cells carry the same shape.
+ * A counter's series take theirs from `resolveCounter(render).shapes`.
*/
-export const VERDICT_SHAPES = Object.freeze(Object.fromEntries(
- VERDICTS.map((v, i) => [v, ["circle", "diamond", "square", "triangle", "ring"][i] ?? "circle"]),
-));
+export { VERDICT_SHAPES };
/** `stampSchedule`'s stamps as a schedule writes them: seconds to the millisecond. */
export function roundStamps(stamps) {
@@ -628,10 +678,10 @@ export function roundStamps(stamps) {
return stamps.map((s) => ({ ...s, at: round(s.at), landed: round(s.landed), out: s.out.map(round) }));
}
-/** The verdicts a cut's stamps use, in VERDICTS order: the tally's cells. */
-export function tallyVerdicts(stamps = []) {
+/** The series a cut's stamps use, in the counter's order (`order`, the verdicts unless given): the tally's cells. */
+export function tallyVerdicts(stamps = [], order = VERDICTS) {
const used = new Set(stamps.map((s) => s.verdict));
- return VERDICTS.filter((v) => used.has(v));
+ return order.filter((v) => used.has(v));
}
/**
@@ -642,21 +692,21 @@ export function tallyVerdicts(stamps = []) {
*
* @returns {Array<{ at: number, verdict: string, count: number, step: number, counts: Record<string, number> }>}
*/
-export function tallySteps(stamps = []) {
- const counts = Object.fromEntries(VERDICTS.map((v) => [v, 0]));
+export function tallySteps(stamps = [], order = VERDICTS) {
+ const counts = Object.fromEntries(order.map((v) => [v, 0]));
return [...stamps]
.sort((a, b) => a.landed - b.landed)
.map((s) => {
const step = s.count ?? 1;
- counts[s.verdict] += step;
+ counts[s.verdict] = (counts[s.verdict] ?? 0) + step;
return { at: s.landed, verdict: s.verdict, count: counts[s.verdict], step, counts: { ...counts } };
});
}
/** Each verdict's count at the end of the cut: the tally's last numbers. */
-export function tallyFinals(stamps = []) {
- const finals = Object.fromEntries(VERDICTS.map((v) => [v, 0]));
- for (const s of stamps) finals[s.verdict] += s.count ?? 1;
+export function tallyFinals(stamps = [], order = VERDICTS) {
+ const finals = Object.fromEntries(order.map((v) => [v, 0]));
+ for (const s of stamps) finals[s.verdict] = (finals[s.verdict] ?? 0) + (s.count ?? 1);
return finals;
}
@@ -667,7 +717,7 @@ export function tallyFinals(stamps = []) {
export function tallyOf(schedule, render) {
const stamps = schedule?.factcheck?.stamps ?? [];
if (!stamps.length || !resolveFactcheck(render).tally.show) return null;
- return tallyVerdicts(stamps);
+ return tallyVerdicts(stamps, resolveCounter(render).order);
}
/**
@@ -677,9 +727,7 @@ export function tallyOf(schedule, render) {
* @returns {Record<string, "always" | "first">}
*/
export function tallyShowAt(render) {
- const w = resolveFactcheck(render).tally.showAt;
- const one = (v) => (TALLY_SHOW_AT.includes(v) ? v : "always");
- return Object.fromEntries(VERDICTS.map((v) => [v, isObj(w) ? one(w[v]) : one(w)]));
+ return { ...resolveCounter(render).showAt };
}
/**
diff --git a/umtool/report-to-video/frame-keys.mjs b/umtool/report-to-video/frame-keys.mjs
@@ -27,6 +27,27 @@
// the ids list (preview messages), and every `data-duration` (each the whole
// page's; checked). Anything else in the page's data stays in.
//
+// PER-MODULE CACHE RULES (release 39, the video modules). Each module's
+// `frameKeys` (modules/<id>.mjs) is its model: the data fields left out of
+// the static part, its own eases, a window's offset -- and two rules that
+// keep the static part MINIMAL:
+//
+// - ASSETS BY CONTENT. A page names its assets by place (`qr03.png`,
+// `shot07.png`: first seen, first numbered), so a post inserted early
+// renumbered every one after it. The key reads each asset reference as
+// its content's hash: an asset is the same asset wherever it is filed.
+// - ITEMS. A page may hand over its items (`items`: each segment's text,
+// each pip, each feed card) -- markup a frame draws only while its GATE
+// is visible: a slot (`gate: [k, prop]`, the item's own opacity or
+// autoAlpha) that is not 0, or for the feed an event that has happened
+// (`event`). An item's markup, the assets it names and its slots' values
+// are in the key of a frame that shows it and of no other, so a changed
+// subtitle recaptures the frames its clip is on screen, and a clip or
+// post inserted later leaves the frames before it as they were.
+//
+// FRAME_KEY_VERSION 2 is these rules: a render keyed by version 1 is
+// captured once more, then reused as ever.
+//
// Refused -- `null`, and the layer is rendered whole as before -- when the
// page is not one this models: no data script, a `data-duration` that is not
// the page's, a window, a cue whose FROM is not what its element holds, two
@@ -42,24 +63,20 @@ import vm from "node:vm";
import { GSAP_FILE } from "./chrome-deck.mjs";
import { feedCues } from "./chrome-feed.mjs";
+import { MODULES } from "./modules/index.mjs";
/** Bumped when what a frame key covers changes: every frame is captured once more. */
-export const FRAME_KEY_VERSION = 1;
+export const FRAME_KEY_VERSION = 2;
-/** The regions whose pages this models, and the data fields their key leaves out of the static part. */
-export const FRAME_KEY_REGIONS = Object.freeze({
- deck: { data: "deck-data", omit: ["init", "cues", "window", "total", "ids"] },
- stamp: { data: "stamp-data", omit: ["init", "cues", "window", "total", "ids"] },
- // The feed plans its cues IN the page, from the heights its cards measure
- // (chrome-feed.mjs): keyed by its EVENTS instead (feedFrameKeys).
- feed: { data: "feed-data", omit: ["window", "total", "ids", "posts", "visibility"], events: true },
- // The finale is a window of the cut by design: its frame n is cut time
- // `from` + n / fps, and its one ease of its own is the page's smoothstep.
- finale: {
- data: "finale-data", omit: ["init", "cues", "from", "dur"], offset: "from",
- eases: { smoothstep: { page: "const EASES = { smoothstep: (p) => p * p * (3 - 2 * p) };", fn: (p) => p * p * (3 - 2 * p) } },
- },
-});
+/**
+ * The regions whose pages this models, and the data fields their key leaves
+ * out of the static part: each module's own `frameKeys` (modules/<id>.mjs),
+ * by its region -- the shell's deck, the stamps, the feed (keyed by its
+ * EVENTS: it plans its cues in the page), the finale (a window of the cut).
+ */
+export const FRAME_KEY_REGIONS = Object.freeze(
+ Object.fromEntries(MODULES.filter((m) => m.region && m.frameKeys).map((m) => [m.region, m.frameKeys])),
+);
/**
* How long after a feed event (a post in, the column hidden or shown) its
@@ -111,11 +128,32 @@ function splitData(html, id) {
return { data, before: html.slice(0, from), after: html.slice(to) };
}
+/** An asset reference in a page: `assets/<name>`. */
+const ASSET_REF = /assets\/([A-Za-z0-9._-]+)/g;
+
+/**
+ * A page's text with every asset reference read as its content's hash
+ * (`assets/#<sha>`), and the names it referenced.
+ */
+function byContent(text, hashOf) {
+ const used = new Set();
+ const out = text.replace(ASSET_REF, (m, name) => {
+ const h = hashOf.get(name);
+ if (h === undefined) return m;
+ used.add(name);
+ return `assets/#${h}`;
+ });
+ return { text: out, used };
+}
+
/**
- * The static part's key: the page less what is keyed per frame, the assets'
- * hashes, the frame rate and the renderer. null when the page is not modelled.
+ * The page split into its static part and its items: `{ data, page, items,
+ * assets }`, `page` the static text (the data script less `omit`, every
+ * item's markup out, every asset by content), `items` each `{ key, gate?,
+ * event?, hash }` in page order, `assets` the static part's asset hashes.
+ * null when the page is not modelled.
*/
-export function staticKey({ html, region, assets = [], fps, version, frames = null }) {
+function splitPage({ html, region, assets = [], fps, frames = null, items = null }) {
const spec = FRAME_KEY_REGIONS[region];
if (!spec) return null;
const parts = splitData(html, spec.data);
@@ -132,12 +170,55 @@ export function staticKey({ html, region, assets = [], fps, version, frames = nu
const durs = [...html.matchAll(/data-duration="([^"]*)"/g)].map((m) => m[1]);
if (!durs.length || durs.some((d) => d !== durs[0])) return null;
const starts = [...html.matchAll(/data-start="([^"]*)"/g)].map((m) => m[1]);
- if (starts.some((s) => s !== "0")) return null;
+ if (starts.some((x) => x !== "0")) return null;
const rest = Object.fromEntries(Object.entries(data).filter(([k]) => !spec.omit.includes(k)));
- const page = (parts.before + JSON.stringify(rest) + parts.after).replace(/data-duration="[^"]*"/g, 'data-duration=""');
- const sorted = [...assets].map(([n, h]) => [String(n), String(h)]).sort((x, y) => x[0].localeCompare(y[0]));
+ let page = (parts.before + JSON.stringify(rest) + parts.after).replace(/data-duration="[^"]*"/g, 'data-duration=""');
+ const hashOf = new Map([...assets].map(([n, h]) => [String(n), String(h)]));
+ // The items out of the page, each hashed with the assets it names.
+ const itemOut = [];
+ const itemAssets = new Set();
+ for (const it of items ?? []) {
+ if (!it || typeof it.html !== "string" || !it.html) return null;
+ const at = page.indexOf(it.html);
+ if (at < 0) return null;
+ // With the whitespace that joins it to what is before it: a page's items
+ // are absolutely placed boxes, and the joins between them are not drawn
+ // -- so a page of n items and one of n + 1 have the same static part.
+ const lead = /\s*$/.exec(page.slice(0, at))[0].length;
+ page = page.slice(0, at - lead) + page.slice(at + it.html.length);
+ const { text, used } = byContent(it.html, hashOf);
+ for (const n of used) itemAssets.add(n);
+ itemOut.push({
+ key: it.key, at,
+ ...(it.gate ? { gate: it.gate } : {}),
+ ...(Number.isInteger(it.event) ? { event: it.event } : {}),
+ hash: createHash("sha1").update(text).digest("hex"),
+ });
+ }
+ // In page order (each removal shifts what follows: the order of `at` as removed is not the page's).
+ const ordered = items?.length ? orderItems(html, items, itemOut) : itemOut;
+ const { text: staticText, used } = byContent(page, hashOf);
+ // The static part's assets: every one it names, and every one no item names.
+ const statics = [...hashOf.entries()].filter(([n]) => used.has(n) || !itemAssets.has(n)).map(([, h]) => h).sort();
+ return { data, page: staticText, items: ordered, assets: statics };
+}
+
+/** The items in the order their markup stands in the page. */
+function orderItems(html, items, out) {
+ const pos = items.map((it) => html.indexOf(it.html));
+ return out.map((o, i) => ({ o, p: pos[i] })).sort((x, y) => x.p - y.p).map((x) => x.o);
+}
+
+/**
+ * The static part's key: the page less what is keyed per frame (and less
+ * its items), its assets by content, the frame rate and the renderer. null
+ * when the page is not modelled.
+ */
+export function staticKey({ html, region, assets = [], fps, version, frames = null, items = null }) {
+ const sp = splitPage({ html, region, assets, fps, frames, items });
+ if (!sp) return null;
return createHash("sha256")
- .update(JSON.stringify({ v: FRAME_KEY_VERSION, region, page, assets: sorted, fps, version }))
+ .update(JSON.stringify({ v: FRAME_KEY_VERSION, region, page: sp.page, assets: sp.assets, fps, version, items: !!items?.length }))
.digest("hex");
}
@@ -149,12 +230,13 @@ const repr = (v) => (typeof v === "number" ? `n${gsapRound(v)}` : `s${JSON.strin
*
* @returns {string[] | null} hex keys, frame 1 first
*/
-export function frameKeys({ html, region, assets = [], fps, frames, version }) {
- const sk = staticKey({ html, region, assets, fps, version, frames });
+export function frameKeys({ html, region, assets = [], fps, frames, version, items = null }) {
+ const sk = staticKey({ html, region, assets, fps, version, frames, items });
if (!sk) return null;
- if (FRAME_KEY_REGIONS[region].events) return feedFrameKeys({ html, sk, fps, frames });
+ const sp = splitPage({ html, region, assets, fps, frames, items });
+ if (FRAME_KEY_REGIONS[region].events) return feedFrameKeys({ html, sk, fps, frames, items: sp.items });
const spec = FRAME_KEY_REGIONS[region];
- const { data } = splitData(html, spec.data);
+ const { data } = sp;
const init = data.init;
const cues = data.cues;
const t0 = spec.offset ? Number(data[spec.offset]) : 0;
@@ -221,16 +303,39 @@ export function frameKeys({ html, region, assets = [], fps, frames, version }) {
// The state's hash: XOR over the slots of each slot's (id, value) hash,
// updated only where a value moves. Each slot's changes come from its own
// cue boundaries (a step) or a running cue (every frame).
+ // One accumulator for the page's own slots and one per item: an item's
+ // slots (its key, or its key's children `<key>.<part>`) count only while
+ // it is shown.
const acc = Buffer.alloc(20);
- const xor = (b) => {
- for (let i = 0; i < 20; i += 1) acc[i] ^= b[i];
+ const itemList = sp.items;
+ const itemAcc = itemList.map(() => Buffer.alloc(20));
+ const itemByKey = new Map(itemList.map((it, i) => [it.key, i]));
+ const ownerOf = (k) => {
+ if (itemByKey.has(k)) return itemByKey.get(k);
+ const dot = k.indexOf(".");
+ return dot > 0 && itemByKey.has(k.slice(0, dot)) ? itemByKey.get(k.slice(0, dot)) : -1;
+ };
+ const owner = new Map();
+ for (const s of slots.values()) owner.set(s.id, ownerOf(s.k));
+ const xorInto = (buf, b) => {
+ for (let i = 0; i < 20; i += 1) buf[i] ^= b[i];
+ };
+ const xor = (id, b) => {
+ const o = owner.get(id);
+ xorInto(o >= 0 ? itemAcc[o] : acc, b);
};
const cur = new Map();
for (const s of slots.values()) {
const v = valueAt(s, t0);
cur.set(s.id, v);
- xor(sha1(`${s.id}\u0001${v}`));
+ xor(s.id, sha1(`${s.id}\u0001${v}`));
}
+ // An item's gate: hidden while its slot holds 0 (at rest, from init or a
+ // finished cue); anything else -- a value, a cue running, a CSS default --
+ // is shown.
+ const HIDDEN = new Set(["in0", "en0"]);
+ const gateId = itemList.map((it) => (it.gate ? `${it.gate[0]}\u0000${it.gate[1]}` : null));
+ for (const id of gateId) if (id !== null && !slots.has(id)) return null;
// Per frame, the slots that may move: those with a cue starting by it or running at it.
const frameOf = (t) => Math.ceil((t - t0) * fps - 1e-6);
const touch = new Map(); // frame -> slots
@@ -254,11 +359,17 @@ export function frameKeys({ html, region, assets = [], fps, frames, version }) {
const v = valueAt(s, t);
const was = cur.get(s.id);
if (v === was) continue;
- xor(sha1(`${s.id}\u0001${was}`));
- xor(sha1(`${s.id}\u0001${v}`));
+ xor(s.id, sha1(`${s.id}\u0001${was}`));
+ xor(s.id, sha1(`${s.id}\u0001${v}`));
cur.set(s.id, v);
}
- out[f] = createHash("sha1").update(sk).update(acc).digest("hex");
+ const h = createHash("sha1").update(sk).update(acc);
+ for (let i = 0; i < itemList.length; i += 1) {
+ const g = gateId[i];
+ if (g !== null && HIDDEN.has(cur.get(g))) continue;
+ h.update(`\u0002${itemList[i].key}\u0003${itemList[i].hash}`).update(itemAcc[i]);
+ }
+ out[f] = h.digest("hex");
}
return out;
}
@@ -274,7 +385,7 @@ export function frameKeys({ html, region, assets = [], fps, frames, version }) {
* page's plan, run here with the shortest and the tallest cards, has a cue
* that runs past the cap after the event before it.
*/
-function feedFrameKeys({ html, sk, fps, frames }) {
+function feedFrameKeys({ html, sk, fps, frames, items = [] }) {
const { data } = splitData(html, FRAME_KEY_REGIONS.feed.data);
const g = Number(data.grid);
const per = g / fps;
@@ -310,13 +421,20 @@ function feedFrameKeys({ html, sk, fps, frames }) {
}
}
+ // A card's markup (its item) is in a frame's key from its post's event
+ // on: before it the card is hidden and moves nothing (the plan is causal:
+ // a post's cues start at its event). An event still to come is in no
+ // frame's key, so a post added later leaves the frames before it alone.
+ const cardOf = new Map(items.filter((it) => Number.isInteger(it.event)).map((it) => [`p${it.event}`, it.hash]));
const out = new Array(frames);
for (let f = 0; f < frames; f += 1) {
const t = f * per;
let sig = "";
for (const e of events) {
const d = t - e.at;
- sig += `${e.tag}=${d < 0 ? "f" : d >= cap ? "s" : d};`;
+ if (d < 0) continue;
+ const card = cardOf.get(e.tag);
+ sig += `${e.tag}=${d >= cap ? "s" : d}${card ? `|${card}` : ""};`;
}
out[f] = createHash("sha1").update(sk).update(sig).digest("hex");
}
diff --git a/umtool/report-to-video/frame-keys.test.mjs b/umtool/report-to-video/frame-keys.test.mjs
@@ -276,3 +276,133 @@ test("feed frame keys: by its events; a moved post keys as it did, a changed one
const C = keys([10, 21, 4, 6]);
assert.equal(C.k[200], A.k[200]);
});
+
+// ---- the module cache rules (release 39): items and assets by content ------
+
+const itemKeysOf = (s, render = RENDER, assets = []) => {
+ const items = [];
+ const html = deckHtml(s, render, { fonts: FONTS, items });
+ return frameKeys({ html, region: "deck", fps: 30, frames: Math.round(s.total * 30), version: "v", assets, items });
+};
+
+test("items: a changed title changes only the frames its clip's text is on screen", () => {
+ const A = itemKeysOf(schedule(0));
+ const T = itemKeysOf(schedule(0, { c02: "Another sanctuary" }));
+ const differ = A.map((k, n) => (k !== T[n] ? n : null)).filter((n) => n != null);
+ assert.ok(differ.length > 0, "the frames that show it change");
+ // c02 plays 14–22 s; its text is in from the handover into it to the one out of it.
+ assert.ok(differ[0] >= 14 * 30 - 15, `nothing before its handover changes (first at ${differ[0]})`);
+ assert.ok(differ.at(-1) <= 22.5 * 30, `nothing after it is gone changes (last at ${differ.at(-1)})`);
+ assert.equal(A.slice(0, 13 * 30).join(), T.slice(0, 13 * 30).join());
+ // The page with items keys apart from the page without (a key is its model's).
+ assert.notEqual(A[500], keysOf(schedule(0))[500]);
+});
+
+test("items: assets keyed by content -- the same picture under another name is the same frame", () => {
+ const s = schedule(0);
+ s.segments = s.segments.map((x, i) => ({ ...x, qrUrl: `https://x.test/${x.id}` }));
+ const render = { ...RENDER, chrome: { ...RENDER.chrome, deck: { qr: { show: true } } } };
+ const items = [];
+ const qrs = (names) => Object.fromEntries(s.segments.map((x, i) => [x.id, `assets/${names[i]}`]));
+ const keyed = (names, hashes) => {
+ const its = [];
+ const html = deckHtml(s, render, { fonts: FONTS, qrSrcs: qrs(names), items: its });
+ return frameKeys({ html, region: "deck", fps: 30, frames: 1200, version: "v", items: its, assets: names.map((n, i) => [n, hashes[i]]) });
+ };
+ void items;
+ const H = ["h0", "h1", "h2", "h3", "h4"];
+ const A = keyed(["qr00.png", "qr01.png", "qr02.png", "qr03.png", "qr04.png"], H);
+ const B = keyed(["qr10.png", "qr11.png", "qr12.png", "qr13.png", "qr14.png"], H);
+ assert.deepEqual(A, B, "renamed assets of the same bytes key alike");
+ const C = keyed(["qr00.png", "qr01.png", "qr02.png", "qr03.png", "qr04.png"], ["h0", "h1", "hX", "h3", "h4"]);
+ const differ = A.map((k, n) => (k !== C[n] ? n : null)).filter((n) => n != null);
+ assert.ok(differ.length > 0 && differ[0] >= 13 * 30, "a changed code changes only where its clip shows");
+});
+
+test("rail pitch: a clip appended leaves every frame before it as it was", async () => {
+ const { estimateSchedule } = await import("./deck.mjs");
+ const PITCH = { ...RENDER, chrome: { ...RENDER.chrome, deck: { pip: { spacing: "pitch", pitch: 40 } } } };
+ const clip = (id, end) => ({ type: "clip", id, video: id, start: 0, end, date: "2024-01-01" });
+ const base = [clip("a", 8), clip("b", 9), clip("c", 7)];
+ const keys = (timeline, render) => {
+ const s = estimateSchedule({ render, timeline, posts: [], provenance: {} });
+ return { s, k: itemKeysOf(s, render) };
+ };
+ const A = keys(base, PITCH);
+ const B = keys([...base, clip("d", 6)], PITCH);
+ // Until the marker reaches c's pip -- and d's pip comes in ahead of it --
+ // every frame is the same; from then on the rail shows d's pip.
+ const cStart = A.s.segments[2].start;
+ const first = A.k.findIndex((k, f) => k !== B.k[f]);
+ assert.ok(first > Math.floor(cStart * 30), `the frames before c keep their keys (first change at frame ${first}, c at ${cStart * 30})`);
+ assert.ok(first < Math.floor((cStart + 1.5) * 30), "d's pip comes in as the marker reaches c");
+ // Even spacing moves every pip: nothing is reused.
+ const E = keys(base, RENDER), F = keys([...base, clip("d", 6)], RENDER);
+ assert.notEqual(E.k[10], F.k[10]);
+});
+
+test("feed items: a changed or added post changes only the frames from its event on", async () => {
+ const { feedHtml } = await import("./chrome-feed.mjs");
+ const { deckSchedule } = await import("./deck.mjs");
+ const FEED = { ...RENDER, chrome: { engine: "hyperframes", layout: "deck", deck: { posts: { layout: "feed" } } } };
+ const CLIPS = [
+ { id: "c1", type: "clip", video: "a", start: 0, end: 10, date: "2024-09-05" },
+ { id: "c2", type: "clip", video: "b", start: 0, end: 20, date: "2024-10-01" },
+ { id: "c3", type: "clip", video: "c", start: 0, end: 6, date: "2025-12-08" },
+ ];
+ const POST = (id, date, text = `words of ${id}`) => ({ id, platform: "bluesky", author: "P", handle: "p.live", date, text, url: `https://bsky.app/profile/p.live/post/${id}` });
+ const keys = (posts) => {
+ const s = deckSchedule({ entries: CLIPS, durs: [10, 20, 6], D: 0.5, render: FEED, provenance: { siteOrigin: "https://x.test", channelSlug: "c" }, posts });
+ const items = [];
+ const html = feedHtml(s, FEED, { fonts: FONTS, items });
+ return { s, k: frameKeys({ html, region: "feed", fps: 30, frames: Math.round(s.total * 30), version: "v", items }) };
+ };
+ const base = [POST("a", "2024-10-19"), POST("b", "2025-01-02")];
+ const A = keys(base);
+ assert.ok(A.k, "modelled with items");
+ const lastIn = A.s.posts.at(-1).in;
+ // b's words changed: nothing before b comes in changes.
+ const B = keys([base[0], POST("b", "2025-01-02", "other words entirely")]);
+ const firstB = A.k.findIndex((k, f) => k !== B.k[f]);
+ assert.ok(firstB >= Math.floor(lastIn * 30), `nothing before b's event changes (first at ${firstB}, b at ${lastIn * 30})`);
+ // A post added on the last clip: nothing before it changes.
+ const C = keys([...base, POST("z", "2026-01-22")]);
+ const zIn = C.s.posts.find((p) => p.id === "z").in;
+ const firstC = A.k.findIndex((k, f) => k !== C.k[f]);
+ assert.ok(firstC >= Math.floor(zIn * 30), `nothing before z's event changes (first at ${firstC}, z at ${zIn * 30})`);
+});
+
+test("compose-chrome with the deck's items: a changed title captures only the frames its clip shows", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "frame-items-"));
+ const env = process.env.HYPERFRAMES_BIN;
+ try {
+ const stub = path.join(dir, "hf-stub.mjs");
+ writeFileSync(stub, STUB);
+ chmodSync(stub, 0o755);
+ process.env.HYPERFRAMES_BIN = stub;
+ const font = path.join(dir, "face.ttf");
+ writeFileSync(font, "face");
+ const render = { ...RENDER, fontRegular: font, fontBold: font };
+ const mp = path.join(dir, "video.manifest.json");
+ writeFileSync(mp, JSON.stringify({ slug: "f", render, timeline: [] }));
+ const out = path.join(dir, "out", "sourced");
+ mkdirSync(out, { recursive: true });
+ const { composeChrome, FRAME_KEYS_FILE } = await import("./compose-chrome.mjs");
+ writeFileSync(path.join(out, "schedule.json"), JSON.stringify(schedule(0)));
+ const first = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30 });
+ assert.equal(first.frameCount, 1200);
+ const keys0 = readFileSync(path.join(first.frames, FRAME_KEYS_FILE), "utf8").trim().split("\n");
+ writeFileSync(path.join(out, "schedule.json"), JSON.stringify(schedule(0, { c02: "Another sanctuary" })));
+ const second = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30 });
+ const keys1 = readFileSync(path.join(second.frames, FRAME_KEYS_FILE), "utf8").trim().split("\n");
+ const changed = keys1.filter((k, i) => k !== keys0[i]).length;
+ // c02 is on screen ~14-22 s of a 40 s cut: about a fifth of the frames, never all.
+ assert.ok(changed > 0 && changed < 300, `${changed} frames changed`);
+ assert.ok(second.reused >= 1200 - changed, `${second.reused} reused`);
+ assert.ok(second.captured <= changed, `${second.captured} captured`);
+ } finally {
+ if (env === undefined) delete process.env.HYPERFRAMES_BIN;
+ else process.env.HYPERFRAMES_BIN = env;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/intro.mjs b/umtool/report-to-video/intro.mjs
@@ -65,16 +65,16 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { promisify } from "node:util";
import {
- INTRO_BEATS, INTRO_GROUNDS, INTRO_ID, INTRO_MARKS, INTRO_SECONDS, INTRO_SECONDS_MAX, INTRO_SECONDS_MIN, INTRO_SITE_DEFAULTS,
- INTRO_STYLE_GROUND, INTRO_STYLE_MARK, INTRO_STYLES, INTRO_SWAPS, INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf,
- introSitePrefix, introUrlText, validateIntro,
+ INTRO_BEATS, INTRO_BRAND_DEFAULT, INTRO_GROUNDS, INTRO_ID, INTRO_MARKS, INTRO_PROJECT_URL, INTRO_SECONDS, INTRO_SECONDS_MAX,
+ INTRO_SECONDS_MIN, INTRO_SITE_DEFAULTS, INTRO_STYLE_GROUND, INTRO_STYLE_MARK, INTRO_STYLES, INTRO_SUFFIX, INTRO_SWAPS,
+ INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf, introSitePrefix, introUrlText, validateIntro,
} from "yt-dlp-transcript-common/lib/report/intro.mjs";
import { SITES_DIR } from "../lib/paths.mjs";
export {
- INTRO_BEATS, INTRO_GROUNDS, INTRO_ID, INTRO_MARKS, INTRO_SECONDS, INTRO_SECONDS_MAX, INTRO_SECONDS_MIN, INTRO_SITE_DEFAULTS,
- INTRO_STYLE_GROUND, INTRO_STYLE_MARK, INTRO_STYLES, INTRO_SWAPS, INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf,
- introSitePrefix, introUrlText, validateIntro,
+ INTRO_BEATS, INTRO_BRAND_DEFAULT, INTRO_GROUNDS, INTRO_ID, INTRO_MARKS, INTRO_PROJECT_URL, INTRO_SECONDS, INTRO_SECONDS_MAX,
+ INTRO_SECONDS_MIN, INTRO_SITE_DEFAULTS, INTRO_STYLE_GROUND, INTRO_STYLE_MARK, INTRO_STYLES, INTRO_SUFFIX, INTRO_SWAPS,
+ INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf, introSitePrefix, introUrlText, validateIntro,
};
const execFileP = promisify(execFile);
@@ -195,6 +195,10 @@ export function introEntry(render, { provenance = null, sitesDir = SITES_DIR } =
return {
type: INTRO_TYPE, id: INTRO_ID, style: o.style, ground: o.ground, mark: o.mark, seconds: o.seconds,
...(o.sound !== undefined ? { sound: o.sound } : {}),
+ // The brand's knobs, only when set (introOf): the plain intro's entry otherwise.
+ ...(o.brand !== undefined ? { brand: o.brand } : {}),
+ ...(o.suffix !== undefined ? { suffix: o.suffix } : {}),
+ ...(o.projectUrl !== undefined ? { projectUrl: o.projectUrl } : {}),
// The site's swap, resolved: only when one was found, so an intro with no
// site (or an "auto" that matched none) is the plain intro's entry.
...(site ? { site, swap: o.swap, url: o.url, urlPlace: o.urlPlace } : {}),
@@ -209,6 +213,15 @@ const siteObject = (site) => {
return rest;
};
+/** The brand kit the intro draws (`render.intro.brand`), refused by the intro's own key. */
+function introKit(brandKit, id) {
+ try {
+ return brandKit(id);
+ } catch (e) {
+ throw new Error(String(e?.message ?? e).replace(/^render\.brand /, "render.intro.brand "));
+ }
+}
+
/**
* The page's site knobs from an entry: `{ site, swap, url, urlPlace }` with the
* defaults filled in, or null (no site: introHtml is called exactly as before).
@@ -337,6 +350,9 @@ export async function renderIntro({ entry, render, encode, manifestDir = process
style: entry.style, ground: entry.ground, seconds: entry.seconds,
...(entry.mark !== undefined ? { mark: entry.mark } : {}),
...(entry.sound !== undefined ? { sound: entry.sound } : {}),
+ ...(entry.brand !== undefined ? { brand: entry.brand } : {}),
+ ...(entry.suffix !== undefined ? { suffix: entry.suffix } : {}),
+ ...(entry.projectUrl !== undefined ? { projectUrl: entry.projectUrl } : {}),
...(siteKnobs
? {
site: siteObject(siteKnobs.site), swap: siteKnobs.swap, urlPlace: siteKnobs.urlPlace,
@@ -353,8 +369,10 @@ export async function renderIntro({ entry, render, encode, manifestDir = process
const fps = render.fps ?? 30;
const html = introHtml({
style: entry.style, ground: entry.ground, ...(entry.mark !== undefined ? { mark: entry.mark } : {}),
- seconds: entry.seconds, width: W, height: H, fps, kit: brandKit("archilyzer-media"),
+ seconds: entry.seconds, width: W, height: H, fps, kit: introKit(brandKit, entry.brand ?? INTRO_BRAND_DEFAULT),
...(siteKnobs ?? {}),
+ ...(entry.suffix !== undefined ? { suffix: entry.suffix } : {}),
+ ...(entry.projectUrl !== undefined ? { projectUrl: entry.projectUrl } : {}),
});
const sound = introSoundPath(entry, manifestDir, standin);
let soundSha = null;
diff --git a/umtool/report-to-video/modules/blur.mjs b/umtool/report-to-video/modules/blur.mjs
@@ -0,0 +1,34 @@
+// THE BLUR (module `blur`, an input): a clip's picture blurred at its segment
+// encode, a caption drawn on it, the sound untouched (a clip's `blur`,
+// `render.blur` on/off for the uncensored variant; report-to-video
+// clip-blur.mjs). It filters the footage, so it has no page and no region.
+import {
+ BLUR_CAPTION_DEFAULT, BLUR_CAPTION_MAX, BLUR_STRENGTH, CLIP_BLUR_KEYS, RENDER_BLUR_VALUES, validateClipBlurEntries, validateRenderBlur,
+} from "../clip-blur.mjs";
+import { defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "blur",
+ version: 1,
+ z: 2,
+ kind: "input",
+ slot: "footage",
+ title: "Blur",
+ summary: "A clip's picture blurred at its encode, a caption on it, the sound as recorded.",
+ configKey: "render.blur",
+ defaults: { blur: "on", caption: BLUR_CAPTION_DEFAULT, strength: BLUR_STRENGTH.default },
+ validate: (_value, { manifest }) => [...validateRenderBlur(manifest), ...validateClipBlurEntries(manifest)],
+ ui: [
+ { key: "blur", type: "enum", options: RENDER_BLUR_VALUES, label: "Blurred clips", default: "on" },
+ { key: "clip.blur", type: "object", keys: CLIP_BLUR_KEYS, label: "A clip's blur",
+ caption: { max: BLUR_CAPTION_MAX, default: BLUR_CAPTION_DEFAULT }, strength: BLUR_STRENGTH },
+ ],
+ docs: {
+ heading: "Blur",
+ intro: "The full reference is [A clip's picture, blurred](#a-clips-picture-blurred).",
+ rows: [
+ ["`render.blur`", "`on` · `off` (the uncensored variant) · default `on`", "`umtool look <p> blur=off`"],
+ ["a clip's `blur`", `\`{on, caption?, strength?, from?, to?}\` -- caption ≤ ${BLUR_CAPTION_MAX}, strength ${BLUR_STRENGTH.min}–${BLUR_STRENGTH.max} (default ${BLUR_STRENGTH.default})`, "`umtool set <p> <clip> blur.on=true`"],
+ ],
+ },
+});
diff --git a/umtool/report-to-video/modules/chapter.mjs b/umtool/report-to-video/modules/chapter.mjs
@@ -0,0 +1,82 @@
+// THE CHAPTER (module `chapter`, region `chapter`): a section bumper over the
+// first seconds of the clip it opens -- a title, a subtitle, a date
+// (`render.chrome.chapter`). One short page per chapter, laid at its own
+// second like a posts window. chrome-story.mjs writes the page.
+import path from "node:path";
+
+import { snapWindow } from "../deck.mjs";
+import { chapterGeometry, chapterHtml, chapterWindows, resolveChapter } from "../chrome-story.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { CHAPTER_DEFAULTS, CHAPTER_LIMITS, CHAPTER_STYLES, validateChapter } from "./story-settings.mjs";
+
+const SEGMENT_RE = /^[A-Za-z0-9_.:-]+$/;
+
+export default defineModule({
+ id: "chapter",
+ version: 1,
+ z: 85,
+ kind: "overlay-window",
+ slot: "footage",
+ title: "Chapters",
+ summary: "A section bumper over the first seconds of the clip it opens: title, subtitle, date.",
+ configKey: "render.chrome.chapter",
+ defaults: CHAPTER_DEFAULTS,
+ validate: (v) => validateChapter(v),
+ resolve: resolveChapter,
+ ui: [
+ { key: "style", type: "enum", options: CHAPTER_STYLES, label: "Style", default: "card" },
+ { key: "seconds", type: "number", min: CHAPTER_LIMITS.seconds[0], max: CHAPTER_LIMITS.seconds[1], step: 0.25, label: "Seconds", default: 3 },
+ { key: "list", type: "list", label: "Chapters", item: [
+ { key: "at", type: "clip", label: "Opens clip" },
+ { key: "title", type: "text", label: "Title" },
+ { key: "subtitle", type: "text", label: "Subtitle" },
+ { key: "date", type: "date", label: "Date" },
+ ] },
+ ],
+ docs: {
+ heading: "Chapters",
+ intro: "A section bumper -- per dog, per crisis, per lawsuit -- over the first `seconds` of the clip it opens (`render.chrome.chapter`, chrome-story.mjs): a window of the cut laid at its own second, over the footage box (the deck stays). It does not insert time: the clip's sound plays under it.",
+ rows: [
+ ["`chrome.chapter.list[]`", `1–${CHAPTER_LIMITS.list} \`{at, title ≤${CHAPTER_LIMITS.title}, subtitle? ≤${CHAPTER_LIMITS.subtitle}, date?}\` -- \`at\` the clip it opens, once each`, "`umtool modules apply <p> --config module-config.json` · `umtool look <p> chapter='{…}'`"],
+ ["`chrome.chapter.style`", "`card` (the footage box covered) · `lower` (a band at its foot) · default `card`", "`umtool look <p> chapter.style=lower`"],
+ ["`chrome.chapter.seconds`", `${CHAPTER_LIMITS.seconds[0]}–${CHAPTER_LIMITS.seconds[1]} s, never past the clip · default 3`, "`umtool look <p> chapter.seconds=2.5`"],
+ ],
+ },
+ region: "chapter",
+ workers: "narrow",
+ noun: "the chapter's",
+ on: (schedule, render) => !!schedule?.segments && chapterWindows(schedule, render).length > 0,
+ check: (schedule, render) => (chapterWindows(schedule, render).length
+ ? null
+ : "the chapter region needs render.chrome.chapter with a chapter at a clip the cut plays"),
+ window(schedule, { window = null, segment = null, fps, total, render = {} }) {
+ const want = window ?? chapterWindows(schedule, render).find((w) => w.segment === segment);
+ if (!want) throw new Error(segment ? `no chapter opens ${segment} in this schedule` : "the chapter region needs a window (or a segment)");
+ if (!SEGMENT_RE.test(String(want.segment))) throw new Error(`chapter: ${want.segment} is not a segment id`);
+ return snapWindow(want, { fps, total });
+ },
+ names: ({ preview, window }) => ({ project: `chapter-${preview ? "preview-" : ""}${window.segment}`, stem: `chapter-${window.segment}` }),
+ async page(ctx) {
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ return chapterHtml(ctx.schedule, ctx.render, ctx.window, { fonts });
+ },
+ regions(schedule, { render, outDir, shift = 0, clip = null }) {
+ const fps = Number(schedule.fps ?? render.fps);
+ const g = chapterGeometry(render, { feed: schedule.layout === "feed" });
+ return chapterWindows(schedule, render)
+ .map((w) => ({ w, s: snapWindow(w, { fps, total: schedule.total }) }))
+ .filter(({ s }) => !clip || (s.from < clip.at + clip.dur && s.to > clip.at))
+ .map(({ w, s }) => assertRegion({
+ name: "chapter",
+ segment: s.segment,
+ window: { segment: w.segment, from: w.from, to: w.to },
+ frames: path.join(outDir, "chrome", `chapter-${s.segment}-frames`),
+ x: g.x, y: g.y, width: g.width, height: g.height,
+ offset: s.from - shift,
+ frameCount: s.frames,
+ }, "window"));
+ },
+ preview: (_slice, { render }) => ({ region: "chapter", geometry: chapterGeometry(render) }),
+ // A window of the cut: frame n is cut time `from` + n / fps.
+ frameKeys: { data: "chapter-data", omit: ["init", "cues", "from", "dur"], offset: "from" },
+});
diff --git a/umtool/report-to-video/modules/chart.mjs b/umtool/report-to-video/modules/chart.mjs
@@ -0,0 +1,36 @@
+// THE CHART BAND (module `chart`, region `chart`): the headcount band the
+// first report cuts drew in place of the footer -- the legacy chrome, before
+// the deck (`render.chromeEngine`). Not render-cached: it re-renders whole.
+// compose-chrome.mjs `chartBandHtml` writes the page.
+import path from "node:path";
+import { readFile } from "node:fs/promises";
+
+import { contentWidth } from "../render-cards.mjs";
+import { ledgerTotals } from "../ledger-totals.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "chart",
+ version: 1,
+ z: 5,
+ kind: "overlay-whole",
+ slot: "footer",
+ title: "Chart band (legacy)",
+ summary: "The headcount band of the first cuts, drawn in place of the footer.",
+ region: "chart",
+ cached: false,
+ async page(ctx) {
+ const { chartBandHtml } = await import("../compose-chrome.mjs");
+ const sched = ctx.schedule ?? JSON.parse(await readFile(path.join(ctx.base, "schedule.json"), "utf8"));
+ const fonts = await ctx.fonts({ regular: "regular", bold: "bold" }, { strict: false });
+ const totals = ledgerTotals(ctx.manifest.ledger);
+ return chartBandHtml(ctx.manifest, totals, sched, { fonts, ...(ctx.duration ? { duration: ctx.duration } : {}) });
+ },
+ regions(_schedule, { render, outDir }) {
+ const H = render.chart?.height ?? 200;
+ return [assertRegion({
+ name: "chart", frames: path.join(outDir, "chrome", "chart-frames"),
+ x: 0, y: render.height - H, width: contentWidth(render), height: H,
+ })];
+ },
+});
diff --git a/umtool/report-to-video/modules/claims.mjs b/umtool/report-to-video/modules/claims.mjs
@@ -0,0 +1,34 @@
+// THE CLAIM CHECKS (module `claims`, a part of the shell): a subject's
+// explicit claims drawn against the record on the deck's rail -- a count over
+// a window of dates, or a goalpost moved (report-to-video claims.mjs; deck.mjs
+// `claimsSchedule`, `claimsLayout`; chrome-claims.mjs). Reads the counter's
+// series (`counter.series`): a count claim's record is one series' stamps.
+import { DECK_CLAIM_KINDS, DECK_CLAIM_LIMITS, DECK_CLAIM_OPS, DECK_CLAIM_PERS } from "../claims.mjs";
+import { settingsOf } from "./settings.mjs";
+import { defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "claims",
+ version: 1,
+ z: 15,
+ kind: "part",
+ host: "shell",
+ slot: "inline",
+ title: "Claim checks",
+ summary: "His explicit claims against the record on the rail: a count over a window, a goalpost moved.",
+ configKey: "render.chrome.deck.claims",
+ defaults: { claims: [] },
+ validate: settingsOf("claims").validate,
+ resolve: (render) => (Array.isArray(render?.chrome?.deck?.claims) ? render.chrome.deck.claims : []),
+ deps: ["counter.series", "rail.layout"],
+ ui: [
+ { key: "claims", type: "claims", label: "Claim checks", kinds: DECK_CLAIM_KINDS, ops: DECK_CLAIM_OPS, pers: DECK_CLAIM_PERS, max: DECK_CLAIM_LIMITS.count },
+ ],
+ docs: {
+ heading: "Claim checks",
+ intro: "The full reference is [Claim checks on the rail](#claim-checks-on-the-rail). A count claim's `tally` names a counter series by id or label.",
+ rows: [
+ ["`deck.claims[]`", `at most ${DECK_CLAIM_LIMITS.count}, each a \`count\` or a \`goalpost\``, "`umtool look <p> deck.claims='[…]'` (`deck.claims=` none)"],
+ ],
+ },
+});
diff --git a/umtool/report-to-video/modules/config-loader.mjs b/umtool/report-to-video/modules/config-loader.mjs
@@ -0,0 +1,477 @@
+// MODULE CONFIG → MANIFEST (release 39): a project's `module-config.json`
+// -- the modules a video wants, written in the design's vocabulary
+// (MODULES-DESIGN.md) by whoever planned the cut -- as a merge patch over
+// its manifest, in the modules' homes. PURE: the config and the manifest
+// in, `{ patch, unmapped, notes }` out. `umtool modules apply` writes the
+// patch (as a take's `--patch`, or through the writers onto the project).
+//
+// config.preset -> preset (the look preset, presets.mjs)
+// modules.subtitle -> render.chrome.deck.subtitle
+// modules.qr -> render.chrome.deck.qr
+// modules.counter.series -> render.chrome.deck.counter.series (+ show, position, showAt)
+// modules.counter.marks -> each clip's marks (`claim` / `claims`, the series' id as verdict, `at`)
+// modules.stamp -> render.chrome.factcheck.stamp (`series.<id>.label` -> the series' stampLabel)
+// modules.rail -> render.chrome.deck.pip (spacing, pitch) + deck.markers (nodes and markers)
+// modules.chapter[] -> render.chrome.chapter.list
+// modules.pair[] -> render.chrome.pair.pairs
+// modules.status[] -> render.chrome.status.items
+// modules.intro -> render.intro
+// modules.finale -> render.chrome.deck.finale (+ `atClip`: the clips from it on take layout "finale")
+//
+// Everything that has no home is said in `unmapped`, one sentence each with
+// the config path -- nothing is dropped silently.
+import { VERDICTS } from "yt-dlp-transcript-common/lib/report/verdicts.mjs";
+
+import { mergePatch } from "../montage-styles.mjs";
+import { MARKER_LIMITS } from "./settings.mjs";
+import { CHAPTER_LIMITS, DATE_RE, PAIR_LIMITS, STATUS_LIMITS } from "./story-settings.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const clone = (v) => JSON.parse(JSON.stringify(v));
+const chars = (s) => [...String(s)].length;
+const fit = (s, max) => (chars(s) <= max ? String(s) : `${[...String(s)].slice(0, max - 1).join("").trimEnd()}…`);
+
+const SERIES_KEYS = ["id", "label", "color", "stampLabel", "tallyLabel", "showAt", "shape", "unit"];
+const STAMP_KEYS = ["show", "seconds", "position", "scale", "motion", "opacity"];
+const FINALE_KEYS = ["video", "motion", "totals", "statsTitle", "railLabels", "pips", "timelineShare", "claims"];
+const INTRO_KEYS = ["style", "ground", "mark", "seconds", "site", "swap", "url", "urlPlace", "brand", "suffix", "projectUrl"];
+
+/**
+ * @param {Record<string, any>} config a module-config.json
+ * @param {Record<string, any>} manifest the project's manifest (its timeline names the clips)
+ * @returns {{ patch: Record<string, any>, unmapped: string[], notes: string[] }}
+ */
+export function moduleConfigToManifest(config, manifest) {
+ if (!isObj(config)) throw new Error("a module config is an object { preset?, modules }");
+ if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error("the manifest has no timeline");
+ const mods = isObj(config.modules) ? config.modules : {};
+ const unmapped = [];
+ const notes = [];
+ const say = (where, why) => unmapped.push(`${where}: ${why}`);
+ const timeline = clone(manifest.timeline);
+ const ids = timeline.map((e) => e?.id);
+ const has = (id) => typeof id === "string" && ids.includes(id);
+ // The timeline's ids named in words, as whole words, in the order they stand.
+ const idsIn = (text) => {
+ const out = [];
+ for (const m of String(text).matchAll(/[A-Za-z0-9][A-Za-z0-9_.:-]*/g)) {
+ const t = m[0].replace(/[.:]+$/, "");
+ if (has(t) && !out.includes(t)) out.push(t);
+ }
+ return out;
+ };
+ const prev = (id) => {
+ const i = ids.indexOf(id);
+ return i > 0 ? ids[i - 1] : null;
+ };
+ const chrome = {};
+ const deck = {};
+ const render = {};
+ const patch = {};
+ let timelineChanged = false;
+
+ for (const k of Object.keys(config)) {
+ if (!["preset", "modules", "project", "intent", "notes", "note", "$comment", "draftEquivalent"].includes(k)) say(k, "not a module-config key");
+ }
+ if (typeof config.preset === "string" && config.preset) patch.preset = config.preset;
+
+ for (const [id, v] of Object.entries(mods)) {
+ const at = `modules.${id}`;
+ switch (id) {
+ case "shell": {
+ for (const k of Object.keys(v ?? {})) {
+ say(`${at}.${k}`, "the deck has no cut-wide title or subtitle (each clip's own is on screen); left out -- the manifest's title is unchanged");
+ }
+ break;
+ }
+ case "subtitle": {
+ const s = {};
+ for (const [k, x] of Object.entries(v ?? {})) {
+ if (k === "parts" || k === "dateFormat") s[k] = x;
+ else say(`${at}.${k}`, "not a subtitle setting (parts, dateFormat)");
+ }
+ if (Object.keys(s).length) deck.subtitle = s;
+ break;
+ }
+ case "qr": {
+ const q = {};
+ for (const [k, x] of Object.entries(v ?? {})) {
+ if (["links", "show", "size"].includes(k)) q[k] = x;
+ else say(`${at}.${k}`, "not a QR setting (links, show, size)");
+ }
+ if (Object.keys(q).length) deck.qr = q;
+ break;
+ }
+ case "counter":
+ counterOf(v, at, { deck, timeline, has, say, notes, mods, setChanged: () => { timelineChanged = true; } });
+ break;
+ case "stamp": {
+ const s = {};
+ for (const [k, x] of Object.entries(v ?? {})) {
+ if (STAMP_KEYS.includes(k)) s[k] = x;
+ else if (k !== "series") say(`${at}.${k}`, `not a stamp setting (${STAMP_KEYS.join(", ")})`);
+ }
+ if (Object.keys(s).length) chrome.factcheck = { ...(chrome.factcheck ?? {}), stamp: s };
+ if (isObj(v?.series)) {
+ for (const [sid, sv] of Object.entries(v.series)) {
+ const series = deck.counter?.series?.find((x) => x.id === sid);
+ if (!series) { say(`${at}.series.${sid}`, "no counter series has this id"); continue; }
+ if (typeof sv?.label === "string") series.stampLabel = sv.label;
+ for (const k of Object.keys(sv ?? {})) if (k !== "label") say(`${at}.series.${sid}.${k}`, "a stamp names a series' word only (label)");
+ }
+ }
+ break;
+ }
+ case "rail":
+ railOf(v, at, { deck, has, prev, say, notes });
+ break;
+ case "chapter": {
+ const list = [];
+ (Array.isArray(v) ? v : []).forEach((c, i) => {
+ const w = `${at}[${i}]`;
+ const clip = c?.atClip ?? c?.at ?? c?.clip;
+ if (!has(clip)) { say(w, `its clip ${clip ?? "(none)"} is not in the timeline: left out`); return; }
+ if (list.some((x) => x.at === clip)) { say(w, `a chapter already opens ${clip}: left out`); return; }
+ const ch = { at: clip, title: fit(c.title ?? "", CHAPTER_LIMITS.title) };
+ if (!c.title) { say(w, "has no title: left out"); return; }
+ if (chars(c.title) > CHAPTER_LIMITS.title) say(`${w}.title`, `shortened to ${CHAPTER_LIMITS.title} characters`);
+ if (c.subtitle) {
+ ch.subtitle = fit(c.subtitle, CHAPTER_LIMITS.subtitle);
+ if (chars(c.subtitle) > CHAPTER_LIMITS.subtitle) say(`${w}.subtitle`, `shortened to ${CHAPTER_LIMITS.subtitle} characters`);
+ }
+ if (c.date !== undefined) {
+ if (DATE_RE.test(String(c.date))) ch.date = c.date;
+ else say(`${w}.date`, `"${c.date}" is not YYYY, YYYY-MM or YYYY-MM-DD: left out`);
+ }
+ for (const k of Object.keys(c)) if (!["atClip", "at", "clip", "title", "subtitle", "date"].includes(k)) say(`${w}.${k}`, "not a chapter field");
+ list.push(ch);
+ });
+ if (list.length > CHAPTER_LIMITS.list) say(at, `${list.length} chapters: the first ${CHAPTER_LIMITS.list} kept`);
+ if (list.length) chrome.chapter = { list: list.slice(0, CHAPTER_LIMITS.list) };
+ break;
+ }
+ case "pair": {
+ const pairs = [];
+ (Array.isArray(v) ? v : []).forEach((p, i) => {
+ const w = `${at}[${i}]`;
+ const side = (s, name) => {
+ if (!isObj(s) || !has(s.clip)) { say(`${w}.${name}`, `its clip ${s?.clip ?? "(none)"} is not in the timeline`); return null; }
+ const out = { clip: s.clip };
+ if (s.date !== undefined) {
+ if (DATE_RE.test(String(s.date))) out.date = s.date;
+ else say(`${w}.${name}.date`, `"${s.date}" is not YYYY, YYYY-MM or YYYY-MM-DD: left out`);
+ }
+ for (const k of Object.keys(s)) if (!["clip", "date", "label"].includes(k)) say(`${w}.${name}.${k}`, "not a pair side field");
+ if (typeof s.label === "string") out.label = fit(s.label, PAIR_LIMITS.label);
+ return out;
+ };
+ const then = side(p?.then, "then");
+ const now = side(p?.now, "now");
+ if (!then || !now) { say(w, "left out (a pair needs both clips in the timeline)"); return; }
+ const pr = { then, now };
+ if (p.caption) {
+ pr.caption = fit(p.caption, PAIR_LIMITS.caption);
+ if (chars(p.caption) > PAIR_LIMITS.caption) say(`${w}.caption`, `shortened to ${PAIR_LIMITS.caption} characters`);
+ }
+ if (p.topic) {
+ pr.topic = fit(p.topic, PAIR_LIMITS.topic);
+ if (chars(p.topic) > PAIR_LIMITS.topic) say(`${w}.topic`, `shortened to ${PAIR_LIMITS.topic} characters`);
+ }
+ if (p.style !== undefined) {
+ const st = { split: "split", card: "then→now", "then→now": "then→now", "then-now": "then→now" }[p.style];
+ if (st) pr.style = st;
+ else say(`${w}.style`, `"${p.style}" is not split or then→now: the pair takes the module's`);
+ }
+ if (Array.isArray(p.also)) {
+ const also = p.also.filter((a) => {
+ if (!has(a?.clip)) { say(`${w}.also`, `${a?.clip} is not in the timeline: left out`); return false; }
+ return true;
+ }).map((a) => ({ clip: a.clip, side: a.side === "then" ? "then" : "now", ...(DATE_RE.test(String(a.date ?? "")) ? { date: a.date } : {}) }));
+ if (also.length) pr.also = also.slice(0, PAIR_LIMITS.also);
+ }
+ for (const k of Object.keys(p)) {
+ if (!["then", "now", "caption", "topic", "style", "also"].includes(k)) say(`${w}.${k}`, "not drawn (a pair draws its dates, topic and caption)");
+ }
+ pairs.push(pr);
+ });
+ if (pairs.length > PAIR_LIMITS.pairs) say(at, `${pairs.length} pairs: the first ${PAIR_LIMITS.pairs} kept`);
+ if (pairs.length) chrome.pair = { pairs: pairs.slice(0, PAIR_LIMITS.pairs) };
+ break;
+ }
+ case "status": {
+ const items = [];
+ (Array.isArray(v) ? v : []).forEach((it, i) => {
+ const w = `${at}[${i}]`;
+ if (!it?.item) { say(w, "has no item: left out"); return; }
+ const sideOf = (s, name) => {
+ if (s === undefined || s === null) return undefined;
+ if (typeof s === "string") {
+ if (chars(s) > STATUS_LIMITS.text) say(`${w}.${name}`, `shortened to ${STATUS_LIMITS.text} characters`);
+ return fit(s, STATUS_LIMITS.text);
+ }
+ if (!isObj(s)) { say(`${w}.${name}`, "not words or an object: left out"); return undefined; }
+ const out = {};
+ if (s.clip !== undefined) {
+ if (has(s.clip)) out.clip = s.clip;
+ else say(`${w}.${name}.clip`, `${s.clip} is not in the timeline: left out`);
+ }
+ if (s.date !== undefined) {
+ if (DATE_RE.test(String(s.date))) out.date = s.date;
+ else say(`${w}.${name}.date`, `"${s.date}" is not YYYY, YYYY-MM or YYYY-MM-DD: left out`);
+ }
+ const words = s.text ?? s.summary;
+ if (words) {
+ out.text = fit(words, STATUS_LIMITS.text);
+ if (chars(words) > STATUS_LIMITS.text) say(`${w}.${name}.${s.text ? "text" : "summary"}`, `shortened to ${STATUS_LIMITS.text} characters`);
+ }
+ for (const k of Object.keys(s)) if (!["clip", "date", "text", "summary"].includes(k)) say(`${w}.${name}.${k}`, "not drawn (a status side draws its date and words)");
+ return out;
+ };
+ const row = { item: fit(it.item, STATUS_LIMITS.item) };
+ if (chars(it.item) > STATUS_LIMITS.item) say(`${w}.item`, `shortened to ${STATUS_LIMITS.item} characters`);
+ const a = sideOf(it.announced, "announced");
+ const o = sideOf(it.outcome, "outcome");
+ if (a !== undefined) row.announced = a;
+ if (o !== undefined) row.outcome = o;
+ let ev = [];
+ if (Array.isArray(it.evidence)) {
+ ev = it.evidence.filter((c) => has(c));
+ for (const c of it.evidence) if (!has(c)) say(`${w}.evidence`, `${c} is not in the timeline: left out`);
+ }
+ // Words that name clips ("28 Oct x01: …", "2026-09-30 (n02)"): the
+ // timeline's ids read out of them, as the row's evidence.
+ const read = [];
+ for (const [k, words] of [["evidence", it.evidence], ["announced", it.announced], ["outcome", it.outcome]]) {
+ if (typeof words !== "string") continue;
+ const found = idsIn(words).filter((c) => !ev.includes(c) && !read.includes(c));
+ if (found.length) { read.push(...found); say(`${w}.${k}`, `words: the clips ${found.join(", ")} read out of them as evidence`); }
+ if (k === "evidence" && !found.length) say(`${w}.evidence`, "words naming no clip in the timeline: left out");
+ }
+ ev = [...ev, ...read];
+ if (ev.length) row.evidence = ev.slice(0, STATUS_LIMITS.evidence);
+ for (const k of Object.keys(it)) if (!["item", "announced", "outcome", "evidence"].includes(k)) say(`${w}.${k}`, "not drawn (a row draws its item, announcement and outcome)");
+ const named = [row.announced?.clip, row.outcome?.clip, ...(row.evidence ?? [])].filter(Boolean);
+ if (!named.length) { say(w, "names no clip in the timeline: left out (it would never be shown)"); return; }
+ items.push(row);
+ });
+ if (items.length > STATUS_LIMITS.items) say(at, `${items.length} items: the first ${STATUS_LIMITS.items} kept`);
+ if (items.length) chrome.status = { items: items.slice(0, STATUS_LIMITS.items) };
+ break;
+ }
+ case "intro": {
+ const intro = {};
+ for (const [k, x] of Object.entries(v ?? {})) {
+ if (INTRO_KEYS.includes(k)) intro[k] = x;
+ else say(`${at}.${k}`, "not an intro setting");
+ }
+ if (Object.keys(intro).length) render.intro = intro;
+ break;
+ }
+ case "finale":
+ finaleOf(v, at, { deck, timeline, has, say, mods, setChanged: () => { timelineChanged = true; } });
+ break;
+ case "feed": {
+ const posts = [...(Array.isArray(v?.posts) ? v.posts : []), ...(Array.isArray(v?.items) ? v.items : [])];
+ say(at, `${posts.length} post(s): a post joins the cut through \`umtool posts add <p> <channel>/<id> --attach <clip>\` (it needs its captured screenshot), not a module setting`);
+ break;
+ }
+ default:
+ say(at, "no module by this name");
+ }
+ }
+
+ if (Object.keys(deck).length) chrome.deck = deck;
+ if (Object.keys(chrome).length) {
+ // A counter's series replace the fact-check verdicts' relabels and the
+ // tally's settings: the two are not set together.
+ if (deck.counter && isObj(manifest.render?.chrome?.factcheck)) {
+ const f = manifest.render.chrome.factcheck;
+ if (f.verdicts !== undefined || f.tally !== undefined) {
+ chrome.factcheck = { ...(chrome.factcheck ?? {}), ...(f.verdicts !== undefined ? { verdicts: null } : {}), ...(f.tally !== undefined ? { tally: null } : {}) };
+ notes.push("render.chrome.factcheck.verdicts / tally removed: the counter's series replace them");
+ }
+ }
+ render.chrome = chrome;
+ }
+ if (Object.keys(render).length) patch.render = render;
+ if (timelineChanged) patch.timeline = timeline;
+ return { patch, unmapped, notes };
+}
+
+/** The counter: its series and settings, and each clip's marks naming a series. */
+function counterOf(v, at, { deck, timeline, has, say, notes, setChanged }) {
+ if (!isObj(v)) { say(at, "must be an object"); return; }
+ const counter = {};
+ const series = [];
+ (Array.isArray(v.series) ? v.series : []).forEach((s, i) => {
+ const w = `${at}.series[${i}]`;
+ if (!isObj(s) || typeof s.id !== "string") { say(w, "has no id: left out"); return; }
+ const out = {};
+ for (const [k, x] of Object.entries(s)) {
+ if (["label", "stampLabel", "tallyLabel", "unit"].includes(k) && typeof x === "string" && chars(x) > 24) {
+ out[k] = fit(x, 24);
+ say(`${w}.${k}`, "shortened to 24 characters");
+ } else if (SERIES_KEYS.includes(k)) out[k] = x;
+ else if (k === "optional") notes.push(`${w}.optional: a series is drawn whether or not it counts anything; kept as an ordinary series`);
+ else if (k !== "$comment") say(`${w}.${k}`, "not a series field");
+ }
+ series.push(out);
+ });
+ if (series.length) counter.series = series;
+ for (const k of ["show", "position", "showAt"]) if (v[k] !== undefined) counter[k] = v[k];
+ for (const k of Object.keys(v)) {
+ if (["series", "marks", "show", "position", "showAt"].includes(k)) continue;
+ if (k === "notCounted") notes.push(`${at}.notCounted: ${v.notCounted.length} clip(s) the plan does not count -- informational, nothing drawn`);
+ else if (k === "legacyVerdicts" || k === "draft1Mapping") notes.push(`${at}.${k}: read to move the draft's verdict marks onto the series`);
+ else say(`${at}.${k}`, "not a counter setting");
+ }
+ if (Object.keys(counter).length) deck.counter = counter;
+ // The marks: each clip's marks, as the config says, its series by id.
+ const legacy = { ...(isObj(v.legacyVerdicts) ? v.legacyVerdicts : {}), ...(isObj(v.draft1Mapping) ? v.draft1Mapping : {}) };
+ const toSeries = Object.fromEntries(Object.entries(legacy).map(([sid, verdict]) => [verdict, sid]));
+ const ids = new Set(series.map((s) => s.id));
+ const byClip = new Map();
+ (Array.isArray(v.marks) ? v.marks : []).forEach((m, i) => {
+ const w = `${at}.marks[${i}]`;
+ const clip = m?.clip;
+ if (!has(clip)) { say(w, `its clip ${clip ?? "(none)"} is not in the timeline: left out`); return; }
+ const sid = m.counter ?? m.verdict;
+ if (!ids.has(sid)) { say(w, `${sid} is not one of the counter's series: left out`); return; }
+ if (!byClip.has(clip)) byClip.set(clip, []);
+ byClip.get(clip).push({ series: sid, ...(typeof m.at === "number" ? { at: m.at } : {}) });
+ for (const k of Object.keys(m)) if (!["clip", "counter", "verdict", "at", "note"].includes(k)) say(`${w}.${k}`, "not a mark field (clip, counter, at)");
+ });
+ if (!series.length) return;
+ for (const e of timeline) {
+ if (!isObj(e)) continue;
+ const had = Array.isArray(e.claims) ? e.claims : e.claim ? [e.claim] : [];
+ const want = byClip.get(e.id);
+ let next;
+ if (want) {
+ next = want.map((m, k) => {
+ // The knobs a mark already had at that second (hold, stamp, label, …) stay.
+ const old = had.find((h) => h.at === m.at) ?? (want.length === 1 ? had[0] : null) ?? {};
+ const { id: _i, verdict: _v, at: _a, ...knobs } = old;
+ // A second mark at the same second counts but does not stamp (two
+ // stamps at once would overlap; the build refuses that).
+ const twin = want.slice(0, k).some((x) => x.at === m.at);
+ return {
+ id: want.length === 1 ? e.id : `${e.id}-${m.series}`, verdict: m.series, ...(m.at !== undefined ? { at: m.at } : {}), ...knobs,
+ ...(twin ? { stamp: false } : {}),
+ };
+ });
+ if (want.some((m, k) => want.slice(0, k).some((x) => x.at === m.at))) {
+ notes.push(`${at}.marks (${e.id}): marks at the same second -- the later ones count without a stamp of their own`);
+ }
+ } else if (had.length) {
+ // A mark the config does not list: onto its series by the draft's mapping, else off.
+ next = had.flatMap((h) => {
+ if (ids.has(h.verdict)) return [h];
+ const sid = toSeries[h.verdict];
+ if (sid) return [{ ...h, verdict: sid }];
+ say(`timeline ${e.id}`, `its mark ${h.id} (${h.verdict}) names no series and the config lists no mark for the clip: removed`);
+ return [];
+ });
+ } else continue;
+ const same = JSON.stringify(next) === JSON.stringify(had);
+ if (same) continue;
+ delete e.claim;
+ delete e.claims;
+ if (next.length === 1) e.claim = next[0];
+ else if (next.length > 1) e.claims = next;
+ setChanged();
+ }
+ if (VERDICTS.some((x) => ids.has(x))) notes.push(`${at}: a series named after a verdict takes that verdict's defaults`);
+}
+
+/** The rail: spacing and pitch, and its nodes and markers as the deck's markers. */
+function railOf(v, at, { deck, has, prev, say, notes }) {
+ if (!isObj(v)) { say(at, "must be an object"); return; }
+ const pip = {};
+ if (v.spacing !== undefined) {
+ if (["even", "time", "pitch"].includes(v.spacing)) pip.spacing = v.spacing;
+ else say(`${at}.spacing`, `"${v.spacing}" is not even, time or pitch`);
+ }
+ if (v.pitch !== undefined) pip.pitch = v.pitch;
+ if (v.color !== undefined) pip.color = v.color;
+ if (Object.keys(pip).length) deck.pip = pip;
+ const markers = [];
+ const add = (after, label, w) => {
+ if (!after) { say(w, "falls before the first clip: the deck's markers stand between two clips -- left out"); return; }
+ if (!has(after)) { say(w, `its clip ${after} is not in the timeline: left out`); return; }
+ if (markers.some((m) => m.after === after)) { say(w, `a marker already stands after ${after}: left out`); return; }
+ if (typeof label !== "string" || !label.trim()) { say(w, "has no label: left out"); return; }
+ const one = label.replace(/\s+/g, " ").trim();
+ if (chars(one) > MARKER_LIMITS.label) say(`${w}.label`, `shortened to ${MARKER_LIMITS.label} characters`);
+ markers.push({ after, label: fit(one, MARKER_LIMITS.label), w });
+ };
+ (Array.isArray(v.markers) ? v.markers : []).forEach((m, i) => add(m?.after, m?.label, `${at}.markers[${i}]`));
+ const dated = [];
+ (Array.isArray(v.nodes) ? v.nodes : []).forEach((n, i) => {
+ const w = `${at}.nodes[${i}]`;
+ if (!isObj(n)) { say(w, "not a node"); return; }
+ if (n.after) add(n.after, n.label, w);
+ else if (n.atClip ?? n.clip ?? n.fromClip) {
+ const clip = n.atClip ?? n.clip ?? n.fromClip;
+ if (!has(clip)) { say(w, `its clip ${clip} is not in the timeline: left out`); return; }
+ add(prev(clip), n.label, w);
+ } else if (Array.isArray(n.clips)) {
+ say(w, "a node over a list of clips (a year) has no one place on the deck's track: left out");
+ return;
+ } else { say(w, "names no clip: left out"); return; }
+ if (n.date) dated.push(w);
+ for (const k of Object.keys(n)) if (!["after", "atClip", "clip", "fromClip", "label", "date", "year", "clips"].includes(k)) say(`${w}.${k}`, "not drawn");
+ });
+ if (dated.length) notes.push(`${at}.nodes: ${dated.length} node date(s) not drawn -- a marker carries its label only`);
+ if (v.by !== undefined) say(`${at}.by`, `the rail is not grouped by ${v.by}; the pips are one per clip`);
+ for (const k of Object.keys(v)) if (!["spacing", "pitch", "color", "markers", "nodes", "by"].includes(k)) say(`${at}.${k}`, "not a rail setting");
+ if (markers.length > MARKER_LIMITS.count) {
+ for (const m of markers.slice(MARKER_LIMITS.count)) say(m.w, `past the deck's ${MARKER_LIMITS.count} markers: left out`);
+ }
+ if (markers.length) deck.markers = markers.slice(0, MARKER_LIMITS.count).map(({ w: _w, ...m }) => m);
+}
+
+/** The finale: its settings, its stats (a counter total counted from the marks), its first clip. */
+function finaleOf(v, at, { deck, timeline, has, say, mods, setChanged }) {
+ if (!isObj(v)) { say(at, "must be an object"); return; }
+ const f = {};
+ for (const k of FINALE_KEYS) if (v[k] !== undefined) f[k] = v[k];
+ const marks = Array.isArray(mods.counter?.marks) ? mods.counter.marks.filter((m) => has(m?.clip)) : [];
+ const total = (sid) => marks.filter((m) => (m.counter ?? m.verdict) === sid).length;
+ if (Array.isArray(v.stats)) {
+ f.stats = v.stats.map((s, i) => {
+ const w = `${at}.stats[${i}]`;
+ const out = { label: typeof s.label === "string" && chars(s.label) > 32 ? fit(s.label, 32) : s.label };
+ if (out.label !== s.label) say(`${w}.label`, "shortened to 32 characters");
+ if (typeof s.note === "string" && chars(s.note) > 60) say(`${w}.note`, "shortened to 60 characters");
+ let value = s.value;
+ const ref = typeof value === "string" ? /^counter\.totals\.(.+)$/.exec(value) : null;
+ if (ref) value = String(total(ref[1]));
+ else if (value === undefined && s.counter) value = String(total(s.counter));
+ if (ref || (s.value === undefined && s.counter)) say(`${w}.value`, `a counter total, counted from the config's marks in this timeline: ${value} (fixed at apply time)`);
+ out.value = typeof value === "number" ? String(value) : value;
+ if (s.note) out.note = fit(s.note, 60);
+ for (const k of Object.keys(s)) if (!["label", "value", "note", "counter", "color"].includes(k)) say(`${w}.${k}`, "not a stat field");
+ if (s.color) out.color = s.color;
+ return out;
+ });
+ }
+ for (const k of Object.keys(v)) {
+ if (FINALE_KEYS.includes(k) || ["stats", "deps", "atClip"].includes(k)) continue;
+ say(`${at}.${k}`, "not a finale setting");
+ }
+ if (Object.keys(f).length) deck.finale = f;
+ if (v.atClip !== undefined) {
+ if (!has(v.atClip)) { say(`${at}.atClip`, `${v.atClip} is not in the timeline: no finale run`); return; }
+ const from = timeline.findIndex((e) => e?.id === v.atClip);
+ for (const e of timeline.slice(from)) {
+ if (isObj(e) && e.type === "clip" && e.layout !== "finale") { e.layout = "finale"; setChanged(); }
+ }
+ }
+}
+
+/** The patch over a manifest: what `umtool modules apply` writes (preset → manifest → patch). */
+export function applyModuleConfig(manifest, config) {
+ const { patch, unmapped, notes } = moduleConfigToManifest(config, manifest);
+ return { manifest: mergePatch(manifest, patch), patch, unmapped, notes };
+}
diff --git a/umtool/report-to-video/modules/config-loader.test.mjs b/umtool/report-to-video/modules/config-loader.test.mjs
@@ -0,0 +1,175 @@
+// module-config.json → the manifest's homes (config-loader.mjs), the look
+// presets (presets.mjs) and the generic panel's model (panel.mjs).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { moduleConfigToManifest } from "./config-loader.mjs";
+import { panelState, panelWrite, setPath, uiBase } from "./panel.mjs";
+import { moduleById } from "./index.mjs";
+import { listPresets, loadPreset, presetFromManifest, presetManifest, resolvePresetLayers } from "../presets.mjs";
+import { selectVariant } from "../build-video.mjs";
+import { validateChrome } from "../deck.mjs";
+import { validateClaims } from "../factcheck.mjs";
+import { storyClipErrors } from "./story-settings.mjs";
+
+const clip = (id, extra = {}) => ({ id, type: "clip", channel: "c", video: "v", start: 0, end: 10, ...extra });
+const manifest = () => ({
+ slug: "t", title: "T",
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#ff0000" } },
+ timeline: [clip("a", { claim: { id: "a", verdict: "PARTLY", at: 5 } }), clip("b"), clip("c"), clip("d")],
+});
+
+const CONFIG = {
+ preset: "plain-deck",
+ intent: "a test",
+ modules: {
+ shell: { title: "Ignored" },
+ subtitle: { parts: ["channel", "date"] },
+ qr: { links: "original" },
+ counter: {
+ series: [{ id: "pitches", label: "Pitches", color: "#e3b23c", showAt: "first", unit: "pitch", $comment: "x" }, { id: "asks", label: "A very long series label indeed", optional: true }],
+ marks: [{ clip: "b", counter: "pitches", at: 3 }, { clip: "b", counter: "asks", at: 3 }, { clip: "zz", counter: "pitches", at: 1 }],
+ legacyVerdicts: { pitches: "PARTLY" },
+ },
+ stamp: { seconds: 3, series: { pitches: { label: "Pitch" } } },
+ rail: { spacing: "pitch", nodes: [{ atClip: "a", label: "first" }, { atClip: "d", label: "A label longer than twenty-four", date: "2020" }, { year: "2021", clips: ["a"], label: "2021" }], markers: [{ after: "b", label: "B" }] },
+ chapter: [{ atClip: "a", title: "One", subtitle: "the first" }, { atClip: "nope", title: "Gone" }],
+ pair: [{ topic: "T", then: { clip: "a", date: "2012-09-29" }, now: { clip: "d", date: "2026" }, caption: "c", style: "card", source: "x" }],
+ status: [
+ { item: "Thing", announced: { clip: "a", date: "2019-06-01", citeUrl: "https://x" }, outcome: "no follow-up found", evidence: ["a", "c"] },
+ { item: "Words", announced: "2026-09-30 (b)", outcome: "consistent", evidence: "c: said" },
+ ],
+ feed: { posts: [{ post: "x/1", attachTo: "a" }] },
+ intro: { style: "boot-dark", site: "auto" },
+ finale: { deps: ["counter"], atClip: "d", statsTitle: "Totals", stats: [{ label: "Pitches", value: "counter.totals.pitches" }, { counter: "asks", label: "Asks" }] },
+ wobble: {},
+ },
+};
+
+test("a module config maps into the manifest's homes; what has none is listed", () => {
+ const m = manifest();
+ const { patch, unmapped, notes } = moduleConfigToManifest(CONFIG, m);
+ assert.equal(patch.preset, "plain-deck");
+ const c = patch.render.chrome;
+ assert.deepEqual(c.deck.subtitle, { parts: ["channel", "date"] });
+ assert.deepEqual(c.deck.qr, { links: "original" });
+ assert.equal(c.deck.counter.series[0].stampLabel, "Pitch");
+ assert.ok(!("$comment" in c.deck.counter.series[0]));
+ assert.equal([...c.deck.counter.series[1].label].length, 24);
+ assert.deepEqual(c.deck.pip, { spacing: "pitch" });
+ assert.deepEqual(c.deck.markers.map((x) => x.after), ["b", "c"]);
+ assert.deepEqual(c.chapter.list, [{ at: "a", title: "One", subtitle: "the first" }]);
+ assert.equal(c.pair.pairs[0].style, "then→now");
+ assert.deepEqual(c.status.items[1].evidence, ["c", "b"]);
+ assert.equal(patch.render.intro.style, "boot-dark");
+ assert.deepEqual(c.deck.finale.stats.map((s) => s.value), ["1", "1"]);
+ // The marks: b counts both series, the second without a stamp; a's draft mark onto its series.
+ const t = Object.fromEntries(patch.timeline.map((e) => [e.id, e]));
+ assert.deepEqual(t.b.claims.map((x) => [x.verdict, x.stamp]), [["pitches", undefined], ["asks", false]]);
+ assert.equal(t.a.claim.verdict, "pitches");
+ assert.equal(t.d.layout, "finale");
+ for (const want of ["modules.shell.title", "modules.counter.marks[2]", "modules.rail.nodes[0]", "modules.rail.nodes[1].label", "modules.rail.nodes[2]",
+ "modules.chapter[1]", "modules.pair[0].source", "modules.status[0].announced.citeUrl", "modules.feed", "modules.wobble"]) {
+ assert.ok(unmapped.some((u) => u.startsWith(want)), `${want} in ${unmapped.join("\n")}`);
+ }
+ assert.ok(notes.some((n) => n.includes("optional")));
+});
+
+test("the mapped manifest, over its preset, builds", () => {
+ const m = manifest();
+ const { patch } = moduleConfigToManifest(CONFIG, m);
+ const seen = resolvePresetLayers(m, [patch]);
+ assert.equal(seen.presetApplied, "plain-deck");
+ const { chrome, ...rest } = seen.render;
+ assert.deepEqual(validateChrome(chrome, rest), []);
+ assert.deepEqual(storyClipErrors(seen), []);
+ assert.deepEqual(validateClaims(seen), []);
+});
+
+test("presets: the three built-ins load and build; merge order preset → manifest → style → patch", () => {
+ const names = listPresets().map((p) => p.name);
+ for (const n of ["huck-deck", "plain-deck", "archive-catalog"]) {
+ assert.ok(names.includes(n), n);
+ const p = loadPreset(n);
+ const { chrome, ...rest } = p.render;
+ assert.deepEqual(validateChrome(chrome, rest), [], n);
+ }
+ const base = { preset: "plain-deck", render: { transition: 0.7, palette: { accent: "#00ff00" } }, timeline: [] };
+ const style = { render: { transition: 0.2 } };
+ const take = { render: { palette: { accent: null } } };
+ const out = resolvePresetLayers(base, [style, take]);
+ assert.equal(out.render.transition, 0.2, "the style over the manifest over the preset");
+ assert.equal(out.render.palette.bg, loadPreset("plain-deck").render.palette.bg, "the preset's palette under");
+ assert.equal(out.render.palette.accent, undefined, "a null in the patch removes the key, the preset's too");
+ assert.equal(out.preset, undefined);
+ assert.equal(out.presetApplied, "plain-deck");
+ // A patch may name the preset.
+ assert.equal(resolvePresetLayers({ render: {}, timeline: [] }, [{ preset: "huck-deck" }]).render.chrome.layout, "deck");
+ // Laid once: a resolved manifest is not laid again.
+ assert.equal(presetManifest(out), out);
+ // Every reader of a cut (selectVariant) sees it.
+ assert.equal(selectVariant({ preset: "archive-catalog", render: { fps: 30 }, timeline: [] }).render.chrome.pair.style, "split");
+ assert.throws(() => resolvePresetLayers({ preset: "no-such", timeline: [] }), /no preset "no-such"/);
+});
+
+test("presetFromManifest keeps the look and leaves the content out", () => {
+ const m = {
+ preset: "huck-deck",
+ render: {
+ crf: 19, timelineExtra: 1,
+ chrome: {
+ engine: "hyperframes", layout: "deck",
+ deck: { claims: [{}], markers: [{ after: "a", label: "x" }], counter: { series: [] }, finale: { video: "side", stats: [{ label: "x", value: "1" }] } },
+ factcheck: { verdicts: {}, stamp: { seconds: 2 } },
+ pair: { style: "split", pairs: [] }, status: { items: [] }, threads: { list: [] },
+ },
+ intro: { style: "boot-dark", site: "jeralyzer" },
+ },
+ };
+ const { preset, dropped } = presetFromManifest(m, { name: "mine" });
+ assert.equal(preset.render.crf, 19);
+ assert.equal(preset.render.chrome.deck.finale.video, "side");
+ assert.equal(preset.render.chrome.deck.claims, undefined);
+ assert.equal(preset.render.chrome.pair.style, "split");
+ assert.equal(preset.render.chrome.status, undefined);
+ assert.equal(preset.render.intro.site, undefined);
+ assert.equal(preset.render.palette.bg, loadPreset("huck-deck").render.palette.bg, "the preset it stood on, under it");
+ for (const d of ["render.timelineExtra", "render.chrome.deck.claims", "render.chrome.deck.markers", "render.chrome.threads", "render.intro.site"]) assert.ok(dropped.includes(d), d);
+});
+
+test("presets come from UMTOOL_PRESETS_DIR when it is set", () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "presets-"));
+ writeFileSync(path.join(dir, "only.json"), JSON.stringify({ name: "only", render: { crf: 30 } }));
+ assert.deepEqual(listPresets({ dir }).map((p) => p.name), ["only"]);
+ assert.equal(loadPreset("only", { dir }).render.crf, 30);
+ writeFileSync(path.join(dir, "bad.json"), JSON.stringify({ name: "other", render: {} }));
+ assert.match(listPresets({ dir }).find((p) => p.name === "bad").error, /not its file's name/);
+});
+
+test("the panel: a module's fields from its descriptor, a save as the writers take it", () => {
+ assert.equal(uiBase(moduleById("rail")), "render.chrome.deck");
+ assert.equal(uiBase(moduleById("pair")), "render.chrome.pair");
+ const m = { ...manifest(), preset: "huck-deck", render: { ...manifest().render, chrome: { pair: { style: "split" } } } };
+ const seen = resolvePresetLayers(m);
+ const rows = panelState(m, seen, {});
+ const pair = rows.find((r) => r.id === "pair");
+ assert.equal(pair.enabled, true);
+ assert.deepEqual(pair.fields, { style: "split" });
+ const finale = rows.find((r) => r.id === "finale");
+ assert.equal(finale.effective.video, "side", "the preset's value, as the build reads it");
+ assert.deepEqual(finale.fields, {}, "none of it the manifest's own");
+ const intro = rows.find((r) => r.id === "intro");
+ assert.equal(intro.enabled, false);
+ // Saves.
+ assert.deepEqual(panelWrite(m, "pair", { fields: { position: "top", "labels.then": "2012" } }).chrome.pair, { style: "split", position: "top", labels: { then: "2012" } });
+ assert.equal(panelWrite(m, "pair", { enabled: false }).chrome, null, "a chrome left empty is removed");
+ assert.deepEqual(panelWrite(m, "chapter", { enabled: true }).chrome.chapter, { list: [] });
+ assert.deepEqual(panelWrite(m, "intro", { enabled: true, fields: { mark: "chime" } }).render, { intro: { style: "boot-dark", site: "auto", mark: "chime" } });
+ assert.deepEqual(panelWrite(m, "rail", { fields: { "pip.spacing": "pitch" } }).chrome.deck, { pip: { spacing: "pitch" } });
+ assert.throws(() => panelWrite(m, "pair", { fields: { wobble: 1 } }), /not one of its fields/);
+ assert.throws(() => panelWrite(m, "qr", { enabled: false }), /not switched on and off/);
+ assert.deepEqual(setPath({ a: { b: 1 } }, "a.b", null), {});
+});
diff --git a/umtool/report-to-video/modules/contract.mjs b/umtool/report-to-video/modules/contract.mjs
@@ -0,0 +1,183 @@
+// THE MODULE CONTRACT (release 39, the video-modules toolkit).
+//
+// Every piece of a report video's chrome -- the deck's shell, its subtitle,
+// QR, rail and counter, the stamps, the posts, the finale, the intro, the
+// teaser, the effects -- is a MODULE: one file under modules/ that exports
+// `defineModule({...})` and is registered in modules/index.mjs. A module says
+// what it is (`kind`, `slot`, `z`), where its settings live in the manifest
+// (`configKey`, `defaults`), how they are checked (`validate`) and filled
+// (`resolve`), what it reads of other modules (`deps`, by NAME -- never by
+// reaching into their slice), how it is drawn (`page` for a HyperFrames page,
+// `render` for an ffmpeg/IM one), where its frames land (`region`), what its
+// render cache keys on (`frameKeys`: the static part and the frame events),
+// and how umtool shows it (`ui`, `preview`, `docs`).
+//
+// A PART (`host` set) is drawn inside its host module's page -- the subtitle,
+// the QR, the rail and the counter are all inside the deck's one page, so
+// their frames are the shell's. It owns its settings, validation, defaults,
+// docs and UI; its pixels are the host's region.
+//
+// Pure: no fs, no ffmpeg, no network. The registry and every module file are
+// imported by the build, the composer and umtool alike.
+
+/** What a module is: how its pixels reach the cut. */
+export const MODULE_KINDS = Object.freeze([
+ // A page over the whole cut (or a window of it), laid by its region at frame 1.
+ "overlay-whole",
+ // Pages laid at their own second: short sequences over a stretch of the cut.
+ "overlay-window",
+ // A segment inserted into the timeline (the intro, a teaser).
+ "segment",
+ // A filter on the footage itself (a clip's blur).
+ "input",
+ // After the master (a trailer, the variant ladder).
+ "post",
+ // Drawn inside another module's page (`host`): settings, checks and docs of its own.
+ "part",
+]);
+
+/**
+ * The layout slots a module may ask for (layout.mjs `slotRect`): the deck's
+ * band at the foot of the frame, the posts column, the stamp's box in the
+ * footage, the footage box itself, the side panel beside it, a popup column
+ * over the footage, the whole frame, or `inline` (a part, in its host's slot).
+ */
+export const MODULE_SLOTS = Object.freeze(["footer", "column", "popup", "stamp", "panel", "footage", "side", "full", "inline"]);
+
+/** How a region is laid over the cut: a whole-cut sequence from frame 1, or a window at its own second. */
+export const REGION_PLACEMENTS = Object.freeze(["whole", "window"]);
+
+const ID_RE = /^[a-z][a-z0-9-]{0,31}$/;
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const isFn = (v) => typeof v === "function";
+
+/** The keys a module definition may carry, each with what it must be. */
+const SPEC = Object.freeze({
+ id: "an id: lower-case letters, digits and dashes",
+ version: "a whole number from 1: bumped when what it draws changes",
+ z: "a number: its stack order, lowest first",
+ kind: `one of ${MODULE_KINDS.join(", ")}`,
+ slot: `one of ${MODULE_SLOTS.join(", ")}`,
+ title: "words: what the module is called in umtool and the docs",
+ summary: "a sentence: what it draws",
+ host: "a part's host module id",
+ region: "the name its frames and project are filed under (chrome/<region>-frames)",
+ configKey: "a dotted manifest path its settings live at (render.chrome.deck.qr)",
+ configKeys: "more dotted paths it owns beside configKey",
+ defaults: "an object: every setting and its default",
+ validate: "a function (config, ctx) => string[]",
+ resolve: "a function (render) => its settings with the defaults filled",
+ deps: "the named outputs of other modules it reads (counter.totals)",
+ provides: "the named outputs it gives (counter.totals)",
+ on: "a function (render, manifest?) => boolean: is it drawn at all",
+ schedule: "a function (doc, ctx) => its slice of the deck schedule",
+ page: "an async function (ctx) => the HTML of its page",
+ render: "an async function (ctx) => what it renders without a page",
+ regions: "a function (schedule, ctx) => its overlay regions",
+ composes: "a function (schedule, ctx) => the compose requests a build makes for it",
+ frameKeys: "its frame-key model: { data, omit, offset?, eases?, events?, items? }",
+ ui: "a field descriptor list for umtool's generic panel",
+ preview: "a function (slice, ctx) => a single-layer preview request",
+ docs: "its knobs.md section: { heading, intro?, rows: [[knob, range, terminal]], after? }",
+ workers: "\"wide\" or \"narrow\": how many renderer workers its page takes",
+ noun: "how a message names its sequence (\"the stamps'\")",
+ cached: "false for a page the render cache does not key (the legacy chart band)",
+ check: "a function (schedule, render) => the sentence why this schedule cannot draw it, or null",
+ window: "a function (schedule, { window, segment, fps, total }) => the window it composes",
+ names: "a function ({ preview, window, entry, suffix }) => { project, stem }",
+ entry: "a function (manifest, segment) => the timeline entry a segment module draws",
+ seconds: "a function (entry, transition, fps) => how long a segment module's page is",
+});
+
+/**
+ * One module, checked and frozen. Throws a sentence naming the key on a
+ * definition no registry should hold: a module that mis-declares itself is a
+ * bug in the build, not a manifest problem.
+ *
+ * @template T
+ * @param {T & { id: string, kind: string }} def
+ * @returns {Readonly<T>}
+ */
+export function defineModule(def) {
+ if (!isObj(def)) throw new Error("defineModule: a module is an object");
+ const where = `module ${def.id ?? "(no id)"}`;
+ for (const k of Object.keys(def)) {
+ if (!(k in SPEC)) throw new Error(`${where}: ${k} is not a module key (${Object.keys(SPEC).join(", ")})`);
+ }
+ if (typeof def.id !== "string" || !ID_RE.test(def.id)) throw new Error(`${where}: id must be ${SPEC.id}`);
+ if (!(Number.isInteger(def.version) && def.version >= 1)) throw new Error(`${where}: version must be ${SPEC.version}`);
+ if (typeof def.z !== "number" || !Number.isFinite(def.z)) throw new Error(`${where}: z must be ${SPEC.z}`);
+ if (!MODULE_KINDS.includes(def.kind)) throw new Error(`${where}: kind must be ${SPEC.kind}`);
+ if (!MODULE_SLOTS.includes(def.slot)) throw new Error(`${where}: slot must be ${SPEC.slot}`);
+ if (typeof def.title !== "string" || !def.title.trim()) throw new Error(`${where}: title must be ${SPEC.title}`);
+ if (def.kind === "part") {
+ if (typeof def.host !== "string" || !ID_RE.test(def.host)) throw new Error(`${where}: a part names its host`);
+ if (def.slot !== "inline") throw new Error(`${where}: a part's slot is inline (it draws in its host's)`);
+ if (def.region !== undefined || def.page !== undefined) throw new Error(`${where}: a part has no region or page of its own`);
+ } else if (def.host !== undefined) {
+ throw new Error(`${where}: only a part has a host`);
+ }
+ if ((def.kind === "overlay-whole" || def.kind === "overlay-window") && typeof def.region !== "string") {
+ throw new Error(`${where}: an overlay names its region`);
+ }
+ for (const k of ["validate", "resolve", "on", "schedule", "page", "render", "regions", "composes", "preview", "check", "window", "names", "entry", "seconds"]) {
+ if (def[k] !== undefined && !isFn(def[k])) throw new Error(`${where}: ${k} must be ${SPEC[k]}`);
+ }
+ if (def.configKey !== undefined && !/^render(\.[A-Za-z]+)+$/.test(def.configKey)) {
+ throw new Error(`${where}: configKey must be ${SPEC.configKey}`);
+ }
+ if (def.configKeys !== undefined && !(Array.isArray(def.configKeys) && def.configKeys.every((k) => /^[a-z]+(\.[A-Za-z]+)*$/.test(k)))) {
+ throw new Error(`${where}: configKeys must be ${SPEC.configKeys}`);
+ }
+ for (const k of ["deps", "provides"]) {
+ if (def[k] !== undefined && !(Array.isArray(def[k]) && def[k].every((n) => /^[a-z][a-z0-9-]*\.[a-zA-Z]+$/.test(n)))) {
+ throw new Error(`${where}: ${k} must be ${SPEC[k]}`);
+ }
+ }
+ for (const p of def.provides ?? []) {
+ if (!p.startsWith(`${def.id}.`)) throw new Error(`${where}: it provides ${p}, which is not its own (${def.id}.<name>)`);
+ }
+ if (def.defaults !== undefined && !isObj(def.defaults)) throw new Error(`${where}: defaults must be ${SPEC.defaults}`);
+ if (def.frameKeys !== undefined && def.frameKeys !== null) {
+ const f = def.frameKeys;
+ if (!isObj(f) || typeof f.data !== "string" || !Array.isArray(f.omit)) throw new Error(`${where}: frameKeys must be ${SPEC.frameKeys}`);
+ }
+ if (def.ui !== undefined && !Array.isArray(def.ui)) throw new Error(`${where}: ui must be ${SPEC.ui}`);
+ if (def.docs !== undefined && !(isObj(def.docs) && typeof def.docs.heading === "string")) throw new Error(`${where}: docs must be ${SPEC.docs}`);
+ if (def.workers !== undefined && !["wide", "narrow"].includes(def.workers)) throw new Error(`${where}: workers must be ${SPEC.workers}`);
+ return Object.freeze({ ...def });
+}
+
+// ---------------------------------------------------------------------------
+// Regions: where a module's frames land in the cut.
+// ---------------------------------------------------------------------------
+
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+
+/**
+ * An overlay region, checked: `{ name, frames, x, y, width, height }`, and
+ * for a window `offset` (the cut second its frame 1 lands on) and
+ * `frameCount`; a chunk of the final encode reads a whole-cut sequence from
+ * `startNumber`. What chromeOverlayChain and the chunked encode take. Returns
+ * the region; throws a sentence on a malformed one.
+ *
+ * @template {{ name: string, frames: string, x: number, y: number, width: number, height: number,
+ * offset?: number, frameCount?: number, startNumber?: number }} R
+ * @param {R} r
+ * @param {"whole" | "window" | null} [placement]
+ * @returns {R}
+ */
+export function assertRegion(r, placement = null) {
+ const where = `region ${r?.name ?? "(no name)"}`;
+ if (!isObj(r) || typeof r.name !== "string" || !r.name) throw new Error(`${where}: a region has a name`);
+ if (typeof r.frames !== "string" || !r.frames) throw new Error(`${where}: a region names its frames' directory`);
+ for (const k of ["x", "y", "width", "height"]) if (!num(r[k])) throw new Error(`${where}: ${k} must be a number`);
+ if (placement === "window") {
+ if (!num(r.offset)) throw new Error(`${where}: a window region has an offset (the cut second its frame 1 lands on)`);
+ if (!(Number.isInteger(r.frameCount) && r.frameCount > 0)) throw new Error(`${where}: a window region has a frame count`);
+ }
+ if (r.startNumber !== undefined && !(Number.isInteger(r.startNumber) && r.startNumber >= 1)) {
+ throw new Error(`${where}: startNumber must be a frame number from 1`);
+ }
+ return r;
+}
diff --git a/umtool/report-to-video/modules/counter.mjs b/umtool/report-to-video/modules/counter.mjs
@@ -0,0 +1,50 @@
+// THE COUNTER (module `counter`, a part of the shell): the deck's running
+// tally of named series, a cell per series the cut counts, each stepping as
+// a mark's stamp lands (report-to-video counter.mjs; factcheck.mjs
+// `tallyCues`; chrome-deck.mjs draws the cells). The finale reads its totals
+// (`counter.totals`); the claim checks name its series.
+import { COUNTER_POSITIONS, COUNTER_SHAPES, COUNTER_SHOW_AT, resolveCounter } from "../counter.mjs";
+import { settingsOf } from "./settings.mjs";
+import { defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "counter",
+ version: 1,
+ z: 14,
+ kind: "part",
+ host: "shell",
+ slot: "inline",
+ title: "Counter",
+ summary: "A running tally of named series in the deck, each cell stepping as a mark's stamp lands.",
+ configKey: "render.chrome.deck.counter",
+ defaults: { series: [], show: true, position: "right", showAt: "always" },
+ validate: settingsOf("counter").validate,
+ resolve: resolveCounter,
+ provides: ["counter.totals", "counter.series"],
+ ui: [
+ { key: "series", type: "series", label: "Series", item: [
+ { key: "id", type: "text", label: "Id" },
+ { key: "label", type: "text", label: "Label" },
+ { key: "color", type: "color", label: "Colour" },
+ { key: "stampLabel", type: "text", label: "Stamp word" },
+ { key: "tallyLabel", type: "text", label: "Cell word" },
+ { key: "showAt", type: "enum", options: COUNTER_SHOW_AT, label: "Show" },
+ { key: "shape", type: "enum", options: COUNTER_SHAPES, label: "Shape" },
+ { key: "unit", type: "text", label: "Unit" },
+ ] },
+ { key: "show", type: "boolean", label: "Show the cells", default: true },
+ { key: "position", type: "enum", options: COUNTER_POSITIONS, label: "Side", default: "right" },
+ { key: "showAt", type: "enum", options: COUNTER_SHOW_AT, label: "Cells appear", default: "always" },
+ ],
+ docs: {
+ heading: "Counter",
+ intro: "The deck's tally as named series (`render.chrome.deck.counter`). A clip's mark names the series it counts (`claim.verdict`, or its alias `claim.counter`); a deck claim's `tally` names one by id or label. Without `counter` the series are the fact-check verdicts with `factcheck.verdicts`' relabels and `factcheck.tally`'s settings, as ever; `umtool migrate <p>` writes those as a `counter` (the render is the same) and the two are not set together.",
+ rows: [
+ ["`deck.counter.series[]`", "1–8 `{id, label, color?, stampLabel?, tallyLabel?, showAt?, shape?, unit?}` -- an `id` a letter then letters, digits, `_` `-`; a verdict's id (`CORROBORATED` …) takes its default label, colour and shape; `label` ≤ 24 and fitting the cell, as the verdicts' are", "`umtool look <p> deck.counter='{\"series\":[{\"id\":\"seizures\",\"label\":\"Seizures\",\"color\":\"#e5534b\",\"stampLabel\":\"Seizure\"}]}'`"],
+ ["`deck.counter.series[].shape`", "`circle` `diamond` `square` `triangle` `ring` · default by place (a verdict's own)", "same"],
+ ["`deck.counter.series[].unit`", "≤ 24 · the noun a count claim's number reads (default its label, lower-cased)", "same"],
+ ["`deck.counter.show`, `.position`, `.showAt`", "bool · `right` `left` · `always` `first` (a series' own `showAt` wins) · defaults `true`, `right`, `always`", "same"],
+ ["a mark's series", "`claim.verdict` (or `claim.counter`): one of the series' ids", "`umtool set <p> <clip> mark.add=seizures@190.2`"],
+ ],
+ },
+});
diff --git a/umtool/report-to-video/modules/counter.test.mjs b/umtool/report-to-video/modules/counter.test.mjs
@@ -0,0 +1,113 @@
+// The counter module: named series in place of the fact-check verdicts
+// (report-to-video counter.mjs, modules/counter.mjs).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { counterOrder, resolveCounter, validateCounter, VERDICT_SHAPES } from "../counter.mjs";
+import { claimOf, marksOf, normalizeClaim, resolveFactcheck, tallyFinals, tallyOf, tallyShowAt, validateClaims } from "../factcheck.mjs";
+import { estimateSchedule, validateChrome } from "../deck.mjs";
+import { deckHtml } from "../chrome-deck.mjs";
+import counter from "./counter.mjs";
+import { moduleProblems } from "./index.mjs";
+
+const PALETTE = { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" };
+const render = (deck = {}, factcheck = undefined) => ({
+ width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE,
+ chrome: { engine: "hyperframes", layout: "deck", deck, ...(factcheck ? { factcheck } : {}) },
+});
+const SERIES = [
+ { id: "seizures", label: "Seizures", color: "#e5534b", stampLabel: "Seizure" },
+ { id: "pitches", label: "Pitches", color: "#e3b23c", showAt: "first" },
+];
+
+test("without a counter the series are the verdicts, as the tally always counted them", () => {
+ const c = resolveCounter(render({}, { verdicts: { CORROBORATED: { label: "Seizures" } }, tally: { showAt: { PARTLY: "first" } } }));
+ assert.equal(c.custom, false);
+ assert.deepEqual(c.order, ["CORROBORATED", "PARTLY", "CONTRADICTED", "NOT_FOUND", "UNTESTABLE"]);
+ assert.equal(c.byId.CORROBORATED.label, "Seizures");
+ assert.deepEqual(c.shapes, VERDICT_SHAPES);
+ assert.equal(c.showAt.PARTLY, "first");
+ assert.equal(c.showAt.CORROBORATED, "always");
+ assert.deepEqual(resolveFactcheck(render()).verdicts, resolveCounter(render()).byId);
+});
+
+test("named series: their order, labels, colours, shapes by place, showAt and unit", () => {
+ const r = render({ counter: { series: [...SERIES, { id: "NOT_FOUND" }, { id: "x", label: "X", unit: "things" }], position: "left" } });
+ const c = resolveCounter(r);
+ assert.equal(c.custom, true);
+ assert.deepEqual(c.order, ["seizures", "pitches", "NOT_FOUND", "x"]);
+ assert.deepEqual(c.byId.seizures, { label: "Seizures", color: "#e5534b", stampLabel: "Seizure" });
+ assert.deepEqual(c.byId.NOT_FOUND, { label: "Not found", color: "#8b93a7" });
+ assert.equal(c.shapes.seizures, "circle");
+ assert.equal(c.shapes.pitches, "diamond");
+ assert.equal(c.shapes.NOT_FOUND, "triangle", "a verdict keeps its own shape");
+ assert.equal(c.series[3].unit, "things");
+ assert.equal(c.showAt.pitches, "first");
+ assert.deepEqual(tallyShowAt(r), c.showAt);
+ assert.equal(resolveFactcheck(r).tally.position, "left");
+ assert.deepEqual(counterOrder(r), c.order);
+});
+
+test("validateCounter: every shape refused in a sentence; one home for the series", () => {
+ assert.deepEqual(validateCounter(undefined), []);
+ assert.deepEqual(validateCounter({ series: SERIES }), []);
+ assert.match(validateCounter({ series: [] })[0], /at least one series/);
+ assert.match(validateCounter({ series: [{ id: "9x", label: "A" }] })[0], /id must be a letter/);
+ assert.match(validateCounter({ series: [{ id: "a", label: "A" }, { id: "a", label: "B" }] })[0], /listed twice/);
+ assert.match(validateCounter({ series: [{ id: "custom" }] })[0], /label is needed/);
+ assert.match(validateCounter({ series: [{ id: "a", label: "A", color: "red" }] })[0], /color must be a hex/);
+ assert.match(validateCounter({ series: [{ id: "a", label: "A", shape: "star" }] })[0], /shape must be one of/);
+ assert.match(validateCounter({ series: SERIES, colour: 1 })[0], /colour is not a counter setting/);
+ assert.match(validateCounter({ series: SERIES }, { factcheck: { verdicts: {} } })[0], /replaces render.chrome.factcheck.verdicts/);
+ // Through the deck's validator: the cell's fit, as the verdicts' labels are held.
+ const long = validateChrome(render({ counter: { series: [{ id: "a", label: "Extraordinarilylong" }] } }).chrome, render());
+ assert.match(long.join("\n"), /no run of its last words fits: set render.chrome.deck.counter.series\[0\].tallyLabel/);
+ assert.deepEqual(validateChrome(render({ counter: { series: SERIES } }).chrome, render()), []);
+});
+
+test("a mark names a series by id: `verdict`, or its alias `counter`", () => {
+ const series = ["seizures", "pitches"];
+ assert.deepEqual(normalizeClaim({ id: "k1", counter: "seizures" }, { series }), { id: "k1", verdict: "seizures" });
+ assert.deepEqual(normalizeClaim({ id: "k1", verdict: "pitches", at: 3 }, { series }), { id: "k1", verdict: "pitches", at: 3 });
+ assert.throws(() => normalizeClaim({ id: "k1", counter: "seizures", verdict: "pitches" }, { series }), /one setting/);
+ assert.throws(() => normalizeClaim({ id: "k1", verdict: "CORROBORATED" }, { series }), /must be one of seizures, pitches/);
+ // Without the series named, the verdicts (as ever).
+ assert.throws(() => normalizeClaim({ id: "k1", verdict: "seizures" }), /must be one of CORROBORATED/);
+ assert.deepEqual(marksOf({ type: "clip", claim: { id: "k", counter: "pitches" } }, series), [{ id: "k", verdict: "pitches" }]);
+ assert.equal(claimOf({ type: "clip", claim: { id: "k", counter: "pitches" } }), null, "not a verdict, not a mark without the series");
+});
+
+test("a cut counting named series: the schedule, the tally's cells, the deck's page", () => {
+ const r = render({ counter: { series: SERIES }, pip: { color: "verdict" } });
+ const manifest = {
+ provenance: {}, posts: [],
+ render: r,
+ timeline: [
+ { type: "clip", id: "a", video: "v1", start: 0, end: 10, claim: { id: "s1", counter: "seizures" } },
+ { type: "clip", id: "b", video: "v2", start: 0, end: 10, claims: [{ id: "p1", verdict: "pitches" }, { id: "s2", verdict: "seizures", count: 2 }] },
+ { type: "clip", id: "c", video: "v3", start: 0, end: 10 },
+ ],
+ };
+ assert.deepEqual(validateClaims(manifest), []);
+ assert.deepEqual(moduleProblems(manifest), {});
+ const s = estimateSchedule(manifest);
+ assert.deepEqual(s.factcheck.stamps.map((x) => [x.claim, x.verdict]), [["s1", "seizures"], ["p1", "pitches"], ["s2", "seizures"]]);
+ assert.deepEqual(tallyOf(s, r), ["seizures", "pitches"]);
+ assert.deepEqual(tallyFinals(s.factcheck.stamps, counterOrder(r)), { seizures: 3, pitches: 1 });
+ const html = deckHtml(s, r, {});
+ assert.match(html, /data-verdict="seizures"/);
+ assert.match(html, /<div class="tlabel">Pitches<\/div>/);
+ assert.match(html, /data-shape="diamond"/);
+ // A series the counter does not have is refused by name.
+ const bad = { ...manifest, timeline: [{ type: "clip", id: "a", video: "v", start: 0, end: 5, claim: { id: "x", verdict: "CORROBORATED" } }] };
+ assert.match(validateClaims(bad)[0], /claim\.verdict must be one of seizures, pitches/);
+});
+
+test("the counter module: its home, its validator, its docs", () => {
+ assert.equal(counter.kind, "part");
+ assert.equal(counter.host, "shell");
+ assert.equal(counter.configKey, "render.chrome.deck.counter");
+ assert.deepEqual(counter.provides, ["counter.totals", "counter.series"]);
+ assert.match(counter.docs.rows[0][0], /deck\.counter\.series/);
+ assert.ok(counter.ui.some((f) => f.key === "series"));
+});
diff --git a/umtool/report-to-video/modules/design.mjs b/umtool/report-to-video/modules/design.mjs
@@ -0,0 +1,25 @@
+// THE DESIGN UNITS every chrome module lays out in (release 39, the
+// video-modules toolkit). A module's own pixel constants are in these units --
+// a 1920×1080 frame -- and the layout engine (layout.mjs) scales them to the
+// output size. A constant another module needs lives HERE, once: no module
+// owns a pixel constant for another (the tally's 124 px cell used to be
+// written in deck.mjs and again in factcheck.mjs).
+//
+// No imports. deck.mjs, factcheck.mjs and the modules all read this file, and
+// it must evaluate before any of them whatever imports first (a cycle through
+// a module that computes a constant from another's at load is a TDZ error).
+
+/** The design frame: every design-unit constant is a pixel of a frame this size. */
+export const DESIGN = Object.freeze({ width: 1920, height: 1080 });
+
+/** The deck's side padding: the rail's ends, the text's left, the QR's right. */
+export const DECK_PAD_X = 48;
+
+/**
+ * The counter's (the fact-check tally's) cell: one per series the cut counts,
+ * `cell` wide with `gap` between, its label in the cell less `labelPad` a side.
+ */
+export const COUNTER_CELL = Object.freeze({ cell: 124, gap: 10, labelPad: 6 });
+
+/** A design-unit length at this render's width (what the scaled geometry multiplies by). */
+export const designScale = (render) => (render?.width ?? DESIGN.width) / DESIGN.width;
diff --git a/umtool/report-to-video/modules/docs.mjs b/umtool/report-to-video/modules/docs.mjs
@@ -0,0 +1,97 @@
+// THE MODULES' DOCS (release 39): umtool/docs/knobs.md's "Modules" section,
+// generated from each module's own `docs` -- so a module's knobs are written
+// once, beside its validator, and the page cannot drift from them.
+//
+// node umtool/report-to-video/modules/docs.mjs rewrite the section
+// node umtool/report-to-video/modules/docs.mjs --check exit 1 when it is stale
+//
+// The section stands between the two markers below; everything else in
+// knobs.md is hand-written and left as it is.
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+import { MODULES } from "./index.mjs";
+
+export const DOCS_BEGIN = "<!-- modules:begin (generated by report-to-video/modules/docs.mjs -- edit the modules, not this) -->";
+export const DOCS_END = "<!-- modules:end -->";
+
+/** knobs.md, beside this checkout's umtool. */
+export const KNOBS_MD = fileURLToPath(new URL("../../docs/knobs.md", import.meta.url));
+
+const KIND_WORDS = {
+ "overlay-whole": "a page over the whole cut",
+ "overlay-window": "pages at their own seconds",
+ segment: "a segment cut into the timeline",
+ input: "a filter on the footage",
+ post: "after the master",
+ part: "drawn in the deck's page",
+};
+
+const cell = (s) => String(s).replace(/\|/g, "\\|").replace(/\n/g, " ");
+
+/** The order the section reads in: the deck and its parts, then by z. */
+function ordered() {
+ const shell = MODULES.find((m) => m.id === "shell");
+ const parts = MODULES.filter((m) => m.host === "shell");
+ const rest = MODULES.filter((m) => m !== shell && m.host !== "shell" && m.docs);
+ return [shell, ...parts, ...rest].filter((m) => m?.docs);
+}
+
+/** The section's markdown, markers included. */
+export function modulesMarkdown() {
+ const out = [
+ DOCS_BEGIN,
+ "## Modules",
+ "",
+ "A report video's chrome is a set of MODULES (`umtool/report-to-video/modules/`), each with its home in the manifest, its",
+ "defaults, its validator and its frame-key rules; the build, the composer and umtool loop over the one registry",
+ "(`modules/index.mjs`). The deck's parts are drawn in its one page; every other module is its own layer, segment or",
+ "filter. A knob absent is its default, and a module whose knobs are all absent draws what it always drew.",
+ "",
+ "| Module | What it is | Its home |",
+ "|---|---|---|",
+ ...ordered().map((m) => `| [${cell(m.docs.heading)}](#${anchor(m.docs.heading)}) \`${m.id}\` | ${cell(m.summary ?? "")} ${KIND_WORDS[m.kind] ? `(${KIND_WORDS[m.kind]})` : ""} | ${m.configKey ? `\`${m.configKey}\`` : "--"} |`),
+ "",
+ ];
+ for (const m of ordered()) {
+ out.push(`### ${m.docs.heading}`, "");
+ if (m.docs.intro) out.push(m.docs.intro, "");
+ if (m.docs.rows?.length) {
+ out.push("| Knob | Range · default | From a terminal |", "|---|---|---|");
+ for (const [knob, range, terminal] of m.docs.rows) out.push(`| ${knob} | ${range} | ${terminal} |`);
+ out.push("");
+ }
+ if (m.docs.after) out.push(m.docs.after, "");
+ }
+ out.push(DOCS_END);
+ return out.join("\n");
+}
+
+/** A heading's GitHub anchor. */
+function anchor(h) {
+ return h.toLowerCase().replace(/[^a-z0-9 -]/g, "").trim().replace(/ /g, "-");
+}
+
+/** knobs.md with its Modules section replaced (or appended, the first time). */
+export function withModulesSection(text) {
+ const section = modulesMarkdown();
+ const a = text.indexOf(DOCS_BEGIN);
+ const b = text.indexOf(DOCS_END);
+ if (a >= 0 && b > a) return text.slice(0, a) + section + text.slice(b + DOCS_END.length);
+ return `${text.replace(/\s*$/, "")}\n\n${section}\n`;
+}
+
+if (import.meta.url === `file://${process.argv[1]}`) {
+ const text = readFileSync(KNOBS_MD, "utf8");
+ const next = withModulesSection(text);
+ if (process.argv.includes("--check")) {
+ if (next !== text) {
+ console.error("umtool/docs/knobs.md's Modules section is stale: run node umtool/report-to-video/modules/docs.mjs");
+ process.exit(1);
+ }
+ console.log("knobs.md's Modules section is current");
+ } else if (next !== text) {
+ writeFileSync(KNOBS_MD, next);
+ console.log("knobs.md: the Modules section rewritten");
+ } else console.log("knobs.md: the Modules section is current");
+}
diff --git a/umtool/report-to-video/modules/docs.test.mjs b/umtool/report-to-video/modules/docs.test.mjs
@@ -0,0 +1,26 @@
+// knobs.md's Modules section is generated from the modules' own docs
+// (modules/docs.mjs): it is current, and every module that has knobs has one.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+
+import { DOCS_BEGIN, DOCS_END, KNOBS_MD, modulesMarkdown, withModulesSection } from "./docs.mjs";
+import { MODULES } from "./index.mjs";
+
+test("knobs.md's Modules section is current (node umtool/report-to-video/modules/docs.mjs rewrites it)", () => {
+ const text = readFileSync(KNOBS_MD, "utf8");
+ assert.ok(text.includes(DOCS_BEGIN) && text.includes(DOCS_END), "the markers are in knobs.md");
+ assert.equal(withModulesSection(text), text);
+});
+
+test("every module with a home in the manifest documents it, and the section names each", () => {
+ const md = modulesMarkdown();
+ for (const m of MODULES) {
+ if (!m.configKey) continue;
+ assert.ok(m.docs, `${m.id} has docs`);
+ assert.ok(md.includes(`### ${m.docs.heading}`), `${m.id}'s section`);
+ assert.ok(md.includes(`\`${m.id}\``), `${m.id} in the table`);
+ }
+ // Idempotent: the section replaces itself.
+ assert.equal(withModulesSection(withModulesSection("# x\n")), withModulesSection("# x\n"));
+});
diff --git a/umtool/report-to-video/modules/feed.mjs b/umtool/report-to-video/modules/feed.mjs
@@ -0,0 +1,77 @@
+// THE FEED (module `feed`, region `feed`): the posts in a column of their own
+// beside the footage for the whole cut, each ticking in as its clip starts
+// (`render.chrome.deck.posts.layout: "feed"`). chrome-feed.mjs writes the
+// page; deck.mjs `feedGeometry` lays the column and the footage beside it.
+import path from "node:path";
+
+import { feedGeometry, resolveDeck } from "../deck.mjs";
+import { feedHtml } from "../chrome-feed.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { DECK_DEFAULTS, POST_LAYOUTS, POST_LINKS, settingsOf } from "./settings.mjs";
+
+export default defineModule({
+ id: "feed",
+ version: 1,
+ z: 20,
+ kind: "overlay-whole",
+ slot: "column",
+ title: "Posts feed",
+ summary: "The cut's posts in a column beside the footage, each ticking in as its clip starts.",
+ configKey: "render.chrome.deck.posts",
+ defaults: DECK_DEFAULTS.posts,
+ // `deck.posts` is the popup posts' and the feed's alike: one validator.
+ validate: (_value, ctx) => settingsOf("popup-posts").validate(ctx.deck ?? {}, ctx),
+ ui: [
+ { key: "show", type: "boolean", label: "Show the posts", default: true },
+ { key: "layout", type: "enum", options: POST_LAYOUTS, label: "Layout", default: "popup" },
+ { key: "links", type: "enum", options: POST_LINKS, label: "QR links to", default: "archive" },
+ { key: "qr", type: "boolean", label: "QR on each card", default: true },
+ { key: "width", type: "number", min: 320, max: 900, label: "Width (px)", default: DECK_DEFAULTS.posts.width },
+ { key: "inset", type: "number", min: 0, max: 80, label: "Inset (px)", default: DECK_DEFAULTS.posts.inset },
+ { key: "maxLines", type: "number", min: 2, max: 14, label: "Lines of words", default: DECK_DEFAULTS.posts.maxLines },
+ { key: "qrSize", type: "number", min: 80, max: 200, label: "QR size", default: DECK_DEFAULTS.posts.qrSize },
+ { key: "shotMaxHeight", type: "number", min: 120, max: 1080, label: "Screenshot height cap", default: null },
+ ],
+ docs: {
+ heading: "Posts feed",
+ intro: "`deck.posts.layout: \"feed\"` with posts to draw: a column for the whole cut, each post ticking in as its clip starts; no hold, no footage move. Shares `deck.posts` with the popup posts.",
+ rows: [
+ ["`deck.posts.layout`", "`popup` · `feed` · default `popup`", "`umtool look <p> deck.posts='{\"layout\":\"feed\"}'`"],
+ ["`deck.posts.width`, `.inset`", "320–900 · 0–80 px · default 600, 24 (the column's width; the footage keeps the inset clear)", "same"],
+ ["`deck.posts.links`, `.qr`", "`archive` · `original`; bool · default `archive`, `true`", "same"],
+ ],
+ },
+ region: "feed",
+ workers: "wide",
+ noun: "the feed's",
+ on: (schedule) => schedule?.layout === "feed",
+ check: (schedule) => (schedule.layout !== "feed"
+ ? "the feed region needs a feed's schedule (layout \"feed\": posts.layout \"feed\" and posts to draw)"
+ : null),
+ async page(ctx) {
+ // The posts feed: the deck's faces and QR maker, one page for the whole cut.
+ const { render, schedule } = ctx;
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ const posts = schedule.posts ?? [];
+ // `posts.qr: false`: no codes are made, and the page draws none.
+ const byUrl = resolveDeck(render).posts.qr === false
+ ? new Map()
+ : await ctx.qrs(posts.map((p) => p.qrUrl), resolveDeck(render).posts.qrSize);
+ const qrSrcs = {};
+ for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl);
+ // A thread shot (a reply over the post it answers) is drawn whole: the
+ // feed gives it the column rather than the room beside the card under it.
+ const threads = new Set();
+ const shotSrcs = await ctx.shots(posts, "shot", threads);
+ // Its items -- each card -- go to the frame keys.
+ const items = [];
+ const html = feedHtml(schedule, render, { fonts, qrSrcs, shotSrcs, threadShots: [...threads], from: ctx.from, duration: ctx.duration, items });
+ return { html, items };
+ },
+ regions(_schedule, { render, outDir, frames = null }) {
+ return [assertRegion({ name: "feed", frames: frames ?? path.join(outDir, "chrome", "feed-frames"), ...feedGeometry(render).column })];
+ },
+ // The feed plans its cues IN the page, from the heights its cards measure
+ // (chrome-feed.mjs): keyed by its EVENTS instead (frame-keys.mjs feedFrameKeys).
+ frameKeys: { data: "feed-data", omit: ["window", "total", "ids", "posts", "visibility"], events: true },
+});
diff --git a/umtool/report-to-video/modules/finale.mjs b/umtool/report-to-video/modules/finale.mjs
@@ -0,0 +1,98 @@
+// THE FINALE (module `finale`, region `finale`): the cut's last clips with the
+// rail redrawn large across the top, the counter's final totals under it,
+// stats cards beside them and the clip in a smaller box (a clip's `layout:
+// "finale"`, `render.chrome.deck.finale`, finale.mjs). One full-frame window
+// over the run, laid LAST: its ground covers every region under it while it
+// is up. chrome-finale.mjs writes the page.
+import path from "node:path";
+
+import { resolveDeck, snapWindow } from "../deck.mjs";
+import { finaleHtml, finaleLayout } from "../chrome-finale.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { FINALE_DEFAULTS, resolveFinale } from "../finale.mjs";
+import { settingsOf } from "./settings.mjs";
+
+export default defineModule({
+ id: "finale",
+ version: 1,
+ z: 90,
+ kind: "overlay-window",
+ slot: "full",
+ title: "Finale",
+ summary: "The cut's last clips under the rail redrawn large, the final totals and stats cards.",
+ configKey: "render.chrome.deck.finale",
+ defaults: FINALE_DEFAULTS,
+ validate: settingsOf("finale").validate,
+ resolve: resolveFinale,
+ deps: ["counter.totals", "rail.layout"],
+ provides: ["finale.window"],
+ ui: [
+ { key: "video", type: "enum", options: ["side", "corner", "hidden"], label: "The clip", default: "side" },
+ { key: "motion", type: "enum", options: ["grow", "cut"], label: "Motion", default: "grow" },
+ { key: "totals", type: "boolean", label: "Totals", default: true },
+ { key: "statsTitle", type: "text", label: "Stats title" },
+ { key: "stats", type: "stats", label: "Stats cards", max: 8 },
+ { key: "railLabels", type: "enum", options: ["all", "nodes"], label: "Rail labels", default: "all" },
+ { key: "pips", type: "boolean", label: "The finale's clips on the rail", default: true },
+ { key: "timelineShare", type: "number", min: 0.38, max: 0.6, step: 0.01, label: "Timeline share (auto when unset)" },
+ { key: "claims", type: "enum", options: ["rotate", "all"], label: "Claim checks", default: "rotate" },
+ ],
+ docs: {
+ heading: "Finale",
+ intro: "The full reference is [The finale](#the-finale-the-timeline-in-primary-view). It reads the counter's totals (`counter.totals`) and the rail's layout (`rail.layout`); the counter reads its window (`finale.window`): a mark that would stamp inside it counts as it opens.",
+ rows: [
+ ["`deck.finale`", "`{video, motion, totals, stats, statsTitle, railLabels, pips, timelineShare, claims}`", "`umtool look <p> deck.finale='{…}'`"],
+ ["a clip's `layout`", "`finale` on one run of clips at the end", "`umtool set <p> <clip> layout=finale`"],
+ ],
+ },
+ region: "finale",
+ workers: "narrow",
+ noun: "the finale's",
+ on: (schedule) => !!schedule?.finale,
+ check: (schedule) => (!schedule.finale
+ ? "the finale region needs a schedule with a finale (a clip with layout \"finale\", render.chrome.deck.finale)"
+ : null),
+ // The finale's window: the schedule's, snapped outward to the frame grid.
+ window: (schedule, { fps, total }) => snapWindow({ segment: "finale", from: schedule.finale.from, to: schedule.finale.to }, { fps, total }),
+ names: ({ preview }) => ({ project: `finale${preview ? "-preview" : ""}`, stem: "finale" }),
+ async page(ctx) {
+ // The finale (chrome-finale.mjs): the deck's faces and QR maker, one page
+ // for its window.
+ const { render, schedule } = ctx;
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ const L = finaleLayout(schedule, render);
+ const qrSrcs = {};
+ if (resolveDeck(render).qr.show) {
+ const byUrl = await ctx.qrs(L.captions.map((c) => c.qrUrl), L.geo.qr.size);
+ for (const c of L.captions) if (c.qrUrl) qrSrcs[c.id] = byUrl.get(c.qrUrl);
+ }
+ return finaleHtml(schedule, render, ctx.window, { fonts, qrSrcs });
+ },
+ /**
+ * The finale's page as an overlay region: the whole frame, its window
+ * snapped to the frame grid and laid at its own second like a posts window
+ * -- `offset` in the BASE's clock (the cut's, or a preview's that starts
+ * `shift` in). `clip` (`{at, dur}`) keeps it only when it intersects.
+ */
+ regions(schedule, { render, outDir, shift = 0, clip = null }) {
+ const f = schedule?.finale;
+ if (!f) return [];
+ const fps = Number(schedule.fps ?? render.fps);
+ const s = snapWindow({ segment: "finale", from: f.from, to: f.to }, { fps, total: schedule.total });
+ if (clip && !(s.from < clip.at + clip.dur && s.to > clip.at)) return [];
+ return [assertRegion({
+ name: "finale",
+ frames: path.join(outDir, "chrome", "finale-frames"),
+ x: 0, y: 0, width: render.width ?? 1920, height: render.height ?? 1080,
+ offset: s.from - shift,
+ frameCount: s.frames,
+ window: s,
+ }, "window")];
+ },
+ // The finale is a window of the cut by design: its frame n is cut time
+ // `from` + n / fps, and its one ease of its own is the page's smoothstep.
+ frameKeys: {
+ data: "finale-data", omit: ["init", "cues", "from", "dur"], offset: "from",
+ eases: { smoothstep: { page: "const EASES = { smoothstep: (p) => p * p * (3 - 2 * p) };", fn: (p) => p * p * (3 - 2 * p) } },
+ },
+});
diff --git a/umtool/report-to-video/modules/flips.mjs b/umtool/report-to-video/modules/flips.mjs
@@ -0,0 +1,43 @@
+// THE FLIPS PANEL (module `flips`, region `flips`): then-and-now pairs in the
+// side panel -- the thread rail's region, one or the other
+// (`render.chrome.flips`, flips.mjs). chrome-flips.mjs writes the page.
+import path from "node:path";
+
+import { flipsHtml } from "../chrome-flips.mjs";
+import { defineModule } from "./contract.mjs";
+import { settingsOf } from "./settings.mjs";
+import { sideRegion } from "./threads.mjs";
+
+export default defineModule({
+ id: "flips",
+ version: 1,
+ z: 80,
+ kind: "overlay-whole",
+ slot: "side",
+ title: "Flips",
+ summary: "Pairs of what was said then and now, in the side panel.",
+ validate: settingsOf("flips").validate,
+ docs: {
+ heading: "Flips",
+ intro: "Then-and-now pairs in the side panel (`render.chrome.flips`, flips.mjs); the thread rail and the flips share the panel: one or the other.",
+ rows: [
+ ["`render.chrome.flips`", "see flips.mjs", "manifest"],
+ ],
+ },
+ region: "flips",
+ workers: "narrow",
+ noun: "the flips panel's",
+ configKey: "render.chrome.flips",
+ on: (schedule) => !!schedule?.flips?.pairs?.length,
+ check: (schedule) => (!schedule.flips?.pairs?.length ? "the flips region needs a schedule with flip pairs (render.chrome.flips)" : null),
+ async page(ctx) {
+ // The flips panel (chrome-flips.mjs): the deck's faces, no QR.
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ return flipsHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration });
+ },
+ regions(_schedule, { render, outDir, frames = null }) {
+ return [sideRegion(render, frames ?? path.join(outDir, "chrome", "flips-frames"), "flips")];
+ },
+ // A cue interpreter like the deck's: keyed per frame (frame-keys.mjs).
+ frameKeys: { data: "flips-data", omit: ["init", "cues", "window", "total", "ids"] },
+});
diff --git a/umtool/report-to-video/modules/fx.mjs b/umtool/report-to-video/modules/fx.mjs
@@ -0,0 +1,53 @@
+// THE EFFECTS (module `fx`, region `fx`): overlays drawn over the footage box
+// -- receipts, a zoom, a scrubber, captions (`render.chrome.fx`, fx.mjs).
+// chrome-fx.mjs writes the page.
+import path from "node:path";
+
+import { fxGeometry } from "../deck.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { settingsOf } from "./settings.mjs";
+
+export default defineModule({
+ id: "fx",
+ version: 1,
+ z: 60,
+ kind: "overlay-whole",
+ slot: "footage",
+ title: "Effects",
+ summary: "Overlays on the picture: receipts, a zoom, a scrubber, captions.",
+ validate: settingsOf("fx").validate,
+ docs: {
+ heading: "Effects",
+ intro: "Overlays on the picture -- receipts, a zoom, the scrubber, a kinetic quote, punch-ins, whip cuts -- (`render.chrome.fx`, fx.mjs); `umtool takes effects <p>` lists the presets.",
+ rows: [
+ ["`render.chrome.fx.<effect>`", "scrubber · receipts · zoom · kineticQuote · redact · odometer · punchIn · thenNow · whip · glitch", "a take: `umtool take <p> --effect <name>`"],
+ ],
+ },
+ region: "fx",
+ workers: "wide",
+ noun: "the effects'",
+ configKey: "render.chrome.fx",
+ on: (schedule) => !!schedule?.fx,
+ check: (schedule) => (!schedule.fx ? "the fx region needs a schedule with an effect on (render.chrome.fx)" : null),
+ async page(ctx) {
+ // The effects (chrome-fx.mjs): the deck's faces, a mono, the screenshots
+ // the receipts and the zoom show, and the scrubber's thumbnails.
+ // A page module reached by a dynamic import, as the teaser's: it carries
+ // its mono as an asset URL (docs/quirks.md).
+ const { fxHtml, FX_MONO_FILE } = await import("../chrome-fx.mjs");
+ const { schedule, render } = ctx;
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ fonts.mono = await ctx.asset(FX_MONO_FILE, "FxMono.ttf");
+ const shots = await ctx.fxShots(schedule.fx);
+ const thumbs = schedule.fx.scrubber?.thumbs ? await ctx.fxThumbs(schedule) : {};
+ return fxHtml(schedule, render, { fonts, assets: { shots, thumbs }, from: ctx.from, duration: ctx.duration });
+ },
+ regions(schedule, { render, outDir, frames = null }) {
+ return [assertRegion({
+ name: "fx", frames: frames ?? path.join(outDir, "chrome", "fx-frames"),
+ ...fxGeometry(render, { feed: schedule.layout === "feed" }),
+ })];
+ },
+ // A cue interpreter like the deck's: keyed per frame (frame-keys.mjs).
+ frameKeys: { data: "fx-data", omit: ["init", "cues", "window", "total"] },
+});
diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs
@@ -0,0 +1,151 @@
+// THE MODULE REGISTRY (release 39): every chrome module, once. The build's
+// overlay pass, the composer, the validator and umtool's panels all loop over
+// this list -- a module joins the video by being registered here, and by
+// nothing else. The order a list is in is its `z`: a region with a higher z
+// is laid over one with a lower.
+//
+// Pure: the module files are, and so is this.
+import { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, REGION_PLACEMENTS } from "./contract.mjs";
+import { settingsOf, settingValue } from "./settings.mjs";
+
+import chart from "./chart.mjs";
+import shell from "./shell.mjs";
+import feed from "./feed.mjs";
+import popupPosts from "./popup-posts.mjs";
+import stamp from "./stamp.mjs";
+import stats from "./stats.mjs";
+import fx from "./fx.mjs";
+import threads from "./threads.mjs";
+import flips from "./flips.mjs";
+import finale from "./finale.mjs";
+import teaser from "./teaser.mjs";
+import subtitle from "./subtitle.mjs";
+import qr from "./qr.mjs";
+import rail from "./rail.mjs";
+import counter from "./counter.mjs";
+import claims from "./claims.mjs";
+import intro from "./intro.mjs";
+import blur from "./blur.mjs";
+import pair from "./pair.mjs";
+import chapter from "./chapter.mjs";
+import status from "./status.mjs";
+
+export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, REGION_PLACEMENTS };
+
+/** Every module, by z (stack order), then id. */
+export const MODULES = Object.freeze(
+ [chart, shell, subtitle, qr, rail, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, intro, blur, pair, chapter, status]
+ .sort((a, b) => a.z - b.z || a.id.localeCompare(b.id)),
+);
+
+{
+ const ids = new Set();
+ const regions = new Set();
+ for (const m of MODULES) {
+ if (ids.has(m.id)) throw new Error(`registry: two modules are ${m.id}`);
+ ids.add(m.id);
+ if (m.region) {
+ if (regions.has(m.region)) throw new Error(`registry: two modules file their frames as ${m.region}`);
+ regions.add(m.region);
+ }
+ }
+ const provided = new Set(MODULES.flatMap((m) => m.provides ?? []));
+ for (const m of MODULES) {
+ if (m.host && !ids.has(m.host)) throw new Error(`registry: ${m.id}'s host ${m.host} is not a module`);
+ for (const d of m.deps ?? []) if (!provided.has(d)) throw new Error(`registry: ${m.id} reads ${d}, which no module provides`);
+ }
+}
+
+const BY_ID = new Map(MODULES.map((m) => [m.id, m]));
+const BY_REGION = new Map(MODULES.filter((m) => m.region).map((m) => [m.region, m]));
+
+/** A module by id, or undefined. */
+export const moduleById = (id) => BY_ID.get(id);
+
+/** The module that files its frames as `region` (`deck` is the shell's), or undefined. */
+export const moduleOfRegion = (region) => BY_REGION.get(region);
+
+/** A module by region, or a sentence saying there is none. */
+export function regionModule(region) {
+ const m = BY_REGION.get(region);
+ if (!m) throw new Error(`unknown chrome region: ${region}`);
+ return m;
+}
+
+/**
+ * The overlays a deck build composes and lays, in z order: every
+ * render-cached overlay module (the deck's shell first, the finale last).
+ */
+export const deckOverlays = () => MODULES.filter((m) => (m.kind === "overlay-whole" || m.kind === "overlay-window") && m.cached !== false);
+
+/**
+ * How a region is laid over the cut: "whole" (a sequence as long as the cut,
+ * from frame 1 -- or a chunk's `startNumber`), "window" (a short sequence at
+ * its own second), or null for the legacy chart band (its chain stays as it
+ * shipped).
+ */
+export function placementOf(region) {
+ const m = BY_REGION.get(region);
+ if (!m || m.cached === false) return null;
+ return m.kind === "overlay-window" ? "window" : m.kind === "overlay-whole" ? "whole" : null;
+}
+
+/** A region's render cache: is its page keyed (`.key`, frame keys), and is it drawn over the whole cut (windowable)? */
+export function regionCaching(region) {
+ const m = regionModule(region);
+ const keyed = m.cached !== false;
+ return { keyed, wholeCut: keyed && m.kind === "overlay-whole" };
+}
+
+/** The parts drawn in `host`'s page, by z. */
+export const partsOf = (host) => MODULES.filter((m) => m.host === host);
+
+/**
+ * The deck schedule as its modules' SLICES, `{ [moduleId]: slice }`: what
+ * each module reads of the one schedule the build writes (schedule.json
+ * keeps its shape -- the pages, umtool's preview and the caches read it).
+ * A module the cut does not use has no slice.
+ */
+export function scheduleSlices(doc) {
+ if (!doc || doc.kind !== "deck") return {};
+ const stamps = doc.factcheck?.stamps ?? [];
+ const out = {
+ shell: { segments: doc.segments, total: doc.total, fps: doc.fps, transition: doc.transition, ...(doc.moves ? { moves: doc.moves } : {}) },
+ rail: { pips: doc.segments.filter((s) => !s.noPip).map((s) => s.id) },
+ ...(stamps.length ? { counter: { stamps }, stamp: { stamps: stamps.filter((s) => s.stamp !== false) } } : {}),
+ ...(doc.layout === "feed" ? { feed: { posts: doc.posts ?? [] } } : doc.posts ? { "popup-posts": { posts: doc.posts } } : {}),
+ ...(doc.finale ? { finale: doc.finale } : {}),
+ ...(doc.deckClaims ? { claims: doc.deckClaims } : {}),
+ ...(doc.threads ? { threads: doc.threads } : {}),
+ ...(doc.flips ? { flips: doc.flips } : {}),
+ ...(doc.stats ? { stats: doc.stats } : {}),
+ ...(doc.fx ? { fx: doc.fx } : {}),
+ };
+ return out;
+}
+
+/**
+ * Every module's own settings checked against a manifest: `{ [moduleId]:
+ * sentences }`, only the modules with something to say. What umtool's
+ * generic panel shows under each module; the build refuses with the same
+ * sentences (deck.mjs validateChrome runs the deck's in one list).
+ */
+export function moduleProblems(manifest) {
+ const render = manifest?.render ?? {};
+ const chrome = render.chrome ?? {};
+ const deckOnCut = !!chrome && typeof chrome === "object" && chrome.layout === "deck";
+ const out = {};
+ for (const m of MODULES) {
+ if (!m.validate) continue;
+ // A deck module's settings are read through its SETTINGS entry (the
+ // path validateChrome reads); any other's at its configKey.
+ const entry = settingsOf(m.id);
+ if ((entry || m.configKey?.startsWith("render.chrome")) && !deckOnCut) continue;
+ const value = entry
+ ? settingValue(chrome, entry)
+ : (m.configKey ?? "").split(".").slice(1).reduce((o, k) => (o && typeof o === "object" ? o[k] : undefined), render);
+ const errors = m.validate(value, { render, chrome, deck: chrome.deck ?? {}, manifest, where: "render.chrome.deck" });
+ if (errors.length) out[m.id] = errors;
+ }
+ return out;
+}
diff --git a/umtool/report-to-video/modules/intro.mjs b/umtool/report-to-video/modules/intro.mjs
@@ -0,0 +1,67 @@
+// THE INTRO (module `intro`, a segment): the brand sting a cut opens with --
+// the wordmark built on the first sound, "media" under it, a mark drawn or
+// chimed, and on the chime a site's name swapped in (`render.intro`;
+// common lib/report/intro.mjs holds its rules, report-to-video intro.mjs
+// renders it, chrome-intro.mjs writes its page).
+//
+// The BRAND is configurable: `brand` names the kit it draws (brands/<id>.json,
+// default archilyzer-media), `suffix` the letters a site's name keeps of the
+// brand's ("lyzer": Jeralyzer swaps "Archi" for "Jera"), `projectUrl` the URL
+// the swap writes beside the site's (default archilyzer.pages.dev; false
+// none). Unset, the intro is the bytes it always was.
+import {
+ INTRO_BRAND_DEFAULT, INTRO_GROUNDS, INTRO_MARKS, INTRO_PROJECT_URL, INTRO_SECONDS, INTRO_SECONDS_MAX, INTRO_SECONDS_MIN,
+ INTRO_STYLES, INTRO_SUFFIX, INTRO_SWAPS, INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf,
+} from "yt-dlp-transcript-common/lib/report/intro.mjs";
+import { BRAND_IDS } from "../brand-ids.mjs";
+import { defineModule } from "./contract.mjs";
+
+/** Every reason `render.intro` cannot be drawn: the common rules, and a brand kit this renderer has. */
+export function validateIntroSettings(value) {
+ const errors = introErrors(value);
+ const brand = value && typeof value === "object" ? value.brand : undefined;
+ if (typeof brand === "string" && !errors.some((e) => e.startsWith("render.intro.brand")) && !BRAND_IDS.includes(brand)) {
+ errors.push(`render.intro.brand "${brand}" is not a brand kit — one of ${BRAND_IDS.join(", ")}`);
+ }
+ return errors;
+}
+
+export default defineModule({
+ id: "intro",
+ version: 1,
+ z: 1,
+ kind: "segment",
+ slot: "full",
+ title: "Intro",
+ summary: "The brand sting the cut opens with, a site's name swapped in on the chime.",
+ configKey: "render.intro",
+ defaults: { style: null, brand: INTRO_BRAND_DEFAULT, suffix: INTRO_SUFFIX, projectUrl: INTRO_PROJECT_URL, seconds: INTRO_SECONDS },
+ validate: (value) => validateIntroSettings(value),
+ resolve: introOf,
+ async render(ctx) {
+ const { renderIntro } = await import("../intro.mjs");
+ return renderIntro(ctx);
+ },
+ ui: [
+ { key: "style", type: "enum", options: INTRO_STYLES, label: "Style" },
+ { key: "ground", type: "enum", options: INTRO_GROUNDS, label: "Ground" },
+ { key: "mark", type: "enum", options: INTRO_MARKS, label: "Mark" },
+ { key: "seconds", type: "number", min: INTRO_SECONDS_MIN, max: INTRO_SECONDS_MAX, step: 0.05, label: "Seconds", default: INTRO_SECONDS },
+ { key: "site", type: "text", label: "Site (auto, an id, none)" },
+ { key: "swap", type: "enum", options: INTRO_SWAPS, label: "Swap" },
+ { key: "url", type: "enum", options: [...INTRO_URLS, false], label: "URLs" },
+ { key: "urlPlace", type: "enum", options: INTRO_URL_PLACES, label: "URLs go" },
+ { key: "brand", type: "enum", options: BRAND_IDS, label: "Brand kit", default: INTRO_BRAND_DEFAULT },
+ { key: "suffix", type: "text", label: "Shared suffix", default: INTRO_SUFFIX },
+ { key: "projectUrl", type: "text", label: "Project URL", default: INTRO_PROJECT_URL },
+ ],
+ docs: {
+ heading: "Intro",
+ intro: "The brand sting (`render.intro`); the style, mark and site knobs are in [The cut](#the-cut). The brand it draws is configurable; unset, it is the Archilyzer intro, byte for byte.",
+ rows: [
+ ["`render.intro.brand`", `a brand kit id (${BRAND_IDS.join(", ")}) · default \`${INTRO_BRAND_DEFAULT}\``, "`umtool look <p> intro='{\"style\":\"boot\",\"brand\":\"archilyzer-media\"}'`"],
+ ["`render.intro.suffix`", `the letters a site's name keeps of the brand's, 1–16 · default \`${INTRO_SUFFIX}\` (Jeralyzer swaps "Archi" for "Jera")`, "a take: `--set render.intro.suffix=lyzer`"],
+ ["`render.intro.projectUrl`", `the project URL the swap writes beside the site's · \`false\` none · default \`${INTRO_PROJECT_URL}\``, "a take: `--set render.intro.projectUrl=false`"],
+ ],
+ },
+});
diff --git a/umtool/report-to-video/modules/intro.test.mjs b/umtool/report-to-video/modules/intro.test.mjs
@@ -0,0 +1,53 @@
+// The intro module: the brand it draws is configurable (render.intro.brand,
+// .suffix, .projectUrl); unset, the page is the Archilyzer intro's.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { INTRO_PROJECT_URL, INTRO_SUFFIX, introErrors, introOf, introSitePrefix } from "yt-dlp-transcript-common/lib/report/intro.mjs";
+import { introHtml, swapPlan, lockupParts, PROJECT_URL_TEXT } from "../chrome-intro.mjs";
+import { brandKit } from "../brand.mjs";
+import { introEntry } from "../intro.mjs";
+import intro, { validateIntroSettings } from "./intro.mjs";
+
+const kit = brandKit("archilyzer-media");
+const base = { style: "boot-dark", mark: "chime", seconds: 4.75, width: 1920, height: 1080, fps: 30, kit };
+const SITE = { name: "Jeralyzer", lead: "Jer", url: "jeralyzer.pages.dev" };
+
+test("the brand's knobs are refused by name and read only when set", () => {
+ assert.deepEqual(introErrors({ style: "boot", brand: "archilyzer-media", suffix: "lyzer", projectUrl: "x.pages.dev" }), []);
+ assert.deepEqual(introErrors({ style: "boot", projectUrl: false }), []);
+ assert.match(introErrors({ style: "boot", brand: "Not An Id" })[0], /render\.intro\.brand must be a brand kit's id/);
+ assert.match(introErrors({ style: "boot", suffix: "ly zer" })[0], /render\.intro\.suffix/);
+ assert.match(introErrors({ style: "boot", projectUrl: "" })[0], /render\.intro\.projectUrl/);
+ assert.match(validateIntroSettings({ style: "boot", brand: "someone-else" })[0], /is not a brand kit — one of archilyzer-media/);
+ assert.equal("brand" in introOf({ intro: "boot" }), false, "an intro without them reads as it did");
+ assert.deepEqual(introOf({ intro: { style: "boot", suffix: "lytics", projectUrl: false } }).projectUrl, false);
+ const entry = introEntry({ intro: { style: "boot", brand: "archilyzer-media", suffix: "lytics" } });
+ assert.equal(entry.brand, "archilyzer-media");
+ assert.equal(entry.suffix, "lytics");
+ assert.equal("projectUrl" in entry, false);
+});
+
+test("the defaults keep today's page; the suffix and the project URL change the swap", () => {
+ assert.equal(PROJECT_URL_TEXT, INTRO_PROJECT_URL);
+ assert.equal(introHtml({ ...base, site: SITE }), introHtml({ ...base, site: SITE, suffix: INTRO_SUFFIX, projectUrl: INTRO_PROJECT_URL }));
+ assert.equal(introSitePrefix("Jeralyzer"), "Jera");
+ assert.equal(introSitePrefix("Jeralytics", "lytics"), "Jera");
+ const parts = lockupParts(kit);
+ const plain = swapPlan({ parts, site: SITE });
+ const none = swapPlan({ parts, site: SITE, projectUrl: false });
+ const other = swapPlan({ parts, site: SITE, projectUrl: "https://example.org/" });
+ assert.deepEqual(plain.urls.map((u) => u.text), ["jeralyzer.pages.dev", "archilyzer.pages.dev"]);
+ assert.deepEqual(none.urls.map((u) => u.text), ["jeralyzer.pages.dev"]);
+ assert.deepEqual(other.urls.map((u) => u.text), ["jeralyzer.pages.dev", "example.org"]);
+ // A suffix the name does not end in swaps the whole word.
+ const whole = swapPlan({ parts, site: SITE, suffix: "lytics" });
+ assert.ok(whole.glyphs.length > plain.glyphs.length);
+});
+
+test("the intro module: a segment with its home, its validator and its docs", () => {
+ assert.equal(intro.kind, "segment");
+ assert.equal(intro.configKey, "render.intro");
+ assert.deepEqual(intro.validate({ style: "boot" }, {}), []);
+ assert.ok(intro.docs.rows.some((r) => r[0].includes("render.intro.brand")));
+});
diff --git a/umtool/report-to-video/modules/layout.mjs b/umtool/report-to-video/modules/layout.mjs
@@ -0,0 +1,69 @@
+// THE LAYOUT ENGINE (release 39): every module asks for a SLOT and gets a
+// rect in the output frame. The slots generalise deckGeometry: the deck's
+// band at the foot of the frame, the footage box above it (moved for the
+// feed's column or the side panel), and the boxes the posts, the stamp and
+// the stats stand in inside it. A module draws in its slot's rect and never
+// in another's: the geometry is computed here, once, from the render block,
+// in design units (design.mjs) scaled to the output size.
+//
+// Pure. The numbers are deck.mjs's geometry functions' -- those stay the one
+// arithmetic, and this file is the one place a module asks them.
+import {
+ deckGeometry, feedGeometry, fxGeometry, postsGeometry, stampGeometry, statsGeometry, threadsGeometry,
+} from "../deck.mjs";
+import { MODULE_SLOTS } from "./contract.mjs";
+import { DESIGN, designScale } from "./design.mjs";
+
+export { DESIGN, designScale };
+
+/**
+ * A slot's rect in the output frame, `{ x, y, width, height }`.
+ *
+ * - `footer`: the deck's band, full width at the foot of the frame.
+ * - `footage`: the picture's box -- the feed's (beside its column) when
+ * `feed`, else the deck's (beside the side panel when that is on).
+ * - `column`: the posts feed's column, flush with the frame's side and top.
+ * - `popup`: where the popup posts stack (in the footage box, or at the
+ * frame's edge when the footage shifts away for them).
+ * - `stamp`: the fact-check stamp's box in the footage, at its position.
+ * - `panel`: the stats panel in the footage, at its position.
+ * - `side`: the side panel (the thread rail, the flips) beside the footage.
+ * - `full`: the whole frame.
+ *
+ * @param {string} slot
+ * @param {any} render
+ * @param {{ feed?: boolean }} [opts]
+ * @returns {{ x: number, y: number, width: number, height: number }}
+ */
+export function slotRect(slot, render, { feed = false } = {}) {
+ switch (slot) {
+ case "footer":
+ return { ...deckGeometry(render).deck };
+ case "footage":
+ return fxGeometry(render, { feed });
+ case "column":
+ return { ...feedGeometry(render).column };
+ case "popup":
+ return postsGeometry(render);
+ case "stamp":
+ return stampGeometry(render, { feed });
+ case "panel":
+ return statsGeometry(render, { feed });
+ case "side": {
+ const { cards: _c, ...box } = threadsGeometry(render);
+ return box;
+ }
+ case "full":
+ return { x: 0, y: 0, width: render?.width ?? DESIGN.width, height: render?.height ?? DESIGN.height };
+ default:
+ throw new Error(`layout: ${slot} is not a slot (${MODULE_SLOTS.filter((s) => s !== "inline").join(", ")})`);
+ }
+}
+
+/** Every slot's rect at once: what umtool's layout view and the module docs draw. */
+export function slotRects(render, opts = {}) {
+ return Object.fromEntries(MODULE_SLOTS.filter((s) => s !== "inline").map((s) => [s, slotRect(s, render, opts)]));
+}
+
+/** A design-unit length in this render's pixels, rounded. */
+export const scaled = (v, render) => Math.round(v * designScale(render));
diff --git a/umtool/report-to-video/modules/migrate.mjs b/umtool/report-to-video/modules/migrate.mjs
@@ -0,0 +1,104 @@
+// MANIFEST MIGRATION (release 39): a manifest written before the modules,
+// rewritten into the modules' homes -- PURE, and the render of what it
+// returns is the render of what it was given, frame for frame.
+//
+// One migration so far, `counter-series`: the fact-check tally becomes the
+// COUNTER's named series (counter.mjs).
+//
+// render.chrome.factcheck.verdicts -> render.chrome.deck.counter.series
+// every verdict a series, in VERDICTS order, its id the verdict (so every
+// mark's `verdict` names it as it always did, and the pages it draws are
+// the bytes they were), carrying the relabels it had: label, colour,
+// stampLabel, tallyLabel.
+// render.chrome.factcheck.tally -> counter.show / position / showAt
+// (one showAt for all is the counter's; one per verdict is the series').
+// render.chrome.deck.claims[].tally -> the series id when it named a label.
+//
+// The stamp's settings (`factcheck.stamp`) stay where they are: they are the
+// stamp module's. A manifest with nothing to count, or already migrated, is
+// returned as it was (`changes` empty). Idempotent.
+import { VERDICTS } from "yt-dlp-transcript-common/lib/report/verdicts.mjs";
+
+import { resolveCounter } from "../counter.mjs";
+import { tallyVerdictOf } from "../claims.mjs";
+import { rawMarksOf } from "../factcheck.mjs";
+
+/** The migrations, in the order they run, each `{ id, summary }`. */
+export const MIGRATIONS = Object.freeze([
+ Object.freeze({ id: "counter-series", summary: "the fact-check verdicts and tally become the counter's named series (render.chrome.deck.counter)" }),
+]);
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const clone = (v) => JSON.parse(JSON.stringify(v));
+
+/** Does this manifest count anything the counter would: a relabel, the tally's settings, a mark, a deck claim? */
+function counts(m) {
+ const chrome = m?.render?.chrome;
+ if (!isObj(chrome) || chrome.layout !== "deck") return false;
+ if (isObj(chrome.deck?.counter)) return false;
+ const f = isObj(chrome.factcheck) ? chrome.factcheck : {};
+ if (f.verdicts !== undefined || f.tally !== undefined) return true;
+ if ((m.timeline ?? []).some((e) => rawMarksOf(e).length)) return true;
+ return Array.isArray(chrome.deck?.claims) && chrome.deck.claims.some((c) => isObj(c) && c.kind === "count");
+}
+
+function counterSeries(m, changes) {
+ const chrome = m.render.chrome;
+ const f = isObj(chrome.factcheck) ? chrome.factcheck : {};
+ const resolved = resolveCounter(m.render);
+ const given = isObj(f.verdicts) ? f.verdicts : {};
+ const tally = isObj(f.tally) ? f.tally : {};
+ const perSeries = isObj(tally.showAt);
+ const series = VERDICTS.map((id) => {
+ const own = isObj(given[id]) ? given[id] : {};
+ return {
+ id,
+ ...own,
+ ...(perSeries && tally.showAt[id] === "first" ? { showAt: "first" } : {}),
+ };
+ });
+ const counter = {
+ series,
+ ...(tally.show === false ? { show: false } : {}),
+ ...(tally.position === "left" ? { position: "left" } : {}),
+ ...(!perSeries && tally.showAt === "first" ? { showAt: "first" } : {}),
+ };
+ const deck = isObj(chrome.deck) ? { ...chrome.deck } : {};
+ // A count claim names its series by id from here on.
+ if (Array.isArray(deck.claims)) {
+ deck.claims = deck.claims.map((c, n) => {
+ if (!isObj(c) || c.kind !== "count" || typeof c.tally !== "string") return c;
+ const id = tallyVerdictOf(c.tally, resolved.byId);
+ if (!id || id === c.tally) return c;
+ changes.push(`render.chrome.deck.claims[${n}].tally: "${c.tally}" -> "${id}" (the series by id)`);
+ return { ...c, tally: id };
+ });
+ }
+ deck.counter = counter;
+ const { verdicts: _v, tally: _t, ...rest } = f;
+ const next = { ...chrome, deck };
+ if (chrome.factcheck !== undefined) next.factcheck = rest;
+ m.render.chrome = next;
+ const relabelled = Object.keys(given).filter((k) => VERDICTS.includes(k));
+ changes.push(
+ `render.chrome.factcheck.verdicts -> render.chrome.deck.counter.series (${VERDICTS.length} series` +
+ `${relabelled.length ? `; ${relabelled.join(", ")} relabelled` : ""})`,
+ );
+ if (f.tally !== undefined) changes.push("render.chrome.factcheck.tally -> render.chrome.deck.counter (show, position, showAt)");
+}
+
+/**
+ * The manifest migrated into the modules' homes: `{ manifest, changes }`,
+ * `manifest` a new object (the one given is not touched) and `changes` a
+ * sentence per move, empty when there was nothing to do.
+ *
+ * @param {Record<string, any>} manifest
+ * @returns {{ manifest: Record<string, any>, changes: string[] }}
+ */
+export function migrateManifest(manifest) {
+ if (!isObj(manifest)) throw new Error("migrateManifest: a manifest is an object");
+ const m = clone(manifest);
+ const changes = [];
+ if (counts(m)) counterSeries(m, changes);
+ return { manifest: changes.length ? m : clone(manifest), changes };
+}
diff --git a/umtool/report-to-video/modules/migrate.test.mjs b/umtool/report-to-video/modules/migrate.test.mjs
@@ -0,0 +1,96 @@
+// migrateManifest (modules/migrate.mjs): the fact-check verdicts and tally
+// into the counter's named series -- pure, idempotent, and the pages it draws
+// the bytes they were.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { migrateManifest, MIGRATIONS } from "./migrate.mjs";
+import { estimateSchedule, snapWindow, validateChrome } from "../deck.mjs";
+import { validateClaims } from "../factcheck.mjs";
+import { deckHtml } from "../chrome-deck.mjs";
+import { stampHtml } from "../chrome-stamp.mjs";
+import { finaleHtml } from "../chrome-finale.mjs";
+
+const PALETTE = { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" };
+
+/** A Huck-shaped cut: one verdict relabelled, a per-verdict showAt, marks, a count claim by label, a finale. */
+function huckish({ tally = { show: true, position: "right", showAt: { PARTLY: "first" } } } = {}) {
+ return {
+ provenance: {}, posts: [],
+ render: {
+ width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE,
+ fontBold: "/usr/share/fonts/TTF/FiraSans-Bold.ttf",
+ chrome: {
+ engine: "hyperframes", layout: "deck",
+ deck: {
+ pip: { color: "verdict" },
+ finale: { totals: true },
+ claims: [{ kind: "count", at: "b", t: 4, said: "“less than ten”", window: { from: "2026-01-01", to: "2026-12-31" }, tally: "Seizures" }],
+ },
+ factcheck: {
+ verdicts: { CORROBORATED: { label: "Seizures", color: "#e5534b", stampLabel: "Seizure" }, PARTLY: { label: "Huck's Blend pitches", tallyLabel: "Pitches" } },
+ stamp: { seconds: 3, position: "top-left", show: true },
+ ...(tally ? { tally } : {}),
+ },
+ },
+ },
+ timeline: [
+ { type: "clip", id: "a", video: "v1", start: 0, end: 10, date: "2026-03-01", claim: { id: "s1", verdict: "CORROBORATED" } },
+ { type: "clip", id: "b", video: "v2", start: 0, end: 12, date: "2026-04-01", claims: [{ id: "p1", verdict: "PARTLY", at: 2 }, { id: "s2", verdict: "CORROBORATED", at: 8 }] },
+ { type: "clip", id: "c", video: "v3", start: 0, end: 10, date: "2026-05-01", layout: "finale", claim: { id: "s3", verdict: "CORROBORATED" } },
+ ],
+ };
+}
+
+function pages(m) {
+ const s = estimateSchedule(m);
+ const r = m.render;
+ return {
+ schedule: JSON.stringify(s),
+ deck: deckHtml(s, r, {}),
+ stamp: stampHtml(s, r, {}),
+ finale: finaleHtml(s, r, snapWindow({ segment: "finale", from: s.finale.from, to: s.finale.to }, { fps: 30, total: s.total }), {}),
+ };
+}
+
+test("the migration moves the verdicts and the tally into deck.counter, and the claim names its series by id", () => {
+ const before = huckish();
+ const frozen = JSON.stringify(before);
+ const { manifest, changes } = migrateManifest(before);
+ assert.equal(JSON.stringify(before), frozen, "the manifest given is not touched");
+ const c = manifest.render.chrome;
+ assert.deepEqual(c.deck.counter, {
+ series: [
+ { id: "CORROBORATED", label: "Seizures", color: "#e5534b", stampLabel: "Seizure" },
+ { id: "PARTLY", label: "Huck's Blend pitches", tallyLabel: "Pitches", showAt: "first" },
+ { id: "CONTRADICTED" }, { id: "NOT_FOUND" }, { id: "UNTESTABLE" },
+ ],
+ });
+ assert.deepEqual(c.factcheck, { stamp: { seconds: 3, position: "top-left", show: true } });
+ assert.equal(c.deck.claims[0].tally, "CORROBORATED");
+ assert.equal(changes.length, 3);
+ assert.match(changes.join("\n"), /factcheck\.verdicts -> render\.chrome\.deck\.counter\.series/);
+ assert.deepEqual(validateChrome(c, manifest.render), []);
+ assert.deepEqual(validateClaims(manifest), []);
+ assert.equal(MIGRATIONS[0].id, "counter-series");
+});
+
+test("the migrated cut draws the same pages, byte for byte", () => {
+ for (const tally of [undefined, { show: true, position: "left", showAt: "first" }, { showAt: { PARTLY: "first" } }]) {
+ const before = huckish({ tally });
+ const a = pages(before);
+ const b = pages(migrateManifest(before).manifest);
+ for (const k of Object.keys(a)) assert.equal(b[k], a[k], `${k} (tally ${JSON.stringify(tally)})`);
+ }
+});
+
+test("idempotent; nothing to count is nothing to do", () => {
+ const once = migrateManifest(huckish()).manifest;
+ const twice = migrateManifest(once);
+ assert.deepEqual(twice.changes, []);
+ assert.deepEqual(twice.manifest, once);
+ const plain = { render: { chrome: { engine: "hyperframes", layout: "deck", deck: {} } }, timeline: [{ type: "clip", id: "a" }] };
+ assert.deepEqual(migrateManifest(plain), { manifest: plain, changes: [] });
+ assert.deepEqual(migrateManifest({ render: {}, timeline: [] }).changes, []);
+ assert.throws(() => migrateManifest(null), /a manifest is an object/);
+});
diff --git a/umtool/report-to-video/modules/pair.mjs b/umtool/report-to-video/modules/pair.mjs
@@ -0,0 +1,72 @@
+// THE PAIR (module `pair`, region `pair`): then and now -- two clips on one
+// subject, each with its date (`render.chrome.pair`). As "split" a strip in
+// the footage box, THEN on one side and NOW on the other, the side playing
+// lit and the pair's caption under them; as "then→now" a card with both
+// dates and an arrow over the pair's first seconds. chrome-story.mjs writes
+// the page; story-settings.mjs holds its rules.
+import path from "node:path";
+
+import { pairGeometry, pairHtml, pairSchedule, resolvePair } from "../chrome-story.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { DATE_FORMATS, PAIR_DEFAULTS, PAIR_LIMITS, PAIR_POSITIONS, PAIR_STYLES, validatePair } from "./story-settings.mjs";
+
+export default defineModule({
+ id: "pair",
+ version: 1,
+ z: 52,
+ kind: "overlay-whole",
+ slot: "footage",
+ title: "Then and now",
+ summary: "Two clips on one subject, each with its date: a then | now strip (or a then→now card) with the pair's caption.",
+ configKey: "render.chrome.pair",
+ defaults: PAIR_DEFAULTS,
+ validate: (v) => validatePair(v),
+ resolve: resolvePair,
+ ui: [
+ { key: "style", type: "enum", options: PAIR_STYLES, label: "Style", default: "split" },
+ { key: "position", type: "enum", options: PAIR_POSITIONS, label: "Strip at", default: "bottom" },
+ { key: "dateFormat", type: "enum", options: DATE_FORMATS, label: "Dates", default: "long" },
+ { key: "labels.then", type: "text", label: "Then label", default: "Then" },
+ { key: "labels.now", type: "text", label: "Now label", default: "Now" },
+ { key: "seconds", type: "number", min: PAIR_LIMITS.seconds[0], max: PAIR_LIMITS.seconds[1], step: 0.5, label: "Card seconds (then→now)", default: 4 },
+ { key: "pairs", type: "list", label: "Pairs", item: [
+ { key: "then.clip", type: "clip", label: "Then clip" },
+ { key: "then.date", type: "date", label: "Then date" },
+ { key: "now.clip", type: "clip", label: "Now clip" },
+ { key: "now.date", type: "date", label: "Now date" },
+ { key: "topic", type: "text", label: "Topic" },
+ { key: "caption", type: "text", label: "Caption" },
+ { key: "style", type: "enum", options: PAIR_STYLES, label: "Style (this pair)" },
+ ] },
+ ],
+ docs: {
+ heading: "Then and now (pair)",
+ intro: "Two clips on one subject, each with its date (`render.chrome.pair`, chrome-story.mjs). The footage is not split -- two clips never play at once: \"split\" is a strip in the footage box, THEN on one side and NOW on the other, the side playing lit, up while either clip plays; \"then→now\" a card with both dates over the pair's first `seconds`. A pair whose clips the cut does not play is not drawn.",
+ rows: [
+ ["`chrome.pair.pairs[]`", `1–${PAIR_LIMITS.pairs} \`{then: {clip, date?, label?}, now: {clip, date?, label?}, caption? ≤${PAIR_LIMITS.caption}, topic? ≤${PAIR_LIMITS.topic}, style?, also?: [{clip, side, date?}]}\` -- a date YYYY, YYYY-MM or YYYY-MM-DD; \`also\` more clips on a side (≤${PAIR_LIMITS.also})`, "`umtool modules apply <p> --config module-config.json` · `umtool look <p> pair='{…}'`"],
+ ["`chrome.pair.style`", "`split` · `then→now` · default `split` (a pair's own `style` wins)", "`umtool look <p> pair.style=then→now`"],
+ ["`chrome.pair.position`, `.dateFormat`, `.seconds`", "`bottom` `top` · `long` `year` `iso` · 1–10 s · default `bottom`, `long`, 4", "`umtool look <p> pair.position=top`"],
+ ["`chrome.pair.labels`", "`{then, now}` ≤16 each · default Then, Now", "`umtool look <p> pair.labels='{\"then\":\"2012\"}'`"],
+ ],
+ },
+ region: "pair",
+ workers: "narrow",
+ noun: "the pair strip's",
+ on: (schedule, render) => !!schedule?.segments && pairSchedule(schedule, render).length > 0,
+ check: (schedule, render) => (pairSchedule(schedule, render).length
+ ? null
+ : "the pair region needs render.chrome.pair with a pair whose clips the cut plays"),
+ async page(ctx) {
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ return pairHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration });
+ },
+ regions(schedule, { render, outDir, frames = null }) {
+ return [assertRegion({
+ name: "pair", frames: frames ?? path.join(outDir, "chrome", "pair-frames"),
+ ...pairGeometry(render, { feed: schedule.layout === "feed" }),
+ })];
+ },
+ preview: (_slice, { render }) => ({ region: "pair", geometry: pairGeometry(render) }),
+ // A cue interpreter: each pair an item, so a changed caption recaptures only its frames.
+ frameKeys: { data: "pair-data", omit: ["init", "cues", "window", "total", "ids"] },
+});
diff --git a/umtool/report-to-video/modules/panel.mjs b/umtool/report-to-video/modules/panel.mjs
@@ -0,0 +1,157 @@
+// THE GENERIC MODULE PANEL'S MODEL (release 39): what umtool's Media tab
+// draws for a module from its `ui` descriptor, and what a save writes --
+// PURE, so the route, the CLI and the tests read one arithmetic.
+//
+// A module's `ui` fields are named by dotted keys relative to its BASE: its
+// configKey, except where the module's fields span its host's object (the
+// deck shell's and the rail's and the claim checks' fields are the deck's
+// own keys, `render.chrome.deck`; the blur's are the render block's). A save
+// is `{ fields: { <dotted key>: value | null } }` -- null removes the key --
+// applied over the manifest as it is, then written by updateChrome (a key
+// under render.chrome) or updateRender (a look key: intro, blur).
+//
+// ENABLE / DISABLE: a module whose settings are an object of their own (the
+// story modules, the finale, the counter, the intro, the claim checks) is ON
+// while that object is in the manifest -- or its look preset -- and OFF when
+// it is removed. The deck's own parts are on with the deck.
+import { MODULES } from "./index.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** Where a module's ui keys are rooted. */
+export function uiBase(m) {
+ if (m.id === "shell" || m.id === "rail" || m.id === "claims") return "render.chrome.deck";
+ if (m.id === "blur") return "render";
+ return m.configKey ?? null;
+}
+
+/** A module's cut-wide fields: a clip's own (`clip.*`, the clip editor's) are not the panel's. */
+export const uiOf = (m) => (m.ui ?? []).filter((f) => !String(f.key).startsWith("clip."));
+
+/** The modules the panel lists: every one with a ui descriptor and a home. */
+export const panelModules = () => MODULES.filter((m) => uiOf(m).length && uiBase(m));
+
+/** Modules that are switched on and off by their object being there. */
+const TOGGLES = Object.freeze({
+ pair: { pairs: [] },
+ chapter: { list: [] },
+ status: { items: [] },
+ finale: {},
+ counter: { series: [{ id: "count", label: "Count" }] },
+ intro: { style: "boot-dark", site: "auto" },
+ claims: null,
+});
+
+/** Is this module toggled by its object's presence, and what does turning it on write? */
+export function toggleOf(m) {
+ return Object.hasOwn(TOGGLES, m.id) ? { on: TOGGLES[m.id] } : null;
+}
+
+/** A dotted path's value in an object. */
+export function getPath(obj, dotted) {
+ return dotted.split(".").reduce((o, k) => (isObj(o) ? o[k] : undefined), obj);
+}
+
+/** A copy of `obj` with `dotted` set to `value` (null or undefined removes it; emptied objects are pruned). */
+export function setPath(obj, dotted, value) {
+ const out = isObj(obj) ? structuredClone(obj) : {};
+ const keys = dotted.split(".");
+ const trail = [out];
+ let cur = out;
+ for (const k of keys.slice(0, -1)) {
+ if (!isObj(cur[k])) cur[k] = {};
+ cur = cur[k];
+ trail.push(cur);
+ }
+ const last = keys[keys.length - 1];
+ if (value === null || value === undefined) {
+ delete cur[last];
+ for (let i = trail.length - 1; i > 0; i -= 1) {
+ if (Object.keys(trail[i]).length) break;
+ delete trail[i - 1][keys[i - 1]];
+ }
+ } else cur[last] = value;
+ return out;
+}
+
+/**
+ * Each panel module's state for a manifest: `{ id, title, summary, kind,
+ * slot, base, ui, docs, toggle, enabled, fields }` -- `fields` its ui keys'
+ * values as the MANIFEST holds them, `seen` as the build reads them (the
+ * preset under it), `problems` its validator's sentences.
+ *
+ * @param {Record<string, any>} manifest the manifest as written
+ * @param {Record<string, any>} seen the manifest with its preset laid under it
+ * @param {Record<string, string[]>} problems moduleProblems(seen)
+ */
+export function panelState(manifest, seen, problems = {}) {
+ return panelModules().map((m) => {
+ const base = uiBase(m);
+ const rel = base.split(".").slice(1).join(".");
+ const own = rel ? getPath(manifest.render ?? {}, rel) : manifest.render ?? {};
+ const eff = rel ? getPath(seen.render ?? {}, rel) : seen.render ?? {};
+ const fields = {};
+ const effective = {};
+ for (const f of uiOf(m)) {
+ const v = getPath(own, f.key);
+ const e = getPath(eff, f.key);
+ if (v !== undefined) fields[f.key] = v;
+ if (e !== undefined) effective[f.key] = e;
+ }
+ const toggle = toggleOf(m);
+ const cfgRel = (m.configKey ?? "").split(".").slice(1).join(".");
+ const enabled = toggle ? getPath(seen.render ?? {}, cfgRel) !== undefined : true;
+ return {
+ id: m.id, title: m.title, summary: m.summary ?? "", kind: m.kind, slot: m.slot, z: m.z,
+ configKey: m.configKey, base, ui: uiOf(m), docs: m.docs?.heading ?? null,
+ toggle: !!toggle, enabled, fields, effective,
+ preview: typeof m.preview === "function" || !!m.region || !!m.host,
+ problems: problems[m.id] ?? [],
+ };
+ });
+}
+
+/**
+ * A panel save as the writers take it: `{ chrome }` (the whole new
+ * render.chrome, for updateChrome) or `{ render }` (a look patch, for
+ * updateRender). `fields` are dotted keys relative to the module's base;
+ * `enabled: false` removes the module's object, `true` writes its default.
+ *
+ * @param {Record<string, any>} manifest
+ * @param {string} id
+ * @param {{ fields?: Record<string, unknown>, enabled?: boolean }} change
+ * @returns {{ chrome?: Record<string, any> | null, render?: Record<string, any> }}
+ */
+export function panelWrite(manifest, id, { fields = {}, enabled } = {}) {
+ const m = panelModules().find((x) => x.id === id);
+ if (!m) throw new Error(`no module ${id} in the panel (${panelModules().map((x) => x.id).join(", ")})`);
+ const base = uiBase(m);
+ const known = new Set(uiOf(m).map((f) => f.key));
+ for (const k of Object.keys(fields)) if (!known.has(k)) throw new Error(`${id}: ${k} is not one of its fields (${[...known].join(", ")})`);
+ const render = structuredClone(manifest.render ?? {});
+ const cfgRel = (m.configKey ?? "").split(".").slice(1).join(".");
+ let next = render;
+ if (enabled === false) {
+ if (!toggleOf(m)) throw new Error(`${id} is drawn with the deck: it is not switched on and off`);
+ next = setPath(next, cfgRel, null);
+ } else {
+ if (enabled === true) {
+ const t = toggleOf(m);
+ if (!t) throw new Error(`${id} is drawn with the deck: it is not switched on and off`);
+ if (getPath(next, cfgRel) === undefined) next = setPath(next, cfgRel, structuredClone(t.on ?? {}));
+ }
+ const rel = base.split(".").slice(1).join(".");
+ for (const [k, v] of Object.entries(fields)) next = setPath(next, rel ? `${rel}.${k}` : k, v === "" ? null : v);
+ }
+ if (base.startsWith("render.chrome") || m.configKey?.startsWith("render.chrome")) {
+ // A chrome left empty is no chrome (updateChrome's null removes the key).
+ return { chrome: next.chrome && Object.keys(next.chrome).length ? next.chrome : null };
+ }
+ // A look key (intro, blur): the patch of the top-level keys it changed.
+ const patch = {};
+ for (const k of new Set([...Object.keys(render), ...Object.keys(next)])) {
+ if (k === "chrome") continue;
+ if (JSON.stringify(render[k]) !== JSON.stringify(next[k])) patch[k] = next[k] === undefined ? null : next[k];
+ }
+ return { render: patch };
+}
diff --git a/umtool/report-to-video/modules/popup-posts.mjs b/umtool/report-to-video/modules/popup-posts.mjs
@@ -0,0 +1,104 @@
+// THE POPUP POSTS (module `popup-posts`, region `posts`): a clip's posts as
+// cards over the footage at the end of the clip (or from its start), one
+// short page per clip that carries them, laid at its own second.
+// chrome-posts.mjs writes the page; deck.mjs `postWindows` / `snapWindow`
+// time it and `postsGeometry` places it.
+import path from "node:path";
+
+import { postsGeometry, postWindows, resolveDeck, snapWindow } from "../deck.mjs";
+import { postsHtml, windowPosts } from "../chrome-posts.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { DECK_DEFAULTS, POST_AT, POST_LAYOUTS, POST_LINKS, settingsOf } from "./settings.mjs";
+
+const SEGMENT_RE = /^[A-Za-z0-9_-]+$/;
+
+export default defineModule({
+ id: "popup-posts",
+ version: 1,
+ z: 30,
+ kind: "overlay-window",
+ slot: "popup",
+ title: "Popup posts",
+ summary: "A clip's posts as cards over the footage, each window its own short page at its own second.",
+ configKey: "render.chrome.deck.posts",
+ defaults: DECK_DEFAULTS.posts,
+ validate: settingsOf("popup-posts").validate,
+ ui: [
+ { key: "show", type: "boolean", label: "Show the posts", default: true },
+ { key: "layout", type: "enum", options: POST_LAYOUTS, label: "Layout", default: "popup" },
+ { key: "links", type: "enum", options: POST_LINKS, label: "QR links to", default: "archive" },
+ { key: "qr", type: "boolean", label: "QR on each card", default: true },
+ { key: "width", type: "number", min: 320, max: 900, label: "Width (px)", default: DECK_DEFAULTS.posts.width },
+ { key: "inset", type: "number", min: 0, max: 80, label: "Inset (px)", default: DECK_DEFAULTS.posts.inset },
+ { key: "maxLines", type: "number", min: 2, max: 14, label: "Lines of words", default: DECK_DEFAULTS.posts.maxLines },
+ { key: "qrSize", type: "number", min: 80, max: 200, label: "QR size", default: DECK_DEFAULTS.posts.qrSize },
+ { key: "at", type: "enum", options: POST_AT, label: "Come up at", default: "end" },
+ { key: "seconds", type: "number", min: 0.5, max: 10, step: 0.5, label: "Seconds each", default: DECK_DEFAULTS.posts.seconds },
+ { key: "hold", type: "number", min: 0, max: 10, step: 0.5, label: "Hold (s)", default: DECK_DEFAULTS.posts.hold },
+ { key: "position", type: "enum", options: ["top-right", "top-left"], label: "Side", default: "top-right" },
+ { key: "shotMaxHeight", type: "number", min: 120, max: 1080, label: "Screenshot height cap", default: null },
+ ],
+ docs: {
+ heading: "Popup posts",
+ intro: "A clip's posts as cards over the footage (`deck.posts`, the `popup` layout), each window its own short page.",
+ rows: [
+ ["`deck.posts.at`", "`end` (the clip's last `seconds` each) · `start` (from the clip's start, sharing it) · default `end`", "`umtool look <p> deck.posts='{\"at\":\"start\"}'`"],
+ ["`deck.posts.seconds`, `.hold`", "0.5–10 · 0–10 s · default 4, 2.5 (the last frame held so the last card can be read)", "same"],
+ ["`deck.posts.position`", "`top-right` · `top-left` · default `top-right`", "same"],
+ ["`deck.posts.shift`", "`false` · `{scale 0.5–1, seconds 0–3}` · default 0.86, 0.6 (the footage moves aside while they are up)", "same"],
+ ["`deck.posts.shotMaxHeight`", "null · 120–1080 px · default null (a full card of words)", "same"],
+ ],
+ },
+ region: "posts",
+ workers: "narrow",
+ noun: "the posts window's",
+ on: (schedule) => postWindows(schedule).length > 0,
+ window(schedule, { window = null, segment = null, fps, total }) {
+ const want = window ?? postWindows(schedule).find((w) => w.segment === segment);
+ if (!want) {
+ throw new Error(segment ? `no post rides on ${segment} in this schedule` : "the posts region needs a window (or a segment)");
+ }
+ if (!SEGMENT_RE.test(String(want.segment))) throw new Error(`posts: ${want.segment} is not a segment id`);
+ return snapWindow(want, { fps, total });
+ },
+ names: ({ preview, window }) => ({ project: `posts-${preview ? "preview-" : ""}${window.segment}`, stem: `posts-${window.segment}` }),
+ async page(ctx) {
+ // The deck's faces and the deck's QR maker: a card is part of the deck's
+ // family, not a second design.
+ const { render, schedule, window } = ctx;
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ const posts = windowPosts(schedule, window.segment);
+ // `posts.qr: false`: no codes are made, and the page draws none.
+ const byUrl = resolveDeck(render).posts.qr === false
+ ? new Map()
+ : await ctx.qrs(posts.map((p) => p.qrUrl), resolveDeck(render).posts.qrSize);
+ const qrSrcs = {};
+ for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl);
+ const shotSrcs = await ctx.shots(posts);
+ const logoSrcs = await ctx.shots(posts, "logo");
+ return postsHtml(schedule, render, window, { fonts, qrSrcs, shotSrcs, logoSrcs });
+ },
+ /**
+ * The posts windows as overlay regions: one per clip that carries posts
+ * (`postWindows`), snapped to the frame grid (`snapWindow`), at
+ * `postsGeometry`. `offset` is the second the window's frame 1 lands on in
+ * the BASE's clock -- the cut's, or a preview's that starts `shift` seconds
+ * in. `clip` (`{at, dur}`) keeps only the windows that intersect it.
+ */
+ regions(schedule, { render, outDir, shift = 0, clip = null }) {
+ const fps = Number(schedule.fps ?? render.fps);
+ const g = postsGeometry(render);
+ return postWindows(schedule)
+ .map((w) => ({ w, s: snapWindow(w, { fps, total: schedule.total }) }))
+ .filter(({ s }) => !clip || (s.from < clip.at + clip.dur && s.to > clip.at))
+ .map(({ w, s }) => assertRegion({
+ name: "posts",
+ segment: s.segment,
+ window: w,
+ frames: path.join(outDir, "chrome", `posts-${s.segment}-frames`),
+ x: g.x, y: g.y, width: g.width, height: g.height,
+ offset: s.from - shift,
+ frameCount: s.frames,
+ }, "window"));
+ },
+});
diff --git a/umtool/report-to-video/modules/qr.mjs b/umtool/report-to-video/modules/qr.mjs
@@ -0,0 +1,35 @@
+// THE QR (module `qr`, a part of the shell): each clip's code in the deck's
+// source cell, and the host it resolves to read up its side -- linked to the
+// archive at the clip (`site`) or to the record itself (`original`). The
+// deck's QR maker (compose-chrome.mjs `qrPngsFor`) draws the codes.
+import { DECK_DEFAULTS, QR_LINKS, settingsOf } from "./settings.mjs";
+import { defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "qr",
+ version: 1,
+ z: 12,
+ kind: "part",
+ host: "shell",
+ slot: "inline",
+ title: "QR",
+ summary: "Each clip's code in the deck, to the archive at the clip or to the record itself.",
+ configKey: "render.chrome.deck.qr",
+ defaults: DECK_DEFAULTS.qr,
+ validate: settingsOf("qr").validate,
+ resolve: (render) => ({ ...DECK_DEFAULTS.qr, ...(render?.chrome?.deck?.qr ?? {}) }),
+ ui: [
+ { key: "show", type: "boolean", label: "Show the code", default: true },
+ { key: "size", type: "number", min: 80, max: 380, step: 2, label: "Size (px)", default: 150 },
+ { key: "links", type: "enum", options: QR_LINKS, label: "Links to", default: "site" },
+ ],
+ docs: {
+ heading: "QR",
+ intro: "Each clip's QR in the deck's source cell. An entry's `citeUrl` wins either way.",
+ rows: [
+ ["`deck.qr.show`", "bool · default `true`", "`umtool look <p> deck.qr='{\"show\":false}'`"],
+ ["`deck.qr.size`", "80–380 px, at most the deck's height less 20 · default 150", "`umtool look <p> deck.qr='{\"size\":130}'`"],
+ ["`deck.qr.links`", "`site` (the archive at the clip's start) · `original` (YouTube at the second, a Rumble page, an X post) · default `site`", "`umtool look <p> deck.qr='{\"links\":\"original\"}'`"],
+ ],
+ },
+});
diff --git a/umtool/report-to-video/modules/rail.mjs b/umtool/report-to-video/modules/rail.mjs
@@ -0,0 +1,61 @@
+// THE RAIL (module `rail`, a part of the shell): the deck's pip track -- a
+// pip per clip, the marker on the one playing, the fuse burning toward the
+// next -- and the markers' flags over it (deck.mjs `pipXs`, `deckMarkers`;
+// chrome-deck.mjs `deckCues`). The finale redraws it large (finale.mjs).
+//
+// `pip.spacing`:
+// - "even" (the default): the pips spread evenly over the track.
+// - "time": each pip at its clip's middle in the cut's clock.
+// - "pitch": each pip `pip.pitch` px after the one before, from the track's
+// left end, and the fuse measured against the whole track -- so a pip's
+// place, and the fuse's progress to it, depend on the clips before it
+// alone, and a clip inserted later moves nothing drawn before it (the
+// frame keys then reuse those frames). The pips the cut has not reached
+// are not drawn until the fuse sets off toward them. A cut with more pips
+// than the track holds at that pitch lays them at the pitch that fits.
+import { DECK_DEFAULTS, MARKER_ALIGNS, MARKER_LAYOUTS, PIP_COLORS, PIP_PITCH, PIP_PITCH_DEFAULT, PIP_SPACINGS, settingsOf } from "./settings.mjs";
+import { defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "rail",
+ version: 1,
+ z: 13,
+ kind: "part",
+ host: "shell",
+ slot: "inline",
+ title: "Rail",
+ summary: "The deck's pip track: a pip per clip, the marker, the fuse, and the markers' flags.",
+ configKey: "render.chrome.deck.pip",
+ configKeys: ["render.chrome.deck.markers", "render.chrome.deck.markerLayout"],
+ defaults: { pip: DECK_DEFAULTS.pip, markers: DECK_DEFAULTS.markers, markerLayout: DECK_DEFAULTS.markerLayout },
+ provides: ["rail.layout"],
+ validate: settingsOf("rail").validate,
+ resolve(render) {
+ const d = render?.chrome?.deck ?? {};
+ const pip = { ...DECK_DEFAULTS.pip, ...(d.pip ?? {}) };
+ return {
+ pip: pip.spacing === "pitch" ? { ...pip, pitch: pip.pitch ?? PIP_PITCH_DEFAULT } : pip,
+ markers: d.markers ?? DECK_DEFAULTS.markers,
+ markerLayout: d.markerLayout ?? DECK_DEFAULTS.markerLayout,
+ };
+ },
+ ui: [
+ { key: "pip.spacing", type: "enum", options: PIP_SPACINGS, label: "Spacing", default: "even" },
+ { key: "pip.pitch", type: "number", min: PIP_PITCH[0], max: PIP_PITCH[1], label: "Pitch (px)", default: PIP_PITCH_DEFAULT, when: { "pip.spacing": "pitch" } },
+ { key: "pip.size", type: "number", min: 2, max: 24, label: "Pip size", default: 6 },
+ { key: "pip.activeSize", type: "number", min: 2, max: 40, label: "Marker size", default: 12 },
+ { key: "pip.color", type: "enum", options: PIP_COLORS, label: "Lit pip colour", default: "accent" },
+ { key: "markers", type: "markers", label: "Markers", align: MARKER_ALIGNS },
+ { key: "markerLayout", type: "enum", options: MARKER_LAYOUTS, label: "Crowded labels", default: "stagger" },
+ ],
+ docs: {
+ heading: "Rail",
+ intro: "The pip track along the top of the deck; the markers' flags stand over it ([markers](#the-cut)).",
+ rows: [
+ ["`deck.pip.spacing`", "`even` · `time` (each pip at its clip's middle) · `pitch` (each `pip.pitch` px after the last, from the left; the pips not yet reached are not drawn, so an insert keeps the frames before it) · default `even`", "`umtool look <p> deck.pip='{\"spacing\":\"pitch\",\"pitch\":24}'`"],
+ ["`deck.pip.pitch`", `${PIP_PITCH[0]}–${PIP_PITCH[1]} px · default ${PIP_PITCH_DEFAULT} (only with \`spacing: "pitch"\`; a cut with more pips than the track holds at it is laid at the pitch that fits)`, "same"],
+ ["`deck.pip.size`, `deck.pip.activeSize`", "2–24 · 2–40 px, the marker at least the pip · default 6, 12", "`umtool look <p> deck.pip='{\"size\":8}'`"],
+ ["`deck.pip.color`", "`accent` · `verdict` (a counted clip's pip takes its series' colour and shape) · default `accent`", "`umtool look <p> deck.pip='{\"color\":\"verdict\"}'`"],
+ ],
+ },
+});
diff --git a/umtool/report-to-video/modules/rail.test.mjs b/umtool/report-to-video/modules/rail.test.mjs
@@ -0,0 +1,51 @@
+// The rail module: pip spacing "pitch" (deck.mjs pipXs, chrome-deck.mjs deckCues)
+// and the settings every deck module validates (modules/settings.mjs).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { estimateSchedule, pipXs, resolveDeck, validateChrome } from "../deck.mjs";
+import { deckCues, deckHtml } from "../chrome-deck.mjs";
+import rail from "./rail.mjs";
+import { SETTINGS, settingsOf } from "./settings.mjs";
+
+const PALETTE = { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" };
+const render = (pip) => ({ width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE, chrome: { engine: "hyperframes", layout: "deck", deck: { pip } } });
+const clip = (id) => ({ type: "clip", id, video: id, start: 0, end: 8 });
+
+test("pipXs at a pitch: each pip a pitch after the last from the left; squeezed only when the track is too short", () => {
+ assert.deepEqual(pipXs(3, 48, 1872, "pitch", null, 40), [48, 88, 128]);
+ assert.deepEqual(pipXs(1, 48, 1872, "pitch", null, 40), [48]);
+ // 100 pips at 40 px need 3960 px: laid at the pitch that fits.
+ const xs = pipXs(100, 48, 1872, "pitch", null, 40);
+ assert.ok(Math.abs(xs.at(-1) - 1872) < 1e-9);
+ assert.equal(xs[0], 48);
+ // A pip's place does not depend on how many come after it.
+ assert.deepEqual(pipXs(4, 48, 1872, "pitch", null, 40).slice(0, 3), pipXs(3, 48, 1872, "pitch", null, 40));
+});
+
+test("the deck at a pitch: pips after the first hidden until the marker reaches the one before; the fuse against the track", () => {
+ const r = render({ spacing: "pitch", pitch: 40 });
+ const s = estimateSchedule({ render: r, timeline: [clip("a"), clip("b"), clip("c")], posts: [], provenance: {} });
+ const { init, cues, pips } = deckCues(s, r);
+ assert.deepEqual(pips.map((p) => p.x), [48, 88, 128]);
+ assert.deepEqual(init.pb1, { opacity: 0 });
+ assert.deepEqual(init.pb2, { opacity: 0 });
+ assert.equal(init.pb0, undefined);
+ assert.ok(cues.some((c) => c.k === "pb1" && c.to.opacity === 1));
+ const html = deckHtml(s, r, {});
+ assert.match(html, /\.fuse \{ position: absolute; left: 48px; top: -1px; width: 1824px;/);
+ assert.match(html, /<div class="pip" data-k="pb1" style="left:85px"><\/div>/);
+ // Even spacing: no pip is hidden, as it always was.
+ const e = deckCues(s, render({}));
+ assert.equal(e.init.pb1, undefined);
+});
+
+test("rail settings: spacing, pitch, and the deck's other keys refused by name", () => {
+ assert.deepEqual(validateChrome(render({ spacing: "pitch", pitch: 24 }).chrome, render({})), []);
+ assert.match(validateChrome(render({ spacing: "grid" }).chrome, render({}))[0], /pip\.spacing must be "even", "time" or "pitch"/);
+ assert.match(validateChrome(render({ pitch: 2 }).chrome, render({}))[0], /pip\.pitch must be from 8 to 200/);
+ assert.equal(resolveDeck(render({})).pip.pitch, undefined, "no pitch unless set: the deck resolves as it did");
+ assert.equal(rail.resolve(render({ spacing: "pitch" })).pip.pitch, 28);
+ assert.equal(rail.validate, settingsOf("rail").validate);
+ assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "pair", "chapter", "status", "finale", "claims", "counter", "shell", "rail", "subtitle", "qr", "popup-posts"]);
+});
diff --git a/umtool/report-to-video/modules/registry.test.mjs b/umtool/report-to-video/modules/registry.test.mjs
@@ -0,0 +1,144 @@
+// The module contract and registry (modules/contract.mjs, modules/index.mjs).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { assertRegion, defineModule, MODULE_KINDS } from "./contract.mjs";
+import {
+ deckOverlays, MODULES, moduleById, moduleOfRegion, partsOf, placementOf, regionCaching, regionModule,
+} from "./index.mjs";
+import { slotRect } from "./layout.mjs";
+import { chromeOverlayChain, chromeRegions, feedRegion, finaleRegions, postsRegions, stampRegion, threadsRegion } from "../build-video.mjs";
+import { deckGeometry, feedGeometry, postsGeometry, stampGeometry, threadsGeometry } from "../deck.mjs";
+
+const RENDER = {
+ width: 1920, height: 1080, fps: 30,
+ palette: { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: {} },
+};
+
+test("defineModule refuses a definition the registry should not hold, by name", () => {
+ const base = { id: "x", version: 1, z: 1, kind: "overlay-whole", slot: "footer", title: "X", region: "x" };
+ assert.equal(defineModule(base).id, "x");
+ assert.ok(Object.isFrozen(defineModule(base)));
+ assert.throws(() => defineModule({ ...base, colour: 1 }), /colour is not a module key/);
+ assert.throws(() => defineModule({ ...base, id: "Bad Id" }), /id must be/);
+ assert.throws(() => defineModule({ ...base, kind: "overlay" }), /kind must be one of/);
+ assert.throws(() => defineModule({ ...base, slot: "middle" }), /slot must be/);
+ assert.throws(() => defineModule({ ...base, region: undefined }), /an overlay names its region/);
+ assert.throws(() => defineModule({ ...base, kind: "part", host: "shell" }), /a part's slot is inline/);
+ assert.throws(() => defineModule({ ...base, kind: "part", slot: "inline", host: "shell" }), /no region or page/);
+ assert.throws(() => defineModule({ ...base, provides: ["other.thing"] }), /not its own/);
+ assert.throws(() => defineModule({ ...base, validate: [] }), /validate must be a function/);
+ assert.deepEqual(MODULE_KINDS, ["overlay-whole", "overlay-window", "segment", "input", "post", "part"]);
+});
+
+test("assertRegion: a window has an offset and a frame count; a malformed region is refused", () => {
+ const r = { name: "deck", frames: "/f", x: 0, y: 890, width: 1920, height: 190 };
+ assert.equal(assertRegion(r), r);
+ assert.throws(() => assertRegion({ ...r, x: "0" }), /x must be a number/);
+ assert.throws(() => assertRegion(r, "window"), /offset/);
+ assert.throws(() => assertRegion({ ...r, offset: 1 }, "window"), /frame count/);
+ assert.ok(assertRegion({ ...r, offset: 1, frameCount: 30 }, "window"));
+ assert.throws(() => assertRegion({ ...r, startNumber: 0 }), /startNumber/);
+});
+
+test("the registry: unique ids and regions, sorted by z, the deck's overlays in today's order", () => {
+ const ids = MODULES.map((m) => m.id);
+ assert.equal(new Set(ids).size, ids.length);
+ for (let i = 1; i < MODULES.length; i += 1) assert.ok(MODULES[i - 1].z <= MODULES[i].z);
+ // The order the build has always laid them in: the finale last.
+ assert.deepEqual(deckOverlays().map((m) => m.region), ["deck", "feed", "posts", "stamp", "stats", "pair", "status", "fx", "threads", "flips", "chapter", "finale"]);
+ assert.equal(moduleOfRegion("deck").id, "shell");
+ assert.equal(regionModule("posts").id, "popup-posts");
+ assert.throws(() => regionModule("nope"), /unknown chrome region: nope/);
+ assert.equal(moduleById("teaser").kind, "segment");
+ for (const m of MODULES.filter((x) => x.host)) assert.ok(moduleById(m.host), `${m.id}'s host`);
+ assert.deepEqual(partsOf("feed"), []);
+});
+
+test("placement and caching come from the module's kind", () => {
+ for (const r of ["deck", "feed", "stamp", "stats", "fx", "threads", "flips"]) assert.equal(placementOf(r), "whole", r);
+ for (const r of ["posts", "finale"]) assert.equal(placementOf(r), "window", r);
+ assert.equal(placementOf("chart"), null);
+ assert.equal(placementOf("teaser"), null);
+ assert.deepEqual(regionCaching("deck"), { keyed: true, wholeCut: true });
+ assert.deepEqual(regionCaching("posts"), { keyed: true, wholeCut: false });
+ assert.deepEqual(regionCaching("teaser"), { keyed: true, wholeCut: false });
+ assert.deepEqual(regionCaching("chart"), { keyed: false, wholeCut: false });
+});
+
+test("the layout engine's slots are the deck geometry's rects", () => {
+ const feedRender = { ...RENDER, chrome: { ...RENDER.chrome, deck: { posts: { layout: "feed" } } } };
+ assert.deepEqual(slotRect("footer", RENDER), deckGeometry(RENDER).deck);
+ assert.deepEqual(slotRect("footage", RENDER), deckGeometry(RENDER).footage);
+ assert.deepEqual(slotRect("footage", feedRender, { feed: true }), feedGeometry(feedRender).footage);
+ assert.deepEqual(slotRect("column", feedRender), feedGeometry(feedRender).column);
+ assert.deepEqual(slotRect("popup", RENDER), postsGeometry(RENDER));
+ assert.deepEqual(slotRect("stamp", RENDER), stampGeometry(RENDER));
+ const { cards: _c, ...side } = threadsGeometry(RENDER);
+ assert.deepEqual(slotRect("side", RENDER), side);
+ assert.deepEqual(slotRect("full", RENDER), { x: 0, y: 0, width: 1920, height: 1080 });
+ assert.throws(() => slotRect("inline", RENDER), /not a slot/);
+});
+
+test("the build's region helpers are the modules' regions, shaped as they always were", () => {
+ const deck = chromeRegions(RENDER, "/o");
+ assert.deepEqual(deck, [{ name: "deck", frames: "/o/chrome/deck-frames", ...deckGeometry(RENDER).deck }]);
+ assert.deepEqual(Object.keys(deck[0]), ["name", "frames", "x", "y", "width", "height"]);
+ const feedRender = { ...RENDER, chrome: { ...RENDER.chrome, deck: { posts: { layout: "feed" } } } };
+ assert.deepEqual(feedRegion(feedRender, "/f"), { name: "feed", frames: "/f", ...feedGeometry(feedRender).column });
+ assert.deepEqual(stampRegion(RENDER, "/s", { layout: "deck" }), { name: "stamp", frames: "/s", ...stampGeometry(RENDER) });
+ assert.equal(threadsRegion(RENDER, "/t", "flips").name, "flips");
+ const schedule = {
+ fps: 30, total: 20,
+ posts: [{ segment: "a", appear: 2, out: [5, 5.5], slot: 0 }, { segment: "b", appear: 9, out: [12, 12.5], slot: 0 }],
+ finale: { from: 15, to: 20 },
+ };
+ const posts = postsRegions(RENDER, "/o", schedule);
+ assert.deepEqual(posts.map((p) => [p.segment, p.offset, p.frameCount]), [["a", 2, 105], ["b", 9, 105]]);
+ assert.deepEqual(postsRegions(RENDER, "/o", schedule, { shift: 8, clip: { at: 8, dur: 2 } }).map((p) => [p.segment, p.offset]), [["b", 1]]);
+ const fin = finaleRegions(RENDER, "/o", schedule);
+ assert.deepEqual(fin.map((f) => [f.name, f.offset, f.frameCount, f.width]), [["finale", 15, 150, 1920]]);
+ assert.deepEqual(finaleRegions(RENDER, "/o", { ...schedule, finale: undefined }), []);
+});
+
+test("the overlay chain lays a module's region by its placement", () => {
+ const regions = [
+ { name: "deck", frames: "/d", x: 0, y: 890, width: 1920, height: 190 },
+ { name: "posts", frames: "/p", x: 1, y: 2, width: 3, height: 4, offset: 2.5, frameCount: 10 },
+ ];
+ const c = chromeOverlayChain({ fps: 30 }, regions, "[v]", 1);
+ assert.deepEqual(c.inputs.slice(0, 2), ["-reinit_filter", "0"]);
+ assert.ok(c.inputs.includes("-itsoffset"));
+ assert.match(c.chain, /overlay=x=0:y=890:format=yuv444:shortest=1\[hf0\]/);
+ assert.match(c.chain, /overlay=x=1:y=2:format=yuv444:eof_action=pass\[hf1\]/);
+ const legacy = chromeOverlayChain({ fps: 30 }, [{ name: "chart", frames: "/c", x: 0, y: 880, width: 1920, height: 200 }], "[v]", 1);
+ assert.equal(legacy.inputs[0], "-framerate");
+ assert.doesNotMatch(legacy.chain, /format=rgba/);
+});
+
+test("scheduleSlices: each module's slice of the one schedule; moduleProblems: each module's own sentences", async () => {
+ const { scheduleSlices, moduleProblems } = await import("./index.mjs");
+ const doc = {
+ kind: "deck", total: 20, fps: 30, transition: 0.5,
+ segments: [{ id: "a" }, { id: "b", noPip: true }],
+ factcheck: { stamps: [{ claim: "k", verdict: "CORROBORATED", segment: "a", stamp: false }, { claim: "j", verdict: "PARTLY", segment: "a" }] },
+ layout: "feed", posts: [{ id: "p" }], finale: { from: 15, to: 20 },
+ };
+ const s = scheduleSlices(doc);
+ assert.deepEqual(Object.keys(s).sort(), ["counter", "feed", "finale", "rail", "shell", "stamp"]);
+ assert.deepEqual(s.rail.pips, ["a"]);
+ assert.equal(s.counter.stamps.length, 2);
+ assert.equal(s.stamp.stamps.length, 1, "the stamps drawn");
+ assert.deepEqual(scheduleSlices({ kind: "chart" }), {});
+ const manifest = {
+ render: { width: 1920, height: 1080, intro: { style: "boot", brand: "x-kit" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { links: "nowhere" }, pip: { spacing: "pitch", pitch: 1 } } } },
+ timeline: [],
+ };
+ const p = moduleProblems(manifest);
+ assert.match(p.qr[0], /qr\.links must be/);
+ assert.match(p.rail[0], /pip\.pitch must be from 8 to 200/);
+ assert.match(p.intro[0], /x-kit" is not a brand kit/);
+ assert.deepEqual(moduleProblems({ render: {}, timeline: [] }), {});
+});
diff --git a/umtool/report-to-video/modules/settings.mjs b/umtool/report-to-video/modules/settings.mjs
@@ -0,0 +1,371 @@
+// THE MODULES' SETTINGS (release 39): every chrome module's home in the
+// manifest, its defaults and its validator -- the one copy. The registry
+// (modules/index.mjs) hands each module its entry, and deck.mjs's
+// validateChrome runs them all in SETTINGS order, so umtool's writers and
+// the build refuse the same things.
+//
+// A LEAF: it imports only files that do not import deck.mjs, because deck.mjs
+// imports it (a cycle through the module files would read a binding before it
+// is set). The deck's own constants live here for that reason, and deck.mjs
+// re-exports them under the names they always had.
+import { deckClaimShapeErrors } from "../claims.mjs";
+import { validateFinaleSettings } from "../finale.mjs";
+import { counterLabelProblem, validateFactcheck } from "../factcheck.mjs";
+import { validateCounter } from "../counter.mjs";
+import { validateThreads } from "../threads.mjs";
+import { validateFlips } from "../flips.mjs";
+import { validateStats } from "../stats.mjs";
+import { validateFx } from "../fx.mjs";
+import { validateChapter, validatePair, validateStatus } from "./story-settings.mjs";
+
+/**
+ * Every deck setting and its default. A manifest names only what it changes;
+ * `resolveDeck` fills the rest. Each default is a setting, not a constant --
+ * the alternative in each comment is a supported value.
+ */
+export const DECK_DEFAULTS = Object.freeze({
+ height: 190,
+ footageScale: 0.82,
+ background: "panel", // | "flush"
+ // spacing | "time" | "pitch". `color` "verdict": a claimed clip's pip, once
+ // lit, takes its claim's verdict colour and shape (counter.mjs). With
+ // "pitch", `pip.pitch` is the px between two pips (PIP_PITCH_DEFAULT when
+ // unset; rail.mjs) -- not a default here, so a deck without it resolves as
+ // it always did.
+ pip: Object.freeze({ spacing: "even", size: 6, activeSize: 12, color: "accent" }),
+ title: Object.freeze({ size: 54, maxChars: 48 }),
+ subtitle: Object.freeze({ parts: "auto", dateFormat: "long" }), // dateFormat | "iso"
+ // `links` is where a clip's QR goes: "site" (the archive's page at the
+ // clip's start) or "original" (the record's own page -- YouTube at the
+ // second, a Rumble page, an X post). An entry's `citeUrl` wins either way.
+ qr: Object.freeze({ show: true, size: 150, links: "site" }),
+ overCards: "hide", // | "show"
+ motion: Object.freeze({ out: 0.3, in: 0.45, pip: 0.7 }),
+ // The manifest's `posts`, drawn as cards over the footage at the end of the
+ // clip each one is attached to. position | "top-left".
+ // `hold` freezes the last frame of a clip that carries posts for that long,
+ // so the last of them can be read before the next clip; `shift` moves the
+ // footage away from the posts column (scaled to `scale`, over `seconds`)
+ // while they are up, or is `false`.
+ // `layout` "popup" draws them as above; "feed" keeps them in a column of
+ // their own beside the footage for the whole cut (feedGeometry), each one
+ // ticking in as its clip starts -- no hold, no move.
+ // `links` is where a post's QR goes: "archive" (the post's page on the
+ // archive the manifest names, `provenance.siteOrigin`, which survives the
+ // post or the platform going away, and links on to the original) or
+ // "original" (the bsky.app / x.com link itself).
+ // `at` is when a popup's posts come up: "end" (the last `seconds` of the
+ // clip, as above) or "start" (from the clip's start, sharing the whole clip
+ // in the order the manifest lists them -- the post beside the words it goes
+ // with, so no hold is needed). `shotMaxHeight` caps a post's screenshot in
+ // px; null keeps it to the height of a full card of words (`maxLines`).
+ posts: Object.freeze({
+ show: true, layout: "popup", seconds: 4, hold: 2.5, position: "top-right", width: 600, qrSize: 120, maxLines: 7,
+ inset: 24, shift: Object.freeze({ scale: 0.86, seconds: 0.6 }), links: "archive", at: "end", shotMaxHeight: null,
+ // `qr: false` draws no QR on any post card (popup or feed); the words
+ // take the code's width. The clip's own deck QR (`qr`) is untouched.
+ qr: true,
+ }),
+ // Flags on the pip track: `[{ after, label, color?, align? }]`, each between
+ // the pip of the clip `after` names and the next, hidden until the fuse
+ // reaches it (deckMarkers). An empty list is no flags, and the deck lays out
+ // as it always did.
+ markers: Object.freeze([]),
+ // Crowded labels: "stagger" lays them in two rows when one would not fit in
+ // a single row (the band grows by MARKER_ROW, the track moves down by it);
+ // "truncate" keeps one row and ellipsizes. A single row that fits is laid
+ // the same either way.
+ markerLayout: "stagger",
+});
+
+/** The pip's colour when lit (`pip.color`): the deck's accent, or a claimed clip's verdict. */
+export const PIP_COLORS = Object.freeze(["accent", "verdict"]);
+
+/** A marker's limits: how many, and a label's characters. */
+export const MARKER_LIMITS = Object.freeze({ count: 12, label: 24 });
+
+/**
+ * Where a marker's label sits against its flag: "auto" (centred when it has
+ * the room, else the stretch it may take -- as it always was), "left" (it
+ * starts at the flag and reads on to the right), "right" (it ends at the
+ * flag), "center" (centred on it, always).
+ */
+export const MARKER_ALIGNS = Object.freeze(["auto", "left", "right", "center"]);
+
+/** `deck.markerLayout`: crowded labels in two rows, or one row ellipsized. */
+export const MARKER_LAYOUTS = Object.freeze(["stagger", "truncate"]);
+
+/** The palette keys a marker's `color` may name (else a `#rgb` / `#rrggbb`). */
+export const MARKER_PALETTE_KEYS = Object.freeze(["fg", "muted", "accent", "amber", "dim"]);
+
+/** A marker with no `color` is drawn in this palette key. */
+export const MARKER_DEFAULT_COLOR = "amber";
+
+/** Where a clip's deck QR links (`qr.links`): the archive at the clip, or the original. */
+export const QR_LINKS = Object.freeze(["site", "original"]);
+
+/** Subtitle tokens a `subtitle.parts` array may name. "auto" picks from these. */
+export const SUBTITLE_TOKENS = Object.freeze(["channel", "title", "date", "clock"]);
+
+/** How the rail lays its pips (`pip.spacing`): evenly, by time, or at a fixed pitch (rail.mjs). */
+export const PIP_SPACINGS = Object.freeze(["even", "time", "pitch"]);
+
+/** The rail's pitch (`pip.pitch`, px between two pips when `spacing` is "pitch"): its bounds. */
+export const PIP_PITCH = Object.freeze([8, 200]);
+
+/** The pitch when `spacing` is "pitch" and `pip.pitch` is unset. */
+export const PIP_PITCH_DEFAULT = 28;
+
+/** When a popup's posts come up (`posts.at`): the end of their clip, or its start. */
+export const POST_AT = Object.freeze(["end", "start"]);
+/** How posts are drawn (`posts.layout`): cards at the end of a clip, or a column for the whole cut. */
+export const POST_LAYOUTS = Object.freeze(["popup", "feed"]);
+/** Where a post's QR links (`posts.links`): its page on the archive, or the platform's own link. */
+export const POST_LINKS = Object.freeze(["archive", "original"]);
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
+
+function unknownKeys(obj, allowed, where, errors) {
+ for (const k of Object.keys(obj)) {
+ if (!allowed.includes(k)) errors.push(`${where}.${k} is not a deck setting`);
+ }
+}
+
+/**
+ * A deck sub-object's check: absent passes, not an object is refused, unknown
+ * keys are refused, then `check` reads it.
+ */
+function sub(d, key, allowed, w, errors, check) {
+ if (d[key] === undefined) return;
+ if (!isObj(d[key])) { errors.push(`${w}.${key} must be an object`); return; }
+ unknownKeys(d[key], allowed, `${w}.${key}`, errors);
+ check(d[key]);
+}
+
+const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
+
+/**
+ * Every reason a `deck.markers` list cannot be drawn, its shape alone (the
+ * timeline is not in `render.chrome`: `validateDeckMarkers` checks `after`
+ * against it). validateChrome calls this.
+ *
+ * @returns {string[]}
+ */
+export function markerShapeErrors(markers, where) {
+ if (markers === undefined) return [];
+ if (!Array.isArray(markers)) return [`${where} must be a list of { after, label, color? }`];
+ const errors = [];
+ if (markers.length > MARKER_LIMITS.count) errors.push(`${where} has ${markers.length} markers (at most ${MARKER_LIMITS.count})`);
+ markers.forEach((m, i) => {
+ const at = `${where}[${i}]`;
+ if (!isObj(m)) { errors.push(`${at} must be { after, label, color? }`); return; }
+ for (const k of Object.keys(m)) {
+ if (!["after", "label", "color", "align"].includes(k)) errors.push(`${at}.${k} is not a marker setting (after, label, color, align)`);
+ }
+ if (m.align !== undefined && !MARKER_ALIGNS.includes(m.align)) {
+ errors.push(`${at}.align must be ${MARKER_ALIGNS.map((a) => `"${a}"`).join(", ")}`);
+ }
+ if (typeof m.after !== "string" || !m.after.trim()) errors.push(`${at}.after must name a clip's id`);
+ const label = typeof m.label === "string" ? m.label.trim() : "";
+ if (!label) errors.push(`${at}.label must be a word or two`);
+ else if (/[\r\n]/.test(label)) errors.push(`${at}.label must be one line`);
+ else if ([...label].length > MARKER_LIMITS.label) {
+ errors.push(`${at}.label is ${[...label].length} characters (at most ${MARKER_LIMITS.label})`);
+ }
+ if (m.color !== undefined && !(typeof m.color === "string" && (HEX_RE.test(m.color) || MARKER_PALETTE_KEYS.includes(m.color)))) {
+ errors.push(`${at}.color must be a #hex colour or one of ${MARKER_PALETTE_KEYS.join(", ")}`);
+ }
+ });
+ return errors;
+}
+
+
+// ---------------------------------------------------------------------------
+// Each module's validator: (its value, { render, chrome, deck, where }) =>
+// sentences. `deck` is `render.chrome.deck` (an object by the time these
+// run), `where` the dotted path the messages name.
+// ---------------------------------------------------------------------------
+
+/** The shell: the deck's size, ground, the title and the motion. */
+export function validateShellSettings(d, { where: w }) {
+ const errors = [];
+ if (d.height !== undefined && !(Number.isInteger(d.height) && numIn(d.height, 120, 400))) {
+ errors.push(`${w}.height must be a whole number of pixels from 120 to 400`);
+ }
+ if (d.footageScale !== undefined && !numIn(d.footageScale, 0.5, 1)) {
+ errors.push(`${w}.footageScale must be from 0.5 to 1`);
+ }
+ if (d.background !== undefined && !["panel", "flush"].includes(d.background)) {
+ errors.push(`${w}.background must be "panel" or "flush"`);
+ }
+ if (d.overCards !== undefined && !["hide", "show"].includes(d.overCards)) {
+ errors.push(`${w}.overCards must be "hide" or "show"`);
+ }
+ sub(d, "title", ["size", "maxChars"], w, errors, (t) => {
+ if (t.size !== undefined && !numIn(t.size, 24, 96)) errors.push(`${w}.title.size must be from 24 to 96`);
+ if (t.maxChars !== undefined && !(Number.isInteger(t.maxChars) && numIn(t.maxChars, 10, 120))) {
+ errors.push(`${w}.title.maxChars must be a whole number from 10 to 120`);
+ }
+ });
+ sub(d, "motion", ["out", "in", "pip"], w, errors, (m) => {
+ for (const k of ["out", "in"]) {
+ if (m[k] !== undefined && !numIn(m[k], 0, 2)) errors.push(`${w}.motion.${k} must be from 0 to 2 seconds`);
+ }
+ if (m.pip !== undefined && !numIn(m.pip, 0, 3)) errors.push(`${w}.motion.pip must be from 0 to 3 seconds`);
+ });
+ return errors;
+}
+
+/** The rail: the pips, the markers and how crowded labels lay. */
+export function validateRailSettings(d, { where: w }) {
+ const errors = [];
+ sub(d, "pip", ["spacing", "size", "activeSize", "color", "pitch"], w, errors, (p) => {
+ if (p.spacing !== undefined && !PIP_SPACINGS.includes(p.spacing)) {
+ errors.push(`${w}.pip.spacing must be "even", "time" or "pitch"`);
+ }
+ if (p.color !== undefined && !PIP_COLORS.includes(p.color)) {
+ errors.push(`${w}.pip.color must be ${PIP_COLORS.map((c) => `"${c}"`).join(" or ")}`);
+ }
+ if (p.size !== undefined && !numIn(p.size, 2, 24)) errors.push(`${w}.pip.size must be from 2 to 24`);
+ if (p.activeSize !== undefined && !numIn(p.activeSize, 2, 40)) {
+ errors.push(`${w}.pip.activeSize must be from 2 to 40`);
+ }
+ if (p.pitch !== undefined && !numIn(p.pitch, PIP_PITCH[0], PIP_PITCH[1])) {
+ errors.push(`${w}.pip.pitch must be from ${PIP_PITCH[0]} to ${PIP_PITCH[1]} pixels`);
+ }
+ const size = p.size ?? DECK_DEFAULTS.pip.size;
+ const active = p.activeSize ?? DECK_DEFAULTS.pip.activeSize;
+ if (numIn(size, 2, 24) && numIn(active, 2, 40) && active < size) {
+ errors.push(`${w}.pip.activeSize must be at least pip.size`);
+ }
+ });
+ errors.push(...markerShapeErrors(d.markers, `${w}.markers`));
+ if (d.markerLayout !== undefined && !MARKER_LAYOUTS.includes(d.markerLayout)) {
+ errors.push(`${w}.markerLayout must be ${MARKER_LAYOUTS.map((l) => `"${l}"`).join(" or ")}`);
+ }
+ return errors;
+}
+
+/** The subtitle: its parts and its date's format. */
+export function validateSubtitleSettings(d, { where: w }) {
+ const errors = [];
+ sub(d, "subtitle", ["parts", "dateFormat"], w, errors, (s) => {
+ if (s.parts !== undefined && s.parts !== "auto") {
+ const ok = Array.isArray(s.parts) && s.parts.length > 0 &&
+ s.parts.every((p) => SUBTITLE_TOKENS.includes(p)) &&
+ new Set(s.parts).size === s.parts.length;
+ if (!ok) {
+ errors.push(`${w}.subtitle.parts must be "auto" or a list of distinct ${SUBTITLE_TOKENS.join("/")}`);
+ }
+ }
+ if (s.dateFormat !== undefined && !["long", "iso"].includes(s.dateFormat)) {
+ errors.push(`${w}.subtitle.dateFormat must be "long" or "iso"`);
+ }
+ });
+ return errors;
+}
+
+/** The QR: shown, its size (inside the deck), where it links. */
+export function validateQrSettings(d, { where: w }) {
+ const errors = [];
+ sub(d, "qr", ["show", "size", "links"], w, errors, (q) => {
+ if (q.show !== undefined && typeof q.show !== "boolean") errors.push(`${w}.qr.show must be true or false`);
+ if (q.links !== undefined && !QR_LINKS.includes(q.links)) {
+ errors.push(`${w}.qr.links must be ${QR_LINKS.map((l) => `"${l}"`).join(" or ")}`);
+ }
+ if (q.size !== undefined && !numIn(q.size, 80, 380)) errors.push(`${w}.qr.size must be from 80 to 380`);
+ const h = d.height ?? DECK_DEFAULTS.height;
+ const size = q.size ?? DECK_DEFAULTS.qr.size;
+ if (numIn(size, 80, 380) && Number.isInteger(h) && size > h - 20) {
+ errors.push(`${w}.qr.size ${size} does not fit a ${h}px deck (at most ${h - 20})`);
+ }
+ });
+ return errors;
+}
+
+/** The posts (the popup cards and the feed): every `deck.posts` setting. */
+export function validatePostsSettings(d, { where: w }) {
+ const errors = [];
+ sub(d, "posts", ["show", "layout", "seconds", "hold", "position", "width", "qrSize", "maxLines", "inset", "shift", "links", "at", "shotMaxHeight", "qr"], w, errors, (p) => {
+ if (p.qr !== undefined && typeof p.qr !== "boolean") errors.push(`${w}.posts.qr must be true or false`);
+ if (p.at !== undefined && !POST_AT.includes(p.at)) {
+ errors.push(`${w}.posts.at must be ${POST_AT.map((a) => `"${a}"`).join(" or ")}`);
+ }
+ if (p.shotMaxHeight !== undefined && p.shotMaxHeight !== null &&
+ !(Number.isInteger(p.shotMaxHeight) && numIn(p.shotMaxHeight, 120, 1080))) {
+ errors.push(`${w}.posts.shotMaxHeight must be null or a whole number of pixels from 120 to 1080`);
+ }
+ if (p.layout !== undefined && !POST_LAYOUTS.includes(p.layout)) {
+ errors.push(`${w}.posts.layout must be ${POST_LAYOUTS.map((l) => `"${l}"`).join(" or ")}`);
+ }
+ if (p.links !== undefined && !POST_LINKS.includes(p.links)) {
+ errors.push(`${w}.posts.links must be ${POST_LINKS.map((l) => `"${l}"`).join(" or ")}`);
+ }
+ if (p.hold !== undefined && !numIn(p.hold, 0, 10)) errors.push(`${w}.posts.hold must be from 0 to 10 seconds`);
+ if (p.shift !== undefined && p.shift !== false) {
+ if (!isObj(p.shift)) errors.push(`${w}.posts.shift must be false or { scale, seconds }`);
+ else {
+ unknownKeys(p.shift, ["scale", "seconds"], `${w}.posts.shift`, errors);
+ if (p.shift.scale !== undefined && !numIn(p.shift.scale, 0.5, 1)) errors.push(`${w}.posts.shift.scale must be from 0.5 to 1`);
+ if (p.shift.seconds !== undefined && !numIn(p.shift.seconds, 0, 3)) errors.push(`${w}.posts.shift.seconds must be from 0 to 3`);
+ }
+ }
+ if (p.show !== undefined && typeof p.show !== "boolean") errors.push(`${w}.posts.show must be true or false`);
+ if (p.seconds !== undefined && !numIn(p.seconds, 0.5, 10)) errors.push(`${w}.posts.seconds must be from 0.5 to 10`);
+ if (p.position !== undefined && !["top-right", "top-left"].includes(p.position)) {
+ errors.push(`${w}.posts.position must be "top-right" or "top-left"`);
+ }
+ if (p.width !== undefined && !(Number.isInteger(p.width) && numIn(p.width, 320, 900))) {
+ errors.push(`${w}.posts.width must be a whole number of pixels from 320 to 900`);
+ }
+ if (p.qrSize !== undefined && !numIn(p.qrSize, 80, 200)) errors.push(`${w}.posts.qrSize must be from 80 to 200`);
+ if (p.maxLines !== undefined && !(Number.isInteger(p.maxLines) && numIn(p.maxLines, 2, 14))) {
+ errors.push(`${w}.posts.maxLines must be a whole number from 2 to 14`);
+ }
+ if (p.inset !== undefined && !numIn(p.inset, 0, 80)) errors.push(`${w}.posts.inset must be from 0 to 80`);
+ });
+ return errors;
+}
+
+/**
+ * Every module's settings, in the order validateChrome runs them: `id` the
+ * module's, `key` its path under `render.chrome` (`deck` keys are read from
+ * the deck object), `configKey` the manifest path its docs name.
+ */
+export const SETTINGS = Object.freeze([
+ // The fact-check (the stamps' settings, and the verdicts and tally the counter reads without `deck.counter`).
+ { id: "stamp", key: "factcheck", configKey: "render.chrome.factcheck",
+ validate: (v, { render }) => validateFactcheck(v, undefined, { fontBold: render.fontBold ?? null }) },
+ { id: "threads", key: "threads", configKey: "render.chrome.threads", validate: (v) => validateThreads(v) },
+ { id: "flips", key: "flips", configKey: "render.chrome.flips", validate: (v) => validateFlips(v) },
+ { id: "stats", key: "stats", configKey: "render.chrome.stats", validate: (v) => validateStats(v) },
+ { id: "fx", key: "fx", configKey: "render.chrome.fx", validate: (v) => validateFx(v) },
+ // The story modules (story-settings.mjs): then and now, the chapters, the status ledger.
+ { id: "pair", key: "pair", configKey: "render.chrome.pair", validate: (v) => validatePair(v) },
+ { id: "chapter", key: "chapter", configKey: "render.chrome.chapter", validate: (v) => validateChapter(v) },
+ { id: "status", key: "status", configKey: "render.chrome.status", validate: (v) => validateStatus(v) },
+ // From here the deck's own keys: `deck` is an object.
+ { id: "finale", key: "deck.finale", configKey: "render.chrome.deck.finale", deck: true,
+ validate: (v, { where }) => validateFinaleSettings(v, `${where}.finale`) },
+ { id: "claims", key: "deck.claims", configKey: "render.chrome.deck.claims", deck: true,
+ validate: (v, { where }) => deckClaimShapeErrors(v, `${where}.claims`) },
+ { id: "counter", key: "deck.counter", configKey: "render.chrome.deck.counter", deck: true,
+ validate: (v, { chrome, render }) => validateCounter(v, {
+ factcheck: chrome.factcheck, labelFits: (s, where) => counterLabelProblem(s, where, { fontBold: render.fontBold ?? null }),
+ }) },
+ { id: "shell", key: "deck", configKey: "render.chrome.deck", deck: true, whole: true, validate: validateShellSettings },
+ { id: "rail", key: "deck", configKey: "render.chrome.deck.pip", deck: true, whole: true, validate: validateRailSettings },
+ { id: "subtitle", key: "deck", configKey: "render.chrome.deck.subtitle", deck: true, whole: true, validate: validateSubtitleSettings },
+ { id: "qr", key: "deck", configKey: "render.chrome.deck.qr", deck: true, whole: true, validate: validateQrSettings },
+ { id: "popup-posts", key: "deck", configKey: "render.chrome.deck.posts", deck: true, whole: true, validate: validatePostsSettings },
+].map((s) => Object.freeze(s)));
+
+/** A module's settings entry, or undefined. */
+export const settingsOf = (id) => SETTINGS.find((s) => s.id === id);
+
+/** The value a SETTINGS entry reads from `render.chrome`. */
+export function settingValue(chrome, entry) {
+ if (entry.whole) return chrome.deck ?? {};
+ return entry.key.split(".").reduce((o, k) => (isObj(o) ? o[k] : undefined), chrome);
+}
diff --git a/umtool/report-to-video/modules/shell.mjs b/umtool/report-to-video/modules/shell.mjs
@@ -0,0 +1,75 @@
+// THE SHELL (module `shell`, region `deck`): the deck's one page at the foot
+// of the frame -- its panel and title, and the band its parts draw in: the
+// subtitle (subtitle.mjs), the QR (qr.mjs), the rail (rail.mjs), the counter
+// (counter.mjs) and the claim checks (claims.mjs) are parts of this page, so
+// their frames are the shell's. chrome-deck.mjs writes the page; deck.mjs
+// holds its arithmetic.
+import path from "node:path";
+
+import { deckGeometry, deckLayout } from "../deck.mjs";
+import { deckHtml } from "../chrome-deck.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { DECK_DEFAULTS, settingsOf } from "./settings.mjs";
+
+export default defineModule({
+ id: "shell",
+ version: 1,
+ z: 10,
+ kind: "overlay-whole",
+ slot: "footer",
+ title: "Deck",
+ summary: "The panel at the foot of the frame: each clip's title, and the band the subtitle, QR, rail and counter draw in.",
+ configKey: "render.chrome.deck",
+ defaults: {
+ height: DECK_DEFAULTS.height, footageScale: DECK_DEFAULTS.footageScale, background: DECK_DEFAULTS.background,
+ overCards: DECK_DEFAULTS.overCards, title: DECK_DEFAULTS.title, motion: DECK_DEFAULTS.motion,
+ },
+ validate: settingsOf("shell").validate,
+ ui: [
+ { key: "height", type: "number", min: 120, max: 400, label: "Deck height (px)", default: DECK_DEFAULTS.height },
+ { key: "footageScale", type: "number", min: 0.5, max: 1, step: 0.01, label: "Footage scale", default: DECK_DEFAULTS.footageScale },
+ { key: "background", type: "enum", options: ["panel", "flush"], label: "Ground", default: DECK_DEFAULTS.background },
+ { key: "overCards", type: "enum", options: ["hide", "show"], label: "Over cards", default: DECK_DEFAULTS.overCards },
+ { key: "title.size", type: "number", min: 24, max: 96, label: "Title size", default: DECK_DEFAULTS.title.size },
+ { key: "title.maxChars", type: "number", min: 10, max: 120, label: "Title characters", default: DECK_DEFAULTS.title.maxChars },
+ { key: "motion.out", type: "number", min: 0, max: 2, step: 0.05, label: "Text out (s)", default: DECK_DEFAULTS.motion.out },
+ { key: "motion.in", type: "number", min: 0, max: 2, step: 0.05, label: "Text in (s)", default: DECK_DEFAULTS.motion.in },
+ { key: "motion.pip", type: "number", min: 0, max: 3, step: 0.05, label: "Marker move (s)", default: DECK_DEFAULTS.motion.pip },
+ ],
+ docs: {
+ heading: "Deck (the shell)",
+ intro: "The panel at the foot of the frame and each clip's title (`render.chrome.deck`); its parts -- the subtitle, the QR, the rail, the counter, the claim checks -- are their own modules below.",
+ rows: [
+ ["`deck.height`", "120–400 px · default 190", "`umtool look <p> deck.height=210`"],
+ ["`deck.footageScale`", "0.5–1 (the footage must fit above the deck) · default 0.82", "`umtool look <p> deck.footageScale=0.8`"],
+ ["`deck.background`", "`panel` · `flush` · default `panel`", "`umtool look <p> deck.background=flush`"],
+ ["`deck.overCards`", "`hide` (the deck slides away over a card) · `show` · default `hide`", "`umtool look <p> deck.overCards=show`"],
+ ["`deck.title`", "`{size 24–96, maxChars 10–120}` · default 54, 48", "`umtool look <p> deck.title='{\"size\":60}'`"],
+ ["`deck.motion`", "`{out 0–2, in 0–2, pip 0–3}` s · default 0.3, 0.45, 0.7", "`umtool look <p> deck.motion='{\"in\":0.6}'`"],
+ ],
+ },
+ region: "deck",
+ workers: "wide",
+ noun: "the deck's",
+ on: () => true,
+ async page(ctx) {
+ const { render, schedule } = ctx;
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ // With the schedule: a staggered marker band moves the QR down and may shrink it.
+ const lay = deckLayout(render, { schedule });
+ const qrSrcs = {};
+ if (lay.qr) {
+ const byUrl = await ctx.qrs(schedule.segments.map((s) => s.qrUrl), lay.qr.size);
+ for (const s of schedule.segments) if (s.qrUrl) qrSrcs[s.id] = byUrl.get(s.qrUrl);
+ }
+ // Its items -- each segment's text, each pip -- go to the frame keys.
+ const items = [];
+ const html = deckHtml(schedule, render, { fonts, qrSrcs, from: ctx.from, duration: ctx.duration, items });
+ return { html, items };
+ },
+ regions(_schedule, { render, outDir, frames = null }) {
+ const { deck } = deckGeometry(render);
+ return [assertRegion({ name: "deck", frames: frames ?? path.join(outDir, "chrome", "deck-frames"), ...deck })];
+ },
+ frameKeys: { data: "deck-data", omit: ["init", "cues", "window", "total", "ids"] },
+});
diff --git a/umtool/report-to-video/modules/stamp.mjs b/umtool/report-to-video/modules/stamp.mjs
@@ -0,0 +1,66 @@
+// THE STAMPS (module `stamp`, region `stamp`): each counted mark's word
+// stamped over the footage as it lands (`render.chrome.factcheck.stamp`).
+// chrome-stamp.mjs writes the page; factcheck.mjs `stampSchedule` times it.
+import path from "node:path";
+
+import { stampGeometry } from "../deck.mjs";
+import { stampHtml } from "../chrome-stamp.mjs";
+import { stampsDrawn } from "../factcheck.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { FACTCHECK_DEFAULTS, FACTCHECK_LIMITS, STAMP_MOTIONS, STAMP_POSITIONS } from "../factcheck.mjs";
+import { settingsOf } from "./settings.mjs";
+
+export default defineModule({
+ id: "stamp",
+ version: 1,
+ z: 40,
+ kind: "overlay-whole",
+ slot: "stamp",
+ title: "Stamps",
+ summary: "Each counted mark's word, stamped over the footage as it lands.",
+ configKey: "render.chrome.factcheck.stamp",
+ defaults: FACTCHECK_DEFAULTS.stamp,
+ validate: settingsOf("stamp").validate,
+ deps: ["counter.series"],
+ ui: [
+ { key: "show", type: "boolean", label: "Draw the stamps", default: true },
+ { key: "seconds", type: "number", min: FACTCHECK_LIMITS.seconds[0], max: FACTCHECK_LIMITS.seconds[1], step: 0.5, label: "Seconds", default: 3 },
+ { key: "position", type: "enum", options: STAMP_POSITIONS, label: "Corner", default: "top-left" },
+ { key: "scale", type: "number", min: FACTCHECK_LIMITS.scale[0], max: FACTCHECK_LIMITS.scale[1], step: 0.05, label: "Scale", default: 1 },
+ { key: "motion", type: "enum", options: STAMP_MOTIONS, label: "Motion", default: "slam" },
+ { key: "opacity", type: "number", min: FACTCHECK_LIMITS.opacity[0], max: FACTCHECK_LIMITS.opacity[1], step: 0.05, label: "Opacity", default: 1 },
+ ],
+ docs: {
+ heading: "Stamps",
+ intro: "Each counted mark's word stamped over the footage as it lands (`render.chrome.factcheck.stamp`); the word is the mark's `label`, else its series' `stampLabel`, else its label.",
+ rows: [
+ ["`factcheck.stamp.show`", "bool · default `true` (`false`: nothing drawn, the counter still counts)", "`umtool look <p> factcheck.stamp.show=false`"],
+ ["`factcheck.stamp.seconds`", `${FACTCHECK_LIMITS.seconds[0]}–${FACTCHECK_LIMITS.seconds[1]} s · default 3`, "`umtool look <p> factcheck.stamp.seconds=4`"],
+ ["`factcheck.stamp.position`", `${STAMP_POSITIONS.map((p) => `\`${p}\``).join(" ")} · default \`top-left\``, "`umtool look <p> factcheck.stamp.position=center`"],
+ ["`factcheck.stamp.scale`, `.motion`, `.opacity`", "0.5–2 · `slam` `pop` `fade` `none` · 0.3–1 · default 1, `slam`, 1", "`umtool look <p> factcheck.stamp.motion=pop`"],
+ ],
+ },
+ region: "stamp",
+ workers: "narrow",
+ noun: "the stamps'",
+ on: (schedule, render) => stampsDrawn(schedule, render),
+ check(schedule, render) {
+ if (!schedule.factcheck?.stamps?.length) return "the stamp region needs a schedule that stamps a claim (an entry with a `claim`)";
+ if (!stampsDrawn(schedule, render)) {
+ return "the stamps are off (render.chrome.factcheck.stamp.show: false): there is no stamp region to compose";
+ }
+ return null;
+ },
+ async page(ctx) {
+ // The fact-check stamps (chrome-stamp.mjs): the deck's faces, no QR.
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ return stampHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration });
+ },
+ regions(schedule, { render, outDir, frames = null }) {
+ return [assertRegion({
+ name: "stamp", frames: frames ?? path.join(outDir, "chrome", "stamp-frames"),
+ ...stampGeometry(render, { feed: schedule.layout === "feed" }),
+ })];
+ },
+ frameKeys: { data: "stamp-data", omit: ["init", "cues", "window", "total", "ids"] },
+});
diff --git a/umtool/report-to-video/modules/stats.mjs b/umtool/report-to-video/modules/stats.mjs
@@ -0,0 +1,49 @@
+// THE STATS (module `stats`, region `stats`): a frame scan's running numbers
+// over the clips that declare them, in a panel in the footage
+// (`render.chrome.stats`, stats.mjs). chrome-stats.mjs writes the page.
+import path from "node:path";
+
+import { statsGeometry } from "../deck.mjs";
+import { statsHtml } from "../chrome-stats.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { settingsOf } from "./settings.mjs";
+
+export default defineModule({
+ id: "stats",
+ version: 1,
+ z: 50,
+ kind: "overlay-whole",
+ slot: "panel",
+ title: "Stats",
+ summary: "A frame scan's running numbers over the clips that declare them.",
+ validate: settingsOf("stats").validate,
+ docs: {
+ heading: "Stats",
+ intro: "A frame scan’s running numbers over the clips that declare them, in a panel in the footage (`render.chrome.stats`, stats.mjs).",
+ rows: [
+ ["`render.chrome.stats.position`", "`top-left` `top-right` `bottom-left` `bottom-right` · default `bottom-left`", "manifest"],
+ ["`render.chrome.stats.fields`, `.name`", "a list of `stack` `stackBB` `playersLeft` `level`; bool · default all, `true`", "manifest"],
+ ],
+ },
+ region: "stats",
+ workers: "narrow",
+ noun: "the stats region's",
+ configKey: "render.chrome.stats",
+ on: (schedule) => !!schedule?.stats?.clips?.length,
+ check: (schedule) => (!schedule.stats?.clips?.length
+ ? "the stats region needs a schedule with a clip that declares it (render.chrome.stats or a clip's stats, and frameScan.overlay points)"
+ : null),
+ async page(ctx) {
+ // The stats region (chrome-stats.mjs): the deck's faces, no QR.
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ return statsHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration });
+ },
+ regions(schedule, { render, outDir, frames = null }) {
+ return [assertRegion({
+ name: "stats", frames: frames ?? path.join(outDir, "chrome", "stats-frames"),
+ ...statsGeometry(render, { feed: schedule.layout === "feed" }),
+ })];
+ },
+ // A cue interpreter like the deck's: keyed per frame (frame-keys.mjs).
+ frameKeys: { data: "stats-data", omit: ["init", "cues", "window", "total", "ids"] },
+});
diff --git a/umtool/report-to-video/modules/status.mjs b/umtool/report-to-video/modules/status.mjs
@@ -0,0 +1,69 @@
+// THE STATUS LEDGER (module `status`, region `status`): a row per item --
+// "announced 12 Mar 2022 → no follow-up found" -- in a column in a corner of
+// the footage box that fills as the cut plays (`render.chrome.status`): a
+// row comes in on its first clip, its outcome on the outcome's clip (else at
+// the end of its last). chrome-story.mjs writes the page.
+import path from "node:path";
+
+import { resolveStatus, statusGeometry, statusHtml, statusRows } from "../chrome-story.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { STATUS_DEFAULTS, STATUS_LIMITS, STATUS_MODES, STATUS_POSITIONS, validateStatus } from "./story-settings.mjs";
+
+export default defineModule({
+ id: "status",
+ version: 1,
+ z: 55,
+ kind: "overlay-whole",
+ slot: "footage",
+ title: "Status ledger",
+ summary: "A row per item -- announced, then followed up or not -- filling a column as the cut plays.",
+ configKey: "render.chrome.status",
+ defaults: STATUS_DEFAULTS,
+ validate: (v) => validateStatus(v),
+ resolve: resolveStatus,
+ ui: [
+ { key: "title", type: "text", label: "Heading", default: STATUS_DEFAULTS.title },
+ { key: "mode", type: "enum", options: STATUS_MODES, label: "Rows", default: "fill" },
+ { key: "position", type: "enum", options: STATUS_POSITIONS, label: "Corner", default: "top-right" },
+ { key: "rows", type: "number", min: STATUS_LIMITS.rows[0], max: STATUS_LIMITS.rows[1], label: "Rows shown", default: 4 },
+ { key: "width", type: "number", min: STATUS_LIMITS.width[0], max: STATUS_LIMITS.width[1], label: "Width (px)", default: 640 },
+ { key: "items", type: "list", label: "Items", item: [
+ { key: "item", type: "text", label: "Item" },
+ { key: "announced.clip", type: "clip", label: "Announced in" },
+ { key: "announced.date", type: "date", label: "Announced on" },
+ { key: "announced.text", type: "text", label: "Announced (words)" },
+ { key: "outcome.clip", type: "clip", label: "Outcome in" },
+ { key: "outcome.date", type: "date", label: "Outcome on" },
+ { key: "outcome.text", type: "text", label: "Outcome" },
+ ] },
+ ],
+ docs: {
+ heading: "Status ledger",
+ intro: "A ledger of items, each announced and then followed up -- or not (`render.chrome.status`, chrome-story.mjs): a column in a corner of the footage box that fills as the cut plays. A row comes in on its first clip (its announcement's, else its first evidence clip); its outcome is written on the outcome's clip, else at the end of its last clip. `fill` keeps the last `rows` rows up from the first on; `each` shows a row alone over its own clips.",
+ rows: [
+ ["`chrome.status.items[]`", `1–${STATUS_LIMITS.items} \`{item ≤${STATUS_LIMITS.item}, announced: words | {clip?, date?, text?}, outcome?: words | {clip?, date?, text?}, evidence?: [clip…]}\` -- at least one clip named`, "`umtool modules apply <p> --config module-config.json` · `umtool look <p> status='{…}'`"],
+ ["`chrome.status.mode`", "`fill` · `each` · default `fill`", "`umtool look <p> status.mode=each`"],
+ ["`chrome.status.position`, `.rows`, `.width`, `.title`", `a corner of the footage box · ${STATUS_LIMITS.rows.join("–")} · ${STATUS_LIMITS.width.join("–")} px · ≤${STATUS_LIMITS.title} · default \`top-right\`, 4, 640, "On the record"`, "`umtool look <p> status.position=bottom-left`"],
+ ],
+ },
+ region: "status",
+ workers: "narrow",
+ noun: "the status ledger's",
+ on: (schedule, render) => !!schedule?.segments && statusRows(schedule, render).length > 0,
+ check: (schedule, render) => (statusRows(schedule, render).length
+ ? null
+ : "the status region needs render.chrome.status with an item whose clips the cut plays"),
+ async page(ctx) {
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ return statusHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration });
+ },
+ regions(schedule, { render, outDir, frames = null }) {
+ return [assertRegion({
+ name: "status", frames: frames ?? path.join(outDir, "chrome", "status-frames"),
+ ...statusGeometry(render, { feed: schedule.layout === "feed" }),
+ })];
+ },
+ preview: (_slice, { render }) => ({ region: "status", geometry: statusGeometry(render) }),
+ // A cue interpreter: each state of the ledger an item, keyed only where it is shown.
+ frameKeys: { data: "status-data", omit: ["init", "cues", "window", "total", "ids"] },
+});
diff --git a/umtool/report-to-video/modules/story-settings.mjs b/umtool/report-to-video/modules/story-settings.mjs
@@ -0,0 +1,210 @@
+// THE STORY MODULES' SETTINGS (release 39): `pair` (then and now, two clips
+// with their dates), `chapter` (a section bumper at a named clip) and
+// `status` (a ledger of items, each announced and then followed up -- or
+// not). Their defaults and validators -- the one copy, a LEAF like
+// settings.mjs (deck.mjs imports it through SETTINGS, so it imports nothing
+// that imports deck.mjs).
+//
+// render.chrome.pair { style, position, dateFormat, labels, seconds, pairs: [...] }
+// render.chrome.chapter { seconds, style, list: [...] }
+// render.chrome.status { title, position, rows, width, mode, items: [...] }
+//
+// A clip is named by its timeline id; whether it is in the cut is checked
+// where the timeline is known (`storyClipErrors`, the writers), not here.
+
+/** A YYYY / YYYY-MM / YYYY-MM-DD date. */
+export const DATE_RE = /^\d{4}(?:-(?:0[1-9]|1[0-2])(?:-(?:0[1-9]|[12]\d|3[01]))?)?$/;
+const CLIP_RE = /^[A-Za-z0-9_.:-]{1,80}$/;
+
+export const PAIR_STYLES = Object.freeze(["split", "then→now"]);
+export const PAIR_POSITIONS = Object.freeze(["bottom", "top"]);
+export const DATE_FORMATS = Object.freeze(["long", "year", "iso"]);
+export const PAIR_SIDES = Object.freeze(["then", "now"]);
+export const PAIR_LIMITS = Object.freeze({ pairs: 60, caption: 200, topic: 60, label: 16, also: 4, seconds: [1, 10] });
+export const PAIR_DEFAULTS = Object.freeze({
+ style: "split", position: "bottom", dateFormat: "long",
+ labels: Object.freeze({ then: "Then", now: "Now" }), seconds: 4, pairs: Object.freeze([]),
+});
+
+export const CHAPTER_STYLES = Object.freeze(["card", "lower"]);
+export const CHAPTER_LIMITS = Object.freeze({ list: 40, title: 48, subtitle: 90, seconds: [1, 8] });
+export const CHAPTER_DEFAULTS = Object.freeze({ seconds: 3, style: "card", list: Object.freeze([]) });
+
+export const STATUS_POSITIONS = Object.freeze(["top-right", "top-left", "bottom-right", "bottom-left"]);
+export const STATUS_MODES = Object.freeze(["fill", "each"]);
+export const STATUS_LIMITS = Object.freeze({ items: 30, item: 140, text: 160, title: 40, rows: [1, 8], width: [360, 900], evidence: 12 });
+export const STATUS_DEFAULTS = Object.freeze({
+ title: "On the record", position: "top-right", rows: 4, width: 640, mode: "fill", items: Object.freeze([]),
+});
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
+const str = (v) => typeof v === "string" && v.trim().length > 0;
+
+function unknown(obj, allowed, where, errors) {
+ for (const k of Object.keys(obj)) if (!allowed.includes(k)) errors.push(`${where}.${k} is not a setting (${allowed.join(", ")})`);
+}
+
+function text(v, max, where, errors, { required = false } = {}) {
+ if (v === undefined) {
+ if (required) errors.push(`${where} is required`);
+ return;
+ }
+ if (typeof v !== "string" || (required && !v.trim())) { errors.push(`${where} must be words`); return; }
+ if ([...v].length > max) errors.push(`${where} is ${[...v].length} characters (at most ${max})`);
+}
+
+function clip(v, where, errors) {
+ if (typeof v !== "string" || !CLIP_RE.test(v)) errors.push(`${where} must name a clip by its timeline id`);
+}
+
+function date(v, where, errors) {
+ if (v === undefined || v === null) return;
+ if (typeof v !== "string" || !DATE_RE.test(v)) errors.push(`${where} must be a date: YYYY, YYYY-MM or YYYY-MM-DD`);
+}
+
+/** Every reason `render.chrome.pair` cannot be drawn (its shape; the clips against the timeline in storyClipErrors). */
+export function validatePair(v, where = "render.chrome.pair") {
+ if (v === undefined) return [];
+ if (!isObj(v)) return [`${where} must be an object`];
+ const errors = [];
+ unknown(v, ["style", "position", "dateFormat", "labels", "seconds", "pairs"], where, errors);
+ if (v.style !== undefined && !PAIR_STYLES.includes(v.style)) errors.push(`${where}.style must be ${PAIR_STYLES.map((s) => `"${s}"`).join(" or ")}`);
+ if (v.position !== undefined && !PAIR_POSITIONS.includes(v.position)) errors.push(`${where}.position must be "bottom" or "top"`);
+ if (v.dateFormat !== undefined && !DATE_FORMATS.includes(v.dateFormat)) errors.push(`${where}.dateFormat must be ${DATE_FORMATS.join(", ")}`);
+ if (v.seconds !== undefined && !numIn(v.seconds, ...PAIR_LIMITS.seconds)) errors.push(`${where}.seconds must be from ${PAIR_LIMITS.seconds[0]} to ${PAIR_LIMITS.seconds[1]}`);
+ if (v.labels !== undefined) {
+ if (!isObj(v.labels)) errors.push(`${where}.labels must be { then, now }`);
+ else {
+ unknown(v.labels, ["then", "now"], `${where}.labels`, errors);
+ for (const s of PAIR_SIDES) text(v.labels[s], PAIR_LIMITS.label, `${where}.labels.${s}`, errors);
+ }
+ }
+ if (v.pairs === undefined) return errors;
+ if (!Array.isArray(v.pairs)) return [...errors, `${where}.pairs must be a list`];
+ if (v.pairs.length > PAIR_LIMITS.pairs) errors.push(`${where}.pairs has ${v.pairs.length} (at most ${PAIR_LIMITS.pairs})`);
+ v.pairs.forEach((p, i) => {
+ const w = `${where}.pairs[${i}]`;
+ if (!isObj(p)) { errors.push(`${w} must be { then, now, caption? }`); return; }
+ unknown(p, ["then", "now", "caption", "topic", "style", "also"], w, errors);
+ for (const s of PAIR_SIDES) {
+ const side = p[s];
+ if (!isObj(side)) { errors.push(`${w}.${s} must be { clip, date? }`); continue; }
+ unknown(side, ["clip", "date", "label"], `${w}.${s}`, errors);
+ clip(side.clip, `${w}.${s}.clip`, errors);
+ date(side.date, `${w}.${s}.date`, errors);
+ text(side.label, PAIR_LIMITS.label, `${w}.${s}.label`, errors);
+ }
+ text(p.caption, PAIR_LIMITS.caption, `${w}.caption`, errors);
+ text(p.topic, PAIR_LIMITS.topic, `${w}.topic`, errors);
+ if (p.style !== undefined && !PAIR_STYLES.includes(p.style)) errors.push(`${w}.style must be ${PAIR_STYLES.map((s) => `"${s}"`).join(" or ")}`);
+ if (p.also !== undefined) {
+ if (!Array.isArray(p.also) || p.also.length > PAIR_LIMITS.also) errors.push(`${w}.also must be a list of at most ${PAIR_LIMITS.also} { clip, side, date? }`);
+ else p.also.forEach((a, j) => {
+ const aw = `${w}.also[${j}]`;
+ if (!isObj(a)) { errors.push(`${aw} must be { clip, side, date? }`); return; }
+ unknown(a, ["clip", "side", "date"], aw, errors);
+ clip(a.clip, `${aw}.clip`, errors);
+ if (!PAIR_SIDES.includes(a.side)) errors.push(`${aw}.side must be "then" or "now"`);
+ date(a.date, `${aw}.date`, errors);
+ });
+ }
+ });
+ return errors;
+}
+
+/** Every reason `render.chrome.chapter` cannot be drawn. */
+export function validateChapter(v, where = "render.chrome.chapter") {
+ if (v === undefined) return [];
+ if (!isObj(v)) return [`${where} must be an object`];
+ const errors = [];
+ unknown(v, ["seconds", "style", "list"], where, errors);
+ if (v.seconds !== undefined && !numIn(v.seconds, ...CHAPTER_LIMITS.seconds)) errors.push(`${where}.seconds must be from ${CHAPTER_LIMITS.seconds[0]} to ${CHAPTER_LIMITS.seconds[1]}`);
+ if (v.style !== undefined && !CHAPTER_STYLES.includes(v.style)) errors.push(`${where}.style must be "card" or "lower"`);
+ if (v.list === undefined) return errors;
+ if (!Array.isArray(v.list)) return [...errors, `${where}.list must be a list`];
+ if (v.list.length > CHAPTER_LIMITS.list) errors.push(`${where}.list has ${v.list.length} (at most ${CHAPTER_LIMITS.list})`);
+ const seen = new Set();
+ v.list.forEach((c, i) => {
+ const w = `${where}.list[${i}]`;
+ if (!isObj(c)) { errors.push(`${w} must be { at, title, subtitle?, date? }`); return; }
+ unknown(c, ["at", "title", "subtitle", "date"], w, errors);
+ clip(c.at, `${w}.at`, errors);
+ if (seen.has(c.at)) errors.push(`${w}.at: ${c.at} already opens a chapter`);
+ seen.add(c.at);
+ text(c.title, CHAPTER_LIMITS.title, `${w}.title`, errors, { required: true });
+ text(c.subtitle, CHAPTER_LIMITS.subtitle, `${w}.subtitle`, errors);
+ date(c.date, `${w}.date`, errors);
+ });
+ return errors;
+}
+
+function statusSide(v, where, errors) {
+ if (v === undefined) return;
+ if (typeof v === "string") { text(v, STATUS_LIMITS.text, where, errors); return; }
+ if (!isObj(v)) { errors.push(`${where} must be words or { clip?, date?, text? }`); return; }
+ unknown(v, ["clip", "date", "text"], where, errors);
+ if (v.clip !== undefined) clip(v.clip, `${where}.clip`, errors);
+ date(v.date, `${where}.date`, errors);
+ text(v.text, STATUS_LIMITS.text, `${where}.text`, errors);
+}
+
+/** Every reason `render.chrome.status` cannot be drawn. */
+export function validateStatus(v, where = "render.chrome.status") {
+ if (v === undefined) return [];
+ if (!isObj(v)) return [`${where} must be an object`];
+ const errors = [];
+ unknown(v, ["title", "position", "rows", "width", "mode", "items"], where, errors);
+ text(v.title, STATUS_LIMITS.title, `${where}.title`, errors);
+ if (v.position !== undefined && !STATUS_POSITIONS.includes(v.position)) errors.push(`${where}.position must be ${STATUS_POSITIONS.join(", ")}`);
+ if (v.mode !== undefined && !STATUS_MODES.includes(v.mode)) errors.push(`${where}.mode must be "fill" or "each"`);
+ if (v.rows !== undefined && !(Number.isInteger(v.rows) && numIn(v.rows, ...STATUS_LIMITS.rows))) errors.push(`${where}.rows must be a whole number from ${STATUS_LIMITS.rows[0]} to ${STATUS_LIMITS.rows[1]}`);
+ if (v.width !== undefined && !(Number.isInteger(v.width) && numIn(v.width, ...STATUS_LIMITS.width))) errors.push(`${where}.width must be a whole number of pixels from ${STATUS_LIMITS.width[0]} to ${STATUS_LIMITS.width[1]}`);
+ if (v.items === undefined) return errors;
+ if (!Array.isArray(v.items)) return [...errors, `${where}.items must be a list`];
+ if (v.items.length > STATUS_LIMITS.items) errors.push(`${where}.items has ${v.items.length} (at most ${STATUS_LIMITS.items})`);
+ v.items.forEach((it, i) => {
+ const w = `${where}.items[${i}]`;
+ if (!isObj(it)) { errors.push(`${w} must be { item, announced, outcome?, evidence? }`); return; }
+ unknown(it, ["item", "announced", "outcome", "evidence"], w, errors);
+ text(it.item, STATUS_LIMITS.item, `${w}.item`, errors, { required: true });
+ statusSide(it.announced, `${w}.announced`, errors);
+ statusSide(it.outcome, `${w}.outcome`, errors);
+ if (it.evidence !== undefined) {
+ if (!Array.isArray(it.evidence) || it.evidence.length > STATUS_LIMITS.evidence) errors.push(`${w}.evidence must be a list of at most ${STATUS_LIMITS.evidence} clip ids`);
+ else it.evidence.forEach((c, j) => clip(c, `${w}.evidence[${j}]`, errors));
+ }
+ const clips = [typeof it.announced === "object" ? it.announced?.clip : undefined, typeof it.outcome === "object" ? it.outcome?.clip : undefined, ...(it.evidence ?? [])];
+ if (!clips.some((c) => typeof c === "string")) errors.push(`${w} names no clip (announced.clip, outcome.clip or evidence): it would never be shown`);
+ });
+ return errors;
+}
+
+/** The clips a story module's settings name, each with the path that names it. */
+export function storyClips(chrome) {
+ const out = [];
+ const c = isObj(chrome) ? chrome : {};
+ (Array.isArray(c.pair?.pairs) ? c.pair.pairs : []).forEach((p, i) => {
+ for (const s of PAIR_SIDES) if (isObj(p?.[s])) out.push([`render.chrome.pair.pairs[${i}].${s}.clip`, p[s].clip]);
+ (Array.isArray(p?.also) ? p.also : []).forEach((a, j) => out.push([`render.chrome.pair.pairs[${i}].also[${j}].clip`, a?.clip]));
+ });
+ (Array.isArray(c.chapter?.list) ? c.chapter.list : []).forEach((ch, i) => out.push([`render.chrome.chapter.list[${i}].at`, ch?.at]));
+ (Array.isArray(c.status?.items) ? c.status.items : []).forEach((it, i) => {
+ for (const s of ["announced", "outcome"]) if (isObj(it?.[s]) && it[s].clip !== undefined) out.push([`render.chrome.status.items[${i}].${s}.clip`, it[s].clip]);
+ (Array.isArray(it?.evidence) ? it.evidence : []).forEach((e, j) => out.push([`render.chrome.status.items[${i}].evidence[${j}]`, e]));
+ });
+ return out.filter(([, id]) => typeof id === "string");
+}
+
+/**
+ * The clips the story modules name that the timeline does not hold: a
+ * sentence each. What a writer refuses with (a chapter at a clip that is not
+ * in the cut would never be drawn). The build tolerates them -- a variant or
+ * an --only build plays fewer clips -- and draws what is there.
+ */
+export function storyClipErrors(manifest) {
+ const ids = new Set((manifest?.timeline ?? []).map((e) => e?.id));
+ return storyClips(manifest?.render?.chrome)
+ .filter(([, id]) => !ids.has(id))
+ .map(([where, id]) => `${where}: no timeline entry is ${id}`);
+}
diff --git a/umtool/report-to-video/modules/story.test.mjs b/umtool/report-to-video/modules/story.test.mjs
@@ -0,0 +1,143 @@
+// The story modules -- pair, chapter, status: their settings, schedules,
+// pages and frame keys, over a synthetic deck schedule.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { frameKeys } from "../frame-keys.mjs";
+import { chapterHtml, chapterWindows, pairHtml, pairSchedule, statusHtml, statusRows, statusStates } from "../chrome-story.mjs";
+import { validateChrome } from "../deck.mjs";
+import { moduleById, moduleProblems } from "./index.mjs";
+import { storyClipErrors, validateChapter, validatePair, validateStatus } from "./story-settings.mjs";
+
+const FPS = 30;
+const segs = [["a", 0, 10], ["b", 10, 20], ["c", 20, 30], ["d", 30, 45]];
+const schedule = {
+ kind: "deck", fps: FPS, total: 45, transition: 0.5,
+ segments: segs.map(([id, start, end]) => ({ id, type: "clip", start, end, duration: end - start, title: id, subtitle: "" })),
+};
+const palette = { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" };
+const render = (chrome) => ({ width: 1920, height: 1080, fps: FPS, palette, chrome: { engine: "hyperframes", layout: "deck", ...chrome } });
+
+const PAIR = { pairs: [
+ { then: { clip: "a", date: "2012-09-29" }, now: { clip: "b", date: "2026-02-27" }, caption: "The same opening, renamed.", topic: "How he opens" },
+ { then: { clip: "c", date: "2019" }, now: { clip: "zz", date: "2026-03" }, caption: "Only the then-clip is in this cut." },
+] };
+const CHAPTER = { list: [{ at: "a", title: "Indy", subtitle: "Labrador" }, { at: "c", title: "Huck", date: "2020-10" }, { at: "nope", title: "Gone" }] };
+const STATUS = { items: [
+ { item: "Wizards of the Coast", announced: { clip: "a", date: "2017-12-08" }, outcome: { clip: "c", date: "2018-01-04", text: "decided not to sue" }, evidence: ["a", "b", "c"] },
+ { item: "CNET", announced: { clip: "b", date: "2019-06-03" }, outcome: "no follow-up found in the archive", evidence: ["b"] },
+] };
+
+test("settings: the shapes the module configs use are accepted, mistakes refused", () => {
+ assert.deepEqual(validatePair(PAIR), []);
+ assert.deepEqual(validateChapter(CHAPTER), []);
+ assert.deepEqual(validateStatus(STATUS), []);
+ assert.match(validatePair({ pairs: [{ then: { clip: "a", date: "Sept 2012" }, now: { clip: "b" } }] }).join(), /date/);
+ assert.match(validatePair({ style: "diagonal" }).join(), /style/);
+ assert.match(validateChapter({ list: [{ at: "a" }] }).join(), /title is required/);
+ assert.match(validateChapter({ list: [{ at: "a", title: "x" }, { at: "a", title: "y" }] }).join(), /already opens/);
+ assert.match(validateStatus({ items: [{ item: "x", announced: "words only" }] }).join(), /names no clip/);
+ assert.match(validateStatus({ items: [], rows: 12 }).join(), /rows/);
+});
+
+test("validateChrome takes the three keys, and refuses through them", () => {
+ assert.deepEqual(validateChrome(render({ pair: PAIR, chapter: CHAPTER, status: STATUS }).chrome, render({})), []);
+ assert.match(validateChrome(render({ chapter: { list: [{ at: "a" }] } }).chrome, render({})).join(), /chapter\.list\[0\]\.title/);
+ const problems = moduleProblems({ render: render({ status: { items: [{ item: "x" }] } }) });
+ assert.ok(problems.status?.length);
+});
+
+test("storyClipErrors names clips the timeline does not hold", () => {
+ const m = { timeline: [{ id: "a" }, { id: "b" }, { id: "c" }], render: render({ pair: PAIR, chapter: CHAPTER }) };
+ const errs = storyClipErrors(m);
+ assert.ok(errs.some((e) => e.includes("zz")));
+ assert.ok(errs.some((e) => e.includes("nope")));
+ assert.equal(errs.length, 2);
+});
+
+test("pair: a pair is up over its clips, each side lit while its clip plays", () => {
+ const r = render({ pair: PAIR });
+ const ps = pairSchedule(schedule, r);
+ assert.equal(ps.length, 2);
+ assert.deepEqual(ps[0].spans, [{ in: 0, out: 20 }]);
+ assert.deepEqual(ps[0].phases.map((p) => p.side), ["then", "now"]);
+ assert.deepEqual(ps[1].phases.map((p) => p.side), ["then"]);
+ const { html, items } = pairHtml(schedule, r, {});
+ assert.match(html, /29 Sep 2012/);
+ assert.match(html, /Feb 2026/);
+ assert.equal(items.length, 2);
+ for (const it of items) assert.ok(html.includes(it.html));
+ assert.ok(moduleById("pair").on(schedule, r));
+ assert.ok(!moduleById("pair").on(schedule, render({})));
+});
+
+test("pair: then→now draws a card over the pair's first seconds", () => {
+ const r = render({ pair: { ...PAIR, style: "then→now", seconds: 3 } });
+ const { html } = pairHtml(schedule, r, {});
+ assert.match(html, /class="arrow"/);
+});
+
+test("pair frame keys: frames off a pair's span share a key; a caption changed recaptures only its pair's frames", () => {
+ const r = render({ pair: PAIR });
+ const frames = 45 * FPS;
+ const keysOf = (rr) => {
+ const { html, items } = pairHtml(schedule, rr, {});
+ return frameKeys({ html, region: "pair", fps: FPS, frames, version: "t", items });
+ };
+ const a = keysOf(r);
+ assert.ok(a, "the page is modelled");
+ const changed = structuredClone(PAIR);
+ changed.pairs[1].caption = "Changed.";
+ const b = keysOf(render({ pair: changed }));
+ const diff = a.map((k, i) => (k !== b[i] ? i : -1)).filter((i) => i >= 0);
+ assert.ok(diff.length > 0);
+ // Pair 1 is up over clip c only (20–30 s): nothing before 20 s changes.
+ assert.ok(diff.every((i) => i / FPS >= 19.9 && i / FPS <= 30.1), `frames ${diff[0]}..${diff[diff.length - 1]}`);
+});
+
+test("chapter: a window per chapter the cut plays, its page keyed from its offset", () => {
+ const r = render({ chapter: CHAPTER });
+ const w = chapterWindows(schedule, r);
+ assert.deepEqual(w.map((x) => [x.segment, x.from, x.to]), [["a", 0, 3], ["c", 20, 23]]);
+ const mod = moduleById("chapter");
+ const regions = mod.regions(schedule, { render: r, outDir: "/tmp/x" });
+ assert.equal(regions.length, 2);
+ assert.equal(regions[1].offset, 20);
+ assert.equal(regions[1].frameCount, 90);
+ const win = mod.window(schedule, { segment: "c", fps: FPS, total: 45, render: r });
+ const html = chapterHtml(schedule, r, win, {});
+ assert.match(html, /Huck/);
+ assert.match(html, /Oct 2020/);
+ const fk = frameKeys({ html, region: "chapter", fps: FPS, frames: 90, version: "t" });
+ assert.ok(fk && fk.length === 90);
+ // A clip's window from the build: only the ones it intersects.
+ assert.equal(mod.regions(schedule, { render: r, outDir: "/tmp/x", clip: { at: 15, dur: 10 }, shift: 15 })[0].offset, 5);
+});
+
+test("status: rows come in on their first clip, outcomes fill on theirs", () => {
+ const r = render({ status: STATUS });
+ const rows = statusRows(schedule, r);
+ assert.deepEqual(rows.map((x) => [x.item, x.in, x.done]), [["Wizards of the Coast", 0, 20], ["CNET", 10, 20]]);
+ const states = statusStates(schedule, r);
+ assert.deepEqual(states.map((s) => [s.at, s.rows.length, s.rows.filter((x) => x.filled).length]), [[0, 1, 0], [10, 2, 0], [20, 2, 2]]);
+ const each = statusStates(schedule, render({ status: { ...STATUS, mode: "each" } }));
+ assert.ok(each.every((s) => s.rows.length === 1));
+ const { html, items } = statusHtml(schedule, r, {});
+ assert.match(html, /decided not to sue/);
+ assert.match(html, /no follow-up found/);
+ const fk = frameKeys({ html, region: "status", fps: FPS, frames: 45 * FPS, version: "t", items });
+ assert.ok(fk);
+ // Nothing changes between two events: frames 31..299 share frame 31's key (after the fade in).
+ assert.equal(new Set(fk.slice(31, 299)).size, 1);
+});
+
+test("the three modules are registered, documented and carry a generic-panel descriptor", () => {
+ for (const id of ["pair", "chapter", "status"]) {
+ const m = moduleById(id);
+ assert.ok(m, id);
+ assert.ok(Array.isArray(m.ui) && m.ui.length >= 3, `${id} ui`);
+ assert.ok(m.docs?.rows?.length, `${id} docs`);
+ assert.equal(typeof m.preview, "function");
+ assert.ok(m.frameKeys);
+ }
+});
diff --git a/umtool/report-to-video/modules/subtitle.mjs b/umtool/report-to-video/modules/subtitle.mjs
@@ -0,0 +1,34 @@
+// THE SUBTITLE (module `subtitle`, a part of the shell): each clip's source
+// line under its title -- who said it, the source's title, the date, the
+// clock in the source -- in the deck's page (deck.mjs `deckText`,
+// attribution.mjs `deckSubtitle`).
+import { DECK_DEFAULTS, SUBTITLE_TOKENS, settingsOf } from "./settings.mjs";
+import { defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "subtitle",
+ version: 1,
+ z: 11,
+ kind: "part",
+ host: "shell",
+ slot: "inline",
+ title: "Subtitle",
+ summary: "Each clip's source line under its title: the channel, the source's title, the date, the clock.",
+ configKey: "render.chrome.deck.subtitle",
+ defaults: DECK_DEFAULTS.subtitle,
+ validate: settingsOf("subtitle").validate,
+ resolve: (render) => ({ ...DECK_DEFAULTS.subtitle, ...(render?.chrome?.deck?.subtitle ?? {}) }),
+ ui: [
+ { key: "parts", type: "list", options: ["auto", ...SUBTITLE_TOKENS], label: "Parts", default: "auto",
+ help: "\"auto\", or the parts in order: channel, title, date, clock" },
+ { key: "dateFormat", type: "enum", options: ["long", "iso"], label: "Date format", default: "long" },
+ ],
+ docs: {
+ heading: "Subtitle",
+ intro: "The source line under each clip's title, in the deck.",
+ rows: [
+ ["`deck.subtitle.parts`", "`auto` · a list of distinct `channel` `title` `date` `clock` · default `auto`", "`umtool look <p> deck.subtitle='{\"parts\":[\"channel\",\"date\",\"clock\"]}'`"],
+ ["`deck.subtitle.dateFormat`", "`long` (24 Oct 2020) · `iso` · default `long`", "`umtool look <p> deck.subtitle='{\"dateFormat\":\"iso\"}'`"],
+ ],
+ },
+});
diff --git a/umtool/report-to-video/modules/teaser.mjs b/umtool/report-to-video/modules/teaser.mjs
@@ -0,0 +1,47 @@
+// THE TEASER (module `teaser`, a segment): a full-frame card of lines that pop
+// in on the beat, inserted into the cut as a timeline entry of its own
+// (`{ type: "teaser" }`, deck.mjs). chrome-teaser.mjs writes the page; the
+// build encodes its frames into segments/<id>.mp4 (build-video's
+// buildTeaserSegment).
+import { teaserSeconds, validateTeaser, validateTeasers } from "../deck.mjs";
+import { defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "teaser",
+ version: 1,
+ z: 0,
+ kind: "segment",
+ slot: "full",
+ title: "Teaser",
+ summary: "A full-frame card of lines popping in on the beat, inserted as its own segment.",
+ validate: (_value, { manifest }) => validateTeasers(manifest),
+ docs: {
+ heading: "Teaser",
+ intro: "A timeline entry `{ type: \"teaser\", lines, … }`: a full-frame card whose lines pop in on the beat, cut in as its own segment (deck.mjs `validateTeaser`; [report-video.md](report-video.md)).",
+ rows: [
+ ["a `teaser` entry", "`lines` (each `{text, role?, hold?, …}`), `tail?`, `dip?`", "`umtool timeline <p> insert …`"],
+ ],
+ },
+ region: "teaser",
+ workers: "wide",
+ noun: "the teaser's",
+ entry(manifest, segment) {
+ const teaser = (manifest.timeline ?? []).find((e) => e.id === segment && e.type === "teaser") ?? null;
+ if (!teaser) return null;
+ const errors = validateTeaser(teaser);
+ if (errors.length) throw new Error(`teaser ${teaser.id}: ${errors.join("; ")}`);
+ return teaser;
+ },
+ seconds: (entry, D, fps) => teaserSeconds(entry, D, fps),
+ names: ({ preview, entry }) => ({ project: `teaser-${preview ? "preview-" : ""}${entry.id}`, stem: `teaser-${entry.id}` }),
+ async page(ctx) {
+ // A page module reached by a dynamic import, so nothing that imports this
+ // file -- umtool's preview helper, the build -- loads its face's URL
+ // unless a teaser is being composed (docs/quirks.md).
+ const { teaserHtml, TEASER_FONT_FILE, TEASER_FONT_ASSET } = await import("../chrome-teaser.mjs");
+ await ctx.projectFile(TEASER_FONT_FILE, TEASER_FONT_ASSET);
+ return teaserHtml(ctx.entry, ctx.render, { font: TEASER_FONT_ASSET, transition: ctx.transition });
+ },
+ // A cue interpreter: a teaser whose words changed recaptures only the frames they are on.
+ frameKeys: { data: "teaser-data", omit: ["init", "cues"] },
+});
diff --git a/umtool/report-to-video/modules/threads.mjs b/umtool/report-to-video/modules/threads.mjs
@@ -0,0 +1,51 @@
+// THE THREAD RAIL (module `threads`, region `threads`): the left panel beside
+// the footage, a card per thread lit as its clips play (`render.chrome.threads`,
+// threads.mjs). chrome-threads.mjs writes the page.
+import path from "node:path";
+
+import { threadsGeometry } from "../deck.mjs";
+import { threadsHtml } from "../chrome-threads.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+import { settingsOf } from "./settings.mjs";
+
+/** The side panel as an overlay region (the thread rail's and the flips'). */
+export function sideRegion(render, frames, name) {
+ const { cards: _c, ...box } = threadsGeometry(render);
+ return assertRegion({ name, frames, ...box });
+}
+
+export default defineModule({
+ id: "threads",
+ version: 1,
+ z: 70,
+ kind: "overlay-whole",
+ slot: "side",
+ title: "Thread rail",
+ summary: "A card per thread beside the footage, lit as its clips play.",
+ validate: settingsOf("threads").validate,
+ docs: {
+ heading: "Thread rail",
+ intro: "A card per thread in the side panel beside the footage, lit as its clips play; a thread’s outcome stamped on its last clip (`render.chrome.threads`, threads.mjs).",
+ rows: [
+ ["`render.chrome.threads.list[]`", "`{id, label, outcome?: {verdict, label?}}`; a clip names its thread with `thread`", "`umtool look <p> chrome.threads=…` (manifest)"],
+ ],
+ },
+ region: "threads",
+ workers: "narrow",
+ noun: "the thread rail's",
+ configKey: "render.chrome.threads",
+ on: (schedule) => !!schedule?.threads?.threads?.length,
+ check: (schedule) => (!schedule.threads?.threads?.length
+ ? "the threads region needs a schedule with a thread rail (render.chrome.threads)"
+ : null),
+ async page(ctx) {
+ // The thread rail (chrome-threads.mjs): the deck's faces, no QR.
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ return threadsHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration });
+ },
+ regions(_schedule, { render, outDir, frames = null }) {
+ return [sideRegion(render, frames ?? path.join(outDir, "chrome", "threads-frames"), "threads")];
+ },
+ // A cue interpreter like the deck's: keyed per frame (frame-keys.mjs).
+ frameKeys: { data: "threads-data", omit: ["init", "cues", "window", "total", "ids"] },
+});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -27,6 +27,7 @@
"./clip-audio": "./clip-audio.mjs",
"./clip-blur": "./clip-blur.mjs",
"./compose-chrome": "./compose-chrome.mjs",
+ "./counter": "./counter.mjs",
"./cues": "./cues.mjs",
"./cut-points": "./cut-points.mjs",
"./deck": "./deck.mjs",
@@ -45,12 +46,15 @@
"./local-media": "./local-media.mjs",
"./join-preview": "./join-preview.mjs",
"./look": "./look.mjs",
+ "./modules": "./modules/index.mjs",
+ "./modules/*": "./modules/*.mjs",
"./mute": "./mute.mjs",
"./narration": "./narration.mjs",
"./narration-review": "./narration-review.mjs",
"./narration-store": "./narration-store.mjs",
"./package.json": "./package.json",
"./post-links": "./post-links.mjs",
+ "./presets": "./presets.mjs",
"./prune-frames": "./prune-frames.mjs",
"./render-cards": "./render-cards.mjs",
"./render-estimate": "./render-estimate.mjs",
diff --git a/umtool/report-to-video/presets.mjs b/umtool/report-to-video/presets.mjs
@@ -0,0 +1,177 @@
+// LOOK PRESETS (release 39, the video modules): a named render block a
+// manifest stands on. `"preset": "<name>"` at the manifest's top level (the
+// key `render.preset` is the x264 encoder preset, and stays that) names a
+// file `umtool/presets/<name>.json` -- `{ name, description, render }` --
+// whose `render` is the BASE LAYER under the manifest's own:
+//
+// preset → manifest → style → take patch
+//
+// each applied over the one before as an RFC 7386 merge patch (mergePatch).
+// So a manifest names only what it changes from its preset, a take's style
+// and patch change it again, and a `null` anywhere above removes the key it
+// names from everything below -- the preset's value included.
+//
+// Resolved at the one door every reader of a cut goes through (build-video
+// `selectVariant`) and where a take merges its patches (takeMaker
+// `makeTake`, takeManifest `resolveTakeManifest`). A resolved manifest
+// carries `presetApplied: <name>` and no `preset`, so it is never laid twice.
+//
+// The presets directory is `UMTOOL_PRESETS_DIR` when set (the e2e suite's),
+// else umtool/presets beside this package. Read synchronously: a preset is a
+// small file, read where a manifest is (and cached by mtime).
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { mergePatch } from "./montage-styles.mjs";
+
+const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url));
+
+/** The directory the presets are read from (and `umtool preset save` writes to). */
+export const presetsDir = () => process.env.UMTOOL_PRESETS_DIR || path.resolve(/* turbopackIgnore: true */ HERE, "..", "presets");
+
+export const PRESET_NAME_RE = /^[a-z][a-z0-9-]{0,47}$/;
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const cache = new Map();
+
+/** Every reason a preset document is not one. */
+export function presetErrors(doc, name = doc?.name) {
+ const errors = [];
+ if (!isObj(doc)) return ["a preset is { name, description?, render }"];
+ for (const k of Object.keys(doc)) if (!["name", "description", "render", "from"].includes(k)) errors.push(`preset.${k} is not a preset key (name, description, render, from)`);
+ if (typeof doc.name !== "string" || !PRESET_NAME_RE.test(doc.name)) errors.push("preset.name must be lower-case letters, digits and dashes");
+ if (name !== undefined && doc.name !== name) errors.push(`preset.name "${doc.name}" is not its file's name "${name}"`);
+ if (!isObj(doc.render)) errors.push("preset.render must be an object (the render block it lays under a manifest)");
+ if (isObj(doc.render) && "chrome" in doc.render && doc.render.chrome !== undefined && !isObj(doc.render.chrome)) errors.push("preset.render.chrome must be an object");
+ return errors;
+}
+
+/** The preset by name: `{ name, description, render }`. Throws a sentence naming the presets on an unknown one. */
+export function loadPreset(name, { dir = presetsDir() } = {}) {
+ if (typeof name !== "string" || !PRESET_NAME_RE.test(name)) throw new Error(`"${name}" is not a preset name (lower-case letters, digits and dashes)`);
+ const file = path.join(/* turbopackIgnore: true */ dir, `${name}.json`);
+ let st;
+ try {
+ st = statSync(/* turbopackIgnore: true */ file);
+ } catch {
+ const known = presetNames({ dir });
+ throw new Error(`no preset "${name}"${known.length ? ` — one of ${known.join(", ")}` : ` (no presets in ${dir})`}`);
+ }
+ const hit = cache.get(file);
+ if (hit && hit.mtime === st.mtimeMs) return structuredClone(hit.doc);
+ const doc = JSON.parse(readFileSync(/* turbopackIgnore: true */ file, "utf8"));
+ const errors = presetErrors(doc, name);
+ if (errors.length) throw new Error(`preset ${name}: ${errors.join("; ")}`);
+ cache.set(file, { mtime: st.mtimeMs, doc });
+ return structuredClone(doc);
+}
+
+/** The presets on disk, by name. */
+export function presetNames({ dir = presetsDir() } = {}) {
+ if (!existsSync(/* turbopackIgnore: true */ dir)) return [];
+ return readdirSync(/* turbopackIgnore: true */ dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)).filter((n) => PRESET_NAME_RE.test(n)).sort();
+}
+
+/** Every preset: `{ name, description }`, by name; an unreadable one with its `error`. */
+export function listPresets({ dir = presetsDir() } = {}) {
+ return presetNames({ dir }).map((name) => {
+ try {
+ const p = loadPreset(name, { dir });
+ return { name, description: p.description ?? "", keys: Object.keys(p.render).sort(), ...(p.from ? { from: p.from } : {}) };
+ } catch (e) {
+ return { name, description: "", error: String(e?.message ?? e) };
+ }
+ });
+}
+
+/**
+ * The manifest a reader sees: the preset `manifest.preset` (or the last of
+ * `patches` that names one) under the manifest, then each patch over it.
+ * Without a preset, `patches` over the manifest -- exactly what makeTake
+ * always did. Returns a new object.
+ *
+ * @param {Record<string, any>} manifest
+ * @param {Array<Record<string, any> | null | undefined>} [patches]
+ * @returns {Record<string, any>}
+ */
+export function resolvePresetLayers(manifest, patches = [], opts = {}) {
+ const layers = patches.filter(Boolean);
+ const merged = layers.reduce((m, p) => mergePatch(m, p), manifest);
+ const name = merged?.preset;
+ if (name === undefined || name === null || name === "") return merged;
+ const preset = loadPreset(name, opts);
+ const out = [manifest, ...layers].reduce((m, p) => mergePatch(m, p), { render: preset.render });
+ delete out.preset;
+ out.presetApplied = name;
+ return out;
+}
+
+/** selectVariant's step: a manifest naming a preset, laid on it; any other as it is. */
+export function presetManifest(manifest) {
+ return manifest && typeof manifest.preset === "string" && manifest.preset ? resolvePresetLayers(manifest) : manifest;
+}
+
+// ---------------------------------------------------------------------------
+// Saving a preset from a project: its LOOK, never its content.
+// ---------------------------------------------------------------------------
+
+/** The render keys a preset keeps: the look (sizes, faces, palette, pacing, encode, QR, intro, the deck's settings). */
+export const PRESET_RENDER_KEYS = Object.freeze([
+ "width", "height", "fps", "audioRate", "audioChannels", "maxHeightSource", "fontRegular", "fontBold", "palette",
+ "transition", "transitionStyle", "fetchPad", "snapWindow", "silenceMinDur", "silenceRelDb", "snapLead", "snapTail",
+ "footerHeight", "headerHeight", "slideSeconds", "crf", "preset", "audioBitrate", "qr", "endFade", "loudness",
+ "captions", "intro", "chrome", "brand",
+]);
+
+/**
+ * The chrome keys that are a cut's CONTENT, not its look: left out of a
+ * saved preset (a deck's claim checks, markers, counter series, the finale's
+ * stats, a thread list, the story modules' lists).
+ */
+const CONTENT = {
+ deck: ["claims", "markers", "counter"],
+ "deck.finale": ["stats", "statsTitle"],
+ // The verdicts' relabels and the tally's settings are the counter's
+ // (migrate.mjs): they travel with a cut's series, and a counter beside
+ // them is refused.
+ factcheck: ["verdicts", "tally"],
+ pair: ["pairs"],
+ chapter: ["list"],
+ status: ["items"],
+};
+
+/**
+ * A preset document from a manifest (`umtool preset save`): its look keys,
+ * its chrome less the cut's content, its preset (when it names one) laid
+ * under it. `dropped` names every content key left out.
+ *
+ * @returns {{ preset: { name: string, description: string, render: Record<string, any>, from?: string }, dropped: string[] }}
+ */
+export function presetFromManifest(manifest, { name, description = "", from = null } = {}) {
+ if (!PRESET_NAME_RE.test(String(name))) throw new Error(`"${name}" is not a preset name (lower-case letters, digits and dashes)`);
+ const m = presetManifest(manifest);
+ const r = isObj(m?.render) ? m.render : {};
+ const render = {};
+ const dropped = [];
+ for (const k of PRESET_RENDER_KEYS) if (r[k] !== undefined) render[k] = structuredClone(r[k]);
+ for (const k of Object.keys(r)) if (!PRESET_RENDER_KEYS.includes(k)) dropped.push(`render.${k}`);
+ const chrome = render.chrome;
+ if (isObj(chrome)) {
+ for (const k of ["threads", "flips", "stats", "fx"]) {
+ if (chrome[k] !== undefined) { dropped.push(`render.chrome.${k}`); delete chrome[k]; }
+ }
+ for (const [where, keys] of Object.entries(CONTENT)) {
+ const obj = where.split(".").reduce((o, k) => (isObj(o) ? o[k] : undefined), chrome);
+ if (!isObj(obj)) continue;
+ for (const k of keys) if (obj[k] !== undefined) { dropped.push(`render.chrome.${where}.${k}`); delete obj[k]; }
+ }
+ for (const k of ["pair", "chapter", "status"]) if (isObj(chrome[k]) && !Object.keys(chrome[k]).length) delete chrome[k];
+ if (isObj(chrome.deck?.finale) && !Object.keys(chrome.deck.finale).length) delete chrome.deck.finale;
+ }
+ if (isObj(render.intro)) {
+ // The site an intro names is the cut's; "auto" (the manifest's own) travels.
+ if (render.intro.site !== undefined && render.intro.site !== "auto") { dropped.push("render.intro.site"); delete render.intro.site; }
+ }
+ return { preset: { name, description, render, ...(from ? { from } : {}) }, dropped };
+}