feat: encounter UX, tracked effects, and character state improvements #10
No files matched your search
@@ -0,0 +1,78 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// rerollAllInitiatives: bulk d20+initMod for every participant.
|
||||||
|
// Single commit, single log, undo restores old values + order.
|
||||||
|
|
||||||
|
const {
|
||||||
|
makeParticipant,
|
||||||
|
startEncounter,
|
||||||
|
rerollAllInitiatives,
|
||||||
|
} = require('@ttrpg/shared');
|
||||||
|
const { mockCtx, undoLast } = require('./_helpers');
|
||||||
|
|
||||||
|
function part(id, init, initMod, extra = {}) {
|
||||||
|
return makeParticipant({
|
||||||
|
id, name: id, type: initMod !== undefined ? 'monster' : 'character',
|
||||||
|
initiative: init, initMod, maxHp: 20, currentHp: 20, ...extra,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function enc(participants, extra = {}) {
|
||||||
|
return {
|
||||||
|
id: 'e1', name: 'reroll-all-test', participants,
|
||||||
|
isStarted: false, isPaused: false, round: 0,
|
||||||
|
currentTurnParticipantId: null, turnOrderIds: [],
|
||||||
|
...extra,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const find = (e, id) => e.participants.find(p => p.id === id);
|
||||||
|
|
||||||
|
describe('rerollAllInitiatives', () => {
|
||||||
|
test('rolls d20+initMod for every participant; single write', async () => {
|
||||||
|
const { ctx, storage } = mockCtx();
|
||||||
|
const e = enc([part('a', 10, 5), part('b', 8, 2), part('c', 15, 0)]);
|
||||||
|
|
||||||
|
const out = await rerollAllInitiatives(e, ctx);
|
||||||
|
|
||||||
|
for (const id of ['a', 'b', 'c']) {
|
||||||
|
const p = find(out, id);
|
||||||
|
const mod = id === 'a' ? 5 : id === 'b' ? 2 : 0;
|
||||||
|
expect(p.initiative).toBeGreaterThanOrEqual(mod + 1);
|
||||||
|
expect(p.initiative).toBeLessThanOrEqual(mod + 20);
|
||||||
|
}
|
||||||
|
// one write for the whole operation
|
||||||
|
expect(storage.calls.filter(c => c.fn === 'updateDoc' && c.path === 'encounters/e1')).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('undo restores exact old initiatives and order', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
const e = enc([part('a', 10, 5), part('b', 8, 2)]);
|
||||||
|
const orderBefore = [...e.turnOrderIds];
|
||||||
|
|
||||||
|
const out = await rerollAllInitiatives(e, ctx);
|
||||||
|
expect(find(out, 'a').initiative).not.toBe(10);
|
||||||
|
|
||||||
|
const undone = await undoLast(ctx, out);
|
||||||
|
expect(find(undone, 'a').initiative).toBe(10);
|
||||||
|
expect(find(undone, 'b').initiative).toBe(8);
|
||||||
|
expect(undone.turnOrderIds).toEqual(orderBefore);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('inactive participants rerolled too (they stay inactive)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
const e = enc([part('a', 10, 1), part('b', 9, 1, { isActive: false })]);
|
||||||
|
|
||||||
|
const out = await rerollAllInitiatives(e, ctx);
|
||||||
|
expect(find(out, 'b').isActive).toBe(false);
|
||||||
|
expect(find(out, 'b').initiative).toBeGreaterThanOrEqual(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws during active combat (not paused)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([part('a', 10, 1)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
|
||||||
|
await expect(rerollAllInitiatives({ ...e, isPaused: false }, ctx)).rejects.toThrow(/paused/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Stable regain hours: stabilization rolls 1d4, persists until healed/revived.
|
||||||
|
// 3rd death save -> stable; manual stabilize -> stable; revive dead -> stable (5e).
|
||||||
|
|
||||||
|
const {
|
||||||
|
makeParticipant,
|
||||||
|
startEncounter,
|
||||||
|
applyHpChange,
|
||||||
|
deathSave,
|
||||||
|
stabilizeParticipant,
|
||||||
|
reviveParticipant,
|
||||||
|
} = require('@ttrpg/shared');
|
||||||
|
const { mockCtx } = require('./_helpers');
|
||||||
|
|
||||||
|
function pc(id, extra = {}) {
|
||||||
|
return makeParticipant({
|
||||||
|
id,
|
||||||
|
name: id,
|
||||||
|
type: 'character',
|
||||||
|
initiative: 10,
|
||||||
|
maxHp: 100,
|
||||||
|
currentHp: 100,
|
||||||
|
...extra,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function enc(participants, extra = {}) {
|
||||||
|
return {
|
||||||
|
id: 'e1',
|
||||||
|
name: 'stable-hours-test',
|
||||||
|
participants,
|
||||||
|
isStarted: false,
|
||||||
|
isPaused: false,
|
||||||
|
round: 0,
|
||||||
|
currentTurnParticipantId: null,
|
||||||
|
turnOrderIds: [],
|
||||||
|
...extra,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const part = e => e.participants.find(p => p.id === 'a');
|
||||||
|
|
||||||
|
async function dyingEnc() {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([pc('a')]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'a', 'damage', 100, ctx);
|
||||||
|
return { e, ctx };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('stableRegainHours', () => {
|
||||||
|
test('3rd death save success rolls 1d4 and stores stableRegainHours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
let out = e;
|
||||||
|
for (let i = 0; i < 3; i++) out = (await deathSave(out, 'a', 'success', ctx)).enc;
|
||||||
|
const p = part(out);
|
||||||
|
expect(p.status).toBe('stable');
|
||||||
|
expect(p.stableRegainHours).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(p.stableRegainHours).toBeLessThanOrEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('manual stabilize also rolls and stores hours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
const out = await stabilizeParticipant(e, 'a', ctx);
|
||||||
|
const p = part(out);
|
||||||
|
expect(p.status).toBe('stable');
|
||||||
|
expect(p.stableRegainHours).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(p.stableRegainHours).toBeLessThanOrEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('heal clears stableRegainHours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
let out = await stabilizeParticipant(e, 'a', ctx);
|
||||||
|
expect(part(out).stableRegainHours).toBeGreaterThanOrEqual(1);
|
||||||
|
out = await applyHpChange(out, 'a', 'heal', 5, ctx);
|
||||||
|
expect(part(out).status).toBe('conscious');
|
||||||
|
expect(part(out).stableRegainHours == null).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reviveParticipant to stable rolls fresh hours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
let out = e;
|
||||||
|
for (let i = 0; i < 3; i++) out = (await deathSave(out, 'a', 'fail', ctx)).enc;
|
||||||
|
expect(part(out).status).toBe('dead');
|
||||||
|
out = await reviveParticipant(out, 'a', ctx);
|
||||||
|
const p = part(out);
|
||||||
|
expect(p.status).toBe('stable');
|
||||||
|
expect(p.stableRegainHours).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(p.stableRegainHours).toBeLessThanOrEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dying (not yet stable) has no stableRegainHours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
const out = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||||
|
expect(part(out).status).toBe('dying');
|
||||||
|
expect(part(out).stableRegainHours == null).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -204,3 +204,71 @@ describe('character writeback on endEncounter', () => {
|
|||||||
expect(storage._writes.find(w => w.path === 'campaigns/camp1')).toBeUndefined();
|
expect(storage._writes.find(w => w.path === 'campaigns/camp1')).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('stable regain hours writeback', () => {
|
||||||
|
function ctxFor(storage) {
|
||||||
|
return {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('stable char carries stableRegainHours to roster', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 },
|
||||||
|
];
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
const enc = makeEncounter({
|
||||||
|
participants: [
|
||||||
|
{ id: 'p1', name: 'Fighter', type: 'character', originalCharacterId: 'char1', initiative: 15, maxHp: 30, currentHp: 0, ac: 17, status: 'stable', stableRegainHours: 3 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await endEncounter(enc, ctxFor(storage));
|
||||||
|
const campWrite = storage._writes.find(w => w.path === 'campaigns/camp1');
|
||||||
|
expect(campWrite).toBeDefined();
|
||||||
|
const fighter = campWrite.patch.players.find(p => p.id === 'char1');
|
||||||
|
expect(fighter.stableRegainHours).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('conscious char clears stale roster stableRegainHours', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30, stableRegainHours: 2 },
|
||||||
|
];
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
const enc = makeEncounter({
|
||||||
|
participants: [
|
||||||
|
{ id: 'p1', name: 'Fighter', type: 'character', originalCharacterId: 'char1', initiative: 15, maxHp: 30, currentHp: 12, ac: 17, status: 'conscious' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await endEncounter(enc, ctxFor(storage));
|
||||||
|
const campWrite = storage._writes.find(w => w.path === 'campaigns/camp1');
|
||||||
|
expect(campWrite).toBeDefined();
|
||||||
|
const fighter = campWrite.patch.players.find(p => p.id === 'char1');
|
||||||
|
expect(fighter.stableRegainHours).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('buildCharacterParticipant carries stable state', () => {
|
||||||
|
const { buildCharacterParticipant } = shared;
|
||||||
|
|
||||||
|
test('roster stable char becomes stable participant with hours', () => {
|
||||||
|
const char = { id: 'c1', name: 'Rogue', defaultMaxHp: 40, defaultCurrentHp: 0, defaultInitMod: 2, stableRegainHours: 4 };
|
||||||
|
const { participant } = buildCharacterParticipant(char);
|
||||||
|
expect(participant.currentHp).toBe(0);
|
||||||
|
expect(participant.status).toBe('stable');
|
||||||
|
expect(participant.stableRegainHours).toBe(4);
|
||||||
|
expect(participant.conditions).toContain('unconscious');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('healthy roster char stays conscious, no hours', () => {
|
||||||
|
const char = { id: 'c2', name: 'Cleric', defaultMaxHp: 30, defaultCurrentHp: 30, defaultInitMod: 1 };
|
||||||
|
const { participant } = buildCharacterParticipant(char);
|
||||||
|
expect(participant.status).toBe('conscious');
|
||||||
|
expect(participant.stableRegainHours).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
+72
-8
@@ -27,6 +27,7 @@ const generateId = () =>
|
|||||||
: `id_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
: `id_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
|
||||||
const rollD20 = () => Math.floor(Math.random() * 20) + 1;
|
const rollD20 = () => Math.floor(Math.random() * 20) + 1;
|
||||||
|
const rollD4 = () => Math.floor(Math.random() * 4) + 1;
|
||||||
|
|
||||||
// Parse HP formula like "2d6+9" or "3d8-2" or "1d20". Roll, return total.
|
// Parse HP formula like "2d6+9" or "3d8-2" or "1d20". Roll, return total.
|
||||||
// Returns null on invalid input. Whitespace/case tolerant.
|
// Returns null on invalid input. Whitespace/case tolerant.
|
||||||
@@ -198,6 +199,16 @@ function expandUndo(entry, currentEnc) {
|
|||||||
: { participants: [...parts, ...added.filter(p => !parts.some(x => x.id === p.id))] },
|
: { participants: [...parts, ...added.filter(p => !parts.some(x => x.id === p.id))] },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
case 'reroll_all_init': {
|
||||||
|
// undo: restore pre-reroll array + order. redo: re-apply rolled array.
|
||||||
|
return {
|
||||||
|
encounterPath: encPath,
|
||||||
|
updates: { participants: u.participants.map(p => ({ ...p })), turnOrderIds: u.turnOrderIds },
|
||||||
|
redo: u.newParticipants && u.newTurnOrderIds
|
||||||
|
? { participants: u.newParticipants.map(p => ({ ...p })), turnOrderIds: u.newTurnOrderIds }
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
case 'remove_participant': {
|
case 'remove_participant': {
|
||||||
const p = u.participant;
|
const p = u.participant;
|
||||||
const turnState = {};
|
const turnState = {};
|
||||||
@@ -240,6 +251,7 @@ function expandUndo(entry, currentEnc) {
|
|||||||
if (vals.status !== undefined) out.status = vals.status;
|
if (vals.status !== undefined) out.status = vals.status;
|
||||||
if (vals.deathSaveSuccesses !== undefined) out.deathSaveSuccesses = vals.deathSaveSuccesses;
|
if (vals.deathSaveSuccesses !== undefined) out.deathSaveSuccesses = vals.deathSaveSuccesses;
|
||||||
if (vals.deathSaveFailures !== undefined) out.deathSaveFailures = vals.deathSaveFailures;
|
if (vals.deathSaveFailures !== undefined) out.deathSaveFailures = vals.deathSaveFailures;
|
||||||
|
if (vals.stableRegainHours !== undefined) out.stableRegainHours = vals.stableRegainHours;
|
||||||
if (vals.isActive !== undefined) out.isActive = vals.isActive;
|
if (vals.isActive !== undefined) out.isActive = vals.isActive;
|
||||||
if (vals.conditions !== undefined) out.conditions = vals.conditions;
|
if (vals.conditions !== undefined) out.conditions = vals.conditions;
|
||||||
return out;
|
return out;
|
||||||
@@ -361,6 +373,7 @@ function makeParticipant(opts) {
|
|||||||
status: opts.status || (opts.currentHp === 0 ? 'dying' : 'conscious'),
|
status: opts.status || (opts.currentHp === 0 ? 'dying' : 'conscious'),
|
||||||
deathSaveSuccesses: opts.deathSaveSuccesses || 0,
|
deathSaveSuccesses: opts.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: opts.deathSaveFailures || 0,
|
deathSaveFailures: opts.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: opts.stableRegainHours !== undefined ? opts.stableRegainHours : null,
|
||||||
hpFormula: opts.hpFormula || null,
|
hpFormula: opts.hpFormula || null,
|
||||||
ac: opts.ac !== undefined ? opts.ac : null,
|
ac: opts.ac !== undefined ? opts.ac : null,
|
||||||
tempHp: opts.tempHp !== undefined ? opts.tempHp : 0,
|
tempHp: opts.tempHp !== undefined ? opts.tempHp : 0,
|
||||||
@@ -373,6 +386,8 @@ function buildCharacterParticipant(character) {
|
|||||||
const finalInitiative = initiativeRoll + modifier;
|
const finalInitiative = initiativeRoll + modifier;
|
||||||
const maxHp = character.defaultMaxHp || DEFAULT_MAX_HP;
|
const maxHp = character.defaultMaxHp || DEFAULT_MAX_HP;
|
||||||
const currentHp = character.defaultCurrentHp != null ? character.defaultCurrentHp : maxHp;
|
const currentHp = character.defaultCurrentHp != null ? character.defaultCurrentHp : maxHp;
|
||||||
|
// Roster carried stable state (from writeback): still down at 0 HP, unconscious.
|
||||||
|
const isStable = currentHp === 0 && character.stableRegainHours != null;
|
||||||
return {
|
return {
|
||||||
participant: makeParticipant({
|
participant: makeParticipant({
|
||||||
name: character.name,
|
name: character.name,
|
||||||
@@ -382,6 +397,9 @@ function buildCharacterParticipant(character) {
|
|||||||
initMod: modifier,
|
initMod: modifier,
|
||||||
maxHp,
|
maxHp,
|
||||||
currentHp,
|
currentHp,
|
||||||
|
status: isStable ? 'stable' : undefined,
|
||||||
|
stableRegainHours: isStable ? character.stableRegainHours : null,
|
||||||
|
conditions: isStable ? ['unconscious'] : [],
|
||||||
ac: character.defaultAc !== undefined ? character.defaultAc : null,
|
ac: character.defaultAc !== undefined ? character.defaultAc : null,
|
||||||
}),
|
}),
|
||||||
roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative },
|
roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative },
|
||||||
@@ -664,6 +682,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
status: participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious'),
|
status: participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious'),
|
||||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
isActive: participant.isActive,
|
isActive: participant.isActive,
|
||||||
conditions: [...(participant.conditions || [])],
|
conditions: [...(participant.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -741,7 +760,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
if (failures >= 3) {
|
if (failures >= 3) {
|
||||||
updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, tempHp: tempFinal, ...(participant.type === 'monster' ? { isActive: false } : {}) };
|
updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, tempHp: tempFinal, ...(participant.type === 'monster' ? { isActive: false } : {}) };
|
||||||
} else {
|
} else {
|
||||||
updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: 0, deathSaveFailures: failures, tempHp: tempFinal };
|
updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: 0, deathSaveFailures: failures, stableRegainHours: null, tempHp: tempFinal };
|
||||||
}
|
}
|
||||||
message = `${participant.name} took ${amount} damage while ${status === 'stable' ? 'stable' : 'dying'}`;
|
message = `${participant.name} took ${amount} damage while ${status === 'stable' ? 'stable' : 'dying'}`;
|
||||||
logDelta = { ...logDelta, to: 0, status: updates.status, deathSaveFailures: updates.deathSaveFailures };
|
logDelta = { ...logDelta, to: 0, status: updates.status, deathSaveFailures: updates.deathSaveFailures };
|
||||||
@@ -763,7 +782,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
} else if (changeType === 'heal') {
|
} else if (changeType === 'heal') {
|
||||||
if (status === 'dead') return encounter;
|
if (status === 'dead') return encounter;
|
||||||
const newHp = Math.min(participant.maxHp, Math.max(1, participant.currentHp + amount));
|
const newHp = Math.min(participant.maxHp, Math.max(1, participant.currentHp + amount));
|
||||||
updates = { currentHp: newHp, status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
updates = { currentHp: newHp, status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null };
|
||||||
message = `${participant.name} healed for ${amount} (${participant.currentHp} → ${newHp} HP)`;
|
message = `${participant.name} healed for ${amount} (${participant.currentHp} → ${newHp} HP)`;
|
||||||
logDelta = { ...logDelta, to: newHp, status: 'conscious', deathSavesCleared: true };
|
logDelta = { ...logDelta, to: newHp, status: 'conscious', deathSavesCleared: true };
|
||||||
} else {
|
} else {
|
||||||
@@ -781,6 +800,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
status: newP.status,
|
status: newP.status,
|
||||||
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: newP.deathSaveFailures || 0,
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
isActive: newP.isActive,
|
isActive: newP.isActive,
|
||||||
conditions: [...(newP.conditions || [])],
|
conditions: [...(newP.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -900,6 +920,7 @@ async function deathSave(encounter, participantId, outcome, ctx) {
|
|||||||
status: statusBefore,
|
status: statusBefore,
|
||||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
isActive: participant.isActive,
|
isActive: participant.isActive,
|
||||||
conditions: [...(participant.conditions || [])],
|
conditions: [...(participant.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -910,8 +931,8 @@ async function deathSave(encounter, participantId, outcome, ctx) {
|
|||||||
} else {
|
} else {
|
||||||
const successes = (participant.deathSaveSuccesses || 0) + (outcome === 'success' ? 1 : 0);
|
const successes = (participant.deathSaveSuccesses || 0) + (outcome === 'success' ? 1 : 0);
|
||||||
const failures = (participant.deathSaveFailures || 0) + (outcome === 'fail' ? 1 : outcome === 'nat1' ? 2 : 0);
|
const failures = (participant.deathSaveFailures || 0) + (outcome === 'fail' ? 1 : outcome === 'nat1' ? 2 : 0);
|
||||||
if (failures >= 3) updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
if (failures >= 3) updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null };
|
||||||
else if (successes >= 3) updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
else if (successes >= 3) updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: rollD4() };
|
||||||
else updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: successes, deathSaveFailures: failures };
|
else updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: successes, deathSaveFailures: failures };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -931,6 +952,7 @@ async function deathSave(encounter, participantId, outcome, ctx) {
|
|||||||
status: newP.status,
|
status: newP.status,
|
||||||
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: newP.deathSaveFailures || 0,
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
isActive: newP.isActive,
|
isActive: newP.isActive,
|
||||||
conditions: [...(newP.conditions || [])],
|
conditions: [...(newP.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -977,7 +999,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) {
|
|||||||
if (status === 'dead') throw new Error('Cannot stabilize dead participant.');
|
if (status === 'dead') throw new Error('Cannot stabilize dead participant.');
|
||||||
if (status === 'stable') return encounter;
|
if (status === 'stable') return encounter;
|
||||||
|
|
||||||
const updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
const updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: rollD4() };
|
||||||
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
|
||||||
);
|
);
|
||||||
@@ -988,6 +1010,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) {
|
|||||||
status,
|
status,
|
||||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
isActive: participant.isActive,
|
isActive: participant.isActive,
|
||||||
conditions: [...(participant.conditions || [])],
|
conditions: [...(participant.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -997,6 +1020,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) {
|
|||||||
status: newP.status,
|
status: newP.status,
|
||||||
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: newP.deathSaveFailures || 0,
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
isActive: newP.isActive,
|
isActive: newP.isActive,
|
||||||
conditions: [...(newP.conditions || [])],
|
conditions: [...(newP.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -1022,7 +1046,7 @@ async function reviveParticipant(encounter, participantId, ctx) {
|
|||||||
// 5e: dead→stable at 0 HP, unconscious, clears death-save counters.
|
// 5e: dead→stable at 0 HP, unconscious, clears death-save counters.
|
||||||
const updates = ruleset === 'generic'
|
const updates = ruleset === 'generic'
|
||||||
? { status: 'conscious', ...(participant.type === 'monster' ? {} : {}), ...(participant.isActive === false ? { isActive: true } : {}) }
|
? { status: 'conscious', ...(participant.type === 'monster' ? {} : {}), ...(participant.isActive === false ? { isActive: true } : {}) }
|
||||||
: { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, isActive: true };
|
: { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: rollD4(), isActive: true };
|
||||||
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
|
||||||
);
|
);
|
||||||
@@ -1033,6 +1057,7 @@ async function reviveParticipant(encounter, participantId, ctx) {
|
|||||||
status,
|
status,
|
||||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
isActive: participant.isActive,
|
isActive: participant.isActive,
|
||||||
conditions: [...(participant.conditions || [])],
|
conditions: [...(participant.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -1042,6 +1067,7 @@ async function reviveParticipant(encounter, participantId, ctx) {
|
|||||||
status: newP.status,
|
status: newP.status,
|
||||||
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: newP.deathSaveFailures || 0,
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
isActive: newP.isActive,
|
isActive: newP.isActive,
|
||||||
conditions: [...(newP.conditions || [])],
|
conditions: [...(newP.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -1152,11 +1178,15 @@ async function endEncounter(encounter, ctx) {
|
|||||||
const oldMaxHp = player.defaultMaxHp;
|
const oldMaxHp = player.defaultMaxHp;
|
||||||
const oldAc = player.defaultAc;
|
const oldAc = player.defaultAc;
|
||||||
const oldCurrentHp = player.defaultCurrentHp;
|
const oldCurrentHp = player.defaultCurrentHp;
|
||||||
oldValues.push({ id: player.id, defaultMaxHp: oldMaxHp, defaultAc: oldAc, defaultCurrentHp: oldCurrentHp });
|
const oldStableRegainHours = player.stableRegainHours !== undefined ? player.stableRegainHours : null;
|
||||||
|
oldValues.push({ id: player.id, defaultMaxHp: oldMaxHp, defaultAc: oldAc, defaultCurrentHp: oldCurrentHp, stableRegainHours: oldStableRegainHours });
|
||||||
const newPlayer = { ...player };
|
const newPlayer = { ...player };
|
||||||
if (cp.maxHp != null && cp.maxHp !== oldMaxHp) { newPlayer.defaultMaxHp = cp.maxHp; changed = true; }
|
if (cp.maxHp != null && cp.maxHp !== oldMaxHp) { newPlayer.defaultMaxHp = cp.maxHp; changed = true; }
|
||||||
if (cp.ac != null && cp.ac !== oldAc) { newPlayer.defaultAc = cp.ac; changed = true; }
|
if (cp.ac != null && cp.ac !== oldAc) { newPlayer.defaultAc = cp.ac; changed = true; }
|
||||||
if (cp.currentHp != null && cp.currentHp !== oldCurrentHp) { newPlayer.defaultCurrentHp = cp.currentHp; changed = true; }
|
if (cp.currentHp != null && cp.currentHp !== oldCurrentHp) { newPlayer.defaultCurrentHp = cp.currentHp; changed = true; }
|
||||||
|
// Stable state: carried while stable, cleared once conscious again.
|
||||||
|
const cpStableRegainHours = cp.status === 'stable' ? (cp.stableRegainHours !== undefined ? cp.stableRegainHours : null) : null;
|
||||||
|
if (cpStableRegainHours !== oldStableRegainHours) { newPlayer.stableRegainHours = cpStableRegainHours; changed = true; }
|
||||||
return newPlayer;
|
return newPlayer;
|
||||||
});
|
});
|
||||||
if (changed) {
|
if (changed) {
|
||||||
@@ -1173,6 +1203,40 @@ async function endEncounter(encounter, ctx) {
|
|||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// rerollAllInitiatives: d20 + stored initMod for EVERY participant, one write.
|
||||||
|
// Allowed pre-combat or paused. Slot-based re-insertion preserves roll order.
|
||||||
|
// Single log entry; undo restores old array + order.
|
||||||
|
async function rerollAllInitiatives(encounter, ctx) {
|
||||||
|
if (encounter.isStarted && !encounter.isPaused) {
|
||||||
|
throw new Error('Reroll initiative only before combat or while paused.');
|
||||||
|
}
|
||||||
|
const oldParticipants = encounter.participants || [];
|
||||||
|
if (oldParticipants.length === 0) return encounter;
|
||||||
|
|
||||||
|
const rolled = oldParticipants.map(p => ({
|
||||||
|
...p,
|
||||||
|
initiative: rollD20() + (p.initMod != null ? p.initMod : 0),
|
||||||
|
}));
|
||||||
|
// slot re-insertion: each rolled participant placed above lower inits
|
||||||
|
const newList = [];
|
||||||
|
for (const p of rolled) {
|
||||||
|
newList.splice(slotIndexForInit(newList, p.initiative), 0, p);
|
||||||
|
}
|
||||||
|
const patch = { participants: newList, ...syncTurnOrder(newList) };
|
||||||
|
const log = {
|
||||||
|
type: 'reroll_all_init',
|
||||||
|
message: `Initiative rerolled for all ${newList.length} participants`,
|
||||||
|
delta: { count: newList.length },
|
||||||
|
undo: {
|
||||||
|
participants: oldParticipants.map(p => ({ ...p })),
|
||||||
|
turnOrderIds: [...(encounter.turnOrderIds || [])],
|
||||||
|
newParticipants: newList.map(p => ({ ...p })),
|
||||||
|
newTurnOrderIds: patch.turnOrderIds,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return commit(encounter, patch, log, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------------------------------
|
// ----------------------------------------------------------------------------
|
||||||
// Display lifecycle — write activeDisplay doc, no combat log.
|
// Display lifecycle — write activeDisplay doc, no combat log.
|
||||||
// ctx.displayPath required.
|
// ctx.displayPath required.
|
||||||
@@ -1199,6 +1263,6 @@ module.exports = {
|
|||||||
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,
|
||||||
reorderParticipants, endEncounter,
|
reorderParticipants, endEncounter, rerollAllInitiatives,
|
||||||
activateDisplay, clearDisplay, toggleHidePlayerHp,
|
activateDisplay, clearDisplay, toggleHidePlayerHp,
|
||||||
};
|
};
|
||||||
+125
-21
@@ -878,11 +878,22 @@ function CharacterManager({ campaignId, campaignCharacters, syncCharacters }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const updatedCharacters = campaignCharacters.map(c =>
|
const updatedCharacters = campaignCharacters.map(c => {
|
||||||
c.id === characterId
|
if (c.id !== characterId) return c;
|
||||||
? { ...c, name: newName.trim(), defaultMaxHp: hp, defaultInitMod: initMod, defaultAc: newDefaultAc !== undefined && newDefaultAc !== '' ? parseInt(newDefaultAc, 10) : null, defaultCurrentHp: newDefaultCurrentHp !== undefined && newDefaultCurrentHp !== '' ? parseInt(newDefaultCurrentHp, 10) : null, isNpc: newIsNpc != null ? newIsNpc : (c.isNpc || false) }
|
const nextCurrentHp = newDefaultCurrentHp !== undefined && newDefaultCurrentHp !== '' ? parseInt(newDefaultCurrentHp, 10) : null;
|
||||||
: c
|
// Healed off the floor: clear carried stable state.
|
||||||
);
|
const nextStableRegainHours = nextCurrentHp != null && nextCurrentHp > 0 ? null : (c.stableRegainHours !== undefined ? c.stableRegainHours : null);
|
||||||
|
return {
|
||||||
|
...c,
|
||||||
|
name: newName.trim(),
|
||||||
|
defaultMaxHp: hp,
|
||||||
|
defaultInitMod: initMod,
|
||||||
|
defaultAc: newDefaultAc !== undefined && newDefaultAc !== '' ? parseInt(newDefaultAc, 10) : null,
|
||||||
|
defaultCurrentHp: nextCurrentHp,
|
||||||
|
stableRegainHours: nextStableRegainHours,
|
||||||
|
isNpc: newIsNpc != null ? newIsNpc : (c.isNpc || false),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await storage.updateDoc(getPath.campaign(campaignId), { players: updatedCharacters });
|
await storage.updateDoc(getPath.campaign(campaignId), { players: updatedCharacters });
|
||||||
@@ -1124,6 +1135,9 @@ function CharacterManager({ campaignId, campaignCharacters, syncCharacters }) {
|
|||||||
{character.defaultCurrentHp != null && character.defaultCurrentHp !== character.defaultMaxHp && (
|
{character.defaultCurrentHp != null && character.defaultCurrentHp !== character.defaultMaxHp && (
|
||||||
<span className="px-1.5 py-0.5 rounded bg-red-950 text-red-300 text-xs font-medium" title="Current HP (carried from last encounter)">Current HP {character.defaultCurrentHp}</span>
|
<span className="px-1.5 py-0.5 rounded bg-red-950 text-red-300 text-xs font-medium" title="Current HP (carried from last encounter)">Current HP {character.defaultCurrentHp}</span>
|
||||||
)}
|
)}
|
||||||
|
{character.stableRegainHours != null && (
|
||||||
|
<span className="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-300 text-xs font-medium border border-emerald-700" title="Stable from last encounter — regains 1 HP after resting">Stable — regains 1 HP after {character.stableRegainHours} hour{character.stableRegainHours > 1 ? 's' : ''}</span>
|
||||||
|
)}
|
||||||
{character.defaultAc != null && (
|
{character.defaultAc != null && (
|
||||||
<span className="px-1.5 py-0.5 rounded bg-sky-900/60 text-sky-200 text-xs font-medium">AC {character.defaultAc}</span>
|
<span className="px-1.5 py-0.5 rounded bg-sky-900/60 text-sky-200 text-xs font-medium">AC {character.defaultAc}</span>
|
||||||
)}
|
)}
|
||||||
@@ -1191,6 +1205,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
const [asNpc, setAsNpc] = useState(false);
|
const [asNpc, setAsNpc] = useState(false);
|
||||||
const combatActive = encounter.isStarted && !encounter.isPaused;
|
const combatActive = encounter.isStarted && !encounter.isPaused;
|
||||||
const [addSectionOpen, setAddSectionOpen] = useState(!combatActive);
|
const [addSectionOpen, setAddSectionOpen] = useState(!combatActive);
|
||||||
|
const [showRerollConfirm, setShowRerollConfirm] = useState(false);
|
||||||
const [editingParticipant, setEditingParticipant] = useState(null);
|
const [editingParticipant, setEditingParticipant] = useState(null);
|
||||||
const [hpChangeValues, setHpChangeValues] = useState({});
|
const [hpChangeValues, setHpChangeValues] = useState({});
|
||||||
const [draggedItemId, setDraggedItemId] = useState(null);
|
const [draggedItemId, setDraggedItemId] = useState(null);
|
||||||
@@ -1392,6 +1407,16 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
setShowDeleteConfirm(true);
|
setShowDeleteConfirm(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const confirmRerollAll = async () => {
|
||||||
|
if (!db) return;
|
||||||
|
try {
|
||||||
|
await shared.rerollAllInitiatives(encounter, buildCtx(encounterPath));
|
||||||
|
} catch (err) {
|
||||||
|
showToast('Failed to reroll initiative.');
|
||||||
|
}
|
||||||
|
setShowRerollConfirm(false);
|
||||||
|
};
|
||||||
|
|
||||||
const confirmDeleteParticipant = async () => {
|
const confirmDeleteParticipant = async () => {
|
||||||
if (!db || !itemToDelete) return;
|
if (!db || !itemToDelete) return;
|
||||||
try {
|
try {
|
||||||
@@ -1440,7 +1465,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
if (isGeneric) {
|
if (isGeneric) {
|
||||||
patch = { currentHp: n, status: n > 0 ? 'conscious' : 'down' };
|
patch = { currentHp: n, status: n > 0 ? 'conscious' : 'down' };
|
||||||
} else {
|
} else {
|
||||||
patch = { currentHp: n, deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
patch = { currentHp: n, deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null };
|
||||||
if (n > 0) { patch.status = 'conscious'; }
|
if (n > 0) { patch.status = 'conscious'; }
|
||||||
else if (p.type === 'monster') { patch.status = 'dead'; patch.isActive = false; }
|
else if (p.type === 'monster') { patch.status = 'dead'; patch.isActive = false; }
|
||||||
else { patch.status = 'dying'; }
|
else { patch.status = 'dying'; }
|
||||||
@@ -1605,28 +1630,45 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
{(() => {
|
{(() => {
|
||||||
const open = addSectionOpen && !combatActive;
|
const open = addSectionOpen && !combatActive;
|
||||||
return (
|
return (
|
||||||
<details open={open} className="mt-2">
|
<div className="mt-2">
|
||||||
<summary
|
<div className="flex flex-wrap justify-between items-center gap-2 mb-2">
|
||||||
onClick={(e) => { if (!combatActive) { e.preventDefault(); setAddSectionOpen(v => !v); } else { e.preventDefault(); } }}
|
<button
|
||||||
className="cursor-pointer text-lg font-medium text-amber-200 font-cinzel tracking-wide flex items-center gap-2 select-none"
|
type="button"
|
||||||
|
onClick={() => setAddSectionOpen(v => !v)}
|
||||||
|
disabled={combatActive}
|
||||||
|
aria-expanded={open}
|
||||||
|
className="text-lg font-medium text-amber-200 font-cinzel tracking-wide flex items-center gap-2 select-none disabled:opacity-60 disabled:cursor-not-allowed"
|
||||||
|
title={open ? 'Hide add form' : 'Show add form'}
|
||||||
>
|
>
|
||||||
{open ? <ChevronDown size={20} /> : <ChevronRight size={20} />}
|
{open ? <ChevronDown size={20} /> : <ChevronRight size={20} />}
|
||||||
Add Participants
|
Add Participants
|
||||||
{combatActive && <span className="text-xs text-stone-400 font-normal ml-2">(pause to add)</span>}
|
{combatActive && <span className="text-xs text-stone-400 font-normal">(pause to add)</span>}
|
||||||
</summary>
|
</button>
|
||||||
{open && (
|
<div className="flex items-center gap-2">
|
||||||
<>
|
|
||||||
<div className="flex justify-end items-center mb-3 mt-2">
|
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
onClick={handleAddAllCampaignCharacters}
|
onClick={handleAddAllCampaignCharacters}
|
||||||
className="px-3 py-1.5 text-xs font-medium text-white bg-violet-700 hover:bg-violet-800 rounded-md transition-colors flex items-center"
|
className="px-3 py-1.5 text-xs font-medium text-white bg-violet-700 hover:bg-violet-800 rounded-md transition-colors flex items-center min-h-[36px]"
|
||||||
disabled={!campaignCharacters || campaignCharacters.length === 0 || combatActive}
|
disabled={!campaignCharacters || campaignCharacters.length === 0 || combatActive}
|
||||||
|
title="Add every campaign character to the encounter, rolling initiative for each"
|
||||||
>
|
>
|
||||||
<Users2 size={16} className="mr-1.5" />
|
<Users2 size={16} className="mr-1.5" />
|
||||||
<Dices size={16} className="mr-1.5" /> Add All (Roll Init)
|
<Dices size={16} className="mr-1.5" /> Add All (Roll Init)
|
||||||
</button>
|
</button>
|
||||||
|
{!combatActive && (participants || []).length > 0 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowRerollConfirm(true)}
|
||||||
|
className="px-3 py-1.5 text-xs font-medium text-white bg-violet-700 hover:bg-violet-800 rounded-md transition-colors flex items-center min-h-[36px]"
|
||||||
|
title="Reroll d20 + init mod for every participant"
|
||||||
|
>
|
||||||
|
<Dices size={16} className="mr-1.5" /> Reroll All Initiative
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
{open && (
|
||||||
|
<>
|
||||||
{/* Warning when combat is active */}
|
{/* Warning when combat is active */}
|
||||||
{encounter.isStarted && !encounter.isPaused && (
|
{encounter.isStarted && !encounter.isPaused && (
|
||||||
<div className="mb-4 p-3 bg-yellow-900 bg-opacity-30 border border-yellow-600 rounded-md flex items-start">
|
<div className="mb-4 p-3 bg-yellow-900 bg-opacity-30 border border-yellow-600 rounded-md flex items-start">
|
||||||
@@ -1806,7 +1848,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
</form>
|
</form>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</details>
|
</div>
|
||||||
);
|
);
|
||||||
})()}
|
})()}
|
||||||
|
|
||||||
@@ -1956,7 +1998,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{hasDeathSaves && participantStatus === 'stable' && (
|
{hasDeathSaves && participantStatus === 'stable' && (
|
||||||
<div className="mt-2 text-xs text-emerald-300/80 italic">Stable — regains 1 HP after 1d4 hours</div>
|
<div className="mt-2 text-xs text-emerald-300/80 italic">Stable — regains 1 HP after {p.stableRegainHours ? `${p.stableRegainHours} hour${p.stableRegainHours > 1 ? 's' : ''}` : '1d4 hours'}</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Death saves - D&D 5e status state machine */}
|
{/* Death saves - D&D 5e status state machine */}
|
||||||
@@ -2184,6 +2226,14 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
title="Delete Participant?"
|
title="Delete Participant?"
|
||||||
message={`Are you sure you want to remove "${itemToDelete?.name}" from this encounter?`}
|
message={`Are you sure you want to remove "${itemToDelete?.name}" from this encounter?`}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<ConfirmationModal
|
||||||
|
isOpen={showRerollConfirm}
|
||||||
|
onClose={() => setShowRerollConfirm(false)}
|
||||||
|
onConfirm={confirmRerollAll}
|
||||||
|
title="Reroll All Initiative?"
|
||||||
|
message={`Reroll initiative for all ${(participants || []).length} participants? Each rolls d20 + their init mod. Current values will be replaced. (Undo is available.)`}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2236,7 +2286,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
|||||||
if (campDoc && Array.isArray(campDoc.players)) {
|
if (campDoc && Array.isArray(campDoc.players)) {
|
||||||
const restored = campDoc.players.map(p => {
|
const restored = campDoc.players.map(p => {
|
||||||
const old = cw.find(c => c.id === p.id);
|
const old = cw.find(c => c.id === p.id);
|
||||||
return old ? { ...p, defaultMaxHp: old.defaultMaxHp, defaultAc: old.defaultAc, defaultCurrentHp: old.defaultCurrentHp } : p;
|
return old ? { ...p, defaultMaxHp: old.defaultMaxHp, defaultAc: old.defaultAc, defaultCurrentHp: old.defaultCurrentHp, stableRegainHours: old.stableRegainHours !== undefined ? old.stableRegainHours : null } : p;
|
||||||
});
|
});
|
||||||
await storage.updateDoc(getPath.campaign(wbId), { players: restored });
|
await storage.updateDoc(getPath.campaign(wbId), { players: restored });
|
||||||
}
|
}
|
||||||
@@ -2457,7 +2507,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
|||||||
onClose={() => setShowEndConfirm(false)}
|
onClose={() => setShowEndConfirm(false)}
|
||||||
onConfirm={confirmEndEncounter}
|
onConfirm={confirmEndEncounter}
|
||||||
title="End Encounter?"
|
title="End Encounter?"
|
||||||
message="Are you sure you want to end this encounter? Initiative order will be reset and it will be removed from the Player Display."
|
message="Are you sure you want to end this encounter? Turn position and round counter will reset (initiative values are kept). It will be removed from the Player Display."
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -3981,6 +4031,60 @@ function DisplayView() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!isGeneric && (p.type === 'character' || p.type === 'npc') && status === 'dying' && (
|
||||||
|
<div data-testid="death-save-tracker" className="flex items-center justify-center gap-3 mt-3">
|
||||||
|
<span className="text-xs md:text-sm text-red-300 font-semibold uppercase tracking-wide">Death Saves</span>
|
||||||
|
<span className="flex items-center gap-1.5">
|
||||||
|
{[1, 2, 3].map(n => (
|
||||||
|
<span
|
||||||
|
key={`ds-${n}`}
|
||||||
|
data-save="success"
|
||||||
|
data-filled={String((p.deathSaveSuccesses || 0) >= n)}
|
||||||
|
className={`w-6 h-6 md:w-7 md:h-7 rounded-full border-2 flex items-center justify-center text-sm md:text-base font-bold ${
|
||||||
|
(p.deathSaveSuccesses || 0) >= n
|
||||||
|
? 'bg-emerald-600 border-emerald-400 text-white'
|
||||||
|
: 'bg-stone-900/60 border-stone-500 text-stone-500'
|
||||||
|
}`}
|
||||||
|
aria-label={
|
||||||
|
(p.deathSaveSuccesses || 0) >= n
|
||||||
|
? `Death save success ${n} of 3`
|
||||||
|
: `Empty success slot ${n} of 3`
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{(p.deathSaveSuccesses || 0) >= n ? '✓' : '·'}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
<span className="flex items-center gap-1.5">
|
||||||
|
{[1, 2, 3].map(n => (
|
||||||
|
<span
|
||||||
|
key={`df-${n}`}
|
||||||
|
data-save="failure"
|
||||||
|
data-filled={String((p.deathSaveFailures || 0) >= n)}
|
||||||
|
className={`w-6 h-6 md:w-7 md:h-7 rounded-full border-2 flex items-center justify-center text-sm md:text-base font-bold ${
|
||||||
|
(p.deathSaveFailures || 0) >= n
|
||||||
|
? 'bg-red-600 border-red-400 text-white'
|
||||||
|
: 'bg-stone-900/60 border-stone-500 text-stone-500'
|
||||||
|
}`}
|
||||||
|
aria-label={
|
||||||
|
(p.deathSaveFailures || 0) >= n
|
||||||
|
? `Death save failure ${n} of 3`
|
||||||
|
: `Empty failure slot ${n} of 3`
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{(p.deathSaveFailures || 0) >= n ? '✕' : '·'}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isGeneric && (p.type === 'character' || p.type === 'npc') && status === 'stable' && (
|
||||||
|
<div className="mt-3 text-center text-base md:text-lg text-emerald-300/90 italic">
|
||||||
|
Stable — regains 1 HP after {p.stableRegainHours ? `${p.stableRegainHours} hour${p.stableRegainHours > 1 ? 's' : ''}` : '1d4 hours'}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{p.conditions?.length > 0 && (
|
{p.conditions?.length > 0 && (
|
||||||
<div className="flex flex-wrap gap-1 mt-2">
|
<div className="flex flex-wrap gap-1 mt-2">
|
||||||
{p.conditions.map(cId => {
|
{p.conditions.map(cId => {
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// Player display death-save tracker: dying/stable characters show save pips.
|
||||||
|
// Admin already has pips; display showed only "(Dying)" label — players blind.
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
import { render, waitFor, screen } 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 = 'artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/c1/encounters/e1';
|
||||||
|
const activeDisplayPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status';
|
||||||
|
|
||||||
|
function seed(participants, ruleset = '5e') {
|
||||||
|
MOCK_DB.set(campaignPath, { name: 'Camp', playerDisplayBackgroundUrl: '' });
|
||||||
|
MOCK_DB.set(encounterPath, { name: 'Enc', participants, ruleset, isStarted: true, round: 2, currentTurnParticipantId: null });
|
||||||
|
MOCK_DB.set(activeDisplayPath, { activeCampaignId: 'c1', activeEncounterId: 'e1', hidePlayerHp: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
function char(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: 'p1',
|
||||||
|
name: 'Rogue',
|
||||||
|
type: 'character',
|
||||||
|
initiative: 18,
|
||||||
|
maxHp: 40,
|
||||||
|
currentHp: 0,
|
||||||
|
isActive: true,
|
||||||
|
status: 'dying',
|
||||||
|
deathSaveSuccesses: 0,
|
||||||
|
deathSaveFailures: 0,
|
||||||
|
conditions: ['unconscious'],
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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 death saves', () => {
|
||||||
|
test('dying character shows success and failure pips with counts', async () => {
|
||||||
|
seed([char({ deathSaveSuccesses: 1, deathSaveFailures: 2 })]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Rogue');
|
||||||
|
|
||||||
|
const row = screen.getByTestId('death-save-tracker');
|
||||||
|
expect(row).toBeInTheDocument();
|
||||||
|
expect(row.querySelectorAll('[data-save="success"]').length).toBe(3);
|
||||||
|
expect(row.querySelectorAll('[data-save="failure"]').length).toBe(3);
|
||||||
|
expect(row.querySelectorAll('[data-save="success"][data-filled="true"]').length).toBe(1);
|
||||||
|
expect(row.querySelectorAll('[data-save="failure"][data-filled="true"]').length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stable character hides pips, shows stable/regains note', async () => {
|
||||||
|
seed([char({ status: 'stable', deathSaveSuccesses: 3 })]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Rogue');
|
||||||
|
|
||||||
|
expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Stable — regains 1 HP after 1d4 hours/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('conscious character shows no pips', async () => {
|
||||||
|
seed([char({ status: 'conscious', currentHp: 10, conditions: [] })]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Rogue');
|
||||||
|
expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('generic ruleset: no pips even at zero HP', async () => {
|
||||||
|
seed([char({ status: 'down' })], 'generic');
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Rogue');
|
||||||
|
expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// Reroll-all-initiative: button in Add Participants header row, confirm modal,
|
||||||
|
// hidden during active combat. Toggle button persists when section collapsed.
|
||||||
|
|
||||||
|
import { screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, selectEncounterByName, addMonsterViaUI, MOCK_DB, startCombatViaUI } from './testHelpers';
|
||||||
|
|
||||||
|
const encPath = (cid, eid) => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`;
|
||||||
|
|
||||||
|
async function setupTwoMonsters(camp = 'RerollAllCamp', enc = 'RerollEnc') {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI(camp);
|
||||||
|
await selectCampaignByName(camp);
|
||||||
|
const eid = await createEncounterViaUI(enc);
|
||||||
|
await selectEncounterByName(enc);
|
||||||
|
await addMonsterViaUI('Alpha', 20, 3);
|
||||||
|
await addMonsterViaUI('Beta', 20, 5);
|
||||||
|
return { cid, eid };
|
||||||
|
}
|
||||||
|
|
||||||
|
const partDoc = (cid, eid) => MOCK_DB.get(encPath(cid, eid));
|
||||||
|
|
||||||
|
describe('reroll all initiative', () => {
|
||||||
|
test('button visible pre-combat; confirm rerolls every participant once', async () => {
|
||||||
|
const { cid, eid } = await setupTwoMonsters();
|
||||||
|
|
||||||
|
const btn = await screen.findByRole('button', { name: 'Reroll All Initiative' });
|
||||||
|
expect(btn).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(btn);
|
||||||
|
expect(await screen.findByText(/Reroll initiative for all/i)).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Confirm/i }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const doc = partDoc(cid, eid);
|
||||||
|
expect(doc.participants).toHaveLength(2);
|
||||||
|
for (const p of doc.participants) {
|
||||||
|
const mod = p.name === 'Alpha' ? 3 : 5;
|
||||||
|
expect(p.initiative).toBeGreaterThanOrEqual(mod + 1);
|
||||||
|
expect(p.initiative).toBeLessThanOrEqual(mod + 20);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Reroll initiative for all/i)).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cancel leaves initiatives untouched', async () => {
|
||||||
|
const { cid, eid } = await setupTwoMonsters('RerollCancelCamp', 'RerollCancelEnc');
|
||||||
|
const before = partDoc(cid, eid).participants.map(p => p.initiative);
|
||||||
|
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: 'Reroll All Initiative' }));
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /^Cancel$/ }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Reroll initiative for all/i)).not.toBeInTheDocument());
|
||||||
|
expect(partDoc(cid, eid).participants.map(p => p.initiative)).toEqual(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hidden during active combat; toggle button still present', async () => {
|
||||||
|
await setupTwoMonsters('RerollCombatCamp', 'RerollCombatEnc');
|
||||||
|
await startCombatViaUI();
|
||||||
|
|
||||||
|
expect(screen.queryByRole('button', { name: 'Reroll All Initiative' })).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /Add Participants/i })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Add Participants toggle button persists when section collapsed', async () => {
|
||||||
|
await setupTwoMonsters('RerollToggleCamp', 'RerollToggleEnc');
|
||||||
|
const toggle = await screen.findByRole('button', { name: /Add Participants/i });
|
||||||
|
expect(toggle).toHaveAttribute('aria-expanded', 'true');
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
// form furled, toggle + Add All still visible
|
||||||
|
expect(screen.queryByPlaceholderText('e.g., Dire Wolf')).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /Add Participants/i })).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /Add All/i })).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Add Participants/i }));
|
||||||
|
expect(screen.getByPlaceholderText('e.g., Dire Wolf')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// Roster stable state: badge on character card, cleared when Current HP raised.
|
||||||
|
|
||||||
|
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName, MOCK_DB } from './testHelpers';
|
||||||
|
|
||||||
|
const campPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`;
|
||||||
|
|
||||||
|
async function setupWithStableChar() {
|
||||||
|
await renderApp();
|
||||||
|
const id = await createCampaignViaUI('StableCamp');
|
||||||
|
await selectCampaignByName('StableCamp');
|
||||||
|
|
||||||
|
// character form
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Fallen Hero' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText('Fallen Hero');
|
||||||
|
|
||||||
|
// writeback would have set these; seed directly
|
||||||
|
const doc = MOCK_DB.get(campPath(id));
|
||||||
|
doc.players = doc.players.map(p => p.name === 'Fallen Hero'
|
||||||
|
? { ...p, defaultCurrentHp: 0, stableRegainHours: 3 }
|
||||||
|
: p);
|
||||||
|
MOCK_DB.set(campPath(id), doc);
|
||||||
|
await screen.findByText(/Stable — regains 1 HP after 3 hours/);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('roster stable state', () => {
|
||||||
|
test('character card shows stable badge with hours', async () => {
|
||||||
|
await setupWithStableChar();
|
||||||
|
expect(screen.getByText(/Stable — regains 1 HP after 3 hours/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('raising Current HP in editor clears stable state', async () => {
|
||||||
|
const id = await setupWithStableChar();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Edit character' }));
|
||||||
|
const curHpInput = await screen.findByTitle('Default Current HP');
|
||||||
|
expect(curHpInput).toHaveValue(0);
|
||||||
|
fireEvent.change(curHpInput, { target: { value: '10' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save character' }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const doc = MOCK_DB.get(campPath(id));
|
||||||
|
const hero = doc.players.find(p => p.name === 'Fallen Hero');
|
||||||
|
expect(hero.defaultCurrentHp).toBe(10);
|
||||||
|
expect(hero.stableRegainHours).toBeNull();
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Stable — regains/)).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -9,7 +9,8 @@ export const fastWaitFor = (cb, opts) => waitFor(cb, { interval: 5, timeout: 100
|
|||||||
|
|
||||||
// Scoped container: the "Add Participants" section (avoids label clashes with CharacterManager).
|
// Scoped container: the "Add Participants" section (avoids label clashes with CharacterManager).
|
||||||
export function getParticipantForm() {
|
export function getParticipantForm() {
|
||||||
const heading = screen.getByText('Add Participants');
|
const heading = screen.getByText((content, element) =>
|
||||||
|
element.tagName === 'BUTTON' && content.trim() === 'Add Participants');
|
||||||
// closest section/div wrapping the form
|
// closest section/div wrapping the form
|
||||||
let node = heading;
|
let node = heading;
|
||||||
for (let i = 0; i < 6; i++) {
|
for (let i = 0; i < 6; i++) {
|
||||||
|
|||||||
Reference in new issue
Block a user