-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathCoreFunctions.js
More file actions
3035 lines (2728 loc) · 128 KB
/
CoreFunctions.js
File metadata and controls
3035 lines (2728 loc) · 128 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
/** CoreFunctions.js
* A place for functions that are required for proper functionality
* This is loaded from Load.js and LoadCharacterPage.js
* so be thoughtful about which functions go in this file
* */
/** The first time we load, collect all the things that we need.
* Remember that this is injected from both Load.js and LoadCharacterPage.js
* If you need to add things for when AboveVTT is actively running, do that in Startup.js
* If you need to add things for when the CharacterPage is running, do that in CharacterPage.js
* If you need to add things for all of the above situations, do that here */
var CONDITIONS = {};
$(function() {
window.EXPERIMENTAL_SETTINGS = {};
window.EXTENSION_PATH = $("#extensionpath").attr('data-path');
window.AVTT_VERSION = $("#avttversion").attr('data-version');
$("head").append('<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"></link>');
$("head").append('<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />');
if (is_encounters_page()) {
window.DM = true; // the DM plays from the encounters page
dmAvatarUrl = $('#site-bar').attr('user-avatar') != undefined ? $('#site-bar').attr('user-avatar') : $('.site-bar .user-interactions-profile-img').attr('src') != undefined ? $('.site-bar .user-interactions-profile-img').attr('src') : $('img[class*="avatarImage"]').attr('src');
dmAvatarUrl = dmAvatarUrl || defaultAvatarUrl;
} else if (is_campaign_page() && !is_spectator_page()) {
// The owner of the campaign (the DM) is the only one with private notes on the campaign page
window.DM = $(".ddb-campaigns-detail-body-dm-notes-private").length === 1;
} else {
window.DM = false;
}
});
const async_sleep = m => new Promise(r => setTimeout(r, m));
const charactersPageRegex = /\/characters\/\d+/;
const tabCommunicationChannel = new BroadcastChannel('aboveVttTabCommunication');
function isIOS() {
return (/iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator?.platform === 'MacIntel' && navigator?.maxTouchPoints > 1));
}
function isMac() {
return (navigator?.userAgentData?.platform || navigator?.platform)?.toLowerCase()?.includes("mac");
}
function getModKeyName() {
return isMac() ? "⌘" : "CTRL";
}
function getCtrlKeyName() {
return isMac() ? "⌃" : "CTRL";
}
function getAltKeyName() {
return isMac() ? "⌘" : "ALT";
}
function getShiftKeyName() {
return isMac() ? "⇧" : "SHIFT";
}
function mydebounce(func, timeout = 800){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
function throttle(func, wait, option = {leading: true, trailing: true}) {
let waiting = false;
let lastArgs = null;
return function wrapper(...args) {
if(!waiting) {
waiting = true;
const startWaitingPeriod = () => setTimeout(() => {
if(option.trailing && lastArgs) {
func.apply(this, lastArgs);
lastArgs = null;
startWaitingPeriod();
}
else {
waiting = false;
}
}, wait);
if(option.leading) {
func.apply(this, args);
} else {
lastArgs = args; // if not leading, treat like another any other function call during the waiting period
}
startWaitingPeriod();
}
else {
lastArgs = args;
}
}
}
/**
* 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);
});
}
/**
* 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");
}
}
function startup_step(stepDescription) {
console.log(`startup_step ${stepDescription}`);
$("#loading-overlay-beholder > .sidebar-panel-loading-indicator > .loading-status-indicator__subtext").text(stepDescription);
}
/// builds and returns the loading indicator that covers the iframe
function build_combat_tracker_loading_indicator(subtext = "One moment while we fetch this monster stat block") {
let loadingIndicator = $(`
<div class="sidebar-panel-loading-indicator">
<svg class="beholder-dm-screen loading-status-indicator__svg animate" viewBox="0 0 285 176" fill="none" xmlns="http://www.w3.org/2000/svg" style="overflow:overlay;margin-top:100px;width:100%;position:relative;padding:0 10%;">
<defs>
<path id="beholder-eye-move-path" d="M0 0 a 15 5 0 0 0 15 0 a 15 5 0 0 1 -15 0 z"></path>
<clipPath id="beholder-eye-socket-clip-path">
<path id="eye-socket" fill-rule="evenodd" clip-rule="evenodd" d="M145.5 76c-8.562 0-15.5-7.027-15.5-15.694 0-8.663 6.938-1.575 15.5-1.575 8.562 0 15.5-7.088 15.5 1.575C161 68.973 154.062 76 145.5 76z"></path>
</clipPath>
</defs>
<g class="beholder-dm-screen__beholder">
<path fill-rule="evenodd" clip-rule="evenodd" d="M145.313 77.36c-10.2 0-18.466-8.27-18.466-18.47 0-10.197 8.266-1.855 18.466-1.855 10.199 0 18.465-8.342 18.465 1.855 0 10.2-8.266 18.47-18.465 18.47m59.557 4.296l-.083-.057c-.704-.5-1.367-1.03-1.965-1.59a12.643 12.643 0 0 1-1.57-1.801c-.909-1.268-1.51-2.653-1.859-4.175-.355-1.521-.461-3.179-.442-4.977.007-.897.049-1.835.087-2.827.038-.995.079-2.032.053-3.194-.031-1.158-.11-2.445-.519-3.97a10.494 10.494 0 0 0-1.014-2.43 8.978 8.978 0 0 0-1.938-2.32 9.64 9.64 0 0 0-2.468-1.54l-.314-.137-.299-.114-.609-.212c-.382-.105-.787-.227-1.151-.298-1.495-.315-2.819-.383-4.065-.39-1.248-.004-2.407.087-3.534.2a56.971 56.971 0 0 0-3.18.44c-6.271.646-12.648 1.559-13.689-.837-1.079-2.487-3.35-8.058 3.115-12.19 4.076.154 8.141.347 12.179.62 1.461.098 2.914.212 4.36.34-4.614.924-9.314 1.7-14.019 2.43h-.015a2.845 2.845 0 0 0-2.388 3.066 2.84 2.84 0 0 0 3.088 2.574c5.125-.462 10.25-.973 15.416-1.696 2.592-.378 5.17-.776 7.88-1.42a29.7 29.7 0 0 0 2.108-.59c.181-.06.363-.117.56-.193.197-.072.378-.136.594-.227.208-.09.405-.17.643-.291l.345-.174.394-.235c.064-.042.124-.076.196-.125l.235-.174.235-.174.117-.099.148-.136c.098-.094.189-.189.283-.287l.137-.152a3.44 3.44 0 0 0 .166-.22c.114-.154.224-.317.318-.484l.072-.125.038-.064.042-.09a5.06 5.06 0 0 0 .367-1.154c.045-.308.06-.63.045-.944a4.322 4.322 0 0 0-.042-.458 5.19 5.19 0 0 0-.386-1.207 5.356 5.356 0 0 0-.499-.799l-.091-.117-.072-.083a5.828 5.828 0 0 0-.303-.318l-.155-.151-.083-.076-.057-.05a9.998 9.998 0 0 0-.503-.382c-.152-.102-.28-.178-.424-.265l-.205-.124-.181-.091-.36-.186a18.713 18.713 0 0 0-.643-.28l-.591-.23c-1.521-.538-2.853-.856-4.197-1.159a83.606 83.606 0 0 0-3.951-.772c-2.604-.45-5.185-.829-7.763-1.166-4.273-.564-8.531-1.029-12.785-1.46 0-.004-.004-.004-.004-.004a38.55 38.55 0 0 0-4.81-3.1v-.004c.397-.223.965-.424 1.688-.549 1.135-.208 2.551-.242 4.05-.185 3.024.11 6.366.59 10.022.662 1.832.02 3.781-.056 5.84-.56a12.415 12.415 0 0 0 3.081-1.188 10.429 10.429 0 0 0 2.702-2.135 2.841 2.841 0 0 0-3.774-4.205l-.208.152c-.825.594-1.76.87-2.956.942-1.188.068-2.566-.09-4.004-.367-2.907-.553-6.003-1.556-9.5-2.32-1.763-.371-3.644-.7-5.802-.73a16.984 16.984 0 0 0-3.455.298 13.236 13.236 0 0 0-3.774 1.333 13.065 13.065 0 0 0-3.376 2.615 14.67 14.67 0 0 0-1.646 2.154h-.004a41.49 41.49 0 0 0-8.436-.863c-1.518 0-3.017.079-4.489.238-1.79-1.563-3.444-3.198-4.833-4.913a21.527 21.527 0 0 1-1.4-1.903 15.588 15.588 0 0 1-1.094-1.893c-.606-1.241-.905-2.422-.893-3.22a3.38 3.38 0 0 1 .038-.55c.034-.155.06-.31.121-.446.106-.273.276-.534.571-.776.579-.496 1.681-.81 2.884-.689 1.207.114 2.487.629 3.615 1.476 1.135.848 2.111 2.044 2.868 3.444l.038.076a2.848 2.848 0 0 0 3.471 1.329 2.843 2.843 0 0 0 1.714-3.641c-.768-2.135-1.96-4.235-3.675-6.003-1.71-1.76-3.924-3.18-6.502-3.872a12.604 12.604 0 0 0-4.076-.416 11.248 11.248 0 0 0-4.284 1.128 10.405 10.405 0 0 0-3.702 3.054c-.499.655-.901 1.37-1.237 2.104-.318.73-.568 1.488-.731 2.237-.337 1.503-.356 2.96-.238 4.315.125 1.362.405 2.63.764 3.822.36 1.196.803 2.317 1.298 3.373a31.9 31.9 0 0 0 1.605 3.043c.458.768.935 1.506 1.427 2.233h-.004a39.13 39.13 0 0 0-4.515 2.384c-3.111-.344-6.2-.76-9.242-1.294-2.033-.364-4.043-.769-6.007-1.26-1.96-.485-3.876-1.045-5.662-1.726a24.74 24.74 0 0 1-2.528-1.102c-.772-.393-1.48-.829-1.987-1.234a4.916 4.916 0 0 1-.56-.507c-.02-.015-.03-.03-.046-.045.288-.28.761-.621 1.314-.905.719-.382 1.566-.711 2.456-.984 1.79-.556 3.762-.9 5.76-1.098l.046-.007a2.843 2.843 0 0 0 2.547-2.805 2.846 2.846 0 0 0-2.824-2.868c-2.301-.02-4.628.11-7.028.567-1.2.231-2.418.538-3.671 1.022-.628.246-1.26.526-1.911.901a10.12 10.12 0 0 0-1.96 1.446c-.648.62-1.307 1.438-1.757 2.524-.114.261-.197.56-.284.844a7.996 7.996 0 0 0-.166.909c-.061.609-.05 1.237.049 1.809.189 1.162.632 2.12 1.109 2.891a11.265 11.265 0 0 0 1.529 1.942c1.056 1.082 2.127 1.88 3.194 2.6a33.287 33.287 0 0 0 3.21 1.855c2.142 1.093 4.284 1.979 6.434 2.774a98.121 98.121 0 0 0 6.464 2.112c.511.147 1.018.291 1.529.435a36.8 36.8 0 0 0-4.458 7.089v.004c-1.908-2.014-3.876-3.997-6.022-5.931a52.386 52.386 0 0 0-3.471-2.888 31.347 31.347 0 0 0-2.028-1.408 17.575 17.575 0 0 0-2.574-1.378 11.177 11.177 0 0 0-1.888-.616c-.761-.16-1.73-.31-3.02-.107a6.543 6.543 0 0 0-1.007.254 6.508 6.508 0 0 0-2.79 1.84 6.7 6.7 0 0 0-.594.783c-.083.129-.174.269-.238.39a7.248 7.248 0 0 0-.681 1.692 9.383 9.383 0 0 0-.3 2.02c-.022.584 0 1.09.038 1.568.084.953.231 1.786.401 2.577l.39 1.764c.027.14.065.268.087.408l.057.428.121.855.065.428.033.443.072.886c.061.586.061 1.196.076 1.801.05 2.426-.11 4.92-.435 7.407a50.6 50.6 0 0 1-1.503 7.35c-.17.594-.367 1.17-.548 1.76a55.283 55.283 0 0 1-.632 1.684l-.352.791c-.061.129-.114.276-.178.39l-.193.356-.186.355c-.064.121-.129.246-.193.326-.129.185-.257.375-.378.575l-.303.485a2.813 2.813 0 0 0 4.462 3.387c.295-.322.59-.655.878-.988.155-.17.265-.333.382-.496l.349-.488.344-.492c.117-.166.2-.325.303-.492l.583-.98a53.92 53.92 0 0 0 1.018-1.964c.295-.659.61-1.321.89-1.984a58.231 58.231 0 0 0 2.69-8.114 58.405 58.405 0 0 0 1.51-8.493c.068-.73.152-1.454.167-2.203l.045-1.12.02-.56-.012-.568-.004-.205c.167.186.333.371.496.557 1.608 1.84 3.179 3.838 4.708 5.889a181.94 181.94 0 0 1 4.481 6.328c.14.2.311.428.477.617.284.33.594.62.924.874 0 .216.003.424.015.636-2.661 2.861-5.265 5.821-7.748 9.034-1.567 2.06-3.096 4.19-4.485 6.715-.685 1.267-1.347 2.645-1.854 4.363-.246.879-.454 1.851-.496 3.02l-.007.44.022.473c.012.159.02.314.038.477.023.166.05.337.076.503.113.666.333 1.385.65 2.07.16.337.356.67.557.992.212.299.44.613.681.878a8.075 8.075 0 0 0 1.54 1.328c1.05.697 2.04 1.06 2.938 1.31 1.79.466 3.292.519 4.723.507 2.842-.053 5.367-.48 7.853-.98 4.943-1.022 9.618-2.434 14.243-3.948a2.845 2.845 0 0 0 1.911-3.236 2.842 2.842 0 0 0-3.323-2.267h-.015c-4.648.878-9.322 1.635-13.864 1.965-2.252.155-4.511.208-6.46-.027a10.954 10.954 0 0 1-1.685-.322c.004-.015.012-.026.015-.037.133-.273.322-.606.534-.954.235-.36.477-.73.768-1.117 1.14-1.548 2.619-3.164 4.183-4.723a83.551 83.551 0 0 1 2.585-2.468 35.897 35.897 0 0 0 2.312 4.16c.125.2.261.405.397.602 3.747-.413 7.415-1.06 10.356-1.617l.037-.007a7.47 7.47 0 0 1 8.702 5.957 7.491 7.491 0 0 1-4.724 8.38C132.172 94.372 138.542 96 145.313 96c20.358 0 37.087-14.708 38.994-33.514.193-.05.386-.098.576-.144a23.261 23.261 0 0 1 2.354-.458c.726-.102 1.393-.14 1.847-.125.125-.004.193.015.299.012.03.003.064.007.098.007h.053c.008.004.015.004.027.004.106 0 .094-.019.09-.068-.007-.05-.022-.125.019-.117.038.007.125.083.216.26.087.19.186.443.269.761.079.33.159.69.219 1.102.129.806.216 1.745.307 2.725.091.984.178 2.02.306 3.1.262 2.138.682 4.435 1.533 6.683.837 2.245 2.154 4.406 3.812 6.15.825.871 1.725 1.655 2.66 2.336.943.677 1.919 1.26 2.911 1.782a2.848 2.848 0 0 0 3.641-.874 2.848 2.848 0 0 0-.674-3.966" fill="#0398F3">
</path>
<g clip-path="url(#beholder-eye-socket-clip-path)">
<circle cx="137.5" cy="60" r="7" fill="#1B9AF0">
<animateMotion dur="2.3s" repeatCount="indefinite">
<mpath xlink:href="#beholder-eye-move-path"></mpath>
</animateMotion>
</circle>
</g>
</g>
<g class="beholder-dm-screen__screen">
<path fill="#3c1e00ff" stroke="#3b3b3bff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" d="M76 76h136v97H76z"></path>
<path d="M218 170.926V74.282l64-35.208v96.644l-64 35.208zM70 171.026V74.318L3 38.974v96.708l67 35.344z" fill="#3c1e00ff" stroke="#3b3b3bff" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
</svg>
<div class="loading-status-indicator__subtext">${subtext}</div>
</div>
`);
loadingIndicator.css({
"display": "block",
"position": "absolute",
"height": "100%",
"width": "100%",
"top": "0px",
"left": "0px",
"z-index": 100000,
"background": "rgb(235, 241, 245)"
});
return loadingIndicator.clone();
}
/**
* Add Dice buttons into sidebar.
*
* We add dice buttons and an input for chatting in the gamelog.
* This does that injection on initial load as well as any time the character sheet re-adds the gamelog to the sidebar.
* See `monitor_character_sidebar_changes` for more details on sidebar changes.
* @returns
*/
function inject_chat_buttons() {
const gameLog = $(".glc-game-log");
if (gameLog.find("#chat-text").length > 0) {
// make sure we only ever inject these once. This gets called a lot on the character sheet which is intentional, but just in case we accidentally call it too many times, let's log it, and return
return;
}
const chatTextWrapper = $(`<div class='chat-text-wrapper sidebar-hover-text' data-hover="Dice Rolling Format: /cmd diceNotation action 

'/r 1d20'

'/roll 1d4 punch:bludgeoning damage'

'/hit 2d20kh1+2 longsword ADV'

'/dmg 1d8-2 longsword:slashing'

'/save 2d20kl1 DEX DISADV'

'/skill 1d20+1d4 Thieves' Tools + Guidance'

Advantage: 2d20kh1 (keep highest)

Disadvantage: 2d20kl1 (keep lowest)

'/w [playername] a whisper to playername'

'/dm for a shortcut to whisper THE DM'

'/timer Timer Title 5:00' or '/timer 5:00'"><input id='chat-text' autocomplete="off" placeholder='Chat, /r 1d20+4..'></div>`
);
const diceRoller = $(`
<div class="dice-roller">
<div>
<img title="d4" alt="d4" height="40px" src="${window.EXTENSION_PATH + "assets/dice/d4.svg"}"/>
</div>
<div>
<img title="d6" alt="d6" height="40px" src="${window.EXTENSION_PATH + "assets/dice/d6.png"}"/>
</div>
<div>
<img title="d8" alt="d8" height="40px" src="${window.EXTENSION_PATH + "assets/dice/d8.svg"}"/>
</div>
<div>
<img title="d10" alt="d10" height="40px" src="${window.EXTENSION_PATH + "assets/dice/d10.svg"}"/>
</div>
<div>
<img title="d100" alt="d100" height="40px" src="${window.EXTENSION_PATH + "assets/dice/d100.png"}"/>
</div>
<div>
<img title="d12" alt="d12" height="40px" src="${window.EXTENSION_PATH + "assets/dice/d12.svg"}"/>
</div>
<div>
<img title="d20" alt="d20" height="40px" src="${window.EXTENSION_PATH + "assets/dice/d20.svg"}"/>
</div>
</div>
`)
const languageSelect= $(`<select id='chat-language'></select>`)
const ignoredLanguages = ['All'];
const knownLanguages = get_my_known_languages();
for (const language of window.ddbConfigJson.languages) {
if (ignoredLanguages.includes(language.name))
continue;
if (!window.DM && !knownLanguages.includes(language.name))
continue;
const option = $(`<option value='${language.id}'>${language.name}</option>`)
languageSelect.append(option);
}
gameLog.append(chatTextWrapper, languageSelect, diceRoller);
$(".dice-roller > div img").on("click", async function(e) {
if ($(".dice-toolbar__dropdown, [class*='DiceContainer_button']").length > 0 && !window.EXPERIMENTAL_SETTINGS['rpgRoller']) {
// DDB dice are on the screen so let's use those. Ours will synchronize when these change.
if (($(".dice-toolbar__dropdown").length > 0 && !$(".dice-toolbar__dropdown").hasClass("dice-toolbar__dropdown-selected")) || $(`[class*='DiceContainer_button']:not([class*='DiceContainer_customDiceRollOpen'])`).length>0) {
// make sure it's open
await $(".dice-toolbar__dropdown-die, [class*='DiceContainer_button']").click();
}
// select the DDB dice matching the one that the user just clicked
let dieSize = $(this).attr("alt");
await $(`.dice-die-button[data-dice='${dieSize}'], [class*='AnchoredPopover_wrapper'] #${dieSize}`).click();
} else {
// there aren't any DDB dice on the screen so use our own
const dataCount = $(this).attr("data-count");
if (dataCount === undefined) {
$(this).attr("data-count", 1);
$(this).parent().append(`<span class="dice-badge">1</span>`);
} else {
$(this).attr("data-count", parseInt(dataCount) + 1);
$(this).parent().append(`<span class="dice-badge">${parseInt(dataCount) + 1}</span>`);
}
if ($(".dice-roller > div img[data-count]").length > 0) {
if(!$(".roll-mod-container").hasClass('show')){
$(".roll-mod-container").addClass("show");
$(".roll-mod-container").find('input').val(0);
}
} else {
$(".roll-mod-container").removeClass("show");
}
}
});
window.rollButtonObserver = new MutationObserver(function() {
// Any time the DDB dice buttons change state, we want to synchronize our dice buttons to match theirs.
$(".dice-die-button").each(function() {
let dieSize = $(this).attr("data-dice");
let ourDiceElement = $(`.dice-roller > div img[alt='${dieSize}']`);
let diceCountElement = $(this).find(".dice-die-button__count");
ourDiceElement.parent().find("span").remove();
if (diceCountElement.length == 0) {
ourDiceElement.removeAttr("data-count");
} else {
let diceCount = parseInt(diceCountElement.text());
ourDiceElement.attr("data-count", diceCount);
ourDiceElement.parent().append(`<span class="dice-badge">${diceCount}</span>`);
}
})
$("[class*='AnchoredPopover_wrapper'] button[id^='d']").each(function () {
let dieSize = this.id;
let ourDiceElement = $(`.dice-roller > div img[alt='${dieSize}']`);
let diceCountElement = $(this).attr('data-quantity');
ourDiceElement.parent().find("span").remove();
if (diceCountElement == undefined) {
ourDiceElement.removeAttr("data-count");
} else {
let diceCount = parseInt(diceCountElement);
ourDiceElement.attr("data-count", diceCount);
ourDiceElement.parent().append(`<span class="dice-badge">${diceCount}</span>`);
}
})
if ($("[class*='AnchoredPopover_wrapper']").length>0 && $("[class*='AnchoredPopover_wrapper'] button[id^='d']").length == 0){
$('.dice-roller .dice-badge').remove();
}
// make sure our roll button is shown/hidden after all animations have completed
setTimeout(function() {
if ($(".dice-toolbar").hasClass("rollable") || $("[class*='DiceContainer_customDiceRollOpen']").length > 0) {
if(!$(".roll-mod-container").hasClass('show')){
$(".roll-mod-container").addClass("show");
$(".roll-mod-container").find('input').val(0);
}
} else {
$(".roll-mod-container").removeClass("show");
}
}, 0);
})
let watchForDicePanel = new MutationObserver((mutations) => {
mutations.every(async (mutation) => {
if (!mutation.addedNodes) return
for (let i = 0; i < mutation.addedNodes.length; i++) {
// do things to your newly added nodes here
let node = mutation.addedNodes[i]
if ((node.className == 'dice-rolling-panel' || $('.dice-rolling-panel').length>0)){
const mutation_target = $(".dice-toolbar__dropdown, [class*='AnchoredPopover_wrapper']")[0];
const mutation_config = { attributes: true, childList: true, characterData: true, subtree: true };
window.rollButtonObserver.observe(mutation_target, mutation_config);
watchForDicePanel.disconnect();
return false;
}
}
return true // must return true if doesn't break
})
});
window.sendToDefaultObserver = new MutationObserver(function() {
localStorage.setItem(`${window.gameId != undefined ? window.gameId : window.myUser}-sendToDefault`, gamelog_send_to_text());
})
let gamelogObserver = new MutationObserver((mutations) => {
mutations.every((mutation) => {
if (!mutation.addedNodes) return
for (let i = 0; i < mutation.addedNodes.length; i++) {
// do things to your newly added nodes here
let node = mutation.addedNodes[i]
if($(node).attr('class')?.includes('-SendToLabel') || $('.glc-game-log [class*="-SendToLabel"] ~ button').length>0){
const sendto_mutation_target = $(".glc-game-log [class*='-SendToLabel'] ~ button")[0];
const sendto_mutation_config = { attributes: true, childList: true, characterData: true, subtree: true };
window.sendToDefaultObserver.observe(sendto_mutation_target, sendto_mutation_config);
gamelogObserver.disconnect();
return false;
}
}
return true // must return true if doesn't break
})
});
watchForDicePanel.observe(document.body, {childList: true, subtree: true, attributes: false, characterData: false});
gamelogObserver.observe(document.body, {childList: true, subtree: true, attributes: false, characterData: false});
$(".dice-roller > div img").on("contextmenu", function(e) {
e.preventDefault();
if ($(".dice-toolbar__dropdown, [class*='DiceContainer_button']").length > 0 && !window.EXPERIMENTAL_SETTINGS['rpgRoller']) {
// There are DDB dice on the screen so update those buttons. Ours will synchronize when these change.
// the only way I could get this to work was with pure javascript. Everything that I tried with jQuery did nothing
let dieSize = $(this).attr("alt");
let element = $(`.dice-die-button[data-dice='${dieSize}'], #${dieSize}`)[0];
let e = element.ownerDocument.createEvent('MouseEvents');
e.initMouseEvent('contextmenu', true, true,
element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
false, false, false, 2, null);
element.dispatchEvent(e);
} else {
let dataCount = $(this).attr("data-count");
if (dataCount !== undefined) {
dataCount = parseInt(dataCount) - 1;
if (dataCount === 0) {
$(this).removeAttr("data-count");
$(this).parent().find("span").remove();
} else {
$(this).attr("data-count", dataCount);
$(this).parent().append(`<span class="dice-badge">${dataCount}</span>`);
}
}
if ($(".dice-roller > div img[data-count]").length > 0) {
if(!$(".roll-mod-container").hasClass('show')){
$(".roll-mod-container").addClass("show");
$(".roll-mod-container").find('input').val(0);
}
} else {
$(".roll-mod-container").removeClass("show");
}
}
});
if ($(".roll-button").length == 0) {
const rollButton = $(`<button class="roll-button">Roll</button>`);
const modInput = $(`<div class='roll-mod-container'>
<button class="roll-button-mod dis roll_mods_button icon-disadvantage markers-icon"></button>
<button class="roll-button-mod minus">-</button>
<input class="roll-input-mod" type='number' value='0' step='1'></input>
<button class="roll-button-mod plus">+</button>
<button class="roll-button-mod adv roll_mods_button icon-advantage markers-icon"></button>
</div>`)
modInput.append(rollButton);
$("body").append(modInput);
let advDis;
modInput.off('click.button').on('click.button', 'button.roll-button-mod', function(e){
e.preventDefault();
const clickedButton = $(this)
const input = modInput.find('input');
if(clickedButton.hasClass('minus')){
input.val(parseInt(input.val())-1);
}
else if(clickedButton.hasClass('plus')){
input.val(parseInt(input.val())+1);
}
else if (clickedButton.hasClass('adv')){
advDis = 'kh';
rollButton.click();
}
else if(clickedButton.hasClass('dis')){
advDis = 'kl'
rollButton.click();
}
});
rollButton.on("click", function (e) {
let modValue = parseInt($('.roll-input-mod').val())
const rollExpression = [];
const diceToCount = $(".dice-roller > div img[data-count]").length>0 ? $(".dice-roller > div img[data-count]") : $('.dice-die-button__count')
diceToCount.each(function() {
let count, dieType;
if($(this).is('.dice-die-button__count')){
count = $(this).text();
dieType = $(this).closest('[data-dice]').attr("data-dice");
}
else{
count = $(this).attr("data-count");
dieType = $(this).attr("alt");
}
if(advDis != undefined){
for (let i = 0; i<count; i++){
rollExpression.push('2' + dieType + advDis + '1');
}
}
else{
rollExpression.push(count + dieType);
}
});
advDis = undefined;
$('.dice-toolbar__dropdown-selected>div:first-of-type')?.click();
let expression = `${rollExpression.join("+")}${modValue<0 ? modValue : `+${modValue}`}`
window.diceRoller.roll(new DiceRoll(expression));
$(".roll-mod-container").removeClass("show");
$(".dice-roller > div img[data-count]").removeAttr("data-count");
$(".dice-roller > div span").remove();
});
}
if (window.chatObserver === undefined) {
window.chatObserver = new ChatObserver();
}
window.chatObserver.observe($("#chat-text"));
$(".GameLog_GameLog__2z_HZ").scroll(function() {
if ($(this).scrollTop() >= 0) {
$(this).removeClass("highlight-gamelog");
}
});
// open, resize, then close the `Send To: (Default)` drop down. It won't resize unless it's open
$("div.MuiPaper-root.MuiMenu-paper").click();
setTimeout(function() {
$("div.MuiPaper-root.MuiMenu-paper").css({
"min-width": "200px"
})
$("div.MuiPaper-root.MuiMenu-paper").click();
}, 0);
}
function find_currently_open_character_sheet() {
if (is_characters_page()) {
return window.location.pathname;
}
let sheet;
$("#sheet").find("iframe").each(function () {
const src = $(this).clone().attr("src");
if (src != "") {
sheet = src;
}
})
return sheet;
}
function monitor_console_logs() {
// slightly modified version of https://stackoverflow.com/a/67449524
if (console.concerningLogs === undefined) {
console.concerningLogs = [];
console.otherLogs = [];
function TS() {
return (new Date).toISOString();
}
function addLog(log) {
if (log.type !== 'log' && log.type !== 'debug') { // we don't currently track debug, but just in case we add them
console.concerningLogs.unshift(log);
if (console.concerningLogs.length > 100) {
console.concerningLogs.length = 100;
}
if (get_avtt_setting_value("aggressiveErrorMessages")) {
showError(new Error(`${log.type} ${log.message}`), ...log.value);
}
} else {
console.otherLogs.unshift(log);
if (console.otherLogs.length > 100) {
console.otherLogs.length = 100;
}
}
}
window.addEventListener('error', function(event) {
addLog({
type: "exception",
timeStamp: TS(),
value: [event.message, `${event.filename}:${event.lineno}:${event.colno}`, event.error?.stack]
});
return false;
});
window.addEventListener('onunhandledrejection', function(event) {
addLog({
type: "exception",
timeStamp: TS(),
value: [event.message, `${event.filename}:${event.lineno}:${event.colno}`, event.error?.stack]
});
return false;
});
window.onerror = function (error, url, line, colno) {
addLog({
type: "exception",
timeStamp: TS(),
value: [error, `${url}:${line}:${colno}`]
});
return false;
}
window.onunhandledrejection = function (event) {
addLog({
type: "promiseRejection",
timeStamp: TS(),
value: [event.message, `${event.filename}: ${event.lineno}:${event.colno}`, event.error?.stack]
});
}
function hookLogType(logType) {
const original = console[logType].bind(console);
return function() {
addLog({
type: logType,
timeStamp: TS(),
value: Array.from(arguments)
});
// Function.prototype.apply.call(console.log, console, arguments);
original.apply(console, arguments);
}
}
// we don't care about debug logs right now
['log', 'error', 'warn'].forEach(logType=> {
console[logType] = hookLogType(logType)
});
}
}
function openDB() {
let promises =[];
promises.push(new Promise(async (resolve, reject) => {
const DBOpenRequest = await indexedDB.open(`AboveVTT-${window.gameId}`, 2); // version 2
DBOpenRequest.onsuccess = (e) => {
resolve(DBOpenRequest.result);
};
DBOpenRequest.onerror = (e) => {
console.warn(e);
};
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
if(!db.objectStoreNames?.contains('exploredData')){
const objectStore = db.createObjectStore("exploredData", { keyPath: "exploredId" });
}
if(!db.objectStoreNames?.contains('journalData')){
const objectStore2 = db.createObjectStore("journalData", { keyPath: "journalId" });
}
};
})
);
promises.push(new Promise((resolve, reject) => {
const DBOpenRequest2 = indexedDB.open(`AboveVTT-Global`, 5);
DBOpenRequest2.onsuccess = (e) => {
resolve(DBOpenRequest2.result);
};
DBOpenRequest2.onerror = (e) => {
console.warn(e);
};
DBOpenRequest2.onupgradeneeded = (event) => {
const db = event.target.result;
if(!db.objectStoreNames?.contains('customizationData')){
const objectStore = db.createObjectStore("customizationData", { keyPath: "customizationId" });
}
if(!db.objectStoreNames?.contains('journalData')){
const objectStore2 = db.createObjectStore("journalData", { keyPath: "journalId" });
}
if (db.objectStoreNames?.contains('avttFilePicker')) {
db.deleteObjectStore('avttFilePicker');
}
};
})
);
return Promise.all(promises);
}
function deleteDB(){
let d = confirm("DELETE ALL LOCAL EXPLORE DATA (CANNOT BE UNDONE)");
if (d === true) {
const objectStore = gameIndexedDb.transaction([`exploredData`], "readwrite").objectStore('exploredData');
const objectStoreRequest = objectStore.clear();
objectStoreRequest.onsuccess = function(event) {
$('#exploredCanvas').remove();
redraw_light();
alert('This campaigns local explored vision data has been cleared.')
};
}
}
function deleteCurrentExploredScene(){
let d = confirm("DELETE CURRENT SCENE EXPLORE DATA (CANNOT BE UNDONE)");
if (d === true) {
deleteExploredScene(window.CURRENT_SCENE_DATA.id)
}
}
function deleteExploredScene(sceneId){
const deleteRequest = gameIndexedDb
.transaction([`exploredData`], "readwrite")
.objectStore('exploredData')
.delete(`explore${window.gameId}${sceneId}`);
deleteRequest.onsuccess = function(event) {
if(sceneId == window.CURRENT_SCENE_DATA.id){
$('#exploredCanvas').remove();
redraw_light();
alert('Scene Explore Trail Data Cleared')
}
};
}
function sanitize_aoe_shape(shape){
// normalize shape
switch(shape) {
case "cube":
shape = "square";
break;
case "sphere":
shape = "circle";
break;
case "cylinder":
shape = "circle";
}
return shape
}
function get_available_styles(){
return [
"Acid",
"Bludgeoning",
"Cold",
"Darkness",
"Default",
"Fire",
"Force",
"Lightning",
"Nature",
"Necrotic",
"Piercing",
"Poison",
"Psychic",
"Radiant",
"Slashing",
"Thunder",
"Water"
]
}
function add_aoe_to_statblock(html){
html = html.replaceAll(/­|/gi, '')
const aoeRegEx = /(([\d]+)-foot(-long ([\d]+)-foot-wide|-long, ([\d]+)-foot-wide|-radius, [\d]+-foot-high|-radius)? ([a-zA-z]+))(.*?[\>\s]([a-zA-Z]+) damage)?/gi
return html.replaceAll(aoeRegEx, function(m, m1, m2,m3, m4, m5, m6, m7, m8){
const shape = m6.toLowerCase();
if(shape != 'cone' && shape != 'sphere' && shape != 'cube' && shape != 'cylinder' && shape != 'line')
return `${m}`
if(shape == 'emanation')
return `${m}` // potentially set a button for aura being set on these if an aura doesn't already exist
else
return `<button class='avtt-aoe-button' border-width='1px' title='Place area of effect token'
data-shape='${shape}'
data-style='${m8 != undefined && get_available_styles().some(shape => shape.toLowerCase().includes(m8.toLowerCase())) ? m8.toLowerCase() : 'default'}'
data-size='${m2}'
data-name='${m6} AoE'
${shape == 'line' ? `data-line-width=${m4 != undefined ? `'${m4}'` : m5 != undefined ? `'${m5}'` : '5'}` : ''}>
${m1}
</button>
${m7 != undefined? m7 : ''}
`
})
}
function add_aoe_statblock_click(target, tokenId = undefined){
target.find(`button.avtt-aoe-button`).off('click.aoe').on('click.aoe', function(e) {
e.stopPropagation();
const color = $(this).attr('data-style');
const shape = $(this).attr('data-shape');
const feet = $(this).attr('data-size');
const name = $(this).attr('data-name');
const lineWidth = $(this).attr('data-line-width');
if(is_abovevtt_page() || window.self != window.top){
window.top.hide_player_sheet();
window.top.minimize_player_sheet();
let options = window.top.build_aoe_token_options(color, shape, feet / window.top.CURRENT_SCENE_DATA.fpsq, name, lineWidth / window.top.CURRENT_SCENE_DATA.fpsq)
if(name == 'Darkness' || name == 'Maddening Darkness' ){
options = {
...options,
darkness: true
}
}
//if single token selected, place there:
if(window.top.CURRENTLY_SELECTED_TOKENS.length == 1) {
window.top.place_aoe_token_at_token(options, window.top.TOKEN_OBJECTS[window.top.CURRENTLY_SELECTED_TOKENS[0]]);
}
else if (window.top.TOKEN_OBJECTS[tokenId] != undefined && !window.top.TOKEN_OBJECTS[tokenId].options.combatGroupToken){
window.top.place_aoe_token_at_token(options, window.top.TOKEN_OBJECTS[tokenId]);
}else {
window.top.place_aoe_token_in_centre(options)
}
}
else if(window.sendToTab != undefined){
const data = {color: color, shape: shape, feet: feet, name: name, lineWidth: lineWidth, tokenId: tokenId}
tabCommunicationChannel.postMessage({
msgType: 'placeAoe',
data: data,
sendTo: window.sendToTab
});
}
})
}
function create_update_token(options, save = true) {
console.log("create_update_token");
let self = this;
let id = options.id;
options.scaleCreated = window.CURRENT_SCENE_DATA.scale_factor;
if (!(id in window.TOKEN_OBJECTS)) {
window.TOKEN_OBJECTS[id] = new Token(options);
window.TOKEN_OBJECTS[id].sync = mydebounce(function(options) {
window.MB.sendMessage('custom/myVTT/token', options);
}, 300);
}
if(options.repositionAoe != undefined){
window.TOKEN_OBJECTS[id].place(0);
let origin, dx, dy;
origin = getOrigin(window.TOKEN_OBJECTS[id]);
dx = origin.x - options.repositionAoe.x;
dy = origin.y - options.repositionAoe.y;
options.left = `${parseFloat(options.left) - dx}px`;
options.top = `${parseFloat(options.top) - dy}px`;
delete options.repositionAoe;
}
window.TOKEN_OBJECTS[id].place(0);
window.TOKEN_OBJECTS[id].sync($.extend(true, {}, options));
}
function add_journal_roll_buttons(target, tokenId=undefined, specificImage=undefined, specificName=undefined){
console.group("add_journal_roll_buttons")
let pastedButtons = target.find('.avtt-roll-button, .integrated-dice__container, .avtt-aoe-button');
for(let i=0; i<pastedButtons.length; i++){
$(pastedButtons[i]).replaceWith($(pastedButtons[i]).text());
}
const rollImage = specificImage ? specificImage : (tokenId) ? window.all_token_objects[tokenId].options.imgsrc : window.PLAYER_IMG
const rollName = specificName ? specificName : (tokenId) ? window.all_token_objects[tokenId].options.revealname == true || window.all_token_objects[tokenId].options.player_owned ? window.all_token_objects[tokenId].options.name : '' : window.PLAYER_NAME
const clickHandler = function(clickEvent) {
clickEvent.stopPropagation();
roll_button_clicked(clickEvent, rollName, rollImage, tokenId ? "monster" : undefined, tokenId)
};
const rightClickHandler = function(contextmenuEvent) {
contextmenuEvent.stopPropagation();
roll_button_contextmenu_handler(contextmenuEvent, rollName, rollImage, tokenId ? "monster" : undefined, tokenId);
}
// replace all "to hit" and "damage" rolls
let currentElement = $(target).clone()
const dashToMinus = /([\s>])−(\d)/gi
// apply most specific regex first matching all possible ways to write a dice notation
// to account for all the nuances of DNDB dice notation.
// numbers can be swapped for any number in the following comment
// matches "1d10", " 1d10 ", "1d10+1", " 1d10+1 ", "1d10 + 1" " 1d10 + 1 "
const strongRoll = /(<strong>)(([0-9]+d[0-9]+)\s?([+-]\s?[0-9]+)?)(<\/strong>)/gi
const damageRollRegexBracket = /(\()(([0-9]+d[0-9]+)\s?([+-]\s?[0-9]+)?)(\))/gi
const damageRollRegex = /([:\s>]|^)(([0-9]+d[0-9]+)\s?([+-]\s?[0-9]+)?)([\.\):\s<,]|$)/gi
// matches " +1 " or " + 1 "
const hitRollRegexBracket = /(?<![0-9]+d[0-9]+)(\()([+-]\s?[0-9]+)(\))/gi
const hitRollRegex = /(?<![0-9]+d[0-9]+)([:\s>]|^)([+-]\s?[0-9]+)([:\s<,]|$)/gi
const dRollRegex = /([\s>]|^)(\s?d[0-9]+)([^+-])/gi
const rechargeRegEx = /(Recharge [0-6]?\s?[—–-]?\s?[0-6])/gi
const actionType = "roll"
const rollType = "AboveVTT"
let updated = currentElement.html()
.replaceAll(strongRoll, `$2`)
.replaceAll(dashToMinus, `$1-$2`)
.replaceAll(damageRollRegexBracket, ` <button data-exp='$3' data-mod='$4' data-rolltype='damage' data-actiontype='${actionType}' class='avtt-roll-button' title='${actionType}'>$1$2$5</button>`)
.replaceAll(damageRollRegex, ` $1<button data-exp='$3' data-mod='$4' data-rolltype='damage' data-actiontype='${actionType}' class='avtt-roll-button' title='${actionType}'>$2</button>$5`)
.replaceAll(hitRollRegexBracket, ` <button data-exp='1d20' data-mod='$2' data-rolltype='to hit' data-actiontype=${actionType} class='avtt-roll-button' title='${actionType}'>$1$2$3</button>`)
.replaceAll(hitRollRegex, ` $1<button data-exp='1d20' data-mod='$2' data-rolltype='to hit' data-actiontype=${actionType} class='avtt-roll-button' title='${actionType}'>$2</button>$3`)
.replaceAll(dRollRegex, `$1<button data-exp='1$2' data-mod='' data-rolltype='to hit' data-actiontype=${actionType} class='avtt-roll-button' title='${actionType}'>$2</button>$3`)
.replaceAll(rechargeRegEx, `<button data-exp='1d6' data-mod='' data-rolltype='recharge' data-actiontype='Recharge' class='avtt-roll-button' title='${actionType}'>$1</button>`)
updated = add_aoe_to_statblock(updated);
let ignoreFormatting = $(currentElement).find('.ignore-abovevtt-formating');
let slashCommandElements = $(currentElement).find('.abovevtt-slash-command-journal')
let $newHTML = $(`<div></div>`).html(updated);
$newHTML.find('.ignore-abovevtt-formating').each(function(index){
$(this).empty().append(ignoreFormatting[index].innerHTML);
})
$newHTML.find('.abovevtt-slash-command-journal').each(function(index){
const slashCommands = [...slashCommandElements[index].innerHTML.matchAll(multiDiceRollCommandRegex)];
if (slashCommands.length === 0) return;
console.debug("inject_dice_roll slashCommands", slashCommands);
let updatedInnerHtml = slashCommandElements[index].innerHTML;
try {
slashCommands[0][0] = slashCommands[0][0].replace(/\(|\)/ig, '');
const diceRoll = DiceRoll.fromSlashCommand(slashCommands[0][0], window.PLAYER_NAME, window.PLAYER_IMG, "character", window.PLAYER_ID); // TODO: add gamelog_send_to_text() once that's available on the characters page without avtt running
updatedInnerHtml = updatedInnerHtml.replace(updatedInnerHtml, `<button class='avtt-roll-formula-button integrated-dice__container' title="${diceRoll.action?.toUpperCase() ?? "CUSTOM"}: ${diceRoll.rollType?.toUpperCase() ?? "ROLL"}" data-slash-command="${slashCommands[0][0]}">${diceRoll.expression}</button>`);
} catch (error) {
console.warn("inject_dice_roll failed to parse slash command. Removing the command to avoid infinite loop", slashCommands, slashCommands[0][0]);
updatedInnerHtml = updatedInnerHtml.replace(updatedInnerHtml, '');
}
$(this).empty().append(updatedInnerHtml);
})
$(target).html($newHTML[0].innerHTML);
$(target).find('button.avtt-roll-button[data-rolltype]').each(function(){
let rollAction = $(this).prevUntil('em>strong').find('strong').last().text().replace('.', '');
rollAction = (rollAction == '') ? $(this).prev('strong').last().text().replace('.', '') : rollAction;
rollAction = (rollAction == '') ? $(this).prevUntil('strong').last().prev().text().replace('.', '') : rollAction;
rollAction = (rollAction == '') ? $(this).parent().prevUntil('em>strong').find('strong').last().text().replace('.', '') : rollAction;
rollAction = (rollAction == '') ? $(this).closest('.mon-stat-block__attribute-value').prev().text().replace('.', '') : rollAction;
rollAction = (rollAction == '') ? $(this).closest('.mon-stat-block__tidbit, [class*="styles_attribute"]').find('>.mon-stat-block__tidbit-label, >[class*="styles_attributeLabel"]').text().replace('.', '') : rollAction;
let rollType = $(this).attr('data-rolltype')
let newStatBlockTables = $(this).closest('table').find('tbody tr:first th').text().toLowerCase();
if(newStatBlockTables.includes('str') || newStatBlockTables.includes('int')){
rollAction = $(this).closest('tr').find('th').text();
rollType = $(this).closest('td').index() == 2 ? 'Check' : 'Save'
}
else if($(this).closest('table').find('tr:first').text().toLowerCase().includes('str')){
let statIndex = $(this).closest('table').find('tr button').index($(this));
let stats = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']
rollAction = stats[statIndex];
rollType = 'Check'
}
else if($(this).closest('.ability-block__stat')?.find('.ability-block__heading').length>0){
rollAction = $(this).closest('.ability-block__stat')?.find('.ability-block__heading').text();
rollType = 'Check'
}
if(rollAction == ''){
rollAction = 'Roll';
}
else if(rollAction.replace(' ', '').toLowerCase() == 'savingthrows'){
rollAction = $(this)[0].previousSibling?.nodeValue?.replace(/[\W]+/gi, '');
rollAction = (rollAction == '') ? $(this).prev()?.text()?.replace(/[\W]+/gi, '') : rollAction;
rollType = 'Save';
}
else if(rollAction.replace(' ', '').toLowerCase() == 'skills'){
rollAction = $(this)[0].previousSibling?.nodeValue?.replace(/[\W]+/gi, '');
rollAction = (rollAction == '') ? $(this).prev()?.text()?.replace(/[\W]+/gi, '') : rollAction;
rollType = 'Check';
}
else if(rollAction.replace(' ', '').toLowerCase() == 'proficiencybonus'){
rollAction = 'Proficiency Bonus';
rollType = 'Roll';
}
else if(rollAction.replace(' ', '').toLowerCase() == 'hp' || rollAction.replace(' ', '').toLowerCase() == 'hitpoints'){
rollAction = 'Hit Points';
rollType = 'Roll';
}
else if(rollAction.replace(' ', '').toLowerCase() == 'initiative'){
rollType = 'Roll';
}
$(this).attr('data-actiontype', rollAction);
$(this).attr('data-rolltype', rollType);
const followingText = $(this)[0].nextSibling?.textContent?.trim()?.split(' ')[0]
const damageType = followingText && window.ddbConfigJson?.damageTypes?.some(d => d.name.toLowerCase() == followingText.toLowerCase()) ? followingText : undefined
if(damageType != undefined){
$(this).attr('data-damagetype', damageType);
}
})
const tokenName = window.all_token_objects && window.all_token_objects[tokenId]?.options?.name ? window.all_token_objects[tokenId]?.options?.name : window.PLAYER_NAME
const tokenImage = window.all_token_objects && window.all_token_objects[tokenId]?.options?.imgsrc ? window.all_token_objects[tokenId]?.options?.imgsrc : window.PLAYER_IMG
const entityType = tokenId ? "monster" : "character";
// terminate the clones reference, overkill but rather be safe when it comes to memory
currentElement = null;
$(target).find(".avtt-roll-button").click(clickHandler);
$(target).find(".avtt-roll-button").on("contextmenu", rightClickHandler);
$(target).find("button.avtt-roll-formula-button").off('click.avttRoll').on('click.avttRoll', function(clickEvent) {
clickEvent.stopPropagation();
const slashCommand = $(clickEvent.currentTarget).attr("data-slash-command");
const followingText = $(clickEvent.currentTarget)[0].nextSibling?.textContent?.trim()?.split(' ')[0]
const damageType = followingText && window.ddbConfigJson.damageTypes.some(d => d.name.toLowerCase() == followingText.toLowerCase()) ? followingText : undefined
const diceRoll = DiceRoll.fromSlashCommand(slashCommand, tokenName, tokenImage, entityType, tokenId, damageType); // TODO: add gamelog_send_to_text() once that's available on the characters page without avtt running
window.diceRoller.roll(diceRoll, undefined, undefined, undefined, undefined, damageType);
});
$(target).find(`button.avtt-roll-formula-button`).off('contextmenu.rpg-roller').on('contextmenu.rpg-roller', function(e){
e.stopPropagation();
e.preventDefault();
let rollData = {}
if($(this).hasClass('avtt-roll-formula-button')){
rollData = DiceRoll.fromSlashCommand($(this).attr('data-slash-command'))
rollData.modifier = `${Math.sign(rollData.calculatedConstant) == 1 ? '+' : ''}${rollData.calculatedConstant}`
}
else{
rollData = getRollData(this)
}
if (rollData.rollType === "damage") {
damage_dice_context_menu(rollData.expression, rollData.modifier, rollData.rollTitle, rollData.rollType, tokenName, tokenImage, entityType, tokenId, damageType)
.present(e.clientY, e.clientX) // TODO: convert from iframe to main window
} else {
standard_dice_context_menu(rollData.expression, rollData.modifier, rollData.rollTitle, rollData.rollType, tokenName, tokenImage, entityType, tokenId)
.present(e.clientY, e.clientX) // TODO: convert from iframe to main window
}
})
console.groupEnd()
}
/**
* Posts a message to the chat when a player connected to the server.
*/
function report_connection() {
if (!is_abovevtt_page())
return;
setTimeout(() => {
let msgdata = {
player: window.PLAYER_NAME,