charts refactored onto the shared coop_chart.js module — rendering unchanged
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/push/woodpecker Pipeline was successful
The tooltip machinery, axis steps, frames, bars, lines and hover targets move to the canonical shared module (ops-docs scripts/shared/coop_chart.js, byte-identical copy spliced into PAGE_HTML at import). PROOF of no visual change: rendered innerHTML captured across 21 chart states (5 trend metrics x 3 ranges, 2 money modes x 3 periods) is byte-identical pre/post refactor. CI: oidc + chart sync pins added to the pipeline; vendored check-page-js.sh splices the module into the extracted page JS.
This commit is contained in:
1 parent
c31f124bd1
commit
5ea2be7247
5 files changed
+412
-243
No files matched your search
@@ -31,6 +31,10 @@ steps:
|
|||||||
- name: tests
|
- name: tests
|
||||||
image: bash
|
image: bash
|
||||||
commands:
|
commands:
|
||||||
|
# Sync pins: the app copies of the shared modules are byte-identical to
|
||||||
|
# the canonical revisions in ops-docs (any hand edit goes red here).
|
||||||
|
- python3 tests/test_oidc_sync.py
|
||||||
|
- python3 tests/test_chart_sync.py
|
||||||
- python3 tests/test_guest_guard.py
|
- python3 tests/test_guest_guard.py
|
||||||
# Run every harness even when one fails, then fail the step — a plain
|
# Run every harness even when one fails, then fail the step — a plain
|
||||||
# command chain would hide all failures after the first.
|
# command chain would hide all failures after the first.
|
||||||
|
|||||||
@@ -0,0 +1,261 @@
|
|||||||
|
/* 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.
|
||||||
|
*/
|
||||||
|
(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 => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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>');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
};
|
||||||
|
})(typeof globalThis !== "undefined" ? globalThis : window);
|
||||||
+73
-241
@@ -18,6 +18,7 @@ Environment (Cloudron env vars):
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from fastapi import FastAPI, Request, HTTPException
|
from fastapi import FastAPI, Request, HTTPException
|
||||||
@@ -347,6 +348,12 @@ def render_page() -> str:
|
|||||||
return PAGE_HTML
|
return PAGE_HTML
|
||||||
|
|
||||||
|
|
||||||
|
# The shared chart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
||||||
|
# byte-identical copy at app/coop_chart.js — tests/test_chart_sync.py pins it)
|
||||||
|
# is spliced into the page's single <script> block at import time, above the
|
||||||
|
# page JS, which destructures CoOpChart into bare function names.
|
||||||
|
CHART_MODULE_JS = (Path(__file__).resolve().parent / "coop_chart.js").read_text()
|
||||||
|
|
||||||
PAGE_HTML = """<!DOCTYPE html>
|
PAGE_HTML = """<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -643,6 +650,7 @@ PAGE_HTML = """<!DOCTYPE html>
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
/*@@CHART_MODULE@@*/
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
|
|
||||||
let flashTimer = null;
|
let flashTimer = null;
|
||||||
@@ -726,11 +734,11 @@ let trendMetric = "members"; // members | spend | requests
|
|||||||
let trendDays = 90; // 0 = all time
|
let trendDays = 90; // 0 = all time
|
||||||
|
|
||||||
const TREND_CONF = {
|
const TREND_CONF = {
|
||||||
members: { kind: "line", title: "Members" },
|
members: { kind: "line", title: "Members", cont: false },
|
||||||
requests: { kind: "bar", title: "Requests per day" },
|
requests: { kind: "bar", title: "Requests per day", cont: false },
|
||||||
spend: { kind: "bar", title: "Spend per day" },
|
spend: { kind: "bar", title: "Spend per day", cont: true },
|
||||||
energy: { kind: "bar", title: "Energy per day" },
|
energy: { kind: "bar", title: "Energy per day", cont: true },
|
||||||
co2e: { kind: "bar", title: "Carbon per day" }
|
co2e: { kind: "bar", title: "Carbon per day", cont: true }
|
||||||
};
|
};
|
||||||
|
|
||||||
async function loadMetrics() {
|
async function loadMetrics() {
|
||||||
@@ -774,23 +782,6 @@ function trendVal(row) {
|
|||||||
return row.requests;
|
return row.requests;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Y-axis step. Counts are people and things, so their ticks must be whole
|
|
||||||
// numbers (a 1.08 headroom factor alone yields labels like 19.17 people).
|
|
||||||
// Money gets the classic 1/2/5 x 10^k rounding so ticks read $5.00, not $4.92.
|
|
||||||
function niceStep(raw) {
|
|
||||||
if (trendMetric === "spend" || trendMetric === "energy" || trendMetric === "co2e") {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
// Counts: whole numbers, rounded up to a half power of ten so ticks read
|
|
||||||
// 3,000 rather than 2,888. Never below 1, so a near-empty series still gets
|
|
||||||
// an integer axis instead of fractions.
|
|
||||||
const p = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1))));
|
|
||||||
return Math.max(1, Math.ceil(raw / (p / 2)) * (p / 2));
|
|
||||||
}
|
|
||||||
|
|
||||||
function trendLabel(v) {
|
function trendLabel(v) {
|
||||||
if (v === null || v === undefined) return "not measured";
|
if (v === null || v === undefined) return "not measured";
|
||||||
if (trendMetric === "spend") return fmt(v);
|
if (trendMetric === "spend") return fmt(v);
|
||||||
@@ -799,100 +790,18 @@ function trendLabel(v) {
|
|||||||
return Number(v).toLocaleString();
|
return Number(v).toLocaleString();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Chart tooltips: exact values on hover ----
|
// ---- Shared chart module ----
|
||||||
// One shared helper serves EVERY chart on the panel; no library, no CDN.
|
// Chart rendering + the exact-value hover tooltips come from the shared
|
||||||
// Contract for a chart (two steps, then tooltips just work):
|
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
||||||
// 1. At render time, stamp each hoverable data element with
|
// byte-identical copy shipped in this image and spliced in above). Destructure
|
||||||
// data-tip-host="<hostId>" and data-tip-i="<index into the data>"
|
// the pieces this page uses so call sites keep bare names. The full contract
|
||||||
// 2. registerChartTips("<hostId>", points) with one point per index:
|
// (stamp data-tip-host/i, then registerChartTips with the EXACT values) is
|
||||||
// { label: "2026-11-07", series: [["Spend", "$12.34"], ["Revenue", "$40.00"]] }
|
// documented in the module header.
|
||||||
// Values MUST come from the chart's own data arrays (exact), never
|
const {
|
||||||
// pixel-estimated, and `series` carries EVERY series at that x.
|
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
|
||||||
// A single delegated listener set on `document` then serves all charts, so
|
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
|
||||||
// re-rendering a chart's innerHTML needs no re-binding, and a new chart (the
|
drawLineRuns, hoverTargets
|
||||||
// finance chart, any future one) joins chart-by-chart as it renders. The box
|
} = CoOpChart;
|
||||||
// is a fixed-position div with pointer-events:none, clamped inside the
|
|
||||||
// viewport so it never flickers off-screen or swallows a click.
|
|
||||||
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 = document.createElement("div");
|
|
||||||
chartTipBox.className = "chart-tip";
|
|
||||||
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);
|
|
||||||
|
|
||||||
function renderTrends() {
|
function renderTrends() {
|
||||||
const host = $("trend-body");
|
const host = $("trend-body");
|
||||||
@@ -915,64 +824,27 @@ function renderTrends() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const maxV = Math.max.apply(null, have);
|
const maxV = Math.max.apply(null, have);
|
||||||
// Axis top = one round step times four ticks: labels land on round numbers
|
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, conf.cont);
|
||||||
// and the peak still clears the frame.
|
const fr = chartFrame({
|
||||||
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4);
|
n: vals.length,
|
||||||
const top = step * 4;
|
top: step * 4,
|
||||||
|
step,
|
||||||
const W = 1000, H = 250, padL = 62, padR = 14, padT = 14, padB = 30;
|
tickLabel: trendLabel,
|
||||||
const plotW = W - padL - padR, plotH = H - padT - padB;
|
aria: conf.title + " over time",
|
||||||
const baseY = padT + plotH;
|
gridStroke: "var(--border)"
|
||||||
const n = vals.length;
|
});
|
||||||
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
|
|
||||||
const yAt = v => baseY - (plotH * v) / top;
|
|
||||||
const parts = [];
|
|
||||||
|
|
||||||
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + conf.title + ' over time">');
|
|
||||||
for (let g = 0; g <= 4; g++) {
|
|
||||||
const yy = baseY - (plotH * g) / 4;
|
|
||||||
const lab = trendLabel(step * g);
|
|
||||||
parts.push('<line x1="' + padL + '" y1="' + yy + '" x2="' + (W - padR) + '" y2="' + yy + '" stroke="var(--border)"/>');
|
|
||||||
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + lab + '</text>');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (conf.kind === "bar") {
|
if (conf.kind === "bar") {
|
||||||
const bw = Math.max(1, plotW / n - 1);
|
drawBars(fr, vals, { color: "var(--green-mid)", host: "trend-body" });
|
||||||
for (let i = 0; i < n; i++) {
|
|
||||||
const v = vals[i];
|
|
||||||
if (v === null || v === undefined) continue;
|
|
||||||
const yy = yAt(v);
|
|
||||||
parts.push('<rect x="' + (xAt(i) - bw / 2) + '" y="' + yy + '" width="' + bw + '" height="' + Math.max(0.6, baseY - yy) + '" fill="var(--green-mid)" data-tip-host="trend-body" data-tip-i="' + i + '"></rect>');
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
// Break the line into contiguous measured runs: a gap stays a gap.
|
// Measured runs only: a gap stays a gap (the module breaks the line).
|
||||||
const runs = [];
|
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
|
||||||
let run = [];
|
hoverTargets(fr, vals, "trend-body");
|
||||||
for (let i = 0; i < n; 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);
|
|
||||||
for (let s = 0; s < runs.length; s++) {
|
|
||||||
const r0 = runs[s];
|
|
||||||
const pts = r0.map(i => xAt(i) + "," + yAt(vals[i])).join(" ");
|
|
||||||
parts.push('<path d="M' + xAt(r0[0]) + "," + baseY + " L" + r0.map(i => xAt(i) + "," + yAt(vals[i])).join(" L") + " L" + xAt(r0[r0.length - 1]) + "," + baseY + ' Z" fill="var(--green-deep)" fill-opacity="0.10"/>');
|
|
||||||
parts.push('<polyline points="' + pts + '" fill="none" stroke="var(--green-deep)" stroke-width="2" stroke-linejoin="round"/>');
|
|
||||||
}
|
|
||||||
for (let i = 0; i < n; i++) {
|
|
||||||
if (vals[i] === null || vals[i] === undefined) continue;
|
|
||||||
parts.push('<circle cx="' + xAt(i) + '" cy="' + yAt(vals[i]) + '" r="7" fill="transparent" data-tip-host="trend-body" data-tip-i="' + i + '"></circle>');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const marks = n > 2 ? [0, Math.floor((n - 1) / 2), n - 1] : [0, n - 1];
|
dateMarks(fr, rows.map(r => r.day));
|
||||||
for (let mi = 0; mi < marks.length; mi++) {
|
fr.parts.push("</svg>");
|
||||||
const i = marks[mi];
|
host.innerHTML = fr.parts.join("");
|
||||||
const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle");
|
|
||||||
parts.push('<text x="' + xAt(i) + '" y="' + (H - 9) + '" text-anchor="' + anchor + '" font-size="11" fill="var(--muted)">' + String(rows[i].day).slice(5) + '</text>');
|
|
||||||
}
|
|
||||||
parts.push("</svg>");
|
|
||||||
host.innerHTML = parts.join("");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Money: revenue / token spend / OC balance over time ----
|
// ---- Money: revenue / token spend / OC balance over time ----
|
||||||
@@ -1025,45 +897,13 @@ function moneyFmt(v) {
|
|||||||
return fmt(v);
|
return fmt(v);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Money ticks use the 1/2/5 x 10^k rule. Steps at or above $1 are integers;
|
// Money ticks use the 1/2/5 x 10^k rule (niceStep(raw, true) from the shared
|
||||||
// below, show cents so a $0.50 tick does not round to $1.
|
// module). Steps at or above $1 are integers; below, show cents so a $0.50
|
||||||
|
// tick does not round to $1.
|
||||||
function moneyTickLabel(v) {
|
function moneyTickLabel(v) {
|
||||||
return v >= 1 ? "$" + Math.round(v).toLocaleString() : "$" + v.toFixed(2);
|
return v >= 1 ? "$" + Math.round(v).toLocaleString() : "$" + v.toFixed(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
function moneyStep(raw) {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
function moneyFrame(rows, top, step, label) {
|
|
||||||
const W = 1000, H = 250, padL = 62, padR = 14, padT = 14, padB = 30;
|
|
||||||
const plotW = W - padL - padR, plotH = H - padT - padB;
|
|
||||||
const baseY = padT + plotH;
|
|
||||||
const n = rows.length;
|
|
||||||
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
|
|
||||||
const yAt = v => baseY - (plotH * v) / top;
|
|
||||||
const parts = [];
|
|
||||||
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + label + '">');
|
|
||||||
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="var(--border)"/>');
|
|
||||||
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + moneyTickLabel(step * g) + '</text>');
|
|
||||||
}
|
|
||||||
return { W, H, padL, padR, baseY, n, xAt, yAt, parts };
|
|
||||||
}
|
|
||||||
|
|
||||||
function moneyDateMarks(fr, rows) {
|
|
||||||
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(rows[i].day).slice(5) + '</text>');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderMoney() {
|
function renderMoney() {
|
||||||
const host = $("money-body");
|
const host = $("money-body");
|
||||||
if (!host || !moneyData) return;
|
if (!host || !moneyData) return;
|
||||||
@@ -1100,43 +940,29 @@ function renderMoneyCumulative(host, rows) {
|
|||||||
for (const r of rows) { const v = r[s.key]; if (v !== null && v !== undefined) tops.push(v); }
|
for (const r of rows) { const v = r[s.key]; if (v !== null && v !== undefined) tops.push(v); }
|
||||||
}
|
}
|
||||||
const maxV = tops.length ? Math.max.apply(null, tops) : 0;
|
const maxV = tops.length ? Math.max.apply(null, tops) : 0;
|
||||||
const step = moneyStep((maxV <= 0 ? 1 : maxV * 1.08) / 4);
|
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
|
||||||
const fr = moneyFrame(rows, step * 4, step, "Cumulative revenue, token spend and OC balance over time");
|
const fr = chartFrame({
|
||||||
|
n: rows.length,
|
||||||
|
top: step * 4,
|
||||||
|
step,
|
||||||
|
tickLabel: moneyTickLabel,
|
||||||
|
aria: "Cumulative revenue, token spend and OC balance over time"
|
||||||
|
});
|
||||||
registerChartTips("money-body", rows.map(r => ({
|
registerChartTips("money-body", rows.map(r => ({
|
||||||
label: r.day,
|
label: r.day,
|
||||||
series: series.map(s => [s.name, moneyFmt(r[s.key])])
|
series: series.map(s => [s.name, moneyFmt(r[s.key])])
|
||||||
})));
|
})));
|
||||||
for (const s of series) {
|
for (const s of series) {
|
||||||
// Contiguous measured runs: a NULL (the balance before snapshots began)
|
// Measured runs only: a NULL (the balance before snapshots began) stays a
|
||||||
// stays a gap — the line is never drawn through invented history.
|
// gap — the line is never drawn through invented history.
|
||||||
const runs = [];
|
drawLineRuns(fr, rows.map(r => r[s.key]), { color: s.color, dotSingle: true, dotR: 3 });
|
||||||
let run = [];
|
|
||||||
for (let i = 0; i < fr.n; i++) {
|
|
||||||
const v = rows[i][s.key];
|
|
||||||
if (v === null || v === undefined) { if (run.length) runs.push(run); run = []; }
|
|
||||||
else run.push(i);
|
|
||||||
}
|
|
||||||
if (run.length) runs.push(run);
|
|
||||||
for (const r0 of runs) {
|
|
||||||
const pts = r0.map(i => fr.xAt(i) + "," + fr.yAt(rows[i][s.key])).join(" ");
|
|
||||||
if (r0.length > 1) {
|
|
||||||
fr.parts.push('<polyline points="' + pts + '" fill="none" stroke="' + s.color + '" stroke-width="2" stroke-linejoin="round"/>');
|
|
||||||
} else {
|
|
||||||
// A single measured day (e.g. the first balance snapshot) still shows.
|
|
||||||
fr.parts.push('<circle cx="' + fr.xAt(r0[0]) + '" cy="' + fr.yAt(rows[r0[0]][s.key]) + '" r="3" fill="' + s.color + '"/>');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// Hover targets: one transparent circle per measured point on every series;
|
// Hover targets: one transparent circle per measured point on every series;
|
||||||
// the tooltip lists all three series at that x.
|
// the tooltip lists all three series at that x.
|
||||||
for (const s of series) {
|
for (const s of series) {
|
||||||
for (let i = 0; i < fr.n; i++) {
|
hoverTargets(fr, rows.map(r => r[s.key]), "money-body");
|
||||||
const v = rows[i][s.key];
|
|
||||||
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="money-body" data-tip-i="' + i + '"></circle>');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
moneyDateMarks(fr, rows);
|
dateMarks(fr, rows.map(r => r.day));
|
||||||
fr.parts.push("</svg>");
|
fr.parts.push("</svg>");
|
||||||
host.innerHTML = fr.parts.join("");
|
host.innerHTML = fr.parts.join("");
|
||||||
}
|
}
|
||||||
@@ -1149,20 +975,20 @@ function renderMoneyDaily(host, rows) {
|
|||||||
const have = vals.filter(v => v !== null && v !== undefined);
|
const have = vals.filter(v => v !== null && v !== undefined);
|
||||||
if (have.length < 2) { host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>"; return; }
|
if (have.length < 2) { host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>"; return; }
|
||||||
const maxV = Math.max.apply(null, have);
|
const maxV = Math.max.apply(null, have);
|
||||||
const step = moneyStep((maxV <= 0 ? 1 : maxV * 1.08) / 4);
|
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
|
||||||
const fr = moneyFrame(rows, step * 4, step, "Token spend per day");
|
const fr = chartFrame({
|
||||||
|
n: rows.length,
|
||||||
|
top: step * 4,
|
||||||
|
step,
|
||||||
|
tickLabel: moneyTickLabel,
|
||||||
|
aria: "Token spend per day"
|
||||||
|
});
|
||||||
registerChartTips("money-body", rows.map(r => ({
|
registerChartTips("money-body", rows.map(r => ({
|
||||||
label: r.day,
|
label: r.day,
|
||||||
series: [["Token spend (daily)", moneyFmt(r.spend_day)]]
|
series: [["Token spend (daily)", moneyFmt(r.spend_day)]]
|
||||||
})));
|
})));
|
||||||
const bw = Math.max(1, (fr.W - fr.padL - fr.padR) / fr.n - 1);
|
drawBars(fr, vals, { color: MONEY_COLORS.spend, host: "money-body" });
|
||||||
for (let i = 0; i < fr.n; i++) {
|
dateMarks(fr, rows.map(r => r.day));
|
||||||
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="' + MONEY_COLORS.spend + '" data-tip-host="money-body" data-tip-i="' + i + '"></rect>');
|
|
||||||
}
|
|
||||||
moneyDateMarks(fr, rows);
|
|
||||||
fr.parts.push("</svg>");
|
fr.parts.push("</svg>");
|
||||||
host.innerHTML = fr.parts.join("");
|
host.innerHTML = fr.parts.join("");
|
||||||
}
|
}
|
||||||
@@ -1529,6 +1355,12 @@ loadModels();
|
|||||||
</body>
|
</body>
|
||||||
</html>"""
|
</html>"""
|
||||||
|
|
||||||
|
# Splice the shared chart module into the page's single <script> block. The
|
||||||
|
# placeholder is a JS comment, so the extracted-and-checked block stays valid
|
||||||
|
# even before the splice (check-page-js.sh performs the same splice when it
|
||||||
|
# runs the harnesses).
|
||||||
|
PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(HTTPException)
|
@app.exception_handler(HTTPException)
|
||||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||||
|
|||||||
+14
-2
@@ -38,8 +38,20 @@ html = src[start:src.index('"""', start)]
|
|||||||
blocks = re.findall(r"<script>(.*?)</script>", html, re.S)
|
blocks = re.findall(r"<script>(.*?)</script>", html, re.S)
|
||||||
if len(blocks) != 1:
|
if len(blocks) != 1:
|
||||||
sys.exit(f"expected exactly 1 <script> block in PAGE_HTML, found {len(blocks)}")
|
sys.exit(f"expected exactly 1 <script> block in PAGE_HTML, found {len(blocks)}")
|
||||||
open(sys.argv[2], "w").write(blocks[0])
|
js = blocks[0]
|
||||||
print(f"extracted {len(blocks[0])} chars of page JS from PAGE_HTML")
|
# Splice the shared chart module exactly as the app does at import time, so
|
||||||
|
# the checked/eval'd JS is what actually serves. The placeholder is a comment,
|
||||||
|
# and a missing module file leaves the placeholder in place (the harness then
|
||||||
|
# fails loudly on the missing CoOpChart instead of silently checking stale JS).
|
||||||
|
from pathlib import Path
|
||||||
|
placeholder = "/*@@CHART_MODULE@@*/"
|
||||||
|
if placeholder in js:
|
||||||
|
module = Path(sys.argv[1]).resolve().parent / "coop_chart.js"
|
||||||
|
if module.exists():
|
||||||
|
js = js.replace(placeholder, module.read_text())
|
||||||
|
print(f"spliced shared chart module ({module.name}) into the extracted page JS")
|
||||||
|
open(sys.argv[2], "w").write(js)
|
||||||
|
print(f"extracted {len(js)} chars of page JS from PAGE_HTML")
|
||||||
PY
|
PY
|
||||||
|
|
||||||
node --check "$TMP/page.js"
|
node --check "$TMP/page.js"
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""coop_chart.js sync pin — the repo copy is byte-identical to the canonical
|
||||||
|
module, and main.py splices it into the served page.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
app/coop_chart.js is a byte-identical copy of the canonical module
|
||||||
|
(co-op/ops-docs repo: scripts/shared/coop_chart.js) — the single source for
|
||||||
|
the hand-rolled chart rendering + hover tooltips both UIs ship. This test
|
||||||
|
pins the copy to the canonical revision recorded below: ANY hand edit to
|
||||||
|
app/coop_chart.js breaks the pin and goes red. To change the module, edit
|
||||||
|
the canonical file and run ops-docs/scripts/sync-chart-module.sh, which
|
||||||
|
re-copies and re-pins both repos in one step (check-chart-sync.py is the
|
||||||
|
pre-deploy gate).
|
||||||
|
|
||||||
|
Generated by sync-chart-module.sh — do not edit by hand.
|
||||||
|
|
||||||
|
Run: python3 tests/test_chart_sync.py
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
CANONICAL_SHA256 = "a029fd40189acc38b8b218921c56e24e0208c8c8e0ab550a320bbd57449f5fed"
|
||||||
|
SPLICE = 'PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)'
|
||||||
|
|
||||||
|
failures = []
|
||||||
|
|
||||||
|
copy = ROOT / "app" / "coop_chart.js"
|
||||||
|
if not copy.exists():
|
||||||
|
failures.append("app/coop_chart.js missing")
|
||||||
|
else:
|
||||||
|
got = hashlib.sha256(copy.read_bytes()).hexdigest()
|
||||||
|
if got == CANONICAL_SHA256:
|
||||||
|
print(f"ok - app/coop_chart.js matches the pinned canonical revision ({got[:16]}…)")
|
||||||
|
else:
|
||||||
|
failures.append(
|
||||||
|
"app/coop_chart.js DRIFTED from the pinned canonical revision\n"
|
||||||
|
f" pinned {CANONICAL_SHA256}\n"
|
||||||
|
f" actual {got}\n"
|
||||||
|
" fix: edit the canonical module (ops-docs: scripts/shared/coop_chart.js) "
|
||||||
|
"and run ops-docs/scripts/sync-chart-module.sh — never hand-edit the copy.")
|
||||||
|
|
||||||
|
main_src = (ROOT / "app" / "main.py")
|
||||||
|
if not main_src.exists():
|
||||||
|
failures.append("app/main.py missing")
|
||||||
|
else:
|
||||||
|
msrc = main_src.read_text()
|
||||||
|
if SPLICE not in msrc:
|
||||||
|
failures.append(
|
||||||
|
"app/main.py does not splice the shared chart module into PAGE_HTML:\n"
|
||||||
|
f" expected literal: {SPLICE}")
|
||||||
|
if 'parent / "coop_chart.js"' not in msrc:
|
||||||
|
failures.append("app/main.py does not load app/coop_chart.js")
|
||||||
|
|
||||||
|
if failures:
|
||||||
|
print()
|
||||||
|
print("FAILED: " + ", ".join(failures))
|
||||||
|
sys.exit(1)
|
||||||
|
print("chart sync pin: OK")
|
||||||
Reference in new issue
Block a user