-
Notifications
You must be signed in to change notification settings - Fork 8
/
flowview.html
1400 lines (1278 loc) · 68.6 KB
/
flowview.html
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
<!DOCTYPE html>
<html>
<head>
<title>Flow Viewer</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script> const version = '2.0.4' </script>
<script src="config.js"></script>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.9/js/bootstrap-dialog.min.js"></script>
<!-- <script type="text/javascript" src="//cdn.athom.com/athom-api/2.1.147/athom-api.min.js"></script> -->
<script>!function(a,b,c,d){"use strict";var e="treeview",f={};f.settings={injectStyle:!0,levels:2,expandIcon:"glyphicon glyphicon-plus",collapseIcon:"glyphicon glyphicon-minus",emptyIcon:"glyphicon",nodeIcon:"",selectedIcon:"",checkedIcon:"glyphicon glyphicon-check",uncheckedIcon:"glyphicon glyphicon-unchecked",color:d,backColor:d,borderColor:d,onhoverColor:"#F5F5F5",selectedColor:"#FFFFFF",selectedBackColor:"#428bca",searchResultColor:"#D9534F",searchResultBackColor:d,enableLinks:!1,highlightSelected:!0,highlightSearchResults:!0,showBorder:!0,showIcon:!0,showCheckbox:!1,showTags:!1,multiSelect:!1,onNodeChecked:d,onNodeCollapsed:d,onNodeDisabled:d,onNodeEnabled:d,onNodeExpanded:d,onNodeSelected:d,onNodeUnchecked:d,onNodeUnselected:d,onSearchComplete:d,onSearchCleared:d},f.options={silent:!1,ignoreChildren:!1},f.searchOptions={ignoreCase:!0,exactMatch:!1,revealResults:!0};var g=function(b,c){return this.$element=a(b),this.elementId=b.id,this.styleId=this.elementId+"-style",this.init(c),{options:this.options,init:a.proxy(this.init,this),remove:a.proxy(this.remove,this),getNode:a.proxy(this.getNode,this),getParent:a.proxy(this.getParent,this),getSiblings:a.proxy(this.getSiblings,this),getSelected:a.proxy(this.getSelected,this),getUnselected:a.proxy(this.getUnselected,this),getExpanded:a.proxy(this.getExpanded,this),getCollapsed:a.proxy(this.getCollapsed,this),getChecked:a.proxy(this.getChecked,this),getUnchecked:a.proxy(this.getUnchecked,this),getDisabled:a.proxy(this.getDisabled,this),getEnabled:a.proxy(this.getEnabled,this),selectNode:a.proxy(this.selectNode,this),unselectNode:a.proxy(this.unselectNode,this),toggleNodeSelected:a.proxy(this.toggleNodeSelected,this),collapseAll:a.proxy(this.collapseAll,this),collapseNode:a.proxy(this.collapseNode,this),expandAll:a.proxy(this.expandAll,this),expandNode:a.proxy(this.expandNode,this),toggleNodeExpanded:a.proxy(this.toggleNodeExpanded,this),revealNode:a.proxy(this.revealNode,this),checkAll:a.proxy(this.checkAll,this),checkNode:a.proxy(this.checkNode,this),uncheckAll:a.proxy(this.uncheckAll,this),uncheckNode:a.proxy(this.uncheckNode,this),toggleNodeChecked:a.proxy(this.toggleNodeChecked,this),disableAll:a.proxy(this.disableAll,this),disableNode:a.proxy(this.disableNode,this),enableAll:a.proxy(this.enableAll,this),enableNode:a.proxy(this.enableNode,this),toggleNodeDisabled:a.proxy(this.toggleNodeDisabled,this),search:a.proxy(this.search,this),clearSearch:a.proxy(this.clearSearch,this)}};g.prototype.init=function(b){this.tree=[],this.nodes=[],b.data&&("string"==typeof b.data&&(b.data=a.parseJSON(b.data)),this.tree=a.extend(!0,[],b.data),delete b.data),this.options=a.extend({},f.settings,b),this.destroy(),this.subscribeEvents(),this.setInitialStates({nodes:this.tree},0),this.render()},g.prototype.remove=function(){this.destroy(),a.removeData(this,e),a("#"+this.styleId).remove()},g.prototype.destroy=function(){this.initialized&&(this.$wrapper.remove(),this.$wrapper=null,this.unsubscribeEvents(),this.initialized=!1)},g.prototype.unsubscribeEvents=function(){this.$element.off("click"),this.$element.off("nodeChecked"),this.$element.off("nodeCollapsed"),this.$element.off("nodeDisabled"),this.$element.off("nodeEnabled"),this.$element.off("nodeExpanded"),this.$element.off("nodeSelected"),this.$element.off("nodeUnchecked"),this.$element.off("nodeUnselected"),this.$element.off("searchComplete"),this.$element.off("searchCleared")},g.prototype.subscribeEvents=function(){this.unsubscribeEvents(),this.$element.on("click",a.proxy(this.clickHandler,this)),"function"==typeof this.options.onNodeChecked&&this.$element.on("nodeChecked",this.options.onNodeChecked),"function"==typeof this.options.onNodeCollapsed&&this.$element.on("nodeCollapsed",this.options.onNodeCollapsed),"function"==typeof this.options.onNodeDisabled&&this.$element.on("nodeDisabled",this.options.onNodeDisabled),"function"==typeof this.options.onNodeEnabled&&this.$element.on("nodeEnabled",this.options.onNodeEnabled),"function"==typeof this.options.onNodeExpanded&&this.$element.on("nodeExpanded",this.options.onNodeExpanded),"function"==typeof this.options.onNodeSelected&&this.$element.on("nodeSelected",this.options.onNodeSelected),"function"==typeof this.options.onNodeUnchecked&&this.$element.on("nodeUnchecked",this.options.onNodeUnchecked),"function"==typeof this.options.onNodeUnselected&&this.$element.on("nodeUnselected",this.options.onNodeUnselected),"function"==typeof this.options.onSearchComplete&&this.$element.on("searchComplete",this.options.onSearchComplete),"function"==typeof this.options.onSearchCleared&&this.$element.on("searchCleared",this.options.onSearchCleared)},g.prototype.setInitialStates=function(b,c){if(b.nodes){c+=1;var d=b,e=this;a.each(b.nodes,function(b,f){f.nodeId=e.nodes.length,f.parentId=d.nodeId,f.hasOwnProperty("selectable")||(f.selectable=!0),f.state=f.state||{},f.state.hasOwnProperty("checked")||(f.state.checked=!1),f.state.hasOwnProperty("disabled")||(f.state.disabled=!1),f.state.hasOwnProperty("expanded")||(!f.state.disabled&&c<e.options.levels&&f.nodes&&f.nodes.length>0?f.state.expanded=!0:f.state.expanded=!1),f.state.hasOwnProperty("selected")||(f.state.selected=!1),e.nodes.push(f),f.nodes&&e.setInitialStates(f,c)})}},g.prototype.clickHandler=function(b){this.options.enableLinks||b.preventDefault();var c=a(b.target),d=this.findNode(c);if(d&&!d.state.disabled){var e=c.attr("class")?c.attr("class").split(" "):[];e.indexOf("expand-icon")!==-1?(this.toggleExpandedState(d,f.options),this.render()):e.indexOf("check-icon")!==-1?(this.toggleCheckedState(d,f.options),this.render()):(d.selectable?this.toggleSelectedState(d,f.options):this.toggleExpandedState(d,f.options),this.render())}},g.prototype.findNode=function(a){var b=a.closest("li.list-group-item").attr("data-nodeid"),c=this.nodes[b];return c||console.log("Error: node does not exist"),c},g.prototype.toggleExpandedState=function(a,b){a&&this.setExpandedState(a,!a.state.expanded,b)},g.prototype.setExpandedState=function(b,c,d){c!==b.state.expanded&&(c&&b.nodes?(b.state.expanded=!0,d.silent||this.$element.trigger("nodeExpanded",a.extend(!0,{},b))):c||(b.state.expanded=!1,d.silent||this.$element.trigger("nodeCollapsed",a.extend(!0,{},b)),b.nodes&&!d.ignoreChildren&&a.each(b.nodes,a.proxy(function(a,b){this.setExpandedState(b,!1,d)},this))))},g.prototype.toggleSelectedState=function(a,b){a&&this.setSelectedState(a,!a.state.selected,b)},g.prototype.setSelectedState=function(b,c,d){c!==b.state.selected&&(c?(this.options.multiSelect||a.each(this.findNodes("true","g","state.selected"),a.proxy(function(a,b){this.setSelectedState(b,!1,d)},this)),b.state.selected=!0,d.silent||this.$element.trigger("nodeSelected",a.extend(!0,{},b))):(b.state.selected=!1,d.silent||this.$element.trigger("nodeUnselected",a.extend(!0,{},b))))},g.prototype.toggleCheckedState=function(a,b){a&&this.setCheckedState(a,!a.state.checked,b)},g.prototype.setCheckedState=function(b,c,d){c!==b.state.checked&&(c?(b.state.checked=!0,d.silent||this.$element.trigger("nodeChecked",a.extend(!0,{},b))):(b.state.checked=!1,d.silent||this.$element.trigger("nodeUnchecked",a.extend(!0,{},b))))},g.prototype.setDisabledState=function(b,c,d){c!==b.state.disabled&&(c?(b.state.disabled=!0,this.setExpandedState(b,!1,d),this.setSelectedState(b,!1,d),this.setCheckedState(b,!1,d),d.silent||this.$element.trigger("nodeDisabled",a.extend(!0,{},b))):(b.state.disabled=!1,d.silent||this.$element.trigger("nodeEnabled",a.extend(!0,{},b))))},g.prototype.render=function(){this.initialized||(this.$element.addClass(e),this.$wrapper=a(this.template.list),this.injectStyle(),this.initialized=!0),this.$element.empty().append(this.$wrapper.empty()),this.buildTree(this.tree,0)},g.prototype.buildTree=function(b,c){if(b){c+=1;var d=this;a.each(b,function(e,f){for(var g=a(d.template.item).addClass("node-"+d.elementId).addClass(f.state.checked?"node-checked":"").addClass(f.state.disabled?"node-disabled":"").addClass(f.state.selected?"node-selected":"").addClass(f.searchResult?"search-result":"").attr("data-nodeid",f.nodeId).attr("style",d.buildStyleOverride(f)),h=0;h<c-1;h++)g.append(d.template.indent);var i=[];if(f.nodes?(i.push("expand-icon"),f.state.expanded?i.push(d.options.collapseIcon):i.push(d.options.expandIcon)):i.push(d.options.emptyIcon),g.append(a(d.template.icon).addClass(i.join(" "))),d.options.showIcon){var i=["node-icon"];i.push(f.icon||d.options.nodeIcon),f.state.selected&&(i.pop(),i.push(f.selectedIcon||d.options.selectedIcon||f.icon||d.options.nodeIcon)),g.append(a(d.template.icon).addClass(i.join(" ")))}if(d.options.showCheckbox){var i=["check-icon"];f.state.checked?i.push(d.options.checkedIcon):i.push(d.options.uncheckedIcon),g.append(a(d.template.icon).addClass(i.join(" ")))}if(d.options.enableLinks?g.append(a(d.template.link).attr("href",f.href).append(f.text)):g.append(f.text),d.options.showTags&&f.tags&&a.each(f.tags,function(c,e){g.append(a(d.template.badge).append(e))}),d.$wrapper.append(g),f.nodes&&f.state.expanded&&!f.state.disabled)return d.buildTree(f.nodes,c)})}},g.prototype.buildStyleOverride=function(a){if(a.state.disabled)return"";var b=a.color,c=a.backColor;return this.options.highlightSelected&&a.state.selected&&(this.options.selectedColor&&(b=this.options.selectedColor),this.options.selectedBackColor&&(c=this.options.selectedBackColor)),this.options.highlightSearchResults&&a.searchResult&&!a.state.disabled&&(this.options.searchResultColor&&(b=this.options.searchResultColor),this.options.searchResultBackColor&&(c=this.options.searchResultBackColor)),"color:"+b+";background-color:"+c+";"},g.prototype.injectStyle=function(){this.options.injectStyle&&!c.getElementById(this.styleId)&&a('<style type="text/css" id="'+this.styleId+'"> '+this.buildStyle()+" </style>").appendTo("head")},g.prototype.buildStyle=function(){var a=".node-"+this.elementId+"{";return this.options.color&&(a+="color:"+this.options.color+";"),this.options.backColor&&(a+="background-color:"+this.options.backColor+";"),this.options.showBorder?this.options.borderColor&&(a+="border:1px solid "+this.options.borderColor+";"):a+="border:none;",a+="}",this.options.onhoverColor&&(a+=".node-"+this.elementId+":not(.node-disabled):hover{background-color:"+this.options.onhoverColor+";}"),this.css+a},g.prototype.template={list:'<ul class="list-group"></ul>',item:'<li class="list-group-item"></li>',indent:'<span class="indent"></span>',icon:'<span class="icon"></span>',link:'<a href="#" style="color:inherit;"></a>',badge:'<span class="badge"></span>'},g.prototype.css=".treeview .list-group-item{cursor:pointer}.treeview span.indent{margin-left:10px;margin-right:10px}.treeview span.icon{width:12px;margin-right:5px}.treeview .node-disabled{color:silver;cursor:not-allowed}",g.prototype.getNode=function(a){return this.nodes[a]},g.prototype.getParent=function(a){var b=this.identifyNode(a);return this.nodes[b.parentId]},g.prototype.getSiblings=function(a){var b=this.identifyNode(a),c=this.getParent(b),d=c?c.nodes:this.tree;return d.filter(function(a){return a.nodeId!==b.nodeId})},g.prototype.getSelected=function(){return this.findNodes("true","g","state.selected")},g.prototype.getUnselected=function(){return this.findNodes("false","g","state.selected")},g.prototype.getExpanded=function(){return this.findNodes("true","g","state.expanded")},g.prototype.getCollapsed=function(){return this.findNodes("false","g","state.expanded")},g.prototype.getChecked=function(){return this.findNodes("true","g","state.checked")},g.prototype.getUnchecked=function(){return this.findNodes("false","g","state.checked")},g.prototype.getDisabled=function(){return this.findNodes("true","g","state.disabled")},g.prototype.getEnabled=function(){return this.findNodes("false","g","state.disabled")},g.prototype.selectNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setSelectedState(a,!0,b)},this)),this.render()},g.prototype.unselectNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setSelectedState(a,!1,b)},this)),this.render()},g.prototype.toggleNodeSelected=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.toggleSelectedState(a,b)},this)),this.render()},g.prototype.collapseAll=function(b){var c=this.findNodes("true","g","state.expanded");this.forEachIdentifier(c,b,a.proxy(function(a,b){this.setExpandedState(a,!1,b)},this)),this.render()},g.prototype.collapseNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setExpandedState(a,!1,b)},this)),this.render()},g.prototype.expandAll=function(b){if(b=a.extend({},f.options,b),b&&b.levels)this.expandLevels(this.tree,b.levels,b);else{var c=this.findNodes("false","g","state.expanded");this.forEachIdentifier(c,b,a.proxy(function(a,b){this.setExpandedState(a,!0,b)},this))}this.render()},g.prototype.expandNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setExpandedState(a,!0,b),a.nodes&&b&&b.levels&&this.expandLevels(a.nodes,b.levels-1,b)},this)),this.render()},g.prototype.expandLevels=function(b,c,d){d=a.extend({},f.options,d),a.each(b,a.proxy(function(a,b){this.setExpandedState(b,c>0,d),b.nodes&&this.expandLevels(b.nodes,c-1,d)},this))},g.prototype.revealNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){for(var c=this.getParent(a);c;)this.setExpandedState(c,!0,b),c=this.getParent(c)},this)),this.render()},g.prototype.toggleNodeExpanded=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.toggleExpandedState(a,b)},this)),this.render()},g.prototype.checkAll=function(b){var c=this.findNodes("false","g","state.checked");this.forEachIdentifier(c,b,a.proxy(function(a,b){this.setCheckedState(a,!0,b)},this)),this.render()},g.prototype.checkNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setCheckedState(a,!0,b)},this)),this.render()},g.prototype.uncheckAll=function(b){var c=this.findNodes("true","g","state.checked");this.forEachIdentifier(c,b,a.proxy(function(a,b){this.setCheckedState(a,!1,b)},this)),this.render()},g.prototype.uncheckNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setCheckedState(a,!1,b)},this)),this.render()},g.prototype.toggleNodeChecked=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.toggleCheckedState(a,b)},this)),this.render()},g.prototype.disableAll=function(b){var c=this.findNodes("false","g","state.disabled");this.forEachIdentifier(c,b,a.proxy(function(a,b){this.setDisabledState(a,!0,b)},this)),this.render()},g.prototype.disableNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setDisabledState(a,!0,b)},this)),this.render()},g.prototype.enableAll=function(b){var c=this.findNodes("true","g","state.disabled");this.forEachIdentifier(c,b,a.proxy(function(a,b){this.setDisabledState(a,!1,b)},this)),this.render()},g.prototype.enableNode=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setDisabledState(a,!1,b)},this)),this.render()},g.prototype.toggleNodeDisabled=function(b,c){this.forEachIdentifier(b,c,a.proxy(function(a,b){this.setDisabledState(a,!a.state.disabled,b)},this)),this.render()},g.prototype.forEachIdentifier=function(b,c,d){c=a.extend({},f.options,c),b instanceof Array||(b=[b]),a.each(b,a.proxy(function(a,b){d(this.identifyNode(b),c)},this))},g.prototype.identifyNode=function(a){return"number"==typeof a?this.nodes[a]:a},g.prototype.search=function(b,c){c=a.extend({},f.searchOptions,c),this.clearSearch({render:!1});var d=[];if(b&&b.length>0){c.exactMatch&&(b="^"+b+"$");var e="g";c.ignoreCase&&(e+="i"),d=this.findNodes(b,e),a.each(d,function(a,b){b.searchResult=!0})}return c.revealResults?this.revealNode(d):this.render(),this.$element.trigger("searchComplete",a.extend(!0,{},d)),d},g.prototype.clearSearch=function(b){b=a.extend({},{render:!0},b);var c=a.each(this.findNodes("true","g","searchResult"),function(a,b){b.searchResult=!1});b.render&&this.render(),this.$element.trigger("searchCleared",a.extend(!0,{},c))},g.prototype.findNodes=function(b,c,d){c=c||"g",d=d||"text";var e=this;return a.grep(this.nodes,function(a){var f=e.getNodeValue(a,d);if("string"==typeof f)return f.match(new RegExp(b,c))})},g.prototype.getNodeValue=function(a,b){var c=b.indexOf(".");if(c>0){var e=a[b.substring(0,c)],f=b.substring(c+1,b.length);return this.getNodeValue(e,f)}return a.hasOwnProperty(b)?a[b].toString():d};var h=function(a){b.console&&b.console.error(a)};a.fn[e]=function(b,c){var d;return this.each(function(){var f=a.data(this,e);"string"==typeof b?f?a.isFunction(f[b])&&"_"!==b.charAt(0)?(c instanceof Array||(c=[c]),d=f[b].apply(f,c)):h("No such method : "+b):h("Not initialized, can not call method : "+b):"boolean"==typeof b?d=f:a.data(this,e,new g(this,a.extend(!0,{},b)))}),d||this}}(jQuery,window,document);</script>
<style>.sidebar-nav li a,.sidebar-nav li a:active,.sidebar-nav li a:focus{text-decoration:none}body{overflow-x:hidden}#wrapper{padding-left:0;-webkit-transition:all .5s ease;-moz-transition:all .5s ease;-o-transition:all .5s ease;transition:all .5s ease}#wrapper.toggled{padding-left:250px}#sidebar-wrapper{z-index:99;position:fixed;left:250px;width:0;height:100%;margin-left:-250px;overflow-y:auto;background:#555;-webkit-transition:all .5s ease;-moz-transition:all .5s ease;-o-transition:all .5s ease;transition:all .5s ease}#wrapper.toggled #sidebar-wrapper{width:250px}#page-content-wrapper{width:100%;position:absolute;padding:15px}#wrapper.toggled #page-content-wrapper{position:absolute;margin-right:-250px}.sidebar-nav{position:absolute;top:0;width:250px;margin:0;padding:0;list-style:none}.sidebar-nav li{text-indent:20px;line-height:40px}.sidebar-nav li a{display:block;color:#999}.sidebar-nav li a:hover{text-decoration:none;color:#fff;background:rgba(255,255,255,.2)}.sidebar-nav>.sidebar-brand{height:65px;font-size:18px;line-height:60px}.sidebar-nav>.sidebar-brand a{color:#999}.sidebar-nav>.sidebar-brand a:hover{color:#fff;background:0 0}@media(min-width:768px){#wrapper{padding-left:250px}#wrapper.toggled{padding-left:0}#sidebar-wrapper{width:250px}#wrapper.toggled #sidebar-wrapper{width:0}#page-content-wrapper{padding:20px;position:relative}#wrapper.toggled #page-content-wrapper{position:relative;margin-right:0}}</style>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.9/css/bootstrap-dialog.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<style>
body {
background-image: linear-gradient(#187596, #029680);
font-family: "Roboto", Helvetica, sans-serif;
font-weight: 300;
}
h1 {
color: white;
}
.panel-heading {
border-top-left-radius: 12px;
border-top-right-radius: 12px;
}
.panel {
background-color: rgba(255, 255, 255, 0.2);
border: none;
border-radius: 12px;
}
.well {
margin-bottom: 5px;
background-color: white;
border: none;
border-radius: 6px;
}
.col-sm-5, .col-sm-2 {
padding-right: 10px;
padding-left: 10px;
}
.node-folders {
padding: 5px 10px;
}
.placeholder {
border: 1px solid green;
background-color: white;
-webkit-box-shadow: 0px 0px 10px #888;
-moz-box-shadow: 0px 0px 10px #888;
box-shadow: 0px 0px 10px #888;
}
.draghandle {
cursor: move;
}
.draghandle-v {
cursor: ns-resize;
}
.folder-state-hover {
background-color: #dff0d8;
color: #3c763d;
border-color: #d6e9c6;
}
.colorbox {
display: inline-block;
height: 13px;
width: 13px;
vertical-align: text-top;
}
/* tokens: */
.label-string {
background-color: rgb(117,213,0);
border-radius: 12px;
}
.label-number {
background-color: rgb(2,170,214);
border-radius: 12px;
}
.label-boolean {
background-color: rgb(213,103,0);
border-radius: 12px;
}
/* loading */
#loadingimg {
-webkit-animation: rotation 2s infinite linear;
padding: 15px;
}
@-webkit-keyframes rotation {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
}
}
</style>
</head>
<body>
<div id="wrapper" class="toggled">
<div id="sidebar-wrapper">
<br />
<br />
<span style="color: white" class="h3"> Folders</span>
<button class="btn btn-default" data="add_btn" data-toggle="tooltip" title="" onclick="addFlowFolder()" data-original-title="Add folder"><i class="fa fa-plus"></i></button>
<button class="btn btn-default" data="edit_btn" data-toggle="tooltip" title="" onclick="editFlowFolder()" data-original-title="Edit folder"><i class="fa fa-pencil"></i></button>
<button class="btn btn-default" data="delete_btn" data-toggle="tooltip" title="" onclick="deleteFlowFolder()" data-original-title="Delete folder"><i class="fa fa-remove"></i></button>
<br />
<br />
<div id="folders">
Showing <span class="label label-info">0</span> flows in <span class="label label-info">0</span> folders</h1>
</div>
</div>
<div id="page-content-wrapper">
<div class=container-fluid>
<h1>Homey Flow Viewer <span id="version" class=h3></span></h1>
<div class="row">
<div class="form-group col-sm-2">
<a href="#menu-toggle" class="btn btn-default" id="menu-toggle">Toggle folders</a>
</div>
<div class="form-group col-sm-2">
<a href="#token-toggle" class="btn btn-default" id="token-toggle">Toggle tokens</a>
</div>
<div class="col-sm-8">
<div class="form-group has-feedback">
<input id="search" type="text" class="form-control" placeholder="Search" onKeyUp="search()" onChange="search()"/>
<i class="glyphicon glyphicon-search form-control-feedback"></i>
</div>
</div>
</div>
<div id="tokens" class="hide"></div>
<div id="flows"></div>
<div class="hide">
<div class="template_token">
<div class="row">
<div class="col-sm-3"><span data="token_uri"></div>
<div class="col-sm-3"><span data="token_title"></div>
<div class="col-sm-3"><span data="token_type"></div>
<div class="col-sm-3"><span data="token_value"></div>
</div>
</div>
<div class="template_flow">
<div class="panel panel-success" data="flow" data-flow-id="" data-folder-id="">
<div class="panel-heading">
<div class="row">
<div class="col-sm-4 draghandle" data="flow_path"></div>
<div class="col-sm-4 text-center">
<span class="text-muted" data="test_btn" data-toggle="tooltip" title="Test flow"><i class="fa fa-play"></i></span>
<strong data="title"></strong>
</div>
<div class="col-sm-4 text-right">
<span class="label label-default" data="label_disabled"></span>
<span class="label label-danger" data="label_broken"></span>
<button class="btn btn-default" data="toggle_btn" data-toggle="tooltip" title="Enable or disable"><i class="fa fa-square-o"></i></button>
<button class="btn btn-default" data="edit_btn" data-toggle="tooltip" title="Rename & Move"><i class="fa fa-pencil"></i></button>
<button class="btn btn-default" data="copy_btn" data-toggle="tooltip" title="Copy"><i class="fa fa-clone"></i></button>
<button class="btn btn-default" data="delete_btn" data-toggle="tooltip" title="Delete"><i class="fa fa-remove"></i></button>
</div>
</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12 small text-center">
<div>Triggered <span data="triggercount"></span> times.</div>
</div>
</div>
<div class="row">
<div class="col-sm-2 small">
<span data="cards_trigger">
<div>When</div>
</span>
</div>
<div class="col-sm-5 small" data="cards_condition">
<span data="cards_condition_group1">
<div>And</div>
</span>
<span data="cards_condition_group2">
<div>Or</div>
</span>
<span data="cards_condition_group3">
<div>Or</div>
</span>
</div>
<div class="col-sm-5 small" data="cards_action">
<span data="cards_action_then">
<div>Then</div>
</span>
<span data="cards_action_else">
<div>Else</div>
</span>
</div>
</div>
</div>
</div>
</div>
<div class="template_card">
<div data="card" class="card">
<div class="well well-sm">
<span class="label label-danger" data="label_danger"></span>
<span class="label label-success pull-right" data="card_type_device"></span>
<span class="label label-info pull-right" data="card_type_app"></span>
<span class="label label-primary pull-right" data="card_type_manager"></span>
<!-- <span class="text-muted draghandle-v" data="move_card_btn"><i class="fa fa-arrows"></i></span> -->
<!-- <span class="text-muted" data="edit_card_btn" data-toggle="tooltip" title="Edit"><i class="fa fa-pencil"></i></span> -->
<span class="text-muted" data="test_card_btn" data-toggle="tooltip" title="Test"><i class="fa fa-play"></i></span>
<span class="text-nowrap"><strong data="card_title"></strong></span><br>
<span class="text-muted" data="card_args"></span>
<span class="text-muted" data="card_delay"></span>
<span class="text-muted" data="card_droptoken"></span>
</div>
</div>
</div>
<div class="dialog_copy form-group">
<label for="copyName">New flow name</label>
<input id="copyName" class="form-control" type="text" value="">
<label for="copyFolder">Parent folder</label>
<select id="copyFolder" class="form-control">
<option value="false">None</option>
</select>
</div>
<div class="dialog_edit form-group">
<label for="editName">Flow name</label>
<input id="editName" class="form-control" type="text" value="">
<label for="editFolder">Parent folder</label>
<select id="editFolder" class="form-control">
<option value="false">None</option>
</select>
</div>
<div class="dialog_folder_edit">
<label for="folderName" >Folder name</label>
<input id="folderName" class="form-control" type="text" value="">
<label for="folderParent">Parent folder</label>
<select id="folderParent" class="form-control">
<option value="false">None</option>
</select>
</div>
<div class="dialog_folder_select">
<label for="folder">Folder</label>
<select id="folder" class="form-control">
</select>
</div>
<div class="dialog_test form-group">
<span class="text-muted" data="Progress:"></span>
<span class="text-muted" data="test_status">initializing...</span>
</div>
<!-- <div class="dialog_edit_card form-group">
<label for="delay">Delay</label>
<input id="delay" class="form-control" type="text" value="">
<div class="arguments"></div>
</div>
<div class="dialog_edit_card_argument text form-group">
<label for="field"></label>
<input id="field" class="form-control" type="text" value="">
</div>
<div class="dialog_edit_card_argument text form-group">
<label for="field"></label>
<input id="field" class="form-control" type="number" value="">
</div> -->
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<p>flows: <span id=flow_count>loading...</span></p>
</div>
</footer>
</div>
<div id="loader" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
<div class="modal-dialog modal-sm">
<div class="modal-content" center style="width: 350px">
<span><img id="loadingimg" height=64 src="https://etc.athom.com/logo/transparent/256.png"></span>
<span id="loadtext"></span>
</div>
</div>
</div>
<script>
// todo https://getbootstrap.com/docs/4.3/components/navbar/
var devices = []
var cards
var folders = []
var flows = []
var tokens = []
$('#version').html(version)
if (setup.ip === '0.0.0.0') alert('Configure your Homey IP in the config.js file...')
if (setup.bearer_token === 'your token') alert('Configure your Bearer token in the config.js file...')
if (setup.homeyId === 'your Homey ID') alert('Configure your Homey ID in the config.js file...')
$.ajaxSetup({
contentType : 'application/json',
headers: {Authorization: 'Bearer ' + setup.bearer_token}
})
jQuery.expr[':'].icontains = jQuery.expr.createPseudo(function (arg) {
return function (elem) {
return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0
}
})
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1)
}
function addToken (token) {
var newToken = $('.template_token').clone()
$(newToken).find('[data=token_uri]').html(token.uriObj.name)
$(newToken).find('[data=token_title]').html(formatToken(token))
$(newToken).find('[data=token_type]').html(token.type)
$(newToken).find('[data=token_value]').html(token.value)
$('#tokens').append(newToken.html())
}
function addFlow (flow) {
var newFlow = $('.template_flow').clone()
$(newFlow).find('[data=flow]').attr('data-flow-id', flow.id)
$(newFlow).find('[data=flow]').attr('data-folder-id', flow.folder)
$(newFlow).find('[data=title]').html(flow.name)
$(newFlow).find('[data=triggercount]').html(flow.triggerCount)
$(newFlow).find('[data=cards_trigger]').append(formatCard(flow.id, flow.trigger, 'trigger', 0).html())
$(newFlow).find('[data=cards_condition_group1]').append(formatCards(flow, 'conditions', 'group1').html())
$(newFlow).find('[data=cards_condition_group2]').append(formatCards(flow, 'conditions', 'group2').html())
$(newFlow).find('[data=cards_condition_group3]').append(formatCards(flow, 'conditions', 'group3').html())
$(newFlow).find('[data=cards_action_then]').append(formatCards(flow, 'actions', 'then').html())
$(newFlow).find('[data=cards_action_else]').append(formatCards(flow, 'actions', 'else').html())
$(newFlow).find('[data=toggle_btn]').attr('onClick', `toggleFlow('${flow.id}')`)
$(newFlow).find('[data=edit_btn]').attr('onClick', `editFlow('${flow.id}')`)
$(newFlow).find('[data=copy_btn]').attr('onClick', `copyFlow('${flow.id}')`)
$(newFlow).find('[data=delete_btn]').attr('onClick', `deleteFlow('${flow.id}')`)
$(newFlow).find('[data=test_btn]').attr('onClick', `testFlow('${flow.id}')`)
$(newFlow).find('[data=flow_path]').html('<i class="fa fa-folder-open" aria-hidden="true"></i> ' + (flow.folder ? formatFolder(flow.folder) : ''))
if (flow.broken) {
$(newFlow).find('[data=flow]').removeClass("panel-success").addClass("panel-danger")
$(newFlow).find('[data=label_broken]').html("BROKEN")
$(newFlow).find('[data=copy_btn]').remove()
}
if ($(newFlow).find('[data=cards_condition_group1] .card').size() === 0 ) $(newFlow).find('[data=cards_condition_group1]').remove()
if ($(newFlow).find('[data=cards_condition_group2] .card').size() === 0 ) $(newFlow).find('[data=cards_condition_group2]').remove()
if ($(newFlow).find('[data=cards_condition_group3] .card').size() === 0 ) $(newFlow).find('[data=cards_condition_group3]').remove()
if ($(newFlow).find('[data=cards_action_then] .card').size() === 0 ) $(newFlow).find('[data=cards_action_then]').remove()
if ($(newFlow).find('[data=cards_action_else] .card').size() === 0 ) $(newFlow).find('[data=cards_action_else]').remove()
// new or existing
if ($(`[data-flow-id=${flow.id}]`).length > 0) {
$(`[data-flow-id=${flow.id}]`).replaceWith(newFlow.html())
} else {
$('#flows').append(newFlow.html())
}
showFlowToggleButton(flow.id)
}
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
function cleanFlowV2 (flow) {
delete flow.broken
if (flow.actions) flow.actions.forEach((action, index) => {if (action.droptoken === false) delete flow.actions[index].droptoken})
if (flow.conditions) flow.conditions.forEach((condition, index) => {if (condition.droptoken === false) delete flow.condition[index].droptoken})
return flow
}
function conditionTitleParse (e, t) {
var a = e.match(/\!\{\{(.*?)\}\}/g)
if (a === null) return e
a.forEach(function(a) {
var n = a
if('!' == a.charAt(0)) a = a.substring(1)
e = e.replace(n, a.replace('{{', '').replace('}}', '').split('|')[t ? 0 : 1] || '')
})
return e
}
function copyFlow (flowId) {
copyFlowDialog(flowId, function(newName, newFolder) {
if (newName) {
if (newFolder === 'false') newFolder = false
$.getJSON(`${setup.protocol}://${setup.ip}/api/manager/flow/flow/${flowId}`, function(existingFlow) {
if (existingFlow.broken) return alert('Cannot clone a broken flow!')
var newFlow = cleanFlowV2(existingFlow)
newFlow.name = newName
newFlow.folder = newFolder
$.post(`${setup.protocol}://${setup.ip}/api/manager/flow/flow`, JSON.stringify(newFlow), function(data) {
console.log('new id', data.id || data)
if (!data.id) return alert('Copy failure...')
loadFlowsAndFolders()
})
})
}
})
}
function deleteFlow (flowId) {
deleteFlowDialog(flowId, function(doDelete) {
if (!doDelete) return
$.ajax({
url: `${setup.protocol}://${setup.ip}/api/manager/flow/flow/${flowId}`,
type: 'DELETE',
success: loadFlowsAndFolders()
})
})
}
function deleteFlowFolder () {
selectFlowFolderDialog(function (folderId) {
if (!folderId) return
deleteFlowFolderDialog(folderId, async function(doDelete) {
if (!doDelete) return
let parentId = getFolder(folderId).parent || null
await asyncForEach(flows.filter(flow => flow.folder === folderId), async (flow) => {
showLoading('move flow ' + flow.name)
console.log('move flow ', flow.id)
await saveFlow(flow.id, {folder: parentId})
})
await asyncForEach(folders.filter(folder => folder.parent === folderId), async (folder) => {
showLoading('move subfolder ' + folder.name)
console.log('move subfolder', folder.id)
await saveFlowFolder(folder.id, {parent: parentId})
})
$.ajax({
url: `${setup.protocol}://${setup.ip}/api/manager/flow/flowfolder/${folderId}`,
type: 'DELETE',
success: loadFlowsAndFolders()
})
})
})
}
function editFlow (flowId) {
editFlowDialog(flowId, async function (newName, newFolder) {
if (newFolder === 'false') newFolder = null
var saveFlow = {name: newName.trim(), folder: newFolder}
if (saveFlow.name.length === 0) return
await saveFlow(flowId, saveFlow)
})
}
function folderOrder (id) {
let order = (getFolder(id)) ? formatOrderNumber(getFolder(id).order) + '|' : '_'
if (getFolder(id).folder) order = folderOrder(getFolder(id).folder) + order
return order
}
function formatArgs (card, definitions, flowId) {
var output = ''
Object.keys(card.args).forEach(function (argument) {
if (Object.prototype.toString.call(definitions.args) === '[object Object]') definitions.args = [definitions.args]
output += '<i>' + argument + '</i>: ' + formatArgValue(definitions.args ? definitions.args.find(item => item.name === argument) : undefined, card.args[argument]) + '<br>'
})
output = output.replace(/(?:\[\[)(.*?)(?:\]\])/g, function (tag) {
tag = tag.replace(/\[|\]/g, '')
var token = {title: tag}
return formatToken(token, flowId)
})
return output
}
function formatArgValue (argDef = {type: 'object'}, value) {
switch (argDef.type) {
case 'autocomplete':
return value.name
case 'dropdown':
return argDef.values.find(item => item.id.toString() === value.toString()).title
case 'color':
return `<span class="colorbox" style="background-color: ${value}"> </span> (${value})`
case 'range':
return value * (argDef.labelMultiplier || 1) + (argDef.title || '')
case 'object':
return value.name || JSON.stringify(value)
case 'text':
case 'number':
case 'time':
return value
default:
return value
}
}
function formatCard (flowId, card, type, index) {
if (isEmptyObject(card)) return noCard()
if (card.broken) return noCard(card.id)
var newCard = $('.template_card').clone()
var definitions = getCard(card.uri, (type === 'trigger') ? type : type.slice(0, -1), card.id)
if (definitions === undefined) {
console.log(`no definitions found for ${type}-card with uri ${card.uri} in flow '${getFlow(flowId).name}', marked as 'NO CARD'`)
return noCard()
}
var app = getApp(card.uri)
if (app === undefined) {
console.log(`no app found for ${type}-card with uri ${card.uri} in flow '${getFlow(flowId).name}', marked as 'NO CARD'`)
return noCard()
}
$(newCard).find('[data=card]').attr('card_index', index)
if (type === 'conditions') {
$(newCard).find('[data=card_title]').html(conditionTitleParse(definitions.title, !card.inverted))
} else {
$(newCard).find('[data=card_title]').html(definitions.title)
}
$(newCard).find('[data=card_type_' + app.uriObj.type + ']').html(app.uriObj.name)
if (app.uriObj.color) $(newCard).find('[data=card_type_' + app.uriObj.type + ']').css('background-color',app.uriObj.color)
if (card.args) $(newCard).find('[data=card_args]').html(formatArgs(card, definitions, flowId))
if (card.delay && card.delay.number !== '0') $(newCard).find('[data=card_delay]').html('<i>delay</i>: ' + card.delay.number + (card.delay.multiplier === 60 ? ' minute' : ' second') + (card.delay.number !== '1' ? 's' : ''))
if (card.droptoken) $(newCard).find('[data=card_droptoken]').html('<i>token</i>: ' + formatToken({title: card.droptoken}, flowId))
if (definitions.tokens) {
var tokens = '<i>tokens</i>:<br /> '
definitions.tokens.forEach(token => {
tokens += formatToken(token, flowId)
})
$(newCard).find('[data=card_droptoken]').html(tokens)
}
if (type === 'trigger') $(newCard).find('[data=move_card_btn], [data=test_card_btn]').remove()
$(newCard).find('[data=test_card_btn]').attr('onClick', `testCard('${flowId}','${type}',${index})`)
return newCard
}
function formatCards (flow, type, group) {
// if (type === 'actions' && flow[type].length === 0) return noCard()
var newCards = $("<div />")
flow[type].forEach(function (card, index) {
if (!group || card.group === group) {
newCards.append(formatCard(flow.id, card, type, index).html())
}
})
return newCards
}
function formatFolder (id) {
var result = getFolder(id).name
if (getFolder(id).parent) result = formatFolder(getFolder(id).parent) + " > " + result
return result
}
function formatOrderNumber (order) {
return ('00000' + order).slice(-5)
}
function formatToken (token, flowId) {
// find local token in flow
if (token.title.indexOf('|') > 0) {
let uri = token.title.split('|')[0]
let id = token.title.split('|')[1]
token = tokens.find(x => (x.uri === uri && (x.id === id || x.title === id))) || token
} else if (!token.type) {
token.type = 'string'
let localTriggerCard = getCard(getFlow(flowId).trigger.uri, 'trigger', getFlow(flowId).trigger.id)
if (localTriggerCard && localTriggerCard.tokens) token = localTriggerCard.tokens.find(x => x.id === token.title) || token
}
var tooltipexample = token.example ? `, example: ${token.example}` : ''
return `<span class="label label-info label-${token.type}" data-toggle="tooltip" title="${token.type}${tooltipexample}">${token.title}</span> `
}
function getApp (uri) {
return cards.trigger.find(app => app.uri === uri) || cards.condition.find(app => app.uri === uri) || cards.action.find(app => app.uri === uri)
}
function getCard (uri, type, id) {
return cards[type].find(card => (card.id === id && card.uri === uri))
}
function getDevice (id) {
return devices.find(device => device.id === id)
}
function getFlow (id) {
return flows.find(flow => flow.id === id)
}
function getFolder (id) {
return folders.find(folder => folder.id === id)
}
function isEmptyObject (obj) {
return Object.getOwnPropertyNames(obj).length === 0
}
function loadCards () {
return new Promise(function (resolve) {
$.getJSON(`${setup.protocol}://${setup.ip}/api/manager/flow/flowcardtrigger/`, function(data) {
cards = {trigger: [], condition: [], action: []}
$.each(data, (index, resultCardTrigger) => cards.trigger.push(resultCardTrigger))
$.getJSON(`${setup.protocol}://${setup.ip}/api/manager/flow/flowcardcondition/`, function(data) {
$.each(data, (index, resultCardCondition) => cards.condition.push(resultCardCondition))
$.getJSON(`${setup.protocol}://${setup.ip}/api/manager/flow/flowcardaction/`, function(data) {
$.each(data, (index, resultCardAction) => cards.action.push(resultCardAction))
resolve(cards)
})
})
})
})
}
function loadDevices () {
return new Promise(function (resolve) {
$.getJSON(`${setup.protocol}://${setup.ip}/api/manager/devices/device/`, function(data) {
devices = []
$.each(data, (index, resultDevice) => devices.push({id: resultDevice.id, name: resultDevice.name}))
resolve(devices)
})
})
}
function loadFlows () {
return new Promise(function (resolve) {
$.getJSON(`${setup.protocol}://${setup.ip}/api/manager/flow/flow/`, function(data) {
flows = []
$.each(data, (index, flow) => flows.push(flow))
resolve(flows)
})
})
}
async function loadFlowsAndFolders (hideloading = true) {
showLoading('loading flows')
flows = await loadFlows()
showLoading('loading folders')
folders = await loadFolders()
showLoading('present flows')
showFolders()
showLoading('making Homey great again')
showFlows()
if (hideloading) hideLoading()
}
function loadFolders () {
return new Promise(function (resolve) {
$.getJSON(`${setup.protocol}://${setup.ip}/api/manager/flow/flowfolder/`, function(data) {
folders = []
$.each(data, (index, folder) => folders.push(folder))
resolve(folders)
})
})
}
function loadTokens (callback) {
return new Promise(function (resolve) {
$.getJSON(`${setup.protocol}://${setup.ip}/api/manager/flowtoken/flowtoken/`, function(data) {
tokens = []
$.each(data, (index, token) => tokens.push(token))
resolve(tokens)
})
})
}
function noCard (id) {
var noCard = $('<div />')
if (id) {
noCard.html(`<br><span class="label label-danger">NO CARD (${id})</span>`)
} else {
noCard.html('<br><span class="label label-danger">NO CARD</span>')
}
return noCard
}
function saveFlow (flowId, flow) {
return new Promise((resolve, reject) => {
$.ajax({
url: `${setup.protocol}://${setup.ip}/api/manager/flow/flow/${flowId}`,
type: 'PUT',
data: JSON.stringify(flow),
success: resolve,
error: reject
})
})
}
function saveFlowFolder (folderId, folder) {
return new Promise((resolve, reject) => {
$.ajax({
url: `${setup.protocol}://${setup.ip}/api/manager/flow/flowfolder/${folderId}`,
type: 'PUT',
data: JSON.stringify(folder),
success: resolve,
error: reject
})
})
}
function showFlows () {
function loopFolders(folders) {
folders.forEach(folder => addFolderFlows(folder))
}
function addFolderFlows(folder) {
flows.filter(x => x.folder === folder.id).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1).map(flow => addFlow(flow))
if (folder.nodes) loopFolders(folder.nodes)
}
addFolderFlows({id: null}) // toplevel
loopFolders(getTree()) // folder structur
setFlowsDraggable()
search()
}
function showFlowToggleButton (flowId) {
if (getFlow(flowId).enabled) {
$(`[data-flow-id=${flowId}] [data=label_disabled]`).html("")
$(`[data-flow-id=${flowId}] [data=toggle_btn] i`).removeClass('fa-square-o').addClass('fa-check-square-o')
if (!getFlow(flowId).broken) {
$(`[data-flow-id=${flowId}]`).removeClass("panel-default").addClass("panel-success")
}
} else {
$(`[data-flow-id=${flowId}] [data=label_disabled]`).html("DISABLED")
$(`[data-flow-id=${flowId}] [data=toggle_btn] i`).removeClass('fa-check-square-o').addClass('fa-square-o')
if (!getFlow(flowId).broken) {
$(`[data-flow-id=${flowId}]`).removeClass("panel-success").addClass("panel-default")
}
}
}
function showFolders () {
$('#folders').treeview({
data: getTree(),
expandIcon: 'glyphicon glyphicon-chevron-right',
collapseIcon: 'glyphicon glyphicon-chevron-down',
showTags: true,
onNodeSelected: function(event, node) {
$('[id=search]').val('')
search()
setTimeout(setFoldersDroppable, 500)
},
onNodeUnselected: function (event, node) {
search()
setTimeout(setFoldersDroppable, 500)
}
})
setFoldersDroppable()
}
function showTokens () {
tokens.forEach(token => {
addToken(token)
})
}
function sortFolders () {
folders.forEach(folder => {
folder.sorting = folderOrder(folder.id)
})
folders.sort((a, b) => (a.sorting > b.sorting ? 1 : -1))
}
async function ready() {
showLoading('loading devices')
devices = await loadDevices()
showLoading('loading cards')
cards = await loadCards()
showLoading('loading tokens')
tokens = await loadTokens()
showTokens()
await loadFlowsAndFolders(false)
connectFlowManager(() => {
setTimeout(() => {
$("#wrapper").toggleClass("toggled")
$('#flow_count').html(flows.length)
setTooltips()
hideLoading()
// setFlowCardsSortable()
}, 500)
})
setTimeout(hideLoading, 5000) // failsave
}
async function updateFlowFolder (flowId, folderId) {
var flow = {name: getFlow(flowId).name, folder: folderId}
await saveFlow(flowId, flow)
await loadFlowsAndFolders()
}
async function toggleFlow (flowId) {
flows.find(flow => flow.id === flowId).enabled = !getFlow(flowId).enabled
await saveFlow(flowId, {enabled: getFlow(flowId).enabled})
showFlowToggleButton(flowId)
}
function copyFlowDialog (flowId, callback) {
var message = $('.dialog_copy').clone()
buildFolderListSelector(message, 'copyFolder')
$(message).find('[id=copyFolder]').val((getFlow(flowId).folder || false).toString())
$(message).find('[id=copyName]').attr('value', `${getFlow(flowId).name} (copy)`)
BootstrapDialog.show({
title: 'Copy flow',
message: message,
buttons: [
{
label: 'Cancel',
action: function (dialogRef) {
dialogRef.close()
callback(false)
}
},{
label: 'Copy',
action: function (dialogRef) {
let newName = dialogRef.getModalBody().find('[id=copyName]').val()
let newFolder = dialogRef.getModalBody().find('[id=copyFolder]').val()
dialogRef.close()
callback(newName, newFolder)
}
}
]
})
}
function deleteFlowDialog (flowId, callback) {
BootstrapDialog.show({
title: 'Delete flow',
message: 'Are you sure you want to delete flow ' + getFlow(flowId).name + '?',
buttons: [
{
label: 'Cancel',
action: function (dialogRef) {
dialogRef.close()
callback(false)
}
},{
label: 'Delete',
action: function (dialogRef) {
dialogRef.close()
callback(true)
}
}
]
})
}
function deleteFlowFolderDialog (folderId, callback) {
let flowCount = flows.filter(flow => flow.folder === folderId).length
let folderCount = folders.filter(folder => folder.parent === folderId).length
let parentId = getFolder(folderId).parent
let deleteMessage = `Are you sure you want to delete folder <strong>${getFolder(folderId).name}</strong>?<br>`
if (flowCount + folderCount > 0) {
deleteMessage += `${flowCount} flow${flowCount === 1 ? '' : 's'}`
deleteMessage += ` and ${folderCount} folder${folderCount === 1 ? '' : 's'} in this folder will be moved to `
deleteMessage += parentId ? `parent flow ${getFolder(parentId).name}.` : 'the top level.'
}
BootstrapDialog.show({
title: 'Delete folder',
message: deleteMessage,
buttons: [
{
label: 'Cancel',
action: function (dialogRef) {
dialogRef.close()
callback(false)
}
},{
label: 'Delete',
action: function (dialogRef) {
dialogRef.close()
callback(true)
}
}
]
})
}
function editFlowDialog (flowId, callback) {
var message = $('.dialog_edit').clone()
buildFolderListSelector(message, 'editFolder')
$(message).find('[id=editName]').attr('value', `${getFlow(flowId).name}`)
$(message).find('[id=editFolder]').val((getFlow(flowId).folder || false).toString())
BootstrapDialog.show({
title: 'Edit and move flow',
message: message,
buttons: [
{
label: 'Cancel',
action: function (dialogRef) {
dialogRef.close()
callback(false)
}
},{
label: 'Save',
action: function (dialogRef) {
var editName = dialogRef.getModalBody().find('[id=editName]').val()
var editFolder = dialogRef.getModalBody().find('[id=editFolder]').val()
dialogRef.close()
callback(editName, editFolder)
}
}
]
})
}
function testDialog () {
var message = $('.dialog_test').clone()
$(message).find('[id=test_status]').html('xxxx')
return BootstrapDialog.show({
title: 'Testing',
message: message,
closable: false,
onshow: function (dialogRef) {
dialogRef.enableButtons(false)
dialogRef.getButton('close').spin()
},
buttons: [
{
id: 'close',
label: 'Close',
action: function (dialogRef) {
dialogRef.close()
}
}
]
})
}
function addFlowFolder () {
addFlowFolderDialog(function (newName, parent) {
var newFolderInfo = {name: newName.trim()}
if (newFolderInfo.name.length === 0) return
if (parent !== "false") newFolderInfo.parent = parent
$.ajax({
url: `${setup.protocol}://${setup.ip}/api/manager/flow/flowfolder`,
type: 'POST',
data: JSON.stringify(newFolderInfo),
success: loadFlowsAndFolders()
})
})
}
function editFlowFolder () {
selectFlowFolderDialog(function (folderId) {
if (!folderId) return
editFlowFolderDialog(folderId, async function (newName, parent) {
if (!newName || newName.trim().length === 0) return
newFolderInfo = {
name: newName.trim(),
parent: parent === "false" ? null : parent
}
await saveFlowFolder(folderId, newFolderInfo)
await loadFlowsAndFolders()
})
})
}
function addFlowFolderDialog ( callback ) {
var message = $('.dialog_folder_edit').clone()
buildFolderListSelector(message, 'folderParent')
var folderSelected = $('#folders').treeview('getSelected').find(x => true)
if (folderSelected) $(message).find('[id=folderParent]').val(folderSelected.id)
BootstrapDialog.show({
title: 'Add folder',
message: message,
buttons: [
{
label: 'Cancel',
action: function (dialogRef) {
dialogRef.close()
callback(false)
}
},{
label: 'Save',
action: function (dialogRef) {
var folderName = dialogRef.getModalBody().find('[id=folderName]').val()
var folderParent = dialogRef.getModalBody().find('[id=folderParent]').val()
dialogRef.close()
callback(folderName, folderParent)
}
}
]
})
}
function selectFlowFolderDialog ( callback ) {
var message = $('.dialog_folder_select').clone()
buildFolderListSelector(message, 'folder')