// THE ANALYSIS ITEM'S PLAN (lane analysis-ending, 12 Nov): an ending built // from the ledger, not from a clip -- a chart of a named run of his weights // with a shaded band, a pace table, a status row and ONE reading line, // inserted into the cut as a timeline entry of its own: // // { "type": "analysis", "id": "an1", "title": "What his own numbers say", // "kicker": "THE KETO RUN · EVERY WEIGHT HE STATED", // "series": { "rows": ["w91", "w87", …] } // or { "from": "", "to": "" } // "band": { "from": "2026-10-23", "to": "2026-11-03", "label": "WORLD SERIES" }, // an event's dates, typed // "marks": [{ "row": "w118", "label": "offers the scale video", "quote": "…" }], // "pace": [{ "from": "2026-09-24", "to": "2026-10-15", "note": "…" }], // "status": [{ "label": "SCALE VIDEO", "value": "NOT POSTED", "note": "offered 23 Oct", "color": "red", "row": "p01" }], // "reading": "…", "footnote": "…", "mark": { "row": "w115" }, // "audio": { "clip": "c46", "start": 4112.6, "end": 4127.1 }, // optional // "seconds": 7 } // without audio; at most 8 // // DATA, NOT DRAWING. Every figure on screen is computed here from a ledger // row and carries that row's id: a point's weight (a `delta` resolved against // the run's start, measure-slice.mjs runStartAt -- the base a loss goal reads), // a mark's figure and date, a pace row's pounds and days, the dashed line's // value. A number TYPED into the words (a title, a label, a note, the reading) // is a lint warning naming the field -- dates aside ("23 Oct", "Oct 2026") -- // unless the field names a row and the number is that row's. // // A BOUND IS NEVER AN EXACT FIGURE. A point whose row is a bound ("< 300") is // drawn hollow (as the trail draws a qualified weight); a pace row that ends on // one says it in words, unsigned and in the right direction: ending on // "< 300" it is "MORE THAN 10.5 lb lost", starting on it "AT MOST 8.5 lb lost". // // PURE: the entry, the ledger, the schema and the timeline in, plain data out. import { dateKey } from "./ledger-shared.mjs"; import { dayNumber, fmtSigned, fmtWeight } from "./measure-draw.mjs"; import { isUsable, runStartOf, speakerOf } from "./measure-slice.mjs"; import { measureQualifier, measureSchema, plotDate } from "./measure-totals.mjs"; import { playEdges } from "./mute.mjs"; import { gapsOf } from "./gaps.mjs"; import { trailLayout, trailLine } from "./trail-plan.mjs"; import { endFadeOf, transitionOf } from "./deck.mjs"; import { itemSpans } from "./full-frame.mjs"; /** The item's length: the silent default and ceiling (no dead air), the floor any item has, the longest audio. */ export const ANALYSIS_SECONDS = Object.freeze({ silent: 7, silentMax: 8, min: 4, audioMax: 30 }); /** * The page's motion, in seconds at full pace (chrome-analysis.mjs draws it): the title, the axes, the band, the line * drawn point to point, then the READING right after the line, the pace and status rows landing beside it. A short * item's motion is scaled by k (at least `kMin`: the line still draws, nothing slams) so the reading is fully lit for * its read time (ANALYSIS_READ) before the picture starts to leave. */ export const ANALYSIS_MOTION = Object.freeze({ title: 0.5, axes: 0.3, band: 0.8, lineFrom: 0.8, line: 2.2, point: 0.3, mark: 0.35, rowGap: 0.25, row: 0.35, rowRise: 10, reading: 0.5, readGap: 0.1, foot: 0.2, kMin: 0.45, }); /** Seconds from the item's start to its reading coming in, at full pace (k = 1); it is fully lit `reading` (its fade, never scaled) later. */ export const READ_AFTER = ANALYSIS_MOTION.lineFrom + ANALYSIS_MOTION.line + ANALYSIS_MOTION.readGap; /** The reading's time fully on screen: `perWord` a word, at least `min`, at most `max` seconds. */ export const ANALYSIS_READ = Object.freeze({ perWord: 0.3, min: 2.5, max: 5 }); /** The reading's words (a dash or a mark is no word). */ export const readingWords = (s) => (String(s ?? "").match(/[\p{L}\p{N}][\p{L}\p{N}'’.,-]*/gu) ?? []).length; /** The reading's read time: words × perWord, clamped to [min, max]. */ export const readHoldOf = (reading) => r2(Math.min(ANALYSIS_READ.max, Math.max(ANALYSIS_READ.min, readingWords(reading) * ANALYSIS_READ.perWord))); /** * When the item's picture starts to LEAVE, in its own seconds: its length less what the build does at its end -- * the dissolve out to the next segment (`render.transition`), or, when it is the cut's last entry, the cut's closing * fade (`render.endFade`; 0: none, the page lit to the last frame). `{ leave, tail, last, seconds }`. */ export function analysisLeave(entry, timeline, render) { const seconds = analysisSeconds(entry); const tl = Array.isArray(timeline) ? timeline : []; const last = tl.length > 0 && tl[tl.length - 1]?.id === entry?.id; const tail = last ? endFadeOf(render ?? {}) : transitionOf(render ?? {}); return { leave: r2(seconds - tail), tail, last, seconds }; } /** How many rows each table holds on the frame (`rows`: pace and status together, the side panel's room). */ export const ANALYSIS_LIMITS = Object.freeze({ pace: 5, status: 2, rows: 5, marks: 6, series: 120 }); /** * What each word field holds, in characters -- the lint's estimate of the frame (the deck's condensed faces at * 1280x720 units); the build measures the page itself and refuses what leaves the frame or overlaps (chrome-analysis.mjs). * `reading` with the audio's QR beside it is `readingQr`. */ export const ANALYSIS_TEXT = Object.freeze({ title: 44, kicker: 64, bandLabel: 28, mark: 46, quote: 100, paceNote: 24, statusLabel: 20, statusValue: 12, statusNote: 36, reading: 185, readingQr: 160, footnote: 120, }); /** The palette roles a status figure may be drawn in (or a #hex). */ export const ANALYSIS_COLORS = Object.freeze(["accent", "amber", "red", "fg", "muted"]); /** The keys an analysis entry may carry. */ export const ANALYSIS_KEYS = Object.freeze([ "type", "id", "title", "kicker", "series", "band", "marks", "pace", "status", "reading", "footnote", "mark", "audio", "seconds", "onscreen", "note", "drafted", ]); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const isIso = (v) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v); const r2 = (v) => Math.round(v * 100) / 100; const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; /** "2026-10-23" as "23 Oct". */ export function dayMonth(iso) { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso ?? "")); return m ? `${Number(m[3])} ${MON[Number(m[2]) - 1]}` : ""; } /** A span's two dates as the pace table says them: "24 Sep → 15 Oct", one month once: "15 → 23 Oct". */ export function spanWords(a, b) { const [da, db] = [dayMonth(a), dayMonth(b)]; const [na, ma] = da.split(" "); const [nb, mb] = db.split(" "); return ma === mb ? `${na} → ${nb} ${mb}` : `${da} → ${db}`; } // --------------------------------------------------------------------------- // Numbers typed into words. // --------------------------------------------------------------------------- const MONTH = "(jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\\.?"; const YEAR = "((?:19|20)\\d{2})"; /** The date tokens a text may carry, strictest first: ISO, day month [year], month day [year], month year. */ const DATE_TOKENS = [ { re: /\b(\d{4})-(\d{2})-(\d{2})\b/gi, of: (m) => ({ y: Number(m[1]), mon: Number(m[2]) - 1, d: Number(m[3]) }) }, { re: new RegExp(`\\b(\\d{1,2})(?:st|nd|rd|th)?\\s+${MONTH}(?:,?\\s+${YEAR})?\\b`, "gi"), of: (m) => ({ d: Number(m[1]), mon: monthIndex(m[2]), y: m[3] ? Number(m[3]) : null }) }, { re: new RegExp(`\\b${MONTH}\\s+(\\d{1,2})(?:st|nd|rd|th)?(?:,?\\s+${YEAR})?\\b`, "gi"), of: (m) => ({ d: Number(m[2]), mon: monthIndex(m[1]), y: m[3] ? Number(m[3]) : null }) }, { re: new RegExp(`\\b${MONTH}\\s+${YEAR}\\b`, "gi"), of: (m) => ({ d: null, mon: monthIndex(m[1]), y: Number(m[2]) }) }, ]; function monthIndex(word) { return MON.findIndex((m) => String(word).toLowerCase().startsWith(m.toLowerCase())); } /** * A text's typed numbers: its date tokens (each `{ text, d, mon, y }`) taken out, then every number left * (`numbers`, as written). A year counts as part of a date only beside a month; a bare "2026" is a number. */ export function typedNumbers(text) { let rest = String(text ?? ""); const dates = []; for (const { re, of } of DATE_TOKENS) { rest = rest.replace(re, (...m) => { dates.push({ text: m[0], ...of(m) }); return " "; }); } return { dates, numbers: rest.match(/\d+(?:[.,]\d+)?/g) ?? [] }; } /** Does a date token name this day (an ISO date)? A token without a year matches any year. */ function dateIs(tok, iso) { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso ?? "")); if (!m) return false; return (tok.d === null || tok.d === Number(m[3])) && tok.mon === Number(m[2]) - 1 && (tok.y === null || tok.y === Number(m[1])); } /** * The warnings a typed field earns: a number left once its dates are taken out -- unless `row` backs it and the * number is that row's figure (`figures`, the row's value and any value it is drawn as); with a row, a date that is * not the row's (its date or its asOf) is said too. */ function numberWarnings(where, text, { row = null, figures = [] } = {}) { if (typeof text !== "string" || !text) return []; const { dates, numbers } = typedNumbers(text); const out = []; const okFigure = (n) => figures.some((f) => Number.isFinite(f) && Math.abs(Math.abs(f) - Math.abs(Number(n.replace(",", ".")))) < 0.051); const stray = row ? numbers.filter((n) => !okFigure(n)) : numbers; if (stray.length) { out.push(`${where} "${text}" has ${stray.map((n) => `"${n}"`).join(", ")} typed -- ${row ? `not ${row.id}'s figure; ` : ""}the item's figures are drawn from ledger rows${row ? "" : " (name the row, or take it out)"}`); } if (row) { const wrong = dates.filter((d) => !dateIs(d, row.date) && !dateIs(d, row.asOf)); if (wrong.length) out.push(`${where} "${text}" says ${wrong.map((d) => `"${d.text}"`).join(", ")} -- not ${row.id}'s date (${dayMonth(row.date)}${row.asOf ? `, as of ${dayMonth(row.asOf)}` : ""})`); } return out; } // --------------------------------------------------------------------------- // Bounds. // --------------------------------------------------------------------------- /** * The bound a pace row's figure is, from its two ends' qualifiers: the true change against the computed one. Ending * on "< v" (the weight was under v) the change is LESS than computed (more lost); starting on it, MORE (less lost); * ">" the other way. Both ends bounding opposite ways: no bound can be said ("unknown"). Null: exact. * * @returns {null | "lt" | "gt" | "unknown"} */ export function paceBound(qa, qb) { const dirs = []; if (qa === "<") dirs.push("gt"); if (qa === ">") dirs.push("lt"); if (qb === "<") dirs.push("lt"); if (qb === ">") dirs.push("gt"); if (!dirs.length) return null; return dirs.every((d) => d === dirs[0]) ? dirs[0] : "unknown"; } /** * A pace row's figure in words: `{ lead, figure, tail, text }`. Exact: the signed change ("−0.7 lb"). A bound, * unsigned and in words that stay true whatever the real change was -- the change LESS than computed is "MORE THAN * 10.5 lb lost" (or "AT MOST n lb gained"), MORE than computed "AT MOST 8.5 lb lost" (or "MORE THAN n lb gained"); * opposite bounds "—". An "about" end ("≈"): "about −9 lb". */ export function paceWords(lb, bound, approx = false) { const n = `${fmtWeight(Math.abs(lb))} lb`; let w; if (bound === "unknown") w = { lead: null, figure: "—", tail: null }; else if (bound === "lt") w = lb < 0 ? { lead: "MORE THAN", figure: n, tail: "lost" } : { lead: "AT MOST", figure: n, tail: "gained" }; else if (bound === "gt") w = lb <= 0 ? { lead: "AT MOST", figure: n, tail: "lost" } : { lead: "MORE THAN", figure: n, tail: "gained" }; else if (approx) w = { lead: "about", figure: `${fmtSigned(lb)} lb`, tail: null }; else w = { lead: null, figure: `${fmtSigned(lb)} lb`, tail: null }; return { ...w, text: [w.lead, w.figure, w.tail].filter(Boolean).join(" ") }; } /** A point as the dry-run and the lint name it: "w115 < 300", "w101 ≈324", "w110 310.5". */ const endWords = (p) => `${p.row} ${p.qualifier === "<" || p.qualifier === ">" ? `${p.qualifier} ` : p.qualifier ?? ""}${fmtWeight(p.value)}`; // --------------------------------------------------------------------------- /** The item's length: the audio's span, else `seconds` (default ANALYSIS_SECONDS.silent). */ export function analysisSeconds(entry) { const a = entry?.audio; if (isObj(a) && Number.isFinite(Number(a.start)) && Number.isFinite(Number(a.end)) && Number(a.end) > Number(a.start)) { return r2(Number(a.end) - Number(a.start)); } const s = Number(entry?.seconds); return Number.isFinite(s) && s > 0 ? s : ANALYSIS_SECONDS.silent; } /** * THE CUT SECONDS NO CHROME DRAWS OVER, for an analysis item (its page is the whole frame): each analysis segment * of the schedule as `[from, to]` cut seconds -- from the first frame of its dissolve in (its segment's start) to the * last of its dissolve out (its end), the cut's end + 1 when it is last: the span the deck's own regions leave out * (full-frame.mjs regionSpans `followsDeck`; every other region's ends a frame sooner). [] without one. */ export const analysisBlackouts = (schedule) => itemSpans(schedule, "analysis"); /** The ledger a cut's analysis reads: the variant's whole measure record (selectVariant keeps it), else the ledger. */ export const analysisLedger = (manifest) => (Array.isArray(manifest?.measureLedger) ? manifest.measureLedger : manifest?.ledger ?? []); /** The context an item's plan reads, from the cut's manifest. */ export const analysisContext = (manifest) => ({ ledger: analysisLedger(manifest), schema: manifest?.ledgerSchema ?? null, timeline: manifest?.timeline ?? [], render: manifest?.render ?? {}, }); /** Every analysis entry's errors, as the build refuses them. */ export function validateAnalysisEntries(manifest) { const items = (manifest?.timeline ?? []).filter((e) => e?.type === "analysis"); const errors = items.flatMap((e) => analysisProblems(e, analysisContext(manifest)).errors); // Its page draws in the deck's faces (instrumentFonts): a cut without them is refused before anything is spent. const r = manifest?.render ?? {}; if (items.length && (!r.fontRegular || !r.fontBold)) errors.push(`timeline ${items[0].id} (analysis): an analysis item draws in the deck's faces -- the cut needs render.fontRegular and render.fontBold`); return errors; } /** Every analysis entry's warnings, as the lint says them. */ export function analysisWarnings(manifest, { only = null } = {}) { return (manifest?.timeline ?? []).filter((e) => e?.type === "analysis" && (!only || e.id === only)).flatMap((e) => analysisProblems(e, analysisContext(manifest)).warnings); } /** * The ledger rows an analysis entry names (series rows, marks, pace ends given as ids, status rows, the dashed * line's row) -- what `umtool ledger rm` counts as a reference. */ export function analysisRowRefs(entry) { const out = new Set(); const add = (v) => { if (typeof v === "string" && v && !isIso(v)) out.add(v); }; if (Array.isArray(entry?.series?.rows)) entry.series.rows.forEach(add); add(entry?.series?.from); add(entry?.series?.to); for (const m of Array.isArray(entry?.marks) ? entry.marks : []) add(m?.row); for (const p of Array.isArray(entry?.pace) ? entry.pace : []) { add(p?.from); add(p?.to); } for (const s of Array.isArray(entry?.status) ? entry.status : []) add(s?.row); add(entry?.mark?.row); return [...out]; } /** * An analysis entry with `patch` laid over it, key by key: a key given replaces the entry's, `null` removes it, a key * not given is kept. Its `type` and `id` are not a patch's to change. Throws a sentence for a patch that is not an object. */ export function applyAnalysisPatch(entry, patch) { if (!isObj(patch)) throw new Error("an analysis patch is a JSON object of the entry's keys"); for (const k of ["type", "id"]) if (k in patch && patch[k] !== entry?.[k]) throw new Error(`an analysis patch does not change its ${k}`); const next = JSON.parse(JSON.stringify(entry)); for (const [k, v] of Object.entries(patch)) { if (v === null) delete next[k]; else next[k] = JSON.parse(JSON.stringify(v)); } return next; } /** * Every reason the item cannot be drawn (`errors`) and what is said about it (`warnings`), each naming the entry and * the row. `ctx`: `{ ledger, schema, timeline, render }` -- the WHOLE ledger (analysisLedger), the ledger's schema, * the cut's timeline. */ export function analysisProblems(entry, ctx) { return resolve(entry, ctx).problems; } /** * The plan: the points (each `{ n, row, value, day, date, said, kind, qualifier, bound, base? }`), the line through * them (trailLine: one point a day, the one said last, in date order), the axes laid in `box` (trailLayout, one * cluster: `lo`/`hi`, `X`/`Y`, `grid`, `months`, the dashed line's `mark`), the band, the marks, the pace rows, the * status rows, the words, the audio and the seconds. Throws the errors (analysisProblems) when there are any. */ export function analysisPlan(entry, ctx, box = { x0: 70, x1: 800, y0: 150, y1: 560 }) { const r = resolve(entry, ctx); if (r.problems.errors.length) throw new Error(r.problems.errors.join("; ")); const { points } = r; const line = trailLine(points); const mark = r.mark ? r.mark.value : null; // By days alone (dayShare 1): on this chart a span's width says its days, the band and the months included. const L = trailLayout(points, box, { thr: Infinity, mark, dayShare: 1 }); const pos = new Map(points.map((p) => [p.n, { x: L.X(p.day), y: L.Y(p.value) }])); const step = L.hi - L.lo > 60 ? 20 : 10; const grid = []; for (let v = Math.ceil(L.lo / step) * step; v <= L.hi; v += step) if (v !== mark) grid.push({ v, y: L.Y(v) }); const c = L.clusters[0]; const months = []; if (c) { const d0 = new Date(c.from * 86400000); let y = d0.getUTCFullYear(), m = d0.getUTCMonth() + 1; for (;; m += 1) { if (m > 11) { m = 0; y += 1; } const day = Date.UTC(y, m, 1) / 86400000; if (day > c.to) break; if (day >= c.from) months.push({ day, x: L.X(day), text: m === 0 ? `JAN ${y}` : MON[m].toUpperCase() }); } } const band = r.band ? { ...r.band, x0: L.X(r.band.fromDay), x1: L.X(r.band.toDay) } : null; const marks = r.marks.map((k) => ({ ...k, at: pos.get(k.n) })); return { title: String(entry.title ?? "").trim(), kicker: String(entry.kicker ?? "").trim(), reading: String(entry.reading ?? "").trim(), footnote: String(entry.footnote ?? "").trim(), points, line: line.map((p) => p.n), pos, layout: { lo: L.lo, hi: L.hi, X: L.X, Y: L.Y, grid, months, mark, markRow: r.mark?.row ?? null, markLabel: r.mark?.label ?? null, markY: mark !== null ? L.Y(mark) : null }, band, marks, pace: r.pace, status: r.status, audio: r.audio, seconds: analysisSeconds(entry), readHold: readHoldOf(entry.reading), readWords: readingWords(entry.reading), ...pickLeave(analysisLeave(entry, ctx?.timeline, ctx?.render)), first: points.length ? line[0] : null, last: points.length ? line[line.length - 1] : null, }; } /** The figures the plan draws, one line each with its row -- what `--dry-run` prints. */ export function analysisFigures(plan) { const out = []; for (const p of plan.points) { out.push(`point ${p.row}: ${p.qualifier ?? ""}${fmtWeight(p.value)} on ${p.date}${p.base ? ` (${p.raw} from ${p.base.row} ${fmtWeight(p.base.value)})` : ""}${p.bound ? " -- a bound, drawn hollow" : ""}`); } if (plan.layout.mark !== null) out.push(`line ${plan.layout.markLabel} (${plan.layout.markRow}), dashed`); if (plan.band) out.push(`band ${plan.band.from} → ${plan.band.to} "${plan.band.label}" (typed dates)`); plan.pace.forEach((x, i) => out.push( `pace[${i}] ${x.span}: ${x.text} (${endWords(x.from)} → ${endWords(x.to)}), ${x.days} days${x.boundRows.length ? ` -- a bound: ${x.boundRows.join(", ")}` : ""}`, )); plan.marks.forEach((k, i) => out.push(`marks[${i}] ${k.row}: ${k.text}`)); plan.status.forEach((s, i) => out.push(`status[${i}] ${s.label}: ${s.value}${s.note ? ` · ${s.note}` : ""}${s.row ? ` (${s.row})` : ""}`)); if (plan.audio) out.push(`audio ${plan.audio.clip} ${plan.audio.start}–${plan.audio.end} (${plan.seconds} s)`); else out.push(`silent, ${plan.seconds} s`); return out; } // --------------------------------------------------------------------------- function resolve(entry, { ledger = [], schema = null, timeline = [], render = {} } = {}) { const errors = []; const warnings = []; const id = entry?.id ?? "?"; const at = `timeline ${id} (analysis)`; const out = { problems: { errors, warnings }, points: [], band: null, marks: [], pace: [], status: [], audio: null, mark: null }; if (!isObj(entry)) { errors.push(`${at}: not an object`); return out; } for (const k of Object.keys(entry)) if (!ANALYSIS_KEYS.includes(k)) errors.push(`${at}: unknown key "${k}"`); if (!String(entry.title ?? "").trim()) errors.push(`${at}: title is empty`); if (typeof entry.reading !== "string" || !entry.reading.trim()) errors.push(`${at}: reading is empty -- the item says ONE reading`); if (render && (Number(render.height) > Number(render.width) || render.format === "vertical")) { errors.push(`${at}: an analysis item has no vertical form -- a 9:16 cut cannot carry it`); } const fits = (where, text, max) => { const s = String(text ?? "").trim(); if (s.length > max) errors.push(`${at}: ${where} is ${s.length} characters -- at most ${max} fit the frame (the lint's estimate; the build measures the page)`); }; const s = measureSchema(schema ?? {}); const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null; const rows = (ledger ?? []).filter((r) => isObj(r) && typeof r.id === "string"); const byId = new Map(rows.map((r) => [r.id, r])); const order = new Map(rows.map((r, i) => [r.id, i])); // ---- the series ---------------------------------------------------------- const series = entry.series; const weightRow = (r) => r.scope === valueTrack && ["current", "past", "delta"].includes(r.population); let picked = []; let spanMode = false; if (isObj(series) && Array.isArray(series.rows)) { if (!series.rows.length) errors.push(`${at}: series.rows is empty`); if (series.rows.length > ANALYSIS_LIMITS.series) errors.push(`${at}: series.rows has ${series.rows.length} rows (at most ${ANALYSIS_LIMITS.series})`); const seen = new Set(); for (const rid of series.rows) { const r = byId.get(String(rid)); if (!r) { errors.push(`${at}: series row ${rid} is not in the ledger`); continue; } if (seen.has(r.id)) { errors.push(`${at}: series row ${rid} is named twice`); continue; } seen.add(r.id); if (!weightRow(r)) { errors.push(`${at}: series row ${rid} is not a weight (${r.scope}/${r.population}) -- a series is current, past or delta rows of the ${valueTrack ?? "value"} track`); continue; } if (speakerOf(r) !== null) { errors.push(`${at}: series row ${rid} is ${speakerOf(r)}'s, not his`); continue; } if (!isUsable(r)) warnings.push(`${at}: series row ${rid} is unresolved -- in no tally, drawn because the item names it`); picked.push(r); } } else if (isObj(series) && (series.from !== undefined || series.to !== undefined)) { spanMode = true; const a = endDay(series.from, byId), b = endDay(series.to, byId); if (!a.ok) errors.push(`${at}: series.from ${a.why}`); if (!b.ok) errors.push(`${at}: series.to ${b.why}`); if (a.ok && b.ok) { if (b.day < a.day) errors.push(`${at}: series.to (${b.date}) is before series.from (${a.date})`); picked = rows.filter((r) => weightRow(r) && speakerOf(r) === null && isUsable(r) && Number.isFinite(Number(r.value)) && dayNumber(plotDate(r)) >= a.day && dayNumber(plotDate(r)) <= b.day); if (!picked.length) errors.push(`${at}: no weight of his between ${a.date} and ${b.date}`); } } else errors.push(`${at}: series is { rows: [ids] } or { from, to }`); const points = []; const baseless = []; for (const r of picked) { const raw = Number(r.value); if (r.value === null || r.value === "" || !Number.isFinite(raw)) { errors.push(`${at}: series row ${r.id} has no number`); continue; } const date = dateKey(plotDate(r)); const day = dayNumber(date); if (!Number.isFinite(day)) { errors.push(`${at}: series row ${r.id} has no date`); continue; } const q = measureQualifier(r, s); let value = raw; let base = null; if (r.population === "delta") { base = runStartOf(rows, schema, r.date); if (!base) { if (spanMode) baseless.push(r); else errors.push(`${at}: series row ${r.id} is a delta (${raw}) with no run start in the record to resolve it against`); continue; } value = r2(base.value + raw); } points.push({ row: r.id, value, raw, day, date, said: r.date ?? date, population: r.population, kind: r.population === "past" ? "remembered" : r.population === "delta" ? "delta" : "stated", qualifier: q, bound: q === "<" || q === ">", ...(base ? { base: { row: base.row, value: base.value } } : {}), }); } if (baseless.length) { const ok = picked.filter((r) => !baseless.includes(r)).map((r) => r.id); errors.push(`${at}: series {from, to} takes ${baseless.map((r) => `${r.id} (${r.value})`).join(", ")} -- deltas with no run start in the record to resolve them against; name the rows instead: "series": { "rows": [${ok.map((x) => `"${x}"`).join(", ")}] }`); } // `t` is the order he SAID them (date, then the ledger's order): of two weights for one day the line takes the later. points.sort((p, q) => dateKey(p.said).localeCompare(dateKey(q.said)) || order.get(p.row) - order.get(q.row)); points.forEach((p, i) => { p.t = i; p.n = i; }); out.points = points; const firstDay = points.length ? Math.min(...points.map((p) => p.day)) : NaN; const lastDay = points.length ? Math.max(...points.map((p) => p.day)) : NaN; // A pace end: a row id, or a date with exactly one point of the series on it. const pointOf = (v) => { if (typeof v !== "string" || !v.trim()) return { ok: false, why: "is missing" }; if (isIso(v)) { const on = points.filter((p) => p.day === dayNumber(v)); if (!on.length) return { ok: false, why: `${v}: no point of the series on that day` }; if (on.length > 1) return { ok: false, why: `${v}: ${on.map((p) => p.row).join(", ")} are all on that day -- name one by id` }; return { ok: true, p: on[0] }; } const p = points.find((x) => x.row === v); if (p) return { ok: true, p }; return { ok: false, why: byId.has(v) ? `${v} is not a point of the series` : `${v} is not in the ledger` }; }; // ---- the dashed line: a row's value -------------------------------------- if (entry.mark !== undefined && entry.mark !== null) { const m = entry.mark; if (!isObj(m) || typeof m.row !== "string") errors.push(`${at}: mark is { "row": "" } -- the dashed line at that row's value (a bare number is not backed by a row)`); else { const r = byId.get(m.row); const v = Number(r?.value); if (!r) errors.push(`${at}: mark.row ${m.row} is not in the ledger`); else if (speakerOf(r) !== null) errors.push(`${at}: mark.row ${m.row} is ${speakerOf(r)}'s, not his`); else if (r.scope !== valueTrack || r.population === "delta" || r.value === null || r.value === "" || !Number.isFinite(v)) { errors.push(`${at}: mark.row ${m.row} has no weight to draw a line at (${r.scope}/${r.population})`); } else out.mark = { row: r.id, value: v, label: fmtWeight(v) }; } } // ---- the band: an event's dates, typed ------------------------------------- if (entry.band !== undefined && entry.band !== null) { const b = entry.band; if (!isObj(b)) errors.push(`${at}: band is { from, to, label }`); else { const a = endDay(b.from, byId), z = endDay(b.to, byId); if (!a.ok) errors.push(`${at}: band.from ${a.why}`); if (!z.ok) errors.push(`${at}: band.to ${z.why}`); if (a.ok && z.ok) { if (z.day < a.day) errors.push(`${at}: band.to (${z.date}) is before band.from (${a.date})`); else if (points.length && (a.day < firstDay || z.day > lastDay)) { errors.push(`${at}: band ${a.date} → ${z.date} is outside the series (${isoOf(firstDay)} → ${isoOf(lastDay)})`); } else out.band = { from: a.date, to: z.date, fromDay: a.day, toDay: z.day, label: String(b.label ?? "").trim() }; } warnings.push(...numberWarnings(`${at}: band.label`, b.label)); fits("band.label", b.label, ANALYSIS_TEXT.bandLabel); } } // ---- the marks ----------------------------------------------------------- const marks = Array.isArray(entry.marks) ? entry.marks : entry.marks === undefined ? [] : null; if (marks === null) errors.push(`${at}: marks is a list`); else { if (marks.length > ANALYSIS_LIMITS.marks) errors.push(`${at}: ${marks.length} marks (at most ${ANALYSIS_LIMITS.marks})`); marks.forEach((m, i) => { if (!isObj(m)) { errors.push(`${at}: marks[${i}] is { row, label, quote? }`); return; } const f = pointOf(String(m.row ?? "")); if (!f.ok) { errors.push(`${at}: marks[${i}].row ${f.why}`); return; } const label = String(m.label ?? "").trim(); const row = byId.get(f.p.row); warnings.push(...numberWarnings(`${at}: marks[${i}].label`, label, { row, figures: [f.p.value, f.p.raw] })); const quote = typeof m.quote === "string" ? m.quote.trim() : ""; const rowQuote = String(row?.quote ?? ""); if (quote && rowQuote && !quoteIn(quote, rowQuote)) warnings.push(`${at}: marks[${i}].quote is not in ${f.p.row}'s quote -- say whose words they are`); fits(`marks[${i}].quote`, quote, ANALYSIS_TEXT.quote); const fig = `${f.p.qualifier === "<" || f.p.qualifier === ">" || f.p.qualifier === "≈" ? `${f.p.qualifier} ` : ""}${fmtWeight(f.p.value)}`; const text = `${fig} · ${dayMonth(f.p.date)}${label ? ` · ${label}` : ""}`; fits(`marks[${i}] ("${text}")`, text, ANALYSIS_TEXT.mark); out.marks.push({ i, row: f.p.row, n: f.p.n, label, quote, text }); }); } // ---- the pace ------------------------------------------------------------ const pace = Array.isArray(entry.pace) ? entry.pace : entry.pace === undefined ? [] : null; if (pace === null) errors.push(`${at}: pace is a list`); else { if (pace.length > ANALYSIS_LIMITS.pace) errors.push(`${at}: ${pace.length} pace rows (at most ${ANALYSIS_LIMITS.pace})`); pace.forEach((x, i) => { if (!isObj(x)) { errors.push(`${at}: pace[${i}] is { from, to, note? }`); return; } const a = pointOf(x.from), b = pointOf(x.to); if (!a.ok) errors.push(`${at}: pace[${i}].from ${a.why}`); if (!b.ok) errors.push(`${at}: pace[${i}].to ${b.why}`); if (!a.ok || !b.ok) return; const days = b.p.day - a.p.day; if (days <= 0) { errors.push(`${at}: pace[${i}] ends (${b.p.date}) on or before it starts (${a.p.date})`); return; } const lb = r2(b.p.value - a.p.value); const bound = paceBound(a.p.bound ? a.p.qualifier : null, b.p.bound ? b.p.qualifier : null); const approx = a.p.qualifier === "≈" || b.p.qualifier === "≈"; const words = paceWords(lb, bound, approx); const boundRows = [a.p, b.p].filter((p) => p.bound).map((p) => p.row); const note = String(x.note ?? "").trim(); warnings.push(...numberWarnings(`${at}: pace[${i}].note`, note)); fits(`pace[${i}].note`, note, ANALYSIS_TEXT.paceNote); if (bound) warnings.push(`${at}: pace[${i}] ends on a bound (${[a.p, b.p].filter((p) => p.bound).map(endWords).join(", ")}) -- drawn as ${words.text}`); out.pace.push({ i, span: spanWords(a.p.date, b.p.date), from: pick(a.p), to: pick(b.p), lb, days, note, bound, boundRows, approx, lead: words.lead, figure: words.figure, tail: words.tail, text: words.text, }); }); } // ---- the status ---------------------------------------------------------- const status = Array.isArray(entry.status) ? entry.status : entry.status === undefined ? [] : null; if (status === null) errors.push(`${at}: status is a list`); else { if (status.length > ANALYSIS_LIMITS.status) errors.push(`${at}: ${status.length} status rows (at most ${ANALYSIS_LIMITS.status})`); status.forEach((x, i) => { if (!isObj(x)) { errors.push(`${at}: status[${i}] is { label, value, note, color, row? }`); return; } const color = x.color === undefined || x.color === null || x.color === "" ? "fg" : String(x.color); if (!ANALYSIS_COLORS.includes(color) && !/^#[0-9a-fA-F]{6}$/.test(color)) errors.push(`${at}: status[${i}].color "${color}" is ${ANALYSIS_COLORS.join(", ")} or a #rrggbb`); const rid = x.row === undefined || x.row === null || x.row === "" ? null : String(x.row); const row = rid ? byId.get(rid) ?? null : null; if (rid && !row) errors.push(`${at}: status[${i}].row ${rid} is not in the ledger`); else if (row && speakerOf(row) !== null) errors.push(`${at}: status[${i}].row ${rid} is ${speakerOf(row)}'s, not his -- a status names his own row`); if (!String(x.label ?? "").trim() || !String(x.value ?? "").trim()) errors.push(`${at}: status[${i}] needs a label and a value`); const figures = row ? [Number(row.value)] : []; for (const k of ["label", "value", "note"]) warnings.push(...numberWarnings(`${at}: status[${i}].${k}`, String(x[k] ?? "").trim(), { row: row && speakerOf(row) === null ? row : null, figures })); fits(`status[${i}].label`, x.label, ANALYSIS_TEXT.statusLabel); fits(`status[${i}].value`, x.value, ANALYSIS_TEXT.statusValue); fits(`status[${i}].note`, x.note, ANALYSIS_TEXT.statusNote); out.status.push({ i, label: String(x.label ?? "").trim(), value: String(x.value ?? "").trim(), note: String(x.note ?? "").trim(), color, row: rid }); }); } const tableRows = (Array.isArray(pace) ? pace.length : 0) + (Array.isArray(status) ? status.length : 0); if (tableRows > ANALYSIS_LIMITS.rows) errors.push(`${at}: ${tableRows} pace and status rows -- the side panel holds ${ANALYSIS_LIMITS.rows}`); // ---- the words ----------------------------------------------------------- for (const k of ["title", "kicker", "reading", "footnote"]) warnings.push(...numberWarnings(`${at}: ${k}`, typeof entry[k] === "string" ? entry[k].trim() : "")); fits("title", entry.title, ANALYSIS_TEXT.title); fits("kicker", entry.kicker, ANALYSIS_TEXT.kicker); fits("footnote", entry.footnote, ANALYSIS_TEXT.footnote); fits(`reading (two lines${entry.audio ? ", beside the QR" : ""})`, entry.reading, entry.audio ? ANALYSIS_TEXT.readingQr : ANALYSIS_TEXT.reading); // ---- the sound and the length -------------------------------------------- const a = entry.audio; if (a !== undefined && a !== null) { if (!isObj(a)) errors.push(`${at}: audio is { clip, start, end }`); else { const clip = (timeline ?? []).find((e) => e?.id === a.clip) ?? null; const st = Number(a.start), en = Number(a.end); if (!clip) errors.push(`${at}: audio.clip ${a.clip ?? "(none)"} is not an entry of the cut`); else if (clip.type !== "clip") errors.push(`${at}: audio.clip ${a.clip} is a ${clip.type} entry, not a clip`); if (!Number.isFinite(st) || !Number.isFinite(en) || en <= st) errors.push(`${at}: audio.start and audio.end are source seconds, end after start`); else if (clip?.type === "clip") { const cut = Number.isFinite(clip.cutStart) && Number.isFinite(clip.cutEnd); const lo = cut ? Number(clip.cutStart) : Number(clip.start), hi = cut ? Number(clip.cutEnd) : Number(clip.end); const gaps = gapsOf(clip).filter((g) => g.from < en && g.to > st); if (en - st > ANALYSIS_SECONDS.audioMax + 1e-6) errors.push(`${at}: audio is ${r2(en - st)} s -- at most ${ANALYSIS_SECONDS.audioMax}`); if (st < lo - 1e-6 || en > hi + 1e-6) { errors.push(`${at}: audio ${st}–${en} is outside ${clip.id}'s ${cut ? "cut" : "window"} ${lo}–${hi} -- it plays only words the cut keeps`); } else if (gaps.length) { errors.push(`${at}: audio ${st}–${en} runs into ${clip.id}'s gap${gaps.length > 1 ? "s" : ""} ${gaps.map((g) => `${g.from}–${g.to}`).join(", ")} -- seconds the cut takes out`); } else { out.audio = { clip: clip.id, start: st, end: en, video: clip.video ?? null }; const heard = playedSpans(clip, render).filter((g) => g.from < en && g.to > st); if (heard.length) { const o = heard.map((g) => `${r2(Math.max(st, g.from))}–${r2(Math.min(en, g.to))}`).join(", "); warnings.push(`${at}: the audio's span plays in the cut too (${clip.id} plays ${o}): its words are heard twice`); } } } if (entry.seconds !== undefined && Number(entry.seconds) !== analysisSeconds(entry)) { warnings.push(`${at}: seconds is the audio's length (${analysisSeconds(entry)}) -- the ${entry.seconds} is not read`); } } } else { const secs = analysisSeconds(entry); if (entry.seconds !== undefined && !(Number(entry.seconds) > 0)) errors.push(`${at}: seconds is a number of seconds`); else if (secs > ANALYSIS_SECONDS.silentMax) errors.push(`${at}: held ${secs} s with no audio (at most ${ANALYSIS_SECONDS.silentMax}: no dead air) -- shorten it or give it audio from a clip`); } if (analysisSeconds(entry) < ANALYSIS_SECONDS.min) errors.push(`${at}: ${analysisSeconds(entry)} s is too short to read (at least ${ANALYSIS_SECONDS.min})`); // THE READING'S TIME: fully lit for its read time before the picture starts to leave, after the fastest calm // motion (k = kMin) has brought it in. if (typeof entry.reading === "string" && entry.reading.trim()) { const lv = analysisLeave(entry, timeline, render); const hold = readHoldOf(entry.reading); if (lv.leave - hold < ANALYSIS_MOTION.kMin * READ_AFTER + ANALYSIS_MOTION.reading - 1e-6) { errors.push(`${at}: the reading (${readingWords(entry.reading)} words) needs ${hold} s on screen; the item is ${lv.seconds} s` + `${lv.tail ? `, its last ${lv.tail} s ${lv.last ? "the cut's closing fade" : "the dissolve out"}` : ""} -- shorten the reading, raise seconds (≤ ${ANALYSIS_SECONDS.silentMax} silent) or put a clip's sound under it`); } } return out; } const pickLeave = (lv) => ({ leave: lv.leave, tail: lv.tail, last: lv.last }); const pick = (p) => ({ row: p.row, date: p.date, value: p.value, qualifier: p.qualifier }); const isoOf = (day) => new Date(day * 86400000).toISOString().slice(0, 10); /** A date or a row id as a day: `{ ok, day, date }` or `{ ok: false, why }`. */ function endDay(v, byId) { if (typeof v !== "string" || !v.trim()) return { ok: false, why: "is missing" }; if (isIso(v)) return { ok: true, day: dayNumber(v), date: v }; const r = byId.get(v); if (!r) return { ok: false, why: `${v} is not a date or a row of the ledger` }; const d = dateKey(plotDate(r)); return Number.isFinite(dayNumber(d)) ? { ok: true, day: dayNumber(d), date: d } : { ok: false, why: `${v} has no date` }; } /** The source spans a clip plays in the cut: its play window less its gaps. */ function playedSpans(clip, render) { const { from, to } = playEdges(clip, render); if (!Number.isFinite(from) || !Number.isFinite(to)) return []; const gaps = [...gapsOf(clip)].sort((x, y) => x.from - y.from); const out = []; let at = from; for (const g of gaps) { if (g.to <= at || g.from >= to) continue; if (g.from > at) out.push({ from: at, to: g.from }); at = Math.max(at, g.to); } if (at < to) out.push({ from: at, to }); return out; } const norm = (s) => String(s).toLowerCase().replace(/[’']/g, "'").replace(/[^a-z0-9' ]+/g, " ").replace(/\s+/g, " ").trim(); /** Each part of a quote (split at an ellipsis) found in the row's words. */ function quoteIn(quote, words) { const w = norm(words); return quote.split(/…|\.\.\./).map(norm).filter(Boolean).every((part) => w.includes(part)); }