// 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" | "sections" | "none" every label and date and the markers' labels, // each pip's label alone, the section markers' labels // alone, or no words (default "all") // "timelineShare": "auto" | 0.38–0.6 how much of the frame's height the timeline takes: // "auto" (the default) the height its rows need, from // the share it always had up to FINALE_SHARE.auto; // a number, that share of the frame, needed or not // "pips": true | false false: the finale's own clips get no pip on the rail // (footer or large) -- the rail is the record alone; their // titles and dates stay in their own area (default true) // "dietRuns": true | false | { marks, low } the whole diet record drawn under the rail (module runs-finale, // chrome-runs-finale.mjs; needs railLabels sections|none; default false): // `marks` [{row, label, peak?}] dots on its weight line with his words, // the heaviest THE peak; `low` the lowest stated weight marked (default on) // "claims": "rotate" | "all" the claim checks (deck.claims) on the large rail: // one at a time, each for an even share of the page's // time (default "rotate"; all at once when there is // one, or too little time for FINALE_CLAIMS.minHold) // } // // 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. */ // "sections": the section markers' labels alone (no pip's label or date); "none": no words on the rail at all // (rev 9, 6 Nov: the promise clock over the finale met the turned dates at the rail's left). export const FINALE_RAIL_LABELS = Object.freeze(["all", "nodes", "sections", "none"]); /** How the claim checks stand on the large rail: one at a time in turn, or all at once. */ export const FINALE_CLAIM_MODES = Object.freeze(["rotate", "all"]); /** * The timeline's share of the frame's height (the rail's region and the gap * under it, from the frame's top to the lower area): `base` is the share it * always had (448 of 1080 px), `auto` the most "auto" grows it to, `min` and * `max` what a number may say. */ export const FINALE_SHARE = Object.freeze({ base: 448 / 1080, auto: 0.54, min: 0.38, max: 0.6 }); /** * "rotate": each claim stands for an even share of the page's time once the * rail is in place, at least `minHold` seconds, with a `fade`-second crossfade * between them; less time than that for each, and they stand all at once. */ export const FINALE_CLAIMS = Object.freeze({ minHold: 6, fade: 0.5 }); /** 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", timelineShare: "auto", claims: "rotate", pips: true, dietRuns: false, }); /** * 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); oneOf("claims", FINALE_CLAIM_MODES); if (f.timelineShare !== undefined && f.timelineShare !== "auto" && !(typeof f.timelineShare === "number" && f.timelineShare >= FINALE_SHARE.min && f.timelineShare <= FINALE_SHARE.max)) { errors.push(`${where}.timelineShare must be "auto" or a number from ${FINALE_SHARE.min} to ${FINALE_SHARE.max} (the frame's height the timeline takes)`); } if (f.totals !== undefined && typeof f.totals !== "boolean") errors.push(`${where}.totals must be true or false`); if (f.pips !== undefined && typeof f.pips !== "boolean") errors.push(`${where}.pips must be true or false`); if (f.dietRuns !== undefined && typeof f.dietRuns !== "boolean") errors.push(...dietRunsProblems(f.dietRuns, `${where}.dietRuns`)); // The diet runs stand under the rail, where "all" and "nodes" put the pips' labels and dates. if (dietRunsOn(f.dietRuns) && !["sections", "none"].includes(f.railLabels ?? FINALE_DEFAULTS.railLabels)) { errors.push(`${where}.dietRuns draws under the rail, where railLabels "${f.railLabels ?? FINALE_DEFAULTS.railLabels}" puts the pips' words: set ${where}.railLabels "sections" or "none"`); } 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's diet runs' marks: how many, and a label's characters. */ export const DIET_RUNS_LIMITS = Object.freeze({ marks: 8, label: 60 }); /** Is the finale's diet record on (`dietRuns`: true, or its object)? */ export const dietRunsOn = (v) => v === true || isObj(v); /** Where the record's weights stand (`dietRuns.weights`): at the date each APPLIED, the date each was SAID, or none. */ export const DIET_RUNS_WEIGHTS = Object.freeze(["applied", "said"]); /** The record's weight layer: "applied" (the default when the record is on), "said", or false. */ export const dietRunsWeights = (v) => (!dietRunsOn(v) ? false : isObj(v) && v.weights !== undefined ? v.weights : "applied"); /** * The design px the finale's diet record takes under the large rail's track * (chrome-runs-finale.mjs): 0 off; with the weight layer, the layer over the * bars and their labels; without it, the bars and their labels alone. */ export const dietRunsPanel = (v) => (!dietRunsOn(v) ? 0 : dietRunsWeights(v) ? 218 : 122); /** Why `deck.finale.dietRuns` (an object) cannot be drawn. */ export function dietRunsProblems(v, where) { if (!isObj(v)) return [`${where} must be true, false or { marks, low, weights }`]; const errors = []; for (const k of Object.keys(v)) if (!["marks", "low", "weights"].includes(k)) errors.push(`${where}.${k} is not a diet-runs setting (marks, low, weights)`); if (v.weights !== undefined && v.weights !== false && !DIET_RUNS_WEIGHTS.includes(v.weights)) errors.push(`${where}.weights must be "applied", "said" or false`); if (v.low !== undefined && typeof v.low !== "boolean") { const p = typeof v.low === "string" ? lineProblem(v.low, DIET_RUNS_LIMITS.label, `${where}.low`) : `${where}.low must be true, false or its label`; if (p) errors.push(p); } if (v.marks !== undefined) { if (!Array.isArray(v.marks)) errors.push(`${where}.marks must be a list of { row, label, peak? }`); else { if (v.marks.length > DIET_RUNS_LIMITS.marks) errors.push(`${where}.marks has ${v.marks.length} (at most ${DIET_RUNS_LIMITS.marks})`); v.marks.forEach((m, i) => { const at = `${where}.marks[${i}]`; if (!isObj(m)) { errors.push(`${at} must be { row, label, peak? }`); return; } for (const k of Object.keys(m)) if (!["row", "label", "peak"].includes(k)) errors.push(`${at}.${k} is not a mark field (row, label, peak)`); if (typeof m.row !== "string" || !m.row.trim()) errors.push(`${at}.row must name a ledger row`); const p = lineProblem(m.label, DIET_RUNS_LIMITS.label, `${at}.label`); if (p) errors.push(p); if (m.peak !== undefined && typeof m.peak !== "boolean") errors.push(`${at}.peak must be true or false`); }); } } 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, `railBottom` * where the rail's region ends (the schedule's `finale.railBottom`, which * `finaleRailBottom` decides; default 412 at 1080p -- the timeline's share as * it always was). * * At 1920×1080 and the default: 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. A taller rail shrinks the lower area: the * clip keeps its aspect and shrinks to fit over its caption and a QR of at * least 96 px, the totals and the cards to the column's height. * * @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, railBottom = null, textScale = 1 } = {}) { 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 bottom = Number.isFinite(railBottom) ? Math.round(railBottom) : py(412); const rail = { top: py(36), bottom, y: py(176), x0: px(120), x1: W - px(96), labelSize: Math.max(FINALE_MIN.railLabel, px(28 * textScale)), dateSize: Math.max(FINALE_MIN.railLabel, px(24 * textScale)), markerSize: Math.max(FINALE_MIN.railLabel, px(24 * textScale)), }; const lowTop = bottom + py(36); 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") { // 40 % of the width -- or, under a taller rail, what fits over the caption and a 96 px QR. const room = lowBottom - lowTop - py(14) - Math.max(capH, px(96)); const vw = Math.min(even(W * 0.4), even((room * W) / H)), 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 size = px(96); const room = lowBottom - size - py(12) - lowTop; const vw = Math.min(even(W * 0.28), even((room * W) / H)), vh = even((vw * H) / W); 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; const twoRows = (verdicts > 0 ? py(150) + py(28) : 0) + (statsTitle ? Math.round(Math.max(22, px(28)) * 1.5) : 0) + 2 * py(124) + px(16); if (verdicts > 0) { const gap = px(20); const cell = Math.min(px(320), Math.floor((column.width - (verdicts - 1) * gap) / verdicts)); // 236 px over the stats -- in a shorter column what the cards leave (each // at least 124 px), never under 150 -- else up to 320. const sRows = statsGrid(stats, column, twoRows).rows; const sNeed = (statsTitle ? Math.round(Math.max(22, px(28)) * 1.5) : 0) + sRows * py(124) + (sRows - 1) * px(16); const height = stats > 0 ? Math.min(py(236), Math.max(py(150), column.height - py(28) - sNeed)) : 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; const { cols, rows } = statsGrid(stats, column, twoRows); 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 }; } /** * The stats cards' grid in `column`: up to three in a row; four as two by two * -- or, in a column shorter than `twoRows` (under a taller rail: the least * totals and two rows of 124 px cards), four in one; then three or four to a row. */ function statsGrid(stats, column, twoRows = 0) { if (stats === 4 && column.height < twoRows && column.width / 4 >= 240) return { cols: 4, rows: 1 }; const cols = stats <= 3 ? stats : stats === 4 ? 2 : stats <= 6 ? 3 : 4; return { cols, rows: Math.ceil(stats / cols) }; } /** * 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 -- at the smallest // angle at which neighbours clear each other. let minD = Infinity; for (let j = 1; j < groups.length; j += 1) minD = Math.min(minD, groups[j].x - groups[j - 1].x); const clearAt = [35, 50, 65].find((a) => minD * Math.sin((a * Math.PI) / 180) >= block + 4); let angle = clearAt ?? 65; // None clears: the rail is crowded. Each label is said ONCE -- a run that // repeats a label laid elsewhere on the rail goes, each distinct one kept // at its longest run (else its first) -- and the rest are FANNED: each slid // along the rail, as little as it can, to a slot at least `pitch` from the // next, joined to its pip by a thin leader over a LEAD-px band under the // track. Only when even the distinct labels' slots do not fit the rail // (past ~45 at 1080p) is the one with the nearest neighbours dropped, until // they fit. Never two that meet. let laid = groups.map((g) => ({ ...g, lx: g.x })); let lead = 0; if (clearAt === undefined && groups.length > 1) { const pitchAt = (a) => Math.ceil((block + 6) / Math.sin((a * Math.PI) / 180)); let pitch = pitchAt(65); // A turned label's line stands to the right of its slot by up to its height: the last slot keeps it on the panel. const lo = groups[0].x, hi = Math.max(groups[groups.length - 1].x, W - m / 2 - block - 4); const fits = (gs) => (gs.length - 1) * pitch <= hi - lo; let kept = [...groups]; { const best = new Map(); for (const g of kept) { const key = `${g.label}\u0000${g.date}`; const b0 = best.get(key); if (!b0 || g.to - g.from > b0.to - b0.from) best.set(key, g); } kept = kept.filter((g) => best.get(`${g.label}\u0000${g.date}`) === g); } while (kept.length > 1 && !fits(kept)) { // The one with the nearest neighbours (never the first). let at = 1, near = Infinity; for (let j = 1; j < kept.length; j += 1) { const d = Math.min(kept[j].x - kept[j - 1].x, j + 1 < kept.length ? kept[j + 1].x - kept[j].x : Infinity); if (d < near) { near = d; at = j; } } kept.splice(at, 1); } // The flattest angle whose slots stay near their pips (none more than // FAN_REACH px off) -- flatter reads easier -- else the steepest. const reach = Math.round(FAN_REACH * (W / 1920)); let lxs = fanSlots(kept.map((g) => g.x), pitch, lo, hi); for (const a of [35, 50]) { const p = pitchAt(a); if ((kept.length - 1) * p > hi - lo) continue; const at = fanSlots(kept.map((g) => g.x), p, lo, hi); if (at.every((v, j) => Math.abs(v - kept[j].x) <= reach)) { angle = a; pitch = p; lxs = at; break; } } laid = kept.map((g, j) => ({ ...g, lx: lxs[j] })); if (laid.some((g) => Math.abs(g.lx - g.x) > 1)) lead = RAIL_LABEL_LEAD; } 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) + lead)); return { mode: "turned", angle, lead, groups: laid.map((g) => { // The room: down to the rail's bottom, and left to the frame's margin. const room = Math.min(drop / sin, (g.lx - m / 2) / cos); return { ...g, row: 0, max: Math.max(40, Math.floor(Math.min(room, Math.max(widthOf(g), 40)))) }; }), }; } /** The band under the track a fanned label's leader crosses, px (1080p design). */ export const RAIL_LABEL_LEAD = 26; /** How far a fanned label may stand from its pip at a flatter angle than 65°, px (1080p design). */ export const FAN_REACH = 120; /** * Slots for labels anchored at `xs` (ascending): each as near its anchor as it * can be (least squares), consecutive ones at least `pitch` apart, all inside * [lo, hi] -- pool-adjacent-violators on x_j − j·pitch, clamped. */ export function fanSlots(xs, pitch, lo, hi) { const n = xs.length; if (!n) return []; const blocks = []; xs.forEach((x, j) => { blocks.push({ sum: x - j * pitch, n: 1 }); while (blocks.length > 1 && blocks[blocks.length - 2].sum / blocks[blocks.length - 2].n > blocks[blocks.length - 1].sum / blocks[blocks.length - 1].n) { const top = blocks.pop(); blocks[blocks.length - 1].sum += top.sum; blocks[blocks.length - 1].n += top.n; } }); const ys = []; for (const b of blocks) for (let i = 0; i < b.n; i += 1) ys.push(b.sum / b.n); const yHi = Math.max(lo, hi - (n - 1) * pitch); return ys.map((v, j) => Math.round((Math.min(yHi, Math.max(lo, v)) + j * pitch) * 100) / 100); } /** * 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, 2 above * that) and side -- reading right from the flag, or left when it would run * off the frame. A label takes the first row where it clears every label * already laid there, on its side or, failing that, the other; one that * clears no row is laid in the row that leaves it the most room and cut to * that room. `layout` is the deck's `markerLayout`: "stagger" (the default) * lays them in up to three rows, "truncate" keeps one row and cuts them, as * the footer does. * * `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, { layout = "stagger" } = {}) { const size = geo.rail.markerSize; const W = geo.W, m = geo.margin; const rows = Array.from({ length: layout === "truncate" ? 1 : RAIL_MARKER_ROWS }, () => []); const GAP = 12; const spanOf = (x, side, w) => (side === "right" ? [x, x + 18 + w] : [x - 18 - w, x]); const clears = (r, [a, b]) => r.every(([c, d]) => a > d + GAP || b < c - GAP); 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 fitsRight = mk.x + 18 + w <= W - m; const fitsLeft = mk.x - 18 - w >= m / 2; const sides = fitsRight ? ["right", ...(fitsLeft ? ["left"] : [])] : ["left"]; for (let row = 0; row < rows.length; row += 1) { for (const side of sides) { const span = spanOf(mk.x, side, w); if (clears(rows[row], span)) { rows[row].push(span); return { j, x: mk.x, label: mk.label, color: mk.color, row, side, max: w }; } } } // No row clears it: the row (and side) that leaves it the most room, the label cut to it. let best = { row: rows.length - 1, side: sides[0], room: -Infinity }; rows.forEach((r, row) => { for (const side of sides) { const room = side === "right" ? Math.min(W - m - mk.x - 18, ...r.filter(([a, b]) => b > mk.x - GAP).map(([a]) => a - mk.x - 18 - GAP)) : Math.min(mk.x - 18 - m / 2, ...r.filter(([a, b]) => a < mk.x + GAP).map(([, b]) => mk.x - 18 - b - GAP)); if (room > best.room) best = { row, side, room }; } }); const max = Math.max(60, Math.min(w, Math.floor(best.room))); rows[best.row].push(spanOf(mk.x, best.side, max)); return { j, x: mk.x, label: mk.label, color: mk.color, row: best.row, side: best.side, max }; }) .sort((a, b) => a.j - b.j) .map(({ j: _j, ...rest }) => rest); } /** How many rows the large rail's marker labels may take when they stagger. */ export const RAIL_MARKER_ROWS = 3; // --------------------------------------------------------------------------- // Over the large rail: the rows the claim checks' words, their span labels and // the markers' labels stand in, packed so no two meet. // --------------------------------------------------------------------------- /** * How far over the track each row's text box starts, px (1080p design): row 0 * just over the track (a per claim's span labels, `12 in a day`), rows 1–3 * the markers' (railMarkerLayout's rows 0–2, at the heights they always had), * every row on 40 px over the last. */ export const aboveTop = (row, size = 24) => (row <= 0 ? Math.round(size * 1.75) : Math.round(size * 3) + (aboveLine(size) + 10) * (row - 1)); /** A row's text box, px: the marker face's line (24 px × 1.25 at the design's size). */ export const aboveLine = (size = 24) => Math.round(size * 1.25); /** * One rail's rows: the intervals laid in each, and the sticks that rise * through them. `markers` reserves each marker's label (`labels: false`: its * flag only) in its row and its stick through every row under it. */ export function aboveRows(marks = [], { labels = true } = {}) { const rows = []; const put = (r, a, b) => { (rows[r] ??= []).push([a, b]); }; for (const mk of marks) { const r = mk.row + 1; const w = labels ? 18 + mk.max : 18; if (mk.side === "left") put(r, mk.x - w, mk.x + 2); else put(r, mk.x - 2, mk.x + w); for (let q = 0; q < r; q += 1) (rows[q] ??= []).push([mk.x - 3, mk.x + 3, "stick"]); } return rows; } const TEXT_GAP = 24; const STICK_GAP = 8; const STEP = 24; const MAX_ROWS = 12; /** * Lay one label in `rows` (aboveRows'), the lowest row first: at its * preferred place, else slid along its row, its stick (when it has one) * anywhere inside its bracket [a, b] and always under the words. Each * candidate must clear its row's words by 24 px and, with its stick, every * row the stick rises through. Records what it takes. * * `item`: `{ w, left, align: "left" | "right" | "center", stick: { x, a, b } | null, * minRow, stickFrom }` -- `stickFrom`: the first row from which the label needs * its stick (a span label in row 0 sits on its bar and needs none). * * @returns {{ row: number, left: number, stickX: number | null }} */ export function placeAbove(rows, item, { W, margin }) { const { w, align = "left", stick = null, minRow = 0, stickFrom = 0 } = item; const lo = margin / 2, hi = W - margin - w; // Words keep TEXT_GAP from words, and STICK_GAP + 4 from a stick (a thin line needs less air). const clears = (r, a, b, gap) => (rows[r] ?? []).every(([c, d, kind]) => { const g = kind === "stick" ? Math.min(gap, STICK_GAP + 4) : gap; return b + g <= c || a >= d + g; }); const stickClears = (r, x) => { for (let q = 0; q < r; q += 1) if (!clears(q, x - 1.5, x + 1.5, STICK_GAP)) return false; return true; }; const byNear = (base, from, to) => { const out = []; for (let k = 0; k <= 60; k += 1) { for (const v of k ? [base - k * STEP, base + k * STEP] : [base]) if (v >= from - 1e-6 && v <= to + 1e-6) out.push(v); if (base - k * STEP < from && base + k * STEP > to) break; } return out; }; const take = (r, left, sx) => { (rows[r] ??= []).push([left, left + w]); if (sx !== null) for (let q = 0; q < r; q += 1) (rows[q] ??= []).push([sx - 1.5, sx + 1.5, "stick"]); return { row: r, left: Math.round(left * 100) / 100, stickX: sx === null ? null : Math.round(sx * 100) / 100 }; }; const sticksIn = (x, a, b) => { // Every STEP from its own place, and every 6 px between: a narrow gap between two sticks is found. const out = byNear(x, a, b); for (let v = a; v <= b; v += 6) if (!out.includes(v)) out.push(v); return out; }; for (let r = minRow; r < MAX_ROWS; r += 1) { const withStick = stick && r >= stickFrom; const sxs = withStick ? sticksIn(stick.x, Math.min(stick.a, stick.x), Math.max(stick.b, stick.x)) : [null]; for (const sx of sxs) { if (sx !== null && !stickClears(r, sx)) continue; const base = sx === null ? item.left : align === "right" ? sx - w + 1 : align === "center" ? sx - w / 2 : sx - 1; // With a stick the words stay over it; without, a span label stays over its point, other words go where they clear. const anchor = stick?.x ?? null; const from = sx !== null ? Math.max(lo, sx - w + 6) : anchor !== null ? Math.max(lo, anchor - w + 6) : lo; const to = sx !== null ? Math.min(hi, sx - 6) : anchor !== null ? Math.min(hi, anchor - 6) : hi; for (const left of byNear(Math.min(to, Math.max(from, base)), from, to)) { if (clears(r, left, left + w, TEXT_GAP)) return take(r, left, sx); } } } // No stick rises clear of the rows under it (everything at once, crowded): // the words without one, in the lowest row they clear near their place. for (let r = Math.max(minRow, 1); r < MAX_ROWS; r += 1) { const anchor = stick?.x ?? item.left + w / 2; for (const left of byNear(Math.min(hi, Math.max(lo, item.left)), Math.max(lo, anchor - w), Math.min(hi, anchor))) { if (clears(r, left, left + w, TEXT_GAP)) return take(r, left, null); } } return take(MAX_ROWS - 1, Math.min(hi, Math.max(lo, item.left)), null); } /** * When the claim checks stand on the large rail: "rotate" gives each of the * `n` claims (a count claim with its band or spans; a goalpost with its * steps) an even share of the page's time from the moment the rail is in * place (`at` + `grow`) to the run's end (`out[0]`, else `to`), in the order * the deck lists them -- when there are two or more and each gets at least * FINALE_CLAIMS.minHold. Otherwise "all", the whole window. * * @returns {{ mode: "rotate" | "all", slots: Array<[number, number]> }} */ export function finaleClaimSlots(fin, n, setting = "rotate") { const r3 = (v) => Math.round(v * 1000) / 1000; const from = (fin?.at ?? 0) + (fin?.grow > 0 ? fin.grow : 0); const to = fin?.out ? fin.out[0] : fin?.to ?? from; const hold = n > 0 ? (to - from) / n : 0; if (setting !== "rotate" || n < 2 || !(hold >= FINALE_CLAIMS.minHold)) { return { mode: "all", slots: Array.from({ length: n }, () => [r3(from), r3(to)]) }; } return { mode: "rotate", slots: Array.from({ length: n }, (_, j) => [r3(from + j * hold), r3(j === n - 1 ? to : from + (j + 1) * hold)]) }; } /** * The claims on the finale's large rail, frame px: the footer's layout * (`fcl`, deck.mjs claimsLayout) mapped onto the large track by `toBig`. Each * count claim's band (with the rail dimmed outside it and its record's pips * ringed) or its spans, and every goalpost step -- each superseded one * dashed, the last solid. Their words, and a per claim's span labels, are * laid in the rows over the track (aboveTop) around the markers' (`marks`, * railMarkerLayout's) so no two meet: a span label on its bar, else higher * with a leader down to it; a claim's words at their bracket's edge, else slid * along their row with their stick moved inside the bracket. * * `mode` "rotate" packs each claim against the markers alone (they stand one * at a time), "all" packs them all together. `rows` is how many rows over * the track the tallest needs, the markers' included. * * @returns {{ mode: "rotate" | "all", rows: number, items: any[] }} */ export function finaleClaims(fcl, { toBig, bigX, size, textWidth: tw = textWidth, ringSize, pips = [], marks = [], markerLabels = true, W = 1920, margin = 48, mode = "all", }) { const r2 = (v) => Math.round(v * 100) / 100; const base = aboveRows(marks, { labels: markerLabels }); const markerRows = marks.length ? Math.max(...marks.map((mk) => mk.row)) + 2 : 0; const words = (said, record, lead = null) => ({ said, record, ...(lead ? { lead } : {}), width: (lead ? tw(`${lead} `, size) + 8 : 0) + tw(said, size) + (record ? tw(` ${record}`, size) + 12 : 0), }); const items = fcl.items.map((it, j) => { if (it.kind === "count") { const band = it.band ? { a: r2(toBig(it.band.a)), b: r2(toBig(it.band.b)) } : null; // Dimmed: the track under each veil, and each pip under one as a dot of // its own size -- a finale pip's ring (it is playing) stays whole. const veils = (it.veils ?? []).map(([a, b]) => [r2(toBig(a)), r2(toBig(b))]); const dots = pips.filter((p) => veils.some(([a, b]) => p.x > a && p.x < b)).map((p) => ({ x: p.x, size: p.size + 4 })); const rings = it.band ? it.tags.map((t) => ({ x: bigX(t.k), size: ringSize })) : []; const spans = (it.spans ?? []).map((sp) => ({ a: r2(toBig(sp.a)), b: r2(toBig(sp.b)), cx: r2(toBig(sp.cx)), label: sp.label, w: tw(String(sp.label).toUpperCase(), size) + Math.round(size * 0.04 * String(sp.label).length), bars: sp.bars.map((bar) => ({ a: r2(toBig(bar.a)), b: r2(toBig(bar.b)) })), })); const record = it.band ? `${it.total} ${it.noun} on camera` : spans.map((sp) => sp.label).join(" · ") || "none on camera"; const left = band ? band.a : spans.length ? spans[0].a : bigX(0); // A band's words hang from its left edge; a per claim's from nothing (its spans carry their counts). const label = { ...words(it.said, record), left: r2(left), stickX: band ? r2(left + 1) : null, j }; return { kind: "count", j, band, veils, dots, rings, spans, label }; } const steps = it.steps.map((st, s) => { const a = r2(toBig(st.a)), b = r2(toBig(st.b)); // What it is (the goalpost's `label`) leads its standing step's words. const last = s === it.steps.length - 1; const w = words(st.said, st.open ? `→ ${st.dueText}` : `· ${st.dueText}`, last && it.label ? `${it.label}:` : null); const align = st.align; const left = align === "right" ? b - w.width : a; const label = { ...w, left: r2(left), stickX: r2(align === "right" ? b - 1 : a + 1), align, j, s, ghost: s + 1 < it.steps.length }; return { a, b, open: st.open, off: st.off, ghost: s + 1 < it.steps.length, label }; }); return { kind: "goalpost", j, ...(it.label ? { name: it.label } : {}), steps }; }); // The words, laid: per claim against the markers ("rotate"), or all together. const geo = { W, margin }; const lay = (its, rows) => { // A per claim's span labels first (on their bars when they can), then each claim's words, a goalpost's standing step first. for (const it of its) { for (const sp of it.spans ?? []) { Object.assign(sp, placeAbove(rows, { w: sp.w, left: sp.cx - sp.w / 2, align: "center", stick: { x: sp.cx, a: sp.cx, b: sp.cx }, minRow: 0, stickFrom: 1 }, geo)); } } for (const it of its) { const labels = it.kind === "count" ? [it.label] : [...it.steps].reverse().map((st) => st.label); for (const l of labels) { const range = it.kind === "count" ? (it.band ? { a: it.band.a + 1, b: it.band.b - 1 } : null) : (() => { const st = it.steps[l.s]; return { a: st.a + 1, b: st.b - 1 }; })(); const placed = placeAbove(rows, { w: l.width + 8, left: l.left, align: l.align === "right" ? "right" : "left", stick: l.stickX === null ? null : { x: l.stickX, a: range.a, b: range.b }, minRow: Math.max(1, markerRows), stickFrom: 0, }, geo); Object.assign(l, placed); } } return rows.length; }; let rows = markerRows; if (mode === "rotate") { for (const it of items) rows = Math.max(rows, lay([it], base.map((r) => [...r]))); } else rows = Math.max(rows, lay(items, base.map((r) => [...r]))); return { mode, rows, items }; }