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

+115
View File
@@ -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']);
});
});
+153 -27
View File
@@ -233,6 +233,7 @@ function expandUndo(entry, currentEnc) {
} }
case 'damage': case 'damage':
case 'heal': case 'heal':
case 'hp_change':
case 'death_save': case 'death_save':
case 'stabilize': case 'stabilize':
case 'revive': case 'revive':
@@ -258,8 +259,23 @@ function expandUndo(entry, currentEnc) {
}; };
return { return {
encounterPath: encPath, encounterPath: encPath,
updates: { participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(oldVals) } : p) }, updates: {
redo: { participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(newVals) } : p) }, 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': case 'add_condition':
@@ -317,22 +333,22 @@ function expandUndo(entry, currentEnc) {
const redoOrdered = u.newTurnOrderIds.map(id => redoPool.get(id)).filter(Boolean); const redoOrdered = u.newTurnOrderIds.map(id => redoPool.get(id)).filter(Boolean);
return { return {
encounterPath: encPath, encounterPath: encPath,
updates: { participants: undoOrdered, turnOrderIds: u.oldTurnOrderIds }, updates: { participants: undoOrdered, turnOrderIds: u.oldTurnOrderIds, ...(u.oldEffects ? { effects: u.oldEffects } : {}) },
redo: { participants: redoOrdered, turnOrderIds: u.newTurnOrderIds }, redo: { participants: redoOrdered, turnOrderIds: u.newTurnOrderIds, ...(u.newEffects ? { effects: u.newEffects } : {}) },
}; };
} }
return { return {
encounterPath: encPath, encounterPath: encPath,
updates: { participants: applyFields(oldVals) }, updates: { participants: applyFields(oldVals), ...(u.oldEffects ? { effects: u.oldEffects } : {}) },
redo: { participants: applyFields(newVals), ...(u.newTurnOrderIds ? { turnOrderIds: u.newTurnOrderIds } : {}) }, redo: { participants: applyFields(newVals), ...(u.newTurnOrderIds ? { turnOrderIds: u.newTurnOrderIds } : {}), ...(u.newEffects ? { effects: u.newEffects } : {}) },
}; };
} }
case 'next_turn': case 'next_turn':
case 'auto_end': { case 'auto_end': {
return { return {
encounterPath: encPath, encounterPath: encPath,
updates: { currentTurnParticipantId: u.currentTurnParticipantId, round: u.round, ...(u.turnOrderIds ? { turnOrderIds: u.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 || [] }, redo: { currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [], ...(u.newEffects ? { effects: u.newEffects } : {}) },
}; };
} }
case 'start_encounter': { case 'start_encounter': {
@@ -358,6 +374,41 @@ function expandUndo(entry, currentEnc) {
// Participant factories (pure — no write) // 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) { function makeParticipant(opts) {
return { return {
id: opts.id || generateId(), id: opts.id || generateId(),
@@ -500,13 +551,25 @@ async function nextTurn(encounter, ctx) {
if (!nextId) throw new Error('Could not determine next participant.'); if (!nextId) throw new Error('Could not determine next participant.');
if (wrapped) nextRound += 1; if (wrapped) nextRound += 1;
const nextParticipant = encounter.participants.find(p => p.id === nextId); 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 = { const log = {
type: 'next_turn', type: 'next_turn',
participantId: nextParticipant.id, participantName: nextParticipant.name, participantId: nextParticipant.id, participantName: nextParticipant.name,
message: `${nextParticipant.name}'s turn (Round ${nextRound})`, message: `${nextParticipant.name}'s turn (Round ${nextRound})`,
delta: { wrapped, prevRound: encounter.round }, 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); return commit(encounter, patch, log, ctx);
} }
@@ -571,29 +634,35 @@ async function updateParticipant(encounter, participantId, updatedData, ctx) {
let patch; let patch;
const oldValues = {}; const oldValues = {};
for (const k of Object.keys(updatedData)) oldValues[k] = target[k]; 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) { if (!('initiative' in updatedData) || updatedData.initiative === target.initiative) {
const sameSlot = existing.map(p => p.id === participantId ? merged : p); const sameSlot = existing.map(p => p.id === participantId ? merged : p);
const fields = Object.keys(updatedData).join(', '); const fields = Object.keys(updatedData).join(', ');
patch = { participants: sameSlot, ...syncTurnOrder(sameSlot) }; patch = { participants: sameSlot, ...syncTurnOrder(sameSlot), ...effectPatch };
const log = { const log = {
type: 'update_participant', type: 'update_participant',
participantId, participantName: target.name, participantId, participantName: target.name,
message: `${target.name} updated (${fields})`, message: `${target.name} updated (${fields})`,
delta: { changedFields: Object.keys(updatedData) }, 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); return commit(encounter, patch, log, ctx);
} else { } else {
const without = existing.filter(p => p.id !== participantId); const without = existing.filter(p => p.id !== participantId);
const idx = slotIndexForInit(without, merged.initiative); const idx = slotIndexForInit(without, merged.initiative);
without.splice(idx, 0, merged); without.splice(idx, 0, merged);
patch = { participants: without, ...syncTurnOrder(without) }; patch = { participants: without, ...syncTurnOrder(without), ...effectPatch };
const log = { const log = {
type: 'update_participant', type: 'update_participant',
participantId, participantName: target.name, participantId, participantName: target.name,
message: `${target.name} updated (initiative: ${merged.initiative})`, message: `${target.name} updated (initiative: ${merged.initiative})`,
delta: { changedFields: Object.keys(updatedData), 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); return commit(encounter, patch, log, ctx);
} }
@@ -685,6 +754,11 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
isActive: participant.isActive, isActive: participant.isActive,
conditions: [...(participant.conditions || [])], 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 updates = {};
let message = ''; let message = '';
@@ -719,9 +793,9 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
participantName: participant.name, participantName: participant.name,
message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`, message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`,
delta: { amount, from: participant.currentHp, to: participant.currentHp, tempHp: tempAfter }, 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; amount = remainingDmg;
const tempBefore = currentTemp; const tempBefore = currentTemp;
@@ -748,9 +822,9 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
participantName: participant.name, participantName: participant.name,
message: `${participant.name} marked inactive (dead monster)`, message: `${participant.name} marked inactive (dead monster)`,
delta: { status: 'dead', isActive: false }, 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; return encounter;
} }
@@ -791,7 +865,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
const updatedParticipants = (encounter.participants || []).map(p => const updatedParticipants = (encounter.participants || []).map(p =>
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : 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 undoAmount = changeType === 'damage' ? amount : -amount;
const newP = updatedParticipants.find(p => p.id === participantId); const newP = updatedParticipants.find(p => p.id === participantId);
const newValues = { const newValues = {
@@ -808,7 +882,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
participantId, participantName: participant.name, participantId, participantName: participant.name,
message, message,
delta: logDelta, delta: logDelta,
undo: { amount: undoAmount, oldValues, newValues }, undo: withEffectUndo({ amount: undoAmount, oldValues, newValues }),
}; };
return commit(encounter, patch, log, ctx); return commit(encounter, patch, log, ctx);
} }
@@ -819,6 +893,11 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount,
const participantId = participant.id; const participantId = participant.id;
let updates, message, logDelta = { amount, from: participant.currentHp }; let updates, message, logDelta = { amount, from: participant.currentHp };
const currentTemp = participant.tempHp || 0; 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') { if (changeType === 'damage') {
// Temp HP absorbs damage first. // Temp HP absorbs damage first.
@@ -837,9 +916,9 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount,
type: 'hp_change', participantId, participantName: participant.name, type: 'hp_change', participantId, participantName: participant.name,
message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`, message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`,
delta: { amount, from: participant.currentHp, to: participant.currentHp, tempHp: tempAfter }, 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; amount = remainingDmg;
const tempFinal = tempAfter; const tempFinal = tempAfter;
@@ -854,11 +933,11 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount,
deathSaveSuccesses: 0, deathSaveFailures: 0, deathSaveSuccesses: 0, deathSaveFailures: 0,
isActive: newP.isActive, conditions: [...(newP.conditions || [])], 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, type: 'deactivate_dead_monster', participantId, participantName: participant.name,
message: `${participant.name} marked inactive (dead monster)`, message: `${participant.name} marked inactive (dead monster)`,
delta: { status: 'dead', isActive: false }, delta: { status: 'dead', isActive: false },
undo: { oldValues, newValues }, undo: withEffectUndo({ oldValues, newValues }),
}, ctx); }, ctx);
} }
return encounter; return encounter;
@@ -895,10 +974,10 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount,
isActive: newP.isActive, conditions: [...(newP.conditions || [])], isActive: newP.isActive, conditions: [...(newP.conditions || [])],
}; };
const undoAmount = changeType === 'damage' ? amount : -amount; const undoAmount = changeType === 'damage' ? amount : -amount;
return commit(encounter, { participants: updatedParticipants }, { return commit(encounter, withEffectPatch({ participants: updatedParticipants }), {
type: changeType, participantId, participantName: participant.name, type: changeType, participantId, participantName: participant.name,
message, delta: logDelta, message, delta: logDelta,
undo: { amount: undoAmount, oldValues, newValues }, undo: withEffectUndo({ amount: undoAmount, oldValues, newValues }),
}, ctx); }, ctx);
} }
@@ -987,6 +1066,52 @@ async function toggleCondition(encounter, participantId, conditionId, ctx) {
return commit(encounter, patch, log, 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) { async function stabilizeParticipant(encounter, participantId, ctx) {
if ((encounter.ruleset || '5e') === 'generic') { if ((encounter.ruleset || '5e') === 'generic') {
throw new Error('Stabilize not available in generic ruleset.'); throw new Error('Stabilize not available in generic ruleset.');
@@ -1261,10 +1386,11 @@ module.exports = {
generateId, rollD20, rollHpFormula, formatInitMod, generateId, rollD20, rollHpFormula, formatInitMod,
sortParticipantsByInitiative, syncTurnOrder, computeTurnOrderAfterRemoval, sortParticipantsByInitiative, syncTurnOrder, computeTurnOrderAfterRemoval,
snapshotOf, buildEntry, expandUndo, snapshotOf, buildEntry, expandUndo,
makeParticipant, buildCharacterParticipant, buildMonsterParticipant, makeEffect, makeParticipant, buildCharacterParticipant, buildMonsterParticipant,
startEncounter, nextTurn, togglePause, startEncounter, nextTurn, togglePause,
addParticipant, addParticipants, updateParticipant, removeParticipant, addParticipant, addParticipants, updateParticipant, removeParticipant,
toggleParticipantActive, applyHpChange, setTempHp, deathSave, stabilizeParticipant, reviveParticipant, markDead, toggleCondition, toggleParticipantActive, applyHpChange, setTempHp, deathSave, stabilizeParticipant, reviveParticipant, markDead, toggleCondition,
addEffect, updateEffect, removeEffect,
reorderParticipants, endEncounter, rerollAllInitiatives, reorderParticipants, endEncounter, rerollAllInitiatives,
activateDisplay, clearDisplay, toggleHidePlayerHp, activateDisplay, clearDisplay, toggleHidePlayerHp,
}; };
+360 -1
View File
@@ -130,6 +130,9 @@ const {
markDead, markDead,
toggleCondition: combatToggleCondition, toggleCondition: combatToggleCondition,
reorderParticipants, reorderParticipants,
addEffect: combatAddEffect,
updateEffect: combatUpdateEffect,
removeEffect: combatRemoveEffect,
} = shared; } = shared;
const ROLL_DISPLAY_DURATION = 5000; 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 (
<Modal onClose={onClose} title="Add Tracked Effect">
<form onSubmit={submit} className="space-y-3">
<label className="block text-sm text-stone-300">
Effect preset
<select aria-label="Effect preset" value={presetId} onChange={(e) => selectPreset(e.target.value)} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white">
<option value="custom">Custom</option>
{is5e && <option value="turned">Turned</option>}
{is5e && <option value="spiritual_weapon">Spiritual Weapon</option>}
</select>
</label>
<label className="block text-sm text-stone-300">
Effect name
<input aria-label="Effect name" value={name} onChange={(e) => setName(e.target.value)} maxLength={60} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white" />
</label>
<div className="grid grid-cols-2 gap-3">
<label className="block text-sm text-stone-300">
Scope
<select aria-label="Effect scope" value={scope} onChange={(e) => setScope(e.target.value)} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white">
<option value="participant">Participant</option>
<option value="encounter">Encounter</option>
</select>
</label>
{scope === 'participant' && (
<label className="block text-sm text-stone-300">
Target
<select aria-label="Effect target" value={targetParticipantId} onChange={(e) => setTargetParticipantId(e.target.value)} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white">
{participants.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
</select>
</label>
)}
</div>
<label className="block text-sm text-stone-300">
Owner (optional)
<select aria-label="Effect owner" value={ownerParticipantId} onChange={(e) => setOwnerParticipantId(e.target.value)} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white">
<option value="">None</option>
{participants.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
</select>
</label>
<div className="grid grid-cols-2 gap-3">
<label className="block text-sm text-stone-300">
Duration
<input aria-label="Duration" type="number" min="1" value={duration} onChange={(e) => setDuration(e.target.value)} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white" />
</label>
<label className="block text-sm text-stone-300">
Duration unit
<select aria-label="Duration unit" value={durationUnit} onChange={(e) => setDurationUnit(e.target.value)} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white">
<option value="rounds">Rounds</option>
{is5e && <option value="minutes">Minutes (×10 rounds)</option>}
</select>
</label>
</div>
<label className="block text-sm text-stone-300">
Player display
<select aria-label="Player display" value={playerDisplay} onChange={(e) => setPlayerDisplay(e.target.value)} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white">
<option value="hidden">Hidden from players</option>
<option value="compact">Compact badge</option>
<option value="prominent">Prominent banner</option>
</select>
</label>
<label className="flex items-center gap-2 text-sm text-stone-300">
<input type="checkbox" checked={expiresOnDamage} onChange={(e) => setExpiresOnDamage(e.target.checked)} />
End when target takes damage
</label>
<label className="block text-sm text-stone-300">
Notes (optional)
<input aria-label="Effect notes" value={notes} onChange={(e) => setNotes(e.target.value)} maxLength={160} className="mt-1 w-full px-3 py-2 bg-stone-800 border border-stone-600 rounded text-white" />
</label>
<div className="flex justify-end gap-3 pt-2">
<button type="button" onClick={onClose} className="px-4 py-2 rounded bg-stone-700 text-stone-200">Cancel</button>
<button type="submit" disabled={!name.trim() || (scope === 'participant' && !targetParticipantId)} className="px-4 py-2 rounded bg-purple-700 hover:bg-purple-600 text-white disabled:opacity-40">Add Effect</button>
</div>
</form>
</Modal>
);
}
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 (
<div className="mt-2 flex flex-wrap items-center gap-2 rounded-md border border-purple-500 bg-purple-950/70 px-3 py-2 text-purple-100" data-testid={`dm-effect-${effect.id}`}>
<span className="font-bold tracking-wide">{effect.name.toUpperCase()}</span>
<label className="inline-flex items-center gap-1 text-sm text-purple-200">
<input
type="number"
min="1"
value={draftRounds}
onChange={(e) => setDraftRounds(e.target.value)}
onBlur={commitRounds}
onKeyDown={(e) => {
if (e.key === 'Enter') e.currentTarget.blur();
if (e.key === 'Escape') { setDraftRounds(String(effect.remainingRounds)); e.currentTarget.blur(); }
}}
aria-label={`Turns left for ${effect.name}`}
className="w-14 rounded border border-purple-500 bg-stone-900 px-1.5 py-0.5 text-center text-white"
/>
rounds
</label>
{owner && <span className="text-xs text-stone-300">Owner: {owner.name}</span>}
{effect.expiresOnDamage && <span className="text-xs text-red-300">Ends on damage</span>}
<span className="ml-auto flex gap-1">
<button type="button" onClick={() => onAdjust(effect, -1)} aria-label={`Decrease ${effect.name} duration`} className="px-2 py-0.5 rounded bg-stone-700 hover:bg-stone-600">−</button>
<button type="button" onClick={() => onAdjust(effect, 1)} aria-label={`Increase ${effect.name} duration`} className="px-2 py-0.5 rounded bg-stone-700 hover:bg-stone-600">+</button>
<button type="button" onClick={() => onRemove(effect)} aria-label={`Remove ${effect.name}`} className="px-2 py-0.5 rounded bg-red-900 hover:bg-red-800 text-red-200">×</button>
</span>
</div>
);
}
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 (
<div data-testid={testId} className="mt-3 rounded-lg border-2 border-purple-400 bg-purple-950/90 px-4 py-3 text-center text-purple-100 shadow-lg">
<div className="text-lg md:text-xl font-bold tracking-widest">{effect.name.toUpperCase()}</div>
<div className="text-sm md:text-base text-purple-200">
{ownerName && <span>{ownerName} · </span>}{effect.remainingRounds} rounds remaining
{effect.expiresOnDamage && <span className="ml-2 text-red-300">· Ends on damage</span>}
</div>
{effect.notes && <div className="mt-1 text-xs md:text-sm text-stone-300">{effect.notes}</div>}
</div>
);
}
return (
<span className="inline-flex items-center gap-1 mt-2 mr-1 px-2 py-1 rounded-full bg-purple-900 border border-purple-500 text-xs md:text-sm text-purple-100 font-medium">
{effect.name} · {effect.remainingRounds} rounds{ownerName ? ` · ${ownerName}` : ''}
</span>
);
}
// ============================================================================ // ============================================================================
// PARTICIPANT MANAGER COMPONENT // PARTICIPANT MANAGER COMPONENT
// ============================================================================ // ============================================================================
@@ -1215,6 +1416,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
const [lastRollDetails, setLastRollDetails] = useState(null); const [lastRollDetails, setLastRollDetails] = useState(null);
const [openConditionsId, setOpenConditionsId] = useState(null); const [openConditionsId, setOpenConditionsId] = useState(null);
const [customConditionInput, setCustomConditionInput] = useState(''); const [customConditionInput, setCustomConditionInput] = useState('');
const [effectModal, setEffectModal] = useState(null);
// Per-campaign custom conditions (DM-added freeform strings). // Per-campaign custom conditions (DM-added freeform strings).
const { data: campaignDoc } = useFirestoreDocument(campaignId ? getPath.campaign(campaignId) : null); 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. // Add freeform condition: persist to campaign palette + apply to current participant.
const addCustomCondition = async (label, participantId = null) => { const addCustomCondition = async (label, participantId = null) => {
const trimmed = (label || '').trim(); 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))) && (
<div className="my-3 rounded-md border border-stone-700 bg-stone-950/60 p-3">
<h4 className="font-semibold text-purple-200">Encounter Effects</h4>
{(encounter.effects || []).filter(effect => effect.scope === 'encounter' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId))).map(effect => (
<EffectControlRow key={effect.id} effect={effect} participants={participants} onAdjust={handleAdjustEffect} onSet={handleSetEffectDuration} onRemove={handleRemoveEffect} />
))}
</div>
)}
{participants.length === 0 && <p className="text-sm text-stone-400">No participants added yet.</p>} {participants.length === 0 && <p className="text-sm text-stone-400">No participants added yet.</p>}
@@ -1863,6 +2143,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
return ( return (
<li <li
key={p.id} key={p.id}
data-testid={`admin-participant-card-${p.id}`}
draggable={isDraggable} draggable={isDraggable}
onDragStart={isDraggable ? (e) => handleDragStart(e, p.id) : undefined} onDragStart={isDraggable ? (e) => handleDragStart(e, p.id) : undefined}
onDragOver={isDraggable ? handleDragOver : undefined} onDragOver={isDraggable ? handleDragOver : undefined}
@@ -2067,6 +2348,13 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
</div> </div>
)} )}
{(encounter.effects || []).filter(effect =>
(effect.scope === 'participant' && effect.targetParticipantId === p.id) ||
(effect.scope === 'encounter' && effect.ownerParticipantId === p.id)
).map(effect => (
<EffectControlRow key={effect.id} effect={effect} participants={participants} onAdjust={handleAdjustEffect} onSet={handleSetEffectDuration} onRemove={handleRemoveEffect} />
))}
{/* Expandable conditions picker */} {/* Expandable conditions picker */}
{openConditionsId === p.id && ( {openConditionsId === p.id && (
<div className="mt-2 p-2 bg-stone-900 rounded-md border border-stone-600"> <div className="mt-2 p-2 bg-stone-900 rounded-md border border-stone-600">
@@ -2086,6 +2374,48 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
); );
})} })}
</div> </div>
{(encounter.ruleset || '5e') === '5e' && (
<>
<p className="text-xs text-stone-400 mt-3 mb-1 font-medium">Tracked Effects</p>
<div className="flex flex-wrap gap-1">
{(() => {
const active = (encounter.effects || []).some(effect => effect.presetId === 'turned' && effect.targetParticipantId === p.id);
return (
<button
type="button"
onClick={() => togglePresetEffect('turned', p)}
aria-label="Turned"
className={`px-2 py-1 rounded text-xs transition-colors ${active ? 'bg-purple-700 border border-purple-300 text-white' : 'bg-stone-700 border border-stone-500 text-stone-300 hover:bg-stone-600'}`}
>
↪ Turned · 10 rounds
</button>
);
})()}
{(() => {
const active = (encounter.effects || []).some(effect => effect.presetId === 'spiritual_weapon' && effect.ownerParticipantId === p.id);
return (
<button
type="button"
onClick={() => togglePresetEffect('spiritual_weapon', p)}
aria-label="Spiritual Weapon"
className={`px-2 py-1 rounded text-xs transition-colors ${active ? 'bg-purple-700 border border-purple-300 text-white' : 'bg-stone-700 border border-stone-500 text-stone-300 hover:bg-stone-600'}`}
>
✨ Spiritual Weapon · 10 rounds
</button>
);
})()}
</div>
</>
)}
<button
type="button"
onClick={() => setEffectModal({ scope: 'participant', targetParticipantId: p.id })}
aria-label="Custom tracked effect"
className="mt-2 px-2 py-1 rounded text-xs bg-purple-900 border border-purple-600 text-purple-100 hover:bg-purple-800"
>
+ Custom tracked effect
</button>
{/* Add custom condition (per-campaign, freeform string) */} {/* Add custom condition (per-campaign, freeform string) */}
<div className="mt-2 flex gap-1"> <div className="mt-2 flex gap-1">
<input <input
@@ -2206,6 +2536,17 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
)} )}
</div> </div>
{effectModal && (
<EffectModal
key={`${effectModal.scope}-${effectModal.targetParticipantId || 'encounter'}`}
encounter={encounter}
defaultScope={effectModal.scope}
defaultTargetParticipantId={effectModal.targetParticipantId}
onClose={() => setEffectModal(null)}
onAdd={handleAddEffect}
/>
)}
<ConfirmationModal <ConfirmationModal
isOpen={showDeleteConfirm} isOpen={showDeleteConfirm}
onClose={() => setShowDeleteConfirm(false)} onClose={() => setShowDeleteConfirm(false)}
@@ -3684,6 +4025,7 @@ function PlayerParticipantCard({ id, isActive, status, onExit, className, childr
return ( return (
<div <div
ref={divRef} ref={divRef}
data-testid={`participant-card-${id}`}
className={`[transition:opacity_1s_ease-in-out,transform_1s_ease-in-out,filter_1s_ease-in-out,border-color_1s_ease-in-out,box-shadow_300ms_ease-in-out] ${fadeClass} ${deathClass} ${className}`} className={`[transition:opacity_1s_ease-in-out,transform_1s_ease-in-out,filter_1s_ease-in-out,border-color_1s_ease-in-out,box-shadow_300ms_ease-in-out] ${fadeClass} ${deathClass} ${className}`}
> >
{children} {children}
@@ -3918,6 +4260,7 @@ function DisplayView() {
} }
const { name, participants, round, currentTurnParticipantId, isStarted, isPaused } = activeEncounterData; const { name, participants, round, currentTurnParticipantId, isStarted, isPaused } = activeEncounterData;
const trackedEffects = activeEncounterData.effects || [];
const hidePlayerHp = activeDisplayData?.hidePlayerHp ?? true; const hidePlayerHp = activeDisplayData?.hidePlayerHp ?? true;
const hideNpcHp = activeDisplayData?.hideNpcHp ?? false; const hideNpcHp = activeDisplayData?.hideNpcHp ?? false;
@@ -3974,6 +4317,12 @@ function DisplayView() {
<p className="text-xl text-stone-400">No active participants.</p> <p className="text-xl text-stone-400">No active participants.</p>
)} )}
<div className="max-w-3xl mx-auto mb-4">
{trackedEffects
.filter(effect => effect.scope === 'encounter' && effect.playerDisplay !== 'hidden' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId)))
.map(effect => <PlayerEffectDisplay key={effect.id} effect={effect} />)}
</div>
<div className="space-y-4 max-w-3xl mx-auto"> <div className="space-y-4 max-w-3xl mx-auto">
{participantsToRender.map(p => { {participantsToRender.map(p => {
const isGeneric = (activeEncounterData.ruleset || '5e') === 'generic'; const isGeneric = (activeEncounterData.ruleset || '5e') === 'generic';
@@ -4022,8 +4371,18 @@ function DisplayView() {
</span> </span>
</div> </div>
{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 <PlayerEffectDisplay key={effect.id} effect={effect} ownerName={owner?.name} />;
})}
{!(hidePlayerHp && p.type === 'character') && !(hideNpcHp && p.type !== 'character') && ( {!(hidePlayerHp && p.type === 'character') && !(hideNpcHp && p.type !== 'character') && (
<div className="flex justify-between items-center"> <div className="flex justify-between items-center mt-2">
<div className="w-full bg-stone-700 rounded-full h-6 md:h-8 relative overflow-hidden border-2 border-stone-600"> <div className="w-full bg-stone-700 rounded-full h-6 md:h-8 relative overflow-hidden border-2 border-stone-600">
<div <div
className={`h-full rounded-full transition-all ${isZeroHp ? 'bg-red-900' : (p.currentHp <= p.maxHp / 4 ? 'bg-red-500' : (p.currentHp <= p.maxHp / 2 ? 'bg-yellow-500' : 'bg-green-500'))}`} className={`h-full rounded-full transition-all ${isZeroHp ? 'bg-red-900' : (p.currentHp <= p.maxHp / 4 ? 'bg-red-500' : (p.currentHp <= p.maxHp / 2 ? 'bg-yellow-500' : 'bg-green-500'))}`}
+78
View File
@@ -0,0 +1,78 @@
import React from 'react';
import { render, screen, within } from '@testing-library/react';
import '@testing-library/jest-dom';
import App from '../App';
import { MOCK_DB } from '../__mocks__/firebase/_mock-db';
const campaignPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/c1';
const encounterPath = `${campaignPath}/encounters/e1`;
const activeDisplayPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status';
function seed(effects) {
const participants = [
{ id: 'p1', name: 'Cleric', type: 'character', initiative: 18, maxHp: 30, currentHp: 30, isActive: true, conditions: [] },
{ id: 'p2', name: 'Zombie', type: 'monster', initiative: 8, maxHp: 22, currentHp: 22, isActive: true, conditions: [] },
];
MOCK_DB.set(campaignPath, { name: 'Camp', playerDisplayBackgroundUrl: '' });
MOCK_DB.set(encounterPath, { name: 'Enc', participants, effects, ruleset: '5e', isStarted: true, round: 2, currentTurnParticipantId: 'p1' });
MOCK_DB.set(activeDisplayPath, { activeCampaignId: 'c1', activeEncounterId: 'e1', hidePlayerHp: false });
}
beforeEach(() => {
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(<App />);
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(<App />);
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(<App />);
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(<App />);
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);
});
});
+108
View File
@@ -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([]));
});
});