-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtreemapViz.js
More file actions
executable file
·629 lines (533 loc) · 21.7 KB
/
Copy pathtreemapViz.js
File metadata and controls
executable file
·629 lines (533 loc) · 21.7 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
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function ($, $jit, require) {
var exports = require('piwik/UI'),
DataTable = exports.DataTable,
dataTablePrototype = DataTable.prototype,
fullPageReports = {
'Actions.getPageUrls': true,
'Actions.getEntryPageUrls': true,
'Actions.getExitPageUrls': true,
'Actions.getEntryPageTitles': true,
'Actions.getExitPageTitles': true,
'Actions.getPageTitles': true,
'Actions.getOutlinks': true,
'Actions.getDownloads': true
},
COLOR_NAMESPACE_NORMAL = 'infoviz-treemap-colors',
COLOR_NAMESPACE_EVOLUTION = 'infoviz-treemap-evolution-colors';
/**
* Class that handles UI behavior for the treemap visualization.
*/
exports.TreemapDataTable = function (element) {
DataTable.call(this, element);
};
$.extend(exports.TreemapDataTable.prototype, dataTablePrototype, {
/**
* Constructor.
*/
init: function () {
dataTablePrototype.init.call(this);
var domElem = this.$element;
var treemapContainerId = this.workingDivId + '-infoviz-treemap';
var treemapContainer = $('.infoviz-treemap', domElem).attr('id', treemapContainerId);
if (!treemapContainer[0]) {
return;
}
// we need to fix the width/height, otherwise treemap is not displayed in case treemap is the default
// visualization for a report eg PageUrls
if (!treemapContainer.height() && this.param.availableHeight) {
treemapContainer.height(this.param.availableHeight);
}
if (!treemapContainer.width() && this.param.availableWidth) {
treemapContainer.width(this.param.availableWidth);
}
this._bindEventCallbacks(domElem);
var self = this;
setTimeout(function () { // use a timeout in case nothing in the DOM has been sized yet
self.createJitTreemap(treemapContainer);
}, 1);
},
/**
* Creates the internal treemap object and renders it.
*/
createJitTreemap: function (treemapContainer) {
var treemapContainerId = treemapContainer.attr('id'),
domElem = this.$element,
headerColor = piwik.ColorManager.getColor(COLOR_NAMESPACE_NORMAL, 'header-background-color'),
self = this;
this.treemap = new $jit.TM.Squarified({
injectInto: treemapContainerId,
titleHeight: 24,
animate: true, // TODO: disable on ipad/w/o native canvas support
offset: 1,
levelsToShow: 1,
constrained: true,
Node: {
color: headerColor
},
Events: {
enable: true,
onClick: function (node, info, event) {
if (event.which == 2) {
self._onMiddleClick(node);
} else {
self._onLeftClickNode(node);
}
},
onRightClick: function (node) {
self._onRightClickNode(node);
}
},
duration: 1000,
Tips: {
enable: false // TODO: show more in tooltips
},
onCreateLabel: function (nodeElement, node) {
self._initNode(nodeElement, node);
},
onPlaceLabel: function (nodeElement, node) {
self._toggleLabelBasedOnAvailableSpace(nodeElement, node);
}
});
this.data = this._prepareTreemapData(treemapContainer.attr('data-data'));
this._refreshTreemap({animate: true});
this._addSeriesPicker(domElem);
},
/**
* Recursively iterates over the entire data tree and executes a function with
* each node.
*
* @param {Function} f The function to execute. Accepts one argument, the node.
* @param {Object} [node] The JSON node object to start from. This defaults to the root
* of the entire tree.
*/
foreachNode: function (f, node) {
node = node || this.data;
f(node);
for (var i = 0; i != (node.children || []).length; ++i) {
this.foreachNode(f, node.children[i]);
}
},
/**
* Changes the metric the treemap displays.
*
* @param {String} metric The name of the metric, e.g. 'nb_visits', 'nb_actions', etc.
*/
changeMetric: function (metric) {
this.param.columns = metric;
this.reloadAjaxDataTable();
},
/**
* Handle events to make this control functional.
*/
_bindEventCallbacks: function (domElem) {
var self = this;
domElem.on('click', '.infoviz-treemap-zoom-out', function (e) {
e.preventDefault();
self._leaveNode();
return false;
});
this.onWidgetResize(function () {
self.resize();
});
},
resize: function () {
var $treemap = this.$element.find('.infoviz-treemap');
var height = $treemap.height();
if (!height && this.param.availableHeight) {
height = this.param.availableHeight;
}
var width = $treemap.width();
if (!width && this.param.availableWidth) {
width = this.param.availableWidth;
}
this.treemap.canvas.resize(width, height);
},
/**
* Adds the SeriesPicker DataTable visualization widget to this treemap visualization.
*/
_addSeriesPicker: function (dataTableDomElem) {
var self = this;
var SeriesPicker = require('piwik/DataTableVisualizations/Widgets').SeriesPicker;
this._seriesPicker = new SeriesPicker(this);
$(this._seriesPicker).bind('placeSeriesPicker', function () {
var displayedColumn = this.getMetricTranslation(self.param.columns);
var metricLabel = $('<span/>')
.addClass('infoviz-treemap-colors')
.attr('data-name', 'header-color')
.text("— " + displayedColumn)
;
var seriesPickerContainer = $('<div/>') // TODO: this behavior should probably be a part of SeriesPicker
.addClass('infoviz-treemap-series-picker')
.append(metricLabel)
.append(this.domElem)
;
dataTableDomElem.find('.infoviz-treemap').prepend(seriesPickerContainer);
});
$(this._seriesPicker).bind('seriesPicked', function (e, columns) {
self.changeMetric(columns[0]);
});
this._seriesPicker.init();
},
/**
* Initializes the display of a treemap node element.
*/
_initNode: function (nodeElement, node) {
var $nodeElement = $(nodeElement),
nodeHasUrl = node.data.metadata && node.data.metadata.url,
nodeHasLogo = node.data.metadata && node.data.metadata.logo;
// add label (w/ logo if it exists)
var $label = $('<div></div>').addClass("infoviz-treemap-node-label");
$label.append($('<span></span>').text(node.name));
var leftImage = null;
if (nodeHasLogo) {
leftImage = node.data.metadata.logo;
} else if (nodeHasUrl) {
leftImage = 'plugins/Morpheus/images/link.png';
}
if (leftImage) {
$label.prepend($('<img style="max-height: 16px"></img>').attr('src', leftImage));
}
$nodeElement.append($label);
// set node tooltip
var tooltip = node.name;
if (nodeHasUrl) {
tooltip += ' (' + node.data.metadata.url + ')';
}
if (node.data.metadata
&& node.data.metadata.tooltip
) {
tooltip += ' ' + node.data.metadata.tooltip;
}
$nodeElement.attr('title', tooltip);
// set label color
if (this.labelColor) {
$label.css('color', this.labelColor);
}
// if the node can be clicked into, show a pointer cursor over it
if (this._canEnterNode(node)
|| nodeHasUrl
) {
$nodeElement.addClass("infoviz-treemap-enterable-node");
}
},
/**
* Shows/hides the label depending on whether there's enough vertical space in the node
* to show it.
*/
_toggleLabelBasedOnAvailableSpace: function (nodeElement, node) {
var $nodeElement = $(nodeElement),
$label = $nodeElement.children('span');
$label.toggle($nodeElement.height() > $label.height());
},
/**
* Prepares data obtained from Piwik server-side code to be used w/ the JIT Treemap
* visualization. Will make sure each node ID is unique and has a color.
*/
_prepareTreemapData: function (data) {
if (typeof data == 'string') {
data = JSON.parse(data);
}
this._prependDataTableIdToNodeIds(this.workingDivId, data);
this._setTreemapColors(data);
return data;
},
/**
* Reloads the treemap visualization using this.data.
*/
_refreshTreemap: function (options) {
if (!options.animate) {
this.treemap.config.animate = false;
}
this.treemap.loadJSON(this.data);
this.treemap.refresh();
if (!options.animate) {
this.treemap.config.animate = true;
}
},
/**
* Alters the ID of each node in tree so it will be unique even if more than one treemap
* is displayed.
*/
_prependDataTableIdToNodeIds: function (idPrefix, tree) {
tree.id = idPrefix + '-' + tree.id;
var children = tree.children || [];
for (var i = 0; i != children.length; ++i) {
this._prependDataTableIdToNodeIds(idPrefix, children[i]);
}
},
/**
* Sets the color of each treemap node.
*/
_setTreemapColors: function (root) {
if (this.props.show_evolution_values) {
this._setTreemapColorsFromEvolution(root);
} else {
this._setTreemapColorsNormal(root);
}
},
_setTreemapColorsFromEvolution: function (root) {
// get colors
var colorManager = piwik.ColorManager;
var colorNames = ['no-change', 'negative-change-max', 'positive-change-max', 'label'];
var colors = colorManager.getColors(COLOR_NAMESPACE_EVOLUTION, colorNames);
// find min-max evolution values to make colors relative to
var minEvolution = -100, maxEvolution = 100;
this.foreachNode(function (node) {
var evolution = node.data.evolution || 0;
if (evolution < 0) {
minEvolution = Math.min(minEvolution, evolution);
} else if (evolution > 0) {
maxEvolution = Math.max(maxEvolution, evolution);
}
}, root);
// color each node
var self = this,
negativeChangeColor = colorManager.getRgb(colors['negative-change-max'] || '#f00'),
positiveChangeColor = colorManager.getRgb(colors['positive-change-max'] || '#0f0'),
noChangeColor = colorManager.getRgb(colors['no-change'] || '#333');
this.foreachNode(function (node) {
var evolution = node.data.evolution || 0;
var color;
if (evolution < 0) {
var colorPercent = (minEvolution - evolution) / minEvolution;
color = colorManager.getSingleColorFromGradient(negativeChangeColor, noChangeColor, colorPercent);
} else if (evolution > 0) {
var colorPercent = (maxEvolution - evolution) / maxEvolution;
color = colorManager.getSingleColorFromGradient(positiveChangeColor, noChangeColor, colorPercent);
} else {
color = colors['no-change'];
}
node.data.$color = color;
}, root);
this.labelColor = colors.label;
},
/**
* Sets the color of treemap nodes using pie-graph-colors.
*/
_setTreemapColorsNormal: function (root) {
var normalColor = piwik.ColorManager.getColor(COLOR_NAMESPACE_NORMAL, 'normal-node-color');
this.foreachNode(function (node) {
node.data.$color = normalColor;
}, root);
},
/**
* Event handler for when a node is left-clicked.
*
* This function will enter the node if it can be entered. If it can't be entered, we try
* and open the node's associated URL, if it has one.
*/
_onLeftClickNode: function (node) {
if (!node) {
return;
}
if (this._nodeHasSubtable(node)) {
this._enterSubtable(node);
} else {
this._openNodeUrl(node);
}
},
/**
* Event handler for when a node is middle clicked.
*
* If the node has a url, this function will load the URL in a new tab/window.
*/
_onMiddleClick: function (node) {
if (!node) {
return;
}
this._openNodeUrl(node);
},
/**
* If the given node has an associated URL, it is opened in a new tab/window.
*/
_openNodeUrl: function (node) {
if (node.data.metadata
&& node.data.metadata.url
) {
window.open(node.data.metadata.url, '_blank');
}
},
/**
* Event handler for when a node is right clicked.
*
* This function will advance to the parent of the current node, if it has one.
*/
_onRightClickNode: function (node) {
this._leaveNode();
},
/**
* Enter a treemap node that is a node for a row w/ a subtable.
*/
_enterSubtable: function (node) {
if (node.data.loading) {
return;
}
if (!node.data.loaded) {
var self = this;
this._loadSubtableNodeChildren(node, function (newNode) {
self._enterNode(newNode);
});
} else {
this._enterNode(node);
}
},
/**
* Enters a node and toggles the zoom out link.
*/
_enterNode: function (node) {
this.treemap.enter(node);
this._toggleZoomOut(true);
},
/**
* Leaves a node and toggles the zoom out link if at the root node.
*/
_leaveNode: function () {
this.treemap.out();
this._toggleZoomOut();
},
/**
* Show/hide the zoom out button based on the currently selected node.
*/
_toggleZoomOut: function (toggle) {
var toggle = toggle || (this.treemap.clickedNode && !this._isFirstLevelNode(this.treemap.clickedNode));
$('.infoviz-treemap-zoom-out', this.$element).css('visibility', toggle ? 'visible' : 'hidden');
},
/**
* Returns true if node is a child of the root node, false if it represents a subtable row.
*/
_isFirstLevelNode: function (node) {
var parents = node.getParents();
if (!parents || !parents.length) {
return true;
}
var parent = parents[0];
return !parent || parent.id.indexOf('treemap-root') != -1;
},
/**
* Loads data for a node's subtable without reloading the datatable view.
*/
_loadSubtableNodeChildren: function (node, callback) {
var ajax = this._getNodeChildrenAjax({
idSubtable: node.data.idSubtable
}, node, callback);
ajax.send();
},
/**
* Loads a node's children via AJAX and updates w/o reloading the datatable view.
*/
_getNodeChildrenAjax: function (overrideParams, node, callback) {
var self = this,
dataNode = self._findNodeWithId(node.id),
params = $.extend({}, self.param, overrideParams, {
module: 'API',
method: 'TreemapVisualization.getTreemapData',
action: 'index',
apiMethod: self.param.module + '.' + self.props.subtable_controller_action,
format: 'json',
column: self.param.columns,
show_evolution_values: self.props.show_evolution_values || 0
});
// make sure parallel load data requests aren't made
node.data.loading = dataNode.data.loading = true;
var ajax = new ajaxHelper();
ajax.addParams(params, 'get');
ajax.setLoadingElement('#' + self.workingDivId + ' .loadingPiwikBelow');
ajax.setCallback(function (response) {
dataNode.data.loaded = true;
delete dataNode.data.loading;
var repsonse = self._prepareTreemapData(response);
dataNode.children = response.children;
self._refreshTreemap({animate: false});
callback(self.treemap.graph.getNode(node.id));
});
ajax.setFormat('json');
return ajax;
},
/**
* Returns true if the given node is the node of an aggregate row, false if otherwise.
*/
_isOthersNode: function (node) {
return this._getRowIdFromNode(node) == -1;
},
/**
* Returns true if the given node has a subtable, false if otherwise.
*/
_nodeHasSubtable: function (node) {
return !!node.data.idSubtable;
},
/**
* Returns true if the given node can be entered, false if otherwise.
*
* A node can be entered if it has a subtable.
*/
_canEnterNode: function (node) {
return this._nodeHasSubtable(node);
},
/**
* Returns the ID of the DataTable row associated with a node.
*/
_getRowIdFromNode: function (node) {
return node.id.substring(node.id.lastIndexOf('_') + 1);
},
/**
* Find node in the JSON data used to initialize the Treemap by its ID.
*/
_findNodeWithId: function (id, node) {
if (!node) {
node = this.data;
}
if (node.id == id) {
return node;
}
for (var i = 0; i != node.children.length; ++i) {
var result = this._findNodeWithId(id, node.children[i]);
if (result) {
return result;
}
}
}
});
DataTable.registerFooterIconHandler('infoviz-treemap', function (dataTable, viewDataTableId) {
var filters = dataTable.resetAllFilters();
// make sure only one column is used
var columns = filters.columns || 'nb_visits';
if (columns.indexOf(',') != -1) {
columns = columns.split(',')[0];
}
dataTable.param.columns = columns;
// determine what the width of a treemap will be, by inserting a dummy infoviz-treemap element
// into the DOM
var $wrapper = dataTable.$element.find('.dataTableWrapper'),
$reportHeader = dataTable._findReportHeader(dataTable.$element),
$dummyTreemap = $('<div/>').addClass('infoviz-treemap').css({'visibility': 'hidden', 'position': 'absolute'});
$wrapper.prepend($dummyTreemap);
var width = $dummyTreemap.width(), height = $dummyTreemap.height();
var report = dataTable.$element.attr('data-report'),
isFullpage = fullPageReports[report];
if (isFullpage) {
height = $(window).height() - dataTable.$element.find('.dataTableFeatures').height() - $reportHeader.height() - 20;
}
// send available width & height so we can pick the best number of elements to display
dataTable.param.availableWidth = width;
dataTable.param.availableHeight = height;
dataTable.param.viewDataTable = viewDataTableId;
dataTable.reloadAjaxDataTable(true, function (response) {
dataTable.dataTableLoaded(response, dataTable.workingDivId);
if (isFullpage) {
piwikHelper.lazyScrollTo($reportHeader || dataTable.$element, 400, true);
}
});
dataTable.notifyWidgetParametersChange(dataTable.$element, {
viewDataTable: viewDataTableId,
availableWidth: width,
availableHeight: height,
columns: columns
});
});
}(jQuery, $jit, require));