/
dataTable.js
1978 lines (1663 loc) · 73.4 KB
/
dataTable.js
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
//-----------------------------------------------------------------------------
// DataTable
//-----------------------------------------------------------------------------
(function ($, require) {
var exports = require('piwik/UI'),
UIControl = exports.UIControl;
/**
* This class contains the client side logic for viewing and interacting with
* Piwik datatables.
*
* The id attribute for DataTables is set dynamically by the initNewDataTables
* method, and this class instance is stored using the jQuery $.data function
* with the 'uiControlObject' key.
*
* To find a datatable element by report (ie, 'DevicesDetection.getBrowsers'),
* use piwik.DataTable.getDataTableByReport.
*
* To get the dataTable JS instance (an instance of this class) for a
* datatable HTML element, use $(element).data('uiControlObject').
*
* @constructor
*/
function DataTable(element) {
UIControl.call(this, element);
this.init();
}
DataTable._footerIconHandlers = {};
DataTable.initNewDataTables = function () {
$('div.dataTable').each(function () {
if (!$(this).attr('id')) {
var tableType = $(this).attr('data-table-type') || 'DataTable',
klass = require('piwik/UI')[tableType] || require(tableType);
if (klass && $.isFunction(klass)) {
var table = new klass(this);
}
}
});
};
DataTable.registerFooterIconHandler = function (id, handler) {
var handlers = DataTable._footerIconHandlers;
if (handlers[id]) {
setTimeout(function () { // fail gracefully
throw new Exception("DataTable footer icon handler '" + id + "' is already being used.")
}, 1);
return;
}
handlers[id] = handler;
};
/**
* Returns the first datatable div displaying a specific report.
*
* @param {string} report The report, eg, UserLanguage.getLanguage
* @return {Element} The datatable div displaying the report, or undefined if
* it cannot be found.
*/
DataTable.getDataTableByReport = function (report) {
var result = undefined;
$('div.dataTable').each(function () {
if ($(this).attr('data-report') == report) {
result = this;
return false;
}
});
return result;
};
$.extend(DataTable.prototype, UIControl.prototype, {
_init: function (domElem) {
// initialize your dataTable in your plugin
},
//initialisation function
init: function () {
var domElem = this.$element;
this.workingDivId = this._createDivId();
domElem.attr('id', this.workingDivId);
this.loadedSubDataTable = {};
this.isEmpty = $('.pk-emptyDataTable', domElem).length > 0;
this.bindEventsAndApplyStyle(domElem);
this._init(domElem);
this.initialized = true;
},
//function triggered when user click on column sort
onClickSort: function (domElem) {
var self = this;
var newColumnToSort = $(domElem).attr('id');
// we lookup if the column to sort was already this one, if it is the case then we switch from desc <-> asc
if (self.param.filter_sort_column == newColumnToSort) {
// toggle the sorted order
if (this.param.filter_sort_order == 'asc') {
self.param.filter_sort_order = 'desc';
}
else {
self.param.filter_sort_order = 'asc';
}
}
self.param.filter_offset = 0;
self.param.filter_sort_column = newColumnToSort;
if (!self.isDashboard()) {
self.notifyWidgetParametersChange(domElem, {
filter_sort_column: newColumnToSort,
filter_sort_order: self.param.filter_sort_order
});
}
self.reloadAjaxDataTable();
},
setGraphedColumn: function (columnName) {
this.param.columns = columnName;
},
isWithinDialog: function (domElem) {
return !!$(domElem).parents('.ui-dialog').length;
},
isDashboard: function () {
return !!$('#dashboardWidgetsArea').length;
},
getReportMetadata: function () {
return JSON.parse(this.$element.attr('data-report-metadata') || '{}');
},
//Reset DataTable filters (used before a reload or view change)
resetAllFilters: function () {
var self = this;
var FiltersToRestore = {};
var filters = [
'filter_column',
'filter_pattern',
'filter_column_recursive',
'filter_pattern_recursive',
'enable_filter_excludelowpop',
'filter_offset',
'filter_limit',
'filter_sort_column',
'filter_sort_order',
'disable_generic_filters',
'columns',
'flat',
'include_aggregate_rows',
'totalRows',
'pivotBy',
'pivotByColumn'
];
for (var key = 0; key < filters.length; key++) {
var value = filters[key];
FiltersToRestore[value] = self.param[value];
delete self.param[value];
}
return FiltersToRestore;
},
//Restores the filters to the values given in the array in parameters
restoreAllFilters: function (FiltersToRestore) {
var self = this;
for (var key in FiltersToRestore) {
self.param[key] = FiltersToRestore[key];
}
},
//Translate string parameters to javascript builtins
//'true' -> true, 'false' -> false
//it simplifies condition tests in the code
cleanParams: function () {
var self = this;
for (var key in self.param) {
if (self.param[key] == 'true') self.param[key] = true;
if (self.param[key] == 'false') self.param[key] = false;
}
},
// Function called to trigger the AJAX request
// The ajax request contains the function callback to trigger if the request is successful or failed
// displayLoading = false When we don't want to display the Loading... DIV .loadingPiwik
// for example when the script add a Loading... it self and doesn't want to display the generic Loading
reloadAjaxDataTable: function (displayLoading, callbackSuccess) {
var self = this;
if (typeof displayLoading == "undefined") {
displayLoading = true;
}
if (typeof callbackSuccess == "undefined") {
callbackSuccess = function (response) {
self.dataTableLoaded(response, self.workingDivId);
};
}
if (displayLoading) {
$('#' + self.workingDivId + ' .loadingPiwik').last().css('display', 'block');
}
$('#loadingError').hide();
// when switching to display graphs, reset limit
if (self && self.param && self.param.viewDataTable && String(self.param.viewDataTable).indexOf('graph') === 0) {
delete self.param.filter_offset;
delete self.param.filter_limit;
}
var container = $('#' + self.workingDivId + ' .piwik-graph');
var params = {};
for (var key in self.param) {
if (typeof self.param[key] != "undefined" && self.param[key] != '')
params[key] = self.param[key];
}
var ajaxRequest = new ajaxHelper();
ajaxRequest.addParams(params, 'get');
ajaxRequest.setCallback(
function (response) {
container.trigger('piwikDestroyPlot');
container.off('piwikDestroyPlot');
callbackSuccess(response);
}
);
ajaxRequest.setErrorCallback(function (deferred, status) {
if (status == 'abort' || !deferred || deferred.status < 400 || deferred.status >= 600) {
return;
}
$('#' + self.workingDivId + ' .loadingPiwik').last().css('display', 'none');
$('#loadingError').show();
});
ajaxRequest.setFormat('html');
ajaxRequest.send(false);
},
// Function called when the AJAX request is successful
// it looks for the ID of the response and replace the very same ID
// in the current page with the AJAX response
dataTableLoaded: function (response, workingDivId) {
var content = $(response);
var idToReplace = workingDivId || $(content).attr('id');
var dataTableSel = $('#' + idToReplace);
// if the current dataTable is located inside another datatable
table = $(content).parents('table.dataTable');
if (dataTableSel.parents('.dataTable').is('table')) {
// we add class to the table so that we can give a different style to the subtable
$(content).find('table.dataTable').addClass('subDataTable');
$(content).find('.dataTableFeatures').addClass('subDataTable');
//we force the initialisation of subdatatables
dataTableSel.replaceWith(content);
}
else {
dataTableSel.find('object').remove();
dataTableSel.replaceWith(content);
}
content.trigger('piwik:dataTableLoaded');
piwikHelper.lazyScrollTo(content[0], 400);
return content;
},
/* This method is triggered when a new DIV is loaded, which happens
- at the first loading of the page
- after any AJAX loading of a DataTable
This method basically add features to the DataTable,
- such as column sorting, searching in the rows, displaying Next / Previous links, etc.
- add styles to the cells and rows (odd / even styles)
- modify some rows to add images if a span img is found, or add a link if a span urlLink is found
- bind new events onclick / hover / etc. to trigger AJAX requests,
nice hovertip boxes for truncated cells
*/
bindEventsAndApplyStyle: function (domElem) {
var self = this;
self.cleanParams();
self.handleSort(domElem);
self.handleLimit(domElem);
self.handleSearchBox(domElem);
self.handleOffsetInformation(domElem);
self.handleAnnotationsButton(domElem);
self.handleEvolutionAnnotations(domElem);
self.handleExportBox(domElem);
self.applyCosmetics(domElem);
self.handleSubDataTable(domElem);
self.handleConfigurationBox(domElem);
self.handleColumnDocumentation(domElem);
self.handleRowActions(domElem);
self.handleCellTooltips(domElem);
self.handleRelatedReports(domElem);
self.handleTriggeredEvents(domElem);
self.handleColumnHighlighting(domElem);
self.handleExpandFooter(domElem);
self.setFixWidthToMakeEllipsisWork(domElem);
self.handleSummaryRow(domElem);
},
setFixWidthToMakeEllipsisWork: function (domElem) {
var self = this;
function isWidgetized()
{
return -1 !== location.search.indexOf('module=Widgetize');
}
function getTableWidth(domElem)
{
var totalWidth = $(domElem).width();
var totalWidthTable = $('table.dataTable', domElem).width(); // fixes tables in dbstats, referrers, ...
if (totalWidthTable < totalWidth) {
totalWidth = totalWidthTable;
}
if (!totalWidth) {
totalWidth = 0;
}
return parseInt(totalWidth, 10);
}
function setMaxTableWidthIfNeeded (domElem, maxTableWidth)
{
var tableWidth = getTableWidth(domElem);
if (tableWidth <= maxTableWidth) {
return;
}
if (isWidgetized() || self.isDashboard()) {
return;
}
$(domElem).width(maxTableWidth);
var parentDataTable = $(domElem).parent('.dataTable');
if (parentDataTable && parentDataTable.length) {
// makes sure dataTableWrapper and DataTable has same size => makes sure maxLabelWidth does not get
// applied in getLabelWidth() since they will have the same size.
parentDataTable.width(maxTableWidth);
}
}
function getLabelWidth(domElem, tableWidth, minLabelWidth, maxLabelWidth)
{
var labelWidth = minLabelWidth;
var columnsInFirstRow = $('tr:nth-child(1) td:not(.label)', domElem);
var widthOfAllColumns = 0;
columnsInFirstRow.each(function (index, column) {
widthOfAllColumns += $(column).outerWidth();
});
if (tableWidth - widthOfAllColumns >= minLabelWidth) {
labelWidth = tableWidth - widthOfAllColumns;
} else if (widthOfAllColumns >= tableWidth) {
labelWidth = tableWidth * 0.5;
}
var innerWidth = 0;
var innerWrapper = domElem.find('.dataTableWrapper');
if (innerWrapper && innerWrapper.length) {
innerWidth = innerWrapper.width();
}
if (labelWidth > maxLabelWidth
&& !isWidgetized()
&& innerWidth !== domElem.width()
&& !self.isDashboard()) {
labelWidth = maxLabelWidth; // prevent for instance table in Actions-Pages is not too wide
}
return parseInt(labelWidth, 10);
}
function getLabelColumnMinWidth(domElem)
{
var minWidth = 0;
var minWidthHead = $('thead .first.label', domElem).css('minWidth');
if (minWidthHead) {
minWidth = parseInt(minWidthHead, 10);
}
var minWidthBody = $('tbody tr:nth-child(1) td.label', domElem).css('minWidth');
if (minWidthBody) {
minWidthBody = parseInt(minWidthBody, 10);
if (minWidthBody && minWidthBody > minWidth) {
minWidth = minWidthBody;
}
}
return parseInt(minWidth, 10);
}
function removePaddingFromWidth(domElem, labelWidth) {
var maxPaddingLeft = 0;
var maxPaddingRight = 0;
$('tbody tr td.label', domElem).each(function (i, node) {
$node = $(node);
var paddingLeft = $node.css('paddingLeft');
paddingLeft = paddingLeft ? Math.round(parseFloat(paddingLeft)) : 0;
var paddingRight = $node.css('paddingRight');
paddingRight = paddingRight ? Math.round(parseFloat(paddingLeft)) : 0;
if (paddingLeft > maxPaddingLeft) {
maxPaddingLeft = paddingLeft;
}
if (paddingRight > maxPaddingRight) {
maxPaddingRight = paddingRight;
}
});
labelWidth = labelWidth - maxPaddingLeft - maxPaddingRight;
return labelWidth;
}
var minLabelWidth = 125;
var maxLabelWidth = 440;
setMaxTableWidthIfNeeded(domElem, 1200);
var tableWidth = getTableWidth(domElem);
var labelColumnMinWidth = getLabelColumnMinWidth(domElem);
var labelColumnWidth = getLabelWidth(domElem, tableWidth, 125, 440);
if (labelColumnMinWidth > labelColumnWidth) {
labelColumnWidth = labelColumnMinWidth;
}
labelColumnWidth = removePaddingFromWidth(domElem, labelColumnWidth);
if (labelColumnWidth) {
$('td.label', domElem).width(labelColumnWidth);
}
$('td span.label', domElem).each(function () { self.tooltip($(this)); });
},
handleLimit: function (domElem) {
var tableRowLimits = piwik.config.datatable_row_limits,
evolutionLimits =
{
day: [30, 60, 90, 180, 365, 500],
week: [4, 12, 26, 52, 104, 500],
month: [3, 6, 12, 24, 36, 120],
year: [3, 5, 10]
};
var self = this;
if (typeof self.parentId != "undefined" && self.parentId != '') {
// no limit selector for subtables
$('.limitSelection', domElem).remove();
return;
}
// configure limit control
var setLimitValue, numbers, limitParamName;
if (self.param.viewDataTable == 'graphEvolution') {
limitParamName = 'evolution_' + self.param.period + '_last_n';
numbers = evolutionLimits[self.param.period] || tableRowLimits;
setLimitValue = function (params, limit) {
params[limitParamName] = limit;
};
}
else {
numbers = tableRowLimits;
limitParamName = 'filter_limit';
setLimitValue = function (params, value) {
params.filter_limit = value;
params.filter_offset = 0;
};
}
function getFilterLimitAsString(limit) {
if (limit == '-1') {
return _pk_translate('General_All').toLowerCase();
}
return limit;
}
// setup limit control
$('.limitSelection', domElem).append('<div><span value="'+ self.param[limitParamName] +'">' + getFilterLimitAsString(self.param[limitParamName]) + '</span></div><ul></ul>');
if (self.props.show_limit_control) {
$('.limitSelection ul', domElem).hide();
for (var i = 0; i < numbers.length; i++) {
$('.limitSelection ul', domElem).append('<li value="' + numbers[i] + '"><span>' + getFilterLimitAsString(numbers[i]) + '</span></li>');
}
$('.limitSelection ul li:last', domElem).addClass('last');
if (!self.isEmpty) {
var show = function() {
$('.limitSelection ul', domElem).show();
$('.limitSelection', domElem).addClass('visible');
$(document).on('mouseup.limitSelection', function(e) {
if (!$(e.target).closest('.limitSelection').length) {
hide();
}
});
};
var hide = function () {
$('.limitSelection ul', domElem).hide();
$('.limitSelection', domElem).removeClass('visible');
$(document).off('mouseup.limitSelection');
};
$('.limitSelection div', domElem).on('click', function () {
$('.limitSelection', domElem).is('.visible') ? hide() : show();
});
$('.limitSelection ul li', domElem).on('click', function (event) {
var limit = parseInt($(event.target).closest('li').attr('value'));
hide();
if (limit != self.param[limitParamName]) {
setLimitValue(self.param, limit);
$('.limitSelection>div>span', domElem).text( getFilterLimitAsString(limit)).attr('value', limit);
self.reloadAjaxDataTable();
var data = {};
data[limitParamName] = self.param[limitParamName];
self.notifyWidgetParametersChange(domElem, data);
}
});
}
else {
$('.limitSelection', domElem).toggleClass('disabled');
}
}
else {
$('.limitSelection', domElem).hide();
}
},
// if sorting the columns is enabled, when clicking on a column,
// - if this column was already the one used for sorting, we revert the order desc<->asc
// - we send the ajax request with the new sorting information
handleSort: function (domElem) {
var self = this;
if (self.props.enable_sort) {
$('.sortable', domElem).off('click.dataTableSort').on('click.dataTableSort',
function () {
$(this).off('click.dataTableSort');
self.onClickSort(this);
}
);
}
if (self.param.filter_sort_column) {
// are we in a subdatatable?
var currentIsSubDataTable = $(domElem).parent().hasClass('cellSubDataTable');
var imageSortClassType = currentIsSubDataTable ? 'sortSubtable' : ''
var imageSortWidth = 16;
var imageSortHeight = 16;
var sortOrder = self.param.filter_sort_order || 'desc';
// we change the style of the column currently used as sort column
// adding an image and the class columnSorted to the TD
var head = $('th', domElem).filter(function () {
return $(this).attr('id') == self.param.filter_sort_column;
}).addClass('columnSorted');
var sortIconHtml = '<span class="sortIcon ' + sortOrder + ' ' + imageSortClassType +'" width="' + imageSortWidth + '" height="' + imageSortHeight + '" />';
var div = head.find('.thDIV');
if (head.hasClass('first') || head.attr('id') == 'label') {
div.append(sortIconHtml);
} else {
div.prepend(sortIconHtml);
}
}
},
//behaviour for the DataTable 'search box'
handleSearchBox: function (domElem, callbackSuccess) {
var self = this;
var currentPattern = self.param.filter_pattern;
if (typeof self.param.filter_pattern != "undefined"
&& self.param.filter_pattern.length > 0) {
currentPattern = self.param.filter_pattern;
}
else if (typeof self.param.filter_pattern_recursive != "undefined"
&& self.param.filter_pattern_recursive.length > 0) {
currentPattern = self.param.filter_pattern_recursive;
}
else {
currentPattern = '';
}
currentPattern = piwikHelper.htmlDecode(currentPattern);
var patternsToReplace = [{from: '?', to: '\\?'}, {from: '+', to: '\\+'}, {from: '*', to: '\\*'}]
$.each(patternsToReplace, function (index, pattern) {
if (0 === currentPattern.indexOf(pattern.to)) {
currentPattern = pattern.from + currentPattern.substr(2);
}
});
$('.dataTableSearchPattern', domElem)
.css({display: 'block'})
.each(function () {
// when enter is pressed in the input field we submit the form
$('.searchInput', this)
.on("keyup",
function (e) {
if (isEnterKey(e)) {
$(this).siblings(':submit').submit();
}
}
)
.val(currentPattern)
;
$(':submit', this).submit(
function () {
var keyword = $(this).siblings('.searchInput').val();
self.param.filter_offset = 0;
$.each(patternsToReplace, function (index, pattern) {
if (0 === keyword.indexOf(pattern.from)) {
keyword = pattern.to + keyword.substr(1);
}
});
if (self.param.search_recursive) {
self.param.filter_column_recursive = 'label';
self.param.filter_pattern_recursive = keyword;
}
else {
self.param.filter_column = 'label';
self.param.filter_pattern = keyword;
}
delete self.param.totalRows;
self.reloadAjaxDataTable(true, callbackSuccess);
}
);
$(':submit', this)
.click(function () { $(this).submit(); })
;
// in the case there is a searched keyword we display the RESET image
if (currentPattern) {
var target = this;
var clearImg = $('<span class="searchReset">\
<img src="plugins/CoreHome/images/reset_search.png" title="Clear" />\
</span>')
.click(function () {
$('.searchInput', target).val('');
$(':submit', target).submit();
});
$('.searchInput', this).after(clearImg);
}
}
);
if (this.isEmpty && !currentPattern) {
$('.dataTableSearchPattern', domElem).hide();
}
},
//behaviour for '< prev' 'next >' links and page count
handleOffsetInformation: function (domElem) {
var self = this;
$('.dataTablePages', domElem).each(
function () {
var offset = 1 + Number(self.param.filter_offset);
var offsetEnd = Number(self.param.filter_offset) + Number(self.param.filter_limit);
var totalRows = Number(self.param.totalRows);
var offsetEndDisp = offsetEnd;
if (self.param.keep_summary_row == 1) --totalRows;
if (offsetEnd > totalRows || Number(self.param.filter_limit) == -1) offsetEndDisp = totalRows;
// only show this string if there is some rows in the datatable
if (totalRows != 0) {
var str = sprintf(_pk_translate('CoreHome_PageOf'), offset + '-' + offsetEndDisp, totalRows);
$(this).text(str);
} else {
$(this).hide();
}
}
);
var $next = $('.dataTableNext', domElem);
// Display the next link if the total Rows is greater than the current end row
$next.each(function () {
var offsetEnd = Number(self.param.filter_offset)
+ Number(self.param.filter_limit);
var totalRows = Number(self.param.totalRows);
if (self.param.keep_summary_row == 1) --totalRows;
if (offsetEnd < totalRows && Number(self.param.filter_limit) != -1) {
$(this).css('display', 'inline');
}
});
// bind the click event to trigger the ajax request with the new offset
$next.off('click');
$next.click(function () {
$(this).off('click');
self.param.filter_offset = Number(self.param.filter_offset) + Number(self.param.filter_limit);
self.reloadAjaxDataTable();
});
var $prev = $('.dataTablePrevious', domElem);
// Display the previous link if the current offset is not zero
$prev.each(function () {
var offset = 1 + Number(self.param.filter_offset);
if (offset != 1) {
$(this).css('display', 'inline');
}
});
// bind the click event to trigger the ajax request with the new offset
// take care of the negative offset, we setup 0
$prev.off('click');
$prev.click(function () {
$(this).off('click');
var offset = Number(self.param.filter_offset) - Number(self.param.filter_limit);
if (offset < 0) { offset = 0; }
self.param.filter_offset = offset;
self.param.previous = 1;
self.reloadAjaxDataTable();
});
},
handleEvolutionAnnotations: function (domElem) {
var self = this;
if (self.param.viewDataTable == 'graphEvolution'
&& $('.annotationView', domElem).length > 0) {
// get dates w/ annotations across evolution period (have to do it through AJAX since we
// determine placement using the elements created by jqplot)
$('.dataTableFeatures', domElem).addClass('hasEvolution');
piwik.annotations.api.getEvolutionIcons(
self.param.idSite,
self.param.date,
self.param.period,
self.param['evolution_' + self.param.period + '_last_n'],
function (response) {
var annotations = $(response),
datatableFeatures = $('.dataTableFeatures', domElem),
noteSize = 16,
annotationAxisHeight = 30 // css height + padding + margin
;
var annotationsCss = {left: 6}; // padding-left of .jqplot-graph element (in _dataTableViz_jqplotGraph.tpl)
// set position of evolution annotation icons
annotations.css(annotationsCss);
piwik.annotations.placeEvolutionIcons(annotations, domElem);
// add new section under axis
annotations.insertAfter($('.datatableRelatedReports', domElem));
// reposition annotation icons every time the graph is resized
$('.piwik-graph', domElem).on('resizeGraph', function () {
piwik.annotations.placeEvolutionIcons(annotations, domElem);
});
// on hover of x-axis, show note icon over correct part of x-axis
datatableFeatures.on('mouseenter', '.evolution-annotations>span', function () {
$(this).css('opacity', 1);
});
datatableFeatures.on('mouseleave', '.evolution-annotations>span', function () {
if ($(this).attr('data-count') == 0) // only hide if there are no annotations for this note
{
$(this).css('opacity', 0);
}
});
// when clicking an annotation, show the annotation viewer for that period
datatableFeatures.on('click', '.evolution-annotations>span', function () {
var spanSelf = $(this),
date = spanSelf.attr('data-date'),
oldDate = $('.annotation-manager', domElem).attr('data-date');
if (date) {
var period = self.param.period;
if (period == 'range') {
period = 'day';
}
piwik.annotations.showAnnotationViewer(
domElem,
self.param.idSite,
date,
period,
undefined, // lastN
function (manager) {
manager.attr('data-is-range', 0);
$('.annotationView img', domElem)
.attr('title', _pk_translate('Annotations_IconDesc'));
var viewAndAdd = _pk_translate('Annotations_ViewAndAddAnnotations'),
hideNotes = _pk_translate('Annotations_HideAnnotationsFor');
// change the tooltip of the previously clicked evolution icon (if any)
if (oldDate) {
$('span', annotations).each(function () {
if ($(this).attr('data-date') == oldDate) {
$(this).attr('title', sprintf(viewAndAdd, oldDate));
return false;
}
});
}
// change the tooltip of the clicked evolution icon
if (manager.is(':hidden')) {
spanSelf.attr('title', sprintf(viewAndAdd, date));
}
else {
spanSelf.attr('title', sprintf(hideNotes, date));
}
}
);
}
});
// when hover over annotation in annotation manager, highlight the annotation
// icon
var runningAnimation = null;
domElem.on('mouseenter', '.annotation', function (e) {
var date = $(this).attr('data-date');
// find the icon for this annotation
var icon = $();
$('span', annotations).each(function () {
if ($(this).attr('data-date') == date) {
icon = $('img', this);
return false;
}
});
if (icon[0] == runningAnimation) // if the animation is already running, do nothing
{
return;
}
// stop ongoing animations
$('span', annotations).each(function () {
$('img', this).removeAttr('style');
});
// start a bounce animation
icon.effect("bounce", {times: 1, distance: 10}, 1000);
runningAnimation = icon[0];
});
// reset running animation item when leaving annotations list
domElem.on('mouseleave', '.annotations', function (e) {
runningAnimation = null;
});
self.$element.trigger('piwik:annotationsLoaded');
}
);
}
},
handleAnnotationsButton: function (domElem) {
var self = this;
if (self.param.idSubtable) // no annotations for subtables, just whole reports
{
return;
}
// show the annotations view on click
$('.annotationView', domElem).click(function () {
var annotationManager = $('.annotation-manager', domElem);
if (annotationManager.length > 0
&& annotationManager.attr('data-is-range') == 1) {
if (annotationManager.is(':hidden')) {
annotationManager.slideDown('slow'); // showing
$('img', this).attr('title', _pk_translate('Annotations_IconDescHideNotes'));
}
else {
annotationManager.slideUp('slow'); // hiding
$('img', this).attr('title', _pk_translate('Annotations_IconDesc'));
}
}
else {
// show the annotation viewer for the whole date range
var lastN = self.param['evolution_' + self.param.period + '_last_n'];
piwik.annotations.showAnnotationViewer(
domElem,
self.param.idSite,
self.param.date,
self.param.period,
lastN,
function (manager) {
manager.attr('data-is-range', 1);
}
);
// change the tooltip of the view annotation icon
$('img', this).attr('title', _pk_translate('Annotations_IconDescHideNotes'));
}
});
},
// DataTable view box (simple table, all columns table, Goals table, pie graph, tag cloud, graph, ...)
handleExportBox: function (domElem) {
var self = this;
if (self.param.idSubtable) {
// no view box for subtables
return;
}
// When the (+) image is hovered, the export buttons are displayed
$('.dataTableFooterIconsShow', domElem)
.show()
.hover(function () {
$(this).fadeOut('slow');
$('.exportToFormatIcons', $(this).parent()).show('slow');
}, function () {}
);
//footer arrow position element name
self.jsViewDataTable = self.param.viewDataTable;
$('.tableAllColumnsSwitch a', domElem).show();
$('.dataTableFooterIcons .tableIcon', domElem).click(function () {
var id = $(this).attr('data-footer-icon-id');
if (!id) {
return;
}
var handler = DataTable._footerIconHandlers[id];
if (!handler) {
handler = DataTable._footerIconHandlers['table'];
}
handler(self, id);
});
//Graph icon Collapsed functionality
self.currentGraphViewIcon = 0;
self.graphViewEnabled = 0;
self.graphViewStartingThreads = 0;
self.graphViewStartingKeep = false; //show keep flag
//define collapsed icons
$('.tableGraphCollapsed a', domElem)
.each(function (i) {
if (self.jsViewDataTable == $(this).attr('data-footer-icon-id')) {
self.currentGraphViewIcon = i;
self.graphViewEnabled = true;
}
})
.each(function (i) {
if (self.currentGraphViewIcon != i) $(this).hide();
});