Debian Codegraph @

debian/missing-sources/d3pie.js

raw
1 /*!
2 * rspamd-D3Pie 1.1.2 (https://github.com/moisseev/rspamd-D3Pie)
3 * Copyright (c) 2022, Alexander Moisseev, BSD 2-Clause
4 */
5
6 /* exported D3Pie */
7 function D3Pie (id, options) {
8 "use strict";
9
10 // Validate ID to prevent CSS selector issues
11 if (typeof id !== "string" || id.length === 0) throw new Error("D3Pie: id must be a non-empty string");
12 // Only allow: letters, underscores, hyphens at start; then any word chars or hyphens
13 if (!(/^[a-zA-Z_-][\w-]*$/u).test(id)) {
14 throw new Error("D3Pie: id must start with a letter, underscore, or hyphen, and contain only " +
15 "alphanumeric characters, hyphens (-), and underscores (_). Got: \"" + id + "\"");
16 }
17
18 const opts = $.extend(true, {
19 canvasPadding: 5,
20 cornerRadius: 3,
21 duration: 1250,
22 gradient: {
23 enabled: true,
24 percentage: 100
25 },
26 labels: {
27 inner: {
28 hideWhenLessThanPercentage: 4,
29 offset: 0.15
30 },
31 outer: {
32 collideHeight: 13,
33 format: "label",
34 pieDistance: 30
35 }
36 },
37 padAngle: 0.01,
38 pieCenterOffset: {
39 x: 0,
40 y: 0
41 },
42 size: {
43 canvasHeight: 400,
44 canvasWidth: 600,
45 pieInnerRadius: "20%",
46 pieOuterRadius: "85%"
47 },
48 title: "",
49 total: {
50 enabled: false
51 }
52 }, options);
53
54 // Validate options to prevent calculation errors and silent failures
55 const errors = [];
56
57 // Helper function to get nested option value by path
58 function getOptionValue (path) {
59 const keys = path.split(".");
60 let value = opts;
61 for (const key of keys) {
62 value = value[key];
63 }
64 return value;
65 }
66
67 // Validate numeric options with min/max constraints
68 function validate (path, constraints) {
69 const value = getOptionValue(path);
70 const num = parseFloat(value);
71 if (!isFinite(num)) {
72 errors.push(path + " must be a finite number, got: " + value);
73 return;
74 }
75 if (typeof constraints.min !== "undefined" && num < constraints.min) {
76 errors.push(path + " must be >= " + constraints.min + ", got: " + num);
77 return;
78 }
79 if (typeof constraints.max !== "undefined" && num > constraints.max) {
80 errors.push(path + " must be <= " + constraints.max + ", got: " + num);
81 }
82 }
83
84 validate("canvasPadding", {min: 0});
85 validate("cornerRadius", {min: 0});
86 validate("duration", {min: 0});
87 validate("gradient.percentage", {min: 0, max: 100});
88 validate("labels.inner.hideWhenLessThanPercentage", {min: 0, max: 100});
89 validate("labels.inner.offset", {min: -1, max: 1});
90 validate("labels.outer.collideHeight", {min: 1});
91 validate("labels.outer.pieDistance", {min: 0});
92 validate("padAngle", {min: 0, max: 2 * Math.PI});
93 validate("pieCenterOffset.x", {});
94 validate("pieCenterOffset.y", {});
95 validate("size.canvasHeight", {min: 50});
96 validate("size.canvasWidth", {min: 50});
97
98 // Validate radius options (can be number or percentage string)
99 function validateRadius (path) {
100 const value = getOptionValue(path);
101
102 // Allow number or percentage string
103 if (typeof value === "number") {
104 if (!isFinite(value) || value < 0) {
105 errors.push(path + " must be a non-negative number, got: " + value);
106 }
107 } else if (typeof value === "string") {
108 const match = (/^(?<pct>\d+)%$/u).exec(value);
109 if (!match) {
110 errors.push(path + " must be a number or percentage string (e.g. \"85%\"), got: " + value);
111 } else {
112 const percentage = parseInt(match.groups.pct, 10);
113 if (percentage > 99) {
114 errors.push(path + " percentage must be 0-99, got: " + percentage + "%");
115 }
116 }
117 } else {
118 errors.push(path + " must be a number or percentage string, got: " + typeof value);
119 }
120 }
121
122 validateRadius("size.pieOuterRadius");
123 validateRadius("size.pieInnerRadius");
124
125 // Validate enum options
126 function validateEnum (path, allowedValues) {
127 const value = getOptionValue(path);
128
129 if (!allowedValues.includes(value)) {
130 const allowedStr = allowedValues.map((v) => "\"" + v + "\"").join(", ");
131 errors.push(path + " must be one of [" + allowedStr + "], got: \"" + value + "\"");
132 }
133 }
134
135 validateEnum("labels.outer.format", ["none", "label"]);
136
137 if (errors.length > 0) throw new Error("D3Pie configuration errors:\n - " + errors.join("\n - "));
138
139 this.destroy = function () {
140 // Remove all event listeners before removing elements
141 d3.select("#" + id).selectAll("*")
142 .on("click", null)
143 .on("mousemove", null)
144 .on("mouseover", null)
145 .on("mouseout", null);
146
147 // Remove SVG and tooltip elements
148 d3.selectAll("#" + id + " svg, #" + id + "-tooltip").remove();
149 };
150 this.destroy();
151
152 const svg = d3.select("#" + id).append("svg")
153 .attr("class", "d3pie")
154 .attr("width", opts.size.canvasWidth)
155 .attr("height", opts.size.canvasHeight);
156
157 let titleHeight = 0;
158 if (opts.title !== "") {
159 const title = svg.append("svg:text")
160 .attr("class", "chart-title")
161 .attr("x", (opts.size.canvasWidth / 2));
162 title.append("tspan")
163 .text(opts.title + " ");
164 titleHeight = title.node().getBBox().height;
165 title.attr("y", titleHeight + opts.canvasPadding);
166 }
167
168 const g = svg.append("g")
169 .attr("transform", "translate(" + ((opts.size.canvasWidth / 2) + opts.pieCenterOffset.x) + "," +
170 ((opts.size.canvasHeight / 2) + (titleHeight / 2) + opts.pieCenterOffset.y + ")"));
171
172 const currentData = {};
173 const outerLabel = {};
174
175 const {outerRadius, innerRadius} = (function () {
176 function pieRadius (r, whole) {
177 if (!(/%/u).test(r)) return parseInt(r, 10);
178 const decimal = Math.max(0, Math.min(99, parseInt(r.replace(/[\D]/u, ""), 10))) / 100;
179 return Math.floor(whole * decimal);
180 }
181
182 const width = opts.size.canvasWidth - (2 * opts.canvasPadding);
183 const height = opts.size.canvasHeight - (2 * opts.canvasPadding) - titleHeight;
184 let overallRadius = Math.min(width, height) / 2;
185 if (opts.labels.outer.format !== "none") {
186 const pieDistance = parseInt(opts.labels.outer.pieDistance, 10);
187 if (overallRadius > pieDistance) overallRadius -= pieDistance;
188 }
189 const oR = pieRadius(opts.size.pieOuterRadius, overallRadius);
190 const iR = pieRadius(opts.size.pieInnerRadius, oR);
191 return {outerRadius: oR, innerRadius: iR};
192 }());
193
194 const labelRadius = outerRadius + opts.labels.outer.pieDistance;
195
196 const lineGenerator = d3.line()
197 .curve(d3.curveCatmullRomOpen);
198
199 const tooltip = d3.select("body").append("div")
200 .attr("id", id + "-tooltip")
201 .attr("class", "d3pie-tooltip");
202 const tooltipText = tooltip
203 .append("span")
204 .attr("id", id + "-tooltip-text");
205
206 function attachListeners (selection) {
207 selection
208 .on("mouseover", function (_, d) {
209 const tot = tooltip.datum().total;
210 const percentage = (tot) ? Math.round(100 * d.data.value / tot) : NaN;
211 if (d.data.value) {
212 tooltip
213 .transition().duration(300)
214 .style("opacity", 1);
215 tooltipText
216 .text(d.data.label + ((tot) ? ": " + d.data.value + " (" + percentage + "%)" : ""));
217 } else {
218 tooltip.transition().duration(300).style("opacity", 0);
219 }
220 // eslint-disable-next-line no-invalid-this
221 tooltip.each(function (datum) { datum.height = this.getBoundingClientRect().height; });
222 })
223 .on("mouseout", function () {
224 tooltip.transition().duration(300).style("opacity", 0);
225 })
226 .on("mousemove", (event) => {
227 const {pageX, pageY} = event;
228 tooltip
229 .style("left", (pageX) + "px")
230 .style("top", function (d) { return (pageY - d.height - 2) + "px"; });
231 });
232 }
233
234 // Slices render in this group (created first so totalG renders on top)
235 const slicesGroup = g.append("g");
236
237 const totalG = g.append("g");
238 attachListeners(totalG);
239 totalG.append("circle")
240 .attr("r", innerRadius)
241 .style("opacity", 0);
242 if (opts.total.enabled) {
243 const totalText = totalG.append("text")
244 .attr("class", "total-text");
245 totalText.append("tspan")
246 .attr("class", "total-value")
247 .style("font-size", (0.6 * innerRadius) + "px");
248 totalText.append("tspan")
249 .attr("x", "0")
250 .attr("dy", 0.5 * innerRadius)
251 .text((typeof opts.total.label !== "undefined") ? opts.total.label : "Total");
252 }
253
254 const defs = svg.append("defs");
255
256 // Mask to prevent color bleeding artifact in donut hole
257 // When padAngle is large and slice angle > π, the inner arc wraps > 180° and renders through center.
258 // This is D3's arc geometry behavior and cannot be fixed without changing the arc itself.
259 // Reproduces with: padAngle ≥ 1.0, slice percentage > 50%
260 // Note: With extreme padAngle values, artifacts may still be visible through gaps between other slices
261 if (innerRadius > 0) {
262 const mask = defs.append("mask")
263 .attr("id", id + "-donut-mask");
264 // White area = visible, black area = hidden
265 // Mask coordinates are relative to the masked element (slicesGroup is at 0,0 in transformed g)
266 mask.append("rect")
267 .attr("x", -opts.size.canvasWidth)
268 .attr("y", -opts.size.canvasHeight)
269 .attr("width", opts.size.canvasWidth * 2)
270 .attr("height", opts.size.canvasHeight * 2)
271 .attr("fill", "white");
272 // Black circle in center = hide slices there
273 mask.append("circle")
274 .attr("r", innerRadius)
275 .attr("fill", "black");
276
277 // Apply mask only to slicesGroup, not to totalG (so text remains visible)
278 slicesGroup.attr("mask", "url(#" + id + "-donut-mask)");
279 }
280
281 this.data = function (arg) {
282 let data = $.extend(true, [], arg);
283
284 // Validate that labels are unique and non-empty (required for D3 keyed data binding)
285 const labels = new Set();
286 for (let i = 0; i < data.length; i += 1) {
287 const item = data[i];
288 if (!item || typeof item.label !== "string" || item.label === "") {
289 throw new Error("D3Pie: data[" + i + "] must have a non-empty string 'label' property");
290 }
291 if (labels.has(item.label)) {
292 throw new Error("D3Pie: duplicate label \"" + item.label + "\" found. All labels must be unique.");
293 }
294 labels.add(item.label);
295 }
296
297 const nodes = [];
298
299 const total = data.reduce(function (a, b) {
300 return a + (b.value || 0);
301 }, 0);
302 tooltip.datum({total});
303 totalG.datum({
304 data: {
305 label: (typeof opts.total.label !== "undefined") ? opts.total.label : "Total",
306 value: total
307 }
308 });
309 if (opts.total.enabled) totalG.select(".total-value").text(d3.format(".3~s")(total));
310
311 // Add placeholder path for empty pie chart
312 data.unshift({
313 label: "undefined",
314 color: opts.gradient.enabled ? "steelblue" : "#ecf1f5",
315 value: (total === 0) ? 1 : 0
316 });
317
318 const colorScale = d3.scaleOrdinal(d3.schemeSet1);
319 function pathColor (d, i) {
320 return (typeof d !== "undefined" &&
321 typeof d.color !== "undefined")
322 ? d.color
323 : colorScale(i);
324 }
325
326 function midpoint (args, innerR, outerR = innerR) {
327 return d3.arc().innerRadius(innerR).outerRadius(outerR).centroid(args);
328 }
329
330 function interpolate (d) { return d3.interpolate(currentData[d.data.label], d); }
331
332 function arcTweenSlice (d) {
333 return function (t) {
334 return d3.arc().padAngle(opts.padAngle).cornerRadius(opts.cornerRadius)
335 .innerRadius(innerRadius).outerRadius(outerRadius)(interpolate(d)(t));
336 };
337 }
338
339 function arcTweenInnerlabel (d) {
340 return function (t) {
341 return "translate(" + midpoint(
342 interpolate(d)(t),
343 innerRadius * (1 - opts.labels.inner.offset),
344 outerRadius * (1 + opts.labels.inner.offset)
345 ) + ")";
346 };
347 }
348
349 function limit (y) {
350 // Avoid 0 and pi positions to prevent changing half-plane
351 const boundary = labelRadius - 0.1;
352 return Math.max(-boundary, Math.min(boundary, y));
353 }
354
355 function arcTweenOuterlabel (d, i) {
356 function newAngle () {
357 // Node Y may be slightly outside of the circle as the bounding force is not a hard limit.
358 const y = limit(nodes[i].y);
359 // Calculate the actual X-position with an equation of a circle centered at the origin (0, 0).
360 let ax = Math.sqrt(Math.pow((labelRadius), 2) - Math.pow(y, 2));
361 if ((d.endAngle + d.startAngle) / 2 > Math.PI) ax *= -1;
362
363 let angle = (Math.PI / 2) - Math.atan2(-y, ax);
364 if (angle < 0) angle += 2 * Math.PI;
365
366 return {startAngle: angle, endAngle: angle};
367 }
368
369 outerLabel[d.data.label].newAngle = newAngle();
370 const interpolateOuterLabel = d3.interpolate(
371 outerLabel[d.data.label].currentAngle,
372 outerLabel[d.data.label].newAngle
373 );
374
375 return function (t) {
376 const position = midpoint(interpolateOuterLabel(t), labelRadius);
377 const [ax, y] = position;
378
379 const linkDistance = 5;
380 const label = (ax > 0)
381 ? {dx: linkDistance, textAnchor: "start"}
382 : {dx: -linkDistance, textAnchor: "end"};
383
384 d3.select(slicesGroup.selectAll(".link").nodes()[i])
385 .datum([
386 midpoint(interpolate(d)(t), outerRadius),
387 midpoint(interpolate(d)(t), outerRadius + linkDistance),
388 [ax, y],
389 [ax + label.dx, y]
390 ])
391 .attr("d", lineGenerator);
392
393 d3.select(slicesGroup.selectAll(".outer-label").nodes()[i])
394 .attr("dx", label.dx)
395 .style("text-anchor", label.textAnchor);
396
397 return "translate(" + position + ")";
398 };
399 }
400
401 const transition = d3.transition().duration(opts.duration);
402
403 if (opts.gradient.enabled) {
404 const gradient = defs.selectAll("radialGradient").data(data, function (d) { return d.label; });
405
406 const gradientEnter = gradient.enter().append("radialGradient")
407 .attr("gradientUnits", "userSpaceOnUse")
408 .attr("cx", 0)
409 .attr("cy", 0)
410 .attr("r", "120%")
411 .attr("id", function (d, i) { return id + "-grad" + i; });
412 gradientEnter.append("stop")
413 .attr("class", "grad-stop-0")
414 .style("stop-color", function (d, i) { return pathColor(d, i); });
415 gradientEnter.append("stop")
416 .attr("class", "grad-stop-1")
417 .attr("offset", opts.gradient.percentage + "%");
418
419 defs.selectAll("radialGradient").select(".grad-stop-0")
420 .transition(transition)
421 .style("stop-color", function (d, i) { return pathColor(d, i); });
422 }
423
424 function key (d) { return d.data.label; }
425
426 const pie = d3.pie()
427 .sort(null)
428 .value(function (d) { return d.value; });
429
430 const sliceG = slicesGroup.selectAll(".slice-g").data(pie(data), key);
431
432 const sliceGEnter = sliceG.enter().append("g")
433 .attr("class", "slice-g");
434 attachListeners(sliceGEnter);
435
436 sliceGEnter
437 .append("path")
438 .attr("id", function (d, i) { return id + "-slice" + i; })
439 .attr("class", "slice")
440 .attr("fill", function (d, i) {
441 return opts.gradient.enabled
442 ? "url(#" + id + "-grad" + i + ")"
443 : pathColor(d.data, i);
444 });
445
446 sliceG
447 .exit()
448 .each(function (d) {
449 // Find by label instead of using exit selection index to avoid array corruption
450 const dataItem = data.find(function (item) { return item.label === d.data.label; });
451 // Set value to 0 to animate shrinking, preserving other properties (color, etc.)
452 if (dataItem) dataItem.value = 0;
453 });
454
455 pie(data).forEach(function (d, i) {
456 if (typeof currentData[d.data.label] === "undefined") {
457 const a = (i) ? currentData[pie(data)[i - 1].data.label].endAngle : 0;
458 currentData[d.data.label] = {startAngle: a, endAngle: a};
459 }
460 });
461
462 slicesGroup.selectAll(".slice")
463 .data(pie(data), key)
464 .transition(transition)
465 .attrTween("d", arcTweenSlice)
466 .end()
467 .then(function () {
468 data = data.filter(function (d, i) { return (i === 0 || d.value); });
469
470 defs.selectAll("radialGradient").data(data, function (d) { return d.label; }).exit().remove();
471 slicesGroup.selectAll(".slice-g").data(pie(data), key).exit()
472 .each(function (d) {
473 delete currentData[d.data.label];
474 delete outerLabel[d.data.label];
475 })
476 .remove();
477
478 for (const d of pie(data)) {
479 currentData[d.data.label] = d;
480 if (opts.labels.outer.format !== "none") {
481 outerLabel[d.data.label].currentAngle = outerLabel[d.data.label].newAngle;
482 }
483 }
484
485 // Ensure exactly one element has the 'first-slice' class:
486 // remove from all, then set on the first .slice-g in DOM order.
487 slicesGroup.selectAll(".slice-g").classed("first-slice", false);
488 const firstSlice = slicesGroup.select(".slice-g");
489 if (!firstSlice.empty()) firstSlice.classed("first-slice", true);
490 })
491 .catch((error) => {
492 // Interrupted transitions reject with pie state object - ignore these, log real errors
493 // Transition states have startAngle/endAngle properties from d3.pie() data
494 if (error && typeof error === "object" && "startAngle" in error && "endAngle" in error) return;
495 console.error("D3Pie error:", error); // eslint-disable-line no-console
496 });
497
498
499 sliceGEnter.append("text")
500 .attr("class", "inner-label")
501 .attr("dy", ".35em");
502
503 function opacityTweenInnerlabels (d) {
504 if (!d.data.value) return function () { return 0; };
505 return function (t) {
506 const o = interpolate(d)(t);
507 const percentage = 100 * (o.endAngle - o.startAngle) / (2 * Math.PI);
508 return percentage < opts.labels.inner.hideWhenLessThanPercentage ? 0 : 1;
509 };
510 }
511
512 slicesGroup.selectAll(".inner-label").data(pie(data), key)
513 .text(function (d) {
514 return (d.data.label === "undefined")
515 ? "undefined"
516 : Math.round(100 * d.data.value / total) + "%";
517 })
518 .transition(transition)
519 .attrTween("opacity", opacityTweenInnerlabels)
520 .attrTween("transform", arcTweenInnerlabel);
521
522
523 if (opts.labels.outer.format !== "none") {
524 pie(data).forEach(function (d, i) {
525 if (typeof outerLabel[d.data.label] === "undefined") {
526 const a = (i) ? currentData[pie(data)[i - 1].data.label].endAngle : 0;
527 outerLabel[d.data.label] = {
528 currentAngle: {startAngle: a, endAngle: a},
529 newAngle: {startAngle: a, endAngle: a}
530 };
531 }
532
533 let fx = 0;
534 const [x, y] = midpoint(d, labelRadius);
535 if (d.data.value) {
536 fx = (x >= 0) ? opts.labels.outer.collideHeight : -opts.labels.outer.collideHeight;
537 }
538 nodes.push({fx, y});
539 });
540 d3.forceSimulation(nodes).alphaMin(0.5)
541 .force("collide", d3.forceCollide(opts.labels.outer.collideHeight / 2))
542 // Custom force to keep all nodes on a circle.
543 .force("boundY", function () {
544 for (const node of nodes) {
545 // Constrain the Y-position of the node to keep it on a circle.
546 node.y = limit(node.y);
547 }
548 })
549 .tick(30);
550
551 const outerLabelsGEnter = sliceGEnter
552 .append("g")
553 .attr("class", "outer-label-g");
554
555 outerLabelsGEnter.append("text")
556 .attr("class", "outer-label")
557 .attr("dy", ".35em")
558 .text(key);
559
560 outerLabelsGEnter.append("path")
561 .attr("class", "link");
562
563 slicesGroup.selectAll(".outer-label-g").data(pie(data), key)
564 .transition(transition)
565 .style("opacity", function (d, i) { return (i && d.value) ? 1 : 0; })
566 // eslint-disable-next-line no-invalid-this
567 .each(function (d, i) { $(this).children(".link").attr("stroke", pathColor(d.data, i)); });
568
569 slicesGroup.selectAll(".outer-label").data(pie(data), key)
570 .transition(transition)
571 .attrTween("transform", arcTweenOuterlabel);
572 }
573 };
574 }