athena-ui-js 1.2.0 → 2.0.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.
Files changed (148) hide show
  1. package/README.md +312 -60
  2. package/docs/migration-2.0.md +83 -0
  3. package/docs/styling.md +86 -0
  4. package/package.json +109 -24
  5. package/src/athena-ui.js +61 -81
  6. package/src/chart.js +6 -0
  7. package/src/classic.js +11 -0
  8. package/src/components.js +6 -0
  9. package/src/controls.js +8 -0
  10. package/src/csv.js +6 -0
  11. package/src/dialog.js +7 -0
  12. package/src/dom.js +6 -0
  13. package/src/feedback.js +6 -0
  14. package/src/format.js +6 -0
  15. package/src/forms.js +7 -0
  16. package/src/i18n.js +6 -0
  17. package/src/inputs.js +9 -0
  18. package/src/libs/config/config.js +1 -2
  19. package/src/libs/core/controls.js +145 -0
  20. package/src/libs/core/cookies.js +55 -0
  21. package/src/libs/core/dateRange.js +121 -0
  22. package/src/libs/core/dom.js +58 -8
  23. package/src/libs/{hephaestus/HTMLElementGenerator/src/HTMLElementGenerator.js → core/elementGenerator.js} +23 -21
  24. package/src/libs/{hephaestus/HTMLElementGenerator/src → core}/errors.js +7 -5
  25. package/src/libs/core/format.js +51 -0
  26. package/src/libs/core/hungarianControls.js +41 -0
  27. package/src/libs/core/i18n.js +104 -6
  28. package/src/libs/core/theme.js +131 -0
  29. package/src/libs/core/validation.js +2 -2
  30. package/src/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.js +13 -7
  31. package/src/libs/hephaestus/LayoutGenerator/footerContentGenerator.js +2 -4
  32. package/src/libs/hephaestus/LayoutGenerator/headerContentGenerator.js +12 -5
  33. package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +3 -3
  34. package/src/libs/hephaestus/MenuGenerator/menuGenerator.js +265 -0
  35. package/src/libs/hephaestus/auth/authState.js +58 -0
  36. package/src/libs/hephaestus/auth/session.js +1 -1
  37. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +519 -87
  38. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +121 -4
  39. package/src/libs/hephaestus/componentGenerator/themePicker.js +73 -0
  40. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +113 -25
  41. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +21 -0
  42. package/src/libs/hephaestus/formGenerator/authForms.js +130 -0
  43. package/src/libs/hephaestus/formGenerator/changePasswordFormGenerator.js +4 -4
  44. package/src/libs/hephaestus/formGenerator/formUtils.js +10 -13
  45. package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +10 -11
  46. package/src/libs/hephaestus/formGenerator/registrationFormGenerator.js +3 -3
  47. package/src/libs/hephaestus/hephaestus.js +0 -5
  48. package/src/libs/hephaestus/inputGenerator/dropZoneGenerator.js +1 -1
  49. package/src/libs/hephaestus/inputGenerator/inputGenerator.js +30 -1
  50. package/src/libs/hephaestus/modalGenerator/modalGenerator.js +25 -12
  51. package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +20 -24
  52. package/src/libs/hephaestus/router/router.js +54 -5
  53. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +290 -16
  54. package/src/menu.js +6 -0
  55. package/src/navigation.js +6 -0
  56. package/src/res/themes/appearance.css +154 -0
  57. package/src/res/themes/default/style.css +688 -82
  58. package/src/res/themes/tokens.css +96 -0
  59. package/src/router.js +6 -0
  60. package/src/sanitize.js +6 -0
  61. package/src/session.js +8 -0
  62. package/src/table.js +6 -0
  63. package/src/testing.js +11 -1
  64. package/src/theme-boot.js +25 -0
  65. package/src/theme.js +7 -0
  66. package/src/validation.js +6 -0
  67. package/types/athena-ui.d.ts +96 -0
  68. package/types/chart.d.ts +1 -0
  69. package/types/classic.d.ts +1 -0
  70. package/types/components.d.ts +1 -0
  71. package/types/controls.d.ts +3 -0
  72. package/types/csv.d.ts +1 -0
  73. package/types/dialog.d.ts +2 -0
  74. package/types/dom.d.ts +1 -0
  75. package/types/feedback.d.ts +1 -0
  76. package/types/format.d.ts +1 -0
  77. package/types/forms.d.ts +2 -0
  78. package/types/i18n.d.ts +1 -0
  79. package/types/inputs.d.ts +4 -0
  80. package/types/libs/config/config.d.ts +96 -0
  81. package/types/libs/config/hooks.d.ts +8 -0
  82. package/types/libs/core/combobox.d.ts +10 -0
  83. package/types/libs/core/controls.d.ts +28 -0
  84. package/types/libs/core/cookies.d.ts +27 -0
  85. package/types/libs/core/csv.d.ts +12 -0
  86. package/types/libs/core/dateRange.d.ts +72 -0
  87. package/types/libs/core/dom.d.ts +65 -0
  88. package/types/libs/core/elementGenerator.d.ts +30 -0
  89. package/types/libs/core/errors.d.ts +29 -0
  90. package/types/libs/core/focus.d.ts +6 -0
  91. package/types/libs/core/format.d.ts +21 -0
  92. package/types/libs/core/hungarianControls.d.ts +2 -0
  93. package/types/libs/core/i18n.d.ts +17 -0
  94. package/types/libs/core/pagination.d.ts +5 -0
  95. package/types/libs/core/sanitize.d.ts +6 -0
  96. package/types/libs/core/tableMath.d.ts +26 -0
  97. package/types/libs/core/theme.d.ts +39 -0
  98. package/types/libs/core/validation.d.ts +56 -0
  99. package/types/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.d.ts +10 -0
  100. package/types/libs/hephaestus/LayoutGenerator/footerContentGenerator.d.ts +4 -0
  101. package/types/libs/hephaestus/LayoutGenerator/headerContentGenerator.d.ts +20 -0
  102. package/types/libs/hephaestus/LayoutGenerator/wrapperContentGenerator.d.ts +1 -0
  103. package/types/libs/hephaestus/MenuGenerator/basicMenuGenerator.d.ts +14 -0
  104. package/types/libs/hephaestus/MenuGenerator/menuGenerator.d.ts +65 -0
  105. package/types/libs/hephaestus/auth/authState.d.ts +26 -0
  106. package/types/libs/hephaestus/auth/session.d.ts +26 -0
  107. package/types/libs/hephaestus/chartGenerator/chartGenerator.d.ts +91 -0
  108. package/types/libs/hephaestus/componentGenerator/componentGenerator.d.ts +222 -0
  109. package/types/libs/hephaestus/componentGenerator/themePicker.d.ts +24 -0
  110. package/types/libs/hephaestus/dialogGenerator/dialogGenerator.d.ts +120 -0
  111. package/types/libs/hephaestus/feedbackGenerator/feedbackGenerator.d.ts +86 -0
  112. package/types/libs/hephaestus/formGenerator/authForms.d.ts +122 -0
  113. package/types/libs/hephaestus/formGenerator/changePasswordFormGenerator.d.ts +6 -0
  114. package/types/libs/hephaestus/formGenerator/formBuilder.d.ts +113 -0
  115. package/types/libs/hephaestus/formGenerator/formUtils.d.ts +8 -0
  116. package/types/libs/hephaestus/formGenerator/loginFormGenerator.d.ts +11 -0
  117. package/types/libs/hephaestus/formGenerator/lostPasswordFormGenerator.d.ts +4 -0
  118. package/types/libs/hephaestus/formGenerator/registrationFormGenerator.d.ts +7 -0
  119. package/types/libs/hephaestus/hephaestus.d.ts +3 -0
  120. package/types/libs/hephaestus/inputGenerator/dropZoneGenerator.d.ts +48 -0
  121. package/types/libs/hephaestus/inputGenerator/inputGenerator.d.ts +185 -0
  122. package/types/libs/hephaestus/inputGenerator/richTextGenerator.d.ts +49 -0
  123. package/types/libs/hephaestus/modalGenerator/modalGenerator.d.ts +2 -0
  124. package/types/libs/hephaestus/navigationGenerator/navigationGenerator.d.ts +150 -0
  125. package/types/libs/hephaestus/router/matchRoute.d.ts +12 -0
  126. package/types/libs/hephaestus/router/router.d.ts +67 -0
  127. package/types/libs/hephaestus/tableGenerator/tableGenerator.d.ts +120 -0
  128. package/types/menu.d.ts +1 -0
  129. package/types/navigation.d.ts +1 -0
  130. package/types/res/themes/themes.d.ts +7 -0
  131. package/types/router.d.ts +1 -0
  132. package/types/sanitize.d.ts +1 -0
  133. package/types/session.d.ts +3 -0
  134. package/types/table.d.ts +1 -0
  135. package/types/testing.d.ts +27 -0
  136. package/types/theme-boot.d.ts +0 -0
  137. package/types/theme.d.ts +2 -0
  138. package/types/validation.d.ts +1 -0
  139. package/src/libs/crypto-js/LICENSE +0 -24
  140. package/src/libs/crypto-js/crypto-js.js +0 -6657
  141. package/src/libs/hephaestus/HTMLControlGenerator/LICENSE +0 -21
  142. package/src/libs/hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js +0 -5
  143. package/src/libs/hephaestus/HTMLElementGenerator/LICENSE +0 -21
  144. package/src/libs/js-cookie/LICENSE +0 -21
  145. package/src/libs/js-cookie/src/api.mjs +0 -103
  146. package/src/libs/js-cookie/src/assign.mjs +0 -10
  147. package/src/libs/js-cookie/src/converter.mjs +0 -14
  148. package/src/libs/libs.js +0 -13
