forked from Stigmatoz/web-activity-time-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchart-core.js
More file actions
528 lines (457 loc) · 18.9 KB
/
chart-core.js
File metadata and controls
528 lines (457 loc) · 18.9 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
function donutChart() {
var width,
height,
darkMode,
margin = { top: 10, right: 10, bottom: 0, left: 10 },
colour = d3.scaleOrdinal(d3.schemeCategory20), // colour scheme
variable, // value in data that will dictate proportions on chart
category, // compare data by
padAngle, // effectively dictates the gap between slices
floatFormat = d3.format('.4r'),
cornerRadius, // sets how rounded the corners are on each slice
percentFormat = d3.format(',.2%');
function chart(selection) {
selection.each(function (data) {
// generate chart
// ===========================================================================================
// Set up constructors for making donut. See https://github.com/d3/d3-shape/blob/master/README.md
var radius = 110;
// creates a new pie generator
var pie = d3.pie()
.value(function (d) { return floatFormat(d[variable]); })
.sort(null);
// contructs and arc generator. This will be used for the donut. The difference between outer and inner
// radius will dictate the thickness of the donut
var arc = d3.arc()
.outerRadius(radius)
.innerRadius(radius * 0.75)
.cornerRadius(cornerRadius)
.padAngle(padAngle);
// ===========================================================================================
// append the svg object to the selection
var svg = selection.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'backColorChart')
.append('g')
.attr('transform', 'translate(' + (width / 2 - 105) + ',' + (height / 2) + ')');
// ===========================================================================================
// ===========================================================================================
// g elements to keep elements within svg modular
svg.append('g').attr('class', 'slices');
svg.append('g').attr('class', 'labelName');
svg.append('g').attr('class', 'lines');
// ===========================================================================================
// ===========================================================================================
// add and colour the donut slices
var path = svg.select('.slices')
.datum(data).selectAll('path')
.data(pie)
.enter().append('path')
.attr('fill', function (d) { return colour(d.data[category]); })
.attr('d', arc)
.attr('id', function (d) { return d.data[category]; });
// ===========================================================================================
var legendG = svg.selectAll(".legend") // note appending it to mySvg and not svg to make positioning easier
.data(pie(data))
.enter().append("g")
.attr("transform", function (d, i) {
return "translate(" + (130) + "," + (i * 20 - 100) + ")"; // place each legend on the right and bump each one down 15 pixels
})
.attr("class", "legend");
if (darkMode)
legendG.style("fill", "#ffffff");
else legendG.style("fill", "black");
legendG.append("rect") // make a matching color rect
.attr("width", 10)
.attr("height", 10)
.attr("fill", function (d, i) {
return colour(d.data[category]);
});
if (darkMode)
legendG.append("text") // add the text
.text(function (d) {
return d.data.url;
})
.style("font-size", 13)
.style('fill', '#ffffff')
.attr("y", 10)
.attr("x", 13);
else
legendG.append("text") // add the text
.text(function (d) {
return d.data.url;
})
.style("fill", "black")
.style("font-size", 14)
.attr("y", 10)
.attr("x", 15);
// ===========================================================================================
// add tooltip to mouse events on slices and labels
d3.selectAll('.labelName text, .slices path').call(toolTip);
// ===========================================================================================
// ===========================================================================================
// Functions
// calculates the angle for the middle of a slice
function midAngle(d) { return d.startAngle + (d.endAngle - d.startAngle) / 2; }
// function that creates and adds the tool tip to a selected element
function toolTip(selection) {
// add tooltip (svg circle element) when mouse enters label or slice
selection.on('mouseenter', function (data) {
d3.selectAll('.toolCircle').remove();
if (darkMode)
svg.append('text')
.attr('class', 'toolCircle')
.attr('dy', -15) // hard-coded. can adjust this to adjust text vertical alignment in tooltip
.html(toolTipHTML(data)) // add text to the circle.
.style('font-size', '.9em')
.style('fill', '#ffffff')
.style('text-anchor', 'middle'); // centres text in tooltip
else
svg.append('text')
.attr('class', 'toolCircle')
.attr('dy', -15)
.html(toolTipHTML(data))
.style('font-size', '.9em')
.style('text-anchor', 'middle');
svg.append('circle')
.attr('class', 'toolCircle')
.attr('r', radius * 0.75) // radius of tooltip circle
.style('fill', 'white') // colour based on category mouse is over
.style('fill-opacity', 0.35);
});
// remove the tooltip when mouse leaves the slice/label
// selection.on('mouseout', function () {
// d3.selectAll('.toolCircle').remove();
// });
}
// function to create the HTML string for the tool tip. Loops through each key in data object
// and returns the html string key: value
function toolTipHTML(data) {
var tip = '',
i = 0;
for (var key in data.data) {
// if value is a number, format it as a percentage
var value = (!isNaN(parseFloat(data.data[key]))) ? percentFormat(data.data[key]) : data.data[key];
if (key === 'summary')
value = convertSummaryTimeToString(data.data[key]);
if (key === 'visits' && data.data[key] !== undefined)
value = data.data[key] + ' visits';
var className = '';
if (key === 'percentage')
className = 'class="percentageValue"';
// leave off 'dy' attr for first tspan so the 'dy' attr on text element works. The 'dy' attr on
// tspan effectively imitates a line break.
if (i === 0) tip += '<tspan x="0">' + value + '</tspan>';
else tip += '<tspan x="0" dy="1.2em"' + className + '>' + value + '</tspan>';
i++;
}
return tip;
}
function angleIsInRangeDifference(tempAngle, currentAngle, difference) {
return currentAngle < (tempAngle + difference) && currentAngle > (tempAngle - difference);
}
// ===========================================================================================
});
}
chart.width = function (value) {
if (!arguments.length) return width;
width = value;
return chart;
};
chart.height = function (value) {
if (!arguments.length) return height;
height = value;
return chart;
};
chart.darkMode = function (value) {
if (!arguments.length) return darkMode;
darkMode = value;
return chart;
};
chart.margin = function (value) {
if (!arguments.length) return margin;
margin = value;
return chart;
};
chart.radius = function (value) {
if (!arguments.length) return radius;
radius = value;
return chart;
};
chart.padAngle = function (value) {
if (!arguments.length) return padAngle;
padAngle = value;
return chart;
};
chart.cornerRadius = function (value) {
if (!arguments.length) return cornerRadius;
cornerRadius = value;
return chart;
};
chart.colour = function (value) {
if (!arguments.length) return colour;
colour = value;
return chart;
};
chart.variable = function (value) {
if (!arguments.length) return variable;
variable = value;
return chart;
};
chart.category = function (value) {
if (!arguments.length) return category;
category = value;
return chart;
};
return chart;
}
function barChart(data, darkMode) {
var margin = { top: 25, right: 5, bottom: 25, left: 5 },
width = 555,
height = 160;
// set the ranges
var x = d3.scaleBand()
.range([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.range([height, 0]);
// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#barChart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function (d) {
if (data.length > 9)
return "<strong><span class='red-label'>" + new Date(d.date).toLocaleDateString() + "</span></strong></br><strong>" + convertShortSummaryTimeToString(d.total) + "</strong>";
else
return "<strong>" + convertShortSummaryTimeToString(d.total) + "</strong>";
});
svg.call(tip);
// Scale the range of the data in the domains
x.domain(data.map(function (d) { return new Date(d.date).toLocaleDateString(); }));
y.domain([0, d3.max(data, function (d) { return d.total; })]);
// append the rectangles for the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) { return x(new Date(d.date).toLocaleDateString()); })
.attr("width", x.bandwidth())
.attr("y", function (d) { return y(d.total); })
.attr("height", function (d) { return height - y(d.total); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
// add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.style("stroke", darkMode ? "white" : "")
.style("stroke-width", darkMode ? "0.5px" : "")
.call(d3.axisBottom(x));
if (data.length > 9)
document.querySelectorAll('#barChart g.tick ').forEach(element => { element.remove() });
if (darkMode){
document.querySelector("#barChart path").setAttribute("stroke", "white");
document.querySelectorAll('#barChart g.tick line').forEach(element => { element.setAttribute("stroke", "white") });
}
}
function drawIntervalChart(data) {
data.forEach(function (item) {
var hFrom = getHourFrom(item.interval);
var hTo = getHourTo(item.interval);
if (hFrom != hTo) {
var sourceTimeFrom = item.interval.split('-')[0].split(':');
var sourceTimeTo = item.interval.split('-')[1].split(':');
var timeTo = sourceTimeFrom[0] + ":" + 59 + ":" + 59;
var timeFrom = sourceTimeTo[0] + ":" + 00 + ":" + 00;
data.push({ "domain": item.domain, "interval": item.interval.split('-')[0] + "-" + timeTo });
data.push({ "domain": item.domain, "interval": timeFrom + "-" + item.interval.split('-')[1] });
}
});
var margin = { top: 5, right: 10, bottom: 20, left: 20 },
width = 580 - margin.left - margin.right,
height = 410 - margin.top - margin.bottom;
//linear 24 hour scale
var y = d3.scaleLinear()
.domain([0, 60])
.range([height, 0]);
//vertical axis
var yAxis = d3.axisLeft()
.ticks(10)
.scale(y);
var x = d3.scaleLinear()
.domain([0, 24])
.range([0, width]);
//vertical axis
var xAxis = d3.axisBottom()
.ticks(24)
.scale(x)
var tickDistance = 4.38;
var tooltip;
if (document.body.classList.contains('dark-mode'))
tooltip = d3.select("#timeChart")
.append("div")
.style("opacity", 0)
.style("display", "none")
.style("position", "absolute")
.attr("class", "tooltip")
.style("background-color", "#cbcbcb")
.style("color", "black")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "5px")
else
tooltip = d3.select("#timeChart")
.append("div")
.style("opacity", 0)
.style("display", "none")
.style("position", "absolute")
.attr("class", "tooltip")
.style("background-color", "white")
.style("color", "black")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "5px")
// Three function that change the tooltip when user hover / move / leave a cell
var mouseover = function (d) {
tooltip
.style("opacity", 1)
.style("display", "block")
d3.select(this)
.style("stroke", "black")
.style("stroke-width", "0.5px")
.style("opacity", 1)
}
var mousemove = function (d) {
tooltip
.html(d.domain + "<br>" + d.interval)
.style("left", (d3.mouse(this)[0]) + 10 + "px")
.style("top", (d3.mouse(this)[1]) + 30 + "px")
}
var mouseleave = function (d) {
tooltip
.style("opacity", 0)
.style("display", "none")
d3.select(this)
.style("stroke", "none")
.style("opacity", 0.8)
}
//create the svg
var svg;
if (document.body.classList.contains('dark-mode'))
svg = d3.select("#timeChart").append("svg")
.style('background-color', '#383838')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
else
svg = d3.select("#timeChart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//draw the axis.
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.attr("class", "label")
.call(xAxis)
.append("text")
.text("Value");
// Add a y-axis with label.
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("class", "label")
.attr("y", 6)
.attr("dy", ".71em")
.attr("text-anchor", "end")
.attr("transform", "rotate(-90)")
.text("Value");
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_axis()
.tickSize(-height, 0, 0)
)
svg.append("g")
.attr("class", "grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
)
//draw the bars, offset y and bar height based on data
svg.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.style("fill", "orangered")
.style("stroke", "#f1f1f1")
.style("stroke-width", "1")
.attr("class", "bar")
.attr("x", function (d) {
return x(getHourFrom(d.interval)) + 2;
})
.attr("width", 20)
.attr("y", function (d) {
return y(getMinutesTo(d.interval)) - 1;
})
.attr("height", function (d) {
var offset = getMinutesTo(d.interval) - getMinutesFrom(d.interval);
if (offset == 0) {
var offsetSeconds = getSecondsTo(d.interval) - getSecondsFrom(d.interval);
if (offsetSeconds <= 3)
return 0;
else
return 1;
}
else return offset * tickDistance;
})
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseleave", mouseleave);
function make_x_axis() {
return d3.axisBottom()
.scale(x)
.ticks(24)
}
function make_y_axis() {
return d3.axisLeft()
.scale(y)
.ticks(10)
}
function getHourFrom(interval) {
var time = interval.split('-')[0];
return time.split(':')[0];
}
function getHourTo(interval) {
var time = interval.split('-')[1];
return time.split(':')[0];
}
function getMinutesFrom(interval) {
var time = interval.split('-')[0];
return time.split(':')[1];
}
function getMinutesTo(interval) {
var time = interval.split('-')[1];
return time.split(':')[1];
}
function getSecondsFrom(interval) {
var time = interval.split('-')[0];
return time.split(':')[2];
}
function getSecondsTo(interval) {
var time = interval.split('-')[1];
return time.split(':')[2];
}
}