/
TemplateEngine.js
1762 lines (1586 loc) · 64.2 KB
/
TemplateEngine.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
/* TemplateEngine.js
*
* copyright (c) 2010-2016, Christian Mayer and the CometVisu contributers.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
* Main Template engine
*
* @author Christian Mayer
* @since 2010
* @module lib/TemplateEngine
* @requires dependencies/jquery
* @requires structure/pure
* @requires config/structure_custom
* @requires lib/TrickOMatic
* @requires lib/PageHandler
* @requires lib/PagePartsHandler
* @requires lib/CometVisuClient
* @requires lib/mockup/Client
* @requires lib/EventHandler
*/
///////////////////////////////////////////////////////////////////////
//
// Main:
//
define([
'jquery', '_common', 'structure_custom', 'TrickOMatic', 'PageHandler', 'PagePartsHandler',
'CometVisuClient', 'CometVisuMockup', 'EventHandler', 'MessageBroker', 'ConfigCache',
'Compatibility', 'jquery-ui', 'strftime',
'jquery.ui.touch-punch', 'jquery.svg.min', 'IconHandler',
'widget_break', 'widget_designtoggle',
'widget_group', 'widget_rgb', 'widget_web', 'widget_image',
'widget_imagetrigger', 'widget_include', 'widget_info', 'widget_infoaction', 'widget_infotrigger',
'widget_line', 'widget_multitrigger', 'widget_navbar', 'widget_page',
'widget_pagejump', 'widget_refresh', 'widget_reload', 'widget_slide',
'widget_switch', 'widget_text', 'widget_toggle', 'widget_trigger',
'widget_pushbutton', 'widget_urltrigger', 'widget_unknown', 'widget_audio',
'widget_video', 'widget_wgplugin_info',
'TransformDefault', 'TransformKnx', 'TransformOpenHab'
], function( $, design, VisuDesign_Custom, Trick_O_Matic, PageHandler, PagePartsHandler, CometVisu,
ClientMockup, EventHandler, MessageBroker, ConfigCache ) {
"use strict";
var instance;
function TemplateEngine( undefined ) {
var thisTemplateEngine = this;
this.libraryVersion = 7;
this.libraryCheck = true;
if ($.getUrlVar('libraryCheck')) {
this.libraryCheck = $.getUrlVar('libraryCheck') != 'false'; // true unless set to false
}
var loadReady = { page: false, plugins: false };
function delaySetup( id ) {
loadReady[ id ] = false;
return function() {
delete loadReady[ id ];
thisTemplateEngine.setup_page();
};
};
this.design = new VisuDesign_Custom();
this.pagePartsHandler = new PagePartsHandler();
this.eventHandler = new EventHandler(this);
this.messageBroker = MessageBroker.getInstance();
this.configCache = ConfigCache.getInstance();
var rememberLastPage = false;
this.currentPage = null;
this.currentPageNavbarVisibility = null;
this.configSettings = {
currentPageUnavailableWidth: -1,
currentPageUnavailableHeight: -1,
// if true the whole widget reacts on click events
// if false only the actor in the widget reacts on click events
bindClickToWidget: false,
// threshold where the mobile.css is loaded
maxMobileScreenWidth: 480,
// threshold where different colspans are used
maxScreenWidthColspanS: 599,
maxScreenWidthColspanM: 839,
mappings: {}, // store the mappings
stylings: {} // store the stylings
};
// use to recognize if the screen width has crossed the maxMobileScreenWidth
var lastBodyWidth=0;
this.ga_list = {};
this.widgetData = {}; // hash to store all widget specific data
this.configSuffix;
if ($.getUrlVar("config")) {
this.configSuffix = $.getUrlVar("config");
}
if ($.getUrlVar('enableCache') === "invalid") {
this.configCache.clear(this.configSuffix);
this.enableCache = true;
} else {
this.enableCache = $.getUrlVar('enableCache') ? $.getUrlVar('enableCache') === "true" : true;
}
/**
* Return (reference to) widgetData object by path.
*/
this.widgetDataGet = function( path ) {
return this.widgetData[ path ] || (this.widgetData[ path ] = {});
};
/**
* Return (reference to) widget data by element
*/
this.widgetDataGetByElement = function( element ) {
var
parent = $(element).parent(),
path = parent.attr('id');
if( path === undefined )
path = parent.parent().attr('id');
return this.widgetDataGet( path );
};
/**
* Merge obj in the widgetData.
*/
this.widgetDataInsert = function( path, obj ) {
var thisWidgetData = this.widgetDataGet( path );
for( var attrname in obj )
thisWidgetData[ attrname ] = obj[ attrname ];
return thisWidgetData;
};
/**
* Structure where a design can set a default value that a widget or plugin
* can use.
* This is especially important for design relevant information like colors
* that can not be set though CSS.
*
* Useage: templateEngine.defaults.plugin.foo = {bar: 'baz'};
*/
this.defaults = { widget: {}, plugin: {} };
/**
* Function to test if the path is in a valid form.
* Note: it doesn't check if it exists!
*/
var pathRegEx = /^id(_[0-9]+)+$/;
this.main_scroll;
this.old_scroll = '';
this.visu;
this.scrollSpeed;
this.defaultColumns = 12;
this.minColumnWidth = 120;
this.enableAddressQueue = $.getUrlVar('enableQueue') ? true : false;
this.configSettings.backend = 'default';
if ($.getUrlVar("backend")) {
this.configSettings.backend = $.getUrlVar("backend");
}
this.initBackendClient = function() {
if ($.getUrlVar('testMode')) {
thisTemplateEngine.visu = new ClientMockup();
require(['TransformMockup'], function() {});
}
else if (thisTemplateEngine.configSettings.backend=="oh") {
thisTemplateEngine.visu = new CometVisu('openhab', thisTemplateEngine.configSettings.backendUrl);
}
else if (thisTemplateEngine.configSettings.backend=="oh2") {
thisTemplateEngine.visu = new CometVisu('openhab2', thisTemplateEngine.configSettings.backendUrl);
} else {
thisTemplateEngine.visu = new CometVisu(thisTemplateEngine.configSettings.backend, thisTemplateEngine.configSettings.backendUrl);
}
function update(json) {
for( var key in json ) {
//$.event.trigger('_' + key, json[key]);
if( !(key in thisTemplateEngine.ga_list) )
continue;
var data = json[ key ];
thisTemplateEngine.ga_list[ key ].forEach( function( id ){
if( typeof id === 'string' )
{
var element = document.getElementById( id );
if (element) {
var type = element.dataset.type || 'page'; // only pages have no datatype set
var updateFn = thisTemplateEngine.design.creators[type].update;
if (updateFn) {
var children = element.children;
if (children[0])
updateFn.call(children[0], key, data);
else
updateFn.call(element, key, data);
}
} else {
console.error("no element with id %s found", id);
}
//console.log( element, type, updateFn );
} else if( typeof id === 'function' ) {
id.call( key, data );
}
});
}
};
thisTemplateEngine.visu.update = function(json) { // overload the handler
profileCV( 'first data start (' + thisTemplateEngine.visu.retryCounter + ')' );
update( json );
profileCV( 'first data updated', true );
thisTemplateEngine.visu.update = update; // handle future requests directly
}
thisTemplateEngine.visu.user = 'demo_user'; // example for setting a user
};
this.configSettings.clientDesign = "";
if (typeof this.forceReload == "undefined") {
this.forceReload = false;
}
if ($.getUrlVar('forceReload')) {
this.forceReload = $.getUrlVar('forceReload') != 'false'; // true unless set
// to false
}
if ($.getUrlVar('forceDevice')) {
this.forceMobile = $.getUrlVar('forceDevice') == 'mobile';
this.forceNonMobile = !this.forceMobile;
} else {
this.forceMobile = false;
this.forceNonMobile = false;
}
var uagent = navigator.userAgent.toLowerCase();
this.mobileDevice = (/(android|blackberry|iphone|ipod|series60|symbian|windows ce|palm)/i.test(uagent));
if (/(nexus 7|tablet)/i.test(uagent)) this.mobileDevice = false; // Nexus 7 and Android Tablets have a "big" screen, so prevent Navbar from scrolling
this.mobileDevice |= this.forceMobile; // overwrite detection when set by URL
// "Bug"-Fix for ID: 3204682 "Caching on web server"
// This isn't a real fix for the problem as that's part of the web browser,
// but
// it helps to avoid the problems on the client, e.g. when the config file
// has changed but the browser doesn't even ask the server about it...
this.forceReload = true;
// Disable features that aren't ready yet
// This can be overwritten in the URL with the parameter "maturity"
this.use_maturity;
if ($.getUrlVar('maturity')) {
this.url_maturity = $.getUrlVar('maturity');
if (!isNaN(this.url_maturity - 0)) {
this.use_maturity = this.url_maturity - 0; // given directly as number
} else {
this.use_maturity = Maturity[this.url_maturity]; // or as the ENUM name
}
}
if (isNaN(this.use_maturity)) {
this.use_maturity = design.Maturity.release; // default to release
}
this.transformEncode = function(transformation, value) {
var basetrans = transformation.split('.')[0];
return transformation in Transform ? Transform[transformation]
.encode(value) : (basetrans in Transform ? Transform[basetrans]
.encode(value) : value);
};
this.transformDecode = function(transformation, value) {
var basetrans = transformation.split('.')[0];
return transformation in Transform ? Transform[transformation]
.decode(value) : (basetrans in Transform ? Transform[basetrans]
.decode(value) : value);
};
this.addAddress = function( address, id ) {
if( address in thisTemplateEngine.ga_list )
thisTemplateEngine.ga_list[ address ].push( id );
else
thisTemplateEngine.ga_list[ address ] = [ id ];
};
this.getAddresses = function() {
return Object.keys(thisTemplateEngine.ga_list);
};
/*
* this function implements widget stylings
*/
this.setWidgetStyling = function(e, value, styling) {
var sty = thisTemplateEngine.configSettings.stylings[styling];
if (sty) {
e.removeClass(sty['classnames']); // remove only styling classes
var findValue = function(v, findExact) {
if (undefined === v) {
return false;
}
if (sty[v]) { // fixed value
e.addClass(sty[v]);
return true;
}
else {
var range = sty['range'];
if (findExact && range[v]) {
e.addClass(range[v][1]);
return true;
}
var valueFloat = parseFloat(v);
for (var min in range) {
if (min > valueFloat) continue;
if (range[min][0] < valueFloat) continue; // check max
e.addClass(range[min][1]);
return true;
}
}
return false;
}
if (!findValue(value, false) && sty['defaultValue'] !== undefined) {
findValue(sty['defaultValue'], true);
}
}
return this;
}
this.map = function(value, this_map) {
if (this_map && thisTemplateEngine.configSettings.mappings[this_map]) {
var m = thisTemplateEngine.configSettings.mappings[this_map];
var ret = value;
if (m.formula) {
ret = m.formula(ret);
}
var mapValue = function(v) {
if (m[v]) {
return m[v];
} else if (m['range']) {
var valueFloat = parseFloat(v);
var range = m['range'];
for (var min in range) {
if (min > valueFloat) continue;
if (range[min][0] < valueFloat) continue; // check max
return range[min][1];
}
}
return v; // pass through when nothing was found
}
var ret = mapValue(ret);
if (!ret && m['defaultValue']) {
ret = mapValue(m['defaultValue']);
}
if( ret !== undefined ) {
return ret;
}
}
return value;
};
/**
* Look up the entry for @param value in the mapping @param this_map and
* @return the next value in the list (including wrap around).
*/
this.getNextMappedValue = function(value, this_map) {
if (this_map && thisTemplateEngine.configSettings.mappings[this_map]) {
var keys = Object.keys(thisTemplateEngine.configSettings.mappings[this_map]);
return keys[ (keys.indexOf( "" + value ) + 1) % keys.length ];
}
return value;
}
this.resetPageValues = function() {
thisTemplateEngine.currentPage = null;
thisTemplateEngine.configSettings.currentPageUnavailableWidth=-1;
thisTemplateEngine.currentPageNavbarVisibility=null;
};
this.getCurrentPageNavbarVisibility = function() {
if (thisTemplateEngine.currentPageNavbarVisibility==null) {
thisTemplateEngine.currentPageNavbarVisibility = thisTemplateEngine.pagePartsHandler.getNavbarsVisibility(thisTemplateEngine.currentPage);
}
return thisTemplateEngine.currentPageNavbarVisibility;
};
// return S, M or L depening on the passed width
function getColspanClass( width )
{
if( width <= thisTemplateEngine.configSettings.maxScreenWidthColspanS )
return 'S';
if( width <= thisTemplateEngine.configSettings.maxScreenWidthColspanM )
return 'M';
return 'L';
}
var oldWidth = -1;
this.adjustColumns = function() {
var
width = thisTemplateEngine.getAvailableWidth(),
oldClass = getColspanClass( oldWidth ),
newClass = getColspanClass( width );
oldWidth = width;
return oldClass != newClass;
};
/**
* return the available width for a the currently visible page
* the available width is calculated by subtracting the following elements widths (if they are visible) from the body width
* - Left-Navbar
* - Right-Navbar
*/
this.getAvailableWidth = function() {
// currently this calculation is done once after every page scroll (where thisTemplateEngine.configSettings.currentPageUnavailableWidth is reseted)
// if the screen width falls below the threshold which activates/deactivates the mobile.css
// the calculation has to be done again, even if the page hasn´t changed (e.g. switching between portrait and landscape mode on a mobile can cause that)
var bodyWidth = $('body').width();
var mobileUseChanged = (lastBodyWidth<thisTemplateEngine.configSettings.maxMobileScreenWidth)!=(bodyWidth<thisTemplateEngine.configSettings.maxMobileScreenWidth);
if (thisTemplateEngine.configSettings.currentPageUnavailableWidth<0 || mobileUseChanged || true) {
// console.log("Mobile.css use changed "+mobileUseChanged);
thisTemplateEngine.configSettings.currentPageUnavailableWidth=0;
var navbarVisibility = thisTemplateEngine.getCurrentPageNavbarVisibility(thisTemplateEngine.currentPage);
var widthNavbarLeft = navbarVisibility.left=="true" && $('#navbarLeft').css('display')!="none" ? Math.ceil( $('#navbarLeft').outerWidth() ) : 0;
if (widthNavbarLeft>=bodyWidth) {
// Left-Navbar has the same size as the complete body, this can happen, when the navbar has no content
// maybe there is a better solution to solve this problem
widthNavbarLeft = 0;
}
var widthNavbarRight = navbarVisibility.right=="true" && $('#navbarRight').css('display')!="none" ? Math.ceil( $('#navbarRight').outerWidth() ) : 0;
if (widthNavbarRight>=bodyWidth) {
// Right-Navbar has the same size as the complete body, this can happen, when the navbar has no content
// maybe there is a better solution to solve this problem
widthNavbarRight = 0;
}
thisTemplateEngine.configSettings.currentPageUnavailableWidth = widthNavbarLeft + widthNavbarRight + 1; // remove an additional pixel for Firefox
// console.log("Width: "+bodyWidth+" - "+widthNavbarLeft+" - "+widthNavbarRight);
}
lastBodyWidth = bodyWidth;
return bodyWidth - thisTemplateEngine.configSettings.currentPageUnavailableWidth;
};
/**
* return the available height for a the currently visible page
* the available height is calculated by subtracting the following elements heights (if they are visible) from the window height
* - Top-Navigation
* - Top-Navbar
* - Bottom-Navbar
* - Statusbar
*
* Notice: the former way to use the subtract the $main.position().top value from the total height leads to errors in certain cases
* because the value of $main.position().top is not reliable all the time
*/
this.getAvailableHeight = function() {
var windowHeight = $(window).height();
thisTemplateEngine.configSettings.currentPageUnavailableHeight=0;
var navbarVisibility = thisTemplateEngine.getCurrentPageNavbarVisibility(thisTemplateEngine.currentPage);
var heightStr = "Height: "+windowHeight;
if ($('#top').css('display') != 'none' && $('#top').outerHeight(true)>0) {
thisTemplateEngine.configSettings.currentPageUnavailableHeight+= Math.max( $('#top').outerHeight(true), $('.nav_path').outerHeight(true) );
heightStr+=" - "+Math.max( $('#top').outerHeight(true), $('.nav_path').outerHeight(true) );
}
else {
heightStr+=" - 0";
}
// console.log($('#navbarTop').css('display')+": "+$('#navbarTop').outerHeight(true));
if ($('#navbarTop').css('display') != 'none' && navbarVisibility.top=="true" && $('#navbarTop').outerHeight(true)>0) {
thisTemplateEngine.configSettings.currentPageUnavailableHeight+=$('#navbarTop').outerHeight(true);
heightStr+=" - "+$('#navbarTop').outerHeight(true);
}
else {
heightStr+=" - 0";
}
if ($('#navbarBottom').css('display') != 'none' && navbarVisibility.bottom=="true" && $('#navbarBottom').outerHeight(true)>0) {
thisTemplateEngine.configSettings.currentPageUnavailableHeight+=$('#navbarBottom').outerHeight(true);
heightStr+=" - "+$('#navbarBottom').outerHeight(true);
}
else {
heightStr+=" - 0";
}
if ($('#bottom').css('display') != 'none' && $('#bottom').outerHeight(true)>0) {
thisTemplateEngine.configSettings.currentPageUnavailableHeight+=$('#bottom').outerHeight(true);
heightStr+=" - #bottom:"+$('#bottom').outerHeight(true);
}
else {
heightStr+=" - 0";
}
if (thisTemplateEngine.configSettings.currentPageUnavailableHeight>0) {
thisTemplateEngine.configSettings.currentPageUnavailableHeight+=1;// remove an additional pixel for Firefox
}
//console.log(heightStr);
//console.log(windowHeight+" - "+thisTemplateEngine.configSettings.currentPageUnavailableHeight);
return windowHeight - thisTemplateEngine.configSettings.currentPageUnavailableHeight;
};
/*
* Make sure everything looks right when the window gets resized. This is
* necessary as the scroll effect requires a fixed element size
*/
/**
* Manager for all resizing issues. It ensures that the real resizing
* calculations are only done as often as really necessary.
*/
this.resizeHandling = (function(){
var
invalidBackdrop = true,
invalidNavbar = true,
invalidPagesize = true,
invalidRowspan = true,
invalidScreensize = true,
$pageSize = $('#pageSize'),
$navbarTop = $('#navbarTop'),
$navbarBottom = $('#navbarBottom'),
width = 0,
height = 0;
var request = null;
function makeAllSizesValid()
{
if (!request) {
request = requestAnimationFrame(function () {
invalidPagesize && makePagesizeValid(); // must be first due to depencies
invalidNavbar && makeNavbarValid();
invalidRowspan && makeRowspanValid();
invalidBackdrop && makeBackdropValid();
request = null;
});
}
}
function makeBackdropValid()
{
if( !templateEngine.currentPage )
return;
var widgetData = templateEngine.widgetData[ templateEngine.currentPage.attr('id') ];
if( '2d' === widgetData.type )
{
var
cssPosRegEx = /(\d*)(.*)/,
backdrop = templateEngine.currentPage.children().children().filter(widgetData.backdroptype)[0],
backdropSVG = widgetData.backdroptype === 'embed' ? backdrop.getSVGDocument() : null,
backdropBBox = backdropSVG ? backdropSVG.children[0].getBBox() : {},
backdropNWidth = backdrop.naturalWidth || backdropBBox.width || width,
backdropNHeight = backdrop.naturalHeight || backdropBBox.height || height,
backdropScale = Math.min( width/backdropNWidth, height/backdropNHeight ),
backdropWidth = backdropNWidth * backdropScale,
backdropHeight = backdropNHeight * backdropScale,
backdropPos = widgetData.backdropalign.split(' '),
backdropLeftRaw = backdropPos[0].match( cssPosRegEx ),
backdropTopRaw = backdropPos[1].match( cssPosRegEx ),
backdropLeft = backdropLeftRaw[2] === '%' ? (width >backdropWidth ? ((width -backdropWidth )*(+backdropLeftRaw[1])/100) : 0) : +backdropLeftRaw[1],
backdropTop = backdropTopRaw[2] === '%' ? (height>backdropHeight ? ((height-backdropHeight)*(+backdropTopRaw[1] )/100) : 0) : +backdropTopRaw[1],
uagent = navigator.userAgent.toLowerCase();
if( backdrop.complete === false || (widgetData.backdroptype === 'embed' && backdropSVG === null) )
{
// backdrop not available yet - reload
setTimeout( thisTemplateEngine.resizeHandling.invalidateBackdrop, 100);
return;
}
// Note 1: this here is a work around for older browsers that can't use
// the object-fit property yet.
// Currently (26.05.16) only Safari is known to not support
// object-position although object-fit itself does work
// Note 2: The embed element allways needs it
if(
widgetData.backdroptype === 'embed' ||
( uagent.indexOf('safari') !== -1 && uagent.indexOf('chrome') === -1 )
)
{
$( backdrop ).css({
width: backdropWidth + 'px',
height: backdropHeight + 'px',
left: backdropLeft + 'px',
top: backdropTop + 'px'
});
}
templateEngine.currentPage.find('.widget_container').toArray().forEach( function( widgetContainer ){
var widgetData = templateEngine.widgetDataGet( widgetContainer.id );
if( widgetData.layout )
{
var
layout = widgetData.layout,
// this assumes that a .widget_container has only one child and this
// is the .widget itself
style = widgetContainer.children[0].style;
if( 'x' in layout )
{
var value = layout.x.match( cssPosRegEx );
if( 'px' === value[2] )
{
style.left = (backdropLeft + value[1]*backdropScale) + 'px';
} else {
style.left = layout.x;
}
}
if( 'y' in layout )
{
var value = layout.y.match( cssPosRegEx );
if( 'px' === value[2] )
{
style.top = (backdropTop + value[1]*backdropScale) + 'px';
} else {
style.top = layout.y;
}
}
if( 'width' in layout )
style.width = layout.width;
if( 'height' in layout )
style.height = layout.height;
}
});
}
invalidBackdrop = false;
}
function makeNavbarValid()
{
if (thisTemplateEngine.mobileDevice) {
//do nothing
} else {
if(
($navbarTop.css('display') !== 'none' && $navbarTop.outerHeight(true)<=2) ||
($navbarBottom.css('display') !== 'none' && $navbarBottom.innerHeight() <=2)
) {
// update references
$navbarTop = $('#navbarTop');
$navbarBottom = $('#navbarBottom');
// Top/Bottom-Navbar is not initialized yet, wait some time and recalculate available height
// this is an ugly workaround, if someone can come up with a better solution, feel free to implement it
window.requestAnimationFrame( thisTemplateEngine.resizeHandling.invalidateNavbar );
return;
}
}
if (thisTemplateEngine.adjustColumns()) {
// the amount of columns has changed -> recalculate the widgets widths
thisTemplateEngine.applyColumnWidths();
}
invalidNavbar = false;
}
function makePagesizeValid()
{
width = thisTemplateEngine.getAvailableWidth();
height = thisTemplateEngine.getAvailableHeight();
$pageSize.text('#main,.page{width:' + (width - 0) + 'px;height:' + height + 'px;}');
invalidPagesize = false;
}
function makeRowspanValid()
{
var
dummyDiv = $(
'<div class="clearfix" id="calcrowspan"><div id="containerDiv" class="widget_container"><div class="widget clearfix text" id="innerDiv" /></div></div>')
.appendTo(document.body).show(),
singleHeight = $('#containerDiv').outerHeight(false),
singleHeightMargin = $('#containerDiv').outerHeight(true),
styles = '';
for( var rowspan in thisTemplateEngine.configSettings.usedRowspans )
{
styles += '.rowspan.rowspan' + rowspan
+ ' { height: '
+ ((rowspan - 1) * singleHeightMargin + singleHeight)
+ "px;}\n";
}
$('#calcrowspan').remove();
// set css style
$('#rowspanStyle').text( styles );
invalidRowspan = false;
}
return {
invalidateBackdrop: function(){
invalidBackdrop = true;
makeAllSizesValid();
},
invalidateNavbar: function(){
invalidNavbar = true;
invalidPagesize = true;
makeAllSizesValid();
},
invalidateRowspan: function(){
invalidRowspan = true;
makeAllSizesValid();
},
invalidateScreensize: function(){
invalidScreensize = true;
invalidPagesize = true;
invalidBackdrop = true;
makeAllSizesValid();
}
};
})();
thisTemplateEngine.configSettings.usedRowspans = {};
this.rowspanClass = function(rowspan) {
thisTemplateEngine.configSettings.usedRowspans[ rowspan ] = true;
return 'rowspan rowspan' + rowspan;
};
thisTemplateEngine.configSettings.pluginsToLoadCount = [];
var xml;
this.parseXML = function(loaded_xml) {
profileCV( 'parseXML' );
xml = loaded_xml;
// erst mal den Cache für AJAX-Requests wieder aktivieren
/*
$.ajaxSetup({
cache : true
});
*/
/*
* First, we try to get a design by url. Secondly, we try to get a predefined
*/
// read predefined design in config
var predefinedDesign = $('pages', xml).attr("design");
if ($('pages', xml).attr("backend")) {
thisTemplateEngine.configSettings.backend = $('pages', xml).attr("backend");
}
if( undefined === $('pages', xml).attr( 'scroll_speed' ) )
thisTemplateEngine.configSettings.scrollSpeed = 400;
else
thisTemplateEngine.configSettings.scrollSpeed = $('pages', xml).attr('scroll_speed') | 0;
if ($('pages', xml).attr('bind_click_to_widget')!=undefined) {
thisTemplateEngine.configSettings.bindClickToWidget = $('pages', xml).attr('bind_click_to_widget')=="true" ? true : false;
}
if ($('pages', xml).attr('default_columns')) {
thisTemplateEngine.configSettings.defaultColumns = $('pages', xml).attr('default_columns');
}
if ($('pages', xml).attr('min_column_width')) {
thisTemplateEngine.configSettings.minColumnWidth = $('pages', xml).attr('min_column_width');
}
thisTemplateEngine.configSettings.screensave_time = $('pages', xml).attr('screensave_time');
thisTemplateEngine.configSettings.screensave_page = $('pages', xml).attr('screensave_page');
// design by url
if ($.getUrlVar("design")) {
thisTemplateEngine.configSettings.clientDesign = $.getUrlVar("design");
}
// design by config file
else if (predefinedDesign) {
thisTemplateEngine.configSettings.clientDesign = predefinedDesign;
}
// selection dialog
else {
thisTemplateEngine.selectDesign();
}
if ($('pages', xml).attr('max_mobile_screen_width'))
thisTemplateEngine.configSettings.maxMobileScreenWidth = $('pages', xml).attr('max_mobile_screen_width');
thisTemplateEngine.configSettings.getCSSlist = [];
if (thisTemplateEngine.configSettings.clientDesign) {
thisTemplateEngine.configSettings.getCSSlist.push( 'css!designs/' + thisTemplateEngine.configSettings.clientDesign + '/basic.css' );
if (!thisTemplateEngine.forceNonMobile) {
thisTemplateEngine.configSettings.getCSSlist.push( 'css!designs/' + thisTemplateEngine.configSettings.clientDesign + '/mobile.css' );
}
thisTemplateEngine.configSettings.getCSSlist.push( 'css!designs/' + thisTemplateEngine.configSettings.clientDesign + '/custom.css' );
thisTemplateEngine.configSettings.getCSSlist.push( 'designs/' + thisTemplateEngine.configSettings.clientDesign + '/design_setup' );
}
// start with the plugins
thisTemplateEngine.configSettings.pluginsToLoad = [];
$('meta > plugins plugin', xml).each(function(i) {
var name = $(this).attr('name');
if (name) {
if (!thisTemplateEngine.configSettings.pluginsToLoad[name]) {
/*
pluginsToLoadCount++;
$.includeScripts(
['plugins/' + name + '/structure_plugin.js'],
delaySetup( 'plugin_' + name)
);
pluginsToLoad[name] = true;
*/
thisTemplateEngine.configSettings.pluginsToLoad.push( 'plugins/' + name + '/structure_plugin' );
}
}
});
/*
if (0 == pluginsToLoadCount) {
delete loadReady.plugins;
}
*/
// then the icons
$('meta > icons icon-definition', xml).each(function(i) {
var $this = $(this);
var name = $this.attr('name');
var uri = $this.attr('uri');
var type = $this.attr('type');
var flavour = $this.attr('flavour');
var color = $this.attr('color');
var styling = $this.attr('styling');
var dynamic = $this.attr('dynamic');
icons.insert(name, uri, type, flavour, color, styling, dynamic);
});
// then the mappings
$('meta > mappings mapping', xml).each(function(i) {
var $this = $(this);
var name = $this.attr('name');
thisTemplateEngine.configSettings.mappings[name] = {};
var formula = $this.find('formula');
if (formula.length > 0) {
var func = eval('var func = function(x){var y;' + formula.text() + '; return y;}; func');
thisTemplateEngine.configSettings.mappings[name]['formula'] = func;
}
$this.find('entry').each(function() {
var $localThis = $(this);
var origin = $localThis.contents();
var value = [];
for (var i = 0; i < origin.length; i++) {
var $v = $(origin[i]);
if ($v.is('icon')) {
value[i] = icons.getIconElement($v.attr('name'), $v.attr('type'), $v.attr('flavour'), $v.attr('color'), $v.attr('styling'), $v.attr('class'));
}
else {
value[i] = $v.text();
}
}
// check for default entry
var isDefaultValue = $localThis.attr('default');
if (isDefaultValue != undefined) {
isDefaultValue = isDefaultValue == "true";
}
else {
isDefaultValue = false;
}
// now set the mapped values
if ($localThis.attr('value')) {
thisTemplateEngine.configSettings.mappings[name][$localThis.attr('value')] = value.length == 1 ? value[0] : value;
if (isDefaultValue) {
thisTemplateEngine.configSettings.mappings[name]['defaultValue'] = $localThis.attr('value');
}
}
else {
if (!thisTemplateEngine.configSettings.mappings[name]['range']) {
thisTemplateEngine.configSettings.mappings[name]['range'] = {};
}
thisTemplateEngine.configSettings.mappings[name]['range'][parseFloat($localThis.attr('range_min'))] = [ parseFloat($localThis.attr('range_max')), value ];
if (isDefaultValue) {
thisTemplateEngine.configSettings.mappings[name]['defaultValue'] = parseFloat($localThis.attr('range_min'));
}
}
});
});
// then the stylings
$('meta > stylings styling', xml).each(function(i) {
var name = $(this).attr('name');
var classnames = '';
thisTemplateEngine.configSettings.stylings[name] = {};
$(this).find('entry').each(function() {
var $localThis = $(this);
classnames += $localThis.text() + ' ';
// check for default entry
var isDefaultValue = $localThis.attr('default');
if (isDefaultValue != undefined) {
isDefaultValue = isDefaultValue == "true";
} else {
isDefaultValue = false;
}
// now set the styling values
if ($localThis.attr('value')) {
thisTemplateEngine.configSettings.stylings[name][$localThis.attr('value')] = $localThis.text();
if (isDefaultValue) {
thisTemplateEngine.configSettings.stylings[name]['defaultValue'] = $localThis.attr('value');
}
} else { // a range
if (!thisTemplateEngine.configSettings.stylings[name]['range'])
thisTemplateEngine.configSettings.stylings[name]['range'] = {};
thisTemplateEngine.configSettings.stylings[name]['range'][parseFloat($localThis.attr('range_min'))] = [parseFloat($localThis.attr('range_max')),$localThis.text()];
if (isDefaultValue) {
thisTemplateEngine.configSettings.stylings[name]['defaultValue'] = parseFloat($localThis.attr('range_min'));
}
}
});
thisTemplateEngine.configSettings.stylings[name]['classnames'] = classnames;
});
var statusContent = "";
// then the status bar
$('meta > statusbar status', xml).each(function(i) {
var type = $(this).attr('type');
var condition = $(this).attr('condition');
var extend = $(this).attr('hrefextend');
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
// @TODO: make this match once the new editor is finished-ish.
var editMode = 'edit_config.html' == sPage;
// skip this element if it's edit-only and we are non-edit, or the other
// way
// round
if (editMode && '!edit' == condition)
return;
if (!editMode && 'edit' == condition)
return;
var text = $(this).text();
switch (extend) {
case 'all': // append all parameters
var search = window.location.search.replace(/\$/g, '$$$$');
text = text.replace(/(href="[^"]*)(")/g, '$1' + search + '$2');
break;
case 'config': // append config file info
var search = window.location.search.replace(/\$/g, '$$$$');
search = search.replace(/.*(config=[^&]*).*|.*/, '$1');
var middle = text.replace(/.*href="([^"]*)".*/g, '{$1}');
if( 0 < middle.indexOf('?') )
search = '&' + search;
else
search = '?' + search;
text = text.replace(/(href="[^"]*)(")/g, '$1' + search + '$2');
break;
}
statusContent += text;
});
thisTemplateEngine.configSettings.footer = btoa(statusContent);
delete loadReady.page;
thisTemplateEngine.init();
thisTemplateEngine.setup_page();
};
this.init = function() {
thisTemplateEngine.initBackendClient();
require( thisTemplateEngine.configSettings.getCSSlist, delaySetup('design') );
var delaySetupPluginsCallback = delaySetup('plugins');
require( thisTemplateEngine.configSettings.pluginsToLoad, delaySetupPluginsCallback, function( err ) {
console.log( 'Plugin loading error! It happend with: "' + err.requireModules[0] + '". Is the plugin available and written correctly?');
delaySetupPluginsCallback();
});
if (thisTemplateEngine.configSettings.footer) {
$('.footer').append(atob(thisTemplateEngine.configSettings.footer));
}
};
/**
* applies the correct width to the widgets corresponding to the given colspan setting
*/
this.applyColumnWidths = function() {
var
width = thisTemplateEngine.getAvailableWidth();
function dataColspan( data )
{
if( width <= thisTemplateEngine.configSettings.maxScreenWidthColspanS )
return data.colspanS;
if( width <= thisTemplateEngine.configSettings.maxScreenWidthColspanM )
return data.colspanM;
return data.colspan;
}
// all containers
['#navbarTop', '#navbarLeft', '#main', '#navbarRight', '#navbarBottom'].forEach( function( area ){
var
allContainer = $(area + ' .widget_container'),