@@ -3,13 +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.
7
8
 
8
- import { resolveElement } from "../../core/dom.js";
9
+ import { resolveElement, uid } from "../../core/dom.js";
10
+ import { getLocale, translate } from "../../core/i18n.js";
9
11
 
10
12
  const NS = "http://www.w3.org/2000/svg";
11
- const PALETTE = ["#4e79a7", "#f28e2b", "#e15759", "#76b7b2", "#59a14f", "#edc948", "#b07aa1", "#ff9da7", "#9c755f", "#bab0ac"];
13
+ const SERIES_COLORS = 8;
12
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
13
16
 
14
17
  const svgEl = (tag, attrs = {}, text) => {
15
18
  const node = document.createElementNS(NS, tag);
@@ -18,7 +21,9 @@ const svgEl = (tag, attrs = {}, text) => {
18
21
  return node;
19
22
  };
20
23
 
21
- const colorOf = (series, index) => series.color ?? PALETTE[index % PALETTE.length];
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) });
22
27
  const formatNumber = n => Number.isInteger(n) ? String(n) : String(+n.toFixed(2));
23
28
 
24
29
  // Rounded axis maximum and tick step, so ticks land on readable numbers.
@@ -30,19 +35,131 @@ function niceScale(span, ticks = 5) {
30
35
  return { span: step * Math.ceil(span / step - 1e-9), step };
31
36
  }
