feat: add round-based tracked effects

- add generic encounter effects with round countdown, damage expiry, logs, and undo/redo
- add 5e Turned and Spiritual Weapon presets inside existing Conditions panel
- support custom participant or encounter effects with owner, notes, duration, and player visibility
- convert 5e minute durations to rounds while keeping generic rules round-only
- show prominent or compact effects on player and DM participant cards
- attach owner-linked encounter effects to owner card with global fallback for ownerless effects
- add direct turns-left editing plus step controls
This commit is contained in:
david raistrick committed 2026-10-20 18:09:56 -04:00
1 parent bca406fca9
commit 295c7e06b4
5 files changed
+814 -28

No files matched your search

+153 -27
View File
@@ -233,6 +233,7 @@ function expandUndo(entry, currentEnc) {
}
case 'damage':
case 'heal':
case 'hp_change':
case 'death_save':
case 'stabilize':
case 'revive':
@@ -258,8 +259,23 @@ function expandUndo(entry, currentEnc) {
};
return {
encounterPath: encPath,
updates: { participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(oldVals) } : p) },
redo: { participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(newVals) } : p) },
updates: {
participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(oldVals) } : p),
...(u.oldEffects ? { effects: u.oldEffects } : {}),
},
redo: {
participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(newVals) } : p),
...(u.newEffects ? { effects: u.newEffects } : {}),
},
};
}
case 'add_effect':
case 'update_effect':
case 'remove_effect': {
return {
encounterPath: encPath,
updates: { effects: u.oldEffects || [] },
redo: { effects: u.newEffects || [] },
};
}
case 'add_condition':
@@ -317,22 +333,22 @@ function expandUndo(entry, currentEnc) {
const redoOrdered = u.newTurnOrderIds.map(id => redoPool.get(id)).filter(Boolean);
return {
encounterPath: encPath,
updates: { participants: undoOrdered, turnOrderIds: u.oldTurnOrderIds },
redo: { participants: redoOrdered, turnOrderIds: u.newTurnOrderIds },
updates: { participants: undoOrdered, turnOrderIds: u.oldTurnOrderIds, ...(u.oldEffects ? { effects: u.oldEffects } : {}) },
redo: { participants: redoOrdered, turnOrderIds: u.newTurnOrderIds, ...(u.newEffects ? { effects: u.newEffects } : {}) },
};
}
return {
encounterPath: encPath,
updates: { participants: applyFields(oldVals) },
redo: { participants: applyFields(newVals), ...(u.newTurnOrderIds ? { turnOrderIds: u.newTurnOrderIds } : {}) },
updates: { participants: applyFields(oldVals), ...(u.oldEffects ? { effects: u.oldEffects } : {}) },
redo: { participants: applyFields(newVals), ...(u.newTurnOrderIds ? { turnOrderIds: u.newTurnOrderIds } : {}), ...(u.newEffects ? { effects: u.newEffects } : {}) },
};
}
case 'next_turn':
case 'auto_end': {
return {
encounterPath: encPath,
updates: { currentTurnParticipantId: u.currentTurnParticipantId, round: u.round, ...(u.turnOrderIds ? { turnOrderIds: u.turnOrderIds } : {}) },
redo: { currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [] },
updates: { currentTurnParticipantId: u.currentTurnParticipantId, round: u.round, ...(u.turnOrderIds ? { turnOrderIds: u.turnOrderIds } : {}), ...(u.oldEffects ? { effects: u.oldEffects } : {}) },
redo: { currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [], ...(u.newEffects ? { effects: u.newEffects } : {}) },
};
}
case 'start_encounter': {
@@ -358,6 +374,41 @@ function expandUndo(entry, currentEnc) {
// Participant factories (pure — no write)
// ----------------------------------------------------------------------------
function makeEffect(opts = {}) {
const rounds = Number(opts.remainingRounds);
return {
id: opts.id || generateId(),
presetId: opts.presetId || 'custom',
name: String(opts.name || 'Effect').trim() || 'Effect',
scope: opts.scope === 'encounter' ? 'encounter' : 'participant',
targetParticipantId: opts.scope === 'encounter' ? null : (opts.targetParticipantId || null),
ownerParticipantId: opts.ownerParticipantId || null,
remainingRounds: Number.isFinite(rounds) ? Math.max(1, Math.floor(rounds)) : 1,
expiresOnDamage: !!opts.expiresOnDamage,
playerDisplay: ['hidden', 'compact', 'prominent'].includes(opts.playerDisplay) ? opts.playerDisplay : 'compact',
notes: String(opts.notes || '').trim(),
createdRound: Number.isFinite(Number(opts.createdRound)) ? Number(opts.createdRound) : 0,
};
}
function tickRoundEffects(effects) {
return (effects || [])
.map(effect => ({ ...effect, remainingRounds: Math.max(0, (effect.remainingRounds || 0) - 1) }))
.filter(effect => effect.remainingRounds > 0);
}
function expireDamageEffects(effects, participantId) {
return (effects || []).filter(effect => !(
effect.scope === 'participant' &&
effect.targetParticipantId === participantId &&
effect.expiresOnDamage
));
}
function effectsChanged(before, after) {
return JSON.stringify(before || []) !== JSON.stringify(after || []);
}
function makeParticipant(opts) {
return {
id: opts.id || generateId(),
@@ -500,13 +551,25 @@ async function nextTurn(encounter, ctx) {
if (!nextId) throw new Error('Could not determine next participant.');
if (wrapped) nextRound += 1;
const nextParticipant = encounter.participants.find(p => p.id === nextId);
const patch = { currentTurnParticipantId: nextParticipant.id, round: nextRound, turnOrderIds: encounter.turnOrderIds };
const oldEffects = [...(encounter.effects || [])];
const newEffects = wrapped ? tickRoundEffects(oldEffects) : oldEffects;
const patch = {
currentTurnParticipantId: nextParticipant.id,
round: nextRound,
turnOrderIds: encounter.turnOrderIds,
...(wrapped && effectsChanged(oldEffects, newEffects) ? { effects: newEffects } : {}),
};
const log = {
type: 'next_turn',
participantId: nextParticipant.id, participantName: nextParticipant.name,
message: `${nextParticipant.name}'s turn (Round ${nextRound})`,
delta: { wrapped, prevRound: encounter.round },
undo: { currentTurnParticipantId: encounter.currentTurnParticipantId, round: encounter.round, turnOrderIds: [...encounter.turnOrderIds] },
undo: {
currentTurnParticipantId: encounter.currentTurnParticipantId,
round: encounter.round,
turnOrderIds: [...encounter.turnOrderIds],
...(wrapped ? { oldEffects, newEffects } : {}),
},
};
return commit(encounter, patch, log, ctx);
}
@@ -571,29 +634,35 @@ async function updateParticipant(encounter, participantId, updatedData, ctx) {
let patch;
const oldValues = {};
for (const k of Object.keys(updatedData)) oldValues[k] = target[k];
const oldEffects = [...(encounter.effects || [])];
const hpReduced = updatedData.currentHp !== undefined && Number(updatedData.currentHp) < Number(target.currentHp);
const newEffects = hpReduced ? expireDamageEffects(oldEffects, participantId) : oldEffects;
const effectChanged = effectsChanged(oldEffects, newEffects);
const effectPatch = effectChanged ? { effects: newEffects } : {};
const effectUndo = effectChanged ? { oldEffects, newEffects } : {};
if (!('initiative' in updatedData) || updatedData.initiative === target.initiative) {
const sameSlot = existing.map(p => p.id === participantId ? merged : p);
const fields = Object.keys(updatedData).join(', ');
patch = { participants: sameSlot, ...syncTurnOrder(sameSlot) };
patch = { participants: sameSlot, ...syncTurnOrder(sameSlot), ...effectPatch };
const log = {
type: 'update_participant',
participantId, participantName: target.name,
message: `${target.name} updated (${fields})`,
delta: { changedFields: Object.keys(updatedData) },
undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds },
undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds, ...effectUndo },
};
return commit(encounter, patch, log, ctx);
} else {
const without = existing.filter(p => p.id !== participantId);
const idx = slotIndexForInit(without, merged.initiative);
without.splice(idx, 0, merged);
patch = { participants: without, ...syncTurnOrder(without) };
patch = { participants: without, ...syncTurnOrder(without), ...effectPatch };
const log = {
type: 'update_participant',
participantId, participantName: target.name,
message: `${target.name} updated (initiative: ${merged.initiative})`,
delta: { changedFields: Object.keys(updatedData), initiative: merged.initiative },
undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds },
undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds, ...effectUndo },
};
return commit(encounter, patch, log, ctx);
}
@@ -685,6 +754,11 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
isActive: participant.isActive,
conditions: [...(participant.conditions || [])],
};
const oldEffects = [...(encounter.effects || [])];
const newEffects = changeType === 'damage' ? expireDamageEffects(oldEffects, participantId) : oldEffects;
const effectChanged = effectsChanged(oldEffects, newEffects);
const withEffectPatch = patch => effectChanged ? { ...patch, effects: newEffects } : patch;
const withEffectUndo = undo => effectChanged ? { ...undo, oldEffects, newEffects } : undo;
let updates = {};
let message = '';
@@ -719,9 +793,9 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
participantName: participant.name,
message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`,
delta: { amount, from: participant.currentHp, to: participant.currentHp, tempHp: tempAfter },
undo: { oldValues, newValues: { ...oldValues, tempHp: tempAfter } },
undo: withEffectUndo({ oldValues, newValues: { ...oldValues, tempHp: tempAfter } }),
};
return commit(encounter, { participants: updatedParticipants0 }, log0, ctx);
return commit(encounter, withEffectPatch({ participants: updatedParticipants0 }), log0, ctx);
}
amount = remainingDmg;
const tempBefore = currentTemp;
@@ -748,9 +822,9 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
participantName: participant.name,
message: `${participant.name} marked inactive (dead monster)`,
delta: { status: 'dead', isActive: false },
undo: { oldValues, newValues },
undo: withEffectUndo({ oldValues, newValues }),
};
return commit(encounter, patch, log, ctx);
return commit(encounter, withEffectPatch(patch), log, ctx);
}
return encounter;
}
@@ -791,7 +865,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
const updatedParticipants = (encounter.participants || []).map(p =>
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
);
const patch = { participants: updatedParticipants };
const patch = withEffectPatch({ participants: updatedParticipants });
const undoAmount = changeType === 'damage' ? amount : -amount;
const newP = updatedParticipants.find(p => p.id === participantId);
const newValues = {
@@ -808,7 +882,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
participantId, participantName: participant.name,
message,
delta: logDelta,
undo: { amount: undoAmount, oldValues, newValues },
undo: withEffectUndo({ amount: undoAmount, oldValues, newValues }),
};
return commit(encounter, patch, log, ctx);
}
@@ -819,6 +893,11 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount,
const participantId = participant.id;
let updates, message, logDelta = { amount, from: participant.currentHp };
const currentTemp = participant.tempHp || 0;
const oldEffects = [...(encounter.effects || [])];
const newEffects = changeType === 'damage' ? expireDamageEffects(oldEffects, participantId) : oldEffects;
const effectChanged = effectsChanged(oldEffects, newEffects);
const withEffectPatch = patch => effectChanged ? { ...patch, effects: newEffects } : patch;
const withEffectUndo = undo => effectChanged ? { ...undo, oldEffects, newEffects } : undo;
if (changeType === 'damage') {
// Temp HP absorbs damage first.
@@ -837,9 +916,9 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount,
type: 'hp_change', participantId, participantName: participant.name,
message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`,
delta: { amount, from: participant.currentHp, to: participant.currentHp, tempHp: tempAfter },
undo: { oldValues, newValues: { ...oldValues, tempHp: tempAfter } },
undo: withEffectUndo({ oldValues, newValues: { ...oldValues, tempHp: tempAfter } }),
};
return commit(encounter, { participants: updatedParticipants0 }, log0, ctx);
return commit(encounter, withEffectPatch({ participants: updatedParticipants0 }), log0, ctx);
}
amount = remainingDmg;
const tempFinal = tempAfter;
@@ -854,11 +933,11 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount,
deathSaveSuccesses: 0, deathSaveFailures: 0,
isActive: newP.isActive, conditions: [...(newP.conditions || [])],
};
return commit(encounter, { participants: updatedParticipants }, {
return commit(encounter, withEffectPatch({ participants: updatedParticipants }), {
type: 'deactivate_dead_monster', participantId, participantName: participant.name,
message: `${participant.name} marked inactive (dead monster)`,
delta: { status: 'dead', isActive: false },
undo: { oldValues, newValues },
undo: withEffectUndo({ oldValues, newValues }),
}, ctx);
}
return encounter;
@@ -895,10 +974,10 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount,
isActive: newP.isActive, conditions: [...(newP.conditions || [])],
};
const undoAmount = changeType === 'damage' ? amount : -amount;
return commit(encounter, { participants: updatedParticipants }, {
return commit(encounter, withEffectPatch({ participants: updatedParticipants }), {
type: changeType, participantId, participantName: participant.name,
message, delta: logDelta,
undo: { amount: undoAmount, oldValues, newValues },
undo: withEffectUndo({ amount: undoAmount, oldValues, newValues }),
}, ctx);
}
@@ -987,6 +1066,52 @@ async function toggleCondition(encounter, participantId, conditionId, ctx) {
return commit(encounter, patch, log, ctx);
}
async function addEffect(encounter, effect, ctx) {
const normalized = makeEffect({ ...effect, createdRound: effect.createdRound ?? encounter.round ?? 0 });
const oldEffects = [...(encounter.effects || [])];
if (oldEffects.some(e => e.id === normalized.id)) throw new Error(`Effect "${normalized.id}" already exists.`);
if (normalized.scope === 'participant' && !normalized.targetParticipantId) throw new Error('Participant effect requires targetParticipantId.');
const newEffects = [...oldEffects, normalized];
const target = (encounter.participants || []).find(p => p.id === normalized.targetParticipantId);
return commit(encounter, { effects: newEffects }, {
type: 'add_effect',
participantId: normalized.targetParticipantId,
participantName: target?.name || null,
message: `${normalized.name} added${target ? ` to ${target.name}` : ''} (${normalized.remainingRounds} rounds)`,
delta: { effectId: normalized.id, name: normalized.name, remainingRounds: normalized.remainingRounds },
undo: { oldEffects, newEffects },
}, ctx);
}
async function updateEffect(encounter, effectId, updates, ctx) {
const oldEffects = [...(encounter.effects || [])];
const existing = oldEffects.find(e => e.id === effectId);
if (!existing) throw new Error('Effect not found.');
const merged = makeEffect({ ...existing, ...updates, id: existing.id });
const newEffects = oldEffects.map(e => e.id === effectId ? merged : e);
return commit(encounter, { effects: newEffects }, {
type: 'update_effect',
participantId: merged.targetParticipantId,
message: `${merged.name} updated (${merged.remainingRounds} rounds)`,
delta: { effectId, remainingRounds: merged.remainingRounds },
undo: { oldEffects, newEffects },
}, ctx);
}
async function removeEffect(encounter, effectId, ctx) {
const oldEffects = [...(encounter.effects || [])];
const existing = oldEffects.find(e => e.id === effectId);
if (!existing) throw new Error('Effect not found.');
const newEffects = oldEffects.filter(e => e.id !== effectId);
return commit(encounter, { effects: newEffects }, {
type: 'remove_effect',
participantId: existing.targetParticipantId,
message: `${existing.name} removed`,
delta: { effectId, name: existing.name },
undo: { oldEffects, newEffects },
}, ctx);
}
async function stabilizeParticipant(encounter, participantId, ctx) {
if ((encounter.ruleset || '5e') === 'generic') {
throw new Error('Stabilize not available in generic ruleset.');
@@ -1261,10 +1386,11 @@ module.exports = {
generateId, rollD20, rollHpFormula, formatInitMod,
sortParticipantsByInitiative, syncTurnOrder, computeTurnOrderAfterRemoval,
snapshotOf, buildEntry, expandUndo,
makeParticipant, buildCharacterParticipant, buildMonsterParticipant,
makeEffect, makeParticipant, buildCharacterParticipant, buildMonsterParticipant,
startEncounter, nextTurn, togglePause,
addParticipant, addParticipants, updateParticipant, removeParticipant,
toggleParticipantActive, applyHpChange, setTempHp, deathSave, stabilizeParticipant, reviveParticipant, markDead, toggleCondition,
addEffect, updateEffect, removeEffect,
reorderParticipants, endEncounter, rerollAllInitiatives,
activateDisplay, clearDisplay, toggleHidePlayerHp,
};