forked from pyrochlore/obsidian-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpie.ts
More file actions
665 lines (596 loc) · 20.5 KB
/
pie.ts
File metadata and controls
665 lines (596 loc) · 20.5 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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
import { Moment } from "moment";
import {
Datasets,
DataPoint,
RenderInfo,
PieInfo,
MonthInfo,
Dataset,
Size,
Transform,
ChartElements,
GraphType,
ValueType,
} from "./data";
import * as helper from "./helper";
import * as d3 from "d3";
import * as expr from "./expr";
import { pie } from "d3";
function setChartScale(
_canvas: HTMLElement,
chartElements: ChartElements,
renderInfo: RenderInfo
) {
let canvas = d3.select(_canvas);
let svg = chartElements.svg;
let svgWidth = parseFloat(svg.attr("width"));
let svgHeight = parseFloat(svg.attr("height"));
svg.attr("width", null)
.attr("height", null)
.attr("viewBox", `0 0 ${svgWidth} ${svgHeight}`)
.attr("preserveAspectRatio", "xMidYMid meet");
if (renderInfo.fitPanelWidth) {
canvas.style("width", "100%");
} else {
canvas.style(
"width",
(svgWidth * renderInfo.fixedScale).toString() + "px"
);
canvas.style(
"height",
(svgHeight * renderInfo.fixedScale).toString() + "px"
);
}
}
function createAreas(
chartElements: ChartElements,
canvas: HTMLElement,
renderInfo: RenderInfo,
pieInfo: PieInfo
): ChartElements {
// clean areas
d3.select(canvas).select("#svg").remove();
var props = Object.getOwnPropertyNames(chartElements);
for (var i = 0; i < props.length; i++) {
// d3.select(chartElements[props[i]]).remove();
delete chartElements[props[i]];
}
// console.log(chartElements);
// whole area for plotting, includes margins
let svg = d3
.select(canvas)
.append("svg")
.attr("id", "svg")
.attr(
"width",
renderInfo.dataAreaSize.width +
renderInfo.margin.left +
renderInfo.margin.right
)
.attr(
"height",
renderInfo.dataAreaSize.height +
renderInfo.margin.top +
renderInfo.margin.bottom
);
chartElements["svg"] = svg;
// graphArea, includes chartArea, title, legend
let graphArea = svg
.append("g")
.attr("id", "graphArea")
.attr(
"transform",
"translate(" +
renderInfo.margin.left +
"," +
renderInfo.margin.top +
")"
)
.attr("width", renderInfo.dataAreaSize.width + renderInfo.margin.right)
.attr(
"height",
renderInfo.dataAreaSize.height + renderInfo.margin.bottom
);
chartElements["graphArea"] = graphArea;
// dataArea, under graphArea, includes points, lines, xAxis, yAxis
let dataArea = graphArea
.append("g")
.attr("id", "dataArea")
.attr("width", renderInfo.dataAreaSize.width)
.attr("height", renderInfo.dataAreaSize.height);
chartElements["dataArea"] = dataArea;
return chartElements;
}
function renderTitle(
canvas: HTMLElement,
chartElements: ChartElements,
renderInfo: RenderInfo,
pieInfo: PieInfo
) {
// console.log("renderTitle");
// under graphArea
if (!renderInfo || !pieInfo) return;
if (!pieInfo.title) return;
let titleSize = helper.measureTextSize(pieInfo.title, "tracker-title");
// Append title
let title = chartElements.graphArea
.append("text")
.text(pieInfo.title) // pivot at center
.attr("id", "title")
.attr(
"transform",
"translate(" +
renderInfo.dataAreaSize.width / 2.0 +
"," +
titleSize.height / 2.0 +
")"
)
.attr("height", titleSize.height) // for later use
.attr("class", "tracker-title");
chartElements["title"] = title;
// Expand parent areas
helper.expandArea(chartElements.svg, 0, titleSize.height);
helper.expandArea(chartElements.graphArea, 0, titleSize.height);
// Move sibling areas
helper.moveArea(chartElements.dataArea, 0, titleSize.height);
return;
}
function renderLegend(
canvas: HTMLElement,
chartElements: ChartElements,
renderInfo: RenderInfo,
pieInfo: PieInfo
) {
// console.log("renderLegend");
// console.log(piInfo.legendPosition);
// console.log(piInfo.legendOrientation);
// Get chart elements
let svg = chartElements.svg;
let graphArea = chartElements.graphArea;
let dataArea = chartElements.dataArea;
let title = chartElements.title;
// Get element width and height
let titleHeight = 0.0;
if (title) {
titleHeight = parseFloat(title.attr("height"));
}
// Get names and their dimension
let names = pieInfo.dataName;
let nameSizes = names.map(function (n) {
return helper.measureTextSize(n, "tracker-legend-label");
});
let indMaxName = 0;
let maxNameWidth = 0.0;
for (let ind = 0; ind < names.length; ind++) {
if (nameSizes[ind].width > maxNameWidth) {
maxNameWidth = nameSizes[ind].width;
indMaxName = ind;
}
}
let maxName = names[indMaxName];
let characterWidth = maxNameWidth / maxName.length;
let nameHeight = nameSizes[indMaxName].height;
let numNames = names.length;
let xSpacing = 2 * characterWidth;
let ySpacing = nameHeight;
let markerWidth = 2 * characterWidth;
// Get legend width and height
let legendWidth = 0;
let legendHeight = 0;
if (pieInfo.legendOrientation === "vertical") {
legendWidth = xSpacing * 3 + markerWidth + maxNameWidth;
legendHeight = (numNames + 1) * ySpacing;
} else if (pieInfo.legendOrientation === "horizontal") {
legendWidth =
(2 * xSpacing + markerWidth) * numNames +
xSpacing +
d3.sum(nameSizes, function (s, i) {
return s.width;
});
legendHeight = ySpacing + nameHeight;
}
// console.log(
// `maxName: ${maxName}, characterWidth: ${characterWidth}, maxNameWidth: ${maxNameWidth}`
// );
// console.log(`xSpacing:${xSpacing}, numNames: ${numNames}, markerWidth: ${markerWidth}`);
// console.log(`legendWidth: ${legendWidth}, legendHeight: ${legendHeight}`);
// Calcualte lengendX and legendY
let legendX = 0.0; // relative to graphArea
let legendY = 0.0;
if (pieInfo.legendPosition === "top") {
// below title
legendX = renderInfo.dataAreaSize.width / 2.0 - legendWidth / 2.0;
legendY = titleHeight;
// Expand svg
helper.expandArea(svg, 0, legendHeight + ySpacing);
// Move dataArea down
helper.moveArea(dataArea, 0, legendHeight + ySpacing);
} else if (pieInfo.legendPosition === "bottom") {
// bellow x-axis label
legendX = renderInfo.dataAreaSize.width / 2.0 - legendWidth / 2.0;
legendY = titleHeight + renderInfo.dataAreaSize.height + ySpacing;
// Expand svg
helper.expandArea(svg, 0, legendHeight + ySpacing);
} else if (pieInfo.legendPosition === "left") {
legendX = 0;
legendY =
titleHeight +
renderInfo.dataAreaSize.height / 2.0 -
legendHeight / 2.0;
// Expand svg
helper.expandArea(svg, legendWidth + xSpacing, 0);
// Move dataArea right
helper.moveArea(dataArea, legendWidth + xSpacing, 0);
} else if (pieInfo.legendPosition === "right") {
legendX = renderInfo.dataAreaSize.width + xSpacing;
legendY =
titleHeight +
renderInfo.dataAreaSize.height / 2.0 -
legendHeight / 2.0;
// Expand svg
helper.expandArea(svg, legendWidth + xSpacing, 0);
} else {
return;
}
// console.log(`legendX: ${legendX}, legendY: ${legendY}`);
let legend = chartElements.graphArea
.append("g")
.attr("id", "legend")
.attr("transform", "translate(" + legendX + "," + legendY + ")");
// console.log('legendX: %d, legendY: %d', legendX, legendY);
let legendBg = legend
.append("rect")
.attr("class", "tracker-legend")
.attr("width", legendWidth)
.attr("height", legendHeight);
if (pieInfo.legendBgColor) {
legendBg.style("fill", pieInfo.legendBgColor);
}
if (pieInfo.legendBorderColor) {
legendBg.style("stroke", pieInfo.legendBorderColor);
}
let markerRadius = 5.0;
let firstMarkerX = xSpacing;
let firstMarkerY = nameHeight;
let firstLabelX = firstMarkerX + xSpacing + markerWidth; // xSpacing + 2 * xSpaing
let firstLabelY = firstMarkerY;
if (pieInfo.legendOrientation === "vertical") {
// points
legend
.selectAll("markers")
.data(names)
.enter()
.append("circle")
.attr("cx", firstMarkerX + markerWidth / 2.0)
.attr("cy", function (name: string, i: number) {
return firstMarkerY + i * ySpacing;
})
.attr("r", function (name: string, i: number) {
return markerRadius;
})
.style("fill", function (name: string, i: number) {
return pieInfo.dataColor[i];
});
// names
let nameLabels = legend
.selectAll("labels")
.data(names)
.enter()
.append("text")
.attr("x", firstLabelX)
.attr("y", function (name: string, i: number) {
return firstLabelY + i * ySpacing;
})
.text(function (name: string, i: number) {
return name;
})
.style("alignment-baseline", "middle")
.attr("class", "tracker-legend-label");
nameLabels.style("fill", function (name: string, i: number) {
return pieInfo.dataColor[i];
});
} else if (pieInfo.legendOrientation === "horizontal") {
let currRenderPosX = 0.0;
let currRenderPosX2 = 0.0;
// points
currRenderPosX = 0.0;
legend
.selectAll("markers")
.data(names)
.enter()
.append("circle")
.attr("cx", function (name: string, i: number) {
if (i === 0) {
currRenderPosX = firstMarkerX + markerWidth / 2.0;
} else {
currRenderPosX +=
nameSizes[i].width + xSpacing + markerWidth + xSpacing;
}
return currRenderPosX;
})
.attr("cy", firstMarkerY)
.attr("r", function (name: string, i: number) {
return markerRadius;
})
.style("fill", function (name: string, i: number) {
return pieInfo.dataColor[i];
});
// names
currRenderPosX = 0.0;
let nameLabels = legend
.selectAll("labels")
.data(names)
.enter()
.append("text")
.attr("x", function (name: string, i: number) {
if (i === 0) {
currRenderPosX = firstLabelX;
} else {
currRenderPosX +=
nameSizes[i].width + xSpacing + markerWidth + xSpacing;
}
return currRenderPosX;
})
.attr("y", firstLabelY)
.text(function (name: string, i: number) {
return name;
})
.style("alignment-baseline", "middle")
.attr("class", "tracker-legend-label");
nameLabels.style("fill", function (name: string, i: number) {
return pieInfo.dataColor[i];
});
}
}
function renderPie(
canvas: HTMLElement,
chartElements: ChartElements,
renderInfo: RenderInfo,
pieInfo: PieInfo
) {
// console.log("renderPie");
// console.log(renderInfo);
let errorMessage = "";
let radius = renderInfo.dataAreaSize.width * 0.5;
let outterRadius = radius * 0.7;
let innerRadius = outterRadius * pieInfo.ratioInnerRadius;
// values
let values: Array<number> = [];
for (let strExpr of pieInfo.data) {
let retValue = expr.resolveValue(strExpr, renderInfo);
if (typeof retValue === "string") {
errorMessage = retValue;
break;
} else if (typeof retValue === "number") {
values.push(retValue);
}
}
if (errorMessage !== "") {
return errorMessage;
}
// console.log(values);
// labels
let labels: Array<string> = [];
for (let strExpr of pieInfo.label) {
let retLabel = expr.resolveTemplate(strExpr, renderInfo);
// console.log(retLabel);
if (retLabel.startsWith("Error")) {
errorMessage = retLabel;
break;
}
labels.push(retLabel);
}
if (errorMessage !== "") {
return errorMessage;
}
// console.log(labels);
// hideLabelLessThan
let hideLabelLessThan = pieInfo.hideLabelLessThan;
// label sizes
let labelSizes = labels.map(function (n) {
return helper.measureTextSize(n, "tracker-tick-label");
});
// extLabel
let extLabels: Array<string> = [];
for (let strExpr of pieInfo.extLabel) {
let retExtLabel = expr.resolveTemplate(strExpr, renderInfo);
if (retExtLabel.startsWith("Error")) {
errorMessage = retExtLabel;
break;
}
extLabels.push(retExtLabel);
}
if (errorMessage !== "") {
return errorMessage;
}
// console.log(extLabels);
// extLabel sizes
let extLabelSizes = extLabels.map(function (n) {
return helper.measureTextSize(n, "tracker-pie-label");
});
// console.log(extLabelSizes);
let showExtLabelOnlyIfNoLabel = pieInfo.showExtLabelOnlyIfNoLabel;
// scale
let colorScale = d3.scaleOrdinal().range(pieInfo.dataColor);
let sectorsGroup = chartElements.dataArea.append("g");
sectorsGroup.attr("transform", function () {
let strTranslate =
"translate(" +
renderInfo.dataAreaSize.width * 0.5 +
"," +
renderInfo.dataAreaSize.height * 0.5 +
")";
return strTranslate;
});
let pie = d3.pie();
let pieValues = pie(values);
let sectors = sectorsGroup
.selectAll("sector")
.data(pieValues)
.enter()
.append("g")
.attr("class", "sector");
let arc = d3.arc().innerRadius(innerRadius).outerRadius(outterRadius);
var hiddenArc = d3
.arc()
.innerRadius(radius * 0.9)
.outerRadius(radius * 0.9);
let sectorPaths = sectors
.append("path")
.attr("fill", function (d: any, i: number) {
return colorScale(i.toString());
})
.attr("d", arc);
function isLabelHidden(arcObj: any) {
// console.log(`start/end: ${arcObj.startAngle}/${arcObj.endAngle}`);
let fraction = (arcObj.endAngle - arcObj.startAngle) / (2.0 * Math.PI);
if (fraction < hideLabelLessThan) {
return true;
}
return false;
}
// label elements
let labelElements = sectorsGroup
.selectAll("label")
.data(pie(values))
.enter()
.append("text")
.text(function (arcObj: any, i: number) {
if (isLabelHidden(arcObj)) {
return "";
}
return labels[i];
})
.attr("transform", function (d: any) {
return (
"translate(" +
arc.centroid(d)[0] +
"," +
arc.centroid(d)[1] +
")"
);
})
.style("text-anchor", "middle")
.attr("class", "tracker-pie-label");
function getMidAngle(arcObj: any) {
return arcObj.startAngle + (arcObj.endAngle - arcObj.startAngle) / 2;
}
// external label elements
let extLabelElements = sectorsGroup
.selectAll("extLabel")
.data(pieValues)
.enter()
.append("text")
.text(function (arcObj: any, i: number) {
if (showExtLabelOnlyIfNoLabel) {
if (labels[i] === "" || isLabelHidden(arcObj)) {
return extLabels[i];
}
return "";
} else {
return extLabels[i];
}
})
.attr("transform", function (arcObj: any, i: number) {
let posLabel = hiddenArc.centroid(arcObj);
let midAngle = getMidAngle(arcObj);
posLabel[0] =
(radius * 0.99 - extLabelSizes[i].width) *
(midAngle < Math.PI ? 1 : -1);
return "translate(" + posLabel[0] + "," + posLabel[1] + ")";
})
.style("text-anchor", function (arcObj: any) {
let midAngle = getMidAngle(arcObj);
return midAngle < Math.PI ? "start" : "end";
})
.attr("class", "tracker-pie-label");
function getPointsForConnectionLines(arcObj: any, i: number) {
let labelWidth = labelSizes[i].width;
let extLabelWidth = extLabelSizes[i].width;
let labelHidden = isLabelHidden(arcObj);
let midAngle = getMidAngle(arcObj);
let posLabel = arc.centroid(arcObj); // line insertion in the slice
let posMiddle = hiddenArc.centroid(arcObj); // line break: we use the other arc generator that has been built only for that
let posExtLabel = hiddenArc.centroid(arcObj); // Label position = almost the same as posB
// console.log(labels[i]);
// console.log(`label/middle/extLabel: ${posLabel}/${posMiddle}/${posExtLabel}`);
let distMiddleToLabel = Math.sqrt(
(posMiddle[0] - posLabel[0]) ** 2 +
(posMiddle[1] - posLabel[1]) ** 2
);
if (labels[i] !== "") {
// shift posLabel, toward the middle point
posLabel[0] =
posLabel[0] +
((posMiddle[0] - posLabel[0]) * labelWidth) / distMiddleToLabel;
posLabel[1] =
posLabel[1] +
((posMiddle[1] - posLabel[1]) * labelWidth) / distMiddleToLabel;
// shift posExtLabel
posExtLabel[0] =
(radius * 0.99 - extLabelWidth - 3) *
(midAngle < Math.PI ? 1 : -1); // multiply by 1 or -1 to put it on the right or on the left
}
distMiddleToLabel = Math.sqrt(
(posMiddle[0] - posLabel[0]) ** 2 +
(posMiddle[1] - posLabel[1]) ** 2
);
let distExtLabelToLabel = Math.sqrt(
(posExtLabel[0] - posLabel[0]) ** 2 +
(posExtLabel[1] - posLabel[1]) ** 2
);
if (distMiddleToLabel > distExtLabelToLabel) {
// console.log("two points");
return [posLabel, posExtLabel];
}
return [posLabel, posMiddle, posExtLabel];
}
// Add lines between sectors and external labels
let lines = sectorsGroup
.selectAll("line")
.data(pieValues)
.enter()
.append("polyline")
.attr("stroke", "black")
.style("fill", "none")
.attr("stroke-width", 1)
.attr("points", function (arcObj: any, i: number) {
if (showExtLabelOnlyIfNoLabel) {
if (labels[i] === "" || isLabelHidden(arcObj)) {
if (extLabels[i] !== "") {
return getPointsForConnectionLines(arcObj, i);
}
}
} else {
if (extLabels[i] !== "") {
return getPointsForConnectionLines(arcObj, i);
}
}
})
.attr("class", "tracker-axis");
}
export function renderPieChart(
canvas: HTMLElement,
renderInfo: RenderInfo,
pieInfo: PieInfo
) {
// console.log("renderPieChart");
// console.log(renderInfo);
if (!renderInfo || !pieInfo) return;
// return "Under construction";
let chartElements: ChartElements = {};
chartElements = createAreas(chartElements, canvas, renderInfo, pieInfo);
// Set default dataColor if no dataColor provided
let defaultDataColor = d3.schemeSpectral[pieInfo.dataColor.length];
for (let i = 0; i < pieInfo.dataColor.length; i++) {
if (pieInfo.dataColor[i] === null) {
pieInfo.dataColor[i] = defaultDataColor[i];
}
}
renderTitle(canvas, chartElements, renderInfo, pieInfo);
renderPie(canvas, chartElements, renderInfo, pieInfo);
if (pieInfo.showLegend) {
renderLegend(canvas, chartElements, renderInfo, pieInfo);
}
setChartScale(canvas, chartElements, renderInfo);
}