// THE MEASURE SLICE (weight video rev 9): one object every measure module // draws from -- the dial, the odometer, the trail, the goals, the peak, the // promise clock, the diet badge. Written into a deck cut's schedule.json as // `doc.measure` by the build when the manifest carries a measure ledger // (`ledgerSchema.kind: "measure"`) and `render.chrome.deck.measure` is set; // `scheduleSlices(doc).measure` hands it to each module's page whole. // // Pure: no I/O. The build reads each clip's words (measure-words.mjs) and the // source second each segment starts at, and passes them in. // // events every ledger row in scope the CUT SHOWS -- pinned to an entry in // the cut, by the row's `entryId` or the entry's ledger pin // (`claim: ""`) -- in cut order, each at the cut second // it lands: the spoken number's word time when the clip's words // have it, else the entry's quoteStart, else the segment's start. // hidden the rows in scope no entry of the cut shows (t: null). // state one entry per event, the state AFTER it, sorted by t; state[0] // (t: 0) is the state before any event. Built from the EVENTS // only: a hidden row never moves a number on screen. // totals over events + hidden: the whole record in scope. // // The odometer rule (ruled 5 Nov 2026, "go by his words"): see lossRuns. import { chronological, dateKey, daysBetween } from "./ledger-shared.mjs"; import { PROMISE_FORMS, boundAgrees, displayRange, measureDisplay, measureQualifier, measureSchema, measureTotals, plotDate } from "./measure-totals.mjs"; import { goalCell, nextRegime, offOf } from "./panel-model.mjs"; import { offsetIn } from "./gaps.mjs"; import { validateGhosts } from "./measure-ghosts.mjs"; import { dietRecord } from "./diet-record.mjs"; import { dietRunsOn } from "./finale.mjs"; export const MEASURE_SLICE_VERSION = 1; export { PROMISE_FORMS }; /** `render.chrome.deck.measure`'s keys. */ export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf", "ghosts", "flash"]); 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) && !Number.isNaN(Date.parse(`${v}T00:00:00Z`)); const r1 = (v) => Math.round(v * 10) / 10; const r3 = (v) => Math.round(v * 1000) / 1000; /** * `render.chrome.deck.measure`, checked: `{ scopes?, scale?, asOf?, ghosts? }` -- * `scopes` a list of track keys (unique, at least one), `scale` `{ min, max }` * (numbers, min < max), `asOf` a date (YYYY-MM-DD), `ghosts` the dial's claim * ghosts (measure-ghosts.mjs: true, false or their knobs). Whether the scopes are * the ledger's tracks is measureSettingsProblems' (it has the schema). * * @returns {string[]} */ export function validateMeasureSettings(v, where = "render.chrome.deck.measure") { if (v === undefined) return []; if (!isObj(v)) return [`${where} must be { ${MEASURE_SETTINGS_KEYS.join(", ")} }`]; const errors = []; for (const k of Object.keys(v)) if (!MEASURE_SETTINGS_KEYS.includes(k)) errors.push(`${where}.${k} is not a measure setting (${MEASURE_SETTINGS_KEYS.join(", ")})`); if (v.scopes !== undefined) { if (!Array.isArray(v.scopes) || !v.scopes.length || v.scopes.some((s) => typeof s !== "string" || !s.trim())) { errors.push(`${where}.scopes must be a list of the ledger's track keys (at least one)`); } else if (new Set(v.scopes).size !== v.scopes.length) errors.push(`${where}.scopes names a track twice`); } if (v.scale !== undefined) { const s = v.scale; if (!isObj(s) || !Number.isFinite(s.min) || !Number.isFinite(s.max)) errors.push(`${where}.scale must be { min, max } in the ledger's unit`); else if (s.min >= s.max) errors.push(`${where}.scale.min must be below scale.max`); else for (const k of Object.keys(s)) if (k !== "min" && k !== "max") errors.push(`${where}.scale.${k} is not a scale setting (min, max)`); } if (v.asOf !== undefined && !isIso(v.asOf)) errors.push(`${where}.asOf must be a date (YYYY-MM-DD)`); // The update flash (update-flash.mjs): every measure widget's outline lights as its value changes. if (v.flash !== undefined && typeof v.flash !== "boolean") errors.push(`${where}.flash must be true or false`); errors.push(...validateGhosts(v.ghosts, `${where}.ghosts`)); return errors; } /** Does this manifest carry a measure ledger? */ export const isMeasureManifest = (manifest) => isObj(manifest?.ledgerSchema) && manifest.ledgerSchema.kind === "measure"; /** Does this cut write a measure slice: a deck, a measure ledger, and `render.chrome.deck.measure` set? */ export function measureOn(manifest) { const chrome = manifest?.render?.chrome; return isMeasureManifest(manifest) && isObj(chrome) && chrome.layout === "deck" && isObj(chrome.deck?.measure); } /** * The measure settings against the manifest: the deck's `measure` shape, that * the manifest has a measure ledger for it, and that every scope is one of * its tracks. * * @returns {string[]} */ export function measureSettingsProblems(manifest) { const v = manifest?.render?.chrome?.deck?.measure; if (v === undefined) return []; const errors = validateMeasureSettings(v); if (errors.length) return errors; if (!isMeasureManifest(manifest)) return ['render.chrome.deck.measure needs a measure ledger (ledgerSchema.kind "measure")']; const tracks = measureSchema(manifest.ledgerSchema).tracks.map((t) => t.key); for (const s of v.scopes ?? []) if (!tracks.includes(s)) errors.push(`render.chrome.deck.measure.scopes: "${s}" is not a track of the ledger (${tracks.join(", ")})`); return errors; } /** * The settings with their defaults: scopes every track, the scale the * schema's yMin..yMax, asOf the render's date. */ export function resolveMeasure(manifest, { asOf = null } = {}) { const schema = measureSchema(manifest.ledgerSchema); const v = manifest?.render?.chrome?.deck?.measure ?? {}; const today = new Date().toISOString().slice(0, 10); return { schema, scopes: Array.isArray(v.scopes) && v.scopes.length ? [...v.scopes] : schema.tracks.map((t) => t.key), scale: isObj(v.scale) ? { min: v.scale.min, max: v.scale.max } : { min: schema.yMin, max: schema.yMax }, asOfRender: asOf ?? v.asOf ?? today, }; } /** * `render.chrome.deck.goals.baseMaxDays` as the slice reads it: whole days (0 = the goal's own day), or null when * unset (or the goal stack is a bare true/false): how long before a loss goal a weight may have been said and still * be the goal's base (measureSlice `goalBase`). The goal stack's settings check its shape (measure-extras-settings.mjs). */ export function goalBaseMaxDays(manifest) { const v = manifest?.render?.chrome?.deck?.goals?.baseMaxDays; return Number.isInteger(v) && v >= 0 ? v : null; } /** A promise_outcome row's `stampNote` -- the words under its stamp on the promise clock -- trimmed, or null. */ export const stampNoteOf = (row) => (typeof row?.stampNote === "string" && row.stampNote.trim() ? row.stampNote.trim() : null); // --------------------------------------------------------------------------- // The odometer // --------------------------------------------------------------------------- /** * Is this row a REAL-TIME loss claim -- one the odometer counts? A `delta` * on the (first) value track, below zero, about now: no `asOf`, and not * marked `retro` (a loss he describes in the past -- "I also lost 64 pounds" * -- with no date to put in `asOf`). */ export function isRealtimeLoss(row, schema) { const s = measureSchema(schema); const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null; return row?.scope === valueTrack && row.population === "delta" && Number(row.value) < 0 && (row.asOf === undefined || row.asOf === null || row.asOf === "") && row.retro !== true; } /** * The runs of real-time loss claims, by HIS words (ruled 5 Nov 2026): * * - only real-time loss claims count (isRealtimeLoss); * - a run is a sequence of them, and its contribution is the HIGHEST claim * in it -- the figure he gave, whatever app or other figure he cites; * - a row's explicit `run` (a whole number, written by the ledger writer * where his words say which run a claim continues -- "since I started") * places it; otherwise a gap of more than `bandGapDays` since the last * claim starts a new run, and a shorter one continues it; * - the total is the sum of the runs' peaks. * * Walked in the order he said them (date, then id). * * @returns {{ runs: Array<{ run: number, start: string, end: string, peak: number, row: string, rows: string[] }>, * runOf: Map, claims: Array<{ id: string, date: string, run: number }>, total: number }} */ export function lossRuns(rows, schema) { const s = measureSchema(schema); const claims = chronological((rows ?? []).filter((r) => isRealtimeLoss(r, s))); const byRun = new Map(); const runOf = new Map(); let prev = null; let next = 0; for (const c of claims) { let run; if (Number.isInteger(c.run) && c.run >= 0) run = c.run; else if (prev && Math.round(daysBetween(prev.date, c.date)) <= s.bandGapDays) run = runOf.get(prev.id); else run = next; next = Math.max(next, run + 1); runOf.set(c.id, run); const v = Math.abs(Number(c.value)); const r = byRun.get(run); if (!r) byRun.set(run, { run, start: c.date, end: c.date, peak: v, row: c.id, rows: [c.id] }); else { r.rows.push(c.id); if (dateKey(c.date) > dateKey(r.end)) r.end = c.date; if (dateKey(c.date) < dateKey(r.start)) r.start = c.date; if (v > r.peak) { r.peak = v; r.row = c.id; } } prev = c; } const runs = [...byRun.values()].sort((a, b) => a.run - b.run); return { runs, runOf, claims: claims.map((c) => ({ id: c.id, date: c.date, run: runOf.get(c.id) })), total: r1(runs.reduce((n, r) => n + r.peak, 0)) }; } /** * THE RUN'S START on day `d`, when the record names one: `{ value, row, date }` * or null. The run open on `d` is the run of his last loss claim on or before * it, within bandGapDays, else of his next one within bandGapDays (a day as a * run begins); its start is a remembered weight about a day within * bandGapDays before the run's first claim, said by `d` (the latest said * wins). A loss goal's base (measureSlice) and an analysis item's deltas * (analysis-plan.mjs) both read it. * * @param {string} d * @param {{ readings: any[], lossClaims: Array<{ id: string, date: string, run: number }>, runById: Map, bandGapDays: number }} ctx * `readings` his value-track current/past rows, chronological; `lossClaims` and `runById` lossRuns' over his usable rows. */ export function runStartAt(d, { readings, lossClaims, runById, bandGapDays }) { let run = null; const before = lossClaims.filter((c) => dateKey(c.date) <= dateKey(d)).pop(); if (before && Math.round(daysBetween(before.date, d)) <= bandGapDays) run = runById.get(before.run) ?? null; else { const after = lossClaims.find((c) => dateKey(c.date) > dateKey(d)); if (after && Math.round(daysBetween(d, after.date)) <= bandGapDays) run = runById.get(after.run) ?? null; } if (!run) return null; const starts = readings.filter((r) => r.population === "past" && r.asOf && dateKey(r.date) <= dateKey(d) && dateKey(r.asOf) <= dateKey(run.start) && Math.round(daysBetween(r.asOf, run.start)) <= bandGapDays); const last = starts[starts.length - 1]; return last ? { value: Number(last.value), row: last.id, date: last.date ?? null } : null; } /** * runStartAt over a ledger: `rows` every row (only his own on the value track * are read, as measureSlice reads them), `schema` the ledger's. */ export function runStartOf(rows, schema, d) { const s = measureSchema(schema); const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null; const own = (rows ?? []).filter((r) => isObj(r) && typeof r.id === "string" && speakerOf(r) === null); const { runs, claims } = lossRuns(own.filter(isUsable), s); const readings = chronological(own.filter((r) => r.scope === valueTrack && (r.population === "current" || r.population === "past") && Number.isFinite(Number(r.value)))); return runStartAt(d, { readings, lossClaims: claims, runById: new Map(runs.map((r) => [r.run, r])), bandGapDays: s.bandGapDays }); } // --------------------------------------------------------------------------- // A row as an event // --------------------------------------------------------------------------- /** A row's kind on the instruments, from its form and its track. */ export function kindOf(row, schema) { const s = measureSchema(schema); const role = s.tracks.find((t) => t.key === row?.scope)?.role ?? null; switch (row?.population) { case "current": return "stated"; case "past": return "remembered"; case "delta": return Number(row.value) < 0 ? "lost" : "gained"; case "goal": return "goal"; case "goal_loss": return "goalLoss"; case "overweight_by": return "overBy"; case "promise": return "promise"; case "promise_check": return "promiseCheck"; case "promise_claim": return "promiseClaim"; case "promise_outcome": return "promiseOutcome"; case "status": return role === "regime" ? "diet" : "status"; default: return row?.population ?? null; } } /** A hidden row's source: an X post when its link or channel says so, else a clip. */ const rowSource = (row) => (/(^|\/\/)(x|twitter)\.com\//.test(String(row?.citeUrl ?? "")) || /-x$/i.test(String(row?.channel ?? "")) ? "post" : "clip"); /** An entry's source kind: a clip, a post, or a card (anything else). */ const entrySource = (entry) => (entry?.type === "clip" ? "clip" : entry?.type === "post" ? "post" : "card"); /** * A RANGE he gave ("330-340 lb", "220–240"): `[lo, hi]` read off the row's * display, or null. The row's `value` is the range's middle (what a single * number is drawn at); the range is what he said, and the instruments draw it * as a range -- a wedge, "330–340" -- never the middle alone. */ export function rangeOf(row) { return displayRange(row?.display); } function eventOf(row, schema, runOf) { const s = measureSchema(schema); const kind = kindOf(row, s); const role = s.tracks.find((t) => t.key === row.scope)?.role ?? null; const n = Number(row.value); const range = role === "regime" ? null : rangeOf(row); return { ...(range ? { range } : {}), row: row.id, scope: row.scope, date: row.date ?? null, asOf: row.asOf ?? null, kind, value: role === "regime" || !Number.isFinite(n) || row.value === null || row.value === "" ? null : n, qualifier: measureQualifier(row, s), display: measureDisplay(row, s), label: row.label ?? null, quote: row.quote ?? null, deadline: row.deadline ?? null, due: isIso(row.due) ? row.due : null, regime: role === "regime" ? String(row.value) : null, event: role === "regime" ? row.event ?? null : null, run: kind === "lost" && runOf.has(row.id) ? runOf.get(row.id) : null, speaker: speakerOf(row), outcome: row.population === "promise_outcome" && typeof row.outcome === "string" ? row.outcome : null, // Not a usable claim (a joke, a misattributed line): on screen when pinned, in no tally (isUsable). ...(row.scopeConfidence === "unresolved" ? { unresolved: true } : {}), }; } /** * Who said the row: null for the subject (no `speaker`), else the speaker's * key ("madamsavvy"). A row by another speaker never moves the subject's * numbers -- current, lost, net, goals, diet, the totals -- it only feeds the * promises (a promise_claim). */ export const speakerOf = (row) => (typeof row?.speaker === "string" && row.speaker.trim() ? row.speaker.trim() : null); /** * Does the row COUNT -- in a tally (goals set, diets, pledges, the odometer, * "under 300", the goal ladder)? Not when its scope is `unresolved`: the * ledger's word for "not a usable claim" (a joke -- w44, "only way I'm losing * 100 lbs is by amputation" -- or a line that is not his). Such a row is still * a row: pinned, it is on screen, and a reading still reads (operator, 6 Nov). */ export const isUsable = (row) => row?.scopeConfidence !== "unresolved" && row?.unresolved !== true; // --------------------------------------------------------------------------- // When a row lands: the spoken number in the clip's words // --------------------------------------------------------------------------- const ONES = { zero: 0, oh: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19 }; const TENS = { twenty: 20, thirty: 30, forty: 40, fourty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 }; const norm = (w) => String(w ?? "").toLowerCase().replace(/[“”"',!?;:()\[\]]/g, "").replace(/\.$/, "").replace(/^\$/, ""); /** * The numbers said in a run of words: `{ i, value }` for each, `i` the index * of its first word -- digits ("291.5", "60", "58.2lbs") and number words * ("two hundred ninety one point five", "a hundred", "fifty eight point two"). * * @param {Array<{ text: string }>} words */ export function spokenNumbers(words) { const toks = words.map((w) => norm(w.text)); const out = []; for (let i = 0; i < toks.length; i += 1) { const t = toks[i]; const digits = /^(\d+(?:\.\d+)?)(?:lbs?|pounds?)?$/.exec(t); if (digits) { out.push({ i, value: Number(digits[1]) }); continue; } const starts = t in ONES || t in TENS || (t === "a" && toks[i + 1] === "hundred"); if (!starts) continue; let total = 0; let cur = 0; let j = i; let any = false; for (; j < toks.length; j += 1) { const w = toks[j]; if (w in ONES) { cur += ONES[w]; any = true; } else if (w in TENS) { cur += TENS[w]; any = true; } else if (w === "a" && toks[j + 1] === "hundred") { cur += 1; } else if (w === "hundred") { cur = (cur || 1) * 100; any = true; } else if (w === "thousand") { total += (cur || 1) * 1000; cur = 0; any = true; } else if (w === "and" && any && (toks[j + 1] in ONES || toks[j + 1] in TENS)) { /* "a hundred and ten" */ } else break; } let value = total + cur; // "point five", "point one five": the digits after the point, one word each. if (toks[j] === "point" && toks[j + 1] in ONES && ONES[toks[j + 1]] < 10) { let frac = ""; let k = j + 1; while (k < toks.length && toks[k] in ONES && ONES[toks[k]] < 10) { frac += String(ONES[toks[k]]); k += 1; } value = Number(`${value}.${frac}`); j = k; } if (any) out.push({ i, value }); i = j - 1; } return out; } /** The words that name a regime when he says it, beyond its key and label. */ const REGIME_WORDS = { glp1: ["ozempic", "ozimpic", "wegovy", "mounjaro", "glp", "glp-1", "semaglutide", "jab"], fasting: ["fasting", "fast"], calories: ["calories", "calorie"], carnivore: ["carnivore"], keto: ["keto", "ketogenic"] }; /** The figure the row's quote says, as he would say it: the magnitude, for a loss or a loss goal. */ function spokenTargets(row, kind) { if (!["stated", "remembered", "lost", "gained", "goal", "goalLoss", "overBy"].includes(kind)) return null; const out = []; const n = Number(row.value); if (Number.isFinite(n)) out.push(Math.abs(n)); // A range he gave ("220-240", "330-340 lb"): either end is his figure. const range = /(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)/.exec(String(row.display ?? "")); if (range) out.push(Number(range[1]), Number(range[2])); return out.length ? out : null; } /** * The source second the row's figure is said in `words` (`[{ text, start }]`, * source seconds), searched from `anchor` (a second before it) to the end, * then anywhere: the first word of the spoken number (a figure row), or the * regime's word (a diet row). Null when the words never say it. */ export function spokenAt(row, kind, words, anchor = -Infinity, schema = null) { if (!Array.isArray(words) || !words.length) return null; const pick = (hits) => hits.find((h) => words[h].start >= anchor - 1) ?? hits[0] ?? null; const targets = spokenTargets(row, kind); if (targets !== null) { const nums = spokenNumbers(words); const exact = nums.filter((n) => targets.some((v) => Math.abs(n.value - v) < 0.05)).map((n) => n.i); const i = pick(exact); return i === null ? null : words[i].start; } if (kind === "diet") { const key = String(row.value ?? ""); const label = schema ? measureSchema(schema).regimes.find((r) => r.key === key)?.label ?? "" : ""; const names = new Set([key, ...(REGIME_WORDS[key] ?? []), ...label.toLowerCase().split(/[^a-z0-9-]+/).filter((w) => w.length > 3)]); const hits = words.map((w, i) => (names.has(norm(w.text)) ? i : -1)).filter((i) => i >= 0); const i = pick(hits); return i === null ? null : words[i].start; } return null; } // --------------------------------------------------------------------------- // The slice // --------------------------------------------------------------------------- /** * The rows of the cut's entries: entry id → the in-scope row ids it shows, in * ledger order -- each row's `entryId`, and each entry's ledger pin * (`claim: ""`). */ export function pinnedRows(timeline, rows) { const ids = new Set(rows.map((r) => r.id)); const out = new Map(); const add = (entryId, rowId) => { if (!ids.has(rowId)) return; const list = out.get(entryId) ?? []; if (!list.includes(rowId)) list.push(rowId); out.set(entryId, list); }; const inCut = new Set((timeline ?? []).map((e) => e?.id)); for (const r of rows) if (r.entryId && inCut.has(r.entryId)) add(r.entryId, r.id); for (const e of timeline ?? []) if (typeof e?.claim === "string" && e.claim.trim()) add(e.id, e.claim.trim()); const order = new Map(rows.map((r, i) => [r.id, i])); for (const list of out.values()) list.sort((a, b) => order.get(a) - order.get(b)); return out; } /** * The measure slice of a cut. * * @param {object} manifest the variant's manifest: `ledgerSchema`, `render`, * `timeline` (the cut's entries), and `ledger` -- the WHOLE ledger, or pass * it as `opts.ledger` (a variant's manifest keeps only the pinned rows). * @param {{ segments: Array<{ id: string, start: number, duration: number }> }} schedule * the deck schedule (deck.mjs deckSchedule's document, or one like it). * @param {{ ledger?: object[], asOf?: string|null, * words?: Map, from?: string }>, * clock?: Map, gaps?: Map> }} [opts] * `words` each clip's words in SOURCE seconds; `clock` the source second * each clip's segment starts at (its cut record's, else the play window's); * `gaps` a clip's gaps. A clip with none of them lands on its quoteStart, * against its own start. */ export function measureSlice(manifest, schedule, opts = {}) { const settings = resolveMeasure(manifest, { asOf: opts.asOf ?? null }); const s = settings.schema; const problems = measureSettingsProblems(manifest); if (problems.length) throw new Error(problems.join("; ")); const scopes = new Set(settings.scopes); const ledger = (opts.ledger ?? manifest.ledger ?? []).filter((r) => isObj(r) && typeof r.id === "string"); const rows = ledger.filter((r) => scopes.has(r.scope)); const byId = new Map(rows.map((r) => [r.id, r])); // HIS rows: every number the instruments draw is the subject's own. const own = rows.filter((r) => speakerOf(r) === null); // What counts in a tally: his own usable rows. const counted = own.filter(isUsable); const { runs, runOf, claims: lossClaims, total } = lossRuns(counted, s); const runById = new Map(runs.map((r) => [r.run, r])); // ---- events: each pinned row at the cut second it lands ------------------- const timeline = manifest.timeline ?? []; const entryById = new Map(timeline.map((e) => [e.id, e])); const segs = (schedule?.segments ?? []).filter((g) => entryById.has(g.id)); const segIndex = new Map(segs.map((g, i) => [g.id, i])); const pins = pinnedRows(timeline.filter((e) => segIndex.has(e.id)), rows); const shown = new Set(); const events = []; for (const seg of segs) { const entry = entryById.get(seg.id); const ids = pins.get(seg.id) ?? []; const from = opts.clock?.get(seg.id) ?? entry.cutStart ?? entry.start ?? null; const gaps = opts.gaps?.get(seg.id) ?? null; const words = opts.words?.get(seg.id) ?? null; const toCut = (src) => { if (!Number.isFinite(src) || !Number.isFinite(from)) return null; const off = offsetIn(src, from, gaps); return r3(Math.min(seg.start + seg.duration, Math.max(seg.start, seg.start + off))); }; for (const id of ids) { if (shown.has(id)) continue; const row = byId.get(id); const ev = eventOf(row, s, runOf); // His figure's own second when the words have it; searched from the // row's cite when that is inside the clip (an entry showing two rows // says them at two seconds), else from the quote's start. const inWindow = (v) => Number.isFinite(v) && Number.isFinite(entry.start) && Number.isFinite(entry.end) && v >= entry.start && v <= entry.end; const anchor = ids.length > 1 && inWindow(row.cite) ? row.cite : entry.quoteStart ?? entry.start ?? -Infinity; const said = entry.type === "clip" && words ? spokenAt(row, ev.kind, words.words, anchor, s) : null; let t = said !== null ? toCut(said) : null; let tFrom = t !== null ? (words.from === "cues" ? "cues" : "words") : null; if (t === null && entry.type === "clip") { const q = ids.length > 1 && inWindow(row.cite) ? row.cite : entry.quoteStart; t = toCut(q); if (t !== null) tFrom = "quote"; } if (t === null) { t = r3(seg.start); tFrom = "segment"; } events.push({ t, tFrom, segment: seg.id, ...ev, source: entrySource(entry), _seg: segIndex.get(seg.id) }); shown.add(id); } } events.sort((a, b) => a.t - b.t || a._seg - b._seg || dateKey(a.date).localeCompare(dateKey(b.date)) || String(a.row).localeCompare(String(b.row))); for (const e of events) delete e._seg; const hidden = chronological(rows.filter((r) => !shown.has(r.id))) .map((r) => ({ t: null, tFrom: null, segment: null, ...eventOf(r, s, runOf), source: rowSource(r) })); // ---- the record's own figures, for the state's fixed ends ----------------- const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null; const regimeTrack = s.tracks.find((t) => t.role === "regime" && scopes.has(t.key))?.key ?? null; const readings = chronological(own.filter((r) => r.scope === valueTrack && (r.population === "current" || r.population === "past") && Number.isFinite(Number(r.value)))); const firstReading = [...readings].sort((a, b) => dateKey(plotDate(a)).localeCompare(dateKey(plotDate(b))) || String(a.id).localeCompare(String(b.id)))[0] ?? null; const netFrom = firstReading ? { value: Number(firstReading.value), date: plotDate(firstReading), row: firstReading.id } : null; /** * A loss goal's target weight: against the start of the run open when he * set it, when the record knows that start (runStartAt) -- else against the * last weight he stated by then, else none (his words stay the goal). */ // A loss goal's base (rev 9, 6 Nov): the run's start when the record names one; // else the latest weight he gave by the goal's date -- stated or remembered, // by the day it was his weight (a remembered one's asOf); else none. A target // below the scale's foot is no target (a stale base: "lose 100" from 240 is // not 140 lb): his words stay the goal -- "LOSE 100", no weight, no tick. const goalBase = (row) => { const d = row.date; const start = runStartAt(d, { readings, lossClaims, runById, bandGapDays: s.bandGapDays }); if (start) return { value: start.value, row: start.row, from: "runStart", date: start.date }; const known = readings .filter((r) => dateKey(r.date) <= dateKey(d)) .sort((a, b) => dateKey(plotDate(a)).localeCompare(dateKey(plotDate(b))) || dateKey(a.date).localeCompare(dateKey(b.date))); const last = known[known.length - 1]; return last ? { value: Number(last.value), row: last.id, from: last.population === "past" ? "remembered" : "stated", date: last.date ?? null } : null; }; // `deck.goals.baseMaxDays` (rev9-a9, 12 Nov: "LOSE 100 (FROM 368)" off a weight he gave eight years before): a // base counts only when its weight was SAID -- its row's date, never a remembered one's asOf -- at most that many // days before the goal's date. A staler one is no base: his words stay the goal, no weight, no tick, no "(FROM …)". // Unset: every base counts, as before. const baseMaxDays = goalBaseMaxDays(manifest); const fresh = (base, row) => baseMaxDays === null || !base || (base.date && Math.round(daysBetween(base.date, row.date)) <= baseMaxDays); const scaleMin = Number.isFinite(settings.scale?.min) ? settings.scale.min : -Infinity; const goalOf = (row) => { let base = row.population === "goal_loss" ? goalBase(row) : null; if (!fresh(base, row)) base = null; let cell = goalCell(row, base, s); if (base && Number.isFinite(cell.value) && cell.value < scaleMin) { base = null; cell = goalCell(row, null, s); } const range = row.population === "goal" ? rangeOf(row) : null; return { value: cell.value, loss: cell.loss, deadline: cell.deadline, due: isIso(row.due) ? row.due : null, row: row.id, display: cell.display, base, ...(range ? { range } : {}) }; }; /** A promise_claim as a promise carries it: who, when said, the day she says she paid, his-or-her words. */ /** A promise_outcome as a promise carries it. */ const outcomeOf = (row) => ({ kind: row.outcome, date: row.date ?? null, row: row.id, ...(stampNoteOf(row) ? { note: stampNoteOf(row) } : {}) }); const claimOf = (row) => ({ row: row.id, speaker: speakerOf(row), date: row.date ?? null, paidOn: isIso(row.paidOn) ? row.paidOn : null, label: row.label ?? row.display ?? null }); // ---- the state after each event ------------------------------------------- let current = null; const remembered = []; let goal = null; const goals = []; const peaks = new Map(); let regime = null; let dietN = 0; const promises = new Map(); const snapshot = (t) => { const lostRuns = [...peaks.entries()].sort((a, b) => a[0] - b[0]).map(([run, p]) => ({ run, start: runById.get(run)?.start ?? null, peak: p.peak, row: p.row })); const off = regimeTrack ? offOf(s, regimeTrack)?.key ?? null : null; return { t, current: current ? { ...current } : null, remembered: remembered.map((x) => ({ ...x })), goal: goal ? { ...goal, ...(goal.base ? { base: { ...goal.base } } : {}) } : null, goals: [...goals], lost: { total: r1(lostRuns.reduce((n, r) => n + r.peak, 0)), runs: lostRuns }, net: { from: netFrom ? { ...netFrom } : null, to: current ? { value: current.value, date: current.asOf ?? current.date, row: current.row } : null, value: netFrom && current ? r1(current.value - netFrom.value) : null, }, diet: regime && regime.key !== off ? { regime: regime.key, display: regime.display, row: regime.row, n: dietN, since: regime.since } : null, promises: [...promises.values()].map((p) => ({ ...p, checks: [...p.checks], claims: p.claims.map((c) => ({ ...c })), outcome: p.outcome ? { ...p.outcome } : null })), }; }; const state = [snapshot(0)]; for (const ev of events) { const row = byId.get(ev.row); // Another speaker's row feeds the promises and nothing else. if (ev.speaker !== null && ev.kind !== "promiseClaim" && ev.kind !== "promiseOutcome") { state.push(snapshot(ev.t)); continue; } // An unresolved row is no claim to count: it moves a reading (it is on screen), never a goal, a diet, a promise. if (ev.unresolved && ev.kind !== "stated" && ev.kind !== "remembered") { state.push(snapshot(ev.t)); continue; } // A bound that agrees with the specific weight in force (">300" while he is at 342) is no new figure: the needle // and the number stay (boundAgrees). One that contradicts it (">300" at 291) moves them, as any reading does. if (ev.kind === "stated" && ev.value !== null && boundAgrees(ev, current)) { /* the current weight stands */ } else if (ev.kind === "stated" && ev.value !== null) current = { value: ev.value, qualifier: ev.qualifier, row: ev.row, date: ev.date, asOf: ev.asOf, ...(ev.range ? { range: [...ev.range] } : {}) }; else if (ev.kind === "remembered" && ev.value !== null) remembered.push({ value: ev.value, asOf: ev.asOf, row: ev.row, date: ev.date, ...(ev.qualifier ? { qualifier: ev.qualifier } : {}), ...(ev.range ? { range: [...ev.range] } : {}) }); else if (ev.kind === "goal" || ev.kind === "goalLoss") { goal = goalOf(row); goals.push(ev.row); } else if (ev.kind === "lost" && ev.run !== null) { const v = Math.abs(ev.value); const p = peaks.get(ev.run); if (!p || v > p.peak) peaks.set(ev.run, { peak: v, row: ev.row }); } else if (ev.kind === "diet" && row.scope === regimeTrack) { const was = regime; regime = nextRegime(regime, row, s); const off = offOf(s, regimeTrack)?.key ?? null; if (regime && regime.key !== off && (!was || was.key !== regime.key)) dietN += 1; } else if (ev.kind === "promise") { promises.set(ev.row, { row: ev.row, said: ev.date, what: ev.display, due: ev.due, kept: row.kept === true, checks: [], claims: [], outcome: null }); } else if (ev.kind === "promiseCheck") { const p = promises.get(row.promise); if (p) { p.checks.push(ev.row); if (row.kept === true) p.kept = true; } } else if (ev.kind === "promiseClaim") { const p = promises.get(row.promise); if (p) p.claims.push(claimOf(row)); } else if (ev.kind === "promiseOutcome") { // How it ended: the latest outcome shown; "kept" keeps it. const p = promises.get(row.promise); if (p && ev.outcome) { p.outcome = outcomeOf(row); if (ev.outcome === "kept") p.kept = true; } } state.push(snapshot(ev.t)); } // `asOf` is the state's own bookkeeping: the current reading carries the // date the contract names, and NET its plot date. for (const st of state) if (st.current) delete st.current.asOf; // ---- totals over the whole record in scope -------------------------------- const all = chronological(own); const lastStated = [...readings].filter((r) => r.population === "current").pop() ?? null; const tallied = all.filter(isUsable); const goalRows = tallied.filter((r) => r.population === "goal" || r.population === "goal_loss"); const repeats = {}; for (const r of goalRows) { const d = measureDisplay(r, s); repeats[d] = (repeats[d] ?? 0) + 1; } const goalRepeats = Object.fromEntries(Object.entries(repeats).filter(([, n]) => n > 1).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))); // THE PEAK DRIFT: the weight he remembers starting from, retold. A // remembered weight above every weight he ever stated at the time, about a // day inside the stated record -- so the 2008 wedding is not a start, and // neither is a floor or a ladder rung below what he was saying then. const stated = readings.filter((r) => r.population === "current"); const maxStated = stated.length ? Math.max(...stated.map((r) => Number(r.value))) : Infinity; const firstStated = stated.length ? stated.map((r) => dateKey(r.date)).sort()[0] : null; const peakDrift = [...new Set(readings.filter((r) => r.population === "past" && r.asOf && firstStated && dateKey(r.asOf) >= firstStated && Number(r.value) > maxStated).map((r) => Number(r.value)))].sort((a, b) => a - b); // UNDER 300: a weight he stated below it, or "under 300" itself -- never a // bound the other way ("over 240" is not a weight under 300). const under = stated.filter(isUsable).filter((r) => { const q = measureQualifier(r, s); return q !== ">" && (Number(r.value) < 300 || (Number(r.value) === 300 && q === "<")); }); const dates = all.map((r) => plotDate(r)).filter(Boolean).map(dateKey).sort(); const promiseRows = tallied.filter((r) => r.population === "promise"); const checksOf = (id) => all.filter((r) => r.population === "promise_check" && r.promise === id); const outcomeRowOf = (id) => chronological(rows).filter((r) => r.population === "promise_outcome" && r.promise === id && typeof r.outcome === "string").pop() ?? null; const claimsOf = (id) => chronological(rows).filter((r) => r.population === "promise_claim" && r.promise === id).map(claimOf); let diets = 0; try { diets = measureTotals(counted, s, { strict: false }).switches; } catch { diets = 0; } const totals = { lost: total, lostRuns: runs.map(({ run, start, end, peak, row, rows: ids }) => ({ run, start, end, peak, row, rows: ids })), net: { from: netFrom?.value ?? null, to: lastStated ? Number(lastStated.value) : null, value: netFrom && lastStated ? r1(Number(lastStated.value) - netFrom.value) : null, fromRow: netFrom?.row ?? null, toRow: lastStated?.id ?? null, }, runs: runs.length, goals: goalRows.length, goalRepeats, diets, peakDrift, under300: { said: under.length, rows: under.map((r) => r.id) }, promises: promiseRows.map((p) => { const checks = checksOf(p.id); const end = outcomeRowOf(p.id); return { row: p.id, said: p.date, what: measureDisplay(p, s), due: isIso(p.due) ? p.due : null, kept: p.kept === true || checks.some((c) => c.kept === true) || end?.outcome === "kept", checks: checks.map((c) => c.id), claims: claimsOf(p.id), outcome: end ? outcomeOf(end) : null, }; }), span: { from: dates[0] ?? null, to: dates[dates.length - 1] ?? null }, }; return { version: MEASURE_SLICE_VERSION, unit: s.unit, scale: settings.scale, asOfRender: settings.asOfRender, scopes: settings.scopes, events, hidden, state, totals, // The whole diet record, for the finale's detailed runs (`deck.finale.dietRuns`): only when it asks. ...(dietRunsOn(manifest?.render?.chrome?.deck?.finale?.dietRuns) ? { record: dietRecord(counted, s, regimeTrack, readings, isObj(manifest.render.chrome.deck.finale.dietRuns) ? manifest.render.chrome.deck.finale.dietRuns : {}) } : {}), }; }