Welcome to mirror list, hosted at ThFree Co, Russian Federation.

treemapViz.js « javascripts « TreemapVisualization « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 37013a08c56a337a35b37b0c3aed588e5d747ec5 (plain)
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
/*!
 * Piwik - Web Analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

(function ($, $jit, require) {

    var dataTable = window.dataTable,
        dataTablePrototype = dataTable.prototype;

    /**
     * Class that handles UI behavior for the treemap visualization.
     */
    window.TreemapDataTable = function () {
        dataTable.call(this);
    };

    $.extend(window.TreemapDataTable.prototype, dataTablePrototype, {

        /**
         * Constructor.
         * 
         * @param {String} workingDivId The HTML ID of the data table DOM element.
         * @param {Element} [domElem] The DOM element of the data table.
         */
        init: function (workingDivId, domElem) {
            if (typeof domElem == "undefined") {
                domElem = $('#' + workingDivId);
            }

            dataTablePrototype.init.call(this, workingDivId, domElem);

            var treemapContainerId = this.workingDivId + '-infoviz-treemap';
            var treemapContainer = $('.infoviz-treemap', domElem).attr('id', treemapContainerId);

            if (!treemapContainer[0]) {
                return;
            }

            this._bindEventCallbacks(domElem);

            var 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: (self.props.depth || 0) + 1,
                constrained: true,
                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;
            });
        },

        /**
         * 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('.dataTableWrapper').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/Zeitgeist/images/link.gif';
            }

            if (leftImage) {
                $label.prepend($('<img></img>').attr('src', leftImage));
            }

            $nodeElement.append($label);

            // set node tooltip
            if (nodeHasUrl) {
                var tooltip = node.data.metadata.url;
            } else {
                var tooltip = node.name;
            }
            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('infoviz-treemap-evolution-colors', 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 seriesColorNames = ['series1', 'series2', 'series3', 'series4', 'series5',
                                    'series6', 'series7', 'series8', 'series9', 'series10'];
            var colors = piwik.ColorManager.getColors('pie-graph-colors', seriesColorNames, true);

            var colorIdx = 0;
            this.foreachNode(function (node) {
                node.data.$color = colors[colorIdx];
                colorIdx = (colorIdx + 1) % colors.length;
            }, 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._isOthersNode(node)) {
                this._enterOthersNode(node);
            } else 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();
        },

        /**
         * Enters a treemap node that is a node for an aggregate row.
         */
        _enterOthersNode: function (node) {
            if (node.data.loading) {
                return;
            }

            if (!node.data.loaded) {
                var self = this;
                this._loadOthersNodeChildren(node, function (newNode) {
                    self._enterNode(newNode);
                });
            } else {
                this._enterNode(node);
            }
        },

        /**
         * 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) {
            $('.infoviz-treemap-zoom-out', this.$element).css('visibility', toggle || !this.treemap.clickedNode ? 'visible' : 'hidden');
        },

        /**
         * Loads data for an aggregate row's node without reloading the datatable view.
         */
        _loadOthersNodeChildren: function (node, callback) {
            var ajax = this._getNodeChildrenAjax({filter_offset: node.data.aggregate_offset}, node, callback);
            ajax.send();
        },

        /**
         * 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 = this._findNodeWithId(node.id),
                params = $.extend({}, this.param, overrideParams, {
                    module: 'API',
                    method: 'TreemapVisualization.getTreemapData',
                    action: 'index',
                    apiMethod: this.param.module + '.' + this.param.action, // TODO: will this work for all subtables?
                    format: 'json',
                    column: this.param.columns,
                    truncateAfter: this.props.max_graph_elements - 1,
                    filter_limit: -1,
                    expanded: 1,
                    depth: this.props.depth || 1,
                    show_evolution_values: this.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 is the node for an aggregate row or has a subtable.
         */
        _canEnterNode: function (node) {
            return this._isOthersNode(node) || 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;
                }
            }
        }
    });

}(jQuery, $jit, require));