From 14f87163ff582b5a96ab2c59aadf5be73e3ad3ec Mon Sep 17 00:00:00 2001 From: Johannes Loher Date: Fri, 23 Jul 2021 12:29:01 +0200 Subject: [PATCH] Keep the source name od effects up to date in the actor sheet. --- src/module/active-effect.ts | 27 +++++++++++++++++++++++--- src/module/actor/sheets/actor-sheet.ts | 2 +- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/module/active-effect.ts b/src/module/active-effect.ts index 6ae292d..d4ace9c 100644 --- a/src/module/active-effect.ts +++ b/src/module/active-effect.ts @@ -3,6 +3,7 @@ // SPDX-License-Identifier: MIT import { DS4Actor } from "./actor/actor"; +import { getGame } from "./helpers"; declare global { interface DocumentClassConfig { @@ -10,7 +11,13 @@ declare global { } } +type PromisedType = T extends Promise ? U : T; export class DS4ActiveEffect extends ActiveEffect { + /** + * A cached reference to the source document to avoid recurring database lookups + */ + protected source: PromisedType> | undefined = undefined; + /** @override */ apply(actor: DS4Actor, change: foundry.data.ActiveEffectData["changes"][number]): unknown { 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 { - return this._getSourceName(); + async getCurrentSourceName(): Promise { + 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 { + if (this.source === undefined) { + this.source = this.data.origin !== undefined ? await fromUuid(this.data.origin) : null; + } + return this.source; } } diff --git a/src/module/actor/sheets/actor-sheet.ts b/src/module/actor/sheets/actor-sheet.ts index 9122a8d..c11ec97 100644 --- a/src/module/actor/sheets/actor-sheet.ts +++ b/src/module/actor/sheets/actor-sheet.ts @@ -49,7 +49,7 @@ export class DS4ActorSheet extends ActorSheet { return { ...effect.toObject(), - sourceName: await effect.getSourceName(), + sourceName: await effect.getCurrentSourceName(), }; }); const enrichedEffects = await Promise.all(enrichedEffectPromises);