-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
pf2e-awardxp.js
375 lines (307 loc) · 13 KB
/
pf2e-awardxp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/* -------------------------------------------- */
/* Hooks */
/* -------------------------------------------- */
/**
* Open dialog at when the preDeleteCombat hook is fired.
*/
Hooks.on('preDeleteCombat', (combat,html,id) => {
if (!game.user.isGM) return
const pcs = combat.combatants.filter(c => c.actor.type==='character' && c.actor.alliance === 'party' && !c.actor.traits.has('eidolon') && !c.actor.traits.has('minion')).map(c => c.actor)
const pwol = game.pf2e.settings.variants.pwol.enabled;
let calulatedXP = game.pf2e.gm.calculateXP(
pcs[0].system.details.level.value,
pcs.length,
combat.combatants.filter(c => c.actor.alliance === 'opposition').map(c => c.actor.system.details.level.value),
combat.combatants.filter(c => c.actor.type === "hazard").map(c => c.actor.system.details.level.value),
{pwol}
)
const award = new game.pf2e_awardxp.Award(null,{destinations:pcs, description:'Encounter (' + calulatedXP.rating.charAt(0).toUpperCase() + calulatedXP.rating.slice(1) + ')', xp:calulatedXP.xpPerPlayer});
award.render(true);
})
Hooks.once("init", async () => {
console.log('PF2E Award XP Init')
game.pf2e_awardxp = {openDialog: Award.openDialog,
openPlayerDialog: Award.openDialog,
Award: Award
}
registerCustomEnrichers();
registerWorldSettings();
});
Hooks.once("ready", async () => {
game.pf2e_awardxp.Award._welcomeMessage();
});
Hooks.on("chatMessage", (app, message, data) => game.pf2e_awardxp.Award.chatMessage(message));
export function registerCustomEnrichers() {
CONFIG.TextEditor.enrichers.push({
pattern: /\[\[\/(?<type>award) (?<config>[^\]]+)]](?:{(?<label>[^}]+)})?/gi,
enricher: enrichAward
})
document.body.addEventListener("click", awardAction);
}
export function registerWorldSettings() {
game.settings.register("pf2e-award-xp", "welcomeMessageShown", {
scope: "world",
name: "welcomeMessageShown",
hint: "welcomeMessageShown",
config: false,
type: Boolean,
default: false
});
}
/* -------------------------------------------- */
/* Enrichers */
/* -------------------------------------------- */
/**
* Enrich an award block displaying amounts for each part granted with a GM-control for awarding to the party.
* @param {object} config Configuration data.
* @param {string} [label] Optional label to replace default text.
* @param {EnrichmentOptions} options Options provided to customize text enrichment.
* @returns {HTMLElement|null} An HTML link if the check could be built, otherwise null.
*/
function parseConfig(match) {
const config = { _config: match, values: [] };
for ( const part of match.match(/(?:[^\s"]+|"[^"]*")+/g) ) {
if ( !part ) continue;
const [key, value] = part.split("=");
const valueLower = value?.toLowerCase();
if ( value === undefined ) config.values.push(key.replace(/(^"|"$)/g, ""));
else if ( ["true", "false"].includes(valueLower) ) config[key] = valueLower === "true";
else if ( Number.isNumeric(value) ) config[key] = Number(value);
else config[key] = value.replace(/(^"|"$)/g, "");
}
return config;
}
async function enrichAward(match, options) {
let { type, config, label } = match.groups;
config = parseConfig(config);
config._input = match[0];
const command = config._config;
const block = document.createElement("span");
block.classList.add("award-block", "pf2eaxp");
block.dataset.awardCommand = command;
block.innerHTML += `<a class="award-link" data-action="awardRequest">
<i class="fa-solid fa-trophy"></i> ${label ?? game.i18n.localize("PF2EAXP.Award.Action")}
</a>
`;
return block;
}
/* -------------------------------------------- */
/* -------------------------------------------- */
/* Actions */
/* -------------------------------------------- */
/**
* Forward clicks on award requests to the Award application.
* @param {Event} event The click event triggering the action.
* @returns {Promise|void}
*/
async function awardAction(event) {
const target = event.target.closest('[data-action="awardRequest"]');
const command = target?.closest("[data-award-command]")?.dataset.awardCommand;
if ( !command ) return;
event.stopPropagation();
Award.handleAward(command);
}
class Award extends FormApplication {
static get defaultOptions() {
return foundry.utils.mergeObject(super.defaultOptions, {
classes: ["pf2e", "award", "dialog","pf2eawardxp"],
template: "modules/pf2e-award-xp/templates/apps/award.hbs",
title: "PF2EAXP.Award.Title",
width: 400,
height: "auto",
currency: null,
xp: null,
type: null,
description: null,
destinations: [],
});
}
getData(options={}) {
const context = super.getData(options);
context.xp = this.options.xp ?? 0;
context.description = this.options.description ?? null;
context.destinations = this.options.destinations.length > 0 ? this.options.destinations : game.actors.party.members.filter(m => m.type === "character" && !m.traits.has('eidolon') && !m.traits.has('minion'));
return context;
}
/** @inheritdoc */
async _updateObject(event, formData) {
const data = foundry.utils.expandObject(formData);
this.form.querySelector('button[name="transfer"]').disabled = true;
if(data['award-type'] != "Custom") {data.description = data['award-type'];}
const destinations = []
for (const actor in data.destination){
if (data.destination[actor] == true) destinations.push(game.actors.get(actor))
}
this.close();
if (game.user.isGM){
await this.constructor.awardXP(data.xp, destinations)
await this.constructor.displayAwardMessages(data.xp, data.description, destinations);
}
}
/**
* Update the actors with the current EXP value.
* @param {integer} amount value of EXP to grant.
* @param {array[actors]} destinations text description to be displayed in chatMessage.
*/
static async awardXP(amount, destinations){
if ( !amount || !destinations.length ) return;
for ( const destination of destinations ) {
try {
console.log(`PFPF2E Award XP - ${destination.name} - ${destination.system.details.xp.value}(starting) + ${amount} (award) = ${destination.system.details.xp.value + amount} (total)`)
await destination.update({'system.details.xp.value': destination.system.details.xp.value + amount})
} catch(err) {
ui.notifications.warn(destination.name + ": " + err.message);
}
}
}
/**
* Send the ChatMessage from the template file.
* @param {integer} amount value of EXP to grant.
* @param {string} description text description to be displayed in chatMessage.
* @param {array[actors]} destinations text description to be displayed in chatMessage.
*/
static async displayAwardMessages(amount, description, destinations) {
const context = {
message: game.i18n.format("PF2EAXP.Award.Message",
{name: game.actors.party.name, award: amount, description: description }),
destinations:destinations
}
const content = await renderTemplate("modules/pf2e-award-xp/templates/chat/party.hbs", context);
const messageData = {
type: CONST.CHAT_MESSAGE_STYLES["OTHER"],
content: content,
speaker: ChatMessage.getSpeaker({actor: this.parent}),
rolls: null,
}
return ChatMessage.create(messageData, {});
}
/* -------------------------------------------- */
/* Event Handling */
/* -------------------------------------------- */
/** @inheritDoc */
activateListeners(html) {
super.activateListeners(html);
this._validateForm();
html.find('[name=award-type]').on( "change", function() {
html.find('[name=xp]')[0].value = this.selectedOptions[0].getAttribute("data-xp");
if (this.selectedOptions[0].value == "Custom"){
$(".pf2e_awardxp_description").css("visibility", "visible");
} else {
$(".pf2e_awardxp_description").css("visibility", "hidden");
}
} );
}
/* -------------------------------------------- */
/** @inheritDoc */
_onChangeInput(event) {
super._onChangeInput(event);
this._validateForm();
}
_validateForm() {
const data = foundry.utils.expandObject(this._getSubmitData());
let valid = true;
this.form.querySelector('button[name="transfer"]').disabled = !valid;
}
/* -------------------------------------------- */
/* Chat Command */
/* -------------------------------------------- */
/**
* Regular expression used to match the /award command in chat messages.
* @type {RegExp}
*/
static COMMAND_PATTERN = new RegExp(/^\/award(?:\s|$)/i);
/* -------------------------------------------- */
/**
* Regular expression used to split currency & xp values from their labels.
* @type {RegExp}
*/
//static VALUE_PATTERN = new RegExp(/^(.+?)(\D+)$/);
static VALUE_PATTERN = new RegExp(/^(\d+)(.*)/);
/* -------------------------------------------- */
/**
* Use the `chatMessage` hook to determine if an award command was typed.
* @param {string} message Text of the message being posted.
* @returns {boolean|void} Returns `false` to prevent the message from continuing to parse.
*/
static chatMessage(message) {
if ( !this.COMMAND_PATTERN.test(message) ) return;
this.handleAward(message);
return false;
}
/**
* Parse the award command and grant an award.
* @param {string} message Award command typed in chat.
*/
static async handleAward(message) {
if ( !game.user.isGM ) {
ui.notifications.error("PF2EAXP.Award.NotGMError", { localize: true });
return;
}
try {
const { xp, description } = this.parseAwardCommand(message);
const award = new game.pf2e_awardxp.Award(null,{xp:parseInt(xp), description:description});
award.render(true);
} catch(err) {
ui.notifications.warn(err.message);
}
}
/**
* Parse the award command and grant an award.
* @param {string} message Award command typed in chat.
*/
static parseAwardCommand(message) {
const command = message.replace(this.COMMAND_PATTERN, "");
let [full, xp, description] = command.match(this.VALUE_PATTERN) ?? [];
return { xp, description };
}
/**
* Use the `openDialog` method is a shim to removed in a furture update.
*/
static openDialog(options={}) {
if ( !game.user.isGM ) {
ui.notifications.error("PF2EAXP.Award.NotGMError", { localize: true });
return;
}
let xp = options.award ?? null;
let description = options.description ?? null;
const award = new game.pf2e_awardxp.Award(null,{xp:xp, description:description});
award.render(true);
}
static _welcomeMessage() {
if (!game.settings.get("pf2e-award-xp", "welcomeMessageShown")) {
if (game.user.isGM) {
const content = [`
<div class="pf2eawardxp">
<h3 class="nue">${game.i18n.localize("PF2EAXP.Welcome.Title")}</h3>
<p class="nue">${game.i18n.localize("PF2EAXP.Welcome.WelcomeMessage1")}</p>
<p class="nue">${game.i18n.localize("PF2EAXP.Welcome.WelcomeMessage2")}</p>
<p>
${game.i18n.localize("PF2EAXP.Welcome.WelcomeEnricherJank")}
</p>
<p class="nue">${game.i18n.localize("PF2EAXP.Welcome.WelcomeMessageOutput")}</p>
<p>
${game.i18n.localize("PF2EAXP.Welcome.WelcomeEnricher")}
</p>
<p class="nue">${game.i18n.localize("PF2EAXP.Welcome.WelcomeMessage3")}</p>
<p>
${game.i18n.localize("PF2EAXP.Welcome.WelcomeCommand")}
</p>
<p class="nue"></p>
<footer class="nue"></footer>
</div>
`];
const chatData = content.map(c => {
return {
whisper: [game.user.id],
speaker: { alias: "PF2E Award Exp" },
flags: { core: { canPopout: true } },
content: c
};
});
ChatMessage.implementation.createDocuments(chatData);
//Set flag to not send message again
game.settings.set("pf2e-award-xp", "welcomeMessageShown", true)
}
}
}
}