-
Notifications
You must be signed in to change notification settings - Fork 3
/
dialog.js
454 lines (415 loc) · 22.2 KB
/
dialog.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
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
import { normaliseCoins, subtractCoins } from "./coins.js";
import { CheckFeat, getPreferredPayMethod, localise, MODULE_NAME, spendingLimit } from "./constants.js";
/**
* Generates a form group HTML for choosing a paying method (for beginning or crafting projets).
*
* @param {"fullCoin" | "preferCoin" | "preferTrove" | "fullTrove" | "free"} preferredDefault One of the potential pay methods.
* @returns {string} The generated form group HTML.
*/
async function getPaymentOptionHTML(preferredDefault = "fullCoin") {
const paymentOptions = [
{ id: "fullCoin", text: localise("ProjectManagement.FullCoin"), selected: preferredDefault === "fullCoin" },
{ id: "preferCoin", text: localise("ProjectManagement.PreferCoin"), selected: preferredDefault === "preferCoin" },
{ id: "preferTrove", text: localise("ProjectManagement.PreferTrove"), selected: preferredDefault === "preferTrove" },
{ id: "fullTrove", text: localise("ProjectManagement.FullTrove"), selected: preferredDefault === "fullTrove" },
{ id: "free", text: localise("ProjectManagement.Free"), selected: preferredDefault === "free" },
];
return await renderTemplate(`modules/${MODULE_NAME}/templates/pay-method.hbs`, { paymentOptions });
}
/**
* Creates a dialog
*
* @param {Object} itemDetails The details of the item to make a project of.
* @param {string} itemDetails.UUID The UUID of the item.
* @param {number} itemDetails.batchSize The size of the batch of the item being crafted.
* Usually 1, 4 or 10, but feats can change this.
* @param {number} itemDetails.DC The crafting DC of the item.
* @param {"fullCoin" | "preferCoin" | "preferTrove" | "fullTrove" | "free"} preferredPayMethod The preferred pay method of the crafter.
* @returns {{startingProgress: game.pf2e.Coins,
* payMethod: "fullCoin" | "preferCoin" | "preferTrove" | "fullTrove" | "free"} | "cancel"}
* An anonymous struct of two values.
* - `startingProgress` is the Coins object of the project's starting Current Value.
* - `payMethod` is the choice of how said starting progress should be paid -- see payWithCoinsAndTrove()
*
* Alternatively, the dialog can return "cancel" if the user pressed the Cancel button.
*/
export async function projectBeginDialog(itemDetails, preferredPayMethod = "fullCoin") {
const item = await fromUuid(itemDetails.UUID);
const maxCost = game.pf2e.Coins.fromPrice(item.price, itemDetails.batchSize || 1).scale(0.5);
return await Dialog.wait({
title: localise("ProjectBeginWindow.Title"),
content: `
<form>
<body>
<section>
<h1>${localise("ProjectBeginWindow.Title")}</h1>
</section>
<section>
<span>${localise("ProjectManagement.CurrentProject")}</span> <strong>${item.name}</strong>
</section>
<section>
${localise("ProjectManagement.RemainingMaterials")} / ${localise("ProjectManagement.MaximumCost")}: <span id="spanNotOverspending"><strong id="remainingMaterials">0 gp</strong> / <strong id="maxCost">0 gp</strong></span><span id="spanOverspending" hidden><strong style="color: red">${localise("ProjectManagement.OverspendingWarning")}</strong></span>
</section>
</body>
<div class="form-group">
<label for="spendingAmount">${localise("ProjectManagement.SpentMaterialsSoFar")}</label>
<input type="text" id="spendingAmount" name="spendingAmount" placeholder="0 gp">
</div>
${await getPaymentOptionHTML(preferredPayMethod)}
</form>
`,
buttons: {
ok: {
label: localise("ProjectBeginWindow.BeginProjectButton"),
icon: "<i class='fa-solid fa-hammer'></i>",
callback: (html) => {
return {
startingProgress: game.pf2e.Coins.fromString($(html).find("#spendingAmount")[0].value).copperValue,
payMethod: $(html).find("#payMethod")[0].value
};
}
},
cancel: {
label: localise("ProjectBeginWindow.CancelButton"),
icon: "<i class='fa-solid fa-ban'></i>",
}
},
default: "ok",
render: ([content]) => {
content
.querySelector("[id=spendingAmount]")
.addEventListener("keyup", (event) => {
const currentSpending = game.pf2e.Coins.fromString(event.target.value);
const remainingSpending = subtractCoins(maxCost, currentSpending);
const form = $(event.target).parent().parent();
form.find("[id=remainingMaterials]").html(!!remainingSpending ? remainingSpending.toString() : maxCost.toString());
if (remainingSpending === null) {
$(event.target).parent().parent().parent().siblings(".dialog-buttons").find(".ok").attr("disabled", "true");
form.find("[id=spanNotOverspending]").attr("hidden", true);
form.find("[id=spanOverspending]").removeAttr("hidden");
} else {
$(event.target).parent().parent().parent().siblings(".dialog-buttons").find(".ok").removeAttr("disabled");
form.find("[id=spanNotOverspending]").removeAttr("hidden");
form.find("[id=spanOverspending]").attr("hidden", true);
}
});
content
.querySelector("[id=maxCost]").innerHTML = maxCost;
content
.querySelector("[id=remainingMaterials]").innerHTML = maxCost;
},
}, { width: 350 });
}
/**
*
* @param {ActorPF2e} actor
* @param {Object} itemDetails The details of the item to make a project of.
* @param {string} itemDetails.UUID The UUID of the item.
* @param {string} itemDetails.projectUUID The UUID of the project itself. Unused.
* @param {number} itemDetails.batchSize The size of the batch of the item being crafted.
* Usually 1, 4 or 10, but feats can change this.
* @returns {{duration: "hour" | "day" | "week",
* overtime: 0 | -5 | -10,
* payMethod: "fullCoin" | "preferCoin" | "preferTrove" | "fullTrove" | "free",
* spendingAmount: game.pf2e.Coins,
* toggles: {XYZ: {value: boolean, rushCost: string}},
* modifiers: {active: boolean, amount: number | string, mode: string, target: string, toggledBy?: string}}}
* An anonymous struct of six values.
* - `duration` determines for how long the crafting activity continues.
* - `overtime` is the Overtime penalty the crafting activity is taking.
* - `payMethod` is the choice of how the crafting activity should be paid for -- see payWithCoinsAndTrove()
* - `spendingAmount` is the Coin the activity will cost.
* - `toggles` is a struct of key-value pairs that were gathered from additional configurations given by feats.
* - `modifiers` is an array of essentially ModifyCraftAProject rule elements,
* with an additional `active` field if they are, well, active.
*
* Alternatively, if cancelled, the dialog will return an empty struct.
*/
export async function projectCraftDialog(actor, itemDetails) {
const item = await fromUuid(itemDetails.UUID);
const extraHTML = [];
let modifiers = [];
for (const rule of actor.rules) {
if (typeof (rule.preCraft) === "function") {
rule.preCraft(item);
}
}
if ("CraftingOption" in actor.synthetics) {
for (const synthetic of actor.synthetics["CraftingOption"]) {
const key = synthetic.label
.replace(/([a-z])([A-Z])/g, "$1-$2")
.replace(/[\s_]+/g, '-')
.toLowerCase();
const checked = synthetic.default ? "checked" : "";
const disabled = synthetic.toggleable ? "" : "disabled";
extraHTML.push(`
<div class="form-group extra-craft-modifiers" >
<label for="${key}">${synthetic.label} <strong style="color: red" hidden></strong></label>
<input type="checkbox" id="${key}" name="${key}" ${checked} ${disabled}>
</div>
<p class="notes">${synthetic.desc}</p>
`);
}
}
if ("ModifyCraftAProject" in actor.synthetics) {
for (const synthetic of actor.synthetics["ModifyCraftAProject"]) {
synthetic.active = synthetic.toggledBy ? false : true;
modifiers.push(synthetic);
}
}
// Purely a fancy thing, but add a horizontal line in front of the custom feat stuff if there is any.
if (extraHTML.length > 0) {
extraHTML.unshift(`<hr>`);
}
return await Dialog.wait({
title: localise("CraftWindow.Title"),
content: `
<form>
<body>
<section>
<h1>${localise("CraftWindow.Title")}</h1>
</section>
<section>
${localise("ProjectManagement.CurrentProject")}: <strong>${item.name}</strong>
</section>
<section>
${localise("ProjectManagement.RemainingMaterials")} / ${localise("ProjectManagement.MaximumCost")}: <span id="spanNotOverspending"><strong id="remainingMaterials">0 gp</strong> / <strong id="maxCost">0 gp</strong></span><span id="spanOverspending" hidden><strong style="color: red">${localise("ProjectManagement.OverspendingWarning")}</strong></span>
</section>
</body>
<div class="form-group">
<label for="spendingAmount">${localise("ProjectManagement.SpentMaterialsSoFar")}</label>
<input type="text" id="spendingAmount" name="spendingAmount" placeholder="0 gp">
</div>
<div class="form-group">
<label for="craftDuration">${localise("CraftWindow.CraftingDuration.Title")}</label>
<select autofocus id="craftDuration" name="craftDuration">
<option value="hour">${localise("CraftWindow.CraftingDuration.Hour")}</option>
<option value="day">${localise("CraftWindow.CraftingDuration.Day")}</option>
<option value="week">${localise("CraftWindow.CraftingDuration.Week")}</option>
</select>
</div>
<div class="form-group">
<label for="overtimePenalty">${localise("CraftWindow.OvertimePenalty.Title")}</label>
<select id="overtimePenalty" name="overtimePenalty">
<option value=0>${localise("CraftWindow.OvertimePenalty.NoOvertime")}</option>
<option value=-5>-5</option>
<option value=-10> -10</option>
</select>
</div>
${await getPaymentOptionHTML(getPreferredPayMethod(actor))}
${extraHTML.join('\n')}
</form>
`,
buttons: {
ok: {
label: localise("CraftWindow.CraftProjectButton"),
icon: "<i class='fa-solid fa-hammer'></i>",
callback: (html) => {
const toggles = {};
$(html).find(".extra-craft-modifiers input").each(function () {
const input = $(this)[0];
toggles[input.name] = {
value: input.checked,
rushCost: input.parentElement.querySelector("label > strong").innerHTML
};
});
return {
duration: $(html).find("#craftDuration")[0].value,
overtime: Number($(html).find("#overtimePenalty")[0].value) || 0,
payMethod: $(html).find("#payMethod")[0].value,
spendingAmount: game.pf2e.Coins.fromString($(html).find("#spendingAmount")[0].value),
toggles,
modifiers
};
}
},
cancel: {
label: localise("CraftWindow.CancelButton"),
icon: "<i class='fa-solid fa-ban'></i>",
callback: (html) => {
return {};
}
}
},
default: "ok",
close: (html) => {
actor.synthetics["CraftingOption"] = [];
actor.synthetics["ModifyCraftAProject"] = [];
},
render: ([content]) => {
content
.querySelector("[id=craftDuration]")
.addEventListener("change", (event) => {
let multipliers = 1;
modifiers.forEach((modifier) => {
if (modifier.target === "max" && modifier.active && modifier.mode === "multiply") {
multipliers = multipliers * modifier.amount;
}
});
const maxCost = normaliseCoins(spendingLimit(event.target.value, actor.level).scale(itemDetails.batchSize).scale(multipliers).copperValue);
$(event.target).parent().parent().find("[id=maxCost]").html(maxCost.toString());
event.target.parentElement.parentElement.querySelector("#spendingAmount").dispatchEvent(new Event("keyup"));
});
content
.querySelector("[id=spendingAmount]")
.addEventListener("keyup", (event) => {
const maxCost = game.pf2e.Coins.fromString($(event.target).parent().parent().find("[id=maxCost]").html());
const currentSpending = game.pf2e.Coins.fromString(event.target.value);
const remainingSpending = subtractCoins(maxCost, currentSpending);
const form = $(event.target).parent().parent();
form.find("[id=remainingMaterials]").html(!!remainingSpending ? remainingSpending.toString() : maxCost.toString());
if (remainingSpending === null) {
$(event.target).parent().parent().parent().siblings(".dialog-buttons").find(".ok").attr("disabled", "true");
form.find("[id=spanNotOverspending]").attr("hidden", true);
form.find("[id=spanOverspending]").removeAttr("hidden");
} else {
$(event.target).parent().parent().parent().siblings(".dialog-buttons").find(".ok").removeAttr("disabled");
form.find("[id=spanNotOverspending]").removeAttr("hidden");
form.find("[id=spanOverspending]").attr("hidden", true);
}
const craftModifierLabels = event.target.parentElement.parentElement.querySelectorAll("div.extra-craft-modifiers > label > strong");
for (let index = 0; index < craftModifierLabels.length; index++) {
craftModifierLabels[index].dispatchEvent(new Event("change"));
}
});
const extraCraftModifierDivs = content
.querySelectorAll("div.extra-craft-modifiers");
for (let i = 0; i < extraCraftModifierDivs.length; i++) {
extraCraftModifierDivs[i].querySelector("input").addEventListener("change", (event) => {
for (const modifier of modifiers) {
if (modifier.toggledBy === event.target.id) {
modifier.active = event.target.checked;
switch (modifier.target) {
case "max":
event.target.parentElement.parentElement.querySelector("#craftDuration").dispatchEvent(new Event("change"));
break;
case "rushCost":
$(event.target).siblings("label").find("strong").attr("amount", modifier.amount);
if (modifier.active) {
$(event.target).siblings("label").find("strong").removeAttr("hidden");
} else {
$(event.target).siblings("label").find("strong").attr("hidden", true);
}
event.target.parentElement.querySelector("label > strong").dispatchEvent(new Event("change"));
break;
}
}
}
});
extraCraftModifierDivs[i].querySelector("label > strong").addEventListener("change", (event) => {
const cost = game.pf2e.Coins.fromString($(event.target).parent().parent().parent().find("[id=spendingAmount]").val()).scale($(event.target).attr("amount"));
$(event.target).html(cost.toString());
});
}
let multipliers = 1;
modifiers.forEach((modifier) => {
if (modifier.target === "max" && modifier.active && modifier.mode === "multiply") {
multipliers = multipliers * modifier.amount;
}
});
const maxCost = spendingLimit("Hour", actor.level).scale(itemDetails.batchSize).scale(multipliers);
content
.querySelector("[id=maxCost]").innerHTML = maxCost;
content
.querySelector("[id=remainingMaterials]").innerHTML = maxCost;
},
});
}
/**
* Edits a project.
*
* @param {Object} projectDetails The project being edit.
* @param {string} projectDetails.ID The UUID of the project itself.
* @param {string} projectDetails.ItemUUID The UUID of the item specifically.
* @param {number} projectDetails.progressInCopper The current progress on the project, measured in copper.
* @param {number} projectDetails.batchSize The amount of items being made at once.
* Usually relevant for consumables more, and is 1 for permanent items.
* @param {number} projectDetails.DC The Crafting DC of the project.
*/
export async function projectEditDialog(projectDetails) {
const item = await fromUuid(projectDetails.ItemUUID);
return await Dialog.wait({
title: localise("EditProjectWindow.Title"),
content: `
<form>
<body>
<section>
<h1>${localise("EditProjectWindow.Title")}</h1>
</section>
<section>
<span>${localise("ProjectManagement.CurrentProject")}:</span> <strong>${item.name}</strong>
</section>
</body>
<div class="form-group">
<label for="currentProgress">${localise("ProjectManagement.CurrentProgress")}</label>
<input type="text" id="currentProgress" name="currentProgress" placeholder="0 gp" value="${normaliseCoins(projectDetails.progressInCopper).toString()}">
</div>
<div class="form-group">
<label for="DC">${localise("EditProjectWindow.DC")}</label>
<input type="number" name="DC" id="DC" value=${projectDetails.DC} min=0 step=1>
</div>
<div class="form-group">
<label for="batchSize">${localise("EditProjectWindow.BatchSize")}</label>
<input type="number" name="batchSize" id="batchSize" value=${projectDetails.batchSize} min=1 step=1>
</div>
</form>
`,
buttons: {
ok: {
label: localise("EditProjectWindow.ConfirmChangesButton"),
icon: "<i class='fas fa-edit fa-1x fa-fw'></i>",
callback: (html) => {
return {
progressInCopper: game.pf2e.Coins.fromString($(html).find("#currentProgress")[0].value).copperValue || -1,
DC: Number($(html).find("#DC")[0].value) || -1,
batchSize: Number($(html).find("#batchSize")[0].value) || -1,
};
}
},
cancel: {
label: localise("EditProjectWindow.CancelButton"),
icon: "<i class='fa-solid fa-ban'></i>",
}
},
default: "ok"
}, { width: 350 });
}
/**
* Posts a project to chat.
*
* @param {ActorPF2e} actor The actor whose project to display in chat.
* @param {string} projectUUID The ID of the project.
*/
export async function projectToChat(actor, projectUUID) {
if (!projectUUID || projectUUID === "") {
console.error("[HEROIC CRAFTING AUTOMATION] Missing Project UUID when posting to chat!");
return;
}
const actorProjects = actor.getFlag(MODULE_NAME, "projects") ?? [];
const project = actorProjects.filter(project => project.ID === projectUUID)[0];
if (!project) {
ui.notifications.error(localise("CharSheet.CannotPostToChat", { name: actor.name, projectUUID }));
return;
}
const item = await fromUuid(project.ItemUUID);
const currentValue = normaliseCoins(project.progressInCopper);
const price = game.pf2e.Coins.fromPrice(item.price, project.batchSize);
const projectDetails = {
UUID: project.ID,
actorID: actor.id,
itemID: project.ItemUUID,
itemImg: item.img,
itemName: item.name,
itemDesc: item.description,
DC: project.DC,
batchSize: project.batchSize,
currentValue: currentValue.toString(),
price: price.toString(),
completion: `${Math.floor(currentValue.copperValue / price.copperValue * 100)}% `
}
ChatMessage.create({
user: game.user.id,
content: await renderTemplate(`modules/${MODULE_NAME}/templates/project-card.hbs`, projectDetails),
speaker: { alias: actor.name },
});
}