Files
member-dashboard/app/coop_chart.js
T
inference-admin c5d4677ec3 chart module: re-pin to the canonical revision that adds the definition layer
Same byte-identical module as the panel; the dashboard's own port to the shared
definitions is the next commit. check-page-js.sh's DOM stub now supports
setAttribute/insertAdjacentHTML, which the shared metric-button builder needs.
2026-11-13 20:55:52 +00:00

422 lines
20 KiB
JavaScript

/* Inference Cooperative — shared hand-rolled chart module.
*
* Canonical copy: co-op/ops-docs repo, scripts/shared/coop_chart.js.
* Byte-identical copies ship in admin-panel/app/ and member-dashboard/app/
* (each repo's tests/test_chart_sync.py pins its copy to this revision — CI
* has no ops-docs checkout). Editing a copy by hand is a dead end: edit the
* canonical file and run ops-docs/scripts/sync-chart-module.sh, which
* re-copies and re-pins both repos in one step.
*
* No chart library, no CDN (the co-op's no-external-dependency rule applies
* to charts like everything else). Colors come from each app's CSS vars, so a
* chart matches the tables around it. The module exposes ONE global,
* CoOpChart; each app's page JS destructures the pieces it needs, so call
* sites keep their bare function names.
*
* Tooltips — exact values on hover (the panel's registerChartTips contract):
* 1. At render time, stamp each hoverable data element with
* data-tip-host="<hostId>" and data-tip-i="<index into the data>"
* 2. registerChartTips("<hostId>", points) with one point per index:
* { label: "2026-11-07", series: [["Spend", "$12.34"], ...] }
* Values MUST come from the chart's own data arrays (exact), never
* pixel-estimated, and `series` carries EVERY series at that x.
* One delegated listener set on document serves every chart, so innerHTML
* re-renders need no re-binding and new charts join chart-by-chart as they
* render. The box is a fixed-position div with pointer-events:none, clamped
* inside the viewport. NULL points get no stamp and no tooltip (the gap
* rule). Styling lives in each app's .chart-tip CSS block.
*
* Drawing helpers — extracted from the admin panel's chart code so both apps
* produce the same shapes from the same code:
* niceStep(raw, continuous) axis step. continuous=true: the 1/2/5 x 10^k
* rule (money, energy, carbon — ticks read $10,
* not $4.92). false: whole counts rounded up to
* a half power of ten, never below 1 (a
* 2,900-request day reads 3,000; a near-empty
* series still gets an integer axis).
* measuredRuns(vals) contiguous non-null index runs. A NULL metric
* renders as a GAP, never a zero, and the line
* is never drawn through unmeasured history.
* chartFrame(cfg) opens the SVG, draws gridlines + y labels
* (top = one round step x 4 ticks, so labels
* land on round numbers by construction).
* dateMarks(fr, days) 3 x-axis date labels (start/mid/end).
* drawBars(fr, vals, opts) bars; NULLs skipped (no zero bars).
* drawLineRuns(fr, vals, opts) lines broken into measured runs.
* hoverTargets(fr, vals, host) transparent hover circles on measured points.
*
* Definition layer — the ONE place a chart is described (both UIs read it):
* CHART_METRICS the metric list, in order: id, title, kind (line|bar|multi),
* cont (continuous axis), fmt (money|count|wh|g), val(row);
* "multi" carries `series` (the money chart). Anything a
* member may see belongs in this list.
* metricDef(id) the definition for a metric id.
* fmtMoney/fmtMetric/fmtMoneyTick shared value formatters, so both apps'
* labels match byte for byte.
* renderChart({host, def, rows, aria}) -> { svg, legend, empty? }
* one renderer for both UIs: registers the EXACT tooltip
* values, breaks lines at NULLs (a gap is never a zero), and
* returns markup plus legend items. The APP writes the DOM —
* element ids, toggle class names and empty-state markup are
* the only parts that legitimately differ per app.
*/
(function (global) {
"use strict";
// HTML escaping, self-contained: identical mapping to both apps' esc() /
// escapeHtml(), so tooltip output bytes match what each app rendered before.
function esc(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
// ---- Chart tooltips: exact values on hover ----
const chartTipData = {}; // hostId -> [{ label, series: [[name, value], ...] }]
let chartTipBox = null; // the singleton tooltip div, created on first use
let chartTipCur = null; // { host, idx } the point currently shown
function registerChartTips(hostId, points) { chartTipData[hostId] = points; }
function chartTipTarget(el) {
return el && el.closest ? el.closest("[data-tip-host]") : null;
}
function hideChartTip() {
chartTipCur = null;
if (chartTipBox) chartTipBox.style.display = "none";
}
function showChartTip(hostId, idx, cx, cy) {
const p = (chartTipData[hostId] || [])[idx];
if (!p) { hideChartTip(); return; }
if (!chartTipBox) {
chartTipBox = global.document.createElement("div");
chartTipBox.className = "chart-tip";
global.document.body.appendChild(chartTipBox);
}
const same = chartTipCur && chartTipCur.host === hostId && chartTipCur.idx === idx;
if (!same) {
let html = '<div class="tip-day">' + esc(p.label) + "</div>";
for (let s = 0; s < p.series.length; s++) {
html += '<div class="tip-row"><span>' + esc(p.series[s][0]) + "</span><b>" + esc(p.series[s][1]) + "</b></div>";
}
chartTipBox.innerHTML = html;
chartTipCur = { host: hostId, idx: idx };
}
chartTipBox.style.display = "block";
moveChartTip(cx, cy);
}
// Position beside the pointer, flipped/clamped so the box stays fully inside
// the viewport at chart edges.
function moveChartTip(cx, cy) {
if (!chartTipBox || chartTipBox.style.display === "none") return;
const pad = 12, m = 4;
const w = chartTipBox.offsetWidth, h = chartTipBox.offsetHeight;
let x = cx + pad, y = cy + pad;
if (x + w > window.innerWidth - m) x = cx - pad - w;
if (x < m) x = m;
if (y + h > window.innerHeight - m) y = cy - pad - h;
if (y < m) y = m;
chartTipBox.style.left = x + "px";
chartTipBox.style.top = y + "px";
}
document.addEventListener("pointerover", (e) => {
const t = chartTipTarget(e.target);
if (!t) return;
showChartTip(t.getAttribute("data-tip-host"), parseInt(t.getAttribute("data-tip-i"), 10), e.clientX, e.clientY);
});
document.addEventListener("pointermove", (e) => {
const t = chartTipTarget(e.target);
if (!t) return;
const host = t.getAttribute("data-tip-host");
const idx = parseInt(t.getAttribute("data-tip-i"), 10);
const cur = chartTipCur;
if (!cur || cur.host !== host || cur.idx !== idx) showChartTip(host, idx, e.clientX, e.clientY);
else moveChartTip(e.clientX, e.clientY);
});
document.addEventListener("pointerout", (e) => {
const from = chartTipTarget(e.target);
if (!from) return;
const to = e.relatedTarget ? chartTipTarget(e.relatedTarget) : null;
if (!to || to.getAttribute("data-tip-host") !== from.getAttribute("data-tip-host")) hideChartTip();
});
// Basic touch: tap/drag shows and follows, release hides it after a beat.
document.addEventListener("pointerup", (e) => {
if (e.pointerType === "touch") setTimeout(hideChartTip, 1600);
});
document.addEventListener("pointercancel", hideChartTip);
// Scrolling or resizing moves the chart under a fixed-position box - hide
// rather than show a tooltip for the wrong point.
window.addEventListener("scroll", hideChartTip, { passive: true });
window.addEventListener("resize", hideChartTip);
// ---- Axis step (see header: continuous vs count rule) ----
function niceStep(raw, continuous) {
if (continuous) {
const mag = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1e-9))));
const norm = raw / mag;
const nice = norm <= 1 ? 1 : (norm <= 2 ? 2 : (norm <= 5 ? 5 : 10));
return nice * mag;
}
const p = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1))));
return Math.max(1, Math.ceil(raw / (p / 2)) * (p / 2));
}
// ---- Contiguous measured runs: a NULL day stays a gap ----
function measuredRuns(vals) {
const runs = [];
let run = [];
for (let i = 0; i < vals.length; i++) {
if (vals[i] === null || vals[i] === undefined) { if (run.length) runs.push(run); run = []; }
else run.push(i);
}
if (run.length) runs.push(run);
return runs;
}
// ---- Frame: opens the SVG, draws gridlines + y-tick labels ----
// cfg: { n, top, step, tickLabel(v)->string, aria, W, H, padL, padR, padT,
// padB, gridStroke }. Defaults match the panel's chart geometry
// (W 1000, H 250, padL 62, padR 14, padT 14, padB 30).
// Axis top = one round step times four ticks: labels land on round numbers
// and the peak still clears the frame.
function chartFrame(cfg) {
const W = cfg.W || 1000, H = cfg.H || 250;
const padL = cfg.padL === undefined ? 62 : cfg.padL;
const padR = cfg.padR === undefined ? 14 : cfg.padR;
const padT = cfg.padT === undefined ? 14 : cfg.padT;
const padB = cfg.padB === undefined ? 30 : cfg.padB;
const plotW = W - padL - padR, plotH = H - padT - padB;
const baseY = padT + plotH;
const n = cfg.n;
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
const yAt = v => baseY - (plotH * v) / cfg.top;
const parts = [];
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + cfg.aria + '">');
for (let g = 0; g <= 4; g++) {
const yy = baseY - (plotH * g) / 4;
parts.push('<line x1="' + padL + '" y1="' + yy + '" x2="' + (W - padR) + '" y2="' + yy + '" stroke="' + (cfg.gridStroke || "var(--border)") + '"/>');
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + cfg.tickLabel(cfg.step * g) + '</text>');
}
return { W, H, padL, padR, baseY, n, xAt, yAt, parts };
}
// ---- X-axis date marks: start / middle / end, day strings YYYY-MM-DD ----
function dateMarks(fr, days) {
const marks = fr.n > 2 ? [0, Math.floor((fr.n - 1) / 2), fr.n - 1] : [0, fr.n - 1];
for (let mi = 0; mi < marks.length; mi++) {
const i = marks[mi];
const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle");
fr.parts.push('<text x="' + fr.xAt(i) + '" y="' + (fr.H - 9) + '" text-anchor="' + anchor + '" font-size="11" fill="var(--muted)">' + String(days[i]).slice(5) + '</text>');
}
}
// ---- Bars. opts: { color, host } — host stamps the elements for tooltips.
// NULL values are skipped (no zero bars, no tooltip on an unmeasured day).
function drawBars(fr, vals, opts) {
const bw = Math.max(1, (fr.W - fr.padL - fr.padR) / fr.n - 1);
for (let i = 0; i < fr.n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
const yy = fr.yAt(v);
fr.parts.push('<rect x="' + (fr.xAt(i) - bw / 2) + '" y="' + yy + '" width="' + bw + '" height="' + Math.max(0.6, fr.baseY - yy) + '" fill="' + opts.color + '"' + (opts.host ? ' data-tip-host="' + opts.host + '" data-tip-i="' + i + '"' : "") + "></rect>");
}
}
// ---- Lines broken into contiguous measured runs. opts:
// color stroke (and default fill for single-point dots)
// area draw the fill-under-line area path (panel Trends style)
// areaColor / areaOpacity area fill override (defaults: color / 0.10)
// dotSingle draw a dot (r = dotR, default 3) for a 1-point run instead of
// nothing — a single measured day still shows (money style)
function drawLineRuns(fr, vals, opts) {
const runs = measuredRuns(vals);
for (let s = 0; s < runs.length; s++) {
const r0 = runs[s];
if (opts.area) {
fr.parts.push('<path d="M' + fr.xAt(r0[0]) + "," + fr.baseY + " L" + r0.map(i => fr.xAt(i) + "," + fr.yAt(vals[i])).join(" L") + " L" + fr.xAt(r0[r0.length - 1]) + "," + fr.baseY + ' Z" fill="' + (opts.areaColor || opts.color) + '" fill-opacity="' + (opts.areaOpacity === undefined ? "0.10" : opts.areaOpacity) + '"/>');
}
if (r0.length > 1 || opts.area) {
fr.parts.push('<polyline points="' + r0.map(i => fr.xAt(i) + "," + fr.yAt(vals[i])).join(" ") + '" fill="none" stroke="' + opts.color + '" stroke-width="2" stroke-linejoin="round"/>');
} else if (opts.dotSingle) {
// A single measured day (e.g. the first balance snapshot) still shows.
fr.parts.push('<circle cx="' + fr.xAt(r0[0]) + '" cy="' + fr.yAt(vals[r0[0]]) + '" r="' + (opts.dotR === undefined ? 3 : opts.dotR) + '" fill="' + opts.color + '"/>');
}
}
}
// ---- Hover targets: one transparent circle per measured point; the
// tooltip lists every series at that x. NULL points get no stamp.
function hoverTargets(fr, vals, host) {
for (let i = 0; i < fr.n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
fr.parts.push('<circle cx="' + fr.xAt(i) + '" cy="' + fr.yAt(v) + '" r="7" fill="transparent" data-tip-host="' + host + '" data-tip-i="' + i + '"></circle>');
}
}
// ==== Chart definitions — the ONE place a chart is described ==============
// A chart is DATA here, not markup: the same metrics, in the same order, with
// the same titles and the same shape in every UI. Each app supplies its own
// data rows and its own DOM (its toggle classes, its empty-state markup, its
// legend element), which is the only thing that legitimately differs.
//
// WHY: the two UIs had drifted while sharing only the drawing primitives —
// the same five metrics shipped with different titles and different chart
// kinds (the panel's "Spend per day" was the dashboard's "What the co-op
// spent (members + the co-op's own accounts)"). Anything a member may see
// belongs in THIS list, so it exists once and cannot drift again.
//
// fmt selects the value formatter: "money" | "count" | "wh" | "g".
// kind is "line" | "bar" | "multi" (multi = N series on one axis, the money
// chart: cumulative revenue, cumulative token spend, and the OC balance,
// which only exists from the day the snapshots began, so it draws as a gap
// before that — never as a zero).
const CHART_METRICS = [
{ id: "members", title: "Members", kind: "line", cont: false, fmt: "count",
val: r => r.members_total },
{ id: "requests", title: "Requests per day", kind: "bar", cont: false, fmt: "count",
val: r => r.requests },
{ id: "spend", title: "Token spend per day", kind: "bar", cont: true, fmt: "money",
val: r => r.spend_usd },
{ id: "money", title: "Money", kind: "multi", cont: true, fmt: "money",
aria: "Cumulative revenue, token spend and OC balance over time",
series: [
{ name: "Revenue", key: "revenue_cum", color: "var(--green-deep)" },
{ name: "Token spend", key: "spend_cum", color: "#4a6a8a" },
{ name: "OC balance", key: "oc_balance", color: "#a97a2a", dotSingle: true }
] },
{ id: "energy", title: "Energy per day", kind: "bar", cont: true, fmt: "wh",
val: r => r.energy_wh },
{ id: "co2e", title: "Carbon per day", kind: "bar", cont: true, fmt: "g",
val: r => r.co2e_g }
];
function metricDef(id) {
for (let i = 0; i < CHART_METRICS.length; i++) if (CHART_METRICS[i].id === id) return CHART_METRICS[i];
return CHART_METRICS[0];
}
// ---- Value formatting (shared so the two apps' labels match byte for byte;
// both already agreed, this only stops them from diverging) ----
function fmtMoney(v) {
const n = Math.abs(Number(v)) < 0.005 ? 0 : (Number(v) || 0);
return "$" + n.toFixed(2);
}
function fmtMetric(def, v) {
if (v === null || v === undefined) return "not measured"; // the gap rule
switch (def && def.fmt) {
case "money": return fmtMoney(v);
case "wh": return Number(v).toLocaleString() + " Wh";
case "g": return Number(v).toLocaleString() + " g";
default: return Number(v).toLocaleString();
}
}
// Money-axis ticks: the 1/2/5 x 10^k rule (niceStep continuous) with integer
// dollars at or above $1 and cents below, so a $0.50 tick does not read "$1".
function fmtMoneyTick(v) {
return v >= 1 ? "$" + Math.round(v).toLocaleString() : "$" + v.toFixed(2);
}
// ---- The chart renderer: one implementation for both UIs ----
// renderChart({ host, def, rows, aria }) -> { svg, legend }
// * registers the EXACT tooltip values (the module's contract) under `host`
// * returns the SVG string and the legend items; the APP writes the DOM,
// because that is the part that differs (element ids, class names)
// * a NULL value stays a GAP: no zero, no bar, and no tooltip stamp
// `rows` for a "multi" chart carry the series keys; otherwise `def.val(row)`.
function renderChart(cfg) {
const def = cfg.def, rows = cfg.rows || [], host = cfg.host;
const legend = [];
if (def.kind === "multi") {
const series = def.series || [];
const vals = series.map(s => rows.map(r => r[s.key]));
const tops = [];
for (let si = 0; si < vals.length; si++) {
for (let i = 0; i < vals[si].length; i++) {
const v = vals[si][i];
if (v !== null && v !== undefined) tops.push(v);
}
}
const maxV = tops.length ? Math.max.apply(null, tops) : 0;
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
const fr = chartFrame({
n: rows.length, top: step * 4, step,
tickLabel: def.fmt === "money" ? fmtMoneyTick : (v => fmtMetric(def, v)),
aria: cfg.aria || def.aria || def.title,
gridStroke: cfg.gridStroke || "var(--border)"
});
registerChartTips(host, rows.map((r, i) => ({
label: r.day,
series: series.map((s, si) => [s.name, fmtMetric(def, vals[si][i])])
})));
for (let si = 0; si < series.length; si++) {
const s = series[si];
drawLineRuns(fr, vals[si], {
color: s.color, dotSingle: s.dotSingle !== false, dotR: 3,
area: !!s.area, areaOpacity: s.areaOpacity
});
hoverTargets(fr, vals[si], host);
legend.push({ color: s.color, name: s.name });
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
return { svg: fr.parts.join(""), legend };
}
const vals = rows.map(def.val);
registerChartTips(host, rows.map((r, i) => ({
label: r.day,
series: [[def.title, fmtMetric(def, vals[i])]]
})));
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) return { svg: "", legend, empty: true };
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, def.cont);
const tickLabel = v => fmtMetric(def, v);
const fr = chartFrame({
n: vals.length, top: step * 4, step, tickLabel,
aria: cfg.aria || (def.title + " over time"),
gridStroke: cfg.gridStroke || "var(--border)"
});
if (def.kind === "bar") {
drawBars(fr, vals, { color: "var(--green-mid)", host });
} else {
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
hoverTargets(fr, vals, host);
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
return { svg: fr.parts.join(""), legend };
}
// chartTipData is exported for inspection (harnesses assert on the exact
// registered points); treat it as read-only in page code.
global.CoOpChart = {
chartTipData,
registerChartTips,
chartTipTarget,
hideChartTip,
showChartTip,
moveChartTip,
niceStep,
measuredRuns,
chartFrame,
dateMarks,
drawBars,
drawLineRuns,
hoverTargets,
// the definition layer both UIs read
CHART_METRICS,
metricDef,
fmtMoney,
fmtMetric,
fmtMoneyTick,
renderChart
};
})(typeof globalThis !== "undefined" ? globalThis : window);