-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathdataTable.js
2023 lines (1685 loc) · 75.6 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
/*!
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://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 (reportId) {
var selector = typeof reportId === 'string' ? '[data-report='+JSON.stringify(reportId)+']' : 'div.dataTable';
$(selector).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
},
_destroy: function() {
UIControl.prototype._destroy.call(this);
// remove handlers to avoid memory leaks
if (this.windowResizeTableAttached) {
$(window).off('resize', this._resizeDataTable);
}
if (this._bodyMouseUp) {
$('body').off('mouseup', this._bodyMouseUp);
}
},
//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;
window.Vue.nextTick().then(() => {
this.bindEventsAndApplyStyle(domElem);
this._init(domElem);
this.enableStickHead(domElem);
this.initialized = true;
});
},
enableStickHead: function (domElem) {
var resizeTimeout = null;
var resize = function(domElem) {
var tableScroller = $(domElem).find('.dataTableScroller');
var tableScrollerWidth = tableScroller.width();
var tableWidth = $(domElem).find('table').width();
if (tableScrollerWidth < tableWidth) {
tableScroller.css('overflow-x', 'scroll');
} else {
tableScroller.css('overflow-x', '');
}
};
// Bind to the resize event of the window object
$(window).on('resize', function () {
resize(domElem);
// trigger another check after a certain delay as during fast resizing
// the width is sometimes reported incorrectly
if (resizeTimeout) {
window.clearTimeout(resizeTimeout);
}
resizeTimeout = window.setTimeout(function(){
resize(domElem);
}, 500);
// Invoke the resize event immediately
}).resize();
},
//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',
'totals',
'include_aggregate_rows',
'totalRows',
'pivotBy',
'pivotByColumn',
'filter_trigger_id'
];
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, extraParams) {
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;
}
delete self.param.showtitle;
var container = $('#' + self.workingDivId + ' .piwik-graph');
var ajaxRequest = new ajaxHelper();
if (self.param.totalRows) {
ajaxRequest.addParams({'totalRows': self.param.totalRows}, 'post');
delete self.param.totalRows;
}
var params = {};
for (var key in self.param) {
if (typeof self.param[key] != "undefined" && self.param[key] !== null && self.param[key] !== '') {
if (key == 'filter_column' || key == 'filter_column_recursive' ) {
// search in (metadata) `combinedLabel` when dimensions are shown separately in flattened tables
// needs to be overwritten for each request as switching a searched table might return no results
// otherwise, as search column doesn't fit anymore
if (self.param.flat == "1" && self.param.show_dimensions == "1") {
params[key] = 'combinedLabel';
} else {
params[key] = 'label';
}
continue;
}
params[key] = self.param[key];
}
}
ajaxRequest.addParams(params, 'get');
if (extraParams) {
ajaxRequest.addParams(extraParams, 'post');
}
ajaxRequest.withTokenInUrl();
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();
},
// 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, doScroll) {
var content = $(response);
if ($.trim($('.dataTableControls', content).html()) === '') {
$('.dataTableControls', content).append(' ');
// fix table controls are not visible because there is no content. prevents limit selection being displayed
// in the middle
}
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');
if (doScroll || 'undefined' === typeof doScroll) {
piwikHelper.lazyScrollTo(content[0], 400);
}
piwikHelper.compileVueEntryComponents(content);
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.preBindEventsAndApplyStyleHook(domElem);
self.handleSort(domElem);
self.handleLimit(domElem);
self.handlePeriod(domElem);
self.handleOffsetInformation(domElem);
self.handleAnnotationsButton(domElem);
self.handleEvolutionAnnotations(domElem);
self.handleExportBox(domElem);
self.applyCosmetics(domElem);
self.handleSubDataTable(domElem);
self.handleConfigurationBox(domElem);
self.handleSearchBox(domElem);
self.handleColumnDocumentation(domElem);
self.handleRowActions(domElem);
self.handleCellTooltips(domElem);
self.handleRelatedReports(domElem);
self.handleTriggeredEvents(domElem);
self.handleColumnHighlighting(domElem);
self.setFixWidthToMakeEllipsisWork(domElem);
self.handleSummaryRow(domElem);
self.postBindEventsAndApplyStyleHook(domElem);
},
preBindEventsAndApplyStyleHook: function (domElem) {
},
postBindEventsAndApplyStyleHook: function (domElem) {
},
isWidgetized: function () {
return -1 !== location.search.indexOf('module=Widgetize');
},
setFixWidthToMakeEllipsisWork: function (domElem) {
var self = this;
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 getLabelWidth(domElem, tableWidth, minLabelWidth, maxLabelWidth)
{
var labelWidth = minLabelWidth;
var columnsInFirstRow = $('tbody tr:not(.parentComparisonRow):not(.comparePeriod):eq(0) 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
&& !self.isWidgetized()
&& innerWidth !== domElem.width()
&& !self.isDashboard()
) {
labelWidth = maxLabelWidth; // prevent for instance table in Actions-Pages is not too wide
}
var allColumns = $('tr:nth-child(1) td.label', domElem).length;
var firstTableColumn = $('table:first tbody>tr:first td.label', domElem).length;
var amount = allColumns;
if (allColumns > 2 * firstTableColumn) {
amount = 2 * firstTableColumn;
}
var newWidth = parseInt(labelWidth / amount, 10)
if (newWidth == 0) {
newWidth = maxLabelWidth; // fallback to the maximum width if zero
}
return newWidth;
}
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 getLabelColumnMaxWidth(domElem)
{
var maxWidth = 0;
var maxWidthHead = $('thead .first.label', domElem).css('maxWidth');
if (maxWidthHead) {
maxWidthHead = parseInt(maxWidthHead, 10);
if (maxWidthHead > 0) {
maxWidth = parseInt(maxWidthHead, 10);
}
}
var maxWidthBody = $('tbody tr:nth-child(1) td.label', domElem).css('maxWidth');
if (maxWidthBody) {
maxWidthBody = parseInt(maxWidthBody, 10);
if (maxWidthBody && maxWidthBody > 0 && (maxWidth === 0 || maxWidthBody < maxWidth)) {
maxWidth = maxWidthBody;
}
}
return parseInt(maxWidth, 10);
}
function removePaddingFromWidth(elem, labelWidth) {
var paddingLeft = elem.css('paddingLeft');
paddingLeft = paddingLeft ? Math.round(parseFloat(paddingLeft)) : 0;
var paddingRight = elem.css('paddingRight');
paddingRight = paddingRight ? Math.round(parseFloat(paddingRight)) : 0;
if (elem.find('.prefix-numeral').length) {
labelWidth -= Math.round(parseFloat(elem.find('.prefix-numeral').outerWidth()));
}
return labelWidth - paddingLeft - paddingRight;
}
var isTableVisualization = this.param.viewDataTable
&& typeof this.param.viewDataTable === 'string'
&& typeof this.param.viewDataTable.indexOf === 'function'
&& this.param.viewDataTable.indexOf('table') !== -1;
if (isTableVisualization) {
// we do this only for html tables
var tableWidth = getTableWidth(domElem);
var labelColumnMinWidth = getLabelColumnMinWidth(domElem);
var labelColumnMaxWidth = getLabelColumnMaxWidth(domElem);
var labelColumnWidth = getLabelWidth(
domElem,
tableWidth,
self.props.min_label_width || 125,
self.props.max_label_width || 440
);
if (labelColumnMinWidth > labelColumnWidth) {
labelColumnWidth = labelColumnMinWidth;
}
if (labelColumnMaxWidth && labelColumnMaxWidth < labelColumnWidth) {
labelColumnWidth = labelColumnMaxWidth;
}
// special handling if the loaded datatable is a subtable
if ($(domElem).closest('.subDataTableContainer').length) {
var parentTable = $(domElem).closest('table.dataTable');
var tableColumns = $('table:eq(0)>thead th', domElem).length;
var parentTableColumns = $('>thead th', parentTable).length;
var labelColumn = $('>tbody td.label:eq(0)', parentTable);
var labelWidthParentTable = labelColumn.outerWidth();
// if the subtable has the same column count as the main table, we rearrange all tables
if (parentTableColumns === tableColumns) {
labelColumnWidth = Math.min(labelColumnWidth, labelWidthParentTable);
// rearrange base table labels, so the tables are displayed aligned
$('>tbody>tr:not(.subDataTableContainer)>td.label', parentTable).each(function() {
$(this).css({
width: removePaddingFromWidth($(this), labelColumnWidth) + 'px'
});
});
// rearrange all subtables having the same column count
$('>tbody>tr.subDataTableContainer', parentTable).each(function() {
if ($('table:eq(0)>thead th', this).length === parentTableColumns) {
$(this).css({
width: removePaddingFromWidth($(this), labelColumnWidth) + 'px'
});
}
});
}
}
if (labelColumnWidth) {
$('td.label', domElem).each(function() {
$(this).css({
width: removePaddingFromWidth($(this), labelColumnWidth) + 'px'
});
});
}
$('td span.label', domElem).each(function () { self.tooltip($(this)); });
}
if (!self.windowResizeTableAttached) {
self.windowResizeTableAttached = true;
// on resize of the window we re-calculate everything.
var timeout = null;
var windowWidth = 0;
var resizeDataTable = function() {
if (windowWidth === $(window).width()) {
return; // only resize a data table if the width changes
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
var isInDom = domElem && domElem[0] && document && document.body && document.body.contains(domElem[0]);
if (isInDom) {
// as domElem might have been removed by now we check whether domElem actually still is in dom
// and do this expensive operation only if needed.
if (isTableVisualization) {
$('td.label', domElem).width('');
}
self.setFixWidthToMakeEllipsisWork(domElem);
windowWidth = $(window).width();
} else {
$(window).off('resize', resizeDataTable);
}
timeout = null;
}, Math.floor((Math.random() * 80) + 220));
// we randomize it just a little to not process all dataTables at similar time but to have a little
// delay in between for smoother resizing. we want to do it between 300 and 400ms
}
$(window).on('resize', resizeDataTable);
self._resizeDataTable = resizeDataTable;
}
},
handleLimit: function (domElem) {
var tableRowLimits = this.props.datatable_row_limits || piwik.config.datatable_row_limits,
evolutionLimits =
{
day: [8, 30, 60, 90, 180],
week: [4, 12, 26, 52, 104],
month: [3, 6, 12, 24, 36, 120],
year: [3, 5, 10]
};
// only allow big evolution limits for non flattened reports
if (!parseInt(this.param.flat)) {
evolutionLimits.day.push(365, 500);
evolutionLimits.week.push(500);
}
var self = this;
if (typeof self.parentId != "undefined" && self.parentId != '') {
return;
}
if (self.props.disable_all_rows_filter_limit) { // remove the -1 value from the limits array
var tempTableRowLimits = [];
tableRowLimits.forEach(function (limit) {
if (limit != -1) {
tempTableRowLimits.push(limit);
}
});
tableRowLimits = tempTableRowLimits;
}
// 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
var selectionMarkup = '<div class="input-field"><select value="'+ self.param[limitParamName] +'">';
var selectedValue = getFilterLimitAsString(self.param[limitParamName]);
if (self.props.show_limit_control) {
for (var i = 0; i < numbers.length; i++) {
var currentValue = getFilterLimitAsString(numbers[i]);
var optionSelected = '';
if (selectedValue == currentValue) {
optionSelected = 'selected';
}
selectionMarkup += '<option value="' + numbers[i] + '"' + optionSelected + '>' + currentValue + '</option>';
}
selectionMarkup += '</select></div>';
$('.limitSelection', domElem).append(selectionMarkup);
var $limitSelect = $('.limitSelection select', domElem);
if (!self.isEmpty) {
$limitSelect.on('change', function (event) {
var limit = $(this).val();
if (limit != self.param[limitParamName]) {
setLimitValue(self.param, limit);
self.reloadAjaxDataTable();
var data = {};
data[limitParamName] = self.param[limitParamName];
self.notifyWidgetParametersChange(domElem, data);
}
});
}
else {
$limitSelect.toggleClass('disabled');
}
$limitSelect.material_select();
$('.limitSelection input', domElem).attr('title', _pk_translate('General_RowsToDisplay'));
}
else {
$('.limitSelection', domElem).hide();
}
},
handlePeriod: function (domElem) {
var $periodSelect = $('.dataTablePeriods .tableIcon', domElem);
var self = this;
$periodSelect.click(function () {
var period = $(this).attr('data-period');
if (!period || period == self.param['period']) {
return;
}
var piwikPeriods = window.CoreHome.Periods;
var formatDate = window.CoreHome.format;
if (self.param['dateUsedInGraph']) {
// this parameter is passed along when switching between periods. So we perfer using
// it, to avoid a change in the end date shown in the graph
var currentPeriod = piwikPeriods.parse('range', self.param['dateUsedInGraph']);
} else {
var currentPeriod = piwikPeriods.parse(self.param['period'], self.param['date']);
}
var endDateOfPeriod = currentPeriod.getDateRange()[1];
endDateOfPeriod = formatDate(endDateOfPeriod);
var newPeriod = piwikPeriods.get(period);
$('.periodName', domElem).html(newPeriod.getDisplayText());
self.param['period'] = period;
self.param['date'] = endDateOfPeriod;
self.reloadAjaxDataTable();
});
},
// 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.slice(2);
}
});
var $searchAction = $('.dataTableAction.searchAction', domElem);
if (!$searchAction.length) {
return;
}
$searchAction.on('click', showSearch);
$searchAction.find('.icon-close').on('click', hideSearch);
var $searchInput = $('.dataTableSearchInput', domElem);
function getOptimalWidthForSearchField() {
var controlBarWidth = $('.dataTableControls', domElem).width();
var spaceLeft = controlBarWidth - $searchAction.position().left;
var idealWidthForSearchBar = 250;
var minimalWidthForSearchBar = 150; // if it's only 150 pixel we still show it on same line
var width = idealWidthForSearchBar;
if (spaceLeft > minimalWidthForSearchBar && spaceLeft < idealWidthForSearchBar) {
width = spaceLeft;
}
if (width > controlBarWidth) {
width = controlBarWidth;
}
return width;
}
function hideSearch(event) {
event.preventDefault();
event.stopPropagation();
var $searchAction = $(this).parents('.searchAction').first();
$searchAction.removeClass('searchActive active forceActionVisible');
$searchAction.css('width', '');
$searchAction.on('click', showSearch);
$searchAction.find('.icon-search').off('click', searchForPattern);
$searchInput.val('');
if (currentPattern) {
// we search for this pattern so if there was a search term before, and someone closes the search
// we show all results again
searchForPattern();
}
}
function showSearch(event) {
event.preventDefault();
event.stopPropagation();
var $searchAction = $(this);
$searchAction.addClass('searchActive forceActionVisible');
var width = getOptimalWidthForSearchField();
$searchAction.css('width', width + 'px');
if (typeof self.param.filter_trigger_id != "undefined"
&& self.param.filter_trigger_id.length > 0) {
var triggerField = document.getElementById(self.param.filter_trigger_id);
if (triggerField) {
triggerField.focus();
}
} else {
$(event.target).siblings('input').focus();
}
$searchAction.find('.icon-search').on('click', searchForPattern);
$searchAction.off('click', showSearch);
}
function searchForPattern(event) {
var keyword = '';
if (event) {
var $input;
if (event.target.tagName.toLowerCase() === 'input') {
$input = $(event.target);
} else if (event.target.tagName.toLowerCase() === 'span') {
$input = $(event.target).siblings('input');
}
if ($input && $input.length) {
keyword = $input.val();
self.param.filter_trigger_id = $input.attr('id');
}
}
if (!keyword && !currentPattern) {
// we search only if a keyword is actually given, or if no keyword is given and a search was performed
// before (in this case we want to clear the search basically.)
return;
}
self.param.filter_offset = 0;
$.each(patternsToReplace, function (index, pattern) {
if (0 === keyword.indexOf(pattern.from)) {
keyword = pattern.to + keyword.slice(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);
}
$searchInput.on("keyup", function (e) {
if (isEnterKey(e)) {
searchForPattern(e);
} else if (isEscapeKey(e)) {
$searchAction.find('.icon-close').click();
}
});
if (currentPattern) {
$searchInput.val(currentPattern);
$searchAction.click();
}
if (this.isEmpty && !currentPattern) {
$searchAction.css({display: 'none'});
}
},
//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('General_Pagination'), offset, offsetEndDisp, totalRows);
$(this).text(str);
} else {
$(this).hide();
}
}
);
var $next = $('.dataTableNext', domElem);