Consolidate armor source retrieval

This commit is contained in:
Carlos Fernandez 2026-03-21 18:57:51 -04:00
parent 1cdabf15a5
commit b6b207299c
4 changed files with 68 additions and 62 deletions

View file

@ -744,15 +744,27 @@ export function getUnusedDamageTypes(parts) {
}, []);
}
/**
*
* @param {{ type: string, parent: Object, disabled: boolean, isSuppressed: boolean }} sources
* @param { boolean } increasing
* @returns
*/
export function orderSourcesForArmorAutoChange(sources, increasing) {
const getSourceWeight = source => {
switch (source.type) {
/** Returns resolved armor sources ordered by application order */
export function getArmorSources(actor) {
const rawArmorSources = Array.from(actor.allApplicableEffects()).filter(x => x.system.armorData);
if (actor.system.armor) rawArmorSources.push(actor.system.armor);
const data = rawArmorSources.map(doc => {
// Get the origin item. Since the actor is already loaded, it should already be cached
// Consider the relative function versions if this causes an issue
const isItem = doc instanceof Item;
const origin = isItem ? doc : doc.origin ? foundry.utils.fromUuidSync(doc.origin) : doc.parent;
return {
origin,
name: origin.name,
document: doc,
data: doc.system.armor ?? doc.system.armorData,
disabled: !!doc.disabled || !!doc.isSuppressed
};
});
return sortBy(data, ({ origin }) => {
switch (origin?.type) {
case 'class':
case 'subclass':
case 'ancestry':
@ -760,23 +772,38 @@ export function orderSourcesForArmorAutoChange(sources, increasing) {
case 'feature':
case 'domainCard':
return 2;
case 'armor':
return 3;
case 'loot':
case 'consumable':
return 3;
case 'character':
return 4;
case 'weapon':
return 5;
case 'character':
case 'armor':
return 6;
default:
return 1;
}
};
return sources
.filter(x => !x.disabled && !x.isSuppressed)
.sort((a, b) =>
increasing ? getSourceWeight(b) - getSourceWeight(a) : getSourceWeight(a) - getSourceWeight(b)
);
});
}
/**
* Returns an array sorted by a function that returns a thing to compare, or an array to compare in order
* Similar to lodash's sortBy function.
*/
export function sortBy(arr, fn) {
const directCompare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
const cmp = (a, b) => {
const resultA = fn(a);
const resultB = fn(b);
if (Array.isArray(resultA) && Array.isArray(resultB)) {
for (let idx = 0; idx < Math.min(resultA.length, resultB.length); idx++) {
const result = directCompare(resultA[idx], resultB[idx]);
if (result !== 0) return result;
}
return 0;
}
return directCompare(resultA, resultB);
};
return arr.sort(cmp);
}