diff --git a/shared/tests/turn.effects.test.js b/shared/tests/turn.effects.test.js new file mode 100644 index 0000000..4a4bcf4 --- /dev/null +++ b/shared/tests/turn.effects.test.js @@ -0,0 +1,115 @@ +const shared = require('@ttrpg/shared'); +const { mockCtx, readyEnc, undoLast } = require('./_helpers'); + +const { + makeEffect, addEffect, updateEffect, removeEffect, + nextTurn, applyHpChange, updateParticipant, +} = shared; + +function effect(overrides = {}) { + return makeEffect({ + name: 'Turned', presetId: 'turned', scope: 'participant', + targetParticipantId: 'p2', remainingRounds: 10, + expiresOnDamage: true, playerDisplay: 'prominent', + ...overrides, + }); +} + +function runningEnc(overrides = {}) { + return { + ...readyEnc(), + isStarted: true, + round: 2, + currentTurnParticipantId: 'p1', + turnOrderIds: ['p1', 'p2'], + effects: [], + ...overrides, + }; +} + +describe('tracked effects', () => { + test('makeEffect normalizes generic effect fields', () => { + const e = effect({ id: 'fx1', remainingRounds: 3.9 }); + expect(e).toEqual(expect.objectContaining({ + id: 'fx1', name: 'Turned', presetId: 'turned', scope: 'participant', + targetParticipantId: 'p2', remainingRounds: 3, + expiresOnDamage: true, playerDisplay: 'prominent', + })); + }); + + test('add, update, remove effect are persisted and undoable', async () => { + const { ctx } = mockCtx(); + let enc = readyEnc({ participants: readyEnc().participants }); + enc.effects = []; + const fx = effect({ id: 'fx1' }); + + enc = await addEffect(enc, fx, ctx); + expect(enc.effects).toEqual([fx]); + enc = await updateEffect(enc, 'fx1', { remainingRounds: 6 }, ctx); + expect(enc.effects[0].remainingRounds).toBe(6); + const afterRemove = await removeEffect(enc, 'fx1', ctx); + expect(afterRemove.effects).toEqual([]); + const undone = await undoLast(ctx, afterRemove); + expect(undone.effects[0]).toEqual(expect.objectContaining({ id: 'fx1', remainingRounds: 6 })); + }); + + test('round wrap decrements timed effects and removes expired effects', async () => { + const { ctx } = mockCtx(); + const enc = runningEnc({ + currentTurnParticipantId: 'p2', + effects: [effect({ id: 'keep', remainingRounds: 2 }), effect({ id: 'expire', remainingRounds: 1 })], + }); + + const out = await nextTurn(enc, ctx); + expect(out.round).toBe(3); + expect(out.effects).toHaveLength(1); + expect(out.effects[0]).toEqual(expect.objectContaining({ id: 'keep', remainingRounds: 1 })); + + const undone = await undoLast(ctx, out); + expect(undone.round).toBe(2); + expect(undone.effects.map(e => [e.id, e.remainingRounds])).toEqual([['keep', 2], ['expire', 1]]); + }); + + test('same-round turn advance does not decrement effects', async () => { + const { ctx } = mockCtx(); + const enc = runningEnc({ effects: [effect({ id: 'fx', remainingRounds: 10 })] }); + const out = await nextTurn(enc, ctx); + expect(out.round).toBe(2); + expect(out.effects[0].remainingRounds).toBe(10); + }); + + test('damage expires targeted effect even when temp HP absorbs all damage; undo restores it', async () => { + const { ctx } = mockCtx(); + const participants = readyEnc().participants.map(p => p.id === 'p2' ? { ...p, tempHp: 5 } : p); + const enc = runningEnc({ participants, effects: [effect({ id: 'fx' })] }); + + const out = await applyHpChange(enc, 'p2', 'damage', 2, ctx); + expect(out.participants.find(p => p.id === 'p2').currentHp).toBe(10); + expect(out.effects).toEqual([]); + + const undone = await undoLast(ctx, out); + expect(undone.effects).toHaveLength(1); + expect(undone.effects[0].id).toBe('fx'); + }); + + test('direct HP reduction expires targeted effect; increase does not', async () => { + const { ctx } = mockCtx(); + let enc = runningEnc({ effects: [effect({ id: 'fx' })] }); + enc = await updateParticipant(enc, 'p2', { currentHp: 8 }, ctx); + expect(enc.effects).toEqual([]); + + enc = { ...enc, effects: [effect({ id: 'fx2' })] }; + enc = await updateParticipant(enc, 'p2', { currentHp: 9 }, ctx); + expect(enc.effects).toHaveLength(1); + }); + + test('damage leaves encounter-wide and non-expiring effects active', async () => { + const { ctx } = mockCtx(); + const enc = runningEnc({ effects: [ + effect({ id: 'weapon', presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', targetParticipantId: null, expiresOnDamage: false }), + effect({ id: 'bless', name: 'Bless', expiresOnDamage: false }), + ] }); + const out = await applyHpChange(enc, 'p2', 'damage', 1, ctx); + expect(out.effects.map(e => e.id)).toEqual(['weapon', 'bless']); + }); +}); diff --git a/shared/turn.js b/shared/turn.js index 5312e0d..0ba6775 100644 --- a/shared/turn.js +++ b/shared/turn.js @@ -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, }; diff --git a/src/App.js b/src/App.js index b99b0ec..b6599bf 100644 --- a/src/App.js +++ b/src/App.js @@ -130,6 +130,9 @@ const { markDead, toggleCondition: combatToggleCondition, reorderParticipants, + addEffect: combatAddEffect, + updateEffect: combatUpdateEffect, + removeEffect: combatRemoveEffect, } = shared; const ROLL_DISPLAY_DURATION = 5000; @@ -1189,6 +1192,204 @@ function CharacterManager({ campaignId, campaignCharacters, syncCharacters }) { ); } +function EffectModal({ encounter, defaultScope, defaultTargetParticipantId, onClose, onAdd }) { + const is5e = (encounter.ruleset || '5e') === '5e'; + const participants = encounter.participants || []; + const [presetId, setPresetId] = useState('custom'); + const [name, setName] = useState(''); + const [scope, setScope] = useState(defaultScope || 'participant'); + const [targetParticipantId, setTargetParticipantId] = useState(defaultTargetParticipantId || participants[0]?.id || ''); + const [ownerParticipantId, setOwnerParticipantId] = useState(encounter.currentTurnParticipantId || ''); + const [duration, setDuration] = useState('10'); + const [durationUnit, setDurationUnit] = useState('rounds'); + const [expiresOnDamage, setExpiresOnDamage] = useState(false); + const [playerDisplay, setPlayerDisplay] = useState('compact'); + const [notes, setNotes] = useState(''); + + const selectPreset = (value) => { + setPresetId(value); + if (value === 'turned') { + setName('Turned'); + setScope('participant'); + setTargetParticipantId(defaultTargetParticipantId || participants[0]?.id || ''); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(true); + setPlayerDisplay('prominent'); + } else if (value === 'spiritual_weapon') { + setName('Spiritual Weapon'); + setScope('encounter'); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(false); + setPlayerDisplay('prominent'); + } else { + setName(''); + setScope(defaultScope || 'participant'); + setTargetParticipantId(defaultTargetParticipantId || participants[0]?.id || ''); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(false); + setPlayerDisplay('compact'); + } + }; + + const submit = (e) => { + e.preventDefault(); + const n = Math.max(1, parseInt(duration, 10) || 1); + if (!name.trim() || (scope === 'participant' && !targetParticipantId)) return; + onAdd({ + presetId, + name: name.trim(), + scope, + targetParticipantId: scope === 'participant' ? targetParticipantId : null, + ownerParticipantId: ownerParticipantId || null, + remainingRounds: durationUnit === 'minutes' && is5e ? n * 10 : n, + expiresOnDamage, + playerDisplay, + notes, + createdRound: encounter.round || 0, + }); + }; + + return ( + +
+ + +
+ + {scope === 'participant' && ( + + )} +
+ +
+ + +
+ + + +
+ + +
+
+
+ ); +} + +function EffectControlRow({ effect, participants, onAdjust, onSet, onRemove }) { + const owner = participants.find(p => p.id === effect.ownerParticipantId); + const [draftRounds, setDraftRounds] = useState(String(effect.remainingRounds)); + useEffect(() => setDraftRounds(String(effect.remainingRounds)), [effect.remainingRounds]); + const commitRounds = () => { + const value = Math.max(1, parseInt(draftRounds, 10) || 1); + setDraftRounds(String(value)); + if (value !== effect.remainingRounds) onSet(effect, value); + }; + return ( +
+ {effect.name.toUpperCase()} + + {owner && Owner: {owner.name}} + {effect.expiresOnDamage && Ends on damage} + + + + + +
+ ); +} + +function PlayerEffectDisplay({ effect, ownerName }) { + if (!effect || effect.playerDisplay === 'hidden') return null; + const testId = effect.scope === 'encounter' ? `encounter-effect-${effect.id}` : `prominent-effect-${effect.id}`; + if (effect.playerDisplay === 'prominent') { + return ( +
+
{effect.name.toUpperCase()}
+
+ {ownerName && {ownerName} · }{effect.remainingRounds} rounds remaining + {effect.expiresOnDamage && · Ends on damage} +
+ {effect.notes &&
{effect.notes}
} +
+ ); + } + return ( + + {effect.name} · {effect.remainingRounds} rounds{ownerName ? ` · ${ownerName}` : ''} + + ); +} + // ============================================================================ // PARTICIPANT MANAGER COMPONENT // ============================================================================ @@ -1215,6 +1416,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp const [lastRollDetails, setLastRollDetails] = useState(null); const [openConditionsId, setOpenConditionsId] = useState(null); const [customConditionInput, setCustomConditionInput] = useState(''); + const [effectModal, setEffectModal] = useState(null); // Per-campaign custom conditions (DM-added freeform strings). const { data: campaignDoc } = useFirestoreDocument(campaignId ? getPath.campaign(campaignId) : null); @@ -1555,6 +1757,75 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp } }; + const handleAddEffect = async (effect) => { + if (!db) return; + try { + await combatAddEffect(encounter, effect, buildCtx(encounterPath)); + setEffectModal(null); + } catch (err) { + showToast(err.message || 'Failed to add effect.'); + } + }; + + const togglePresetEffect = async (presetId, participant) => { + if (!db) return; + const existing = (encounter.effects || []).find(effect => presetId === 'turned' + ? effect.presetId === 'turned' && effect.targetParticipantId === participant.id + : effect.presetId === 'spiritual_weapon' && effect.ownerParticipantId === participant.id); + try { + if (existing) { + await combatRemoveEffect(encounter, existing.id, buildCtx(encounterPath)); + return; + } + if (presetId === 'turned') { + await combatAddEffect(encounter, { + presetId: 'turned', name: 'Turned', scope: 'participant', + targetParticipantId: participant.id, + ownerParticipantId: encounter.currentTurnParticipantId || null, + remainingRounds: 10, expiresOnDamage: true, + playerDisplay: 'prominent', createdRound: encounter.round || 0, + }, buildCtx(encounterPath)); + } else if (presetId === 'spiritual_weapon') { + await combatAddEffect(encounter, { + presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', + ownerParticipantId: participant.id, + remainingRounds: 10, expiresOnDamage: false, + playerDisplay: 'prominent', createdRound: encounter.round || 0, + }, buildCtx(encounterPath)); + } + } catch (err) { + showToast(err.message || 'Failed to update effect.'); + } + }; + + const handleAdjustEffect = async (effect, delta) => { + if (!db) return; + const next = Math.max(1, (effect.remainingRounds || 1) + delta); + try { + await combatUpdateEffect(encounter, effect.id, { remainingRounds: next }, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message || 'Failed to update effect.'); + } + }; + + const handleSetEffectDuration = async (effect, remainingRounds) => { + if (!db) return; + try { + await combatUpdateEffect(encounter, effect.id, { remainingRounds }, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message || 'Failed to update effect.'); + } + }; + + const handleRemoveEffect = async (effect) => { + if (!db) return; + try { + await combatRemoveEffect(encounter, effect.id, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message || 'Failed to remove effect.'); + } + }; + // Add freeform condition: persist to campaign palette + apply to current participant. const addCustomCondition = async (label, participantId = null) => { const trimmed = (label || '').trim(); @@ -1839,6 +2110,15 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp ); })()} + {(encounter.effects || []).some(effect => effect.scope === 'encounter' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId))) && ( +
+

Encounter Effects

+ {(encounter.effects || []).filter(effect => effect.scope === 'encounter' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId))).map(effect => ( + + ))} +
+ )} + {participants.length === 0 &&

No participants added yet.

} @@ -1863,6 +2143,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp return (
  • handleDragStart(e, p.id) : undefined} onDragOver={isDraggable ? handleDragOver : undefined} @@ -2067,6 +2348,13 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp )} + {(encounter.effects || []).filter(effect => + (effect.scope === 'participant' && effect.targetParticipantId === p.id) || + (effect.scope === 'encounter' && effect.ownerParticipantId === p.id) + ).map(effect => ( + + ))} + {/* Expandable conditions picker */} {openConditionsId === p.id && (
    @@ -2086,6 +2374,48 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp ); })}
    + {(encounter.ruleset || '5e') === '5e' && ( + <> +

    Tracked Effects

    +
    + {(() => { + const active = (encounter.effects || []).some(effect => effect.presetId === 'turned' && effect.targetParticipantId === p.id); + return ( + + ); + })()} + {(() => { + const active = (encounter.effects || []).some(effect => effect.presetId === 'spiritual_weapon' && effect.ownerParticipantId === p.id); + return ( + + ); + })()} +
    + + )} + + {/* Add custom condition (per-campaign, freeform string) */}
    + {effectModal && ( + setEffectModal(null)} + onAdd={handleAddEffect} + /> + )} + setShowDeleteConfirm(false)} @@ -3684,6 +4025,7 @@ function PlayerParticipantCard({ id, isActive, status, onExit, className, childr return (
    {children} @@ -3918,6 +4260,7 @@ function DisplayView() { } const { name, participants, round, currentTurnParticipantId, isStarted, isPaused } = activeEncounterData; + const trackedEffects = activeEncounterData.effects || []; const hidePlayerHp = activeDisplayData?.hidePlayerHp ?? true; const hideNpcHp = activeDisplayData?.hideNpcHp ?? false; @@ -3974,6 +4317,12 @@ function DisplayView() {

    No active participants.

    )} +
    + {trackedEffects + .filter(effect => effect.scope === 'encounter' && effect.playerDisplay !== 'hidden' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId))) + .map(effect => )} +
    +
    {participantsToRender.map(p => { const isGeneric = (activeEncounterData.ruleset || '5e') === 'generic'; @@ -4022,8 +4371,18 @@ function DisplayView() {
    + {trackedEffects + .filter(effect => ( + (effect.scope === 'participant' && effect.targetParticipantId === p.id) || + (effect.scope === 'encounter' && effect.ownerParticipantId === p.id) + ) && effect.playerDisplay !== 'hidden') + .map(effect => { + const owner = participants.find(ownerParticipant => ownerParticipant.id === effect.ownerParticipantId); + return ; + })} + {!(hidePlayerHp && p.type === 'character') && !(hideNpcHp && p.type !== 'character') && ( -
    +
    { + const favicon = document.createElement('link'); + favicon.rel = 'icon'; + favicon.href = '/favicon.ico'; + document.head.appendChild(favicon); + window.history.replaceState({}, '', '/display'); + global.alert = jest.fn(); + window.open = jest.fn(); + Element.prototype.scrollIntoView = jest.fn(); +}); + +afterEach(() => { + document.querySelectorAll('link[rel="icon"]').forEach(l => l.remove()); + window.history.replaceState({}, '', '/'); +}); + +describe('player display tracked effects', () => { + test('prominent participant effect renders clear banner with countdown', async () => { + seed([{ id: 'fx1', presetId: 'turned', name: 'Turned', scope: 'participant', targetParticipantId: 'p2', ownerParticipantId: 'p1', remainingRounds: 7, expiresOnDamage: true, playerDisplay: 'prominent' }]); + render(); + await screen.findByText('Zombie'); + expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('TURNED'); + expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('7 rounds remaining'); + expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('Ends on damage'); + }); + + test('compact participant effect renders badge; hidden effect does not render', async () => { + seed([ + { id: 'fx1', name: 'Bless', scope: 'participant', targetParticipantId: 'p2', remainingRounds: 3, playerDisplay: 'compact' }, + { id: 'fx2', name: 'Secret', scope: 'participant', targetParticipantId: 'p2', remainingRounds: 4, playerDisplay: 'hidden' }, + ]); + render(); + await screen.findByText('Zombie'); + expect(screen.getByText(/Bless · 3 rounds/i)).toBeInTheDocument(); + expect(screen.queryByText(/Secret/i)).not.toBeInTheDocument(); + }); + + test('owner-linked encounter effect renders prominently on owner card', async () => { + seed([{ id: 'fx3', presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', ownerParticipantId: 'p1', remainingRounds: 8, expiresOnDamage: false, playerDisplay: 'prominent' }]); + render(); + await screen.findByText('Zombie'); + const clericCard = screen.getByTestId('participant-card-p1'); + const banner = within(clericCard).getByTestId('encounter-effect-fx3'); + expect(banner).toHaveTextContent('SPIRITUAL WEAPON'); + expect(banner).toHaveTextContent('Cleric'); + expect(banner).toHaveTextContent('8 rounds remaining'); + }); + + test('ownerless encounter effect remains in global fallback area', async () => { + seed([{ id: 'fx4', name: 'Fog Cloud', scope: 'encounter', ownerParticipantId: null, remainingRounds: 5, playerDisplay: 'prominent' }]); + render(); + await screen.findByText('Zombie'); + const banner = screen.getByTestId('encounter-effect-fx4'); + expect(banner).toHaveTextContent('FOG CLOUD'); + expect(screen.getByTestId('participant-card-p1')).not.toContainElement(banner); + expect(screen.getByTestId('participant-card-p2')).not.toContainElement(banner); + }); +}); diff --git a/src/tests/TrackedEffects.test.js b/src/tests/TrackedEffects.test.js new file mode 100644 index 0000000..c6fd5d2 --- /dev/null +++ b/src/tests/TrackedEffects.test.js @@ -0,0 +1,108 @@ +import { screen, fireEvent, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { + setupReady, addMonsterViaUI, renderApp, createCampaignViaUI, + selectCampaignByName, selectEncounterByName, MOCK_DB, +} from './testHelpers'; + +function latestEncounter() { + const row = [...MOCK_DB._state.docs.entries()] + .filter(([path]) => path.includes('/encounters/')) + .pop(); + return row ? MOCK_DB.get(row[0]) : null; +} + +describe('tracked effects DM UI', () => { + test('5e Turned preset creates prominent 10-round damage-expiring participant effect', async () => { + await setupReady('Turned Camp', 'Turned Encounter'); + await addMonsterViaUI('Zombie', 22, -2); + + expect(screen.queryByRole('button', { name: 'Add effect to Zombie' })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + fireEvent.click(screen.getByRole('button', { name: 'Turned' })); + + await waitFor(() => { + const fx = latestEncounter().effects[0]; + expect(fx).toMatchObject({ + presetId: 'turned', name: 'Turned', scope: 'participant', + remainingRounds: 10, expiresOnDamage: true, playerDisplay: 'prominent', + }); + expect(fx.targetParticipantId).toBe(latestEncounter().participants.find(p => p.name === 'Zombie').id); + }); + expect(await screen.findByText('TURNED')).toBeInTheDocument(); + expect(screen.getByLabelText('Turns left for Turned')).toHaveValue(10); + }); + + test('custom encounter effect converts 5e minutes to rounds and supports prominent display', async () => { + await setupReady('Effect Camp', 'Effect Encounter'); + await addMonsterViaUI('Cleric', 30, 2); + + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + fireEvent.click(screen.getByRole('button', { name: 'Custom tracked effect' })); + fireEvent.change(screen.getByLabelText('Effect scope'), { target: { value: 'encounter' } }); + fireEvent.change(screen.getByLabelText('Effect name'), { target: { value: 'Spirit Guardians' } }); + fireEvent.change(screen.getByLabelText('Duration'), { target: { value: '2' } }); + fireEvent.change(screen.getByLabelText('Duration unit'), { target: { value: 'minutes' } }); + fireEvent.change(screen.getByLabelText('Player display'), { target: { value: 'prominent' } }); + fireEvent.click(screen.getByRole('button', { name: 'Add Effect' })); + + await waitFor(() => expect(latestEncounter().effects[0]).toMatchObject({ + name: 'Spirit Guardians', scope: 'encounter', remainingRounds: 20, + playerDisplay: 'prominent', + })); + expect(screen.getByText('SPIRIT GUARDIANS')).toBeInTheDocument(); + expect(screen.getByLabelText('Turns left for Spirit Guardians')).toHaveValue(20); + }); + + test('Spiritual Weapon preset creates 10-round encounter effect', async () => { + await setupReady('Weapon Camp', 'Weapon Encounter'); + await addMonsterViaUI('Cleric', 30, 2); + + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + fireEvent.click(screen.getByRole('button', { name: 'Spiritual Weapon' })); + + await waitFor(() => expect(latestEncounter().effects[0]).toMatchObject({ + presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', + remainingRounds: 10, expiresOnDamage: false, playerDisplay: 'prominent', + })); + const clericId = latestEncounter().participants.find(p => p.name === 'Cleric').id; + expect(within(screen.getByTestId(`admin-participant-card-${clericId}`)).getByText('SPIRITUAL WEAPON')).toBeInTheDocument(); + }); + + test('generic ruleset offers custom effects only and rounds only', async () => { + await renderApp(); + await createCampaignViaUI('Generic Effect Camp'); + await selectCampaignByName('Generic Effect Camp'); + fireEvent.click(screen.getByRole('button', { name: /Create Encounter/i })); + fireEvent.change(await screen.findByLabelText(/Encounter Name/i), { target: { value: 'Generic Effect Encounter' } }); + fireEvent.click(screen.getByRole('radio', { name: /Generic/i })); + fireEvent.click(screen.getByRole('button', { name: /^Create$/i })); + await selectEncounterByName('Generic Effect Encounter'); + await addMonsterViaUI('Generic Mob', 10, 0); + + expect(screen.queryByRole('button', { name: 'Add encounter effect' })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + expect(screen.queryByRole('button', { name: 'Turned' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Spiritual Weapon' })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Custom tracked effect' })); + const durationOptions = [...screen.getByLabelText('Duration unit').options].map(o => o.value); + expect(durationOptions).toEqual(['rounds']); + }); + + test('effect duration controls adjust and remove effect', async () => { + await setupReady('Control Camp', 'Control Encounter'); + await addMonsterViaUI('Ghoul', 18, 2); + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + fireEvent.click(screen.getByRole('button', { name: 'Turned' })); + await screen.findByText('TURNED'); + + const turnsInput = screen.getByLabelText('Turns left for Turned'); + fireEvent.change(turnsInput, { target: { value: '3' } }); + fireEvent.blur(turnsInput); + await waitFor(() => expect(latestEncounter().effects[0].remainingRounds).toBe(3)); + fireEvent.click(screen.getByRole('button', { name: 'Decrease Turned duration' })); + await waitFor(() => expect(latestEncounter().effects[0].remainingRounds).toBe(2)); + fireEvent.click(screen.getByRole('button', { name: 'Remove Turned' })); + await waitFor(() => expect(latestEncounter().effects).toEqual([])); + }); +});