-
Notifications
You must be signed in to change notification settings - Fork 31
/
script.js
1681 lines (1473 loc) · 59 KB
/
script.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
/*
#### Material Design CSS for ioBroker.vis
(c) 2017ff Uhula, MIT License
version: v2.5 30.04.2020
source: https://github.com/Uhula/ioBroker-Material-Design-Style
changelog: https://github.com/Uhula/ioBroker-Material-Design-Style/blob/master/changelog.MD
*/
// Zur sicheren CSS-Erkennung der Runtime eine CSS-Klasse anlegen
document.documentElement.className += " mdui-runtime";
// Überprüfen ob touch zur Verfügung steht und entsprechend eine
// CSS Klasse touch bzw no-touch erzeugen
document.documentElement.className +=
(("ontouchstart" in document.documentElement) ? " mdui-touch" : " mdui-notouch");
/* -----
MDUI
-----
Sammlung von JS-Funktionen für das Material Design
(c) 2017ff Uhula, MIT License
*/
var MDUI = (function () {
let defConfig = {"primary_color":"indigo",
"secondary_color":"blue",
"content_color":"#f8f8f8",
"color1":"#ff0000",
"color1_dark":"#800000",
"color2":"#00ff00",
"color2_dark":"#008000",
"color3":"#0000ff",
"color3_dark":"#000080"
},
lastConfig = defConfig,
styleSheet = null,
lastPageID = "";
observerSlider = null;
observerConfig = null;
observerPage = null;
observerDialog = null;
swipe = {enabled:false};
tooltip = {hint:null, timeout:null};
lockclick = false;
// light normal dark
let colors = {
red: {c200:"#ff7961", c500:"#f44336", c700:"#ba000d" },
pink: {c200:"#ff6090", c500:"#e91e63", c700:"#b0003a" },
purple: {c200:"#d05ce3", c500:"#9c27b0", c700:"#6a0080" },
deeppurple: {c200:"#9a67ea", c500:"#673ab7", c700:"#320b86" },
indigo: {c200:"#757de8", c500:"#3f51b5", c700:"#002984" },
blue: {c200:"#6ec6ff", c500:"#2196f3", c700:"#0069c0" },
lightblue: {c200:"#67daff", c500:"#03a9f4", c700:"#007ac1" },
cyan: {c200:"#62efff", c500:"#00bcd4", c700:"#008ba3" },
teal: {c200:"#52c7b8", c500:"#009688", c700:"#00675b" },
green: {c200:"#80e27e", c500:"#4caf50", c700:"#087f23" },
lightgreen: {c200:"#bef67a", c500:"#8bc34a", c700:"#5a9216" },
lime: {c200:"#ffff6e", c500:"#cddc39", c700:"#99aa00" },
yellow: {c200:"#ffff72", c500:"#ffeb3b", c700:"#c8b900" },
amber: {c200:"#fff350", c500:"#ffc107", c700:"#c79100" },
orange: {c200:"#ffc947", c500:"#ff9800", c700:"#c66900" },
deeporange: {c200:"#ff8a50", c500:"#ff5722", c700:"#c41c00" },
brown: {c200:"#a98274", c500:"#795548", c700:"#4b2c20" },
grey: {c200:"#cfcfcf", c500:"#9e9e9e", c700:"#707070" },
darkgrey: {c200:"#383838", c500:"#303030", c700:"#212121" },
bluegrey: {c200:"#8eacbb", c500:"#607d8b", c700:"#34515e" },
white: {c200:"#ffffff", c500:"#f8f8f8", c700:"#f0f0f0" },
black: {c200:"#303030", c500:"#212121", c700:"#000000" }
};
function _init() {
observerSlider = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
_onChangeSlider( mutation.target );
});
});
observerConfig = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
_onChangeConfig( mutation.target );
});
});
observerPage = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
_onChangePage( mutation.target );
});
});
observerDialog = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
_onChangeDialog( mutation.target );
});
});
}
// für alle ui-slider-handle Instanzen "style" überwachen um die Wertanzeige via css
// durchführen zu können (vis rendert dort die left/bottom neu)
function _initObserverSlider() {
observerSlider.disconnect();
let nodelist = document.querySelectorAll('.mdui-slider .ui-slider-handle');
if (nodelist) {
let i;
for (i = 0; i < nodelist.length; i++) {
_onChangeSlider( nodelist[i] );
observerSlider.observe(nodelist[i], {
attributes: true,
attributeFilter: ["style"]
});
}
}
}
// für mdui-config Elemente überwachen
function _initObserverConfig() {
observerConfig.disconnect();
let nodelist = document.querySelectorAll('.mdui-config');
if (nodelist) {
let i;
for (i = 0; i < nodelist.length; i++) {
observerConfig.observe(nodelist[i], {
subtree: true,
childList: true
});
}
}
}
// vis_container überwachen: childlist
function _initObserverPage() {
observerPage.disconnect();
let nodelist = document.querySelectorAll('#vis_container');
if (nodelist) {
let i;
for (i = 0; i < nodelist.length; i++) {
observerPage.observe(nodelist[i], {
subtree: true,
childList: true
});
}
}
}
// ui-dialog
function _initObserverDialog() {
observerDialog.disconnect();
let nodelist = document.querySelectorAll('.ui-dialog');
if (nodelist) {
let i;
for (i = 0; i < nodelist.length; i++) {
observerDialog.observe(nodelist[i], {
attributes: true,
attributeFilter: ["style"]
});
}
}
}
// ui-slider haben keine Werte im HTML, lediglich "left" bzw. "bottom" (bei vertikal)
// werden für das ui-slider-handle gerendert. Hier wird dieser Wert in ein
// neues Attribut "mdui-slider-value" gesetzt um dieses via CSS als Bubble
// anzeigen zu können
function _onChangeSlider( ele ) {
let value = "0%";
if (ele.style.left!=="")
value = ele.style.left;
if (ele.style.bottom!=="")
value = ele.style.bottom;
// nn% -> nn
value = value.replace(/%/g, "");
if (ele.style.left!=="")
ele.style.width = (100 - value) + "%";
if (ele.style.bottom!=="")
ele.style.height = (100 - value) + "%";
// mdui-range angegeben?
let values = ele.parentElement.parentElement.className;
values = _getSuffix(values, "mdui-range-");
if (values!="") {
values = values.split("-");
if (values.length>1)
value = value/100 * (values[1]-values[0]) + values[0] * 1.0;
else if (values.length>0)
value = value/100 * values[0];
}
if (Math.abs(value)<10)
value = Math.round( value*10 ) / 10;
else
value = Math.round( value );
ele.setAttribute("mdui-slider-value",value);
}
// wenn sich die config ändert, muss evtl ein reload der Seite stattfinden
function _onChangeConfig( ele ) {
_getConfig();
_patchColors();
_patchWidgetColors();
_initObserverConfig();
}
function _onLoad() {
let sel = "#"+lastPageID+" ";
try {
$(sel+"[class*='mdui-onload'][class*='mdui-expand']:not(.mdui-active)").each( function (index) {
_toggleExpand( $(this) );
});
$(sel+"[class*='mdui-onload'][class*='mdui-toggle']:not(.mdui-active)").each( function (index) {
_handleToggle( $(this) );
});
$(sel+"[class*='mdui-onload'][class*='mdui-fullscreen']:not(.mdui-active)").each( function (index) {
_toggleFullscreen( $(this) );
});
} catch(err) { console.log("[MDUI._onLoad] ",err.message ); }
}
// wenn sich die config ändert, muss evtl ein reload der Seite stattfinden
function _onChangePage( ele ) {
let pageID = "";
let $eles = $( "#vis_container>:not([style*='display: none'])[id*='visview_']" );
if ( $eles.length < 1 || $eles.length > 2) return;
pageID = $eles[$eles.length-1].id;
//console.log("[MDUI.onChangePage] ",lastPageID," ",pageID);
// wenn ein ui-datepicker hinzugekommen ist, dann dort die Farben anpassen
if (this.datepickerCount != $(".ui-datepicker").length ) {
this.datepickerCount = $(".ui-datepicker").length;
_patchColors();
}
// beim Seitenwechsel ausführen
if ( (pageID!="") && (lastPageID!=pageID) ) {
lastPageID=pageID;
setTimeout( function () {
_getConfig();
_patchColors();
_patchWidgetColors();
_handleTables();
_handleDialogs();
_handleInputs();
_handleVIS();
_initObserverSlider();
_initObserverConfig();
_initObserverDialog();
_onResizeWindow( $(window) );
_onLoad();
// favicon anpassen
$("#vis_container>:not([style*='display: none']) .mdui-favicon img").each( function (index) {
if ($(this)[0].src)
$("link[rel='shortcut icon']").attr("href", $(this)[0].src);
});
// page-name anpassen
let pagename = decodeURI( window.location.hash.substr(1,255) );
$(".mdui-page-name").each( function (index) {
$(this).html( pagename );
});
$(".mdui-page-title").each( function (index) {
// "pageMeine_ioBroker_Vis" -> "Meine ioBroker Vis"
let title = '';
let c;
for (let i=0; i<pagename.length; i++) {
c = pagename[i];
if (title=='') {
if (c==c.toUpperCase()) title += c;
} else {
if (c=='_') c = ' ';
title += c;
}
}
$(this).html( title );
});
}, 100);
}
_initObserverPage();
}
// wenn ein Dialog sichtbar wird, dann seine Farben anpassen
function _onChangeDialog( ele ) {
_patchWidgetColors();
//_handleDialogs();
_initObserverDialog();
}
// liefert den suffix einer gegebenen class zurück
// Bsp: mdui-target-w00002 -> w00002
// mdui-range-100-200 -> 100-200
function _getSuffix( s, classname ) {
let suf = "";
if (s.includes(classname)) {
suf = s.substr(s.indexOf(classname)+classname.length,1000)+" ";
suf = suf.substr(0,suf.indexOf(" "));
}
return suf;
}
// liefert den suffix einer gegebenen class eine $ele zurück
function _getClassSuffix( $ele, classname ) {
if ($ele)
return _getSuffix($ele.attr( "class" ),classname);
else
return "";
}
// aktuelle mdui-config entladen
function _getConfig() {
$("#vis_container>:not([style*='display: none']) [class*='mdui-config ']").each( function (index) {
try {
lastConfig = JSON.parse("{"+$(this)[0].innerText+"}");
} catch(err) { console.log( "MDUI._getConfig: ", err.message ); }
});
if (!lastConfig.hasOwnProperty("primary_color"))
lastConfig.primary_color = defConfig.primary_color
if (!lastConfig.hasOwnProperty("secondary_color"))
lastConfig.secondary_color = defConfig.secondary_color;
if (!lastConfig.hasOwnProperty("content_color"))
lastConfig.content_color = defConfig.content_color;
}
//
function _getGroupID( ele ) { return _getClassSuffix(ele, "mdui-group-" ); }
//
function _getTargetID( ele ) { return _getClassSuffix(ele, "mdui-target-" ); }
//
function _getScrollbarWidth() {
let $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
}
//
function _getScrollbarHeight() {
var $outer = $('<div>').css({visibility: 'hidden', height: 100, overflow: 'scroll'}).appendTo('body'),
heightWithScroll = $('<div>').css({height: '100%'}).appendTo($outer).outerHeight();
$outer.remove();
return 100 - heightWithScroll;
}
// action: command(param1,param2,...)
function _executeAction(action){ try {
if (action) {
let cmd = action.split('(')[0];
let param = action.split('(')[1];
param = param.slice(0,param.length-1);
param = param.split(',');
switch (cmd.toUpperCase() ) {
case 'SETVALUE' :
vis.setValue(param[0], param[1]);
break;
case 'CHANGEVIEW' :
vis.changeView( param[0] );
break;
//showMessage(message, title, icon, width, callback)
case 'SHOWMESSAGE' :
vis.showMessage( param[0], param[1], param[2], param[3] );
_patchColors();
break;
}
}
} catch(err) { console.log( "[MDUI._executeAction] " + err.message ); }
}
function _isDarkTheme(ele) {
while (ele) {
if (ele.classList.contains('mdui-dark'))
return true;
ele = ele.parentElement;
};
return false;
}
function _formatDatetime(date, format) {
function fill(comp) {
return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
}
var months = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];
var d = format;
var o = {
"y+": date.getFullYear(), // year
"m+": fill(date.getMonth()+1), //month
"M+": months[date.getMonth()], //month
"d+": fill(date.getDate()), //day
"H+": fill((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
"h+": fill(date.getHours()), //hour
"n+": fill(date.getMinutes()), //minute
"s+": fill(date.getSeconds()), //second
"S+": fill(date.getMilliseconds()), //millisecond,
"b+": (date.getHours() >= 12) ? 'PM' : 'AM'
};
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
d = d.replace(RegExp.$1, o[k]);
}
}
return d;
}
// alle Elemente mit class "mdui-group-XXX" togglen, in denen
// XXX aus class "mdui-group-XXX" des ele ist UND
// alle Elemente mit class "mdui-target-XXX" togglen, in denen
// XXX aus class "mdui-target-XXX" des ele ist
function _handleToggle( $ele ) {
$ele.toggleClass("ui-state-active");
$ele.toggleClass("mdui-active");
var id = _getGroupID( $ele );
if (id!=="")
$("[class*='mdui-group-"+id+"']").not("[class*='mdui-toggle']").each( function (index) {
$(this).toggleClass("mdui-hide");
$(this).toggleClass("mdui-hide-show");
});
id = _getTargetID( $ele );
if (id!=="")
$( "[class*='mdui-target-"+id+"']").not("[class*='mdui-toggle']").each( function (index) {
$(this).toggleClass("mdui-hide");
$(this).toggleClass("mdui-hide-show");
});
}
// das nächste übergeordnete .mdui-card* Element wird
// - collapsed, wenn es expanded ist
// - expanded, wenn es collapsed ist
function _toggleExpand( $ele ){
if (!$ele) return;
let $target = $ele.closest("[class*='mdui-listitem']");
if ($target.length===0) $target = $ele.closest("[class*='mdui-card']");
if ($target.length===0) return;
// wurde im ele eine Höhe mit angegeben?
let h = _getClassSuffix( $ele, "mdui-expand-" ) ;
if (h==="") h="64";
// element um 180° drehen
let styleold = $ele.attr("styleold");
$ele.toggleClass("mdui-active");
if (styleold) {
$ele.attr("style",styleold);
$ele.removeAttr("styleold");
} else {
styleold = $ele.attr("style");
$ele.attr("styleold",styleold);
$ele.attr("style",styleold + " transform:rotate(180deg); transition:transform 0.33s; ");
}
// target Element expandieren oder collabieren
styleold = $target.attr("styleold") || "";
if (styleold!=="") {
$target.attr("style",styleold + " transition:all 0.33s;");
$target.removeAttr("styleold");
} else {
styleold = $target.attr("style") || "";
if (styleold==="") styleold="top:0;";
$target.attr("styleold",styleold);
$target.attr("style",styleold + " max-height:"+h+"px !important; " + " min-height:"+h+"px !important; transition:all 0.33s; ");
}
}
// das nächste übergeordnete .vis-view Element wird
// - fullscreen angezeigt, wenn es noch nicht fullscreen ist
// - wieder normal angezeigt, wenn es fullscreen ist
/* <div class="vis-widget mdui-button mdui-fullscreen mdui-center vis-tpl-basic-HTML" style="width: 36px; height: 36px; left: calc(100% - 52px); top: 16px; z-index: 1;" id="w00005">
<div class="vis-widget-body">
<i class="material-icons">fullscreen</i>
</div>
</div>
*/
function _toggleFullscreen( $ele ){
if (!$ele) return;
let $target = $ele.closest(".vis-view");
if (!$target) return;
var styleold = $target.attr("styleold");
$ele.toggleClass("mdui-active");
if (styleold) {
let html = $ele.html();
html = html.replace(/fullscreen_exit/g, "fullscreen");
$ele.html( html );
$target.attr("style",styleold);
$target.removeAttr("styleold");
$target.appendTo(".mdui-id-"+$target.attr("id"));
} else {
let html = $ele.html();
html = html.replace(/fullscreen/g, "fullscreen_exit");
$ele.html( html );
$target.parent().addClass("mdui-id-"+$target.attr("id"));
$target.attr("styleold",$target.attr("style"));
// dark-theme?
if ($ele.closest(".mdui-content.mdui-dark").length) $target.addClass("mdui-dark");
$target.attr("style","position:fixed; left:8px; top:8px; min-width:0; width:calc(100% - 16px); min-height:0; height:calc(100% - 16px); z-index: 2147483647 !important; background-color: "+lastConfig.content_color+" !important; box-shadow: 0 0 0 1px rgba(0,0,0,0.3), 0 14px 28px rgba(0,0,0,0.65), 0 10px 10px rgba(0,0,0,0.62); border-radius: 4px;");
$target.appendTo( "body" );
}
}
// ele muss class Einträge für das Target und den Skalierungsmodus haben
// "mdui-target-(id) mdui-scale-(scalemode)"
// id: Ziel-Element mit id=id, welches ein zu skalierendes img enthält
// scalemode: fit / hfit / vfit / in / out / (number)
// number: Zahl in %
function _scale( ele ) {
var id = _getTargetID( ele );
var $img = $( "#"+id+" img" );
if ($img) {
var scale = _getClassSuffix(ele, "mdui-scale-" );
$img.width("1px"); // Scrollbars entfernen um die echte Höhe zu bekommen
$img.height("1px");
var dim = {
pw : $img.parent().width(),
ph : $img.parent().height(),
w : $img[0].naturalWidth,
h : $img[0].naturalHeight
};
switch(scale) {
case "fit":
if (dim.pw / dim.w < dim.ph / dim.h ) scale = dim.pw / dim.w;
else scale = dim.ph / dim.h;
break;
case "hfit":
if (dim.pw / dim.w < dim.ph / dim.h ) scale = dim.pw / dim.w;
else scale = (dim.pw - _getScrollbarWidth() - 4 ) / dim.w;
break;
case "vfit":
if ( dim.pw / dim.w > dim.ph / dim.h ) scale = dim.ph / dim.h;
else scale = (dim.ph - _getScrollbarHeight() - 4 ) / dim.h;
break;
case "in":
case "out":
var old = $img.attr( "style" );
old = old.substr(old.indexOf("scale(")+6,20);
old = old.substr(0,old.indexOf(")"));
if (old * 1==0) scale = 1;
else if (scale=="in") scale = old * 1.41;
else scale = old / 1.41;
break;
default:
if (scale<=0 || scale>10000)
scale = 100;
scale = scale/100;
}
scale = Math.round(scale*100)/100;
$img.attr( "style", "position:absolute;top:0;left:0;transform-origin:0 0;transition: transform 0.3s ease-out; transform:scale("+scale+");" );
}
}
// ersetzt im src-Attribute des Unter-Elements von (id) den "&range=&
// durch den Wert des in ele angegebenen (span). Für flot-Diagramme
// "mdui-target-(id) mdui-timespan-(span)"
// id: Ziel-Element mit id=id, welches das flot (src) enthält
// span: inc / dec / (number)
// number: Zahl in Minuten
function _timespan( ele ) {
var src = "";
function __patchParam( paramName, offset ) {
let reParam = RegExp(paramName+"=[^&]*", "i");
let reVal = RegExp("[+-][0-9]*", "i");
let param = src.match(reParam);
console.log("timespan param:",param);
if ( param ) {
param = param[0];
let paramval = param.match( reVal );
if (paramval) {
paramval = Math.floor(paramval) + offset;
param = param.replace( reVal, paramval<0 ? paramval : "-0" );
} else {
if ( (param[param.length-2]=="/") && ("smhdwMy".indexOf(param[param.length-1])>=0) )
param = param.substr(0,param.length-2) + (offset<0 ? offset : "-0") + param[param.length-1] + param.substr(param.length-2,2);
}
console.log("timespan src:",src);
src = src.replace(reParam, param);
console.log("timespan src:",src);
}
}
var id = _getTargetID( ele );
var target = $( "#"+id+" [src]" );
if (target) {
let timespan = _getClassSuffix(ele, "mdui-timespan-" );
src = target.attr( "src" );
// flot
if (src.indexOf("&range=">=0)) {
let min = src.substr(src.indexOf("&range=")+7,20);
min = min.substr(0,min.indexOf("&"));
switch(timespan) {
case "inc":
min = min * 2;
break;
case "dec":
min = min / 2;
break;
default:
if ( timespan<=0 )
timespan = 1440;
min = timespan;
}
src = src.replace(/&range=[0-9]*&/g, "&range="+min+"&");
target.attr("src",src);
}
// grafana
// from=now/d, from=now-1d/d
if (src.indexOf("from=">=0) && src.indexOf("to=">=0)) {
__patchParam( "from", timespan=="inc" ? +1 : -1);
__patchParam( "to", timespan=="inc" ? +1 : -1);
target.attr("src",src);
}
}
}
// ersetzt im src-Attribute des Unter-Elements von (id) einen url-Parameter
function _srcparam( ele ) {
var id = _getTargetID( ele );
var target = $( "#"+id+" [src]" );
if (target) {
let params = _getClassSuffix(ele, "mdui-srcparam-" ).split("&");
let src = target.attr( "src" );
// grafana
// http://192.168.2.8:3000/d/ek8fMryWz/iobroker-cpu?orgId=1&from=1580383496316&to=1580405096316&var-ID_WC_Temp=20&var-ID_HZR_Temp=17&panelId=4&fullscreen
for (let i=0; i<params.length; i++) {
let key = params[i].substr(0,params[i].indexOf("="));
let value = params[i].substr(key.length+1,1000);
let re = new RegExp(key+"=[^&]*", 'g');
src = src.replace(re, key+"="+value); // encodeURI()
}
target.attr("src",src);
}
}
/* */
function _resetTable( $ele, $table ) {
$table.find("tbody>tr").each( function(index) {
$(this).width("auto");
$(this).height("auto");
$(this).find("td").each( function(index) {
$(this).attr("labelth","");
});
});
}
/* */
function _handleTable( $ele, $table, opt ) {
function setColWidth( colwidth ) {
$table.find("tbody>tr").each( function(index) {
$(this).outerWidth(colwidth);
});
}
function setColHeight() {
var height = 0;
$table.find("tbody>tr").each( function(index) {
if ($(this).height() > height ) height = $(this).height();
});
if ( height > 0 )
$table.find("tbody>tr").each( function(index) {
$(this).height( height );
});
}
var innerWidth = $ele.innerWidth();
_resetTable($ele, $table);
if (opt.label) {
// Zellen mit Labels aus <th> ergänzen ?
var labels = [];
$table.find("thead>tr>th").each( function(index) {
labels[index] = $(this).text();
});
$table.find("tbody>tr").each( function(index) {
$(this).find("td").each( function(index) {
if (index < labels.length)
$(this).attr("labelth",labels[index]);
});
});
}
if (opt.colwidth>1) setColWidth(opt.colwidth);
if (opt.colwidth>2) setColHeight();
return true;
}
/* Alle mdui-table durchlaufen und überprüfen, ob die minimale Width erreicht
wurde um sie in den responsive State zu überführen
mdui-table-(mode)(-opt1)(-opt2)...(-optn)
mdui-table-ascard-r600-w200-l */
function _handleTables( ) {
$("[class*='mdui-table-']").each( function (index) {
var $ele = $(this);
var $table;
$table = $ele;
if (!$table.is("table")) $table=$table.find("table");
if (!$table.is("table")) return true; // next each
var innerWidth = $ele.innerWidth();
var classes = $ele.attr("class")
.split(" ")
.filter( function ( ele ) {
return (ele.indexOf("mdui-table-opt") > -1); });
var opts = [];
var opt;
for (var i = 0; i < classes.length; i++) {
opts[i] = [];
opts[i].reswidth = 9999;
opts[i].colwidth = 0;
opts[i].label = false;
opt = classes[i].substr(15,200).split("-");
for (var j = 0; j < opt.length; j++) {
switch(opt[j][0]) {
case "r":
opts[i].reswidth = parseInt(opt[j].substr(1,5));
break;
case "w":
opts[i].colwidth = parseInt(opt[j].substr(1,5));
break;
case "c":
opts[i].colwidth = parseInt(opt[j].substr(1,5));
if (opts[i].colwidth>0) opts[i].colwidth = (innerWidth-_getScrollbarWidth()) / opts[i].colwidth - 10;
break;
case "l":
opts[i].label = true;
break;
default:
}
}
}
opts.sort(function(a, b){return a.reswidth-b.reswidth});
if (opts.length === 0) return true; // next each
var handled = false;
for (i = 0; i < opts.length; i++) {
if ( innerWidth < opts[i].reswidth )
handled = _handleTable( $ele, $table, opts[i]);
if (handled) break;
}
if (!handled) _resetTable($ele, $table);
});
}
/* Dialogtitle|class=mdui-red-bg|style=min-width:50%;min-height:90%; */
function _handleDialogs( ) {
try {
$("[class*='ui-dialog ']").each( function (index) {
var $ele = $(this);
var $title = $ele.find("div>span[class*='ui-dialog-title']");
if ( ($title) && ($title.html()!=="") ) {
var html = '';
var params = $title.html().split("|");
var param = '';
for (var p = 0; p < params.length; p++) {
param = params[p];
if (param.substr(0,6)=="class=")
$ele.addClass(param.substr(6,1024));
else if (param.substr(0,6)=="style=") {
var csss = $ele.attr('style') + param.substr(6,1024);
$ele.attr('style', csss );
} else html = html + param + " ";
}
$title.html( html );
}
});
} catch(err) { console.log("[MDUI.handleDialogs] ", err.message ); }
}
/* Aus dem "text" Input bei mdui-input-number ein "number" machen */
function _handleInputs( ) {
try {
$("[class*='mdui-placeholder-']").each( function (index) {
let s = _getClassSuffix( $(this), "mdui-placeholder-" );
$(this).find("input").each( function (index) {
$(this)[0].placeholder = s;
} );
});
$(".mdui-input-number input").each( function () {
let $ele = $(this);
$ele[0].type = "number";
});
$(".mdui-input-color input").each( function () {
let $ele = $(this);
$ele[0].type = "color";
});
$(".mdui-input-date input").each( function () {
let $ele = $(this);
$ele[0].type = "date";
});
$(".mdui-input-time input").each( function () {
let $ele = $(this);
$ele[0].type = "time";
});
} catch(err) { console.log("[MDUI.handleInputs] ", err.message ); }
}
/* */
function _handleVIS( ) { try {
function _addHeadline(headline) {
return `<tr>
<td class='mdui-value mdui-blue'>${headline}</td>
<td></td>
</tr>`;
}
function _addRow(key, keydef, val) {
let icon = keydef.hasOwnProperty('icon')?keydef.icon:'';
return `<tr>
<td class='mdui-subtitle' style='width:50%;'>${key}</td>
<td class='mdui-label' style='width:50%;'>${val}</td>
</tr>`;
}
const VIS_INFO = {
'version':{'icon':'build'},
'user':{'icon':'person'},
'language':{'icon':'language'},
'instance':{'icon':'looks_one'},
'activeView':{'icon':'crop_square'},
'isTouch':{'icon':'touch_app'},
'__views_count':{},
'__states_count':{}
};
const VIS_INFO_CONN = {
'namespace':{},
'_isConnected':{},
'_reloadInterval':{},
'_reconnectInterval':{}
};
const HEAD = `<table style='width:100%; table-layout:fixed; word-break:break-all;'>`;
const FOOT = `</table>`;
vis.__views_count = Object.keys(vis.views).length;
vis.__states_count = Math.round( Object.keys(vis.states).length / 4);
$(".mdui-vis-info").each( function () {
let ele = $(this)[0];
let html='', key='';
html += _addHeadline('vis');
for (key in VIS_INFO)
html += _addRow(key,VIS_INFO[key],vis[key]);
html += _addHeadline('vis connection');
for (key in VIS_INFO_CONN)
html += _addRow(key,VIS_INFO_CONN[key],vis.conn[key]);
html += _addHeadline('views');
for (key in vis.views) {
let val=vis.views[key].hasOwnProperty('widgets')?Object.keys(vis.views[key].widgets).length:'0';
html += _addRow(key,{},val+' Widgets');
}
html += _addHeadline('states');
for (key in vis.states) {
if (key.includes('.val'))
html += _addRow(key,{},vis.states[key]);
}
ele.innerHTML = HEAD + html + FOOT;
});
} catch(err) { console.log("[MDUI.handleVIS] ", err.message ); }
}
// wandelt ein integer in die #rrggbb Darstellung um
function _toRGB(n) {
if ( (n.length>0) && ((n[0]<"0") || (n[0]>"9")) )
return n;
if(n < 0) {
n = 0xFFFFFFFF + n + 1;
}
return "#" + ("000000" + n.toString(16).toUpperCase()).substr(-6);
}
// wandelt eine Farbe im hex-Format (#000000) in ein RGB-Array[2] um
function _hexToRGB(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? [parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)]
: [0,0,0];
};
//
function _hexToRGBA(hex, transparence) {
let RGB = _hexToRGB(hex);
return 'rgba('+RGB[0]+','+RGB[1]+','+RGB[2]+','+transparence+')';
}
function _getLuminance(r, g, b) {
var a = [r, g, b].map(function (v) {
v /= 255;
return v <= 0.03928
? v / 12.92
: Math.pow( (v + 0.055) / 1.055, 2.4 );
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
function _contrast(rgb1, rgb2) {
var l1 = _getLuminance(rgb1[0], rgb1[1], rgb1[2]) + 0.05;
var l2 = _getLuminance(rgb2[0], rgb2[1], rgb2[2]) + 0.05;
if ( l1 > l2 )
return l1 / l2
else
return l2 / l1;
}
// liefert die fontColor auf Basis der backgroundColor durch Berechnung
// des Kontrasts
function _getFontColor(bc) {
if ( _contrast(_hexToRGB(bc),_hexToRGB("#000000")) < 6 )
return "#ffffff";
else
return "#000000";
}
// ersetzt in bekannten WIdgets schwarze und weisse Font
function _patchWidgetColors( ) {
let fontColor = _getFontColor( _getColorFromConfig("content_color",lastConfig.content_color,200,defConfig.content_color) );
let isDark = fontColor=="#ffffff";
// flot Widget
$("#vis_container:not([style*='display: none']) iframe[src*='flot'],.ui-dialog iframe[src*='flot']").each(
function (index) {
var $ele = $(this)[0];
var src = $ele.src;
/*
src = src.replace(/&bg=%23[0-9]*&/g, "&bg=%23f00000&");
src = src.replace(/&x_labels_color=%23[0-9]*&/g, "&x_labels_color=%23f00000&");
*/
if (isDark) {
src = src.replace(/%23000000/g, "%23111111");
src = src.replace(/%23ffffff/g, "%23000001");
src = src.replace(/%23111111/g, "%23fffffe");
} else {
src = src.replace(/%23000001/g, "%23111111");
src = src.replace(/%23fffffe/g, "%23000000");
src = src.replace(/%23111111/g, "%23ffffff");
}
$ele.src = src;
});
// svg-clock
/* Striche, Ticks */
$(".svg--clock defs line").each( function (index) {
$(this)[0].style.stroke = fontColor;
});
/* Stundenzeiger */
$("#hands > g.hand--h").each( function (index) {
$(this)[0].style.stroke = fontColor;
});
$("#hands > g.hand--h > line").each( function (index) {
$(this)[0].style.stroke = fontColor;
});
/* Minutenzeiger */
$("#hands > g.hand--m").each( function (index) {
$(this)[0].style.stroke = fontColor;
});
$("#hands > g.hand--m > line").each( function (index) {
$(this)[0].style.stroke = fontColor;
});
/* Ziffern */
$(".svg--clock .svg--ticks text").each( function (index) {
$(this)[0].style.fill = fontColor;
});