-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathapp.js
1397 lines (1235 loc) · 58.4 KB
/
app.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
/**
* Analytics
*
* SPDX-FileCopyrightText: 2019-2024 Marcel Scherello
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/** global: OCA */
/** global: OCP */
/** global: OC */
/** global: t */
/** global: table */
/** global: Chart */
/** global: cloner */
/** global: _ */
'use strict';
document.addEventListener('DOMContentLoaded', function () {
OCA.Analytics.initialDocumentTitle = document.title;
OCA.Analytics.Visualization.hideElement('analytics-warning');
if (document.getElementById('advanced').value === 'true') {
OCA.Analytics.isDataset = true;
}
OCA.Analytics.translationAvailable = OCA.Analytics.Core.getInitialState('translationAvailable');
// Todo:
// register handlers for the navigation bar as in panorama
window.addEventListener("beforeprint", function () {
//document.getElementById('chartContainer').style.height = document.getElementById('myChart').style.height;
});
OCA.Analytics.Core.init();
});
OCA.Analytics = Object.assign({}, OCA.Analytics, {
TYPE_GROUP: 0,
TYPE_INTERNAL_FILE: 1,
TYPE_INTERNAL_DB: 2,
TYPE_GIT: 3,
TYPE_EXTERNAL_FILE: 4,
TYPE_EXTERNAL_REGEX: 5,
TYPE_SPREADSHEET: 7,
TYPE_SHARED: 99,
SHARE_TYPE_USER: 0,
SHARE_TYPE_GROUP: 1,
SHARE_TYPE_LINK: 3,
SHARE_TYPE_ROOM: 10,
initialDocumentTitle: null,
isDataset: false,
currentReportData: {},
chartObject: null,
tableObject: [],
// flexible mapping depending on type required by the used chart library
chartTypeMapping: {
'datetime': 'line',
'column': 'bar',
'columnSt': 'bar', // map stacked type also to base type; needed in filter
'columnSt100': 'bar', // map stacked type also to base type; needed in filter
'area': 'line',
'line': 'line',
'doughnut': 'doughnut'
},
datasources: [],
datasets: [],
reports: [],
unsavedFilters: null,
refreshTimer: null,
currentXhrRequest: null,
translationAvailable: false,
isNewObject: false,
headers: function () {
let headers = new Headers();
headers.append('requesttoken', OC.requestToken);
headers.append('OCS-APIREQUEST', 'true');
headers.append('Content-Type', 'application/json');
return headers;
}
});
/**
* @namespace OCA.Analytics.Core
*/
OCA.Analytics.Core = {
init: function () {
if (document.getElementById('sharingToken').value !== '') {
document.getElementById('byAnalytics').classList.toggle('analyticsFullscreen');
OCA.Analytics.Backend.getData();
return;
}
// URL semantic is analytics/*type*/id
let regex = /\/analytics\/([a-zA-Z0-9]+)\/(\d+)/;
let match = window.location.href.match(regex);
if (match) {
OCA.Analytics.Navigation.init(parseInt(match[2]));
} else {
OCA.Analytics.Navigation.init();
// Dashboard has to be loaded from the navigation as it depends on the report index
}
OCA.Analytics.Visualization.showElement('analytics-intro');
if (!OCA.Analytics.isDataset) {
OCA.Analytics.UI.reportOptionsEventlisteners();
document.getElementById("infoBoxReport").addEventListener('click', OCA.Analytics.Navigation.handleNewButton);
document.getElementById("infoBoxIntro").addEventListener('click', OCA.Analytics.Wizard.showFirstStart);
document.getElementById("infoBoxWiki").addEventListener('click', OCA.Analytics.Core.openWiki);
document.getElementById('fullscreenToggle').addEventListener('click', OCA.Analytics.Visualization.toggleFullscreen);
}
},
getDistinctValues: function (array, index) {
let unique = [];
let distinct = [];
if (array === undefined) {
return distinct;
}
for (let i = 0; i < array.length; i++) {
if (!unique[array[i][index]]) {
distinct.push(array[i][index]);
unique[array[i][index]] = 1;
}
}
return distinct;
},
getInitialState: function (key) {
const app = 'analytics';
const elem = document.querySelector('#initial-state-' + app + '-' + key);
if (elem === null) {
return false;
}
return JSON.parse(atob(elem.value))
},
openWiki: function () {
window.open('https://github.com/rello/analytics/wiki', '_blank');
}
};
OCA.Analytics.UI = {
buildReport: function () {
document.getElementById('reportHeader').innerText = OCA.Analytics.currentReportData.options.name;
if (OCA.Analytics.currentReportData.options.subheader !== '') {
document.getElementById('reportSubHeader').innerText = OCA.Analytics.currentReportData.options.subheader;
OCA.Analytics.Visualization.showElement('reportSubHeader');
}
document.title = OCA.Analytics.currentReportData.options.name + ' - ' + OCA.Analytics.initialDocumentTitle;
if (OCA.Analytics.currentReportData.status !== 'nodata' && parseInt(OCA.Analytics.currentReportData.error) === 0) {
// if the user uses a special time parser (e.g. DD.MM), the data needs to be sorted differently
OCA.Analytics.currentReportData = OCA.Analytics.Visualization.sortDates(OCA.Analytics.currentReportData);
/*
Sorting of integer values on x-axis #389
Natural sorting needs to be selectable with a report or column parameter (drilldown dialog)
OCA.Analytics.currentReportData.data.sort((a, b) => {
let result = a[0].localeCompare(b[0], undefined, { numeric: true });
if (result === 0) {
return a[1].localeCompare(b[1], undefined, { numeric: true });
}
return result;
});
*/
OCA.Analytics.currentReportData.data = OCA.Analytics.Visualization.formatDates(OCA.Analytics.currentReportData.data);
let visualization = OCA.Analytics.currentReportData.options.visualization;
if (visualization === 'chart') {
let ctx = document.getElementById('myChart').getContext('2d');
OCA.Analytics.Visualization.buildChart(ctx, OCA.Analytics.currentReportData, OCA.Analytics.UI.getDefaultChartOptions());
} else if (visualization === 'table') {
OCA.Analytics.Visualization.buildDataTable(document.getElementById("tableContainer"), OCA.Analytics.currentReportData);
} else {
let ctx = document.getElementById('myChart').getContext('2d');
OCA.Analytics.Visualization.buildChart(ctx, OCA.Analytics.currentReportData, OCA.Analytics.UI.getDefaultChartOptions());
OCA.Analytics.Visualization.buildDataTable(document.getElementById("tableContainer"), OCA.Analytics.currentReportData);
}
} else {
OCA.Analytics.Visualization.showElement('noDataContainer');
if (parseInt(OCA.Analytics.currentReportData.error) !== 0) {
OCA.Analytics.Notification.notification('error', OCA.Analytics.currentReportData.error);
}
}
OCA.Analytics.UI.buildReportOptions();
},
getDefaultChartOptions: function () {
return {
maintainAspectRatio: false,
responsive: true,
scales: {
'primary': {
type: 'linear',
stacked: false,
position: 'left',
display: true,
grid: {
display: true,
},
ticks: {
callback: function (value) {
return value.toLocaleString();
},
},
},
'secondary': {
type: 'linear',
stacked: false,
position: 'right',
display: false,
grid: {
display: false,
},
ticks: {
callback: function (value) {
return value.toLocaleString();
},
},
},
'x': {
stacked: false,
type: 'category',
time: {
parser: 'YYYY-MM-DD HH:mm',
tooltipFormat: 'LL',
},
distribution: 'linear',
grid: {
display: false
},
display: true,
},
},
animation: {
duration: 0 // general animation time
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
// let datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
let datasetLabel = data.datasets[tooltipItem.datasetIndex].label || data.labels[tooltipItem.index];
if (tooltipItem['yLabel'] !== '') {
return datasetLabel + ': ' + parseFloat(tooltipItem['yLabel']).toLocaleString();
} else {
return datasetLabel;
}
}
}
},
plugins: {
legend: {
display: false,
},
datalabels: {
display: false,
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
value = (value * 100 / sum).toFixed(0);
if (value > 5) {
return value + "%";
} else {
return '';
}
},
},
zoom: {
pan: {
enabled: true,
mode: 'x',
modifierKey: 'ctrl',
},
zoom: {
drag: {
enabled: true
},
mode: 'x',
onZoom: this.toggleZoomResetButton,
},
}
},
};
},
toggleZoomResetButton: function () {
OCA.Analytics.Visualization.showElement('chartZoomReset');
},
handleZoomResetButton: function () {
OCA.Analytics.chartObject.resetZoom();
OCA.Analytics.Visualization.hideElement('chartZoomReset');
},
toggleChartLegend: function () {
OCA.Analytics.chartObject.legend.options.display = !OCA.Analytics.chartObject.legend.options.display
OCA.Analytics.chartObject.update();
},
downloadChart: function () {
OCA.Analytics.UI.hideReportMenu();
document.getElementById('downloadChartLink').href = OCA.Analytics.chartObject.toBase64Image();
document.getElementById('downloadChartLink').setAttribute('download', OCA.Analytics.currentReportData.options.name + '.png');
document.getElementById('downloadChartLink').click();
},
resetContentArea: function () {
if (OCA.Analytics.isDataset) {
OCA.Analytics.Visualization.showElement('analytics-intro');
document.getElementById('app-sidebar').classList.add('disappear');
} else {
let key = Object.keys(OCA.Analytics.tableObject)[0];
if (key !== undefined) {
OCA.Analytics.tableObject[key].destroy();
}
OCA.Analytics.tableObject = [];
OCA.Analytics.Visualization.hideElement('chartContainer');
OCA.Analytics.Visualization.hideElement('chartLegendContainer');
document.getElementById('chartContainer').innerHTML = '';
document.getElementById('chartContainer').innerHTML = '<button id="chartZoomReset" hidden>' + t('analytics', 'Reset zoom') + '</button><canvas id="myChart" ></canvas>';
document.getElementById('chartZoomReset').addEventListener('click', OCA.Analytics.UI.handleZoomResetButton);
OCA.Analytics.Visualization.hideElement('tableContainer');
OCA.Analytics.Visualization.hideElement('tableSeparatorContainer');
//OCA.Analytics.Visualization.hideElement('tableMenuBar');
document.getElementById('tableContainer').innerHTML = '';
OCA.Analytics.Visualization.hideElement('reportSubHeader');
OCA.Analytics.Visualization.hideElement('noDataContainer');
document.getElementById('reportHeader').innerHTML = '';
document.getElementById('reportSubHeader').innerHTML = '';
OCA.Analytics.Visualization.showElement('reportMenuBar');
OCA.Analytics.UI.hideReportMenu();
document.getElementById('reportMenuChartOptions').disabled = false;
document.getElementById('reportMenuTableOptions').disabled = false;
document.getElementById('reportMenuAnalysis').disabled = false;
document.getElementById('reportMenuDrilldown').disabled = false;
document.getElementById('reportMenuDownload').disabled = false;
document.getElementById('reportMenuAnalysis').disabled = false;
document.getElementById('reportMenuTranslate').disabled = false;
}
},
buildReportOptions: function () {
let currentReport = OCA.Analytics.currentReportData;
let canUpdate = parseInt(currentReport.options['permissions']) === OC.PERMISSION_UPDATE;
let isInternalShare = currentReport.options['isShare'] !== undefined;
let isExternalShare = document.getElementById('sharingToken').value !== '';
if (isExternalShare) {
if (canUpdate) {
OCA.Analytics.Visualization.hideElement('reportMenuIcon');
OCA.Analytics.Filter.refreshFilterVisualisation();
} else {
//document.getElementById('reportMenuBar').remove();
OCA.Analytics.Visualization.hideElement('reportMenuBar');
//document.getElementById('reportMenuBar').id = 'reportMenuBarHidden';
}
return;
}
if (!canUpdate) {
OCA.Analytics.Visualization.hideElement('reportMenuBar');
}
if (isInternalShare) {
OCA.Analytics.Visualization.showElement('reportMenuIcon');
}
if (!OCA.Analytics.translationAvailable) {
document.getElementById('reportMenuTranslate').disabled = true;
} else {
document.getElementById('translateLanguage').value = (OC.getLanguage() === 'en') ? 'en-gb' : OC.getLanguage();
OCA.Analytics.Translation.languages();
}
if (currentReport.options.chart === 'doughnut') {
document.getElementById('reportMenuAnalysis').disabled = true;
}
let visualization = currentReport.options.visualization;
if (visualization === 'table') {
document.getElementById('reportMenuChartOptions').disabled = true;
document.getElementById('reportMenuTableOptions').disabled = false;
document.getElementById('reportMenuAnalysis').disabled = true;
document.getElementById('reportMenuDownload').disabled = true;
}
if (visualization === 'chart') {
document.getElementById('reportMenuTableOptions').disabled = true;
}
let refresh = parseInt(currentReport.options.refresh);
isNaN(refresh) ? refresh = 0 : refresh;
document.getElementById('refresh' + refresh).checked = true;
OCA.Analytics.Filter.refreshFilterVisualisation();
},
reportOptionsEventlisteners: function () {
document.getElementById('addFilterIcon').addEventListener('click', OCA.Analytics.Filter.openFilterDialog);
document.getElementById('reportMenuIcon').addEventListener('click', OCA.Analytics.UI.toggleReportMenu);
//document.getElementById('tableMenuIcon').addEventListener('click', OCA.Analytics.UI.toggleTableMenu);
document.getElementById('saveIcon').addEventListener('click', OCA.Analytics.Filter.Backend.saveReport);
document.getElementById('reportMenuSave').addEventListener('click', OCA.Analytics.Filter.Backend.newReport);
document.getElementById('reportMenuDrilldown').addEventListener('click', OCA.Analytics.Filter.openDrilldownDialog);
document.getElementById('reportMenuChartOptions').addEventListener('click', OCA.Analytics.Filter.openChartOptionsDialog);
document.getElementById('reportMenuTableOptions').addEventListener('click', OCA.Analytics.Filter.openTableOptionsDialog);
document.getElementById('reportMenuAnalysis').addEventListener('click', OCA.Analytics.UI.showReportMenuAnalysis);
document.getElementById('reportMenuRefresh').addEventListener('click', OCA.Analytics.UI.showReportMenuRefresh);
document.getElementById('reportMenuTranslate').addEventListener('click', OCA.Analytics.UI.showReportMenuTranslate);
document.getElementById('translateLanguage').addEventListener('change', OCA.Analytics.Translation.translate);
document.getElementById('trendIcon').addEventListener('click', OCA.Analytics.Functions.trend);
document.getElementById('disAggregateIcon').addEventListener('click', OCA.Analytics.Functions.disAggregate);
document.getElementById('aggregateIcon').addEventListener('click', OCA.Analytics.Functions.aggregate);
//document.getElementById('linearRegressionIcon').addEventListener('click', OCA.Analytics.Functions.linearRegression);
document.getElementById('backIcon').addEventListener('click', OCA.Analytics.UI.showReportMenuMain);
document.getElementById('backIcon2').addEventListener('click', OCA.Analytics.UI.showReportMenuMain);
document.getElementById('backIcon3').addEventListener('click', OCA.Analytics.UI.showReportMenuMain);
document.getElementById('reportMenuDownload').addEventListener('click', OCA.Analytics.UI.downloadChart);
document.getElementById('chartLegend').addEventListener('click', OCA.Analytics.UI.toggleChartLegend);
//document.getElementById('menuSearchBox').addEventListener('keypress', OCA.Analytics.UI.tableSearch);
let refresh = document.getElementsByName('refresh');
for (let i = 0; i < refresh.length; i++) {
refresh[i].addEventListener('change', OCA.Analytics.Filter.Backend.saveRefresh);
}
},
hideReportMenu: function () {
if (document.getElementById('reportMenu') !== null) {
document.getElementById('reportMenu').classList.remove('open');
}
},
toggleReportMenu: function () {
document.getElementById('reportMenu').classList.toggle('open');
document.getElementById('reportMenuMain').style.removeProperty('display');
document.getElementById('reportMenuSubAnalysis').style.setProperty('display', 'none', 'important');
document.getElementById('reportMenuSubRefresh').style.setProperty('display', 'none', 'important');
document.getElementById('reportMenuSubTranslate').style.setProperty('display', 'none', 'important');
},
toggleTableMenu: function () {
document.getElementById('tableMenu').classList.toggle('open');
document.getElementById('tableMenuMain').style.removeProperty('display');
},
showReportMenuAnalysis: function () {
document.getElementById('reportMenuMain').style.setProperty('display', 'none', 'important');
document.getElementById('reportMenuSubAnalysis').style.removeProperty('display');
},
showReportMenuRefresh: function () {
document.getElementById('reportMenuMain').style.setProperty('display', 'none', 'important');
document.getElementById('reportMenuSubRefresh').style.removeProperty('display');
},
showReportMenuTranslate: function () {
document.getElementById('reportMenuMain').style.setProperty('display', 'none', 'important');
document.getElementById('reportMenuSubTranslate').style.removeProperty('display');
},
showReportMenuMain: function () {
document.getElementById('reportMenuSubAnalysis').style.setProperty('display', 'none', 'important');
document.getElementById('reportMenuSubRefresh').style.setProperty('display', 'none', 'important');
document.getElementById('reportMenuSubTranslate').style.setProperty('display', 'none', 'important');
document.getElementById('reportMenuMain').style.removeProperty('display');
},
tableSearch: function () {
OCA.Analytics.tableObject.search(this.value).draw();
},
showDropDownList: function (evt) {
if (document.getElementById('tmpList')) {
return;
}
let inputField = evt.target;
if (!inputField.hasAttribute('data-dropDownListIndex')) {
return;
}
// make the list align-able
inputField.style.position = 'relative';
let dropDownListIndex = inputField.dataset.dropdownlistindex;
// get the values for the list from the report data
let listValues = OCA.Analytics.Core.getDistinctValues(OCA.Analytics.currentReportData.data, dropDownListIndex);
let ul = document.createElement('ul');
ul.id = 'tmpList';
ul.classList.add('dropDownList');
ul.style.width = '198px';
// take over the class from the input field to ensure same size
for (let className of inputField.classList) {
ul.classList.add(className);
}
let listCount = 0;
let listCountMax = 4;
for (let item of listValues) {
let li = document.createElement('li');
li.id = item;
li.innerText = item;
li.title = item;
listCount > listCountMax ? li.style.display = 'none' : li.style.display = '';
ul.appendChild(li);
listCount++;
}
// show a dummy element when the list is longer
let liDummy = document.createElement('li');
liDummy.innerText = '...';
liDummy.id = 'dummy';
listCount <= listCountMax ? liDummy.style.display = 'none' : liDummy.style.display = '';
ul.appendChild(liDummy);
// add the list to the input field and "open" its border at the bottom
inputField.insertAdjacentElement('afterend', ul);
inputField.classList.add('dropDownListParentOpen');
// create an event listener on document level to recognize a click outside the list
document.addEventListener('click', OCA.Analytics.UI.handleDropDownListClicked);
inputField.addEventListener('keyup', function (event) {
let li = document.getElementById('tmpList').getElementsByTagName('li');
if (event.key === 'Tab') {
// if the Tab key is pressed, we mimic autocompletion by using the first visible entry
event.preventDefault(); // prevent the focus from moving to the next element
// loop through all li items in the list
for (let i = 0; i < li.length; i++) {
// if the li is visible, set the input value to its text and hide the list
if (li[i].style.display !== 'none') {
inputField.value = li[i].textContent;
OCA.Analytics.UI.hideDropDownList();
break; // exit the loop after finding the first visible li
}
}
} else {
// for every keypress, we filter the list vor matching entries
let filter = inputField.value.toUpperCase(); // get the typed text in uppercase
// loop through all li items in the list
listCount = 0;
for (let i = 0; i < li.length; i++) {
let txtValue = li[i].textContent || li[i].innerText; // get the text in the li
// if the li text doesn't match the typed text, hide it
if (txtValue.toUpperCase().indexOf(filter) > -1 && listCount < listCountMax) {
li[i].style.display = "";
listCount++;
} else if (li[i].id === 'dummy' && listCount >= listCountMax) {
// always show the ... when there are more values available
li[i].style.display = "";
listCount++;
} else {
li[i].style.display = "none";
}
}
}
});
},
handleDropDownListClicked: function (event) {
let dropDownList = document.getElementById('tmpList');
let inputField = dropDownList.previousElementSibling;
let isClickInside = dropDownList.contains(event.target);
let isClickOnInput = inputField === event.target;
// If the click is inside the list and the target is an LI
if (isClickInside && event.target.tagName === 'LI') {
inputField.value = event.target.textContent;
OCA.Analytics.UI.hideDropDownList();
}
// If the click is outside the list, hide the list
else if (!isClickInside && !isClickOnInput) {
OCA.Analytics.UI.hideDropDownList();
}
},
hideDropDownList: function () {
// remove the global event listener again
document.removeEventListener('click', OCA.Analytics.UI.handleDropDownListClicked);
let dropDownList = document.getElementById('tmpList');
let inputField = dropDownList.previousElementSibling;
inputField.classList.remove('dropDownListParentOpen');
dropDownList.remove();
}
};
OCA.Analytics.Translation = {
translate: function () {
let name = OCA.Analytics.currentReportData.options.name;
let subheader = OCA.Analytics.currentReportData.options.subheader;
let header = OCA.Analytics.currentReportData.header;
let dimensions = JSON.stringify(OCA.Analytics.currentReportData.dimensions);
let text = name + '**' + subheader + '**' + header + '**' + dimensions;
let targetLanguage = document.getElementById('translateLanguage').value;
targetLanguage = targetLanguage === 'EN' ? 'EN-US' : targetLanguage;
let requestUrl = OC.generateUrl('ocs/v2.php/translation/translate');
fetch(requestUrl, {
method: 'POST',
headers: OCA.Analytics.headers(),
body: JSON.stringify({
fromLanguage: null,
text: text,
toLanguage: targetLanguage
})
})
.then(response => {
if (!response.ok) {
if (response.status === 400) {
OCA.Analytics.Notification.notification('error', t('analytics', 'Translation error. Possibly wrong ISO code?'));
return Promise.reject('400 Error');
}
}
return response.text();
})
.then(data => {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(data, "text/xml");
let text = xmlDoc.getElementsByTagName("text")[0].childNodes[0].nodeValue;
text = text.split('**');
let from = xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
OCA.Analytics.currentReportData.options.name = text[0];
OCA.Analytics.currentReportData.options.subheader = text[1];
OCA.Analytics.currentReportData.header = text[2].split(',');
OCA.Analytics.currentReportData.dimensions = JSON.parse(text[3]);
OCA.Analytics.UI.resetContentArea();
OCA.Analytics.UI.buildReport();
})
.catch(error => {
console.log('There has been a problem with your fetch operation: ', error);
});
},
languages: function () {
const elem = document.querySelector('#initial-state-analytics-translationLanguages');
let translateLanguage = document.getElementById('translateLanguage');
translateLanguage.innerHTML = '';
let option = document.createElement('option');
option.text = t('analytics', 'Choose language');
option.value = '';
translateLanguage.appendChild(option);
const set = new Set();
for (const item of JSON.parse(atob(elem.value))) {
if (!set.has(item.from)) {
set.add(item.from)
let option = document.createElement('option');
option.text = item.fromLabel;
option.value = item.from;
translateLanguage.appendChild(option);
}
}
}
};
OCA.Analytics.Functions = {
trend: function () {
OCA.Analytics.Visualization.showElement('chartLegendContainer');
OCA.Analytics.UI.hideReportMenu();
let numberDatasets = OCA.Analytics.chartObject.data.datasets.length;
let datasetType = 'time';
for (let y = 0; y < numberDatasets; y++) {
let dataset = OCA.Analytics.chartObject.data.datasets[y];
let newLabel = dataset.label + " " + t('analytics', 'Trend');
// generate trend only for visible data series
if (OCA.Analytics.chartObject.isDatasetVisible(y) === false) continue;
// dont add trend twice
if (OCA.Analytics.chartObject.data.datasets.find(o => o.label === newLabel) !== undefined) continue;
// dont add trend for a trend
if (dataset.label.substr(dataset.label.length - 5) === t('analytics', 'Trend')) continue;
let yValues = [];
for (let i = 0; i < dataset.data.length; i++) {
if (typeof (dataset.data[i]) === 'number') {
datasetType = 'bar';
yValues.push(parseInt(dataset.data[i]));
} else {
yValues.push(parseInt(dataset.data[i]["y"]));
}
}
let xValues = [];
for (let i = 1; i <= dataset.data.length; i++) {
xValues.push(i);
}
let regression = OCA.Analytics.Functions.regressionFunction(xValues, yValues);
let ylast = ((dataset.data.length) * regression["slope"]) + regression["intercept"];
let data = [];
if (datasetType === 'time') {
data = [
{x: dataset.data[0]["x"], y: regression["intercept"]},
{x: dataset.data[dataset.data.length - 1]["x"], y: ylast},
]
} else {
for (let i = 1; i < dataset.data.length + 1; i++) {
data.push(((i) * regression["slope"]) + regression["intercept"]);
}
}
let newDataset = {
label: newLabel,
backgroundColor: dataset.backgroundColor,
borderColor: dataset.borderColor,
borderDash: [5, 5],
type: 'line',
yAxisID: dataset.yAxisID,
data: data
};
OCA.Analytics.chartObject.data.datasets.push(newDataset);
}
OCA.Analytics.chartObject.update();
},
regressionFunction: function (x, y) {
const n = y.length;
let sx = 0;
let sy = 0;
let sxy = 0;
let sxx = 0;
let syy = 0;
for (let i = 0; i < n; i++) {
sx += x[i];
sy += y[i];
sxy += x[i] * y[i];
sxx += x[i] * x[i];
syy += y[i] * y[i];
}
const mx = sx / n;
const my = sy / n;
const yy = n * syy - sy * sy;
const xx = n * sxx - sx * sx;
const xy = n * sxy - sx * sy;
const slope = xy / xx;
const intercept = my - slope * mx;
return {slope, intercept};
},
aggregate: function () {
OCA.Analytics.Functions.aggregationFunction('aggregate');
// const cumulativeSum = (sum => value => sum += value)(0);
// datasets[0]['data'] = datasets[0]['data'].map(cumulativeSum)
},
disAggregate: function () {
OCA.Analytics.Functions.aggregationFunction('disaggregate');
},
aggregationFunction: function (mode) {
OCA.Analytics.Visualization.showElement('chartLegendContainer');
OCA.Analytics.UI.hideReportMenu();
let numberDatasets = OCA.Analytics.chartObject.data.datasets.length;
let newLabel;
for (let y = 0; y < numberDatasets; y++) {
let dataset = OCA.Analytics.chartObject.data.datasets[y];
if (mode === 'aggregate') {
newLabel = dataset.label + " " + t('analytics', 'Aggregation');
} else {
newLabel = dataset.label + " " + t('analytics', 'Disaggregation');
}
// generate trend only for visible data series
if (OCA.Analytics.chartObject.isDatasetVisible(y) === false) continue;
// dont add trend twice
if (OCA.Analytics.chartObject.data.datasets.find(o => o.label === newLabel) !== undefined) continue;
// dont add trend for a trend
if (dataset.label.substr(dataset.label.length - 5) === "Trend") continue;
if (dataset.label.substr(dataset.label.length - 11) === t('analytics', 'Aggregation')) continue;
if (dataset.label.substr(dataset.label.length - 14) === t('analytics', 'Disaggregation')) continue;
let lastValue = 0;
let newValue;
let newData = OCA.Analytics.chartObject.data.datasets[y]['data'].map(function (currentValue, index, arr) {
if (mode === 'aggregate') {
if (typeof (currentValue) === 'number') {
newValue = currentValue + lastValue;
lastValue = newValue;
} else {
newValue = {x: currentValue["x"], y: parseInt(currentValue["y"]) + lastValue};
lastValue = parseInt(currentValue["y"]) + lastValue;
}
} else {
if (typeof (currentValue) === 'number') {
newValue = currentValue - lastValue;
lastValue = currentValue;
} else {
newValue = {x: currentValue["x"], y: parseInt(currentValue["y"]) - lastValue};
lastValue = parseInt(currentValue["y"]);
}
return newValue;
}
return newValue;
})
let newDataset = {
label: newLabel,
backgroundColor: dataset.backgroundColor,
borderColor: dataset.borderColor,
borderDash: [5, 5],
type: 'line',
yAxisID: 'secondary',
data: newData
};
OCA.Analytics.chartObject.data.datasets.push(newDataset);
}
OCA.Analytics.chartObject.update();
},
};
OCA.Analytics.Datasource = {
buildDropdown: async function (target, filter) {
let optionsInit = document.createDocumentFragment();
let optionInit = document.createElement('option');
optionInit.value = '';
optionInit.innerText = t('analytics', 'Loading');
optionsInit.appendChild(optionInit);
document.getElementById(target).innerHTML = '';
document.getElementById(target).appendChild(optionsInit);
let filterDatasource = '';
if (filter) {
filterDatasource = '/' + filter;
}
// need to offer an await here, because the datasourceOptions is important for subsequent functions in the sidebar
let requestUrl = OC.generateUrl('apps/analytics/datasource' + filterDatasource);
let response = await fetch(requestUrl, {
method: 'GET',
headers: OCA.Analytics.headers()
});
let data = await response.json();
OCA.Analytics.datasources = data;
let options = document.createDocumentFragment();
let option = document.createElement('option');
option.value = '';
option.innerText = t('analytics', 'Please select');
options.appendChild(option);
let sortedOptions = OCA.Analytics.Datasource.sortOptions(data['datasources']);
sortedOptions.forEach((entry) => {
let value = entry[1];
option = document.createElement('option');
option.value = entry[0];
option.innerText = value;
options.appendChild(option);
});
document.getElementById(target).innerHTML = '';
document.getElementById(target).appendChild(options);
if (document.getElementById(target).dataset.typeId) {
// in case the value was set in the sidebar before the dropdown was ready
document.getElementById(target).value = document.getElementById(target).dataset.typeId;
}
},
sortOptions: function (obj) {
let sortable = [];
for (let key in obj)
if (obj.hasOwnProperty(key))
sortable.push([key, obj[key]]);
sortable.sort(function (a, b) {
let x = a[1].toLowerCase(),
y = b[1].toLowerCase();
return x < y ? -1 : x > y ? 1 : 0;
});
return sortable;
},
buildDatasourceRelatedForm: function (datasource) {
let template = OCA.Analytics.datasources.options[datasource];
let form = document.createElement('div');
let insideSection = false;
form.id = 'dataSourceOptions';
if (typeof (template) === 'undefined') {
OCA.Analytics.Notification.notification('error', t('analytics', 'Data source not available anymore'));
return form;
}
// create a hidden dummy for the data source type
form.appendChild(OCA.Analytics.Datasource.buildOptionHidden('dataSourceType', datasource));
for (let templateOption of template) {
// loop all options of the datasource template and create the input form
// if it is a section, we don´t need the usual labels
if (templateOption.type === 'section') {
let tableRow = OCA.Analytics.Datasource.buildOptionsSection(templateOption);
form.appendChild(tableRow);
insideSection = true;
continue;
}
// create the label column
let tableRow = document.createElement('div');
tableRow.style.display = insideSection === false ? 'table-row' : 'none';
let label = document.createElement('div');
label.style.display = 'table-cell';
label.style.width = '100%';
label.innerText = templateOption.name;
// create the info icon column
let infoColumn = document.createElement('div');
infoColumn.style.display = 'table-cell';
infoColumn.style.minWidth = '20px';
//create the input fields
let input = OCA.Analytics.Datasource.buildOptionsInput(templateOption);
input.style.display = 'table-cell';
if (templateOption.type) {
if (templateOption.type === 'tf') {
input = OCA.Analytics.Datasource.buildOptionsSelect(templateOption);
} else if (templateOption.type === 'filePicker') {
input.addEventListener('click', OCA.Analytics.Datasource.handleFilepicker);
} else if (templateOption.type === 'columnPicker') {
input.addEventListener('click', OCA.Analytics.Datasource.handleColumnPicker);
}
}
form.appendChild(tableRow);
tableRow.appendChild(label);
tableRow.appendChild(input);
tableRow.appendChild(infoColumn);
}
return form;
},
buildOptionHidden: function (id, value) {
let dataSourceType = document.createElement('input');
dataSourceType.hidden = true;
dataSourceType.id = id;
dataSourceType.innerText = value;
return dataSourceType;
},
buildOptionsInput: function (templateOption) {
let type = templateOption.type && templateOption.type === 'longtext' ? 'textarea' : 'input';
let input = document.createElement(type);
input.style.display = 'inline-flex';
input.classList.add('sidebarInput');
input.placeholder = templateOption.placeholder;
input.id = templateOption.id;
input.dataset.type = templateOption.type;
if (templateOption.type && templateOption.type === 'number') {
input.type = 'number';
input.min = '1';
}
if (templateOption.type) {
input.autocomplete = 'off';
}
return input;
},
buildOptionsSection: function (templateOption) {
let tableRow = document.createElement('div');
tableRow.classList.add('sidebarHeaderClosed');
let label = document.createElement('a');
label.style.display = 'table-cell';
label.style.width = '100%';
label.innerText = templateOption.name;
label.id = 'optionSectionHeader';
label.addEventListener('click', OCA.Analytics.Datasource.showHiddenOptions);
tableRow.appendChild(label);
return tableRow;
},
buildOptionsCheckboxIndicator: function (templateOption) {
let input = document.createElement('input');
input.type = 'checkbox'
input.disabled = true;
input.style.display = 'inline-flex';