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 #16686
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/3694-observability-5-one-great-chart-real-siz → main 0 commits fork 3 threads · 3 unresolved
15 files
changed +461
−30
- docs/design/areas/chart.md
- docs/features/board-chart-hover.md
- src/boards/chart.ts
- src/boards/marks.ts
- src/boards/panel_data.ts
- src/flow/pages_read.ts
- src/web/chart_hover.ts
- src/web/pages/boards-stream.ts
- src/web/pages/boards-view.ts
- src/web/style/content.ts
- test/boards-marks.test.ts
- test/boards-page.test.ts
- test/boards-stream.test.ts
- test/chart-hover-marks.test.ts
- test/chart-hover-script.test.ts
docs/design/areas/chart.md +10
| @@ -32,3 +32,13 @@ Drawn by `src/web/studio/money_line.ts`; styled in `src/web/style/content.ts`. | ||
| 32 | 32 | - `.money-gap` — the gap, signed with + or −, in the text colour; `data-sign="down"` (a loss) alone takes `--attn`. The accent is never a gap's: it is for the link. The app page's month card wears it too. |
| 33 | 33 | - `.money-spend` — the slider's position in words (#11102), the line's one link to Settings → Economics, in the accent; it never breaks inside itself, so the row wraps between its parts. |
| 34 | 34 | - `.money-chart` — the thirty-day SVG, 240 × 48, server-rendered, no library. `.money-cost` (muted) and `.money-revenue` (text colour) are its two polylines; `.money-band` holds one polygon per pair of days, `data-sign` tinting the gap between them: a faint text-colour wash for a profit, `--attn` for a loss. |
| 35 | ||
| 36 | ## Hover and release marks (#3694) | |
| 37 | ||
| 38 | `.chart-tip` is the one tooltip of every line and bar chart on a page (a popover, so it sits in the | |
| 39 | top layer with no z-index): the hovered label in bold, then each chart that has that label and its | |
| 40 | value. `.chart-cross` is the crosshair drawn at that label in each of those charts, solid in the text | |
| 41 | colour. `.chart-mark` is a release, roll or config change: a dashed vertical line in the muted text | |
| 42 | colour, named in the chart's sentence for a screen reader. `.chart-mark-hit` is its invisible, wider twin that a pointer or | |
| 43 | finger finds; its `data-mark` words go in the tooltip. The tooltip has no border or shadow: it is a | |
| 44 | `--muted` fill over the card. |
docs/features/board-chart-hover.md added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | --- | |
| 2 | topic: Your apps | |
| 3 | row: Board charts: a synced crosshair, one tooltip and release marks | |
| 4 | --- | |
| 5 | # Board charts: a synced crosshair, one tooltip and release marks | |
| 6 | ||
| 7 | A board's time charts share one crosshair. Point at a chart on a board and a vertical line | |
| 8 | appears in every time chart on that board, at the same time. One tooltip lists each chart's value | |
| 9 | at that time; past eight charts it ends with "+N more". | |
| 10 | ||
| 11 | - **Mouse:** move over a chart. Move off it, scroll, or press Escape and both go away. | |
| 12 | - **Phone:** tap a point. The first tap shows the tooltip; a second tap on the same point follows | |
| 13 | its link. A tap outside hides it. A drag still scrolls the page (`touch-action: pan-y`). | |
| 14 | - **Keyboard:** Tab to a point's link and the tooltip shows; moving on hides it. | |
| 15 | ||
| 16 | Releases show as dashed vertical marks on the time axis (`releaseMarks` in | |
| 17 | `src/boards/marks.ts`, oldest first, at most 40, a rolled-back release says so). A mark says | |
| 18 | itself in a `data-mark` attribute, not a native `title`; point at or tap it and the tooltip shows | |
| 19 | its words. A live redraw leaves the marks where they were. | |
| 20 | ||
| 21 | The hover code is a few lines of inline script (`src/web/chart_hover.ts`). The charts are | |
| 22 | server-rendered SVG, so without script they still show every point; the crosshair only adds. | |
| 23 | Each point carries its label, words and value as `data-` attributes, which the script reads. | |
| 24 | ||
| 25 | ## Try it | |
| 26 | ||
| 27 | Open `/boards/<slug>` as an admin, then point at, tap or Tab to a point on a line chart. | |
| 28 | ||
| 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. |
src/boards/chart.ts +61 −16
| @@ -105,7 +105,50 @@ function tickWords(labels: readonly string[]): string[] { | ||
| 105 | 105 | const t = (s: string) => escapeXml(clean(s)); |
| 106 | 106 | const linked = (href: string | undefined, inner: string) => |
| 107 | 107 | href === undefined ? inner : `<a href="${escapeXml(href)}">${inner}</a>`; |
| 108 | const tip = (label: string, v: number) => `<title>${escapeXml(label)}: ${escapeXml(formatValue(v))}</title>`; | |
| 108 | /** | |
| 109 | * What a point says on hover, as attributes the page's hover script reads (`web/chart_hover.ts`): | |
| 110 | * its raw label (the key charts on one time axis share), the label as words, its value. No | |
| 111 | * `<title>`: a native tooltip per point is thousands of nodes and cannot be synced or styled. | |
| 112 | */ | |
| 113 | const tip = (raw: string, label: string, v: number) => | |
| 114 | `data-l="${escapeXml(clean(raw))}" data-t="${escapeXml(label)}" data-v="${escapeXml(formatValue(v))}"`; | |
| 115 | ||
| 116 | /** | |
| 117 | * A release, roll or config change drawn as a vertical mark: `at` is an ISO time, `text` what | |
| 118 | * happened. | |
| 119 | */ | |
| 120 | export type Mark = { at: string; text: string }; | |
| 121 | /** The most marks a chart draws; the newest win. */ | |
| 122 | export const MARK_CAP = 40; | |
| 123 | const labelMs = (l: string) => (STAMP.test(l) ? Date.parse(l.length > 10 && !l.endsWith("Z") ? `${l}Z` : l) : Number.NaN); | |
| 124 | ||
| 125 | /** | |
| 126 | * Vertical marks at the x of each mark's time, between the buckets either side of it; only on a | |
| 127 | * chart whose labels are all times, and only for marks inside its span (one bucket past the end | |
| 128 | * counts as the last). `x(i)` is the plot's 0–100 place of bucket `i`. | |
| 129 | */ | |
| 130 | export function marksSvg(marks: readonly Mark[] | undefined, labels: readonly string[], x: (i: number) => number): string { | |
| 131 | if (marks === undefined || marks.length === 0 || labels.length < 2) return ""; | |
| 132 | const ts = labels.map(labelMs); | |
| 133 | if (ts.some((m) => Number.isNaN(m))) return ""; | |
| 134 | const last = ts.length - 1; | |
| 135 | const end = ts[last]! + (ts[last]! - ts[last - 1]!); | |
| 136 | const out: string[] = []; | |
| 137 | for (const m of [...marks].sort((a, b) => Date.parse(a.at) - Date.parse(b.at)).slice(-MARK_CAP)) { | |
| 138 | const at = Date.parse(m.at); | |
| 139 | if (Number.isNaN(at) || at < ts[0]! || at > end) continue; | |
| 140 | let i = 0; | |
| 141 | while (i < last && ts[i + 1]! <= at) i++; | |
| 142 | const f = i === last ? 0 : (at - ts[i]!) / (ts[i + 1]! - ts[i]!); | |
| 143 | const px = x(i) + f * ((i === last ? x(i) : x(i + 1)) - x(i)); | |
| 144 | // The wide, invisible line is what a pointer, a tap or a finger finds; the thin one is what is | |
| 145 | // seen. The hover script reads `data-mark` (the words) and lists it in its tooltip: no | |
| 146 | // `<title>`. | |
| 147 | const at2 = `x1="${num(px)}" x2="${num(px)}" y1="0" y2="100"`; | |
| 148 | out.push(`<line class="chart-mark" ${at2}/><line class="chart-mark-hit" ${at2} data-mark="${t(m.text)}"/>`); | |
| 149 | } | |
| 150 | return out.join(""); | |
| 151 | } | |
| 109 | 152 | |
| 110 | 153 | /** The top of a y axis: the first of these steps, times a power of ten, at or above `v`. */ |
| 111 | 154 | const STEPS = [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]; |
| @@ -125,6 +168,8 @@ function scale(lo: number, hi: number) { | ||
| 125 | 168 | |
| 126 | 169 | const GRID = [0, 50, 100].map((y) => `<line class="chart-grid" x1="0" x2="100" y1="${y}" y2="${y}"/>`).join(""); |
| 127 | 170 | const plot = (inner: string) => `<svg class="chart-plot" viewBox="0 0 100 100" preserveAspectRatio="none" focusable="false">${GRID}${inner}</svg>`; |
| 171 | const markNote = (marks: readonly Mark[] | undefined) => | |
| 172 | marks === undefined || marks.length === 0 ? "" : ` Marked: ${marks.slice(-MARK_CAP).map((m) => clean(m.text)).join("; ")}.`; | |
| 128 | 173 | const yAxis = (s: { top: number; bottom: number }) => |
| 129 | 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>`; |
| 130 | 175 | |
| @@ -173,7 +218,7 @@ function hits(points: readonly Point[], x: (i: number) => number): string { | ||
| 173 | 218 | const left = i === 0 ? 0 : (x(i - 1) + x(i)) / 2; |
| 174 | 219 | const end = Math.min(n - 1, i + every - 1); |
| 175 | 220 | const right = end === n - 1 ? 100 : (x(end) + x(end + 1)) / 2; |
| 176 | out.push(linked(p.href, `<rect class="chart-hit" x="${num(left)}" y="0" width="${num(right - left)}" height="100">${tip(say(p.label), p.value)}</rect>`)); | |
| 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)}/>`)); | |
| 177 | 222 | } |
| 178 | 223 | return out.join(""); |
| 179 | 224 | } |
| @@ -184,19 +229,19 @@ const path = (values: readonly number[], x: (i: number) => number, y: (v: number | ||
| 184 | 229 | ? `M40 ${num(y(values[0]!))} L60 ${num(y(values[0]!))}` |
| 185 | 230 | : values.map((v, i) => `${i === 0 ? "M" : "L"}${num(x(i))} ${num(y(v))}`).join(" "); |
| 186 | 231 | |
| 187 | export function lineChart(points: readonly Point[], title: string): string { | |
| 232 | export function lineChart(points: readonly Point[], title: string, marks?: readonly Mark[]): string { | |
| 188 | 233 | if (points.length === 0) return nothing("line", title); |
| 189 | 234 | const values = points.map((p) => p.value); |
| 190 | 235 | const s = scale(Math.min(...values), Math.max(...values)); |
| 191 | 236 | const x = across(points.length); |
| 192 | 237 | const d = path(values, x, s.y); |
| 193 | 238 | const wash = points.length < 2 ? "" : `<path class="chart-wash" d="${d} L100 ${num(s.y(0))} L0 ${num(s.y(0))} Z"/>`; |
| 194 | return frame("line", title, says(title, points.map((p) => p.label), values), | |
| 195 | `${yAxis(s)}${plot(`${wash}<path class="chart-line" d="${d}"/>${hits(points, x)}`)}${xAxis(points.map((p) => p.label))}`); | |
| 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))}`); | |
| 196 | 241 | } |
| 197 | 242 | |
| 198 | 243 | /** One bar per point, from zero; a slot is 100 / n wide and the bar 70% of it. */ |
| 199 | export function barChart(points: readonly Point[], title: string): string { | |
| 244 | export function barChart(points: readonly Point[], title: string, marks?: readonly Mark[]): string { | |
| 200 | 245 | if (points.length === 0) return nothing("bar", title); |
| 201 | 246 | const values = points.map((p) => p.value); |
| 202 | 247 | const s = scale(Math.min(...values), Math.max(...values)); |
| @@ -205,10 +250,10 @@ export function barChart(points: readonly Point[], title: string): string { | ||
| 205 | 250 | const bars = points.map((p, i) => { |
| 206 | 251 | const top = Math.min(s.y(p.value), s.y(0)); |
| 207 | 252 | const h = Math.abs(s.y(p.value) - s.y(0)); |
| 208 | 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(say(p.label), p.value)}</rect>`); | |
| 253 | 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)}/>`); | |
| 209 | 254 | }); |
| 210 | return frame("bar", title, says(title, points.map((p) => p.label), values), | |
| 211 | `${yAxis(s)}${plot(bars.join(""))}${xAxis(points.map((p) => p.label), true)}`); | |
| 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)}`); | |
| 212 | 257 | } |
| 213 | 258 | |
| 214 | 259 | /** |
| @@ -248,7 +293,7 @@ export function gridOf(cells: readonly Cell[], keep: number) { | ||
| 248 | 293 | * colour. Negative values are drawn as 0 (a stack of signed values has no |
| 249 | 294 | * single reading) and the scale is the tallest stack. |
| 250 | 295 | */ |
| 251 | export function stackedArea(cells: readonly Cell[], title: string): string { | |
| 296 | export function stackedArea(cells: readonly Cell[], title: string, marks?: readonly Mark[]): string { | |
| 252 | 297 | const { xs, names, values } = gridOf(cells, MAX_SERIES); |
| 253 | 298 | if (xs.length === 0) return nothing("area", title); |
| 254 | 299 | const pos = values.map((r) => r.map((v) => Math.max(0, v))); |
| @@ -266,8 +311,8 @@ export function stackedArea(cells: readonly Cell[], title: string): string { | ||
| 266 | 311 | upper.forEach((v, i) => (base[i] = v)); |
| 267 | 312 | return `<path class="area fg-s${k % 8}" d="${[...fwd, ...back, "Z"].join(" ")}"><title>${t(n)}: ${escapeXml(formatValue(total))} in all</title></path>`; |
| 268 | 313 | }); |
| 269 | return frame("area", title, `${says(title, xs, tops)} Stacked: ${names.map(clean).join(", ")}.`, | |
| 270 | `${yAxis(s)}${plot(bands.join(""))}${xAxis(xs)}${legend(names)}`); | |
| 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)}`); | |
| 271 | 316 | } |
| 272 | 317 | |
| 273 | 318 | /** |
| @@ -339,12 +384,12 @@ export function emptySource(kind: Chart, title: string, source: string): string | ||
| 339 | 384 | * One chart by name: the one door a page draws a panel through. With a `source` name and no |
| 340 | 385 | * cells, the panel says its source has nothing recorded instead of drawing an empty chart. |
| 341 | 386 | */ |
| 342 | export function drawChart(chart: Chart, cells: readonly Cell[], title: string, source?: string): string { | |
| 387 | export function drawChart(chart: Chart, cells: readonly Cell[], title: string, source?: string, marks?: readonly Mark[]): string { | |
| 343 | 388 | if (cells.length === 0 && source !== undefined && clean(source) !== "") return emptySource(chart, title, source); |
| 344 | 389 | switch (chart) { |
| 345 | case "line": return lineChart(cells, title); | |
| 346 | case "bar": return barChart(cells, title); | |
| 347 | case "area": return stackedArea(cells, title); | |
| 390 | case "line": return lineChart(cells, title, marks); | |
| 391 | case "bar": return barChart(cells, title, marks); | |
| 392 | case "area": return stackedArea(cells, title, marks); | |
| 348 | 393 | case "number": return numberChart(cells, title); |
| 349 | 394 | case "heat": return heatStrip(cells, title); |
| 350 | 395 | case "table": return tableChart(cells, title); |
src/boards/marks.ts added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | /** | |
| 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. | |
| 5 | */ | |
| 6 | import type { Database } from "bun:sqlite"; | |
| 7 | import { MARK_CAP as LIMIT, type Mark } from "./chart.ts"; | |
| 8 | ||
| 9 | /** The newest releases as marks, oldest first; a failed read is no marks, never a failed page. */ | |
| 10 | export function releaseMarks(db: Database, limit = LIMIT): Mark[] { | |
| 11 | try { | |
| 12 | 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)" : ""}` })); | |
| 18 | } catch { | |
| 19 | return []; | |
| 20 | } | |
| 21 | } |
src/boards/panel_data.ts +3 −3
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | * checked the asker is an admin. |
| 9 | 9 | */ |
| 10 | 10 | import type { Database } from "bun:sqlite"; |
| 11 | import { drawChart, usesSeries, type Cell, type Chart } from "./chart.ts"; | |
| 11 | import { drawChart, usesSeries, type Cell, type Chart, type Mark } from "./chart.ts"; | |
| 12 | 12 | import { BUCKETS, MAX_STEP, oldestTime, runQuery, type Answer, type Bucket, type Row } from "./query.ts"; |
| 13 | 13 | import type { Board, Panel } from "./store.ts"; |
| 14 | 14 | |
| @@ -146,10 +146,10 @@ export function latestOf(panel: Panel, rows: readonly Row[]): number | null { | ||
| 146 | 146 | } |
| 147 | 147 | |
| 148 | 148 | /** Draw `panel` from its rows: the chart is markup from here on, so whoever reads the rows off the serving thread draws them there too. */ |
| 149 | export function drawnPanel(panel: Panel, answer: PanelData): PanelDrawn { | |
| 149 | export function drawnPanel(panel: Panel, answer: PanelData, marks?: readonly Mark[]): PanelDrawn { | |
| 150 | 150 | if (!answer.ok) return answer; |
| 151 | 151 | 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), latest }; | |
| 152 | return { ok: true, chart: drawChart(panel.chart, cellsOf(answer.rows), panel.title, typeof panel.query.source === "string" ? panel.query.source : undefined, marks), latest }; | |
| 153 | 153 | } |
| 154 | 154 | |
| 155 | 155 | /** 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 +3 −1
| @@ -22,6 +22,7 @@ import type { App, ForgeConfig } from "../app.ts"; | ||
| 22 | 22 | import { drawAnswer, type AnswerDrawn } from "../boards/answer.ts"; |
| 23 | 23 | import { GUIDE } from "../boards/guide.ts"; |
| 24 | 24 | import { toQuery, type Params } from "../boards/params.ts"; |
| 25 | import { releaseMarks } from "../boards/marks.ts"; | |
| 25 | 26 | import { drawnPanel, panelData, runFor, type PanelDrawn } from "../boards/panel_data.ts"; |
| 26 | 27 | import { runQuery } from "../boards/query.ts"; |
| 27 | 28 | import { BOARDS_OWNER, BOARDS_REPO, listBoards, readBoard, type Board, type Stored } from "../boards/store.ts"; |
| @@ -332,7 +333,8 @@ export async function readFlowPicture(env: PagesEnv, job: FlowJob): Promise<Flow | ||
| 332 | 333 | export async function readBoardPicture(env: PagesEnv, job: BoardJob): Promise<BoardPicture> { |
| 333 | 334 | const t0 = performance.now(); |
| 334 | 335 | const board = (await readBoard(env.reposRoot, job.slug)) ?? null; |
| 335 | const panels = board === null ? [] : board.panels.map((panel) => drawnPanel(panel, panelData(env.db, board, panel, {}, job.now))); | |
| 336 | const marks = board === null ? [] : releaseMarks(env.db); | |
| 337 | const panels = board === null ? [] : board.panels.map((panel) => drawnPanel(panel, panelData(env.db, board, panel, {}, job.now), marks)); | |
| 336 | 338 | return { at: job.now, ms: performance.now() - t0, board, panels }; |
| 337 | 339 | } |
| 338 | 340 |
src/web/chart_hover.ts added +100
| @@ -0,0 +1,100 @@ | ||
| 1 | /** | |
| 2 | * The hover of every time chart on a page: one tooltip and one crosshair, synced. A point is a | |
| 3 | * rect carrying `data-l` (its raw label, the key charts on one time axis share), `data-t` (the | |
| 4 | * label as words) and `data-v` (its value). Pointing at one (a mouse over it, a tap, or focus on | |
| 5 | * 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. | |
| 10 | */ | |
| 11 | export const chartHoverJs = /* js */ ` | |
| 12 | (function () { | |
| 13 | var NS = 'http://www.w3.org/2000/svg'; | |
| 14 | var tip = document.createElement('div'); | |
| 15 | tip.className = 'chart-tip'; tip.setAttribute('popover', 'manual'); tip.setAttribute('aria-hidden', 'true'); | |
| 16 | document.body.appendChild(tip); | |
| 17 | var lines = []; | |
| 18 | function charts() { return document.querySelectorAll('.chart[data-chart="line"], .chart[data-chart="bar"]'); } | |
| 19 | function hide() { | |
| 20 | if (tip.matches(':popover-open')) tip.hidePopover(); | |
| 21 | lines.forEach(function (l) { l.remove(); }); | |
| 22 | lines = []; shown = null; | |
| 23 | } | |
| 24 | function find(chart, label) { | |
| 25 | var rs = chart.querySelectorAll('[data-l]'); | |
| 26 | for (var i = 0; i < rs.length; i++) if (rs[i].getAttribute('data-l') === label) return rs[i]; | |
| 27 | return null; | |
| 28 | } | |
| 29 | var shown = null, pending = false; | |
| 30 | function place(pt) { | |
| 31 | var w = tip.offsetWidth, h = tip.offsetHeight; | |
| 32 | var left = Math.min(Math.max(8, pt.x + 12), window.innerWidth - w - 8); | |
| 33 | var top = pt.y - h - 12 < 8 ? pt.y + 16 : pt.y - h - 12; | |
| 34 | tip.style.left = left + 'px'; tip.style.top = top + 'px'; | |
| 35 | } | |
| 36 | function open(head, rows, pt) { | |
| 37 | tip.textContent = ''; tip.appendChild(head); if (rows) tip.appendChild(rows); | |
| 38 | tip.showPopover(); place(pt); | |
| 39 | } | |
| 40 | function at(el, ev) { | |
| 41 | if (ev && typeof ev.clientX === 'number') return { x: ev.clientX, y: ev.clientY }; | |
| 42 | var b = el.getBoundingClientRect(); | |
| 43 | return { x: b.left + b.width / 2, y: b.top }; | |
| 44 | } | |
| 45 | function show(target, pt) { | |
| 46 | hide(); shown = target; | |
| 47 | var head = document.createElement('strong'); | |
| 48 | var mark = target.getAttribute('data-mark'); | |
| 49 | if (mark !== null) { head.textContent = mark; open(head, null, pt); return; } | |
| 50 | var label = target.getAttribute('data-l'); | |
| 51 | head.textContent = target.getAttribute('data-t') || label; | |
| 52 | var rows = document.createElement('div'); | |
| 53 | var n = 0, more = 0; | |
| 54 | charts().forEach(function (chart) { | |
| 55 | var r = find(chart, label); if (!r) return; | |
| 56 | var plot = chart.querySelector('svg.chart-plot'); | |
| 57 | var x = Number(r.getAttribute('x')) + Number(r.getAttribute('width')) / 2; | |
| 58 | var ln = document.createElementNS(NS, 'line'); | |
| 59 | ln.setAttribute('class', 'chart-cross'); | |
| 60 | ln.setAttribute('x1', x); ln.setAttribute('x2', x); ln.setAttribute('y1', '0'); ln.setAttribute('y2', '100'); | |
| 61 | plot.appendChild(ln); lines.push(ln); | |
| 62 | if (n++ >= 8) { more++; return; } | |
| 63 | var row = document.createElement('div'); | |
| 64 | var name = document.createElement('span'); name.textContent = chart.getAttribute('aria-label') || ''; | |
| 65 | var val = document.createElement('b'); val.textContent = r.getAttribute('data-v'); | |
| 66 | row.appendChild(name); row.appendChild(val); rows.appendChild(row); | |
| 67 | }); | |
| 68 | if (more) { var m = document.createElement('div'); m.textContent = '+' + more + ' more'; rows.appendChild(m); } | |
| 69 | open(head, rows, pt); | |
| 70 | } | |
| 71 | function hitOf(t) { return t && t.closest ? t.closest('.chart-plot [data-l], .chart-plot [data-mark]') : null; } | |
| 72 | // A mouse points; a finger taps (the first tap shows, the second follows a link); the keyboard focuses. | |
| 73 | document.addEventListener('pointermove', function (ev) { | |
| 74 | if (ev.pointerType === 'touch') return; | |
| 75 | var hit = hitOf(ev.target); | |
| 76 | if (hit) show(hit, at(hit, ev)); else if (shown) hide(); | |
| 77 | }); | |
| 78 | document.addEventListener('pointerdown', function (ev) { | |
| 79 | var hit = hitOf(ev.target); | |
| 80 | if (!hit) { hide(); return; } | |
| 81 | pending = ev.pointerType === 'touch' && shown !== hit; | |
| 82 | show(hit, at(hit, ev)); | |
| 83 | }); | |
| 84 | document.addEventListener('click', function (ev) { | |
| 85 | if (pending && hitOf(ev.target)) ev.preventDefault(); | |
| 86 | pending = false; | |
| 87 | }); | |
| 88 | document.addEventListener('focusin', function (ev) { | |
| 89 | var a = ev.target && ev.target.closest ? ev.target.closest('.chart a') : null; | |
| 90 | var hit = a && a.querySelector('[data-l]'); | |
| 91 | if (hit) show(hit, at(hit, null)); | |
| 92 | }); | |
| 93 | document.addEventListener('focusout', function (ev) { | |
| 94 | if (ev.target && ev.target.closest && ev.target.closest('.chart a')) hide(); | |
| 95 | }); | |
| 96 | document.addEventListener('pointerout', function (ev) { if (!ev.relatedTarget && ev.pointerType !== 'touch') hide(); }); | |
| 97 | document.addEventListener('scroll', hide, { passive: true }); | |
| 98 | document.addEventListener('keydown', function (e) { if (e.key === 'Escape') hide(); }); | |
| 99 | })(); | |
| 100 | `; |
src/web/pages/boards-stream.ts +2 −2
| @@ -109,7 +109,7 @@ export const boardStreamJs = /* js */ ` | ||
| 109 | 109 | var slot = 100 / n; |
| 110 | 110 | list.forEach(function (p, i) { |
| 111 | 111 | var top = Math.min(s.y(p[1]), s.y(0)), h = Math.abs(s.y(p[1]) - s.y(0)); |
| 112 | plot.appendChild(el('rect', { 'class': 'bar', x: r2(slot * i + slot * 0.15), y: r2(top), width: r2(slot * 0.7), height: r2(h) }, p[0] + ': ' + fmt(p[1]))); | |
| 112 | plot.appendChild(el('rect', { 'class': 'bar', x: r2(slot * i + slot * 0.15), y: r2(top), width: r2(slot * 0.7), height: r2(h), 'data-l': p[0], 'data-t': p[0], 'data-v': fmt(p[1]) })); | |
| 113 | 113 | }); |
| 114 | 114 | } else { |
| 115 | 115 | var d2 = line(vals, s.y), ln = plot.querySelector('.chart-line'), wash = plot.querySelector('.chart-wash'); |
| @@ -119,7 +119,7 @@ export const boardStreamJs = /* js */ ` | ||
| 119 | 119 | clear(plot, '.chart-hit'); |
| 120 | 120 | list.forEach(function (p, i) { |
| 121 | 121 | var l = i === 0 || n < 2 ? 0 : (i + i - 1) * 50 / (n - 1), rt = i === n - 1 ? 100 : (i + i + 1) * 50 / (n - 1); |
| 122 | plot.appendChild(el('rect', { 'class': 'chart-hit', x: r2(l), y: '0', width: r2(rt - l), height: '100' }, p[0] + ': ' + fmt(p[1]))); | |
| 122 | plot.appendChild(el('rect', { 'class': 'chart-hit', x: r2(l), y: '0', width: r2(rt - l), height: '100', 'data-l': p[0], 'data-t': p[0], 'data-v': fmt(p[1]) })); | |
| 123 | 123 | }); |
| 124 | 124 | } |
| 125 | 125 | words(card, list); return true; |
src/web/pages/boards-view.ts +4 −2
| @@ -15,6 +15,7 @@ import { driftSection } from "./boards-drift.ts"; | ||
| 15 | 15 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; |
| 16 | 16 | import { liveRegionsJs } from "../client.ts"; |
| 17 | 17 | import { boardStreamJs } from "./boards-stream.ts"; |
| 18 | import { chartHoverJs } from "../chart_hover.ts"; | |
| 18 | 19 | import { notFoundPage, signInFirst } from "../chrome.ts"; |
| 19 | 20 | import { html, when, type Html } from "../html.ts"; |
| 20 | 21 | import { page } from "../layout.ts"; |
| @@ -27,6 +28,7 @@ import { boardsHoldsCard } from "./boards-holds.ts"; | ||
| 27 | 28 | import { alarmLines } from "../studio/alarm_lines.ts"; |
| 28 | 29 | import { boardPicture, boardsPicture, isFailed, LONG_WAIT_MS, waitAnswer } from "../../flow/pages.ts"; |
| 29 | 30 | import { isPinned, listPins } from "../../boards/pins.ts"; |
| 31 | import { releaseMarks } from "../../boards/marks.ts"; | |
| 30 | 32 | import { drawnPanel, panelData, runFor, type PanelDrawn } from "../../boards/panel_data.ts"; |
| 31 | 33 | import { readParams } from "../../boards/params.ts"; |
| 32 | 34 | import { paramsOf, queryFields } from "./boards.ts"; |
| @@ -48,7 +50,7 @@ export function drawPanel( | ||
| 48 | 50 | * The panel as a worker read and drew it (`flow/pages.ts`); without it the rows are read and |
| 49 | 51 | * drawn here, for a direct caller. |
| 50 | 52 | */ |
| 51 | drawn: PanelDrawn = drawnPanel(panel, panelData(app.db, board, panel, {}, Date.now(), run)), | |
| 53 | drawn: PanelDrawn = drawnPanel(panel, panelData(app.db, board, panel, {}, Date.now(), run), releaseMarks(app.db)), | |
| 52 | 54 | ): Html { |
| 53 | 55 | const q = paramsOf(panel.query, panel.chart); |
| 54 | 56 | const body = !drawn.ok ? html`<p class="muted small">${drawn.error}</p>` : chartFrame(panel.chart, drawn.chart); |
| @@ -278,7 +280,7 @@ export async function boardShow(ctx: Ctx): Promise<Response> { | ||
| 278 | 280 | ${panels} |
| 279 | 281 | ${manage(slug, board, queryFields(readParams(ctx.url.searchParams)), listPins(ctx.app.db, ctx.auth.user?.id ?? ""))} |
| 280 | 282 | </div>`, |
| 281 | scriptJs: boardStreamJs, | |
| 283 | scriptJs: boardStreamJs + chartHoverJs, | |
| 282 | 284 | }); |
| 283 | 285 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 284 | 286 | return response; |
src/web/style/content.ts +8 −1
| @@ -222,12 +222,19 @@ a.origin-chip:hover { border-color: var(--border-strong); color: var(--fg); } | ||
| 222 | 222 | .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; } |
| 223 | 223 | .chart-y.is-rows { justify-content: space-around; height: var(--chart-h); max-width: 112px; margin-block: 0; } |
| 224 | 224 | .chart-y.is-rows span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; } |
| 225 | .chart-plot { grid-column: 2; grid-row: 1; display: block; width: 100%; height: var(--chart-h); overflow: visible; color: var(--accent); } | |
| 225 | .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); } | |
| 226 | 226 | .chart-grid { stroke: var(--border); stroke-width: 1; vector-effect: non-scaling-stroke; } |
| 227 | 227 | .chart-line { fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; } |
| 228 | 228 | .chart-wash { fill: currentColor; fill-opacity: 0.08; } |
| 229 | 229 | .chart-hit { fill: currentColor; fill-opacity: 0; } |
| 230 | 230 | .chart-hit:hover, .chart a:focus-visible > .chart-hit { fill-opacity: 0.14; } |
| 231 | /* A release, roll or config change: a dashed vertical mark; the synced crosshair is solid. */ | |
| 232 | .chart-mark-hit { stroke: transparent; stroke-width: 8; vector-effect: non-scaling-stroke; pointer-events: stroke; } | |
| 233 | .chart-mark { pointer-events: none; stroke: var(--muted-fg); stroke-width: 1; stroke-dasharray: 3 3; vector-effect: non-scaling-stroke; } | |
| 234 | .chart-cross { stroke: var(--fg); stroke-width: 1; vector-effect: non-scaling-stroke; pointer-events: none; } | |
| 235 | .chart-tip { margin: 0; inset: auto; overflow: visible; max-width: min(320px, calc(100vw - 16px)); padding: 6px 8px; font-size: var(--fs-min); line-height: 16px; font-variant-numeric: tabular-nums; color: var(--fg); background: var(--muted); border: 0; border-radius: var(--radius); pointer-events: none; } | |
| 236 | .chart-tip > div > div { display: flex; justify-content: space-between; gap: 16px; } | |
| 237 | .chart-tip > div > div > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted-fg); } | |
| 231 | 238 | .chart .bar, .chart .cell { fill: currentColor; } |
| 232 | 239 | .chart .bar:hover, .chart a:focus-visible > .bar { fill-opacity: 0.7; } |
| 233 | 240 | .chart .cell { stroke: var(--card); stroke-width: 1; vector-effect: non-scaling-stroke; } |
test/boards-marks.test.ts added +58
| @@ -0,0 +1,58 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { Database } from "bun:sqlite"; | |
| 3 | import { lineChart, marksSvg, MARK_CAP } from "../src/boards/chart.ts"; | |
| 4 | import { releaseMarks } from "../src/boards/marks.ts"; | |
| 5 | import { boardStreamJs } from "../src/web/pages/boards-stream.ts"; | |
| 6 | import { readFileSync } from "node:fs"; | |
| 7 | ||
| 8 | const db = () => { | |
| 9 | const d = new Database(":memory:"); | |
| 10 | d.run("CREATE TABLE keeper_release (version TEXT, stage TEXT, cut_at TEXT)"); | |
| 11 | return d; | |
| 12 | }; | |
| 13 | ||
| 14 | describe("releaseMarks", () => { | |
| 15 | test("oldest first, rolled back says so", () => { | |
| 16 | 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 | expect(releaseMarks(d)).toEqual([ | |
| 19 | { at: "2026-11-01T00:00:00Z", text: "Release v1 (rolled back)" }, | |
| 20 | { at: "2026-11-02T00:00:00Z", text: "Release v2" }, | |
| 21 | ]); | |
| 22 | }); | |
| 23 | test("capped at the chart's cap, newest kept", () => { | |
| 24 | 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 | const m = releaseMarks(d, 1000); | |
| 27 | expect(m.length).toBe(MARK_CAP); | |
| 28 | expect(m[m.length - 1]!.text).toBe(`Release v${MARK_CAP + 9}`); | |
| 29 | }); | |
| 30 | test("a failed read is no marks", () => { | |
| 31 | expect(releaseMarks(new Database(":memory:"))).toEqual([]); | |
| 32 | }); | |
| 33 | }); | |
| 34 | ||
| 35 | describe("marks on a chart", () => { | |
| 36 | const days = ["2026-11-01", "2026-11-02", "2026-11-03"].map((label, i) => ({ label, value: i })); | |
| 37 | test("sorted by instant, not by string, across offsets", () => { | |
| 38 | const svg = marksSvg( | |
| 39 | [{ at: "2026-11-02T01:00:00+05:00", text: "B" }, { at: "2026-11-01T23:00:00Z", text: "A" }], | |
| 40 | days.map((d) => d.label), (i) => i * 50); | |
| 41 | expect(svg.indexOf('data-mark="B"')).toBeLessThan(svg.indexOf('data-mark="A"')); | |
| 42 | }); | |
| 43 | test("a mark is hoverable: it sits above the hit columns and says itself in an attribute", () => { | |
| 44 | const html = lineChart(days, "Runs", [{ at: "2026-11-02T00:00:00Z", text: "Release v1" }]); | |
| 45 | expect(html.indexOf("chart-mark-hit")).toBeGreaterThan(html.lastIndexOf("chart-hit")); | |
| 46 | expect(html).toContain('data-mark="Release v1"'); | |
| 47 | expect(html).not.toContain("<title>Release"); | |
| 48 | }); | |
| 49 | }); | |
| 50 | ||
| 51 | describe("the board page and the live redraw", () => { | |
| 52 | test("the board page ships the hover script", () => { | |
| 53 | expect(readFileSync("src/web/pages/boards-view.ts", "utf8")).toContain("boardStreamJs + chartHoverJs"); | |
| 54 | }); | |
| 55 | test("a stream frame leaves the marks alone", () => { | |
| 56 | expect(boardStreamJs).not.toContain("chart-mark"); | |
| 57 | }); | |
| 58 | }); |
test/boards-page.test.ts +3 −3
| @@ -131,7 +131,7 @@ describe("/boards/data", () => { | ||
| 131 | 131 | expect(body.match(/<path class="chart-line" d="M[^"]*"/g)?.length).toBe(1); |
| 132 | 132 | expect(body.match(HIT)?.length).toBe(3); |
| 133 | 133 | // A day is said as a day, under the plot and in the point's own words. |
| 134 | expect(body).toContain("<title>Oct 2: 2</title>"); | |
| 134 | expect(body).toContain(`data-t="Oct 2" data-v="2"`); | |
| 135 | 135 | }); |
| 136 | 136 | |
| 137 | 137 | test("a point links to the rows behind it", async () => { |
| @@ -287,8 +287,8 @@ describe("chart geometry", () => { | ||
| 287 | 287 | test("bars: two slots of 50, bars 70% wide, heights in proportion", () => { |
| 288 | 288 | const svg = barChart([{ label: "a", value: 1 }, { label: "b", value: 4 }], "t"); |
| 289 | 289 | // top 4, so 25 per unit; slots start at 0 and 50; a bar is 35 wide, 7.5 in. |
| 290 | expect(svg).toContain('<rect class="bar" x="7.5" y="75" width="35" height="25">'); | |
| 291 | expect(svg).toContain('<rect class="bar" x="57.5" y="0" width="35" height="100">'); | |
| 290 | expect(svg).toContain('<rect class="bar" x="7.5" y="75" width="35" height="25" data-l="a"'); | |
| 291 | expect(svg).toContain('<rect class="bar" x="57.5" y="0" width="35" height="100" data-l="b"'); | |
| 292 | 292 | }); |
| 293 | 293 | test("the y axis tops out at a round number, and says its three values as text", () => { |
| 294 | 294 | expect([4.26, 7307, 0.69, 136, 0].map(niceTop)).toEqual([5, 8000, 0.8, 150, 1]); |
test/boards-stream.test.ts +2 −2
| @@ -184,8 +184,8 @@ describe("the page's drawer", () => { | ||
| 184 | 184 | p.heard.panels!({ data: JSON.stringify({ at: 2, panels: [{ i: 0, points: [["check", 5], ["build", 3]], now: "3" }] }) }); |
| 185 | 185 | const bars = p.plot.kids.filter((k: any) => k.attrs.class === "bar"); |
| 186 | 186 | expect(bars.length).toBe(3); |
| 187 | expect(bars[0].textContent).toBe("check: 5"); | |
| 188 | expect(bars[2].textContent).toBe("build: 3"); | |
| 187 | expect([bars[0].attrs["data-l"], bars[0].attrs["data-v"]]).toEqual(["check", "5"]); | |
| 188 | expect([bars[2].attrs["data-l"], bars[2].attrs["data-v"]]).toEqual(["build", "3"]); | |
| 189 | 189 | expect(p.ys[0].textContent).toBe("5"); |
| 190 | 190 | expect(p.now.textContent).toBe("3"); |
| 191 | 191 | expect(p.sr.textContent).toContain("3 points; lowest 1, highest 5, latest 3"); |
test/chart-hover-marks.test.ts added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { barChart, lineChart, marksSvg } from "../src/boards/chart.ts"; | |
| 3 | import { chartHoverJs } from "../src/web/chart_hover.ts"; | |
| 4 | ||
| 5 | const days = ["2026-11-01", "2026-11-02", "2026-11-03", "2026-11-04", "2026-11-05"].map((label, i) => ({ label, value: i * 10 })); | |
| 6 | ||
| 7 | describe("a point says itself in attributes, not native titles", () => { | |
| 8 | test("line and bar points carry label, words and value", () => { | |
| 9 | for (const html of [lineChart(days, "Runs"), barChart(days, "Runs")]) { | |
| 10 | expect(html).toContain(`data-l="2026-11-03" data-t="Nov 3" data-v="20"`); | |
| 11 | expect(html).not.toContain("<title>Nov"); | |
| 12 | } | |
| 13 | }); | |
| 14 | test("a label is escaped in the attribute", () => { | |
| 15 | const html = lineChart([{ label: `a"><script>`, value: 1 }], "t"); | |
| 16 | expect(html).not.toContain("<script>"); | |
| 17 | }); | |
| 18 | }); | |
| 19 | ||
| 20 | describe("release marks", () => { | |
| 21 | test("a mark halfway between two days sits halfway between their x", () => { | |
| 22 | // 5 days → x = 0, 25, 50, 75, 100; 2026-11-02T12:00 is between day 2 and 3 → 37.5. | |
| 23 | const svg = marksSvg([{ at: "2026-11-02T12:00:00Z", text: "Release v9" }], days.map((d) => d.label), (i) => i * 25); | |
| 24 | expect(svg).toContain(`x1="37.5"`); | |
| 25 | expect(svg).toContain('data-mark="Release v9"'); | |
| 26 | }); | |
| 27 | test("a mark outside the span is not drawn", () => { | |
| 28 | expect(marksSvg([{ at: "2026-10-01T00:00:00Z", text: "old" }], days.map((d) => d.label), (i) => i * 25)).toBe(""); | |
| 29 | }); | |
| 30 | test("a line chart draws marks and names them for a screen reader; bars too", () => { | |
| 31 | const marks = [{ at: "2026-11-03T00:00:00Z", text: "Release <b>1</b>" }]; | |
| 32 | for (const html of [lineChart(days, "Runs", marks), barChart(days, "Runs", marks)]) { | |
| 33 | expect(html).toContain('class="chart-mark"'); | |
| 34 | expect(html).toContain("Marked: Release <b>1</b>."); | |
| 35 | expect(html).not.toContain("<b>1</b>"); | |
| 36 | } | |
| 37 | expect(lineChart(days, "Runs")).not.toContain("chart-mark"); | |
| 38 | }); | |
| 39 | test("labels that are not times take no marks", () => { | |
| 40 | const html = lineChart([{ label: "a", value: 1 }, { label: "b", value: 2 }], "x", [{ at: "2026-11-03T00:00:00Z", text: "r" }]); | |
| 41 | expect(html).not.toContain("chart-mark"); | |
| 42 | }); | |
| 43 | }); | |
| 44 | ||
| 45 | describe("the hover script", () => { | |
| 46 | test("syncs a crosshair by label and sets text as text", () => { | |
| 47 | expect(chartHoverJs).toContain("chart-cross"); | |
| 48 | expect(chartHoverJs).toContain("data-l"); | |
| 49 | expect(chartHoverJs).not.toContain("innerHTML"); | |
| 50 | expect(chartHoverJs).not.toContain("eval("); | |
| 51 | }); | |
| 52 | }); |
test/chart-hover-script.test.ts added +104
| @@ -0,0 +1,104 @@ | ||
| 1 | /** The hover script, run against a minimal DOM: mouse, tap, focus, marks, "+N more". */ | |
| 2 | import { describe, expect, test } from "bun:test"; | |
| 3 | import { chartHoverJs } from "../src/web/chart_hover.ts"; | |
| 4 | ||
| 5 | type El = any; | |
| 6 | function dom(chartCount = 10) { | |
| 7 | const mk = (tag = "div", attrs: Record<string, string> = {}): El => { | |
| 8 | const e: El = { tag, attrs: { ...attrs }, kids: [], text: "", style: {}, parent: null, open: false, offsetWidth: 100, offsetHeight: 40 }; | |
| 9 | e.setAttribute = (k: string, v: unknown) => (e.attrs[k] = String(v)); | |
| 10 | e.getAttribute = (k: string) => e.attrs[k] ?? null; | |
| 11 | e.appendChild = (c: El) => (c.parent = e, e.kids.push(c), c); | |
| 12 | e.remove = () => { if (e.parent) e.parent.kids = e.parent.kids.filter((k: El) => k !== e); }; | |
| 13 | e.matches = () => e.open; | |
| 14 | e.showPopover = () => { e.open = true; }; | |
| 15 | e.hidePopover = () => { e.open = false; }; | |
| 16 | e.getBoundingClientRect = () => ({ left: 10, top: 20, width: 30, height: 40 }); | |
| 17 | e.closest = (sel: string) => { | |
| 18 | for (let n: El = e; n; n = n.parent) if (sel.split(",").some((s) => (s.includes("[data-mark]") && n.attrs["data-mark"] !== undefined) || (s.includes("[data-l]") && n.attrs["data-l"] !== undefined) || (s.includes(".chart a") && n.tag === "a"))) return n; | |
| 19 | return null; | |
| 20 | }; | |
| 21 | e.querySelector = (sel: string) => (sel === "svg.chart-plot" ? e.kids.find((k: El) => k.tag === "svg") ?? null : sel === "[data-l]" ? e.kids.find((k: El) => k.attrs["data-l"] !== undefined) ?? null : null); | |
| 22 | const all = (n: El): El[] => n.kids.flatMap((k: El) => [k, ...all(k)]); | |
| 23 | e.querySelectorAll = () => all(e).filter((k: El) => k.attrs["data-l"] !== undefined); | |
| 24 | Object.defineProperty(e, "textContent", { get: () => e.text + e.kids.map((k: El) => k.textContent).join(""), set: (v: string) => ((e.text = v), (e.kids = [])) }); | |
| 25 | return e; | |
| 26 | }; | |
| 27 | const charts: El[] = []; | |
| 28 | const hits: El[] = []; | |
| 29 | for (let i = 0; i < chartCount; i++) { | |
| 30 | const chart = mk("div", { "data-chart": "line", "aria-label": `Chart ${i}` }); | |
| 31 | const svg = mk("svg"); | |
| 32 | const link = mk("a"); | |
| 33 | const rect = mk("rect", { "data-l": "2026-11-02", "data-t": "Nov 2", "data-v": String(i), x: "40", width: "20" }); | |
| 34 | link.appendChild(rect); | |
| 35 | svg.appendChild(link); | |
| 36 | if (i === 0) svg.appendChild(mk("line", { "data-mark": "Release v9" })); | |
| 37 | chart.appendChild(svg); | |
| 38 | charts.push(chart); | |
| 39 | hits.push(rect); | |
| 40 | } | |
| 41 | const mark = charts[0]!.kids[0]!.kids.find((k: El) => k.attrs["data-mark"] !== undefined); | |
| 42 | const body = mk("body"); | |
| 43 | const listeners: Record<string, ((e: El) => void)[]> = {}; | |
| 44 | const document = { | |
| 45 | body, | |
| 46 | createElement: (t: string) => mk(t), | |
| 47 | createElementNS: (_: string, t: string) => mk(t), | |
| 48 | querySelectorAll: () => charts, | |
| 49 | addEventListener: (n: string, f: (e: El) => void) => (listeners[n] ??= []).push(f), | |
| 50 | }; | |
| 51 | new Function("document", "window", chartHoverJs)(document, { innerWidth: 800 }); | |
| 52 | const tip = body.kids[0]!; | |
| 53 | const fire = (n: string, e: El) => listeners[n]?.forEach((f) => f({ preventDefault() { e.prevented = true; }, ...e })); | |
| 54 | return { tip, hits, mark, charts, fire }; | |
| 55 | } | |
| 56 | const crosses = (charts: El[]) => charts.flatMap((c) => c.kids[0].kids.filter((k: El) => k.attrs.class === "chart-cross")).length; | |
| 57 | ||
| 58 | describe("the hover script", () => { | |
| 59 | test("a mouse over a point opens one tooltip, a crosshair in every chart, and '+N more' past 8", () => { | |
| 60 | const d = dom(); | |
| 61 | d.fire("pointermove", { target: d.hits[3], pointerType: "mouse", clientX: 100, clientY: 100 }); | |
| 62 | expect(d.tip.open).toBe(true); | |
| 63 | expect(d.tip.textContent).toContain("Nov 2"); | |
| 64 | expect(d.tip.textContent).toContain("Chart 3"); | |
| 65 | expect(d.tip.textContent).toContain("+2 more"); | |
| 66 | expect(crosses(d.charts)).toBe(10); | |
| 67 | d.fire("pointerout", { target: d.hits[3], relatedTarget: null, pointerType: "mouse" }); | |
| 68 | expect(d.tip.open).toBe(false); | |
| 69 | expect(crosses(d.charts)).toBe(0); | |
| 70 | }); | |
| 71 | test("a tap shows it with no pointermove, the first tap does not follow the link, a tap outside hides", () => { | |
| 72 | const d = dom(2); | |
| 73 | const first: El = { target: d.hits[1], pointerType: "touch", clientX: 5, clientY: 50 }; | |
| 74 | d.fire("pointerdown", first); | |
| 75 | expect(d.tip.open).toBe(true); | |
| 76 | const click: El = { target: d.hits[1] }; | |
| 77 | d.fire("click", click); | |
| 78 | expect(click.prevented).toBe(true); | |
| 79 | d.fire("pointerdown", { target: d.hits[1], pointerType: "touch", clientX: 5, clientY: 50 }); | |
| 80 | const again: El = { target: d.hits[1] }; | |
| 81 | d.fire("click", again); | |
| 82 | expect(again.prevented).toBeUndefined(); | |
| 83 | d.fire("pointerdown", { target: { closest: () => null }, pointerType: "touch" }); | |
| 84 | expect(d.tip.open).toBe(false); | |
| 85 | }); | |
| 86 | test("focus on a point's link shows it, from the rect's box; blur hides", () => { | |
| 87 | const d = dom(2); | |
| 88 | d.fire("focusin", { target: d.hits[0].parent }); | |
| 89 | expect(d.tip.open).toBe(true); | |
| 90 | expect(d.tip.textContent).toContain("Chart 0"); | |
| 91 | d.fire("focusout", { target: d.hits[0].parent }); | |
| 92 | expect(d.tip.open).toBe(false); | |
| 93 | }); | |
| 94 | test("a release mark shows its words alone", () => { | |
| 95 | const d = dom(2); | |
| 96 | d.fire("pointermove", { target: d.mark, pointerType: "mouse", clientX: 1, clientY: 60 }); | |
| 97 | expect(d.tip.textContent).toBe("Release v9"); | |
| 98 | expect(crosses(d.charts)).toBe(0); | |
| 99 | }); | |
| 100 | test("text is set as text", () => { | |
| 101 | expect(chartHoverJs).not.toContain("innerHTML"); | |
| 102 | expect(chartHoverJs).not.toContain("eval("); | |
| 103 | }); | |
| 104 | }); |
new above
offline
Says marks use attributes, not a native title, but marksSvg emits a <title>. Make doc and code agree (finding 2).