network-monitor/app/static/js/charts.js
neil 54a765510a Network monitor: hub, probes, Docker and native installers
Hub (FastAPI + no-build web UI):
- Network health: live probe/target matrix, status strips, incidents
- Probes: add (with install command), rename, remove, latency and throughput charts
- Clients merged from AdGuard, DHCP, query log and probe ARP tables; names,
  categories, suspicious flag, notes, per-client DNS requests
- Query log, domain detail (clients, related subdomains), blocked domains via
  the AdGuard Home /control API

Probe: tests peers (ping, HTTP, throughput), gateway, LAN and public DNS,
internet URLs and an optional VPS; buffers results while the hub is down.
Gateway and ARP from /proc/net on Linux, route/arp on macOS.

Install: install.sh (hub) and install-probe.sh (generated from it), each in
docker mode (compose; default on Linux hosts) or native mode (venv + systemd
or launchd; default on macOS and in LXC). Both modes deploy with an update
command that checks the new commit and rolls back on failure.

CLAUDE.md carries shared context for Claude Code sessions on each machine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 18:10:29 -08:00

214 lines
9.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Inline SVG / HTML charts on the house tokens: status strips, line charts, stacked bars,
// plus one shared tooltip. Labels go in with textContent only.
import { el } from './ui.js';
const NS = 'http://www.w3.org/2000/svg';
export function s(tag, attrs = {}, ...kids) {
const n = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v != null) n.setAttribute(k, v);
for (const c of kids.flat()) if (c != null) n.append(c);
return n;
}
// ---------- status ----------
export const STATUS = {
ok: { label: 'OK', chip: 'ok' },
degraded: { label: 'Degraded', chip: 'warn' },
down: { label: 'Down', chip: 'danger' },
nodata: { label: 'No data', chip: '' },
};
export function statusChip(st, text) {
const x = STATUS[st] || STATUS.nodata;
return el(`span.chip${x.chip ? `.${x.chip}` : ''}`, {}, text || x.label);
}
export function statusLegend() {
return el('div.viz-legend', { 'aria-label': 'Legend' },
...['ok', 'degraded', 'down', 'nodata'].map((k) => el('span.viz-legend-item', {}, el(`span.viz-swatch.s-${k}`), STATUS[k].label)));
}
export function seriesLegend(items, kind = 'line') {
return el('div.viz-legend', {},
...items.map((it) => el('span.viz-legend-item', {}, el(`span.${kind === 'line' ? 'viz-linekey' : 'viz-swatch'}`, { style: `background:${it.color}` }), it.name)));
}
// ---------- tooltip ----------
let tip;
export function showTip(x, y, content) {
if (!tip) {
tip = el('div.viz-tip', { role: 'tooltip', hidden: true });
document.body.append(tip);
}
tip.replaceChildren(...content.filter(Boolean));
tip.hidden = false;
const r = tip.getBoundingClientRect();
let left = x + 14;
if (left + r.width > innerWidth - 8) left = x - 14 - r.width;
let top = y + 14;
if (top + r.height > innerHeight - 8) top = y - 14 - r.height;
tip.style.left = `${Math.max(8, left)}px`;
tip.style.top = `${Math.max(8, top)}px`;
}
export function hideTip() { if (tip) tip.hidden = true; }
export const tipTitle = (t) => el('div.viz-tip-title', {}, t);
export const tipRow = (value, label, color, kind = 'line') =>
el('div.viz-tip-row', {}, color ? el(`span.${kind === 'line' ? 'viz-linekey' : 'viz-swatch'}`, { style: `background:${color}` }) : null,
el('strong', {}, value), label ? el('span.muted', {}, label) : null);
function hover(target, describe) {
target.addEventListener('pointermove', (e) => { const c = describe(e); if (c) showTip(e.clientX, e.clientY, c); else hideTip(); });
target.addEventListener('pointerleave', hideTip);
}
// ---------- status strip: one cell per time bucket ----------
/** buckets: [{s, n, down, slow, latency} | null]; describe(i, bucket) -> tooltip nodes */
export function strip(buckets, describe) {
const n = buckets.length;
const wrap = el('div.strip', { style: `--n:${n}` });
for (const b of buckets) wrap.append(el(`span.s-${b ? b.s : 'nodata'}`));
hover(wrap, (e) => {
const r = wrap.getBoundingClientRect();
const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * n)));
return describe(i, buckets[i]);
});
return wrap;
}
// ---------- responsive SVG helper ----------
function responsive(draw, height) {
const box = el('div.chart', { style: `height:${height}px` });
let last = 0;
const ro = new ResizeObserver(() => {
const w = Math.floor(box.clientWidth);
if (w && w !== last) { last = w; box.replaceChildren(draw(w)); }
});
ro.observe(box);
return box;
}
function niceMax(v) {
if (!(v > 0)) return 1;
const p = 10 ** Math.floor(Math.log10(v));
for (const m of [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (v <= m * p) return m * p;
return 10 * p;
}
// ---------- line chart ----------
/**
* lineChart({ n, xLabel(i), series: [{name, color, values}], marks: [count per bucket],
* fmt(v), height, describe(i) -> extra tooltip nodes })
* Gaps (null) break the line. `marks` draws failure ticks along the baseline.
*/
export function lineChart(o) {
const H = o.height || 150;
return responsive((W) => {
const padL = 48, padR = o.series.length > 1 ? 64 : 14, padT = 10, padB = 24;
const iw = Math.max(10, W - padL - padR), ih = H - padT - padB;
const n = o.n;
const all = o.series.flatMap((x) => x.values).filter((v) => v != null);
const max = niceMax(Math.max(0, ...all));
const x = (i) => padL + ((i + 0.5) / n) * iw;
const y = (v) => padT + ih - (v / max) * ih;
const g = s('svg', { width: W, height: H, viewBox: `0 0 ${W} ${H}`, class: 'viz', role: 'img', 'aria-label': o.label || 'Chart' });
for (const t of [0, max / 2, max]) {
g.append(s('line', { x1: padL, x2: padL + iw, y1: y(t), y2: y(t), class: t === 0 ? 'viz-axis' : 'viz-grid' }));
g.append(s('text', { x: padL - 6, y: y(t), dy: '0.32em', 'text-anchor': 'end', class: 'viz-tick' }, o.fmt(t)));
}
for (const i of [0, Math.floor((n - 1) / 2), n - 1]) {
g.append(s('text', { x: x(i), y: H - 6, 'text-anchor': i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle', class: 'viz-tick' }, o.xLabel(i)));
}
(o.marks || []).forEach((m, i) => {
if (m) g.append(s('rect', { x: x(i) - 1.5, y: padT + ih - 7, width: 3, height: 7, rx: 1, class: 'viz-fail' }));
});
const labels = [];
for (const ser of o.series) {
let d = '';
ser.values.forEach((v, i) => {
if (v == null) return;
const prev = ser.values[i - 1];
d += `${prev == null ? 'M' : 'L'}${x(i).toFixed(1)},${y(v).toFixed(1)}`;
const next = ser.values[i + 1];
if (prev == null && next == null) g.append(s('circle', { cx: x(i), cy: y(v), r: 2.5, fill: ser.color }));
});
if (d) g.append(s('path', { d, fill: 'none', stroke: ser.color, 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' }));
const li = ser.values.findLastIndex((v) => v != null);
if (o.series.length > 1 && li >= 0) labels.push({ y: y(ser.values[li]), text: ser.name, x: x(li) });
}
// Direct end labels; skip any that would collide (the legend still names it).
labels.sort((a, b) => a.y - b.y);
let lastY = -99;
for (const l of labels) {
if (l.y - lastY < 13) continue;
lastY = l.y;
g.append(s('text', { x: padL + iw + 6, y: l.y, dy: '0.32em', class: 'viz-label' }, l.text));
}
const cross = s('line', { y1: padT, y2: padT + ih, class: 'viz-cross', visibility: 'hidden' });
const hit = s('rect', { x: padL, y: 0, width: iw, height: H, fill: 'transparent' });
g.append(cross, hit);
hit.addEventListener('pointermove', (e) => {
const r = hit.getBoundingClientRect();
const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * n)));
cross.setAttribute('x1', x(i)); cross.setAttribute('x2', x(i)); cross.setAttribute('visibility', 'visible');
showTip(e.clientX, e.clientY, [tipTitle(o.xLabel(i, true)),
...o.series.map((ser) => tipRow(ser.values[i] == null ? 'no data' : o.fmt(ser.values[i]), o.series.length > 1 ? ser.name : '', ser.color)),
...(o.describe ? o.describe(i) : [])]);
});
hit.addEventListener('pointerleave', () => { cross.setAttribute('visibility', 'hidden'); hideTip(); });
return g;
}, H);
}
// ---------- stacked bars ----------
function topRounded(x, y, w, h, r) {
r = Math.min(r, h, w / 2);
return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`;
}
/** stackedBars({ n, xLabel(i), series: [{name, color, values}], height }) – bottom series first. */
export function stackedBars(o) {
const H = o.height || 150;
return responsive((W) => {
const padL = 40, padR = 10, padT = 10, padB = 24;
const iw = Math.max(10, W - padL - padR), ih = H - padT - padB;
const n = o.n;
const totals = Array.from({ length: n }, (_, i) => o.series.reduce((a, ser) => a + (ser.values[i] || 0), 0));
const max = niceMax(Math.max(1, ...totals));
const slot = iw / n, bw = Math.min(24, slot * 0.7);
const y = (v) => padT + ih - (v / max) * ih;
const g = s('svg', { width: W, height: H, viewBox: `0 0 ${W} ${H}`, class: 'viz', role: 'img', 'aria-label': o.label || 'Chart' });
for (const t of [0, max / 2, max]) {
g.append(s('line', { x1: padL, x2: padL + iw, y1: y(t), y2: y(t), class: t === 0 ? 'viz-axis' : 'viz-grid' }));
g.append(s('text', { x: padL - 6, y: y(t), dy: '0.32em', 'text-anchor': 'end', class: 'viz-tick' }, Math.round(t).toLocaleString()));
}
for (const i of [0, Math.floor((n - 1) / 2), n - 1]) {
g.append(s('text', { x: padL + slot * (i + 0.5), y: H - 6, 'text-anchor': i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle', class: 'viz-tick' }, o.xLabel(i)));
}
for (let i = 0; i < n; i++) {
const bx = padL + slot * i + (slot - bw) / 2;
let acc = 0;
const segs = o.series.map((ser) => ({ ser, v: ser.values[i] || 0 })).filter((x) => x.v > 0);
segs.forEach((seg, k) => {
const y0 = y(acc), y1 = y(acc + seg.v);
const gap = k > 0 ? 2 : 0;
const h = Math.max(0, y0 - y1 - gap);
const top = k === segs.length - 1;
g.append(top ? s('path', { d: topRounded(bx, y1, bw, h, 4), fill: seg.ser.color }) : s('rect', { x: bx, y: y1, width: bw, height: h, fill: seg.ser.color }));
acc += seg.v;
});
const hit = s('rect', { x: padL + slot * i, y: padT, width: slot, height: ih, fill: 'transparent', class: 'viz-hit' });
hover(hit, () => [tipTitle(o.xLabel(i, true)), ...o.series.map((ser) => tipRow((ser.values[i] || 0).toLocaleString(), ser.name, ser.color, 'box'))]);
g.append(hit);
}
return g;
}, H);
}