Public: anyone can read this; the crew can change it.

Board charts: readable time ticks, y-axis units, hover on stacked areas, marks for rolls and config changes #17081

opened this

Merged 35h 25m ago, live in production

mason/forge:mason/16727-board-charts-readable-time-ticks-y-axis → main 0 commits fork 5 threads · 5 unresolved

  • Merged. mason/16727-board-charts-readable-time-ticks-y-axis was merged into main as 6919047.

Review

Sign in to review this change.
14 files changed +252 −59
docs/design/areas/chart.md +1
@@ -7,6 +7,7 @@ Every chart on a board, on Explore the data and on /system is drawn one way. The
77 - `.chart-box` — the frame `chartBox()` writes (`.is-table` for a table panel); it is the container a narrow chart measures itself against.
88 - `.chart` — the grid: the y values, the plot, the labels under it, the legend. `data-chart` names the kind.
99 - `.chart-y` — the three values of the y axis (top, middle, zero), centred on the gridlines; `.is-rows` for a heat strip's row names.
10 - `.chart-unit` — the unit after the top y value ("ms", "rows"), a span inside `.chart-y` in the chart's muted colour, set under the top value out of the flow so a unit never widens the axis or moves the plot.
1011 - `.chart-plot` — the stretched SVG. `.chart-grid` its three hairlines, `.chart-line` a series' line (`.spark` under a number), `.chart-wash` the faint fill under one line, `.bar` a bar, `.area` a stacked band, `.cell` a heat cell.
1112 - `.chart-hit` — a point's full-height hover column: it says the value (`<title>`), washes on hover and on its link's focus, and is the link to the rows behind the point.
1213 - `.chart-x` — at most five labels under the plot, placed at their points (`.is-one` for a single point, `.is-slots` when a few bars each get their own place); under 440px of chart it keeps the first, the middle and the last.
docs/features/board-chart-hover.md +10 −5
@@ -1,8 +1,8 @@
11 ---
22 topic: Your apps
3 row: Board charts: a synced crosshair, one tooltip and release marks
3 row: Board charts: a synced crosshair, one tooltip and marks
44 ---
5 # Board charts: a synced crosshair, one tooltip and release marks
5 # Board charts: a synced crosshair, one tooltip and marks
66
77 A board's time charts share one crosshair. Point at a chart on a board and a vertical line
88 appears in every time chart on that board, at the same time. One tooltip lists each chart's value
@@ -13,7 +13,7 @@ at that time; past eight charts it ends with "+N more".
1313 its link. A tap outside hides it. A drag still scrolls the page (`touch-action: pan-y`).
1414 - **Keyboard:** Tab to a point's link and the tooltip shows; moving on hides it.
1515
16 Releases show as dashed vertical marks on the time axis (`releaseMarks` in
16 Releases show as dashed vertical marks on the time axis (`boardMarks` in
1717 `src/boards/marks.ts`, oldest first, at most 40, a rolled-back release says so). A mark says
1818 itself in a `data-mark` attribute, not a native `title`; point at or tap it and the tooltip shows
1919 its words. A live redraw leaves the marks where they were.
@@ -26,5 +26,10 @@ Each point carries its label, words and value as `data-` attributes, which the s
2626
2727 Open `/boards/<slug>` as an admin, then point at, tap or Tab to a point on a line chart.
2828
29 Not here yet: readable time ticks ("Mon 20"), units on the y axis, the crosshair on stacked
30 areas, and marks for rolls and config changes. They are in their own issues.
29 Day ticks under a chart lead with the weekday when they span a week ("Mon 20"), naming the month
30 where they cross into another ("Sun Nov 30", "Mon Dec 1"); over a longer range they say the month
31 and day ("Nov 3"). Under the top of the y axis is its unit ("ms", "rows"), taken from the panel's aggregate and column. A stacked area
32 has a hover column per time too: its tooltip says the stack's total. Marks are releases (the cut
33 and the moment the roll went live), and config changes ("Config forge: keys by name": the keys,
34 never the values). In the terminal, `/boards/<slug>` lists the same marks under the panels
35 ("marked on the charts") and the unit after a panel's latest value.
src/boards/chart.ts +56 −21
@@ -57,6 +57,7 @@ export function formatValue(v: number): string {
5757 return grouped(v, a >= 100 ? 0 : a >= 10 ? 1 : 2);
5858 }
5959
60 const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
6061 const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
6162 const STAMP = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2})(?::(\d{2}))?(?::[\d.]+)?Z?)?$/;
6263
@@ -77,6 +78,33 @@ export function sayLabels(labels: readonly string[]): (label: string) => string
7778 return daily ? (l) => labelWords(l.slice(0, 10)) : labelWords;
7879 }
7980
81 const WEEK_MS = 7 * 86_400_000;
82 /**
83 * Day ticks as words. Within a week a reader finds a day by its weekday ("Mon 20"), and the month
84 * is said where the ticks cross into another ("Sun Nov 30", "Mon Dec 1"); past a week the
85 * weekday says nothing a reader can place, so every tick is the month and day ("Nov 3").
86 */
87 function dayTicks(parts: readonly (RegExpExecArray | null)[]): string[] {
88 const dated = parts.filter((m): m is RegExpExecArray => m !== null);
89 const utc = (m: RegExpExecArray) => Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
90 const month = (m: RegExpExecArray) => MONTHS[Number(m[2]) - 1] ?? m[2]!;
91 const date = (m: RegExpExecArray) => String(Number(m[3]));
outdated

Principle 8 (plain words) and the issue's 'readable ticks': the weekday replaces the month, so ticks 30 days apart say 'Mon 3 ... Mon 31 ... Mon 14' with no month. Keep the month when the ticks cross one or span more than a week, and test a month boundary.

92 const first = dated[0];
93 const last = dated[dated.length - 1];
94 if (first !== undefined && last !== undefined && utc(last) - utc(first) > WEEK_MS) {
95 return parts.map((m) => (m === null ? "" : `${month(m)} ${date(m)}`));
96 }
97 const crosses = dated.some((m) => month(m) !== month(dated[0]!));
98 let seen = "";
99 return parts.map((m) => {
100 if (m === null) return "";
101 const name = month(m);
102 const words = `${WEEKDAYS[new Date(utc(m)).getUTCDay()]} ${crosses && name !== seen ? `${name} ` : ""}${date(m)}`;
103 seen = name;
104 return words;
105 });
106 }
107
80108 /**
81109 * The labels under a plot, for the few points that get one: a day for day
82110 * buckets, and for ticks that each fall on a day of their own; otherwise the
@@ -89,12 +117,13 @@ function tickWords(labels: readonly string[]): string[] {
89117 const daily =
90118 parts.every((m) => m === null || m[4] === undefined || (m[4] === "00" && (m[5] ?? "00") === "00")) ||
91119 (labels.length > 1 && days.every((d, i) => d !== "" && d !== days[i - 1]));
120 const dayWords = daily ? dayTicks(parts) : [];
92121 let day = "";
93122 return labels.map((l, i) => {
94123 const m = parts[i];
95124 if (m === null || m === undefined) return clean(l);
96125 const d = days[i]!;
97 if (daily) return d;
126 if (daily) return dayWords[i]!;
98127 const at = `${m[4]}:${m[5] ?? "00"}`;
99128 const out = d === day ? at : `${d}, ${at}`;
100129 day = d;
@@ -170,8 +199,13 @@ const GRID = [0, 50, 100].map((y) => `<line class="chart-grid" x1="0" x2="100" y
170199 const plot = (inner: string) => `<svg class="chart-plot" viewBox="0 0 100 100" preserveAspectRatio="none" focusable="false">${GRID}${inner}</svg>`;
171200 const markNote = (marks: readonly Mark[] | undefined) =>
172201 marks === undefined || marks.length === 0 ? "" : ` Marked: ${marks.slice(-MARK_CAP).map((m) => clean(m.text)).join("; ")}.`;
173 const yAxis = (s: { top: number; bottom: number }) =>
174 `<div class="chart-y" aria-hidden="true"><span>${escapeXml(formatValue(s.top))}</span><span>${escapeXml(formatValue((s.top + s.bottom) / 2))}</span><span>${escapeXml(formatValue(s.bottom))}</span></div>`;
202 /**
203 * What a y value counts ("ms", "rows"): said once, after the top value of the axis, and in the
204 * chart's sentence.
205 */
206 const unitWords = (unit: string | undefined) => (unit === undefined ? "" : clean(unit).slice(0, 16));
207 const yAxis = (s: { top: number; bottom: number }, unit?: string) =>
208 `<div class="chart-y" aria-hidden="true"><span>${escapeXml(formatValue(s.top))}${unitWords(unit) === "" ? "" : ` <span class="chart-unit">${escapeXml(unitWords(unit))}</span>`}</span><span>${escapeXml(formatValue((s.top + s.bottom) / 2))}</span><span>${escapeXml(formatValue(s.bottom))}</span></div>`;
175209
176210 /**
177211 * At most X_TICKS labels under the plot, evenly spread from its first point to
@@ -193,13 +227,13 @@ const legend = (names: readonly string[]) =>
193227 `<ul class="chart-key">${names.map((n, i) => `<li title="${t(n)}"><svg class="fg-s${i % 8}" viewBox="0 0 8 8" width="8" height="8" aria-hidden="true"><rect width="8" height="8" rx="2"/></svg><span>${t(n)}</span></li>`).join("")}</ul>`;
194228
195229 /** What the picture says, for a reader who cannot see it. */
196 function says(title: string, labels: readonly string[], values: readonly number[]): string {
230 function says(title: string, labels: readonly string[], values: readonly number[], unit?: string): string {
197231 if (values.length === 0) return `${clean(title)}: no points.`;
198232 const say = sayLabels(labels);
199233 const first = say(labels[0] ?? "");
200234 const last = say(labels[labels.length - 1] ?? "");
201235 const range = labels.length === 1 ? `1 point, ${first}` : `${labels.length} points from ${first} to ${last}`;
202 return `${clean(title)}: ${range}; lowest ${formatValue(Math.min(...values))}, highest ${formatValue(Math.max(...values))}, latest ${formatValue(values[values.length - 1] ?? 0)}.`;
236 return `${clean(title)}: ${range}; lowest ${formatValue(Math.min(...values))}, highest ${formatValue(Math.max(...values))}, latest ${formatValue(values[values.length - 1] ?? 0)}${unitWords(unit) === "" ? "" : ` ${unitWords(unit)}`}.`;
203237 }
204238
205239 const frame = (kind: Chart, title: string, summary: string, inner: string) =>
@@ -208,17 +242,18 @@ const nothing = (kind: Chart, title: string) =>
208242 frame(kind, title, `${clean(title)}: no points.`, `<p class="chart-none">No points in this range.</p>`);
209243
210244 /** One column per point (or per few, past MAX_HITS) that says the point's value on hover and links to its rows. */
211 function hits(points: readonly Point[], x: (i: number) => number): string {
245 function hits(points: readonly Point[], x: (i: number) => number, extra?: (i: number) => string): string {
212246 const n = points.length;
213247 const say = sayLabels(points.map((p) => p.label));
214248 const every = Math.ceil(n / MAX_HITS);
215249 const out: string[] = [];
216250 for (let i = 0; i < n; i += every) {
217 const p = points[Math.min(n - 1, i + Math.floor(every / 2))]!;
251 const pick = Math.min(n - 1, i + Math.floor(every / 2));
252 const p = points[pick]!;
218253 const left = i === 0 ? 0 : (x(i - 1) + x(i)) / 2;
219254 const end = Math.min(n - 1, i + every - 1);
220255 const right = end === n - 1 ? 100 : (x(end) + x(end + 1)) / 2;
221 out.push(linked(p.href, `<rect class="chart-hit" x="${num(left)}" y="0" width="${num(right - left)}" height="100" ${tip(p.label, say(p.label), p.value)}/>`));
256 out.push(linked(p.href, `<rect class="chart-hit" x="${num(left)}" y="0" width="${num(right - left)}" height="100" ${tip(p.label, say(p.label), p.value)}${extra === undefined ? "" : extra(pick)}/>`));
222257 }
223258 return out.join("");
224259 }
@@ -229,19 +264,19 @@ const path = (values: readonly number[], x: (i: number) => number, y: (v: number
229264 ? `M40 ${num(y(values[0]!))} L60 ${num(y(values[0]!))}`
230265 : values.map((v, i) => `${i === 0 ? "M" : "L"}${num(x(i))} ${num(y(v))}`).join(" ");
231266
232 export function lineChart(points: readonly Point[], title: string, marks?: readonly Mark[]): string {
267 export function lineChart(points: readonly Point[], title: string, marks?: readonly Mark[], unit?: string): string {
233268 if (points.length === 0) return nothing("line", title);
234269 const values = points.map((p) => p.value);
235270 const s = scale(Math.min(...values), Math.max(...values));
236271 const x = across(points.length);
237272 const d = path(values, x, s.y);
238273 const wash = points.length < 2 ? "" : `<path class="chart-wash" d="${d} L100 ${num(s.y(0))} L0 ${num(s.y(0))} Z"/>`;
239 return frame("line", title, says(title, points.map((p) => p.label), values) + markNote(marks),
240 `${yAxis(s)}${plot(`${wash}<path class="chart-line" d="${d}"/>${hits(points, x)}${marksSvg(marks, points.map((p) => p.label), x)}`)}${xAxis(points.map((p) => p.label))}`);
274 return frame("line", title, says(title, points.map((p) => p.label), values, unit) + markNote(marks),
275 `${yAxis(s, unit)}${plot(`${wash}<path class="chart-line" d="${d}"/>${hits(points, x)}${marksSvg(marks, points.map((p) => p.label), x)}`)}${xAxis(points.map((p) => p.label))}`);
241276 }
242277
243278 /** One bar per point, from zero; a slot is 100 / n wide and the bar 70% of it. */
244 export function barChart(points: readonly Point[], title: string, marks?: readonly Mark[]): string {
279 export function barChart(points: readonly Point[], title: string, marks?: readonly Mark[], unit?: string): string {
245280 if (points.length === 0) return nothing("bar", title);
246281 const values = points.map((p) => p.value);
247282 const s = scale(Math.min(...values), Math.max(...values));
@@ -252,8 +287,8 @@ export function barChart(points: readonly Point[], title: string, marks?: readon
252287 const h = Math.abs(s.y(p.value) - s.y(0));
253288 return linked(p.href, `<rect class="bar" x="${num(slot * i + slot * 0.15)}" y="${num(top)}" width="${num(slot * 0.7)}" height="${num(h)}" ${tip(p.label, say(p.label), p.value)}/>`);
254289 });
255 return frame("bar", title, says(title, points.map((p) => p.label), values) + markNote(marks),
256 `${yAxis(s)}${plot(bars.join("") + marksSvg(marks, points.map((p) => p.label), (i) => slot * (i + 0.5)))}${xAxis(points.map((p) => p.label), true)}`);
290 return frame("bar", title, says(title, points.map((p) => p.label), values, unit) + markNote(marks),
291 `${yAxis(s, unit)}${plot(bars.join("") + marksSvg(marks, points.map((p) => p.label), (i) => slot * (i + 0.5)))}${xAxis(points.map((p) => p.label), true)}`);
257292 }
258293
259294 /**
@@ -293,7 +328,7 @@ export function gridOf(cells: readonly Cell[], keep: number) {
293328 * colour. Negative values are drawn as 0 (a stack of signed values has no
294329 * single reading) and the scale is the tallest stack.
295330 */
296 export function stackedArea(cells: readonly Cell[], title: string, marks?: readonly Mark[]): string {
331 export function stackedArea(cells: readonly Cell[], title: string, marks?: readonly Mark[], unit?: string): string {
297332 const { xs, names, values } = gridOf(cells, MAX_SERIES);
298333 if (xs.length === 0) return nothing("area", title);
299334 const pos = values.map((r) => r.map((v) => Math.max(0, v)));
@@ -311,8 +346,8 @@ export function stackedArea(cells: readonly Cell[], title: string, marks?: reado
311346 upper.forEach((v, i) => (base[i] = v));
312347 return `<path class="area fg-s${k % 8}" d="${[...fwd, ...back, "Z"].join(" ")}"><title>${t(n)}: ${escapeXml(formatValue(total))} in all</title></path>`;
313348 });
314 return frame("area", title, `${says(title, xs, tops)} Stacked: ${names.map(clean).join(", ")}.${markNote(marks)}`,
315 `${yAxis(s)}${plot(bands.join("") + marksSvg(marks, xs, x))}${xAxis(xs)}${legend(names)}`);
349 return frame("area", title, `${says(title, xs, tops, unit)} Stacked: ${names.map(clean).join(", ")}.${markNote(marks)}`,
350 `${yAxis(s, unit)}${plot(bands.join("") + hits(xs.map((label, i) => ({ label, value: tops[i]! })), x, (i) => ` data-b="${escapeXml(JSON.stringify(names.map((n, k) => [clean(n), formatValue(pos[k]![i]!)])))}"`) + marksSvg(marks, xs, x))}${xAxis(xs)}${legend(names)}`);
316351 }
317352
318353 /**
@@ -384,12 +419,12 @@ export function emptySource(kind: Chart, title: string, source: string): string
384419 * One chart by name: the one door a page draws a panel through. With a `source` name and no
385420 * cells, the panel says its source has nothing recorded instead of drawing an empty chart.
386421 */
387 export function drawChart(chart: Chart, cells: readonly Cell[], title: string, source?: string, marks?: readonly Mark[]): string {
422 export function drawChart(chart: Chart, cells: readonly Cell[], title: string, source?: string, marks?: readonly Mark[], unit?: string): string {
388423 if (cells.length === 0 && source !== undefined && clean(source) !== "") return emptySource(chart, title, source);
389424 switch (chart) {
390 case "line": return lineChart(cells, title, marks);
391 case "bar": return barChart(cells, title, marks);
392 case "area": return stackedArea(cells, title, marks);
425 case "line": return lineChart(cells, title, marks, unit);
426 case "bar": return barChart(cells, title, marks, unit);
427 case "area": return stackedArea(cells, title, marks, unit);
393428 case "number": return numberChart(cells, title);
394429 case "heat": return heatStrip(cells, title);
395430 case "table": return tableChart(cells, title);
src/boards/marks.ts +49 −9
@@ -1,21 +1,61 @@
11 /**
2 * The marks every time chart on a board carries: the forge's releases, as the release keeper cut
3 * them (`keeper_release`), one vertical line each. Plain rows in, plain marks out; a chart draws
4 * only those inside its own span (`marksSvg`). A forge that has cut none draws none.
2 * The marks every time chart on a board carries, one vertical line each: the forge's releases as
3 * the release keeper cut them (`keeper_release`: the cut, and the moment the roll went live) and
4 * its configuration changes (`config_change`: which scope, which keys, by whom). Plain rows in,
5 * plain marks out; a chart draws only those inside its own span (`marksSvg`). A forge that has
6 * none draws none.
57 */
68 import type { Database } from "bun:sqlite";
79 import { MARK_CAP as LIMIT, type Mark } from "./chart.ts";
810
9 /** The newest releases as marks, oldest first; a failed read is no marks, never a failed page. */
11 const cap = (limit: number) => Math.max(1, Math.min(limit, LIMIT));
12
13 /**
14 * The newest releases as marks, oldest first: each one's cut, and its roll going live when it did.
15 * A failed read is no marks, never a failed page.
16 */
1017 export function releaseMarks(db: Database, limit = LIMIT): Mark[] {
1118 try {
1219 const rows = db
13 .query("SELECT version, stage, cut_at FROM keeper_release ORDER BY cut_at DESC LIMIT ?")
14 .all(Math.max(1, Math.min(limit, LIMIT))) as { version: string; stage: string; cut_at: string }[];
15 return rows
16 .reverse()
17 .map((r) => ({ at: r.cut_at, text: `Release ${r.version}${r.stage === "rolled_back" ? " (rolled back)" : ""}` }));
20 .query("SELECT version, stage, cut_at, live_at FROM keeper_release ORDER BY cut_at DESC LIMIT ?")
21 .all(cap(limit)) as { version: string; stage: string; cut_at: string; live_at: string | null }[];
22 return rows.reverse().flatMap((r) => {
23 const cut = { at: r.cut_at, text: `Release ${r.version}${r.stage === "rolled_back" ? " (rolled back)" : ""}` };
24 return r.live_at === null ? [cut] : [cut, { at: r.live_at, text: `Rolled ${r.version} live` }];
25 });
1826 } catch {
1927 return [];
2028 }
2129 }
30
31 /**
32 * The newest configuration changes as marks, oldest first; the keys are named, never their values.
33 */
34 export function configMarks(db: Database, limit = LIMIT): Mark[] {
35 try {
36 const rows = db
37 .query("SELECT scope, keys, by, at FROM config_change ORDER BY at DESC LIMIT ?")
38 .all(cap(limit)) as { scope: string; keys: string; by: string; at: string }[];
39 return rows.reverse().map((r) => {
40 let keys: string[] = [];
41 try {
42 const parsed: unknown = JSON.parse(r.keys);
43 if (Array.isArray(parsed)) keys = parsed.filter((k): k is string => typeof k === "string").slice(0, 3);
44 } catch { /* keys unreadable: the mark says the scope alone */ }
45 return { at: r.at, text: `Config ${r.scope}${keys.length === 0 ? "" : `: ${keys.join(", ")}`} by ${r.by}` };
46 });
47 } catch {
48 return [];
49 }
50 }
51
52 /**
53 * Every mark a board draws: releases, rolls and config changes, oldest first, the newest `limit`
54 * kept.
55 */
56 export function boardMarks(db: Database, limit = LIMIT): Mark[] {
57 return [...releaseMarks(db, limit), ...configMarks(db, limit)]
58 .filter((m) => !Number.isNaN(Date.parse(m.at)))
59 .sort((a, b) => Date.parse(a.at) - Date.parse(b.at))
60 .slice(-cap(limit));
61 }
src/boards/panel_data.ts +11 −1
@@ -133,6 +133,16 @@ export const cellsOf = (rows: readonly Row[], hrefs: readonly (string | null)[]
133133 ...(hrefs[i] ? { href: hrefs[i]! } : {}),
134134 }));
135135
136 /**
137 * What a panel's y values count: "rows" for a count; the unit alone for a column ending `_ms`,
138 * `_s`, `_bytes` or `_cents`. Nothing for any other column: a column's name is not a unit.
139 */
140 export function unitOf(query: Record<string, unknown>): string | undefined {
141 if (query.aggregate === "count") return "rows";
142 const c = query.column;
143 return typeof c === "string" ? /_(ms|s|bytes|cents)$/.exec(c)?.[1] : undefined;
144 }
145
136146 /** A panel as it is drawn: its chart's markup and, for one series over time, its latest value; or why it could not be read. */
outdated

A column name is not a unit: max(id) would read 'id'. Return undefined unless the column ends in _ms, _s, _bytes or _cents, and test unitOf directly.

137147 export type PanelDrawn = { ok: true; chart: string; latest: number | null } | { ok: false; error: string };
138148
@@ -149,7 +159,7 @@ export function latestOf(panel: Panel, rows: readonly Row[]): number | null {
149159 export function drawnPanel(panel: Panel, answer: PanelData, marks?: readonly Mark[]): PanelDrawn {
150160 if (!answer.ok) return answer;
151161 const latest = latestOf(panel, answer.rows);
152 return { ok: true, chart: drawChart(panel.chart, cellsOf(answer.rows), panel.title, typeof panel.query.source === "string" ? panel.query.source : undefined, marks), latest };
162 return { ok: true, chart: drawChart(panel.chart, cellsOf(answer.rows), panel.title, typeof panel.query.source === "string" ? panel.query.source : undefined, marks, unitOf(panel.query)), latest };
153163 }
154164
155165 /** A text cell a spreadsheet will not read as a formula, quoted when it holds a comma, quote or newline. */
src/flow/pages_read.ts +2 −2
@@ -22,7 +22,7 @@ import type { App, ForgeConfig } from "../app.ts";
2222 import { drawAnswer, type AnswerDrawn } from "../boards/answer.ts";
2323 import { GUIDE } from "../boards/guide.ts";
2424 import { toQuery, type Params } from "../boards/params.ts";
25 import { releaseMarks } from "../boards/marks.ts";
25 import { boardMarks } from "../boards/marks.ts";
2626 import { drawnPanel, panelData, runFor, type PanelDrawn } from "../boards/panel_data.ts";
2727 import { runQuery } from "../boards/query.ts";
2828 import { BOARDS_OWNER, BOARDS_REPO, listBoards, readBoard, type Board, type Stored } from "../boards/store.ts";
@@ -338,7 +338,7 @@ export async function readFlowPicture(env: PagesEnv, job: FlowJob): Promise<Flow
338338 export async function readBoardPicture(env: PagesEnv, job: BoardJob): Promise<BoardPicture> {
339339 const t0 = performance.now();
340340 const board = (await readBoard(env.reposRoot, job.slug)) ?? null;
341 const marks = board === null ? [] : releaseMarks(env.db);
341 const marks = board === null ? [] : boardMarks(env.db);
342342 const seen = board === null || job.range === undefined ? board : { ...board, range: job.range };
343343 const panels = board === null || seen === null ? [] : board.panels.map((panel) => drawnPanel(panel, panelData(env.db, seen, panel, {}, job.now), marks));
344344 return { at: job.now, ms: performance.now() - t0, board, panels };
src/tui/screens/boards.ts +15 −8
@@ -15,10 +15,11 @@
1515 */
1616
1717 import { movedKey } from "./moved_key.ts";
18 import { formatValue } from "../../boards/chart.ts";
18 import { formatValue, type Mark } from "../../boards/chart.ts";
19 import { boardMarks } from "../../boards/marks.ts";
1920 import { keyOf } from "../../web/keymap.ts";
2021 import { watchBoard, type Frame } from "../../boards/live_hub.ts";
21 import { panelData, type PanelData } from "../../boards/panel_data.ts";
22 import { panelData, unitOf, type PanelData } from "../../boards/panel_data.ts";
2223 import { RANGES, type Board } from "../../boards/store.ts";
2324 import { nextRange, viewed, type View } from "../../boards/view_bar.ts";
2425 import { listPinned, movePinned, pinPanel, unpinPanel } from "../../actions/board-pins.ts";
@@ -66,23 +67,26 @@ export async function boardRows(session: Session): Promise<BoardRow[]> {
6667 export const stepWords = (s: number): string =>
6768 s % 86_400 === 0 ? `${s / 86_400}d` : s % 3600 === 0 ? `${s / 3600}h` : s % 60 === 0 ? `${s / 60}m` : `${s}s`;
6869
70 /** The newest marks the terminal lists under a board. */
71 const MARKS_SHOWN = 8;
72
6973 /**
7074 * What a panel's data says in one line: its last bucket and step, its row count, or why it was
7175 * refused.
7276 */
73 export function dataLine(d: PanelData): string {
77 export function dataLine(d: PanelData, unit?: string): string {
7478 if (!d.ok) return `refused: ${plain(d.error)}`;
7579 if (d.step === null) return plural(d.rows.length, "row");
7680 const last = d.rows.at(-1);
7781 const at = `step ${stepWords(d.step)} · ${plural(d.rows.length, "point")}`;
78 return last === undefined ? `no points · ${at}` : `last ${plain(String(last.group ?? "all"))}: ${formatValue(last.value ?? 0)} · ${at}`;
82 return last === undefined ? `no points · ${at}` : `last ${plain(String(last.group ?? "all"))}: ${formatValue(last.value ?? 0)}${unit === undefined ? "" : ` ${plain(unit)}`} · ${at}`;
7983 }
8084
8185 /**
8286 * A board, panel by panel, as lines of text; the panel at `at` is marked, a
8387 * pinned one says so, and each panel with its `data` read says what it holds.
8488 */
85 export function boardLines(board: Board, at = -1, pinned: readonly string[] = [], data: readonly PanelData[] = [], moved: ReadonlyMap<number, string> = new Map(), viewing = false): string[] {
89 export function boardLines(board: Board, at = -1, pinned: readonly string[] = [], data: readonly PanelData[] = [], moved: ReadonlyMap<number, string> = new Map(), viewing = false, marks: readonly Mark[] = []): string[] {
8690 const lines = [
8791 plain(board.title),
8892 `range ${board.range} · refresh ${board.refresh} · ${plural(board.panels.length, "panel")}${viewing ? " · a view, not saved" : ""}`,
@@ -93,10 +97,12 @@ export function boardLines(board: Board, at = -1, pinned: readonly string[] = []
9397 .join(" ");
9498 lines.push("", `${i === at ? "▸ " : ""}${plain(p.title)}${pinned.includes(p.title) ? " [pinned to home]" : ""}`, ` ${p.chart} · ${p.w}×${p.h}`, ` ${query === "" ? "no query" : query}`);
9599 const d = data[i];
96 if (d !== undefined) lines.push(` ${dataLine(d)}`);
100 if (d !== undefined) lines.push(` ${dataLine(d, unitOf(p.query))}`);
97101 const m = moved.get(i);
98102 if (m !== undefined) lines.push(` ${m}`);
99103 }
104 // What the page draws as vertical marks on its time charts, newest last.
105 if (marks.length > 0) lines.push("", "marked on the charts (UTC):", ...marks.slice(-MARKS_SHOWN).map((m) => ` ${plain(m.at.slice(0, 16).replace("T", " "))} ${plain(m.text)}`));
100106 return lines;
101107 }
102108
@@ -114,6 +120,7 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
114120 let at = board.panels.length > 0 ? 0 : -1;
115121 let pinned: string[] = [];
116122 let data: PanelData[] = [];
123 let marks: Mark[] = [];
117124 /** The panel `x` asked about (where it sat and its title), until `y` or `n`. */
118125 let asking: { readonly index: number; readonly title: string } | undefined;
119126 // The gate is `changeBoard`'s, read once as the list's is.
@@ -133,7 +140,7 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
133140 // Only an admin person reaches this screen (`showBoard` let them in), as `panelData` asks.
134141 const seen = shown();
135142 data = seen.panels.map((p) => panelData(f.app.db, seen, p));
136 lines = boardLines(seen, at, pinned, data, moved, viewing());
143 lines = boardLines(seen, at, pinned, data, moved, viewing(), (marks = boardMarks(f.app.db)));
137144 ctx.invalidate();
138145 };
139146 /** Pin the marked panel, or unpin it when it is; `by` moves a pinned one in the home order. */
@@ -246,7 +253,7 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
246253 }
247254 if (e.key === "[" || e.key === "]") {
248255 if (board.panels.length > 0) at = (at + (e.key === "]" ? 1 : board.panels.length - 1)) % board.panels.length;
249 lines = boardLines(board, at, pinned, data, moved);
256 lines = boardLines(shown(), at, pinned, data, moved, viewing(), marks);
250257 return true;
251258 }
252259 if (e.key === "v") return look({ ...view, range: nextRange(shown().range) }), true;
src/web/chart_hover.ts +12 −5
@@ -3,10 +3,10 @@
33 * rect carrying `data-l` (its raw label, the key charts on one time axis share), `data-t` (the
44 * label as words) and `data-v` (its value). Pointing at one (a mouse over it, a tap, or focus on
55 * its link) draws a crosshair at the same label in every chart that has it and lists each chart's
6 * value in one tooltip. A release mark (`data-mark`) shows its words alone. Text is set as text,
7 * the tooltip is a popover (the top layer, so no z-index) and `aria-hidden` (the chart's own
8 * sentence is the screen reader's), and without script a chart is still drawn whole. Shipped per
9 * page (`PageOptions.scriptJs`); zero dependencies.
6 * value in one tooltip. A mark (`data-mark`: a release, a roll, a config change) shows its words
7 * alone. Text is set as text, the tooltip is a popover (the top layer, so no z-index) and
8 * `aria-hidden` (the chart's own sentence is the screen reader's), and without script a chart is
9 * still drawn whole. Shipped per page (`PageOptions.scriptJs`); zero dependencies.
1010 */
1111 export const chartHoverJs = /* js */ `
1212 (function () {
@@ -15,7 +15,7 @@ export const chartHoverJs = /* js */ `
1515 tip.className = 'chart-tip'; tip.setAttribute('popover', 'manual'); tip.setAttribute('aria-hidden', 'true');
1616 document.body.appendChild(tip);
1717 var lines = [];
18 function charts() { return document.querySelectorAll('.chart[data-chart="line"], .chart[data-chart="bar"]'); }
18 function charts() { return document.querySelectorAll('.chart[data-chart="line"], .chart[data-chart="bar"], .chart[data-chart="area"]'); }
1919 function hide() {
2020 if (tip.matches(':popover-open')) tip.hidePopover();
2121 lines.forEach(function (l) { l.remove(); });
@@ -64,6 +64,13 @@ export const chartHoverJs = /* js */ `
6464 var name = document.createElement('span'); name.textContent = chart.getAttribute('aria-label') || '';
6565 var val = document.createElement('b'); val.textContent = r.getAttribute('data-v');
6666 row.appendChild(name); row.appendChild(val); rows.appendChild(row);
67 var by = []; try { by = JSON.parse(r.getAttribute('data-b') || '[]'); } catch (e) { by = []; }
68 for (var j = 0; j < by.length && j < 8; j++) {
69 var sr = document.createElement('div');
70 var sn = document.createElement('span'); sn.textContent = String(by[j][0]);
71 var sv = document.createElement('b'); sv.textContent = String(by[j][1]);
72 sr.appendChild(sn); sr.appendChild(sv); rows.appendChild(sr);
73 }
6774 });
6875 if (more) { var m = document.createElement('div'); m.textContent = '+' + more + ' more'; rows.appendChild(m); }
6976 open(head, rows, pt);
src/web/pages/boards-view.ts +2 −2
@@ -34,7 +34,7 @@ import { boardsHoldsCard } from "./boards-holds.ts";
3434 import { alarmLines } from "../studio/alarm_lines.ts";
3535 import { boardPicture, boardsPicture, isFailed, LONG_WAIT_MS, waitAnswer } from "../../flow/pages.ts";
3636 import { isPinned, listPins } from "../../boards/pins.ts";
37 import { releaseMarks } from "../../boards/marks.ts";
37 import { boardMarks } from "../../boards/marks.ts";
3838 import { drawnPanel, panelData, runFor, type PanelDrawn } from "../../boards/panel_data.ts";
3939 import { readParams } from "../../boards/params.ts";
4040 import { paramsOf, queryFields } from "./boards.ts";
@@ -56,7 +56,7 @@ export function drawPanel(
5656 * The panel as a worker read and drew it (`flow/pages.ts`); without it the rows are read and
5757 * drawn here, for a direct caller.
5858 */
59 drawn: PanelDrawn = drawnPanel(panel, panelData(app.db, board, panel, {}, Date.now(), run), releaseMarks(app.db)),
59 drawn: PanelDrawn = drawnPanel(panel, panelData(app.db, board, panel, {}, Date.now(), run), boardMarks(app.db)),
6060 ): Html {
6161 const q = paramsOf(panel.query, panel.chart);
6262 const body = !drawn.ok ? html`<p class="muted small">${drawn.error}</p>` : chartFrame(panel.chart, drawn.chart);
src/web/style/content.ts +3
@@ -231,6 +231,9 @@ a.where-place, button.where-place { cursor: pointer; }
231231 .chart-box { --chart-h: 168px; min-width: 0; color: var(--accent); container-type: inline-size; }
232232 .chart { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 4px 8px; font-size: var(--fs-min); line-height: 16px; color: var(--muted-fg); font-variant-numeric: tabular-nums; }
233233 .chart-y { display: flex; flex-direction: column; align-items: flex-end; justify-content: space-between; height: calc(var(--chart-h) + 16px); margin-block: -8px; white-space: nowrap; }
234 /* The unit sits under the top value, out of the flow, so "12 ms" never widens the axis or moves the plot. */
235 .chart-y > span { position: relative; }
236 .chart-unit { position: absolute; top: 100%; right: 0; }

Non-blocking: an absolutely placed unit can overhang to the left of the axis at 360px if it is longer than the numbers. Cap the unit length (unitWords slices at 16; 8 is enough for ms, rows, bytes, cents) or check it on a phone.

234237 .chart-y.is-rows { justify-content: space-around; height: var(--chart-h); max-width: 112px; margin-block: 0; }
235238 .chart-y.is-rows span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
236239 .chart-plot { touch-action: pan-y; grid-column: 2; grid-row: 1; display: block; width: 100%; height: var(--chart-h); overflow: visible; color: var(--accent); }
test/boards-marks.test.ts +44 −4
@@ -1,20 +1,21 @@
11 import { describe, expect, test } from "bun:test";
22 import { Database } from "bun:sqlite";
33 import { lineChart, marksSvg, MARK_CAP } from "../src/boards/chart.ts";
4 import { releaseMarks } from "../src/boards/marks.ts";
4 import { unitOf } from "../src/boards/panel_data.ts";
5 import { boardMarks, configMarks, releaseMarks } from "../src/boards/marks.ts";
56 import { boardStreamJs } from "../src/web/pages/boards-stream.ts";
67 import { readFileSync } from "node:fs";
78
89 const db = () => {
910 const d = new Database(":memory:");
10 d.run("CREATE TABLE keeper_release (version TEXT, stage TEXT, cut_at TEXT)");
11 d.run("CREATE TABLE keeper_release (version TEXT, stage TEXT, cut_at TEXT, live_at TEXT)");
1112 return d;
1213 };
1314
1415 describe("releaseMarks", () => {
1516 test("oldest first, rolled back says so", () => {
1617 const d = db();
17 d.run("INSERT INTO keeper_release VALUES ('v2','live','2026-11-02T00:00:00Z'),('v1','rolled_back','2026-11-01T00:00:00Z')");
18 d.run("INSERT INTO keeper_release VALUES ('v2','live','2026-11-02T00:00:00Z',NULL),('v1','rolled_back','2026-11-01T00:00:00Z',NULL)");
1819 expect(releaseMarks(d)).toEqual([
1920 { at: "2026-11-01T00:00:00Z", text: "Release v1 (rolled back)" },
2021 { at: "2026-11-02T00:00:00Z", text: "Release v2" },
@@ -22,7 +23,7 @@ describe("releaseMarks", () => {
2223 });
2324 test("capped at the chart's cap, newest kept", () => {
2425 const d = db();
25 for (let i = 0; i < MARK_CAP + 10; i++) d.run("INSERT INTO keeper_release VALUES (?, 'live', ?)", [`v${i}`, new Date(Date.UTC(2026, 0, 1 + i)).toISOString()]);
26 for (let i = 0; i < MARK_CAP + 10; i++) d.run("INSERT INTO keeper_release VALUES (?, 'live', ?, NULL)", [`v${i}`, new Date(Date.UTC(2026, 0, 1 + i)).toISOString()]);
2627 const m = releaseMarks(d, 1000);
2728 expect(m.length).toBe(MARK_CAP);
2829 expect(m[m.length - 1]!.text).toBe(`Release v${MARK_CAP + 9}`);
@@ -32,6 +33,26 @@ describe("releaseMarks", () => {
3233 });
3334 });
3435
36 describe("rolls and config changes", () => {
37 const both = () => {
38 const d = db();
39 d.run("CREATE TABLE config_change (scope TEXT, keys TEXT, by TEXT, at TEXT)");
40 d.run("INSERT INTO keeper_release VALUES ('v3','live','2026-11-02T00:00:00Z','2026-11-02T00:10:00Z')");
41 d.run("INSERT INTO config_change VALUES ('forge','[\"a\",\"b\"]','mason','2026-11-02T00:05:00Z'),('app/x','not json','ana','2026-11-01T00:00:00Z')");
42 return d;
43 };
44 test("a roll that went live is its own mark", () => {
45 expect(releaseMarks(both()).map((m) => m.text)).toEqual(["Release v3", "Rolled v3 live"]);
46 });
47 test("a config change names its scope, keys and author, never values", () => {
48 expect(configMarks(both()).map((m) => m.text)).toEqual(["Config app/x by ana", "Config forge: a, b by mason"]);
49 });
50 test("a board's marks are all of them in time order", () => {
51 expect(boardMarks(both()).map((m) => m.text)).toEqual(["Config app/x by ana", "Release v3", "Config forge: a, b by mason", "Rolled v3 live"]);
52 expect(boardMarks(new Database(":memory:"))).toEqual([]);
53 });
54 });
55
3556 describe("marks on a chart", () => {
3657 const days = ["2026-11-01", "2026-11-02", "2026-11-03"].map((label, i) => ({ label, value: i }));
3758 test("sorted by instant, not by string, across offsets", () => {
@@ -56,3 +77,22 @@ describe("the board page and the live redraw", () => {
5677 expect(boardStreamJs).not.toContain("chart-mark");
5778 });
5879 });
80
81 describe("unitOf", () => {
82 test("a count is rows, a known suffix is the unit, anything else has none", () => {
83 expect(unitOf({ aggregate: "count" })).toBe("rows");
84 expect(unitOf({ aggregate: "avg", column: "duration_ms" })).toBe("ms");
85 expect(unitOf({ aggregate: "max", column: "id" })).toBeUndefined();
86 expect(unitOf({ aggregate: "sum", column: "status" })).toBeUndefined();
87 expect(unitOf({ aggregate: "sum" })).toBeUndefined();
88 });
89 });
90
91 describe("boardMarks with an unreadable time", () => {
92 test("a mark whose time does not parse is left out", () => {
93 const d = db();
94 d.run("INSERT INTO keeper_release VALUES ('1.0','live','not a time',NULL)");
95 d.run("INSERT INTO keeper_release VALUES ('1.1','live','2026-11-02T00:00:00Z',NULL)");
96 expect(boardMarks(d).map((m) => m.text)).toEqual(["Release 1.1"]);
97 });
98 });
test/boards-page.test.ts +1 −1
@@ -302,7 +302,7 @@ describe("chart geometry", () => {
302302 expect([...hours.matchAll(/<span><span>([^<]*)<\/span><\/span>/g)].map((m) => m[1])).toEqual(["Nov 12, 23:00", "Nov 13, 00:00", "01:00"]);
303303 // Ticks that each fall on a day of their own say the day: a time alone would not say which.
304304 const week = lineChart(Array.from({ length: 5 }, (_, d) => ({ label: `2026-11-0${d + 1}T17:00:00Z`, value: d })), "t");
305 expect([...week.matchAll(/<span><span>([^<]*)<\/span><\/span>/g)].map((m) => m[1])).toEqual(["Nov 1", "Nov 2", "Nov 3", "Nov 4", "Nov 5"]);
305 expect([...week.matchAll(/<span><span>([^<]*)<\/span><\/span>/g)].map((m) => m[1])).toEqual(["Sun 1", "Mon 2", "Tue 3", "Wed 4", "Thu 5"]);
306306 });
307307 test("a chart says in a sentence what its picture shows", () => {
308308 expect(lineChart([{ label: "2026-11-12", value: 3 }, { label: "2026-11-13", value: 1 }], "Runs")).toContain('<p class="sr-only">Runs: 2 points from Nov 12 to Nov 13; lowest 1, highest 3, latest 1.</p>');
test/chart-hover-marks.test.ts +34 −1
@@ -1,5 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2 import { barChart, lineChart, marksSvg } from "../src/boards/chart.ts";
2 import { barChart, lineChart, marksSvg, stackedArea } from "../src/boards/chart.ts";
33 import { chartHoverJs } from "../src/web/chart_hover.ts";
44
55 const days = ["2026-11-01", "2026-11-02", "2026-11-03", "2026-11-04", "2026-11-05"].map((label, i) => ({ label, value: i * 10 }));
@@ -17,6 +17,39 @@ describe("a point says itself in attributes, not native titles", () => {
1717 });
1818 });
1919
20 describe("readable ticks, units and stacked hover", () => {
21 test("day ticks lead with the weekday", () => {
22 expect(lineChart(days, "Runs")).toContain("<span><span>Sun 1</span></span>");
23 });
24 const ticks = (labels: string[]) =>
25 [...lineChart(labels.map((label, value) => ({ label, value })), "t").matchAll(/<span><span>([^<]*)<\/span><\/span>/g)].map((m) => m[1]);
26 test("day ticks that cross a month say the month where it starts and where it turns", () => {
27 expect(ticks(["2026-11-28", "2026-11-29", "2026-11-30", "2026-12-01", "2026-12-02"])).toEqual(["Sat Nov 28", "Sun 29", "Mon 30", "Tue Dec 1", "Wed 2"]);
28 });
29 test("day ticks over more than a week say the month and day, not the weekday", () => {
30 const month = Array.from({ length: 91 }, (_, d) => new Date(Date.UTC(2026, 8, 3 + d)).toISOString().slice(0, 10));
31 expect(ticks(month)).toEqual(["Sep 3", "Sep 26", "Oct 18", "Nov 10", "Dec 2"]);
32 });
33 test("a unit follows the top of the y axis and ends the sentence", () => {
34 const html = lineChart(days, "Runs", undefined, "ms");
35 expect(html).toContain('<span class="chart-unit">ms</span>');
36 expect(html).toContain("latest 40 ms.");
37 expect(lineChart(days, "Runs")).not.toContain("chart-unit");
38 });
39 test("a stacked area has a hover column per x, valued at the stack", () => {
40 const cells = days.flatMap((d) => ["a", "b"].map((series) => ({ ...d, series, value: 5 })));
41 const html = stackedArea(cells, "Runs");
42 expect(html).toContain(`data-l="2026-11-03" data-t="Nov 3" data-v="10"`);
43 expect(chartHoverJs).toContain('data-chart="area"');
44 });
45 test("each stacked hover column carries every series' value for the tooltip", () => {
46 const cells = days.flatMap((d) => ["a", "b"].map((series, k) => ({ ...d, series, value: 5 + k })));
47 const html = stackedArea(cells, "Runs");
48 expect(html).toContain(`data-b="[[&quot;a&quot;,&quot;5&quot;],[&quot;b&quot;,&quot;6&quot;]]"`);
49 expect(chartHoverJs).toContain("data-b");
50 });
51 });
52
2053 describe("release marks", () => {
2154 test("a mark halfway between two days sits halfway between their x", () => {
2255 // 5 days → x = 0, 25, 50, 75, 100; 2026-11-02T12:00 is between day 2 and 3 → 37.5.
test/tui-boards.test.ts +12
@@ -247,3 +247,15 @@ test("a live frame says, under its panel, how many points moved and the latest v
247247 const lines = boardLines(board, -1, [], [], new Map([[1, liveWords(frame, 1)!]]));
248248 expect(lines.filter((l) => l.includes("live 16:05:09Z"))).toHaveLength(1);
249249 });
250
251 test("the terminal lists the marks the page draws, and a panel's unit after its latest value", async () => {
252 const { boardLines, dataLine } = await import("../src/tui/screens/boards.ts");
253 const panel: Panel = { title: "A", chart: "line", query: { source: "runs", aggregate: "avg", column: "duration_ms", groupBy: { bucket: "hour" } }, w: 1, h: 1 };
254 const board: Board = { title: "T", range: "all", refresh: "10s", panels: [panel] };
255 const data = { ok: true as const, rows: [{ group: "2026-11-02T00:00:00Z", value: 12 }], from: null, to: null, step: 3600 };
256 const lines = boardLines(board, -1, [], [data], new Map(), false, [{ at: "2026-11-02T00:10:00Z", text: "Rolled v3 live" }]);
257 expect(lines.some((l) => l.includes("12 ms"))).toBe(true);
258 expect(lines).toContain("marked on the charts (UTC):");
259 expect(lines).toContain(" 2026-11-02 00:10 Rolled v3 live");
260 expect(dataLine(data)).not.toContain(" ms");
261 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs