athena-ui-js 1.1.0 → 1.3.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.
- package/README.md +273 -23
- package/package.json +11 -7
- package/src/athena-ui.js +33 -10
- package/src/libs/config/config.js +8 -1
- package/src/libs/core/combobox.js +1 -1
- package/src/libs/core/controls.js +153 -0
- package/src/libs/core/dateRange.js +121 -0
- package/src/libs/core/dom.js +88 -11
- package/src/libs/{hephaestus/HTMLElementGenerator/src/HTMLElementGenerator.js → core/elementGenerator.js} +23 -21
- package/src/libs/{hephaestus/HTMLElementGenerator/src → core}/errors.js +7 -5
- package/src/libs/core/format.js +51 -0
- package/src/libs/core/hungarianControls.js +41 -0
- package/src/libs/core/i18n.js +64 -0
- package/src/libs/core/theme.js +131 -0
- package/src/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.js +4 -6
- package/src/libs/hephaestus/LayoutGenerator/footerContentGenerator.js +2 -4
- package/src/libs/hephaestus/LayoutGenerator/headerContentGenerator.js +12 -5
- package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +3 -3
- package/src/libs/hephaestus/MenuGenerator/menuGenerator.js +253 -0
- package/src/libs/hephaestus/auth/authState.js +58 -0
- package/src/libs/hephaestus/chartGenerator/chartGenerator.js +530 -65
- package/src/libs/hephaestus/componentGenerator/componentGenerator.js +124 -6
- package/src/libs/hephaestus/componentGenerator/themePicker.js +73 -0
- package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +100 -13
- package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +23 -2
- package/src/libs/hephaestus/formGenerator/authForms.js +130 -0
- package/src/libs/hephaestus/formGenerator/formBuilder.js +5 -5
- package/src/libs/hephaestus/formGenerator/formUtils.js +10 -9
- package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +9 -9
- package/src/libs/hephaestus/hephaestus.js +7 -2
- package/src/libs/hephaestus/inputGenerator/dropZoneGenerator.js +2 -2
- package/src/libs/hephaestus/inputGenerator/inputGenerator.js +37 -8
- package/src/libs/hephaestus/inputGenerator/richTextGenerator.js +2 -2
- package/src/libs/hephaestus/modalGenerator/modalGenerator.js +17 -11
- package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +20 -11
- package/src/libs/hephaestus/router/router.js +56 -6
- package/src/libs/hephaestus/tableGenerator/tableGenerator.js +368 -29
- package/src/libs/libs.js +3 -3
- package/src/res/themes/appearance.css +154 -0
- package/src/res/themes/default/style.css +649 -2
- package/src/testing.js +71 -0
- package/src/theme-boot.js +25 -0
- package/src/libs/hephaestus/HTMLControlGenerator/LICENSE +0 -21
- package/src/libs/hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js +0 -5
- package/src/libs/hephaestus/HTMLElementGenerator/LICENSE +0 -21
|
@@ -3,11 +3,16 @@
|
|
|
3
3
|
//LICENCE: MIT
|
|
4
4
|
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
5
|
|
|
6
|
-
// Dependency free SVG charts: bar, line, pie and donut.
|
|
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";
|
|
7
11
|
|
|
8
12
|
const NS = "http://www.w3.org/2000/svg";
|
|
9
|
-
const
|
|
13
|
+
const SERIES_COLORS = 8;
|
|
10
14
|
const 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
|
|
11
16
|
|
|
12
17
|
const svgEl = (tag, attrs = {}, text) => {
|
|
13
18
|
const node = document.createElementNS(NS, tag);
|
|
@@ -16,7 +21,9 @@ const svgEl = (tag, attrs = {}, text) => {
|
|
|
16
21
|
return node;
|
|
17
22
|
};
|
|
18
23
|
|
|
19
|
-
const
|
|
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) });
|
|
20
27
|
const formatNumber = n => Number.isInteger(n) ? String(n) : String(+n.toFixed(2));
|
|
21
28
|
|
|
22
29
|
// Rounded axis maximum and tick step, so ticks land on readable numbers.
|
|
@@ -28,19 +35,131 @@ function niceScale(span, ticks = 5) {
|
|
|
28
35
|
return { span: step * Math.ceil(span / step - 1e-9), step };
|
|
29
36
|
}
|
|
30
37
|
|
|
31
|
-
|
|
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) {
|
|
32
94
|
let x = MARGIN.left;
|
|
33
95
|
const y = height - 12;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
96
|
+
entries.forEach(({ name, props, series }) => {
|
|
97
|
+
const group = svgEl("g", { class: "chart-legend-item", tabindex: 0, role: "button", "aria-pressed": "true", "aria-label": name });
|
|
98
|
+
group.append(svgEl("rect", { x, y: y - 9, width: 10, height: 10, class: `chart-swatch ${props.class ?? ""}`.trim(), ...(props.color ? { color: props.color } : {}) }));
|
|
99
|
+
group.append(svgEl("text", { x: x + 14, y, class: "chart-legend" }, name));
|
|
100
|
+
if (series != null) {
|
|
101
|
+
const toggle = () => {
|
|
102
|
+
const hidden = group.getAttribute("aria-pressed") === "true";
|
|
103
|
+
group.setAttribute("aria-pressed", hidden ? "false" : "true");
|
|
104
|
+
group.classList.toggle("is-off", hidden);
|
|
105
|
+
for (const node of svg.querySelectorAll(`[data-series="${series}"]`)) node.classList.toggle("chart-hidden", hidden);
|
|
106
|
+
ctx.tooltip.hide();
|
|
107
|
+
};
|
|
108
|
+
group.addEventListener("click", toggle);
|
|
109
|
+
group.addEventListener("keydown", event => {
|
|
110
|
+
if (event.key === "Enter" || event.key === " ") {
|
|
111
|
+
event.preventDefault();
|
|
112
|
+
toggle();
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
svg.append(group);
|
|
37
117
|
x += 14 + name.length * 7 + 14;
|
|
38
|
-
|
|
39
|
-
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// One tooltip per chart, drawn inside the SVG and moved with attributes (no inline style). Shows on hover and on keyboard focus.
|
|
122
|
+
function createTooltip(svg, width) {
|
|
123
|
+
const group = svgEl("g", { class: "chart-tooltip", "aria-hidden": "true" });
|
|
124
|
+
const box = svgEl("rect", { class: "chart-tooltip-box", rx: 4 });
|
|
125
|
+
const text = svgEl("text", { class: "chart-tooltip-text" });
|
|
126
|
+
group.append(box, text);
|
|
127
|
+
const show = (x, y, lines) => {
|
|
128
|
+
text.replaceChildren(...lines.map((line, i) => svgEl("tspan", { x: 8, dy: i ? 15 : 0 }, line)));
|
|
129
|
+
group.classList.add("is-visible");
|
|
130
|
+
let w = 80;
|
|
131
|
+
let h = lines.length * 15 + 8;
|
|
132
|
+
try {
|
|
133
|
+
const bbox = text.getBBox();
|
|
134
|
+
w = bbox.width + 16;
|
|
135
|
+
h = bbox.height + 10;
|
|
136
|
+
} catch { /* not rendered: the estimate stays */ }
|
|
137
|
+
text.setAttribute("y", 15);
|
|
138
|
+
const left = Math.min(Math.max(x - w / 2, 2), Math.max(width - w - 2, 2));
|
|
139
|
+
const top = Math.max(y - h - 10, 2);
|
|
140
|
+
box.setAttribute("width", w);
|
|
141
|
+
box.setAttribute("height", h);
|
|
142
|
+
group.setAttribute("transform", `translate(${left} ${top})`);
|
|
143
|
+
};
|
|
144
|
+
const hide = () => group.classList.remove("is-visible");
|
|
145
|
+
svg.append(group);
|
|
146
|
+
return { show, hide, group };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 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.
|
|
150
|
+
function addTip(ctx, node, x, y, lines) {
|
|
151
|
+
node.setAttribute("tabindex", "0");
|
|
152
|
+
node.setAttribute("aria-label", lines.join(", "));
|
|
153
|
+
node.setAttribute("role", "img");
|
|
154
|
+
const show = () => ctx.tooltip.show(x, y, lines);
|
|
155
|
+
node.addEventListener("pointerenter", show);
|
|
156
|
+
node.addEventListener("focus", show);
|
|
157
|
+
node.addEventListener("pointerleave", ctx.tooltip.hide);
|
|
158
|
+
node.addEventListener("blur", ctx.tooltip.hide);
|
|
40
159
|
}
|
|
41
160
|
|
|
42
|
-
// Draws grid
|
|
43
|
-
function
|
|
161
|
+
// Draws the value grid and the y axis for the range [min, min + scale.span].
|
|
162
|
+
function addValueAxis(svg, { min, scale, width, height }) {
|
|
44
163
|
const plotW = width - MARGIN.left - MARGIN.right;
|
|
45
164
|
const plotH = height - MARGIN.top - MARGIN.bottom;
|
|
46
165
|
const y = value => MARGIN.top + plotH - ((value - min) / scale.span) * plotH;
|
|
@@ -50,26 +169,32 @@ function addAxes(svg, { labels, min, scale, width, height }) {
|
|
|
50
169
|
svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: y(v), y2: y(v), class: "chart-grid" }));
|
|
51
170
|
svg.append(svgEl("text", { x: MARGIN.left - 8, y: y(v) + 4, "text-anchor": "end", class: "chart-tick" }, formatNumber(v)));
|
|
52
171
|
}
|
|
53
|
-
const band = plotW / Math.max(labels.length, 1);
|
|
54
|
-
labels.forEach((label, i) => svg.append(svgEl("text",
|
|
55
|
-
{ x: MARGIN.left + band * (i + 0.5), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, label)));
|
|
56
172
|
svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left, y1: MARGIN.top, y2: MARGIN.top + plotH, class: "chart-axis" }));
|
|
57
173
|
// The category axis sits at zero when the range includes it, so negative bars hang below it.
|
|
58
174
|
const baseline = y(Math.min(Math.max(0, min), min + scale.span));
|
|
59
175
|
svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: baseline, y2: baseline, class: "chart-axis" }));
|
|
60
|
-
return {
|
|
176
|
+
return { y, baseline, plotW, plotH };
|
|
61
177
|
}
|
|
62
178
|
|
|
63
|
-
function valueRange(
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
179
|
+
function valueRange(values, zero = true) {
|
|
180
|
+
const finite = values.filter(Number.isFinite);
|
|
181
|
+
if (!finite.length) return { min: 0, scale: niceScale(1) };
|
|
182
|
+
let min = zero ? Math.min(0, ...finite) : Math.min(...finite);
|
|
183
|
+
const max = Math.max(zero ? 0 : -Infinity, ...finite);
|
|
184
|
+
const scale = niceScale(max - min);
|
|
185
|
+
if (!zero) min = Math.floor(min / scale.step) * scale.step; // start the axis at a round number
|
|
186
|
+
return { min, scale: niceScale(max - min) };
|
|
68
187
|
}
|
|
69
188
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
189
|
+
/* ------------------DRAWERS------------------- */
|
|
190
|
+
|
|
191
|
+
function drawBar(svg, ctx) {
|
|
192
|
+
const { labels, series, width, height } = ctx;
|
|
193
|
+
const { min, scale } = valueRange(series.flatMap(s => s.data));
|
|
194
|
+
const { y, plotW, plotH } = addValueAxis(svg, { min, scale, width, height });
|
|
195
|
+
const band = plotW / Math.max(labels.length, 1);
|
|
196
|
+
labels.forEach((label, i) => svg.append(svgEl("text",
|
|
197
|
+
{ x: MARGIN.left + band * (i + 0.5), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, label)));
|
|
73
198
|
const groupWidth = band * 0.8;
|
|
74
199
|
const barWidth = groupWidth / series.length;
|
|
75
200
|
series.forEach((s, si) => s.data.forEach((value, i) => {
|
|
@@ -77,31 +202,221 @@ function drawBar(svg, { labels, series, width, height }) {
|
|
|
77
202
|
const top = Math.min(y(value), y(0));
|
|
78
203
|
const bar = svgEl("rect", {
|
|
79
204
|
x, y: top, width: Math.max(barWidth - 2, 1), height: Math.abs(y(0) - y(value)),
|
|
80
|
-
|
|
205
|
+
"data-series": si, ...seriesProps(s, si)
|
|
81
206
|
});
|
|
82
|
-
bar.
|
|
207
|
+
bar.setAttribute("class", `chart-bar ${bar.getAttribute("class") ?? ""}`.trim());
|
|
208
|
+
addTip(ctx, bar, x + barWidth / 2, top, [`${s.name ?? ""} ${labels[i] ?? ""}`.trim(), formatNumber(value)]);
|
|
83
209
|
svg.append(bar);
|
|
84
210
|
}));
|
|
85
211
|
}
|
|
86
212
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const {
|
|
213
|
+
// 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).
|
|
214
|
+
function drawLine(svg, ctx) {
|
|
215
|
+
const { labels, series, width, height, times, area, options, zoom } = ctx;
|
|
216
|
+
const plotW = width - MARGIN.left - MARGIN.right;
|
|
217
|
+
const plotH = height - MARGIN.top - MARGIN.bottom;
|
|
218
|
+
const count = Math.max(...series.map(s => s.data.length));
|
|
219
|
+
const position = i => (times ? times[i] : i); // x position of point i in the units of the axis
|
|
220
|
+
const full = times ? { from: Math.min(...times.slice(0, count)), to: Math.max(...times.slice(0, count)) } : { from: -0.5, to: count - 0.5 };
|
|
221
|
+
const view = zoom ? { from: Math.max(zoom.from, full.from), to: Math.min(zoom.to, full.to) } : full;
|
|
222
|
+
if (!(view.to > view.from)) Object.assign(view, full);
|
|
223
|
+
const x = p => MARGIN.left + ((p - view.from) / (view.to - view.from || 1)) * plotW;
|
|
224
|
+
|
|
225
|
+
// The points in view, plus one on each side so the line leaves the plot
|
|
226
|
+
const visible = series.map(s => {
|
|
227
|
+
const inside = [];
|
|
228
|
+
for (let i = 0; i < s.data.length; i++) {
|
|
229
|
+
const p = position(i);
|
|
230
|
+
if (p >= view.from && p <= view.to && Number.isFinite(s.data[i])) inside.push(i);
|
|
231
|
+
}
|
|
232
|
+
return inside;
|
|
233
|
+
});
|
|
234
|
+
const zeroBased = area || options.zero !== false;
|
|
235
|
+
const { min, scale } = valueRange(series.flatMap((s, si) => visible[si].map(i => s.data[i])), zeroBased);
|
|
236
|
+
const { y, baseline } = addValueAxis(svg, { min, scale, width, height });
|
|
237
|
+
|
|
238
|
+
// x axis
|
|
239
|
+
if (times) {
|
|
240
|
+
const { ticks: stops, step } = timeTicks(view.from, view.to);
|
|
241
|
+
const format = timeFormatter(step);
|
|
242
|
+
for (const t of stops) {
|
|
243
|
+
svg.append(svgEl("line", { x1: x(t), x2: x(t), y1: MARGIN.top + plotH, y2: MARGIN.top + plotH + 4, class: "chart-axis" }));
|
|
244
|
+
svg.append(svgEl("text", { x: x(t), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, format(t)));
|
|
245
|
+
}
|
|
246
|
+
} else {
|
|
247
|
+
const first = Math.max(Math.ceil(view.from + 0.5), 0);
|
|
248
|
+
const last = Math.min(Math.floor(view.to - 0.5), count - 1);
|
|
249
|
+
const every = Math.max(1, Math.ceil((last - first + 1) / Math.max(Math.floor(plotW / 60), 1)));
|
|
250
|
+
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] ?? ""));
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const clipId = uid("chart-clip");
|
|
254
|
+
const clip = svgEl("clipPath", { id: clipId });
|
|
255
|
+
clip.append(svgEl("rect", { x: MARGIN.left, y: MARGIN.top - 4, width: plotW, height: plotH + 8 }));
|
|
256
|
+
svg.append(clip);
|
|
257
|
+
const timeFormat = times ? new Intl.DateTimeFormat(getLocale(), { dateStyle: "medium", timeStyle: "medium" }) : null;
|
|
258
|
+
const when = i => (times ? timeFormat.format(times[i]) : (labels[i] ?? ""));
|
|
259
|
+
const dotted = Math.max(...visible.map(v => v.length)) <= DOT_LIMIT;
|
|
260
|
+
|
|
90
261
|
series.forEach((s, si) => {
|
|
91
|
-
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
262
|
+
// Neighbours outside the view keep the line running to the edge of the plot
|
|
263
|
+
const inside = visible[si];
|
|
264
|
+
const lo = inside.length ? inside[0] : 0;
|
|
265
|
+
const hi = inside.length ? inside.at(-1) : -1;
|
|
266
|
+
const around = [];
|
|
267
|
+
for (let i = Math.max(lo - 1, 0); i <= Math.min(hi + 1, s.data.length - 1); i++) if (Number.isFinite(s.data[i])) around.push(i);
|
|
268
|
+
const drawn = decimate(around, s.data, Math.floor(plotW));
|
|
269
|
+
const points = drawn.map(i => [x(position(i)), y(s.data[i])]);
|
|
270
|
+
const group = svgEl("g", { "data-series": si, ...seriesProps(s, si) });
|
|
271
|
+
const clipped = svgEl("g", { "clip-path": `url(#${clipId})` });
|
|
272
|
+
if (area && points.length) {
|
|
273
|
+
const outline = [`M${points[0][0]},${baseline}`, ...points.map(p => `L${p.join(",")}`), `L${points.at(-1)[0]},${baseline}`, "Z"];
|
|
274
|
+
clipped.append(svgEl("path", { d: outline.join(" "), class: "chart-area" }));
|
|
275
|
+
}
|
|
276
|
+
clipped.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none" }));
|
|
277
|
+
group.append(clipped);
|
|
278
|
+
if (dotted) {
|
|
279
|
+
for (const i of inside) {
|
|
280
|
+
const dot = svgEl("circle", { cx: x(position(i)), cy: y(s.data[i]), r: 4, class: "chart-point" });
|
|
281
|
+
addTip(ctx, dot, x(position(i)), y(s.data[i]), [`${s.name ?? ""} ${when(i)}`.trim(), formatNumber(s.data[i])]);
|
|
282
|
+
group.append(dot);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
svg.append(group);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
if (options.interactive === false) return;
|
|
289
|
+
|
|
290
|
+
// 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.
|
|
291
|
+
const hit = svgEl("rect", { class: "chart-hit", x: MARGIN.left, y: MARGIN.top, width: plotW, height: plotH, fill: "transparent" });
|
|
292
|
+
const marker = svgEl("line", { class: "chart-marker", y1: MARGIN.top, y2: MARGIN.top + plotH, display: "none" });
|
|
293
|
+
const selection = svgEl("rect", { class: "chart-selection", y: MARGIN.top, height: plotH, display: "none" });
|
|
294
|
+
const toPosition = clientX => {
|
|
295
|
+
const box = hit.getBoundingClientRect();
|
|
296
|
+
const scaleX = box.width ? plotW / box.width : 1;
|
|
297
|
+
return view.from + (((clientX - box.left) * scaleX) / plotW) * (view.to - view.from);
|
|
298
|
+
};
|
|
299
|
+
// The point (of the first series that has one) nearest to a position on the axis
|
|
300
|
+
const nearest = target => {
|
|
301
|
+
let best = null;
|
|
302
|
+
series.forEach((s, si) => {
|
|
303
|
+
const idx = visible[si];
|
|
304
|
+
let lowIdx = 0;
|
|
305
|
+
let highIdx = idx.length - 1;
|
|
306
|
+
while (lowIdx < highIdx) {
|
|
307
|
+
const mid = (lowIdx + highIdx) >> 1;
|
|
308
|
+
if (position(idx[mid]) < target) lowIdx = mid + 1;
|
|
309
|
+
else highIdx = mid;
|
|
310
|
+
}
|
|
311
|
+
for (const c of [idx[lowIdx - 1], idx[lowIdx]]) {
|
|
312
|
+
if (c != null && (best == null || Math.abs(position(c) - target) < Math.abs(position(best) - target))) best = c;
|
|
313
|
+
}
|
|
100
314
|
});
|
|
315
|
+
return best;
|
|
316
|
+
};
|
|
317
|
+
const showAt = index => {
|
|
318
|
+
if (index == null) return;
|
|
319
|
+
const px = x(position(index));
|
|
320
|
+
marker.setAttribute("x1", px);
|
|
321
|
+
marker.setAttribute("x2", px);
|
|
322
|
+
marker.removeAttribute("display");
|
|
323
|
+
const lines = [when(index), ...series.map(s => (Number.isFinite(s.data[index]) ? `${s.name ? `${s.name}: ` : ""}${formatNumber(s.data[index])}` : null)).filter(Boolean)];
|
|
324
|
+
const top = Math.min(...series.map(s => (Number.isFinite(s.data[index]) ? y(s.data[index]) : Infinity)));
|
|
325
|
+
ctx.tooltip.show(px, Number.isFinite(top) ? top : MARGIN.top, lines);
|
|
326
|
+
};
|
|
327
|
+
const hideAt = () => {
|
|
328
|
+
marker.setAttribute("display", "none");
|
|
329
|
+
ctx.tooltip.hide();
|
|
330
|
+
};
|
|
331
|
+
let dragStart = null;
|
|
332
|
+
hit.addEventListener("pointermove", event => {
|
|
333
|
+
if (dragStart != null) {
|
|
334
|
+
const a = Math.min(dragStart, event.clientX);
|
|
335
|
+
const b = Math.max(dragStart, event.clientX);
|
|
336
|
+
const box = hit.getBoundingClientRect();
|
|
337
|
+
const k = box.width ? plotW / box.width : 1;
|
|
338
|
+
selection.setAttribute("x", MARGIN.left + (a - box.left) * k);
|
|
339
|
+
selection.setAttribute("width", (b - a) * k);
|
|
340
|
+
selection.removeAttribute("display");
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
showAt(nearest(toPosition(event.clientX)));
|
|
101
344
|
});
|
|
345
|
+
hit.addEventListener("pointerleave", () => { if (dragStart == null) hideAt(); });
|
|
346
|
+
if (options.zoom) {
|
|
347
|
+
hit.addEventListener("pointerdown", event => {
|
|
348
|
+
if (event.button != null && event.button !== 0) return;
|
|
349
|
+
dragStart = event.clientX;
|
|
350
|
+
try { hit.setPointerCapture(event.pointerId); } catch { /* the pointer is gone */ }
|
|
351
|
+
});
|
|
352
|
+
const finish = event => {
|
|
353
|
+
if (dragStart == null) return;
|
|
354
|
+
const from = toPosition(Math.min(dragStart, event.clientX));
|
|
355
|
+
const to = toPosition(Math.max(dragStart, event.clientX));
|
|
356
|
+
const moved = Math.abs(event.clientX - dragStart);
|
|
357
|
+
dragStart = null;
|
|
358
|
+
selection.setAttribute("display", "none");
|
|
359
|
+
if (moved > 6 && ctx.hooks?.zoom) ctx.hooks.zoom({ from, to });
|
|
360
|
+
};
|
|
361
|
+
hit.addEventListener("pointerup", finish);
|
|
362
|
+
hit.addEventListener("pointercancel", () => { dragStart = null; selection.setAttribute("display", "none"); });
|
|
363
|
+
hit.addEventListener("dblclick", () => ctx.hooks?.zoom(null));
|
|
364
|
+
hit.setAttribute("tabindex", "0");
|
|
365
|
+
hit.setAttribute("role", "application");
|
|
366
|
+
hit.setAttribute("aria-label", translate("chart.zoomHint"));
|
|
367
|
+
hit.addEventListener("keydown", event => {
|
|
368
|
+
const span = view.to - view.from;
|
|
369
|
+
const mid = (view.from + view.to) / 2;
|
|
370
|
+
let next;
|
|
371
|
+
if (event.key === "+" || event.key === "=") next = { from: mid - span / 4, to: mid + span / 4 };
|
|
372
|
+
else if (event.key === "-" || event.key === "_") next = { from: mid - span, to: mid + span };
|
|
373
|
+
else if (event.key === "ArrowLeft") next = { from: view.from - span / 4, to: view.to - span / 4 };
|
|
374
|
+
else if (event.key === "ArrowRight") next = { from: view.from + span / 4, to: view.to + span / 4 };
|
|
375
|
+
else if (event.key === "0" || event.key === "Escape") next = null;
|
|
376
|
+
else return;
|
|
377
|
+
event.preventDefault();
|
|
378
|
+
ctx.hooks?.zoom(next);
|
|
379
|
+
});
|
|
380
|
+
if (zoom) {
|
|
381
|
+
const reset = svgEl("g", { class: "chart-reset", role: "button", tabindex: 0, "aria-label": translate("chart.resetZoom") });
|
|
382
|
+
reset.append(svgEl("text", { x: width - MARGIN.right, y: 24, "text-anchor": "end", class: "chart-legend" }, `↺ ${translate("chart.resetZoom")}`));
|
|
383
|
+
reset.addEventListener("click", () => ctx.hooks?.zoom(null));
|
|
384
|
+
reset.addEventListener("keydown", event => {
|
|
385
|
+
if (event.key === "Enter" || event.key === " ") {
|
|
386
|
+
event.preventDefault();
|
|
387
|
+
ctx.hooks?.zoom(null);
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
svg.append(reset);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
svg.append(marker, selection, hit);
|
|
102
394
|
}
|
|
103
395
|
|
|
104
|
-
|
|
396
|
+
// A small line without axes, legend or title: for a table cell or a stat tile. Its tooltips still work.
|
|
397
|
+
function drawSparkline(svg, ctx) {
|
|
398
|
+
const { series, width, height } = ctx;
|
|
399
|
+
const s = series[0];
|
|
400
|
+
const values = s.data.filter(Number.isFinite);
|
|
401
|
+
const min = Math.min(...values);
|
|
402
|
+
const max = Math.max(...values);
|
|
403
|
+
const pad = 3;
|
|
404
|
+
const x = i => pad + (s.data.length === 1 ? (width - 2 * pad) / 2 : (i / (s.data.length - 1)) * (width - 2 * pad));
|
|
405
|
+
const y = v => height - pad - (max === min ? (height - 2 * pad) / 2 : ((v - min) / (max - min)) * (height - 2 * pad));
|
|
406
|
+
const points = s.data.map((v, i) => [x(i), y(v)]).filter((_, i) => Number.isFinite(s.data[i]));
|
|
407
|
+
const group = svgEl("g", { "data-series": 0, ...seriesProps(s, 0) });
|
|
408
|
+
group.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none" }));
|
|
409
|
+
const last = points.at(-1);
|
|
410
|
+
if (last) {
|
|
411
|
+
const dot = svgEl("circle", { cx: last[0], cy: last[1], r: 2.5, class: "chart-point" });
|
|
412
|
+
addTip(ctx, dot, last[0], last[1], [formatNumber(values.at(-1))]);
|
|
413
|
+
group.append(dot);
|
|
414
|
+
}
|
|
415
|
+
svg.append(group);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function drawPie(svg, ctx) {
|
|
419
|
+
const { labels, series, width, height, donut } = ctx;
|
|
105
420
|
const data = series[0].data.map(v => Math.max(0, v));
|
|
106
421
|
const total = data.reduce((a, b) => a + b, 0);
|
|
107
422
|
const cx = width / 2;
|
|
@@ -113,54 +428,197 @@ function drawPie(svg, { labels, series, width, height, donut }) {
|
|
|
113
428
|
data.forEach((value, i) => {
|
|
114
429
|
if (!total || !value) return;
|
|
115
430
|
const sweep = (value / total) * Math.PI * 2;
|
|
116
|
-
const color = PALETTE[i % PALETTE.length];
|
|
117
431
|
let slice;
|
|
118
432
|
if (sweep >= Math.PI * 2 - 1e-6) {
|
|
119
433
|
// A single full slice cannot be drawn as an arc.
|
|
120
434
|
slice = donut
|
|
121
|
-
? svgEl("circle", { cx, cy, r: (r + inner) / 2, fill: "none",
|
|
122
|
-
: svgEl("circle", { cx, cy, r
|
|
435
|
+
? svgEl("circle", { cx, cy, r: (r + inner) / 2, fill: "none", "stroke-width": r - inner, class: "chart-ring" })
|
|
436
|
+
: svgEl("circle", { cx, cy, r });
|
|
123
437
|
} else {
|
|
124
438
|
const end = start + sweep;
|
|
125
439
|
const large = sweep > Math.PI ? 1 : 0;
|
|
126
440
|
const d = donut
|
|
127
441
|
? `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`
|
|
128
442
|
: `M${cx},${cy} L${point(r, start)} A${r},${r} 0 ${large} 1 ${point(r, end)} Z`;
|
|
129
|
-
slice = svgEl("path", { d
|
|
443
|
+
slice = svgEl("path", { d });
|
|
130
444
|
}
|
|
131
|
-
slice.setAttribute("class",
|
|
132
|
-
slice.
|
|
445
|
+
slice.setAttribute("class", `chart-slice ${slice.getAttribute("class") ?? ""} ${seriesClass(i)}`.replace(/\s+/g, " ").trim());
|
|
446
|
+
slice.setAttribute("data-series", i);
|
|
447
|
+
const mid = start + sweep / 2;
|
|
448
|
+
const [tx, ty] = point(r * (donut ? (1 + 0.55) / 2 : 0.6), mid).split(",").map(Number);
|
|
449
|
+
addTip(ctx, slice, tx, ty, [labels[i] ?? "", `${formatNumber(value)} (${Math.round(value / total * 100)}%)`]);
|
|
133
450
|
svg.append(slice);
|
|
134
451
|
start += sweep;
|
|
135
452
|
});
|
|
136
453
|
// The legend of a pie lists the slices, not the series.
|
|
137
|
-
return labels.map((name, i) => ({ name,
|
|
454
|
+
return labels.map((name, i) => ({ name, props: { class: seriesClass(i) }, series: i }));
|
|
138
455
|
}
|
|
139
456
|
|
|
140
457
|
const DRAWERS = {
|
|
141
458
|
bar: drawBar,
|
|
142
459
|
line: drawLine,
|
|
460
|
+
area: (svg, ctx) => drawLine(svg, { ...ctx, area: true }),
|
|
461
|
+
sparkline: drawSparkline,
|
|
143
462
|
pie: drawPie,
|
|
144
|
-
donut: (svg,
|
|
463
|
+
donut: (svg, ctx) => drawPie(svg, { ...ctx, donut: true })
|
|
145
464
|
};
|
|
146
465
|
|
|
466
|
+
/* ------------------TABLE OF VALUES------------------- */
|
|
467
|
+
|
|
468
|
+
// The same numbers as a table, for screen readers and for people who want to read them off or copy them.
|
|
469
|
+
function buildDataTable({ labels, series, times, title, type }) {
|
|
470
|
+
const details = document.createElement("details");
|
|
471
|
+
details.className = "chart-data";
|
|
472
|
+
const summary = document.createElement("summary");
|
|
473
|
+
summary.textContent = translate("showAsTable");
|
|
474
|
+
const table = document.createElement("table");
|
|
475
|
+
table.className = "athena-table chart-data-table";
|
|
476
|
+
if (title) table.createCaption().textContent = title;
|
|
477
|
+
const headRow = table.createTHead().insertRow();
|
|
478
|
+
const names = type === "pie" || type === "donut" ? [series[0].name ?? ""] : series.map((s, i) => s.name ?? `${translate("series")} ${i + 1}`);
|
|
479
|
+
["", ...names].forEach((name, i) => {
|
|
480
|
+
const th = document.createElement("th");
|
|
481
|
+
th.scope = "col";
|
|
482
|
+
th.textContent = i ? name : (times ? translate("time") : "");
|
|
483
|
+
headRow.append(th);
|
|
484
|
+
});
|
|
485
|
+
const body = table.createTBody();
|
|
486
|
+
const shown = type === "pie" || type === "donut" ? [series[0]] : series;
|
|
487
|
+
const count = Math.max(...shown.map(s => s.data.length));
|
|
488
|
+
const when = times ? new Intl.DateTimeFormat(getLocale(), { dateStyle: "medium", timeStyle: "medium" }) : null;
|
|
489
|
+
for (let i = 0; i < count; i++) {
|
|
490
|
+
const row = body.insertRow();
|
|
491
|
+
const head = document.createElement("th");
|
|
492
|
+
head.scope = "row";
|
|
493
|
+
head.textContent = times ? when.format(times[i]) : (labels[i] ?? "");
|
|
494
|
+
row.append(head);
|
|
495
|
+
for (const s of shown) row.insertCell().textContent = s.data[i] == null ? "" : formatNumber(s.data[i]);
|
|
496
|
+
}
|
|
497
|
+
details.append(summary, table);
|
|
498
|
+
return details;
|
|
499
|
+
}
|
|
500
|
+
|
|
147
501
|
/**
|
|
148
502
|
* Draws a chart as inline SVG and appends it to its parent.
|
|
149
503
|
*
|
|
150
504
|
* @param {object} options
|
|
151
|
-
* @param {"bar"|"line"|"pie"|"donut"} [options.type="bar"]
|
|
152
|
-
* @param {string} [options.parent] id
|
|
505
|
+
* @param {"bar"|"line"|"area"|"sparkline"|"pie"|"donut"} [options.type="bar"]
|
|
506
|
+
* @param {string|Element} [options.parent] element, id or selector, defaults to "wrapper"
|
|
153
507
|
* @param {string} [options.id] id of the svg element
|
|
154
|
-
* @param {string} [options.title]
|
|
508
|
+
* @param {string} [options.title] drawn above the chart, and its accessible name
|
|
155
509
|
* @param {string[]} [options.labels] category labels
|
|
156
|
-
* @param {
|
|
157
|
-
*
|
|
158
|
-
* @param {number}
|
|
159
|
-
*
|
|
160
|
-
* @
|
|
510
|
+
* @param {(number|Date|string)[]} [options.times] line and area charts: the time of every value (Date, ms or a date string).
|
|
511
|
+
* The x axis becomes a time axis with ticks at round times, and the points sit at their real distance.
|
|
512
|
+
* @param {{name?: string, data: number[], color?: string}[]} options.series pie / donut / sparkline use the first series only.
|
|
513
|
+
* Colours come from the theme (--series-1 ... --series-8); `color` is an override for one series.
|
|
514
|
+
* @param {number} [options.width=600] (a sparkline: 120)
|
|
515
|
+
* @param {number} [options.height=360] (a sparkline: 32)
|
|
516
|
+
* @param {boolean} [options.legend] default: shown for several series, and for pie / donut. Clicking an entry hides / shows its series.
|
|
517
|
+
* @param {boolean} [options.table=false] adds a "Show as table" section with the values below the chart
|
|
518
|
+
* @param {boolean} [options.zero=true] line charts: false lets the value axis start near the smallest value
|
|
519
|
+
* @param {boolean} [options.zoom=false] line and area charts: drag over the plot to zoom into that range, double click (or the
|
|
520
|
+
* reset button, or 0 / Esc) to zoom out; with the keyboard on the plot: + and - zoom, the arrow keys pan
|
|
521
|
+
* @param {{from: number, to: number}|null} [options.zoomRange] the range in view, in the units of the x axis: milliseconds with
|
|
522
|
+
* `times`, otherwise the index of the point (-0.5 is the left edge of the first point)
|
|
523
|
+
* @param {(range: ({from: number, to: number}|null)) => void} [options.onZoom] called when a person zooms or resets
|
|
524
|
+
* @param {number} [options.maxPoints] `push` keeps at most this many points per series (the oldest are dropped)
|
|
525
|
+
* @param {boolean} [options.interactive=true] line and area charts: false leaves out the pointer layer (tooltip that follows the pointer, zoom)
|
|
526
|
+
* @returns {(SVGElement & {element: SVGElement, update: (options?: object) => SVGElement, destroy: () => void,
|
|
527
|
+
* zoom: (from: number, to: number) => void, resetZoom: () => void, getZoom: () => ({from: number, to: number}|null),
|
|
528
|
+
* push: (point: {x?: (number|Date|string), label?: string, values: (number|number[])}, config?: {maxPoints?: number}) => void,
|
|
529
|
+
* dataTable: (HTMLElement|null)})|null}
|
|
530
|
+
* the SVG element, which also carries the handle ({ element, update(options), destroy() }) of the other
|
|
531
|
+
* components; null when the options are invalid. `parent` is an element, an id or a selector.
|
|
532
|
+
* `push` adds a point to every series (a number for the first series, or one value per series; `x` is the time with
|
|
533
|
+
* `times`, `label` the category) and draws the chart again at most once per frame, however often it is called.
|
|
161
534
|
*/
|
|
162
535
|
export function generateChart(options = {}) {
|
|
163
|
-
const {
|
|
536
|
+
const state = { used: { ...options, series: (options.series ?? []).map(s => ({ ...s, data: [...(s.data ?? [])] })) }, current: null, queued: false };
|
|
537
|
+
if (options.labels) state.used.labels = [...options.labels];
|
|
538
|
+
if (options.times) state.used.times = [...options.times];
|
|
539
|
+
const hooks = {
|
|
540
|
+
zoom: range => {
|
|
541
|
+
state.used = { ...state.used, zoomRange: range ?? null };
|
|
542
|
+
handle.redraw();
|
|
543
|
+
options.onZoom?.(range ?? null);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
const handle = {
|
|
547
|
+
element: () => state.current.svg,
|
|
548
|
+
redraw() {
|
|
549
|
+
const next = buildChart(state.used, hooks);
|
|
550
|
+
if (!next) return state.current?.svg;
|
|
551
|
+
if (state.current) {
|
|
552
|
+
state.current.svg.replaceWith(next.svg);
|
|
553
|
+
state.current.table?.remove();
|
|
554
|
+
if (next.table) next.svg.after(next.table);
|
|
555
|
+
}
|
|
556
|
+
state.current = next;
|
|
557
|
+
return attach(next.svg);
|
|
558
|
+
},
|
|
559
|
+
update(changes = {}) {
|
|
560
|
+
state.used = { ...state.used, ...changes };
|
|
561
|
+
return handle.redraw();
|
|
562
|
+
},
|
|
563
|
+
destroy() {
|
|
564
|
+
state.current.svg.remove();
|
|
565
|
+
state.current.table?.remove();
|
|
566
|
+
},
|
|
567
|
+
zoom: (from, to) => hooks.zoom({ from, to }),
|
|
568
|
+
resetZoom: () => hooks.zoom(null),
|
|
569
|
+
getZoom: () => state.used.zoomRange ?? null,
|
|
570
|
+
push(point, config = {}) {
|
|
571
|
+
const used = state.used;
|
|
572
|
+
const values = Array.isArray(point.values) ? point.values : [point.values];
|
|
573
|
+
used.series.forEach((s, i) => s.data.push(values[i] ?? NaN));
|
|
574
|
+
if (used.times) used.times.push(toTime(point.x ?? Date.now()));
|
|
575
|
+
else if (used.labels) used.labels.push(String(point.label ?? used.labels.length + 1));
|
|
576
|
+
const limit = config.maxPoints ?? used.maxPoints;
|
|
577
|
+
const extra = limit ? used.series[0].data.length - limit : 0;
|
|
578
|
+
if (extra > 0) {
|
|
579
|
+
for (const s of used.series) s.data.splice(0, extra);
|
|
580
|
+
used.times?.splice(0, extra);
|
|
581
|
+
used.labels?.splice(0, extra);
|
|
582
|
+
}
|
|
583
|
+
if (state.queued) return;
|
|
584
|
+
state.queued = true;
|
|
585
|
+
// Once per frame (the timer is for pages where frames are paused or late)
|
|
586
|
+
let timer = 0;
|
|
587
|
+
const run = () => {
|
|
588
|
+
if (!state.queued) return;
|
|
589
|
+
state.queued = false;
|
|
590
|
+
clearTimeout(timer);
|
|
591
|
+
handle.redraw();
|
|
592
|
+
};
|
|
593
|
+
requestAnimationFrame(run);
|
|
594
|
+
timer = setTimeout(run, 100);
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
const attach = svg => Object.defineProperties(svg, {
|
|
598
|
+
element: { get: () => state.current.svg, configurable: true },
|
|
599
|
+
update: { value: handle.update, configurable: true },
|
|
600
|
+
destroy: { value: handle.destroy, configurable: true },
|
|
601
|
+
zoom: { value: handle.zoom, configurable: true },
|
|
602
|
+
resetZoom: { value: handle.resetZoom, configurable: true },
|
|
603
|
+
getZoom: { value: handle.getZoom, configurable: true },
|
|
604
|
+
push: { value: handle.push, configurable: true },
|
|
605
|
+
dataTable: { get: () => state.current.table ?? null, configurable: true }
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
const built = buildChart(state.used, hooks);
|
|
609
|
+
if (!built) return null;
|
|
610
|
+
state.current = built;
|
|
611
|
+
const host = resolveElement(options.parent ?? "wrapper") ?? document.body;
|
|
612
|
+
host.append(built.svg);
|
|
613
|
+
if (built.table) built.svg.after(built.table);
|
|
614
|
+
return attach(built.svg);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function buildChart(options = {}, hooks) {
|
|
618
|
+
const { type = "bar", id, title } = options;
|
|
619
|
+
const sparkline = type === "sparkline";
|
|
620
|
+
const width = options.width ?? (sparkline ? 120 : 600);
|
|
621
|
+
const height = options.height ?? (sparkline ? 32 : 360);
|
|
164
622
|
const draw = DRAWERS[type];
|
|
165
623
|
const series = (options.series ?? []).filter(s => Array.isArray(s?.data) && s.data.length);
|
|
166
624
|
if (!draw || !series.length) {
|
|
@@ -170,18 +628,25 @@ export function generateChart(options = {}) {
|
|
|
170
628
|
const labels = (options.labels ?? []).map(String);
|
|
171
629
|
const count = Math.max(...series.map(s => s.data.length));
|
|
172
630
|
while (labels.length < count) labels.push(String(labels.length + 1));
|
|
631
|
+
const times = options.times && (type === "line" || type === "area") ? options.times.map(toTime) : null;
|
|
632
|
+
if (times && (times.length < count || times.some(Number.isNaN))) {
|
|
633
|
+
console.error("Athena UI: generateChart `times` needs a valid time for every value", options);
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
173
636
|
|
|
174
|
-
const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class:
|
|
637
|
+
const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class: `athena-chart athena-chart-${type}`, role: "img" });
|
|
175
638
|
if (id) svg.id = id;
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}
|
|
639
|
+
const summary = `${title ?? translate(`chart.${type}`)}: ${series.map(s => s.name ?? "").filter(Boolean).join(", ")}`.replace(/: $/, "");
|
|
640
|
+
svg.setAttribute("aria-label", options.ariaLabel ?? summary);
|
|
641
|
+
if (title && !sparkline) svg.append(svgEl("text", { x: width / 2, y: 24, "text-anchor": "middle", class: "chart-title" }, title));
|
|
180
642
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
643
|
+
// The tooltip is created first, so the shapes can use it, and moved to the end afterwards, so it is drawn on top.
|
|
644
|
+
const tooltip = createTooltip(svg, width);
|
|
645
|
+
const ctx = { labels, series, width, height, times, options, tooltip, hooks, zoom: options.zoomRange ?? null };
|
|
646
|
+
const pieLegend = draw(svg, ctx);
|
|
647
|
+
if (!sparkline && (options.legend ?? (Boolean(pieLegend) || series.length > 1))) {
|
|
648
|
+
addLegend(svg, pieLegend ?? series.map((s, i) => ({ name: s.name ?? `${translate("series")} ${i + 1}`, props: seriesProps(s, i), series: i })), width, height, ctx);
|
|
184
649
|
}
|
|
185
|
-
|
|
186
|
-
return svg;
|
|
650
|
+
svg.append(tooltip.group);
|
|
651
|
+
return { svg, table: options.table ? buildDataTable({ labels, series, times, title, type }) : null };
|
|
187
652
|
}
|