-
Notifications
You must be signed in to change notification settings - Fork 185
/
base-axis-chart.ts
649 lines (530 loc) · 18.3 KB
/
base-axis-chart.ts
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
// D3 Imports
import {
mouse,
select
} from "d3-selection";
import { scaleBand, scaleLinear } from "d3-scale";
import { axisBottom, axisLeft, axisRight } from "d3-axis";
import { min, max } from "d3-array";
import { BaseChart } from "./base-chart";
import * as Configuration from "./configuration";
import { Tools } from "./tools";
export class BaseAxisChart extends BaseChart {
x: any;
y: any;
y2: any;
thresholdDimensions: any;
constructor(holder: Element, configs: any) {
super(holder, configs);
const { axis } = configs.options;
if (axis) {
this.x = axis.x;
this.y = axis.y;
this.y2 = axis.y2;
}
}
setSVG(): any {
super.setSVG();
this.container.classed("chart-axis", true);
this.innerWrap.append("g")
.attr("class", "x grid");
this.innerWrap.append("g")
.attr("class", "y grid");
return this.svg;
}
initialDraw(data?: any) {
if (data) {
this.displayData = data;
}
// If an axis exists
const xAxisRef = select(this.holder).select(".axis.x");
if (!xAxisRef.node()) {
this.setSVG();
// Scale out the domains
// Set the x & y axis as well as their labels
this.setXScale();
this.setXAxis();
this.setYScale();
this.setYAxis();
// Draw the x & y grid
this.drawXGrid();
this.drawYGrid();
this.addOrUpdateLegend();
} else {
const holderRef = select(this.holder);
this.innerWrap = holderRef.select("g.inner-wrap");
this.svg = holderRef.select("svg.chart-svg");
}
this.draw();
this.addDataPointEventListener();
}
update() {
this.displayData = this.updateDisplayData();
this.updateXandYGrid();
this.setXScale();
this.setXAxis();
this.setYScale();
this.setYAxis();
this.interpolateValues(this.displayData);
}
updateDisplayData() {
const oldData = Tools.clone(this.data);
const activeLegendItems = this.getActiveLegendItems();
// Get new data by filtering the data based off of the legend
const newDisplayData = Object.assign({}, oldData);
if (this.getLegendType() === Configuration.legend.basedOn.SERIES) {
newDisplayData.datasets = oldData.datasets.filter(dataset => {
// If this datapoint is active on the legend
const activeSeriesItemIndex = activeLegendItems.indexOf(dataset.label);
return activeSeriesItemIndex !== -1;
});
} else {
const dataIndeciesToRemove = [];
newDisplayData.labels = oldData.labels.filter((label, index) => {
// If this datapoint is active on the legend
const activeSeriesItemIndex = activeLegendItems.indexOf(label);
if (activeSeriesItemIndex === -1) {
dataIndeciesToRemove.push(index);
}
return activeSeriesItemIndex !== -1;
});
if (dataIndeciesToRemove.length > 0) {
newDisplayData.datasets = oldData.datasets.map(dataset => {
dataset.data = dataset.data.filter((dataPoint, i) => {
return dataIndeciesToRemove.indexOf(i) === -1;
});
return dataset;
});
}
}
return newDisplayData;
}
addLabelsToDataPoints(d, index) {
const { datasets } = this.displayData;
return datasets.map(dataset => ({
label: d,
datasetLabel: dataset.label,
value: dataset.data[index]
}));
}
draw() {
console.warn("You should implement your own `draw()` function.");
}
interpolateValues(newData: any) {
console.warn("You should implement your own `interpolateValues()` function.");
}
/**************************************
* Computations/Calculations *
*************************************/
// TODO - Refactor
getChartSize(container = this.container) {
let ratio, marginForLegendTop;
if (container.node().clientWidth > Configuration.charts.widthBreak) {
ratio = Configuration.charts.magicRatio;
marginForLegendTop = 0;
} else {
marginForLegendTop = Configuration.charts.marginForLegendTop;
ratio = 1;
}
// Store computed actual size, to be considered for change if chart does not support axis
const marginsToExclude = Configuration.charts.margin.left + Configuration.charts.margin.right;
const computedChartSize = {
height: container.node().clientHeight - marginForLegendTop,
width: (container.node().clientWidth - marginsToExclude) * ratio
};
return computedChartSize;
}
resizeChart() {
// Reposition the legend
this.positionLegend();
if (this.innerWrap.select(".axis-label.x").nodes().length > 0 && this.options.scales.x.title) {
this.repositionXAxisTitle();
}
this.dispatchEvent("resize");
}
/**************************************
* Axis & Grids *
*************************************/
setXScale(xScale?: any) {
if (xScale) {
this.x = xScale;
} else {
const { bar: margins } = Configuration.charts.margin;
const { scales } = this.options;
const chartSize = this.getChartSize();
const width = chartSize.width - margins.left - margins.right;
this.x = scaleBand().rangeRound([0, width]).padding(Configuration.scales.x.padding);
this.x.domain(this.displayData.labels);
}
}
setXAxis(noAnimation?: boolean) {
const { bar: margins } = Configuration.charts.margin;
const chartSize = this.getChartSize();
const height = chartSize.height - margins.top - margins.bottom;
const t = noAnimation ? this.getInstantTransition() : this.getDefaultTransition();
const xAxis = axisBottom(this.x)
.tickSize(0)
.tickSizeOuter(0);
let xAxisRef = this.svg.select("g.x.axis");
// If the <g class="x axis"> exists in the chart SVG, just update it
if (xAxisRef.nodes().length > 0) {
xAxisRef = this.svg.select("g.x.axis")
.transition(t)
.attr("transform", `translate(0, ${height})`)
// Casting to any because d3 does not offer appropriate typings for the .call() function
.call(xAxis);
} else {
xAxisRef = this.innerWrap.append("g")
.attr("class", "x axis");
xAxisRef.call(xAxis);
}
// Update the position of the pieces of text inside x-axis
xAxisRef.selectAll("g.tick text")
.attr("y", Configuration.scales.magicY1)
.attr("x", Configuration.scales.magicX1)
.attr("dy", ".35em")
.attr("transform", `rotate(${Configuration.scales.xAxisAngle})`)
.style("text-anchor", "end")
.call(text => this.wrapTick(text));
// get the tickHeight after the ticks have been wrapped
const tickHeight = this.getLargestTickHeight(xAxisRef.selectAll(".tick")) + Configuration.scales.tick.heightAddition;
// Add x-axis title
if (this.innerWrap.select(".axis-label.x").nodes().length === 0 && this.options.scales.x.title) {
xAxisRef.append("text")
.attr("class", "x axis-label")
.attr("text-anchor", "middle")
.attr("transform", `translate(${xAxisRef.node().getBBox().width / 2}, ${tickHeight})`)
.text(this.options.scales.x.title);
}
// get the yHeight after the height of the axis has settled
const yHeight = this.getChartSize().height - this.svg.select(".x.axis").node().getBBox().height;
xAxisRef.attr("transform", `translate(0, ${yHeight})`);
}
repositionXAxisTitle() {
const xAxisRef = this.svg.select("g.x.axis");
const tickHeight = this.getLargestTickHeight(xAxisRef.selectAll(".tick")) + Configuration.scales.tick.heightAddition;
const xAxisTitleRef = this.svg.select("g.x.axis text.x.axis-label");
xAxisTitleRef.attr("class", "x axis-label")
.attr("text-anchor", "middle")
.attr("transform", `translate(${xAxisRef.node().getBBox().width / 2}, ${tickHeight})`)
.text(this.options.scales.x.title);
}
getYMax() {
const { datasets } = this.displayData;
const { scales } = this.options;
let yMax;
if (datasets.length === 1) {
yMax = max(datasets[0].data);
} else {
yMax = max(datasets, (d: any) => (max(d.data)));
}
if (scales.y.yMaxAdjuster) {
yMax = scales.y.yMaxAdjuster(yMax);
}
return yMax;
}
getYMin() {
const { datasets } = this.displayData;
const { scales } = this.options;
let yMin;
if (datasets.length === 1) {
yMin = min(datasets[0].data);
} else {
yMin = min(datasets, (d: any) => (min(d.data)));
}
if (scales.y.yMinAdjuster) {
yMin = scales.y.yMinAdjuster(yMin);
}
return yMin;
}
setYScale(yScale?: any) {
const chartSize = this.getChartSize();
const height = chartSize.height - this.innerWrap.select(".x.axis").node().getBBox().height;
const { scales } = this.options;
const yMin = this.getYMin();
const yMax = this.getYMax();
if (yScale) {
this.y = yScale;
} else {
this.y = scaleLinear().range([height, 0]);
this.y.domain([Math.min(yMin, 0), yMax]);
}
if (scales.y2 && scales.y2.ticks.max) {
this.y2 = scaleLinear().rangeRound([height, 0]);
this.y2.domain([scales.y2.ticks.min, scales.y2.ticks.max]);
}
}
setYAxis(noAnimation?: boolean) {
const chartSize = this.getChartSize();
const { scales } = this.options;
const t = noAnimation ? this.getInstantTransition() : this.getDefaultTransition();
const yAxis = axisLeft(this.y)
.ticks(scales.y.numberOfTicks || Configuration.scales.y.numberOfTicks)
.tickSize(0)
.tickFormat(scales.y.formatter);
let yAxisRef = this.svg.select("g.y.axis");
const horizontalLine = this.svg.select("line.domain");
this.svg.select("g.x.axis path.domain")
.remove();
// If the <g class="y axis"> exists in the chart SVG, just update it
if (yAxisRef.nodes().length > 0) {
yAxisRef.transition(t)
// Casting to any because d3 does not offer appropriate typings for the .call() function
.call(yAxis as any);
horizontalLine.transition(t)
.attr("y1", this.y(0))
.attr("y2", this.y(0))
.attr("x1", 0)
.attr("x2", chartSize.width);
} else {
yAxisRef = this.innerWrap.append("g")
.attr("class", "y axis yAxes");
yAxisRef.call(yAxis);
yAxisRef.append("line")
.classed("domain", true)
.attr("y1", this.y(0))
.attr("y2", this.y(0))
.attr("x1", 0)
.attr("x2", chartSize.width)
.attr("stroke", Configuration.scales.domain.color)
.attr("fill", Configuration.scales.domain.color)
.attr("stroke-width", Configuration.scales.domain.strokeWidth);
}
Tools.moveToFront(horizontalLine);
if (scales.y2 && scales.y2.ticks.max) {
const secondaryYAxis = axisRight(this.y2)
.ticks(scales.y2.numberOfTicks || Configuration.scales.y2.numberOfTicks)
.tickSize(0)
.tickFormat(scales.y2.formatter);
const secondaryYAxisRef = this.svg.select("g.y2.axis");
// If the <g class="y axis"> exists in the chart SVG, just update it
if (secondaryYAxisRef.nodes().length > 0) {
secondaryYAxisRef.transition(t)
.attr("transform", `translate(${this.getChartSize().width}, 0)`)
// Being cast to any because d3 does not offer appropriate typings for the .call() function
.call(secondaryYAxis as any);
} else {
this.innerWrap.append("g")
.attr("class", "y2 axis yAxes")
.attr("transform", `translate(${this.getChartSize().width}, 0)`)
.call(secondaryYAxis);
}
}
}
drawXGrid() {
const yHeight = this.getChartSize().height - this.getBBox(".x.axis").height;
const xGrid = axisBottom(this.x)
.tickSizeInner(-yHeight)
.tickSizeOuter(0);
const g = this.innerWrap.select(".x.grid")
.attr("transform", `translate(0, ${yHeight})`)
.call(xGrid);
this.cleanGrid(g);
}
drawYGrid() {
const { scales } = this.options;
const { thresholds } = this.options.scales.y;
const yHeight = this.getChartSize().height - this.getBBox(".x.axis").height;
const yGrid = axisLeft(this.y)
.tickSizeInner(-this.getChartSize().width)
.tickSizeOuter(0);
yGrid.ticks(scales.y.numberOfTicks || Configuration.scales.y.numberOfTicks);
const g = this.innerWrap.select(".y.grid")
.attr("transform", "translate(0, 0)")
.call(yGrid);
this.cleanGrid(g);
if (thresholds && thresholds.length > 0) {
this.addOrUpdateThresholds(g, false);
}
}
addOrUpdateThresholds(yGrid, animate?) {
const t = animate === false ? this.getInstantTransition() : this.getDefaultTransition();
const width = this.getChartSize().width;
const { thresholds } = this.options.scales.y;
// Check if the thresholds container <g> exists
const thresholdContainerExists = this.innerWrap.select("g.thresholds").nodes().length > 0;
const thresholdRects = thresholdContainerExists
? this.innerWrap.selectAll("g.thresholds rect")
: this.innerWrap.append("g").classed("thresholds", true).selectAll("rect").data(thresholds);
const calculateYPosition = d => {
return Math.max(0, this.y(d.range[1]));
};
const calculateHeight = d => {
const height = Math.abs(this.y(d.range[1]) - this.y(d.range[0]));
const yMax = this.y(this.y.domain()[0]);
// If the threshold is getting cropped because it is extending beyond
// the top of the chart, update its height to reflect the crop
if (this.y(d.range[1]) < 0) {
return Math.max(0, height + this.y(d.range[1]));
} else if (this.y(d.range[1]) + height > yMax) {
// If the threshold is getting cropped because it is extending beyond
// the bottom of the chart, update its height to reflect the crop
return Math.max(0, yMax - calculateYPosition(d));
}
return Math.max(0, height);
};
const calculateOpacity = d => {
const height = Math.abs(this.y(d.range[1]) - this.y(d.range[0]));
// If the threshold is to be shown anywhere
// outside of the top edge of the chart, hide it
if (this.y(d.range[1]) + height <= 0) {
return 0;
}
return 1;
};
// Applies to thresholds being added
thresholdRects.enter()
.append("rect")
.classed("bar", true)
.attr("x", 0)
.attr("y", d => calculateYPosition(d))
.attr("width", width)
.attr("height", d => calculateHeight(d))
.attr("fill", d => Configuration.scales.y.thresholds.colors[d.theme])
.attr("opacity", 0)
.transition(t)
.attr("opacity", d => calculateOpacity(d));
// Update thresholds
thresholdRects
.transition(t)
.attr("x", 0)
.attr("y", d => calculateYPosition(d))
.attr("width", width)
.attr("height", d => calculateHeight(d))
.attr("opacity", d => calculateOpacity(d))
.attr("fill", d => Configuration.scales.y.thresholds.colors[d.theme]);
// Applies to thresholds getting removed
thresholdRects.exit()
.transition(t)
.style("opacity", 0)
.remove();
}
updateXandYGrid(noAnimation?: boolean) {
const { thresholds } = this.options.scales.y;
// setTimeout is needed here, to take into account the new position of bars
// Right after transitions are initiated for the
setTimeout(() => {
const t = noAnimation ? this.getInstantTransition() : this.getDefaultTransition();
// Update X Grid
const chartSize = this.getChartSize();
const yHeight = chartSize.height - this.getBBox(".x.axis").height;
const xGrid = axisBottom(this.x)
.tickSizeInner(-yHeight)
.tickSizeOuter(0);
const g_xGrid = this.innerWrap.select(".x.grid")
.transition(t)
.attr("transform", `translate(0, ${yHeight})`)
.call(xGrid);
this.cleanGrid(g_xGrid);
// Update Y Grid
const yGrid = axisLeft(this.y)
.tickSizeInner(-chartSize.width)
.tickSizeOuter(0)
.tickFormat("" as any);
const g_yGrid = this.innerWrap.select(".y.grid")
.transition(t)
.attr("transform", `translate(0, 0)`)
.call(yGrid);
g_yGrid.transition(t);
this.cleanGrid(g_yGrid);
if (thresholds && thresholds.length > 0) {
this.addOrUpdateThresholds(g_yGrid, !noAnimation);
}
}, 0);
}
cleanGrid(g) {
g.selectAll("line")
.attr("stroke", Configuration.grid.strokeColor);
g.selectAll("text").style("display", "none").remove();
g.select(".domain").style("stroke", "none");
}
// TODO - Refactor
wrapTick(ticks) {
const self = this;
const letNum = Configuration.scales.tick.maxLetNum;
ticks.each(function(t) {
if (t && t.length > letNum / 2) {
const tick = select(this);
const y = tick.attr("y");
tick.text("");
const tspan1 = tick.append("tspan")
.attr("x", 0).attr("y", y).attr("dx", Configuration.scales.dx).attr("dy", `-${Configuration.scales.tick.dy}`);
const tspan2 = tick.append("tspan")
.attr("x", 0).attr("y", y).attr("dx", Configuration.scales.dx).attr("dy", Configuration.scales.tick.dy);
if (t.length < letNum - 3) {
tspan1.text(t.substring(0, t.length / 2));
tspan2.text(t.substring(t.length / 2 + 1, t.length));
} else {
tspan1.text(t.substring(0, letNum / 2));
tspan2.text(t.substring(letNum / 2, letNum - 3) + "...");
tick.on("click", dd => {
self.showLabelTooltip(dd, true);
});
}
}
});
}
// TODO - Refactor
getLargestTickHeight(ticks) {
let largestHeight = 0;
ticks.each(function() {
let tickLength = 0;
try {
tickLength = this.getBBox().height;
} catch (e) {
console.log(e);
}
if (tickLength > largestHeight) {
largestHeight = tickLength;
}
});
return largestHeight;
}
/**************************************
* Events & User interactions *
*************************************/
addDataPointEventListener() {
const self = this;
const { accessibility } = this.options;
this.svg.selectAll("rect")
.on("click", function(d) {
self.dispatchEvent("bar-onClick", d);
})
.on("mouseover", function(d) {
select(this)
.attr("stroke-width", Configuration.bars.mouseover.strokeWidth)
.attr("stroke", self.colorScale[d.datasetLabel](d.label))
.attr("stroke-opacity", Configuration.bars.mouseover.strokeOpacity);
self.showTooltip(d, this);
self.reduceOpacity(this);
})
.on("mousemove", function(d) {
const tooltipRef = select(self.holder).select("div.chart-tooltip");
const relativeMousePosition = mouse(self.holder as HTMLElement);
tooltipRef.style("left", relativeMousePosition[0] + Configuration.tooltip.magicLeft2 + "px")
.style("top", relativeMousePosition[1] + "px");
})
.on("mouseout", function(d) {
const { strokeWidth, strokeWidthAccessible } = Configuration.bars.mouseout;
select(this)
.attr("stroke-width", accessibility ? strokeWidthAccessible : strokeWidth)
.attr("stroke", accessibility ? self.colorScale[d.datasetLabel](d.label) : "none")
.attr("stroke-opacity", Configuration.bars.mouseout.strokeOpacity);
self.hideTooltip();
});
this.svg.selectAll("circle.dot")
.on("mouseover", function(d) {
select(this)
.attr("stroke", self.colorScale[d.datasetLabel](d.label))
.attr("stroke-opacity", Configuration.lines.points.mouseover.strokeOpacity);
self.showTooltip(d, this);
self.reduceOpacity(this);
})
.on("mouseout", function(d) {
select(this)
.attr("stroke", self.colorScale[d.datasetLabel](d.label))
.attr("stroke-opacity", Configuration.lines.points.mouseout.strokeOpacity);
self.hideTooltip();
});
}
}