-
Notifications
You must be signed in to change notification settings - Fork 62
/
CharactersPage.js
1630 lines (1475 loc) · 73.7 KB
/
CharactersPage.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
/* CharactersPage.js - scripts that are exclusive to the Characters page */
$(function() {
init_characters_pages();
});
let recentCharacterUpdates = {};
const debounce_add_extras = mydebounce(() => {
if (is_abovevtt_page()) {
$('.add-monster-token-to-vtt').remove();
const extraRows = $('.ct-extra-row')
for(let i=0; i<extraRows.length; i++){
$(extraRows[i]).append($(`<button class='add-monster-token-to-vtt'>+</button>`))
}
let pc = find_pc_by_player_id(my_player_id(), false)
const playerTokenID = pc ? pc.sheet : '';
$('.add-monster-token-to-vtt').off('click.addExtra').on('click.addExtra', async function(e){
e.stopImmediatePropagation();
let tokenPosition = (window.TOKEN_OBJECTS[playerTokenID]) ?
{
x: parseFloat(window.TOKEN_OBJECTS[playerTokenID].options.left) + parseFloat(window.TOKEN_OBJECTS[playerTokenID].options.size)/2,
y: parseFloat(window.TOKEN_OBJECTS[playerTokenID].options.top) + parseFloat(window.TOKEN_OBJECTS[playerTokenID].options.size)/2
} :
center_of_view();
let playerData = await DDBApi.fetchCharacterDetails([window.PLAYER_ID])
let tokenName = $(this).parent().find('.ddbc-extra-name').text().replace("*", '');
let monsterData = playerData[0].extras.creatures.filter(d => d.name == tokenName)[0];
let extraOptions = {
hitPointInfo: {
current: $(this).parent().find('.ct-extra-row__hp-value--current').text(),
maximum: $(this).parent().find('.ct-extra-row__hp-value--total').text(),
},
armorClass: $(this).parent().find('.ct-extra-row__ac').text(),
sizeId: monsterData.sizeId,
name: monsterData.name,
player_owned: true,
share_vision: window.myUser ? window.myUser : true,
hidden: false,
locked: false,
deleteableByPlayers: true,
lockRestrictDrop: "none",
restrictPlayerMove: false
}
if(!window.TOKEN_OBJECTS[playerTokenID])
tokenPosition = convert_point_from_view_to_map(tokenPosition.x, tokenPosition.y)
window.MB.sendMessage("custom/myVTT/place-extras-token", {
monsterData: monsterData,
centerView: tokenPosition,
sceneId: window.CURRENT_SCENE_DATA.id,
extraOptions: extraOptions
});
})
}
}, 100);
const sendCharacterUpdateEvent = mydebounce(() => {
if (window.DM) return;
console.log("sendCharacterUpdateEvent")
const pcData = {...recentCharacterUpdates};
recentCharacterUpdates = {};
if (is_abovevtt_page()) {
window.MB.sendMessage("custom/myVTT/character-update", {
characterId: window.PLAYER_ID,
pcData: pcData
});
update_pc_with_data(window.PLAYER_ID, pcData);
} else {
tabCommunicationChannel.postMessage({
msgType: 'CharacterData',
characterId: window.location.href.split('/').slice(-1)[0],
pcData: pcData
});
}
}, 1500);
/** @param changes {object} the changes that were observed. EX: {hp: 20} */
function character_sheet_changed(changes) {
console.log("character_sheet_changed", changes);
recentCharacterUpdates = {...recentCharacterUpdates, ...changes};
sendCharacterUpdateEvent();
}
function send_character_hp(maxhp) {
const pc = find_pc_by_player_id(find_currently_open_character_sheet(), false); // use `find_currently_open_character_sheet` in case we're not on CharactersPage for some reason
if(maxhp > 0){ //the player just died and we are sending removed node max hp data
character_sheet_changed({
hitPointInfo: {
current: 0,
maximum: maxhp,
temp: 0
},
deathSaveInfo: read_death_save_info()
});
}
else{
character_sheet_changed({
hitPointInfo: {
current: read_current_hp(),
maximum: read_max_hp(pc?.hitPointInfo?.maximum),
temp: read_temp_hp()
},
deathSaveInfo: read_death_save_info()
});
}
}
function read_abilities(container = $(document)) {
const scoreOnTop = container.find(`.ddbc-ability-summary__primary [class*='styles_signed'][class*='styles_large']`).length === 0;
let abilitiesObject = [
{name: 'str', save: 0, score: 0, label: 'Strength', modifier: 0},
{name: 'dex', save: 0, score: 0, label: 'Dexterity', modifier: 0},
{name: 'con', save: 0, score: 0, label: 'Constitution', modifier: 0},
{name: 'int', save: 0, score: 0, label: 'Intelligence', modifier: 0},
{name: 'wis', save: 0, score: 0, label: 'Wisdom', modifier: 0},
{name: 'cha', save: 0, score: 0, label: 'Charisma', modifier: 0}
];
for(let i = 0; i < 6; i++){
if(scoreOnTop){
abilitiesObject[i].score = parseInt($( container.find(`.ddbc-ability-summary__primary button`)[i]).text());
abilitiesObject[i].modifier = parseInt($( container.find(`.ddbc-ability-summary__secondary`)[i]).text());
}
else{
abilitiesObject[i].score = parseInt($( container.find(`.ddbc-ability-summary__secondary`)[i]).text());
abilitiesObject[i].modifier = parseInt($( container.find(`.ddbc-ability-summary__primary button`)[i]).text());
}
abilitiesObject[i].save = parseInt($( container.find(`.ddbc-saving-throws-summary__ability-modifier [class*='styles_numberDisplay']`)[i]).text());
}
return abilitiesObject;
}
function send_abilities() {
character_sheet_changed({abilities: read_abilities()});
}
function read_senses(container = $(document)) {
// this seems to be the same for both desktop and mobile layouts which is nice for once
try {
let changeData = {};
const passiveSenses = container.find(".ct-senses__callouts .ct-senses__callout");
const perception = parseInt($(passiveSenses[0]).find(".ct-senses__callout-value").text());
if (perception) changeData.passivePerception = perception;
const investigation = parseInt($(passiveSenses[1]).find(".ct-senses__callout-value").text());
if (investigation) changeData.passiveInvestigation = investigation;
const insight = parseInt($(passiveSenses[2]).find(".ct-senses__callout-value").text());
if (insight) changeData.passiveInsight = insight;
const senses = container.find(".ct-senses__summary").text().split(",").map(sense => {
try {
const name = sense.trim().split(" ")[0].trim();
const distance = sense.trim().substring(name.length).trim();
return { name: name, distance: distance };
} catch (senseError) {
console.debug("Failed to parse sense", sense, senseError);
return undefined;
}
}).filter(s => s); // filter out any undefined
if (senses.length > 0) {
changeData.senses = senses;
}
return changeData;
} catch (error) {
console.debug("Failed to send senses", error);
return undefined;
}
}
function send_senses() {
const changeData = read_senses();
if (changeData) {
character_sheet_changed(changeData);
}
}
function read_conditions(container = $(document)) {
let conditionsSet = [];
container.find('.ct-conditions-summary .ddbc-condition__name').each(function(){
let level = null;
if($(this).find('.ddbc-condition__level').length>0){
level = parseInt($(this).find('.ddbc-condition__level').text().replace(/\W|\D/gi, ''))
}
conditionsSet.push({
name: $(this).contents().not($(this).children()).text(),
level: level
});
})
return conditionsSet;
}
function read_speeds(container = $(document), speedManagePage) {
speedManagePage = speedManagePage || container.find(".ct-speed-manage-pane");
let speeds = [];
if (speedManagePage.find(".ct-speed-manage-pane__speeds").length > 0) {
// the sidebar is open, let's grab them all
speedManagePage.find(".ct-speed-manage-pane__speed").each(function() {
const container = $(this);
const name = container.find(".ct-speed-manage-pane__speed-label").text();
const distance = parseInt(container.find(".ddbc-distance-number__number").text());
speeds.push({name: name, distance: distance});
});
if (speeds.length) {
return speeds;
}
}
// just update the primary speed
const name = container.find(".ct-speed-box__heading").text();
const distance = parseInt( container.find(".ct-speed-box__box-value .ddbc-distance-number .ddbc-distance-number__number").text() ) || 0;
return [ { name: name, distance: distance } ];
}
function send_movement_speeds(container, speedManagePage) {
let speeds = read_speeds(container, speedManagePage);
if (!speeds) {
return;
}
const pc = find_pc_by_player_id(find_currently_open_character_sheet(), false); // use `find_currently_open_character_sheet` in case we're not on CharactersPage for some reason
if (pc && pc.speeds) {
pc.speeds.forEach(pcSpeed => {
const updatedSpeedIndex = speeds.findIndex(us => us.name === pcSpeed.name);
if (updatedSpeedIndex < 0) { // couldn't read this speed so inject the pc.speeds value
speeds.push(pcSpeed);
}
})
}
if (speeds.length > 0) {
character_sheet_changed({speeds: speeds});
}
}
function read_current_hp(container = $(document)) {
let element = container.find(`.ct-health-manager__health-item.ct-health-manager__health-item--cur .ct-health-manager__health-item-value`)
if(element.length){
return parseInt(element.text())
}
element = container.find(`.ct-health-summary__hp-number[aria-labelledby*='ct-health-summary-current-label']`);
if (element.length) {
return parseInt(element.text()) || 0;
}
element = container.find(`.ct-status-summary-mobile__hp-current`);
if (element.length) {
const hpValue = parseInt(element.text()) || 0;
if (hpValue && container.find(`.ct-status-summary-mobile__hp--has-temp`).length) {
// DDB doesn't display the temp value on mobile layouts so set this to 1 less, so we can at least show that there is temp hp. See `read_temp_hp` for the other side of this
if(container.find('.ct-health-manager__health-item--temp').length){
return hpValue - parseInt(container.find('.ct-health-manager__health-item--temp .ct-health-manager__input').val()); /// if hp side panel is open check this for temp hp
}
return hpValue - 1;
}
return hpValue;
}
return 0;
}
function read_temp_hp(container = $(document)) {
let element = container.find(`.ct-health-manager__health-item.ct-health-manager__health-item--temp .ct-health-manager__health-item-value input.ct-health-manager__input`)
if(element.length){
return parseInt(element.val())
}
element = container.find(`.ct-health-summary__hp-number[aria-labelledby*='ct-health-summary-temp-label']`)
if (element.length) {
return parseInt(element.text()) || 0;
}
if (container.find(`.ct-status-summary-mobile__hp--has-temp`).length) {
if(container.find('.ct-health-manager__health-item--temp').length){
return parseInt(('.ct-health-manager__health-item--temp .ct-health-manager__input').val()); // if hp side panel is open check this for temp hp
}
// DDB doesn't display the temp value on mobile layouts so just set it to 1, so we can at least show that there is temp hp. See `read_current_hp` for the other side of this
return 1;
}
return 0;
}
function read_max_hp(currentMaxValue = 0, container = $(document)) {
let element = container.find(`.ct-health-manager__health-item.ct-health-manager__health-item--max .ct-health-manager__health-item-value .ct-health-manager__health-max-current`)
if(element.length){
return parseInt(element.text())
}
element = container.find(`.ct-health-summary__hp-number[aria-labelledby*='ct-health-summary-max-label']`);
if (element.length) {
return parseInt(element.text()) || currentMaxValue;
}
element = container.find(".ct-status-summary-mobile__hp-max");
if (element.length) {
return parseInt(element.text()) || currentMaxValue;
}
return currentMaxValue;
}
function read_death_save_info(container = $(document)) {
if (container.find(".ct-status-summary-mobile__deathsaves-marks").length) {
return {
failCount: container.find('.ct-status-summary-mobile__deathsaves--fail .ct-status-summary-mobile__deathsaves-mark--active').length || 0,
successCount: container.find('.ct-status-summary-mobile__deathsaves--success .ct-status-summary-mobile__deathsaves-mark--active').length || 0
};
}
return {
failCount: container.find('.ct-health-summary__deathsaves--fail .ct-health-summary__deathsaves-mark--active').length || 0,
successCount: container.find('.ct-health-summary__deathsaves--success .ct-health-summary__deathsaves-mark--active').length || 0
};
}
function read_inspiration(container = $(document)) {
if (container.find(".ct-inspiration__status--active").length) {
return true;
}
if (container.find(".ct-status-summary-mobile__inspiration .ct-status-summary-mobile__button--active").length) {
return true
}
return false;
}
// Good canidate for service worker
async function init_characters_pages(container = $(document)) {
// this is injected on Main.js when avtt is running. Make sure we set it when avtt is not running
if (typeof window.EXTENSION_PATH !== "string" || window.EXTENSION_PATH.length <= 1) {
window.EXTENSION_PATH = container.find("#extensionpath").attr('data-path');
}
// it's ok to call both of these, because they will do any clean up they might need and then return early
init_character_sheet_page();
init_character_list_page_without_avtt();
if(!is_abovevtt_page()){
tabCommunicationChannel.addEventListener ('message', (event) => {
if(event.data.msgType == 'setupObserver'){
if(event.data.tab == undefined && event.data.rpgRoller != true && window.self==window.top){
$(`.integrated-dice__container:not('.above-aoe'):not(.avtt-roll-formula-button)`).off('click.rpg-roller');
$(`.integrated-dice__container:not('.above-aoe'):not(.avtt-roll-formula-button)`).off('contextmenu.rpg-roller')
}else{
convertToRPGRoller();
}
window.EXPERIMENTAL_SETTINGS['rpgRoller'] = event.data.rpgRoller;
if(window.sendToTab != false || event.data.tab == undefined){
window.sendToTab = (window.self != window.top) ? event.data.iframeTab : event.data.tab;
}
if(window.sendToTabRPGRoller != false || event.data.rpgTab == undefined){
window.sendToTabRPGRoller = (window.self != window.top) ? event.data.iframeTab : event.data.rpgTab;
}
}
if(event.data.msgType =='removeObserver'){
$(`.integrated-dice__container:not('.above-aoe'):not(.avtt-roll-formula-button)`).off('click.rpg-roller');
$(`.integrated-dice__container:not('.above-aoe'):not(.avtt-roll-formula-button)`).off('contextmenu.rpg-roller')
delete window.EXPERIMENTAL_SETTINGS['rpgRoller'];
window.sendToTabRPGRoller = undefined;
window.sendToTab = undefined;
setTimeout(function(){
tabCommunicationChannel.postMessage({
msgType: 'isAboveOpen'
});
}, 300)
}
if(event.data.msgType =='disableSendToTab' && window.self == window.top){
window.sendToTab = undefined;
}
})
tabCommunicationChannel.postMessage({
msgType: 'isAboveOpen'
})
window.diceRoller = new DiceRoller();
window.ddbConfigJson = await DDBApi.fetchConfigJson();
}
}
const debounceConvertToRPGRoller = mydebounce(() => {convertToRPGRoller()}, 20)
const debounceRemoveRPGRoller = mydebounce(() => {
$(`.integrated-dice__container:not('.above-aoe'):not(.avtt-roll-formula-button)`).off('click.rpg-roller');
$(`.integrated-dice__container:not('.above-aoe'):not(.avtt-roll-formula-button)`).off('contextmenu.rpg-roller')
delete window.EXPERIMENTAL_SETTINGS['rpgRoller'];
}, 20)
function convertToRPGRoller(){
if(is_abovevtt_page() && window.EXPERIMENTAL_SETTINGS['rpgRoller'] != true){
$(`.integrated-dice__container:not('.above-combo-roll'):not('.above-aoe'):not(.avtt-roll-formula-button)`).off('click.rpg-roller')
$(`.integrated-dice__container:not('.above-combo-roll'):not('.above-aoe'):not(.avtt-roll-formula-button)`).off('contextmenu.rpg-roller')
return;
}
let urlSplit = window.location.href.split("/");
if(urlSplit.length > 0 && !is_abovevtt_page()) {
window.PLAYER_ID = urlSplit[urlSplit.length - 1].split('?')[0];
}
$(`.integrated-dice__container:not('.above-combo-roll'):not('.above-aoe'):not(.avtt-roll-formula-button)`).off('contextmenu.rpg-roller').on('contextmenu.rpg-roller', function(e){
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.expression.match(allDiceRegex) && window.EXPERIMENTAL_SETTINGS['rpgRoller'] != true){
return;
}
e.stopPropagation();
e.preventDefault();
if (rollData.rollType === "damage") {
damage_dice_context_menu(rollData.expression, rollData.modifier, rollData.rollTitle, rollData.rollType, window.PLAYER_NAME, window.PLAYER_IMG)
.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, window.PLAYER_NAME, window.PLAYER_IMG)
.present(e.clientY, e.clientX) // TODO: convert from iframe to main window
}
})
$(`.integrated-dice__container:not('.above-combo-roll'):not('.above-aoe'):not(.avtt-roll-formula-button)`).off('click.rpg-roller').on('click.rpg-roller', function(e){
let rollData = {}
rollData = getRollData(this);
if(!rollData.expression.match(allDiceRegex) && window.EXPERIMENTAL_SETTINGS['rpgRoller'] != true){
return;
}
e.stopImmediatePropagation();
window.diceRoller.roll(new DiceRoll(rollData.expression, rollData.rollTitle, rollData.rollType));
});
}
/** actions to take on the character sheet when AboveVTT is NOT running */
function init_character_sheet_page() {
if (!is_characters_page()) return;
// check for name and image
set_window_name_and_image(function() {
observe_character_sheet_changes($(document));
inject_join_exit_abovevtt_button();
observe_character_theme_change();
observe_character_image_change();
});
// observe window resizing and injeect our join/exit button if necessary
window.addEventListener('resize', function(event) {
inject_join_exit_abovevtt_button();
});
}
/** actions to take on the characters list when AboveVTT is NOT running */
function init_character_list_page_without_avtt() {
inject_join_button_on_character_list_page();
// observe window.location change. DDB dynamically changes the page when you click the View button instead of navigating to a new page
window.oldHref = document.location.href;
if (window.location_href_observer) {
window.location_href_observer.disconnect();
delete window.location_href_observer;
}
window.location_href_observer = new MutationObserver(function(mutationList, observer) {
if (oldHref !== document.location.href) {
if (!is_characters_list_page()) {
console.log("Detected location change from", oldHref, "to", document.location.href);
window.oldHref = document.location.href;
init_characters_pages();
}
else{
init_character_list_page_without_avtt()
}
}
});
window.location_href_observer.observe(document.querySelector("body"), { childList: true, subtree: true });
}
/** Called from our character sheet observer for Dice Roll formulae.
* @param element the jquery element that we observed changes to */
function inject_dice_roll(element, clear=true) {
if (element.find(".integrated-dice__container").length > 0) {
console.debug("inject_dice_roll already has a button")
return;
}
if(element.hasClass("ddbc-note-components__component--damage")){
element.find('.ddbc-damage').toggleClass('above-vtt-visited ddb-note-roll', true);
}
else{
const slashCommands = [...element.text().matchAll(multiDiceRollCommandRegex)];
if (slashCommands.length === 0) return;
console.debug("inject_dice_roll slashCommands", slashCommands);
let updatedInnerHtml = element.text();
for (const command of slashCommands) {
try {
let iconRoll = command[0].startsWith('/ir');
let originalCommand = command[0];
if(iconRoll){
command[0] = command[0].replace(/^(\/ir)/i, '/r')
command[1] = 'r';
}
const diceRoll = DiceRoll.fromSlashCommand(command[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(originalCommand, `<button class='avtt-roll-formula-button integrated-dice__container ${iconRoll ? 'abovevtt-icon-roll' : ''}' title="${diceRoll.action?.toUpperCase() ?? "CUSTOM"}: ${diceRoll.rollType?.toUpperCase() ?? "ROLL"}" data-slash-command="${command[0]}">${diceRoll.expression}</button>`);
} catch (error) {
console.warn("inject_dice_roll failed to parse slash command. Removing the command to avoid infinite loop", command, command[0]);
updatedInnerHtml = updatedInnerHtml.replace(command[0], '');
}
}
if(clear == true){
element.empty();
}
console.debug("inject_dice_roll updatedInnerHtml", updatedInnerHtml);
element.append(updatedInnerHtml);
}
element.find(".integrated-dice__container, .ddb-note-roll").off('click.avttRoll').on('click.avttRoll', function(clickEvent) {
clickEvent.stopPropagation();
if($(this).hasClass('avtt-roll-formula-button')){
const slashCommand = $(clickEvent.currentTarget).attr("data-slash-command");
const diceRoll = DiceRoll.fromSlashCommand(slashCommand, 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
window.diceRoller.roll(diceRoll);
}
else{
let rollData = getRollData(this);
window.diceRoller.roll(new DiceRoll(rollData.expression, rollData.rollTitle, rollData.rollType));
}
});
element.find(`.integrated-dice__container, .ddb-note-roll`).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, window.PLAYER_NAME, window.PLAYER_IMG)
.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, window.PLAYER_NAME, window.PLAYER_IMG)
.present(e.clientY, e.clientX) // TODO: convert from iframe to main window
}
})
}
/**
* Observes character sheet changes and:
* injects Dice Roll buttons when a slash command is in item notes.
* updates window.PLAYER_NAME when the character name changes.
* @param {DOMObject} documentToObserve documentToObserve is `$(document)` on the characters page, and `$(event.target).contents()` every where else */
function observe_character_sheet_changes(documentToObserve) {
if (window.character_sheet_observer) {
window.character_sheet_observer.disconnect();
}
window.character_sheet_observer = new MutationObserver(function(mutationList, observer) {
// console.log("character_sheet_observer", mutationList);
// initial injection of our buttons
const notes = documentToObserve.find(".ddbc-note-components__component:not('.above-vtt-dice-visited')");
notes.each(function() {
// console.log("character_sheet_observer iterating", mutationList);
try {
inject_dice_roll($(this));
$(this).addClass("above-vtt-dice-visited"); // make sure we only parse this element once
} catch (error) {
console.log("inject_dice_roll failed to process element", error);
}
});
if(is_abovevtt_page()){
if($('.dice-rolling-panel').length == 0 && window.diceWarning == undefined){
showDiceDisabledWarning();
}
else if($('.dice-rolling-panel').length > 0){
delete window.diceWarning;
}
}
if(is_abovevtt_page() || window.self != window.top){
const icons = documentToObserve.find(".ddbc-note-components__component--aoe-icon:not('.above-vtt-visited')");
if (icons.length > 0) {
icons.wrap(function() {
if(!window.top?.CURRENT_SCENE_DATA?.fpsq)
return;
$(this).addClass("above-vtt-visited");
const button = $("<button class='above-aoe integrated-dice__container'></button>");
const spellContainer = $(this).closest('.ct-spells-spell')
const name = spellContainer.find(".ddbc-spell-name").first().text()
let color = "default"
const feet = $(this).prev().find("[class*='styles_numberDisplay'] span:first-of-type").text();
const dmgIcon = $(this).closest('.ct-spells-spell').find('.ddbc-damage-type-icon');
if (dmgIcon.length == 1){
color = dmgIcon.attr('class').split(' ').filter(d => d.startsWith('ddbc-damage-type-icon--'))[0].split('--')[1];
}
let shape = $(this).find('svg').first().attr('class').split(' ').filter(c => c.startsWith('ddbc-aoe-type-icon--'))[0].split('--')[1];
shape = window.top.sanitize_aoe_shape(shape)
button.attr("title", "Place area of effect token")
button.attr("data-shape", shape);
button.attr("data-style", color);
button.attr("data-size", Math.round(feet / window.top.CURRENT_SCENE_DATA.fpsq));
button.attr("data-name", name);
// Players need the token side panel for this to work for them.
// adjustments will be needed in enable_Draggable_token_creation when they do to make sure it works correctly
// set_full_path(button, `${RootFolder.Aoe.path}/${shape} AoE`)
// enable_draggable_token_creation(button);
button.css("border-width","1px");
button.click(function(e) {
e.stopPropagation();
// hide the sheet, and drop the token. Don't reopen the sheet because they probably want to position the token right away
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)
if(name == 'Darkness' || name == 'Maddening Darkness' ){
options = {
...options,
darkness: true
}
}
window.top.place_aoe_token_in_centre(options)
// place_token_in_center_of_view only works for the DM
// place_token_in_center_of_view(options)
});
return button;
});
console.log(`${icons.length} aoe spells discovered`);
}
}
const spells = documentToObserve.find(".ct-spells-spell__action:not('.above-vtt-visited')")
if (spells.length > 0){
$(spells).addClass("above-vtt-visited");
$(spells).css({
'-webkit-user-select': 'none',
'-ms-user-select': 'none',
'user-select': 'none',
})
spells.off().on('mouseover.color', function(e){
if(e.shiftKey){
$(this).toggleClass('advantageHover', true)
}
else if(e.ctrlKey || e.metaKey){
$(this).toggleClass('disadvantageHover', true)
}else{
$(this).toggleClass('advantageHover', false)
$(this).toggleClass('disadvantageHover', false)
}
})
spells.off('mouseleave.color').on('mouseleave.color', function(e){
$(this).toggleClass('advantageHover', false)
$(this).toggleClass('disadvantageHover', false)
})
spells.off('click.multiroll').on('click.multiroll', function(e) {
if($(this).children('button').length == 0){
e.stopPropagation();
}
let rollButtons = $(this).parent().find(`.integrated-dice__container:not('.avtt-roll-formula-button'):not('.above-vtt-visited'):not('.above-vtt-dice-visited'):not('.above-aoe'), .integrated-dice__container.abovevtt-icon-roll`);
let spellSave = $(this).parent().find(`.ct-spells-spell__save`);
let spellSaveText;
if(spellSave.length>0){
spellSaveText = `${spellSave.find('.ct-spells-spell__save-label').text().toUpperCase()} DC${spellSave.find('.ct-spells-spell__save-value').text()}`;
}
for(let i = 0; i<rollButtons.length; i++){
let data = getRollData(rollButtons[i]);
let diceRoll;
let damageTypeText = window.diceRoller.getDamageType(rollButtons[i]);
if(data.expression != undefined){
if (/^1d20[+-]([0-9]+)/g.test(data.expression)) {
if(e.altKey){
if(e.shiftKey){
diceRoll = new DiceRoll(`3d20kh1${data.modifier}`, data.rollTitle, data.rollType);
}
else if(e.ctrlKey || e.metaKey){
diceRoll = new DiceRoll(`3d20kl1${data.modifier}`, data.rollTitle, data.rollType);
}
}
else if(e.shiftKey){
diceRoll = new DiceRoll(`2d20kh1${data.modifier}`, data.rollTitle, data.rollType);
}
else if(e.ctrlKey || e.metaKey){
diceRoll = new DiceRoll(`2d20kl1${data.modifier}`, data.rollTitle, data.rollType);
}else{
diceRoll = new DiceRoll(data.expression, data.rollTitle, data.rollType);
}
}
else{
diceRoll = new DiceRoll(data.expression, data.rollTitle, data.rollType)
}
window.diceRoller.roll(diceRoll, true, window.CHARACTER_AVTT_SETTINGS.critRange ? window.CHARACTER_AVTT_SETTINGS.critRange : 20, window.CHARACTER_AVTT_SETTINGS.crit ? window.CHARACTER_AVTT_SETTINGS.crit : 2, spellSaveText, damageTypeText);
spellSaveText = undefined;
}
}
if(rollButtons.length == 0 && spellSaveText != undefined){
let msgdata = {
player: window.PLAYER_NAME,
img: window.PLAYER_IMG,
text: `<div class='custom-spell-save-text' style='font-weight:600'><span>Casts ${$(this).parent().find('[class*="styles_spellName"]').text()}: </span><span>${spellSaveText}</span></div>`,
playerId: window.PLAYER_ID,
sendTo: window.sendToTab
}
if(is_abovevtt_page()){
window.MB.inject_chat(msgdata)
}
else if(window.sendToTab != undefined){
tabCommunicationChannel.postMessage({
msgType: 'SendToGamelog',
player: msgdata.player,
img: msgdata.img,
text: msgdata.text,
sendTo: msgdata.sendTo
});
}
}
});
if($(`style#advantageHover`).length == 0){
$('body').append(`
<style id='advantageHover'>
.ddbc-combat-attack__icon.above-vtt-visited,
.ct-spells-spell__action.above-vtt-visited .ct-spells-spell__at-will{
border: 1px solid var(--theme-color, #ddd);
border-radius: 5px;
padding: 3px;
margin: 0px 2px 0px 0px;
}
#site .advantageHover svg [fill="#b0b7bd"],
#site .advantageHover svg [fill="#242528"],
#site .advantageHover svg .prefix__st0,
#site .advantageHover svg .prefix__st2,
#site .advantageHover svg .prefix__st4,
#site .advantageHover svg [fill="#b0b7bd"] *,
#site .advantageHover svg [fill="#242528"] *{
fill: #4fcf4f !important;
}
#site .advantageHover {
color: #4fcf4f !important;
}
#site .disadvantageHover svg [fill="#b0b7bd"],
#site .disadvantageHover svg [fill="#242528"],
#site .disadvantageHover svg .prefix__st0,
#site .disadvantageHover svg .prefix__st2,
#site .disadvantageHover svg .prefix__st4,
#site .disadvantageHover svg [fill="#b0b7bd"] *,
#site .disadvantageHover svg [fill="#242528"] *{
fill: #bb4242 !important;
}
#site .disadvantageHover {
color: #4fcf4f !important;
}
</style>`);
}
}
const spellDamageButtons = $(`.ddbc-spell-damage-effect .integrated-dice__container:not('.above-vtt-visited-spell-damage')`)
if(spellDamageButtons.length > 0){
$(spellDamageButtons).addClass("above-vtt-visited-spell-damage");
spellDamageButtons.off('click.spellSave').on('click.spellSave', function(e){
let spellSave = $(this).closest('.ddbc-combat-attack, .ct-spells-spell').find(`[class*='__save']`);
let spellSaveText;
if(spellSave.length>0){
spellSaveText = `${spellSave.find('[class*="__save-label"]').text().toUpperCase()} DC${spellSave.find('[class*="__save-value"]').text()}`;
}
window.diceRoller.setPendingSpellSave(spellSaveText);
})
}
const damageButtons = $(`.ddb-note-roll:not('.above-vtt-visited-damage'), .integrated-dice__container:not('.above-vtt-visited-damage')`)
if(damageButtons.length > 0){
$(damageButtons).addClass("above-vtt-visited-damage");
damageButtons.off('click.damageType').on('click.damageType', function(e){
window.diceRoller.getDamageType(this);
})
}
const attackIcons = documentToObserve.find(".ddbc-combat-attack__icon:not('.above-vtt-visited')")
if (attackIcons.length > 0){
if(!window.CHARACTER_AVTT_SETTINGS){
window.CHARACTER_AVTT_SETTINGS = {}
}
if($('#icon-roll-optons').length == 0){
let urlSplit = window.location.href.split("/");
window.PLAYER_ID = urlSplit[urlSplit.length - 1].split('?')[0];
window.CHARACTER_AVTT_SETTINGS = $.parseJSON(localStorage.getItem("CHARACTER_AVTT_SETTINGS" + window.PLAYER_ID));
if(!(typeof window.CHARACTER_AVTT_SETTINGS === 'object') || window.CHARACTER_AVTT_SETTINGS === null){
window.CHARACTER_AVTT_SETTINGS = {};
}
let settingOption = {
"versatile":{
label: "Versatile rolls",
type: "dropdown",
options: [
{ value: "both", label: "Roll both damages", description: "Both 1 and 2 handed rolls will be rolled." },
{ value: "1", label: "1-Handed", description: "1-handed rolls will be rolled." },
{ value: "2", label: "2-Handed", description: "2-handed rolls will be rolled." }
],
defaultValue: "both"
},
"crit":{
label: "Crit Type",
type: "dropdown",
options:[
{ value: "0", label: "Double damage dice", description: "Doubles damage dice for crits." },
{ value: "1", label: "Perfect Crits", description: "Rolls the original dice and adds a max roll" },
{ value: "3", label: "Double total damage", description: "Rolls the original dice adds modifier then doubles it" },
{ value: "2", label: "Manual", description: "Rolls are not modified based on crit" },
],
defaultValue: "0"
},
"critRange":{
label: "Crit Range",
type: "input",
inputType: 'number',
max: '20',
min: '1',
step: '1',
defaultValue: "20"
}
}
let options = $(`<div id='icon-roll-options'
style= 'z-index: 100000;
width: 20%;
height: 20%;
width: 300px;
height: 300px;
position: fixed;
display: none;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: var(--theme-background-solid);
box-shadow: 0px 0px 4px var(--theme-contrast);
padding-right: 5px;
border-radius: 15px;
border: 1px solid var(--theme-contrast);
color: var(--theme-contrast);
'>
</div>`)
let closeOptions = $(`<div id='close-icon-roll-options'
style='z-index: 99999;
height: 100%;
width: 100%;
position: fixed;
top: 0px;
left: 0px;
background: rgba(0, 0, 0, 0.4);
display: none;'/>`)
closeOptions.off().on('click', function(){
options.css('display', 'none');
closeOptions.css('display', 'none');
})
options.append(closeOptions);
$('body').append(closeOptions, options);
for(let i in settingOption){
if(window.CHARACTER_AVTT_SETTINGS[i] == undefined){
window.CHARACTER_AVTT_SETTINGS[i] = settingOption[i].defaultValue;
}
let wrapper = $(`
<div id='${i}Setting' style='font-size: 14px;display:flex; margin: 10px 0px 10px 0px;align-items: center;' data-option-name="${i}">
<div style="margin-right: 3px; margin-left: 10px; flex-grow: 1;font-weight: 700;font-size: 14px;">${settingOption[i].label}:</div>
</div>
`);
let input;
if(settingOption[i].type == 'dropdown'){
input = $(`<select name="${i}" style='font-size: 14px; padding:0px'></select>`);
for (const option of settingOption[i].options) {
input.append(`<option value="${option.value}">${option.label}</option>`);
}
if (window.CHARACTER_AVTT_SETTINGS[i] !== undefined) {
input.find(`option[value='${window.CHARACTER_AVTT_SETTINGS[i]}']`).attr('selected','selected');
}
const currentlySetOption = settingOption[i].options.find(o => o.value === window.CHARACTER_AVTT_SETTINGS[i]) || settingOption[i].options.find(o => o.value === settingOption[i].defaultValue);
input.change(function(event) {
let newValue = event.target.value;
window.CHARACTER_AVTT_SETTINGS[i] = newValue;
localStorage.setItem("CHARACTER_AVTT_SETTINGS" + window.PLAYER_ID, JSON.stringify(window.CHARACTER_AVTT_SETTINGS));
const updatedOption = settingOption[i].options.find(o => o.value === newValue) || settingOption[i].options.find(o => o.value === settingOption[i].defaultValue);
});
}
else if(settingOption[i].type == 'input'){
input = $(`<input min='${settingOption[i].min}' max='${settingOption[i].max}' step='${settingOption[i].step}' type='${settingOption[i].inputType}' value='${window.CHARACTER_AVTT_SETTINGS[i]}'/>`)
input.change(function(event) {
let newValue = event.target.value;
window.CHARACTER_AVTT_SETTINGS[i] = newValue;
localStorage.setItem("CHARACTER_AVTT_SETTINGS" + window.PLAYER_ID, JSON.stringify(window.CHARACTER_AVTT_SETTINGS));
});
}
wrapper.append(input);
options.append(wrapper)
}
let optionsInfo = $(`<div style='font-size: 11px; margin: 10px; align-items: flex-start; display: flex; flex-direction: column;'>
<div style='margin-bottom:5px;'>• These settings only apply to rolls made with icons/cast buttons to the left of actions/spells.</div>
<div style='margin-bottom:5px;'>• Perfect Crits is a normal roll + max roll on crit dice</div>
<div style='margin-bottom:5px;'>• Double Damage Total is 2*(dice damage+mod)</div>
<div style='margin-bottom:5px;'>• Hold Shift/Ctrl to roll ADV/DIS respectively.</div>
<div style='margin-bottom:5px;'>• Hold Alt + Shift/Ctrl to roll Super ADV/DIS respectively</div>
</div>`)
options.append(optionsInfo);
}
if($('#avtt-icon-roll-span').length == 0){
let settings = $(`<span id='avtt-icon-roll-span' style="font-weight: 700;font-size: 11px;">AVTT Icon Roll Settings <span style='font-size: 11px;'class="ddbc-manage-icon__icon "></span></span>`)
settings.off().on('click', function(){
$('#close-icon-roll-options').css('display', 'block');
$('#icon-roll-options').css('display', 'block');
})
$('.ct-primary-box__tab--actions .ct-actions h2').after(settings)
}
$(attackIcons).addClass("above-vtt-visited");
$(attackIcons).css({
'-webkit-user-select': 'none',
'-ms-user-select': 'none',
'user-select': 'none',
})
attackIcons.off().on('mouseover.color', function(e){
if(e.shiftKey){
$(this).toggleClass('advantageHover', true)
}
else if(e.ctrlKey || e.metaKey){
$(this).toggleClass('disadvantageHover', true)
}else{
$(this).toggleClass('advantageHover', false)
$(this).toggleClass('disadvantageHover', false)
}
})
attackIcons.off('mouseleave.color').on('mouseleave.color', function(e){
$(this).toggleClass('advantageHover', false)
$(this).toggleClass('disadvantageHover', false)
})
attackIcons.off('click.multiroll contextmenu.multiroll').on('click.multiroll contextmenu.multiroll', function(e) {
e.preventDefault();
e.stopPropagation();
let versatileRoll = window.CHARACTER_AVTT_SETTINGS.versatile;
let rollButtons = $(this).parent().find(`.integrated-dice__container:not('.avtt-roll-formula-button'):not('.above-vtt-visited'):not('.above-vtt-dice-visited'):not('.above-aoe'), .integrated-dice__container.abovevtt-icon-roll`);
let spellSave = $(this).parent().find(`[class*='__save']`);
let spellSaveText;
if(spellSave.length>0){
spellSaveText = `${spellSave.find('[class*="__save-label"]').text().toUpperCase()} DC${spellSave.find('[class*="__save-value"]').text()}`;
}
for(let i = 0; i<rollButtons.length; i++){
let isVersatileDamage = $(rollButtons[i]).parent().hasClass('ddb-combat-item-attack__damage--is-versatile')
if(isVersatileDamage && versatileRoll =='1'){
if($(rollButtons[i]).parent().find('.integrated-dice__container:first-of-type')[0] != rollButtons[i])
continue;
}
else if(isVersatileDamage && versatileRoll =='2'){
if($(rollButtons[i]).parent().find('.integrated-dice__container:first-of-type')[0] == rollButtons[i])
continue;
}
let data = getRollData(rollButtons[i]);
let damageTypeText = window.diceRoller.getDamageType(rollButtons[i]);
let diceRoll;
if(data.expression != undefined){
if (/^1d20[+-]([0-9]+)/g.test(data.expression)) {
if(e.altKey){