32
37
 
33
- function addLegend(svg, entries, width, height) {
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) {
34
94
  let x = MARGIN.left;
35
95
  const y = height - 12;
36
- for (const { name, color } of entries) {
37
- svg.append(svgEl("rect", { x, y: y - 9, width: 10, height: 10, fill: color }));
38
- svg.append(svgEl("text", { x: x + 14, y, class: "chart-legend" }, name));
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);
39
117
  x += 14 + name.length * 7 + 14;
40
- if (x > width) break;
41
- }
118
+ });
42
119
  }
43
120
 
44
- // Draws grid, ticks and axes for the value range [min, min + scale.span].
45
- function addAxes(svg, { labels, min, scale, width, height }) {
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);
159
+ }
160
+
161
+ // Draws the value grid and the y axis for the range [min, min + scale.span].
162
+ function addValueAxis(svg, { min, scale, width, height }) {
46
163
  const plotW = width - MARGIN.left - MARGIN.right;
47
164
  const plotH = height - MARGIN.top - MARGIN.bottom;
48
165
  const y = value => MARGIN.top + plotH - ((value - min) / scale.span) * plotH;
@@ -52,26 +169,32 @@ function addAxes(svg, { labels, min, scale, width, height }) {
52
169
  svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: y(v), y2: y(v), class: "chart-grid" }));
53
170
  svg.append(svgEl("text", { x: MARGIN.left - 8, y: y(v) + 4, "text-anchor": "end", class: "chart-tick" }, formatNumber(v)));
54
171
  }
55
- const band = plotW / Math.max(labels.length, 1);
56
- labels.forEach((label, i) => svg.append(svgEl("text",
57
- { x: MARGIN.left + band * (i + 0.5), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, label)));
58
172
  svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left, y1: MARGIN.top, y2: MARGIN.top + plotH, class: "chart-axis" }));
59
173
  // The category axis sits at zero when the range includes it, so negative bars hang below it.
60
174
  const baseline = y(Math.min(Math.max(0, min), min + scale.span));
61
175
  svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: baseline, y2: baseline, class: "chart-axis" }));
62
- return { band, y };
176
+ return { y, baseline, plotW, plotH };
63
177
  }
64
178
 
65
- function valueRange(series) {
66
- const values = series.flatMap(s => s.data);
67
- const min = Math.min(0, ...values);
68
- const scale = niceScale(Math.max(0, ...values) - min);
69
- return { min, scale };
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) };
70
187
  }
