// THE MEASURE'S DRAWING KIT (lane scale-dial): the pure pieces the measure's
// pages share -- the dial (chrome-instruments.mjs: `dial`, `dial-finale`), the
// odometer, the trail, and any later module that reads `schedule.measure`
// (measure-extras' goals, peak, promise and diet are meant to take them too):
//
// - cueList: a cue interpreter's `init` and `cues` (chrome-deck.mjs says why
// a page is one), every cue with its FROM stated and clamped so no two run
// on one element at once -- the shape frame-keys.mjs models, so a frame
// whose values are a frame's before it is reused, not captured again;
// - measureTrack: the measure's states read once into what changes when
// (the stated weight, the remembered ones, the goal, the odometer's total,
// NET, the "under 300" claims);
// - the dial's face, its angles and the odometer's wheels, as markup;
// - pageHtml: the page around them -- HyperFrames' root and clip, the data
// script, and the interpreter with `?still=` and the preview's `deck:seek`.
//
// Pure: strings in, strings out. No fs.
import { cueTime, pageDuration } from "./deck.mjs";
import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
export const INSTANT = 0.001;
export const r4 = (v) => Math.round(v * 10000) / 10000;
const r2 = (v) => Math.round(v * 100) / 100;
export const esc = (s) =>
String(s ?? "")
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """);
/**
* A cue list being built. `add(k, at, dur, to, ease)` asks for element `k`
* to reach `to` over [at, at + dur]; `build()` orders them, clamps each to
* start once the last cue on its element has finished (shortened to end
* where it would have), and states every FROM (the last `to` on that
* element, or its init). Times land on the deck's sub-frame grid (cueTime),
* so a moment the cut moved by whole frames draws exactly what it drew.
*/
export function cueList(fps) {
const init = {};
const ev = [];
return {
init,
set(k, props) {
init[k] = { ...(init[k] ?? {}), ...props };
},
add(k, at, dur, to, ease = "none") {
if (!Number.isFinite(at)) return;
const rounded = Object.fromEntries(Object.entries(to).map(([p, v]) => [p, typeof v === "number" ? r4(v) : v]));
ev.push({ k, at: cueTime(Math.max(0, at), fps), dur: r4(Math.max(INSTANT, dur)), to: rounded, ease, n: ev.length });
},
build() {
ev.sort((a, b) => a.at - b.at || a.n - b.n);
const state = Object.fromEntries(Object.entries(init).map(([k, v]) => [k, { ...v }]));
const freeAt = new Map();
const cues = [];
for (const e of ev) {
let { at, dur } = e;
const free = freeAt.get(e.k) ?? 0;
if (at < free) {
const end = at + dur;
at = r4(free);
dur = r4(Math.max(INSTANT, end - at));
}
const cur = state[e.k] ?? (state[e.k] = {});
const from = {};
for (const p of Object.keys(e.to)) from[p] = cur[p];
Object.assign(cur, e.to);
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
return { init, cues: settleFirstFrame(init, cues, fps) };
},
};
}
// ---------------------------------------------------------------------------
// Words and numbers.
// ---------------------------------------------------------------------------
const MONTHS = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
/** "2026-10-26" as "26 OCT 2026"; a first of the month (an approximate as-of) as "JUL 2023". */
export function fmtDate(iso, { day = true } = {}) {
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso ?? ""));
if (!m) return "";
const mon = MONTHS[Number(m[2]) - 1] ?? "";
return day && m[3] !== "01" ? `${Number(m[3])} ${mon} ${m[1]}` : `${mon} ${m[1]}`;
}
/** A weight as he gave it: whole when whole, else to a tenth. */
export function fmtWeight(v) {
if (!Number.isFinite(v)) return "—";
const r = Math.round(v * 10) / 10;
return Number.isInteger(r) ? String(r) : r.toFixed(1);
}
/** A signed difference with a real minus: "−76.5", "+4". */
export function fmtSigned(v) {
if (!Number.isFinite(v)) return "—";
const s = fmtWeight(Math.abs(v));
return v < 0 ? `−${s}` : v > 0 ? `+${s}` : "0";
}
/** The qualifier as the dial prints it before the digits. */
export const qualifierMark = (q) => (q === "≈" ? "≈" : q === ">" ? ">" : q === "<" ? "<" : "");
/** A weight as the dial writes it: a range "330–340" (never its middle alone), else its qualifier and number. */
export const weightWords = (x) => (Array.isArray(x?.range) && x.range.length === 2
? `${fmtWeight(x.range[0])}–${fmtWeight(x.range[1])}`
: `${qualifierMark(x?.qualifier)}${fmtWeight(x?.value)}`);
/** A day number for an ISO date (for spacing by date). */
export const dayNumber = (iso) => {
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso ?? ""));
return m ? Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) / 86400000 : NaN;
};
// ---------------------------------------------------------------------------
// The measure, read into what changes when.
// ---------------------------------------------------------------------------
/** The index of the state in force at cut second `t` (the last with state.t <= t). */
export function stateIndexAt(states, t) {
let lo = 0, hi = states.length - 1, ans = 0;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (states[mid].t <= t + 1e-9) { ans = mid; lo = mid + 1; } else hi = mid - 1;
}
return ans;
}
const sameCurrent = (a, b) => (a?.row ?? null) === (b?.row ?? null) && (a?.value ?? null) === (b?.value ?? null) && (a?.qualifier ?? null) === (b?.qualifier ?? null);
const sameGoal = (a, b) => (a?.row ?? null) === (b?.row ?? null) && (a?.value ?? null) === (b?.value ?? null);
const sameNet = (a, b) => (a?.from?.row ?? null) === (b?.from?.row ?? null) && (a?.to?.row ?? null) === (b?.to?.row ?? null) &&
(a?.from?.value ?? null) === (b?.from?.value ?? null) && (a?.to?.value ?? null) === (b?.to?.value ?? null);
/**
* The measure read once: each thing an instrument draws, as the list of times
* it changes, from the states (`measure.state`, sorted by t, the first at 0).
*
* - `current`: each stated weight in force, from its `t` (the first entry
* the state before any, `value: null`), with the date of the weighing
* (the event's `asOf`, else its date);
* - `remembered`: each remembered weight as it is first said;
* - `goals`: each latest goal (null when none), from its `t`;
* - `lost`: the odometer's total from each `t` -- the running HIGHEST, so it
* only ever goes up -- and its runs;
* - `net`: NET from each `t` it changes;
* - `under`: each "under 300" claim (`totals.under300.rows`) the cut shows;
* - `stated`: every stated weight the cut shows, for the trail (by date).
*/
export function measureTrack(measure) {
const states = Array.isArray(measure?.state) && measure.state.length ? measure.state : [{ t: 0 }];
const events = Array.isArray(measure?.events) ? measure.events : [];
const byRow = new Map(events.map((e) => [e.row, e]));
const current = [];
const remembered = [];
const goals = [];
const lost = [];
const net = [];
states.forEach((s, i) => {
const prev = i ? states[i - 1] : null;
const t = i ? Number(s.t) : 0;
if (!i || !sameCurrent(prev.current, s.current)) {
const c = s.current ?? null;
const ev = c ? byRow.get(c.row) : null;
const range = Array.isArray(c?.range) ? c.range : Array.isArray(ev?.range) ? ev.range : null;
current.push({ t, value: c?.value ?? null, qualifier: c?.qualifier ?? null, row: c?.row ?? null, date: ev?.asOf ?? c?.date ?? null, ...(range ? { range } : {}) });
}
const rem = Array.isArray(s.remembered) ? s.remembered : [];
const had = prev && Array.isArray(prev.remembered) ? prev.remembered.length : 0;
for (let j = had; j < rem.length; j += 1) {
const ev = byRow.get(rem[j].row);
const range = Array.isArray(rem[j].range) ? rem[j].range : Array.isArray(ev?.range) ? ev.range : null;
// How many times he has told this start so far (the moving start's count, on the dial's ghost: "told 5×").
const told = remembered.filter((r) => Math.abs(r.value - rem[j].value) < 0.05).length + 1;
remembered.push({ t, value: rem[j].value, asOf: rem[j].asOf ?? null, row: rem[j].row, qualifier: ev?.qualifier ?? rem[j].qualifier ?? null, told, ...(range ? { range } : {}) });
}
if (!i || !sameGoal(prev.goal, s.goal)) goals.push({ t, goal: s.goal ?? null });
const total = Number(s.lost?.total) || 0;
const top = lost.length ? lost[lost.length - 1].total : 0;
const runs = Array.isArray(s.lost?.runs) ? s.lost.runs.length : 0;
if (!i) lost.push({ t, total: Math.max(0, total), runs });
else if (total > top + 1e-9 || runs !== lost[lost.length - 1].runs) lost.push({ t, total: Math.max(top, total), runs });
if (!i || !sameNet(prev.net, s.net)) net.push({ t, net: s.net ?? null });
});
const underRows = new Set(measure?.totals?.under300?.rows ?? []);
const under = events.filter((e) => underRows.has(e.row) && Number.isFinite(e.t)).map((e) => ({ t: e.t, row: e.row }));
const stated = events
.filter((e) => e.kind === "stated" && Number.isFinite(e.value) && Number.isFinite(e.t))
.map((e) => ({ t: e.t, row: e.row, value: e.value, qualifier: e.qualifier ?? null, date: e.asOf ?? e.date }));
return { current, remembered, goals, lost, net, under, stated };
}
// ---------------------------------------------------------------------------
// The dial.
// ---------------------------------------------------------------------------
/** The dial's sweep: the scale's min at A0, its max at A1, degrees clockwise from 12 o'clock. */
export const DIAL_SWEEP = Object.freeze({ a0: -135, a1: 135 });
/** A weight's angle on a dial of `scale` ({min, max}), clamped to the sweep. */
export function dialAngle(v, scale) {
const { min, max } = scale;
const c = Math.max(min, Math.min(max, v));
return DIAL_SWEEP.a0 + ((c - min) / (max - min)) * (DIAL_SWEEP.a1 - DIAL_SWEEP.a0);
}
/** The point at `deg` (clockwise from 12 o'clock) and radius `r` about (cx, cy). */
export function polar(cx, cy, r, deg) {
const a = ((deg - 90) * Math.PI) / 180;
return [r2(cx + r * Math.cos(a)), r2(cy + r * Math.sin(a))];
}
/** An annular sector's path, from `a0` to `a1` degrees between radii r0 < r1. */
export function sectorPath(cx, cy, r0, r1, a0, a1) {
const [p, q] = [polar(cx, cy, r1, a0), polar(cx, cy, r1, a1)];
const [s, t] = [polar(cx, cy, r0, a1), polar(cx, cy, r0, a0)];
const lg = Math.abs(a1 - a0) > 180 ? 1 : 0;
return `M${p} A${r1},${r1} 0 ${lg} 1 ${q} L${s} A${r0},${r0} 0 ${lg} 0 ${t}Z`;
}
/**
* A weight's wedge, in pounds: a RANGE he gave, the range itself ("330-340");
* else a qualifier's -- "≈" 3 under to 1 over, ">" 10 up, "<" 10 down.
*/
export function wedgeRange(value, q, range = null) {
if (Array.isArray(range) && range.length === 2 && range[1] > range[0]) return [range[0], range[1]];
if (q === "≈") return [value - 3, value + 1];
if (q === ">") return [value, value + 10];
if (q === "<") return [value - 10, value];
return null;
}
/**
* The dial face's scale figures -- a label every 20 lb and the mark's -- where
* dialFaceSvg draws them: each its value, its anchor (`x` its middle, `y` its
* baseline), its font size and its `box` in the face's px. The box is the
* glyphs' estimate, a little generous (a digit of the condensed face is about
* half an em wide, the cap height about three quarters of one), so a word laid
* beside it on the face keeps clear of the figure whichever font is loaded.
* The one geometry for both the face and whatever must stay off its figures.
*/
export function dialFigures({ size, scale, mark = 300 }) {
const C = size / 2;
const R = C - Math.round(size * 0.012);
const Rf = R - Math.round(size * 0.026);
const u = size / 524;
const fig = (v, r, lift, font, isMark) => {
const [x, y0] = polar(C, C, r, dialAngle(v, scale));
const y = r2(y0 + lift * u), fs = r2(font * u);
const w = String(v).length * fs * 0.6;
return { v, x, y, fs, mark: isMark, box: { x0: x - w / 2, x1: x + w / 2, y0: y - fs * 0.78, y1: y + fs * 0.06 } };
};
const out = [];
for (let v = Math.ceil(scale.min / 20) * 20; v <= scale.max + 1e-9; v += 20) {
if (Number.isFinite(mark) && v === mark) continue;
out.push(fig(v, Rf - 54 * u, 8, 24, false));
}
if (Number.isFinite(mark) && mark >= scale.min && mark <= scale.max) out.push(fig(mark, Rf - 58 * u, 9, 28, true));
return out;
}
/**
* The dial face as SVG markup, `size` px square: the bezel, the face, a tick
* every 2 lb (longer every 10, longest every 20), a label every 20, the
* `mark` weight (300) accented. Static: nothing on it moves.
*/
export function dialFaceSvg({ size, scale, mark = 300, colors, labelFont = "sans-serif" }) {
const C = size / 2;
const R = C - Math.round(size * 0.012);
const Rf = R - Math.round(size * 0.026);
const u = size / 524;
const out = [];
out.push(`