-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdarksheet.js
More file actions
9709 lines (9154 loc) · 481 KB
/
Copy pathdarksheet.js
File metadata and controls
9709 lines (9154 loc) · 481 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;
const DARKSCREEN_STORE_DEFAULTS = {
version: 1,
lastpage: "party",
journey: { list: {}, activeId: null },
disposition: { list: [] },
dread: { list: {}, activeId: null, displayId: null },
diseases: { list: [], custom: {}, dismissedReminder: "" },
itemTempering: {},
gmScreen: { activePresetId: "default", order: ["default"], presets: { default: { id: "default", name: "Default", slots: [] } } },
grimoire: {
url: "https://giffyglyph.com/darkerdungeons/grimoire/4.0.0/en/contents.html",
bookmarks: []
},
resting: { campingDc: "10", lookout: "", campFailures: "—", campActivityDc: "—", campLookoutResult: "—", lifestyle: "comfortable" },
campfire: { active: false },
cityRest: { active: false },
campSetup: { active: false, players: {} }
};
const DARKSHEET_DREAD_MOOD_DEFAULTS = [
{ threshold: 0, text: "You feel relatively safe." },
{ threshold: 5, text: "The air turns uneasy." },
{ threshold: 10, text: "Every shadow feels watchful." },
{ threshold: 20, text: "You are in danger." },
{ threshold: 40, text: "Something terrible is close." },
{ threshold: 80, text: "The dread is overwhelming." },
{ threshold: 160, text: "There is no escaping this place." }
];
const darksheetDreadMoodRuntime = {
activeKey: null,
lastKey: null,
phase: "",
timers: []
};
const DARKSHEET_SIZE_SLOTS = { tiny: 6, sm: 14, med: 18, lg: 22, huge: 30, grg: 46 };
const DARKSHEET_SLOT_CAPACITY_FORMULAS = {
flatStr: "flatStr",
sizeStr: "sizeStr",
sizeStr2: "sizeStr2"
};
function darksheetSlotCapacityFormula() {
try {
const formula = game.settings.get('darksheet', 'slotCapacityFormula');
return Object.values(DARKSHEET_SLOT_CAPACITY_FORMULAS).includes(formula)
? formula
: DARKSHEET_SLOT_CAPACITY_FORMULAS.sizeStr;
} catch (_error) {
return DARKSHEET_SLOT_CAPACITY_FORMULAS.sizeStr;
}
}
function darksheetActorSlotCapacity(actor) {
const formula = darksheetSlotCapacityFormula();
const sizeKey = actor?.system?.traits?.size ?? "med";
const sizeSlots = Number(DARKSHEET_SIZE_SLOTS[sizeKey] ?? DARKSHEET_SIZE_SLOTS.med);
const strScore = Number(actor?.system?.abilities?.str?.value ?? 0);
const strengthSlots = Number.isFinite(strScore) ? Math.max(0, strScore) : 0;
let baseSlots = sizeSlots;
let strengthMultiplier = 1;
if (formula === DARKSHEET_SLOT_CAPACITY_FORMULAS.flatStr) {
baseSlots = 0;
} else if (formula === DARKSHEET_SLOT_CAPACITY_FORMULAS.sizeStr2) {
strengthMultiplier = 2;
}
return {
formula,
sizeSlots: baseSlots,
strengthSlots,
strengthMultiplier,
maxSlots: Math.max(1, baseSlots + strengthSlots * strengthMultiplier)
};
}
function darksheetCloneData(data) {
if (globalThis.foundry?.utils?.deepClone) return foundry.utils.deepClone(data);
return JSON.parse(JSON.stringify(data));
}
function darksheetRefreshCharacterSheets() {
Object.values(globalThis.ui?.windows ?? {}).forEach(app => {
if (app?.actor?.type === "character") app.render(false);
});
}
function darksheetDreadInfluenceTier(max) {
const m = Number(max || 0);
if (m <= 1) return { label: "Trivial", max: 1 };
if (m <= 5) return { label: "Fleeting", max: 5 };
if (m <= 10) return { label: "Noticeable", max: 10 };
if (m <= 20) return { label: "Unmistakable", max: 20 };
if (m <= 40) return { label: "Powerful", max: 40 };
if (m <= 80) return { label: "Indomitable", max: 80 };
return { label: "Absolute", max: Number(max || 1000) };
}
function darksheetIndefiniteArticle(text = "") {
return /^[aeiou]/i.test(String(text).trim()) ? "an" : "a";
}
function darksheetDreadBannerZone() {
const store = getDarkscreenStore()?.dread ?? {};
const displayId = store.displayId;
return displayId && store.list?.[displayId] ? store.list[displayId] : null;
}
function darksheetDreadBannerText(zone) {
const tier = darksheetDreadInfluenceTier(zone?.max ?? 20);
return `You can feel ${darksheetIndefiniteArticle(tier.label)} ${tier.label} Influence`;
}
function darksheetNormalizeDreadMoodThresholds(raw = DARKSHEET_DREAD_MOOD_DEFAULTS) {
const source = Array.isArray(raw)
? raw
: raw && typeof raw === "object"
? Object.values(raw)
: DARKSHEET_DREAD_MOOD_DEFAULTS;
const rows = [];
for (const entry of source ?? []) {
const threshold = Math.max(0, Number(entry?.threshold ?? entry?.value ?? entry?.min ?? 0));
const text = String(entry?.text ?? entry?.label ?? entry?.message ?? "").trim();
if (!Number.isFinite(threshold) || !text) continue;
rows.push({ threshold, text });
}
const fallback = darksheetCloneData(DARKSHEET_DREAD_MOOD_DEFAULTS);
const normalized = rows.length ? rows : fallback;
return normalized.sort((a, b) => Number(a.threshold) - Number(b.threshold));
}
function darksheetDreadMoodThresholds() {
try {
return darksheetNormalizeDreadMoodThresholds(game.settings.get('darksheet', 'dreadMoodThresholds'));
} catch (_error) {
return darksheetNormalizeDreadMoodThresholds(DARKSHEET_DREAD_MOOD_DEFAULTS);
}
}
function darksheetDreadMoodForZone(zone) {
const max = Math.max(1, Number(zone?.max ?? 20));
const current = Math.max(0, Math.min(max, Number(zone?.current ?? 0)));
const rows = darksheetDreadMoodThresholds();
let active = rows[0] ?? DARKSHEET_DREAD_MOOD_DEFAULTS[0];
for (const row of rows) {
if (current + 0.0001 >= Number(row.threshold ?? 0)) active = row;
else break;
}
return {
...active,
current,
key: `${Number(active.threshold ?? 0)}:${active.text}`
};
}
function darksheetDreadMoodClass(mood) {
const threshold = Number(mood?.threshold ?? 0);
if (threshold >= 90) return "is-critical";
if (threshold >= 75) return "is-dire";
if (threshold >= 50) return "is-danger";
if (threshold >= 25) return "is-uneasy";
return "is-safe";
}
function darksheetDreadMoodKey(zone, mood) {
return `${zone?.id ?? zone?.name ?? "zone"}:${Number(mood?.threshold ?? 0)}:${mood?.text ?? ""}`;
}
function darksheetClearDreadMoodTimers({ clearLast = false } = {}) {
for (const timer of darksheetDreadMoodRuntime.timers) globalThis.clearTimeout(timer);
darksheetDreadMoodRuntime.timers = [];
darksheetDreadMoodRuntime.activeKey = null;
darksheetDreadMoodRuntime.phase = "";
if (clearLast) darksheetDreadMoodRuntime.lastKey = null;
}
function darksheetSetDreadMoodPhase(moodEl, phase = "") {
darksheetDreadMoodRuntime.phase = phase;
moodEl?.classList?.remove("is-typing", "is-holding", "is-fading");
if (phase) moodEl?.classList?.add(phase);
}
function darksheetDreadMoodDelayForChar(char = "") {
const base = 24 + Math.random() * 74;
if (/[.,;:!?]/.test(char)) return base + 130 + Math.random() * 140;
if (/\s/.test(char)) return base * 0.55;
return base;
}
function darksheetStartDreadMoodTyping(moodEl, mood, moodKey) {
if (!moodEl || !mood?.text) return;
darksheetClearDreadMoodTimers();
darksheetDreadMoodRuntime.activeKey = moodKey;
darksheetDreadMoodRuntime.lastKey = moodKey;
moodEl.hidden = false;
moodEl.textContent = "";
darksheetSetDreadMoodPhase(moodEl, "is-typing");
const chars = Array.from(String(mood.text));
let index = 0;
const schedule = (fn, delay) => {
const timer = globalThis.setTimeout(() => {
darksheetDreadMoodRuntime.timers = darksheetDreadMoodRuntime.timers.filter(id => id !== timer);
fn();
}, delay);
darksheetDreadMoodRuntime.timers.push(timer);
};
const typeNext = () => {
if (darksheetDreadMoodRuntime.activeKey !== moodKey || !document.body.contains(moodEl)) return;
if (index >= chars.length) {
darksheetSetDreadMoodPhase(moodEl, "is-holding");
schedule(() => {
if (darksheetDreadMoodRuntime.activeKey !== moodKey || !document.body.contains(moodEl)) return;
darksheetSetDreadMoodPhase(moodEl, "is-fading");
schedule(() => {
if (darksheetDreadMoodRuntime.activeKey !== moodKey || !document.body.contains(moodEl)) return;
moodEl.hidden = true;
moodEl.textContent = "";
darksheetClearDreadMoodTimers();
darksheetDreadMoodRuntime.lastKey = moodKey;
}, 1200);
}, 1800);
return;
}
moodEl.textContent += chars[index];
index += 1;
schedule(typeNext, darksheetDreadMoodDelayForChar(chars[index - 1]));
};
schedule(typeNext, 120 + Math.random() * 220);
}
function darksheetFormatDreadAmount(value) {
const number = Number(value ?? 0);
if (!Number.isFinite(number)) return "0";
if (Number.isInteger(number)) return String(number);
return number.toFixed(2).replace(/\.?0+$/, "");
}
function darksheetDreadBannerHeading(zone) {
if (!game.user?.isGM) return `<div class="darksheet-dread-zone-banner__label">Dread Zone</div>`;
const max = Math.max(1, Number(zone?.max ?? 20));
const current = Math.max(0, Math.min(max, Number(zone?.current ?? 0)));
return `
<div class="darksheet-dread-zone-banner__heading">
<button type="button" class="darksheet-dread-zone-banner__adjust" data-darksheet-dread-banner-change="-1" title="Reduce displayed dread" aria-label="Reduce displayed dread">
<i class="fas fa-minus" inert></i>
</button>
<div class="darksheet-dread-zone-banner__title">
<div class="darksheet-dread-zone-banner__label">Dread Zone</div>
<div class="darksheet-dread-zone-banner__meter">${darksheetFormatDreadAmount(current)} / ${darksheetFormatDreadAmount(max)} dread</div>
</div>
<button type="button" class="darksheet-dread-zone-banner__adjust" data-darksheet-dread-banner-change="1" title="Add displayed dread" aria-label="Add displayed dread">
<i class="fas fa-plus" inert></i>
</button>
</div>
`;
}
async function darksheetChangeDisplayedDread(amount) {
if (!game.user?.isGM) return;
const screenData = getDarkscreenStore();
const dread = screenData.dread ?? {};
const displayId = dread.displayId;
const zone = displayId ? dread.list?.[displayId] : null;
if (!zone) {
ui.notifications.warn("Darksheet | No player-facing dread zone is active.");
return;
}
const max = Math.max(1, Number(zone.max ?? 20));
const current = Math.max(0, Math.min(max, Number(zone.current ?? 0)));
const next = Math.max(0, Math.min(max, current + Number(amount || 0)));
dread.list[displayId] = { ...zone, current: next, max };
await writeDarkscreenStore({ ...screenData, dread });
if (globalThis.Darksheet?._darkscreen?.rendered) await globalThis.Darksheet.darkScreenReload?.();
darksheetUpdateDreadZoneBanner();
}
function darksheetHandleDreadBannerClick(event) {
const button = event.target?.closest?.("[data-darksheet-dread-banner-change]");
if (!button) return;
event.preventDefault();
event.stopPropagation();
darksheetChangeDisplayedDread(Number(button.dataset.darksheetDreadBannerChange)).catch(error => {
console.error("Darksheet | Failed to adjust displayed dread.", error);
ui.notifications.error("Darksheet | Failed to adjust displayed dread.");
});
}
function darksheetUpdateDreadZoneBanner() {
if (!globalThis.document?.body) return;
const id = "darksheet-dread-zone-banner";
const zone = darksheetDreadBannerZone();
let banner = document.getElementById(id);
if (!zone) {
darksheetClearDreadMoodTimers({ clearLast: true });
banner?.remove();
return;
}
if (!banner) {
banner = document.createElement("div");
banner.id = id;
banner.className = "darksheet-dread-zone-banner";
banner.addEventListener("click", darksheetHandleDreadBannerClick);
banner.innerHTML = `
<div data-darksheet-dread-banner-heading></div>
<div class="darksheet-dread-zone-banner__text"></div>
<div class="darksheet-dread-zone-banner__mood" hidden></div>
`;
document.body.append(banner);
}
const mood = darksheetDreadMoodForZone(zone);
const moodKey = darksheetDreadMoodKey(zone, mood);
const headingEl = banner.querySelector("[data-darksheet-dread-banner-heading]");
const textEl = banner.querySelector(".darksheet-dread-zone-banner__text");
const moodEl = banner.querySelector(".darksheet-dread-zone-banner__mood");
if (headingEl) headingEl.innerHTML = darksheetDreadBannerHeading(zone);
if (textEl) textEl.textContent = darksheetDreadBannerText(zone);
if (!moodEl) return;
const currentPhase = darksheetDreadMoodRuntime.activeKey === moodKey ? darksheetDreadMoodRuntime.phase : "";
moodEl.className = `darksheet-dread-zone-banner__mood ${darksheetDreadMoodClass(mood)}`;
if (currentPhase) moodEl.classList.add(currentPhase);
moodEl.dataset.darksheetDreadMoodKey = moodKey;
if (darksheetDreadMoodRuntime.activeKey === moodKey) return;
if (darksheetDreadMoodRuntime.lastKey !== moodKey) {
darksheetStartDreadMoodTyping(moodEl, mood, moodKey);
return;
}
moodEl.hidden = true;
moodEl.textContent = "";
}
function darksheetNormalizeItemBulkTable(raw, fallback = itemBulk) {
const hasExplicitSource = raw && typeof raw === "object";
const source = hasExplicitSource ? raw : fallback;
const table = {};
for (const [name, value] of Object.entries(source ?? {})) {
const key = String(name ?? "").trim();
const slots = Number(value);
if (key && Number.isFinite(slots)) table[key] = slots;
}
if (Object.keys(table).length) return table;
return hasExplicitSource ? {} : darksheetCloneData(fallback);
}
function darksheetNormalizeFragileItems(raw, fallback = fragileItems) {
const hasExplicitSource = raw != null;
const source = Array.isArray(raw)
? raw
: raw && typeof raw === "object"
? Object.values(raw)
: fallback;
const seen = new Set();
const list = [];
for (const value of source ?? []) {
const itemName = String(value ?? "").trim();
const key = itemName.toLocaleLowerCase();
if (!itemName || seen.has(key)) continue;
seen.add(key);
list.push(itemName);
}
if (list.length) return list;
return hasExplicitSource ? [] : darksheetCloneData(fallback);
}
function darksheetItemBulkTable() {
try {
return darksheetNormalizeItemBulkTable(game.settings.get('darksheet', 'itemAutomationSlotTable'));
} catch (_error) {
return darksheetNormalizeItemBulkTable(itemBulk);
}
}
function darksheetFragileItemsTable() {
try {
return darksheetNormalizeFragileItems(game.settings.get('darksheet', 'itemAutomationFragileTable'));
} catch (_error) {
return darksheetNormalizeFragileItems(fragileItems);
}
}
function darksheetSlotTableToText(table = itemBulk) {
return Object.entries(darksheetNormalizeItemBulkTable(table))
.map(([name, slots]) => `${name} = ${slots}`)
.join("\n");
}
function darksheetSlotTableToRows(table = itemBulk) {
return Object.entries(darksheetNormalizeItemBulkTable(table))
.map(([name, slots]) => ({ name, slots }));
}
function darksheetFragileItemsToText(items = fragileItems) {
return darksheetNormalizeFragileItems(items).join("\n");
}
function darksheetFragileItemsToTags(items = fragileItems) {
return darksheetNormalizeFragileItems(items).map(name => ({ name }));
}
function darksheetParseSlotTableText(text) {
const table = {};
const errors = [];
String(text ?? "").split(/\r?\n/).forEach((rawLine, index) => {
const line = rawLine.trim();
if (!line || line.startsWith("#") || line.startsWith("//")) return;
const separator = line.includes("=") ? "=" : line.includes("\t") ? "\t" : line.includes("|") ? "|" : "";
if (!separator) {
errors.push(`Line ${index + 1}: use "Item Name = Slots".`);
return;
}
const parts = line.split(separator);
const value = parts.pop();
const name = parts.join(separator).trim();
const slots = Number(String(value ?? "").trim());
if (!name) errors.push(`Line ${index + 1}: missing item name.`);
else if (!Number.isFinite(slots)) errors.push(`Line ${index + 1}: slots must be a number.`);
else table[name] = slots;
});
if (errors.length) throw new Error(errors.join("\n"));
return table;
}
function darksheetParseFragileItemsText(text) {
return darksheetNormalizeFragileItems(String(text ?? "")
.split(/\r?\n/)
.map(line => line.trim())
.filter(line => line && !line.startsWith("#") && !line.startsWith("//")));
}
function darksheetExtractRoll(result) {
if (!result) return null;
if (Array.isArray(result)) {
for (const entry of result) {
const roll = darksheetExtractRoll(entry);
if (roll) return roll;
}
return null;
}
if (globalThis.Roll && result instanceof Roll) return result;
if (Array.isArray(result.rolls) && result.rolls.length) return darksheetExtractRoll(result.rolls);
if (result.roll) return darksheetExtractRoll(result.roll);
if (result.message) return darksheetExtractRoll(result.message);
if (result.total != null || result._total != null) return result;
return null;
}
function darksheetRollTotal(roll) {
const total = Number(roll?.total ?? roll?._total);
return Number.isFinite(total) ? total : 0;
}
function darksheetRollMessageIds(result, ids = new Set(), seen = new WeakSet()) {
if (!result) return ids;
if (Array.isArray(result)) {
result.forEach(entry => darksheetRollMessageIds(entry, ids, seen));
return ids;
}
if (typeof result !== "object") return ids;
if (seen.has(result)) return ids;
seen.add(result);
for (const key of ["id", "_id"]) {
const value = result[key];
if (typeof value === "string" && (result.documentName === "ChatMessage" || result.constructor?.name === "ChatMessage")) ids.add(value);
}
const optionId = result.options?.messageId ?? result.options?.chatMessageId;
if (typeof optionId === "string") ids.add(optionId);
if (result.message) darksheetRollMessageIds(result.message, ids, seen);
if (result.chatMessage) darksheetRollMessageIds(result.chatMessage, ids, seen);
if (Array.isArray(result.rolls)) darksheetRollMessageIds(result.rolls, ids, seen);
return ids;
}
function darksheetAnimatedDiceAvailable() {
const dice3d = game?.dice3d;
if (!dice3d) return false;
try {
if (typeof dice3d.isEnabled === "function") return !!dice3d.isEnabled();
} catch (_error) {}
return true;
}
function darksheetBeginRollSettleWait({ grace = 500, timeout = 8000 } = {}) {
if (!darksheetAnimatedDiceAvailable()) return { wait: async () => {}, cancel: () => {} };
let done = false;
let waitingForIds = null;
let resolve;
let timeoutId = null;
const completion = new Promise(r => { resolve = r; });
const processed = [];
const completed = new Set();
const finish = () => {
if (done) return;
done = true;
try { Hooks.off("diceSoNiceMessageProcessed", onProcessed); } catch (_error) {}
try { Hooks.off("diceSoNiceRollComplete", onComplete); } catch (_error) {}
if (timeoutId) globalThis.clearTimeout(timeoutId);
resolve?.();
};
const onProcessed = (messageId, data = {}) => {
processed.push({ id: messageId == null ? "" : String(messageId), willAnimate: !!data.willTrigger3DRoll });
};
const onComplete = (messageId) => {
const id = messageId == null ? "" : String(messageId);
completed.add(id);
if (waitingForIds === null) return;
if (!waitingForIds || !waitingForIds.size || !id || waitingForIds.has(id)) finish();
};
try {
Hooks.on("diceSoNiceMessageProcessed", onProcessed);
Hooks.on("diceSoNiceRollComplete", onComplete);
} catch (_error) {
finish();
}
return {
wait: async (result = null) => {
if (done) return;
const messageIds = darksheetRollMessageIds(result);
await new Promise(resolveGrace => globalThis.setTimeout(resolveGrace, grace));
if (done) return;
const relevant = messageIds.size
? processed.find(entry => messageIds.has(entry.id))
: processed[processed.length - 1];
if (!relevant?.willAnimate) {
finish();
return;
}
waitingForIds = messageIds;
if (!messageIds.size || completed.has("") || Array.from(messageIds).some(id => completed.has(id))) {
finish();
return;
}
timeoutId = globalThis.setTimeout(finish, timeout);
await completion;
},
cancel: finish
};
}
async function darksheetShowRollAndWait(roll) {
const waiter = darksheetBeginRollSettleWait();
try {
if (game?.dice3d?.showForRoll) await game.dice3d.showForRoll(roll, game.user, true);
await waiter.wait(roll);
} catch (error) {
waiter.cancel();
throw error;
}
return roll;
}
const DarksheetFormApplication = globalThis.foundry?.appv1?.api?.FormApplication ?? globalThis.FormApplication;
class DarksheetItemAutomationTablesConfig extends DarksheetFormApplication {
static get defaultOptions() {
return foundry.utils.mergeObject(super.defaultOptions, {
id: "darksheet-item-automation-tables",
title: "Darksheet Automatic Item Tables",
template: "modules/darksheet/templates/item-automation-tables.html",
width: 720,
height: "auto",
resizable: true,
closeOnSubmit: false
});
}
getData(options = {}) {
return {
...super.getData(options),
slotTable: darksheetSlotTableToText(darksheetItemBulkTable()),
slotRows: darksheetSlotTableToRows(darksheetItemBulkTable()),
fragileTable: darksheetFragileItemsToText(darksheetFragileItemsTable()),
fragileTags: darksheetFragileItemsToTags(darksheetFragileItemsTable())
};
}
activateListeners(html) {
super.activateListeners(html);
const root = html?.[0] ?? html;
html.find("[data-action='add-slot-row']").on("click", event => {
event.preventDefault();
const body = root?.querySelector?.("[data-slot-table-body]");
if (!body) return;
const search = root?.querySelector?.("[data-slot-search]");
if (search) search.value = "";
body.insertAdjacentHTML("afterbegin", this._slotRowHtml());
body.querySelector("[data-slot-row] input[name='slotName']")?.focus();
this._filterSlotRows(root);
});
html.find("[data-slot-search]").on("input", () => this._filterSlotRows(root));
html.find("[data-slot-table-body]").on("input", "input", () => this._filterSlotRows(root));
html.find("[data-slot-table-body]").on("click", "[data-action='remove-slot-row']", event => {
event.preventDefault();
event.currentTarget.closest("[data-slot-row]")?.remove();
});
html.find("[data-action='add-fragile-tag']").on("click", event => {
event.preventDefault();
this._addFragileTag(root);
});
html.find("[data-fragile-new]").on("keydown", event => {
if (event.key !== "Enter") return;
event.preventDefault();
this._addFragileTag(root);
});
html.find("[data-fragile-tags]").on("click", "[data-action='remove-fragile-tag']", event => {
event.preventDefault();
event.currentTarget.closest("[data-fragile-tag]")?.remove();
});
html.find("[data-action='reset-defaults']").on("click", async event => {
event.preventDefault();
const confirmed = await Dialog.confirm({
title: "Reset Automatic Item Tables",
content: "<p>Reset automatic slot and fragile item tables to Darksheet defaults?</p>"
});
if (!confirmed) return;
await game.settings.set('darksheet', 'itemAutomationSlotTable', darksheetCloneData(itemBulk));
await game.settings.set('darksheet', 'itemAutomationFragileTable', darksheetCloneData(fragileItems));
ui.notifications?.info("Darksheet | Automatic item tables reset.");
darksheetRefreshCharacterSheets();
this.render(false);
});
}
_slotRowHtml({ name = "", slots = "" } = {}) {
return `
<tr data-slot-row>
<td><input type="text" name="slotName" value="${escapeSheetHtml(name)}" placeholder="Item name match"></td>
<td><input type="number" name="slotSlots" value="${escapeSheetHtml(slots)}" step="any" placeholder="0"></td>
<td class="ds-slot-table__remove"><button type="button" data-action="remove-slot-row"><i class="fas fa-trash"></i> Remove</button></td>
</tr>
`;
}
_filterSlotRows(root) {
const query = String(root?.querySelector?.("[data-slot-search]")?.value ?? "").trim().toLocaleLowerCase();
root?.querySelectorAll?.("[data-slot-row]").forEach(row => {
const name = String(row.querySelector("[name='slotName']")?.value ?? "").toLocaleLowerCase();
const slots = String(row.querySelector("[name='slotSlots']")?.value ?? "").toLocaleLowerCase();
row.hidden = !!query && !name.includes(query) && !slots.includes(query);
});
}
_fragileTagHtml(name) {
return `
<span class="ds-fragile-tag" data-fragile-tag>
<input type="hidden" name="fragileTag" value="${escapeSheetHtml(name)}">
<span>${escapeSheetHtml(name)}</span>
<button type="button" data-action="remove-fragile-tag" title="Remove ${escapeSheetHtml(name)}"><i class="fas fa-xmark"></i></button>
</span>
`;
}
_addFragileTag(root) {
const input = root?.querySelector?.("[data-fragile-new]");
const container = root?.querySelector?.("[data-fragile-tags]");
const name = String(input?.value ?? "").trim();
if (!name || !container) return;
const exists = Array.from(container.querySelectorAll("input[name='fragileTag']"))
.some(tag => String(tag.value ?? "").trim().toLocaleLowerCase() === name.toLocaleLowerCase());
if (exists) {
ui.notifications?.warn(`Darksheet | ${name} is already in the fragile list.`);
return;
}
container.insertAdjacentHTML("beforeend", this._fragileTagHtml(name));
input.value = "";
input.focus();
}
_slotTableFromForm(form) {
const table = {};
const errors = [];
Array.from(form?.querySelectorAll?.("[data-slot-row]") ?? []).forEach((row, index) => {
const name = String(row.querySelector("[name='slotName']")?.value ?? "").trim();
const rawSlots = String(row.querySelector("[name='slotSlots']")?.value ?? "").trim();
if (!name && !rawSlots) return;
const slots = Number(rawSlots);
if (!name) errors.push(`Slot row ${index + 1}: missing item name.`);
else if (!Number.isFinite(slots)) errors.push(`Slot row ${index + 1}: slots must be a number.`);
else table[name] = slots;
});
if (errors.length) throw new Error(errors.join("\n"));
return table;
}
_fragileTagsFromForm(form) {
const tags = Array.from(form?.querySelectorAll?.("input[name='fragileTag']") ?? [])
.map(input => String(input.value ?? "").trim())
.filter(Boolean);
return darksheetNormalizeFragileItems(tags, []);
}
async _updateObject(_event, formData) {
try {
const field = key => formData?.get?.(key) ?? formData?.[key] ?? "";
const form = _event?.currentTarget ?? this.form;
const slotTable = form ? this._slotTableFromForm(form) : darksheetParseSlotTableText(field("slotTable"));
const fragileTable = form ? this._fragileTagsFromForm(form) : darksheetParseFragileItemsText(field("fragileTable"));
await game.settings.set('darksheet', 'itemAutomationSlotTable', slotTable);
await game.settings.set('darksheet', 'itemAutomationFragileTable', fragileTable);
ui.notifications?.info("Darksheet | Automatic item tables saved.");
darksheetRefreshCharacterSheets();
this.close();
} catch (error) {
console.error("Darksheet | Could not save automatic item tables.", error);
ui.notifications?.error(`Darksheet | ${error.message}`);
}
}
}
class DarksheetDreadMoodTextConfig extends DarksheetFormApplication {
static get defaultOptions() {
return foundry.utils.mergeObject(super.defaultOptions, {
id: "darksheet-dread-mood-texts",
title: "Darksheet Dread Mood Texts",
template: "modules/darksheet/templates/dread-mood-texts.html",
width: 680,
height: "auto",
resizable: true,
closeOnSubmit: false
});
}
getData(options = {}) {
return {
...super.getData(options),
rows: darksheetDreadMoodThresholds()
};
}
activateListeners(html) {
super.activateListeners(html);
const root = html?.[0] ?? html;
html.find("[data-action='add-dread-mood-row']").on("click", event => {
event.preventDefault();
const body = root?.querySelector?.("[data-dread-mood-body]");
if (!body) return;
body.insertAdjacentHTML("afterbegin", this._rowHtml({ threshold: 0, text: "" }));
body.querySelector("[data-dread-mood-row] input[name='moodText']")?.focus();
});
html.find("[data-dread-mood-body]").on("click", "[data-action='remove-dread-mood-row']", event => {
event.preventDefault();
event.currentTarget.closest("[data-dread-mood-row]")?.remove();
});
html.find("[data-action='reset-defaults']").on("click", async event => {
event.preventDefault();
const confirmed = await Dialog.confirm({
title: "Reset Dread Mood Texts",
content: "<p>Reset Dread mood threshold text to Darksheet defaults?</p>"
});
if (!confirmed) return;
await game.settings.set('darksheet', 'dreadMoodThresholds', darksheetCloneData(DARKSHEET_DREAD_MOOD_DEFAULTS));
globalThis.Darksheet?.updateDreadZoneBanner?.();
ui.notifications?.info("Darksheet | Dread mood texts reset.");
this.render(false);
});
}
_rowHtml({ threshold = 0, text = "" } = {}) {
return `
<tr data-dread-mood-row>
<td><input type="number" name="moodThreshold" value="${escapeSheetHtml(threshold)}" min="0" step="1"></td>
<td><input type="text" name="moodText" value="${escapeSheetHtml(text)}" placeholder="You feel watched."></td>
<td class="ds-slot-table__remove"><button type="button" data-action="remove-dread-mood-row"><i class="fas fa-trash"></i> Remove</button></td>
</tr>
`;
}
_rowsFromForm(form) {
const rows = [];
const errors = [];
Array.from(form?.querySelectorAll?.("[data-dread-mood-row]") ?? []).forEach((row, index) => {
const rawThreshold = String(row.querySelector("[name='moodThreshold']")?.value ?? "").trim();
const text = String(row.querySelector("[name='moodText']")?.value ?? "").trim();
if (!rawThreshold && !text) return;
const threshold = Number(rawThreshold);
if (!Number.isFinite(threshold)) errors.push(`Mood row ${index + 1}: threshold must be a number.`);
else if (threshold < 0) errors.push(`Mood row ${index + 1}: threshold must be 0 or higher.`);
else if (!text) errors.push(`Mood row ${index + 1}: missing mood text.`);
else rows.push({ threshold, text });
});
if (errors.length) throw new Error(errors.join("\n"));
return darksheetNormalizeDreadMoodThresholds(rows);
}
async _updateObject(event, _formData) {
try {
const rows = this._rowsFromForm(event?.currentTarget ?? this.form);
await game.settings.set('darksheet', 'dreadMoodThresholds', rows);
globalThis.Darksheet?.updateDreadZoneBanner?.();
ui.notifications?.info("Darksheet | Dread mood texts saved.");
this.close();
} catch (error) {
console.error("Darksheet | Could not save dread mood texts.", error);
ui.notifications?.error(`Darksheet | ${error.message}`);
}
}
}
//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', 'requireRecipes', {
name: 'Require Crafting Recipes',
hint: 'When enabled, a character must own the matching recipe item to craft a jewel or oil in the Crafting tab (GM quick mode bypasses this).',
scope: 'world',
config: true,
default: false,
type: Boolean,
});
game.settings.register('darksheet', 'publicRecipes', {
name: 'Public Crafting Recipes',
hint: 'GM-managed Darksheet recipes available to all players.',
scope: 'world',
config: false,
default: [],
type: Object,
});
game.settings.register('darksheet', 'sharedRecipes', {
name: 'Shared Crafting Recipes',
hint: 'Player-shared Darksheet recipe references available to all players.',
scope: 'world',
config: false,
default: [],
type: Object,
});
game.settings.register('darksheet', 'wearDisplay', {
name: 'Item Wear Display',
hint: 'How an item\'s quality (worn / well-worn / scarred) is shown in the inventory.',
scope: 'world',
config: true,
default: 'tag',
type: String,
choices: {
tag: 'Name tag (default)',
border: 'Colored icon border',
cracks: 'Cracks on the icon (+ colored border)'
},
});
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', 'slotCapacityFormula', {
name: 'Inventory Slot Capacity Formula',
hint: 'Controls how many inventory slots a character has when the slot-based inventory is enabled.',
scope: 'world',
config: true,
default: DARKSHEET_SLOT_CAPACITY_FORMULAS.sizeStr,
type: String,
choices: {
[DARKSHEET_SLOT_CAPACITY_FORMULAS.flatStr]: 'Flat STR',
[DARKSHEET_SLOT_CAPACITY_FORMULAS.sizeStr]: 'Creature size + STR',
[DARKSHEET_SLOT_CAPACITY_FORMULAS.sizeStr2]: 'Creature size + STR*2'
},
onChange: () => {
globalThis.Darksheet?.darkScreenReload?.();
Object.values(globalThis.ui?.windows ?? {}).forEach(app => {
if (app?.actor?.type === "character") app.render(false);
});
}
});
/*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', 'itemAutomationSlotTable', {
name: 'Automatic Item Slot Table',
hint: 'Internal storage for the editable automatic item slot lookup table.',
scope: 'world',
config: false,
default: darksheetCloneData(itemBulk),
type: Object,
});
game.settings.register('darksheet', 'itemAutomationFragileTable', {
name: 'Automatic Fragile Item Table',
hint: 'Internal storage for the editable automatic fragile item lookup table.',
scope: 'world',
config: false,
default: darksheetCloneData(fragileItems),
type: Object,
});
game.settings.registerMenu('darksheet', 'itemAutomationTables', {
name: 'Automatic Item Tables',
label: 'Configure Tables',
hint: 'Edit which item names receive automatic slots and which names count as fragile.',
scope: 'world',
icon: 'fas fa-table-list',
type: DarksheetItemAutomationTablesConfig,
restricted: true
});
game.settings.register('darksheet', 'dreadMoodThresholds', {
name: 'Dread Mood Texts',
hint: 'Internal storage for player-facing Dread zone mood text thresholds.',
scope: 'world',
config: false,
default: darksheetCloneData(DARKSHEET_DREAD_MOOD_DEFAULTS),
type: Object,
onChange: () => globalThis.Darksheet?.updateDreadZoneBanner?.()
});
game.settings.registerMenu('darksheet', 'dreadMoodTexts', {
name: 'Dread Mood Texts',
label: 'Configure Texts',
hint: 'Edit the animated Dread banner text shown at different current dread amounts.',
scope: 'world',
icon: 'fas fa-comment-dots',
type: DarksheetDreadMoodTextConfig,
restricted: true
});
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,