Keep the source name od effects up to date in the actor sheet.

This commit is contained in:
Johannes Loher 2021-07-23 12:29:01 +02:00
parent f92bbff902
commit 14f87163ff
2 changed files with 25 additions and 4 deletions

View file

@ -3,6 +3,7 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
import { DS4Actor } from "./actor/actor"; import { DS4Actor } from "./actor/actor";
import { getGame } from "./helpers";
declare global { declare global {
interface DocumentClassConfig { interface DocumentClassConfig {
@ -10,7 +11,13 @@ declare global {
} }
} }
type PromisedType<T> = T extends Promise<infer U> ? U : T;
export class DS4ActiveEffect extends ActiveEffect { export class DS4ActiveEffect extends ActiveEffect {
/**
* A cached reference to the source document to avoid recurring database lookups
*/
protected source: PromisedType<ReturnType<typeof fromUuid>> | undefined = undefined;
/** @override */ /** @override */
apply(actor: DS4Actor, change: foundry.data.ActiveEffectData["changes"][number]): unknown { apply(actor: DS4Actor, change: foundry.data.ActiveEffectData["changes"][number]): unknown {
change.value = Roll.replaceFormulaData(change.value, actor.data); change.value = Roll.replaceFormulaData(change.value, actor.data);
@ -23,9 +30,23 @@ export class DS4ActiveEffect extends ActiveEffect {
} }
/** /**
* A public wrapper for {@link ActiveEffect#_getSourceName}. * Gets the current source name based on the cached source object.
*/ */
async getSourceName(): Promise<string> { async getCurrentSourceName(): Promise<string> {
return this._getSourceName(); const game = getGame();
const origin = await this.getSource();
if (origin === null) return game.i18n.localize("None");
return origin.name ?? game.i18n.localize("Unknown");
}
/**
* Gets the source document for this effect. Uses the cached {@link DS4ActiveEffect#origin} if it has already been
* set.
*/
protected async getSource(): ReturnType<typeof fromUuid> {
if (this.source === undefined) {
this.source = this.data.origin !== undefined ? await fromUuid(this.data.origin) : null;
}
return this.source;
} }
} }

View file

@ -49,7 +49,7 @@ export class DS4ActorSheet extends ActorSheet<ActorSheet.Options, DS4ActorSheetD
const enrichedEffectPromises = this.actor.effects.map(async (effect) => { const enrichedEffectPromises = this.actor.effects.map(async (effect) => {
return { return {
...effect.toObject(), ...effect.toObject(),
sourceName: await effect.getSourceName(), sourceName: await effect.getCurrentSourceName(),
}; };
}); });
const enrichedEffects = await Promise.all(enrichedEffectPromises); const enrichedEffects = await Promise.all(enrichedEffectPromises);