garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/components/charts.tsx

raw

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<A> extends Measured<A> {
    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 (
            <rect
                x={x}
                y={y}
                width={w}
                height={h}
                fill="transparent"
                onpointerenter={() => this.show(tx, ty, lines)}
                onpointerleave={() => this.hide()}
                onclick={() => this.show(tx, ty, lines)}
            />
        )
    }

    frame(height: number, svg: m.Children, legend?: m.Children) {
        return (
            <div class="chart" onpointerleave={() => this.hide()}>
                {legend}
                <div class="chart__plot" style={{height: `${height}px`}}>
                    {this.width > 0 ? (
                        <svg width={this.width} height={height} role="img">
                            {svg}
                        </svg>
                    ) : null}
                    {this.tip ? (
                        <div
                            class="chart__tip"
                            style={{
                                left: `${Math.min(Math.max(this.tip.x, 70), this.width - 70)}px`,
                                top: `${this.tip.y}px`,
                            }}
                        >
                            {this.tip.lines.map((l, i) => (i === 0 ? <b>{l}</b> : <div>{l}</div>))}
                        </div>
                    ) : null}
                </div>
            </div>
        )
    }

    axisY(ticks: number[], y: (v: number) => number, label: (v: number) => string) {
        return ticks.map((t) => (
            <g>
                <line class="chart__grid" x1={PAD.left} x2={this.width - PAD.right} y1={y(t)} y2={y(t)} />
                <text class="chart__label" x={PAD.left - 6} y={y(t) + 4} text-anchor="end">
                    {label(t)}
                </text>
            </g>
        ))
    }

    /** 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) => (
                <text class="chart__label" x={x(d)} y={this.height() - 8} text-anchor="middle">
                    {label(d)}
                </text>
            ))
    }

    abstract height(): number
}

export interface Legend {
    label: string
    color: string
}

export function legend(items: Legend[]) {
    if (items.length < 2) return null
    return (
        <ul class="chart__legend">
            {items.map((i) => (
                <li>
                    <span class="chart__swatch" style={{background: i.color}} />
                    {i.label}
                </li>
            ))}
        </ul>
    )
}

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<BarsAttrs> {
    height() {
        return 180
    }

    view({attrs}: m.Vnode<BarsAttrs>) {
        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 ? (
                    <path d={barPath(bx, y1, barW, Math.max(0, y0 - y1 - (s > 0 ? 2 : 0)))} fill={attrs.series[s]!.color} />
                ) : (
                    <rect x={bx} y={y1} width={barW} height={Math.max(0, y0 - y1 - (s > 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 (
                <g>
                    {parts}
                    {this.hit(x(d) - band / 2, PAD.top, band, h - PAD.top - PAD.bottom, x(d), y(total) - 8, lines)}
                </g>
            )
        })
        return this.frame(
            h,
            [
                ...this.axisY(ticks, y, attrs.axis ?? attrs.format),
                <line class="chart__axis" x1={PAD.left} x2={this.width - PAD.right} y1={y(0)} y2={y(0)} />,
                ...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<LinesAttrs> {
    tall = 180

    height() {
        return this.tall
    }

    view({attrs}: m.Vnode<LinesAttrs>) {
        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 <path d={d} fill="none" stroke={attrs.series[s]!.color} stroke-width={2} stroke-linejoin="round" />
        })
        // 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]) => (
                    <rect class="chart__span" x={x(Math.max(a, attrs.from))} y={PAD.top} width={Math.max(2, x(Math.min(b, attrs.to)) - x(Math.max(a, attrs.from)))} height={h - PAD.top - PAD.bottom} />
                )),
                ...this.axisY(ticks, y, attrs.format),
                <line class="chart__axis" x1={PAD.left} x2={this.width - PAD.right} y1={y(0)} y2={y(0)} />,
                ...lines,
                ...hits,
                ...shown.map((k) => (
                    <g>
                        <line class="chart__mark" x1={x(k.t)} x2={x(k.t)} y1={PAD.top - 4} y2={h - PAD.bottom} />
                        {k.tagged ? (
                            <text class="chart__marklabel" x={x(k.t) + 3} y={PAD.top + 6}>
                                {k.lines[0]}
                            </text>
                        ) : null}
                        {this.hit(x(k.t) - 6, PAD.top - 4, 12, h - PAD.top - PAD.bottom + 4, x(k.t), PAD.top, k.lines)}
                    </g>
                )),
                ...marks.map((t) => (
                    <text class="chart__label" x={x(t)} y={h - 8} text-anchor="middle">
                        {(attrs.tick ?? attrs.label)(t)}
                    </text>
                )),
            ],
            legend(attrs.series),
        )
    }
}