Archilyzer · Source

archilyzer

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

commit 1bd66d03765b78765b74c60762714af96b8400c0
parent a02cd2b80943910e43676e01f951391f84c185c5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 23:38:18 -0500

umtool: the streak chain -- a chain per run, cracked with its length when it ends

A fifth measure extra (`streak`, render.chrome.deck.streak; operator, 5 Nov:
"all the p3 and p2 modules that could be used here should be tried out"): a
chain per run along a time axis by in-record date. A run starts a chain, each
day it holds extends it (the live chain grows with the in-record date on
screen, "DAY n" beside it), and when it ends the chain cracks -- its tip
snaps off, a red break, its length tagged on a red flash ("KETO · 41 days") --
then dims into the row, so the stop-start rhythm stays on screen.

Source-agnostic: each source is an adapter from the measure slice to runs
`{ key, name, color, start, startT, end, endT, ended, detail }` and the
drawing reads only runs -- `diet` (the state's diet turning on or changing
regime or number starts a run; off ends it), `lostRuns` (the odometer's runs,
each to its last claim before the next), and `pledges` for the sobriety video
(a pledge starts a run, a lapse snaps it "after 73 days"; an adapter with a
TODO until the ledger writes those kinds, its shape unit-tested).
`axis: "runs"` lays the chains one after another (√ of their length) instead
of on the dates. It sits bottom-centre, between the diet badge and the goal
stack (z 65, under the badge), so either or both can run.

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

Diffstat:
Mumtool/docs/knobs.md | 15++++++++++++++-
Mumtool/report-to-video/chrome-measure-extras.mjs | 163++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/measure-extras.mjs | 167++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/measure-extras.test.mjs | 45++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/modules/index.mjs | 3++-
Mumtool/report-to-video/modules/measure-extras-settings.mjs | 22+++++++++++++++++++---
Mumtool/report-to-video/modules/rail.test.mjs | 2+-
Mumtool/report-to-video/modules/registry.test.mjs | 6+++---
Aumtool/report-to-video/modules/streak.mjs | 41+++++++++++++++++++++++++++++++++++++++++
9 files changed, 447 insertions(+), 17 deletions(-)

diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1466,6 +1466,7 @@ filter. A knob absent is its default, and a module whose knobs are all absent dr | [Then and now (pair)](#then-and-now-pair) `pair` | Two clips on one subject, each with its date: a then \| now strip (or a then→now card) with the pair's caption. (a page over the whole cut) | `render.chrome.pair` | | [Status ledger](#status-ledger) `status` | A row per item -- announced, then followed up or not -- filling a column as the cut plays. (a page over the whole cut) | `render.chrome.status` | | [Effects](#effects) `fx` | Overlays on the picture: receipts, a zoom, a scrubber, captions. (a page over the whole cut) | `render.chrome.fx` | +| [Streak chain](#streak-chain) `streak` | A chain per run along the in-record dates, cracked with its length when the run ends; past runs dimmed in a row. (a page over the whole cut) | `render.chrome.deck.streak` | | [Diet badge](#diet-badge) `diet` | The diet he names as a stamp that slams on at each change, with its number; "No diet" when the state says so. (a page over the whole cut) | `render.chrome.deck.diet` | | [Moving start](#moving-start) `peak` | The starting weight as he retells it: a tick per telling on a small scale, a count per repeat, the drift bracketed. (a page over the whole cut) | `render.chrome.deck.peak` | | [Goal stack](#goal-stack) `goals` | Each goal he names as a sticky note on a pile -- a repeat merged with its count, a deadline counted down to the render date. (a page over the whole cut) | `render.chrome.deck.goals` | @@ -1485,7 +1486,7 @@ it can be seeked. `POST /api/report/chrome/preview` returns every such module th build's predicate) as `layers: [{id, z, region, clock, ready, geometry, src | windows}]`; the client lays them by z over the deck's page, a whole-cut page for the whole cut, a window module's page only inside each window. -Declaring `play`: `stats`, `pair`, `status`, `fx`, `diet`, `peak`, `goals`, `threads`, `flips`, `chapter`, `promise`. +Declaring `play`: `stats`, `pair`, `status`, `fx`, `streak`, `diet`, `peak`, `goals`, `threads`, `flips`, `chapter`, `promise`. Still drawn by their own paths (the response's `src`, `feed`, `posts`, `stamp` and `finale` keys), and what moving each onto `play` needs: the deck (`shell`) -- its typed words patched in live (`deck:text`) and the `deck:ready` @@ -1690,6 +1691,18 @@ Overlays on the picture -- receipts, a zoom, the scrubber, a kinetic quote, punc | beside popup posts that move the footage (`deck.posts.shift`) | the effects are drawn over the footage box where it stays, so an effect on screen WHILE the posts hold the footage aside is refused, naming both and their seconds — a zoom, receipts, a quote or a punch-in on its own clip's span; a whip, glitch or THEN/NOW wipe around its cut; the scrubber and the odometer over every clip (so beside any shift). A persisting bar holds it aside from its first post to its glide back. Apart in time, both are drawn. `umtool check` reads the estimated schedule; the build checks again on the measured one before any chrome is drawn | `deck.posts.shift=false`, the feed, or move one of them | | the zoom's timing (`fx.zoom.at`, `.hold`) | up 0.2 s into the clip's clean span (the card rises in over 0.38 s, `back.out`); its focus box draws 0.55 s later (0.45 s); it pushes in on the box at `at` — seconds into the clip, default as soon as the box has drawn — over 1 s (`power2.inOut`), then drifts slowly on the detail. It leaves with a 0.3 s fade 0.3 s before the clip's clean span ends, or with `hold` (0.5–10 s) that long after the push lands (never past the clip's own leave) | `fx.zoom='{…,"hold":4}'` | +### Streak chain + +A chain per run along a time axis by in-record date (`render.chrome.deck.streak`, measure-extras.mjs): a run starts a chain, each day it holds extends it (the live chain grows with the in-record date of what is on screen, its day count beside it), and when the run ends the chain cracks -- its tip snaps off, a red break, its length tagged ("KETO · 41 days", a lapse "after 73 days") -- then dims into the row, so the stop-start rhythm stays on screen. `source` picks the runs: `diet` (the state's diet turning on or changing -- a new regime or diet number -- ends the last and starts the next; off ends it), `lostRuns` (the odometer's runs, each from its start to the next one's), `pledges` (the sobriety video's: a `pledge` event starts a run, a `lapse` snaps it -- an adapter only until the ledger writes those kinds). `axis: "runs"` lays the chains one after another, each as wide as the square root of its length, instead of on the dates. It sits bottom-centre, between the diet badge and the goal stack, so the diet badge, the chain, or both can run (`umtool look <p> deck.diet=false` / `deck.streak=false`). + +| Knob | Range · default | From a terminal | +|---|---|---| +| `deck.streak` | `true` · `false` · `{show, position, x, y, scale, hold, finale, source, axis, title, color, colors, labels}` · default on with a measure slice | `umtool look <p> deck.streak=false` | +| `deck.streak.source`, `.axis` | `diet` `lostRuns` `pledges` · `date` `runs` · default `diet`, `date` | `umtool look <p> deck.streak.source=lostRuns` | +| `deck.streak.position`, `.x`/`.y`, `.scale` | an anchor in the footage box · design px · 0.5–2 · default `bottom-center`, unset, 1 | `umtool look <p> deck.streak.position=bottom-left` | +| `deck.streak.hold`, `.finale` | null (up from the first run on) or 2–600 s · `hide` `show` · default null, `hide` | `umtool look <p> deck.streak.hold=15` | +| `deck.streak.title`, `.color`, `.colors`, `.labels` | ≤40 · #hex · `{<regime>: #hex}` · `{<regime>: words}` · default the source's word, the accent, the regimes' inks and names | `umtool look <p> deck.streak.title='Every diet'` | + ### Diet badge The diet he names as a rubber stamp in a corner of the footage box (`render.chrome.deck.diet`, measure-extras.mjs): at each change of the state's diet -- its regime or its diet number -- a new stamp slams on (in big and turned, onto the page, a shake), the regime's word in its ink and "DIET #n" under it with the ledger's words when they say more ("Keto · 5 carbs a day"); a change of words alone fades the new stamp in. A null diet after one fades to "NO DIET" in grey. It draws `state.diet` as the measure slice gives it -- the off-scope rule ("off GLP-1" while on keto is still keto) is the ledger's. The inks default to the quartering-diet regimes' (keto #E0913C, carnivore #C9534B, fasting #4E9BD8, calories #3FA9A0, glp1 #B168C6, other #8E97A8, off #98A29B). diff --git a/umtool/report-to-video/chrome-measure-extras.mjs b/umtool/report-to-video/chrome-measure-extras.mjs @@ -15,8 +15,8 @@ import { rgba } from "./chrome-deck.mjs"; import { compileCues, cuePageHtml, esc, INSTANT, joinSpans, r4, spanEvents } from "./chrome-cues.mjs"; import { - daysLeftText, dietStates, goalStates, measureExtraGeometry, measureOf, MEASURE_BOXES, - monthYear, peakStates, promiseStates, shortDate, upSpans, weightText, + daysBetween, daysLeftText, daysText, dietStates, goalStates, measureExtraGeometry, measureOf, MEASURE_BOXES, + monthYear, peakStates, promiseStates, shortDate, streakStates, upSpans, weightText, } from "./measure-extras.mjs"; import { MEASURE_RED, resolveMeasureExtra } from "./modules/measure-extras-settings.mjs"; @@ -448,3 +448,162 @@ export function dietHtml(schedule, render, opts = {}) { </div>`; return { html: page("diet", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`)), items }; } + +// --------------------------------------------------------------------------- +// STREAK: the chains. +// --------------------------------------------------------------------------- + +/** Each source's own word over the readout when `title` is not set. */ +const STREAK_TITLES = Object.freeze({ diet: "Diet runs", lostRuns: "Weight-loss runs", pledges: "Dry streaks" }); + +/** + * The streak chain's page: `{ html, items }`. Past chains are items of their + * own (each up from its crack on, dimmed); the live chain and the readout are + * a block per state. + */ +export function streakHtml(schedule, render, opts = {}) { + const cfg = resolveMeasureExtra("streak", render); + const { runs, states, span } = streakStates(schedule, render); + if (!cfg || !states.length) throw new Error("streak: the schedule's measure slice has no run on camera"); + const F = frameOf("streak", schedule, render); + const { px } = F; + const pal = render.palette; + const red = MEASURE_RED; + const X0 = px(196); + const X1 = F.geo.width - px(18); + const barY = px(66); + const barH = px(16); + // Where a run's chain stands: to scale on the dates, or each in its own slot (√ of its length). + const total = Math.max(1, daysBetween(span[0], span[1]) ?? 1); + const xOfDate = (d) => r4(X0 + ((daysBetween(span[0], d) ?? 0) / total) * (X1 - X0)); + let slots = null; + if (cfg.axis === "runs") { + const gap = px(3); + const ws = runs.map((r) => Math.sqrt(r.days + 1)); + const k = (X1 - X0 - gap * (runs.length - 1)) / ws.reduce((a, b) => a + b, 0); + let x = X0; + slots = ws.map((w) => { const s = { x: r4(x), w: r4(Math.max(px(2), w * k)) }; x += w * k + gap; return s; }); + } + const left = (i) => (slots ? slots[i].x : xOfDate(runs[i].start)); + const widthAt = (i, days) => { + if (slots) return r4(Math.max(px(3), slots[i].w * Math.sqrt(days + 1) / Math.sqrt(runs[i].days + 1))); + return r4(Math.max(px(3), (days / total) * (X1 - X0))); + }; + const spans = upSpans(states.map((s) => s.at), cfg, schedule); + const items = []; + const init = {}; + const extra = []; + // The past chains: each up from its crack, the tip snapping off, its length + // tagged until the next crack, then dimmed into the row. + const cracks = runs.map((r, i) => ({ i, t: r.endT })).filter((c) => c.t !== null).sort((a, b) => a.t - b.t); + const chains = runs.map((r, i) => { + if (r.endT === null) return ""; + const k = `c${i}`; + const w = widthAt(i, r.days); + const next = cracks.find((c) => c.t > r.endT + 1e-6); + init[k] = { autoAlpha: 0 }; + init[`${k}.b`] = { opacity: 1 }; + init[`${k}.tip`] = { x: 0, y: 0, rotation: 0, opacity: 1 }; + init[`${k}.l`] = { opacity: 0, scale: 1.5 }; + init[`${k}.z`] = { opacity: 0 }; + init[`${k}.lf`] = { opacity: 0.95 }; + extra.push({ k, at: r.endT, dur: INSTANT, to: { autoAlpha: 1 }, ease: "none" }); + extra.push({ k: `${k}.tip`, at: r.endT, dur: 0.5, to: { x: px(16), y: px(14), rotation: 38, opacity: 0 }, ease: "power2.in" }); + extra.push({ k: `${k}.l`, at: r.endT, dur: 0.3, to: { opacity: 1, scale: 1 }, ease: "back.out(2)" }); + extra.push({ k: `${k}.z`, at: r.endT, dur: 0.12, to: { opacity: 1 }, ease: "power1.out" }); + extra.push({ k: `${k}.lf`, at: r.endT + 0.2, dur: 1, to: { opacity: 0 }, ease: "power1.in" }); + extra.push({ k: `${k}.b`, at: r.endT + 0.6, dur: 0.8, to: { opacity: 0.36 }, ease: "power1.out" }); + // The break and the tag stay until the next crack takes over. + if (next) { + extra.push({ k: `${k}.l`, at: Math.max(r.endT + 0.35, next.t), dur: INSTANT, to: { opacity: 0 }, ease: "none" }); + extra.push({ k: `${k}.z`, at: Math.max(r.endT + 0.15, next.t), dur: INSTANT, to: { opacity: 0 }, ease: "none" }); + } + const word = r.days === 0 && r.zeroWord ? r.zeroWord : r.ended === "lapse" ? `after ${daysText(r.days)}` : daysText(r.days); + const lx = Math.max(X0, Math.min(X1 - px(240), left(i) + w - px(120))); + const html = `<div class="ch" data-k="${k}"><div class="bar" data-k="${k}.b" style="left:${left(i)}px;width:${w}px;--c:${esc(r.color)}"></div><div class="tip" data-k="${k}.tip" style="left:${r4(left(i) + w - px(6))}px;--c:${esc(r.color)}"></div><div class="zz" data-k="${k}.z" style="left:${r4(left(i) + w - px(3))}px"></div><div class="tag" data-k="${k}.l" style="left:${r4(lx)}px"><span class="tf" data-k="${k}.lf"></span><b style="color:${esc(r.color)}">${esc(r.name)}</b> · ${esc(word)}</div></div>`; + items.push({ key: k, gate: [k, "autoAlpha"], html }); + return html; + }).join(""); + const compiled = stateCues(states, spans, { + own: (st, j, init2) => { + const ev = []; + if (!st.live) return ev; + const prev = states[j - 1]; + const k = `s${j}.lv`; + const w = widthAt(st.live.i, st.live.days); + const from = prev?.live?.i === st.live.i ? widthAt(st.live.i, prev.live.days) : px(3); + if (from !== w) { + init2[k] = { width: from }; + ev.push({ k, at: st.at, dur: 0.4, to: { width: w }, ease: "power2.out" }); + } + return ev; + }, + }, init); + const allCues = compileCues(compiled.init, [...compiled.cues.map(({ from: _f, ...c }) => c), ...extra]); + const blocks = states.map((st, j) => { + let readout; + let live = ""; + if (st.live) { + const r = runs[st.live.i]; + live = `<div class="bar live" data-k="s${j}.lv" style="left:${left(st.live.i)}px;width:${widthAt(st.live.i, st.live.days)}px;--c:${esc(r.color)}"></div>`; + readout = `<div class="nm" style="color:${esc(r.color)}">${esc(r.name)}</div><div class="dy">Day ${st.live.days}</div>${r.detail ? `<div class="dt">${esc(r.detail)}</div>` : ""}`; + } else { + const last = [...runs.keys()].filter((i) => runs[i].endT !== null && runs[i].endT <= st.at + 1e-6).pop(); + const r = last !== undefined ? runs[last] : null; + readout = r + ? `<div class="nm sn">Snapped</div><div class="dy sm">${esc(r.name)}</div><div class="dt">after ${esc(daysText(r.days))}</div>` + : `<div class="nm sn">—</div>`; + } + const html = `<div class="st" data-k="s${j}"><div class="ro">${readout}</div>${live}</div>`; + items.push({ key: `s${j}`, gate: [`s${j}`, "autoAlpha"], html }); + return html; + }); + // The axis: the years, when the chains stand on the dates. + const years = []; + if (!slots) { + const y0 = Number(span[0].slice(0, 4)); + const y1 = Number(span[1].slice(0, 4)); + const every = y1 - y0 > 8 ? 2 : 1; + for (let y = y0 + 1; y <= y1; y += 1) { + const x = xOfDate(`${y}-01-01`); + years.push(`<div class="yt" style="left:${x}px"></div>${(y - y0) % every === 0 ? `<div class="yl" style="left:${r4(x - px(20))}px">${y}</div>` : ""}`); + } + } + const title = cfg.title ?? STREAK_TITLES[cfg.source]; + const css = ` + #pn { position: absolute; inset: 0; visibility: hidden; opacity: 0; border-radius: ${px(10)}px; + background: ${rgba(pal.bg, 0.9)}; box-shadow: 0 ${px(8)}px ${px(26)}px rgba(0, 0, 0, 0.45); } + .ti { position: absolute; left: ${px(18)}px; top: ${px(12)}px; font-family: 'DeckSansBold', sans-serif; font-size: ${px(15)}px; + letter-spacing: 0.14em; text-transform: uppercase; color: ${pal.muted}; white-space: nowrap; } + .ax { position: absolute; left: ${X0}px; width: ${r4(X1 - X0)}px; top: ${barY + barH + px(10)}px; height: ${px(2)}px; background: ${rgba(pal.muted, 0.45)}; } + .yt { position: absolute; top: ${barY + barH + px(6)}px; width: ${px(1)}px; height: ${px(10)}px; background: ${rgba(pal.muted, 0.6)}; } + .yl { position: absolute; top: ${barY + barH + px(18)}px; width: ${px(40)}px; text-align: center; font-size: ${px(14)}px; color: ${pal.muted}; + font-variant-numeric: tabular-nums; } + .ch, .st { position: absolute; inset: 0; visibility: hidden; opacity: 0; } + /* A chain: links of the run's colour, a gap every few pixels. */ + .bar { position: absolute; top: ${barY}px; height: ${barH}px; border-radius: ${px(4)}px; + background: repeating-linear-gradient(90deg, var(--c) 0 ${px(6)}px, transparent ${px(6)}px ${px(8)}px); } + .bar.live { box-shadow: 0 0 ${px(10)}px var(--c); } + .tip { position: absolute; top: ${barY}px; width: ${px(6)}px; height: ${barH}px; border-radius: ${px(2)}px; background: var(--c); } + .zz { position: absolute; top: ${barY - px(4)}px; width: ${px(6)}px; height: ${barH + px(8)}px; + background: linear-gradient(115deg, transparent 40%, ${red} 40% 60%, transparent 60%); } + .tf { position: absolute; inset: 0; border-radius: ${px(4)}px; background: ${rgba(red, 0.75)}; z-index: -1; } + .tag { position: absolute; top: ${px(36)}px; width: ${px(240)}px; isolation: isolate; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + font-size: ${px(16)}px; line-height: ${px(22)}px; color: ${pal.fg}; transform-origin: 50% 100%; } + .tag b { font-family: 'DeckSansBold', sans-serif; text-transform: uppercase; letter-spacing: 0.06em; } + .ro { position: absolute; left: ${px(18)}px; top: ${px(34)}px; width: ${px(166)}px; } + .nm { font-family: ${DISPLAY}; font-size: ${px(32)}px; line-height: ${px(36)}px; text-transform: uppercase; white-space: nowrap; + overflow: hidden; text-overflow: ellipsis; } + .nm.sn { color: ${red}; } + .dy { font-family: ${DISPLAY}; font-size: ${px(30)}px; line-height: ${px(34)}px; color: ${pal.fg}; text-transform: uppercase; + white-space: nowrap; font-variant-numeric: tabular-nums; } + .dy.sm { font-size: ${px(22)}px; line-height: ${px(28)}px; overflow: hidden; text-overflow: ellipsis; } + .dt { font-size: ${px(15)}px; line-height: ${px(19)}px; color: ${pal.muted}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }`; + const body = `<div id="pn" data-k="pn"> + <div class="ti">${esc(title)}</div> + ${slots ? "" : `<div class="ax"></div>${years.join("")}`} + ${chains} + ${blocks.join("\n ")} + </div>`; + return { html: page("streak", schedule, opts, F, css, body, allCues.init, allCues.cues, states.map((_, j) => `s${j}`)), items }; +} diff --git a/umtool/report-to-video/measure-extras.mjs b/umtool/report-to-video/measure-extras.mjs @@ -451,6 +451,170 @@ export function dietStates(schedule, render) { } // --------------------------------------------------------------------------- +// 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, + start: 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 // --------------------------------------------------------------------------- @@ -460,6 +624,7 @@ export const MEASURE_BOXES = Object.freeze({ peak: Object.freeze({ width: 280, height: 470 }), promise: Object.freeze({ width: 620, height: 200 }), diet: Object.freeze({ width: 440, height: 200 }), + streak: Object.freeze({ width: 620, height: 150 }), }); /** @@ -467,7 +632,7 @@ export const MEASURE_BOXES = Object.freeze({ * 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"} id + * @param {"goals" | "peak" | "promise" | "diet" | "streak"} id * @returns {{ x: number, y: number, width: number, height: number }} */ export function measureExtraGeometry(id, render, { feed = false } = {}) { diff --git a/umtool/report-to-video/measure-extras.test.mjs b/umtool/report-to-video/measure-extras.test.mjs @@ -9,20 +9,21 @@ import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { goalsHtml, dietHtml, peakHtml, promiseHtml, spreadLabels, stampSize } from "./chrome-measure-extras.mjs"; +import { goalsHtml, dietHtml, peakHtml, promiseHtml, spreadLabels, stampSize, streakHtml } from "./chrome-measure-extras.mjs"; import { cuePageHtml } from "./chrome-cues.mjs"; import { estimateSchedule, validateChrome } from "./deck.mjs"; import { frameKeys } from "./frame-keys.mjs"; import { - daysBetween, deadlineDate, dietStates, goalStates, goalText, measureExtraGeometry, peakStates, promiseStates, upSpans, + daysBetween, deadlineDate, dietRuns, dietStates, goalStates, goalText, lostRunsRuns, measureExtraGeometry, peakStates, pledgeRuns, + promiseStates, streakStates, upSpans, } from "./measure-extras.mjs"; import { deckOverlays, moduleById, moduleProblems, playModules, scheduleSlices } from "./modules/index.mjs"; import { resolveMeasureExtra, validateMeasureExtra } from "./modules/measure-extras-settings.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures/measure-extras/measure.json"), "utf8")); -const IDS = ["goals", "peak", "promise", "diet"]; -const PAGES = { goals: goalsHtml, peak: peakHtml, promise: promiseHtml, diet: dietHtml }; +const IDS = ["goals", "peak", "promise", "diet", "streak"]; +const PAGES = { goals: goalsHtml, peak: peakHtml, promise: promiseHtml, diet: dietHtml, streak: streakHtml }; const RENDER = { width: 1920, height: 1080, fps: 30, @@ -134,6 +135,38 @@ test("diet: a stamp per change of regime or number, words alone not slammed, a n assert.ok(stampSize("Counting calories", 330) < stampSize("Keto", 330)); }); +test("streak: runs through a per-source adapter -- diet runs, lost runs, pledges -- and the chain's states", () => { + const cfg = resolveMeasureExtra("streak", RENDER); + const runs = dietRuns(MEASURE, cfg); + assert.equal(runs.length, 66, "a run per diet (regime and number)"); + assert.deepEqual([runs[0].name, runs[0].start, runs[0].ended, runs[0].detail], ["Some diet", "2018-02-06", "new", "diet #1"]); + assert.equal(runs.at(-1).end, null, "the last is open"); + for (const r of runs.slice(0, -1)) assert.ok(r.endT >= r.startT && r.end >= r.start); + // A diet turned off ends its run "off". + const m = clone(MEASURE); + m.state[m.state.length - 1].diet = null; + assert.equal(dietRuns(m, cfg).at(-1).ended, "off"); + // Lost runs: the state's runs, each ended at its last claim before the next. + const lost = clone(MEASURE); + lost.state = lost.state.map((s, i) => ({ ...s, lost: { total: 0, runs: i < 40 ? [{ run: 1, start: "2021-04-30", peak: 13.5 }] : [{ run: 1, start: "2021-04-30", peak: 13.5 }, { run: 2, start: "2023-05-09", peak: 29 }] } })); + const lr = lostRunsRuns(lost, cfg, RENDER.palette); + assert.deepEqual(lr.map((r) => [r.name, r.start, r.ended, r.detail]), [["Run 1", "2021-04-30", "new", "down 13.5"], ["Run 2", "2023-05-09", null, "down 29"]]); + // Pledges (the sobriety video's adapter): a pledge starts a run, a lapse snaps it. + const p = { events: [ + { t: 1, row: "d1", kind: "pledge", date: "2026-01-01", display: "Dry" }, + { t: 2, row: "d2", kind: "lapse", date: "2026-03-15" }, + { t: 3, row: "d3", kind: "pledge", date: "2026-04-01", display: "Dry" }, + ], state: [{}, {}, {}, {}] }; + const pr = pledgeRuns(p, cfg, RENDER.palette); + assert.deepEqual(pr.map((r) => [r.start, r.end, r.ended]), [["2026-01-01", "2026-03-15", "lapse"], ["2026-04-01", null, null]]); + // The chain: a state per change, the live run's days with the in-record date; the axis' span to the render date. + const { states, span, runs: rs } = streakStates(schedule(), RENDER); + assert.equal(span[1], MEASURE.asOfRender); + assert.ok(states.some((s) => s.cracked !== null)); + assert.equal(states.at(-1).live.i, rs.length - 1); + assert.equal(streakStates(schedule(), withDeck({ streak: { source: "lostRuns" } })).runs.length, 0, "the trimmed fixture keeps no lost runs"); +}); + test("up: from the first event to the end (or the finale), or `hold` seconds after each", () => { assert.deepEqual(upSpans([10, 20], { hold: null, finale: "hide" }, { total: 100 }), [{ in: 10, out: 100 }]); assert.deepEqual(upSpans([10, 20], { hold: null, finale: "hide" }, { total: 100, finale: { from: 90, to: 100 } }), [{ in: 10, out: 90 }]); @@ -151,7 +184,8 @@ test("the pages: a block per state, each an item gated by its own autoAlpha, key const fk = frameKeys({ html, region: id, assets: [], fps: 30, frames: 740 * 30, version: "t", items }); assert.ok(fk, `${id}: the frame-key model reads its page`); const distinct = new Set(fk).size; - assert.ok(distinct < fk.length / 10, `${id}: ${distinct} distinct frames of ${fk.length}`); + // (The streak cracks 65 times in the fixture's 12 minutes, each a 1.8 s snap: a fifth.) + assert.ok(distinct < fk.length / (id === "streak" ? 5 : 10), `${id}: ${distinct} distinct frames of ${fk.length}`); // Before its first event the region is empty: every frame there is the same frame. assert.equal(fk[0], fk[30 * 5], id); } @@ -212,6 +246,7 @@ test("the modules: drawn only with a measure slice and something of their own to } assert.ok(playModules().some((m) => m.id === "promise")); assert.ok(moduleById("promise").z > moduleById("finale").z, "the promise clock is drawn over the finale"); + assert.equal(moduleById("streak").z < moduleById("diet").z, true, "the chain under the badge: either or both"); assert.equal(moduleById("goals").on(schedule({ ...MEASURE, events: MEASURE.events.filter((e) => !e.kind.startsWith("goal")) }), RENDER), false); assert.deepEqual(scheduleSlices(schedule()).measure, MEASURE); }); diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs @@ -35,12 +35,13 @@ import diet from "./diet.mjs"; import peak from "./peak.mjs"; import goals from "./goals.mjs"; import promise from "./promise.mjs"; +import streak from "./streak.mjs"; export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, PLAY_CLOCKS, REGION_PLACEMENTS }; /** Every module, by z (stack order), then id. */ export const MODULES = Object.freeze( - [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, intro, blur, pair, chapter, status, chat, diet, peak, goals, promise] + [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, intro, blur, pair, chapter, status, chat, diet, peak, goals, promise, streak] .sort((a, b) => a.z - b.z || a.id.localeCompare(b.id)), ); diff --git a/umtool/report-to-video/modules/measure-extras-settings.mjs b/umtool/report-to-video/modules/measure-extras-settings.mjs @@ -9,6 +9,7 @@ // render.chrome.deck.peak { show, position, x, y, scale, hold, finale, title, color, values } // render.chrome.deck.promise { show, position, x, y, scale, hold, finale, label, verb, kept, broken, checks } // render.chrome.deck.diet { show, position, x, y, scale, hold, finale, colors, labels } +// render.chrome.deck.streak { show, position, x, y, scale, hold, finale, source, axis, title, color, colors, labels } // // Each is ON whenever the cut has a measure slice (the build writes one only // for a manifest with a measure ledger and `deck.measure` set) and something @@ -36,6 +37,12 @@ export const MEASURE_FINALE = Object.freeze(["hide", "show"]); /** Which remembered weights the moving start draws (`peak.values`): the totals' drift values, or every one. */ export const PEAK_VALUES = Object.freeze(["drift", "all"]); +/** Where the streak chain's runs come from (`streak.source`): diet runs, his lost-weight runs, pledges (the sobriety video's; adapter only). */ +export const STREAK_SOURCES = Object.freeze(["diet", "lostRuns", "pledges"]); + +/** How the streak chain lays its runs (`streak.axis`): to scale on the in-record dates, or one after another (√ of their length). */ +export const STREAK_AXES = Object.freeze(["date", "runs"]); + /** What a promise check's line quotes (`promise.checks`): the ledger row's label, or its transcript quote. */ export const PROMISE_CHECKS = Object.freeze(["label", "quote"]); @@ -79,10 +86,13 @@ export const MEASURE_DEFAULTS = Object.freeze({ promise: Object.freeze({ ...COMMON, position: "top-center", finale: "show", label: null, verb: "offered", kept: "Posted", broken: "None posted", checks: "label" }), // The diet badge: up from the first diet on, re-stamped at every change. diet: Object.freeze({ ...COMMON, position: "bottom-left", colors: Object.freeze({}), labels: Object.freeze({}) }), + // The streak chain: bottom-centre, between the diet badge and the goal + // stack, so either or both can run. `title` null is the source's own word. + streak: Object.freeze({ ...COMMON, position: "bottom-center", source: "diet", axis: "date", title: null, color: null, colors: Object.freeze({}), labels: Object.freeze({}) }), }); /** The four ids, in the order they are drawn. */ -export const MEASURE_EXTRAS = Object.freeze(["diet", "peak", "goals", "promise"]); +export const MEASURE_EXTRAS = Object.freeze(["diet", "peak", "goals", "promise", "streak"]); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi; @@ -101,7 +111,7 @@ export function resolveMeasureExtra(id, render) { if (v === false) return null; const own = isObj(v) ? v : {}; const out = { ...base, ...own }; - if (id === "diet") { + if (id === "diet" || id === "streak") { out.colors = { ...DIET_COLORS, ...(isObj(own.colors) ? own.colors : {}) }; out.labels = { ...DIET_LABELS, ...(isObj(own.labels) ? own.labels : {}) }; } @@ -165,7 +175,13 @@ export function validateMeasureExtra(id, v, where = `render.chrome.deck.${id}`) for (const k of ["label", "verb", "kept", "broken"]) text(v[k], L.text, `${where}.${k}`, errors, { nullable: k === "label" }); if (v.checks !== undefined && !PROMISE_CHECKS.includes(v.checks)) errors.push(`${where}.checks must be "label" or "quote"`); } - if (id === "diet") { + if (id === "streak") { + if (v.source !== undefined && !STREAK_SOURCES.includes(v.source)) errors.push(`${where}.source must be ${STREAK_SOURCES.map((x) => `"${x}"`).join(", ")}`); + if (v.axis !== undefined && !STREAK_AXES.includes(v.axis)) errors.push(`${where}.axis must be "date" or "runs"`); + text(v.title, L.text, `${where}.title`, errors); + color(v.color, `${where}.color`, errors); + } + if (id === "diet" || id === "streak") { for (const k of ["colors", "labels"]) { if (v[k] === undefined) continue; if (!isObj(v[k])) { errors.push(`${where}.${k} must be { <regime>: … }`); continue; } diff --git a/umtool/report-to-video/modules/rail.test.mjs b/umtool/report-to-video/modules/rail.test.mjs @@ -47,5 +47,5 @@ test("rail settings: spacing, pitch, and the deck's other keys refused by name", assert.equal(resolveDeck(render({})).pip.pitch, undefined, "no pitch unless set: the deck resolves as it did"); assert.equal(rail.resolve(render({ spacing: "pitch" })).pip.pitch, 28); assert.equal(rail.validate, settingsOf("rail").validate); - assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "chat", "pair", "chapter", "status", "finale", "claims", "counter", "shell", "rail", "section-title", "subtitle", "qr", "popup-posts", "diet", "peak", "goals", "promise"]); + assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "chat", "pair", "chapter", "status", "finale", "claims", "counter", "shell", "rail", "section-title", "subtitle", "qr", "popup-posts", "diet", "peak", "goals", "promise", "streak"]); }); diff --git a/umtool/report-to-video/modules/registry.test.mjs b/umtool/report-to-video/modules/registry.test.mjs @@ -47,8 +47,8 @@ test("the registry: unique ids and regions, sorted by z, the deck's overlays in assert.equal(new Set(ids).size, ids.length); for (let i = 1; i < MODULES.length; i += 1) assert.ok(MODULES[i - 1].z <= MODULES[i].z); // The order the build has always laid them in: the finale last of all but the - // promise clock, which is drawn over it (the measure extras, z 66-68 and 95). - assert.deepEqual(deckOverlays().map((m) => m.region), ["deck", "feed", "posts", "stamp", "chat", "stats", "pair", "status", "fx", "diet", "peak", "goals", "threads", "flips", "chapter", "finale", "promise"]); + // promise clock, which is drawn over it (the measure extras, z 65-68 and 95). + assert.deepEqual(deckOverlays().map((m) => m.region), ["deck", "feed", "posts", "stamp", "chat", "stats", "pair", "status", "fx", "streak", "diet", "peak", "goals", "threads", "flips", "chapter", "finale", "promise"]); assert.equal(moduleOfRegion("deck").id, "shell"); assert.equal(regionModule("posts").id, "popup-posts"); assert.throws(() => regionModule("nope"), /unknown chrome region: nope/); @@ -152,7 +152,7 @@ test("play: a live-preview contract only an overlay with a page and regions decl assert.throws(() => defineModule({ ...base, play: { clock: "cut", ready: "x" } }), /play must be/); assert.throws(() => defineModule({ ...base, page: undefined, play: { clock: "cut", ready: "x:ready" } }), /only an overlay with a page/); assert.throws(() => defineModule({ ...base, kind: "segment", play: { clock: "cut", ready: "x:ready" } }), /only an overlay with a page/); - assert.deepEqual(playModules().map((m) => m.id), ["stats", "pair", "status", "fx", "diet", "peak", "goals", "threads", "flips", "chapter", "promise"]); + assert.deepEqual(playModules().map((m) => m.id), ["stats", "pair", "status", "fx", "streak", "diet", "peak", "goals", "threads", "flips", "chapter", "promise"]); for (const m of playModules()) assert.equal(m.play.ready, `${m.region}:ready`, m.id); }); diff --git a/umtool/report-to-video/modules/streak.mjs b/umtool/report-to-video/modules/streak.mjs @@ -0,0 +1,41 @@ +// THE STREAK CHAIN (module `streak`, region `streak`): a chain per run along +// the in-record dates -- a run starts a chain, each day it holds extends it, +// and when it ends (the diet off, a new run, a lapse) the chain cracks with a +// snap and its length ("KETO · 41 days"); past chains stay dimmed in the row, +// so the stop-start rhythm shows. Source-agnostic: each source is an adapter +// to runs (measure-extras.mjs dietRuns, lostRunsRuns, pledgeRuns) and the +// drawing reads only runs (`render.chrome.deck.streak`; +// chrome-measure-extras.mjs streakHtml). It and the diet badge share the +// bottom of the footage box: either or both. +import { streakHtml } from "../chrome-measure-extras.mjs"; +import { streakStates } from "../measure-extras.mjs"; +import { measureExtraModule } from "./measure-extras-module.mjs"; +import { STREAK_AXES, STREAK_SOURCES } from "./measure-extras-settings.mjs"; + +export default measureExtraModule({ + id: "streak", + z: 65, + title: "Streak chain", + summary: "A chain per run along the in-record dates, cracked with its length when the run ends; past runs dimmed in a row.", + states: (schedule, render) => streakStates(schedule, render).states, + html: streakHtml, + needs: "a run of its source (a diet, a lost-weight run, a pledge)", + ui: [ + { key: "source", type: "enum", options: STREAK_SOURCES, label: "Runs of", default: "diet" }, + { key: "axis", type: "enum", options: STREAK_AXES, label: "Laid on", default: "date" }, + { key: "title", type: "text", label: "Heading (default the source's)" }, + { key: "color", type: "color", label: "Chain colour (lost runs, pledges; default the palette's accent)" }, + { key: "colors", type: "object", label: "Diet runs: ink per regime" }, + { key: "labels", type: "object", label: "Diet runs: words per regime" }, + ], + docs: { + intro: "A chain per run along a time axis by in-record date (`render.chrome.deck.streak`, measure-extras.mjs): a run starts a chain, each day it holds extends it (the live chain grows with the in-record date of what is on screen, its day count beside it), and when the run ends the chain cracks -- its tip snaps off, a red break, its length tagged (\"KETO · 41 days\", a lapse \"after 73 days\") -- then dims into the row, so the stop-start rhythm stays on screen. `source` picks the runs: `diet` (the state's diet turning on or changing -- a new regime or diet number -- ends the last and starts the next; off ends it), `lostRuns` (the odometer's runs, each from its start to the next one's), `pledges` (the sobriety video's: a `pledge` event starts a run, a `lapse` snaps it -- an adapter only until the ledger writes those kinds). `axis: \"runs\"` lays the chains one after another, each as wide as the square root of its length, instead of on the dates. It sits bottom-centre, between the diet badge and the goal stack, so the diet badge, the chain, or both can run (`umtool look <p> deck.diet=false` / `deck.streak=false`).", + rows: [ + ["`deck.streak`", "`true` · `false` · `{show, position, x, y, scale, hold, finale, source, axis, title, color, colors, labels}` · default on with a measure slice", "`umtool look <p> deck.streak=false`"], + ["`deck.streak.source`, `.axis`", "`diet` `lostRuns` `pledges` · `date` `runs` · default `diet`, `date`", "`umtool look <p> deck.streak.source=lostRuns`"], + ["`deck.streak.position`, `.x`/`.y`, `.scale`", "an anchor in the footage box · design px · 0.5–2 · default `bottom-center`, unset, 1", "`umtool look <p> deck.streak.position=bottom-left`"], + ["`deck.streak.hold`, `.finale`", "null (up from the first run on) or 2–600 s · `hide` `show` · default null, `hide`", "`umtool look <p> deck.streak.hold=15`"], + ["`deck.streak.title`, `.color`, `.colors`, `.labels`", "≤40 · #hex · `{<regime>: #hex}` · `{<regime>: words}` · default the source's word, the accent, the regimes' inks and names", "`umtool look <p> deck.streak.title='Every diet'`"], + ], + }, +});