-
Notifications
You must be signed in to change notification settings - Fork 25
/
graph.js
1863 lines (1672 loc) · 63.3 KB
/
graph.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
//----------------------------------------------------------------------------------------
// graph.js used by both view.php and embed.php
//----------------------------------------------------------------------------------------
var feeds = [];
feedlist = [];
var plotdata = [];
var datetimepicker1;
var datetimepicker2;
var embed = false;
var skipmissing = 0;
var requesttype = "interval";
var showcsv = 0;
var showmissing = false;
var showtag = true;
var showlegend = true;
var floatingtime=1;
var yaxismin="auto";
var yaxismax="auto";
var yaxismin2="auto";
var yaxismax2="auto";
var csvtimeformat="datestr";
var csvnullvalues="show";
var csvheaders="showNameTag";
var current_graph_id = "";
var current_graph_name = "";
var previousPoint = 0;
var active_histogram_feed = 0;
var saveGraphsApp = false;
var panning = false;
//----------------------------------------------------------------------------------------
// Events shared by both view and embed mode
//----------------------------------------------------------------------------------------
$("#graph_zoomout").click(function () {floatingtime=0; view.zoomout(); graph_reload();});
$("#graph_zoomin").click(function () {floatingtime=0; view.zoomin(); graph_reload();});
$('#graph_right').click(function () {floatingtime=0; view.panright(); graph_reload();});
$('#graph_left').click(function () {floatingtime=0; view.panleft(); graph_reload();});
$('.graph_time').change(function () {
floatingtime=1;
view.timewindow($(this).val()/24.0);
view.calc_interval();
graph_reload();
});
$('.graph_time_refresh').click(function () {
floatingtime=1;
view.timewindow($('.graph_time').val()/24.0);
view.calc_interval();
graph_reload();
});
// Graph zooming
$('#placeholder').bind("plotselected", function (event, ranges) {
floatingtime=0;
view.start = ranges.xaxis.from;
view.end = ranges.xaxis.to;
view.calc_interval();
timeWindowChanged = 1;
graph_reload();
panning = true; setTimeout(function() {panning = false; }, 100);
});
$('#placeholder').bind("plothover", function (event, pos, item) {
var item_value;
if (item) {
var z = item.dataIndex;
if (previousPoint != item.datapoint) {
var dp=feedlist[item.seriesIndex].dp;
var feedid = feedlist[item.seriesIndex].id;
previousPoint = item.datapoint;
$("#tooltip").remove();
var item_time = item.datapoint[0];
if (typeof(item.datapoint[2])==="undefined") {
item_value=item.datapoint[1].toFixed(dp);
} else {
item_value=(item.datapoint[1]-item.datapoint[2]).toFixed(dp);
}
item_value+=' '+getFeedUnit(feedid);
var date = moment(item_time).format('llll')
tooltip(item.pageX, item.pageY, "<span style='font-size:11px'>"+item.series.label+"</span>"+
"<br>"+item_value +
"<br><span style='font-size:11px'>"+date+"</span>"+
"<br><span style='font-size:11px'>("+(item_time/1000)+")</span>", "#fff");
}
} else $("#tooltip").remove();
});
// Graph click
//$("#placeholder").bind("touchstarted", function (event, pos) {
// $("#legend").hide();
// showlegend = false;
//});
$("#placeholder").bind("touchended", function (event, ranges) {
if (ranges.xaxis.from!=undefined) {
view.start = ranges.xaxis.from;
view.end = ranges.xaxis.to;
view.calc_interval();
timeWindowChanged = 1;
graph_reload();
panning = true; setTimeout(function() {panning = false; }, 100);
}
});
// on finish sidebar hide/show
$(document).on('window.resized hidden.sidebar.collapse shown.sidebar.collapse', function() {
graph_resize();
graph_draw();
})
function graph_resize()
{
var top_offset = 0;
if (embed) top_offset = 35;
var placeholder_bound = $('#placeholder_bound');
var placeholder = $('#placeholder');
var width = placeholder_bound.width();
var height = width * 0.5;
if (height<300) height = 300;
if (embed) height = $(window).height();
placeholder.width(width);
placeholder_bound.height(height-top_offset);
placeholder.height(height-top_offset);
}
function datetimepickerInit()
{
$("#datetimepicker1").datetimepicker({
language: 'en-EN'
});
$("#datetimepicker2").datetimepicker({
language: 'en-EN'
});
// only used in embed mode
$('.navigation-timewindow').click(function () {
$("#navigation-timemanual").show();
$("#navigation").hide();
});
// only used in embed mode
$('.navigation-timewindow-set').click(function () {
$("#navigation-timemanual").hide();
$("#navigation").show();
reloadDatetimePrep();
graph_reload();
});
// $('#datetimepicker1').on("changeDate", function (e) { }); // Could use for rounding on selection
// $('#datetimepicker2').on("changeDate", function (e) { }); // Could use for rounding on selection
datetimepicker1 = $('#datetimepicker1').data('datetimepicker');
datetimepicker2 = $('#datetimepicker2').data('datetimepicker');
}
function reloadDatetimePrep()
{
var timewindowStart = parseTimepickerTime($("#request-start").val());
var timewindowEnd = parseTimepickerTime($("#request-end").val());
if (!timewindowStart) { alert("Please enter a valid start date."); return false; }
if (!timewindowEnd) { alert("Please enter a valid end date."); return false; }
if (timewindowStart>=timewindowEnd) { alert("Start date must be further back in time than end date."); return false; }
view.start = timewindowStart*1000;
view.end = timewindowEnd*1000;
}
//----------------------------------------------------------------------------------------
// Side bar feed selector and events associated with editor only, not loaded in embed mode
//----------------------------------------------------------------------------------------
function graph_init_editor()
{
if (!feeds) feeds = feedlist;
var numberoftags = 0;
feedsbytag = {};
for (var z in feeds) {
if (feedsbytag[feeds[z].tag]==undefined) {
feedsbytag[feeds[z].tag] = [];
numberoftags++;
}
feedsbytag[feeds[z].tag].push(feeds[z]);
}
// Draw sidebar feed selector -------------------------------------------
var out = "";
out += "<colgroup>";
out += "<col span='1' style='width: 70%;'>";
out += "<col span='1' style='width: 15%;'>";
out += "<col span='1' style='width: 15%;'>";
out += "</colgroup>";
for (var tag in feedsbytag) {
tagname = tag;
if (tag=="") tagname = "undefined";
out += "<thead>";
out += "<tr class='tagheading' data-tag='"+tagname+"' tabindex='0'>";
out += "<th colspan='3'><span class='caret'></span>"+tagname+"</th>";
out += "</tr>";
out += "</thead>";
out += "<tbody class='tagbody' data-tag='"+tagname+"'>";
for (var z in feedsbytag[tag])
{
out += "<tr style='color:#666'>";
var name = feedsbytag[tag][z].name;
if (name && name.length>20) {
name = name.substr(0,20)+"..";
}
out += "<th class='feed-title' title='"+name+"' data-feedid='"+feedsbytag[tag][z].id+"' tabindex='0'><span class='text-truncate d-inline-block'>"+name+"</span></th>";
out += "<td><input class='feed-select-left' data-feedid='"+feedsbytag[tag][z].id+"' type='checkbox'></td>";
out += "<td><input class='feed-select-right' data-feedid='"+feedsbytag[tag][z].id+"' type='checkbox'></td>";
out += "</tr>";
}
out += "</tbody>";
}
// ---------------------------------------------------------------
// Writting direct to the menu system here
// ---------------------------------------------------------------
// 1. Populate custom l3 menu from sidebar html placed in hidden element
$(".menu-l3").html($("#sidebar_html").html());
// 2. Clear original hidden element
$("#sidebar_html").html("");
// 3. Populate with feed list selector
$("#feeds").html(out);
// 4. Show l3 menu
if (menu.width>=576) menu.show_l3();
// 5. Enable l3 menu so that collapsing and re-expanding works
if (menu.obj.setup!=undefined) {
menu.obj.setup.l2.graph.l3 = []
menu.active_l3 = true;
}
if (session_write) load_saved_graphs_menu();
// ---------------------------------------------------------------
if (feeds.length>12 && numberoftags>2) {
$(".tagbody").hide();
}
$("#info").show();
if ($("#showmissing")[0]!=undefined) $("#showmissing")[0].checked = showmissing;
if ($("#showtag")[0]!=undefined) $("#showtag")[0].checked = showtag;
if ($("#showlegend")[0]!=undefined) $("#showlegend")[0].checked = showlegend;
datetimepickerInit();
// Events start here -------------------------------------------
$("#reload").click(function(){
reloadDatetimePrep();
view.interval = $("#request-interval").val();
view.limitinterval = $("#request-limitinterval")[0].checked*1;
graph_reload();
});
$("#clear").click(function(){
feedlist = [];
plotdata = [];
skipmissing = 0;
requesttype = "interval";
showcsv = 0;
showmissing = false;
showtag = true;
showlegend = true;
floatingtime=1;
yaxismin="auto";
yaxismax="auto";
yaxismin2="auto";
yaxismax2="auto";
csvtimeformat="datestr";
csvnullvalues="show";
csvheaders="showNameTag";
current_graph_id = "";
current_graph_name = "";
previousPoint = 0;
active_histogram_feed = 0;
var timeWindow = 3600000*24.0*7;
var now = Math.round(+new Date * 0.001)*1000;
view.start = now - timeWindow;
view.end = now;
view.calc_interval();
load_feed_selector();
graph_reload();
});
$("#showcsv").click(function(){
csvShowHide("swap");
});
$(".csvoptions").hide();
$("body").on("click",".average",function(){
var feedid = $(this).attr("feedid");
for (var z in feedlist) {
if (feedlist[z].id==feedid) {
if ($(this)[0].checked) {
feedlist[z].average = 1;
} else {
feedlist[z].average = 0;
}
break;
}
}
graph_draw();
});
$("body").on("click", ".move-feed", function(){
var feedid = $(this).attr("feedid")*1;
var curpos = parseInt(feedid);
var moveby = parseInt($(this).attr("moveby"));
var newpos = curpos + moveby;
if (newpos>=0 && newpos<feedlist.length){
newfeedlist = arrayMove(feedlist,curpos,newpos);
graph_draw();
}
});
$("body").on("click",".delta",function(){
var feedid = $(this).attr("feedid");
for (var z in feedlist) {
if (feedlist[z].id==feedid) {
if ($(this)[0].checked) {
feedlist[z].delta = 1;
} else {
feedlist[z].delta = 0;
}
break;
}
}
graph_draw();
});
$("body").on("change",".linecolor",function(){
var feedid = $(this).attr("feedid");
for (var z in feedlist) {
if (feedlist[z].id==feedid) {
feedlist[z].color = $(this).val();
break;
}
}
graph_draw();
});
$("body").on("change",".fill",function(){
var feedid = $(this).attr("feedid");
for (var z in feedlist) {
if (feedlist[z].id==feedid) {
feedlist[z].fill = $(this)[0].checked;
break;
}
}
graph_draw();
});
$("body").on("change",".stack",function(){
var feedid = $(this).attr("feedid");
for (var z in feedlist) {
if (feedlist[z].id==feedid) {
feedlist[z].stack = $(this)[0].checked;
break;
}
}
graph_draw();
});
$("body").on("click keyup",".feed-title", function(event){
let enterKey = 13;
if((event.type === 'keyup' && event.which === enterKey) || event.type === 'click') {
var feedid = $(this).data("feedid");
$('.feed-select-left[data-feedid="' + feedid + '"]').click();
event.preventDefault();
}
});
$("body").on("click",".feed-select-left",function(){
var feedid = $(this).data("feedid");
var checked = $(this)[0].checked;
var loaded = false;
for (var z in feedlist) {
if (feedlist[z].id==feedid) {
if (!checked) {
feedlist.splice(z,1);
} else {
feedlist[z].yaxis = 1;
loaded = true;
$(".feed-select-right[data-feedid="+feedid+"]")[0].checked = false;
}
}
}
if (loaded==false && checked) pushfeedlist(feedid, 1);
graph_reload();
});
$("body").on("click",".feed-select-right",function(){
var feedid = $(this).data("feedid");
var checked = $(this)[0].checked;
var loaded = false;
for (var z in feedlist) {
if (feedlist[z].id==feedid) {
if (!checked) {
feedlist.splice(z,1);
} else {
feedlist[z].yaxis = 2;
loaded = true;
$(".feed-select-left[data-feedid="+feedid+"]")[0].checked = false;
}
}
}
if (loaded==false && checked) pushfeedlist(feedid, 2);
graph_reload();
});
$("body").on("click keyup",".tagheading",function(event){
let enterKey = 13;
if((event.type === 'keyup' && event.which === enterKey) || event.type === 'click') {
var tag = $(this).data("tag");
var e = $(".tagbody[data-tag='"+tag+"']");
if (e.is(":visible")) e.hide(); else e.show();
event.preventDefault();
}
});
$("#showmissing").click(function(){
if ($("#showmissing")[0].checked) showmissing = true; else showmissing = false;
graph_draw();
});
$("#showlegend").click(function(){
if ($("#showlegend")[0].checked) showlegend = true; else showlegend = false;
graph_draw();
});
$("#showtag").click(function(){
if ($("#showtag")[0].checked) showtag = true; else showtag = false;
graph_draw();
});
$("#request-fixinterval").click(function(){
if ($("#request-fixinterval")[0].checked) view.fixinterval = true; else view.fixinterval = false;
if (view.fixinterval) {
$("#request-interval").prop('disabled', true);
} else {
$("#request-interval").prop('disabled', false);
}
});
$("#request-type").val("interval");
$("#request-type").change(function() {
var mode = $(this).val();
if (mode!="interval") {
$(".fixed-interval-options").hide();
view.fixinterval = true;
} else {
$(".fixed-interval-options").show();
view.fixinterval = false;
}
view.mode = mode
// Intervals are set here for bar graph bar width sizing
// and for changing between interval and daily, weekly, monthly, annual modes
if (mode=="daily") view.interval = 86400;
if (mode=="weekly") view.interval = 86400*7;
if (mode=="monthly") view.interval = 86400*30;
if (mode=="annual") view.interval = 86400*365;
$("#request-interval").val(view.interval);
graph_reload();
});
$("body").on("change",".decimalpoints",function(){
var feedid = $(this).attr("feedid");
var dp = $(this).val();
for (var z in feedlist) {
if (feedlist[z].id == feedid) {
feedlist[z].dp = dp;
graph_draw();
break;
}
}
});
$("body").on("change",".plottype",function(){
var feedid = $(this).attr("feedid");
var plottype = $(this).val();
for (var z in feedlist) {
if (feedlist[z].id == feedid) {
feedlist[z].plottype = plottype;
graph_draw();
break;
}
}
});
// left axis
$("body").on("change","#yaxis-min",function(){
yaxismin = $(this).val();
graph_draw();
});
$("body").on("change","#yaxis-max",function(){
yaxismax = $(this).val();
graph_draw();
});
// right axis
$("body").on("change","#yaxis-min2",function(){
yaxismin2 = $(this).val();
graph_draw();
});
$("body").on("change","#yaxis-max2",function(){
yaxismax2 = $(this).val();
graph_draw();
});
$("body").on("click",".reset-yaxis",function(){
$(this).parent().find('input').val('auto');
})
$("#csvtimeformat").change(function(){
csvtimeformat=$(this).val();
printcsv();
});
$("#csvnullvalues").change(function(){
csvnullvalues=$(this).val();
printcsv();
});
$("#csvheaders").change(function(){
csvheaders=$(this).val();
printcsv();
});
$("#download-csv").click(function(){
download_data("graph.csv", $("#csv").val())
});
$('body').on("click",".legendColorBox",function(d){
var country = $(this).html().toLowerCase();
// console.log(country);
});
$(".feed-options-show-stats").click(function(event){
$("#feed-options-table").hide();
$("#feed-stats-table").show();
$(".feed-options-show-options").removeClass('hide');
$(".feed-options-show-stats").addClass('hide');
event.preventDefault();
});
$(".feed-options-show-options").click(function(event){
$("#feed-options-table").show();
$("#feed-stats-table").hide();
$(".feed-options-show-options").addClass('hide');
$(".feed-options-show-stats").removeClass('hide');
event.preventDefault();
});
/**
* show sidebar if mobile view hiding sidebar
*/
$(document).on('click', '.alert a.open-sidebar', function(event) {
if (typeof show_sidebar !== 'undefined') {
show_sidebar();
// @todo: ensure the 3rd level graph menu is open
}
return false;
});
}
function pushfeedlist(feedid, yaxis) {
var f = getfeed(feedid);
var dp=0;
if (f==false) f = getfeedpublic(feedid);
if (f!=false) {
if (f.value % 1 !== 0 ) dp=1;
feedlist.push({id:feedid, name:f.name, tag:f.tag, yaxis:yaxis, fill:0, scale: 1.0, offset: 0.0, delta:0, average:0, dp:dp, plottype:'lines'});
}
}
function graph_reload()
{
var ds = new Date(view.start);
var de = new Date(view.end);
// Round start and end time
if (view.mode=="daily" || view.mode=="weekly") {
view.start = (new Date(ds.getFullYear(), ds.getMonth(), ds.getDate(), 0,0,0,0)).getTime();
view.end = (new Date(de.getFullYear(), de.getMonth(), de.getDate(), 0,0,0,0)).getTime();
} else if (view.mode=="monthly") {
var month_offset = 0;
if (ds.getMonth()==de.getMonth()) month_offset = 1;
view.start = (new Date(ds.getFullYear(), ds.getMonth(), 1, 0,0,0,0)).getTime();
view.end = (new Date(de.getFullYear(), de.getMonth()+month_offset, 1, 0,0,0,0)).getTime();
} else if (view.mode=="annual") {
var year_offset = 0;
if (ds.getFullYear()==de.getFullYear()) year_offset = 1;
view.start = (new Date(ds.getFullYear(), 0, 1, 0,0,0,0)).getTime();
view.end = (new Date(de.getFullYear()+1, 0, 1, 0,0,0,0)).getTime();
} else {
view.start = Math.floor((view.start*0.001) / view.interval) * view.interval * 1000;
view.end = Math.ceil((view.end*0.001) / view.interval) * view.interval * 1000;
}
if(datetimepicker1) {
datetimepicker1.setLocalDate(new Date(view.start));
datetimepicker1.setEndDate(new Date(view.end));
}
if(datetimepicker2) {
datetimepicker2.setLocalDate(new Date(view.end));
datetimepicker2.setStartDate(new Date(view.start));
}
$("#request-interval").val(view.interval);
$("#request-limitinterval").attr("checked",view.limitinterval);
// Convert feedlist into csv properties
var ids = [];
var averages = [];
var deltas = [];
for (var z in feedlist) {
ids.push(feedlist[z].id);
if (feedlist[z].average==false) feedlist[z].average = 0;
averages.push(feedlist[z].average)
if (feedlist[z].delta==false) feedlist[z].delta = 0;
deltas.push(feedlist[z].delta)
}
var data = {
ids: ids.join(','),
start: view.start,
end: view.end,
skipmissing: skipmissing,
limitinterval: view.limitinterval,
apikey: apikey,
average: averages.join(','),
delta: deltas.join(',')
}
if (view.mode!="interval") {
data.interval = view.mode;
} else {
data.interval = view.interval;
}
if (ids.length === 0) {
graph_resize();
graph_draw();
var title = _lang['Select a feed'] + '.';
var message = _lang['Please select a feed from the Feeds List'];
var icon = '<svg class="icon show_chart"><use xlink:href="#icon-show_chart"></use></svg>';
var markup = ['<div class="alert alert-info"><a href="#" class="open-sidebar"><strong>',icon,title,'</strong>',message,'</a></div>'].join(' ');
$('#error').show()
.html(markup);
return false;
} else {
$('#graph-wrapper').removeClass('empty');
$('#cloned_toggle').remove();
// get feedlist data
$.getJSON(path+"feed/data.json", data, addFeedlistData)
.fail(handleFeedlistDataError)
.done(checkFeedlistData);
}
}
function addFeedlistData(response){
// loop through feedlist and add response data to data property
var valid = false;
for (i in feedlist) {
let feed = feedlist[i];
for (j in response) {
let item = response[j];
if (parseInt(feed.id) === parseInt(item.feedid) && item.data!=undefined) {
feed.postprocessed = false;
feed.data = item.data;
}
if (!item || !item.data || typeof item.data.success === 'undefined') {
valid = true;
}
}
}
// alter feedlist base on user selection
if (valid) set_feedlist();
}
function handleFeedlistDataError(jqXHR, error, message){
error = error === 'parsererror' ? _('Received data not in correct format. Check the logs for more details'): error;
var errorstr = '<div class="alert alert-danger" title="'+message+'"><strong>'+_('Request error')+':</strong> ' + error + '</div>';
$('#error').html(errorstr).show();
}
function checkFeedlistData(response){
// display message to user if response not valid
var message = '';
var messages = [];
var badfeeds = [];
if (typeof(response) === 'object' && response.message) {
if (response.success === false && response.feeds ) badfeeds = badfeeds.concat(response.feeds);
messages.push(response.message);
} else
for (i in response) {
var item = response[i];
if (typeof item.data !== 'undefined') {
if (typeof item.data.success !== 'undefined' && !item.data.success) {
messages.push(item.data.message);
}
} else {
// response is jqXHR object
messages.push(response.responseText);
}
}
message = messages.join(', ');
var errorstr = '';
if (messages.length > 0) {
errorstr = '<div class="alert alert-danger"><strong>'+_('Request error')+':</strong> ' + message;
if( badfeeds.length )
errorstr += '<button id="remove_missing" type="button" class="btn">'+_('Remove missing') + '</button>';
errorstr += '</div>'
$('#error').html(errorstr).show();
if( badfeeds.length )
$('#remove_missing').click(() => {
feedlist = feedlist.filter((feed)=>!badfeeds.find((id)=>feed.id === id));
graph_reload();
});
} else {
$('#error').hide();
}
}
function set_feedlist() {
for (var z in feedlist)
{
var scale = $(".scale[feedid="+feedlist[z].id+"]").val();
if (scale!=undefined) feedlist[z].scale = scale;
var offset = $(".offset[feedid="+feedlist[z].id+"]").val();
if (offset!=undefined) feedlist[z].offset = offset;
// check to ensure feed scaling and data are only applied once
if (feedlist[z].postprocessed==false) {
feedlist[z].postprocessed = true;
console.log("postprocessing feed "+feedlist[z].id+" "+feedlist[z].name);
// Apply a scale to feed values
if (feedlist[z].scale!=undefined && feedlist[z].scale!=1.0) {
for (var i=0; i<feedlist[z].data.length; i++) {
if (feedlist[z].data[i][1]!=null) {
feedlist[z].data[i][1] = feedlist[z].data[i][1] * feedlist[z].scale;
}
}
}
// Apply a offset to feed values
if (feedlist[z].offset!=undefined && feedlist[z].offset!=0.0) {
for (var i=0; i<feedlist[z].data.length; i++) {
if (feedlist[z].data[i][1]!=null) {
feedlist[z].data[i][1] = feedlist[z].data[i][1] + 1*feedlist[z].offset;
}
}
}
}
}
// call graph_draw() once feedlist is altered
graph_draw();
}
function group_legend_values(_flot, placeholder) {
var legend = document.getElementById('legend');
var current_legend = placeholder[0].nextSibling;
if (!current_legend) {
legend.innerHTML = '';
return;
}
var current_legend_labels = current_legend.querySelector('table tbody');
var rows = Object.values(current_legend_labels.childNodes);
var left = [];
var right = [];
var output = "";
for (n in rows){
var row = rows[n];
var isRight = row.querySelector('.label-right');
if (isRight){
right.push(row);
} else {
left.push(row);
}
}
output += '<div class="grid-container">';
output += ' <div class="col left">';
output += ' <ul class="unstyled">';
output += build_rows(left);
output += ' </ul>';
output += ' </div>';
output += ' <div class="col right">';
output += ' <ul class="unstyled">';
output += build_rows(right);
output += ' </ul>';
output += ' </div>';
output += '</div>';
// populate new legend with html
legend.innerHTML = output;
// hide old legend
current_legend.style.display = 'none';
// add onclick events to links within legend
var items = legend.querySelectorAll('[data-legend-series]');
for(i = 0; i < items.length; i++) {
var item = items[i];
var link = item.querySelector('a');
// handle click of legend link
if (!link) continue;
link.addEventListener('click', onClickLegendLink)
}
}
function onClickLegendLink(event) {
event.preventDefault();
var link = event.currentTarget;
// toggle opacity of the link
link.classList.toggle('faded');
// re-draw the chart with the plot lines hidden/shown
var index = link.dataset.index;
var current_data = plot_statistics.getData()
var feed = feedlist.find(function(item) { return item.id == this; }, current_data[index].id);
if (feed == undefined) return;
switch (feed.plottype) {
case 'lines': current_data[index].lines.show = !current_data[index].lines.show; break;
case 'bars': current_data[index].bars.show = !current_data[index].bars.show; break;
case 'points': current_data[index].points.show = !current_data[index].points.show; break;
case 'steps': current_data[index].steps.show = !current_data[index].steps.show; break;
}
plot_statistics.setData(current_data);
// re-draw
plot_statistics.draw();
}
function build_rows(rows) {
var output = "";
for (x in rows) {
var row = rows[x];
var label = row.querySelector('.legendLabel')
var span = label.querySelector('span');
var index = span.dataset.index;
var id = span.dataset.id;
var colour = '<div class="legendColorBox">' + row.querySelector('.legendColorBox').innerHTML + '</div>'
// add <li> to the html
output += ' <li data-legend-series><a href="' + path + 'graph/' + id + '" data-index="' + index + '" data-id="' + id + '">' + colour + label.innerText + '</a></li>';
}
return output;
}
function graph_draw()
{
var options = {
lines: { fill: false },
xaxis: {
mode: "time",
timezone: "browser",
min: view.start,
max: view.end,
monthNames: moment ? moment.monthsShort() : null,
dayNames: moment ? moment.weekdaysMin() : null
},
yaxes: [ { }, {
// align if we are to the right
alignTicksWithAxis: 1,
position: "right"
//tickFormatter: euroFormatter
} ],
grid: {hoverable: true, clickable: true},
selection: { mode: "x" },
legend: {
show: false,
position: "nw",
toggle: true,
labelFormatter: function(label, item){
text = label;
cssClass = 'label-left';
title = 'Left Axis';
if (item.isRight) {
cssClass = 'label-right';
title = 'Right Axis';
}
data_attr = ' data-id="' + item.id + '" data-index="' + item.index + '"';
return '<span' + data_attr + ' class="' + cssClass + '" title="'+title+'">' + text +'</span>'
},
},
toggle: { scale: "visible" },
touch: { pan: "x", scale: "x" },
hooks: {
// bindEvents: [group_legend_values] // CHAVEIRO: this is breaking the touch function with the label overlapping the default flot one. Maybe a flot bug, maybe my lack of knowledge
}
}
if (showlegend) options.legend.show = true;
if (yaxismin!='auto' && yaxismin!='') { options.yaxes[0].min = yaxismin; }
if (yaxismin2!='auto' && yaxismin2!='') { options.yaxes[1].min = yaxismin2; }
if (yaxismax!='auto' && yaxismax!='') { options.yaxes[0].max = yaxismax; }
if (yaxismax2!='auto' && yaxismax2!='') { options.yaxes[1].max = yaxismax2; }
var time_in_window = (view.end - view.start) / 1000;
var hours = Math.floor(time_in_window / 3600);
var mins = Math.round(((time_in_window / 3600) - hours)*60);
if (mins!=0) {
if (mins<10) mins = "0"+mins;
} else {
mins = "";
}
if (!embed) $("#window-info").html("<b>"+_lang['Window']+":</b> "+printdate(view.start)+" <b>→</b> "+printdate(view.end)+"<br><b>"+_lang['Length']+":</b> "+hours+"h"+mins+" ("+time_in_window+" seconds)");
plotdata = [];
for (var z in feedlist) {
var data = feedlist[z].data;
// Hide missing data (only affects the plot view)
if (!showmissing) {
var tmp = [];
for (var n in data) {
if (data[n][1]!=null) tmp.push(data[n]);
}
data = tmp;
}
// Add series to plot
var label = "";
if (showtag) label += feedlist[z].tag+": ";
label += feedlist[z].name;
// label += ' '+getFeedUnit(feedlist[z].id);
var stacked = (typeof(feedlist[z].stack) !== "undefined" && feedlist[z].stack);
var plot = {label:label, data:data, yaxis:feedlist[z].yaxis, color: feedlist[z].color, stack: stacked};
if (feedlist[z].plottype=="lines") { plot.lines = { show: true, fill: (feedlist[z].fill ? (stacked ? 1.0 : 0.5) : 0.0), fill: feedlist[z].fill } };
if (feedlist[z].plottype=="bars") { plot.bars = { align: "center", fill: (feedlist[z].fill ? (stacked ? 1.0 : 0.5) : 0.0), show: true, barWidth: view.interval * 1000 * 0.75 } };
if (feedlist[z].plottype == 'points') plot.points = {show: true, radius: 3};
if (feedlist[z].plottype=="steps") { plot.lines = { steps: true, show: true, fill: (feedlist[z].fill ? (stacked ? 1.0 : 0.5) : 0.0), fill: feedlist[z].fill } };
plot.isRight = feedlist[z].yaxis === 2;
plot.id = feedlist[z].id;
plot.index = z;
plotdata.push(plot);
}
if (plotdata.length > 1) {
// show right yaxis options if required
$('#yaxis_right').show()
} else {
$('#yaxis_right').hide()
}
plot_statistics = $.plot($('#placeholder'), plotdata, options);
if (!embed) {
for (var z in feedlist) {
feedlist[z].stats = stats(feedlist[z].data);
}
var default_linecolor = "000";
var out = "";
for (var z in feedlist) {
var dp = feedlist[z].dp;
out += "<tr>";
out += "<td>";
if (z > 0) {
out += "<a class='move-feed' title='"+_lang['Move up']+"' feedid="+z+" moveby=-1 ><i class='icon-arrow-up'></i></a>";
}
if (z < feedlist.length-1) {
out += "<a class='move-feed' title='"+_lang['Move down']+"' feedid="+z+" moveby=1 ><i class='icon-arrow-down'></i></a>";
}
out += "</td>";
out += "<td>"+getFeedName(feedlist[z])+"</td>";
out += "<td><select class='plottype' feedid="+feedlist[z].id+" style='width:80px'>";
var selected = "";
if (feedlist[z].plottype == "lines") selected = "selected"; else selected = "";
out += "<option value='lines' "+selected+">"+_lang['Lines']+"</option>";
if (feedlist[z].plottype == "bars") selected = "selected"; else selected = "";
out += "<option value='bars' "+selected+">"+_lang['Bars']+"</option>";
if (feedlist[z].plottype == "points") selected = "selected"; else selected = "";
out += "<option value='points' "+selected+">"+_lang['Points']+"</option>";