-
-
Notifications
You must be signed in to change notification settings - Fork 646
Expand file tree
/
Copy pathcharts.js
More file actions
438 lines (362 loc) · 13.8 KB
/
Copy pathcharts.js
File metadata and controls
438 lines (362 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/* Pi-hole: A black hole for Internet advertisements
* (c) 2023 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
/* global upstreamIPs:false, utils:false */
"use strict";
globalThis.THEME_COLORS = [
"#f56954",
"#3c8dbc",
"#00a65a",
"#00c0ef",
"#f39c12",
"#0073b7",
"#001f3f",
"#39cccc",
"#3d9970",
"#01ff70",
"#ff851b",
"#f012be",
"#8e24aa",
"#d81b60",
"#222222",
"#d2d6de",
];
globalThis.htmlLegendPlugin = {
id: "htmlLegend",
afterUpdate(chart, arguments_, options) {
// Use the built-in legendItems generator
const items = chart.options.plugins.legend.labels.generateLabels(chart);
// Exit early if the legend has the same items as last time
const isLegendUnchanged =
options.lastLegendItems &&
items.length === options.lastLegendItems.length &&
items.every(
(item, index) =>
item.text === options.lastLegendItems[index].text &&
item.hidden === options.lastLegendItems[index].hidden
);
if (isLegendUnchanged) {
return;
}
// else: Update the HTML legend if it is different from last time or if it
// did not exist
// Save the legend items so we can check against them next time to see if we
// need to update the legend
options.lastLegendItems = items;
const ul = getOrCreateLegendList(options.containerID);
// Remove old legend items
ul.replaceChildren();
for (const item of items) {
const li = document.createElement("li");
// Select the corresponding "slice" of the chart when the mouse is over a legend item
li.addEventListener("mouseover", () => {
chart.setActiveElements([
{
datasetIndex: 0,
index: item.index,
},
]);
chart.update();
});
// Deselect all "slices"
li.addEventListener("mouseout", () => {
chart.setActiveElements([]);
chart.update();
});
// Color checkbox (toggle visibility)
const boxSpan = document.createElement("span");
boxSpan.title = "Toggle visibility";
boxSpan.style.color = item.fillStyle;
boxSpan.style.cursor = "pointer";
boxSpan.innerHTML = `<i class="colorBoxWrapper fa ${item.hidden ? "fa-square" : "fa-check-square"}"></i>`;
boxSpan.addEventListener("click", () => {
const { type } = chart.config;
const isPieOrDoughnut = type === "pie" || type === "doughnut";
if (isPieOrDoughnut) {
// Pie and doughnut charts only have a single dataset and visibility is per item
chart.toggleDataVisibility(item.index);
} else {
const isVisible = chart.isDatasetVisible(item.datasetIndex);
chart.setDatasetVisibility(item.datasetIndex, !isVisible);
}
chart.update();
});
const link = document.createElement("a");
const isQueryTypeChart = chart.canvas.id === "queryTypePieChart";
const isForwardDestinationChart = chart.canvas.id === "forwardDestinationPieChart";
if (isQueryTypeChart || isForwardDestinationChart) {
// Text (link to query log page)
link.title = `List ${item.text} queries`;
link.className = "legend-label-text clickable";
if (isQueryTypeChart) {
link.href = `queries?type=${item.text}`;
} else {
// Encode the forward destination as it may contain an "#" character
link.href = `queries?upstream=${encodeURIComponent(upstreamIPs[item.index])}`;
// If server name and IP are different:
if (item.text !== upstreamIPs[item.index]) {
// replace the title tooltip to include the upstream IP to the text ...
link.title = `List ${item.text} (${upstreamIPs[item.index]}) queries`;
// ... and include the server name (without port) to the querystring, to match
// the text used on the SELECT element (sent by suggestions API endpoint)
link.href += ` (${item.text.split("#", 1)[0]})`;
}
}
} else {
// no clickable links in other charts
link.className = "legend-label-text";
}
link.style.textDecoration = item.hidden ? "line-through" : "";
link.textContent = item.text;
li.append(boxSpan, link);
ul.append(li);
}
},
};
globalThis.customTooltips = context => {
const tooltip = context.tooltip;
const canvasId = context.chart.canvas.id;
const tooltipElement = getOrCreateTooltipElement(canvasId, tooltip.options, context);
// Hide if no tooltip
if (tooltip.opacity === 0) {
tooltipElement.style.opacity = 0;
return;
}
// Set caret position
setTooltipCaretPosition(tooltipElement, tooltip);
// Set tooltip content
if (tooltip.body) {
setTooltipContent(tooltipElement, tooltip);
}
// Position tooltip
positionTooltip(tooltipElement, tooltip, context);
// Make tooltip visible
tooltipElement.style.opacity = 1;
};
function getOrCreateTooltipElement(canvasId, options, context) {
let tooltipElement = document.getElementById(`${canvasId}-customTooltip`);
if (tooltipElement) {
return tooltipElement;
}
// Create Tooltip Element once per chart
tooltipElement = document.createElement("div");
tooltipElement.id = `${canvasId}-customTooltip`;
tooltipElement.className = "chartjs-tooltip";
tooltipElement.innerHTML = '<div class="arrow"></div> <table></table>';
// Avoid browser's font-zoom since we know that <body>'s
// font-size was set to 14px by Bootstrap's CSS
// Use Number.parseFloat to convert the line height from a string (like "16px") to a number
// Using Number only would return NaN if the string contains non-numeric characters
//eslint-disable-next-line unicorn/prefer-number-coercion
const fontZoom = Number.parseFloat(getComputedStyle(document.body).fontSize) / 14;
// Set styles and font
tooltipElement.style.cssText = `
padding: ${options.padding}px ${options.padding}px;
border-radius: ${options.cornerRadius}px;
font: ${options.bodyFont.string};
font-family: ${options.bodyFont.family};
font-size: ${options.bodyFont.size / fontZoom}px;
font-style: ${options.bodyFont.style};
`;
// Append Tooltip next to canvas-containing box
tooltipElement.ancestor = context.chart.canvas.closest(".box[id]").parentNode;
tooltipElement.ancestor.append(tooltipElement);
return tooltipElement;
}
function setTooltipCaretPosition(tooltipElement, tooltip) {
tooltipElement.classList.remove("left", "right", "center", "top", "bottom");
tooltipElement.classList.add(tooltip.xAlign, tooltip.yAlign);
}
function setTooltipContent(tooltipElement, tooltip) {
const bodyLines = tooltip.body.map(bodyItem => bodyItem.lines);
if (bodyLines.length === 0) {
return;
}
const titleLines = tooltip.title || [];
let tooltipHtml = "<thead>";
for (const title of titleLines) {
tooltipHtml += `<tr><th>${utils.escapeHtml(title)}</th></tr>`;
}
tooltipHtml += "</thead><tbody>";
const devicePixel = (1 / window.devicePixelRatio).toFixed(1);
let printed = 0;
for (const [index, body] of bodyLines.entries()) {
const labelColors = tooltip.labelColors[index];
const style =
`background-color: ${labelColors.backgroundColor}; ` +
`outline: 1px solid ${labelColors.backgroundColor}; ` +
`border: ${devicePixel}px solid #fff`;
const span = `<span class="chartjs-tooltip-key" style="${style}"></span>`;
const number_ = body[0].split(": ");
// Do not display entries with value of 0 in bar chart,
// but pass through entries with "0.0%" (in pie charts)
if (number_[1] !== "0") {
tooltipHtml += `<tr><td>${span}${body}</td></tr>`;
printed++;
}
}
if (printed < 1) {
tooltipHtml += "<tr><td>No activity recorded</td></tr>";
}
tooltipHtml += "</tbody>";
const tableRoot = tooltipElement.querySelector("table");
tableRoot.innerHTML = tooltipHtml;
}
function positionTooltip(tooltipElement, tooltip, context) {
if (tooltip.opacity === 0 || tooltipElement.style.opacity === 0) {
return;
}
const canvasPos = context.chart.canvas.getBoundingClientRect();
const boxPos = tooltipElement.ancestor.getBoundingClientRect();
const offsetX = canvasPos.left - boxPos.left;
const offsetY = canvasPos.top - boxPos.top;
const tooltipWidth = tooltipElement.offsetWidth;
const tooltipHeight = tooltipElement.offsetHeight;
const { caretX, caretY } = tooltip;
const { caretPadding } = tooltip.options;
const arrowMinIndent = 2 * tooltip.options.cornerRadius;
const arrowSize = 5;
// Check if this is a queryOverTimeChart or clientsChart - these should stick to x-axis
const canvasId = context.chart.canvas.id;
const isTimelineChart = canvasId === "queryOverTimeChart" || canvasId === "clientsChart";
let tooltipX = offsetX + caretX;
let arrowX;
// Compute X position
if (tooltip.yAlign === "top" || tooltip.yAlign === "bottom") {
switch (tooltip.xAlign) {
case "center": {
// Set a minimal X position to 5px to prevent
// the tooltip to stick out left of the viewport
const minX = 5;
tooltipX = Math.max(minX, tooltipX - tooltipWidth / 2);
arrowX = tooltip.caretX - (tooltipX - offsetX);
break;
}
case "left": {
tooltipX -= arrowMinIndent;
arrowX = arrowMinIndent;
break;
}
case "right": {
tooltipX -= tooltipWidth - arrowMinIndent;
arrowX = tooltipWidth - arrowMinIndent;
break;
}
// No default
}
} else if (tooltip.yAlign === "center") {
switch (tooltip.xAlign) {
case "left": {
tooltipX += caretPadding;
break;
}
case "right": {
tooltipX -= tooltipWidth - caretPadding;
break;
}
case "center": {
tooltipX -= tooltipWidth / 2;
break;
}
// No default
}
}
// Adjust X position if tooltip is centered inside ancestor
if (document.documentElement.clientWidth <= 2 * tooltip.width && tooltip.xAlign === "center") {
tooltipX = (tooltipElement.ancestor.offsetWidth - tooltipWidth) / 2;
tooltipX = Math.max(tooltipX, offsetX + caretX - arrowMinIndent); // Prevent left overflow
tooltipX = Math.min(tooltipX, offsetX + caretX - tooltipWidth + arrowMinIndent); // Prevent right overflow
arrowX = offsetX + caretX - tooltipX;
}
let tooltipY;
if (isTimelineChart) {
// For timeline charts, always position tooltip below the chart with caret pointing to x-axis
const chartArea = context.chart.chartArea;
const canvasBottom = chartArea.bottom;
tooltipY = offsetY + canvasBottom + arrowSize + caretPadding;
// Ensure the arrow points to the correct X position
arrowX = tooltip.caretX - (tooltipX - offsetX);
} else {
tooltipY = offsetY + caretY;
switch (tooltip.yAlign) {
case "top": {
tooltipY += arrowSize + caretPadding;
break;
}
case "center": {
tooltipY -= tooltipHeight / 2;
if (tooltip.xAlign === "left") {
tooltipX += arrowSize;
} else if (tooltip.xAlign === "right") {
tooltipX -= arrowSize;
}
break;
}
case "bottom": {
tooltipY -= tooltipHeight + arrowSize + caretPadding;
break;
}
// No default
}
}
// Position tooltip and display
tooltipElement.style.top = `${tooltipY.toFixed(1)}px`;
tooltipElement.style.left = `${tooltipX.toFixed(1)}px`;
// Set arrow position
const arrowElement = tooltipElement.querySelector(".arrow");
let arrowLeftPosition = "";
if (arrowX !== undefined) {
// Calculate percentage X value depending on the tooltip's
// width to avoid hanging arrow out on tooltip width changes
const arrowXpercent = ((100 / tooltipWidth) * arrowX).toFixed(1);
arrowLeftPosition = `${arrowXpercent}%`;
}
arrowElement.style.left = arrowLeftPosition;
}
globalThis.doughnutTooltip = tooltipLabel => {
if (tooltipLabel.parsed === 0) {
return "";
}
// tooltipLabel.chart._metasets[0].total returns the total percentage of the shown slices
// to compensate rounding errors we round to one decimal
let percentageTotalShown = tooltipLabel.chart._metasets[0].total.toFixed(1);
const label = ` ${utils.escapeHtml(tooltipLabel.label)}`;
let itemPercentage;
// if we only show < 1% percent of all, show each item with two decimals
if (percentageTotalShown < 1) {
itemPercentage = tooltipLabel.parsed.toFixed(2);
} else {
// show with one decimal, but in case the item share is really small it could be rounded to 0.0
// we compensate for this
itemPercentage =
tooltipLabel.parsed.toFixed(1) === "0.0" ? "< 0.1" : tooltipLabel.parsed.toFixed(1);
}
// even if no doughnut slice is hidden, sometimes percentageTotalShown is slightly less than 100
// we therefore use 99.9 to decide if slices are hidden (we only show with 0.1 precision)
if (percentageTotalShown > 99.9) {
// All items shown
return `${label}: ${itemPercentage}%`;
}
// set percentageTotalShown again without rounding to account
// for cases where the total shown percentage would be <0.1% of all
percentageTotalShown = tooltipLabel.chart._metasets[0].total;
const percentageOfShownItems = ((tooltipLabel.parsed * 100) / percentageTotalShown).toFixed(1);
return (
`${label}:<br>• ${itemPercentage}% of all data<br>` +
`• ${percentageOfShownItems}% of shown items`
);
};
// chartjs plugin used by the custom doughnut legend
function getOrCreateLegendList(id) {
const legendContainer = document.getElementById(id);
let listContainer = legendContainer.querySelector("ul");
if (listContainer) {
return listContainer;
}
listContainer = document.createElement("ul");
legendContainer.append(listContainer);
return listContainer;
}