Bug/chat roll fixes (#726)

* #635 & #637

* #653

* Fix: #681 #682 #685 #686

* Fix duplicate messages

* Remove comments
This commit is contained in:
Dapoulp 2025-08-08 21:34:55 +02:00 committed by GitHub
parent 5d0a4382cc
commit f9cb0954f9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 242 additions and 546 deletions

View file

@ -333,6 +333,20 @@ export default function DHApplicationMixin(Base) {
const doc = getDocFromElementSync(target);
return doc?.system?.attack?.damage.parts.length || doc?.damage?.parts.length;
},
callback: async (target, event) => {
const doc = await getDocFromElement(target),
action = doc?.system?.attack ?? doc;
return action && action.use(event, { byPassRoll: true })
}
});
options.unshift({
name: 'DAGGERHEART.APPLICATIONS.ContextMenu.useItem',
icon: 'fa-solid fa-burst',
condition: target => {
const doc = getDocFromElementSync(target);
return doc?.system?.attack?.damage.parts.length || doc?.damage?.parts.length;
},
callback: async (target, event) => {
const doc = await getDocFromElement(target),
action = doc?.system?.attack ?? doc;

View file

@ -33,14 +33,6 @@ export default class DhpChatLog extends foundry.applications.sidebar.tabs.ChatLo
html.querySelectorAll('.simple-roll-button').forEach(element =>
element.addEventListener('click', event => this.onRollSimple(event, data.message))
);
html.querySelectorAll('.target-container').forEach(element => {
element.addEventListener('mouseenter', this.hoverTarget);
element.addEventListener('mouseleave', this.unhoverTarget);
element.addEventListener('click', this.clickTarget);
});
html.querySelectorAll('.button-target-selection').forEach(element => {
element.addEventListener('click', event => this.onTargetSelection(event, data.message));
});
html.querySelectorAll('.healing-button').forEach(element =>
element.addEventListener('click', event => this.onHealing(event, data.message))
);
@ -138,33 +130,6 @@ export default class DhpChatLog extends foundry.applications.sidebar.tabs.ChatLo
});
}
onTargetSelection(event, message) {
event.stopPropagation();
const msg = ui.chat.collection.get(message._id);
msg.system.targetMode = Boolean(event.target.dataset.targetHit);
}
hoverTarget(event) {
event.stopPropagation();
const token = canvas.tokens.get(event.currentTarget.dataset.token);
if (!token?.controlled) token._onHoverIn(event, { hoverOutOthers: true });
}
unhoverTarget(event) {
const token = canvas.tokens.get(event.currentTarget.dataset.token);
if (!token?.controlled) token._onHoverOut(event);
}
clickTarget(event) {
event.stopPropagation();
const token = canvas.tokens.get(event.currentTarget.dataset.token);
if (!token) {
ui.notifications.info(game.i18n.localize('DAGGERHEART.UI.Notifications.attackTargetDoesNotExist'));
return;
}
game.canvas.pan(token);
}
async onRollSimple(event, message) {
const buttonType = event.target.dataset.type ?? 'damage',
total = message.rolls.reduce((a, c) => a + Roll.fromJSON(c).total, 0),

View file

@ -115,7 +115,6 @@ export default class DHBaseAction extends ActionMixin(foundry.abstract.DataModel
if (!this.actor) throw new Error("An Action can't be used outside of an Actor context.");
if (this.chatDisplay) await this.toChat();
let { byPassRoll } = options,
config = this.prepareConfig(event, byPassRoll);
for (let i = 0; i < this.constructor.extraSchemas.length; i++) {
@ -145,9 +144,9 @@ export default class DHBaseAction extends ActionMixin(foundry.abstract.DataModel
if (this.rollDamage && this.damage.parts.length) await this.rollDamage(event, config);
else if (this.trigger) await this.trigger(event, config);
else if (this.hasSave || this.hasEffect) {
const roll = new Roll('');
const roll = new CONFIG.Dice.daggerheart.DHRoll('');
roll._evaluated = true;
if (this.hasTarget) config.targetSelection = config.targets.length > 0;
if(config.hasTarget) config.targetSelection = config.targets.length > 0;
await CONFIG.Dice.daggerheart.DHRoll.toMessage(roll, config);
}
}
@ -180,7 +179,6 @@ export default class DHBaseAction extends ActionMixin(foundry.abstract.DataModel
hasHealing: this.damage?.parts?.length && this.type === 'healing',
hasEffect: !!this.effects?.length,
hasSave: this.hasSave,
hasTarget: true,
selectedRollMode: game.settings.get('core', 'rollMode'),
isFastForward: event.shiftKey,
data: this.getRollData(),
@ -248,8 +246,11 @@ export default class DHBaseAction extends ActionMixin(foundry.abstract.DataModel
)
this.update({ 'uses.value': this.uses.value + 1 });
if (config.roll?.success || successCost)
(config.message ?? config.parent).update({ 'system.successConsumed': true });
if(config.roll?.success || successCost) {
setTimeout(() => {
(config.message ?? config.parent).update({'system.successConsumed': true})
}, 50);
}
}
/* */
@ -368,15 +369,15 @@ export default class DHBaseAction extends ActionMixin(foundry.abstract.DataModel
async updateChatMessage(message, targetId, changes, chain = true) {
setTimeout(async () => {
const chatMessage = ui.chat.collection.get(message._id),
msgTarget =
chatMessage.system.targets.find(mt => mt.id === targetId) ??
chatMessage.system.oldTargets.find(mt => mt.id === targetId);
msgTarget.saved = changes;
const chatMessage = ui.chat.collection.get(message._id);
await chatMessage.update({
system: {
targets: chatMessage.system.targets,
oldTargets: chatMessage.system.oldTargets
flags: {
[game.system.id]: {
"reactionRolls": {
[targetId]: changes
}
}
}
});
}, 100);

View file

@ -25,7 +25,6 @@ export default class DHActorRoll extends foundry.abstract.TypeDataModel {
title: new fields.StringField(),
roll: new fields.ObjectField(),
targets: targetsField(),
oldTargets: targetsField(),
targetSelection: new fields.BooleanField({ initial: false }),
hasRoll: new fields.BooleanField({ initial: false }),
hasDamage: new fields.BooleanField({ initial: false }),
@ -63,24 +62,14 @@ export default class DHActorRoll extends foundry.abstract.TypeDataModel {
return actionItem.system.actionsList?.find(a => a.id === this.source.action);
}
get messageTemplate() {
return 'systems/daggerheart/templates/ui/chat/roll.hbs';
}
get targetMode() {
return this.targetSelection;
}
set targetMode(mode) {
this.targetSelection = mode;
this.updateTargets();
this.registerTargetHook();
this.parent.update({
system: {
targetSelection: this.targetSelection,
oldTargets: this.oldTargets
}
});
this.updateTargets();
}
get hitTargets() {
@ -88,29 +77,25 @@ export default class DHActorRoll extends foundry.abstract.TypeDataModel {
}
async updateTargets() {
this.currentTargets = this.getTargetList();
if (!this.targetSelection) {
this.currentTargets.forEach(ct => {
if (this.targets.find(t => t.actorId === ct.actorId)) return;
const indexTarget = this.oldTargets.findIndex(ot => ot.actorId === ct.actorId);
if (indexTarget === -1) this.oldTargets.push(ct);
});
if (this.hasSave) this.setPendingSaves();
if (this.currentTargets.length) {
if (!this.parent._id) return;
const updates = await this.parent.update({
system: {
oldTargets: this.oldTargets
}
});
if (!updates && ui.chat.collection.get(this.parent.id)) ui.chat.updateMessage(this.parent);
if(!ui.chat.collection.get(this.parent.id)) return;
let targets;
if(this.targetSelection)
targets = this.targets;
else
targets = Array.from(game.user.targets).map(t => game.system.api.fields.ActionFields.TargetField.formatTarget(t));
this.parent.setFlag(game.system.id, "targets", targets);
await this.parent.updateSource({
system: {
targetSelection: this.targetSelection
}
}
});
}
registerTargetHook() {
if (this.targetSelection && this.targetHook !== null) {
Hooks.off('targetToken', this.targetHook);
if(!this.parent.isAuthor) return;
if(this.targetSelection && this.targetHook !== null) {
Hooks.off("targetToken", this.targetHook);
this.targetHook = null;
} else if (!this.targetSelection && this.targetHook === null) {
this.targetHook = Hooks.on('targetToken', foundry.utils.debounce(this.updateTargets.bind(this), 50));
@ -120,35 +105,35 @@ export default class DHActorRoll extends foundry.abstract.TypeDataModel {
prepareDerivedData() {
if (this.hasTarget) {
this.hasHitTarget = this.targets.filter(t => t.hit === true).length > 0;
this.updateTargets();
this.registerTargetHook();
if (this.targetSelection === true) {
this.targetShort = this.targets.reduce(
(a, c) => {
if (c.hit) a.hit += 1;
else a.miss += 1;
return a;
},
{ hit: 0, miss: 0 }
);
this.currentTargets = this.getTargetList();
this. registerTargetHook();
if(this.targetSelection === true && this.hasRoll) {
this.targetShort = this.targets.reduce((a,c) => {
if(c.hit) a.hit += 1;
else a.miss += 1;
return a;
}, {hit: 0, miss: 0})
}
if (this.hasSave) this.setPendingSaves();
}
this.canViewSecret = this.parent.speakerActor?.testUserPermission(game.user, 'OBSERVER');
this.canButtonApply = game.user.isGM;
}
getTargetList() {
return this.targetSelection !== true
? Array.from(game.user.targets).map(t => {
const target = game.system.api.fields.ActionFields.TargetField.formatTarget(t),
oldTarget =
this.targets.find(ot => ot.actorId === target.actorId) ??
this.oldTargets.find(ot => ot.actorId === target.actorId);
if (oldTarget) return oldTarget;
return target;
})
: this.targets;
const targets = this.targetSelection && this.parent.isAuthor ? this.targets : (this.parent.getFlag(game.system.id, "targets") ?? this.targets),
reactionRolls = this.parent.getFlag(game.system.id, "reactionRolls");
if(reactionRolls) {
Object.entries(reactionRolls).forEach(([k, r]) => {
const target = targets.find(t => t.id === k);
if(target) target.saved = r;
});
}
return targets;
}
setPendingSaves() {

View file

@ -15,6 +15,7 @@ export default class TargetField extends fields.SchemaField {
static prepareConfig(config) {
if (!this.target?.type) return [];
config.hasTarget = true;
let targets;
if (this.target?.type === CONFIG.DH.GENERAL.targetTypes.self.id)
targets = [this.actor.token ?? this.actor.prototypeToken];

View file

@ -285,6 +285,7 @@ export function ActionMixin(Base) {
}
};
ChatMessage.applyRollMode(msg, game.settings.get('core', 'rollMode'));
cls.create(msg);
}
}

View file

@ -139,17 +139,17 @@ export default class D20Roll extends DHRoll {
static postEvaluate(roll, config = {}) {
const data = super.postEvaluate(roll, config);
data.type = config.roll?.type;
data.difficulty = config.roll.difficulty;
if (config.targets?.length) {
config.targetSelection = true;
config.targets.forEach(target => {
const difficulty = config.roll.difficulty ?? target.difficulty ?? target.evasion;
target.hit = roll.isCritical || roll.total >= difficulty;
});
data.success = config.targets.some(target => target.hit);
} else if (config.roll.difficulty) {
data.difficulty = config.roll.difficulty;
data.success = config.targets.some(target => target.hit)
} else if (config.roll.difficulty)
data.success = roll.isCritical || roll.total >= config.roll.difficulty;
}
data.advantage = {
type: config.roll.advantage,
dice: roll.dAdvantage?.denomination,

View file

@ -30,16 +30,16 @@ export default class DamageRoll extends DHRoll {
}
static async buildPost(roll, config, message) {
const chatMessage = config.source?.message ? ui.chat.collection.get(config.source.message) : getDocumentClass('ChatMessage').applyRollMode({}, config.rollMode);
if (game.modules.get('dice-so-nice')?.active) {
const pool = foundry.dice.terms.PoolTerm.fromRolls(
Object.values(config.damage).flatMap(r => r.parts.map(p => p.roll))
),
diceRoll = Roll.fromTerms([pool]);
await game.dice3d.showForRoll(diceRoll, game.user, true);
await game.dice3d.showForRoll(diceRoll, game.user, true, chatMessage.whisper, chatMessage.blind);
}
await super.buildPost(roll, config, message);
if (config.source?.message) {
const chatMessage = ui.chat.collection.get(config.source.message);
chatMessage.update({ 'system.damage': config.damage });
}
}

View file

@ -2,7 +2,7 @@ import D20RollDialog from '../applications/dialogs/d20RollDialog.mjs';
export default class DHRoll extends Roll {
baseTerms = [];
constructor(formula, data, options) {
constructor(formula, data = {}, options = {}) {
super(formula, data, options);
if (!this.data || !Object.keys(this.data).length) this.data = options.data;
}
@ -15,6 +15,8 @@ export default class DHRoll extends Roll {
static messageType = 'adversaryRoll';
static CHAT_TEMPLATE = 'systems/daggerheart/templates/ui/chat/roll.hbs';
static DefaultDialog = D20RollDialog;
static async build(config = {}, message = {}) {
@ -92,9 +94,36 @@ export default class DHRoll extends Roll {
system: config,
rolls: [roll]
};
config.selectedRollMode ??= game.settings.get('core', 'rollMode');
if(roll._evaluated) return await cls.create(msg, { rollMode: config.selectedRollMode });
return msg;
}
/** @inheritDoc */
async render({flavor, template=this.constructor.CHAT_TEMPLATE, isPrivate=false, ...options}={}) {
if ( !this._evaluated ) return;
const chatData = await this._prepareChatRenderContext({flavor, isPrivate, ...options});
return foundry.applications.handlebars.renderTemplate(template, chatData);
}
/** @inheritDoc */
async _prepareChatRenderContext({flavor, isPrivate=false, ...options}={}) {
if(isPrivate) {
return {
user: game.user.id,
flavor: null,
title: "???",
roll: {
total: "??"
},
hasRoll: true,
isPrivate
}
} else {
options.message.system.user = game.user.id;
return options.message.system;
}
}
static applyKeybindings(config) {
if (config.event)

View file

@ -149,7 +149,7 @@ export default class DualityRoll extends D20Roll {
}
if (this.rallyFaces)
this.terms.push(
new foundry.dice.terms.OperatorTerm({ operator: this.hasDisadvantage ? '-' : '+' }),
new foundry.dice.terms.OperatorTerm({ operator: '+' }),
new foundry.dice.terms.Die({ faces: this.rallyFaces })
);
}

View file

@ -1,21 +1,31 @@
export default class DhpChatMessage extends foundry.documents.ChatMessage {
async renderHTML() {
if (this.system.messageTemplate)
this.content = await foundry.applications.handlebars.renderTemplate(this.system.messageTemplate, {
...this.system,
_source: this.system._source
});
const actor = game.actors.get(this.speaker.actor);
const actorData = actor ?? {
const actorData = actor && this.isContentVisible ? actor : {
img: this.author.avatar ? this.author.avatar : 'icons/svg/mystery-man.svg',
name: ''
};
/* We can change to fully implementing the renderHTML function if needed, instead of augmenting it. */
const html = await super.renderHTML({ actor: actorData, author: this.author });
this.applyPermission(html);
if (this.type === 'dualityRoll') {
this.enrichChatMessage(html);
this.addChatListeners(html);
return html;
}
enrichChatMessage(html) {
const elements = html.querySelectorAll('[data-perm-id]');
elements.forEach(e => {
const uuid = e.dataset.permId,
document = fromUuidSync(uuid);
if (!document) return;
e.setAttribute('data-view-perm', document.testUserPermission(game.user, 'OBSERVER'));
e.setAttribute('data-use-perm', document.testUserPermission(game.user, 'OWNER'));
});
if (this.isContentVisible && this.type === 'dualityRoll') {
html.classList.add('duality');
switch (this.system.roll?.result?.duality) {
case 1:
@ -29,36 +39,9 @@ export default class DhpChatMessage extends foundry.documents.ChatMessage {
break;
}
}
this.enrichChatMessage(html);
return html;
}
applyPermission(html) {
const elements = html.querySelectorAll('[data-perm-id]');
elements.forEach(e => {
const uuid = e.dataset.permId,
document = fromUuidSync(uuid);
if (!document) return;
e.setAttribute('data-view-perm', document.testUserPermission(game.user, 'OBSERVER'));
e.setAttribute('data-use-perm', document.testUserPermission(game.user, 'OWNER'));
});
}
async _preCreate(data, options, user) {
options.speaker = ChatMessage.getSpeaker();
const rollActorOwner = data.rolls?.[0]?.data?.parent?.owner;
if (rollActorOwner) {
data.author = rollActorOwner ? rollActorOwner.id : data.author;
await this.updateSource({ author: rollActorOwner ?? user });
}
return super._preCreate(data, options, rollActorOwner ?? user);
}
enrichChatMessage(html) {
addChatListeners(html) {
html.querySelectorAll('.damage-button').forEach(element =>
element.addEventListener('click', this.onDamage.bind(this))
);
@ -66,6 +49,16 @@ export default class DhpChatMessage extends foundry.documents.ChatMessage {
html.querySelectorAll('.duality-action-effect').forEach(element =>
element.addEventListener('click', this.onApplyEffect.bind(this))
);
html.querySelectorAll('.roll-target').forEach(element => {
element.addEventListener('mouseenter', this.hoverTarget);
element.addEventListener('mouseleave', this.unhoverTarget);
element.addEventListener('click', this.clickTarget);
});
html.querySelectorAll('.button-target-selection').forEach(element => {
element.addEventListener('click', this.onTargetSelection.bind(this));
});
}
getTargetList() {
@ -146,4 +139,30 @@ export default class DhpChatMessage extends foundry.documents.ChatMessage {
if (action) action.consume(this.system, true);
}
}
hoverTarget(event) {
event.stopPropagation();
const token = canvas.tokens.get(event.currentTarget.dataset.token);
if (!token?.controlled) token._onHoverIn(event, { hoverOutOthers: true });
}
unhoverTarget(event) {
const token = canvas.tokens.get(event.currentTarget.dataset.token);
if (!token?.controlled) token._onHoverOut(event);
}
clickTarget(event) {
event.stopPropagation();
const token = canvas.tokens.get(event.currentTarget.dataset.token);
if (!token) {
ui.notifications.info(game.i18n.localize('DAGGERHEART.UI.Notifications.attackTargetDoesNotExist'));
return;
}
game.canvas.pan(token);
}
onTargetSelection(event) {
event.stopPropagation();
this.system.targetMode = Boolean(event.target.dataset.targetHit);
}
}