Archilyzer · Source

archilyzer

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

commit bff9f3aa907550a56909fd092a23fa6d27f18a6d
parent d960d321af29a5ef3f5e29c633674d40ad50c7fd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 13:51:29 -0400

Merge lane/deck-finale: a finale layout -- the timeline into primary view, the tally's totals large, author stats cards, the clip in a side box (renderer + validation; the editor is owed)

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

Diffstat:
Aplans/deck-finale.md | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/knobs.md | 28++++++++++++++++++++++++++++
Mumtool/lib/report/knobsCli.test.mjs | 4++++
Mumtool/lib/report/manifest.mjs | 9+++++++++
Mumtool/report-to-video/build-video.mjs | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/chrome-deck.mjs | 6++++--
Aumtool/report-to-video/chrome-finale.mjs | 607+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/compose-chrome.mjs | 31++++++++++++++++++++++++++-----
Mumtool/report-to-video/deck.mjs | 158++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Aumtool/report-to-video/finale.mjs | 461+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/finale.test.mjs | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/lint.mjs | 8+++++++-
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/verify-build.mjs | 10+++++++++-
14 files changed, 1621 insertions(+), 29 deletions(-)

diff --git a/plans/deck-finale.md b/plans/deck-finale.md @@ -0,0 +1,53 @@ +# Deck finale — the timeline in primary view (lane `lane/deck-finale`, K3) + +Asked by the operator on 2026-10-22 for the Huck seizure-timeline video: "For the finale we can move the +timeline into primary view, and prominently show our totals as well as 'seizures per year' and maybe +'incidents per year'." Scope narrowed the same day to what the render needs (the Huck video's first release). + +## Rulings + +- A timeline clip's `layout: "finale"` (default `"clip"`) marks the finale. The marked clips are ONE run of + consecutive clips, with at least one clip before it and no clip after it; a card, still or teaser may follow. + `validateFinaleEntries` (finale.mjs) refuses anything else — the build, the lint, `structureErrors` and + `updateClip` (`umtool set <p> <clip> layout=…`; a write that adds a run problem is refused). +- `render.chrome.deck.finale`: `video` side|corner|hidden (side), `motion` grow|cut (grow), `totals` (true), + `stats` ≤ 8 `{label ≤ 32, value ≤ 16, note? ≤ 60, color?}`, `statsTitle` ≤ 40, `railLabels` all|nodes (all). + Validated in `validateChrome` (unknown keys refused); no default is filled into `DECK_DEFAULTS`. +- Geometry at 1080p (`finaleGeometry`, scaled with the frame): the rail across y 36–412, rail labels 28 px + and dates/marker labels 24 px (floor 24), totals numbers 128 px (floor 96), pips 2.5× the footer's (floor + 2×); the clip 768×432 at (1104, 448) ("side"), 538×302 bottom right ("corner"), none ("hidden"). +- Rail labels: each pip's deck title (else its date); consecutive equal labels share one, anchored between + their pips over a span line; a date the label already says is not repeated; one row, else two, else turned + 35°/50°/65° and hung down-left of the pip (the track starts far enough in for the first to read whole). +- The schedule (`deckSchedule`): `segments[i].finale`, `finale {segments, video, motion, start, at, grow, + cover, hide, from, to, out?, box, footage, dates}`; each finale clip's footage moves into the box through + `schedule.moves` (the existing footage move, at the join, so `--chrome-only` changes it) — the first over + 0.8 s from `at` ("grow"), the rest from their first frame; "hidden" moves nothing. +- "grow": `at` = start + max(D, D/2 + 0.08 + deck.motion.in) — the deck hands its words over to the first + finale clip as to any clip, then goes at `at`; the page draws the deck's ground, words, rail, tally and QR + where it stood and moves them up; the ground's hole shrinks with the footage on the move's smoothstep. + "cut": the page dissolves in over the run's first dissolve; the deck goes once it is covered. +- A claim stamped on a finale clip counts at the finale's start (`landed` = `start`) and is not drawn + (`stamp: false`, `finale: true`): the finale's totals are final. +- Popup posts on a finale clip are not drawn (no hold, no move); the feed keeps its column (covered). +- The finale page is a full-frame window region (`finaleRegions`, compose-chrome `--region finale`), laid last. +- Absent a valid finale run the schedule, the deck page and the graph are the bytes they were, `deck.finale` + set or not (finale.test.mjs). + +## Owed (deferred by the scope change) + +- `umtool/components/projects/FinaleEditor.tsx` (deck.finale fields, the stats list editor, a per-clip + "Finale layout" toggle list through `updateClip`'s `layout`), its one-line mount in OnscreenSection.tsx, and + OnscreenSection's `saveSettings` carrying `deck.finale` through (today a deck-settings save there drops it; + `umtool look deck.finale=…` and `PUT /api/report/chrome` keep it). +- An umtool e2e spec for the editor. +- umtool's live On-screen preview (`/api/report/chrome/preview`, `previewSchedule`) does not compose the + finale page; a build or `--chrome-only` renders it. A still: `compose-chrome.mjs --region finale --still`. +- `verify-build` checks the finale window's frame count; the Huck cut has not been rebuilt here. + +## Files + +`umtool/report-to-video/`: `finale.mjs`, `chrome-finale.mjs`, `finale.test.mjs` (new); `deck.mjs`, +`chrome-deck.mjs`, `compose-chrome.mjs`, `build-video.mjs`, `verify-build.mjs`, `lint.mjs`, `package.json` +(`./finale`). `umtool/lib/report/manifest.mjs` (`updateClip`'s run guard, `structureErrors`), +`lib/report/knobsCli.test.mjs`. Docs: `umtool/docs/knobs.md`. diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -45,6 +45,34 @@ claim's id and verdict and keeps its knobs while the id stays the same. The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets the look's keys (`transition=0.3`, …: [report-video.md](report-video.md#the-look-captions-loudness-shorts-release-36)). +## The finale (the timeline in primary view) + +The cut's last clips with the footer's rail redrawn large across the top (every pip lit, the markers flagged, +each pip's label), the tally's final counts large under it, stats cards beside them, and the clip in a smaller +box with its title, source line and QR. The deck footer and popup posts are not drawn over it. + +| Knob | Range · default | From a terminal | +|---|---|---| +| clip `layout` | `clip` · `finale` (default `clip`) — one run of consecutive clips, after at least one clip, no clip after it (a card, still or teaser may follow). A write that would break the run is refused: mark from the last clip back, unmark from the first on | `umtool set <p> <clip> layout=finale` | +| `deck.finale.video` | `side` (the clip 40 % wide, right) · `corner` (28 %, bottom right) · `hidden` (heard only) · default `side` | `umtool look <p> deck.finale='{"video":"corner"}'` | +| `deck.finale.motion` | `grow` (the footer's rail, tally and QR travel to their places over 0.8 s once the deck's words are in; the footage shrinks into its box with them) · `cut` (the page dissolves in over the run's first dissolve) · default `grow` | same | +| `deck.finale.totals` | bool · `true` — the verdicts' final counts, 128 px | same | +| `deck.finale.stats` | ≤ 8 `{label ≤ 32, value ≤ 16, note? ≤ 60, color?}` (`color`: a `#hex` or `fg` `muted` `accent` `amber`) · none | same | +| `deck.finale.statsTitle` | ≤ 40 characters · none | same | +| `deck.finale.railLabels` | `all` (each pip's label, its date when the label does not already say it, the markers' labels) · `nodes` (the pips' labels only) · default `all` | same | + +Every key of `deck.finale` goes in one JSON value, e.g. + +```sh +umtool look <p> deck.finale='{"statsTitle":"Seizures he reported","stats":[{"label":"2025 (from 26 Feb)","value":"5+","note":"4 incidents"}]}' +umtool set <p> heartstrings layout=finale +``` + +The totals use the fact-check's verdict labels and colours (`factcheck.verdicts.<V>.label`). A claim whose stamp +would land inside the finale counts as the finale opens and is not drawn. Without a finale entry the cut is the +bytes it was, `deck.finale` set or not. The render: `<out>/<variant>/chrome/finale-frames/` (a full-frame window +over the run, laid last); a still: `compose-chrome.mjs <manifest> --region finale --still <cut s> --png <file>`. + ## Make variants, and the sync report | | In umtool | From a terminal | Route | diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs @@ -72,6 +72,10 @@ test("umtool set: claim and audio knobs through the writers; key= clears; a bad assert.equal("layout" in (await read(dir)).timeline[1], false); assert.equal(await run("set", "c02", "layout=wide"), 1); assert.match(lines.at(-1), /layout must be/); + // The finale is one run of the last clips: c01 alone would have c02 after it (finale.mjs). + assert.equal(await run("set", "c01", "layout=finale"), 1); + assert.match(lines.at(-1), /no clip may follow the finale/); + assert.equal("layout" in (await read(dir)).timeline[0], false); }); test("umtool look: the fact-check's stamp, a verdict's stamp word, markers, layout, the ladder, a look key", async () => { diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -38,6 +38,7 @@ import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/ import { validateRoom } from "umtool-report-to-video/room"; import { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; +import { validateFinaleEntries } from "umtool-report-to-video/finale"; import { validateClipAudio } from "umtool-report-to-video/clip-audio"; import { CLAIM_KNOBS, claimKnobsOf, claimKnobValue, normalizeClaimKnobPatch, stampingEntryId, variantsProblems } from "./knobs.mjs"; import { validateNarration } from "umtool-report-to-video/narration"; @@ -394,6 +395,12 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri if (v === null || v === "" || v === "clip") delete entry.layout; else if (v === "finale") entry.layout = "finale"; else throw new Error(`layout must be "finale" or "clip" (the default), not ${JSON.stringify(v)}`); + // The finale's run (finale.mjs): a write may not break it -- refused + // when it adds a problem the file did not have. Mark from the last + // clip back, unmark from the first on. + const was = new Set(validateFinaleEntries(JSON.parse(raw))); + const bad = validateFinaleEntries(manifest).filter((e) => !was.has(e)); + if (bad.length) throw new Error(`layout: ${bad.join("; ")}`); } // ---- the walk's verdict ------------------------------------------------- @@ -1313,6 +1320,8 @@ function structureErrors(manifest) { ...validateClaims(manifest), // The deck's markers follow clips: removing one a marker names is refused. ...validateDeckMarkers(manifest), + // The finale is one run of the last clips: moving a clip past it is refused. + ...validateFinaleEntries(manifest), ...validateTeasers(manifest), ...validateNarration(manifest), ...validateDrafted(manifest), diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -147,6 +147,7 @@ import { import { fxOn, fxQuoteSpan, resolveFx, fxWhipJoins, fxWipeJoins, fxWordsOf, fxZoomJoins, validateFxEntries } from "./fx.mjs"; import { claimOf, stampsDrawn, validateClaims } from "./factcheck.mjs"; import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs"; +import { validateFinaleEntries } from "./finale.mjs"; import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -3319,9 +3320,11 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts // deck's is. // The stats region (`name: "stats"`) likewise. // The effects region (`name: "fx"`) likewise. + // The finale (`name: "finale"`, chrome-finale.mjs) is a window like a + // posts window's -- the whole frame, laid last. const deck = r.name === "deck" || r.name === "feed" || r.name === "stamp" || r.name === "threads" || r.name === "flips" || r.name === "stats" || r.name === "fx"; - const posts = r.name === "posts"; + const posts = r.name === "posts" || r.name === "finale"; inputs.push( ...(deck || posts ? ["-reinit_filter", "0"] : []), ...(posts ? ["-itsoffset", offsetArg(r.offset)] : []), @@ -3380,6 +3383,32 @@ export function postsRegions(render, outDir, schedule, { shift = 0, clip = null })); } +/** + * The finale's page (a schedule with `finale`, chrome-finale.mjs) as an + * overlay region: the whole frame, its window snapped to the frame grid + * (`snapWindow`) and laid at its own second like a posts window -- `offset` + * in the BASE's clock (the cut's, or a preview's that starts `shift` in). + * `clip` (`{at, dur}`) keeps it only when it intersects. No finale: none. + * + * @returns {Array<{ name: "finale", frames: string, x: number, y: number, width: number, height: number, + * offset: number, frameCount: number, window: object }>} + */ +export function finaleRegions(render, outDir, schedule, { shift = 0, clip = null } = {}) { + const f = schedule?.finale; + if (!f) return []; + const fps = Number(schedule.fps ?? render.fps); + const s = snapWindow({ segment: "finale", from: f.from, to: f.to }, { fps, total: schedule.total }); + if (clip && !(s.from < clip.at + clip.dur && s.to > clip.at)) return []; + return [{ + name: "finale", + frames: path.join(outDir, "chrome", "finale-frames"), + x: 0, y: 0, width: render.width ?? 1920, height: render.height ?? 1080, + offset: s.from - shift, + frameCount: s.frames, + window: s, + }]; +} + /** The posts feed as an overlay region: its frames at feedGeometry's column. */ export function feedRegion(render, frames) { return { name: "feed", frames, ...feedGeometry(render).column }; @@ -4789,6 +4818,29 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro }); regions.push(threadsRegion(render, fl.frames, "flips")); } + + // The finale (a schedule with `finale`, chrome-finale.mjs): one full-frame + // window over the run's seconds, laid LAST -- its ground covers every + // region under it while it is up. A preview window takes it only when it + // intersects; its frames are the build's, as the posts windows' are. + for (const fr of finaleRegions(render, outDir, schedule, { shift: clip ? clip.at : 0, clip })) { + EMIT("chrome", { phase: "compose", region: "finale" }); + const t1 = Date.now(); + const p = await composeChrome({ + manifestPath, outDir, variant, region: "finale", doRender: true, + fps: render.fps, workers: 2, quality: "high", format: "png-sequence", + }); + if (p.frames !== fr.frames || p.frameCount !== fr.frameCount) { + throw new Error(`the finale rendered ${p.frameCount} frames to ${p.frames}; the overlay expects ${fr.frameCount} at ${fr.frames}`); + } + EMIT("chrome", { + phase: p.cached ? "cached" : "render", region: "finale", + frames: p.frameCount, key: p.key, dir: p.frames, + seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), + }); + const { window: _w, frameCount: _n, ...region } = fr; + regions.push(region); + } return { regions, outLabel: "[hfout]" }; } @@ -5263,7 +5315,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole), ...validateTransitionStyle(whole), - ...validateLook(whole), ...validateClipAudioEntries(whole), + ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateFinaleEntries(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -239,7 +239,9 @@ export function deckCues(schedule, render) { if (v.hide) { // The text on the way down stays until it is off screen, then is gone // for good -- nothing is handed over behind a card. - const prev = segs.slice(0, v.i).map((s, j) => j).filter((j) => !segs[j].hideDeck).pop(); + // (Into the finale the deck goes over the finale clip itself, its text + // handed over to: that is the last shown. Its segment is not hidden.) + const prev = segs.slice(0, v.i + 1).map((s, j) => j).filter((j) => !segs[j].hideDeck).pop(); if (prev !== undefined) { add(keyOf(prev, "seg"), v.at[1], INSTANT, { autoAlpha: 0 }, "none", why); const pk = pipOf.get(segs[prev].id); @@ -322,7 +324,7 @@ export const MARKER_POP = Object.freeze({ from: 0.35, seconds: 0.35 }); * A verdict pip's shape as CSS, `size` px: a circle, a diamond (a square * turned, shrunk to the circle's reach), a square, a triangle, a ring. */ -function shapeCss(shape, size, color) { +export function shapeCss(shape, size, color) { const d = Math.round(size * 0.78 * 100) / 100; switch (shape) { case "diamond": diff --git a/umtool/report-to-video/chrome-finale.mjs b/umtool/report-to-video/chrome-finale.mjs @@ -0,0 +1,607 @@ +// The deck's FINALE composition (finale.mjs): one full-frame HyperFrames page +// over the window the schedule's `finale` covers -- the cut's last clips with +// the timeline in primary view. +// +// PURE, like chrome-deck.mjs: a schedule and a render block in, an HTML string +// out. compose-chrome.mjs copies the assets in beside it, writes it and renders +// it (`region: "finale"`); the build lays its frames over the cut at the +// window's second, last, over every other region. +// +// What it draws: the footer's rail redrawn large across the top (every pip +// lit, the fuse burnt through, the markers flagged, each pip's label and +// date), the tally's final counts large under it, the author's stats cards, +// and -- around the box the clip has moved into (the build's footage move, +// deck.mjs `finaleSchedule`) -- the frame's ground, the clip's title, source +// line and QR. With `video: "hidden"` the ground covers the footage whole. +// +// "grow": every piece starts where the footer drew it -- the track, each pip, +// each flag, each tally cell, the QR -- and travels to its place over +// FINALE_MOTION.grow, while the ground's hole shrinks with the footage on the +// same smoothstep the move's perspective filter uses, so picture and hole +// never part. "cut": the page dissolves in at its first second, everything +// in place. Either way the page fades out through the dissolve after the run. +// +// The timeline is cues, each stating its from (chrome-deck.mjs says why). +import { deckLayout, deckMarkers, pageDuration, pipSegments, pipXs, resolveDeck } from "./deck.mjs"; +import { mix, rgba, shapeCss, subtitleMarkup } from "./chrome-deck.mjs"; +import { resolveFactcheck, tallyFinals, tallyOf, tallyVerdicts, VERDICT_SHAPES } from "./factcheck.mjs"; +import { + FINALE_MOTION, finaleGeometry, railLabelLayout, railMarkerLayout, resolveFinale, textWidth, +} from "./finale.mjs"; + +/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */ +const INSTANT = 0.001; + +/** The hole's ground reaches this far past the clip's box -- past the frame's far edge at any scale it is drawn at. */ +const HOLE_REACH = 8000; + +const esc = (s) => + String(s ?? "") + .replace(/&/g, "&amp;") + .replace(/</g, "&lt;") + .replace(/>/g, "&gt;") + .replace(/"/g, "&quot;"); + +const r2 = (v) => Math.round(v * 100) / 100; +const r4 = (v) => Math.round(v * 10000) / 10000; + +/** A colour a stat or marker names: a hex, or a palette key. */ +const colorOf = (key, pal, fallback) => (typeof key === "string" && /^#/.test(key) ? key : pal[key] ?? fallback); + +/** + * Everything the finale page draws and where, frame px -- the large rail's + * pips, labels and flags, the totals' cells, the stats' cards, the clip's + * captions and QR -- and where the footer drew each piece the "grow" starts + * from. Pure; the tests read the legibility floors off it. + */ +export function finaleLayout(schedule, render) { + const fin = schedule.finale; + if (!fin) throw new Error("finale: the schedule has no finale (no entry with layout \"finale\")"); + const f = resolveFinale(render); + const deck = resolveDeck(render); + const fc = resolveFactcheck(render); + const pal = render.palette; + const stamps = schedule.factcheck?.stamps ?? []; + const verdicts = f.totals && stamps.length ? tallyVerdicts(stamps) : []; + const geo = finaleGeometry(render, { verdicts: verdicts.length, stats: f.stats.length, statsTitle: !!f.statsTitle }); + const { rail } = geo; + + // The footer, as chrome-deck.mjs lays it: where the grow starts. + const tally = tallyOf(schedule, render); + const lay = deckLayout(render, { tally, schedule }); + const deckY = geo.H - lay.height; + const pipped = pipSegments(schedule); + const time = deck.pip.spacing === "time" ? { total: schedule.total, segments: pipped } : null; + const fxs = pipXs(pipped.length, lay.pipTrack.x0, lay.pipTrack.x1, deck.pip.spacing, time); + const byVerdict = deck.pip.color === "verdict"; + const footSize = deck.pip.size; + const footV = Math.max(footSize, Math.round((footSize * 5) / 3)); + const bigSize = Math.max(14, Math.round(footSize * 2.5)); + const bigV = Math.round((bigSize * 5) / 3); + + // The large rail: the pips across it, then their labels -- and when the + // labels turn, the track starts far enough in that the first one reads whole. + const info = pipped.map((s) => ({ label: s.title || fin.dates?.[s.id] || "", date: fin.dates?.[s.id] ?? "" })); + const dates = f.railLabels === "all"; + let x0 = rail.x0; + let xs = pipXs(pipped.length, x0, rail.x1, deck.pip.spacing, time); + let labels = railLabelLayout(xs.map((x, k) => ({ x, ...info[k] })), geo, { dates }); + if (labels.mode === "turned" && labels.groups.length) { + const g0 = labels.groups[0]; + const w0 = Math.min(320, Math.max(textWidth(g0.label, rail.labelSize), textWidth(g0.date, rail.dateSize, false))); + const need = Math.round(geo.margin / 2 + w0 * Math.cos((labels.angle * Math.PI) / 180)); + if (need > x0) { + x0 = Math.min(need, Math.round(geo.W * 0.2)); + xs = pipXs(pipped.length, x0, rail.x1, deck.pip.spacing, time); + labels = railLabelLayout(xs.map((x, k) => ({ x, ...info[k] })), geo, { dates }); + } + } + const verdictColors = fc.verdicts; + const finSet = new Set(fin.segments); + const pips = pipped.map((s, k) => { + const v = byVerdict && s.claim?.verdict ? s.claim.verdict : null; + return { + id: s.id, x: r2(xs[k]), size: v ? bigV : bigSize, ...(v ? { verdict: v, shape: VERDICT_SHAPES[v], color: verdictColors[v]?.color ?? pal.accent } : {}), + foot: { x: r2(fxs[k]), size: v ? footV : footSize }, + ...(finSet.has(s.id) ? { here: true } : {}), + }; + }); + // The flags, mapped from the footer's track onto the large one. + const span = lay.pipTrack.x1 - lay.pipTrack.x0; + const toBig = (x) => r2(x0 + ((x - lay.pipTrack.x0) * (rail.x1 - x0)) / (span || 1)); + const footMarks = deckMarkers(schedule, render, fxs, pipped, lay); + const marks = railMarkerLayout(footMarks.map((mk) => ({ x: toBig(mk.x), label: mk.label, color: mk.color })), geo) + .map((mk, j) => ({ ...mk, foot: { x: r2(footMarks[j].x) } })); + + // The totals: the tally's verdicts, each at its final count. + const finals = tallyFinals(stamps); + const tb = lay.tally ?? null; + const T = geo.totals; + const totals = T + ? verdicts.map((v, j) => ({ + verdict: v, count: finals[v], label: verdictColors[v]?.label ?? v, color: verdictColors[v]?.color ?? pal.accent, + shape: VERDICT_SHAPES[v], x: T.x + j * (T.cell + T.gap), y: T.y, width: T.cell, height: T.height, + ...(tb && tally?.[j] === v ? { foot: { x: tb.x + j * (tb.cell + tb.gap), y: deckY + tb.y, width: tb.cell, height: tb.height } } : {}), + })) + : []; + const S = geo.stats; + const stats = S + ? f.stats.map((s, j) => ({ + ...s, + color: colorOf(s.color, pal, pal.fg), + x: S.x + (j % S.cols) * (S.cardW + S.gap), + y: S.y + S.titleH + Math.floor(j / S.cols) * (S.cardH + S.gap), + width: S.cardW, height: S.cardH, + })) + : []; + // The rail's panel ends under its lowest label (inside the rail's region). + const lineL = Math.round(rail.labelSize * 1.15), lineD = Math.round(rail.dateSize * 1.15); + const blockOf = (gr) => lineL + (gr.date ? lineD : 0); + let low = rail.y + 60; + for (const gr of labels.groups) { + if (labels.mode === "turned") { + const a = (labels.angle * Math.PI) / 180; + const w = Math.min(gr.max, Math.max(textWidth(gr.label, rail.labelSize), textWidth(gr.date, rail.dateSize, false))); + low = Math.max(low, rail.y + 24 + w * Math.sin(a) + blockOf(gr) * Math.cos(a)); + } else low = Math.max(low, rail.y + 30 + (gr.row + 1) * (blockOf(gr) + 6)); + } + // What the labels leave of the rail's region, half above the flags and half + // under the labels: the track moves down by half of it. + const shift = Math.max(0, Math.floor((rail.bottom - low) / 2)); + const panel = { bottom: rail.bottom + 12 }; + const segs = schedule.segments.filter((s) => finSet.has(s.id)); + const captions = segs.map((s) => ({ id: s.id, start: s.start, title: s.title, subtitle: s.subtitle, qrUrl: s.qrUrl ?? null })); + return { + geo, + rail: { ...rail, x0, track: { x0, x1: rail.x1, y: rail.y + shift } }, + foot: { + y: deckY, + track: { x0: lay.pipTrack.x0, x1: lay.pipTrack.x1, y: deckY + lay.pipTrack.y }, + qr: lay.qr ? { ...lay.qr, y: deckY + lay.qr.y } : null, + // The deck's ground and its first finale clip's words, where it drew + // them: what "grow" takes over from (chrome-deck.mjs's colours). + ground: { + height: lay.height, + top: deck.background === "panel" ? mix(pal.bg, pal.fg, 0.095) : pal.bg, + bottom: deck.background === "panel" ? mix(pal.bg, pal.fg, 0.04) : pal.bg, + plateX: deck.background === "panel" && lay.qr ? lay.qr.x - 46 : null, + }, + text: { ...lay.text, titleY: deckY + lay.text.titleY, subtitleY: deckY + lay.text.subtitleY, ruleY: deckY + lay.text.ruleY }, + }, + pips, labels, marks, totals, stats, captions, panel, + statsTitle: f.statsTitle, + railLabels: f.railLabels, + video: f.video, motion: f.motion, + box: fin.box ?? null, footage: fin.footage, + }; +} + +/** + * Everything the finale page's timeline does, as data, in the cut's clock: + * `init` (t = the window's first second) and `cues` in time order, each with + * its from -- chrome-deck.mjs `deckCues`'s contract. + */ +export function finaleCues(schedule, render, L = finaleLayout(schedule, render)) { + const fin = schedule.finale; + const D = schedule.transition ?? 0; + const A = fin.at; + const G = fin.grow > 0 ? fin.grow : 0; + const grow = L.motion === "grow" && G > 0; + const R = A + G; + const m = FINALE_MOTION; + const init = {}; + const put = (k, v) => { init[k] = { ...(init[k] ?? {}), ...v }; }; + const ev = []; + const add = (k, at, dur, to, ease, why) => ev.push({ k, at: r4(at), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); + const ft = L.foot.track, bt = L.rail.track; + + // From a rect the footer drew to this one: a uniform scale, centres matched + // (the element's transform-origin is its top-left). + const fromRect = (F, B) => { + const s = Math.min(F.width / B.width, F.height / B.height); + return { x: r2(F.x + F.width / 2 - (B.width * s) / 2 - B.x), y: r2(F.y + F.height / 2 - (B.height * s) / 2 - B.y), scale: r4(s) }; + }; + const travel = (k, from, why) => { + if (grow) { + put(k, from); + add(k, A, G, Object.fromEntries(Object.keys(from).map((p) => [p, p.startsWith("scale") || p === "opacity" ? 1 : 0])), "power3.inOut", why); + } else put(k, Object.fromEntries(Object.keys(from).map((p) => [p, p.startsWith("scale") || p === "opacity" ? 1 : 0]))); + }; + // At rest: a scale is 1, an offset 0. + const rest = (extra) => Object.fromEntries(Object.keys(extra).map((p) => [p, p.startsWith("scale") ? 1 : 0])); + const reveal = (k, at, why, extra = {}) => { + if (grow) { + put(k, { opacity: 0, ...extra }); + add(k, at, m.reveal, { opacity: 1, ...rest(extra) }, "power2.out", why); + } else put(k, { opacity: 1, ...rest(extra) }); + }; + + // The stage: "cut" dissolves it in at the run's start; either way it leaves + // through the dissolve after the run. + if (grow) put("stage", { opacity: 1 }); + else { + put("stage", { opacity: 0 }); + add("stage", fin.start, D, { opacity: 1 }, "power1.inOut", "finale in"); + } + if (fin.out) add("stage", fin.out[0], fin.out[1] - fin.out[0], { opacity: 0 }, "power1.inOut", "finale out"); + + // The ground: around the clip's box (its hole shrinks with the footage on + // the move's smoothstep), or over everything when the clip is heard only. + if (L.box) { + const B = L.box, F = L.footage; + if (grow) { + put("hole", { x: r2(F.x - B.x), y: r2(F.y - B.y), scaleX: r4(F.width / B.width), scaleY: r4(F.height / B.height) }); + add("hole", A, G, { x: 0, y: 0, scaleX: 1, scaleY: 1 }, "smoothstep", "finale hole"); + put("veil", { opacity: 0 }); + add("veil", A, fin.cover - A, { opacity: 1 }, "power1.inOut", "finale ground"); + } else { + put("hole", { x: 0, y: 0, scaleX: 1, scaleY: 1 }); + put("veil", { opacity: 1 }); + } + reveal("frame", R, "finale frame"); + } else if (grow) { + put("ground", { opacity: 0 }); + add("ground", A, fin.cover - A, { opacity: 1 }, "power1.inOut", "finale ground"); + } else put("ground", { opacity: 1 }); + // The rail's panel once the footage has left it. + reveal("panel", Math.max(A, R - 0.1), "finale panel"); + // "grow": the deck's ground and words where it stood (it went at `at`): + // the ground sinks and fades as the pieces rise, the words go first. + if (grow) { + put("dg", { opacity: 1, y: 0 }); + add("dg", A, G * 0.6, { opacity: 0, y: 40 }, "power2.in", "finale deck ground"); + put("dt", { opacity: 1 }); + add("dt", A, 0.2, { opacity: 0 }, "power1.out", "finale deck words"); + } + + // The rail: track, fuse and pips from the footer's track. + const bw = bt.x1 - bt.x0; + travel("track", { x: r2(ft.x0 - bt.x0), y: r2(ft.y - bt.y), scaleX: r4((ft.x1 - ft.x0) / bw), scaleY: 0.5 }, "finale rail"); + const p0 = L.pips[0], pn = L.pips[L.pips.length - 1]; + if (L.pips.length > 1) { + const fw = pn.x - p0.x; + travel("fuse", { x: r2(p0.foot.x - p0.x), y: r2(ft.y - bt.y), scaleX: r4((pn.foot.x - p0.foot.x) / fw), scaleY: 0.5 }, "finale rail"); + } + L.pips.forEach((p, k) => { + travel(`p${k}`, { x: r2(p.foot.x - p.x), y: r2(ft.y - bt.y), scale: r4(p.foot.size / p.size) }, `finale pip ${p.id}`); + if (p.here) reveal(`ring${k}`, R, `finale here ${p.id}`, { scale: 0.6 }); + }); + L.marks.forEach((mk, j) => { + travel(`mk${j}`, { x: r2(mk.foot.x - mk.x), y: r2(ft.y - bt.y), scale: 0.4 }, "finale marker"); + if (L.railLabels === "all") reveal(`ml${j}`, R + j * m.stagger, "finale marker label"); + }); + L.labels.groups.forEach((g, j) => { + reveal(`pl${j}`, R + 0.05 + j * (m.stagger / 2), "finale label"); + if (g.to > g.from) reveal(`sp${j}`, R, "finale span"); + }); + + // The totals: each cell from the footer tally's cell, else in. + L.totals.forEach((c, j) => { + if (c.foot) travel(`tc${j}`, fromRect(c.foot, c), `finale total ${c.verdict}`); + else reveal(`tc${j}`, A + G * 0.5, `finale total ${c.verdict}`, { y: 24 }); + }); + if (L.statsTitle) reveal("stt", R, "finale stats title"); + L.stats.forEach((s, j) => reveal(`sc${j}`, R + 0.1 + j * m.stagger, "finale stat", { y: 24 })); + + // The clip's caption and QR: the first from the footer's QR; each later + // finale clip's at its mid-dissolve. + L.captions.forEach((c, i) => { + if (i === 0) { + reveal(`cap${i}`, A + G * 0.6, "finale caption"); + if (L.foot.qr && c.qrUrl) { + const q = L.geo.qr; + travel(`qr${i}`, fromRect({ x: L.foot.qr.x, y: L.foot.qr.y, width: L.foot.qr.size, height: L.foot.qr.size }, { x: q.x, y: q.y, width: q.size, height: q.size }), "finale qr"); + } else reveal(`qr${i}`, A + G * 0.6, "finale qr"); + return; + } + const mid = c.start + D / 2; + put(`cap${i}`, { autoAlpha: 0 }); + put(`qr${i}`, { autoAlpha: 0 }); + add(`cap${i - 1}`, mid, INSTANT, { autoAlpha: 0 }, "none", `finale caption ${c.id}`); + add(`qr${i - 1}`, mid, INSTANT, { autoAlpha: 0 }, "none", `finale caption ${c.id}`); + add(`cap${i}`, mid, INSTANT, { autoAlpha: 1 }, "none", `finale caption ${c.id}`); + add(`qr${i}`, mid, INSTANT, { autoAlpha: 1 }, "none", `finale caption ${c.id}`); + }); + + // Order, clamp per element, state the froms (deckCues' walk). + ev.forEach((e, n) => { e.n = n; }); + ev.sort((x, y) => x.at - y.at || x.n - y.n); + const state = Object.fromEntries(Object.entries(init).map(([k, v]) => [k, { ...v }])); + const freeAt = new Map(); + const cues = []; + for (const e of ev) { + let { at, dur } = e; + const free = freeAt.get(e.k) ?? -Infinity; + if (at < free) { + const end = at + dur; + at = r4(free); + dur = r4(Math.max(INSTANT, end - at)); + } + const cur = state[e.k] ?? (state[e.k] = {}); + const from = {}; + for (const p of Object.keys(e.to)) from[p] = cur[p] ?? (p.startsWith("scale") || p === "opacity" || p === "autoAlpha" ? 1 : 0); + Object.assign(cur, e.to); + freeAt.set(e.k, r4(at + dur)); + cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why }); + } + return { init, cues }; +} + +/** + * The finale page's HTML, for its window (`window` = compose-chrome's + * `snapWindow` of the schedule's `finale.from`–`to`; frame 1 is cut time + * `window.from`). `fonts` = `{ regular, bold }`, `qrSrcs` = `{ [segmentId]: + * "assets/qrNN.png" }`, `gsap` = the vendored script's asset path. + */ +export function finaleHtml(schedule, render, window, opts = {}) { + const L = finaleLayout(schedule, render); + const { init, cues } = finaleCues(schedule, render, L); + const pal = render.palette; + const g = L.geo; + const W = g.W, H = g.H; + const fonts = opts.fonts ?? {}; + const qrSrcs = opts.qrSrcs ?? {}; + const gsapSrc = opts.gsap ?? "assets/gsap.min.js"; + const from = Number(window.from); + const dur = r4(Number(window.to) - from); + if (!(dur > 0)) throw new Error("finale: the window is empty"); + const fps = schedule.fps ?? render.fps ?? 30; + const rail = L.rail; + const Y = rail.track.y; + const panelTop = mix(pal.bg, pal.fg, 0.06); + const panelBottom = mix(pal.bg, pal.fg, 0.025); + + const hole = L.box + ? `<div class="veil" data-k="veil"><div class="hole" data-k="hole" style="left:${L.box.x}px; top:${L.box.y}px; width:${L.box.width}px; height:${L.box.height}px"></div></div>` + + `<div class="vframe" data-k="frame" style="left:${L.box.x}px; top:${L.box.y}px; width:${L.box.width}px; height:${L.box.height}px"></div>` + : `<div class="ground" data-k="ground"></div>`; + + const pipHtml = L.pips + .map((p, k) => { + const half = p.size / 2; + const look = p.verdict ? shapeCss(p.shape, p.size, esc(p.color)) : `border-radius:50%; background:${pal.accent};`; + const ring = p.here + ? `<div class="ring" data-k="ring${k}" style="left:${r2(p.x - p.size)}px; top:${r2(Y - p.size)}px; width:${p.size * 2}px; height:${p.size * 2}px"></div>` + : ""; + return ( + ring + + `<div class="pip" data-k="p${k}" data-id="${esc(p.id)}"${p.verdict ? ` data-verdict="${esc(p.verdict)}"` : ""} ` + + `style="left:${r2(p.x - half)}px; top:${r2(Y - half)}px; width:${p.size}px; height:${p.size}px; ${look}"></div>` + ); + }) + .join(""); + + // The spans under a label several pips share. + const spans = L.labels.groups + .map((gr, j) => { + if (!(gr.to > gr.from)) return ""; + const a = L.pips[gr.from].x, b = L.pips[gr.to].x; + return `<div class="span" data-k="sp${j}" style="left:${r2(a)}px; top:${Y + Math.round(L.pips[gr.from].size / 2) + 8}px; width:${r2(b - a)}px"></div>`; + }) + .join(""); + + // "grow": the deck's ground and the first finale clip's words, where the + // deck drew them, for the page to take over from. + const fg0 = L.foot.ground, ftx = L.foot.text, c0 = L.captions[0]; + const deckCopy = L.motion === "grow" && (schedule.finale.grow ?? 0) > 0 + ? `<div class="dg" data-k="dg" style="top:${L.foot.y}px; height:${fg0.height}px">` + + (fg0.plateX !== null ? `<div class="dplate" style="left:${fg0.plateX}px"></div>` : "") + `</div>` + + `<div class="dt" data-k="dt">` + + (c0?.title ? `<div class="dtt" style="left:${ftx.x}px; top:${ftx.titleY}px; max-width:${ftx.width}px">${esc(c0.title)}</div>` + + `<div class="drule" style="left:${ftx.x}px; top:${ftx.ruleY}px"></div>` : "") + + `<div class="dts" style="left:${ftx.x}px; top:${c0?.title ? ftx.subtitleY : ftx.titleY}px; max-width:${ftx.width}px">${subtitleMarkup(c0?.subtitle ?? "")}</div></div>` + : ""; + + const lineL = Math.round(rail.labelSize * 1.15); + const lineD = Math.round(rail.dateSize * 1.15); + const turned = L.labels.mode === "turned"; + const labelHtml = L.labels.groups + .map((gr, j) => { + const top = turned ? Y + 24 : Y + 30 + gr.row * (lineL + (gr.date ? lineD : 0) + 6); + const left = turned ? gr.x - gr.max : gr.x - gr.max / 2; + const style = turned + ? `left:${r2(left)}px; top:${top}px; width:${gr.max}px; text-align:right; transform-origin:100% 0; transform:rotate(${-L.labels.angle}deg)` + : `left:${r2(left)}px; top:${top}px; width:${gr.max}px; text-align:center`; + return ( + `<div class="pl${turned ? " turned" : ""}" data-k="pl${j}" style="${style}">` + + `<div class="pll">${esc(gr.label)}</div>${gr.date ? `<div class="pld">${esc(gr.date)}</div>` : ""}</div>` + ); + }) + .join(""); + + const rowTop = [Y - 72, Y - 112]; + const markHtml = L.marks + .map((mk, j) => { + const top = rowTop[mk.row] ?? rowTop[0]; + const stick = Y - top - 2; + const label = L.railLabels === "all" + ? `<div class="ml" data-k="ml${j}" style="top:${top - Y}px; ${mk.side === "right" ? "left:18px" : "right:18px"}; max-width:${mk.max}px">${esc(mk.label)}</div>` + : ""; + return ( + `<div class="mf" data-k="mk${j}" style="left:${r2(mk.x)}px; top:${Y}px; --mc:${esc(mk.color)}">` + + `<div class="ms" style="top:${-stick}px; height:${stick}px"></div>` + + `<div class="mh${mk.side === "left" ? " left" : ""}" style="top:${-stick}px"></div>${label}</div>` + ); + }) + .join(""); + + const T = g.totals; + const totalsHtml = L.totals + .map((c, j) => + `<div class="tc" data-k="tc${j}" data-verdict="${esc(c.verdict)}" style="left:${c.x}px; top:${c.y}px; width:${c.width}px; height:${c.height}px; ` + + `--vc:${esc(c.color)}; --vr:${rgba(c.color, 0.45)}; --vl:${mix(c.color, pal.fg, 0.35)}">` + + `<div class="tbar"></div>` + + `<div class="tshape" style="${shapeCss(c.shape, Math.round(T.labelSize * 0.9), esc(c.color))}"></div>` + + `<div class="tnum">${c.count}</div><div class="tlab">${esc(c.label)}</div></div>`) + .join(""); + + const S = g.stats; + const statsHtml = (L.statsTitle && S ? `<div class="stt" data-k="stt" style="left:${S.x}px; top:${S.y}px; width:${S.width}px">${esc(L.statsTitle)}</div>` : "") + + L.stats + .map((s, j) => + `<div class="sc" data-k="sc${j}" style="left:${s.x}px; top:${s.y}px; width:${s.width}px; height:${s.height}px; --sc:${esc(s.color)}">` + + `<div class="sv">${esc(s.value)}</div><div class="sl">${esc(s.label)}</div>${s.note ? `<div class="sn">${esc(s.note)}</div>` : ""}</div>`) + .join(""); + + const cap = g.caption; + const q = g.qr; + const captionHtml = L.captions + .map((c, i) => { + const src = qrSrcs[c.id]; + return ( + `<div class="cap" data-k="cap${i}" data-seg="${esc(c.id)}" style="left:${cap.x}px; top:${cap.y}px; width:${cap.width}px">` + + (c.title ? `<div class="ct">${esc(c.title)}</div>` : "") + + `<div class="cs">${subtitleMarkup(c.subtitle)}</div></div>` + + `<div class="cqr" data-k="qr${i}" style="left:${q.x}px; top:${q.y}px; width:${q.size}px; height:${q.size}px">` + + (src ? `<img src="${esc(src)}" width="${q.size}" height="${q.size}" alt="">` : "") + + `</div>` + ); + }) + .join(""); + + const data = { + from: r4(from), dur, init, + cues: cues.map(({ why, ...c }) => c), + }; + const json = JSON.stringify(data).replace(/</g, "\\u003c"); + const fuseLeft = L.pips[0]?.x ?? rail.track.x0; + const fuseW = L.pips.length > 1 ? L.pips[L.pips.length - 1].x - fuseLeft : 0; + + return `<!doctype html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=${W}, height=${H}" /> + <script src="${esc(gsapSrc)}"></script> + <style> + @font-face { font-family: 'DeckSans'; font-weight: 400; font-style: normal; src: url('${esc(fonts.regular ?? "")}'); } + @font-face { font-family: 'DeckSansBold'; font-weight: 400; font-style: normal; src: url('${esc(fonts.bold ?? "")}'); } + * { margin: 0; padding: 0; box-sizing: border-box; } + html, body { width: ${W}px; height: ${H}px; overflow: hidden; background: transparent; } + body { font-family: 'DeckSans', sans-serif; font-synthesis: none; color: ${pal.fg}; + -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; } + #root { position: relative; width: ${W}px; height: ${H}px; overflow: hidden; } + .stage { position: absolute; inset: 0; } + /* The ground: the clip's box is a hole in it, its reach past any edge. */ + .veil { position: absolute; inset: 0; } + .dg { position: absolute; left: 0; width: ${W}px; background: linear-gradient(180deg, ${L.foot.ground.top} 0%, ${L.foot.ground.bottom} 100%); } + .dplate { position: absolute; top: 0; right: 0; height: 100%; background: ${rgba(pal.bg, 0.45)}; border-left: 1px solid ${rgba(pal.fg, 0.07)}; } + .dt > div { position: absolute; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .dtt { font-family: 'DeckSansBold', sans-serif; font-size: ${L.foot.text.titleSize}px; line-height: ${L.foot.text.titleBox}px; letter-spacing: -0.012em; } + .dts { display: flex; font-size: ${L.foot.text.subtitleSize}px; line-height: ${L.foot.text.subtitleBox}px; color: ${pal.muted}; } + .dts .sep { flex: none; color: ${pal.accent}; padding: 0 0.42em; font-family: 'DeckSansBold', sans-serif; } + .dts .part { flex: none; } + .dts .part:not(:first-child):not(:last-child), .dts .part:first-child:nth-last-child(-n+3) { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; } + .drule { width: ${Math.round(L.foot.text.titleSize * 1.5)}px; height: 4px; border-radius: 2px; background: ${pal.accent}; } + .hole { position: absolute; transform-origin: 0 0; box-shadow: 0 0 0 ${HOLE_REACH}px ${pal.bg}; } + .ground { position: absolute; inset: 0; background: ${pal.bg}; } + .vframe { position: absolute; border-radius: 2px; box-shadow: 0 0 0 1px ${rgba(pal.fg, 0.18)}, 0 10px 34px rgba(0, 0, 0, 0.45); } + .panel { position: absolute; left: ${Math.round(g.margin / 2)}px; top: ${rail.top - 12}px; width: ${W - g.margin}px; + height: ${L.panel.bottom - (rail.top - 12)}px; border-radius: 14px; + background: linear-gradient(180deg, ${panelTop} 0%, ${panelBottom} 100%); + box-shadow: inset 0 1px 0 ${rgba(pal.fg, 0.06)}; } + .track { position: absolute; left: ${rail.track.x0}px; top: ${Y - 2}px; width: ${rail.track.x1 - rail.track.x0}px; height: 4px; + border-radius: 2px; background: ${rgba(pal.fg, 0.14)}; transform-origin: 0 50%; } + .fuse { position: absolute; left: ${r2(fuseLeft)}px; top: ${Y - 2}px; width: ${r2(fuseW)}px; height: 4px; border-radius: 2px; + background: ${pal.accent}; transform-origin: 0 50%; } + .pip { position: absolute; transform-origin: 50% 50%; } + .ring { position: absolute; border-radius: 50%; box-shadow: 0 0 0 3px ${pal.fg}, 0 0 22px 6px ${rgba(pal.accent, 0.5)}; } + .span { position: absolute; height: 2px; border-radius: 1px; background: ${rgba(pal.fg, 0.35)}; } + .pl { position: absolute; white-space: nowrap; } + .pll, .pld { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .pll { font-family: 'DeckSansBold', sans-serif; font-size: ${rail.labelSize}px; line-height: ${lineL}px; color: ${pal.fg}; + text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5); } + .pld { font-size: ${rail.dateSize}px; line-height: ${lineD}px; color: ${pal.muted}; } + .mf { position: absolute; width: 0; height: 0; transform-origin: 0 0; } + .ms { position: absolute; left: -2px; width: 4px; border-radius: 2px; background: var(--mc); } + .mh { position: absolute; left: 2px; width: 16px; height: 14px; background: var(--mc); clip-path: polygon(0% 0%, 100% 50%, 0% 100%); } + .mh.left { left: -18px; clip-path: polygon(100% 0%, 0% 50%, 100% 100%); } + .ml { position: absolute; height: ${Math.round(rail.markerSize * 1.25)}px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + font-family: 'DeckSansBold', sans-serif; font-size: ${rail.markerSize}px; line-height: ${Math.round(rail.markerSize * 1.25)}px; + letter-spacing: 0.04em; text-transform: uppercase; color: var(--mc); text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); margin-top: -${Math.round(rail.markerSize * 0.2)}px; } + .tc { position: absolute; border-radius: 14px; background: ${rgba(pal.fg, 0.045)}; box-shadow: inset 0 0 0 2px var(--vr); + overflow: hidden; transform-origin: 0 0; } + .tbar { position: absolute; left: 0; top: 0; width: 100%; height: 8px; background: var(--vc); } + .tshape { position: absolute; left: 20px; top: 26px; width: ${Math.round((T?.labelSize ?? 24) * 0.9)}px; height: ${Math.round((T?.labelSize ?? 24) * 0.9)}px; } + .tnum { position: absolute; left: 0; top: ${T ? Math.round(T.height * 0.12) : 0}px; width: 100%; text-align: center; + font-family: 'DeckSansBold', sans-serif; font-size: ${T?.numberSize ?? 0}px; line-height: ${T ? Math.round(T.numberSize * 1.1) : 0}px; + color: var(--vc); font-variant-numeric: tabular-nums; letter-spacing: -0.02em; } + .tlab { position: absolute; left: 12px; right: 12px; bottom: ${T ? Math.round(T.height * 0.1) : 0}px; text-align: center; + font-family: 'DeckSansBold', sans-serif; font-size: ${T?.labelSize ?? 0}px; line-height: ${T ? Math.round(T.labelSize * 1.3) : 0}px; + letter-spacing: 0.08em; text-transform: uppercase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--vl); } + .stt { position: absolute; font-family: 'DeckSansBold', sans-serif; font-size: ${S?.titleSize ?? 0}px; line-height: ${S?.titleH ?? 0}px; + letter-spacing: 0.06em; text-transform: uppercase; color: ${pal.muted}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .sc { position: absolute; border-radius: 12px; background: ${rgba(pal.fg, 0.04)}; box-shadow: inset 0 0 0 1px ${rgba(pal.fg, 0.1)}; + padding: ${S ? Math.round(Math.min(18, S.cardH * 0.1)) : 0}px 18px; overflow: hidden; + display: flex; flex-direction: column; justify-content: center; border-left: 5px solid var(--sc); } + .sv { font-family: 'DeckSansBold', sans-serif; font-size: ${S?.valueSize ?? 0}px; line-height: 1.05; color: var(--sc); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; } + .sl { font-family: 'DeckSansBold', sans-serif; font-size: ${S?.labelSize ?? 0}px; line-height: 1.25; color: ${pal.fg}; + margin-top: 4px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } + .sn { font-size: ${S?.noteSize ?? 0}px; line-height: 1.25; color: ${pal.muted}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .cap { position: absolute; } + .ct { font-family: 'DeckSansBold', sans-serif; font-size: ${cap.titleSize}px; line-height: ${Math.round(cap.titleSize * 1.2)}px; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .cs { display: flex; white-space: nowrap; overflow: hidden; font-size: ${cap.subSize}px; line-height: ${Math.round(cap.subSize * 1.3)}px; color: ${pal.muted}; } + .cs .part { flex: none; } + .cs .part:not(:first-child):not(:last-child), .cs .part:first-child:nth-last-child(-n+3) { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; } + .cs .sep { flex: none; color: ${pal.accent}; padding: 0 0.42em; font-family: 'DeckSansBold', sans-serif; } + .cqr { position: absolute; transform-origin: 0 0; } + .cqr img { display: block; width: 100%; height: 100%; border-radius: 6px; image-rendering: pixelated; + box-shadow: 0 0 0 1px ${rgba(pal.fg, 0.25)}, 0 6px 18px rgba(0, 0, 0, 0.35); } + </style> + </head> + <body> + <div id="root" data-composition-id="finale" data-start="0" data-duration="${pageDuration(dur, fps)}" data-width="${W}" data-height="${H}"> + <div id="finale-clip" class="clip" data-start="0" data-duration="${pageDuration(dur, fps)}" data-track-index="1"> + <div class="stage" data-k="stage"> + ${hole} + ${deckCopy} + <div class="panel" data-k="panel"></div> + <div class="track" data-k="track"></div> + ${L.pips.length > 1 ? `<div class="fuse" data-k="fuse"></div>` : ""} + ${spans}${markHtml}${pipHtml} + ${labelHtml} + ${totalsHtml} + ${statsHtml} + ${captionHtml} + </div> + </div> + </div> + + <script id="finale-data" type="application/json">${json}</script> + <script> + const F = JSON.parse(document.getElementById("finale-data").textContent); + const byK = {}; + for (const el of document.querySelectorAll("[data-k]")) byK[el.dataset.k] = el; + // The footage move's ease (build-video moveFilter): 3p² − 2p³. + const EASES = { smoothstep: (p) => p * p * (3 - 2 * p) }; + for (const k of Object.keys(F.init)) if (byK[k]) gsap.set(byK[k], F.init[k]); + const inner = gsap.timeline({ paused: true }); + for (const c of F.cues) { + const el = byK[c.k]; + if (!el) continue; + inner.fromTo(el, c.from, { ...c.to, duration: c.dur, ease: EASES[c.ease] ?? c.ease, immediateRender: false }, c.at); + } + // The cues are in the cut's clock; the window plays [from, from + dur] of it. + const tl = gsap.timeline({ paused: true }); + tl.add(inner.tweenFromTo(F.from, F.from + F.dur, { duration: F.dur, ease: "none" }), 0); + window.__timelines = window.__timelines || {}; + window.__timelines["finale"] = tl; + const ready = Promise.all([ + document.fonts.load("28px DeckSansBold"), + document.fonts.load("24px DeckSans"), + ]).catch(() => {}).then(() => { document.documentElement.dataset.fit = "1"; }); + const params = new URLSearchParams(location.search); + // The review still, in CUT seconds. + const still = params.get("still"); + if (still !== null) { + const at = Math.max(0, Math.min(F.dur, Number(still) - F.from)); + tl.seek(at, false); + ready.then(() => tl.seek(at, false)); + } + </script> + </body> +</html> +`; +} diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -51,6 +51,7 @@ import { stampsDrawn } from "./factcheck.mjs"; import { threadsHtml } from "./chrome-threads.mjs"; import { flipsHtml } from "./chrome-flips.mjs"; import { statsHtml } from "./chrome-stats.mjs"; +import { finaleHtml, finaleLayout } from "./chrome-finale.mjs"; import { fxGeometry } from "./deck.mjs"; const run = promisify(execFile); @@ -807,6 +808,19 @@ async function regionHtml(region, { manifest, manifestDir, base, projDir, assets const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); return statsHtml(schedule, manifest.render, { fonts, from, duration }); } + if (region === "finale") { + // The finale (chrome-finale.mjs): the deck's faces and QR maker, one page + // for its window. + const render = manifest.render; + const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + const L = finaleLayout(schedule, render); + const qrSrcs = {}; + if (resolveDeck(render).qr.show) { + const byUrl = await qrPngsFor(L.captions.map((c) => c.qrUrl), render, L.geo.qr.size, assetsDir); + for (const c of L.captions) if (c.qrUrl) qrSrcs[c.id] = byUrl.get(c.qrUrl); + } + return finaleHtml(schedule, render, window, { fonts, qrSrcs }); + } if (region === "teaser") { // A page module reached by a dynamic import, so nothing that imports this // file -- umtool's preview helper, the build -- loads its face's URL @@ -945,7 +959,7 @@ export async function composeChrome({ // The regions keyed by the render cache: the two drawn from the deck's // schedule, and a teaser, drawn from its own timeline entry. const keyed = region === "deck" || region === "feed" || region === "posts" || region === "teaser" || region === "stamp" || - region === "threads" || region === "flips" || region === "stats" || region === "fx"; + region === "threads" || region === "flips" || region === "stats" || region === "fx" || region === "finale"; // The regions drawn over the whole cut from its schedule, windowable alike. const wholeCut = region === "deck" || region === "feed" || region === "stamp" || region === "threads" || region === "flips" || region === "stats" || region === "fx"; @@ -957,7 +971,7 @@ export async function composeChrome({ if (errors.length) throw new Error(`teaser ${teaser.id}: ${errors.join("; ")}`); } let sched = schedule; - if ((wholeCut || region === "posts") && !sched) { + if ((wholeCut || region === "posts" || region === "finale") && !sched) { const p = path.join(base, "schedule.json"); try { sched = JSON.parse(await readFile(p, "utf8")); @@ -981,6 +995,9 @@ export async function composeChrome({ if (region === "fx" && !sched.fx) { throw new Error("the fx region needs a schedule with an effect on (render.chrome.fx)"); } + if (region === "finale" && !sched.finale) { + throw new Error("the finale region needs a schedule with a finale (a clip with layout \"finale\", render.chrome.deck.finale)"); + } if (region === "stamp" && !sched.factcheck?.stamps?.length) { throw new Error("the stamp region needs a schedule that stamps a claim (an entry with a `claim`)"); } @@ -1007,10 +1024,14 @@ export async function composeChrome({ if (!/^[A-Za-z0-9_-]+$/.test(String(want.segment))) throw new Error(`posts: ${want.segment} is not a segment id`); win = snapWindow(want, { fps: rate, total }); } + // The finale's window: the schedule's, snapped outward to the frame grid. + if (region === "finale") win = snapWindow({ segment: "finale", from: sched.finale.from, to: sched.finale.to }, { fps: rate, total }); const projName = region === "posts" ? `posts-${preview ? "preview-" : ""}${win.segment}` + : region === "finale" + ? `finale${preview ? "-preview" : ""}` : region === "teaser" ? `teaser-${preview ? "preview-" : ""}${teaser.id}` : wholeCut && preview ? `${region}-preview` : `${region}${suffix}`; @@ -1065,7 +1086,7 @@ export async function composeChrome({ // A sequence is a directory; every other format is a file. const sequence = format === "png-sequence"; - const stem = region === "posts" ? `posts-${win.segment}` : region === "teaser" ? `teaser-${teaser.id}` : `${region}${suffix}`; + const stem = region === "posts" ? `posts-${win.segment}` : region === "finale" ? "finale" : region === "teaser" ? `teaser-${teaser.id}` : `${region}${suffix}`; const target = sequence ? path.join(base, "chrome", `${stem}-frames`) : path.join(base, "chrome", `${stem}.${format}`); @@ -1112,7 +1133,7 @@ if (import.meta.url === `file://${process.argv[1]}`) { const manifestPath = argv.find((a, i) => !a.startsWith("--") && !VALUED.has(argv[i - 1])); if (!manifestPath) { console.error( - "usage: compose-chrome.mjs <manifest.json> [--region chart|deck|feed|stamp|stats|threads|flips|fx|posts|teaser] [--variant sourced|full]\n" + + "usage: compose-chrome.mjs <manifest.json> [--region chart|deck|feed|stamp|stats|threads|flips|fx|posts|finale|teaser] [--variant sourced|full]\n" + " [--segment <id>] (posts: the clip whose window to compose; teaser: its entry)\n" + " [--from <s>] [--duration <s>] [--out <dir>] [--preview]\n" + " [--still <s> --png <path>]\n" + @@ -1135,7 +1156,7 @@ if (import.meta.url === `file://${process.argv[1]}`) { still: num("--still"), png: flag("--png"), // The deck renders four-wide by default; the band keeps the renderer's own default. - workers: num("--workers") ?? (region === "deck" || region === "feed" || region === "teaser" || region === "fx" ? 4 : region === "posts" || region === "stamp" || region === "stats" || region === "threads" || region === "flips" ? 2 : null), + workers: num("--workers") ?? (region === "deck" || region === "feed" || region === "teaser" || region === "fx" ? 4 : region === "posts" || region === "finale" || region === "stamp" || region === "stats" || region === "threads" || region === "flips" ? 2 : null), quality: flag("--quality") ?? "high", format: flag("--format") ?? "png-sequence", fps: num("--fps"), diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -26,6 +26,7 @@ import { flipSchedule, flipsOn, validateFlips } from "./flips.mjs"; import { overlayPointsOf, resolveStats, statsSchedule, statsWanted, validateStats } from "./stats.mjs"; import { fxOn, fxSchedule, validateFx } from "./fx.mjs"; import { estimatedNarratedCardSeconds, hasNarration } from "./narration.mjs"; +import { FINALE_MOTION, finaleGeometry, finaleRunOf, finaleRunProblems, resolveFinale, validateFinaleSettings } from "./finale.mjs"; /** Is the left panel on: the thread rail (threads.mjs) or the flips panel (flips.mjs) -- one region, one or the other. */ export const railOn = (render) => threadsOn(render) || flipsOn(render); @@ -211,7 +212,10 @@ export function validateChrome(chrome, render = {}) { const d = chrome.deck ?? {}; if (!isObj(d)) return [...errors, "render.chrome.deck must be an object"]; const w = "render.chrome.deck"; - unknownKeys(d, Object.keys(DECK_DEFAULTS), w, errors); + // `finale` (finale.mjs) is the deck's too, with no default to fill: absent, + // nothing about the deck changes. + unknownKeys(d, [...Object.keys(DECK_DEFAULTS), "finale"], w, errors); + errors.push(...validateFinaleSettings(d.finale, `${w}.finale`)); if (d.height !== undefined && !(Number.isInteger(d.height) && numIn(d.height, 120, 400))) { errors.push(`${w}.height must be a whole number of pixels from 120 to 400`); @@ -956,20 +960,31 @@ export function deckSchedule({ // and the posts' timing below are measured with it. `durs` are the segments' // own (probed or estimated) lengths. (The feed holds nothing: postHolds.) const holds = deck.posts.show ? postHolds({ posts, entries, metas, render }) : new Map(); + // The finale (finale.mjs): the run of entries marked `layout: "finale"`, + // when it is one the deck draws. Its clips hold for nothing and carry no + // posts. None: everything below is as it always was. + const fin = finaleRunOf(entries) && !finaleRunProblems(entries).length ? finaleRunOf(entries) : null; + const finIds = new Set(fin ? entries.slice(fin.first, fin.last + 1).map((e) => e.id) : []); + for (const id of finIds) holds.delete(id); const full = durs.map((d, i) => d + (holds.get(entries[i].id) ?? 0)); const { starts, total } = scheduleFrom(full, D); const multiChannel = isMultiChannel(entries, provenance); const round = (v) => Math.round(v * 1000) / 1000; const segs = entries.map((e, i) => ({ id: e.id, start: starts[i], duration: full[i] })); - const placed = deck.posts.show ? postSchedule({ posts, entries, metas, segments: segs, D, total, render, provenance }) : []; + const scheduled = deck.posts.show ? postSchedule({ posts, entries, metas, segments: segs, D, total, render, provenance }) : []; // The feed is a layout only when it has posts to draw: a feed with none is // the deck alone, and writes the schedule a deck without posts always did. - const feed = placed.length > 0 && deck.posts.layout === "feed"; + // (Decided before the finale's posts are left out: the build frames the + // cut's footage by the same rule, feedOn.) + const feed = scheduled.length > 0 && deck.posts.layout === "feed"; + // A popup over a finale clip is not drawn (no hold, no footage move); the + // feed's column keeps every post, under the finale's page while it is up. + const placed = fin && !feed ? scheduled.filter((p) => !finIds.has(p.segment)) : scheduled; const moves = placed.length && !feed ? footageMoves({ posts: placed, segments: segs, render }) : []; // A claim stamped at a source second (`claim.at`) needs the source second // its segment starts at: the cut record's (`clipClock`), else the play // window's estimate. Only then: a cut without `at` places what it did. - const stamps = stampSchedule({ + const stamped = stampSchedule({ segments: segs.map((s, i) => { const claim = claimOf(entries[i]); if (claim?.at === undefined) return { ...s, claim }; @@ -978,6 +993,17 @@ export function deckSchedule({ }), D, total, render, }); + // The finale: when it opens, how, where its clips play, and the window its + // page covers. A stamp that would land during it counts as it opens instead + // -- its totals are final -- and is not drawn: there is no footage box to + // stamp, and the clip before is not the claim's. + const finale = fin ? finaleSchedule({ entries, segs, fin, D, total, render, feed, metas, provenance, deck }) : null; + const stamps = finale + ? stamped.map((s) => (finIds.has(s.segment) + ? { ...s, at: finale.start, landed: finale.start, out: [finale.start, finale.start], stamp: false, finale: true } + : s)) + : stamped; + const allMoves = finale ? [...moves, ...finale.moves] : moves; const threads = threadsOn(render) ? threadSchedule({ segments: segs.map((s, i) => ({ ...s, thread: threadOf(entries[i]) })), D, total, render, moves }) : null; @@ -1034,8 +1060,12 @@ export function deckSchedule({ // And on one stamped at a source second, the second its segment starts // at -- what placed the stamp, kept for a preview to place it again. ...(claimOf(e)?.at !== undefined ? { sourceFrom: round(clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from) } : {}), + // Only on a finale clip, likewise. + ...(finIds.has(e.id) ? { finale: true } : {}), }; }), + // The finale: present only when the cut has one. + ...(finale ? { finale: finale.doc } : {}), // The fact-check stamps: present only when a claim is stamped. ...(stamps.length ? { factcheck: { stamps: roundStamps(stamps) } } : {}), // The thread rail: present only when it is on. @@ -1049,7 +1079,86 @@ export function deckSchedule({ // Present only when there are posts to draw, so a cut without them writes // the schedule it always did. ...(placed.length ? { posts: roundPosts(placed) } : {}), - ...(moves.length ? { moves: moves.map((m) => ({ ...m, at: round(m.at), segmentAt: round(m.segmentAt) })) } : {}), + ...(allMoves.length ? { moves: allMoves.map((m) => ({ ...m, at: round(m.at), segmentAt: round(m.segmentAt) })) } : {}), + }; +} + +/** + * The finale's part of the schedule (finale.mjs), from the cut's segments and + * the run `fin` (`{ first, last }` entry indices): + * + * - `start`: the run's first segment's start; `at`: when its motion starts -- + * "grow": once the dissolve into it is over and the deck's words have come + * in (start + max(D, D/2 + 0.08 + deck.motion.in)), "cut": the start; + * - `cover`: when its page's ground is opaque; `hide`: when the deck goes + * ("grow": at `at` -- the page draws the deck's ground and pieces where it + * stood and takes over from them; "cut": at `cover`); + * - `from`/`to`: the page's window -- from `at`, to the end of the cut or + * through the dissolve out of the run, its `out`; + * - `box`: the clip's box (null with `video: "hidden"`), `footage`: the box + * the clip is in until then (the deck's or the feed's); + * - `dates`: each segment's date as the deck prints it, for the rail's labels; + * - and `moves` (not in the document): each finale clip's footage into the + * box -- the first grown over FINALE_MOTION.grow from `at` ("grow"), every + * other one there from its first frame. "hidden" moves nothing: the page + * covers it. + */ +function finaleSchedule({ entries, segs, fin, D, total, render, feed, metas, provenance, deck }) { + const f = resolveFinale(render); + const round = (v) => Math.round(v * 1000) / 1000; + const first = segs[fin.first]; + const start = first.start; + const grow = f.motion === "grow" ? FINALE_MOTION.grow : 0; + // "grow" starts once the dissolve into the run is over and the deck has + // handed its words over to the first finale clip (deckChoreography). + const at = f.motion === "grow" ? start + Math.max(D, D / 2 + 0.08 + deck.motion.in) : start; + const cover = f.motion === "grow" ? at + FINALE_MOTION.cover : start + D; + // The deck goes as the grow starts (the page draws its ground and pieces + // where it stood), or once the dissolved-in page covers it. + const hide = f.motion === "grow" ? at : cover; + const next = segs[fin.last + 1] ?? null; + const out = next ? (D > 0 ? [next.start, next.start + D] : [next.start, next.start]) : null; + const to = out ? out[1] : total; + const footage = feed ? feedGeometry(render).footage : deckGeometry(render).footage; + const box = f.video === "hidden" ? null : finaleGeometry(render).video; + const moves = []; + if (box) { + for (let i = fin.first; i <= fin.last; i += 1) { + const s = segs[i]; + const lead = i === fin.first; + moves.push({ + segment: s.id, at: lead ? at : s.start, segmentAt: lead ? at - s.start : 0, seconds: lead ? grow : 0, from: footage, to: box, + }); + } + } + const dates = {}; + entries.forEach((e, i) => { + if (e.type !== "clip" && e.type !== "image") return; + const meta = metas[i] ?? {}; + const date = e.type === "clip" ? attributionParts(e, meta, provenance).date : String(e.date ?? "").trim(); + const printed = deckSubtitle({ channel: "", title: "", date, at: null }, { ...deck.subtitle, parts: ["date"] }, false); + if (printed) dates[e.id] = printed; + }); + return { + start, + moves, + cover, + doc: { + segments: segs.slice(fin.first, fin.last + 1).map((s) => s.id), + video: f.video, + motion: f.motion, + start: round(start), + at: round(at), + grow, + cover: round(cover), + hide: round(hide), + from: round(at), + to: round(to), + ...(out ? { out: out.map(round) } : {}), + box, + footage, + dates, + }, }; } @@ -1112,11 +1221,34 @@ export function deckChoreography(schedule, render) { const handovers = []; const visibility = []; const slide = Math.max(D, inn); + // A finale segment (finale.mjs) is away from the deck as a card is: the + // finale's page takes the footer's place, which goes at `finale.hide`. + const away = (s) => !!(s.hideDeck || s.finale); + const finaleOff = schedule.finale?.hide; + const handover = (i, m) => ({ + i, + from: segs[i - 1].id, + to: segs[i].id, + m, + out: [m - out, m], + in: [m, m + inn], + sub: [m + 0.08, m + 0.08 + inn], + qr: [m - 0.125, m + 0.125], + pip: [m - pip / 2, m + pip / 2], + }); if (segs.length && segs[0].hideDeck) visibility.push({ i: 0, hide: true, at: [0, 0] }); for (let i = 1; i < segs.length; i += 1) { const m = segs[i].start + D / 2; - const a = segs[i - 1].hideDeck; - const b = segs[i].hideDeck; + const a = away(segs[i - 1]); + const b = away(segs[i]); + // Into the finale: the deck hands over to its first clip as to any clip + // -- the finale's page takes over from what it then shows -- and goes in + // the instant the finale says (`finale.hide`). + if (!a && b && segs[i].finale && !segs[i].hideDeck && Number.isFinite(finaleOff)) { + handovers.push(handover(i, m)); + visibility.push({ i, hide: true, at: [finaleOff, finaleOff] }); + continue; + } if (a !== b) { // Gone before the card is fully up; back once the footage is. Into a // teaser that dips, the deck is gone in an instant at the frame the @@ -1129,17 +1261,7 @@ export function deckChoreography(schedule, render) { continue; } if (b) continue; - handovers.push({ - i, - from: segs[i - 1].id, - to: segs[i].id, - m, - out: [m - out, m], - in: [m, m + inn], - sub: [m + 0.08, m + 0.08 + inn], - qr: [m - 0.125, m + 0.125], - pip: [m - pip / 2, m + pip / 2], - }); + handovers.push(handover(i, m)); } return { handovers, visibility }; } diff --git a/umtool/report-to-video/finale.mjs b/umtool/report-to-video/finale.mjs @@ -0,0 +1,461 @@ +// The deck's FINALE layout: the cut's last clips with the timeline in primary +// view. +// +// timeline entry: "layout": "finale" (a clip; default "clip") +// render.chrome.deck.finale: { +// "video": "side" | "corner" | "hidden", the clip's box (default "side") +// "motion": "grow" | "cut", how the layout comes in (default "grow") +// "totals": true, the tally's final counts, large +// "stats": [{ "label", "value", "note"?, "color"? }], up to 8, the author's words +// "statsTitle": "…", over the stats (optional) +// "railLabels": "all" | "nodes" every label and date and the markers' labels, +// } or each pip's label alone (default "all") +// +// While a finale entry plays, the footer's rail is redrawn large across the +// top of the frame (every pip lit, the whole history), the totals panel and +// the stats cards stand under it, and the clip plays in a smaller box -- or is +// heard only -- with its title, source line and QR kept beside it. The deck +// footer and the posts are not drawn over it. chrome-finale.mjs draws the +// page; deck.mjs puts the run, the clip's move and the window in the schedule. +// +// The run: the entries marked `layout: "finale"` are ONE run of consecutive +// clips, after at least one clip, and no clip follows it (a card, a still or +// a teaser may) -- the rail it shows is the whole history, complete. +// +// PURE, like deck.mjs: validation, defaults, geometry, the rail's labels. No +// fs, no ffmpeg, and no import of deck.mjs (deck.mjs imports this file). + +/** An entry's layout: the clip as ever, or the finale. */ +export const ENTRY_LAYOUTS = Object.freeze(["clip", "finale"]); + +/** Where the clip plays during the finale: a box at the side, a corner, or sound only. */ +export const FINALE_VIDEOS = Object.freeze(["side", "corner", "hidden"]); + +/** How the finale comes in: the footer grows into it, or a dissolve straight to it. */ +export const FINALE_MOTIONS = Object.freeze(["grow", "cut"]); + +/** What the large rail labels: everything (labels, dates, markers) or the pips' labels only. */ +export const FINALE_RAIL_LABELS = Object.freeze(["all", "nodes"]); + +/** The palette keys a stat's `color` may name (else a `#rgb` / `#rrggbb`). */ +export const FINALE_PALETTE_KEYS = Object.freeze(["fg", "muted", "accent", "amber"]); + +/** How many stats, and each field's characters. */ +export const FINALE_LIMITS = Object.freeze({ stats: 8, label: 32, value: 16, note: 60, statsTitle: 40 }); + +/** Every finale setting and its default. */ +export const FINALE_DEFAULTS = Object.freeze({ + video: "side", + motion: "grow", + totals: true, + stats: Object.freeze([]), + statsTitle: null, + railLabels: "all", +}); + +/** + * The motion's seconds: the grow (footage box, rail and tally into their + * places), when the ground over the rest is opaque, and the labels' and + * cards' entrance after it. + */ +export const FINALE_MOTION = Object.freeze({ grow: 0.8, cover: 0.45, reveal: 0.35, stagger: 0.06 }); + +/** The legibility floors the geometry keeps (1080p px): the tests hold it to them. */ +export const FINALE_MIN = Object.freeze({ railLabel: 24, totals: 96, pipScale: 2 }); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/; +const even = (v) => Math.round(v / 2) * 2; + +/** One line of at most `max` characters, or a reason it is not. */ +function lineProblem(v, max, where, { required = true } = {}) { + if (v === undefined && !required) return null; + if (typeof v !== "string") return `${where} must be text`; + const s = v.trim(); + if (!s) return required ? `${where} must not be empty` : null; + if (/[\r\n]/.test(s)) return `${where} must be one line`; + if ([...s].length > max) return `${where} is ${[...s].length} characters (at most ${max})`; + return null; +} + +/** + * Every reason `render.chrome.deck.finale` cannot be drawn, as sentences. + * Unknown keys are refused, as the deck's are. validateChrome calls this. + * + * @returns {string[]} + */ +export function validateFinaleSettings(f, where = "render.chrome.deck.finale") { + if (f === undefined) return []; + if (!isObj(f)) return [`${where} must be an object`]; + const errors = []; + for (const k of Object.keys(f)) { + if (!(k in FINALE_DEFAULTS)) errors.push(`${where}.${k} is not a finale setting (${Object.keys(FINALE_DEFAULTS).join(", ")})`); + } + const oneOf = (k, list) => { + if (f[k] !== undefined && !list.includes(f[k])) errors.push(`${where}.${k} must be ${list.map((v) => `"${v}"`).join(", ")}`); + }; + oneOf("video", FINALE_VIDEOS); + oneOf("motion", FINALE_MOTIONS); + oneOf("railLabels", FINALE_RAIL_LABELS); + if (f.totals !== undefined && typeof f.totals !== "boolean") errors.push(`${where}.totals must be true or false`); + if (f.statsTitle !== undefined && f.statsTitle !== null) { + const p = lineProblem(f.statsTitle, FINALE_LIMITS.statsTitle, `${where}.statsTitle`); + if (p) errors.push(p); + } + if (f.stats !== undefined) { + if (!Array.isArray(f.stats)) errors.push(`${where}.stats must be a list of { label, value, note?, color? }`); + else { + if (f.stats.length > FINALE_LIMITS.stats) errors.push(`${where}.stats has ${f.stats.length} (at most ${FINALE_LIMITS.stats})`); + f.stats.forEach((s, i) => { + const at = `${where}.stats[${i}]`; + if (!isObj(s)) { errors.push(`${at} must be { label, value, note?, color? }`); return; } + for (const k of Object.keys(s)) { + if (!["label", "value", "note", "color"].includes(k)) errors.push(`${at}.${k} is not a stat field (label, value, note, color)`); + } + for (const p of [ + lineProblem(s.label, FINALE_LIMITS.label, `${at}.label`), + lineProblem(typeof s.value === "number" && Number.isFinite(s.value) ? String(s.value) : s.value, FINALE_LIMITS.value, `${at}.value`), + lineProblem(s.note, FINALE_LIMITS.note, `${at}.note`, { required: false }), + ]) if (p) errors.push(p); + if (s.color !== undefined && !(typeof s.color === "string" && (HEX_RE.test(s.color) || FINALE_PALETTE_KEYS.includes(s.color)))) { + errors.push(`${at}.color must be a #hex colour or one of ${FINALE_PALETTE_KEYS.join(", ")}`); + } + }); + } + } + return errors; +} + +/** The finale settings with every default filled in (the stats trimmed, a number value as text). */ +export function resolveFinale(render) { + const f = isObj(render?.chrome?.deck?.finale) ? render.chrome.deck.finale : {}; + const stats = Array.isArray(f.stats) ? f.stats : []; + return { + ...FINALE_DEFAULTS, + ...f, + stats: stats.filter(isObj).map((s) => ({ + label: String(s.label ?? "").trim(), + value: String(s.value ?? "").trim(), + ...(typeof s.note === "string" && s.note.trim() ? { note: s.note.trim() } : {}), + ...(typeof s.color === "string" ? { color: s.color } : {}), + })), + statsTitle: typeof f.statsTitle === "string" && f.statsTitle.trim() ? f.statsTitle.trim() : null, + }; +} + +/** Is this entry marked for the finale? */ +export const isFinale = (entry) => entry?.layout === "finale"; + +/** + * The finale run in a cut's entries (one variant's, in order): the first and + * last index of the entries marked `layout: "finale"`, or null when none is. + * Shape only -- `finaleRunProblems` says whether it is a run the deck draws. + * + * @returns {{ first: number, last: number } | null} + */ +export function finaleRunOf(entries = []) { + let first = -1, last = -1; + entries.forEach((e, i) => { + if (!isFinale(e)) return; + if (first < 0) first = i; + last = i; + }); + return first < 0 ? null : { first, last }; +} + +/** + * Why one cut's finale entries are not a run the deck draws, as sentences: + * consecutive, clips only, at least one clip before them and none after. + * + * @returns {string[]} + */ +export function finaleRunProblems(entries = [], label = "") { + const run = finaleRunOf(entries); + if (!run) return []; + const errors = []; + const cut = label ? ` (the ${label} cut)` : ""; + for (let i = run.first; i <= run.last; i += 1) { + const e = entries[i]; + if (!isFinale(e)) { + errors.push(`the finale entries must be consecutive${cut}: ${e?.id ?? "?"} sits between them without layout "finale"`); + break; + } + } + if (!entries.slice(0, run.first).some((e) => e?.type === "clip")) { + errors.push(`the finale${cut} needs a clip before it: the rail it shows is the history so far`); + } + const after = entries.slice(run.last + 1).find((e) => e?.type === "clip"); + if (after) errors.push(`no clip may follow the finale${cut}: ${after.id ?? "?"} does (a card, a still or a teaser may)`); + return errors; +} + +/** + * Every timeline entry's `layout`, checked: one of ENTRY_LAYOUTS, "finale" + * only on a clip, and -- in each cut a variant makes of the timeline -- one + * run as `finaleRunProblems` says. The build and the lint refuse with these; + * umtool's finale writer refuses before it writes. + * + * @returns {string[]} + */ +export function validateFinaleEntries(manifest) { + const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const errors = []; + timeline.forEach((e, i) => { + if (e?.layout === undefined) return; + const where = `timeline[${i}] (${e?.id ?? "?"}).layout`; + if (!ENTRY_LAYOUTS.includes(e.layout)) errors.push(`${where} must be ${ENTRY_LAYOUTS.map((l) => `"${l}"`).join(" or ")}`); + else if (e.layout === "finale" && e.type !== "clip") errors.push(`${where}: "finale" is a clip's layout, not a ${e.type ?? "entry"}'s`); + }); + if (errors.length || !timeline.some(isFinale)) return errors; + // Each cut the variants make (selectVariant's filter): one run in each. + const variants = timeline.some((e) => e?.variant) ? ["sourced", "full"] : [null]; + for (const v of variants) { + const cut = timeline.filter((e) => !e?.variant || e.variant === v); + errors.push(...finaleRunProblems(cut, v ?? "")); + } + return [...new Set(errors)]; +} + +// --------------------------------------------------------------------------- +// Geometry. Frame px; the 1080p numbers are the design, scaled with the frame. +// --------------------------------------------------------------------------- + +/** + * About how wide a line of text draws, px, in the deck's sans at `size` (bold + * or not): each character at a generous advance for its kind, so a label + * called fitting does fit. Mixed case (the finale does not upper-case its + * pip labels; markers' labels are measured upper-cased by the caller). + */ +export function textWidth(text, size, bold = true) { + let em = 0; + for (const ch of String(text ?? "")) { + if (ch === " ") em += 0.25; + else if (/[.,:;'!|’‘]/.test(ch)) em += 0.27; + else if (/[0-9]/.test(ch)) em += 0.57; + else if (/[MW@&mw]/.test(ch)) em += 0.86; + else if (/[A-Z]/.test(ch)) em += 0.64; + else if (/[a-z]/.test(ch)) em += 0.53; + else em += 0.6; + } + return Math.ceil(em * size * (bold ? 1.04 : 1)); +} + +/** + * Where everything sits in the finale's frame, px. `verdicts` is how many + * cells the totals panel has (0: none), `stats` how many cards. + * + * At 1920×1080: the rail across the top (y 36–412, the track at `rail.y`); + * under it the lower area (y 448–1044). "side": the clip 768×432 at the + * right (40 % of the width), its caption under it with the QR at its end; + * the totals and stats in the left column (1008 wide). "corner": the clip + * 538×302 (28 %) in the bottom-right corner over its caption; the column + * 1238 wide. "hidden": no box; the caption and QR at the top of a right + * column, the left as in "corner". The totals' numbers are 128 px (≥ 96), + * the rail's labels 28 px and its dates 24. + * + * @returns {{ W: number, H: number, k: number, margin: number, + * rail: { top: number, bottom: number, y: number, x0: number, x1: number, labelSize: number, dateSize: number, markerSize: number }, + * video: { x: number, y: number, width: number, height: number } | null, + * caption: { x: number, y: number, width: number, titleSize: number, subSize: number }, + * qr: { x: number, y: number, size: number }, + * totals: { x: number, y: number, width: number, height: number, cell: number, gap: number, numberSize: number, labelSize: number } | null, + * stats: { x: number, y: number, width: number, height: number, titleSize: number, titleH: number, + * cols: number, rows: number, cardW: number, cardH: number, gap: number, valueSize: number, labelSize: number, noteSize: number } | null, + * column: { x: number, y: number, width: number, height: number } }} + */ +export function finaleGeometry(render, { verdicts = 0, stats = 0, statsTitle = false } = {}) { + const W = render?.width ?? 1920; + const H = render?.height ?? 1080; + const k = W / 1920; + const kh = H / 1080; + const px = (v) => Math.round(v * k); + const py = (v) => Math.round(v * kh); + const m = px(48); + const f = resolveFinale(render); + const rail = { + top: py(36), bottom: py(412), y: py(176), + x0: px(120), x1: W - px(96), + labelSize: Math.max(FINALE_MIN.railLabel, px(28)), dateSize: Math.max(FINALE_MIN.railLabel, px(24)), + markerSize: Math.max(FINALE_MIN.railLabel, px(24)), + }; + const lowTop = py(448); + const lowBottom = H - py(36); + let video = null; + let caption; + let qr; + let colRight; + const capTitle = px(34), capSub = Math.max(20, px(24)); + const capH = Math.round(capTitle * 1.2) + Math.round(capSub * 1.3) + py(8); + if (f.video === "side") { + const vw = even(W * 0.4), vh = even((vw * H) / W); + video = { x: W - m - vw, y: lowTop, width: vw, height: vh }; + const size = Math.min(px(112), lowBottom - (video.y + vh + py(14))); + qr = { x: video.x + vw - size, y: video.y + vh + py(14), size }; + caption = { x: video.x, y: video.y + vh + py(14), width: vw - size - px(20), titleSize: capTitle, subSize: capSub }; + colRight = video.x - m; + } else if (f.video === "corner") { + const vw = even(W * 0.28), vh = even((vw * H) / W); + const size = px(96); + video = { x: W - m - vw, y: lowBottom - size - py(12) - vh, width: vw, height: vh }; + qr = { x: video.x + vw - size, y: lowBottom - size, size }; + caption = { x: video.x, y: lowBottom - size, width: vw - size - px(16), titleSize: capTitle, subSize: capSub }; + colRight = video.x - m; + } else { + const cw = even(W * 0.28); + const size = px(112); + caption = { x: W - m - cw, y: lowTop, width: cw, titleSize: capTitle, subSize: capSub }; + qr = { x: W - m - size, y: lowTop + capH + py(16), size }; + colRight = caption.x - m; + } + const column = { x: m, y: lowTop, width: colRight - m, height: lowBottom - lowTop }; + let totals = null; + let y = lowTop; + if (verdicts > 0) { + const gap = px(20); + const cell = Math.min(px(320), Math.floor((column.width - (verdicts - 1) * gap) / verdicts)); + const height = stats > 0 ? py(236) : Math.min(py(320), column.height); + totals = { + x: column.x, y, width: verdicts * cell + (verdicts - 1) * gap, height, cell, gap, + numberSize: Math.max(FINALE_MIN.totals, Math.round(Math.min(height * 0.54, cell * 0.62))), + labelSize: Math.max(20, px(24)), + }; + y += height + py(28); + } + let statsBox = null; + if (stats > 0) { + const titleSize = Math.max(22, px(28)); + const titleH = statsTitle ? Math.round(titleSize * 1.5) : 0; + const height = lowBottom - y; + // Up to three in a row; four as two by two; then three or four to a row. + const cols = stats <= 3 ? stats : stats === 4 ? 2 : stats <= 6 ? 3 : 4; + const rows = Math.ceil(stats / cols); + const gap = px(16); + const cardW = Math.floor((column.width - (cols - 1) * gap) / cols); + // At most 220 px a card in one row, 170 in two: a card is a number and two lines, not a poster. + const cardH = Math.min(Math.floor((height - titleH - (rows - 1) * gap) / rows), py(rows > 1 ? 170 : 220)); + statsBox = { + x: column.x, y, width: column.width, height, titleSize, titleH, cols, rows, cardW, cardH, gap, + valueSize: Math.max(40, Math.round(Math.min(cardH * (rows > 1 ? 0.4 : 0.42), px(rows > 1 ? 56 : 80)))), + labelSize: Math.max(18, px(22)), + noteSize: Math.max(16, px(18)), + }; + } + return { W, H, k, margin: m, rail, video, caption, qr, totals, stats: statsBox, column }; +} + +/** + * Does `label` already say the date `date` says, in any spelling ("26 Aug + * 2026", "Aug 26, 2026", "2026-08-26")? Then the date line would say it twice. + */ +export function sameDate(label, date) { + const tokens = (s) => { + const t = String(s ?? "").toLowerCase(); + const iso = /(\d{4})-(\d{2})-(\d{2})/.exec(t); + if (iso) return { y: iso[1], m: Number(iso[2]), d: Number(iso[3]) }; + const y = /\b(\d{4})\b/.exec(t)?.[1] ?? null; + const mi = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].findIndex((m) => t.includes(m)); + const d = /\b(\d{1,2})\b/.exec(t.replace(/\b\d{4}\b/, ""))?.[1] ?? null; + return { y, m: mi < 0 ? null : mi + 1, d: d === null ? null : Number(d) }; + }; + const a = tokens(label), b = tokens(date); + if (String(label).trim() === String(date).trim()) return true; + if (b.y === null || b.m === null) return String(label).includes(String(date)); + return a.y === b.y && a.m === b.m && (b.d === null || a.d === b.d); +} + +/** + * The large rail's pip labels, laid: consecutive pips with the same words + * share one label (anchored between them). Each label is `label` (the + * segment's deck title, else its date) over `date` (with `railLabels: + * "all"`, when it says something the label does not). One row under the + * track when every label fits its stretch, else two alternating rows, else + * every label turned (`angle`, degrees) and hung from its pip, the smallest + * angle at which neighbours clear each other -- each cut to the room it has. + * + * `pips` are `{ x, label, date }` in rail order (frame px). + * + * @returns {{ mode: "row" | "rows" | "turned", angle: number, + * groups: Array<{ from: number, to: number, x: number, label: string, date: string, row: number, max: number }> }} + */ +export function railLabelLayout(pips, geo, { dates = true } = {}) { + const { labelSize, dateSize, y, bottom } = geo.rail; + const W = geo.W; + const m = geo.margin; + const groups = []; + for (let i = 0; i < pips.length; i += 1) { + const label = String(pips[i].label ?? "").trim(); + const raw = dates ? String(pips[i].date ?? "").trim() : ""; + const date = raw && !sameDate(label, raw) ? raw : ""; + const last = groups[groups.length - 1]; + if (last && last.label === label && last.date === date) { last.to = i; continue; } + groups.push({ from: i, to: i, label, date }); + } + for (const g of groups) g.x = Math.round(((pips[g.from].x + pips[g.to].x) / 2) * 100) / 100; + const widthOf = (g) => Math.max(textWidth(g.label, labelSize), textWidth(g.date, dateSize, false)); + const fitsRows = (rows) => { + const lastRight = Array(rows).fill(-Infinity); + return groups.every((g, j) => { + const w = widthOf(g); + const r = j % rows; + const left = g.x - w / 2, right = g.x + w / 2; + if (left < m || right > W - m || left < lastRight[r] + 16) return false; + lastRight[r] = right; + return true; + }); + }; + if (fitsRows(1)) return { mode: "row", angle: 0, groups: groups.map((g) => ({ ...g, row: 0, max: widthOf(g) })) }; + const lines = groups.some((g) => g.date) ? 2 : 1; + const block = Math.round(labelSize * 1.15) + (lines > 1 ? Math.round(dateSize * 1.15) : 0); + if (lines === 1 && fitsRows(2)) return { mode: "rows", angle: 0, groups: groups.map((g, j) => ({ ...g, row: j % 2, max: widthOf(g) })) }; + // Turned: hung down-left of each pip, reading up to it. + let minD = Infinity; + for (let j = 1; j < groups.length; j += 1) minD = Math.min(minD, groups[j].x - groups[j - 1].x); + const angle = [35, 50, 65].find((a) => minD * Math.sin((a * Math.PI) / 180) >= block + 4) ?? 65; + const sin = Math.sin((angle * Math.PI) / 180), cos = Math.cos((angle * Math.PI) / 180); + const drop = Math.max(40, bottom - (y + Math.round(labelSize * 0.9))); + return { + mode: "turned", + angle, + groups: groups.map((g) => { + // The room: down to the rail's bottom, and left to the frame's margin. + const room = Math.min(drop / sin, (g.x - m / 2) / cos); + return { ...g, row: 0, max: Math.max(40, Math.floor(Math.min(room, Math.max(widthOf(g), 40)))) }; + }), + }; +} + +/** + * The large rail's markers: each flag's x (mapped from its x on the footer's + * track), its label's row (0 just over the track's band, 1 above it) and + * side -- reading right from the flag, or left when it would run off the + * frame. A label that clears neither row is cut to the room it has. + * + * `marks` are `{ x, label, color }` (frame px on the large track). + * + * @returns {Array<{ x: number, label: string, color: string, row: number, side: "right" | "left", max: number }>} + */ +export function railMarkerLayout(marks, geo) { + const size = geo.rail.markerSize; + const W = geo.W, m = geo.margin; + const rows = [[], []]; + return [...marks] + .map((mk, j) => ({ mk, j })) + .sort((a, b) => a.mk.x - b.mk.x) + .map(({ mk, j }) => { + const w = textWidth(String(mk.label).toUpperCase(), size) + Math.round(size * 0.04 * String(mk.label).length); + const side = mk.x + 18 + w > W - m ? "left" : "right"; + const span = side === "right" ? [mk.x, mk.x + 18 + w] : [mk.x - 18 - w, mk.x]; + let row = rows.findIndex((r) => r.every(([a, b]) => span[0] > b + 12 || span[1] < a - 12)); + let max = w; + if (row < 0) { + // Neither row clears it: the row with the most room, the label cut to it. + row = 1; + const blockers = rows[1].map(([a, b]) => (side === "right" ? a - mk.x - 30 : mk.x - b - 30)).filter((v) => v > 0); + max = Math.max(60, Math.min(w, ...blockers)); + } + rows[row].push(side === "right" ? [mk.x, mk.x + 18 + max] : [mk.x - 18 - max, mk.x]); + return { j, x: mk.x, label: mk.label, color: mk.color, row, side, max }; + }) + .sort((a, b) => a.j - b.j) + .map(({ j: _j, ...rest }) => rest); +} diff --git a/umtool/report-to-video/finale.test.mjs b/umtool/report-to-video/finale.test.mjs @@ -0,0 +1,218 @@ +// The deck's finale (finale.mjs, chrome-finale.mjs): validation of +// `render.chrome.deck.finale` and an entry's `layout`, the run rule, the +// schedule's `finale` (the clip's move, the deck's hide, stamps landed before +// it), the legibility floors, the page -- and a cut without a finale written +// byte for byte as before. +// +// Run with: node --test finale.test.mjs +import assert from "node:assert/strict"; +import test from "node:test"; + +import { deckChoreography, deckSchedule, estimateSchedule, validateChrome } from "./deck.mjs"; +import { deckHtml } from "./chrome-deck.mjs"; +import { finaleCues, finaleHtml, finaleLayout } from "./chrome-finale.mjs"; +import { + FINALE_DEFAULTS, FINALE_MIN, FINALE_MOTION, finaleGeometry, finaleRunProblems, railLabelLayout, validateFinaleEntries, + validateFinaleSettings, +} from "./finale.mjs"; +import { validatorErrors } from "./lint.mjs"; +import { finaleRegions } from "./build-video.mjs"; + +const PALETTE = { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" }; +const CHROME = { engine: "hyperframes", layout: "deck" }; +const BASE = { width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE }; +const PROV = { siteOrigin: "https://example.test", channelSlug: "chan" }; +const STATS = [ + { label: "2025 (from 26 Feb)", value: "5+", note: "4 incidents" }, + { label: "2026 (to 21 Oct)", value: "23+", note: "8 incidents" }, + { label: "His “seizure free” 18 months", value: "8+", note: "7 incidents, before the Costco refill" }, +]; +const renderWith = (deck = {}, extra = {}) => ({ + ...BASE, + chrome: { + ...CHROME, + deck: { pip: { color: "verdict" }, ...deck }, + factcheck: { verdicts: { CORROBORATED: { label: "Seizure episodes", color: "#6fa8dc" }, CONTRADICTED: { label: "Grift", color: "#e3b23c" } } }, + ...extra, + }, +}); + +// 26 clips, every other one claimed, the last marked for the finale. +const N = 26; +const clips = (finale = [N - 1]) => Array.from({ length: N }, (_, i) => ({ + id: `c${i}`, type: "clip", video: `v${i}`, start: 100, end: 130, + onscreen: { title: `${(i % 28) + 1} Oct 2026` }, + ...(i % 2 ? { claim: { id: `k${i}`, verdict: i % 4 === 1 ? "CORROBORATED" : "CONTRADICTED" } } : {}), + ...(finale.includes(i) ? { layout: "finale" } : {}), +})); +const DURS = Array.from({ length: N }, () => 30); +const sched = (entries, render, D = 0.5) => deckSchedule({ entries, durs: entries.map(() => 30), D, render, provenance: PROV }); + +test("deck.finale: every key validated, unknown keys refused, the defaults", () => { + assert.deepEqual(validateFinaleSettings(undefined), []); + assert.deepEqual(validateFinaleSettings({ video: "corner", motion: "cut", totals: false, railLabels: "nodes", statsTitle: "Seizures he reported", stats: STATS }), []); + const errs = validateFinaleSettings({ + video: "left", motion: "slide", totals: "yes", railLabels: "some", statsTitle: "x".repeat(41), colour: 1, + stats: [{ label: "", value: "1" }, { label: "ok", value: "12345678901234567" }, { label: "ok", value: "1", note: "n".repeat(61), color: "red" }, { label: "ok", value: "1", size: 2 }], + }); + for (const want of [ + 'render.chrome.deck.finale.video must be "side", "corner", "hidden"', + 'render.chrome.deck.finale.motion must be "grow", "cut"', + 'render.chrome.deck.finale.railLabels must be "all", "nodes"', + "render.chrome.deck.finale.totals must be true or false", + "render.chrome.deck.finale.statsTitle is 41 characters (at most 40)", + "render.chrome.deck.finale.stats[0].label must not be empty", + "render.chrome.deck.finale.stats[1].value is 17 characters (at most 16)", + "render.chrome.deck.finale.stats[2].note is 61 characters (at most 60)", + "render.chrome.deck.finale.stats[2].color must be a #hex colour or one of fg, muted, accent, amber", + "render.chrome.deck.finale.stats[3].size is not a stat field (label, value, note, color)", + ]) assert.ok(errs.includes(want), `missing: ${want}\n${errs.join("\n")}`); + assert.ok(errs.some((e) => e.startsWith("render.chrome.deck.finale.colour is not a finale setting"))); + assert.ok(validateFinaleSettings({ stats: Array.from({ length: 9 }, () => ({ label: "a", value: "1" })) }).includes("render.chrome.deck.finale.stats has 9 (at most 8)")); + assert.deepEqual(FINALE_DEFAULTS.video, "side"); + assert.deepEqual(FINALE_DEFAULTS.motion, "grow"); + assert.deepEqual(FINALE_DEFAULTS.railLabels, "all"); + // Through validateChrome (the writer's and the build's door). + assert.deepEqual(validateChrome({ ...CHROME, deck: { finale: { stats: STATS, statsTitle: "Seizures he reported" } } }), []); + assert.ok(validateChrome({ ...CHROME, deck: { finale: { video: "pip" } } }).includes('render.chrome.deck.finale.video must be "side", "corner", "hidden"')); +}); + +test("layout: clip or finale, finale on a clip; one run, a clip before it, none after", () => { + assert.deepEqual(validateFinaleEntries({ timeline: clips() }), []); + assert.deepEqual(validateFinaleEntries({ timeline: clips([24, 25]) }), []); + assert.deepEqual(validateFinaleEntries({ timeline: [...clips([25]), { id: "end", type: "card" }] }), [], "a card may follow"); + const bad = validateFinaleEntries({ timeline: [{ id: "a", type: "clip", layout: "wide" }, { id: "b", type: "card", layout: "finale" }] }); + assert.ok(bad.includes('timeline[0] (a).layout must be "clip" or "finale"'), bad.join("\n")); + assert.ok(bad.includes('timeline[1] (b).layout: "finale" is a clip\'s layout, not a card\'s'), bad.join("\n")); + assert.ok(finaleRunProblems(clips([23, 25])).some((e) => e.includes("consecutive") && e.includes("c24"))); + assert.ok(finaleRunProblems(clips([24])).some((e) => e.startsWith("no clip may follow the finale") && e.includes("c25"))); + assert.ok(finaleRunProblems(clips([0])).some((e) => e.includes("needs a clip before it"))); + // The lint names them, as the build refuses them. + assert.ok(validatorErrors({ render: renderWith(), timeline: clips([24]) }).some((e) => e.includes("no clip may follow"))); + assert.ok(validatorErrors({ render: renderWith({ finale: { video: "pip" } }), timeline: clips() }) + .includes('render.chrome.deck.finale.video must be "side", "corner", "hidden"'), "the lint validates deck.finale"); + assert.deepEqual(validatorErrors({ render: renderWith({ finale: { stats: STATS } }), timeline: clips() }), []); +}); + +test("legibility at 1080p: rail labels ≥ 24 px, totals ≥ 96 px, pips ≥ 2× the footer's", () => { + for (const video of ["side", "corner", "hidden"]) { + const g = finaleGeometry(renderWith({ finale: { video, stats: STATS } }), { verdicts: 2, stats: 3, statsTitle: true }); + assert.ok(g.rail.labelSize >= FINALE_MIN.railLabel && g.rail.dateSize >= FINALE_MIN.railLabel && g.rail.markerSize >= FINALE_MIN.railLabel, video); + assert.ok(g.totals.numberSize >= FINALE_MIN.totals, `${video}: ${g.totals.numberSize}`); + assert.ok(g.rail.x1 - g.rail.x0 >= 1600, "the rail runs the frame's width"); + // Everything inside the frame and below the rail. + for (const box of [g.totals, g.stats, g.video, { ...g.qr, width: g.qr.size, height: g.qr.size }].filter(Boolean)) { + assert.ok(box.x >= 0 && box.y >= g.rail.bottom && box.x + box.width <= 1920 && box.y + box.height <= 1080, `${video}: ${JSON.stringify(box)}`); + } + } + const side = finaleGeometry(renderWith({ finale: { video: "side" } })); + assert.deepEqual(side.video, { x: 1104, y: 448, width: 768, height: 432 }, "40 % of the width"); + assert.equal(finaleGeometry(renderWith({ finale: { video: "corner" } })).video.width, 538, "28 %"); + assert.equal(finaleGeometry(renderWith({ finale: { video: "hidden" } })).video, null); + // Five verdicts still get ≥ 96 px numbers. + assert.ok(finaleGeometry(renderWith({ finale: {} }), { verdicts: 5, stats: 8 }).totals.numberSize >= 96); + + const r = renderWith({ finale: { stats: STATS } }); + const s = sched(clips(), r); + const L = finaleLayout(s, r); + for (const p of L.pips) assert.ok(p.size >= FINALE_MIN.pipScale * p.foot.size, `${p.id}: ${p.size} vs ${p.foot.size}`); + assert.equal(L.pips.length, N, "every clip has its pip, the finale's too"); + assert.equal(L.pips.filter((p) => p.here).length, 1); +}); + +test("rail labels: shared words merge, crowded labels turn, every label stays on the frame", () => { + const g = finaleGeometry(renderWith({ finale: {} })); + const few = railLabelLayout([{ x: 300, label: "Arrives" }, { x: 900, label: "First seizure" }, { x: 1500, label: "ER" }], g); + assert.equal(few.mode, "row"); + const crowd = railLabelLayout(Array.from({ length: 26 }, (_, i) => ({ x: 160 + i * 68, label: `${i} Oct 2026` })), g); + assert.equal(crowd.mode, "turned"); + assert.ok(crowd.angle >= 35 && crowd.angle <= 65); + const merged = railLabelLayout([{ x: 200, label: "24 Aug" }, { x: 260, label: "24 Aug" }, { x: 900, label: "25 Aug" }], g); + assert.equal(merged.groups.length, 2); + assert.equal(merged.groups[0].x, 230); + // A date the label already says is not said twice. + assert.equal(railLabelLayout([{ x: 500, label: "Oct 21, 2026", date: "Oct 21, 2026" }], g).groups[0].date, ""); + assert.equal(railLabelLayout([{ x: 500, label: "26 Aug 2026", date: "Aug 26, 2026" }], g).groups[0].date, "", "in another spelling"); + assert.equal(railLabelLayout([{ x: 500, label: "26 Aug 2026", date: "2026-08-26" }], g).groups[0].date, ""); + assert.equal(railLabelLayout([{ x: 500, label: "The ER", date: "Aug 24, 2026" }], g).groups[0].date, "Aug 24, 2026"); + assert.equal(railLabelLayout([{ x: 500, label: "24 Aug 2026", date: "Aug 26, 2026" }], g).groups[0].date, "Aug 26, 2026", "a different day is said"); +}); + +test("the schedule: the run, the clip's move, the deck's hide, stamps landed before it", () => { + const r = renderWith({ finale: { stats: STATS } }); + const s = sched(clips([24, 25]), r); + const f = s.finale; + const first = s.segments[24]; + assert.deepEqual(f.segments, ["c24", "c25"]); + assert.equal(f.start, first.start); + assert.ok(Math.abs(f.at - (first.start + Math.max(0.5, 0.25 + 0.08 + 0.45))) < 1e-3, "grow waits for the dissolve and the words"); + assert.equal(f.hide, f.at); + assert.ok(Math.abs(f.cover - (f.at + FINALE_MOTION.cover)) < 1e-3); + assert.equal(f.to, s.total); + assert.ok(s.segments[24].finale && s.segments[25].finale && !s.segments[23].finale); + // Each finale clip's footage moves into the box: the first grows, the next is there. + const moves = s.moves.filter((m) => m.segment === "c24" || m.segment === "c25"); + assert.equal(moves[0].seconds, FINALE_MOTION.grow); + assert.ok(Math.abs(moves[0].segmentAt - (f.at - first.start)) < 1e-3); + assert.deepEqual([moves[1].seconds, moves[1].segmentAt], [0, 0]); + assert.deepEqual(moves[0].to, f.box); + // c25's claim would stamp inside the finale: counted at its start, not drawn. + const k25 = s.factcheck.stamps.find((x) => x.claim === "k25"); + assert.deepEqual([k25.landed, k25.stamp, k25.finale], [f.start, false, true]); + assert.ok(s.factcheck.stamps.every((x) => x.landed <= f.start)); + // The deck hands over into the run, and goes at `hide`. + const ch = deckChoreography(s, r); + assert.ok(ch.handovers.some((h) => h.to === "c24")); + assert.ok(!ch.handovers.some((h) => h.to === "c25")); + assert.deepEqual(ch.visibility.find((v) => v.i === 24), { i: 24, hide: true, at: [f.hide, f.hide] }); + // "cut": the page dissolves in over the run's first dissolve; the deck goes once covered. + const c = sched(clips(), renderWith({ finale: { motion: "cut", video: "hidden" } })).finale; + assert.deepEqual([c.at, c.grow, c.hide, c.box], [c.start, 0, c.cover, null]); + // A card after the run: the page leaves through its dissolve. + const withCard = deckSchedule({ entries: [...clips(), { id: "end", type: "card", seconds: 5 }], durs: [...DURS, 5], D: 0.5, render: r, provenance: PROV }); + assert.deepEqual(withCard.finale.out, [withCard.segments[N].start, withCard.segments[N].start + 0.5].map((v) => Math.round(v * 1000) / 1000)); +}); + +test("the page: the large rail, the totals at their final counts, the stats, the clip's caption", () => { + const r = renderWith({ finale: { statsTitle: "Seizures he reported", stats: STATS } }); + const s = sched(clips(), r); + const win = finaleRegions(r, "/tmp/x", s)[0].window; + const html = finaleHtml(s, r, win, {}); + assert.equal((html.match(/class="pip"/g) ?? []).length, N); + assert.equal((html.match(/class="pl[ "]/g) ?? []).length, N, "a label per pip (none shared here)"); + assert.equal((html.match(/class="sc"/g) ?? []).length, 3); + assert.match(html, /Seizures he reported/); + assert.match(html, /<div class="tnum">6<\/div><div class="tlab">Grift<\/div>/); + assert.match(html, /<div class="tnum">7<\/div><div class="tlab">Seizure episodes<\/div>/); + assert.match(html, /His “seizure free” 18 months/); + assert.match(html, /class="ct">26 Oct 2026</); + assert.match(html, /data-composition-id="finale"/); + // Every cue states its from; the hole eases on the move's smoothstep. + const { cues } = finaleCues(s, r); + assert.ok(cues.every((c) => Object.keys(c.to).every((p) => p in c.from))); + const hole = cues.find((c) => c.k === "hole"); + assert.equal(hole.ease, "smoothstep"); + assert.equal(hole.at, s.finale.at); + assert.equal(hole.dur, FINALE_MOTION.grow); + // The region: the whole frame, a window from `at` to the end. + const reg = finaleRegions(r, "/tmp/x", s)[0]; + assert.deepEqual([reg.x, reg.y, reg.width, reg.height], [0, 0, 1920, 1080]); + assert.ok(reg.offset <= s.finale.from && reg.offset > s.finale.from - 1 / 30); +}); + +test("byte identity: no finale entry -- the schedule and the deck page are as they were, finale settings or not", () => { + const entries = clips([]); + const plain = renderWith(); + const withSettings = renderWith({ finale: { stats: STATS, video: "corner" } }); + const a = sched(entries, plain); + const b = sched(entries, withSettings); + assert.equal(JSON.stringify(a), JSON.stringify(b)); + assert.equal(a.finale, undefined); + assert.ok(a.segments.every((x) => !("finale" in x))); + assert.equal(deckHtml(a, plain), deckHtml(b, withSettings)); + assert.deepEqual(finaleRegions(plain, "/tmp/x", a), []); + // A finale that breaks the run is not drawn (the validators refuse it). + assert.equal(sched(clips([24]), withSettings).finale, undefined); + // An estimate carries the finale as the build's schedule does. + assert.ok(estimateSchedule({ render: withSettings, timeline: clips(), provenance: PROV }).finale); +}); diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -78,10 +78,11 @@ import { existsSync } from "node:fs"; import path from "node:path"; import { deckOn, deckQrUrl, postArchiveUrl, postNativeId, postQrUrl, resolveDeck, teaserLines, - validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, + validateChrome, validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, } from "./deck.mjs"; import { validateClaims } from "./factcheck.mjs"; import { validateClipAudioEntries } from "./clip-audio.mjs"; +import { validateFinaleEntries } from "./finale.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; import { validateStatsEntries } from "./stats.mjs"; @@ -245,9 +246,14 @@ export function validatorErrors(whole) { ...validateTransitionStyle(whole), // Release 36: render.captions, render.loudness and a clip's vertical crop. ...validateLook(whole), + // The deck finale: each entry's `layout` and the one run (finale.mjs). + ...validateFinaleEntries(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); + // render.chrome itself (deck.finale included), as the build refuses it. + const { chrome, ...rest } = whole.render; + errors.push(...validateChrome(chrome, rest)); // The deck's markers against the whole timeline, as the build refuses them. errors.push(...validateDeckMarkers(whole)); } diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -28,6 +28,7 @@ "./deck": "./deck.mjs", "./drafts-review": "./drafts-review.mjs", "./factcheck": "./factcheck.mjs", + "./finale": "./finale.mjs", "./frames-cut": "./frames-cut.mjs", "./fx": "./fx.mjs", "./ledger-totals": "./ledger-totals.mjs", diff --git a/umtool/report-to-video/verify-build.mjs b/umtool/report-to-video/verify-build.mjs @@ -18,7 +18,7 @@ import { promisify } from "node:util"; import { readdir, readFile, stat } from "node:fs/promises"; import path from "node:path"; -import { postsRegions, selectVariant, variantPaths } from "./build-video.mjs"; +import { finaleRegions, postsRegions, selectVariant, variantPaths } from "./build-video.mjs"; import { deckGeometry, deckOn, frameCount, postsGeometry, resolveDeck, teaserSeconds, transitionOf } from "./deck.mjs"; import { statsClips } from "./stats.mjs"; import { stampsDrawn } from "./factcheck.mjs"; @@ -216,8 +216,16 @@ export async function verifyDeck(variantDir, render, file, problems, manifest = problems.push(`${r.frames} holds ${got} frames; the posts window on ${r.segment} is ${r.frameCount}`); } } + // The finale (chrome-finale.mjs): one window, as long as snapWindow says. + let finale = null; + for (const r of finaleRegions(render, variantDir, schedule)) { + const got = await countFrames(r.frames); + finale = { frames: got, expectedFrames: r.frameCount, at: r.offset }; + if (got !== r.frameCount) problems.push(`${r.frames} holds ${got} frames; the finale's window is ${r.frameCount}`); + } const holds = await verifyHolds(file, schedule, render, problems); return { + ...(finale ? { finale } : {}), total: schedule.total, frames, expectedFrames: want, videoFrames, segments: schedule.segments.length, ...(feed ? { feed } : {}), ...(stamp ? { stamp } : {}),