forked from Roger4325/TaleSpire-VTT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDMScript.js
More file actions
4673 lines (3741 loc) · 175 KB
/
DMScript.js
File metadata and controls
4673 lines (3741 loc) · 175 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
function extractRollResult(message) {
console.log(message)
// Implement a function to extract the roll result from the message
// You might need to parse the message to get the roll result.
// For example, you can use regular expressions or string manipulation.
// The message might be something like "Player rolled a 4 on the dice".
// Extract the number (4) and return it as the roll result.
// This will depend on the format of your messages.
}
let monsterNames
let monsterData
//This function is the first function that is called on load and I have been using as if it is an INIT() function.
async function establishMonsterData(){
const monsterDataObject = AppData.monsterLookupInfo;
monsterNames = monsterDataObject.monsterNames;
monsterData = monsterDataObject.monsterData;
loadAndSetLanguage();
loadDataFromCampaignStorage();
populateConditionsTable();
populateEffectsTable();
populateSchoolofMagicTable();
populateTravelTable()
populateTravelCostTable()
updateShopTable("adventuringSupplies")
await loadTableData()
loadDataFromGlobalStorage('checklists')
.then((checklistData) => {
updateChecklistUI(checklistData);
})
.catch((error) => {
console.error('Error loading checklist data:', error);
});
await loadDataFromGlobalStorage('Shop Data')
.then((shopData) => {
// This function will process the shop data and add it to the categoryGroups
for (const [shopTitle, shopInfo] of Object.entries(shopData)) {
addShopToCategoryGroups(shopTitle, shopInfo);
}
populateShopSelect()
})
.catch((error) => {
console.error('Error loading shop data:', error);
});
// Initialize the event listeners for existing cells
const existingCells = document.querySelectorAll("[contenteditable='true']");
existingCells.forEach(cell => {
tableEditing(cell);
});
loadDataFromCampaignStorage('DmNotes')
.then((groupNotesData) => {
loadNotesGroupData(groupNotesData.groupNotesData)
console.log("here")
})
.catch((error) => {
showErrorModal('Error loading DmNotes data:', error);
});
populateMonsterDropdown()
await mergeOtherPlayers(playersInCampaign)
populatePlayerDropdown()
populateConditionSelect();
populateEquipmentList();
initAbacus();
}
async function loadAndSetLanguage(){
setLanguage(savedLanguage);
}
const messageHandlers = {
'request-stats': handleRequestedStats,
'update-health': handleUpdatePlayerHealth,
'apply-damage': handleApplyMonsterDamage,
'update-init' : handleUpdatePlayerInitiative,
'request-init-list' : handleRequestInitList,
// Add more as needed
};
function handleMessage(message) {
const parsedMessage = JSON.parse(message);
const { type, uuid, data, from } = parsedMessage;
// Check if there's a handler for the message type
if (messageHandlers[type]) {
messageHandlers[type](parsedMessage);
} else {
console.error(`Unhandled message type: ${type}`);
}
}
const playerCharacters = [
{ name: 'Custom', hp: { current: 40, max: 40 }, ac: 14, initiative: 0 ,passivePerception: 0, spellSave: 12}
];
function populateMonsterDropdown() {
console.warn("populateMonsterDropdown")
// Populate the dropdown list with monster names
const monsterList = document.getElementById("monster-list");
const nameInput = document.getElementById("monster-name-input");
const dropdownContainer = document.getElementById("monster-dropdown-container");
monsterList.style.display = 'none'; // Initially hide the dropdown
// Clear the existing list
monsterList.innerHTML = '';
// Populate the dropdown
monsterNames.forEach(monsterName => {
const listItem = document.createElement('li');
listItem.textContent = monsterName;
listItem.addEventListener('click', () => {
nameInput.value = monsterName; // Set the input value to selected monster
createEmptyMonsterCard(monsterName);
monsterList.style.display = 'none'; // Hide the dropdown
});
monsterList.appendChild(listItem);
});
// Show dropdown on focus
if (!nameInput._dropdownEventsAttached) {
nameInput.addEventListener('focus', () => {
monsterList.style.display = 'block';
});
// Filter dropdown items based on input
nameInput.addEventListener('input', () => {
const filterText = nameInput.value.toLowerCase();
monsterList.querySelectorAll('li').forEach(li => {
const monsterName = li.textContent.toLowerCase();
li.style.display = monsterName.includes(filterText) ? 'block' : 'none';
});
});
// Hide dropdown when clicking outside
document.addEventListener('click', (event) => {
if (!dropdownContainer.contains(event.target) && event.target !== nameInput) {
setTimeout(() => {
monsterList.style.display = 'none';
}, 300);
}
});
}
}
// Event listener for saving each encounter
document.getElementById('save-encounter').addEventListener('click', function() {
const savePopup = document.querySelector('.save-popup');
if (savePopup) {
closePopup(); // Close the popup if it's open
} else {
showSavePopup(); // Show the save popup if it's not open
}
});
// Event listener for loading each encounter
document.getElementById('load-encounter').addEventListener('click', function() {
const loadPopup = document.querySelector('.load-popup');
if (loadPopup) {
closePopup(); // Close the popup if it's open
} else {
loadEncountersAndPopulateCards(); // Show the load popup if it's not open
}
});
document.getElementById('rollInitiative').addEventListener('click', () => {
const monsterCards = document.querySelectorAll('.monster-card');
monsterCards.forEach(card => {
// Find the element with the data-name="Initiative"
const initiativeElement = card.querySelector('[data-name="Initiative"]');
if (initiativeElement) {
const diceType = initiativeElement.getAttribute('data-dice-type');
// Use regex to extract the modifier part, which could be positive or negative
const match = diceType.match(/1d20([+-]\d+)/);
// Default initMod to 0 if no modifier is found
const initMod = match ? parseInt(match[1], 10) : 0;
const randomRoll = Math.floor(Math.random() * 20) + 1;
const totalInitiative = randomRoll + initMod;
const initInput = card.querySelector('.init-input');
if (initInput) {
initInput.value = totalInitiative;
} else {
console.log(`Initiative for ${card.id}: ${totalInitiative}`);
}
}
});
reorderCards()
});
let currentTurnIndex = 0; // Track the current turn
let roundCounter = 1; // Track rounds
document.getElementById('next-turn-btn').addEventListener('click', nextTurn);
document.getElementById('previous-turn-btn').addEventListener('click', previousTurn);
makeRoundEditable() //Adding an event listener to the round counter to allow editing the round.
function activateMonsterCard(card){
if (activeMonsterCard) {
activeMonsterCard.style.borderColor = ''; // Reset to default border color
}
// Set this card as the active card
activeMonsterCard = card;
// Change the border color of the active card to red
card.style.borderColor = 'red';
}
function createEmptyMonsterCard(monster) {
// Create the monster card container
const card = document.createElement('div');
card.classList.add('monster-card');
card.addEventListener('click', () => {
activateMonsterCard(card)
});
const tracker = document.getElementById('initiative-tracker');
if (tracker) {
tracker.appendChild(card);
} else {
console.error('Initiative tracker container not found.');
}
if (monster){
updateMonsterCard(card, monster)
}
return card
}
function updateMonsterCard(card, monster) {
// Clear previous content
card.innerHTML = '';
// Check if the monster is a string (name) or an object (full monster data)
let monsterName, selectedMonsterData, monsterCurrentHp, monsterMaxHp, monsterTempHP, newConditionsMap, monsterVisable
if (typeof monster === 'string') {
// If a string is provided, it's just the monster name, so we fetch the data
monsterName = monster;
selectedMonsterData = monsterData[monster]; // Look up monster data by name
monsterCurrentHp = selectedMonsterData.HP.Value
monsterMaxHp = selectedMonsterData.HP.Value
monsterTempHP = 0;
monsterVisable = 0;
} else if (typeof monster === 'object') {
// If an object is provided, use the data from the monster object that we loaded
monsterName = monster.name; // Name from the object
const rearrangedName = monsterName.replace(/\s\([A-Z]\)$/, ''); // Removes the letter in parentheses
selectedMonsterData = monsterData[rearrangedName]; // Get the stored monster data based on the name
monsterCurrentHp = monster.currentHp;
monsterMaxHp = monster.maxHp;
monsterTempHP = monster.tempHp;
newConditionsMap = monster.conditions;
monsterVisable = monster.isClosed;
}
// Handle missing monster data
if (!selectedMonsterData) {
console.error(`Monster data not found for: ${monsterName}`);
return;
}
// Create the monster initiative box
const initDiv = document.createElement('div');
initDiv.classList.add('monster-init');
const initInput = document.createElement('input');
initInput.type = 'number';
initInput.value = monster.init || 0; // Use initiative from the object, if available
initInput.classList.add('init-input');
initInput.addEventListener('change', () => reorderCards());
initDiv.appendChild(initInput);
// Add monster picture
const monsterPictureDiv = document.createElement('div');
monsterPictureDiv.classList.add('monster-picture-div');
const monsterPicture = document.createElement('img');
monsterPicture.classList.add('monster-picture');
monsterPictureDiv.appendChild(monsterPicture);
// Monster info section
const monsterInfo = document.createElement('div');
monsterInfo.classList.add('monster-info');
const monsterNameDiv = document.createElement('div');
monsterNameDiv.classList.add('monster-name');
// Determine the monster name to use
let monsterNameToUse
if(monster.name){
monsterNameDiv.textContent = monster.name
}
else{
monsterNameToUse = selectedMonsterData.Name
const existingNames = Array.from(document.getElementsByClassName('monster-name')).map(nameElem => nameElem.textContent.replace(/\s\([A-Z]\)$/, ''));
const count = existingNames.filter(name => name === monsterNameToUse).length;
monsterNameDiv.textContent = `${monsterNameToUse} (${String.fromCharCode(65 + count)})`;
}
// Add a unique identifier to the monster name
monsterNameDiv.addEventListener('click', function () {
const monsterNameText = monsterNameDiv.textContent.replace(/\s\([A-Z]\)$/, '');
console.log(monsterNameText)
showMonsterCardDetails(monsterNameText);
});
// Stats section (AC, Initiative, Speed)
const statsDiv = document.createElement('div');
statsDiv.classList.add('monster-details');
let monsterInitiative
if(selectedMonsterData.InitiativeModifier < 0){
monsterInitiative = selectedMonsterData.InitiativeModifier;
}
else{
monsterInitiative = "+" + selectedMonsterData.InitiativeModifier;
}
const initiativeButton = parseAndReplaceDice({ name: 'Initiative' }, `Init Mod: ${monsterInitiative} <br>`);
// Check for Spellcasting trait and extract spell save DC
let spellDC = null;
if (selectedMonsterData.Traits) {
for (const trait of selectedMonsterData.Traits) {
if (trait.Name.toLowerCase().includes("spellcasting")) {
const content = trait.Content;
const dcMatch = content.match(/spell save DC (\d+)/i);
if (dcMatch) {
spellDC = dcMatch[1];
break;
}
}
}
}
const statsSpan = document.createElement('span');
statsSpan.classList.add('non-editable');
const acText = document.createTextNode(`${translations[savedLanguage].monsterStatsLabels.AC}: ${selectedMonsterData.AC.Value} | `);
const speedText = document.createTextNode(` ${translations[savedLanguage].monsterStatsLabels.Speed}: ${selectedMonsterData.Speed}`);
statsSpan.appendChild(acText);
// Add Spell Save DC to the stats section if found
if (spellDC) {
const dcSpan = document.createElement('span');
dcSpan.classList.add('spell-dc');
dcSpan.textContent = `${translations[savedLanguage].monsterStatsLabels.DC}: ${spellDC} | `;
statsSpan.appendChild(dcSpan);
}
statsSpan.appendChild(initiativeButton);
statsSpan.appendChild(speedText);
statsDiv.appendChild(statsSpan);
// Create context menu once (place this at the top of your script)
const contextMenu = document.createElement('div');
contextMenu.className = 'custom-context-menu';
contextMenu.style.display = 'none';
document.body.appendChild(contextMenu);
// Add Quick Actions if available
if (selectedMonsterData.QuickAction && Array.isArray(selectedMonsterData.QuickAction)) {
selectedMonsterData.QuickAction.forEach((action) => {
// Create container for the quick action
const quickActionContainer = document.createElement('div');
quickActionContainer.classList.add('quick-action-container');
quickActionContainer.style.display = 'flex';
quickActionContainer.style.gap = '5px';
quickActionContainer.style.alignItems = 'center';
// Action name label
const actionLabel = document.createElement('span');
actionLabel.textContent = (action.Name || 'Quick Action') + ": ";
quickActionContainer.appendChild(actionLabel);
// To Hit section
const toHitLabel = document.createElement('span');
toHitLabel.classList.add('actionButtonLabel');
toHitLabel.setAttribute('data-dice-type', "1d20"+action.ToHit);
toHitLabel.setAttribute('data-name', action.Name);
quickActionContainer.appendChild(toHitLabel);
const toHitButton = document.createElement('button');
toHitButton.classList.add('actionButton');
toHitButton.textContent = action.ToHit;
quickActionContainer.appendChild(toHitButton);
// Damage section
const damageLabel = document.createElement('span');
damageLabel.classList.add('actionButtonLabel');
damageLabel.setAttribute('data-dice-type', action.Damage);
damageLabel.setAttribute('data-name', action.DamageType);
quickActionContainer.appendChild(damageLabel);
const damageButton = document.createElement('button');
damageButton.classList.add('actionButton');
damageButton.textContent = action.Damage;
// Add right-click context menu for crit damage
damageButton.addEventListener('contextmenu', (event) => {
event.preventDefault();
contextMenu.innerHTML = '';
// Double the damage dice
const doubledDice = action.Damage.replace(/(\d+)d(\d+)/g,
(match, rolls, sides) => `${rolls * 2}d${sides}`);
// Create crit label
const critLabel = document.createElement('label');
critLabel.className = "actionButtonLabel damageDiceButton";
critLabel.setAttribute('value', "0");
critLabel.setAttribute('data-dice-type', doubledDice);
critLabel.setAttribute('data-name', damageLabel.getAttribute('data-name'));
// Create crit button
const critButton = document.createElement('button');
critButton.className = 'crit-button actionButton skillbuttonstyler';
critButton.textContent = "Crit";
contextMenu.appendChild(critLabel);
contextMenu.appendChild(critButton);
// Position and show menu
contextMenu.style.left = `${event.pageX}px`;
contextMenu.style.top = `${event.pageY}px`;
contextMenu.style.display = 'block';
rollableButtons(); // Enable rolling for the new crit button
});
quickActionContainer.appendChild(damageButton);
statsDiv.appendChild(quickActionContainer);
});
rollableButtons();
}
// Close context menu on click (add this elsewhere in your script)
document.addEventListener('click', () => {
contextMenu.style.display = 'none';
});
// Add monster name and stats to the monster info
monsterInfo.appendChild(monsterNameDiv);
monsterInfo.appendChild(statsDiv);
const conditionsDiv = document.createElement('div');
conditionsDiv.classList.add('conditions-trackers');
card.appendChild(initDiv);
card.appendChild(monsterPictureDiv);
card.appendChild(monsterInfo);
card.appendChild(conditionsDiv);
// Add conditions from the newConditionsMap back to the card
if (Array.isArray(newConditionsMap)) {
newConditionsMap.forEach(conditionName => {
// Call monsterConditions directly with the condition name
// This assumes monsterConditions has been modified to accept a condition name
if (conditionName) {
activeMonsterCard = card; // Set the active monster card to the current one
monsterConditions(conditionName); // Call with context and value
}
});
}
// HP section
const monsterHP = document.createElement('div');
monsterHP.classList.add('monster-hp');
const currentHPDiv = document.createElement('span');
currentHPDiv.classList.add('current-hp');
currentHPDiv.contentEditable = true;
currentHPDiv.textContent = monsterCurrentHp
const maxHPDiv = document.createElement('span');
maxHPDiv.classList.add('max-hp');
maxHPDiv.contentEditable = true;
maxHPDiv.textContent = monsterMaxHp
currentHPDiv.addEventListener('blur', () => {
// Optionally evaluate the result when the user finishes editing
try {
const currentExpression = currentHPDiv.textContent.trim();
const adjustment = extractAdjustment(currentExpression);
adjustMonsterHealth(adjustment);
}
catch {
currentHPDiv.textContent = 0;
}
});
// Blur on Enter key press
currentHPDiv.addEventListener('keydown', (event) => {
if (event.key === "Enter") {
event.preventDefault(); // Prevent a new line in the contentEditable
currentHPDiv.blur();
}
});
maxHPDiv.addEventListener('blur', () => {
// Optionally evaluate the result when the user finishes editing
try {
const currentExpression = maxHPDiv.textContent.trim();
const adjustment = extractAdjustment(currentExpression);
adjustMonsterHealth(adjustment);
}
catch {
maxHPDiv.textContent = 0;
}
});
// Blur on Enter key press
maxHPDiv.addEventListener('keydown', (event) => {
if (event.key === "Enter") {
event.preventDefault(); // Prevent a new line in the contentEditable
maxHPDiv.blur();
}
});
function extractAdjustment(expression) {
// Trim the expression and match the last operation with its operand
const match = expression.trim().match(/([-+*/]\s*-?\d+)$/);
if (match) {
const adjustment = match[0].replace(/\s+/g, ''); // Remove spaces
return adjustment.startsWith('+') ? adjustment.slice(1) : adjustment; // Remove leading '+' if present
}
return null; // Return null if no match
}
const hpDisplay = document.createElement('div');
hpDisplay.classList.add('hp-display');
hpDisplay.appendChild(currentHPDiv);
hpDisplay.appendChild(document.createTextNode(' / '));
hpDisplay.appendChild(maxHPDiv);
const hpAdjustInput = document.createElement('input');
hpAdjustInput.type = 'number';
hpAdjustInput.classList.add('hp-adjust-input');
hpAdjustInput.placeholder = 'Math +n or -n';
const tempHPDiv = document.createElement('span');
tempHPDiv.classList.add('temp-hp');
tempHPDiv.contentEditable = true;
tempHPDiv.textContent = monsterTempHP || 0; // Use tempHp from the object, if available
const tempHPContainer = document.createElement('div');
tempHPContainer.classList.add('temp-hp-container');
const tempHPText = document.createElement('span'); // Create a span for the text
tempHPText.classList.add('non-editable'); // Add the non-editable class to the span
tempHPText.textContent = 'Temp: '; // Add the text
tempHPContainer.appendChild(tempHPText); // Append the span to the container
tempHPDiv.addEventListener('keydown', (event) => {
if (event.key === "Enter") {
event.preventDefault();
tempHPDiv.blur();
}
});
tempHPDiv.addEventListener('blur', () => {
const value = parseFloat(tempHPDiv.textContent.trim());
if (isNaN(value) || value < 0) {
tempHPDiv.textContent = 0;
}
else {
tempHPDiv.textContent = Math.floor(value);
}
});
tempHPContainer.appendChild(tempHPDiv);
// Add event listener for HP adjustment
hpAdjustInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
const adjustment = parseInt(hpAdjustInput.value, 10);
if (isNaN(adjustment)) return;
adjustMonsterHealth(adjustment)
hpAdjustInput.value = ''; // Clear input
}
});
function adjustMonsterHealth(adjustment){
let currentHP = parseInt(currentHPDiv.textContent, 10) || 0;
const maxHP = parseInt(maxHPDiv.textContent, 10) || selectedMonsterData.HP.Value;
let tempHP = parseInt(tempHPDiv.textContent, 10) || 0; // Get current temp HP
// Subtract from temp HP first, then from current HP if temp HP is depleted
if (adjustment < 0) { // Damage case
let damage = Math.abs(adjustment);
// Subtract damage from temp HP first
if (tempHP > 0) {
const tempHPRemainder = tempHP - damage;
if (tempHPRemainder >= 0) {
tempHP = tempHPRemainder;
damage = 0;
} else {
damage -= tempHP; // Subtract remaining damage after temp HP is depleted
tempHP = 0;
}
}
// If there's still damage left, subtract from current HP
if (damage > 0) {
currentHP = Math.max(0, currentHP - damage);
}
if (currentHP < maxHP / 2) {
monsterConditions("bloodied");
}
if (activeMonsterCard) {
// Find the condition tracker div inside the active monster card
conditionTrackerDiv = activeMonsterCard.querySelector('.condition-tracker');
// Retrieve the condition set from the conditions map for this specific monster
conditionsSet = conditionsMap.get(activeMonsterCard);
if (!conditionsSet) {
console.log('No conditions set for this monster yet.');
} else {
if (conditionsSet.has('Concentration')) {
const dc = Math.max(10, Math.ceil(damage / 2));
showErrorModal(`Roll a Con save. <br> DC: ${dc}`,1000);
}
}
} else {
console.log('No active monster selected.');
conditionTrackerDiv = document.getElementById('conditionTracker');
conditionsSet = conditionsMap.get(conditionTrackerDiv);
}
} else if (adjustment > 0) { // Healing case
currentHP = Math.min(maxHP, currentHP + adjustment); // Heal current HP, but no effect on temp HP
if (currentHP > maxHP / 2) {
console.log(`Monster is at less than half HP. Current HP: ${currentHP}, Max HP: ${maxHP}`);
removeMonsterCondition("Bloodied");
}
}
// Update HP and temp HP displays
currentHPDiv.textContent = currentHP;
tempHPDiv.textContent = tempHP;
}
monsterHP.appendChild(hpDisplay);
monsterHP.appendChild(tempHPContainer);
monsterHP.appendChild(hpAdjustInput);
const eyeAndCloseDiv = document.createElement('div');
eyeAndCloseDiv.classList.add('eye-and-close-buttons');
// Open Eye Button
const openEyeButton = document.createElement('button');
openEyeButton.classList.add('eye-button');
openEyeButton.classList.add('nonRollButton');
if (monsterVisable === 0){
openEyeButton.innerHTML = '<i class="fa fa-eye" aria-hidden="true"></i>';
}
else{
openEyeButton.innerHTML = '<i class="fa fa-eye-slash" aria-hidden="true"></i>';
}
openEyeButton.addEventListener('click', () => {
// Toggle between open and closed eye
if (openEyeButton.querySelector('i').classList.contains('fa-eye')) {
openEyeButton.innerHTML = '<i class="fa fa-eye-slash" aria-hidden="true"></i>';
card.style.opacity = "0.5";
} else {
openEyeButton.innerHTML = '<i class="fa fa-eye" aria-hidden="true"></i>';
card.style.opacity = "1";
}
debouncedSendInitiativeListToPlayer();
});
// Delete button
const deleteButtonDiv = document.createElement('div');
deleteButtonDiv.classList.add('monster-card-delete-button');
const deleteButton = document.createElement('button');
deleteButton.classList.add('nonRollButton');
deleteButton.textContent = "X";
deleteButton.addEventListener('click', () => {
card.remove();
reorderCards();
});
deleteButtonDiv.appendChild(deleteButton);
eyeAndCloseDiv.appendChild(openEyeButton);
eyeAndCloseDiv.appendChild(deleteButtonDiv);
// Add all components to the card in a consistent layout
card.appendChild(monsterHP);
card.appendChild(eyeAndCloseDiv);
reorderCards();
rollableButtons(); // Update rollable buttons after card updates
}
// Event listener for hiding the monster stat block
document.getElementById('closeMonsterCard').addEventListener('click', function() {
toggleMonsterCardVisibility(false);
});
let currentSelectedMonsterName = '';
function showMonsterCardDetails(monsterName) {
// Check if the monster card is currently visible
const monsterCardContainer = document.getElementById('monsterCardContainer');
if (monsterCardContainer.classList.contains('visible') && currentSelectedMonsterName === monsterName) {
// Hide the card if it's already open
toggleMonsterCardVisibility(false);
return; // Exit the function early
}
// Find the monster in the new data source monsterData
const monster = monsterData[monsterName];
if (monster) {
currentSelectedMonsterName = monsterName;
// Populate all fields
populateMonsterFields(monster);
// Show the monster card container
toggleMonsterCardVisibility(true);
} else {
console.error(`Monster data not found for: ${monsterName}`);
}
}
// Toggles the visibility of the monster card
function toggleMonsterCardVisibility(isVisible) {
const monsterCardContainer = document.getElementById('monsterCardContainer');
if (isVisible) {
monsterCardContainer.classList.remove('hidden');
monsterCardContainer.classList.add('visible');
} else {
monsterCardContainer.classList.remove('visible');
monsterCardContainer.classList.add('hidden');
}
}
// Reusable function to populate data conditionally
function populateField(elementId, label, value, isRollable = false) {
const element = document.getElementById(elementId);
if (value || value === 0) {
const labelText = label ? `<strong>${label}:</strong> ` : ''; // Add colon and break only if label exists
if (isRollable) {
// Use parseAndReplaceDice to handle rollable text
element.innerHTML = ''; // Clear the element content
const parsedContent = parseAndReplaceDice({ name: label }, value, true);
const labelNode = document.createElement('span');
labelNode.innerHTML = labelText;
element.appendChild(labelNode);
element.appendChild(parsedContent);
} else {
if (value || value === 0) {
// Only add colon if label is non-empty
const labelText = label ? `<strong>${label}:</strong> ` : '';
if (isRollable) {
element.innerHTML = ''; // Clear content
const parsedContent = parseAndReplaceDice({ name: label }, value, true);
element.appendChild(document.createTextNode(labelText));
element.appendChild(parsedContent);
} else {
const formattedValue = typeof value === 'string'
? value.replace(/,\s*/g, ', ')
: Array.isArray(value) ? value.join(', ') : String(value);
element.innerHTML = `${labelText}${formattedValue}`;
}
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
// Populates monster fields
function populateMonsterFields(monster) {
// Populate basic monster info
populateField('monsterName', '', monster.Name);
populateField('monsterType', '', monster.Type, false);
populateField('monsterAC', `${translations[savedLanguage].monsterStatsLabels["AC"]}`, monster.AC?.Value, false);
populateField('monsterHP', `${translations[savedLanguage].monsterStatsLabels["HP"]}`, `${monster.HP?.Value} ${monster.HP?.Notes}`, true);
populateField('monsterSpeed', `${translations[savedLanguage].monsterStatsLabels["Speed"]}`, monster.Speed);
populateField('monsterLanguages', `${translations[savedLanguage].monsterStatsLabels["Languages"]}`, monster.Languages, false);
populateField('monsterDamageVulnerabilities', `${translations[savedLanguage].monsterStatsLabels["Vulnerabilities"]}`, monster.DamageVulnerabilities, false);
populateField('monsterDamageResistances', `${translations[savedLanguage].monsterStatsLabels["Resistances"]}`, monster.DamageResistances, false);
populateField('monsterDamageImmunities', `${translations[savedLanguage].monsterStatsLabels["Immunities"]}`, monster.DamageImmunities, false);
populateField('monsterConditionImmunities', `${translations[savedLanguage].monsterStatsLabels["Condition Immunities"]}`, monster.ConditionImmunities, false);
populateField('monsterSenses', `${translations[savedLanguage].monsterStatsLabels["Senses"]}`, monster.Senses, false);
populateField('monsterChallenge', `${translations[savedLanguage].monsterStatsLabels["CR"]}`, monster.Challenge||monster.CR, false);
function checkAndPopulateSection(elementId, data, type) {
const container = document.getElementById(elementId);
container.innerHTML = ''; // Always clear previous content
if (data && data.length > 0) {
populateMonsterListField(elementId, data, type);
}
}
populateMonsterListField('monsterAbilityScores', monster.Abilities, 'abilityScores');
checkAndPopulateSection('monsterSkills', monster.Skills, 'skill');
checkAndPopulateSection('monsterSaves', monster.Saves, 'savingThrow');
checkAndPopulateSection('monsterActions', monster.Actions, 'action');
checkAndPopulateSection('monsterReactions', monster.Reactions, 'action');
checkAndPopulateSection('monsterAbilities', monster.Traits, 'traits');
checkAndPopulateSection('monsterLegendaryActions', monster.LegendaryActions, 'legendaryAction');
rollableButtons()
}
// Updated function to populate list fields with various item types
function populateMonsterListField(elementId, items, type) {
const container = document.getElementById(elementId);
container.innerHTML = ''; // Clear previous content
// Check if items exist and are not empty
if (items) {
// Handle if items is an array (Actions, Legendary Actions, Skills, Saving Throws)
if (Array.isArray(items) && items.length > 0) {
items.forEach(item => {
let itemContent;
// Determine the item content based on the type
switch (type) {
case 'traits':
case 'action':
case 'reaction':
case 'legendaryAction':
itemContent = parseAndReplaceDice({ name: item.Name }, `<strong>${item.Name}: </strong>${item.Content}`, true);
break;
case 'savingThrow':
const savemodifier = parseInt(item.Modifier) >= 0 ? `+${item.Modifier}` : item.Modifier;
itemContent = parseAndReplaceDice({ name: item.Name + " Save"}, `<strong>${item.Name} : </strong> ${savemodifier}`);
break;
case 'skill':
const skillmodifier = parseInt(item.Modifier) >= 0 ? `+${item.Modifier}` : item.Modifier;
itemContent = parseAndReplaceDice({ name: item.Name}, `<strong>${item.Name} : </strong> ${skillmodifier}`);
break;
default:
itemContent = document.createElement('div');
itemContent.textContent = item.Name || 'Unknown Item';
}
if (itemContent) {
container.appendChild(itemContent);
// Create and append a <br> element after each item
const lineBreak = document.createElement('br');
container.appendChild(lineBreak);
}
});
container.style.display = '';
}
// Handle if items is an object (Ability Scores)
else if (typeof items === 'object' && !Array.isArray(items)) {
Object.keys(items).forEach(key => {
const abilityScore = items[key];
// Calculate the ability modifier
const modifier = Math.floor((abilityScore - 10) / 2);
const modifierText = modifier >= 0 ? `+${modifier}` : `${modifier}`; // Add "+" for positive numbers, no change for negative
// Create a container for the ability score and rollable modifier
const scoreElement = document.createElement('div');
// Create the static part of the text (ability score)
const staticText = document.createElement('strong');
staticText.textContent = `${key} : `;
scoreElement.appendChild(staticText);
scoreElement.appendChild(document.createTextNode(`${abilityScore} `));
// Use the parseAndReplaceDice function to make the modifier rollable, and append it
const rollableModifier = parseAndReplaceDice({ name: key }, modifierText, true);
scoreElement.appendChild(rollableModifier); // Appends the actual button or label returned by the function
container.appendChild(scoreElement); // Append the entire scoreElement to the container
});
container.style.display = ''; // Ensure the container is displayed
} else {
container.style.display = 'none';
}
} else {
container.style.display = 'none';
}
}
function populatePlayerDropdown() {
const playerList = document.getElementById("player-list");
const nameInput = document.getElementById("player-name-input");
const dropdownContainer = document.getElementById("player-dropdown-container");
playerList.style.display = 'none'; // Initially hide the dropdown
// Clear the existing list
playerList.innerHTML = '';
// Populate the dropdown
playerCharacters.forEach(player => {
const listItem = document.createElement('li');
listItem.textContent = player.name;
listItem.addEventListener('click', () => {
// Find the selected player
const selectedPlayer = playerCharacters.find(p => p.name === listItem.textContent);
console.log(selectedPlayer)
createEmptyPlayerCard(selectedPlayer)
// updatePlayerCard(card, selectedPlayer);
// Hide the dropdown after selection
playerList.style.display = 'none';
});
playerList.appendChild(listItem);
});
nameInput.addEventListener('focus', () => {
playerList.style.display = 'block';
});
nameInput.addEventListener('input', () => {
const filterText = nameInput.value.toLowerCase();
playerList.querySelectorAll('li').forEach(li => {
const playerName = li.textContent.toLowerCase();
li.style.display = playerName.includes(filterText) ? 'block' : 'none';
});
});
document.addEventListener('click', (event) => {
if (!dropdownContainer.contains(event.target) && event.target !== nameInput) {
setTimeout(() => {
playerList.style.display = 'none';
}, 300);
}
});
}