-
Notifications
You must be signed in to change notification settings - Fork 64
/
Main.js
4193 lines (3700 loc) · 180 KB
/
Main.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
/**
* Before the page refreshes perform the innards
* @param {Event} event
*/
window.onbeforeunload = function(event)
{
if (is_abovevtt_page()) {
tabCommunicationChannel.postMessage({
msgType: 'removeObserver'
})
console.log("refreshing page, storing zoom first");
add_zoom_to_storage();
window.PeerManager.send(PeerEvent.goodbye());
}
};
/** Parses the given URL for GoogleDrive or Dropbox semantics and returns an updated URL.
* @param {String} url to parse
* @return {String} a sanitized and possibly modified url to help with loading maps */
function parse_img(url) {
let retval = url;
if (typeof retval !== "string") {
console.log("parse_img is converting", url, "to an empty string");
retval = "";
} else if (retval.trim().startsWith("data:")) {
console.warn("parse_img is removing a data url because those are not allowed");
retval = "";
} else if (retval.includes("https://drive.google.com") && !retval.match(/id=([a-zA-Z0-9_-]+)/g)) {
const parsed = 'https://drive.google.com/thumbnail?id=' + retval.split('/')[5] +'&sz=w3000';
retval = parsed;
console.log("parse_img is converting", url, "to", retval);
return retval;
}
else if (retval.startsWith("https://drive.google.com") || (retval.includes("https://drive.usercontent.google.com")) && retval.match(/id=([a-zA-Z0-9_-]+)/g)) {
const parsed = 'https://drive.google.com/thumbnail?id=' + retval.matchAll(/id=([a-zA-Z0-9_-]+)/g).next().value[1] +'&sz=w3000';
retval = parsed;
console.log("parse_img is converting", url, "to", retval);
return retval;
}
else if(retval.startsWith("https://www.googleapis.com/drive/v3/files/")){ // fix due to 1.5/1.6 beta
const fileid = retval.split('files/')[1].split('?')[0];
const parsed = 'https://drive.google.com/thumbnail?id=' + fileid +'&sz=w3000';
retval = parsed;
return retval;
}
else if(retval.includes("dropbox.com")){
const splitUrl = url.split('dropbox.com');
const parsed = `https://dl.dropboxusercontent.com${splitUrl[splitUrl.length-1]}`
console.log("parse_img is converting", url, "to", parsed);
retval = parsed;
}
else if(retval.includes("https://1drv.ms/"))
{
if(retval.split('/')[4].length == 1){
retval = retval;
}
else{
retval = "https://api.onedrive.com/v1.0/shares/u!" + btoa(url) + "/root/content";
}
}
if(retval.includes("discordapp.com")){
retval = update_old_discord_link(retval)
}
return retval;
}
function update_old_discord_link(link){
if(link == 'https://cdn.discordapp.com/attachments/1083353621778923581/1110550133134852206/lightbulb.png'){
link = 'https://www.googleapis.com/drive/v3/files/1_QnkvmGct2dzeu-pBO9ofT-828pWvCcn?alt=media&key=AIzaSyBcA_C2gXjTueKJY2iPbQbDvkZWrTzvs5I'
}
else if(link == "https://cdn.discordapp.com/attachments/1083353621778923581/1083353624891105290/star.png"){
link = 'https://drive.google.com/uc?id=1F868fVhQnzFALTcnEIXUDeAl3UKZccKA';
}
else if(link == "https://cdn.discordapp.com/attachments/1083353621778923581/1083353624652038215/skull.png"){
link = "https://drive.google.com/uc?id=1of0nmVMh8rnt9pz6iri9gtq-mCQmgCWA"
}
else if(link == "https://cdn.discordapp.com/attachments/1083353621778923581/1083353625113399376/mappin.png"){
link = "https://drive.google.com/uc?id=1excaNtaLfn_Hj5EHuH-h8iimpzC36i0M"
}
else if(link == "https://cdn.discordapp.com/attachments/1083353621778923581/1148091041589756005/flame1.gif"){
link = "https://drive.google.com/uc?id=1eWHXQsHloLuocYOuHnvvd0zymZQMH7sm"
}
return link;
}
/**
* Waits for a global variable to be set.
* Then triggers the callback function.
* @param {String} name a global variable name
* @param {Function} callback
*/
function whenAvailable(name, callback) {
let interval = 10; // ms
window.setTimeout(function() {
if (window[name]) {
callback(window[name]);
} else {
whenAvailable(name, callback);
}
}, interval);
}
/**
* Returns a random color in hex format.
* @returns String
*/
function getRandomColorOLD() {
let letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
/**
* Generates a random uuid string.
* @returns String
*/
function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/**
* Generates a random integer number between min and max.
* @param {Number} min lower boundary (including)
* @param {Number} max upper boundary (excluding)
* @returns Number
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
/**
* Constrains a given number between a minimum and maximum value.
* @param {Number} Number a given value
* @param {Number} min lower boundary (including)
* @param {Number} max upper boundary (including)
* @returns Number
*/
function clamp (number, min, max) {
return Math.min(Math.max(number, min), max)
}
/**
* Extracts a YouTube VideoID from a given URL.
* Returns false if no ID vas found.
* @param {String} url Youtube video URL
* @returns String | false
*/
function youtube_parser(url) {
let regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
let match = url.match(regExp);
return (match && match[7].length == 11) ? match[7] : false;
}
/**
* Check is a given URL is valid
* @param {string} value any URL
* @returns boolean
*/
function validateUrl(value) {
return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value);
}
const MAX_ZOOM = 5
const MIN_ZOOM = 0.001
const debounce_scroll_event = mydebounce(function(){
setTimeout(function(){
$(window).off('scroll.projectorMode').on("scroll.projectorMode", projector_scroll_event);
}, 200)
}, 200)
/**
* Changes the zoom level.
* @param {Number} newZoom new zoom value
* @param {Number} x zoom center horizontal
* @param {Number} y zoom center vertical
*/
function change_zoom(newZoom, x, y, reset = false) {
console.group("change_zoom")
console.log("zoom", newZoom, x , y)
let zoomCenterX = x || $(window).width() / 2
let zoomCenterY = y || $(window).height() / 2
// window.VTTMargin is the size of the black area to the left and top of the map
let centerX = Math.round((($(window).scrollLeft() + zoomCenterX) - window.VTTMargin) * (1.0 / window.ZOOM));
let centerY = Math.round((($(window).scrollTop() + zoomCenterY) - window.VTTMargin) * (1.0 / window.ZOOM));
window.ZOOM = newZoom;
let pageX = Math.round(centerX * window.ZOOM - zoomCenterX) + window.VTTMargin;
let pageY = Math.round(centerY * window.ZOOM - zoomCenterY) + window.VTTMargin;
if($('#projector_zoom_lock.enabled > [class*="is-active"]').length>0 && window.DM)
$(window).off('scroll.projectorMode')
if(reset != true){
$(window).scrollLeft(pageX);
$(window).scrollTop(pageY);
}
$('#VTTWRAPPER').css({
"--window-zoom": window.ZOOM,
"--font-size-zoom": Math.max(12 * Math.max((3 - window.ZOOM), 0), 8.5) + "px"
})
set_default_vttwrapper_size();
if(reset == true){
$("#scene_map")[0].scrollIntoView({
behavior: 'auto',
block: 'center',
inline: 'center'
});
if($('#hide_rightpanel').hasClass('point-right') && $('.ct-sidebar.ct-sidebar--hidden').length == 0)
$(window).scrollLeft(window.scrollX + 170); // 170 half of game log
}
$(".peerCursorPosition").css("transform", "scale(" + 1/window.ZOOM + ")");
if($('#projector_zoom_lock.enabled > [class*="is-active"]').length>0 && window.DM)
debounce_scroll_event()
console.groupEnd()
}
/**
* Adds the current zoom level and scrollLeft, scrollTop offsets to local storage along with the title of the scene.
*/
function add_zoom_to_storage() {
console.group("add_zoom_to_storage");
console.log("storing zoom");
if(window.ZOOM !== get_reset_zoom()) {
const zooms = JSON.parse(localStorage.getItem('zoom')) || [];
const zoomIndex = zooms.findIndex(zoom => zoom.title === window.CURRENT_SCENE_DATA.title);
const centerView = center_of_view();
const sidebarSize = ($('#hide_rightpanel.point-right').length>0 ? 340 : 0);
if (zoomIndex !== -1) {
zooms[zoomIndex].zoom = window.ZOOM;
zooms[zoomIndex].leftOffset = window.scrollX + window.innerWidth/2 - sidebarSize/2;
zooms[zoomIndex].topOffset = window.scrollY + window.innerHeight/2;
}
else{
// zoom doesn't exist
zooms.push({
"title": window.CURRENT_SCENE_DATA.title,
"zoom":window.ZOOM,
"leftOffset": window.scrollX + window.innerWidth/2 - sidebarSize/2,
"topOffset": window.scrollY + window.innerHeight/2
});
}
localStorage.setItem('zoom', JSON.stringify(zooms));
} else {console.log("zoom has not changed, skipping storage")}
console.groupEnd("add_zoom_to_storage")
}
/**
* Sets default values for VTTWRAPPER and black_layer based off zoom.
*/
function set_default_vttwrapper_size() {
$("#VTTWRAPPER").width($("#scene_map").width() * window.CURRENT_SCENE_DATA.scale_factor * window.ZOOM + 1400);
$("#VTTWRAPPER").height($("#scene_map").height() * window.CURRENT_SCENE_DATA.scale_factor * window.ZOOM + 1400);
$("#black_layer").width(($("#scene_map").width()) * window.CURRENT_SCENE_DATA.scale_factor * window.ZOOM + 2000 + window.VTTMargin );
$("#black_layer").height(($("#scene_map").height()) * window.CURRENT_SCENE_DATA.scale_factor * window.ZOOM + 2000 + window.VTTMargin );
}
/**
* Removes the zoom for the current scene from local storage, applied when user click "fit zoom" button.
*/
function remove_zoom_from_storage() {
const zooms = JSON.parse(localStorage.getItem('zoom')) || [];
const zoomIndex = zooms.findIndex(zoom => zoom.title === window.CURRENT_SCENE_DATA.title);
if (zoomIndex !== -1) {
console.log("removing zoom from storage", zooms[zoomIndex]);
zooms.splice(zoomIndex, 1);
}
localStorage.setItem('zoom', JSON.stringify(zooms));
}
/**
* Retrieves the zoom and scroll position from local storage using the scene title, will call reset_zoom if not found.
*/
function apply_zoom_from_storage() {
console.group("apply_zoom_from_storage");
const sidebarSize = ($('#hide_rightpanel.point-right').length>0 ? 340 : 0);
let initial_x = isNaN(parseInt(window.CURRENT_SCENE_DATA.initial_x)) ? undefined : window.CURRENT_SCENE_DATA.initial_x - window.innerWidth/2 + sidebarSize/2;
let initial_y = isNaN(parseInt(window.CURRENT_SCENE_DATA.initial_y)) ? undefined : window.CURRENT_SCENE_DATA.initial_y - window.innerHeight/2;
let initial_zoom = isNaN(parseInt(window.CURRENT_SCENE_DATA.initial_zoom)) ? undefined : window.CURRENT_SCENE_DATA.initial_zoom;
if(initial_zoom != undefined){
change_zoom(initial_zoom)
if(initial_x != undefined && initial_y != undefined)
window.scrollTo(initial_x, initial_y)
}
else{
const zoomState = localStorage.getItem("zoom");
if (zoomState != null) {
const zooms = JSON.parse(zoomState);
const zoomIndex = zooms.findIndex(zoom => zoom.title === window.CURRENT_SCENE_DATA.title);
if(zoomIndex !== -1) {
console.log("restoring zoom level", zooms[zoomIndex]);
change_zoom(zooms[zoomIndex].zoom)
if(initial_x != undefined && initial_y != undefined)
window.scrollTo(initial_x, initial_y)
else
window.scrollTo(zooms[zoomIndex].leftOffset - window.innerWidth/2 + sidebarSize/2, zooms[zoomIndex].topOffset - window.innerHeight/2)
}
else{
// Zooms in storage but not for this scene
console.log("scene does not have a zoom stored")
reset_zoom()
if(initial_x != undefined && initial_y != undefined)
window.scrollTo(initial_x, initial_y)
}
}
else{
// no zooms in storage
console.log("no zooms in storage")
reset_zoom()
if(initial_x != undefined && initial_y != undefined)
window.scrollTo(initial_x, initial_y)
}
}
console.groupEnd()
}
/**
* Decreases zoom level by 10%.
* Prevents zooming below MIN_ZOOM.
*/
function decrease_zoom() {
if (window.ZOOM > MIN_ZOOM) {
change_zoom(window.ZOOM * 0.9);
}
}
/**
* Gets the zoom values that will fit the map to the viewport
* @return {Number}
*/
function get_reset_zoom() {
const sidebar_open = ($('#hide_rightpanel').hasClass('point-right') && $('.ct-sidebar.ct-sidebar--hidden').length == 0) ? 340 : 0;
const wH = $(window).height();
const mH = $("#scene_map").height()*window.CURRENT_SCENE_DATA.scale_factor;
const wW = $(window).width()-sidebar_open;
const mW = $("#scene_map").width()*window.CURRENT_SCENE_DATA.scale_factor;
console.log(wH, mH, wW, mW);
return Math.min((wH / mH), (wW / mW));
}
/**
* Entrypoint for user clicking the fit map button.
* Will remove local storage state as by default this function is called when no state is found.
*/
function reset_zoom() {
console.group("reset_zoom");
console.log("zooming on centre of map");
// change_zoom is great for mouse zooming, but tricky when just hitting the centre of the map
// so don't give it any x/y and just use the scrollIntoView center instead
change_zoom(get_reset_zoom(), undefined, undefined, true);
// Don't store any zoom for this scene as we default to map fit on load
remove_zoom_from_storage();
console.groupEnd();
}
/**
* Increases zoom level by 10%.
*/
function increase_zoom() {
change_zoom(window.ZOOM * 1.10);
}
/**
* Extracts the character ID from a given URL.
* Returns -1 if no ID is found.
* @param {String} sheet_url a DDB character URL
* @returns string | -1
*/
function getPlayerIDFromSheet(sheet_url) {
let playerID = -1;
if(sheet_url) {
let urlSplit = sheet_url.split("/");
if(urlSplit.length > 0) {
playerID = urlSplit[urlSplit.length - 1].split('?')[0];
}
}
return playerID;
}
window.YTTIMEOUT = null;
/**
* Shows an error message when a map_load_error event occurs.
* @param {Event} e event object
*/
function map_load_error_cb(e) {
console.log(e);
let src = e.currentTarget.getAttribute("src");
$('#loadingStyles').remove();
console.error("map_load_error_cb src", src, e);
if (typeof src === "string") {
let specificMessage = `Please make sure the image is accessible to anyone on the internet.`;
if (src.includes("drive.google") || window.CURRENT_SCENE_DATA.map.includes("drive.google")) {
showGoogleDriveWarning();
}
else if (confirm(`Map could not be loaded!\n${specificMessage}\nYou may also need to disable ad blockers.\nWould you like to try loading the image in a separate tab to verify that it's accessible? If you are currently logged in to google, you will need to log out or open the image in a different browser or an incognito window to truly test it.`)) {
if (window.DM || confirm(`SPOILER ALERT!!!\nIf you click OK, you might see the entire map without fog of war. However, the map isn't loading at all so you will probably see a broken link. Are you sure you want to test this image?`)) {
window.open(window.CURRENT_SCENE_DATA.map, '_blank');
}
}
}
}
/**
* The first time we load, an overlay is shown to mask all the window modifications we do.
* This removes it. See `Load.js` for the injection of the overlay.
*/
function remove_loading_overlay() {
console.debug("remove_loading_overlay")
$("#loading_overlay").animate({ "opacity": 0 }, 1000, function() {
$("#loading_overlay").hide();
});
}
/**
* Creates a new map for DM & Players.
* Both DM and players use this when you're in the cloud.
* @param {String} url the URL to the map
* @param {Boolean} is_video flag for animated maps
* @param {Number} width of the map
* @param {Number} height of the map
* @param {Function} callback trigged after map is loaded
*/
async function load_scenemap(url, is_video = false, width = null, height = null, UVTTFile = false, callback = null) {
clearInterval(window.YTINTERVAL);
$("#scene_map_container").toggleClass('map-loading', true);
$("[id='scene_map']").remove();
if (window.YTTIMEOUT != null) {
clearTimeout(window.YTTIMEOUT);
window.YTTIMEOUT = null;
}
$("#youtube_controls_button").css('visibility', 'hidden');
console.log("is video? " + is_video);
if (url.includes("youtube.com") || url.includes("youtu.be")) {
$("#youtube_controls_button").css('visibility', '');
$("#scene_map_container").toggleClass('video', true);
if (width == null) {
width = 1920;
height = 1080;
}
let newmap = $('<div style="width:' + width + 'px;height:' + height + 'px;position:absolute;top:0;left:0;z-index:10" id="scene_map" />');
$("#map_items").append(newmap);
videoid = youtube_parser(url);
window.YTPLAYER = new YT.Player('scene_map', {
width: width,
height: height,
videoId: videoid,
playerVars: { 'autoplay': 0, 'controls': 1, 'rel': 0 },
events: {
'onStateChange': function(event) {
if (event.data == 0) window.YTPLAYER.seekTo(0);
},
'onReady': function(e) {
let ytvolume=window.MIXER?.state()?.animatedMap?.volume != undefined ? window.MIXER?.state()?.animatedMap?.volume : $("#youtube_volume").val();
if(ytvolume)
e.target.setVolume(ytvolume);
else
e.target.setVolume(25);
e.target.playVideo();
const loopTime = window.YTPLAYER.playerInfo.duration - 0.15;
window.YTINTERVAL = setInterval(function (){
const current_time = window.YTPLAYER.getCurrentTime();
if (current_time > loopTime) {
window.YTPLAYER.seekTo(0);
window.YTPLAYER.playVideo();
}
}, 10);
}
}
});
callback();
$("#scene_map_container").toggleClass('map-loading', false);
}
else if (is_video === "0" || !is_video) {
$("#scene_map_container").toggleClass('video', false);
let newmap;
if(UVTTFile && width != null){
newmap = $(`<img id='scene_map' src='${url}' style='position:absolute;top:0;left:0;z-index:10'>`);
newmap.width(width);
newmap.height(height);
}
else{
url = await getGoogleDriveAPILink(url)
newmap = $(`<img id='scene_map' src='${url}' style='position:absolute;top:0;left:0;z-index:10'>`);
}
newmap.on("error", map_load_error_cb);
newmap.on("load", () => {
$("#scene_map_container").toggleClass('map-loading', false);
});
if (callback != null) {
newmap.on("load", callback);
}
$("#map_items").append(newmap);
}
else {
console.log("LOAD MAP " + width + " " + height);
$("#scene_map_container").toggleClass('video', true);
let newmapSize = 'width: 100vw; height: 100vh;';
if (width != null) {
newmapSize = 'width: ' + width + 'px; height: ' + height + 'px;';
}
let videoVolume = window.MIXER?.state()?.animatedMap?.volume != undefined ? window.MIXER?.state()?.animatedMap?.volume : $("#youtube_volume").val() != undefined ? $("#youtube_volume").val() : 0.25;
if(window.DM){
videoVolume = videoVolume/100 * $("#master-volume input").val();
}
else{
videoVolume = videoVolume * $("#master-volume input").val()
}
if(url.includes('google')){
if (url.startsWith("https://drive.google.com") && url.indexOf("uc?id=") < 0 && url.indexOf("thumbnail?id=") < 0 ) {
const parsed = 'https://drive.google.com/uc?id=' + url.split('/')[5];
const fileid = parsed.split('=')[1];
url = `https://www.googleapis.com/drive/v3/files/${fileid}?alt=media&key=AIzaSyBcA_C2gXjTueKJY2iPbQbDvkZWrTzvs5I`;
}
else if (url.startsWith("https://drive.google.com") && url.indexOf("uc?id=") > -1) {
const fileid = url.split('=')[1];
url = `https://www.googleapis.com/drive/v3/files/${fileid}?alt=media&key=AIzaSyBcA_C2gXjTueKJY2iPbQbDvkZWrTzvs5I`;
}
else if (url.startsWith("https://drive.google.com") && url.indexOf("thumbnail?id=") > -1) {
const fileid = url.split('=')[1].split('&')[0];
url = `https://www.googleapis.com/drive/v3/files/${fileid}?alt=media&key=AIzaSyBcA_C2gXjTueKJY2iPbQbDvkZWrTzvs5I`;
}
}
else if(url.includes('onedrive')){
url = url.replace('embed?', 'download?');
}
else if(url.includes("https://1drv.ms/"))
{
url = "https://api.onedrive.com/v1.0/shares/u!" + btoa(url) + "/root/content";
}
let newmap = $(`<video style="${newmapSize} position: absolute; top: 0; left: 0;z-index:10" playsinline autoplay loop data-volume='0.25' onloadstart="this.volume=${videoVolume/100}" id="scene_map" src="${url}" />`);
newmap.off("loadeddata").one("loadeddata", callback);
newmap.off("error").on("error", map_load_error_cb);
if (width == null) {
newmap.off("loadedmetadata").on("loadedmetadata", function (e) {
console.log("video width:", this.videoWidth);
console.log("video height:", this.videoHeight);
$('#scene_map').width(this.videoWidth);
$('#scene_map').height(this.videoHeight);
$("#scene_map_container").toggleClass('map-loading', false);
});
}
else{
$("#scene_map_container").toggleClass('map-loading', false);
}
$("#map_items").append(newmap);
}
$('#scene_map ~ #scene_map').remove()
}
/**
* Displays a marker at the given point in the given color.
* Scrolls to marker if dontscroll flag is not set
* @param {Object} data see Main.js: init_ui -> tempOverlay.dblclick function for details
* @param {Boolean} dontscroll prevent scrolling
*/
function set_pointer(data, dontscroll = false) {
let marker = $("<div></div>");
marker.css({
"position": "absolute",
"top": data.y - 50,
"left": data.x - 50,
"width": "100px",
"height": "100px",
"z-index": "30",
"border-radius": "50%",
"opacity": "1.0",
"border-width": "18px",
"border-style": "double",
"border-color": data.color,
"transform": `scale(${(1 / window.ZOOM)})`,
"--ping-scale":`${(1 / window.ZOOM)}`,
"animation": 'pingAnimate linear 3s infinite',
"filter": "drop-shadow(1px 1px 0px #000)"
});
$("#tokens").append(marker);
setTimeout(function(){marker.fadeOut(1000)}, 2000);
setTimeout(function(){marker.remove()}, 3000);
// Calculate pageX and pageY and scroll there!
if(!dontscroll){
let pageX = Math.round(data.x * window.ZOOM - ($(window).width() / 2));
let pageY = Math.round(data.y * window.ZOOM - ($(window).height() / 2));
let sidebarSize = ($('#hide_rightpanel.point-right').length>0 ? 340 : 0);
$("html,body").animate({
scrollTop: pageY + window.VTTMargin,
scrollLeft: pageX + window.VTTMargin + sidebarSize/2,
}, 500);
}
}
/**
* Add .notification and .highlight-gamelog classes to #switch_gamelog.
*/
function notify_gamelog() {
if (window.color) {
$("#switch_gamelog").css("--player-border-color", window.color);
}
if (!$("#switch_gamelog").hasClass("selected-tab")) {
if ($("#switch_gamelog").hasClass("notification")) {
$("#switch_gamelog").removeClass("notification");
setTimeout(function() {
$("#switch_gamelog").addClass("notification");
}, 400);
} else {
$("#switch_gamelog").addClass("notification");
}
}
if ($(".GameLog_GameLog__2z_HZ").scrollTop() < 0) {
$(".GameLog_GameLog__2z_HZ").addClass("highlight-gamelog");
}
}
/**
* Add .notification and .highlight-gamelog classes to #switch_gamelog.
* @param {string} color - a valid css color
*/
function flash_tokens_tab(color) {
const tokensTab = window.DM ? $("#switch_tokens") : $("#switch_characters");
// unlike the gamelog, we don't want this to stay highlighted. Just flash it, and be done
tokensTab.css("--player-border-color", color);
tokensTab.addClass("notification");
setTimeout(function() {
tokensTab.removeClass("notification");
}, 800);
}
function select_next_tab() {
const currentlySelected = $(".sidebar__controls .selected-tab");
if (currentlySelected.attr("id") === "switch_settings") {
return; // already as far right as we can go
}
const nextTab = currentlySelected.next();
if (nextTab.length === 1) {
change_sidbar_tab(nextTab);
}
}
function select_prev_tab() {
const currentlySelected = $(".sidebar__controls .selected-tab");
if (currentlySelected.attr("id") === "switch_gamelog") {
return; // already as far left as we can go
}
const previousTab = currentlySelected.prev();
if (previousTab.length === 1) {
change_sidbar_tab(previousTab);
}
}
/**
* Triggers sidebar tab change based on given event.
* @param {event} e click event
*/
function switch_control(e) {
change_sidbar_tab($(e.currentTarget));
}
/**
* Removes 'active' classes from active sidebar tab
*/
function deselect_all_sidebar_tabs() {
$(".selected-tab .sidebar-tab-image").removeClass("ct-primary-box__tab--extras ddbc-tab-list__nav-item ddbc-tab-list__nav-item--is-active");
$(".selected-tab").removeClass("selected-tab");
}
/**
* Changes the active tab in the sidebar.
* @param {DOMObject} clickedTab selected DOM object.
* @param {Boolean} isCharacterSheetInfo switch back to gamelog if false
*/
function change_sidbar_tab(clickedTab, isCharacterSheetInfo = false) {
deselect_all_sidebar_tabs();
clickedTab.addClass("selected-tab").removeClass("notification");
clickedTab.find(".sidebar-tab-image").addClass("ct-primary-box__tab--extras ddbc-tab-list__nav-item ddbc-tab-list__nav-item--is-active");
close_sidebar_modal();
$(clickedTab.attr("data-target")).addClass('selected-tab');
disable_draggable_change_folder();
// switch back to gamelog if they change tabs
if (!isCharacterSheetInfo) {
// This only happens when `is_character_page() == true` and the user clicked the gamelog tab.
// This is an important distinction, because we switch to the gamelog tab when the user clicks info on their character sheet that causes details to be displayed instead of the gamelog.
// Since the user clicked the tab, we need to show the gamelog instead of any detail info that was previously shown.
let gameLogButton = $("div.ct-character-header__group--game-log.ct-character-header__group--game-log-last, [data-original-title='Game Log'] button")
if(gameLogButton.length == 0){
gameLogButton = $(`[d='M243.9 7.7c-12.4-7-27.6-6.9-39.9 .3L19.8 115.6C7.5 122.8 0 135.9 0 150.1V366.6c0 14.5 7.8 27.8 20.5 34.9l184 103c12.1 6.8 26.9 6.8 39.1 0l184-103c12.6-7.1 20.5-20.4 20.5-34.9V146.8c0-14.4-7.7-27.7-20.3-34.8L243.9 7.7zM71.8 140.8L224.2 51.7l152 86.2L223.8 228.2l-152-87.4zM48 182.4l152 87.4V447.1L48 361.9V182.4zM248 447.1V269.7l152-90.1V361.9L248 447.1z']`).closest('[role="button"]'); // this is a fall back to look for the gamelog svg icon and look for it's button.
}
gameLogButton.click()
}
}
/**
* Posts a message to the chat when a player connected to the server.
*/
function report_connection() {
let msgdata = {
player: window.PLAYER_NAME,
img: window.PLAYER_IMG,
text: PLAYER_NAME + " has connected to the server!",
};
window.MB.inject_chat(msgdata);
}
function use_iframes_for_monsters() { // this is just in case we find a bug and need to give users an easy way to fall back to iframes
close_sidebar_modal();
$("#resizeDragMon").remove();
window.fetchMonsterStatBlocks = true;
localStorage.setItem("use_iframes_for_monsters", "true");
}
function stop_using_iframes_for_monsters() { // this is just in case we find a bug and need to give users an easy way to fall back to iframes
close_sidebar_modal();
$("#resizeDragMon").remove();
window.fetchMonsterStatBlocks = false;
localStorage.setItem("use_iframes_for_monsters", "false");
}
function should_use_iframes_for_monsters() {
if (window.fetchMonsterStatBlocks === undefined) {
window.fetchMonsterStatBlocks = localStorage.getItem("use_iframes_for_monsters") === "true";
}
return window.fetchMonsterStatBlocks;
}
/**
* Loads and displays a monster stats block
* @param {Number} monsterId given monster ID
* @param {UUID} tokenId selected token ID
*/
function load_monster_stat(monsterId, tokenId, customStatBlock=undefined) {
if(customStatBlock){
let container = build_draggable_monster_window();
display_stat_block_in_container(customStatBlock, container, tokenId, customStatBlock);
$(".sidebar-panel-loading-indicator").hide();
return;
}
if(window.all_token_objects[tokenId].options.monster == 'open5e'){
let container = build_draggable_monster_window();
build_and_display_stat_block_with_id(window.all_token_objects[tokenId].options.stat, container, tokenId, function () {
$(".sidebar-panel-loading-indicator").hide();
}, true);
return;
}
if (should_use_iframes_for_monsters()) {
load_monster_stat_iframe(monsterId, tokenId);
return;
}
let container = build_draggable_monster_window();
build_and_display_stat_block_with_id(monsterId, container, tokenId, function () {
$(".sidebar-panel-loading-indicator").hide();
});
}
function load_monster_stat_iframe(monsterId, tokenId) {
console.group("load_monster_stat")
// monster block exists
if($("#monster_block").length > 0){
// same monster, update trackers and return early
if ($("#monster_block").attr("data-monid") == monsterId){
const token = window.TOKEN_OBJECTS[tokenId];
// rebuild any ability trackers specific to this token
rebuild_ability_trackers($("#monster_block").contents(), tokenId)
$("#resizeDragMon").removeClass("hideMon");
console.groupEnd()
return
}
// clean up old monster block before removing
$("#monster_block").attr("id","old_monster_block")
$("#old_monster_block").hide()
$(".sidebar-panel-loading-indicator").show()
$("#old_monster_block").off("load")
$("#old_monster_block").attr("src", null)
$('#old_monster_block').remove();
$("#resizeDragMon").removeClass("hideMon");
}
// create a monster block wrapper element
if (! $("#resizeDragMon").length) {
const monStatBlockContainer = $(`<div id='resizeDragMon' style="display:none; left:300px"></div>`);
$("body").append(monStatBlockContainer)
monStatBlockContainer.append(build_combat_tracker_loading_indicator())
const loadingIndicator = monStatBlockContainer.find(".sidebar-panel-loading-indicator")
loadingIndicator.css("top", "25px")
loadingIndicator.css("height", "calc(100% - 25px)")
monStatBlockContainer.show("slow")
monStatBlockContainer.resize(function(e) {
e.stopPropagation();
});
}
const iframe = $(`<iframe id=monster_block data-monid=${monsterId}>`);
iframe.css("display", "none");
$("#resizeDragMon").append(iframe);
window.StatHandler.getStat(monsterId, function(stats) {
iframe.on("load", function(event) {
console.log('carico mostro');
$(event.target).contents().find("body[class*='marketplace']").replaceWith($("<div id='noAccessToContent' style='height: 100%;text-align: center;width: 100%;padding: 10px;font-weight: bold;color: #944;'>You do not have access to this content on DndBeyond.</div>"));
$(event.target).contents().find("#mega-menu-target").remove();
$(event.target).contents().find(".site-bar").remove();
$(event.target).contents().find(".page-header").remove();
$(event.target).contents().find(".homebrew-comments").remove();
$(event.target).contents().find("header").hide();
$(event.target).contents().find("#site-main").css("padding", "0px");
$(event.target).contents().find("#footer").remove();
const img = $(event.target).contents().find(".detail-content").find(".image");
const statblock = $(event.target).contents().find(".mon-stat-block");
if (img.length == 1) {
img.insertAfter(statblock);
const sendToGamelog = $("<button>Send IMG To Gamelog</button>");
img.css("text-align", "center");
img.append(sendToGamelog);
const imgsrc = img.find("a").attr('href');
sendToGamelog.click(function() {
const msgdata = {
player: window.PLAYER_NAME,
img: window.PLAYER_IMG,
text: "<img width='100%' class='magnify' href='" + imgsrc + "' src='" + imgsrc + "'>",
};
window.MB.inject_chat(msgdata);
});
}
scan_monster($(event.target).contents(), stats, tokenId);
$(event.target).contents().find("a").attr("target", "_blank");
$(".sidebar-panel-loading-indicator").hide()
$("#monster_block").fadeIn("slow")
console.groupEnd()
});
iframe.attr('src', stats.data.url)
})
$(iframe).on("load", function(event){
const tooltipCSS = $(`<style>.hovering-tooltip{ display: block !important; left: 5px !important; right: 5px !important; pointer-events: none !important; min-width: calc(100% - 10px);} </style>`);
$("head", $("#monster_block").contents()).append(tooltipCSS);
$("body", $("#monster_block").contents()).css('width', 'calc(100% + 670px)');
$("#site", $("#monster_block").contents()).css('padding-right', '670px');
$(".tooltip-hover", $("#monster_block").contents()).on("mouseover mousemove", function(){
$("#db-tooltip-container .body .tooltip, #db-tooltip-container", $("#monster_block").contents()).toggleClass("hovering-tooltip", true);
});
$(".tooltip-hover", $("#monster_block").contents()).on("mouseout", function(){
$("#db-tooltip-container .body .tooltip, #db-tooltip-container", $("#monster_block").contents()).toggleClass("hovering-tooltip", false);
});
// if the user right-clicks a tooltip, send it to the gamelog
$(event.target).contents().off("contextmenu").on("contextmenu", ".tooltip-hover", function(clickEvent) {
clickEvent.preventDefault();
clickEvent.stopPropagation();
const toPost = $("#db-tooltip-container", $("#monster_block").contents()).clone();
toPost.find(".waterdeep-tooltip").attr("style", "display:block!important");
toPost.find(".tooltip").attr("style", "display:block!important");
toPost.css({
"top": "0px",
"left": "0px",
"position": "relative"
});
toPost.find(".tooltip").css({
"max-height": "1000px",
"min-width": "0",
"max-width": "100%",
"width": "100%"
});
toPost.find(".tooltip-header").css({
"min-height": "70px",
"height": "auto"
});
toPost.find(".tooltip-body").css({
"max-height": "1000px"
});
window.MB.inject_chat({
player: window.PLAYER_NAME,
img: window.PLAYER_IMG,
text: toPost.html()
});
});
});
/*Set draggable and resizeable on monster sheets for players. Allow dragging and resizing through iFrames by covering them to avoid mouse interaction*/
if($("#monster_close_title_button").length==0){
const monster_close_title_button=$('<div id="monster_close_title_button"><svg class="" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><g transform="rotate(-45 50 50)"><rect></rect></g><g transform="rotate(45 50 50)"><rect></rect></g></svg></div>')
$("#resizeDragMon").append(monster_close_title_button);
monster_close_title_button.click(function() {
close_player_monster_stat_block()
});
}
if($("#resizeDragMon .popout-button").length==0){
const monster_popout_button=$('<div class="popout-button"><svg xmlns="http://www.w3.org/2000/svg" height="18px" viewBox="0 0 24 24" width="18px" fill="#000000"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M18 19H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h5c.55 0 1-.45 1-1s-.45-1-1-1H5c-1.11 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-6c0-.55-.45-1-1-1s-1 .45-1 1v5c0 .55-.45 1-1 1zM14 4c0 .55.45 1 1 1h2.59l-9.13 9.13c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L19 6.41V9c0 .55.45 1 1 1s1-.45 1-1V4c0-.55-.45-1-1-1h-5c-.55 0-1 .45-1 1z"/></svg></div>')
$("#resizeDragMon").append(monster_popout_button);
monster_popout_button.click(function() {
let name = $("#resizeDragMon .avtt-stat-block-container .mon-stat-block__name-link").text();
popoutWindow(name, $("#resizeDragMon .avtt-stat-block-container"));
name = name.replace(/(\r\n|\n|\r)/gm, "").trim();
$(window.childWindows[name].document).find(".avtt-roll-button").on("contextmenu", function (contextmenuEvent) {
$(window.childWindows[name].document).find("body").append($("div[role='presentation']").clone(true, true));
let popoutContext = $(window.childWindows[name].document).find(".dcm-container");
let maxLeft = window.childWindows[name].innerWidth - popoutContext.width();
let maxTop = window.childWindows[name].innerHeight - popoutContext.height();
if(parseInt(popoutContext.css("left")) > maxLeft){
popoutContext.css("left", maxLeft)
}
if(parseInt(popoutContext.css("top")) > maxTop){
popoutContext.css("top", maxTop)
}
$(window.childWindows[name].document).find("div[role='presentation']").on("click", function (clickEvent) {
$(window.childWindows[name].document).find("div[role='presentation']").remove();
});
$(".dcm-backdrop").remove();
});
monster_close_title_button.click();
});
}
$("#resizeDragMon").addClass("moveableWindow");
if(!$("#resizeDragMon").hasClass("minimized")){
$("#resizeDragMon").addClass("restored");
}
else{
$("#resizeDragMon").dblclick();
}
$("#resizeDragMon").resizable({
addClasses: false,
handles: "all",
containment: "#windowContainment",
start: function () {
$("#resizeDragMon").append($('<div class="iframeResizeCover"></div>'));
$("#sheet").append($('<div class="iframeResizeCover"></div>'));
},
stop: function () {
$('.iframeResizeCover').remove();
},
minWidth: 200,
minHeight: 200
});
$("#resizeDragMon").mousedown(function(){
frame_z_index_when_click($(this));
});