Public: anyone can read this; the crew can change it.
Observability 5: one great chart - real size, readable axes, nice ticks, palette, tooltips, synced crosshair, release marks #3725
scout/forge:scout/3694-observability-5-one-great-chart-real-siz → main 1 commit fork
9 files
changed +387
−84
src/boards/chart.ts +123 −54
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | * area, a single number with a sparkline and a heat strip are SVG; a table is |
| 5 | 5 | * HTML. The viewBox is fixed and the element carries its aspect ratio, so the |
| 6 | 6 | * space is held before the first paint and nothing shifts. Colour is |
| 7 | * `currentColor` (series are told apart by opacity and named in a legend); | |
| 7 | * `currentColor` (series wear the palette's classes `s0`..`s7` and are named in an HTML legend); | |
| 8 | 8 | * every label is stripped of what XML cannot carry, clamped, then escaped. |
| 9 | 9 | */ |
| 10 | 10 | import { escapeXml } from "../web/og/card.ts"; |
| @@ -23,12 +23,18 @@ export const usesSeries = (c: Chart) => c === "area" || c === "heat" || c === "t | ||
| 23 | 23 | |
| 24 | 24 | export const CHART_WIDTH = 720; |
| 25 | 25 | export const CHART_HEIGHT = 260; |
| 26 | const LEFT = 56; | |
| 26 | const LEFT = 64; | |
| 27 | 27 | const RIGHT = 16; |
| 28 | 28 | const TOP = 16; |
| 29 | const BOTTOM = 40; | |
| 29 | const BOTTOM = 32; | |
| 30 | 30 | const MAX_LABEL = 16; |
| 31 | 31 | const X_TICKS = 6; |
| 32 | const FONT = 12; | |
| 33 | ||
| 34 | /** A vertical mark on the time axis: a release, a roll, a config change. `label` is an x label of the chart. */ | |
| 35 | export type Mark = { label: string; text: string }; | |
| 36 | /** What a caller may say about a chart beyond its points. */ | |
| 37 | export type Opts = { unit?: string; marks?: readonly Mark[] }; | |
| 32 | 38 | |
| 33 | 39 | const clean = (s: string) => |
| 34 | 40 | s.replace(/[^\u0009\u000A\u000D --�]/gu, "").replace(/\s+/g, " ").trim(); |
| @@ -47,6 +53,44 @@ export function formatValue(v: number): string { | ||
| 47 | 53 | return num(v); |
| 48 | 54 | } |
| 49 | 55 | |
| 56 | /** A number with its unit: `$` leads, anything else trails. */ | |
| 57 | export function withUnit(v: number, unit = ""): string { | |
| 58 | const u = clamp(unit, 8); | |
| 59 | return u === "$" ? `${v < 0 ? "-" : ""}$${formatValue(Math.abs(v))}` : u === "" ? formatValue(v) : `${formatValue(v)} ${u}`; | |
| 60 | } | |
| 61 | ||
| 62 | /** Gridline values over [min(0, lo), max(0, hi)] at a 1, 2, 2.5, 5 or 10 step: 0, 25, 50 — never 22.32. */ | |
| 63 | export function niceTicks(lo: number, hi: number, count = 5): number[] { | |
| 64 | const min = Math.min(0, lo); | |
| 65 | const max = Math.max(0, hi); | |
| 66 | const raw = (max - min || 1) / count; | |
| 67 | const mag = 10 ** Math.floor(Math.log10(raw)); | |
| 68 | const f = raw / mag; | |
| 69 | const step = (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * mag; | |
| 70 | const first = Math.floor(min / step + 1e-9); | |
| 71 | const last = Math.ceil(max / step - 1e-9); | |
| 72 | const out: number[] = []; | |
| 73 | for (let i = first; i <= last; i++) out.push(Math.round(i * step * 1e9) / 1e9); | |
| 74 | return out; | |
| 75 | } | |
| 76 | ||
| 77 | const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; | |
| 78 | const ISO = /^(\d{4})-(\d\d)-(\d\d)[T ](\d\d):(\d\d)/; | |
| 79 | /** | |
| 80 | * Human time labels for ISO x labels: `14:00` within one day, `Mon 20` when | |
| 81 | * every bucket is a whole day, `Mon 20 14:00` across days. Anything that is | |
| 82 | * not a timestamp is kept as it came. | |
| 83 | */ | |
| 84 | export function humanTimes(xs: readonly string[]): string[] { | |
| 85 | const m = xs.map((x) => ISO.exec(x)); | |
| 86 | if (xs.length === 0 || m.some((r) => r === null)) return [...xs]; | |
| 87 | const when = m.map((r) => ({ d: new Date(Date.UTC(+r![1]!, +r![2]! - 1, +r![3]!)), day: `${r![1]}-${r![2]}-${r![3]}`, hm: `${r![4]}:${r![5]}` })); | |
| 88 | const dayLabel = (w: (typeof when)[number]) => `${DAYS[w.d.getUTCDay()]} ${w.d.getUTCDate()}`; | |
| 89 | if (when.every((w) => w.hm === "00:00")) return when.map(dayLabel); | |
| 90 | if (when.every((w) => w.day === when[0]!.day)) return when.map((w) => w.hm); | |
| 91 | return when.map((w) => `${dayLabel(w)} ${w.hm}`); | |
| 92 | } | |
| 93 | ||
| 50 | 94 | const W = CHART_WIDTH - LEFT - RIGHT; |
| 51 | 95 | const H = CHART_HEIGHT - TOP - BOTTOM; |
| 52 | 96 | const MAX_SERIES = 8; |
| @@ -54,75 +98,109 @@ const MAX_ROWS = 12; | ||
| 54 | 98 | const t = (s: string, n = MAX_LABEL) => escapeXml(clamp(s, n)); |
| 55 | 99 | const linked = (href: string | undefined, inner: string) => |
| 56 | 100 | href === undefined ? inner : `<a href="${escapeXml(href)}">${inner}</a>`; |
| 57 | const tip = (label: string, v: number) => `<title>${t(label, 40)}: ${escapeXml(formatValue(v))}</title>`; | |
| 58 | 101 | |
| 59 | /** The `<svg>` open tag and its title. */ | |
| 60 | const open = (title: string) => [ | |
| 61 | `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${CHART_WIDTH} ${CHART_HEIGHT}" width="${CHART_WIDTH}" height="${CHART_HEIGHT}" role="img" aria-label="${t(title, 120)}" class="chart" preserveAspectRatio="xMidYMid meet" font-size="10" font-family="inherit" fill="currentColor">`, | |
| 62 | `<title>${t(title, 120)}</title>`, | |
| 63 | ]; | |
| 102 | type Series = readonly [name: string, values: readonly number[]]; | |
| 103 | ||
| 104 | /** | |
| 105 | * The `<svg>` open tag and its title. The data the client needs to answer a | |
| 106 | * hover (labels, each series' formatted values, the plot's span, the marks) | |
| 107 | * rides on the element, escaped as attributes; the client reads, never trusts | |
| 108 | * it as markup. | |
| 109 | */ | |
| 110 | const open = (title: string, tipData?: { xs: readonly string[]; series: readonly Series[]; unit: string; marks: readonly Mark[]; pad: boolean }) => { | |
| 111 | const data = tipData === undefined ? "" : [ | |
| 112 | ` data-xs="${escapeXml(JSON.stringify(humanTimes(tipData.xs).map((x) => clamp(x, 24))))}"`, | |
| 113 | ` data-raw="${escapeXml(JSON.stringify(tipData.xs.map((x) => clamp(x, 40))))}"`, | |
| 114 | ` data-series="${escapeXml(JSON.stringify(tipData.series.map(([n, vs]) => [clamp(n, 24), vs.map((v) => withUnit(v, tipData.unit))])))}"`, | |
| 115 | ` data-marks="${escapeXml(JSON.stringify(tipData.marks.filter((m) => tipData.xs.includes(m.label)).map((m) => [m.label, clamp(m.text, 80)])))}"`, | |
| 116 | ` data-x0="${LEFT}" data-x1="${CHART_WIDTH - RIGHT}" data-pad="${tipData.pad ? 1 : 0}"`, | |
| 117 | ].join(""); | |
| 118 | return [ | |
| 119 | `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${CHART_WIDTH} ${CHART_HEIGHT}" width="${CHART_WIDTH}" height="${CHART_HEIGHT}" role="img" aria-label="${t(title, 120)}" class="chart" preserveAspectRatio="xMidYMid meet" font-size="${FONT}" font-family="inherit" fill="currentColor"${data}>`, | |
| 120 | `<title>${t(title, 120)}</title>`, | |
| 121 | ]; | |
| 122 | }; | |
| 64 | 123 | const nothing = (out: string[]) => { |
| 65 | 124 | out.push(`<text x="${CHART_WIDTH / 2}" y="${CHART_HEIGHT / 2}" text-anchor="middle">No points</text></svg>`); |
| 66 | 125 | return out.join(""); |
| 67 | 126 | }; |
| 68 | 127 | |
| 69 | /** A y scale over [min(0, lo), max(0, hi)] with three gridlines drawn into `out`. */ | |
| 70 | function yAxis(out: string[], lo: number, hi: number) { | |
| 71 | const min = Math.min(0, lo); | |
| 72 | const span = Math.max(0, hi) - min || 1; | |
| 128 | /** A y scale over the nice ticks, each drawn as a gridline and a label into `out`. */ | |
| 129 | function yAxis(out: string[], lo: number, hi: number, unit: string) { | |
| 130 | const ticks = niceTicks(lo, hi); | |
| 131 | const min = ticks[0]!; | |
| 132 | const span = ticks[ticks.length - 1]! - min || 1; | |
| 73 | 133 | const y = (v: number) => TOP + H - ((v - min) / span) * H; |
| 74 | for (const f of [0, 0.5, 1]) { | |
| 75 | const v = min + span * f; | |
| 134 | for (const v of ticks) { | |
| 76 | 135 | const gy = y(v); |
| 77 | 136 | out.push( |
| 78 | 137 | `<line x1="${LEFT}" x2="${CHART_WIDTH - RIGHT}" y1="${num(gy)}" y2="${num(gy)}" stroke="currentColor" stroke-opacity="0.2"/>`, |
| 79 | `<text x="${LEFT - 6}" y="${num(gy + 4)}" text-anchor="end">${escapeXml(formatValue(v))}</text>`, | |
| 138 | `<text class="yl" x="${LEFT - 6}" y="${num(gy + 4)}" text-anchor="end">${escapeXml(withUnit(v, unit))}</text>`, | |
| 80 | 139 | ); |
| 81 | 140 | } |
| 82 | 141 | return y; |
| 83 | 142 | } |
| 84 | 143 | |
| 85 | /** At most X_TICKS labels under the plot, at `x(i)`. */ | |
| 144 | /** At most X_TICKS human labels under the plot, at `x(i)`; the client drops any that would touch. */ | |
| 86 | 145 | function xLabels(out: string[], labels: readonly string[], x: (i: number) => number) { |
| 146 | const human = humanTimes(labels); | |
| 87 | 147 | const step = Math.max(1, Math.ceil(labels.length / X_TICKS)); |
| 88 | labels.forEach((l, i) => { | |
| 148 | human.forEach((l, i) => { | |
| 89 | 149 | if (i % step !== 0) return; |
| 90 | out.push(`<text x="${num(x(i))}" y="${CHART_HEIGHT - 16}" text-anchor="middle">${t(l)}</text>`); | |
| 150 | out.push(`<text class="xl" x="${num(x(i))}" y="${CHART_HEIGHT - 10}" text-anchor="middle">${t(l)}</text>`); | |
| 91 | 151 | }); |
| 92 | 152 | } |
| 93 | 153 | |
| 154 | /** Dashed verticals for the marks whose label is on this axis. */ | |
| 155 | function drawMarks(out: string[], labels: readonly string[], marks: readonly Mark[], x: (i: number) => number) { | |
| 156 | for (const m of marks) { | |
| 157 | const i = labels.indexOf(m.label); | |
| 158 | if (i < 0) continue; | |
| 159 | out.push(`<line class="mark" x1="${num(x(i))}" x2="${num(x(i))}" y1="${TOP}" y2="${TOP + H}" stroke="currentColor" stroke-dasharray="4 3" stroke-opacity="0.7"/>`, | |
| 160 | `<path class="mark-flag" d="M${num(x(i) - 4)} ${TOP} h8 l-4 6 z"/>`); | |
| 161 | } | |
| 162 | } | |
| 163 | ||
| 94 | 164 | const lo = (ps: readonly Point[]) => Math.min(...ps.map((p) => p.value)); |
| 95 | 165 | const hi = (ps: readonly Point[]) => Math.max(...ps.map((p) => p.value)); |
| 166 | const tip = (label: string, v: number) => `<title>${t(label, 40)}: ${escapeXml(formatValue(v))}</title>`; | |
| 167 | const unitOf = (o: Opts) => o.unit ?? ""; | |
| 96 | 168 | |
| 97 | export function lineChart(points: readonly Point[], title: string): string { | |
| 98 | const out = open(title); | |
| 99 | const y = yAxis(out, lo(points), hi(points)); | |
| 169 | export function lineChart(points: readonly Point[], title: string, o: Opts = {}): string { | |
| 170 | const xs = points.map((p) => p.label); | |
| 171 | const marks = o.marks ?? []; | |
| 172 | const out = open(title, { xs, series: [[title, points.map((p) => p.value)]], unit: unitOf(o), marks, pad: false }); | |
| 173 | const y = yAxis(out, lo(points), hi(points), unitOf(o)); | |
| 100 | 174 | if (points.length === 0) return nothing(out); |
| 101 | 175 | const x = (i: number) => LEFT + (points.length < 2 ? W / 2 : (i * W) / (points.length - 1)); |
| 102 | xLabels(out, points.map((p) => p.label), x); | |
| 176 | xLabels(out, xs, x); | |
| 177 | drawMarks(out, xs, marks, x); | |
| 103 | 178 | const d = points.map((p, i) => `${i === 0 ? "M" : "L"}${num(x(i))} ${num(y(p.value))}`).join(" "); |
| 104 | out.push(`<path d="${d}" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>`); | |
| 179 | out.push(`<path class="s0" d="${d}" fill="none" stroke-width="2" stroke-linejoin="round"/>`); | |
| 105 | 180 | points.forEach((p, i) => { |
| 106 | out.push(linked(p.href, `<circle cx="${num(x(i))}" cy="${num(y(p.value))}" r="4">${tip(p.label, p.value)}</circle>`)); | |
| 181 | out.push(linked(p.href, `<circle class="s0" cx="${num(x(i))}" cy="${num(y(p.value))}" r="4"></circle>`)); | |
| 107 | 182 | }); |
| 108 | 183 | out.push("</svg>"); |
| 109 | 184 | return out.join(""); |
| 110 | 185 | } |
| 111 | 186 | |
| 112 | 187 | /** One bar per point, from zero; a slot is W / n wide and the bar 70% of it. */ |
| 113 | export function barChart(points: readonly Point[], title: string): string { | |
| 114 | const out = open(title); | |
| 115 | const y = yAxis(out, lo(points), hi(points)); | |
| 188 | export function barChart(points: readonly Point[], title: string, o: Opts = {}): string { | |
| 189 | const xs = points.map((p) => p.label); | |
| 190 | const marks = o.marks ?? []; | |
| 191 | const out = open(title, { xs, series: [[title, points.map((p) => p.value)]], unit: unitOf(o), marks, pad: true }); | |
| 192 | const y = yAxis(out, lo(points), hi(points), unitOf(o)); | |
| 116 | 193 | if (points.length === 0) return nothing(out); |
| 117 | 194 | const slot = W / points.length; |
| 118 | 195 | const bw = Math.max(1, slot * 0.7); |
| 119 | 196 | const x = (i: number) => LEFT + slot * i + slot / 2; |
| 120 | xLabels(out, points.map((p) => p.label), x); | |
| 197 | xLabels(out, xs, x); | |
| 198 | drawMarks(out, xs, marks, x); | |
| 121 | 199 | points.forEach((p, i) => { |
| 122 | 200 | const top = Math.min(y(p.value), y(0)); |
| 123 | 201 | const h = Math.abs(y(p.value) - y(0)); |
| 124 | 202 | out.push(linked(p.href, |
| 125 | `<rect class="bar" x="${num(x(i) - bw / 2)}" y="${num(top)}" width="${num(bw)}" height="${num(h)}">${tip(p.label, p.value)}</rect>`)); | |
| 203 | `<rect class="bar s0" x="${num(x(i) - bw / 2)}" y="${num(top)}" width="${num(bw)}" height="${num(h)}"></rect>`)); | |
| 126 | 204 | }); |
| 127 | 205 | out.push("</svg>"); |
| 128 | 206 | return out.join(""); |
| @@ -160,18 +238,9 @@ export function gridOf(cells: readonly Cell[], keep: number) { | ||
| 160 | 238 | return { xs, names, values, hrefs }; |
| 161 | 239 | } |
| 162 | 240 | |
| 163 | /** Series opacity: the first is the strongest, each next one lighter. */ | |
| 164 | const shade = (i: number, n: number) => num(n < 2 ? 0.8 : 0.85 - (0.6 * i) / (n - 1)); | |
| 165 | ||
| 166 | function legend(out: string[], names: readonly string[]) { | |
| 167 | const each = W / Math.max(1, names.length); | |
| 168 | names.forEach((n, i) => { | |
| 169 | const lx = LEFT + each * i; | |
| 170 | out.push( | |
| 171 | `<rect class="key" x="${num(lx)}" y="${CHART_HEIGHT - 10}" width="8" height="8" fill-opacity="${shade(i, names.length)}"/>`, | |
| 172 | `<text x="${num(lx + 12)}" y="${CHART_HEIGHT - 2}">${t(n, 14)}</text>`, | |
| 173 | ); | |
| 174 | }); | |
| 241 | /** The legend as HTML under the chart: it wraps, so it never overlaps, and its text is the page's own. */ | |
| 242 | function legend(names: readonly string[]) { | |
| 243 | return `<ul class="chart-legend">${names.map((n, i) => `<li><i class="key s${i}"></i>${t(n, 24)}</li>`).join("")}</ul>`; | |
| 175 | 244 | } |
| 176 | 245 | |
| 177 | 246 | /** |
| @@ -179,26 +248,26 @@ function legend(out: string[], names: readonly string[]) { | ||
| 179 | 248 | * are drawn as 0 — a stack of signed values has no single reading — and the |
| 180 | 249 | * scale is the tallest stack. |
| 181 | 250 | */ |
| 182 | export function stackedArea(cells: readonly Cell[], title: string): string { | |
| 183 | const out = open(title); | |
| 251 | export function stackedArea(cells: readonly Cell[], title: string, o: Opts = {}): string { | |
| 184 | 252 | const { xs, names, values } = gridOf(cells, MAX_SERIES); |
| 253 | const marks = o.marks ?? []; | |
| 254 | const out = open(title, { xs, series: names.map((n, i) => [n, values[i]!] as const), unit: unitOf(o), marks, pad: false }); | |
| 185 | 255 | const pos = values.map((r) => r.map((v) => Math.max(0, v))); |
| 186 | 256 | const tops = xs.map((_, i) => pos.reduce((a, r) => a + r[i]!, 0)); |
| 187 | const y = yAxis(out, 0, Math.max(0, ...tops)); | |
| 257 | const y = yAxis(out, 0, Math.max(0, ...tops), unitOf(o)); | |
| 188 | 258 | if (xs.length === 0) return nothing(out); |
| 189 | 259 | const x = (i: number) => LEFT + (xs.length < 2 ? W / 2 : (i * W) / (xs.length - 1)); |
| 190 | 260 | xLabels(out, xs, x); |
| 261 | drawMarks(out, xs, marks, x); | |
| 191 | 262 | const base = xs.map(() => 0); |
| 192 | names.forEach((n, s) => { | |
| 263 | names.forEach((_, s) => { | |
| 193 | 264 | const upper = base.map((b, i) => b + pos[s]![i]!); |
| 194 | 265 | const fwd = upper.map((v, i) => `${i === 0 ? "M" : "L"}${num(x(i))} ${num(y(v))}`); |
| 195 | 266 | const back = base.map((v, i) => `L${num(x(i))} ${num(y(v))}`).reverse(); |
| 196 | const total = pos[s]!.reduce((a, v) => a + v, 0); | |
| 197 | out.push(`<path class="area" d="${[...fwd, ...back, "Z"].join(" ")}" fill-opacity="${shade(s, names.length)}" stroke="currentColor" stroke-width="1">${tip(n, total)}</path>`); | |
| 267 | out.push(`<path class="area s${s}" d="${[...fwd, ...back, "Z"].join(" ")}" fill-opacity="0.75" stroke-width="1"></path>`); | |
| 198 | 268 | upper.forEach((v, i) => (base[i] = v)); |
| 199 | 269 | }); |
| 200 | legend(out, names); | |
| 201 | out.push("</svg>"); | |
| 270 | out.push("</svg>", legend(names)); | |
| 202 | 271 | return out.join(""); |
| 203 | 272 | } |
| 204 | 273 | |
| @@ -264,11 +333,11 @@ export function tableChart(cells: readonly Cell[], title: string): string { | ||
| 264 | 333 | } |
| 265 | 334 | |
| 266 | 335 | /** One chart by name: the one door a page draws a panel through. */ |
| 267 | export function drawChart(chart: Chart, cells: readonly Cell[], title: string): string { | |
| 336 | export function drawChart(chart: Chart, cells: readonly Cell[], title: string, o: Opts = {}): string { | |
| 268 | 337 | switch (chart) { |
| 269 | case "line": return lineChart(cells, title); | |
| 270 | case "bar": return barChart(cells, title); | |
| 271 | case "area": return stackedArea(cells, title); | |
| 338 | case "line": return lineChart(cells, title, o); | |
| 339 | case "bar": return barChart(cells, title, o); | |
| 340 | case "area": return stackedArea(cells, title, o); | |
| 272 | 341 | case "number": return numberChart(cells, title); |
| 273 | 342 | case "heat": return heatStrip(cells, title); |
| 274 | 343 | case "table": return tableChart(cells, title); |
src/boards/marks.ts added +36
| @@ -0,0 +1,36 @@ | ||
| 1 | /** | |
| 2 | * Release marks for a time axis: each landed release becomes a vertical line | |
| 3 | * on the bucket it fell into. Pure over the labels and the `release` table; | |
| 4 | * a chart whose labels are not timestamps gets none. | |
| 5 | */ | |
| 6 | import type { Database } from "bun:sqlite"; | |
| 7 | import type { Mark } from "./chart.ts"; | |
| 8 | ||
| 9 | const MAX_MARKS = 50; | |
| 10 | ||
| 11 | /** The label of the bucket `at` falls in: the last label at or before it, within one bucket's width. */ | |
| 12 | export function bucketOf(labels: readonly string[], at: number): string | undefined { | |
| 13 | const times = labels.map((l) => Date.parse(l)); | |
| 14 | if (times.length < 2 || times.some(Number.isNaN)) return undefined; | |
| 15 | const gaps = times.slice(1).map((t, i) => t - times[i]!).sort((a, b) => a - b); | |
| 16 | const width = gaps[Math.floor(gaps.length / 2)]!; | |
| 17 | if (width <= 0) return undefined; | |
| 18 | let found: number | undefined; | |
| 19 | times.forEach((t, i) => { if (t <= at) found = i; }); | |
| 20 | return found === undefined || at >= times[found]! + width ? undefined : labels[found]; | |
| 21 | } | |
| 22 | ||
| 23 | export function releaseMarks(db: Database, labels: readonly string[]): Mark[] { | |
| 24 | const first = Date.parse(labels[0] ?? ""); | |
| 25 | const last = Date.parse(labels[labels.length - 1] ?? ""); | |
| 26 | if (Number.isNaN(first) || Number.isNaN(last)) return []; | |
| 27 | const rows = db.query<{ sha: string; ok: number; created_at: string }, [string, string]>( | |
| 28 | "SELECT sha, ok, created_at FROM release WHERE created_at >= ? AND created_at <= ? ORDER BY created_at LIMIT 50", | |
| 29 | ).all(new Date(first).toISOString(), new Date(last + 86_400_000).toISOString()); | |
| 30 | const marks: Mark[] = []; | |
| 31 | for (const r of rows) { | |
| 32 | const label = bucketOf(labels, Date.parse(r.created_at)); | |
| 33 | if (label !== undefined && marks.length < MAX_MARKS) marks.push({ label, text: `release ${r.sha.slice(0, 7)}${r.ok ? "" : " (preflight failed)"}` }); | |
| 34 | } | |
| 35 | return marks; | |
| 36 | } |
src/web/chart-client.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | /** | |
| 2 | * The charts' client: three small jobs on the SVGs `boards/chart.ts` draws. | |
| 3 | * Real size — text is set so it renders at 12 px whatever the SVG is scaled | |
| 4 | * to, and x labels that would touch are hidden. Hover — a tooltip with the | |
| 5 | * bucket's values and any release mark, from the `data-*` the server wrote. | |
| 6 | * Crosshair — every chart that has the hovered x label shows its line at it. | |
| 7 | * Text goes in with `textContent`; nothing here parses markup. | |
| 8 | */ | |
| 9 | export const chartJs = /* js */ ` | |
| 10 | (function () { | |
| 11 | var NS = 'http://www.w3.org/2000/svg'; | |
| 12 | var svgs = [].slice.call(document.querySelectorAll('svg.chart[data-xs]')); | |
| 13 | if (svgs.length === 0) return; | |
| 14 | function json(el, name) { try { return JSON.parse(el.getAttribute(name)) || []; } catch (e) { return []; } } | |
| 15 | function fit(s) { | |
| 16 | var w = s.getBoundingClientRect().width; | |
| 17 | if (!w) return; | |
| 18 | s.style.setProperty('--fs', (12 * 720 / w).toFixed(2) + 'px'); | |
| 19 | var edge = -1e9; | |
| 20 | [].forEach.call(s.querySelectorAll('.xl'), function (t) { | |
| 21 | t.style.visibility = 'visible'; | |
| 22 | var b = t.getBBox(); | |
| 23 | if (b.x < edge + 6) t.style.visibility = 'hidden'; else edge = b.x + b.width; | |
| 24 | }); | |
| 25 | } | |
| 26 | var tip = document.createElement('div'); | |
| 27 | tip.className = 'chart-tip'; | |
| 28 | tip.hidden = true; | |
| 29 | document.body.appendChild(tip); | |
| 30 | var charts = svgs.map(function (s) { | |
| 31 | var line = document.createElementNS(NS, 'line'); | |
| 32 | line.setAttribute('class', 'xhair'); | |
| 33 | line.setAttribute('y1', '16'); | |
| 34 | line.setAttribute('y2', '228'); | |
| 35 | line.style.display = 'none'; | |
| 36 | s.appendChild(line); | |
| 37 | var c = { s: s, line: line, raw: json(s, 'data-raw'), xs: json(s, 'data-xs'), series: json(s, 'data-series'), | |
| 38 | marks: json(s, 'data-marks'), x0: +s.getAttribute('data-x0'), x1: +s.getAttribute('data-x1'), pad: s.getAttribute('data-pad') === '1' }; | |
| 39 | c.x = function (i) { | |
| 40 | var n = c.raw.length, w = c.x1 - c.x0; | |
| 41 | return c.pad ? c.x0 + w / n * (i + 0.5) : c.x0 + (n < 2 ? w / 2 : i * w / (n - 1)); | |
| 42 | }; | |
| 43 | fit(s); | |
| 44 | if (typeof ResizeObserver !== 'undefined') new ResizeObserver(function () { fit(s); }).observe(s); | |
| 45 | return c; | |
| 46 | }); | |
| 47 | function hide() { | |
| 48 | tip.hidden = true; | |
| 49 | charts.forEach(function (c) { c.line.style.display = 'none'; }); | |
| 50 | } | |
| 51 | function nearest(c, e) { | |
| 52 | var m = c.s.getScreenCTM(); | |
| 53 | if (!m || c.raw.length === 0) return -1; | |
| 54 | var p = c.s.createSVGPoint(); | |
| 55 | p.x = e.clientX; p.y = e.clientY; | |
| 56 | var x = p.matrixTransform(m.inverse()).x, best = 0, d = 1e9; | |
| 57 | for (var i = 0; i < c.raw.length; i++) { var di = Math.abs(c.x(i) - x); if (di < d) { d = di; best = i; } } | |
| 58 | return best; | |
| 59 | } | |
| 60 | function row(parent, cls, text) { | |
| 61 | var d = document.createElement('div'); | |
| 62 | if (cls) d.className = cls; | |
| 63 | d.textContent = text; | |
| 64 | parent.appendChild(d); | |
| 65 | return d; | |
| 66 | } | |
| 67 | charts.forEach(function (c) { | |
| 68 | c.s.addEventListener('pointermove', function (e) { | |
| 69 | var i = nearest(c, e); | |
| 70 | if (i < 0) return hide(); | |
| 71 | var label = c.raw[i]; | |
| 72 | charts.forEach(function (o) { | |
| 73 | var j = o.raw.indexOf(label); | |
| 74 | if (j < 0) { o.line.style.display = 'none'; return; } | |
| 75 | o.line.setAttribute('x1', o.x(j)); o.line.setAttribute('x2', o.x(j)); | |
| 76 | o.line.style.display = ''; | |
| 77 | }); | |
| 78 | tip.textContent = ''; | |
| 79 | row(tip, 'chart-tip-t', c.xs[i]); | |
| 80 | c.series.forEach(function (sr, k) { | |
| 81 | var r = row(tip, 'chart-tip-r', ''); | |
| 82 | var key = document.createElement('i'); | |
| 83 | key.className = 'key s' + (c.series.length === 1 ? 0 : k); | |
| 84 | r.appendChild(key); | |
| 85 | r.appendChild(document.createTextNode(c.series.length === 1 ? sr[1][i] : sr[0] + ': ' + sr[1][i])); | |
| 86 | }); | |
| 87 | c.marks.forEach(function (m) { if (m[0] === label) row(tip, 'chart-tip-m', '▾ ' + m[1]); }); | |
| 88 | tip.hidden = false; | |
| 89 | var w = tip.offsetWidth, left = e.clientX + 14; | |
| 90 | if (left + w > window.innerWidth - 8) left = e.clientX - w - 14; | |
| 91 | tip.style.left = Math.max(8, left) + 'px'; | |
| 92 | tip.style.top = Math.max(8, e.clientY - tip.offsetHeight - 10) + 'px'; | |
| 93 | }); | |
| 94 | c.s.addEventListener('pointerleave', hide); | |
| 95 | }); | |
| 96 | })(); | |
| 97 | `; |
src/web/pages/boards-view.ts +3 −2
| @@ -21,6 +21,7 @@ import { fragment, page } from "../layout.ts"; | ||
| 21 | 21 | import { btn, card, empty } from "../ui.ts"; |
| 22 | 22 | import { flowPanel, flowPanelCss } from "./flow-panel.ts"; |
| 23 | 23 | import { isPinned, listPins } from "../../boards/pins.ts"; |
| 24 | import { chartJs } from "../chart-client.ts"; | |
| 24 | 25 | import { cellsOf, chartBox, paramsOf, queryFields, readParams, runFor } from "./boards.ts"; |
| 25 | 26 | |
| 26 | 27 | const RANGE_MS = { "1h": 3_600_000, "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 } as const; |
| @@ -47,7 +48,7 @@ export function drawPanel( | ||
| 47 | 48 | const q = paramsOf(panel.query, panel.chart); |
| 48 | 49 | const body = !answer.ok |
| 49 | 50 | ? html`<p class="muted small">${answer.error}</p>` |
| 50 | : chartBox(panel.chart, cellsOf(answer.rows), panel.title); | |
| 51 | : chartBox(panel.chart, cellsOf(answer.rows), panel.title, app.db); | |
| 51 | 52 | const explore = new URLSearchParams(Object.entries(q).filter(([k, v]) => v !== "" && k !== "rows")); |
| 52 | 53 | return html`<div class="card bp-w${String(panel.w)} bp-h${String(panel.h)}"> |
| 53 | 54 | <div class="card-head"><h2>${panel.title}</h2> |
| @@ -191,7 +192,7 @@ export async function boardShow(ctx: Ctx): Promise<Response> { | ||
| 191 | 192 | ${btn("All boards", { href: "/boards", variant: "ghost" })}</div> |
| 192 | 193 | ${panels} |
| 193 | 194 | ${manage(slug, board, queryFields(readParams(ctx.url.searchParams)), listPins(ctx.app.db, ctx.auth.user?.id ?? ""))}`, |
| 194 | scriptJs: liveRegionsJs, | |
| 195 | scriptJs: liveRegionsJs + chartJs, | |
| 195 | 196 | }); |
| 196 | 197 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 197 | 198 | return response; |
src/web/pages/boards.ts +10 −3
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | * Anyone else gets the not-found page. |
| 9 | 9 | */ |
| 10 | 10 | import type { Database } from "bun:sqlite"; |
| 11 | import { releaseMarks } from "../../boards/marks.ts"; | |
| 12 | import { chartJs } from "../chart-client.ts"; | |
| 11 | 13 | import { CHART_NAMES, CHARTS, drawChart, usesSeries, type Cell, type Chart } from "../../boards/chart.ts"; |
| 12 | 14 | import { runQuery, type Answer, type Query, type Row } from "../../boards/query.ts"; |
| 13 | 15 | import { gaps, SYSTEM } from "../../boards/sampler.ts"; |
| @@ -94,8 +96,12 @@ export const cellsOf = (rows: readonly Row[], hrefs: readonly (string | null)[] | ||
| 94 | 96 | })); |
| 95 | 97 | |
| 96 | 98 | /** A drawn chart in the box that holds its space. */ |
| 97 | export const chartBox = (chart: Chart, cells: readonly Cell[], title: string) => | |
| 98 | html`<div class="chart-box${chart === "table" ? " is-table" : ""}">${raw(drawChart(chart, cells, title))}</div>`; | |
| 99 | export const chartBox = (chart: Chart, cells: readonly Cell[], title: string, db?: Database) => { | |
| 100 | const marks = db !== undefined && (chart === "line" || chart === "bar" || chart === "area") | |
| 101 | ? releaseMarks(db, [...new Set(cells.map((c) => c.label))]) | |
| 102 | : []; | |
| 103 | return html`<div class="chart-box${chart === "table" ? " is-table" : ""}">${raw(drawChart(chart, cells, title, { marks }))}</div>`; | |
| 104 | }; | |
| 99 | 105 | |
| 100 | 106 | const link = (p: Params) => { |
| 101 | 107 | const s = new URLSearchParams(); |
| @@ -280,7 +286,7 @@ export async function boardsPage(ctx: Ctx): Promise<Response> { | ||
| 280 | 286 | const split = answer.rows[0]?.series !== undefined; |
| 281 | 287 | const chart = |
| 282 | 288 | p.rows === "" |
| 283 | ? chartBox(p.chart, points, `${p.aggregate} of ${p.source}`) | |
| 289 | ? chartBox(p.chart, points, `${p.aggregate} of ${p.source}`, ctx.app.db) | |
| 284 | 290 | : html`<p class="muted small">The rows behind a point, as the values of ${cols[0] ?? ""} with how many rows have each. <a href="${link({ ...p, rows: "" })}">Back to the chart</a>.</p>`; |
| 285 | 291 | result = html`${chart} |
| 286 | 292 | ${when(p.rows !== "" || p.chart !== "table", () => html`<table class="table"> |
| @@ -336,6 +342,7 @@ export async function boardsPage(ctx: Ctx): Promise<Response> { | ||
| 336 | 342 | const response = page({ |
| 337 | 343 | ctx, |
| 338 | 344 | title: "Boards", |
| 345 | scriptJs: chartJs, | |
| 339 | 346 | body: html`<div class="page-head"><h1>Data</h1>${btn("All boards", { href: "/boards", variant: "ghost" })}</div> |
| 340 | 347 | ${form} ${absent} ${card(result, { head: html`<h2>${p.source}</h2>`, extra: "boards-result" })} ${pin} ${sources}`, |
| 341 | 348 | }); |
src/web/pages/system.ts +6 −2
| @@ -10,6 +10,8 @@ | ||
| 10 | 10 | * (RSS) beside its JS heap, hourly for 24 h (#2151): RSS climbing while the |
| 11 | 11 | * heap stays flat is native memory growth. Drawn on the server as SVG. |
| 12 | 12 | */ |
| 13 | import { chartJs } from "../chart-client.ts"; | |
| 14 | import { releaseMarks } from "../../boards/marks.ts"; | |
| 13 | 15 | import { drawChart } from "../../boards/chart.ts"; |
| 14 | 16 | import { canSeeMemory, memoryHours } from "../../boards/memory.ts"; |
| 15 | 17 | import { telemetryReader } from "../../actions/telemetry.ts"; |
| @@ -68,9 +70,11 @@ const hhmm = (at: number) => new Date(at).toISOString().slice(0, 16).replace("T" | ||
| 68 | 70 | function memorySection(ctx: Ctx): Html { |
| 69 | 71 | if (!canSeeMemory(ctx.auth.user)) return html``; |
| 70 | 72 | const hours = memoryHours(ctx.app.db, Date.now()); |
| 73 | const labels = hours.map((h) => new Date(h.at).toISOString()); | |
| 74 | const marks = releaseMarks(ctx.app.db, labels); | |
| 71 | 75 | const series = (title: string, pick: (h: (typeof hours)[number]) => number) => |
| 72 | 76 | card( |
| 73 | html`<div class="chart-box">${raw(drawChart("line", hours.map((h) => ({ label: hhmm(h.at).slice(11), value: pick(h) / 1_048_576 })), title))}</div>`, | |
| 77 | html`<div class="chart-box">${raw(drawChart("line", hours.map((h, i) => ({ label: labels[i]!, value: pick(h) / 1_048_576 })), title, { unit: "MiB", marks }))}</div>`, | |
| 74 | 78 | { head: html`<h2>${title}</h2>` }, |
| 75 | 79 | ); |
| 76 | 80 | return hours.length === 0 |
| @@ -179,5 +183,5 @@ export function systemPage(ctx: Ctx): Response { | ||
| 179 | 183 | <button class="btn" data-size="sm" type="button" data-sort="mem" aria-pressed="false"><kbd>m</kbd> memory</button></span></p></div> |
| 180 | 184 | <div id="sys-procs">${at("sys-procs")}</div> |
| 181 | 185 | ${memorySection(ctx)}`; |
| 182 | return page({ ctx, title: "System", body, wide: true, scriptJs: systemLiveJs }); | |
| 186 | return page({ ctx, title: "System", body, wide: true, scriptJs: systemLiveJs + chartJs }); | |
| 183 | 187 | } |
src/web/style/content.ts +23 −4
| @@ -361,11 +361,30 @@ a.origin-chip:hover { border-color: var(--border-strong); color: var(--fg); } | ||
| 361 | 361 | } |
| 362 | 362 | .backups-now { margin-top: 12px; } |
| 363 | 363 | .backups-drill { overflow-wrap: anywhere; } |
| 364 | .chart-box { color: var(--accent); aspect-ratio: 720 / 260; max-width: 720px; } | |
| 365 | .chart-box .chart { display: block; width: 100%; height: auto; } | |
| 366 | .chart-box text { fill: var(--muted-fg); font-family: var(--mono); } | |
| 367 | .chart-box circle { fill: var(--accent); } | |
| 364 | .chart-box { color: var(--accent); max-width: 720px; | |
| 365 | --s0: #3d8bd8; --s1: #e0900f; --s2: #1fa88a; --s3: #c2609a; --s4: #8a6fd6; --s5: #d2553f; --s6: #8f9aa6; --s7: #a98a2a; } | |
| 366 | .chart-box .chart { display: block; width: 100%; height: auto; overflow: hidden; } | |
| 367 | .chart-box text { fill: var(--muted-fg); font-family: var(--mono); font-variant-numeric: tabular-nums; } | |
| 368 | .chart-box .chart text:not(.big) { font-size: var(--fs, 12px); } | |
| 369 | .chart-box .s0 { --c: var(--s0); } .chart-box .s1 { --c: var(--s1); } .chart-box .s2 { --c: var(--s2); } .chart-box .s3 { --c: var(--s3); } | |
| 370 | .chart-box .s4 { --c: var(--s4); } .chart-box .s5 { --c: var(--s5); } .chart-box .s6 { --c: var(--s6); } .chart-box .s7 { --c: var(--s7); } | |
| 371 | .chart-box path[class~="s0"]:not(.area), .chart-box path[class~="s1"]:not(.area) { stroke: var(--c); } | |
| 372 | .chart-box circle, .chart-box rect.bar, .chart-box .area, .chart-box .key { fill: var(--c, var(--accent)); } | |
| 373 | .chart-box .area { stroke: var(--c); } | |
| 374 | .chart-box .mark { color: var(--muted-fg); } .chart-box .mark-flag { fill: var(--muted-fg); } | |
| 375 | .chart-box .xhair { stroke: var(--fg); stroke-opacity: .5; stroke-width: 1; pointer-events: none; } | |
| 368 | 376 | .chart-box .big { fill: var(--fg); font-family: inherit; } |
| 377 | .chart-legend { list-style: none; margin: 4px 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: 12px; color: var(--muted-fg); } | |
| 378 | .chart-legend li { display: inline-flex; align-items: center; gap: 6px; } | |
| 379 | .key { display: inline-block; width: 10px; height: 10px; border-radius: 2px; background: var(--c, var(--s0, var(--accent))); } | |
| 380 | .chart-tip { position: fixed; z-index: 50; pointer-events: none; background: var(--surface, var(--bg)); color: var(--fg); | |
| 381 | border: 1px solid var(--border, currentColor); border-radius: var(--radius-sm); padding: 6px 8px; font-size: 12px; | |
| 382 | font-variant-numeric: tabular-nums; box-shadow: 0 4px 16px rgb(0 0 0 / .25); max-width: 280px; } | |
| 383 | .chart-tip[hidden] { display: none; } | |
| 384 | .chart-tip-t { color: var(--muted-fg); } .chart-tip-r { display: flex; align-items: center; gap: 6px; } | |
| 385 | .chart-tip .s0 { --c: var(--s0); } .chart-tip .s1 { --c: var(--s1); } .chart-tip .s2 { --c: var(--s2); } .chart-tip .s3 { --c: var(--s3); } | |
| 386 | .chart-tip .s4 { --c: var(--s4); } .chart-tip .s5 { --c: var(--s5); } .chart-tip .s6 { --c: var(--s6); } .chart-tip .s7 { --c: var(--s7); } | |
| 387 | .chart-tip { --s0: #3d8bd8; --s1: #e0900f; --s2: #1fa88a; --s3: #c2609a; --s4: #8a6fd6; --s5: #d2553f; --s6: #8f9aa6; --s7: #a98a2a; } | |
| 369 | 388 | .chart-box.is-table { aspect-ratio: auto; height: 260px; overflow: auto; } |
| 370 | 389 | .bp-h2 .chart-box.is-table { height: 400px; } |
| 371 | 390 | .bp-h3 .chart-box.is-table { height: 540px; } |
test/boards-page.test.ts +87 −17
| @@ -9,7 +9,9 @@ import { mkdtemp, rm } from "node:fs/promises"; | ||
| 9 | 9 | import { tmpdir } from "node:os"; |
| 10 | 10 | import { join } from "node:path"; |
| 11 | 11 | import { createApp } from "../src/app.ts"; |
| 12 | import { barChart, drawChart, CHARTS, gridOf, heatStrip, lineChart, numberChart, stackedArea, tableChart } from "../src/boards/chart.ts"; | |
| 12 | import { barChart, drawChart, CHARTS, gridOf, heatStrip, humanTimes, lineChart, niceTicks, numberChart, stackedArea, tableChart, withUnit } from "../src/boards/chart.ts"; | |
| 13 | import { bucketOf, releaseMarks } from "../src/boards/marks.ts"; | |
| 14 | import { chartJs } from "../src/web/chart-client.ts"; | |
| 13 | 15 | import { createToken } from "../src/core/tokens.ts"; |
| 14 | 16 | import { createUser } from "../src/core/users.ts"; |
| 15 | 17 | import { serve } from "../src/http/server.ts"; |
| @@ -68,8 +70,8 @@ describe("/boards/data", () => { | ||
| 68 | 70 | const res = await get("/boards/data?source=runs&by=day", "admin"); |
| 69 | 71 | expect(res.status).toBe(200); |
| 70 | 72 | const body = await res.text(); |
| 71 | expect(body.match(/<path d="M[^"]*" fill="none" stroke="currentColor" stroke-width="2"/g)?.length).toBe(1); | |
| 72 | expect(body.match(/<circle cx="[^"]*" cy="[^"]*" r="4">/g)?.length).toBe(3); | |
| 73 | expect(body.match(/<path class="s0" d="M[^"]*" fill="none" stroke-width="2"/g)?.length).toBe(1); | |
| 74 | expect(body.match(/<circle class="s0" cx="[^"]*" cy="[^"]*" r="4">/g)?.length).toBe(3); | |
| 73 | 75 | expect(body).toContain("2026-10-02T00:00:00Z"); |
| 74 | 76 | }); |
| 75 | 77 | |
| @@ -110,7 +112,7 @@ describe("/boards/data", () => { | ||
| 110 | 112 | |
| 111 | 113 | test("a filter narrows the points", async () => { |
| 112 | 114 | const body = await (await get("/boards/data?source=runs&by=day&from=2026-10-02&to=2026-10-03", "admin")).text(); |
| 113 | expect(body.match(/<circle cx="[^"]*" cy="[^"]*" r="4">/g)?.length).toBe(1); | |
| 115 | expect(body.match(/<circle class="s0" cx="[^"]*" cy="[^"]*" r="4">/g)?.length).toBe(1); | |
| 114 | 116 | }); |
| 115 | 117 | |
| 116 | 118 | test("hostile params are escaped", async () => { |
| @@ -175,15 +177,15 @@ describe("every chart type from one seeded query", () => { | ||
| 175 | 177 | const count = (body: string, re: RegExp) => body.match(re)?.length ?? 0; |
| 176 | 178 | |
| 177 | 179 | test("line draws one point per day, the series set aside", async () => { |
| 178 | expect(count(await drawn("line"), /<circle cx="[^"]*" cy="[^"]*" r="4">/g)).toBe(3); | |
| 180 | expect(count(await drawn("line"), /<circle class="s0" cx="[^"]*" cy="[^"]*" r="4">/g)).toBe(3); | |
| 179 | 181 | }); |
| 180 | 182 | test("bar draws one bar per day", async () => { |
| 181 | expect(count(await drawn("bar"), /<rect class="bar"/g)).toBe(3); | |
| 183 | expect(count(await drawn("bar"), /<rect class="bar s0"/g)).toBe(3); | |
| 182 | 184 | }); |
| 183 | 185 | test("stacked area draws one band per kind, with a legend", async () => { |
| 184 | 186 | const body = await drawn("area"); |
| 185 | expect(count(body, /<path class="area"/g)).toBe(3); | |
| 186 | expect(count(body, /<rect class="key"/g)).toBe(3); | |
| 187 | expect(count(body, /<path class="area s\d"/g)).toBe(3); | |
| 188 | expect(count(body, /<i class="key s\d"><\/i>/g)).toBe(3); | |
| 187 | 189 | }); |
| 188 | 190 | test("number draws the latest day's count and a three-point sparkline", async () => { |
| 189 | 191 | const body = await drawn("number"); |
| @@ -207,7 +209,7 @@ describe("every chart type from one seeded query", () => { | ||
| 207 | 209 | expect(await listed(check)).toEqual(["m3", "m4"]); |
| 208 | 210 | }); |
| 209 | 211 | test("an unknown chart falls back to line", async () => { |
| 210 | expect(count(await drawn("pie"), /<circle cx="[^"]*" cy="[^"]*" r="4">/g)).toBe(3); | |
| 212 | expect(count(await drawn("pie"), /<circle class="s0" cx="[^"]*" cy="[^"]*" r="4">/g)).toBe(3); | |
| 211 | 213 | }); |
| 212 | 214 | test("the chart is chosen beside the query", async () => { |
| 213 | 215 | const body = await drawn("heat"); |
| @@ -218,12 +220,12 @@ describe("every chart type from one seeded query", () => { | ||
| 218 | 220 | }); |
| 219 | 221 | |
| 220 | 222 | describe("chart geometry", () => { |
| 221 | // The plot is 648 × 204 (720 − 56 − 16 by 260 − 16 − 40), its top-left at (56, 16). | |
| 222 | test("bars: two slots of 324, bars 70% wide, heights in proportion", () => { | |
| 223 | // The plot is 640 × 212 (720 − 64 − 16 by 260 − 16 − 32), its top-left at (64, 16). | |
| 224 | test("bars: two slots of 320, bars 70% wide, heights in proportion", () => { | |
| 223 | 225 | const svg = barChart([{ label: "a", value: 1 }, { label: "b", value: 3 }], "t"); |
| 224 | // scale 204/3 = 68 per unit; slot centres 218 and 542; bar 226.8 wide. | |
| 225 | expect(svg).toContain('<rect class="bar" x="104.6" y="152" width="226.8" height="68">'); | |
| 226 | expect(svg).toContain('<rect class="bar" x="428.6" y="16" width="226.8" height="204">'); | |
| 226 | // scale 212/3 per unit; slot centres 224 and 544; bar 224 wide. | |
| 227 | expect(svg).toContain('<rect class="bar s0" x="112" y="157.33" width="224" height="70.67">'); | |
| 228 | expect(svg).toContain('<rect class="bar s0" x="432" y="16" width="224" height="212">'); | |
| 227 | 229 | }); |
| 228 | 230 | test("stacked area: bands sit on the ones before them", () => { |
| 229 | 231 | const cells = [ |
| @@ -231,9 +233,9 @@ describe("chart geometry", () => { | ||
| 231 | 233 | { label: "t2", series: "a", value: 3 }, { label: "t2", series: "b", value: 1 }, |
| 232 | 234 | ]; |
| 233 | 235 | const svg = stackedArea(cells, "t"); |
| 234 | // tallest stack 4 → y(v) = 220 − 51v; x is 56 and 704. | |
| 235 | expect(svg).toContain('d="M56 169 L704 67 L704 220 L56 220 Z"'); | |
| 236 | expect(svg).toContain('d="M56 67 L704 16 L704 67 L56 169 Z"'); | |
| 236 | // tallest stack 4 → y(v) = 228 − 53v; x is 64 and 704. | |
| 237 | expect(svg).toContain('d="M64 175 L704 69 L704 228 L64 228 Z"'); | |
| 238 | expect(svg).toContain('d="M64 69 L704 16 L704 69 L64 175 Z"'); | |
| 237 | 239 | }); |
| 238 | 240 | test("heat: opacity is 0.06 + 0.94 × value / largest", () => { |
| 239 | 241 | const svg = heatStrip([ |
| @@ -279,3 +281,71 @@ describe("lineChart", () => { | ||
| 279 | 281 | expect(lineChart([], "t")).toContain("No points"); |
| 280 | 282 | }); |
| 281 | 283 | }); |
| 284 | ||
| 285 | describe("one great chart", () => { | |
| 286 | test("y ticks are nice: 0, 25, 50 — never 22.32", () => { | |
| 287 | expect(niceTicks(0, 50)).toEqual([0, 10, 20, 30, 40, 50]); | |
| 288 | expect(niceTicks(0, 100)).toEqual([0, 20, 40, 60, 80, 100]); | |
| 289 | expect(niceTicks(0, 1)).toEqual([0, 0.2, 0.4, 0.6, 0.8, 1]); | |
| 290 | expect(niceTicks(0, 44.64)).toEqual([0, 10, 20, 30, 40, 50]); | |
| 291 | expect(niceTicks(-3, 8)).toContain(0); | |
| 292 | }); | |
| 293 | test("time ticks are human, not cut ISO strings", () => { | |
| 294 | expect(humanTimes(["2026-10-20T14:00:00Z", "2026-10-20T15:00:00Z"])).toEqual(["14:00", "15:00"]); | |
| 295 | expect(humanTimes(["2026-10-20T00:00:00Z", "2026-10-21T00:00:00Z"])).toEqual(["Tue 20", "Wed 21"]); | |
| 296 | expect(humanTimes(["2026-10-20T23:00:00Z", "2026-10-21T01:00:00Z"])).toEqual(["Tue 20 23:00", "Wed 21 01:00"]); | |
| 297 | expect(humanTimes(["a", "b"])).toEqual(["a", "b"]); | |
| 298 | }); | |
| 299 | test("units: $ leads, others trail", () => { | |
| 300 | expect(withUnit(12, "$")).toBe("$12"); | |
| 301 | expect(withUnit(1.5, "GiB")).toBe("1.5 GiB"); | |
| 302 | expect(withUnit(3)).toBe("3"); | |
| 303 | }); | |
| 304 | test("text is 12px, never a native title per point, and a series wears a palette class", () => { | |
| 305 | const pts = [1, 2, 3].map((v, i) => ({ label: `2026-10-20T1${i}:00:00Z`, value: v })); | |
| 306 | const svg = lineChart(pts, "t", { unit: "s" }); | |
| 307 | expect(svg).toContain('font-size="12"'); | |
| 308 | expect(svg).not.toMatch(/font-size="(?!12|72)\d+"/); | |
| 309 | expect(svg.match(/<title>/g)?.length).toBe(1); | |
| 310 | expect(svg).toContain('class="s0"'); | |
| 311 | expect(svg).toContain(">2 s</text>"); | |
| 312 | expect(svg).toContain(">11:00</text>"); | |
| 313 | }); | |
| 314 | test("a hover's data rides on the svg, escaped", () => { | |
| 315 | const svg = barChart([{ label: '"><script>', value: 1 }], "t"); | |
| 316 | expect(svg).not.toContain("<script>"); | |
| 317 | expect(svg).toContain('data-pad="1"'); | |
| 318 | }); | |
| 319 | test("marks draw a dashed vertical only where their label is on the axis", () => { | |
| 320 | const pts = [0, 1, 2].map((i) => ({ label: `2026-10-20T1${i}:00:00Z`, value: i })); | |
| 321 | const svg = lineChart(pts, "t", { marks: [{ label: pts[1]!.label, text: "release abc1234" }, { label: "elsewhere", text: "x" }] }); | |
| 322 | expect(svg.match(/class="mark"/g)?.length).toBe(1); | |
| 323 | expect(svg).toContain("release abc1234"); | |
| 324 | expect(svg).toContain('x1="384"'); | |
| 325 | }); | |
| 326 | test("the legend is HTML under the chart, one key per series", () => { | |
| 327 | const html = stackedArea([{ label: "a", series: "x", value: 1 }, { label: "a", series: "y", value: 2 }], "t"); | |
| 328 | expect(html).toMatch(/<\/svg><ul class="chart-legend"><li><i class="key s0"><\/i>x<\/li><li><i class="key s1"><\/i>y<\/li><\/ul>/); | |
| 329 | expect(html).toContain('class="area s1"'); | |
| 330 | }); | |
| 331 | test("releases become marks on the bucket they fell in", () => { | |
| 332 | const labels = ["2026-10-20T10:00:00Z", "2026-10-20T11:00:00Z", "2026-10-20T12:00:00Z"]; | |
| 333 | expect(bucketOf(labels, Date.parse("2026-10-20T11:25:00Z"))).toBe(labels[1]!); | |
| 334 | expect(bucketOf(labels, Date.parse("2026-10-20T09:59:00Z"))).toBeUndefined(); | |
| 335 | expect(bucketOf(labels, Date.parse("2026-10-20T13:00:00Z"))).toBeUndefined(); | |
| 336 | expect(bucketOf(["a", "b"], 0)).toBeUndefined(); | |
| 337 | app.db.run("INSERT INTO release (sha, repo_id, pull_number, ok, line, created_at) VALUES ('abcdef1234', 'rb', 1, 1, 'ok', '2026-10-20T11:25:00.000Z')"); | |
| 338 | expect(releaseMarks(app.db, labels)).toEqual([{ label: labels[1]!, text: "release abcdef1" }]); | |
| 339 | }); | |
| 340 | test("the client sets text to 12px, shows a tooltip and syncs a crosshair", () => { | |
| 341 | expect(chartJs).toContain("'--fs'"); | |
| 342 | expect(chartJs).toContain("pointermove"); | |
| 343 | expect(chartJs).toContain("o.raw.indexOf(label)"); | |
| 344 | expect(chartJs).not.toContain("innerHTML"); | |
| 345 | }); | |
| 346 | test("the board page ships the chart client and holds no native tooltips", async () => { | |
| 347 | const page = await (await get("/boards/data?source=runs&aggregate=count&groupBy=day&chart=line", "admin")).text(); | |
| 348 | expect(page).toContain("pointermove"); | |
| 349 | expect(page).not.toMatch(/<circle[^>]*><title>/); | |
| 350 | }); | |
| 351 | }); |
test/boards-store.test.ts +2 −2
| @@ -33,7 +33,7 @@ const PANELS = [ | ||
| 33 | 33 | panel("Runs by kind", { source: "runs", aggregate: "count", groupBy: "kind" }), |
| 34 | 34 | panel("Turns by state", { source: "runs", aggregate: "sum", column: "turns", groupBy: "state" }), |
| 35 | 35 | ]; |
| 36 | const LINE = /<path d="M[^"]*" fill="none" stroke="currentColor" stroke-width="2"/g; | |
| 36 | const LINE = /<path class="s0" d="M[^"]*" fill="none" stroke-width="2"/g; | |
| 37 | 37 | const asAdmin = (path: string, init: RequestInit = {}) => |
| 38 | 38 | fetch(servers.url + path, { redirect: "manual", ...init, headers: { authorization: `Bearer ${tok.admin}`, ...init.headers } }); |
| 39 | 39 | const post = (path: string, fields: Record<string, string>, who = "admin", headers: Record<string, string> = {}) => |
| @@ -234,7 +234,7 @@ describe("/boards", () => { | ||
| 234 | 234 | const page = await (await asAdmin("/boards/charts")).text(); |
| 235 | 235 | // runs in range: three days × three kinds for the heat strip; three days of bars, the series set aside |
| 236 | 236 | expect(page.match(/<rect class="cell"/g)?.length).toBe(9); |
| 237 | expect(page.match(/<rect class="bar"/g)?.length).toBe(3); | |
| 237 | expect(page.match(/<rect class="bar s0"/g)?.length).toBe(3); | |
| 238 | 238 | expect(page).toContain('<option value="heat" selected>heat strip</option>'); |
| 239 | 239 | expect(parseBoard({ ...board, panels: [{ ...board.panels[0], chart: "pie" }] }).ok).toBe(false); |
| 240 | 240 | await deleteBoard(app, alice, "charts"); |
new above
offline