71
188
 
72
- function drawBar(svg, { labels, series, width, height }) {
73
- const { min, scale } = valueRange(series);
74
- const { band, y } = addAxes(svg, { labels, min, scale, width, height });
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)));
75
198
  const groupWidth = band * 0.8;
76
199
  const barWidth = groupWidth / series.length;
77
200
  series.forEach((s, si) => s.data.forEach((value, i) => {
@@ -79,31 +202,221 @@ function drawBar(svg, { labels, series, width, height }) {
79
202
  const top = Math.min(y(value), y(0));
80
203
  const bar = svgEl("rect", {
81
204
  x, y: top, width: Math.max(barWidth - 2, 1), height: Math.abs(y(0) - y(value)),
82
- fill: colorOf(s, si), class: "chart-bar"
205
+ "data-series": si, ...seriesProps(s, si)
83
206
  });
84
- bar.append(svgEl("title", {}, `${s.name ?? ""} ${labels[i] ?? ""}: ${formatNumber(value)}`.trim()));
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)]);
85
209
  svg.append(bar);
86
210
  }));
87
211
  }
88
212
 
89
- function drawLine(svg, { labels, series, width, height }) {
90
- const { min, scale } = valueRange(series);
91
- const { band, y } = addAxes(svg, { labels, min, scale, width, height });
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
+
92
261
  series.forEach((s, si) => {
93
- const color = colorOf(s, si);
94
- const points = s.data.map((v, i) => [MARGIN.left + band * (i + 0.5), y(v)]);
95
- svg.append(svgEl("polyline", {
96
- points: points.map(p => p.join(",")).join(" "), fill: "none", stroke: color, "stroke-width": 2, class: "chart-line"
97
- }));
98
- points.forEach(([cx, cy], i) => {
99
- const dot = svgEl("circle", { cx, cy, r: 4, fill: color, class: "chart-point" });
100
- dot.append(svgEl("title", {}, `${s.name ?? ""} ${labels[i] ?? ""}: ${formatNumber(s.data[i])}`.trim()));
101
- svg.append(dot);
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
+ }
102
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)));
103
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);
394
+ }
395
+
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);
104
416
  }
105
417
 
