Files
cloud-ip-validator/internal/dashboard/static/registry-trend.js
T

154 lines
7.2 KiB
JavaScript
Raw Normal View History

/* The chart "dynamics over runs" of the registry ("registry_trend" in
registry.html): one line per target or site, one point per finished run, drawn
by the vendored Chart.js. The data comes with the loaded block (data-trend of
#registry-trend); the view (% / checks) and the period live in the address bar
(trend_view, trend_from, trend_to). Listeners sit on the document, so they keep
working after htmx replaces the block. */
(function () {
'use strict';
if (window.registryTrendBound) return;
window.registryTrendBound = true;
var STEP = 26;
var data = null, chart = null;
function view() { return document.getElementById('registry-trend-view').value === 'count' ? 'count' : 'pct'; }
function pad(n) { return (n < 10 ? '0' : '') + n; }
function utc(iso, full) {
var d = new Date(iso), s = pad(d.getUTCDate()) + '.' + pad(d.getUTCMonth() + 1);
return full ? d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + ' ' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ' UTC' : s;
}
// the top of the count axis: the most checks in any point, rounded up so that four ticks are round numbers
function niceMax(m) {
var unit = m <= 40 ? 1 : Math.pow(10, Math.floor(Math.log10(m))) / 2;
return Math.max(4, Math.ceil(m / (4 * unit)) * 4 * unit);
}
function css(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); }
// a run without checks of the target is null: a gap in the line, not a zero
function values(s, pct) {
var v = data.runs.map(function () { return null; });
s.p.forEach(function (p) { v[p[0]] = pct ? p[1] * 100 / p[2] : p[1]; });
return v;
}
function axis(opts, pct) {
var most = 0;
data.series.forEach(function (s) { s.p.forEach(function (p) { most = Math.max(most, p[2]); }); });
var top = pct ? 100 : niceMax(most), y = opts.scales.y;
y.max = top; y.ticks.stepSize = top / 4;
y.ticks.callback = function (v) { return pct ? v + '%' : v; };
}
// colours come from the theme tokens, so they are read again when the theme changes
function paint() {
if (!chart) return;
var text = css('--text-muted'), grid = css('--border-soft'), line = css('--border');
chart.data.datasets.forEach(function (d, i) { d.borderColor = d.backgroundColor = d.pointBackgroundColor = css('--tr-c' + i % 10); d.pointBorderColor = css('--surface'); });
var o = chart.options, y = o.scales.y, x = o.scales.x;
x.ticks.color = y.ticks.color = o.plugins.legend.labels.color = text;
x.grid.color = line; y.grid.color = grid;
chart.update('none');
}
function draw(root) {
var canvas = root.querySelector('canvas'), pct = view() === 'pct';
canvas.parentNode.style.minWidth = Math.max(520, data.runs.length * STEP) + 'px';
var still = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var opts = {
responsive: true, maintainAspectRatio: false, spanGaps: false,
animation: still ? false : { duration: 300 },
interaction: { mode: 'index', intersect: false },
font: { family: css('--font-mono'), size: 11 },
scales: {
x: { grid: { drawOnChartArea: false }, ticks: { maxRotation: 0 } },
y: { min: 0, ticks: {} }
},
plugins: {
legend: { labels: { boxWidth: 12, boxHeight: 3, useBorderRadius: true, borderRadius: 2 } },
tooltip: {
callbacks: {
title: function (it) { var r = data.runs[it[0].dataIndex]; return 'Запуск ' + r.id + ', ' + utc(r.at, true) + ' · адресов ' + r.n; },
label: function (c) {
var p = data.series[c.datasetIndex].p.filter(function (q) { return q[0] === c.dataIndex; })[0];
return c.dataset.label + ': успешно ' + p[1] + ' из ' + p[2] + ' · ' + Math.round(p[1] * 1000 / p[2]) / 10 + '%';
}
}
}
}
};
axis(opts, pct);
chart = new Chart(canvas, {
type: 'line',
data: {
labels: data.runs.map(function (r) { return ['#' + r.id, utc(r.at)]; }),
datasets: data.series.map(function (s, i) {
return { label: s.l, data: values(s, pct), borderWidth: 2, pointRadius: 3, pointHoverRadius: 5, tension: 0, borderDash: i >= 10 ? [6, 3] : [] };
})
},
options: opts
});
paint();
}
// the view switch only changes the values and the axis
function refresh() {
var pct = view() === 'pct';
chart.data.datasets.forEach(function (d, i) { d.data = values(data.series[i], pct); });
axis(chart.options, pct);
chart.update();
}
function init() {
var root = document.getElementById('registry-trend');
if (chart && root && root.contains(chart.canvas)) return; // htmx:load of something else
if (chart) { chart.destroy(); chart = null; } // htmx replaced the block: the old canvas is gone
if (!root || !root.dataset.trend || !window.Chart) return;
try { data = JSON.parse(root.dataset.trend); } catch (e) { return; }
draw(root);
}
function setParam(k, v) {
var u = new URL(location.href);
if (v) u.searchParams.set(k, v); else u.searchParams.delete(k);
history.replaceState(history.state, '', u);
}
// the period changes the data: keep it in the URL and reload the block
function reload() {
var panel = document.getElementById('registry-trend-panel');
if (!panel || !window.htmx) return;
var f = document.getElementById('trend-from').value, t = document.getElementById('trend-to').value, qs = new URLSearchParams(panel.dataset.qs);
qs.delete('trend_from'); qs.delete('trend_to');
if (f) qs.set('trend_from', f);
if (t) qs.set('trend_to', t);
setParam('trend_from', f); setParam('trend_to', t);
document.getElementById('trend-reset').hidden = !(f || t);
window.htmx.ajax('GET', '/registry/trend?' + qs, { target: '#registry-trend', swap: 'outerHTML' });
// the same period counts the always-pass tile
var ap = new URLSearchParams(panel.dataset.apQs);
ap.delete('trend_from'); ap.delete('trend_to');
if (f) ap.set('trend_from', f);
if (t) ap.set('trend_to', t);
window.htmx.ajax('GET', '/registry/always-pass?' + ap, { target: '#registry-always-pass', swap: 'outerHTML' });
}
document.addEventListener('click', function (e) {
var b = e.target.closest('[data-trend-view]');
if (b) {
document.getElementById('registry-trend-view').value = b.dataset.trendView;
setParam('trend_view', b.dataset.trendView);
document.querySelectorAll('[data-trend-view]').forEach(function (x) { x.setAttribute('aria-pressed', x === b ? 'true' : 'false'); });
if (chart) refresh();
} else if (e.target.closest('#trend-reset')) {
document.getElementById('trend-from').value = ''; document.getElementById('trend-to').value = '';
reload();
}
});
document.addEventListener('change', function (e) {
if (e.target.id === 'trend-from' || e.target.id === 'trend-to') reload();
});
document.addEventListener('htmx:load', init);
// the theme is switched by data-theme on <html> or by the system setting
new MutationObserver(paint).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', paint);
init();
})();