-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdarksheet.js
More file actions
2037 lines (1843 loc) · 82.7 KB
/
darksheet.js
File metadata and controls
2037 lines (1843 loc) · 82.7 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
import {
applications
} from "../../../../systems/dnd5e/dnd5e.mjs"
let activateDDTab = false;
//Register Sheet
Hooks.once('init', function() {
//console.log("Darker DnD | Initializing Darker Dungeons for the D&D 5th Edition System\n", "_____________________________________________________________________________________________\n", " ____ _ ____ \n", " | _ \\ __ _ _ __ | | __ ___ _ __ | _ \\ _ _ _ __ __ _ ___ ___ _ __ ___ \n", " | | | | / _` || '__|| |/ // _ \| '__| | | | || | | || '_ \\ / _` | / _ \\ / _ \\ | '_ \\ / __| \n", " | |_| || (_| || | | <| __/| | | |_| || |_| || | | || (_| || __/| (_) || | | |\\__ \\ \n", " |____/ \\__,_||_| |_|\\_\\\\___||_| |____/ \\__,_||_| |_| \\__, | \\___| \\___/ |_| |_||___/ \n", " |___/ \n", "_____________________________________________________________________________________________");
/*Actors.registerSheet('dnd5e', darksheet, {
types: ['character']
});*/
game.settings.register('darksheet', 'slotbasedinventory', {
name: 'Inventory Slot System',
hint: 'When enabled, the inventory will use a slot-based system instead of a weight-based system.',
scope: 'world',
config: true,
default: true,
type: Boolean,
});
game.settings.register('darksheet', 'equippedDontUseSlots', {
name: 'Equipped Item Behaviour',
hint: 'When enabled, equipped items dont count towards your carry capacity.',
scope: 'world',
config: true,
default: true,
type: Boolean,
});
/*game.settings.register('darksheet', 'ActiveInitiativeHadTurn', { //ACTIVE INITIATIVE
name: 'Saved Active Initiative Value',
hint: 'Do not modify. This value saves the turn order for Active Initiative.',
scope: 'world',
config: false,
default: "",
type: String,
});
game.settings.register('darksheet', 'activeInitiative', {
name: 'Active Initiative [TESTING]',
hint: 'Enables Active Initiative, a system for dynamic turn order during combat.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'activeInitiativeDisplayTurns', {
name: 'Additional Active Initiative Display',
hint: 'When enabled, additional actor information is displayed during Active Initiative.',
scope: 'world',
config: true,
default: true,
type: Boolean,
});*/
game.settings.register('darksheet', 'automaticSlots', {
name: 'Automatic Slot Calculation',
hint: 'When enabled, tries to automatically add slots to items in inventory by using a db.',
scope: 'world',
config: true,
default: true,
type: Boolean,
});
game.settings.register('darksheet', 'automaticFragility', {
name: 'Automatic Item Fragility',
hint: 'When enabled, tries to automatically add delicate and sturdy fragility to items in inventory by using a db.',
scope: 'world',
config: true,
default: true,
type: Boolean,
});
game.settings.register('darksheet', 'savecantrips', {
name: 'Variant Rule: Safe Cantrips',
hint: 'Disables the use of the d12 burnout die for cantrips when enabled.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'hidenotches', {
name: 'Hide Notches',
hint: 'When enabled, the notches on inventory items and item sheets are hidden.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'disableItemDamage', {
name: 'Disable item Damage',
hint: 'Turns off the display of information for item damage, fragility, and condition in the inventory.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'hideammodie', { //TODO hideammodie Setting
name: 'Hide Ammunition Die',
hint: 'When enabled, the ammunition die section is hidden from player inventories and item sheets.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'hidechecks', {
name: 'Hide "Checks" Section from Character Sheets',
hint: 'When enabled, the "checks" section is hidden from all character sheets.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
/*game.settings.register('darksheet', 'nonpcattack', {//TODO NPCATTACK setting
name: 'Disable NPC Attacks',
hint: 'When enabled, only roll damage when using NPC attacks. This feature only supports the BetterNPCSheet5e module.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});*/
game.settings.register('darksheet', 'smalldefense', {
name: 'Variant Rule: Small Defense',
hint: 'When enabled, smaller modifiers are used while playing with Active Defense. Defense Rolls: When you make a defense roll, roll a d20 and add your AC minus 10. The opposing DC is 12 plus the attackers normal attack bonus.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'destroyshatter', {
name: 'Shattered Items Do Not Destroy',
hint: 'When enabled, shattered items with [Shattered] in their name are kept instead of being deleted.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'shatterwhen1', {
name: '[Houserule] Shatter When 1',
hint: 'When enabled, items shatter when they reach 1 AC or 1 damage regardless of fragility.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'disableWoundSystem', {
name: 'Disable Wound System',
hint: 'Disables wounds and prevents them to be rendered on the sheet.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
/*
game.settings.register('darksheet', 'silverstandard', { //TODO silverstandard setting
name: '[Houserule] Silver Standard',
hint: 'When enabled, all items will have sp (silver pieces) value instead of gp (gold pieces).',
scope: 'world',
config: true,
default: false,
type: Boolean,
});*/
//TODO IMPLEMENT DARKSCREEN
/*game.settings.register('darksheet', 'globalTemp', { //TODO GM MANAGED TEMPERATURE
name: 'GM-Managed Temperature',
hint: 'When enabled, players can no longer select their temperature on their character sheets. You can still change the regional magic as the GM or with the Darkscreen.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'globalRegMagic', { //TODO GM MANAGED TEMPERATURE
name: 'GM-Managed Regional Magic',
hint: 'When enabled, players can no longer select regional magic on their character sheets. You can still change the regional magic as the GM or with the Darkscreen.',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'afflictionFromComp', { //TODO AFFLICTION AUTO APPLY
name: 'Afflictions from Compendium',
hint: 'When enabled, rolls from the Afflictions compendium instead of the rollable table and displays the compendium entry in chat.',
scope: 'world',
config: false,
default: false,
type: Boolean,
});*/
game.settings.register('darksheet', 'darkScreenPartyDisplay', {
name: 'Online Character Filter',
hint: 'Displays only the online characters in the party view',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
});
Hooks.once('init', () => {
loadTemplates([
'modules/darksheet/templates/Tab_DD.html',
'modules/darksheet/templates/character-sheet.html'
]);
});
Hooks.on(`renderActorSheet`, (app, html, data) => {
if (app.actor.type != 'character') return;
const element = document.querySelector('a.item.active');
if (element) {
element.focus();
}
//This way to reactivate the tab is inspired by Ethck's 5e Downtime Tracking Module
addDarkSheetTab(app, html, data).then(function() {
if (app.activateDDTab) {
app._tabs[0].activate("dd");
}
});
addStressBar(app, html, data);
applyInventoryAdditions(app, html, data);
applyFatigueAndTemperatureAdditions(app, html, data);
applySpellBurnoutToSheet(app, html, data);
darkSheetSetup(app, html, data);
if (!game.settings.get('darksheet', 'disableWoundSystem')) {
addWoundsToSheet(app, html, data);
}
setTimeout(() => {
// Blur the active element after reload
document.activeElement.blur();
}, 0);
});
async function applySpellBurnoutToSheet(app, html, data) {
let container = html.find(".spells").find(".top");
let inventoryAdditionsTemplate = await renderTemplate("modules/darksheet/templates/spellburnout.html", data);
// Convert the HTML string into DOM elements
let tempDiv = document.createElement("div");
tempDiv.innerHTML = inventoryAdditionsTemplate;
container.append(tempDiv.children)
}
async function applyFatigueAndTemperatureAdditions(app, html, data) {
let container = html.find(".main-content").find(".tab-body").find(".details").find(".right").find(".flexrow");
let inventoryAdditionsTemplate = await renderTemplate("modules/darksheet/templates/fatigue.html", data);
// Convert the HTML string into DOM elements
let tempDiv = document.createElement("div");
tempDiv.innerHTML = inventoryAdditionsTemplate;
container.append(tempDiv.children)
}
async function applyInventoryAdditions(app, html, data) {
let inventoryContainer = html.find(".inventory-element");
if (inventoryContainer.length > 0) {
let inventoryAdditionsTemplate = await renderTemplate("modules/darksheet/templates/inventoryAdditions.html", data);
// Convert the HTML string into DOM elements
let tempDiv = document.createElement("div");
tempDiv.innerHTML = inventoryAdditionsTemplate;
// Get the 4th child position (index 3, since it's zero-based)
let children = inventoryContainer.children();
if (children.length >= 2) {
children.eq(2).after(tempDiv.children);
} else {
// If there are fewer than 4 children, append at the end
inventoryContainer.append(tempDiv.children);
}
}
}
async function addStressBar(app, html, data) {
let stressValue = data.actor.flags.darksheet?.attributes?.stress ?? 0;
// Determine the next stress max threshold
let stressMax = 20;
if (stressValue >= 35) stressMax = 40;
else if (stressValue >= 30) stressMax = 35;
else if (stressValue >= 20) stressMax = 30;
// Calculate the stress bar width as a percentage
let stressBarWidth = (stressValue / stressMax) * 100;
if (stressBarWidth > 100) stressBarWidth = 100; // Ensure it doesn't exceed 100%
// Determine the color based on severity
let stressColor = "#228B22"; // Deep Green (Safe)
if (stressValue >= 10) stressColor = "#B8860B"; // Dark Yellow (Mild Stress)
if (stressValue >= 20) stressColor = "#D2691E"; // Dark Orange (High Stress)
if (stressValue >= 30) stressColor = "#8B0000"; // Red (Critical Stress)
data.stressBarWidth = stressBarWidth;
data.stressColor = stressColor;
// Flags to determine which afflictions to show
data.showAffliction1 = stressValue >= 20 || data.actor.flags.darksheet.attributes.affliction1?.value !== "default";
data.showAffliction2 = stressValue >= 30 || data.actor.flags.darksheet.attributes.affliction2?.value !== "default";
data.showAffliction3 = stressValue >= 35 || data.actor.flags.darksheet.attributes.affliction3?.value !== "default";
data.showBreakingPoint = stressValue >= 40;
// Inject computed values
data.stressMax = stressMax;
let meterGroup = html.find(".meter-group").eq(1);
if (meterGroup.length > 0) {
let stressBarTemplate = await renderTemplate("modules/darksheet/templates/stressbar.html", data);
meterGroup.append(stressBarTemplate);
}
// **Get stress input & value span**
let stressInput = html.find("#darkStressbar");
let stressValueSpan = html.find(".darkStressValue");
// **Clicking on meter hides span and focuses input**
html.find(".stress-points").on("click", () => {
stressValueSpan.hide();
stressInput.show().focus();
});
// **Handle input blur (hide input, show span)**
stressInput.on("blur", async (ev) => {
let newValue = ev.target.value;
let stressValue = parseInt(newValue, 10);
if (!isNaN(stressValue)) {
await app.actor.update({
'flags.darksheet.attributes.stress': stressValue
});
}
stressInput.hide();
stressValueSpan.show();
});
// **Pressing Enter submits and hides input**
stressInput.on("keypress", async (ev) => {
if (ev.key === "Enter") {
let newValue = ev.target.value;
let stressValue = parseInt(newValue, 10);
if (!isNaN(stressValue)) {
await app.actor.update({
'flags.darksheet.attributes.stress': stressValue
});
}
stressInput.hide();
stressValueSpan.text(stressValue).show();
}
});
// Hide input field initially
stressInput.hide();
}
Hooks.on(`renderItemSheet5e2`, (app, html, data) => {
//Insert additional data
loadItemData(app, html, data);
});
Hooks.on('preCreateChatMessage', (app, html, data) => {
//console.log("Chat Message Detected");
let actor = game.actors.get(app.speaker.actor);
let item = actor.items.get(html.flags.dnd5e.item.id);
let spellburnout = false;
let iscantrip = false;
if (item == null) return;
if (item.system.level == 0) {
iscantrip = true;
}
if (item.type == "spell") {
spellburnout = true;
} else {
return;
}
if (!iscantrip && spellburnout && actor.flags.darksheet.attributes.autmomaticburnout && app.user.id === game.user.id || iscantrip && !game.settings.get('darksheet', 'savecantrips') && actor.flags.darksheet.attributes.autmomaticburnout && app.user.id === game.user.id) {
//console.log("[Darksheet] Rolling automatic burnout for " + actor.name);
rollBurnout(actor);
}
});
async function loadItemData(app, html, data) {
console.log("Loading Darksheet item data...");
if (data.item.type == "Spell" || data.item.type == "Feature") return; //DISABLE SPELL AND FEATURES
data.NotEditable = !data.cssClass.includes("editable");
let itemDataTemplate = await renderTemplate("modules/darksheet/templates/itemdata.html", data);
const firstElement = html.find('.sheet-header').first();
if (firstElement.length > 0) {
firstElement.append(itemDataTemplate); // Append at the end instead of prepending
} else {
html.find('.item-properties').append(itemDataTemplate); // Fallback
}
}
async function addWoundsToSheet(sheet, html, data) {
let actor = sheet.actor;
let woundlist = actor.flags.darksheet.woundlist;
//console.log(actor.flags.darksheet);
if (html.find("woundsection").count == 2) return;
if (actor.flags.darksheet.woundlist == undefined) {
await actor.update({
'flags.darksheet.woundlist': []
});
}
if (actor.flags.darksheet.displayOldWounds == undefined) {
await actor.update({
'flags.darksheet.displayOldWounds': false
});
}
//RENDER WOUNDS
var woundBarDiv = document.createElement("div");
woundBarDiv.classList.add("pills-group", "woundsection", "woundS1");
woundBarDiv.innerHTML = '<button type="button" class="rollable button" title="Click to roll for reopened wounds" class="deathsavelabel woundroll rollReopenWounds rollable" actorid="' + actor.id + '">Reopen Wounds</button><button type="button" class="rollable button addwoundbutton" id="addwound" actorID="' + sheet.actor.id + '"><i class="fas fa-plus"></i> Add Wound</button>';
let woundTable = await renderTemplate("modules/darksheet/templates/wounds.html", data);
let countersSection = html.find(".main-content").find(".tab-body").find(".details").find(".right").find(".flexrow");
countersSection.after(woundTable);
countersSection.after(woundBarDiv);
let woundList = html.find(".woundlist");
for (let count = 0; count < woundlist.length; count++) {
let wound = woundlist[count];
let label = wound.treated == false ? '<label class="exhaustiontip">+1 Exh.</label>' : '';
let treated = wound.treated == true ? 'checked' : '';
if (!wound.healed)
await woundList.append('<tr id="woundtr"><td><input type="text" id="wounddes' + count + '" name="' + count + '" value="' + wound.location + '" placeholder="Where is this wound?"></td><td><input class="woundcheckbox" name="' + count + '" id="woundcheck' + count + '" type="checkbox" data-dtype="Boolean" ' + treated + '/></td><td><input class="removewoundbutton" name="' + count + '" type="button" id="wound1"value=""><i class="fa-light fa-bandage healWoundButton"></i></td><td>' + label + '</td></th></tr>');
woundList.find("#wounddes" + count).on("change", async (ev) => {
ev.preventDefault();
// Handle the input change event
//console.log("Input value changed:", ev.target.value);
let actor = game.actors.get(ev.currentTarget.closest(".woundlist").getAttribute("actorid"));
let _woundlist = actor.flags.darksheet.woundlist ? actor.flags.darksheet.woundlist : [];
// EDIT WOUND
_woundlist[ev.currentTarget.name].location = ev.target.value;
await actor.setFlag('darksheet', 'woundlist', woundlist, {
diff: true
});
await document.activeElement.blur();
});
woundList.find("#woundcheck" + count).on("change", async (ev) => {
ev.preventDefault();
let actor = game.actors.get(ev.currentTarget.closest(".woundlist").getAttribute("actorid"));
let _woundlist = actor.flags.darksheet.woundlist ? actor.flags.darksheet.woundlist : [];
_woundlist[ev.currentTarget.name].treated = ev.target.checked;
await actor.setFlag('darksheet', 'woundlist', woundlist, {
diff: true
});
await document.activeElement.blur();
});
woundList.find(".removewoundbutton[name='" + count + "']").on("click", async (ev) => {
ev.preventDefault();
let actor = game.actors.get(ev.currentTarget.closest(".woundlist").getAttribute("actorid"));
let _woundlist = actor.flags.darksheet.woundlist ? actor.flags.darksheet.woundlist : [];
// EDIT WOUND
_woundlist[ev.currentTarget.name].healed = true;
getTimeStamp().then((timestamp) => {
_woundlist[ev.currentTarget.name].healedDate = timestamp;
});
await actor.update({
'flags.darksheet.woundlist': woundlist
});
await document.activeElement.blur();
});
}
if (actor.flags.darksheet.displayOldWounds) {
await woundList.append('<tr id="oldwounds" actorid="' + actor.id + '"><td colspan="4" class="oldWoundsColspan"><label class="oldWoundsLabel">Old Wounds</label><i class="fas fa-angle-down" style="margin-top: -8px; font-size:14px; padding:5px"></i></td></tr>');
for (let count = 0; count < woundlist.length; count++) {
let wound = woundlist[count];
let label = wound.treated == true ? '<label class="exhaustiontip">+1 Exh.</label>' : '';
let treated = wound.treated == true ? 'checked' : '';
if (wound.healed) {
let datesInfo = "Gained: " + wound.gainedDate + " | Healed: " + wound.healedDate;
let _wound = await html.find(".woundlist").append('<tr id="oldwoundtr"><td><input type="text" id="wounddes' + count + '" name="' + count + '" value="' + wound.location + '" disabled placeholder="Where is this wound?"></td><td style="color:grey;">Healed</td><td><input class="removewoundbutton" name="' + count + '" type="button" id="wound1"value=""><i class="fa-solid fa-x deleteWoundButton"></i></td><td><a title="' + datesInfo + '"><i class="fa-regular fa-square-info woundInformation"></a></i></td></th></tr>');
html.find(".removewoundbutton[name='" + count + "']").on("click", async (ev) => {
ev.preventDefault();
// Handle the deletion event
let actor = game.actors.get(ev.currentTarget.closest(".woundlist").getAttribute("actorid"));
let _woundlist = actor.flags.darksheet.woundlist ? actor.flags.darksheet.woundlist : [];
// REMOVE WOUND
_woundlist.splice(ev.currentTarget.name, 1);
await actor.update({
'flags.darksheet.woundlist': woundlist
});
document.activeElement.blur();
});
}
}
} else {
await html.find(".woundlist").append('<tr id="oldwounds" actorid="' + actor.id + '"><td colspan="4" class="oldWoundsColspan"><label class="oldWoundsLabel">Old Wounds</label><i class="fas fa-angle-up" style="margin-top: -8px; font-size:14px; padding:5px"></i></td></tr>');
}
html.find('#oldwounds').click((ev) => {
ev.preventDefault();
let actor = game.actors.get(ev.currentTarget.getAttribute("actorid"));
actor.update({
"flags.darksheet.displayOldWounds": !actor.flags.darksheet.displayOldWounds
});
});
html.find('.addwoundbutton').click((ev) => {
ev.preventDefault();
let actor = game.actors.get(ev.currentTarget.getAttribute("actorid"));
addWoundToCharacter(actor);
});
html.find('.rollHealWounds').click((ev) => {
ev.preventDefault();
let actor = game.actors.get(ev.currentTarget.getAttribute("actorid"));
rollHealingWounds(actor);
});
html.find('.rollReopenWounds').click((ev) => {
ev.preventDefault();
let actor = game.actors.get(ev.currentTarget.getAttribute("actorid"));
rollReopenWounds(actor);
});
}
async function rollReopenWounds(actor) {
let woundlist = actor.getFlag('darksheet', 'woundlist');
let reopenedWounds = [];
for (let i = 0; i < woundlist.length; i++) {
let wound = woundlist[i];
if (!wound.healed && wound.treated) {
let roll = await new Roll("1d20").evaluate({
async: true
});
let effect = "";
if (roll.total == 1) {
effect = "The wound reopens and you lose a hit die (no longer treated).";
wound.healed = false;
wound.treated = false;
wound.hitDieLost = true;
await actor.setFlag('darksheet', 'woundlist', woundlist, {
diff: true
});
reopenedWounds.push(i);
createRollMessage(actor, "Wound-Reopen: " + wound.location, roll, null, roll.total, null, "1d20", 'fa-regular fa-face-head-bandage', effect, "darksheetNegativeMessage");
} else if (roll.total >= 2 && roll.total <= 8) {
effect = "The wound reopens (no longer treated).";
wound.healed = false;
wound.treated = false;
await actor.setFlag('darksheet', 'woundlist', woundlist, {
diff: true
});
reopenedWounds.push(i);
createRollMessage(actor, "Wound-Reopen: " + wound.location, roll, null, roll.total, null, "1d20", 'fa-regular fa-face-head-bandage', effect, "darksheetNegativeMessage");
} else if (roll.total >= 9 && roll.total <= 20) {
effect = "The wound remains closed.";
createRollMessage(actor, "Wound-Reopen: " + wound.location, roll, null, roll.total, null, "1d20", 'fa-regular fa-face-head-bandage', effect);
}
}
}
}
async function rollHealingWounds(actor) {
let woundlist = actor.getFlag('darksheet', 'woundlist');
let healedWounds = [];
let failedHealingChecks = [];
let style = "";
let flavorText = "";
for (let i = 0; i < woundlist.length; i++) {
let wound = woundlist[i];
if (!wound.healed) {
let roll = await new Roll("1d20").evaluate({
async: true
});
if (roll.total + actor.data.data.skills.med.total >= 15) {
healedWounds.push(i);
wound.healed = true;
wound.healedDate = Date.now();
await actor.setFlag('darksheet', 'woundlist', woundlist, {
diff: true
});
style = "darksheetPositiveMessage";
flavorText = "Wound is healed.";
} else {
failedHealingChecks.push(i);
style = "darksheetNegativeMessage";
flavorText = "Is not fully healed yet.";
}
createRollMessage(actor, "Healing Wounds: " + wound.location, roll, null, roll.total, null, "1d20 + CON (Medicine) Mod", 'fa-regular fa-bandage', flavorText, style);
}
}
}
async function addWoundToCharacter(actor) {
let woundlisttext;
let woundlist = actor.flags.darksheet.woundlist ? actor.flags.darksheet.woundlist : [];
let date = '';
await getTimeStamp().then((timestamp) => {
date = timestamp;
});
//ADD WOUND
let wound = {
location: "",
treated: false,
healed: false,
gainedDate: date,
healedDate: ''
}
woundlist.push(wound);
await actor.setFlag('darksheet', 'woundlist', woundlist, {
diff: true
});
}
async function getTimeStamp() {
const currentDate = new Date();
// Get the date components
const day = String(currentDate.getDate()).padStart(2, '0');
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const year = currentDate.getFullYear();
// Get the time components
const hours = String(currentDate.getHours()).padStart(2, '0');
const minutes = String(currentDate.getMinutes()).padStart(2, '0');
const seconds = String(currentDate.getSeconds()).padStart(2, '0');
// Construct the formatted date string
const formattedDate = `${day}/${month}/${year} ${hours}:${minutes}:${seconds}`;
return formattedDate;
}
async function addDarkSheetTab(app, html, data) {
//ADD NEW DD TAB
let test = html.find(".tabs").append('<a class="item control" data-group="primary" data-tab="dd" data-tooltip="Darker Dungeons" aria-label="Darker Dungeons"><i class="fas fa-skull"></i></a>');
let sheet = html.find(".tab-body");
let hideChecks = game.settings.get("darksheet", "hidechecks");
data.hidechecks = hideChecks;
let darkSheetTabHTML = await renderTemplate("modules/darksheet/templates/Tab_DD.html", data);
await sheet.append(darkSheetTabHTML);
// Set Training Tab as Active
html.find('.tabs .item[data-tab="dd"]').click((ev) => {
ev.preventDefault();
app.activateDDTab = true;
});
// Unset Training Tab as Active
html.find('.tabs .item:not(.tabs .item[data-tab="dd"])').click((ev) => {
ev.preventDefault();
app.activateDDTab = false;
});
}
async function darkSheetSetup(app, html, data) {
let actor = game.actors.contents.find((a) => a._id === data.actor._id);
if (actor === undefined) {
return;
}
let saveCantrips = game.settings.get('darksheet', 'savecantrips');
data.savecantrips = saveCantrips;
//SET UP SHEET BY SETTING CLASSES
//DEATH SAVES
const deathSaves = html.find('.death-saves');
deathSaves.find('.counter-value').children().first().remove();
deathSaves.find('.counter-value').children().first().remove();
deathSaves.children().first()
.removeAttr('data-action')
.addClass('tableCheck')
.attr('tableCheck', 'Death Saving Throw');
//ACTIVE INITIATIVE
let armorclass = html[0].getElementsByClassName("attribute-name box-title")[2];
if (armorclass == undefined) //NEW SHEET
armorclass = html[0].getElementsByClassName("ac-badge")[0];
armorclass.classList.add("rollable", "darksheet_AC");
let primaryCastingAbility = data.actor.system.attributes.spellcasting;
// Find the specific spellcasting card div where the data-ability attribute matches the primaryCastingAbility.
let spellcastingCard = Array.from(document.querySelectorAll('.spellcasting.card.primary'))
.find(card => card.getAttribute('data-ability') === primaryCastingAbility);
//ACTIVE SAVES
if (spellcastingCard) {
let abilitySpan = spellcastingCard.querySelector('.ability');
abilitySpan.classList.add("rollable", "darksheet_AS");
}
//SPELL BURNOUT
let spellFilters = html.find(".spellcasting-ability");
let spellBurn = await renderTemplate("modules/darksheet/templates/spellburnout.html", data);
spellFilters.append(spellBurn);
//DEATHSAVES
/*//Deactivate OLD
html.find(".death-saves").remove();
let sheet = html.find(".counters");
let DeathSaves = await renderTemplate("modules/darksheet/templates/deathsaves.html", data);
sheet.prepend(DeathSaves);*/
//region INVENTORY
if (!game.settings.get("darksheet", "hidenotches")) {
const randomNotch = document.createElement("button");
randomNotch.classList.add("randomnotch", "rollable", "button");
randomNotch.type = "button";
randomNotch.textContent = "Random Notch";
const currencyElement = html[0].querySelector(".currency");
currencyElement.insertBefore(randomNotch, currencyElement.firstChild);
}
//ADD HEADER ATTRIBUTES
let currentSlots = 0;
actor.items.forEach(function(item) {
// Ensure that item.flags.darksheet?.item?.slots and item.system.quantity are defined, otherwise use 0
const slots = item.flags?.darksheet?.item?.slots ?? 0;
const quantity = item.system?.quantity ?? 0;
if (!(game.settings.get('darksheet', 'equippedDontUseSlots') && item.system.equipped)) {
currentSlots += slots * quantity;
}
});
let maxSlots = 18;
let percentage = 0;
let STRBONUS = actor.system.abilities.str.value * Math.max(1, Math.min(actor.system.attributes.encumbrance.mod, 8));
if (actor.flags.darksheet && actor.flags.darksheet.attributes) {
switch (actor.system.traits.size) {
case "tiny":
maxSlots = 6;
break;
case "sm":
maxSlots = 14;
break;
case "med":
maxSlots = 18;
break;
case "lg":
maxSlots = 22;
break;
case "huge":
maxSlots = 30;
break;
case "grg":
maxSlots = 46;
break;
default:
maxSlots = 18;
break;
}
maxSlots += STRBONUS;
}
percentage = (currentSlots / maxSlots) * 100;
if (game.settings.get('darksheet', 'slotbasedinventory')) { // IF SLOTS ARE ENABLED
//SET ENCUMBRANCE BAR
let encumbrance = html.find(".encumbrance").find(".meter");
const currentValue = encumbrance.find("div").find(".value")[0];
currentValue.textContent = parseFloat(currentSlots).toFixed(1);;
const maxValue = encumbrance.find("div").find(".max")[0];
maxValue.textContent = maxSlots + " Slots";
const multiplier = html.find(".encumbrance").find(".info").find(".multiplier").find(".value")[0];
multiplier.textContent = "x" + Math.max(1, Math.min(actor.system.attributes.encumbrance.mod, 8));
const size = html.find(".encumbrance").find(".info").find(".size");
size.find(".value")[0].textContent = "+" + (maxSlots - STRBONUS);
size.find(".label")[0].textContent = "Size-Slots";
size.appendTo(size.parent());
if(percentage <= 100)
encumbrance[0].style = "--bar-percentage:" + Math.min(percentage, 100) + "%;";
else
encumbrance[0].style = "background: red;border: 2px solid red;--bar-percentage:" + Math.min(percentage, 100) + "%;";
//SET BAR ARROWS
//REMOVE FIRST 2 Arrows
encumbrance[0].children[2].remove();
encumbrance[0].children[2].remove();
encumbrance[0].children[2].remove();
encumbrance[0].children[1].remove();
}
let inventoryList = html[0].getElementsByClassName("inventory-list")[0];
for (let i = 0; i < inventoryList.getElementsByClassName("items-header").length; i++) {
//SET WEIGHT TO SLOTS
if (game.settings.get('darksheet', 'slotbasedinventory'))
inventoryList.getElementsByClassName("items-header")[i].getElementsByClassName("item-weight")[0].innerHTML = "Slots";
let node = inventoryList.getElementsByClassName("items-header")[i].children[1];
if (!game.settings.get('darksheet', 'hidenotches')) {
//NOTCHES
let notchesHeader = document.createElement("div");
notchesHeader.classList.add("item-header", "item-weight", "item-notches");
notchesHeader.innerHTML = 'Notches';
inventoryList.getElementsByClassName("items-header")[i].insertBefore(notchesHeader, node);
}
//AMMODIE
if (!game.settings.get('darksheet', 'hideammodie')) {
let ammodieHeader = document.createElement("div");
ammodieHeader.classList.add("item-header", "item-weight", "item-ammodie");
ammodieHeader.innerHTML = 'Ammodie';
inventoryList.getElementsByClassName("items-header")[i].insertBefore(ammodieHeader, node);
}
}
//region INVENTORY
//DISPLAY ATTRIBUTES IN LIST
let automaticSlots = game.settings.get('darksheet', 'automaticSlots');
let automaticFragility = game.settings.get('darksheet', 'automaticFragility');
let updates = [];
for (let i = 0; i < inventoryList.getElementsByClassName("item").length; i++) {
//CREATE ELEMENTS
var _notches = document.createElement("div");
var _ammodie = document.createElement("div");
var _slots = document.createElement("div");
//ASSIGN CLASSES
if (!game.settings.get('darksheet', 'hidenotches'))
_notches.classList.add("item-detail", "item-weight", "item-notches");
_ammodie.classList.add("item-detail", "item-weight", "item-ammodieLabel");
if (game.settings.get('darksheet', 'slotbasedinventory'))
_slots.classList.add("item-detail", "item-weight", "item-slots");
//GET DATA
let item = inventoryList.getElementsByClassName("item")[i];
let itemRow = item.getElementsByClassName("item-row")[0];
let _item = actor.items.find(i => i.id == item.dataset.itemId);
if (_item.flags.darksheet == undefined || automaticFragility && _item.flags.darksheet.item.fragility == "" || automaticSlots && _item.flags.darksheet.item.slots == null) {
//try find slot
let slot = 1;
let fragility = "";
for (const [itemName, bulkValue] of Object.entries(itemBulk)) {
if (_item.name.includes(itemName)) {
// Handle slot assignment based on automaticSlots setting
if (automaticSlots) {
let slot = bulkValue;
console.log(`Darksheet | ${_item.name} is assigned ${slot} slots.`);
}
// Check fragility based on automaticFragility setting
if (automaticFragility) {
if (isItemFragile(_item.name)) {
console.log(`Darksheet | ${_item.name} is considered fragile.`);
fragility = 1;
} else {
console.log(`Darksheet | ${_item.name} is not considered fragile.`);
fragility = 10;
}
console.log(`Darksheet | ${_item.name} has a fragility rating of ${fragility}.`);
}
break;
}
}
updates.push({
"_id": _item.id,
"flags.darksheet.item.slots": slot,
//"flags.darksheet.item.notches": null,
//"flags.darksheet.item.quality": "pristine",
"flags.darksheet.item.fragility": fragility,
//"flags.darksheet.item.temper": "",
"flags.darksheet.item.ammodie": "",
});
}
if (_item?.flags?.darksheet?.item) {
let itemData = _item.flags.darksheet.item;
let product = itemData.slots * _item.system.quantity;
let usesSlots = (product % 1 === 0) ? product.toString() : product.toFixed(1);
//GET REFERENCE TO ITEM WEIGHT TO REMOVE IT LATER; BECAUSE IT SHARES THE CLASS WITH THE ADDED ELEMENTS
let itemWeight = item.getElementsByClassName("item-weight")[0];
let price = item.getElementsByClassName("item-price")[0];
//FILL WITH DATA
let minusNotchButton = document.createElement("button");
minusNotchButton.type = "button";
let plusNotchButton = document.createElement("button");
plusNotchButton.type = "button";
minusNotchButton.innerHTML = "<label>-</label>";
plusNotchButton.innerHTML = "<label>+</label>";
minusNotchButton.classList.add("darksheetbuttonMinus", "notchButton");
plusNotchButton.classList.add("darksheetbuttonPlus", "notchButton");
if (!game.settings.get('darksheet', 'hidenotches'))
_notches.append(
itemData?.notches > 0 ? minusNotchButton : "",
itemData?.notches > 0 ? itemData?.notches : "",
plusNotchButton
);
_ammodie.innerHTML = itemData.ammodie !== undefined ? '<label class="ammodieLabel">' + itemData.ammodie + '</label>' : "";
if (game.settings.get('darksheet', 'slotbasedinventory')) _slots.innerHTML = itemData.slots !== undefined ? usesSlots : "";
//INSERT NOTCHES
if (!game.settings.get('darksheet', 'hidenotches'))
if(itemRow)
itemRow.insertBefore(_notches, price);
if (itemData.ammodie == "")
_ammodie.classList.remove("item-ammodieLabel");
if (!game.settings.get('darksheet', 'hideammodie'))
itemRow.insertBefore(_ammodie, price);
if (game.settings.get('darksheet', 'slotbasedinventory')) {
itemRow.insertBefore(_slots, itemWeight);
itemWeight.remove();
}
if (!game.settings.get('darksheet', 'disableItemDamage')) {
//CHANGE DISPLAY NAME
let itemname = _item.name;
/*if (_item.flags.darksheet.item.temper) {
itemname = "[" + _item.flags.darksheet.item.temper + "] " + itemname;
}*/ //OLD TEMPER DISPLAY METHOD
if (_item.type == "weapon" && _item.system.damage.base.denomination > 0) {
itemname += " ("+_item.system.damage.base.number+"d" + _item.system.damage.base.denomination + ")";
}
if (_item.type == "equipment" && _item.system.armor.value != 0) {
itemname += " (" + _item.system.armor.value + " AC)";
}
/*if(_item.flags.darksheet.item.fragility){
const notchOptions = {
1: 'Delicate',
2: 'Frail',
3: 'Basic',
5: 'Solid',
10: 'Sturdy',
15: 'Durable',
20: 'Very Sturdy',
50: 'Fabled',
100: 'Indestructible'
};
itemname = "["+notchOptions[_item.flags.darksheet.item.fragility] + "] " + itemname;
}*/
item.children[0].children[0].children[1].children[0].innerHTML = itemname;
//TEMPER
if (_item.flags.darksheet.item.temper) {
let temper = _item.flags.darksheet.item.temper;
let temperLabel = document.createElement("span");
temperLabel.classList.add("DarktemperLabel","darktemper"+temper);
temperLabel.textContent = temper.charAt(0).toUpperCase() + temper.slice(1);
item.classList.add(temper);
let titleElement = item.getElementsByClassName("title")[0];
if (titleElement) {
titleElement.prepend(temperLabel); // Prepend the quality label
}
}
//QUALITY
if (_item.flags.darksheet.item.quality) {
let quality = _item.flags.darksheet.item.quality;
if(quality == "pristine") continue;
let qualityLabel = document.createElement("span");
qualityLabel.classList.add("DarkQualityLabel","darkQuality"+quality);
qualityLabel.textContent = quality.charAt(0).toUpperCase() + quality.slice(1);
item.classList.add(quality);
let titleElement = item.getElementsByClassName("title")[0];
if (titleElement) {
titleElement.prepend(qualityLabel); // Prepend the quality label
}
}
//SHATTERED
// Add a separate label if shattered
if (itemname.includes("[Shattered]")) {
let shatteredLabel = document.createElement("span");
shatteredLabel.classList.add("shattered-label");
shatteredLabel.textContent = "Shattered";
//item.children[0].children[0].children[1].children[0].prepend(shatteredLabel); // Add shattered label at the beginning