106
- function drawPie(svg, { labels, series, width, height, donut }) {
418
+ function drawPie(svg, ctx) {
419
+ const { labels, series, width, height, donut } = ctx;
107
420
  const data = series[0].data.map(v => Math.max(0, v));
108
421
  const total = data.reduce((a, b) => a + b, 0);
109
422
  const cx = width / 2;
@@ -115,86 +428,197 @@ function drawPie(svg, { labels, series, width, height, donut }) {
115
428
  data.forEach((value, i) => {
116
429
  if (!total || !value) return;
117
430
  const sweep = (value / total) * Math.PI * 2;
118
- const color = PALETTE[i % PALETTE.length];
119
431
  let slice;
120
432
  if (sweep >= Math.PI * 2 - 1e-6) {
121
433
  // A single full slice cannot be drawn as an arc.
122
434
  slice = donut
123
- ? svgEl("circle", { cx, cy, r: (r + inner) / 2, fill: "none", stroke: color, "stroke-width": r - inner })
124
- : svgEl("circle", { cx, cy, r, fill: color });
435
+ ? svgEl("circle", { cx, cy, r: (r + inner) / 2, fill: "none", "stroke-width": r - inner, class: "chart-ring" })
436
+ : svgEl("circle", { cx, cy, r });
125
437
  } else {
126
438
  const end = start + sweep;
127
439
  const large = sweep > Math.PI ? 1 : 0;
128
440
  const d = donut
129
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`
130
442
  : `M${cx},${cy} L${point(r, start)} A${r},${r} 0 ${large} 1 ${point(r, end)} Z`;
131
- slice = svgEl("path", { d, fill: color, stroke: "#fff" });
443
+ slice = svgEl("path", { d });
132
444
  }
133
- slice.setAttribute("class", "chart-slice");
134
- slice.append(svgEl("title", {}, `${labels[i] ?? ""}: ${formatNumber(value)} (${Math.round(value / total * 100)}%)`));
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)}%)`]);
135
450
  svg.append(slice);
136
451
  start += sweep;
137
452
  });
138
453
  // The legend of a pie lists the slices, not the series.
139
- return labels.map((name, i) => ({ name, color: PALETTE[i % PALETTE.length] }));
454
+ return labels.map((name, i) => ({ name, props: { class: seriesClass(i) }, series: i }));
140
455
  }
141
456
 
142
457
  const DRAWERS = {
143
458
  bar: drawBar,
144
459
  line: drawLine,
460
+ area: (svg, ctx) => drawLine(svg, { ...ctx, area: true }),
461
+ sparkline: drawSparkline,
145
462
  pie: drawPie,
146
- donut: (svg, o) => drawPie(svg, { ...o, donut: true })
463
+ donut: (svg, ctx) => drawPie(svg, { ...ctx, donut: true })
147
464
  };
148
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
+
149
501
  /**
150
502
  * Draws a chart as inline SVG and appends it to its parent.
151
503
  *
152
504
  * @param {object} options
153
- * @param {"bar"|"line"|"pie"|"donut"} [options.type="bar"]
154
- * @param {string} [options.parent] id of the parent element, defaults to "wrapper"
505
+ * @param {"bar"|"line"|"area"|"sparkline"|"pie"|"donut"} [options.type="bar"]
506
+ * @param {string|Element} [options.parent] element, id or selector, defaults to "wrapper"
155
507
  * @param {string} [options.id] id of the svg element
156
- * @param {string} [options.title]
508
+ * @param {string} [options.title] drawn above the chart, and its accessible name
157
509
  * @param {string[]} [options.labels] category labels
158
- * @param {{name?: string, data: number[], color?: string}[]} options.series pie / donut use the first series only
159
- * @param {number} [options.width=600]
160
- * @param {number} [options.height=360]
161
- * @param {boolean} [options.legend] default: shown for several series, and for pie / donut
162
- * @returns {(SVGElement & {element: SVGElement, update: (options?: object) => void, destroy: () => void})|null}
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}
163
530
  * the SVG element, which also carries the handle ({ element, update(options), destroy() }) of the other
164
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.
165
534
  */
166
535
  export function generateChart(options = {}) {
167
- const svg = buildChart(options);
168
- if (!svg) return null;
169
- (resolveElement(options.parent ?? "wrapper") ?? document.body).append(svg);
170
- return withHandle(svg, options);
171
- }
172
-
173
- // update(changes) draws the chart again with the old options plus the changes, in the same place.
174
- function withHandle(svg, options) {
175
- let current = svg;
176
- let used = options;
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
+ };
177
546
  const handle = {
178
- get element() { return current; },
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
+ },
179
559
  update(changes = {}) {
180
- const next = buildChart({ ...used, ...changes });
181
- if (!next) return current;
182
- used = { ...used, ...changes };
183
- current.replaceWith(next);
184
- current = withHandle(next, used);
185
- return current;
560
+ state.used = { ...state.used, ...changes };
561
+ return handle.redraw();
186
562
  },
187
- destroy() { current.remove(); }
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
+ }
188
596
  };
189
- return Object.defineProperties(svg, {
190
- element: { get: () => handle.element, configurable: true },
597
+ const attach = svg => Object.defineProperties(svg, {
598
+ element: { get: () => state.current.svg, configurable: true },
191
599
  update: { value: handle.update, configurable: true },
192
- destroy: { value: handle.destroy, 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 }
193
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);
194
615
  }
195
616
 
196
- function buildChart(options = {}) {
197
- const { type = "bar", id, title, width = 600, height = 360 } = options;
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);
198
622
  const draw = DRAWERS[type];
199
623
  const series = (options.series ?? []).filter(s => Array.isArray(s?.data) && s.data.length);
200
624
  if (!draw || !series.length) {
@@ -204,17 +628,25 @@ function buildChart(options = {}) {
204
628
  const labels = (options.labels ?? []).map(String);
205
629
  const count = Math.max(...series.map(s => s.data.length));
206
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
+ }
207
636
 
208
- const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class: "athena-chart", role: "img" });
637
+ const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class: `athena-chart athena-chart-${type}`, role: "img" });
209
638
  if (id) svg.id = id;
210
- if (title) {
211
- svg.setAttribute("aria-label", title);
212
- svg.append(svgEl("text", { x: width / 2, y: 24, "text-anchor": "middle", class: "chart-title" }, title));
213
- }
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));
214
642
 
215
- const pieLegend = draw(svg, { labels, series, width, height });
216
- if (options.legend ?? (Boolean(pieLegend) || series.length > 1)) {
217
- addLegend(svg, pieLegend ?? series.map((s, i) => ({ name: s.name ?? `Series ${i + 1}`, color: colorOf(s, i) })), width, height);
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);
218
649
  }
219
- return svg;
650
+ svg.append(tooltip.group);
651
+ return { svg, table: options.table ? buildDataTable({ labels, series, times, title, type }) : null };
220
652
  }