-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconversionDiagram.js
More file actions
694 lines (538 loc) · 16.6 KB
/
conversionDiagram.js
File metadata and controls
694 lines (538 loc) · 16.6 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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
/**
* @file conversionDiagram.js
* @author Sanne Peters
* @copyright Sanstream Creations 2013, but if you ask nicely I might let you use it for free.
* @description This file needs more doc blocks.
*/
var ConversionDiagram = new Class({
rawDataObject: null,
parsedDataObject: null,
currentDataObject: null,
conversionData: null,
orderedDates: null,
shownItemsScale: null,
seenItemsScale: null,
boughtItemsScale: null,
linearScales: null,
logScale: null,
totals: null, // holds an array with all the totals
svgElement: null,
svgMargin: 14,
monthsListWidth: 100,
diagramWidth: 700,
diagramContainer: null,
diagramAreaHeight: null,
firstItemShown: 0,
/**
* Constructor
* @param {object} dataObject parsed raw json.
* @param {string} containerIdentifier css selector for a specific element.
* @return {void}
*/
initialize: function(dataObject, containerIdentifier,firstItemShown){
var self = this;
// testing data:
if(self.suppliedDataIsOk()){
// set up the visual prerequisites:
self.svgElement = d3.select(containerIdentifier).append('svg');
self.svgElement.attr('width', self.monthsListWidth + self.diagramWidth + self.svgMargin*2);
self.diagramAreaHeight = self.diagramWidth * 0.70;
self.svgElement.attr('height', self.diagramAreaHeight + self.svgMargin*2);
self.monthListContainer = self.svgElement.append('g').attr('class','monthListContainer');
self.diagramContainer = self.svgElement.append('g').attr('class','diagramContainer');
self.scopeLine = self.svgElement.append('path')
.classed('ScopeLine',true)
.attr('d',self.setScopeLineDims.bind(this));
self.addColumnLabels();
self.linearScales = new Array();
self.rawDataObject = dataObject;
// Do the neccesary calculations and data-treatment:
self.convertRawData();
self.setTimeFrameShown(0);
self.renderMonthsList();
//visual rendering:
self.renderDiagram();
}
},
/**
* Check to figure out if the data is workable, still a stub.
* @return {boolean}
*/
suppliedDataIsOk: function () {
return true;
},
/**
* Draws the line values for the 'd' attribute of a svg path.
* @param {object} datum The d3 datum object of the path.
*/
setScopeLineDims: function(datum) {
var xOffset = 200;
// Preseting the coordinates of the scope-line:
var points = {
'a':{
'x': xOffset + 30,
'y': 2
},
'b':{
'x': xOffset + 20,
'y': 2
},
'c':{
'x': xOffset,
'y': 2 + 20
},
'd':{
'x': xOffset,
'y': this.diagramAreaHeight - 15
},
'e':{
'x': xOffset + 20,
'y': this.diagramAreaHeight
},
'f':{
'x': xOffset + 30,
'y': this.diagramAreaHeight
}
}
// applying them:
var line = [
[" M" + points.a.x + "," + points.a.y ],
[' L' + points.b.x + "," + points.b.y ],
[' C' + points.c.x +',' + points.b.y ],
[ points.c.x + "," + points.c.y ],
[ points.c.x + "," + points.c.y ],
[' L' + points.d.x + "," + points.d.y ],
[' C' + points.d.x +',' + points.d.y ],
[ points.d.x + "," + points.e.y ],
[ points.e.x + "," + points.e.y ],
[' L' + points.f.x + "," + points.f.y ],
];
return line.flatten().join(" ");
},
/**
* Adds the Column labels, yup it totally does.
*/
addColumnLabels:function () {
var self = this;
var columnLabelGroup = self.svgElement.append('g').classed('ColumnLabelGroup',true);
['Shown...', 'seen...', 'and bought.'].each(function(labelName, index){
columnLabelGroup.append('text')
.classed('ColumnLabel',true)
.attr('x', 260 + index * 160)
.attr('y',10)
.attr('width', 100)
.text(labelName);
});
},
/**
* sets the total of the ammounts, sizes, and y-offsets of all the data-types. Aw yiss..
*/
setTotals: function () {
var self = this;
self.totals = [];
self.sizes = [];
self.offsets = [];
for (var sub = 0; sub < self.currentDataObject[0].length; sub++) {
var totalData = [];
for (var i = 0; i < self.currentDataObject.length; i++) {
totalData.push(self.currentDataObject[i][sub]);
}
self.totals[sub] = d3.sum(totalData);
}
self.totals.each(function(total){
self.sizes.push( self.logScale(total) );
});
self.sizes.each(function(size){
self.offsets.push( (self.diagramAreaHeight - self.svgMargin - size) * 0.50 );
});
},
/**
* Converts the raw data to a format the we can work with.
* @return {void}
*/
convertRawData: function(){
var self = this;
self.parsedDataObject = {};
self.orderedDates = [];
Object.each(self.rawDataObject, function(data, rawDate){
var jsDate = new Date(rawDate);
self.orderedDates.push({
'date':jsDate,
'selected': false
});
self.parsedDataObject[jsDate] = self.createConversionData(data);
});
self.orderedDates.sort(function(a,b){
return a.date > b.date;
});
},
/**
* Basically create a pivot table version of the original.
* @return {array}
*/
createConversionData: function(conversionDataSet) {
conversionData = [];
conversionData.length = conversionDataSet[0].length;
for (var i = 0; i < conversionDataSet[0].length; i++) {
conversionData[i] = [];
conversionData[i].length = conversionDataSet.length;
for (var range = 0; range < conversionDataSet.length; range++){
conversionData[i][range] = conversionDataSet[range][i];
}
};
return conversionData;
},
/**
* attaches the attribute values.
* @param {object} d3Element
* @param {string} classes
* @param {integer} xOffset
* @param {integer} width
* @param {integer} value
* @param {integer} verticalOffset
* @param {function} scalingMethod
* @return {void}
*/
attachBlockAttrs:function(d3Element, classes, xOffset, width, value, dataType, verticalOffset, scalingMethod){
var self = this;
var scaledValue = scalingMethod(value);
var blockValues = {
'height':scaledValue,
'y': verticalOffset,
'x': xOffset,
'width': width
};
d3Element.attr('class', (scaledValue > 13) ? classes : classes + ' ValueHidden');
d3Element.attr('height',scaledValue);
d3Element.attr('y', verticalOffset);
d3Element.attr('x', xOffset);
d3Element.attr('width', width);
d3Element.attr('data-type', dataType);
if(d3Element.node().nodeName != 'g'){
if(scaledValue > 15){
d3.select(d3Element.node().getParent()).append('text')
.attr('class','Label ' + classes)
.attr('x', xOffset + 60)
.attr('y', verticalOffset + scaledValue.toInt() * 0.5 + 3)
.attr('data-fortype', dataType)
.attr('text-anchor','end')
.text(value)
}
else{
d3Element.append('title')
.attr('data-fortype', dataType)
.text(value);
}
}
return blockValues;
},
/**
* attaches the attribute values.
* @param {object} d3Element
* @param {string} classes
* @param {integer} xOffset
* @param {integer} width
* @param {integer} value
* @param {integer} verticalOffset
* @param {function} scalingMethod
* @return {void}
*/
updateBlockAttrs:function(d3Element, value, verticalOffset, scalingMethod){
var self = this;
var scaledValue = scalingMethod(value);
var blockValues = {
'height':scaledValue,
'y': verticalOffset,
'x': d3Element.attr('x').toInt(),
'width': d3Element.attr('width').toInt()
};
d3Element.transition().attr('height',scaledValue);
d3Element.transition().attr('y', verticalOffset);
// update the text labeling
if(d3Element.node().nodeName != 'g'){
var dataType = d3Element.attr('data-type');
var label = d3.select(d3Element.node().parentNode).selectAll('[data-fortype="'+ dataType +'"]');
if(scaledValue > 15){
if ( label.node().tagName === 'title' ){
// get rid of the title tag and append a text tag.
label.remove();
label = d3.select(d3Element.node().parentNode).append('text');
label.attr('class','Label ' + d3Element.attr('class'));
label.attr('x', d3Element.attr('x').toInt() + 60);
label.attr('data-fortype', dataType);
label.attr('text-anchor','end');
}
// just update the text tag further:
label.transition().attr('y', verticalOffset + scaledValue.toInt() * 0.5 + 3)
.text(value);
}
else{
if( label.node().tagName === 'text' ){
// We need a title tag instead of a text tag, so get rid of the first:
label.remove();
label = d3Element.append('title')
.attr('data-fortype', dataType);
}
label.text(value);
}
}
return blockValues;
},
/**
* Returns the sum of the subset with the highest sum.
* @param {array} dataObject
* @return {integer}
*/
getLargestAmount: function (dataObject) {
return d3.sum(
dataObject.map(function(item){
return item[0];
})
);
},
/**
* Hub method for all the rendering of the diagram.
* @return {void}
*/
renderDiagram: function(){
var self = this;
var largestAmount = self.getLargestAmount(self.currentDataObject);
self.logScale = function(x){
if (x == 0)return x;
else return (self.diagramAreaHeight -(self.svgMargin * 2)) * ((Math.log(x)/Math.log(5)) / (Math.log( largestAmount )/Math.log(5)) );
};
self.setTotals();
self.setLinearScales();
var attachedData = self.diagramContainer.selectAll('.DatumGroup').data(self.currentDataObject);
self.updateComponents(attachedData);
self.removeComponents(attachedData);
self.enterComponents(attachedData);
},
/**
* Method for entering the new elements based on the data.
* @param {array} attachedData
* @return {void}
*/
enterComponents: function(attachedData){
var self = this;
var enteredDataSelection = attachedData.enter();
var dataGroups = enteredDataSelection.append('g').attr('class','DatumGroup');
dataGroups.each(function(datum,index){
var dataGroup = d3.select(this);
var rectArray = [];
datum.each(function(subDatum, subIndex){
rectArray.push(
self.attachBlockAttrs(
dataGroup.append('rect'),
'Count',
160 * (subIndex + 1) + self.monthsListWidth,
70,
subDatum,
subIndex,
self.offsets[subIndex] + self.svgMargin,
self.linearScales[subIndex]
)
);
self.offsets[subIndex] += self.linearScales[subIndex](subDatum);
});
rectArray.each(function(rect, index){
if( (index < rectArray.length - 1) ){
var conversionPath = dataGroup.append('path');
conversionPath.attr('class','ConversionPath');
conversionPath.attr('d', self.createConversionPath(rectArray[index], rectArray[index + 1]));
}
});
});
},
/**
* Method for updating existing elements based on the data.
* @param {array} attachedData
* @return {void}
*/
updateComponents: function (attachedData){
var self = this;
attachedData.transition().each(function(datum,index){
if(datum){
var dataGroup = d3.select(this);
var rectArray = [];
dataGroup.selectAll('rect.Count').each(function(rect, subIndex){
rectArray.push(self.updateBlockAttrs(
d3.select(this),
datum[subIndex],
self.offsets[subIndex] + self.svgMargin,
self.linearScales[subIndex]
));
self.offsets[subIndex] += self.linearScales[subIndex](datum[subIndex]);
});
dataGroup.selectAll('path.ConversionPath').each(function(path, index){
d3.select(this).transition()
.attr('d', self.createConversionPath(rectArray[index], rectArray[index + 1]));
});
}
});
},
removeComponents: function (attachedData){
attachedData.exit().remove();
},
/**
* Builds the bezier path for the conversionspath.
* @param {d3 element} startBlock
* @param {d3 element} endBlock
* @return {string}
*/
createConversionPath: function(startBlock, endBlock){
var curveInclineTop = 0.5;
var curveInclineBottom = 0.5;
var ax = startBlock.width + startBlock.x;
var ay = startBlock.y;
var bx = endBlock.x;
var by = endBlock.y;
var cx = startBlock.width + startBlock.x;
var cy = startBlock.y + startBlock.height;
var dx = endBlock.x;
var dy = endBlock.y + endBlock.height;
var topLine = [ [" M" + (ax + 1) + "," + ay],
[' C'], [+ (ax + 1) + "," + ay ],
[((bx - ax) * 0.5 * 0.75 + ax ) + ','+ ay],
[((bx - ax) * 0.5 + ax ) +','+ ((by - ay) * 0.5 + ay )],
[' S'], [(bx - 1)+ ',' + by ], [(bx - 1)+ ',' + by ]];
var bottomLine = [ [" L" + (dx - 1) + "," + dy],
[' C'], [+ (dx - 1) + "," + dy ],
[((dx - cx) * 0.5 * 1.25 + cx ) + ','+ dy],
[((dx - cx) * 0.5 + cx ) +','+ ((dy - cy) * 0.5 + cy )],
[' S'], [(cx + 1) + ',' + cy ], [(cx + 1) + ',' + cy ],
[' Z'] ];
return topLine.flatten().join(" ") + bottomLine.flatten().join(" ");
},
/**
* Sets the linear scales of each dataset.
*/
setLinearScales: function () {
var self = this;
for (var i = 0; i < self.totals.length; i++) {
self.linearScales[i] = d3.scale.linear().domain([0, self.totals[i] ]).range([0, self.sizes[i] ]);
};
},
/**
* Sets the date in orderedDates to selected and set the appriopiate currentDataObject.
* @param {integer} index Index of the date selected.
*/
setTimeFrameShown: function (index) {
var self = this;
// resetting the selected states of each date:
self.orderedDates.each(function(object){
object.selected = false;
});
// setting the current selected date to true
self.orderedDates[index].selected = true;
var date = self.orderedDates[index].date;
self.currentDataObject = self.parsedDataObject[date];
},
switchMonth: function (monthNumber) {
var self = this;
self.setTimeFrameShown(monthNumber);
self.updateMonthList();
self.renderDiagram();
},
/**
* Builds the monthlist.
* @return {void}
*/
renderMonthsList: function() {
var self = this;
var formatDate = d3.time.format('%B %Y');
var attachedDates = self.monthListContainer.selectAll('.DateGroup').data(self.orderedDates);
var dateGroups = attachedDates.enter()
.append('g')
.classed('DateGroup', true)
.on('click',function(datum,index){
console.log(this);
self.switchMonth(index);
});
boxWidth = 120;
boxXOffset = 21;
dateGroups.append('rect')
.classed('DateBox',true)
.attr('width',boxWidth)
.attr('height',30)
.classed('Selected', function(datum){
return datum.selected;
})
.attr('x', 21)
.attr('y', function(datum, index){
return 50 * index + 30;
});
dateGroups.append('path')
.classed('DateAnchorLine',true)
.classed('Selected', function(datum){
return datum.selected;
})
.attr('d', function(datum, index){
return 'M '+ (boxWidth + boxXOffset) + ',' + (50 * index + 30 + 15 ) +
' L' + (boxWidth + boxXOffset + ((datum.selected)? 59 : 15) ) +',' + (50 * index + 30 + 15);
})
.attr('stroke','#000');
dateGroups.append('circle')
.classed('DateAnchorDot',true)
.attr('cx', function(datum){
return boxWidth + boxXOffset + ((datum.selected)? 59 : 15);
})
.attr('cy', function(datum, index){
return 50 * index + 30 + 15;
})
.attr('r',function(datum){
return (datum.selected)? 5 : 2;
});
dateGroups.append('text')
.attr('x', 21 + 10)
.attr('y', function(datum, index){
return 50 * index + 30 + 20;
})
.text(function(datum){
return formatDate(datum.date);
});
},
updateMonthList: function () {
var self = this;
var attachedDates = self.monthListContainer.selectAll('.DateGroup').data(self.orderedDates);
console.log(attachedDates);
attachedDates.selectAll('rect.DateBox')
.classed('Selected', function(datum){
return datum.selected;
});
boxWidth = 120;
boxXOffset = 21;
pathIndex = 0;
attachedDates.selectAll('path.DateAnchorLine')
// .classed('Selected', function(datum){
// return datum.selected;
// })
.transition()
.attr('d', function(datum){
pathIndex += 1;
console.log(this,datum,pathIndex);
return 'M '+ (boxWidth + boxXOffset) + ',' +
(50 * (pathIndex - 1) + 30 + 15 ) +
' L' + (boxWidth + boxXOffset + ((datum.selected)? 59 : 15) ) +',' +
(50 * (pathIndex - 1) + 30 + 15);
});
attachedDates.selectAll('circle.DateAnchorDot').transition()
.attr('cx', function(datum){
return boxWidth + boxXOffset + ((datum.selected)? 59 : 15);
})
.attr('r',function(datum){
return (datum.selected)? 5 : 2;
});
}
});
// Adding the visualisation to the dom, when the dom is ready.
$(document).addEvent('domready', function(){
var dataLocation = '';
if (typeof BASE_URI == 'undefined') dataLocation = "http://localhost/~conversionDiagram/";
else dataLocation = BASE_URI + 'uploads/conversionDiagram/';
// Load the data from the json file:
d3.json( dataLocation + "conversionData.json", function(json, error) {
if (error) return console.warn(error);
conversion = new ConversionDiagram(json, '#conversionDiagramWrapper');
});
});