foundry-sw5e/module/apps/trait-selector.js

87 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-06-24 14:23:02 -04:00
/**
* A specialized form used to select from a checklist of attributes, traits, or properties
* @implements {FormApplication}
2020-06-24 14:23:02 -04:00
*/
2020-09-11 17:11:11 -04:00
export default class TraitSelector extends FormApplication {
2020-06-24 14:23:02 -04:00
/** @override */
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
id: "trait-selector",
2020-06-24 14:23:02 -04:00
classes: ["sw5e"],
title: "Actor Trait Selection",
template: "systems/sw5e/templates/apps/trait-selector.html",
width: 320,
height: "auto",
choices: {},
allowCustom: true,
minimum: 0,
maximum: null
});
}
/* -------------------------------------------- */
/**
* Return a reference to the target attribute
* @type {String}
*/
get attribute() {
return this.options.name;
2020-06-24 14:23:02 -04:00
}
/* -------------------------------------------- */
/** @override */
getData() {
// Get current values
let attr = getProperty(this.object._data, this.attribute);
if (getType(attr) !== "Object") attr = {value: [], custom: ""};
2020-06-24 14:23:02 -04:00
// Populate choices
2020-06-24 14:23:02 -04:00
const choices = duplicate(this.options.choices);
for (let [k, v] of Object.entries(choices)) {
2020-06-24 14:23:02 -04:00
choices[k] = {
label: v,
chosen: attr ? attr.value.includes(k) : false
};
2020-06-24 14:23:02 -04:00
}
// Return data
return {
2020-06-24 14:23:02 -04:00
allowCustom: this.options.allowCustom,
choices: choices,
2020-06-24 14:23:02 -04:00
custom: attr ? attr.custom : ""
};
2020-06-24 14:23:02 -04:00
}
/* -------------------------------------------- */
/** @override */
_updateObject(event, formData) {
const updateData = {};
// Obtain choices
const chosen = [];
for (let [k, v] of Object.entries(formData)) {
if (k !== "custom" && v) chosen.push(k);
2020-06-24 14:23:02 -04:00
}
updateData[`${this.attribute}.value`] = chosen;
// Validate the number chosen
if (this.options.minimum && chosen.length < this.options.minimum) {
2020-06-24 14:23:02 -04:00
return ui.notifications.error(`You must choose at least ${this.options.minimum} options`);
}
if (this.options.maximum && chosen.length > this.options.maximum) {
2020-06-24 14:23:02 -04:00
return ui.notifications.error(`You may choose no more than ${this.options.maximum} options`);
}
// Include custom
if (this.options.allowCustom) {
2020-06-24 14:23:02 -04:00
updateData[`${this.attribute}.custom`] = formData.custom;
}
// Update the object
this.object.update(updateData);
}
}