-
Notifications
You must be signed in to change notification settings - Fork 315
Expand file tree
/
Copy pathdom.ui.js
More file actions
2405 lines (2204 loc) · 78.6 KB
/
Copy pathdom.ui.js
File metadata and controls
2405 lines (2204 loc) · 78.6 KB
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
/* This file is part of Jeedom.
*
* Jeedom 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.
*
* Jeedom 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 Jeedom. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict"
/* jeeDOM UI functionnalities
*/
domUtils.showLoading = function(_timeout) {
document.getElementById('div_jeedomLoading')?.seen()
//Hanging timeout:
if (domUtils.loadingTimeout && domUtils.loadingTimeout != null) {
clearTimeout(domUtils.loadingTimeout)
domUtils.loadingTimeout = null
}
if (_timeout && typeof _timeout == 'number') {
domUtils.loadingTimeout = setTimeout(() => {
if (!document.getElementById('div_jeedomLoading')?.isHidden()) {
domUtils.hideLoading()
domUtils.DOMloading = 0
if (jeedomUtils) jeedomUtils.showAlert({ level: 'danger', message: 'Operation Timeout: Something has gone wrong!' })
}
}, _timeout * 1000)
}
}
domUtils.hideLoading = function() {
document.getElementById('div_jeedomLoading')?.unseen()
if (domUtils.loadingTimeout && domUtils.loadingTimeout != null) {
clearTimeout(domUtils.loadingTimeout)
domUtils.loadingTimeout = null
}
}
/* HTMLCollection is live, NodeList is static and iterable
*/
//HTMLCollection.prototype.forEach = Array.prototype.forEach
/* Shortcuts Functions
*/
//Hide Show as seen(), unseen() as prototype show/hide are ever declared and fired by bootstrap and jquery
Element.prototype.isVisible = function() {
return this.offsetWidth > 0 || this.offsetHeight > 0 || this.getClientRects().length > 0 || this.offsetParent != null
}
Element.prototype.isHidden = function() {
return (this.offsetParent === null)
}
Element.prototype.seen = function() {
this.removeClass('hidden')
this.style.display = ''
return this
}
NodeList.prototype.seen = function() {
for (var idx = 0; idx < this.length; idx++) {
this[idx].seen()
}
return this
}
Element.prototype.unseen = function() {
this.addClass('hidden')
return this
}
NodeList.prototype.unseen = function() {
for (var idx = 0; idx < this.length; idx++) {
this[idx].unseen()
}
return this
}
Element.prototype.toggle = function() {
if (this.isHidden()) {
this.seen()
} else {
this.unseen()
}
return this
}
NodeList.prototype.toggle = function() {
for (var idx = 0; idx < this.length; idx++) {
this[idx].toggle()
}
return this
}
Element.prototype.empty = function() {
while (this.firstChild) {
this.removeChild(this.lastChild)
}
return this
}
NodeList.prototype.empty = function() {
for (var idx = 0; idx < this.length; idx++) {
this[idx].empty()
}
return this
}
//CSS Class manipulation
Element.prototype.addClass = function(_className /*, _className... */) {
if (_className == '') return this
let args = Array.prototype.slice.call(arguments)
if (args[0].includes(' ')) args = args[0].split(' ')
this.classList.add(...args)
return this
}
NodeList.prototype.addClass = function(_className /*, _className... */) {
if (_className == '') return this
let args = Array.prototype.slice.call(arguments)
for (let idx = 0; idx < this.length; idx++) {
this[idx].addClass(...args)
}
return this
}
Element.prototype.removeClass = function(_className /*, _className... */) {
if (_className == '') {
this.classList = ''
return this
}
let args = Array.prototype.slice.call(arguments)
if (args.length > 0 && args[0].includes(' ')) args = args[0].split(' ')
this.classList.remove(...args)
return this
}
NodeList.prototype.removeClass = function(_className /*, _className... */) {
if (_className == '') return this
let args = Array.prototype.slice.call(arguments)
for (let idx = 0; idx < this.length; idx++) {
this[idx].removeClass(...args)
}
return this
}
Element.prototype.toggleClass = function(_className) {
this.classList.toggle(_className)
return this
}
NodeList.prototype.toggleClass = function() {
for (let idx = 0; idx < this.length; idx++) {
this[idx].toggleClass()
}
return this
}
Element.prototype.hasClass = function(_className) {
return this.classList.contains(_className)
}
//Misc
NodeList.prototype.last = function() {
return Array.from(this).pop() || null
}
NodeList.prototype.remove = function() {
for (let idx = 0; idx < this.length; idx++) {
this[idx].remove()
}
return this
}
Element.prototype.fade = function(_delayms, _opacity, _callback) {
let opacity = parseInt(this.style.opacity) || 0
let interval = 50,
gap = interval / _delayms,
delay = 0,
self = this
if (opacity > _opacity) gap = gap * -1
let func = function() {
let stop = false
delay += interval
opacity = opacity + gap
if (gap > 0 && opacity >= _opacity) {
opacity = _opacity
stop = true
}
if (gap < 0 && opacity <= 0) {
opacity = 0
self.unseen()
stop = true
}
self.style.opacity = opacity
if (stop) {
window.clearInterval(fading)
if (typeof _callback === 'function') {
_callback()
}
}
}
self.seen()
var fading = window.setInterval(func, interval)
return this
}
Element.prototype.insertAtCursor = function(_valueString) {
if (this.selectionStart >= 0) {
let value = this.value.substring(0, this.selectionStart) + _valueString
this.value = value + this.value.substring(this.selectionEnd, this.value.length)
this.setSelectionRange(value.length, value.length)
} else {
this.value += _valueString
}
return this
}
Element.prototype.closestAll = function(_selector) {
//var parents = this.parentNode.querySelectorAll(':scope > :nth-child(' + Array.from(this.parentNode.children).indexOf(this) + 1 +')') //Empty nodeList
var parents = []
var parent = this.closest(_selector)
while (parent != null) {
parents.push(parent)
parent = parent.parentNode.closest(_selector)
}
return parents
}
HTMLSelectElement.prototype.sortOptions = function(_text) {
if (!isset(_text)) _text = true
var optionsAr = Array.from(this.options)
optionsAr.sort(function(a, b) {
if (_text) {
return a.textContent > b.textContent ? 1 : -1
} else {
return a.value > b.value ? 1 : -1
}
})
for (let opt of optionsAr) {
this.appendChild(opt)
}
this.selectedIndex = 0
return this
}
/* Widgets
*/
domUtils.issetWidgetOptParam = function(_def, _param) {
if (_def != '#' + _param + '#') return true
return false
}
domUtils.createWidgetSlider = function(_options) {
try {
if (_options.sliderDiv.hasClass('slider') && _options.sliderDiv.noUiSlider) {
_options.sliderDiv.noUiSlider.destroy()
}
} catch (error) { }
let createOptions = {
start: [_options.state],
connect: [true, false],
step: _options.step,
range: {
'min': _options.min,
'max': _options.max
},
tooltips: _options.tooltips
}
if (isset(_options.format) && _options.format == true) {
createOptions.format = {
from: Number,
to: function(value) {
let dec = _options.step.toString().includes('.') ? (_options.step.toString().length - 1) - _options.step.toString().indexOf('.') : 0
return ((Math.round(value * (100 / _options.step)) / (100 / _options.step)).toFixed(dec) + ' ' + _options.unite).trim()
}
}
}
if (isset(_options.vertical) && _options.vertical == true) {
createOptions.orientation = 'vertical'
createOptions.direction = 'rtl'
}
try {
return noUiSlider.create(_options.sliderDiv, createOptions)
} catch (error) { }
}
/*Components
*/
document.addEventListener('DOMContentLoaded', function() {
if (document.head.querySelectorAll('script[src*="bootstrap.min.js"]').length == 0) {
document.body.addEventListener('click', function(event) {
//Close all dropdowns
document.querySelectorAll('div.dropdown.open').removeClass('open')
document.querySelectorAll('button.dropdown-toggle').forEach(_bt => _bt.parentNode.removeClass('open'))
var _target = null
//Accordions
if (_target = event.target.closest('a.accordion-toggle')) {
event.preventDefault()
let ref = _target.getAttribute('href')
if (!ref) return
let panelGroup = _target.closest('div.panel-group')
if (!panelGroup) {
var panel = document.querySelector(ref)
} else {
var panel = panelGroup.querySelector(ref)
}
if (!panel) return
var isOpen = panel.hasClass('in')
//Close all if has parent declared:
var parentRef = _target.getAttribute('data-parent')
if (parentRef && parentRef != '') {
_target.closest(parentRef)?.querySelectorAll('div.panel-collapse').removeClass('in')
}
isOpen ? panel.removeClass('in') : panel.addClass('in')
return
}
//Collapse
if (_target = event.target.closest('a[data-toggle="collapse"]')) {
_target.parentNode.querySelector('.collapse')?.toggleClass('in')
return
}
//Tabs
if (_target = event.target.closest('a[role="tab"]')) {
event.preventDefault()
let tabList = _target.closest('[role="tablist"]')
if (!tabList) return
let contentContainer = tabList.nextElementSibling
if (!contentContainer || !contentContainer.hasClass('tab-content')) return
let contentRef = _target.getAttribute('data-target')
if (!contentRef) contentRef = _target.getAttribute('href')
if (!contentRef) return
let tab = document.querySelector(contentRef)
if (!tab) return
//Update current tab level:
tabList.querySelectorAll('li[role="presentation"].active').removeClass('active')
_target.closest('li[role="presentation"]')?.addClass('active')
contentContainer.querySelectorAll('div[role="tabpanel"].active').removeClass('active')
tab.addClass('active')
//Update tabs inside current tab:
tab.querySelectorAll('[role="tablist"]').forEach(_list => {
let active = _list.querySelector('li.active')
if (active == null) {
_list.querySelector('a[role="tab"]').click()
} else {
active.querySelector('a[role="tab"]').click()
}
})
if (_target.getAttribute('data-target') == '' && event.target.getAttribute('href') == '') return
if (_target.closest('.ui-dialog-content') != null) return
if (_target.closest('.jeeDialog') != null) return
if (jeeFrontEnd.PREVIOUS_PAGE == null) {
window.history.replaceState('', '', 'index.php?' + window.location.href.split("index.php?")[1])
jeeFrontEnd.PREVIOUS_PAGE = 'index.php?' + window.location.href.split("index.php?")[1]
}
window.location.hash = _target.getAttribute('data-target') || _target.getAttribute('href')
return
}
//DropDowns
if (_target = event.target.closest('button.dropdown-toggle')) {
_target.parentNode.toggleClass('open')
return
}
})
}
})
/*Autocomplete inputs
If several inputs share same autocomplete (same options), set un id on call options so they all share same container.
Each input has their own focus/blut/keyup/keydown event (keydown prevent arrow up/down moving selection to input start/end)
As autocomplete container can have multiple reference input, it has only one click listerner, and transit some data:
._jeeComplete.reference : current focused input
._jeeComplete.references : all inputs using this container
._jeeComplete.request : the current _options.request to set current input value
*/
HTMLInputElement.prototype.jeeComplete = function(_options) {
var defaultOptions = {
ignoreKeyCodes: [8, 13, 16, 17, 18, 27, 46],
zIndex: 5000,
minLength: 1,
forceSingle: false,
id: false,
data: {
value: null,
text: null,
item: this,
content: null,
container: null,
},
_source: function(request) {
if (typeof _options.source === 'function') {
_options.data.content = _options.source(request, _options._response)
} else {
var matches = []
var term = jeedomUtils.normTextLower(request.term)
_options.sourceAr.forEach(_pair => {
if (jeedomUtils.normTextLower(_pair.value).includes(term)) {
matches.push(_pair)
}
})
_options._response(matches)
}
},
_response: function(matches) {
if (matches === false) return
var matchesAr = []
if (Array.isArray(matches) && matches.length > 0) {
if (!is_object(matches[0])) {
matches.forEach(_src => {
matchesAr.push({ text: _src, value: _src })
})
matches = matchesAr
}
} else { //invalid data
return false
}
_options.data.content = matches
_options.response(event, _options.data)
_options.setUIContent()
},
response: function(event, ui) { },
focus: function(event) { },
select: function(event, ui) { },
}
//Merge defaults and submitted options:
_options = domUtils.extend(defaultOptions, _options)
_options.sourceAr = []
if (Array.isArray(_options.source)) {
if (is_object(_options.source[0])) {
_options.sourceAr = _options.source
} else {
_options.source.forEach(_src => {
_options.sourceAr.push({ text: _src, value: _src })
})
}
}
//Let know this input has autocomple:
this._jeeComplete = _options
var createEvents = false
//Support same container for multiple inputs:
if (_options.id != false) {
_options.data.container = document.getElementById(_options.id)
}
if (_options.data.container == null) {
createEvents = true
_options.data.container = document.createElement('ul')
_options.data.container.addClass('jeeComplete').unseen()
_options.data.container._jeeComplete = { reference: _options.data.item, references: [_options.data.item] }
_options.data.container = document.body.appendChild(_options.data.container)
} else {
_options.data.container._jeeComplete.references.push(_options.data.item)
}
if (_options.id == false) {
_options.data.container.uniqueId()
_options.id = _options.data.container.getAttribute('id')
} else {
_options.data.container.setAttribute('id', _options.id)
}
_options.request = {
term: '',
start: null,
end: null
}
_options.setUIContent = function(_paires) {
if (!Array.isArray(_options.data.content) || _options.data.content.length == 0) {
_options.data.container.unseen()
return
}
_options.data.container.empty()
var newValue
_options.data.content.forEach(_pair => {
newValue = document.createElement('li')
newValue.innerHTML = '<div data-value=' + _pair.value + '>' + _pair.text + '</div>'
newValue.addClass('jeeCompleteItem')
_options.data.container.appendChild(newValue)
})
var inputPos = _options.data.item.getBoundingClientRect()
_options.data.container.style.zIndex = _options.zIndex
_options.data.container.style.top = inputPos.top + _options.data.item.offsetHeight + 'px'
_options.data.container.style.left = inputPos.left + 'px'
_options.data.container.style.width = _options.data.item.offsetWidth + 'px'
setTimeout(function() {
_options.data.container.seen()
}, 250)
}
/*Events
click = mousedown + mouseup
use mousdown to fire before focusout
*/
if (createEvents) {
_options.data.container.registerEvent('mousedown', function jeeComplete(event) {
var selectedLi = event.target.closest('li.jeeCompleteItem') || event.target
if (selectedLi == null) return
var selected = selectedLi.firstChild
var ulContainer = document.getElementById(_options.id)
//set selected value and send to registered select option:
_options.data.value = selected.getAttribute('data-value')
_options.data.text = selected.textContent
_options.data.item = ulContainer._jeeComplete.reference
var next = _options.select(event, _options.data)
if (next === false) {
return
}
_options.request = ulContainer._jeeComplete.request
if (_options.forceSingle) {
ulContainer._jeeComplete.reference.value = _options.data.text
} else {
var inputValue = ulContainer._jeeComplete.reference.value
inputValue = inputValue.substring(0, _options.request.start - 1) + inputValue.substring(_options.request.end - 1)
inputValue = inputValue.slice(0, _options.request.start - 1) + _options.data.text + inputValue.slice(_options.request.start - 1)
ulContainer._jeeComplete.reference.value = inputValue
}
_options.data.container.unseen()
setTimeout(() => {
ulContainer._jeeComplete.reference.blur()
})
}, { capture: true, buble: true })
}
this.unRegisterEvent('keydown', 'jeeComplete').registerEvent('keydown', function jeeComplete(event) {
if (event.key == 'ArrowDown' || event.key == 'ArrowUp') {
event.preventDefault()
}
})
this.unRegisterEvent('keyup', 'jeeComplete').registerEvent('keyup', function jeeComplete(event) {
/*keyCode:
Backspace 8
Enter 13
Shift 16
Control 17
Alt 18
AltGraph 18
Escape 27
ArrowLeft 37
ArrowUp 38
ArrowRight 39
ArrowDown 40
Delete 46
*/
if (event.ctrlKey || event.altKey || event.metaKey) return
if (event.key == ' ') {
_options.request.term = ''
return
}
if (_options.request.term == '') {
_options.request.start = event.target.selectionStart
_options.request.end = event.target.selectionEnd
} else if (!event.key.includes('Arrow') && event.key != 'Backspace' && event.key != 'Delete') {
_options.request.end = event.target.selectionEnd
}
//Arrow up/down select guest:
if (event.key == 'ArrowDown') {
if (_options.data.container.querySelector('li.jeeCompleteItem.active') == null) {
_options.data.container.querySelector('li.jeeCompleteItem')?.addClass('active')
} else {
var active = _options.data.container.querySelector('li.jeeCompleteItem.active')
if (active.nextElementSibling != null) {
active.removeClass('active').nextElementSibling.addClass('active')
}
}
return
}
if (event.key == 'ArrowUp') {
if (_options.data.container.querySelector('li.jeeCompleteItem.active') == null) {
_options.data.container.querySelectorAll('li.jeeCompleteItem').last()?.addClass('active')
} else {
var active = _options.data.container.querySelector('li.jeeCompleteItem.active')
if (active.previousElementSibling != null) {
active.removeClass('active').previousElementSibling.addClass('active')
}
}
return
}
if (event.key == 'Enter') {
_options.data.container.querySelector('li.jeeCompleteItem.active')?.firstChild.triggerEvent('mousedown')
_options.data.container.unseen()
setTimeout(() => {
event.target.blur()
})
return
}
if (event.key == 'Backspace') {
_options.data.container.unseen()
_options.request.term = _options.request.term.slice(0, -1)
_options.request.end--
document.getElementById(_options.id)._jeeComplete.request = _options.request
_options._source(_options.request)
return
} else if (event.key == 'Delete') {
_options.data.container.unseen()
if (event.target.selectionStart >= _options.request.start && event.target.selectionEnd <= _options.request.end) {
_options.request.end--
_options.request.term = _options.request.term.substr(_options.request.start - 1, _options.request.end - 1)
document.getElementById(_options.id)._jeeComplete.request = _options.request
_options._source(_options.request)
}
} else if (event.key == 'ArrowLeft') {
_options.data.container.unseen()
return
} else if (event.key == 'ArrowRight') {
_options.data.container.unseen()
return
} else if (_options.ignoreKeyCodes.includes(event.keyCode)) {
return
} else {
_options.request.term += event.key
_options.request.end++
}
if (event.key.length == 1 && _options.request.term.length >= _options.minLength) {
document.getElementById(_options.id)._jeeComplete.request = _options.request
_options._source(_options.request)
}
})
this.unRegisterEvent('focus', 'jeeComplete').registerEvent('focus', function jeeComplete(event) {
_options.data.item = event.target
document.getElementById(_options.id)._jeeComplete.reference = event.target
_options.focus(event)
})
this.unRegisterEvent('blur', 'jeeComplete').registerEvent('blur', function jeeComplete(event) {
event.target.triggerEvent('change')
setTimeout(function() { //Let time for click!
_options.request.term = ''
_options.data.container.unseen()
}, 250)
})
}
domUtils.syncJeeCompletes = function() {
document.querySelectorAll('ul.jeeComplete').forEach(_jee => {
var existing = []
_jee._jeeComplete.references.forEach(_ref => {
if (_ref.isConnected === true) {
existing.push(_ref)
}
})
if (existing.length > 0) {
_jee._jeeComplete.references = existing
} else {
_jee.remove()
}
})
}
/* jeeDialog()
jeeDialog.toast() Handle toast
jeeDialog.alert() / confirm() / prompt() Handle mini modals
jeeDialog.modal() handle mini modal with predefined content
jeeDialog.dialog() handle complete moveable/resiable dialogs
*/
var jeeDialog = (function() {
'use strict'
let exports = {
_description: 'Jeedom dialog function handling modals and alert messages. /core/dom/dom.ui.js'
}
/*________________TOAST
*/
exports.toast = function(_options) {
var defaultOptions = {
id: 'jeeToastContainer',
positionClass: jeedom.theme['interface::toast::position'] || 'toast-bottom-right',
title: '',
message: '',
level: 'info',
timeOut: jeedom.theme['interface::toast::duration'] * 1000 || 3000,
extendedTimeOut: jeedom.theme['interface::toast::duration'] * 1000 || 3000,
emptyBefore: false,
attachTo: false,
onclick: function(event) {
var toast = event.target.closest('.jeeToast.toast')
toast._jeeDialog.close(toast)
}
}
//Merge defaults and submitted options:
_options = domUtils.extend(defaultOptions, _options)
_options.timeOut = parseInt(_options.timeOut)
_options.extendedTimeOut = parseInt(_options.extendedTimeOut)
var toastContainer = document.getElementById('jeeToastContainer')
if (toastContainer == null) {
toastContainer = document.createElement('div')
toastContainer.setAttribute('id', _options.id)
toastContainer.addClass('jeeToastContainer', _options.positionClass)
document.body.appendChild(toastContainer)
} else {
if (_options.emptyBefore) {
toastContainer.empty()
}
}
//Main toast div:
var toast = document.createElement('div')
toast.addClass('jeeToast', 'toast', 'toast-' + _options.level)
//Child title div:
var toastTitle = document.createElement('div')
toastTitle.addClass('jeeToast', 'toastTitle')
toastTitle.innerHTML = _options.title
toast.appendChild(toastTitle)
//Child message div:
var toastMessage = document.createElement('div')
toastMessage.innerHTML = _options.message
toastMessage.addClass('jeeToast', 'toastMessage')
toast.appendChild(toastMessage)
//Child progress bar:
if (_options.timeOut > 0) {
_options.progressIntervalId = null
var toastProgress = document.createElement('div')
toastProgress.addClass('jeeToast', 'toastProgress')
toast.appendChild(toastProgress)
}
//Add to container:
toastContainer.appendChild(toast)
if (_options.attachTo) {
try {
if (typeof _options.attachTo === 'string') {
_options.attachTo = document.querySelector(_options.attachTo)
}
if (_options.attachTo != null) {
_options.attachTo.appendChild(toastContainer)
}
} catch (error) { }
} else {
if (toastContainer.parentNode != document.body) {
document.body.appendChild(toastContainer)
}
}
//Register element _jeeDialog object:
toast._jeeDialog = {
close: function(toast) {
toast.remove()
}
}
if (_options.timeOut > 0) {
toast._jeeDialog.setHideTimeout = function(_delay) {
toast._jeeDialog.hideTimeoutId = setTimeout(function() {
toast.remove()
if (toastContainer.childNodes.length == 0) {
exports.clearToasts()
}
}, _delay)
}
toast._jeeDialog.setHideTimeout(_options.timeOut)
//Progress bar:
toast._jeeDialog.progressBar = toastProgress
toast._jeeDialog.updateProgress = function(timeout) {
var percentage = ((toast._jeeDialog.progressBarHideETA - (new Date().getTime())) / parseFloat(timeout)) * 100
toast._jeeDialog.progressBar.style.width = percentage + '%'
}
toast._jeeDialog.progressBarHideETA = new Date().getTime() + parseFloat(_options.timeOut)
toast._jeeDialog.progressIntervalId = setInterval(toast._jeeDialog.updateProgress, 10, _options.timeOut)
//Events:
toast.addEventListener('mouseenter', function(event) {
clearTimeout(event.target._jeeDialog.hideTimeoutId)
clearInterval(event.target._jeeDialog.progressIntervalId)
})
toast.addEventListener('mouseleave', function(event) {
event.target._jeeDialog.setHideTimeout(_options.extendedTimeOut)
event.target._jeeDialog.progressBarHideETA = new Date().getTime() + parseFloat(_options.extendedTimeOut)
event.target._jeeDialog.progressIntervalId = setInterval(event.target._jeeDialog.updateProgress, 10, _options.extendedTimeOut)
})
} else {
toast.style.paddingBottom = '6px'
}
toast.addEventListener('click', function(event) {
_options.onclick(event)
})
return toast
}
exports.clearToasts = function() {
document.querySelectorAll('.jeeToastContainer')?.remove()
return true
}
/* Dialogs / popups common:
*/
exports.setDialogDefaults = function(_options) {
let commonDefaults = {
id: '',
autoOpen: true,
width: '30vw',
height: '20vh',
position: {
from: 'center',
to: 'center'
},
backdrop: true,
isMainDialog: false,
container: document.body,
open: function() { },
onShown: function() { },
beforeClose: function() { },
onClose: function() {
cleanBackdrop()
}
}
_options = domUtils.extend(commonDefaults, _options)
return _options
}
function setDialog(_container) {
var _params = _container._jeeDialog.options
let defaultParams = {
setTitle: true,
setContent: true,
setFooter: true,
backdrop: true,
buttons: {}
}
_params = domUtils.extend(defaultParams, _params)
setBackDrop(_params)
var template = document.createElement('template')
//Title part and close button:
if (_params.setTitle) {
if (_params.isMainDialog) {
var dialogTitle = document.createElement('div')
dialogTitle.addClass('jeeDialogTitle')
let html = '<span class="title">' + _params.title + '</span>'
html += '<div class="titleButtons">'
html += '<button class="btClose" type="button"></button>'
html += '<button class="btToggleMaximize" type="button"></button>'
//html += '<button class="btMinimize" type="button"></button>'
html += '</div>'
dialogTitle.innerHTML = html
template.appendChild(dialogTitle)
dialogTitle.querySelector('button.btClose').addEventListener('click', function(event) {
event.target.closest('div.jeeDialog')._jeeDialog.close()
cleanBackdrop()
})
dialogTitle.querySelector('button.btToggleMaximize').addEventListener('click', function(event) {
let dialog = event.target.closest('div.jeeDialog')
if (dialog.getAttribute('data-maximize') == '0') { //Not maximized
dialog.setAttribute('data-maximize', '1')
} else { //Restore
dialog.setAttribute('data-maximize', '0')
}
let onResize = dialog._jeeDialog.options.onResize
if (onResize) {
setTimeout(function() { onResize(event) })
}
})
/*
dialogTitle.querySelector('button.btMinimize').addEventListener('click', function(event) {
//Do stuff!!
})
*/
}
else {
var dialogTitle = document.createElement('div')
dialogTitle.addClass('jeeDialogTitle')
dialogTitle.innerHTML = '<span class="title">' + _params.title + '</span><button class="btClose" type="button"></button>'
template.appendChild(dialogTitle)
dialogTitle.querySelector(':scope > .btClose').addEventListener('click', function(event) {
event.target.closest('div.jeeDialog')._jeeDialog.close()
cleanBackdrop()
})
}
}
//Content part:
if (_params.setContent) {
var dialogContent = document.createElement('div')
dialogContent.addClass('jeeDialogContent')
if (_params.message != undefined && _params.message != '') {
dialogContent.innerHTML = '<div>' + _params.message + '</div>'
}
template.appendChild(dialogContent)
}
//Footer part and buttons:
if (_params.setFooter) {
var dialogFooter = document.createElement('div')
dialogFooter.addClass('jeeDialogFooter')
template.appendChild(dialogFooter)
let buttons = {}
for (let button of Object.entries(_params.buttons)) {
buttons[button[0]] = domUtils.extend(_params.defaultButtons[button[0]], button[1])
}
for (let defaultButton of Object.entries(_params.defaultButtons)) {
if (!isset(buttons[defaultButton[0]])) {
buttons[defaultButton[0]] = defaultButton[1]
}
}
for (var button of Object.entries(buttons)) {
var buttonEL = exports.addButton(button, dialogFooter)
if (buttonEL.getAttribute('data-type') === 'confirm') {
_container.addEventListener('keyup', function(event) {
if (event.key !== 'Enter') return
if (event.target.getAttribute('data-type') === 'confirm') return //Avoid double call with button focused
event.preventDefault()
event.target.closest('div.jeeDialog').querySelector('button[data-type="confirm"]')?.click()
})
}
if (buttonEL.getAttribute('data-type') === 'cancel') {
_container.addEventListener('keyup', function(event) {
if (event.key !== 'Escape') return
if (event.target.getAttribute('data-type') === 'cancel') return //Avoid double call with button focused
event.preventDefault()
event.target.closest('div.jeeDialog').querySelector('button[data-type="cancel"]')?.click()
})
}
}
}
_container.append(...template.children)
return _container
}
exports.addButton = function(_button, _footer) {
let button = document.createElement('button')
button.setAttribute('type', 'button')
button.setAttribute('data-type', _button[0])
button.innerHTML = _button[1].label
button.classList = 'button ' + _button[1].className
if (isset(_button[1].callback)) {
for (var [key, value] of Object.entries(_button[1].callback)) {
button.addEventListener(key, function(event) {
value.apply(this, [event, this.getAttribute('data-type')])
})
}
}
if (_button[0] === 'cancel') {
_footer.prepend(button)
} else {
_footer.appendChild(button)
}
return button
}
function setPosition(_dialog, _params) {
_dialog.style = null
if (_params.width) {
if (is_int(_params.width)) {
_dialog.style.width = _params.width + 'px'
} else {
_dialog.style.width = _params.width
}
if (_params.isMainDialog) {
//Horizontally centered:
let bRect = document.body.getBoundingClientRect()
let mRect = _dialog.getBoundingClientRect()
_dialog.style.left = (bRect.width / 2) - (mRect.width / 2) + "px"
}
}
if (_params.height) {
if (is_int(_params.height)) {
_dialog.style.height = _params.height + 'px'