forked from Xacus/demonlord
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase-actor-sheet.js
More file actions
908 lines (804 loc) · 33.9 KB
/
base-actor-sheet.js
File metadata and controls
908 lines (804 loc) · 33.9 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
const { HandlebarsApplicationMixin, DialogV2 } = foundry.applications.api
const { ActorSheetV2 } = foundry.applications.sheets
import { onManageActiveEffect, prepareActiveEffectCategories } from '../../active-effects/effects'
import { buildOverview } from '../../chat/effect-messages'
import { DL } from '../../config'
import { DemonlordItem } from '../../item/item'
import tippy from "tippy.js";
import { buildDropdownListHover } from "../../utils/handlebars-helpers";
import { DLAfflictions } from '../../active-effects/afflictions'
import launchRollDialog from '../../dialog/roll-dialog'
import { TokenManager } from '../../pixi/token-manager'
const tokenManager = new TokenManager()
const { TextEditor } = foundry.applications.ux //eslint-disable-line no-shadow
export default class DLBaseActorSheet extends HandlebarsApplicationMixin(ActorSheetV2) {
static DEFAULT_OPTIONS = {
tag: 'form',
form: {
//handler: this.onSubmit,
//submitOnChange: true,
//closeOnSubmit: false
},
classes: ['demonlord-v2-sheet', 'demonlord-v2-actor'], // TODO: Add actor type to classes: this.type === 'character' ? (this.isPC ? 'pc' : 'npc') : this.type
actions: {
createItem: this.onCreateItem,
editItem: this.onEditItem,
deleteItem: this.onDeleteItem,
toggleWear: this.onToggleWear,
toggleInfo: this.onToggleInfo,
editWealth: this.onEditWealth,
},
window: {
resizable: true
},
position: {
width: 960,
height: 800,
},
scrollY: [],
editable: true
}
static PARTS = {
sidebar: { template: 'systems/demonlord/templates/actor/parts/character-sheet-sidemenu.hbs' },
header: { template: 'systems/demonlord/templates/actor/parts/character-sheet-header.hbs' },
tabs: { template: 'systems/demonlord/templates/generic/tab-navigation.hbs' },
// Tabs
character: { template: 'systems/demonlord/templates/actor/tabs/character.hbs' },
combat: { template: 'systems/demonlord/templates/actor/tabs/combat.hbs' },
talents: { template: 'systems/demonlord/templates/actor/tabs/talents.hbs' },
magic: { template: 'systems/demonlord/templates/actor/tabs/magic.hbs' },
inventory: { template: 'systems/demonlord/templates/actor/tabs/item.hbs' },
background: { template: 'systems/demonlord/templates/actor/tabs/background.hbs' },
afflictions: { template: 'systems/demonlord/templates/actor/tabs/afflictions.hbs' },
effects: { template: 'systems/demonlord/templates/actor/tabs/effects.hbs' }
}
get canEdit() {
let editable = this.options.editable && (this.document.isOwner || this.document.isGM)
if (this.document.pack) {
const pack = game.packs.get(this.document.pack)
if (pack.locked) editable = false
}
return editable
}
get limited() {
return this.document.limited
}
/** @override */
_configureRenderOptions(options) {
super._configureRenderOptions(options)
// These parts are always rendered
options.parts = ['sidebar', 'header', 'tabs']
}
/** @override */
static setPosition(options = {}) {
const position = super.setPosition(options)
const sheetBody = this.element.find('.sheet-body')
const bodyHeight = position.height - 125
sheetBody.css('height', bodyHeight)
return position
}
/* -------------------------------------------- */
/* Data */
/* -------------------------------------------- */
/** @override */
_prepareTabs(tabGroup) {
const tabs = super._prepareTabs(tabGroup);
// Set initial tab if actor ownership is limited
if (this.actor.limited && this.constructor.TABS[tabGroup]) {
const limitedInitial = this.constructor.TABS[tabGroup].limitedInitial ?? this.constructor.TABS[tabGroup].initial
Object.keys(tabs).forEach(t => {
tabs[t].active = (t === limitedInitial)
tabs[t].cssClass = tabs[t].active ? 'active' : ''
})
}
return tabs
}
/** @override */
async _prepareContext(options) {
const context = await super._prepareContext(options)
context.isGM = game.user.isGM
context.isOwner = this.document.isOwner
context.ownership = this.actor.getUserLevel()
context.config = DL
context.actor = this.document
context.system = this.document.system
context.isCreature = this.document.type === 'creature'
context.isCharacter = this.document.type === 'character'
context.isNPC = this.document.type === 'character' && !this.document.system.isPC
context.effects = true
context.generalEffects = prepareActiveEffectCategories(Array.from(this.document.allApplicableEffects()), true)
context.effectsOverview = buildOverview(this.document)
context.flags = this.document.flags
context.immunities = this.getImmunities()
context.addCreatureInventoryTab = game.settings.get('demonlord', 'addCreatureInventoryTab')
context.hideTurnMode = game.settings.get('demonlord', 'optionalRuleInitiativeMode') === 's' ? false : true
context.hideFortune = game.settings.get('demonlord', 'fortuneHide') ? true : false
context.isTraitMode2025 = game.settings.get('demonlord', 'optionalRuleTraitMode2025')
//context.tabs = this._getTabs(options.parts)
context.tabs = this._prepareTabs('primary')
context.effectsTabs = this._prepareTabs('effects')
if ((context.isCreature || context.isVehicle) && !context.addCreatureInventoryTab) {
context.tabs.inventory.hide = true
}
// Enrich HTML
context.system.enrichedDescription = await TextEditor.implementation.enrichHTML(this.document.system.description);
// Attributes checkbox
for (const attr of Object.entries(context.system.attributes)) {
attr.isCheckbox = attr.dtype === 'Boolean'
}
// Retrieve data for nested items
const m = new Map()
for await (const item of this.document.items) {
const type = item.type
item.system.enrichedDescription = await TextEditor.implementation.enrichHTML(item.system.description)
m.has(type) ? m.get(type).push(item) : m.set(type, [item])
}
context._itemsByType = m;
return context;
}
async _preparePartContext(partId, context, options) {
await super._preparePartContext(partId, context, options)
switch (partId) {
case 'sidebar':
case 'header':
break
case 'tabs':
// Hide some tabs for limited actors
Object.keys(context.tabs).forEach(k => context.tabs[k].hide = (this.actor.limited && !context.tabs[k].alwaysShow))
break
case 'effects':
context.tab = context.tabs[partId]
context.cssClass = context.tab.cssClass
context.active = context.tab.active
context.effectsTab = context.effectsTabs.general
break
default:
context.tab = context.tabs[partId]
context.cssClass = context.tab.cssClass
context.active = context.tab.active
break
}
return context
}
_prepareItems(sheetData) {
const m = sheetData._itemsByType
const actorData = sheetData.actor
const actorHasChangeBool = (actor, key) => {
return Array.from(actor.allApplicableEffects()).filter(e => !e.disabled && e.changes.filter(c => c.key === key && c.value === '1').length > 0).length > 0
}
const noAttacks = actorHasChangeBool(actorData, 'system.maluses.noAttacks')
const noSpells = actorHasChangeBool(actorData, 'system.maluses.noSpells')
actorData.weapons = noAttacks ? [] : (m.get('weapon') || [])
actorData.spells = noSpells ? [] : (m.get('spell') || [])
actorData.talents = m.get('talent') || []
actorData.features = m.get('feature') || []
// Sorting traits in alphabetical order with an exception: Immune, Frightening and Horrifying have to be at the top.
actorData.features.sort(function(a, b) {
if ((a.name.toLowerCase().includes('immune')) != (b.name.toLowerCase().includes('immune'))) {
return a.name.toLowerCase().includes('immune') ? -1 : 1;
}
if ((a.name.toLowerCase().includes('frightening')) != (b.name.toLowerCase().includes('frightening'))) {
return a.name.toLowerCase().includes('frightening') ? -1 : 1;
}
if ((a.name.toLowerCase().includes('horrifying')) != (b.name.toLowerCase().includes('horrifying'))) {
return a.name.toLowerCase().includes('horrifying') ? -1 : 1;
}
return a.name > b.name ? 1 :
a.name < b.name ? -1 : 0;
})
// Sort spells in the spellbooks by their rank
actorData.spells.sort((a, b) => a.system.rank - b.system.rank)
// Prepare the book (spells divided by tradition)
actorData.spellbook = noSpells ? [] : this._prepareBook(actorData.spells, 'tradition', 'spells')
}
_prepareBook(items, dataGroupProperty, returnItemsName) {
const m = new Map()
items.forEach(i => {
const group = i.system[dataGroupProperty] || ''
if (m.has(group)) m.get(group).push(i)
else m.set(group, [i])
})
return Array.from(m.keys()).map(k => ({
[dataGroupProperty]: k,
[returnItemsName]: m.get(k),
})).sort(
(a, b) => a[dataGroupProperty]?.localeCompare(b[dataGroupProperty]) ?? 0
)
}
/* -------------------------------------------- */
/* Actions */
/* -------------------------------------------- */
static async onCreateItem(event) {
event.preventDefault()
event.stopPropagation()
const header = event.target.closest('[data-type]') // Get the type of item to create.
const type = header.dataset.type // Grab any data associated with this control.
const itemData = {
name: `New ${type.capitalize()}`,
type: type,
system: foundry.utils.duplicate(header.dataset),
}
// Remove the type from the dataset since it's in the itemData.type prop.
return await DemonlordItem.create(itemData, { parent: this.document })
}
// eslint-disable-next-line no-unused-vars
static async onEditItem(event) {
const id = event.target.closest('[data-item-id]').dataset.itemId
const item = this.document.items.get(id)
item.sheet.render(true)
}
static async onDeleteItem(event) {
const li = event.target.closest('[data-item-id]')
await this.showDeleteDialog(game.i18n.localize('DL.DialogAreYouSure'), game.i18n.localize('DL.DialogDeleteItemText'), li)
}
static async onEditWealth() {
await this.actor.update({ 'system.wealth.edit': !this.actor.system.wealth.edit }).then(() => this.render())
}
static async onToggleWear(event) {
const id = event.target.closest('[data-item-id]').dataset.itemId
const item = this.actor.items.get(id)
await item.update({ 'system.wear': !item.system.wear }, { parent: this.actor })
}
static async onToggleInfo(event) {
const elem = $(event.target)
const root = elem.closest('[data-item-id]')
const selector = '.fa-chevron-down, .fa-chevron-up'
const chevron = elem.is(selector) ? elem : elem.find(selector);
const elements = $(root).find('.dlInfo')
elements.each((_, i) => {
if (i.style.display === 'none') {
$(i).slideDown(100)
chevron?.removeClass('fa-chevron-up')
chevron?.addClass('fa-chevron-down')
} else {
$(i).slideUp(100)
chevron?.removeClass('fa-chevron-down')
chevron?.addClass('fa-chevron-up')
}
})
}
/* -------------------------------------------- */
/* Auxiliary functions */
/* -------------------------------------------- */
_getTabs(parts) {
const tabGroup = 'primary'
const tabs = {}
for (const partId of parts) {
const tab = {
id: '',
group: tabGroup,
//label: 'DL.Tabs'
icon: `icon-${partId}`
}
if (['character', 'combat', 'talents', 'magic', 'inventory', 'background', 'afflictions', 'effects'].includes(partId)) {
tab.id = partId
//tab.label += capitalize(partId)
} else {
continue
}
tab.active = this.tabGroups[tab.group] === tab.id
tab.cssClass = tab.active ? 'active' : ''
tabs[partId] = tab
}
return tabs
}
/* -------------------------------------------- */
async showDeleteDialog(title, content, htmlItem) {
const deleteItem = async () => {
const id = htmlItem.dataset.itemId || htmlItem.dataset['item-id']
await Item.deleteDocuments([id], { parent: this.document })
//htmlItem.slideUp(200, () => this.render(false))
}
const d = new DialogV2({
window: {
title: title,
},
content: content,
buttons: [
{
action: 'yes',
icon: 'fas fa-check',
label: game.i18n.localize('DL.DialogYes'),
callback: async () => await deleteItem(),
default: true
},
{
action: 'no',
icon: 'fas fa-times',
label: game.i18n.localize('DL.DialogNo'),
}
],
close: () => { }
})
d.render(true)
}
/* -------------------------------------------- */
/* Listeners */
/* -------------------------------------------- */
/** @override */
async _onRender(context, options) { // eslint-disable-line no-unused-vars
super._onRender(context, options)
let e = this.element
/*
* Modified version of the awesome https://github.com/saif-ellafi/foundryvtt-actor-link-indicator
* Big thanks to saif-ellafi
*/
if (game.user.isGM && game.settings.get('demonlord', 'showActorLinkStatus')) {
const isUnique = this.actor.prototypeToken.actorLink;
let actorLink
if (this.actor.token === null) {
actorLink = {
style: isUnique ? 'color: darkorange;text-shadow: 0 0 8px darkorange; cursor: pointer;' : 'color: var(--demonlord-red);text-shadow: 0 0 8px var(--demonlord-red); cursor: pointer;',
icon: isUnique ? 'fas fa-link' : 'fas fa-unlink',
tooltip: isUnique ? game.i18n.localize('DL.UnLinkActorData') : game.i18n.localize('DL.LinkActorData')
}
} else {
actorLink = {
style: 'color: red;text-shadow: 0 0 8px red;',
icon: 'fas fa-unlink',
tooltip: game.i18n.localize('DL.SyntheticToken'),
}
}
let actorLinkIndicator = `<actorlink class="${actorLink.icon}" style ="${actorLink.style}" data-tooltip="${actorLink.tooltip}"></actorlink>`
e.querySelector("actorlink")?.remove()
e.querySelector(".header-control")?.insertAdjacentHTML("beforebegin", actorLinkIndicator)
// eslint-disable-next-line no-unused-vars
e.querySelector("actorlink")?.addEventListener('click', async ev => {
this.actor.update({
'prototypeToken.actorLink': !this.actor.prototypeToken.actorLink
})
})
}
const autoresize = (el) => {
const jEl = $(el)
if (jEl.prop("tagName") === 'INPUT') {
const setSize = () => {
let size = Math.max(1, (el.value?.length || el.placeholder?.length))
let ff = jEl.css('font-family')
if (ff.includes('Libertine')) {
el.style.width = (size + 4) + 'ch'
} else {
el.size = size
}
}
setSize()
el.oninput = setSize
} else if (jEl.prop("tagName") === 'TEXTAREA') {
const getHeight = () => Math.max(0, el?.scrollHeight)
jEl.height(0)
jEl.height(getHeight() + 'px')
el.oninput = () => {
jEl.height(0)
jEl.height(getHeight() + 'px')
}
}
}
e.querySelectorAll('[autosize]').forEach(el => autoresize(el))
// Tooltips
tippy(e.querySelectorAll('[data-tippy-content]'))
tippy(e.querySelectorAll('[data-tippy-html]'), {
content(reference) {
return $(reference).data('tippyHtml')
},
allowHTML: true
})
tippy(e.querySelectorAll('.dl-new-project-2.dropdown'), {
content(reference) {
return buildDropdownListHover(reference.attributes.name.value, reference.attributes.value.value, context.actor)
},
allowHTML: true,
interactive: true,
trigger: 'click',
placement: 'bottom',
arrow: false,
offset: [0, 0],
theme: 'demonlord-dropdown',
animation: 'shift-away',
})
tippy(e.querySelectorAll('[data-tab="afflictions"] [data-tippy-affliction]'), {
content(reference) {
return $(reference).data('tippyAffliction')
},
trigger: 'mouseenter',
arrow: true,
placement: 'right-start',
})
document.querySelector('[data-tippy-root]')?.remove()
// Everything below here is only needed if the sheet is editable
if (!this.options.editable) return
if (this.document.parent?.isOwner) {
const dragHandler = async ev => await this._onDrag(ev)
e.querySelectorAll('.nested-item').forEach(el => {
el.setAttribute('draggable', true)
el.addEventListener('dragstart', dragHandler, false)
el.addEventListener('dragend', dragHandler, false)
})
}
/*if (this.canEdit()) {
const inputs = e.querySelectorAll('input')
inputs.focus(ev => ev.currentTarget.select())
}*/
if (this.actor.isOwner) {
// Effects control
e.querySelectorAll('.effect-control')?.forEach(el => el.addEventListener('click', async ev => await onManageActiveEffect(ev, this.document)))
// Disable afflictions
e.querySelector('.disableafflictions')?.addEventListener('click', async () => {
await DLAfflictions.clearAfflictions(this.document)
})
// Affliction checkboxes
e.querySelectorAll('[data-tab="afflictions"] .item-group-affliction.checkable')?.forEach(el => el.addEventListener('mousedown', async ev => {
const input = ev.target.closest('.checkable').querySelector('input')
const checked = input.checked
const afflictionId = input.dataset.name
if (ev.button == 0) {
if (checked) {
// Ignore if there's an active effect that sets this condition (except for the status effects)
const effect = this.actor.appliedEffects.find(ae => ae.statuses.size === 0 && ae.changes.some(c => c.key === 'system.maluses.affliction' && c.value === afflictionId))
if (effect) {
ui.notifications.warn(game.i18n.localize('DL.DialogWarningAfflictionFromEffect'))
} else {
input.checked = false
const affliction = this.actor.effects.find(ef => ef?.statuses?.has(afflictionId))
if (!affliction) return false
await affliction.delete()
}
} else {
if (this.actor.isImmuneToAffliction(afflictionId)) {
ui.notifications.warn(game.i18n.localize('DL.DialogWarningActorImmune'));
return false;
}
input.checked = true
const affliction = CONFIG.statusEffects.find(a => a.id === afflictionId)
if (!affliction) return false
affliction['statuses'] = [affliction.id]
if (affliction.id === "horrified")
{
affliction.description = game.settings.get('demonlord', 'optionalRuleBaneValue') ? affliction.description.replace('3','2') : affliction.description = affliction.description.replace('2','3')
game.settings.get('demonlord', 'optionalRuleBaneValue') ? Object.keys(affliction.changes).forEach(function(value){ affliction.changes[value].value = -2 }) : Object.keys(affliction.changes).forEach(function(value){ affliction.changes[value].value = -3 })
}
await ActiveEffect.create(affliction, { parent: this.actor })
const targets = tokenManager.targets
switch (afflictionId) {
case 'help': {
const attribute = this.actor.system.attributes.intellect
if (!DLAfflictions.isActorBlocked(this.actor, 'challenge', attribute.key) && targets.length === 1)
launchRollDialog(this.actor, this.actor.name + ' - ' + game.i18n.localize('DL.DialogChallengeRoll') + attribute.label, async (event, html) => {
let result = await this.actor.rollAttributeChallenge(attribute, html.form.elements.boonsbanes.value, html.form.elements.modifier.value)
if (result._total >= 10 || game.settings.get('demonlord', 'optionalRuleDieRollsMode') === 'b' && result._total >= 11) {
affliction['statuses'] = [affliction.id]
const effect = CONFIG.statusEffects.find(a => a.id === "helped")
effect['statuses'] = [effect.id]
if (game.user.isGM) {
await ActiveEffect.create(effect, {
parent: targets[0].actor
})
} else {
game.socket.emit('system.demonlord', {
request: "createEffect",
tokenuuid: targets[0].document.uuid,
effectData: effect
})
}
}
})
break;
}
case 'stabilize': {
const attribute = this.actor.system.attributes.intellect
const isIncapacitated = targets.length === 1 ? targets[0].actor.appliedEffects.find(ef => ef?.statuses?.has('incapacitated')) : false
if (!DLAfflictions.isActorBlocked(this.actor, 'challenge', attribute.key) && isIncapacitated)
launchRollDialog(this.actor, this.actor.name + ' - ' + game.i18n.localize('DL.DialogChallengeRoll') + attribute.label, async (event, html) => {
let result = await this.actor.rollAttributeChallenge(attribute, html.form.elements.boonsbanes.value, html.form.elements.modifier.value)
if (result._total >= 10 || game.settings.get('demonlord', 'optionalRuleDieRollsMode') === 'b' && result._total >= 11) {
if (game.user.isGM) {
await targets[0].actor.increaseDamage(-1)
} else {
game.socket.emit('system.demonlord', {
request: "increaseDamage",
tokenuuid: targets[0].document.uuid,
increment: -1
})
}
}
})
break;
}
}
}
return true
} else if (ev.button == 2) {
// Toggle immunity
const effectName = game.i18n.format('DL.AfflictionImmunityEffectName', { affliction: game.i18n.localize(`DL.${afflictionId}`) })
const immuneEffects = this.actor.appliedEffects.filter(a => !a.disabled).filter(a => a.name === effectName && a.changes.length === 1 && a.changes[0].key === 'system.bonuses.immune.affliction' && a.changes[0].value === afflictionId)
if (immuneEffects?.length) {
await immuneEffects[0].delete()
} else {
await this.actor.createEmbeddedDocuments('ActiveEffect', [
{
name: effectName,
icon: this.actor.img,
origin: this.actor.uuid,
transfer: false,
flags: { demonlord: { sourceType: this.actor.type } },
changes: [
{
key: 'system.bonuses.immune.affliction',
value: afflictionId,
mode: 2
}
]
}
])
}
}
}))
// Toggle accordion
// e.querySelectorAll('.toggleAccordion').forEach(el => el.addEventListener('click', async ev => {
// const div = ev.currentTarget
// if (div.nextElementSibling.style.display === 'none') {
// div.nextElementSibling.style.display = 'block'
// div.className = 'toggleAccordion change'
// } else {
// div.nextElementSibling.style.display = 'none'
// div.className = 'toggleAccordion'
// }
// if (['action', 'afflictions', 'damage'].includes(div.dataset.type)) {
// const type = capitalize(div.dataset.type)
// const k = 'system.afflictionsTab.hideAction' + type
// const v = !this.actor.system.afflictionsTab[`hide${type}`]
// await this.actor.update({[k]: v})
// }
// }))
// Clone inventory item
e.querySelectorAll('.item-clone')?.forEach(el => el.addEventListener('click', async ev => {
const li = $(ev.currentTarget).parents('.item')
const item = foundry.utils.duplicate(this.actor.items.get(li.data('itemId')))
await Item.create(item, { parent: this.actor })
}))
// Wear item style
e.querySelectorAll('.item-wear')?.forEach(el => {
const itemId = $(el).closest('[data-item-id]').data('itemId')
const item = this.actor.items.get(itemId)
if (
item.system.wear &&
item.system.requirement?.minvalue != '' &&
item.system.requirement?.attribute != '' &&
+item.system.requirement?.minvalue > (+this.actor.getAttribute(item.system.requirement?.attribute)?.value + +this.actor.getAttribute(item.system.requirement?.attribute)?.requirementModifier)
) {
$(el).addClass('dl-text-red')
}
})
// Spell uses
e.querySelectorAll('.spell-uses')?.forEach(el => el.addEventListener('mousedown', async ev => {
const li = ev.target.closest('[data-item-id]')
const item = this.actor.items.get(li.dataset.itemId)
let uses = +item.system.castings.value
const usesmax = +item.system.castings.max
if (ev.button == 0) uses = uses < usesmax ? uses + 1 : 0
else if (ev.button == 2) uses = uses > 0 ? uses - 1 : 0
await item.update({ 'system.castings.value': uses }, { parent: this.actor })
}))
// Rollable Attributes
e.querySelectorAll('.attribute .name')?.forEach(el => el.addEventListener('click', ev => {
const div = $(ev.currentTarget)
const attributeName = div.data('key')
const attribute = this.actor.getAttribute(attributeName)
if (!attribute.immune) {
// Make an attribute attack if a target is selected, otherwise, challenge roll
if (game.user.targets?.ids.length && !(event.ctrlKey || event.metaKey)) {
this.actor.rollAttack(attribute)
} else {
this.actor.rollChallenge(attribute)
}
}
}))
// Set immune on rollable attribute
e.querySelectorAll('.attribute .name')?.forEach(el => el.addEventListener('contextmenu', async ev => {
const div = $(ev.currentTarget)
const attributeName = div.data('key')
await this.actor.update({ system: { attributes: { [attributeName]: { immune: !this.actor.system.attributes[attributeName].immune } } } })
}))
// Rollable Attack
e.querySelectorAll('.attack-roll')?.forEach(el => el.addEventListener('click', async ev => {
const id = $(ev.currentTarget).closest('[data-item-id]').data('itemId')
await this.actor.rollWeaponAttack(id, { event: ev })
}))
// Rollable Talent
e.querySelectorAll('.talent-roll').forEach(el => el.addEventListener('mousedown', async ev => {
const id = $(ev.currentTarget).closest('[data-item-id]').data('itemId')
if (ev.button == 0) await this.actor.rollTalent(id, { event: ev })
else if (ev.button == 2) await this.actor.deactivateTalent(this.actor.items.get(id), 0)
}))
// Talent uses
e.querySelectorAll('.talent-uses').forEach(el => el.addEventListener('mousedown', async ev => {
const id = $(ev.currentTarget).closest('[data-item-id]').data('itemId')
const talent = this.actor.items.get(id)
if (ev.button == 0) await this.actor.activateTalent(talent, true)
else if (ev.button == 2) await this.actor.deactivateTalent(talent, 1)
}))
// Rollable Attack Spell
e.querySelectorAll('.magic-roll').forEach(el => el.addEventListener('click', async ev => {
const id = ev.currentTarget.closest("[data-item-id]").dataset.itemId
await this.actor.rollSpell(id, { event: ev })
}))
// Rollable (generic)
e.querySelectorAll('.rollable, .item-roll').forEach(el => el.addEventListener('click', async event => {
event.preventDefault()
const element = event.currentTarget
const dataset = element.dataset
if (dataset.roll) {
const roll = new Roll(dataset.roll, this.actor.system)
const label = dataset.label ? `Rolling ${dataset.label}` : ''
await roll.roll().toMessage({
speaker: ChatMessage.getSpeaker({ actor: this.actor }),
flavor: label,
})
} else {
const id = event.currentTarget.closest("[data-item-id]").dataset.itemId
await this.actor.rollItem(id, { event: event })
}
}))
// Drag events for macros.
if (this.actor.isOwner) {
const handler = ev => this._onDragStart(ev)
e.querySelectorAll('.dropitem').forEach(el => {
if (el.classList.contains('inventory-header')) return
el.setAttribute('draggable', true)
el.addEventListener('dragstart', handler, false)
})
}
}
}
/* -------------------------------------------- */
/* Drop item event */
/* -------------------------------------------- */
async _onDrag(ev) {
const itemIndex = ev.currentTarget.closest('[data-item-index]').dataset.itemIndex
const data = this.document
if (ev.type == 'dragend') {
if (data.system.contents[itemIndex].system.quantity <= 1) {
await this.deleteContentsItem(itemIndex)
} else {
await this.decreaseContentsItemQuantity(itemIndex)
}
} else if (ev.type == 'dragstart') {
const dragData = { type: 'Item', 'uuid': data.system.contents[itemIndex].uuid }
ev.dataTransfer.setData("text/plain", JSON.stringify(dragData));
}
}
// async _addItem(data, level, group) {
// const levelItem = new PathLevelItem()
// const itemData = foundry.utils.duplicate(this.document)
// const item = await getNestedItemData(data)
// if (!item || ['ancestry', 'path', 'creaturerole'].includes(item.type)) return
// levelItem.uuid = item.uuid ?? data.uuid
// levelItem.id = item.id || item._id
// levelItem._id = item._id || item.id
// levelItem.name = item.name
// levelItem.description = item.system.description
// levelItem.pack = data.pack ? data.pack : ''
// levelItem.data = item
// levelItem.img = item.img
// if (this.document.type === 'ancestry' || this.document.type === 'path') {
// if (level === '0') {
// if (group === 'feature') itemData.system.levels[level].talents.push(levelItem)
// else itemData.system.levels[level][group].push(levelItem)
// } else {
// itemData.system.levels[level][group].push(levelItem)
// }
// } else {
// // Anything without levels
// itemData.system[group].push(levelItem)
// }
// await this.document.update(itemData)
// }
/*
_onDragOver(event) {
$(event.target).addClass('drop-hover')
}
_onDragLeave(event) {
$(event.target).removeClass('drop-hover')
}*/
/** @override */
async _onDropItem(ev, _item) {
try {
const incantation = this.tabGroups.primary === 'inventory' && _item.type === 'spell' ? true : false
const item = incantation ? await this.createIncantation(_item) : _item
// TODO: If item (by ID) exists in this object, ignore
if (this.actor.items.has(_item.id)) return
const isAllowed = await this.checkDroppedItem(_item)
if (isAllowed) {
const data = foundry.utils.duplicate(item);
let dropItem = await this.actor.createEmbeddedDocuments('Item', [data])
await this.postDropItemCreate(data)
if (incantation) await this.embedSpell(dropItem[0], foundry.utils.duplicate(_item))
} else {
console.warn('Wrong item type dragged', this.document, item)
}
} catch (err) {
console.warn(err)
}
}
async checkDroppedItem(_itemData) {
return true
}
async postDropItemCreate(_itemData) {
return true
}
async embedSpell(incantation, spell) {
const containerData = foundry.utils.duplicate(incantation)
containerData.system.contents.push(spell)
await incantation.update(containerData, {diff: false})
}
async createIncantation(_itemData) {
let availability
let value
switch (_itemData.system.rank) {
case 0:
availability = 'U'
value = '1 ss'
break
case 1:
availability = 'U'
value = '5 ss'
break
case 2:
availability = 'R'
value = '1 gc'
break
case 3:
availability = 'R'
value = '5 gc'
break
case 4:
availability = 'E'
value = '10 gc'
break
case 5:
availability = 'E'
value = '50 gc'
break
case 6:
availability = 'E'
value = '100 gc'
break
case 7:
availability = 'E'
value = '250 gc'
break
case 8:
availability = 'E'
value = '500 gc'
break
case 9:
availability = 'E'
value = '1000 gc'
break
case 10:
availability = 'E'
value = '5000 gc'
break
}
let incantation = new Item({
name: `${game.i18n.localize('DL.ConsumableTypeI')}: ${_itemData.name}`,
type: 'item',
system: {
consumabletype: 'I',
description : _itemData.system.description,
enrichedDescription : _itemData.system.enrichedDescription,
enrichedDescriptionUnrolled : _itemData.system.enrichedDescriptionUnrolled,
availability : availability,
value : value,
},
img: _itemData.img,
})
return incantation
}
getImmunities() {
const immunities = {}
for (let immunityEffect of this.actor.appliedEffects.flatMap(e => e.changes).filter(c => c.key === 'system.bonuses.immune.affliction')) {
immunities[immunityEffect.value] = true
}
return immunities
}
}