import m from '@garage44/mithril' import {Measured} from '@/components/measured' import {day} from '@/lib/format' import {local} from '@/lib/reactive' /* * The history's charts: hand-drawn SVG, drawn at the container's width. * Colour by job — a series colour is an entity's (a machine's), status colours * are only for state — text in the text tokens, a recessive grid, and a * tooltip on every mark (hover, or a tap on a phone). */ /** The categorical slots, in their fixed order (see app.css `--series-*`). */ export const SERIES = ['var(--series-1)', 'var(--series-2)', 'var(--series-3)', 'var(--series-4)'] const PAD = {top: 12, right: 12, bottom: 26, left: 44} /** A round axis maximum and its ticks. */ function niceScale(max: number, ticks = 4): number[] { if (!(max > 0)) return [0, 1] const raw = max / ticks const mag = 10 ** Math.floor(Math.log10(raw)) const step = [1, 2, 2.5, 5, 10].map((s) => s * mag).find((s) => s >= raw)! const out: number[] = [] for (let v = 0; v <= max + step * 0.001; v += step) out.push(v) if (out[out.length - 1]! < max) out.push(out[out.length - 1]! + step) return out } /** A bar whose top end is rounded and whose foot sits square on the baseline. */ function barPath(x: number, y: number, w: number, h: number, r = 4): string { if (h <= 0) return '' const rr = Math.min(r, w / 2, h) return `M${x},${y + h}V${y + rr}Q${x},${y} ${x + rr},${y}H${x + w - rr}Q${x + w},${y} ${x + w},${y + rr}V${y + h}Z` } interface Tip { x: number y: number lines: string[] } abstract class Chart extends Measured { private st = local({tip: null as Tip | null}) get tip(): Tip | null { return this.st.tip } set tip(t: Tip | null) { this.st.tip = t } show(x: number, y: number, lines: string[]) { this.tip = {x, y, lines} } hide() { this.tip = null } /** The hit area for one mark: bigger than the mark, hover or tap. */ hit(x: number, y: number, w: number, h: number, tx: number, ty: number, lines: string[]) { return ( this.show(tx, ty, lines)} onpointerleave={() => this.hide()} onclick={() => this.show(tx, ty, lines)} /> ) } frame(height: number, svg: m.Children, legend?: m.Children) { return ( this.hide()}> {legend} {this.width > 0 ? ( {svg} ) : null} {this.tip ? ( {this.tip.lines.map((l, i) => (i === 0 ? {l} : {l}))} ) : null} ) } axisY(ticks: number[], y: (v: number) => number, label: (v: number) => string) { return ticks.map((t) => ( {label(t)} )) } /** Date labels under the plot (or what `label` calls each), thinned to what fits. */ axisX(dayKeys: number[], x: (d: number) => number, label: (d: number) => string = (d) => day(new Date(d * 1000))) { const every = Math.max(1, Math.ceil(dayKeys.length / Math.max(1, Math.floor((this.width - PAD.left) / 64)))) return dayKeys .filter((_, i) => (dayKeys.length - 1 - i) % every === 0) .map((d) => ( {label(d)} )) } abstract height(): number } export interface Legend { label: string color: string } export function legend(items: Legend[]) { if (items.length < 2) return null return ( {items.map((i) => ( {i.label} ))} ) } export interface BarsAttrs { days: number[] /** One entry per series, stacked bottom to top in this order. */ series: Legend[] /** The value of each series on each day, same order as `series`. */ value: (day: number) => number[] format: (v: number) => string /** The axis' labels, when `format` is too wide for it: `format` otherwise. */ axis?: (v: number) => string /** Extra tooltip lines for a day, under the per-series values. */ note?: (day: number) => string[] /** What to call each of `days` when they are not days (hours of the day): a date otherwise. */ label?: (day: number) => string } /** Values per day as bars, stacked when there is more than one series. */ export class Bars extends Chart { height() { return 180 } view({attrs}: m.Vnode) { const h = this.height() const plotW = this.width - PAD.left - PAD.right const band = plotW / Math.max(1, attrs.days.length) const barW = Math.max(2, Math.min(28, band - 2)) const values = attrs.days.map((d) => attrs.value(d)) const ticks = niceScale(Math.max(0, ...values.map((v) => v.reduce((a, b) => a + b, 0)))) const top = ticks[ticks.length - 1]! const y = (v: number) => PAD.top + (h - PAD.top - PAD.bottom) * (1 - v / top) const x = (d: number) => PAD.left + band * (attrs.days.indexOf(d) + 0.5) const marks = attrs.days.map((d, i) => { const v = values[i]! let base = 0 const parts = v.map((value, s) => { if (value <= 0) return null const y0 = y(base) base += value // A 2px surface gap between stacked segments. const y1 = y(base) const isTop = v.slice(s + 1).every((n) => n <= 0) const bx = x(d) - barW / 2 return isTop ? ( 0 ? 2 : 0)))} fill={attrs.series[s]!.color} /> ) : ( 0 ? 2 : 0))} fill={attrs.series[s]!.color} /> ) }) const total = v.reduce((a, b) => a + b, 0) const lines = [ attrs.label ? attrs.label(d) : day(new Date(d * 1000)), ...(attrs.series.length > 1 ? attrs.series.map((s, k) => `${s.label}: ${attrs.format(v[k]!)}`) : [attrs.format(total)]), ...(attrs.note?.(d) ?? []), ] return ( {parts} {this.hit(x(d) - band / 2, PAD.top, band, h - PAD.top - PAD.bottom, x(d), y(total) - 8, lines)} ) }) return this.frame( h, [ ...this.axisY(ticks, y, attrs.axis ?? attrs.format), , ...marks, ...this.axisX(attrs.days, x, attrs.label), ], legend(attrs.series), ) } } export interface LinesAttrs { /** One entry per series. */ series: Legend[] /** Each series' points, `[time (s), value]`, oldest first; same order as `series`. */ points: [number, number][][] from: number to: number /** The spacing of the points: a longer gap is drawn as a break in the line. */ step: number format: (v: number) => string /** What to call a time in the tooltip, and on the axis unless `tick` says. */ label: (t: number) => string /** What to call a time on the axis, when shorter than `label` (a date without its time). */ tick?: (t: number) => string /** Moments drawn as a dashed line across the plot (a deploy), each with its tooltip; the first line is its tag. */ marks?: {t: number; lines: string[]}[] /** Spans shaded behind the lines (a service down), `[from, to]`. */ spans?: [number, number][] /** The plot's height, 180 unless said. */ tall?: number } /** Values over time as lines, one per series, broken where a series has no points. */ export class Lines extends Chart { tall = 180 height() { return this.tall } view({attrs}: m.Vnode) { this.tall = attrs.tall ?? 180 const h = this.height() const span = Math.max(1, attrs.to - attrs.from) const plotW = this.width - PAD.left - PAD.right const ticks = niceScale(Math.max(0, ...attrs.points.flat().map((p) => p[1]))) const top = ticks[ticks.length - 1]! const y = (v: number) => PAD.top + (h - PAD.top - PAD.bottom) * (1 - v / top) const x = (t: number) => PAD.left + (plotW * (t - attrs.from)) / span const lines = attrs.points.map((pts, s) => { let d = '' pts.forEach(([t, v], i) => { const gap = i === 0 || t - pts[i - 1]![0] > 2 * attrs.step d += `${gap ? 'M' : 'L'}${x(t).toFixed(1)},${y(v).toFixed(1)}` }) return }) // A hit band per slot of `step` (of several, past 288 of them), with each series' first value there. const slotStep = attrs.step * Math.max(1, Math.ceil(span / attrs.step / 288)) const slots = Math.ceil(span / slotStep) const band = (plotW * slotStep) / span const hits = Array.from({length: slots}, (_, i) => { const t0 = attrs.from + i * slotStep const vals = attrs.points.map((pts) => pts.find(([t]) => t >= t0 && t < t0 + slotStep)?.[1]) if (vals.every((v) => v == null)) return null const high = Math.max(...vals.map((v) => v ?? 0)) const lines = [ attrs.label(t0), ...attrs.series.flatMap((s, k) => (vals[k] == null ? [] : [`${s.label}: ${attrs.format(vals[k]!)}`])), ] return this.hit(PAD.left + i * band, PAD.top, band, h - PAD.top - PAD.bottom, x(t0 + attrs.step / 2), y(high) - 8, lines) }) // Time labels: about one per 80 px, at round hours. const hours = Math.max(1, Math.ceil(span / 3600 / Math.max(1, Math.floor(plotW / 80)))) const marks: number[] = [] for (let t = Math.ceil(attrs.from / 3600) * 3600; t <= attrs.to; t += 3600) { // Not so near an edge that the label is cut off. const near = x(t) < PAD.left + 28 || x(t) > this.width - PAD.right - 28 const at = new Date(t * 1000) // Past a day apart, at midnight every so many days. const due = hours < 24 ? at.getHours() % hours === 0 : at.getHours() === 0 && Math.round(t / 86400) % Math.ceil(hours / 24) === 0 if (due && !near) marks.push(t) } // Marks in the range, each tagged unless the last tagged one is too near for its tag to fit. let lastTag = -Infinity const shown = (attrs.marks ?? []) .filter((k) => k.t >= attrs.from && k.t <= attrs.to) .sort((a, b) => a.t - b.t) .map((k) => { const tagged = x(k.t) - lastTag >= 64 if (tagged) lastTag = x(k.t) return {...k, tagged} }) return this.frame( h, [ ...(attrs.spans ?? []).map(([a, b]) => ( )), ...this.axisY(ticks, y, attrs.format), , ...lines, ...hits, ...shown.map((k) => ( {k.tagged ? ( {k.lines[0]} ) : null} {this.hit(x(k.t) - 6, PAD.top - 4, 12, h - PAD.top - PAD.bottom + 4, x(k.t), PAD.top, k.lines)} )), ...marks.map((t) => ( {(attrs.tick ?? attrs.label)(t)} )), ], legend(attrs.series), ) } }