athena-ui-js 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,722 +1,772 @@
1
- //chartGenerator for Athena UI
2
- //Author: Csaba Tóth https://github.com/csabatibortoth/
3
- //LICENCE: MIT
4
- //Repository: https://github.com/csabatibortoth/athena-ui
5
-
6
- // Dependency free SVG charts: bar, line, area, sparkline, pie and donut. Colours come from the theme (--series-1 ... --series-8,
7
- // see the stylesheet), nothing is styled inline, so a strict Content-Security-Policy works.
8
-
9
- import { resolveElement, uid } from "../../core/dom.js";
10
- import { getLocale, translate } from "../../core/i18n.js";
11
-
12
- const NS = "http://www.w3.org/2000/svg";
13
- const SERIES_COLORS = 8;
14
- const DEFAULT_MARGIN = { top: 40, right: 20, bottom: 50, left: 55 };
15
- const DOT_LIMIT = 80; // up to this many points in view every point is a dot with a tooltip; more: the tooltip follows the pointer
16
-
17
- const svgEl = (tag, attrs = {}, text) => {
18
- const node = document.createElementNS(NS, tag);
19
- for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value);
20
- if (text != null) node.textContent = text;
21
- return node;
22
- };
23
-
24
- const seriesClass = index => `s${(index % SERIES_COLORS) + 1}`;
25
- // A colour given by the caller goes in the `color` attribute (the shapes paint with currentColor); otherwise the class picks it from the theme.
26
- const seriesProps = (series, index) => (series.color ? { color: series.color } : { class: seriesClass(index) });
27
- const formatNumber = n => Number.isInteger(n) ? String(n) : String(+n.toFixed(2));
28
-
29
- // Rounded axis maximum and tick step, so ticks land on readable numbers.
30
- function niceScale(span, ticks = 5) {
31
- if (span <= 0) return { span: 1, step: 1 / ticks };
32
- const rough = span / ticks;
33
- const magnitude = 10 ** Math.floor(Math.log10(rough));
34
- const step = [1, 2, 5, 10].map(m => m * magnitude).find(s => s >= rough);
35
- return { span: step * Math.ceil(span / step - 1e-9), step };
36
- }
37
-
38
- /* ------------------TIME AXIS------------------- */
39
-
40
- const SECOND = 1000;
41
- const MINUTE = 60 * SECOND;
42
- const HOUR = 60 * MINUTE;
43
- const DAY = 24 * HOUR;
44
- const TIME_STEPS = [SECOND, 5 * SECOND, 15 * SECOND, 30 * SECOND, MINUTE, 5 * MINUTE, 15 * MINUTE, 30 * MINUTE, HOUR, 3 * HOUR, 6 * HOUR,
45
- 12 * HOUR, DAY, 2 * DAY, 7 * DAY, 14 * DAY, 30 * DAY, 90 * DAY, 365 * DAY];
46
-
47
- /** Tick positions (ms) at round times between `from` and `to`, about `count` of them. */
48
- export function timeTicks(from, to, count = 6) {
49
- const step = TIME_STEPS.find(s => (to - from) / s <= count) ?? TIME_STEPS.at(-1);
50
- // Ticks of a day or more start at midnight of the local day, shorter ones at a multiple of the step.
51
- const offset = step >= DAY ? new Date(from).getTimezoneOffset() * MINUTE : 0;
52
- const ticks = [];
53
- for (let t = Math.ceil((from - offset) / step) * step + offset; t <= to; t += step) ticks.push(t);
54
- return { ticks, step };
55
- }
56
-
57
- function timeFormatter(step) {
58
- const locale = getLocale();
59
- const options = step < MINUTE ? { hour: "2-digit", minute: "2-digit", second: "2-digit" }
60
- : step < DAY ? { hour: "2-digit", minute: "2-digit" }
61
- : step < 90 * DAY ? { month: "short", day: "numeric" }
62
- : { month: "short", year: "numeric" };
63
- const format = new Intl.DateTimeFormat(locale, options);
64
- return t => format.format(t);
65
- }
66
-
67
- const toTime = value => (value instanceof Date ? value.getTime() : typeof value === "number" ? value : Date.parse(value));
68
-
69
- /**
70
- * Keeps about `buckets` x positions of a long series: of every bucket the lowest and the highest value stay (in their order),
71
- * so peaks are not lost. Returns the kept indices.
72
- */
73
- export function decimate(indices, values, buckets) {
74
- if (indices.length <= buckets * 2) return indices;
75
- const size = indices.length / buckets;
76
- const kept = [];
77
- for (let b = 0; b < buckets; b++) {
78
- const slice = indices.slice(Math.floor(b * size), Math.floor((b + 1) * size));
79
- if (!slice.length) continue;
80
- let low = slice[0];
81
- let high = slice[0];
82
- for (const i of slice) {
83
- if (values[i] < values[low]) low = i;
84
- if (values[i] > values[high]) high = i;
85
- }
86
- kept.push(...(low === high ? [low] : low < high ? [low, high] : [high, low]));
87
- }
88
- return kept;
89
- }
90
-
91
- /* ------------------PARTS------------------- */
92
-
93
- function addLegend(svg, entries, width, height, ctx) {
94
- const MARGIN = ctx.margin;
95
- let x = MARGIN.left;
96
- const y = height - 12;
97
- entries.forEach(({ name, props, series }) => {
98
- const group = svgEl("g", { class: "chart-legend-item", tabindex: 0, role: "button", "aria-pressed": "true", "aria-label": name, "data-legend": series ?? "" });
99
- group.append(svgEl("rect", { x, y: y - 9, width: 10, height: 10, class: `chart-swatch ${props.class ?? ""}`.trim(), ...(props.color ? { color: props.color } : {}) }));
100
- group.append(svgEl("text", { x: x + 14, y, class: "chart-legend" }, name));
101
- if (series != null) {
102
- const toggle = () => {
103
- const hidden = group.getAttribute("aria-pressed") === "true";
104
- group.setAttribute("aria-pressed", hidden ? "false" : "true");
105
- group.classList.toggle("is-off", hidden);
106
- for (const node of svg.querySelectorAll(`[data-series="${series}"]`)) node.classList.toggle("chart-hidden", hidden);
107
- ctx.hooks?.legend?.(series, hidden);
108
- ctx.tooltip.hide();
109
- };
110
- group.addEventListener("click", toggle);
111
- group.addEventListener("keydown", event => {
112
- if (event.key === "Enter" || event.key === " ") {
113
- event.preventDefault();
114
- toggle();
115
- }
116
- });
117
- }
118
- svg.append(group);
119
- x += 14 + name.length * 7 + 14;
120
- });
121
- }
122
-
123
- // One tooltip per chart, drawn inside the SVG and moved with attributes (no inline style). Shows on hover and on keyboard focus.
124
- function createTooltip(svg, width) {
125
- const group = svgEl("g", { class: "chart-tooltip", "aria-hidden": "true" });
126
- const box = svgEl("rect", { class: "chart-tooltip-box", rx: 4 });
127
- const text = svgEl("text", { class: "chart-tooltip-text" });
128
- group.append(box, text);
129
- const show = (x, y, lines) => {
130
- text.replaceChildren(...lines.map((line, i) => svgEl("tspan", { x: 8, dy: i ? 15 : 0 }, line)));
131
- group.classList.add("is-visible");
132
- let w = 80;
133
- let h = lines.length * 15 + 8;
134
- try {
135
- const bbox = text.getBBox();
136
- w = bbox.width + 16;
137
- h = bbox.height + 10;
138
- } catch { /* not rendered: the estimate stays */ }
139
- text.setAttribute("y", 15);
140
- const left = Math.min(Math.max(x - w / 2, 2), Math.max(width - w - 2, 2));
141
- const top = Math.max(y - h - 10, 2);
142
- box.setAttribute("width", w);
143
- box.setAttribute("height", h);
144
- group.setAttribute("transform", `translate(${left} ${top})`);
145
- };
146
- const hide = () => group.classList.remove("is-visible");
147
- svg.append(group);
148
- return { show, hide, group };
149
- }
150
-
151
- // Makes a shape react to the pointer and the keyboard focus. It is focusable and named, so the values can be read without a mouse.
152
- function addTip(ctx, node, x, y, lines) {
153
- node.setAttribute("tabindex", "0");
154
- node.setAttribute("aria-label", lines.join(", "));
155
- node.setAttribute("role", "img");
156
- const show = () => ctx.tooltip.show(x, y, lines);
157
- node.addEventListener("pointerenter", show);
158
- node.addEventListener("focus", show);
159
- node.addEventListener("pointerleave", ctx.tooltip.hide);
160
- node.addEventListener("blur", ctx.tooltip.hide);
161
- }
162
-
163
- // Draws the value grid and the y axis for the range [min, min + scale.span].
164
- function addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format = formatNumber }) {
165
- const plotW = width - MARGIN.left - MARGIN.right;
166
- const plotH = height - MARGIN.top - MARGIN.bottom;
167
- const y = value => MARGIN.top + plotH - ((value - min) / scale.span) * plotH;
168
- const ticks = Math.round(scale.span / scale.step);
169
- for (let i = 0; i <= ticks; i++) {
170
- const v = min + i * scale.step;
171
- svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: y(v), y2: y(v), class: "chart-grid" }));
172
- svg.append(svgEl("text", { x: MARGIN.left - 8, y: y(v) + 4, "text-anchor": "end", class: "chart-tick" }, format(v)));
173
- }
174
- svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left, y1: MARGIN.top, y2: MARGIN.top + plotH, class: "chart-axis" }));
175
- // The category axis sits at zero when the range includes it, so negative bars hang below it.
176
- const baseline = y(Math.min(Math.max(0, min), min + scale.span));
177
- svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: baseline, y2: baseline, class: "chart-axis" }));
178
- return { y, baseline, plotW, plotH };
179
- }
180
-
181
- function valueRange(values, zero = true) {
182
- const finite = values.filter(Number.isFinite);
183
- if (!finite.length) return { min: 0, scale: niceScale(1) };
184
- let min = zero ? Math.min(0, ...finite) : Math.min(...finite);
185
- const max = Math.max(zero ? 0 : -Infinity, ...finite);
186
- const scale = niceScale(max - min);
187
- if (!zero) min = Math.floor(min / scale.step) * scale.step; // start the axis at a round number
188
- return { min, scale: niceScale(max - min) };
189
- }
190
-
191
- /* ------------------DRAWERS------------------- */
192
-
193
- function drawBar(svg, ctx) {
194
- const { labels, series, width, height, format } = ctx;
195
- const MARGIN = ctx.margin;
196
- const { min, scale } = valueRange(series.flatMap(s => s.data));
197
- const { y, plotW, plotH } = addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format: ctx.tickFormat });
198
- const band = plotW / Math.max(labels.length, 1);
199
- labels.forEach((label, i) => svg.append(svgEl("text",
200
- { x: MARGIN.left + band * (i + 0.5), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, label)));
201
- const groupWidth = band * 0.8;
202
- const barWidth = groupWidth / series.length;
203
- series.forEach((s, si) => s.data.forEach((value, i) => {
204
- const x = MARGIN.left + band * i + (band - groupWidth) / 2 + barWidth * si;
205
- const top = Math.min(y(value), y(0));
206
- const bar = svgEl("rect", {
207
- x, y: top, width: Math.max(barWidth - 2, 1), height: Math.abs(y(0) - y(value)),
208
- "data-series": si, ...seriesProps(s, si)
209
- });
210
- bar.setAttribute("class", `chart-bar ${bar.getAttribute("class") ?? ""}`.trim());
211
- addTip(ctx, bar, x + barWidth / 2, top, [`${s.name ?? ""} ${labels[i] ?? ""}`.trim(), format(value)]);
212
- svg.append(bar);
213
- }));
214
- }
215
-
216
- // Line and area charts, with a category or a time axis, zoom (a range of the x axis) and long series (no dots, a pointer tooltip).
217
- function drawLine(svg, ctx) {
218
- const { labels, series, width, height, times, area, options, zoom, format } = ctx;
219
- const MARGIN = ctx.margin;
220
- const plotW = width - MARGIN.left - MARGIN.right;
221
- const plotH = height - MARGIN.top - MARGIN.bottom;
222
- const count = Math.max(...series.map(s => s.data.length));
223
- const position = i => (times ? times[i] : i); // x position of point i in the units of the axis
224
- // The range of the x axis: what the data covers, or the one asked for (a window of the last hour that is only half measured)
225
- const full = times ? (options.timeRange && options.timeRange.to > options.timeRange.from ? { from: toTime(options.timeRange.from), to: toTime(options.timeRange.to) } : { from: Math.min(...times.slice(0, count)), to: Math.max(...times.slice(0, count)) }) : { from: -0.5, to: count - 0.5 };
226
- const view = zoom ? { from: Math.max(zoom.from, full.from), to: Math.min(zoom.to, full.to) } : full;
227
- if (!(view.to > view.from)) Object.assign(view, full);
228
- const x = p => MARGIN.left + ((p - view.from) / (view.to - view.from || 1)) * plotW;
229
-
230
- // The points in view, plus one on each side so the line leaves the plot
231
- const visible = series.map(s => {
232
- const inside = [];
233
- for (let i = 0; i < s.data.length; i++) {
234
- const p = position(i);
235
- if (p >= view.from && p <= view.to && Number.isFinite(s.data[i])) inside.push(i);
236
- }
237
- return inside;
238
- });
239
- const zeroBased = area || options.zero !== false;
240
- const { min, scale } = valueRange(series.flatMap((s, si) => visible[si].map(i => s.data[i])), zeroBased);
241
- const { y, baseline } = addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format: ctx.tickFormat });
242
-
243
- // x axis
244
- if (times) {
245
- const { ticks: stops, step } = timeTicks(view.from, view.to);
246
- const format = timeFormatter(step);
247
- for (const t of stops) {
248
- svg.append(svgEl("line", { x1: x(t), x2: x(t), y1: MARGIN.top + plotH, y2: MARGIN.top + plotH + 4, class: "chart-axis" }));
249
- svg.append(svgEl("text", { x: x(t), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, format(t)));
250
- }
251
- } else {
252
- const first = Math.max(Math.ceil(view.from + 0.5), 0);
253
- const last = Math.min(Math.floor(view.to - 0.5), count - 1);
254
- const every = Math.max(1, Math.ceil((last - first + 1) / Math.max(Math.floor(plotW / 60), 1)));
255
- for (let i = first; i <= last; i += every) svg.append(svgEl("text", { x: x(i), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, labels[i] ?? ""));
256
- }
257
-
258
- const clipId = uid("chart-clip");
259
- const clip = svgEl("clipPath", { id: clipId });
260
- clip.append(svgEl("rect", { x: MARGIN.left, y: MARGIN.top - 4, width: plotW, height: plotH + 8 }));
261
- svg.append(clip);
262
- const timeFormat = times ? new Intl.DateTimeFormat(getLocale(), { dateStyle: "medium", timeStyle: "medium" }) : null;
263
- const when = i => (times ? timeFormat.format(times[i]) : (labels[i] ?? ""));
264
- const dotted = Math.max(...visible.map(v => v.length)) <= DOT_LIMIT;
265
-
266
- series.forEach((s, si) => {
267
- // Neighbours outside the view keep the line running to the edge of the plot
268
- const inside = visible[si];
269
- const lo = inside.length ? inside[0] : 0;
270
- const hi = inside.length ? inside.at(-1) : -1;
271
- // Without `gaps` a missing value is skipped and the line goes on; with it the line breaks there, and a point on its own is a dot
272
- const runs = [];
273
- let run = [];
274
- for (let i = Math.max(lo - 1, 0); i <= Math.min(hi + 1, s.data.length - 1); i++) {
275
- if (Number.isFinite(s.data[i])) run.push(i);
276
- else if (options.gaps) {
277
- if (run.length) runs.push(run);
278
- run = [];
279
- }
280
- }
281
- if (run.length) runs.push(run);
282
- const group = svgEl("g", { "data-series": si, ...seriesProps(s, si) });
283
- const clipped = svgEl("g", { "clip-path": `url(#${clipId})` });
284
- for (const members of runs) {
285
- const points = decimate(members, s.data, Math.floor(plotW)).map(i => [x(position(i)), y(s.data[i])]);
286
- if (area && points.length) {
287
- const outline = [`M${points[0][0]},${baseline}`, ...points.map(p => `L${p.join(",")}`), `L${points.at(-1)[0]},${baseline}`, "Z"];
288
- clipped.append(svgEl("path", { d: outline.join(" "), class: "chart-area" }));
289
- }
290
- if (points.length === 1 && options.gaps) clipped.append(svgEl("circle", { cx: points[0][0], cy: points[0][1], r: 2.5, class: "chart-point chart-lone-point" }));
291
- else clipped.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none", pathLength: 1 }));
292
- }
293
- group.append(clipped);
294
- if (dotted) {
295
- for (const i of inside) {
296
- const dot = svgEl("circle", { cx: x(position(i)), cy: y(s.data[i]), r: 4, class: "chart-point" });
297
- addTip(ctx, dot, x(position(i)), y(s.data[i]), [`${s.name ?? ""} ${when(i)}`.trim(), format(s.data[i])]);
298
- group.append(dot);
299
- }
300
- }
301
- svg.append(group);
302
- });
303
-
304
- if (options.interactive === false) return;
305
-
306
- // A transparent layer over the plot: the tooltip follows the pointer, a drag selects a range to zoom into, and the keyboard pans and zooms.
307
- const hit = svgEl("rect", { class: "chart-hit", x: MARGIN.left, y: MARGIN.top, width: plotW, height: plotH, fill: "transparent" });
308
- const marker = svgEl("line", { class: "chart-marker", y1: MARGIN.top, y2: MARGIN.top + plotH, display: "none" });
309
- const selection = svgEl("rect", { class: "chart-selection", y: MARGIN.top, height: plotH, display: "none" });
310
- const toPosition = clientX => {
311
- const box = hit.getBoundingClientRect();
312
- const scaleX = box.width ? plotW / box.width : 1;
313
- return view.from + (((clientX - box.left) * scaleX) / plotW) * (view.to - view.from);
314
- };
315
- // The point (of the first series that has one) nearest to a position on the axis
316
- const nearest = target => {
317
- let best = null;
318
- series.forEach((s, si) => {
319
- const idx = visible[si];
320
- let lowIdx = 0;
321
- let highIdx = idx.length - 1;
322
- while (lowIdx < highIdx) {
323
- const mid = (lowIdx + highIdx) >> 1;
324
- if (position(idx[mid]) < target) lowIdx = mid + 1;
325
- else highIdx = mid;
326
- }
327
- for (const c of [idx[lowIdx - 1], idx[lowIdx]]) {
328
- if (c != null && (best == null || Math.abs(position(c) - target) < Math.abs(position(best) - target))) best = c;
329
- }
330
- });
331
- return best;
332
- };
333
- const showAt = index => {
334
- if (index == null) return;
335
- const px = x(position(index));
336
- marker.setAttribute("x1", px);
337
- marker.setAttribute("x2", px);
338
- marker.removeAttribute("display");
339
- const lines = [when(index), ...series.map(s => (Number.isFinite(s.data[index]) ? `${s.name ? `${s.name}: ` : ""}${format(s.data[index])}` : null)).filter(Boolean)];
340
- const top = Math.min(...series.map(s => (Number.isFinite(s.data[index]) ? y(s.data[index]) : Infinity)));
341
- ctx.tooltip.show(px, Number.isFinite(top) ? top : MARGIN.top, lines);
342
- };
343
- const hideAt = () => {
344
- marker.setAttribute("display", "none");
345
- ctx.tooltip.hide();
346
- };
347
- let dragStart = null;
348
- hit.addEventListener("pointermove", event => {
349
- if (dragStart != null) {
350
- const a = Math.min(dragStart, event.clientX);
351
- const b = Math.max(dragStart, event.clientX);
352
- const box = hit.getBoundingClientRect();
353
- const k = box.width ? plotW / box.width : 1;
354
- selection.setAttribute("x", MARGIN.left + (a - box.left) * k);
355
- selection.setAttribute("width", (b - a) * k);
356
- selection.removeAttribute("display");
357
- return;
358
- }
359
- showAt(nearest(toPosition(event.clientX)));
360
- });
361
- hit.addEventListener("pointerleave", () => { if (dragStart == null) hideAt(); });
362
- if (options.zoom) {
363
- hit.addEventListener("pointerdown", event => {
364
- if (event.button != null && event.button !== 0) return;
365
- dragStart = event.clientX;
366
- try { hit.setPointerCapture(event.pointerId); } catch { /* the pointer is gone */ }
367
- });
368
- const finish = event => {
369
- if (dragStart == null) return;
370
- const from = toPosition(Math.min(dragStart, event.clientX));
371
- const to = toPosition(Math.max(dragStart, event.clientX));
372
- const moved = Math.abs(event.clientX - dragStart);
373
- dragStart = null;
374
- selection.setAttribute("display", "none");
375
- if (moved > 6 && ctx.hooks?.zoom) ctx.hooks.zoom({ from, to });
376
- };
377
- hit.addEventListener("pointerup", finish);
378
- hit.addEventListener("pointercancel", () => { dragStart = null; selection.setAttribute("display", "none"); });
379
- hit.addEventListener("dblclick", () => ctx.hooks?.zoom(null));
380
- hit.setAttribute("tabindex", "0");
381
- hit.setAttribute("role", "application");
382
- hit.setAttribute("aria-label", translate("chart.zoomHint"));
383
- hit.addEventListener("keydown", event => {
384
- const span = view.to - view.from;
385
- const mid = (view.from + view.to) / 2;
386
- let next;
387
- if (event.key === "+" || event.key === "=") next = { from: mid - span / 4, to: mid + span / 4 };
388
- else if (event.key === "-" || event.key === "_") next = { from: mid - span, to: mid + span };
389
- else if (event.key === "ArrowLeft") next = { from: view.from - span / 4, to: view.to - span / 4 };
390
- else if (event.key === "ArrowRight") next = { from: view.from + span / 4, to: view.to + span / 4 };
391
- else if (event.key === "0" || event.key === "Escape") next = null;
392
- else return;
393
- event.preventDefault();
394
- ctx.hooks?.zoom(next);
395
- });
396
- if (zoom) {
397
- const reset = svgEl("g", { class: "chart-reset", role: "button", tabindex: 0, "aria-label": translate("chart.resetZoom") });
398
- reset.append(svgEl("text", { x: width - MARGIN.right, y: 24, "text-anchor": "end", class: "chart-legend" }, `↺ ${translate("chart.resetZoom")}`));
399
- reset.addEventListener("click", () => ctx.hooks?.zoom(null));
400
- reset.addEventListener("keydown", event => {
401
- if (event.key === "Enter" || event.key === " ") {
402
- event.preventDefault();
403
- ctx.hooks?.zoom(null);
404
- }
405
- });
406
- svg.append(reset);
407
- }
408
- }
409
- svg.append(marker, selection, hit);
410
- }
411
-
412
- // A small line without axes, legend or title: for a table cell or a stat tile. Its tooltips still work.
413
- function drawSparkline(svg, ctx) {
414
- const { series, width, height, format } = ctx;
415
- const s = series[0];
416
- const values = s.data.filter(Number.isFinite);
417
- const min = Math.min(...values);
418
- const max = Math.max(...values);
419
- const pad = 3;
420
- const x = i => pad + (s.data.length === 1 ? (width - 2 * pad) / 2 : (i / (s.data.length - 1)) * (width - 2 * pad));
421
- const y = v => height - pad - (max === min ? (height - 2 * pad) / 2 : ((v - min) / (max - min)) * (height - 2 * pad));
422
- const points = s.data.map((v, i) => [x(i), y(v)]).filter((_, i) => Number.isFinite(s.data[i]));
423
- const group = svgEl("g", { "data-series": 0, ...seriesProps(s, 0) });
424
- group.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none" }));
425
- const last = points.at(-1);
426
- if (last) {
427
- const dot = svgEl("circle", { cx: last[0], cy: last[1], r: 2.5, class: "chart-point" });
428
- addTip(ctx, dot, last[0], last[1], [format(values.at(-1))]);
429
- group.append(dot);
430
- }
431
- svg.append(group);
432
- }
433
-
434
- function drawPie(svg, ctx) {
435
- const { labels, series, width, height, donut, format } = ctx;
436
- const MARGIN = ctx.margin;
437
- const data = series[0].data.map(v => Math.max(0, v));
438
- const total = data.reduce((a, b) => a + b, 0);
439
- const cx = width / 2;
440
- const cy = MARGIN.top + (height - MARGIN.top - MARGIN.bottom) / 2;
441
- const r = Math.min(width - MARGIN.left - MARGIN.right, height - MARGIN.top - MARGIN.bottom) / 2;
442
- const inner = donut ? r * 0.55 : 0;
443
- const point = (radius, angle) => [cx + radius * Math.cos(angle), cy + radius * Math.sin(angle)].join(",");
444
- let start = -Math.PI / 2;
445
- data.forEach((value, i) => {
446
- if (!total || !value) return;
447
- const sweep = (value / total) * Math.PI * 2;
448
- let slice;
449
- if (sweep >= Math.PI * 2 - 1e-6) {
450
- // A single full slice cannot be drawn as an arc.
451
- slice = donut
452
- ? svgEl("circle", { cx, cy, r: (r + inner) / 2, fill: "none", "stroke-width": r - inner, class: "chart-ring" })
453
- : svgEl("circle", { cx, cy, r });
454
- } else {
455
- const end = start + sweep;
456
- const large = sweep > Math.PI ? 1 : 0;
457
- const d = donut
458
- ? `M${point(r, start)} A${r},${r} 0 ${large} 1 ${point(r, end)} L${point(inner, end)} A${inner},${inner} 0 ${large} 0 ${point(inner, start)} Z`
459
- : `M${cx},${cy} L${point(r, start)} A${r},${r} 0 ${large} 1 ${point(r, end)} Z`;
460
- slice = svgEl("path", { d });
461
- }
462
- slice.setAttribute("class", `chart-slice ${slice.getAttribute("class") ?? ""} ${seriesClass(i)}`.replace(/\s+/g, " ").trim());
463
- slice.setAttribute("data-series", i);
464
- const mid = start + sweep / 2;
465
- const [tx, ty] = point(r * (donut ? (1 + 0.55) / 2 : 0.6), mid).split(",").map(Number);
466
- addTip(ctx, slice, tx, ty, [labels[i] ?? "", `${format(value)} (${Math.round(value / total * 100)}%)`]);
467
- svg.append(slice);
468
- start += sweep;
469
- });
470
- // The legend of a pie lists the slices, not the series.
471
- return labels.map((name, i) => ({ name, props: { class: seriesClass(i) }, series: i }));
472
- }
473
-
474
- const DRAWERS = {
475
- bar: drawBar,
476
- line: drawLine,
477
- area: (svg, ctx) => drawLine(svg, { ...ctx, area: true }),
478
- sparkline: drawSparkline,
479
- pie: drawPie,
480
- donut: (svg, ctx) => drawPie(svg, { ...ctx, donut: true })
481
- };
482
-
483
- /* ------------------TABLE OF VALUES------------------- */
484
-
485
- // The same numbers as a table, for screen readers and for people who want to read them off or copy them.
486
- function buildDataTable({ labels, series, times, title, type, format = formatNumber }) {
487
- const details = document.createElement("details");
488
- details.className = "chart-data";
489
- const summary = document.createElement("summary");
490
- summary.textContent = translate("showAsTable");
491
- const table = document.createElement("table");
492
- table.className = "athena-table chart-data-table";
493
- if (title) table.createCaption().textContent = title;
494
- const headRow = table.createTHead().insertRow();
495
- const names = type === "pie" || type === "donut" ? [series[0].name ?? ""] : series.map((s, i) => s.name ?? `${translate("series")} ${i + 1}`);
496
- ["", ...names].forEach((name, i) => {
497
- const th = document.createElement("th");
498
- th.scope = "col";
499
- th.textContent = i ? name : (times ? translate("time") : "");
500
- headRow.append(th);
501
- });
502
- const body = table.createTBody();
503
- const shown = type === "pie" || type === "donut" ? [series[0]] : series;
504
- const count = Math.max(...shown.map(s => s.data.length));
505
- const when = times ? new Intl.DateTimeFormat(getLocale(), { dateStyle: "medium", timeStyle: "medium" }) : null;
506
- for (let i = 0; i < count; i++) {
507
- const row = body.insertRow();
508
- const head = document.createElement("th");
509
- head.scope = "row";
510
- head.textContent = times ? when.format(times[i]) : (labels[i] ?? "");
511
- row.append(head);
512
- for (const s of shown) row.insertCell().textContent = s.data[i] == null ? "" : format(s.data[i]);
513
- }
514
- details.append(summary, table);
515
- return details;
516
- }
517
-
518
- /**
519
- * Draws a chart as inline SVG and appends it to its parent.
520
- *
521
- * @param {object} options
522
- * @param {"bar"|"line"|"area"|"sparkline"|"pie"|"donut"} [options.type="bar"]
523
- * @param {string|Element} [options.parent] element, id or selector, defaults to "wrapper"
524
- * @param {string} [options.id] id of the svg element
525
- * @param {string} [options.title] drawn above the chart, and its accessible name
526
- * @param {string[]} [options.labels] category labels
527
- * @param {(number|Date|string)[]} [options.times] line and area charts: the time of every value (Date, ms or a date string).
528
- * The x axis becomes a time axis with ticks at round times, and the points sit at their real distance.
529
- * @param {{name?: string, data: number[], color?: string}[]} options.series pie / donut / sparkline use the first series only.
530
- * Colours come from the theme (--series-1 ... --series-8); `color` is an override for one series.
531
- * @param {number} [options.width=600] (a sparkline: 120)
532
- * @param {number} [options.height=360] (a sparkline: 32)
533
- * @param {boolean} [options.legend] default: shown for several series, and for pie / donut. Clicking an entry hides / shows its series.
534
- * @param {boolean} [options.table=false] adds a "Show as table" section with the values below the chart
535
- * @param {boolean} [options.zero=true] line charts: false lets the value axis start near the smallest value
536
- * @param {boolean} [options.zoom=false] line and area charts: drag over the plot to zoom into that range, double click (or the
537
- * reset button, or 0 / Esc) to zoom out; with the keyboard on the plot: + and - zoom, the arrow keys pan
538
- * @param {{from: number, to: number}|null} [options.zoomRange] the range in view, in the units of the x axis: milliseconds with
539
- * `times`, otherwise the index of the point (-0.5 is the left edge of the first point)
540
- * @param {(range: ({from: number, to: number}|null)) => void} [options.onZoom] called when a person zooms or resets
541
- * @param {number} [options.maxPoints] `push` keeps at most this many points per series (the oldest are dropped)
542
- * @param {number[]} [options.hiddenSeries] the series (or slices) that are hidden at the start; a person hides and shows them with the legend, and a redraw keeps that
543
- * @param {boolean} [options.animate=true] the first drawing animates: bars grow, a line is drawn, slices pop in (not when it is redrawn, and not under reduced motion)
544
- * @param {boolean} [options.interactive=true] line and area charts: false leaves out the pointer layer (tooltip that follows the pointer, zoom)
545
- * @param {boolean} [options.gaps=false] line and area charts: a missing value (null, NaN, undefined) breaks the line, and a point on its own is a dot;
546
- * without it the line goes on from the value before to the one after
547
- * @param {{from: (number|Date|string), to: (number|Date|string)}} [options.timeRange] line and area charts with `times`: the range of the time axis, when it is not the one
548
- * the data covers (the last hour, of which only the last quarter has been measured)
549
- * @param {(value: number) => string} [options.format] how a value is written: on the axis, in the tooltips and in the table of values (default: whole numbers, otherwise two decimals)
550
- * @param {(value: number) => string} [options.tickFormat] how the numbers of the value axis are written, when they should not be written like the values (a chart of whole numbers has ticks of 0.2)
551
- * @param {{top?: number, right?: number, bottom?: number, left?: number}} [options.margin] room around the plot in px (default 40, 20, 50, 55): a chart without a title and a legend does not need the top
552
- * @param {boolean} [options.responsive=false] the chart is as wide as its parent and follows it when it changes (`height` stays); `width` is only the first guess
553
- * @returns {(SVGElement & {element: SVGElement, update: (options?: object) => SVGElement, destroy: () => void,
554
- * zoom: (from: number, to: number) => void, resetZoom: () => void, getZoom: () => ({from: number, to: number}|null),
555
- * push: (point: {x?: (number|Date|string), label?: string, values: (number|number[])}, config?: {maxPoints?: number}) => void,
556
- * dataTable: (HTMLElement|null)})|null}
557
- * the SVG element, which also carries the handle ({ element, update(options), destroy() }) of the other
558
- * components; null when the options are invalid. `parent` is an element, an id or a selector.
559
- * `push` adds a point to every series (a number for the first series, or one value per series; `x` is the time with
560
- * `times`, `label` the category) and draws the chart again at most once per frame, however often it is called.
561
- */
562
- export function generateChart(options = {}) {
563
- const state = { used: { ...options, series: (options.series ?? []).map(s => ({ ...s, data: [...(s.data ?? [])] })) }, current: null, queued: false };
564
- if (options.labels) state.used.labels = [...options.labels];
565
- if (options.times) state.used.times = [...options.times];
566
- const hidden = new Set(options.hiddenSeries ?? []);
567
- let resizing = null;
568
- // Only the first drawing animates (bars grow, the line is drawn, slices pop in): a redraw while streaming or zooming must not start it again
569
- let firstDrawing = options.animate !== false;
570
- const hooks = {
571
- legend: (series, off) => {
572
- if (off) hidden.add(series);
573
- else hidden.delete(series);
574
- state.used.hiddenSeries = [...hidden];
575
- },
576
- zoom: range => {
577
- state.used = { ...state.used, zoomRange: range ?? null };
578
- handle.redraw();
579
- options.onZoom?.(range ?? null);
580
- }
581
- };
582
- const handle = {
583
- element: () => state.current.svg,
584
- redraw() {
585
- const next = buildChart(state.used, hooks, { animate: false });
586
- if (!next) return state.current?.svg;
587
- // A redraw replaces the whole SVG (every second while streaming, and when someone zooms). The keyboard focus would be lost
588
- // with it, so it goes to the same place in the new one: the same legend entry, the same point, or the plot.
589
- const old = state.current?.svg;
590
- const active = old && old.contains(document.activeElement) ? document.activeElement : null;
591
- const focusables = active ? [...old.querySelectorAll("[tabindex]")] : [];
592
- const position = active ? focusables.indexOf(active) : -1;
593
- if (state.current) {
594
- old.replaceWith(next.svg);
595
- state.current.table?.remove();
596
- if (next.table) next.svg.after(next.table);
597
- }
598
- state.current = next;
599
- if (active) {
600
- const now = [...next.svg.querySelectorAll("[tabindex]")];
601
- (active.classList.contains("chart-hit") || active.classList.contains("chart-reset") ? next.svg.querySelector(".chart-hit") : now[position] ?? next.svg.querySelector(".chart-hit"))?.focus({ preventScroll: true });
602
- }
603
- return attach(next.svg);
604
- },
605
- update(changes = {}) {
606
- state.used = { ...state.used, ...changes };
607
- return handle.redraw();
608
- },
609
- destroy() {
610
- resizing?.disconnect();
611
- state.current.svg.remove();
612
- state.current.table?.remove();
613
- },
614
- zoom: (from, to) => hooks.zoom({ from, to }),
615
- resetZoom: () => hooks.zoom(null),
616
- getZoom: () => state.used.zoomRange ?? null,
617
- push(point, config = {}) {
618
- const used = state.used;
619
- const values = Array.isArray(point.values) ? point.values : [point.values];
620
- used.series.forEach((s, i) => s.data.push(values[i] ?? NaN));
621
- if (used.times) used.times.push(toTime(point.x ?? Date.now()));
622
- else if (used.labels) used.labels.push(String(point.label ?? used.labels.length + 1));
623
- const limit = config.maxPoints ?? used.maxPoints;
624
- const extra = limit ? used.series[0].data.length - limit : 0;
625
- if (extra > 0) {
626
- for (const s of used.series) s.data.splice(0, extra);
627
- used.times?.splice(0, extra);
628
- used.labels?.splice(0, extra);
629
- }
630
- if (state.queued) return;
631
- state.queued = true;
632
- // Once per frame (the timer is for pages where frames are paused or late)
633
- let timer = 0;
634
- const run = () => {
635
- if (!state.queued) return;
636
- state.queued = false;
637
- clearTimeout(timer);
638
- handle.redraw();
639
- };
640
- requestAnimationFrame(run);
641
- timer = setTimeout(run, 100);
642
- }
643
- };
644
- const attach = svg => Object.defineProperties(svg, {
645
- element: { get: () => state.current.svg, configurable: true },
646
- update: { value: handle.update, configurable: true },
647
- destroy: { value: handle.destroy, configurable: true },
648
- zoom: { value: handle.zoom, configurable: true },
649
- resetZoom: { value: handle.resetZoom, configurable: true },
650
- getZoom: { value: handle.getZoom, configurable: true },
651
- push: { value: handle.push, configurable: true },
652
- dataTable: { get: () => state.current.table ?? null, configurable: true }
653
- });
654
-
655
- const host = resolveElement(options.parent ?? "wrapper") ?? document.body;
656
- if (options.responsive && host.clientWidth >= 120) state.used.width = Math.floor(host.clientWidth);
657
- const built = buildChart(state.used, hooks, { animate: firstDrawing });
658
- firstDrawing = false;
659
- if (!built) return null;
660
- state.current = built;
661
- host.append(built.svg);
662
- if (built.table) built.svg.after(built.table);
663
- if (options.responsive && typeof ResizeObserver === "function") {
664
- // The chart is as wide as its parent (the height stays): redrawn once per frame when the parent changes its width
665
- let frame = 0;
666
- resizing = new ResizeObserver(() => {
667
- cancelAnimationFrame(frame);
668
- frame = requestAnimationFrame(() => {
669
- const width = Math.floor(host.clientWidth);
670
- if (width >= 120 && width !== state.used.width) handle.update({ width });
671
- });
672
- });
673
- resizing.observe(host);
674
- }
675
- return attach(built.svg);
676
- }
677
-
678
- function buildChart(options = {}, hooks, { animate = false } = {}) {
679
- const { type = "bar", id, title } = options;
680
- const sparkline = type === "sparkline";
681
- const width = options.width ?? (sparkline ? 120 : 600);
682
- const height = options.height ?? (sparkline ? 32 : 360);
683
- const draw = DRAWERS[type];
684
- const series = (options.series ?? []).filter(s => Array.isArray(s?.data) && s.data.length);
685
- if (!draw || !series.length) {
686
- console.error("Athena UI: generateChart needs a valid type and at least one series with data", options);
687
- return null;
688
- }
689
- const labels = (options.labels ?? []).map(String);
690
- const count = Math.max(...series.map(s => s.data.length));
691
- while (labels.length < count) labels.push(String(labels.length + 1));
692
- const times = options.times && (type === "line" || type === "area") ? options.times.map(toTime) : null;
693
- if (times && (times.length < count || times.some(Number.isNaN))) {
694
- console.error("Athena UI: generateChart `times` needs a valid time for every value", options);
695
- return null;
696
- }
697
-
698
- const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class: `athena-chart athena-chart-${type}${animate && type !== "sparkline" ? " athena-chart-animated" : ""}`, role: "img" });
699
- if (id) svg.id = id;
700
- const summary = `${title ?? translate(`chart.${type}`)}: ${series.map(s => s.name ?? "").filter(Boolean).join(", ")}`.replace(/: $/, "");
701
- svg.setAttribute("aria-label", options.ariaLabel ?? summary);
702
- if (title && !sparkline) svg.append(svgEl("text", { x: width / 2, y: 24, "text-anchor": "middle", class: "chart-title" }, title));
703
-
704
- // The tooltip is created first, so the shapes can use it, and moved to the end afterwards, so it is drawn on top.
705
- const tooltip = createTooltip(svg, width);
706
- const margin = { ...DEFAULT_MARGIN, ...(options.margin ?? {}) };
707
- const format = typeof options.format === "function" ? options.format : formatNumber;
708
- const tickFormat = typeof options.tickFormat === "function" ? options.tickFormat : format;
709
- const ctx = { labels, series, width, height, times, options, tooltip, hooks, zoom: options.zoomRange ?? null, margin, format, tickFormat };
710
- const pieLegend = draw(svg, ctx);
711
- if (!sparkline && (options.legend ?? (Boolean(pieLegend) || series.length > 1))) {
712
- addLegend(svg, pieLegend ?? series.map((s, i) => ({ name: s.name ?? `${translate("series")} ${i + 1}`, props: seriesProps(s, i), series: i })), width, height, ctx);
713
- }
714
- svg.append(tooltip.group);
715
- for (const index of options.hiddenSeries ?? []) {
716
- for (const node of svg.querySelectorAll(`[data-series="${index}"]`)) node.classList.add("chart-hidden");
717
- const entry = svg.querySelector(`.chart-legend-item[data-legend="${index}"]`);
718
- entry?.setAttribute("aria-pressed", "false");
719
- entry?.classList.add("is-off");
720
- }
721
- return { svg, table: options.table ? buildDataTable({ labels, series, times, title, type, format }) : null };
722
- }
1
+ //chartGenerator for Athena UI
2
+ //Author: Csaba Tóth https://github.com/csabatibortoth/
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ // Dependency free SVG charts: bar, line, area, sparkline, pie and donut. Colours come from the theme (--series-1 ... --series-8,
7
+ // see the stylesheet), nothing is styled inline, so a strict Content-Security-Policy works.
8
+
9
+ import { resolveElement, uid } from "../../core/dom.js";
10
+ import { getLocale, translate } from "../../core/i18n.js";
11
+
12
+ const NS = "http://www.w3.org/2000/svg";
13
+ const SERIES_COLORS = 8;
14
+ const DEFAULT_MARGIN = { top: 40, right: 20, bottom: 50, left: 55 };
15
+ const DOT_LIMIT = 80; // up to this many points in view every point is a dot with a tooltip; more: the tooltip follows the pointer
16
+
17
+ const svgEl = (tag, attrs = {}, text) => {
18
+ const node = document.createElementNS(NS, tag);
19
+ for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value);
20
+ if (text != null) node.textContent = text;
21
+ return node;
22
+ };
23
+
24
+ const seriesClass = index => `s${(index % SERIES_COLORS) + 1}`;
25
+ // A colour given by the caller goes in the `color` attribute (the shapes paint with currentColor); otherwise the class picks it from the theme.
26
+ const seriesProps = (series, index) => (series.color ? { color: series.color } : { class: seriesClass(index) });
27
+ // The time in a tooltip and in the table of values: `timeFormat` is a function (milliseconds) => text, or the options of Intl.DateTimeFormat
28
+ const DEFAULT_TIME_FORMAT = { dateStyle: "medium", timeStyle: "medium" };
29
+ function makeTimeFormatter(timeFormat) {
30
+ if (typeof timeFormat === "function") return timeFormat;
31
+ const formatter = new Intl.DateTimeFormat(getLocale(), timeFormat && typeof timeFormat === "object" ? timeFormat : DEFAULT_TIME_FORMAT);
32
+ return t => formatter.format(t);
33
+ }
34
+ const formatNumber = n => Number.isInteger(n) ? String(n) : String(+n.toFixed(2));
35
+
36
+ // Rounded axis maximum and tick step, so ticks land on readable numbers.
37
+ function niceScale(span, ticks = 5) {
38
+ if (span <= 0) return { span: 1, step: 1 / ticks };
39
+ const rough = span / ticks;
40
+ const magnitude = 10 ** Math.floor(Math.log10(rough));
41
+ const step = [1, 2, 5, 10].map(m => m * magnitude).find(s => s >= rough);
42
+ return { span: step * Math.ceil(span / step - 1e-9), step };
43
+ }
44
+
45
+ /* ------------------TIME AXIS------------------- */
46
+
47
+ const SECOND = 1000;
48
+ const MINUTE = 60 * SECOND;
49
+ const HOUR = 60 * MINUTE;
50
+ const DAY = 24 * HOUR;
51
+ const TIME_STEPS = [SECOND, 5 * SECOND, 15 * SECOND, 30 * SECOND, MINUTE, 5 * MINUTE, 15 * MINUTE, 30 * MINUTE, HOUR, 3 * HOUR, 6 * HOUR,
52
+ 12 * HOUR, DAY, 2 * DAY, 7 * DAY, 14 * DAY, 30 * DAY, 90 * DAY, 365 * DAY];
53
+
54
+ /** Tick positions (ms) at round times between `from` and `to`, about `count` of them. */
55
+ export function timeTicks(from, to, count = 6) {
56
+ const step = TIME_STEPS.find(s => (to - from) / s <= count) ?? TIME_STEPS.at(-1);
57
+ // Ticks of a day or more start at midnight of the local day, shorter ones at a multiple of the step.
58
+ const offset = step >= DAY ? new Date(from).getTimezoneOffset() * MINUTE : 0;
59
+ const ticks = [];
60
+ for (let t = Math.ceil((from - offset) / step) * step + offset; t <= to; t += step) ticks.push(t);
61
+ return { ticks, step };
62
+ }
63
+
64
+ function timeFormatter(step) {
65
+ const locale = getLocale();
66
+ const options = step < MINUTE ? { hour: "2-digit", minute: "2-digit", second: "2-digit" }
67
+ : step < DAY ? { hour: "2-digit", minute: "2-digit" }
68
+ : step < 90 * DAY ? { month: "short", day: "numeric" }
69
+ : { month: "short", year: "numeric" };
70
+ const format = new Intl.DateTimeFormat(locale, options);
71
+ return t => format.format(t);
72
+ }
73
+
74
+ const toTime = value => (value instanceof Date ? value.getTime() : typeof value === "number" ? value : Date.parse(value));
75
+
76
+ /**
77
+ * Keeps about `buckets` x positions of a long series: of every bucket the lowest and the highest value stay (in their order),
78
+ * so peaks are not lost. Returns the kept indices.
79
+ */
80
+ export function decimate(indices, values, buckets) {
81
+ if (indices.length <= buckets * 2) return indices;
82
+ const size = indices.length / buckets;
83
+ const kept = [];
84
+ for (let b = 0; b < buckets; b++) {
85
+ const slice = indices.slice(Math.floor(b * size), Math.floor((b + 1) * size));
86
+ if (!slice.length) continue;
87
+ let low = slice[0];
88
+ let high = slice[0];
89
+ for (const i of slice) {
90
+ if (values[i] < values[low]) low = i;
91
+ if (values[i] > values[high]) high = i;
92
+ }
93
+ kept.push(...(low === high ? [low] : low < high ? [low, high] : [high, low]));
94
+ }
95
+ return kept;
96
+ }
97
+
98
+ /* ------------------PARTS------------------- */
99
+
100
+ function addLegend(svg, entries, width, height, ctx) {
101
+ const MARGIN = ctx.margin;
102
+ let x = MARGIN.left;
103
+ const y = height - 12;
104
+ entries.forEach(({ name, props, series }) => {
105
+ const group = svgEl("g", { class: "chart-legend-item", tabindex: 0, role: "button", "aria-pressed": "true", "aria-label": name, "data-legend": series ?? "" });
106
+ group.append(svgEl("rect", { x, y: y - 9, width: 10, height: 10, class: `chart-swatch ${props.class ?? ""}`.trim(), ...(props.color ? { color: props.color } : {}) }));
107
+ group.append(svgEl("text", { x: x + 14, y, class: "chart-legend" }, name));
108
+ if (series != null) {
109
+ const toggle = () => {
110
+ const hidden = group.getAttribute("aria-pressed") === "true";
111
+ group.setAttribute("aria-pressed", hidden ? "false" : "true");
112
+ group.classList.toggle("is-off", hidden);
113
+ for (const node of svg.querySelectorAll(`[data-series="${series}"]`)) node.classList.toggle("chart-hidden", hidden);
114
+ ctx.hooks?.legend?.(series, hidden);
115
+ ctx.tooltip.hide();
116
+ };
117
+ group.addEventListener("click", toggle);
118
+ group.addEventListener("keydown", event => {
119
+ if (event.key === "Enter" || event.key === " ") {
120
+ event.preventDefault();
121
+ toggle();
122
+ }
123
+ });
124
+ }
125
+ svg.append(group);
126
+ x += 14 + name.length * 7 + 14;
127
+ });
128
+ }
129
+
130
+ // One tooltip per chart, drawn inside the SVG and moved with attributes (no inline style). Shows on hover and on keyboard focus.
131
+ function createTooltip(svg, width) {
132
+ const group = svgEl("g", { class: "chart-tooltip", "aria-hidden": "true" });
133
+ const box = svgEl("rect", { class: "chart-tooltip-box", rx: 4 });
134
+ const text = svgEl("text", { class: "chart-tooltip-text" });
135
+ group.append(box, text);
136
+ const show = (x, y, lines) => {
137
+ text.replaceChildren(...lines.map((line, i) => svgEl("tspan", { x: 8, dy: i ? 15 : 0 }, line)));
138
+ group.classList.add("is-visible");
139
+ let w = 80;
140
+ let h = lines.length * 15 + 8;
141
+ try {
142
+ const bbox = text.getBBox();
143
+ w = bbox.width + 16;
144
+ h = bbox.height + 10;
145
+ } catch { /* not rendered: the estimate stays */ }
146
+ text.setAttribute("y", 15);
147
+ const left = Math.min(Math.max(x - w / 2, 2), Math.max(width - w - 2, 2));
148
+ const top = Math.max(y - h - 10, 2);
149
+ box.setAttribute("width", w);
150
+ box.setAttribute("height", h);
151
+ group.setAttribute("transform", `translate(${left} ${top})`);
152
+ };
153
+ const hide = () => group.classList.remove("is-visible");
154
+ svg.append(group);
155
+ return { show, hide, group };
156
+ }
157
+
158
+ // Makes a shape react to the pointer and the keyboard focus. It is focusable and named, so the values can be read without a mouse.
159
+ function addTip(ctx, node, x, y, lines) {
160
+ node.setAttribute("tabindex", "0");
161
+ node.setAttribute("aria-label", lines.join(", "));
162
+ node.setAttribute("role", "img");
163
+ const show = () => ctx.tooltip.show(x, y, lines);
164
+ node.addEventListener("pointerenter", show);
165
+ node.addEventListener("focus", show);
166
+ node.addEventListener("pointerleave", ctx.tooltip.hide);
167
+ node.addEventListener("blur", ctx.tooltip.hide);
168
+ }
169
+
170
+ // Draws the value grid and the y axis for the range [min, min + scale.span].
171
+ function addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format = formatNumber }) {
172
+ const plotW = width - MARGIN.left - MARGIN.right;
173
+ const plotH = height - MARGIN.top - MARGIN.bottom;
174
+ const y = value => MARGIN.top + plotH - ((value - min) / scale.span) * plotH;
175
+ const ticks = Math.round(scale.span / scale.step);
176
+ for (let i = 0; i <= ticks; i++) {
177
+ const v = min + i * scale.step;
178
+ svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: y(v), y2: y(v), class: "chart-grid" }));
179
+ svg.append(svgEl("text", { x: MARGIN.left - 8, y: y(v) + 4, "text-anchor": "end", class: "chart-tick" }, format(v)));
180
+ }
181
+ svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left, y1: MARGIN.top, y2: MARGIN.top + plotH, class: "chart-axis" }));
182
+ // The category axis sits at zero when the range includes it, so negative bars hang below it.
183
+ const baseline = y(Math.min(Math.max(0, min), min + scale.span));
184
+ svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: baseline, y2: baseline, class: "chart-axis" }));
185
+ return { y, baseline, plotW, plotH };
186
+ }
187
+
188
+ function valueRange(values, zero = true) {
189
+ const finite = values.filter(Number.isFinite);
190
+ if (!finite.length) return { min: 0, scale: niceScale(1) };
191
+ let min = zero ? Math.min(0, ...finite) : Math.min(...finite);
192
+ const max = Math.max(zero ? 0 : -Infinity, ...finite);
193
+ const scale = niceScale(max - min);
194
+ if (!zero) min = Math.floor(min / scale.step) * scale.step; // start the axis at a round number
195
+ return { min, scale: niceScale(max - min) };
196
+ }
197
+
198
+ /* ------------------DRAWERS------------------- */
199
+
200
+ function drawBar(svg, ctx) {
201
+ const { labels, series, width, height, format } = ctx;
202
+ const MARGIN = ctx.margin;
203
+ const { min, scale } = valueRange(series.flatMap(s => s.data));
204
+ const { y, plotW, plotH } = addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format: ctx.tickFormat });
205
+ const band = plotW / Math.max(labels.length, 1);
206
+ labels.forEach((label, i) => svg.append(svgEl("text",
207
+ { x: MARGIN.left + band * (i + 0.5), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, label)));
208
+ const groupWidth = band * 0.8;
209
+ const barWidth = groupWidth / series.length;
210
+ series.forEach((s, si) => s.data.forEach((value, i) => {
211
+ const x = MARGIN.left + band * i + (band - groupWidth) / 2 + barWidth * si;
212
+ const top = Math.min(y(value), y(0));
213
+ const bar = svgEl("rect", {
214
+ x, y: top, width: Math.max(barWidth - 2, 1), height: Math.abs(y(0) - y(value)),
215
+ "data-series": si, ...seriesProps(s, si)
216
+ });
217
+ bar.setAttribute("class", `chart-bar ${bar.getAttribute("class") ?? ""}`.trim());
218
+ addTip(ctx, bar, x + barWidth / 2, top, [`${s.name ?? ""} ${labels[i] ?? ""}`.trim(), format(value)]);
219
+ svg.append(bar);
220
+ }));
221
+ }
222
+
223
+ // Line and area charts, with a category or a time axis, zoom (a range of the x axis) and long series (no dots, a pointer tooltip).
224
+ function drawLine(svg, ctx) {
225
+ const { labels, series, width, height, times, area, options, zoom, format } = ctx;
226
+ const MARGIN = ctx.margin;
227
+ const plotW = width - MARGIN.left - MARGIN.right;
228
+ const plotH = height - MARGIN.top - MARGIN.bottom;
229
+ const count = Math.max(...series.map(s => s.data.length));
230
+ const position = i => (times ? times[i] : i); // x position of point i in the units of the axis
231
+ // The range of the x axis: what the data covers, or the one asked for (a window of the last hour that is only half measured)
232
+ const full = times ? (options.timeRange && options.timeRange.to > options.timeRange.from ? { from: toTime(options.timeRange.from), to: toTime(options.timeRange.to) } : { from: Math.min(...times.slice(0, count)), to: Math.max(...times.slice(0, count)) }) : { from: -0.5, to: count - 0.5 };
233
+ const view = zoom ? { from: Math.max(zoom.from, full.from), to: Math.min(zoom.to, full.to) } : full;
234
+ if (!(view.to > view.from)) Object.assign(view, full);
235
+ const x = p => MARGIN.left + ((p - view.from) / (view.to - view.from || 1)) * plotW;
236
+
237
+ // The points in view, plus one on each side so the line leaves the plot
238
+ const visible = series.map(s => {
239
+ const inside = [];
240
+ for (let i = 0; i < s.data.length; i++) {
241
+ const p = position(i);
242
+ if (p >= view.from && p <= view.to && Number.isFinite(s.data[i])) inside.push(i);
243
+ }
244
+ return inside;
245
+ });
246
+ const zeroBased = area || options.zero !== false;
247
+ const { min, scale } = valueRange(series.flatMap((s, si) => visible[si].map(i => s.data[i])), zeroBased);
248
+ const { y, baseline } = addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format: ctx.tickFormat });
249
+
250
+ // x axis
251
+ if (times) {
252
+ const { ticks: stops, step } = timeTicks(view.from, view.to);
253
+ const format = timeFormatter(step);
254
+ for (const t of stops) {
255
+ svg.append(svgEl("line", { x1: x(t), x2: x(t), y1: MARGIN.top + plotH, y2: MARGIN.top + plotH + 4, class: "chart-axis" }));
256
+ svg.append(svgEl("text", { x: x(t), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, format(t)));
257
+ }
258
+ } else {
259
+ const first = Math.max(Math.ceil(view.from + 0.5), 0);
260
+ const last = Math.min(Math.floor(view.to - 0.5), count - 1);
261
+ const every = Math.max(1, Math.ceil((last - first + 1) / Math.max(Math.floor(plotW / 60), 1)));
262
+ for (let i = first; i <= last; i += every) svg.append(svgEl("text", { x: x(i), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, labels[i] ?? ""));
263
+ }
264
+
265
+ const clipId = uid("chart-clip");
266
+ const clip = svgEl("clipPath", { id: clipId });
267
+ clip.append(svgEl("rect", { x: MARGIN.left, y: MARGIN.top - 4, width: plotW, height: plotH + 8 }));
268
+ svg.append(clip);
269
+ const when = i => (times ? ctx.formatTime(times[i]) : (labels[i] ?? ""));
270
+ // `points: false` never draws the dots (the tooltip still follows the pointer and the keyboard), so a chart with few points looks like one with many
271
+ const dotted = options.points !== false && Math.max(...visible.map(v => v.length)) <= DOT_LIMIT;
272
+
273
+ series.forEach((s, si) => {
274
+ // Neighbours outside the view keep the line running to the edge of the plot
275
+ const inside = visible[si];
276
+ const lo = inside.length ? inside[0] : 0;
277
+ const hi = inside.length ? inside.at(-1) : -1;
278
+ // Without `gaps` a missing value is skipped and the line goes on; with it the line breaks there, and a point on its own is a dot
279
+ const runs = [];
280
+ let run = [];
281
+ for (let i = Math.max(lo - 1, 0); i <= Math.min(hi + 1, s.data.length - 1); i++) {
282
+ if (Number.isFinite(s.data[i])) run.push(i);
283
+ else if (options.gaps) {
284
+ if (run.length) runs.push(run);
285
+ run = [];
286
+ }
287
+ }
288
+ if (run.length) runs.push(run);
289
+ const group = svgEl("g", { "data-series": si, ...seriesProps(s, si) });
290
+ const clipped = svgEl("g", { "clip-path": `url(#${clipId})` });
291
+ for (const members of runs) {
292
+ const points = decimate(members, s.data, Math.floor(plotW)).map(i => [x(position(i)), y(s.data[i])]);
293
+ if (area && points.length) {
294
+ const outline = [`M${points[0][0]},${baseline}`, ...points.map(p => `L${p.join(",")}`), `L${points.at(-1)[0]},${baseline}`, "Z"];
295
+ clipped.append(svgEl("path", { d: outline.join(" "), class: "chart-area" }));
296
+ }
297
+ if (points.length === 1 && options.gaps) {
298
+ // a lone point keeps a tooltip of its own, also when the chart draws no dots
299
+ const lone = svgEl("circle", { cx: points[0][0], cy: points[0][1], r: 2.5, class: "chart-point chart-lone-point" });
300
+ if (options.interactive !== false) addTip(ctx, lone, points[0][0], points[0][1], [`${s.name ?? ""} ${when(members[0])}`.trim(), format(s.data[members[0]])]);
301
+ clipped.append(lone);
302
+ }
303
+ else clipped.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none", pathLength: 1 }));
304
+ }
305
+ group.append(clipped);
306
+ if (dotted) {
307
+ for (const i of inside) {
308
+ const dot = svgEl("circle", { cx: x(position(i)), cy: y(s.data[i]), r: 4, class: "chart-point" });
309
+ addTip(ctx, dot, x(position(i)), y(s.data[i]), [`${s.name ?? ""} ${when(i)}`.trim(), format(s.data[i])]);
310
+ group.append(dot);
311
+ }
312
+ }
313
+ svg.append(group);
314
+ });
315
+
316
+ if (options.interactive === false) return;
317
+
318
+ // A transparent layer over the plot: the tooltip follows the pointer, a drag selects a range to zoom into, and the keyboard pans and zooms.
319
+ const hit = svgEl("rect", { class: "chart-hit", x: MARGIN.left, y: MARGIN.top, width: plotW, height: plotH, fill: "transparent" });
320
+ const marker = svgEl("line", { class: "chart-marker", y1: MARGIN.top, y2: MARGIN.top + plotH, display: "none" });
321
+ const selection = svgEl("rect", { class: "chart-selection", y: MARGIN.top, height: plotH, display: "none" });
322
+ const toPosition = clientX => {
323
+ const box = hit.getBoundingClientRect();
324
+ const scaleX = box.width ? plotW / box.width : 1;
325
+ return view.from + (((clientX - box.left) * scaleX) / plotW) * (view.to - view.from);
326
+ };
327
+ // The point (of the first series that has one) nearest to a position on the axis
328
+ const nearest = target => {
329
+ let best = null;
330
+ series.forEach((s, si) => {
331
+ const idx = visible[si];
332
+ let lowIdx = 0;
333
+ let highIdx = idx.length - 1;
334
+ while (lowIdx < highIdx) {
335
+ const mid = (lowIdx + highIdx) >> 1;
336
+ if (position(idx[mid]) < target) lowIdx = mid + 1;
337
+ else highIdx = mid;
338
+ }
339
+ for (const c of [idx[lowIdx - 1], idx[lowIdx]]) {
340
+ if (c != null && (best == null || Math.abs(position(c) - target) < Math.abs(position(best) - target))) best = c;
341
+ }
342
+ });
343
+ return best;
344
+ };
345
+ const showAt = index => {
346
+ if (index == null) return;
347
+ const px = x(position(index));
348
+ marker.setAttribute("x1", px);
349
+ marker.setAttribute("x2", px);
350
+ marker.removeAttribute("display");
351
+ const lines = [when(index), ...series.map(s => (Number.isFinite(s.data[index]) ? `${s.name ? `${s.name}: ` : ""}${format(s.data[index])}` : null)).filter(Boolean)];
352
+ const top = Math.min(...series.map(s => (Number.isFinite(s.data[index]) ? y(s.data[index]) : Infinity)));
353
+ ctx.tooltip.show(px, Number.isFinite(top) ? top : MARGIN.top, lines);
354
+ };
355
+ const hideAt = () => {
356
+ marker.setAttribute("display", "none");
357
+ ctx.tooltip.hide();
358
+ };
359
+ let dragStart = null;
360
+ hit.addEventListener("pointermove", event => {
361
+ if (dragStart != null) {
362
+ const a = Math.min(dragStart, event.clientX);
363
+ const b = Math.max(dragStart, event.clientX);
364
+ const box = hit.getBoundingClientRect();
365
+ const k = box.width ? plotW / box.width : 1;
366
+ selection.setAttribute("x", MARGIN.left + (a - box.left) * k);
367
+ selection.setAttribute("width", (b - a) * k);
368
+ selection.removeAttribute("display");
369
+ return;
370
+ }
371
+ showAt(nearest(toPosition(event.clientX)));
372
+ });
373
+ hit.addEventListener("pointerleave", () => { if (dragStart == null) hideAt(); });
374
+ if (options.zoom) {
375
+ hit.addEventListener("pointerdown", event => {
376
+ if (event.button != null && event.button !== 0) return;
377
+ dragStart = event.clientX;
378
+ try { hit.setPointerCapture(event.pointerId); } catch { /* the pointer is gone */ }
379
+ });
380
+ const finish = event => {
381
+ if (dragStart == null) return;
382
+ const from = toPosition(Math.min(dragStart, event.clientX));
383
+ const to = toPosition(Math.max(dragStart, event.clientX));
384
+ const moved = Math.abs(event.clientX - dragStart);
385
+ dragStart = null;
386
+ selection.setAttribute("display", "none");
387
+ if (moved > 6 && ctx.hooks?.zoom) ctx.hooks.zoom({ from, to });
388
+ };
389
+ hit.addEventListener("pointerup", finish);
390
+ hit.addEventListener("pointercancel", () => { dragStart = null; selection.setAttribute("display", "none"); });
391
+ hit.addEventListener("dblclick", () => ctx.hooks?.zoom(null));
392
+ hit.setAttribute("tabindex", "0");
393
+ hit.setAttribute("role", "application");
394
+ hit.setAttribute("aria-label", translate("chart.zoomHint"));
395
+ hit.addEventListener("keydown", event => {
396
+ const span = view.to - view.from;
397
+ const mid = (view.from + view.to) / 2;
398
+ let next;
399
+ if (event.key === "+" || event.key === "=") next = { from: mid - span / 4, to: mid + span / 4 };
400
+ else if (event.key === "-" || event.key === "_") next = { from: mid - span, to: mid + span };
401
+ else if (event.altKey) return; // Alt + arrows read the values (below)
402
+ else if (event.key === "ArrowLeft") next = { from: view.from - span / 4, to: view.to - span / 4 };
403
+ else if (event.key === "ArrowRight") next = { from: view.from + span / 4, to: view.to + span / 4 };
404
+ else if (event.key === "0" || event.key === "Escape") next = null;
405
+ else return;
406
+ event.preventDefault();
407
+ ctx.hooks?.zoom(next);
408
+ });
409
+ if (zoom) {
410
+ const reset = svgEl("g", { class: "chart-reset", role: "button", tabindex: 0, "aria-label": translate("chart.resetZoom") });
411
+ reset.append(svgEl("text", { x: width - MARGIN.right, y: 24, "text-anchor": "end", class: "chart-legend" }, `↺ ${translate("chart.resetZoom")}`));
412
+ reset.addEventListener("click", () => ctx.hooks?.zoom(null));
413
+ reset.addEventListener("keydown", event => {
414
+ if (event.key === "Enter" || event.key === " ") {
415
+ event.preventDefault();
416
+ ctx.hooks?.zoom(null);
417
+ }
418
+ });
419
+ svg.append(reset);
420
+ }
421
+ }
422
+ // Reading the values with the keyboard: the arrow keys move the tooltip from point to point (with `zoom` the arrows pan, so Alt + arrow reads),
423
+ // Home and End go to the first and the last point, Escape hides the tooltip
424
+ if (!options.zoom) {
425
+ hit.setAttribute("tabindex", "0");
426
+ hit.setAttribute("role", "application");
427
+ hit.setAttribute("aria-label", translate("chart.readHint"));
428
+ }
429
+ let reading = null;
430
+ const readable = () => {
431
+ const byPosition = new Map();
432
+ series.forEach((s, si) => visible[si].forEach(i => { if (!byPosition.has(position(i))) byPosition.set(position(i), i); }));
433
+ return [...byPosition].sort((a, b) => a[0] - b[0]).map(entry => entry[1]);
434
+ };
435
+ hit.addEventListener("keydown", event => {
436
+ if (options.zoom && !event.altKey && event.key !== "Home" && event.key !== "End") return;
437
+ const all = readable();
438
+ if (!all.length) return;
439
+ let at = reading == null ? -1 : all.indexOf(reading);
440
+ if (event.key === "ArrowRight") at = at < 0 ? 0 : Math.min(at + 1, all.length - 1);
441
+ else if (event.key === "ArrowLeft") at = at < 0 ? all.length - 1 : Math.max(at - 1, 0);
442
+ else if (event.key === "Home") at = 0;
443
+ else if (event.key === "End") at = all.length - 1;
444
+ else if (event.key === "Escape" && !options.zoom) {
445
+ reading = null;
446
+ hideAt();
447
+ return;
448
+ } else return;
449
+ event.preventDefault();
450
+ reading = all[at];
451
+ showAt(reading);
452
+ });
453
+ hit.addEventListener("blur", () => { reading = null; hideAt(); });
454
+ svg.append(marker, selection, hit);
455
+ }
456
+
457
+ // A small line without axes, legend or title: for a table cell or a stat tile. Its tooltips still work.
458
+ function drawSparkline(svg, ctx) {
459
+ const { series, width, height, format } = ctx;
460
+ const s = series[0];
461
+ const values = s.data.filter(Number.isFinite);
462
+ const min = Math.min(...values);
463
+ const max = Math.max(...values);
464
+ const pad = 3;
465
+ const x = i => pad + (s.data.length === 1 ? (width - 2 * pad) / 2 : (i / (s.data.length - 1)) * (width - 2 * pad));
466
+ const y = v => height - pad - (max === min ? (height - 2 * pad) / 2 : ((v - min) / (max - min)) * (height - 2 * pad));
467
+ const points = s.data.map((v, i) => [x(i), y(v)]).filter((_, i) => Number.isFinite(s.data[i]));
468
+ const group = svgEl("g", { "data-series": 0, ...seriesProps(s, 0) });
469
+ group.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none" }));
470
+ const last = points.at(-1);
471
+ if (last) {
472
+ const dot = svgEl("circle", { cx: last[0], cy: last[1], r: 2.5, class: "chart-point" });
473
+ addTip(ctx, dot, last[0], last[1], [format(values.at(-1))]);
474
+ group.append(dot);
475
+ }
476
+ svg.append(group);
477
+ }
478
+
479
+ function drawPie(svg, ctx) {
480
+ const { labels, series, width, height, donut, format } = ctx;
481
+ const MARGIN = ctx.margin;
482
+ const data = series[0].data.map(v => Math.max(0, v));
483
+ const total = data.reduce((a, b) => a + b, 0);
484
+ const cx = width / 2;
485
+ const cy = MARGIN.top + (height - MARGIN.top - MARGIN.bottom) / 2;
486
+ const r = Math.min(width - MARGIN.left - MARGIN.right, height - MARGIN.top - MARGIN.bottom) / 2;
487
+ const inner = donut ? r * 0.55 : 0;
488
+ const point = (radius, angle) => [cx + radius * Math.cos(angle), cy + radius * Math.sin(angle)].join(",");
489
+ let start = -Math.PI / 2;
490
+ data.forEach((value, i) => {
491
+ if (!total || !value) return;
492
+ const sweep = (value / total) * Math.PI * 2;
493
+ let slice;
494
+ if (sweep >= Math.PI * 2 - 1e-6) {
495
+ // A single full slice cannot be drawn as an arc.
496
+ slice = donut
497
+ ? svgEl("circle", { cx, cy, r: (r + inner) / 2, fill: "none", "stroke-width": r - inner, class: "chart-ring" })
498
+ : svgEl("circle", { cx, cy, r });
499
+ } else {
500
+ const end = start + sweep;
501
+ const large = sweep > Math.PI ? 1 : 0;
502
+ const d = donut
503
+ ? `M${point(r, start)} A${r},${r} 0 ${large} 1 ${point(r, end)} L${point(inner, end)} A${inner},${inner} 0 ${large} 0 ${point(inner, start)} Z`
504
+ : `M${cx},${cy} L${point(r, start)} A${r},${r} 0 ${large} 1 ${point(r, end)} Z`;
505
+ slice = svgEl("path", { d });
506
+ }
507
+ slice.setAttribute("class", `chart-slice ${slice.getAttribute("class") ?? ""} ${seriesClass(i)}`.replace(/\s+/g, " ").trim());
508
+ slice.setAttribute("data-series", i);
509
+ const mid = start + sweep / 2;
510
+ const [tx, ty] = point(r * (donut ? (1 + 0.55) / 2 : 0.6), mid).split(",").map(Number);
511
+ addTip(ctx, slice, tx, ty, [labels[i] ?? "", `${format(value)} (${Math.round(value / total * 100)}%)`]);
512
+ svg.append(slice);
513
+ start += sweep;
514
+ });
515
+ // The legend of a pie lists the slices, not the series.
516
+ return labels.map((name, i) => ({ name, props: { class: seriesClass(i) }, series: i }));
517
+ }
518
+
519
+ const DRAWERS = {
520
+ bar: drawBar,
521
+ line: drawLine,
522
+ area: (svg, ctx) => drawLine(svg, { ...ctx, area: true }),
523
+ sparkline: drawSparkline,
524
+ pie: drawPie,
525
+ donut: (svg, ctx) => drawPie(svg, { ...ctx, donut: true })
526
+ };
527
+
528
+ /* ------------------TABLE OF VALUES------------------- */
529
+
530
+ // The same numbers as a table, for screen readers and for people who want to read them off or copy them.
531
+ function buildDataTable({ labels, series, times, title, type, format = formatNumber, formatTime }) {
532
+ const details = document.createElement("details");
533
+ details.className = "chart-data";
534
+ const summary = document.createElement("summary");
535
+ summary.textContent = translate("showAsTable");
536
+ const table = document.createElement("table");
537
+ table.className = "athena-table chart-data-table";
538
+ if (title) table.createCaption().textContent = title;
539
+ const headRow = table.createTHead().insertRow();
540
+ const names = type === "pie" || type === "donut" ? [series[0].name ?? ""] : series.map((s, i) => s.name ?? `${translate("series")} ${i + 1}`);
541
+ ["", ...names].forEach((name, i) => {
542
+ const th = document.createElement("th");
543
+ th.scope = "col";
544
+ th.textContent = i ? name : (times ? translate("time") : "");
545
+ headRow.append(th);
546
+ });
547
+ const body = table.createTBody();
548
+ const shown = type === "pie" || type === "donut" ? [series[0]] : series;
549
+ const count = Math.max(...shown.map(s => s.data.length));
550
+ const when = times ? { format: formatTime } : null;
551
+ for (let i = 0; i < count; i++) {
552
+ const row = body.insertRow();
553
+ const head = document.createElement("th");
554
+ head.scope = "row";
555
+ head.textContent = times ? when.format(times[i]) : (labels[i] ?? "");
556
+ row.append(head);
557
+ for (const s of shown) row.insertCell().textContent = s.data[i] == null ? "" : format(s.data[i]);
558
+ }
559
+ details.append(summary, table);
560
+ return details;
561
+ }
562
+
563
+ /**
564
+ * Draws a chart as inline SVG and appends it to its parent.
565
+ *
566
+ * @param {object} options
567
+ * @param {"bar"|"line"|"area"|"sparkline"|"pie"|"donut"} [options.type="bar"]
568
+ * @param {string|Element} [options.parent] element, id or selector, defaults to "wrapper"
569
+ * @param {string} [options.id] id of the svg element
570
+ * @param {string} [options.title] drawn above the chart, and its accessible name
571
+ * @param {string[]} [options.labels] category labels
572
+ * @param {(number|Date|string)[]} [options.times] line and area charts: the time of every value (Date, ms or a date string).
573
+ * The x axis becomes a time axis with ticks at round times, and the points sit at their real distance.
574
+ * @param {{name?: string, data: number[], color?: string}[]} options.series pie / donut / sparkline use the first series only.
575
+ * Colours come from the theme (--series-1 ... --series-8); `color` is an override for one series.
576
+ * @param {number} [options.width=600] (a sparkline: 120)
577
+ * @param {number} [options.height=360] (a sparkline: 32)
578
+ * @param {boolean} [options.legend] default: shown for several series, and for pie / donut. Clicking an entry hides / shows its series.
579
+ * @param {boolean} [options.table=false] adds a "Show as table" section with the values below the chart
580
+ * @param {boolean} [options.zero=true] line charts: false lets the value axis start near the smallest value
581
+ * @param {boolean} [options.zoom=false] line and area charts: drag over the plot to zoom into that range, double click (or the
582
+ * reset button, or 0 / Esc) to zoom out; with the keyboard on the plot: + and - zoom, the arrow keys pan.
583
+ * Without `zoom` the arrow keys on the plot read the values from point to point (Home and End: first and last, Esc: hide); with `zoom` that is Alt + arrow
584
+ * @param {{from: number, to: number}|null} [options.zoomRange] the range in view, in the units of the x axis: milliseconds with
585
+ * `times`, otherwise the index of the point (-0.5 is the left edge of the first point)
586
+ * @param {(range: ({from: number, to: number}|null)) => void} [options.onZoom] called when a person zooms or resets
587
+ * @param {number} [options.maxPoints] `push` keeps at most this many points per series (the oldest are dropped)
588
+ * @param {number[]} [options.hiddenSeries] the series (or slices) that are hidden at the start; a person hides and shows them with the legend, and a redraw keeps that
589
+ * @param {boolean} [options.animate=true] the first drawing animates: bars grow, a line is drawn, slices pop in (not when it is redrawn, and not under reduced motion)
590
+ * @param {boolean} [options.interactive=true] line and area charts: false leaves out the pointer layer (tooltip that follows the pointer, zoom)
591
+ * @param {boolean} [options.gaps=false] line and area charts: a missing value (null, NaN, undefined) breaks the line, and a point on its own is a dot;
592
+ * without it the line goes on from the value before to the one after
593
+ * @param {{from: (number|Date|string), to: (number|Date|string)}} [options.timeRange] line and area charts with `times`: the range of the time axis, when it is not the one
594
+ * the data covers (the last hour, of which only the last quarter has been measured)
595
+ * @param {(value: number) => string} [options.format] how a value is written: on the axis, in the tooltips and in the table of values (default: whole numbers, otherwise two decimals)
596
+ * @param {((time: number) => string)|Intl.DateTimeFormatOptions} [options.timeFormat] how a time is written in the tooltips and in the table of values (`times` only): a function of the
597
+ * time in milliseconds, or the options of Intl.DateTimeFormat (default: `{ dateStyle: "medium", timeStyle: "medium" }`, for example "Nov 19, 2026, 6:15:09 PM")
598
+ * @param {boolean} [options.points=true] line and area charts: false never draws the dots, however few the points are (the tooltip still follows the pointer and the keyboard)
599
+ * @param {(value: number) => string} [options.tickFormat] how the numbers of the value axis are written, when they should not be written like the values (a chart of whole numbers has ticks of 0.2)
600
+ * @param {{top?: number, right?: number, bottom?: number, left?: number}} [options.margin] room around the plot in px (default 40, 20, 50, 55): a chart without a title and a legend does not need the top
601
+ * @param {boolean} [options.responsive=false] the chart is as wide as its parent and follows it when it changes (`height` stays); `width` is only the first guess
602
+ * @returns {(SVGElement & {element: SVGElement, update: (options?: object) => SVGElement, destroy: () => void,
603
+ * zoom: (from: number, to: number) => void, resetZoom: () => void, getZoom: () => ({from: number, to: number}|null),
604
+ * push: (point: {x?: (number|Date|string), label?: string, values: (number|number[])}, config?: {maxPoints?: number}) => void,
605
+ * dataTable: (HTMLElement|null)})|null}
606
+ * the SVG element, which also carries the handle ({ element, update(options), destroy() }) of the other
607
+ * components; null when the options are invalid. `parent` is an element, an id or a selector.
608
+ * `push` adds a point to every series (a number for the first series, or one value per series; `x` is the time with
609
+ * `times`, `label` the category) and draws the chart again at most once per frame, however often it is called.
610
+ */
611
+ export function generateChart(options = {}) {
612
+ const state = { used: { ...options, series: (options.series ?? []).map(s => ({ ...s, data: [...(s.data ?? [])] })) }, current: null, queued: false };
613
+ if (options.labels) state.used.labels = [...options.labels];
614
+ if (options.times) state.used.times = [...options.times];
615
+ const hidden = new Set(options.hiddenSeries ?? []);
616
+ let resizing = null;
617
+ // Only the first drawing animates (bars grow, the line is drawn, slices pop in): a redraw while streaming or zooming must not start it again
618
+ let firstDrawing = options.animate !== false;
619
+ const hooks = {
620
+ legend: (series, off) => {
621
+ if (off) hidden.add(series);
622
+ else hidden.delete(series);
623
+ state.used.hiddenSeries = [...hidden];
624
+ },
625
+ zoom: range => {
626
+ state.used = { ...state.used, zoomRange: range ?? null };
627
+ handle.redraw();
628
+ options.onZoom?.(range ?? null);
629
+ }
630
+ };
631
+ const handle = {
632
+ element: () => state.current.svg,
633
+ redraw() {
634
+ const next = buildChart(state.used, hooks, { animate: false });
635
+ if (!next) return state.current?.svg;
636
+ // A redraw replaces the whole SVG (every second while streaming, and when someone zooms). The keyboard focus would be lost
637
+ // with it, so it goes to the same place in the new one: the same legend entry, the same point, or the plot.
638
+ const old = state.current?.svg;
639
+ const active = old && old.contains(document.activeElement) ? document.activeElement : null;
640
+ const focusables = active ? [...old.querySelectorAll("[tabindex]")] : [];
641
+ const position = active ? focusables.indexOf(active) : -1;
642
+ if (state.current) {
643
+ old.replaceWith(next.svg);
644
+ state.current.table?.remove();
645
+ if (next.table) next.svg.after(next.table);
646
+ }
647
+ state.current = next;
648
+ if (active) {
649
+ const now = [...next.svg.querySelectorAll("[tabindex]")];
650
+ (active.classList.contains("chart-hit") || active.classList.contains("chart-reset") ? next.svg.querySelector(".chart-hit") : now[position] ?? next.svg.querySelector(".chart-hit"))?.focus({ preventScroll: true });
651
+ }
652
+ return attach(next.svg);
653
+ },
654
+ update(changes = {}) {
655
+ state.used = { ...state.used, ...changes };
656
+ return handle.redraw();
657
+ },
658
+ destroy() {
659
+ resizing?.disconnect();
660
+ state.current.svg.remove();
661
+ state.current.table?.remove();
662
+ },
663
+ zoom: (from, to) => hooks.zoom({ from, to }),
664
+ resetZoom: () => hooks.zoom(null),
665
+ getZoom: () => state.used.zoomRange ?? null,
666
+ push(point, config = {}) {
667
+ const used = state.used;
668
+ const values = Array.isArray(point.values) ? point.values : [point.values];
669
+ used.series.forEach((s, i) => s.data.push(values[i] ?? NaN));
670
+ if (used.times) used.times.push(toTime(point.x ?? Date.now()));
671
+ else if (used.labels) used.labels.push(String(point.label ?? used.labels.length + 1));
672
+ const limit = config.maxPoints ?? used.maxPoints;
673
+ const extra = limit ? used.series[0].data.length - limit : 0;
674
+ if (extra > 0) {
675
+ for (const s of used.series) s.data.splice(0, extra);
676
+ used.times?.splice(0, extra);
677
+ used.labels?.splice(0, extra);
678
+ }
679
+ if (state.queued) return;
680
+ state.queued = true;
681
+ // Once per frame (the timer is for pages where frames are paused or late)
682
+ let timer = 0;
683
+ const run = () => {
684
+ if (!state.queued) return;
685
+ state.queued = false;
686
+ clearTimeout(timer);
687
+ handle.redraw();
688
+ };
689
+ requestAnimationFrame(run);
690
+ timer = setTimeout(run, 100);
691
+ }
692
+ };
693
+ const attach = svg => Object.defineProperties(svg, {
694
+ element: { get: () => state.current.svg, configurable: true },
695
+ update: { value: handle.update, configurable: true },
696
+ destroy: { value: handle.destroy, configurable: true },
697
+ zoom: { value: handle.zoom, configurable: true },
698
+ resetZoom: { value: handle.resetZoom, configurable: true },
699
+ getZoom: { value: handle.getZoom, configurable: true },
700
+ push: { value: handle.push, configurable: true },
701
+ dataTable: { get: () => state.current.table ?? null, configurable: true }
702
+ });
703
+
704
+ const host = resolveElement(options.parent ?? "wrapper") ?? document.body;
705
+ if (options.responsive && host.clientWidth >= 120) state.used.width = Math.floor(host.clientWidth);
706
+ const built = buildChart(state.used, hooks, { animate: firstDrawing });
707
+ firstDrawing = false;
708
+ if (!built) return null;
709
+ state.current = built;
710
+ host.append(built.svg);
711
+ if (built.table) built.svg.after(built.table);
712
+ if (options.responsive && typeof ResizeObserver === "function") {
713
+ // The chart is as wide as its parent (the height stays): redrawn once per frame when the parent changes its width
714
+ let frame = 0;
715
+ resizing = new ResizeObserver(() => {
716
+ cancelAnimationFrame(frame);
717
+ frame = requestAnimationFrame(() => {
718
+ const width = Math.floor(host.clientWidth);
719
+ if (width >= 120 && width !== state.used.width) handle.update({ width });
720
+ });
721
+ });
722
+ resizing.observe(host);
723
+ }
724
+ return attach(built.svg);
725
+ }
726
+
727
+ function buildChart(options = {}, hooks, { animate = false } = {}) {
728
+ const { type = "bar", id, title } = options;
729
+ const sparkline = type === "sparkline";
730
+ const width = options.width ?? (sparkline ? 120 : 600);
731
+ const height = options.height ?? (sparkline ? 32 : 360);
732
+ const draw = DRAWERS[type];
733
+ const series = (options.series ?? []).filter(s => Array.isArray(s?.data) && s.data.length);
734
+ if (!draw || !series.length) {
735
+ console.error("Athena UI: generateChart needs a valid type and at least one series with data", options);
736
+ return null;
737
+ }
738
+ const labels = (options.labels ?? []).map(String);
739
+ const count = Math.max(...series.map(s => s.data.length));
740
+ while (labels.length < count) labels.push(String(labels.length + 1));
741
+ const times = options.times && (type === "line" || type === "area") ? options.times.map(toTime) : null;
742
+ if (times && (times.length < count || times.some(Number.isNaN))) {
743
+ console.error("Athena UI: generateChart `times` needs a valid time for every value", options);
744
+ return null;
745
+ }
746
+
747
+ const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class: `athena-chart athena-chart-${type}${animate && type !== "sparkline" ? " athena-chart-animated" : ""}`, role: "img" });
748
+ if (id) svg.id = id;
749
+ const summary = `${title ?? translate(`chart.${type}`)}: ${series.map(s => s.name ?? "").filter(Boolean).join(", ")}`.replace(/: $/, "");
750
+ svg.setAttribute("aria-label", options.ariaLabel ?? summary);
751
+ if (title && !sparkline) svg.append(svgEl("text", { x: width / 2, y: 24, "text-anchor": "middle", class: "chart-title" }, title));
752
+
753
+ // The tooltip is created first, so the shapes can use it, and moved to the end afterwards, so it is drawn on top.
754
+ const tooltip = createTooltip(svg, width);
755
+ const margin = { ...DEFAULT_MARGIN, ...(options.margin ?? {}) };
756
+ const format = typeof options.format === "function" ? options.format : formatNumber;
757
+ const tickFormat = typeof options.tickFormat === "function" ? options.tickFormat : format;
758
+ const formatTime = makeTimeFormatter(options.timeFormat);
759
+ const ctx = { labels, series, width, height, times, options, tooltip, hooks, zoom: options.zoomRange ?? null, margin, format, tickFormat, formatTime };
760
+ const pieLegend = draw(svg, ctx);
761
+ if (!sparkline && (options.legend ?? (Boolean(pieLegend) || series.length > 1))) {
762
+ addLegend(svg, pieLegend ?? series.map((s, i) => ({ name: s.name ?? `${translate("series")} ${i + 1}`, props: seriesProps(s, i), series: i })), width, height, ctx);
763
+ }
764
+ svg.append(tooltip.group);
765
+ for (const index of options.hiddenSeries ?? []) {
766
+ for (const node of svg.querySelectorAll(`[data-series="${index}"]`)) node.classList.add("chart-hidden");
767
+ const entry = svg.querySelector(`.chart-legend-item[data-legend="${index}"]`);
768
+ entry?.setAttribute("aria-pressed", "false");
769
+ entry?.classList.add("is-off");
770
+ }
771
+ return { svg, table: options.table ? buildDataTable({ labels, series, times, title, type, format, formatTime }) : null };
772
+ }