// THE MEASURE EXTRAS (weight video rev 9, lane measure-extras): what the goal
// stack, the moving start, the promise clock and the diet badge draw, as data
// -- each a list of STATES on the cut's clock, read off the schedule's
// `measure` slice (CONTRACT.md: `measure.events` in cut order, `measure.state`
// the state after each one). chrome-measure-extras.mjs draws them; the
// modules (modules/goals.mjs, peak.mjs, promise.mjs, diet.mjs) register them.
//
// PURE: a schedule and a render block in, plain data out. No fs, no browser.
//
// The rules, as the operator and the contract give them:
// - GOALS: every goal / goalLoss event drops a note on a pile; a goal said
// again in the same words merges into its note with a count ("lose 100
// ×8") and comes to the front. A goal with a `deadline` counts down to
// `measure.asOfRender` ("by Christmas · 50 days left · needs 226.5"): the
// date is parsed from his words (deadlineDate), and words with no date in
// them ("by my birthday") keep their label and no countdown.
// - PEAK: every remembered weight that is one of the totals' `peakDrift`
// values (the starts he tells: 365.7 → 370 → 385 → 387 → ≈390) adds a tick
// on a small vertical scale, a retelling of the same number a count; the
// spread from the lowest to the highest so far is the drift.
// - PROMISE: from a promise on, the days since he said it -- to the in-record
// date of what is on screen, and from the finale (or a beat after the last
// event) to the render date, counted up a day at a time; each check's words
// under it; kept, "POSTED".
// - DIET: the state's diet, re-stamped at each change of regime or diet
// number; a null diet after one is "NO DIET" (the producer has applied the
// off-scope rule: this only draws state.diet).
import { deckGeometry, feedGeometry, instrumentsGeometry, overlayBox, pictureK } from "./deck.mjs";
import { chapterCover, chapterWindows } from "./chrome-story.mjs";
import { dietTagWidth, MEASURE_EXTRAS, MEASURE_POSITIONS, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs";
import { STAMP_NOTE } from "./ledger-shared.mjs";
import { resolveShelf } from "./modules/shelf-settings.mjs";
import { stackedOn, stackedStandDowns } from "./vertical-deck.mjs";
const r4 = (v) => Math.round(v * 10000) / 10000;
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const even = (v) => 2 * Math.round(v / 2);
const evenDown = (v) => 2 * Math.floor(v / 2);
/** The schedule's measure slice, when it has one the extras can read. */
export function measureOf(schedule) {
const m = schedule?.measure;
return isObj(m) && Array.isArray(m.events) && Array.isArray(m.state) ? m : null;
}
// ---------------------------------------------------------------------------
// Dates.
// ---------------------------------------------------------------------------
const ISO_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
const utc = (iso) => {
const m = ISO_RE.exec(String(iso ?? ""));
return m ? Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) : null;
};
const iso = (ms) => new Date(ms).toISOString().slice(0, 10);
/** Whole days from `a` to `b` (YYYY-MM-DD), or null. */
export function daysBetween(a, b) {
const x = utc(a);
const y = utc(b);
return x === null || y === null ? null : Math.round((y - x) / 86400000);
}
const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
/** The n-th weekday (0 Sunday) of a month, as UTC ms. */
function nthWeekday(year, month, weekday, n) {
const first = new Date(Date.UTC(year, month, 1)).getUTCDay();
return Date.UTC(year, month, 1 + ((weekday - first + 7) % 7) + 7 * (n - 1));
}
/** The days his words can name, each `(year) => ms`. */
const NAMED_DAYS = [
[/christmas eve/, (y) => Date.UTC(y, 11, 24)],
[/christmas|xmas/, (y) => Date.UTC(y, 11, 25)],
[/new year'?s eve/, (y) => Date.UTC(y, 11, 31)],
[/new year'?s?(?: day)?|the new year/, (y) => Date.UTC(y, 0, 1)],
[/halloween/, (y) => Date.UTC(y, 9, 31)],
[/thanksgiving/, (y) => nthWeekday(y, 10, 4, 4)],
[/valentine'?s/, (y) => Date.UTC(y, 1, 14)],
[/(?:the )?(?:4th|fourth) of july|july (?:4th|4)|independence day/, (y) => Date.UTC(y, 6, 4)],
[/end of (?:the )?(?:year|(?:19|20)\d{2})|year'?s end/, (y) => Date.UTC(y, 11, 31)],
];
/**
* The date a goal's deadline words name, as YYYY-MM-DD, or null when they
* name none he has given ("by my birthday", "by summer"). `said` is the date
* he said it: "by Christmas" is the next Christmas from then (25 Dec of its
* year, or the year after when said after it), "next year" a year on, an
* explicit year that year ("by the end of 2026", "by Halloween 2027"), an ISO
* date itself, "by March 3" the next 3 March.
*
* @param {string | null | undefined} words
* @param {string | null | undefined} said
*/
export function deadlineDate(words, said) {
if (typeof words !== "string" || !words.trim()) return null;
const w = words.toLowerCase().replace(/[’`]/g, "'").replace(/\s+/g, " ").trim();
const isoIn = /(\d{4}-\d{2}-\d{2})/.exec(w);
if (isoIn && utc(isoIn[1]) !== null) return isoIn[1];
const base = utc(said);
const saidYear = base === null ? null : new Date(base).getUTCFullYear();
const yearIn = /\b(20\d{2}|19\d{2})\b/.exec(w);
const next = /\bnext year\b/.test(w);
const pick = (f) => {
if (yearIn) return f(Number(yearIn[1]));
if (saidYear === null) return null;
let at = f(saidYear + (next ? 1 : 0));
// Said after this year's: the next one.
if (!next && at < base) at = f(saidYear + 1);
return at;
};
for (const [re, f] of NAMED_DAYS) {
if (re.test(w)) {
const at = pick(f);
return at === null ? null : iso(at);
}
}
// "by March 3", "by 3 March", "by march 3rd".
const md = new RegExp(`\\b(${MONTHS.join("|")})[a-z]*\\.? (\\d{1,2})(?:st|nd|rd|th)?\\b|\\b(\\d{1,2})(?:st|nd|rd|th)? (?:of )?(${MONTHS.join("|")})[a-z]*\\b`).exec(w);
if (md) {
const mon = MONTHS.indexOf(md[1] ?? md[4]);
const day = Number(md[2] ?? md[3]);
if (day >= 1 && day <= 31) {
const at = pick((y) => Date.UTC(y, mon, day));
return at === null ? null : iso(at);
}
}
return null;
}
/** "23 Oct" (or "23 Oct 2025" with `year`) from YYYY-MM-DD. */
export function shortDate(d, { year = false } = {}) {
const m = ISO_RE.exec(String(d ?? ""));
if (!m) return String(d ?? "");
const mon = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][Number(m[2]) - 1];
return `${Number(m[3])} ${mon}${year ? ` ${m[1]}` : ""}`;
}
/** "Jan 2021" from YYYY-MM-DD. */
export function monthYear(d) {
const m = ISO_RE.exec(String(d ?? ""));
if (!m) return "";
return `${["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][Number(m[2]) - 1]} ${m[1]}`;
}
/** A weight as he says it: 365.7, 390 (no trailing .0). */
export const weightText = (v) => (Number.isFinite(v) ? (Math.round(v * 10) % 10 === 0 ? String(Math.round(v)) : (Math.round(v * 10) / 10).toFixed(1)) : "");
/** "50 days left" | "1 day left" | "today" | "3 days past". */
export function daysLeftText(n) {
if (n === null) return "";
if (n === 0) return "today";
if (n > 0) return `${n} day${n === 1 ? "" : "s"} left`;
return `${-n} day${n === -1 ? "" : "s"} past`;
}
// ---------------------------------------------------------------------------
// The shared clock: when each module is up.
// ---------------------------------------------------------------------------
/** The finale's window in the cut, or null. */
const finaleOf = (schedule) => (isObj(schedule?.finale) && Number.isFinite(schedule.finale.from) ? schedule.finale : null);
/**
* When a module is up: from each event to `hold` seconds after it (spans
* that touch joined), or -- `hold` 0 or null -- from its first event to the end;
* never inside the finale's window unless `finale: "show"`.
*
* @returns {Array<{ in: number, out: number }>}
*/
export function upSpans(times, cfg, schedule) {
const total = Number(schedule.total) || 0;
const fin = finaleOf(schedule);
const end = fin && cfg.finale !== "show" ? Math.min(total, fin.from) : total;
const ts = times.filter((t) => Number.isFinite(t) && t < end).sort((a, b) => a - b);
if (!ts.length) return [];
if (!cfg.hold) return [{ in: r4(ts[0]), out: r4(end) }];
const out = [];
for (const t of ts) {
const span = { in: t, out: Math.min(end, t + cfg.hold) };
const last = out[out.length - 1];
if (last && span.in <= last.out + 1e-6) last.out = Math.max(last.out, span.out);
else out.push(span);
}
return out.map((s) => ({ in: r4(s.in), out: r4(s.out) }));
}
/** Each event with the state after it, in cut order (events with no time are not on screen). */
function stepsOf(m) {
const out = [];
m.events.forEach((e, i) => {
if (!Number.isFinite(e?.t)) return;
out.push({ e, s: m.state[i + 1] ?? m.state[m.state.length - 1] ?? null, i });
});
return out.sort((a, b) => a.e.t - b.e.t || a.i - b.i);
}
/** A stable pseudo-random number in [-1, 1] from a string (a note's jitter). */
export function jitter(s, salt = 0) {
let h = 2166136261 ^ salt;
for (const ch of String(s)) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);
return ((h >>> 0) % 2001) / 1000 - 1;
}
// ---------------------------------------------------------------------------
// GOALS
// ---------------------------------------------------------------------------
/** How a note's words read: "LOSE 100", "≈250 LB", "220–240 LB". */
export function goalText(e, unit = "lb") {
const d = String(e.display ?? "").trim() || (Number.isFinite(e.value) ? weightText(Math.abs(e.value)) : "");
if (e.kind === "goalLoss") return d.toUpperCase();
const q = e.qualifier === "≈" && !d.startsWith("≈") ? "≈" : "";
const range = d.replace(/(\d)\s*-\s*(\d)/, "$1–$2");
return /^[≈~<>]?\d/.test(range) ? `${q}${range} ${unit}`.toUpperCase() : range.toUpperCase();
}
/**
* A goal's base as its note writes it -- "(FROM 346.7)", "(FROM ≈390)" -- from the
* slice's `goal.base` ({ value, row }), the qualifier its row carries; null
* when there is none.
*/
export function goalBaseText(base, m) {
if (!base || !Number.isFinite(base.value)) return null;
const row = [...(m?.events ?? []), ...(m?.hidden ?? [])].find((e) => e.row === base.row);
const q = typeof row?.qualifier === "string" && /^[≈<>]$/.test(row.qualifier) ? row.qualifier : "";
return `(FROM ${q}${weightText(base.value)})`;
}
/**
* The pile's states: one per goal event, `{ at, top, goalsSet, notes }` --
* `notes` back to front (the last is the one that just landed, `top` its key),
* each `{ key, text, count, date, deadline, deadlineDate, days, target, rot,
* dx, depth, prev }` (`prev` its depth in the state before, null when new).
*/
export function goalStates(schedule, render) {
const m = measureOf(schedule);
const cfg = resolveMeasureExtra("goals", render);
if (!m || !cfg) return [];
const notes = new Map();
let order = [];
const states = [];
let prevDepth = new Map();
let n = 0;
for (const { e, s } of stepsOf(m)) {
if (e.kind !== "goal" && e.kind !== "goalLoss") continue;
// A goal of his that counts: not another speaker's, not an `unresolved` row (a joke) -- as the slice's tallies
// and the dial's goal board (measure-slice.mjs isUsable, measure-goals.mjs).
if (e.unresolved === true || (typeof e.speaker === "string" && e.speaker.trim())) continue;
n += 1;
const text = goalText(e, m.unit ?? "lb");
const key = text.toLowerCase();
let note = notes.get(key);
if (!note) {
note = { key, id: `n${notes.size}`, count: 0, rot: r4(jitter(e.row ?? key) * 5), dx: r4(jitter(e.row ?? key, 7) * 10) };
notes.set(key, note);
}
note.count += 1;
note.text = text;
note.date = e.date ?? null;
note.deadline = typeof e.deadline === "string" && e.deadline.trim() ? e.deadline.trim() : null;
// The ledger's own `due` when it has one (the producer resolves it), else his words read here.
const due = [e.due, s?.goal?.row === e.row ? s.goal.due : null].find((d) => typeof d === "string" && /^\d{4}-\d{2}-\d{2}$/.test(d)) ?? null;
note.deadlineDate = note.deadline ? due ?? deadlineDate(note.deadline, e.date) : null;
note.days = note.deadlineDate && m.asOfRender ? daysBetween(m.asOfRender, note.deadlineDate) : null;
// The weight it comes to: a goal's own number, or the state's resolution of a goalLoss.
const target = s?.goal && s.goal.row === e.row && Number.isFinite(s.goal.value) ? s.goal.value
: e.kind === "goal" && Number.isFinite(e.value) ? e.value : null;
note.target = target;
// The weight he had stated when he set it (`goals.base`): the slice's own base for this goal -- the weight the
// gauge's target is reckoned from (measure-slice.mjs goalBase: the run's start, else the latest weight he gave by
// the goal's date) -- with its row's qualifier. None resolved, none shown: never one made up here.
note.base = cfg.base && s?.goal?.row === e.row ? goalBaseText(s.goal.base, m) : null;
order = [...order.filter((k) => k !== key), key];
const shown = order.slice(-cfg.max);
const depth = new Map(shown.map((k, i) => [k, shown.length - 1 - i]));
states.push({
at: r4(e.t),
top: key,
repeat: note.count > 1,
goalsSet: Array.isArray(s?.goals) ? s.goals.length : n,
notes: shown.map((k) => {
const x = notes.get(k);
return {
key: k, id: x.id, text: x.text, count: x.count, date: x.date, deadline: x.deadline,
deadlineDate: x.deadlineDate, days: x.days, target: x.target, base: x.base ?? null, rot: x.rot, dx: x.dx,
depth: depth.get(k), prev: k === key ? null : prevDepth.get(k) ?? null,
};
}),
});
prevDepth = depth;
}
return states;
}
// ---------------------------------------------------------------------------
// PEAK
// ---------------------------------------------------------------------------
const near = (a, b) => Math.abs(a - b) < 0.05;
/**
* The moving start's states: one per remembered weight it draws, `{ at,
* ticks: [{ value, count, approx, latest }], lo, hi, drift, told }`, and the
* scale's range over the whole cut (`range: [min, max]`) on each.
*/
export function peakStates(schedule, render) {
const m = measureOf(schedule);
const cfg = resolveMeasureExtra("peak", render);
if (!m || !cfg) return [];
const drift = Array.isArray(m.totals?.peakDrift) ? m.totals.peakDrift.filter(Number.isFinite) : [];
const counts = cfg.values === "drift" && drift.length > 0;
const steps = stepsOf(m).filter(({ e }) => e.kind === "remembered" && Number.isFinite(e.value) && (!counts || drift.some((v) => near(v, e.value))));
if (!steps.length) return [];
const all = steps.map(({ e }) => e.value);
let lo = Math.floor(Math.min(...all) - 3);
let hi = Math.ceil(Math.max(...all) + 3);
if (hi - lo < 12) {
const mid = (hi + lo) / 2;
lo = Math.floor(mid - 6);
hi = Math.ceil(mid + 6);
}
const ticks = new Map();
const states = [];
steps.forEach(({ e }, j) => {
const v = Math.round(e.value * 10) / 10;
const t = ticks.get(v) ?? { value: v, count: 0, approx: false };
t.count += 1;
if (e.qualifier === "≈" || String(e.display ?? "").startsWith("≈")) t.approx = true;
ticks.set(v, t);
const vals = [...ticks.keys()];
const min = Math.min(...vals);
const max = Math.max(...vals);
states.push({
at: r4(e.t),
row: e.row ?? null,
latest: v,
repeat: t.count > 1,
ticks: [...ticks.values()].sort((a, b) => a.value - b.value).map((x) => ({ ...x, latest: x.value === v })),
lo: min, hi: max, drift: r4(max - min), told: j + 1,
range: [lo, hi],
});
});
return states;
}
// ---------------------------------------------------------------------------
// PROMISE
// ---------------------------------------------------------------------------
/** After the last event, how long before the clock counts on to the render date (no finale). */
export const PROMISE_SETTLE = 4;
/** The count-up to the render date: a day a step, over at most this long. */
export const PROMISE_COUNT_UP = 1.2;
export { STAMP_NOTE };
/** The stamp's second line: the outcome's own note, else the clock's words ("by 26 Oct · no video"). */
export function stampNoteLine(outcome) {
if (typeof outcome?.note === "string" && outcome.note.trim()) return outcome.note.trim();
return `${outcome?.date ? `by ${shortDate(outcome.date)} · ` : ""}no video`;
}
/** The strip's words after the outcome's: a note's first clause (to its first · , ; — or " -- "), else "no video". */
export function stampNoteClause(outcome) {
const note = typeof outcome?.note === "string" ? outcome.note.trim() : "";
if (!note) return "no video";
return note.split(/\s+--\s+|\s*[·;—]\s*|,\s+/)[0].trim() || note;
}
/**
* The lint's warnings for the stamp notes (lint.mjs): a `stampNote` longer than the stamp's line holds -- it is one
* line, never wrapped, so it runs past the stamp's border and into the as-of beside it.
* @returns {string[]}
*/
export function stampNoteWarnings(manifest) {
const out = [];
for (const row of Array.isArray(manifest?.ledger) ? manifest.ledger : []) {
if (row?.population !== "promise_outcome" || typeof row.stampNote !== "string") continue;
const note = row.stampNote.trim();
if (note.length > STAMP_NOTE.fit) {
out.push(`ledger ${row.id}.stampNote "${note}" is ${note.length} characters: the promise clock's stamp holds about ${STAMP_NOTE.fit} on its second line (it is one line, never wrapped) -- it will run past the stamp; shorten it (umtool ledger
set ${row.id} --stampNote "…")`);
}
}
return out;
}
/** The promise outcomes the clock draws (CONTRACT addendum 2): kept stops the count; refunded and withdrawn do not. */
export const PROMISE_OUTCOMES = Object.freeze(["kept", "refunded", "withdrawn"]);
/**
* The promise clock's states: `{ at, rows: [row], asOf }`, one row (the latest
* promise): `{ row, what, said, days, to, kept, outcome: { kind, date } | null,
* claim: { speaker, date, paidOn } | null (the first claim with a `paidOn`, else
* the first), `to` the in-record date so far (the latest date of any event seen
* in cut order, never before `said`), word: { text, date, speaker, his } |
* null, fresh }` -- `to` the date the days are counted to, `claim` another
* party's (her) latest claim on it (CONTRACT addendum: "PAID 23 OCT BY
* @MadamSavvy"), `word` the latest words said about it -- his check, her
* claim, the outcome's -- `fresh` when they just came in (they flash). A state
* wherever any of that changes. From the finale's start (else PROMISE_SETTLE
* after the last event) the days count up to `measure.asOfRender`, a day a
* step -- unless it was kept: the count stops on the day it was.
*/
export function promiseStates(schedule, render) {
const m = measureOf(schedule);
const cfg = resolveMeasureExtra("promise", render);
if (!m || !cfg) return [];
const steps = stepsOf(m);
const first = steps.find(({ e }) => e.kind === "promise");
if (!first) return [];
const byRow = new Map([...m.events, ...(m.hidden ?? [])].filter((e) => e?.row).map((e) => [e.row, e]));
const total = Number(schedule.total) || 0;
const wordsOf = (e) => {
const w = cfg.checks === "quote" ? e.quote || e.label : e.label || e.quote;
return w ? String(w).trim() : null;
};
// The latest words on each promise, in cut order (his checks, her claims, the outcome's).
const lastWord = new Map();
const outcomeOf = (p) => {
const o = isObj(p.outcome) && PROMISE_OUTCOMES.includes(p.outcome.kind) ? p.outcome : null;
const note = typeof o?.note === "string" && o.note.trim() ? o.note.trim() : null;
return o ? { kind: o.kind, date: o.date ?? null, ...(note ? { note } : {}) } : p.kept === true ? { kind: "kept", date: null } : null;
};
const rowsAt = (s, freshRow) => (Array.isArray(s?.promises) ? s.promises : [])
.filter((p) => p && p.said)
.slice(-1)
.map((p) => {
const ev = byRow.get(p.row);
const outcome = outcomeOf(p);
const claims = Array.isArray(p.claims) ? p.claims.filter((c) => isObj(c)) : [];
// "PAID ": the first claim that says when she paid (`paidOn`), else the first claim.
const c = claims.find((x) => typeof x.paidOn === "string" && x.paidOn) ?? claims[0] ?? null;
// His checks named by the state (an older slice has no events for the words: the row's).
const checks = Array.isArray(p.checks) ? p.checks : [];
let word = lastWord.get(p.row) ?? null;
if (!word && checks.length) {
const ce = byRow.get(checks[checks.length - 1]);
const text = ce ? wordsOf(ce) : null;
if (text) word = { row: ce.row, text, date: ce.date ?? null, speaker: ce.speaker ?? null, his: !ce.speaker };
}
// Kept stops the count on the day it was kept.
const stop = outcome?.kind === "kept" && outcome.date ? outcome.date : null;
// AS OF: the in-record date of the playhead -- the latest date of ANY event
// seen so far in cut order (the cut is chronological; a running max, so it
// never goes back), never before the promise itself (rev 9, 6 Nov: "2 DAYS
// AS OF 25 OCT" lagged through c46, which is 26 Oct).
const latest = seen && seen > p.said ? seen : p.said;
const to = stop ?? latest;
return {
row: p.row,
what: cfg.label ?? ev?.display ?? p.what ?? "promise",
said: p.said,
days: Math.max(0, daysBetween(p.said, to) ?? 0),
to,
kept: outcome?.kind === "kept",
outcome,
claim: c ? { speaker: c.speaker ?? null, date: c.date ?? null, paidOn: c.paidOn ?? null } : null,
word: word ? { text: word.text, date: word.date, speaker: word.speaker, his: word.his, outcome: !!word.outcome } : null,
fresh: !!freshRow && word?.row === freshRow,
};
});
const out = [];
let lastSig = null;
let lastS = null;
// The in-record date so far: the running max of every event's date, in cut order.
let seen = null;
for (const { e, s } of steps) {
if (typeof e.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(e.date) && (!seen || e.date > seen)) seen = e.date;
if (e.t < first.e.t) continue;
let fresh = null;
if ((e.kind === "promiseCheck" || e.kind === "promiseClaim" || e.kind === "promiseOutcome") && e.promise) {
const text = wordsOf(e);
if (text) {
lastWord.set(e.promise, { row: e.row, text, date: e.date ?? null, speaker: e.speaker ?? null, his: !e.speaker || e.kind === "promiseCheck", outcome: e.kind === "promiseOutcome" });
fresh = e.row;
}
}
const rows = rowsAt(s, fresh);
lastS = s;
if (!rows.length) continue;
const sig = JSON.stringify(rows);
if (sig === lastSig) continue;
lastSig = sig;
const at = r4(e.t);
if (out.length && Math.abs(out[out.length - 1].at - at) < 1e-6) out.pop();
out.push({ at, rows, asOf: false });
}
if (!out.length) return [];
// On to the render date: from the finale, else a beat after the last event.
const fin = finaleOf(schedule);
const lastAt = out[out.length - 1].at;
const from = fin ? Math.max(lastAt + 0.5, fin.from) : lastAt + PROMISE_SETTLE;
const asOf = m.asOfRender;
if (asOf && from < total - 0.2) {
const base = rowsAt(lastS, null);
const target = base.map((r) => (r.kept && r.outcome?.date ? r.days : Math.max(0, daysBetween(r.said, asOf) ?? 0)));
const toOf = (r) => (r.kept && r.outcome?.date ? r.to : asOf);
const steps2 = Math.max(0, ...target.map((d, i) => d - base[i].days));
if (steps2 > 0) {
const n = Math.min(steps2, 30);
const dt = Math.min(PROMISE_COUNT_UP / n, 0.25);
for (let k = 1; k <= n; k += 1) {
const rows = base.map((r, i) => ({ ...r, days: Math.round(r.days + ((target[i] - r.days) * k) / n), to: toOf(r), fresh: false }));
out.push({ at: r4(Math.min(total - 0.05, from + (k - 1) * dt)), rows, asOf: k === n });
}
} else out.push({ at: r4(from), rows: base.map((r) => ({ ...r, to: toOf(r), fresh: false })), asOf: true });
}
return out;
}
// ---------------------------------------------------------------------------
// DIET
// ---------------------------------------------------------------------------
/**
* The diet badge's states: `{ at, diet: { regime, label, detail, n, color } |
* null, slam }` -- one per change of the state's diet (regime, number or
* words); `slam` when the regime or the number changed (a new stamp), not
* for words alone. The states before any diet are left out; a null after
* one is "No diet", faded in.
*/
export function dietStates(schedule, render) {
const m = measureOf(schedule);
const cfg = resolveMeasureExtra("diet", render);
if (!m || !cfg) return [];
const out = [];
let prev;
let any = false;
for (const { e, s } of stepsOf(m)) {
const d = isObj(s?.diet) ? s.diet : null;
if (!d && !any) continue;
const key = d ? `${d.regime}|${d.n}|${d.display}` : "none";
if (key === prev?.key) continue;
any = true;
const regime = d ? String(d.regime ?? "other") : "off";
const label = cfg.labels[regime] ?? regime;
const display = d ? String(d.display ?? "").trim() : "";
const generic = !display || display.toLowerCase() === label.toLowerCase() || display.toLowerCase() === String(cfg.labels.other ?? "").toLowerCase() || display.toLowerCase() === regime;
// `since`: the in-record day he named it (the state's, the producer's), else the event's date.
const since = (d ? d.since : null) ?? e.date ?? null;
const diet = d ? { regime, label, detail: generic ? "" : display, n: Number.isFinite(d.n) ? d.n : null, color: cfg.colors[regime] ?? cfg.colors.other, since } : null;
const slam = !!d && (!prev?.diet || prev.diet.regime !== regime || prev.diet.n !== diet.n);
const at = r4(e.t);
if (out.length && Math.abs(out[out.length - 1].at - at) < 1e-6) out.pop();
out.push({ at, diet, slam, key, since });
prev = { key, diet };
}
// THE HISTORY (the tags form, `diet.form: "tags"`): each state's last `tags` diets, newest first -- a new
// diet (a slam) or a "No diet" pushes a tag in at the front and the oldest past `tags` off; a change of the
// words alone replaces the newest tag in place. Each tag `{ id, diet, since }`, `id` stable across states.
const n = cfg.tags ?? 3;
let shown = [];
let id = 0;
return out.map(({ key: _k, since, ...st }, j) => {
const wordsOnly = j > 0 && !!st.diet && !st.slam && !!out[j - 1].diet;
// New words for the same diet keep the day he switched to it: the tag dates the SWITCH, not the words.
const kept = wordsOnly && shown[0] ? shown[0].since : since;
const diet = wordsOnly && st.diet ? { ...st.diet, since: kept } : st.diet;
const tag = { id: id++, diet, since: kept };
shown = wordsOnly ? [tag, ...shown.slice(1)] : [tag, ...shown].slice(0, n);
return { ...st, diet, tags: shown, replaced: wordsOnly };
});
}
/**
* The diet's running day count (`diet.days`, on its front tag): `{ at, days,
* run }` wherever it changes -- the days on the current diet (dietRuns: its
* `since`, a new regime or diet number a new run) to the in-record date at the
* playhead (the running latest date of every event so far), the same number
* the streak chain's "Day N" reads; `run` null while no diet is on.
*/
export function dietDays(schedule, render) {
const m = measureOf(schedule);
const cfg = resolveMeasureExtra("diet", render);
if (!m || !cfg) return [];
const runs = dietRuns(m, cfg);
const out = [];
let date = null;
for (const { e } of stepsOf(m)) {
if (e.date) date = isoMax(date, e.date);
const t = e.t;
const run = runs.findIndex((r) => r.startT <= t + 1e-6 && (r.endT === null || r.endT > t + 1e-6));
if (run < 0 && !out.length) continue;
const days = run >= 0 ? runDays(runs[run], isoMax(runs[run].start, date)) : null;
const last = out[out.length - 1];
if (last && last.days === days && last.run === (run >= 0 ? run : null)) continue;
if (last && Math.abs(last.at - t) < 1e-6) out.pop();
out.push({ at: r4(t), days, run: run >= 0 ? run : null });
}
return out;
}
// ---------------------------------------------------------------------------
// STREAK: a chain per run, cracked when it ends.
// ---------------------------------------------------------------------------
//
// SOURCE-AGNOSTIC. Each source is an ADAPTER from the measure slice to RUNS --
// `{ key, name, color, start, startT, end, endT, ended, detail }`: `start` the
// run's first in-record date and `startT` the cut second it comes on screen,
// `end`/`endT` the same for its end (null while it is open), `ended` the word
// for how ("off", "new", "lapse") -- and the chain draws runs, nothing else.
// A run's length is its days from `start` to `end` (an open run's to the
// in-record date at the playhead).
const isoMax = (a, b) => (!a ? b : !b ? a : a > b ? a : b);
/**
* DIET runs: a run starts when the state's diet turns on (or changes regime
* or diet number: a new diet) and ends at the next change -- "new" -- or when
* the diet turns off -- "off" (the state's diet, with the producer's
* off-scope rule applied).
*/
export function dietRuns(m, cfg) {
const runs = [];
let open = null;
for (const { e, s } of stepsOf(m)) {
const d = isObj(s?.diet) ? s.diet : null;
const key = d ? `${d.regime}|${d.n}` : null;
if (key === (open?.key ?? null)) continue;
if (open) {
open.end = isoMax(open.start, e.date ?? open.start);
open.endT = r4(e.t);
open.ended = d ? "new" : "off";
open = null;
}
if (d) {
const regime = String(d.regime ?? "other");
open = {
key, name: cfg.labels[regime] ?? regime, color: cfg.colors[regime] ?? cfg.colors.other,
// The state's `since` (the producer's: the day the regime opened), else the event's date.
start: d.since ?? e.date ?? null, startT: r4(e.t), end: null, endT: null, ended: null,
detail: Number.isFinite(d.n) ? `diet #${d.n}` : "",
};
runs.push(open);
}
}
return runs;
}
/**
* LOST runs (the odometer's runs, `state.lost.runs`): a run starts when the
* state first names it -- at its own `start` date -- and ends when the next
* one starts ("new"), its chain reaching the last day he claimed a loss in it
* (its last `lost` event's date) -- the gap to the next is the time between.
*/
export function lostRunsRuns(m, cfg, pal = {}) {
const runs = [];
const seen = new Set();
let open = null;
const lastClaim = new Map();
for (const { e, s } of stepsOf(m)) {
if (e.kind === "lost" && e.run !== null && e.run !== undefined && e.date) lastClaim.set(`run${e.run}`, isoMax(lastClaim.get(`run${e.run}`), e.date));
for (const r of Array.isArray(s?.lost?.runs) ? s.lost.runs : []) {
const key = `run${r.run}`;
if (seen.has(key)) {
if (open?.key === key && Number.isFinite(r.peak)) open.detail = `down ${weightText(r.peak)}`;
continue;
}
seen.add(key);
const start = r.start ?? e.date ?? null;
if (open) {
const claimed = lastClaim.get(open.key);
const nextStart = start ?? open.start;
open.end = isoMax(open.start, claimed && claimed < nextStart ? claimed : nextStart);
open.endT = r4(e.t);
open.ended = "new";
}
open = {
key, name: `Run ${runs.length + 1}`, color: cfg.color ?? pal.accent ?? "#22AB83", zeroWord: "one claim",
start, startT: r4(e.t), end: null, endT: null, ended: null,
detail: Number.isFinite(r.peak) ? `down ${weightText(r.peak)}` : "",
};
runs.push(open);
}
}
return runs;
}
/**
* PLEDGES (the sobriety video's): a `pledge` event starts a run, a `lapse`
* snaps it ("after 73 days"). TODO(sobriety video): the measure contract has
* no drinking scope yet -- these event kinds are this adapter's assumption
* until the ledger writes them; the drawing needs nothing more.
*/
export function pledgeRuns(m, cfg, pal = {}) {
const runs = [];
let open = null;
for (const { e } of stepsOf(m)) {
if (e.kind === "pledge" && !open) {
open = {
key: e.row ?? `p${runs.length}`, name: e.display || cfg.labels.dry || "Dry", color: cfg.color ?? pal.accent ?? "#3FA9A0",
start: e.date ?? null, startT: r4(e.t), end: null, endT: null, ended: null, detail: "",
};
runs.push(open);
} else if (e.kind === "lapse" && open) {
open.end = isoMax(open.start, e.date ?? open.start);
open.endT = r4(e.t);
open.ended = "lapse";
open = null;
}
}
return runs;
}
const ADAPTERS = { diet: dietRuns, lostRuns: lostRunsRuns, pledges: pledgeRuns };
/** The source's runs, through its adapter. */
export function streakRuns(schedule, render) {
const m = measureOf(schedule);
const cfg = resolveMeasureExtra("streak", render);
if (!m || !cfg) return [];
return ADAPTERS[cfg.source](m, cfg, render?.palette ?? {});
}
/** A run's days from its start to `to`. */
export const runDays = (run, to) => Math.max(0, daysBetween(run.start, to) ?? 0);
/** "41 days" | "1 day". */
export const daysText = (n) => `${n} day${n === 1 ? "" : "s"}`;
/**
* The streak chain's states: one wherever the live chain or its count moves
* -- a run starting, a run ending, the in-record date moving on under an
* open run -- each `{ at, date, live: { i, days } | null, cracked: i | null }`
* (`cracked` the run that just ended, at its own state). With the runs, the
* date span the axis covers (`span: [from, to]`) and each run's final days.
*/
export function streakStates(schedule, render) {
const m = measureOf(schedule);
const runs = streakRuns(schedule, render);
if (!m || !runs.length) return { runs: [], states: [], span: null };
const states = [];
let date = null;
const push = (at, st) => {
const sig = JSON.stringify([st.live, st.cracked]);
const last = states[states.length - 1];
if (last && Math.abs(last.at - at) < 1e-6) states.pop();
else if (last && JSON.stringify([last.live, last.cracked]) === sig && st.cracked === null) return;
states.push({ at: r4(at), date: st.date, live: st.live, cracked: st.cracked });
};
const firstT = runs[0].startT;
for (const { e } of stepsOf(m)) {
if (e.date) date = isoMax(date, e.date);
if (e.t < firstT) continue;
const t = e.t;
const ended = runs.findIndex((r) => r.endT !== null && Math.abs(r.endT - t) < 1e-6);
const li = runs.findIndex((r) => r.startT <= t + 1e-6 && (r.endT === null || r.endT > t + 1e-6));
const live = li >= 0 ? { i: li, days: runDays(runs[li], isoMax(runs[li].start, date)) } : null;
push(t, { date, live, cracked: ended >= 0 ? ended : null });
}
const finalDate = date;
const ends = runs.map((r) => (r.end ?? isoMax(r.start, finalDate)));
const from = runs.map((r) => r.start).filter(Boolean).sort()[0] ?? finalDate;
const to = [m.asOfRender, ...ends].filter(Boolean).sort().at(-1);
return { runs: runs.map((r, i) => ({ ...r, days: runDays(r, ends[i]) })), states, span: [from, to] };
}
// ---------------------------------------------------------------------------
// GEOMETRY
// ---------------------------------------------------------------------------
/** Each module's box in design pixels (1920 wide), before `scale`. */
export const MEASURE_BOXES = Object.freeze({
goals: Object.freeze({ width: 400, height: 330 }),
peak: Object.freeze({ width: 280, height: 470 }),
promise: Object.freeze({ width: 640, height: 260 }),
diet: Object.freeze({ width: 440, height: 200 }),
streak: Object.freeze({ width: 620, height: 150 }),
// The promise clock in the instruments' column (`promise.slot`): the trail's slot, its compact form.
promiseColumn: Object.freeze({ width: 600, height: 138 }),
});
/** One diet tag (`diet.form: "tags"`), design px: its width, the air between two, and the row's height. */
export const DIET_TAG = Object.freeze({ width: 220, gap: 12, height: 116 });
/**
* Where tag `i` (0 the newest) stands from the row's left, design px: side by
* side `gap` apart, or -- `overlap` above 0 -- fanned, each older one shifted
* right by the share of a tag that shows (`1 - overlap`).
*/
export const dietTagStep = (overlap = 0, days = false) =>
(overlap > 0 ? Math.round(dietTagWidth(days) * (1 - overlap)) : dietTagWidth(days) + DIET_TAG.gap);
/** The diet's row (or fan) of `n` tags, design px. */
export const dietTagsBox = (n, overlap = 0, days = false) => ({
width: dietTagWidth(days) + (n - 1) * dietTagStep(overlap, days),
height: DIET_TAG.height,
});
/**
* The goal stack ON THE SHELF (`goals.position: "shelf"`), design px: the
* count of goals set in a column at the left, then the notes fanned sideways
* like the diet's tags -- the newest in front -- each older one showing at
* least `back` (its goal's words), more when the shelf has width to give
* (shelfLayout). `natural` is that tightest fan, `widest` the notes side by side.
*/
export const GOALS_SHELF = Object.freeze({ count: 84, gap: 10, card: 250, back: 110, height: 116, step: 12 });
export const goalsShelfWidth = (max, { widest = false } = {}) =>
GOALS_SHELF.count + GOALS_SHELF.gap + GOALS_SHELF.card + (max - 1) * (widest ? GOALS_SHELF.card + GOALS_SHELF.step : GOALS_SHELF.back);
/** A module's design box: the promise clock's compact one in the column, the diet's row of tags, the goals on the shelf. */
export function measureBox(id, render) {
if (id === "promise" && resolveMeasureExtra("promise", render)?.slot === "column") return MEASURE_BOXES.promiseColumn;
if (id === "diet") {
const cfg = resolveMeasureExtra("diet", render);
if (cfg?.form === "tags") return dietTagsBox(cfg.tags ?? 3, cfg.overlap ?? 0, cfg.days === true);
}
if (id === "goals") {
const cfg = resolveMeasureExtra("goals", render);
if (cfg?.position === SHELF_POSITION) return { width: goalsShelfWidth(cfg.max ?? 4), height: GOALS_SHELF.height };
}
return MEASURE_BOXES[id];
}
/** The note's slot on the shelf is only drawn this wide or wider, design px. */
export const SHELF_NOTE_MIN = 160;
/**
* The SHELF's occupants laid out (`deck.shelf`, deck.mjs deckGeometry's
* `shelf`): `{ rect, slots: { [item]: {x, y, width, height} } }`, or null with
* no shelf. Left to right in `items` order, `gap` apart: each measure extra on
* it at its own design box scaled to the shelf's height (all of them a size
* down together, centred in the height, when they would not fit its width);
* the goals' fan widens into what width is left (up to its notes side by
* side), then the note takes what is still left at its place (none under
* SHELF_NOTE_MIN).
* An item that is off takes no slot.
*/
export function shelfLayout(render) {
const shelf = resolveShelf(render);
const g = deckGeometry(render);
if (!shelf || !g.shelf) return null;
const rect = g.shelf;
const k = g.W / 1920;
const gap = Math.round(shelf.gap * k);
const items = shelf.items.filter((i) => i === "note" || resolveMeasureExtra(i, render)?.position === SHELF_POSITION);
const boxes = items.map((i) => (i === "note" ? null : measureBox(i, render)));
const fixed = boxes.reduce((a, b) => a + (b ? (b.width * rect.height) / b.height : 0), 0);
const gaps = gap * Math.max(0, items.length - 1);
const fit = fixed > 0 ? Math.min(1, (rect.width - gaps) / fixed) : 1;
const h = Math.max(2, evenDown(rect.height * fit));
const widths = boxes.map((b) => (b ? evenDown((b.width * h) / b.height) : 0));
let rest = rect.width - widths.reduce((a, b) => a + b, 0) - gaps;
// The goals' fan takes the width left over, up to its notes side by side: its older notes show more of
// themselves rather than the shelf ending in a gap. (Then the note, in what is still left.)
const gi = items.indexOf("goals");
if (gi >= 0 && rest > 0) {
const cfg = resolveMeasureExtra("goals", render);
const widest = evenDown((goalsShelfWidth(cfg.max ?? 4, { widest: true }) * h) / GOALS_SHELF.height);
const more = Math.max(0, Math.min(rest, widest - widths[gi]));
widths[gi] += evenDown(more);
rest -= evenDown(more);
}
const noteW = items.includes("note") && rest >= SHELF_NOTE_MIN * k ? evenDown(rest) : 0;
const slots = {};
let x = rect.x;
const y = rect.y + Math.round((rect.height - h) / 2);
items.forEach((it, i) => {
const w = it === "note" ? noteW : widths[i];
if (!w) return;
slots[it] = it === "note" ? { x, y: rect.y, width: w, height: evenDown(rect.height) } : { x, y, width: w, height: h };
x += w + gap;
});
return { rect, slots };
}
/**
* The promise clock's slot in the instruments' column: the trail's (it yields
* while the clock is up), else the column's foot as tall as the trail would be.
*/
export function promiseColumnRect(render) {
const g = instrumentsGeometry(render);
if (g.trail) return { ...g.trail };
const k = (render?.width ?? 1920) / 1920;
const h = Math.round(138 * k);
return { x: g.column.x, y: g.column.y + g.column.height - h, width: g.column.width, height: h };
}
/**
* The strip a promise clock in the FOOTAGE box draws while a post item is up:
* one line in the post box's top margin, over the card (the post's pad, as
* postLayout lays it: 36 design px of the box's height) -- all of it but a
* pixel above and a pixel and a gap below, so its words can be read (rev 9:
* 22 px at 1080, not 16; promiseStripType).
*/
export function promiseStripRect(render, { feed = false } = {}) {
const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage;
const pad = Math.round(36 * (f.height / 1080));
return { x: f.x + pad, y: f.y + 1, width: f.width - 2 * pad, height: Math.max(18, pad - 3) };
}
/** The strip's words at 1080: no smaller than this when the margin holds them. */
export const PROMISE_STRIP_PX = 22;
/**
* The strip's type: its size, and whether its words go on two lines. One line
* at PROMISE_STRIP_PX (scaled with the frame) when the margin is tall enough
* and the longest line (`chars`, an uppercase condensed-bold line at about 0.64
* em a character, its spacing in) fits its width; two lines at that size when
* only the width is short and two fit the height; else the largest one line
* that fits both. Lines are set solid (line-height 1).
*
* @returns {{ size: number, lines: 1 | 2 }}
*/
export function promiseStripType(rect, render, chars) {
const k = (render?.height ?? 1080) / 1080;
const want = PROMISE_STRIP_PX * k;
const room = rect.height - 2 * k; // a pixel of air above and below the glyphs
const em = 0.64;
const fitsWide = (size) => chars * em * size <= rect.width;
const r = (v) => Math.floor(v * 100) / 100;
if (room >= want - 1e-6 && fitsWide(want)) return { size: r(Math.max(want, Math.min(room, rect.height * 0.62))), lines: 1 };
if (room >= 2 * want - 1e-6 && fitsWide(want / 2)) return { size: r(want), lines: 2 };
return { size: r(Math.min(room, rect.width / Math.max(1, chars * em))), lines: 1 };
}
/**
* A module's region in the frame: its box (MEASURE_BOXES × `scale`, scaled
* with the frame) at its anchor in the footage box (the feed's for a feed
* cut), 24 px in -- or at `x`/`y` (design pixels) when set. Never off the frame.
*
* @param {"goals" | "peak" | "promise" | "diet" | "streak"} id
* @returns {{ x: number, y: number, width: number, height: number }}
*/
export function measureExtraGeometry(id, render, { feed = false } = {}) {
const cfg = resolveMeasureExtra(id, render) ?? resolveMeasureExtra(id, { chrome: { deck: {} } });
if (id === "promise" && cfg.slot === "column") return promiseColumnRect(render);
// On the shelf: its slot there (shelfLayout).
if (cfg.position === SHELF_POSITION) {
const slot = shelfLayout(render)?.slots[id];
if (slot) return { ...slot };
}
const g = deckGeometry(render);
const f = overlayBox(render, { feed });
// Over the footage at its design size scaled with the frame (pictureK: the stacked vertical deck's own).
const pk = pictureK(render, g.W);
const k = pk * (cfg.scale ?? 1);
const box = measureBox(id, render);
const width = Math.min(even(box.width * k), even(g.W));
const height = Math.min(even(box.height * k), even(g.H));
let x;
let y;
if (Number.isFinite(cfg.x) && Number.isFinite(cfg.y)) {
x = cfg.x * (g.W / 1920);
y = cfg.y * (g.W / 1920);
} else {
const inset = Math.round(24 * pk);
const [v, h] = cfg.position.split("-");
x = h === "left" ? f.x + inset : h === "right" ? f.x + f.width - inset - width : f.x + (f.width - width) / 2;
y = v === "top" ? f.y + inset : f.y + f.height - inset - height;
}
x = Math.max(0, Math.min(g.W - width, Math.round(x)));
y = Math.max(0, Math.min(g.H - height, Math.round(y)));
return { x, y, width, height };
}
// ---------------------------------------------------------------------------
// MOVING CLEAR: post items' cards and chapter bands.
// ---------------------------------------------------------------------------
//
// While a post item's card (the deck schedule's `covers`, deck.mjs postCovers:
// the card, slot and strip as postLayout lays them) or a chapter band
// (chrome-story.mjs chapterCover, over chapterWindows) is up where a module
// stands, the module moves to a slot clear of it -- the anchors of the footage
// box in its preference order, a size down if it must (MEASURE_DODGE_SCALES),
// never onto another measure module that is up then -- or hides when nothing
// fits (`onPosts` / `onChapters`: "dodge" | "hide" | "show"). One pure answer
// for all five, so two modules never dodge into one slot; each module's page
// and region read their own part of it.
/** The sizes a dodging module may take, largest first; below the last it hides. */
export const MEASURE_DODGE_SCALES = Object.freeze([1, 0.85, 0.7, 0.6, 0.5]);
/** How long a module takes to move clear, and back. */
export const MEASURE_DODGE_MOVE = 0.3;
/** The order the five are placed in (the first takes a free slot first): the promise clock, then the rest. */
const DODGE_ORDER = Object.freeze(["promise", "goals", "peak", "diet", "streak"]);
const intersects = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
const within = (a, b) => a.x >= b.x && a.y >= b.y && a.x + a.width <= b.x + b.width && a.y + a.height <= b.y + b.height;
const overlapsSpan = (spans, from, to) => spans.some((sp) => sp.in < to - 1e-6 && sp.out > from + 1e-6);
/** A module's box at an anchor of the footage box and a size (its own `scale` times `size`). */
export function anchorRect(id, render, anchor, size = 1, { feed = false } = {}) {
const cfg = resolveMeasureExtra(id, render) ?? resolveMeasureExtra(id, { chrome: { deck: {} } });
const g = deckGeometry(render);
const f = overlayBox(render, { feed });
const pk = pictureK(render, g.W);
const k = pk * (cfg.scale ?? 1) * size;
const box = measureBox(id, render);
const width = Math.min(even(box.width * k), even(f.width));
const height = Math.min(even(box.height * k), even(f.height));
const inset = Math.round(24 * pk);
const [v, h] = anchor.split("-");
const x = h === "left" ? f.x + inset : h === "right" ? f.x + f.width - inset - width : f.x + (f.width - width) / 2;
const y = v === "top" ? f.y + inset : f.y + f.height - inset - height;
return { x: Math.round(x), y: Math.round(y), width, height };
}
/** The anchors a module tries when it moves: its own first, then the same edge, then the rest. */
function anchorsFor(position) {
const [v] = position.split("-");
const same = MEASURE_POSITIONS.filter((p) => p !== position && p.startsWith(v));
const other = MEASURE_POSITIONS.filter((p) => p !== position && !p.startsWith(v));
return [position, ...same, ...other];
}
/** When a module is up: its states' times through upSpans. */
function upOf(id, schedule, render) {
const cfg = resolveMeasureExtra(id, render);
if (!cfg) return [];
const states = id === "goals" ? goalStates(schedule, render)
: id === "peak" ? peakStates(schedule, render)
: id === "promise" ? promiseStates(schedule, render)
: id === "diet" ? dietStates(schedule, render)
: streakStates(schedule, render).states;
return upSpans(states.map((s) => s.at), cfg, schedule);
}
/**
* What covers the footage when: `[{ kind: "post" | "chapter", from, to, rects }]`,
* the post items' cards (the schedule's `covers`) and the chapter bands.
*/
export function measureCovers(schedule, render) {
const feed = schedule?.layout === "feed";
const out = [];
for (const c of Array.isArray(schedule?.covers) ? schedule.covers : []) {
if (Number.isFinite(c?.from) && Number.isFinite(c?.to) && Array.isArray(c.rects) && c.rects.length) out.push({ kind: "post", from: c.from, to: c.to, rects: c.rects });
}
const chapters = render?.chrome?.chapter ? chapterWindows(schedule, render) : [];
if (chapters.length) {
const band = chapterCover(render, { feed });
// Where each bumper stands: its band, or beside a post card its side margin (chrome-story.mjs chapterPlacement).
for (const w of chapters) out.push({ kind: "chapter", from: w.from, to: w.to, rects: [w.place?.mode === "side" ? w.place.rect : band] });
}
return out.sort((a, b) => a.from - b.from);
}
/** `spans` (each `{ from, to, ... }`) with [from, to) cut out of them: a span across it is split in two. */
function carveSpans(spans, from, to) {
const out = [];
for (const sp of spans) {
if (sp.to <= from || sp.from >= to) { out.push(sp); continue; }
if (sp.from < from) out.push({ ...sp, to: from });
if (sp.to > to) out.push({ ...sp, from: to });
}
return out;
}
/**
* Every measure module's placement over the cut: `{ [id]: { home, region,
* moves: [{ from, to, rect | null, size }] } }` -- `home` where it stands,
* each move a span it stands elsewhere (`rect` at `size`) or is hidden
* (`rect` null), `region` the box its frames are drawn in (home and every
* slot it moves to). A module with nothing to move clear of: its home alone.
*/
export function measurePlacements(schedule, render, { finaleSlot = null } = {}) {
const feed = schedule?.layout === "feed";
const covers = schedule ? measureCovers(schedule, render) : [];
// A module on the shelf stands in its own slot there, clear of the footage: nothing covers it, so it never
// dodges and nothing dodges around it (only an entry's hideModules hides it).
const shelved = (id) => resolveMeasureExtra(id, render)?.position === SHELF_POSITION;
const out = {};
for (const id of MEASURE_EXTRAS) {
const home = measureExtraGeometry(id, render, { feed });
out[id] = { home, region: home, moves: [], up: covers.length && schedule && resolveMeasureExtra(id, render) ? upOf(id, schedule, render) : [] };
}
// THE PROMISE CLOCK stays on screen through the post items (rev 9, 6 Nov): in
// the instruments' column it stands in the trail's slot and nothing in the
// footage moves it; in the footage box, while a post item is up, it gives way
// to a one-line strip in the post's top margin (`strips`, promiseStripRect).
const pcfg = resolveMeasureExtra("promise", render);
const inColumn = pcfg?.slot === "column";
out.promise.strips = [];
if (pcfg && !inColumn && schedule) {
const up = out.promise.up.length ? out.promise.up : upOf("promise", schedule, render);
for (const c of covers) {
if (c.kind !== "post" || pcfg.onPosts === "show" || !overlapsSpan(up, c.from, c.to)) continue;
out.promise.moves.push({ from: c.from, to: c.to, rect: null, size: 1 });
if (pcfg.onPosts === "dodge") out.promise.strips.push({ from: c.from, to: c.to });
}
}
// Two extras whose homes overlap (the clip box is smaller beside the
// instruments' column) while both are up: the later in DODGE_ORDER moves
// clear of the earlier, as of a cover of its own.
if (schedule) {
for (const id of MEASURE_EXTRAS) if (!out[id].up.length && resolveMeasureExtra(id, render)) out[id].up = upOf(id, schedule, render);
DODGE_ORDER.forEach((a, i) => {
for (const b of DODGE_ORDER.slice(i + 1)) {
if (!resolveMeasureExtra(a, render) || !resolveMeasureExtra(b, render) || shelved(a) || shelved(b) || !intersects(out[a].home, out[b].home)) continue;
if ((a === "promise" || b === "promise") && inColumn) continue;
for (const sa of out[a].up) for (const sb of out[b].up) {
const from = Math.max(sa.in, sb.in);
const to = Math.min(sa.out, sb.out);
if (to - from > 1e-3) covers.push({ kind: "module", only: b, from, to, rects: [out[a].home] });
}
}
});
covers.sort((x, y) => x.from - y.from);
}
for (const c of covers) {
const hit = (r) => c.rects.some((b) => intersects(r, b));
// (The promise clock is not moved by a post card here: in the column nothing in the footage meets it, and in
// the footage box it becomes the strip above.)
const skip = (id) => shelved(id) || (id === "promise" && (inColumn || c.kind === "post"));
const active = DODGE_ORDER.filter((id) => !skip(id) && resolveMeasureExtra(id, render) && overlapsSpan(out[id].up, c.from, c.to) && (!c.only || c.only === id));
// The modules that stay where they are take their homes first.
const taken = [];
const toMove = [];
for (const id of active) {
const cfg = resolveMeasureExtra(id, render);
const mode = c.kind === "post" ? cfg.onPosts : c.kind === "chapter" ? cfg.onChapters : "dodge";
if (mode === "show" || !hit(out[id].home)) taken.push(out[id].home);
else toMove.push({ id, cfg, mode });
}
// Every other extra up in the span keeps its place: no slot onto it.
for (const id of DODGE_ORDER) {
if (active.includes(id) || shelved(id) || (id === "promise" && inColumn) || !resolveMeasureExtra(id, render) || !overlapsSpan(out[id].up, c.from, c.to)) continue;
taken.push(out[id].home);
}
const footage = feed ? feedGeometry(render).footage : deckGeometry(render).footage;
for (const { id, cfg, mode } of toMove) {
let move = null;
if (mode === "dodge") {
const pinned = Number.isFinite(cfg.x) && Number.isFinite(cfg.y);
// Never into an anchor the module avoids (`avoid`, default the top-left: the streams' face cam).
const avoid = Array.isArray(cfg.avoid) ? cfg.avoid : [];
const anchors = anchorsFor(pinned ? "top-left" : cfg.position).filter((a) => !avoid.includes(a) || a === cfg.position);
search: for (const size of MEASURE_DODGE_SCALES) {
for (const a of anchors) {
const r = anchorRect(id, render, a, size, { feed });
if (!within(r, footage) || hit(r) || taken.some((t) => intersects(t, r))) continue;
move = { from: c.from, to: c.to, rect: r, size };
break search;
}
}
}
if (!move) move = { from: c.from, to: c.to, rect: null, size: 1 };
else taken.push(move.rect);
out[id].moves.push(move);
}
}
// THE FINALE: the promise clock waits out the dial's finale and takes its place at the handoff
// (`finaleSlot`: chrome-measure-extras.mjs promiseFinaleSlot -- the finale's lower column, clear of the rail);
// in the column with no such slot it is hidden over the finale (the column is under the finale's page).
const fin = schedule?.finale && Number.isFinite(schedule.finale.from) ? schedule.finale : null;
if (pcfg && fin) {
if (finaleSlot) {
out.promise.moves.push({ from: fin.from, to: finaleSlot.at, rect: null, size: 1 });
out.promise.moves.push({ from: finaleSlot.at, to: Number(schedule.total) || fin.to, rect: finaleSlot.rect, size: finaleSlot.size });
} else if (inColumn) out.promise.moves.push({ from: fin.from, to: Number(schedule.total) || fin.to, rect: null, size: 1 });
}
// THE STACKED VERTICAL DECK (vertical-deck.mjs): over a post item (its card takes the picture's room) and a
// twocrop clip (its strip carries the numbers) every extra stands down, as an entry's hideModules hides it.
if (stackedOn(render)) {
for (const sd of stackedStandDowns(schedule)) {
for (const id of MEASURE_EXTRAS) {
if (!resolveMeasureExtra(id, render)) continue;
out[id].moves = carveSpans(out[id].moves, sd.from, sd.to);
out[id].moves.push({ from: sd.from, to: sd.to, rect: null, size: 1 });
if (id === "promise") out.promise.strips = carveSpans(out.promise.strips, sd.from, sd.to);
}
}
}
// An entry that hides modules over its span (`hideModules`, deck.mjs entryHides -- text in the footage no
// dodge can know of, rev 9: the refund email in v02): each named module hidden there with its own fade, whatever
// it would otherwise have done in that span.
for (const h of Array.isArray(schedule?.hides) ? schedule.hides : []) {
if (!(Number.isFinite(h?.from) && Number.isFinite(h?.to) && h.to > h.from) || !Array.isArray(h.modules)) continue;
for (const id of h.modules) {
if (!out[id] || !resolveMeasureExtra(id, render)) continue;
out[id].moves = carveSpans(out[id].moves, h.from, h.to);
out[id].moves.push({ from: h.from, to: h.to, rect: null, size: 1 });
if (id === "promise") out.promise.strips = carveSpans(out.promise.strips, h.from, h.to);
}
}
for (const id of MEASURE_EXTRAS) {
const p = out[id];
// Two moves that meet, to the same place: one.
const merged = [];
for (const m of p.moves.sort((a, b) => a.from - b.from)) {
const last = merged[merged.length - 1];
const same = last && JSON.stringify(last.rect) === JSON.stringify(m.rect) && last.size === m.size;
if (same && m.from - last.to < MEASURE_DODGE_MOVE * 2 + 0.05) last.to = Math.max(last.to, m.to);
else merged.push({ ...m });
}
p.moves = merged;
const rects = [p.home, ...merged.map((m) => m.rect).filter(Boolean), ...(p.strips?.length ? [promiseStripRect(render, { feed })] : [])];
const x0 = Math.min(...rects.map((r) => r.x));
const y0 = Math.min(...rects.map((r) => r.y));
const x1 = Math.max(...rects.map((r) => r.x + r.width));
const y1 = Math.max(...rects.map((r) => r.y + r.height));
p.region = { x: x0, y: y0, width: even(x1 - x0), height: even(y1 - y0) };
delete p.up;
}
return out;
}