commit f8a76b901d1dd94b789a4d3f8752669b04383690
parent 3f02f81c91b07b405f81077db6a0819ffbf1c594
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 29 Oct 2026 00:09:56 -0400
umtool: look presets, module-config.json applied, the generic module panel and single-layer preview
- presets.mjs: `"preset": "<name>"` at the manifest's top level lays
umtool/presets/<name>.json's render block UNDER the manifest -- preset →
manifest → style → take patch, each an RFC 7386 merge patch. Resolved in
selectVariant (every reader of a cut), makeTake and resolveTakeManifest;
a resolved manifest carries `presetApplied`. (`render.preset` stays the
x264 encoder preset.) Built-ins: huck-deck (from polemic-huck's render,
its content left out), plain-deck (the Trisha final's look),
archive-catalog (a then/now archive look: dated subtitle, pitched rail,
the pair strip).
- updatePreset (a writer) and updateChrome validating the chrome over the
cut's preset; the story modules' clips checked against the timeline.
- modules/config-loader.mjs: a project's module-config.json (the design's
vocabulary) as a merge patch over its manifest -- the preset, subtitle,
QR, counter series and each clip's marks, stamps, rail markers, chapters,
pairs, status ledger, intro, finale (its stats' counter totals counted,
its run's layout) -- and every field with no home listed by path.
- `umtool modules list | apply <p> [--config F] [--dry-run | --take <id> …]`
and `umtool preset list | show | save <name> --from <p> | apply <name> <p>`.
- modules/panel.mjs + GET/PUT /api/report/modules + ModulesPanel in the
Media tab: every module with a `ui` descriptor drawn from it, on/off for a
module that is an object of its own, its checks, a save through the
writers, the look preset; the story modules, the finale's contents and
the intro's brand and site among them.
- POST /api/report/chrome/preview { layers: [ids] }: those modules composed
alone through their own pages (`<region>-preview[-<segment>]`), served by
the files route.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
20 files changed, 2135 insertions(+), 9 deletions(-)
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 (write.chrome) return updateChrome(r.project.dir, write.chrome, { 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
@@ -54,6 +54,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
// umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]
@@ -773,6 +777,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)",
@@ -844,6 +852,8 @@ const COMMANDS = {
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,
diff --git a/umtool/components/projects/ModulesPanel.tsx b/umtool/components/projects/ModulesPanel.tsx
@@ -0,0 +1,392 @@
+"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"]);
+
+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) 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);
+ }, [first?.src]); // eslint-disable-line react-hooks/exhaustive-deps
+ 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&still=${t}`} data-testid="module-preview-iframe"
+ onLoad={(e) => e.currentTarget.contentWindow?.postMessage({ type: "deck:seek", t }, "*")}
+ 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/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -42,6 +42,8 @@ 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";
@@ -1036,12 +1038,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);
}
@@ -1050,6 +1058,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
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/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -750,3 +750,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
@@ -649,6 +649,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) };
@@ -660,3 +665,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";
@@ -511,9 +512,11 @@ export async function makeTake(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";
@@ -335,7 +336,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 } : {}) })));
}
/**
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.deepEqual(panelWrite(m, "pair", { enabled: false }).chrome, {});
+ 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/panel.mjs b/umtool/report-to-video/modules/panel.mjs
@@ -0,0 +1,153 @@
+// 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;
+}
+
+/** The modules the panel lists: every one with a ui descriptor and a home. */
+export const panelModules = () => MODULES.filter((m) => Array.isArray(m.ui) && m.ui.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 m.ui) {
+ 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: m.ui, 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>, 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(m.ui.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")) {
+ return { chrome: next.chrome ?? {} };
+ }
+ // 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/package.json b/umtool/report-to-video/package.json
@@ -53,6 +53,7 @@
"./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",
"./resolve-windows": "./resolve-windows.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(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(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(dir, `${name}.json`);
+ let st;
+ try {
+ st = statSync(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(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(dir)) return [];
+ return readdirSync(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 };
+}