diff --git a/.agents/skills/ttrpg-encounter-builder/SKILL.md b/.agents/skills/ttrpg-encounter-builder/SKILL.md index 89ff02c..bb123cb 100644 --- a/.agents/skills/ttrpg-encounter-builder/SKILL.md +++ b/.agents/skills/ttrpg-encounter-builder/SKILL.md @@ -53,6 +53,47 @@ Returns JSON array of campaign docs = server mode confirmed. HTML (SPA shell) = firebase mode OR backend not mounted. Either way, this skill won't work — tell the user. +## Spec files + +Spec files are EPHEMERAL. /tmp is fine — they get cleaned, that's expected. + +- Source of truth for stats = the user's message at ask-time. Spec JSON is a + transit format, not an archive. +- If a spec is gone, rebuild it from the original message. Never reconstruct + from memory. +- **The durable record is the server DB.** Encounter docs are self-describing: + participant name, type, hpFormula, maxHp, ac, initiative, status all stored. + "Fix the thing from 2 weeks ago" → query `campaigns/{cid}/encounters`, read + the docs, reconstruct context from live data. `logs/{id}` entries add the + action history. +- Therefore: store enough in the DB to reconstruct later. hpFormula always + kept on monster/npc participants; never strip it. Never write campaign or + encounter data into the tracker repo. + +## Spec vetting (before build) + +Validate the spec before writing anything. Reject, don't guess: + +- **Monster/npc with neither `maxHp` nor `hpFormula`** → hard error. A silent + default of 10 HP has caused real damage; never fall back to defaults. + Escape hatch: `--allow-defaults` flag permits it with a loud warning. +- **Missing `ac`** → warning (build continues). +- **Missing `initMod` and `initiative`** → warning; initMod defaults 0. +- **`type: "character"` in spec** → see PC rules below. +- **Duplicate participant names within one encounter** → allowed but warn + (numbered names preferred for display clarity). + +## PC rules (hard) + +- **Allowed:** add a PC to the campaign roster (`players[]`), or add a PC + from the roster into an encounter, copying stats verbatim from the roster. +- **Forbidden:** creating a `character` participant with invented stats, or + editing any existing character-type participant's HP, AC, formula, + conditions, or status. Player stat fixes happen in the UI or from the + user's explicit values — tooling never "repairs" PCs. +- A build spec containing `type: "character"` without `originalCharacterId` + resolving to a roster entry → hard error. + ## Data model (read this before writing) Three nested entities, all opaque JSON docs in a path-keyed KV store: diff --git a/.agents/skills/ttrpg-encounter-builder/scripts/build-encounters.js b/.agents/skills/ttrpg-encounter-builder/scripts/build-encounters.js index 66c1ddb..654f4d7 100644 --- a/.agents/skills/ttrpg-encounter-builder/scripts/build-encounters.js +++ b/.agents/skills/ttrpg-encounter-builder/scripts/build-encounters.js @@ -21,11 +21,23 @@ // initiative: optional manual override. If omitted, rolled d20 + initMod. // initMod default 0. maxHp default 10. // +// VALIDATION (hard rules): +// - monster/npc with neither maxHp nor hpFormula = FATAL. Defaults caused real +// damage once; never silently assume 10 HP. --allow-defaults to override. +// - character type in spec = FATAL unless --allow-pc-add, which requires +// originalCharacterId + copies stats from the campaign roster verbatim. +// - missing ac or initMod = warning, build continues. +// // Output: written encounter ids + rolled initiatives. Exit 0 on success. 'use strict'; const crypto = require('crypto'); +const argv = process.argv.slice(2); +const FLAGS = new Set(argv.filter(a => a.startsWith('--'))); +const ARGS = argv.filter(a => !a.startsWith('--')); +const warn = (msg) => console.error(`WARN: ${msg}`); + const genId = () => (typeof crypto !== 'undefined' && crypto.randomUUID) ? crypto.randomUUID() @@ -84,10 +96,41 @@ async function findCampaignId(host, name) { return matches[0].id; } +// Vetting. Returns {ok, errors[], warnings[]}. Never silent about missing data. +function vetSpec(encounters) { + const errors = []; + const warnings = []; + encounters.forEach((enc, ei) => { + const seen = new Set(); + for (const p of enc.participants || []) { + const where = `encounter "${enc.name}", participant "${p.name}"`; + const type = p.type || 'monster'; + const hasHp = p.maxHp !== undefined && p.maxHp !== null; + const hasFormula = typeof p.hpFormula === 'string' && p.hpFormula.trim(); + if (type === 'character') { + errors.push(`${where}: character type not allowed in build spec (PC stats come from roster, via UI or explicit user values)`); + continue; + } + if (!hasHp && !hasFormula) { + if (FLAGS.has('--allow-defaults')) { + warnings.push(`${where}: no maxHp/hpFormula — defaulting to 10 (--allow-defaults)`); + } else { + errors.push(`${where}: no maxHp and no hpFormula. Refusing to guess HP. Add the stat from the source or pass --allow-defaults.`); + } + } + if (p.ac === undefined || p.ac === null) warnings.push(`${where}: no ac`); + if (p.initMod === undefined && p.initiative === undefined) warnings.push(`${where}: no initMod/initiative (defaulting mod 0)`); + if (seen.has(p.name)) warnings.push(`${where}: duplicate name in encounter (number them for display clarity)`); + seen.add(p.name); + } + }); + return { ok: errors.length === 0, errors, warnings }; +} + async function main() { - const [host, campaignName, specArg] = process.argv.slice(2); + const [host, campaignName, specArg] = ARGS; if (!host || !campaignName || !specArg) { - console.error('Usage: node build-encounters.js '); + console.error('Usage: node build-encounters.js [--allow-defaults]'); process.exit(1); } const specRaw = specArg === '-' @@ -96,6 +139,14 @@ async function main() { const encounters = JSON.parse(specRaw); if (!Array.isArray(encounters)) throw new Error('spec must be a JSON array of encounters'); + const vet = vetSpec(encounters); + vet.warnings.forEach(warn); + if (!vet.ok) { + console.error('SPEC REJECTED:'); + vet.errors.forEach(e => console.error(` - ${e}`)); + process.exit(3); + } + const cid = await findCampaignId(host, campaignName); console.log(`campaign: "${campaignName}" -> ${cid}`); diff --git a/TODO.md b/TODO.md index e67569c..a9be139 100644 --- a/TODO.md +++ b/TODO.md @@ -5,6 +5,39 @@ Backlog of bugs + long-term items. Milestones live in REWORK_PLAN.md. ## Open + + + +merge from one encoutner into another? option roll init for merged or use init + + + +x init tracker - turned for 10 rounds... and maybe other stuff like spiritual weapon? +x also, conditiojns - no turned + +x make cafinete button be yes caf no caf not caf/moon + +x init reroll on edit npcdoes not work oh thats HP...... + +x player intexrface for death savers + + + +tool. monsters know what they are doing + + +on tablet, input a) doesnt work on last char in list amd b) pops up stupid CC/pw input bar in middle of screen +init tracker tablet blacks every time edit hp snad submit, does not do it not in FS butdoes cause the tablet bottom bar to come up +and the damn UI kept blacking out on tablet. thats new. and the damn keyboar inpt still not sane. +- cant find a fix, dont use full screen on tablet + + + + + + + + x caff doent work on fron tpage or big tablet x max/caff need to float or at least be availabe in combagt popout diff --git a/docker/restart-bee.sh b/docker/restart-bee.sh new file mode 100755 index 0000000..bc14f93 --- /dev/null +++ b/docker/restart-bee.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +export DOCKER_CONTEXT=bee +exec "$(dirname "$0")/restart.sh" diff --git a/shared/tests/turn.effects.test.js b/shared/tests/turn.effects.test.js new file mode 100644 index 0000000..4a4bcf4 --- /dev/null +++ b/shared/tests/turn.effects.test.js @@ -0,0 +1,115 @@ +const shared = require('@ttrpg/shared'); +const { mockCtx, readyEnc, undoLast } = require('./_helpers'); + +const { + makeEffect, addEffect, updateEffect, removeEffect, + nextTurn, applyHpChange, updateParticipant, +} = shared; + +function effect(overrides = {}) { + return makeEffect({ + name: 'Turned', presetId: 'turned', scope: 'participant', + targetParticipantId: 'p2', remainingRounds: 10, + expiresOnDamage: true, playerDisplay: 'prominent', + ...overrides, + }); +} + +function runningEnc(overrides = {}) { + return { + ...readyEnc(), + isStarted: true, + round: 2, + currentTurnParticipantId: 'p1', + turnOrderIds: ['p1', 'p2'], + effects: [], + ...overrides, + }; +} + +describe('tracked effects', () => { + test('makeEffect normalizes generic effect fields', () => { + const e = effect({ id: 'fx1', remainingRounds: 3.9 }); + expect(e).toEqual(expect.objectContaining({ + id: 'fx1', name: 'Turned', presetId: 'turned', scope: 'participant', + targetParticipantId: 'p2', remainingRounds: 3, + expiresOnDamage: true, playerDisplay: 'prominent', + })); + }); + + test('add, update, remove effect are persisted and undoable', async () => { + const { ctx } = mockCtx(); + let enc = readyEnc({ participants: readyEnc().participants }); + enc.effects = []; + const fx = effect({ id: 'fx1' }); + + enc = await addEffect(enc, fx, ctx); + expect(enc.effects).toEqual([fx]); + enc = await updateEffect(enc, 'fx1', { remainingRounds: 6 }, ctx); + expect(enc.effects[0].remainingRounds).toBe(6); + const afterRemove = await removeEffect(enc, 'fx1', ctx); + expect(afterRemove.effects).toEqual([]); + const undone = await undoLast(ctx, afterRemove); + expect(undone.effects[0]).toEqual(expect.objectContaining({ id: 'fx1', remainingRounds: 6 })); + }); + + test('round wrap decrements timed effects and removes expired effects', async () => { + const { ctx } = mockCtx(); + const enc = runningEnc({ + currentTurnParticipantId: 'p2', + effects: [effect({ id: 'keep', remainingRounds: 2 }), effect({ id: 'expire', remainingRounds: 1 })], + }); + + const out = await nextTurn(enc, ctx); + expect(out.round).toBe(3); + expect(out.effects).toHaveLength(1); + expect(out.effects[0]).toEqual(expect.objectContaining({ id: 'keep', remainingRounds: 1 })); + + const undone = await undoLast(ctx, out); + expect(undone.round).toBe(2); + expect(undone.effects.map(e => [e.id, e.remainingRounds])).toEqual([['keep', 2], ['expire', 1]]); + }); + + test('same-round turn advance does not decrement effects', async () => { + const { ctx } = mockCtx(); + const enc = runningEnc({ effects: [effect({ id: 'fx', remainingRounds: 10 })] }); + const out = await nextTurn(enc, ctx); + expect(out.round).toBe(2); + expect(out.effects[0].remainingRounds).toBe(10); + }); + + test('damage expires targeted effect even when temp HP absorbs all damage; undo restores it', async () => { + const { ctx } = mockCtx(); + const participants = readyEnc().participants.map(p => p.id === 'p2' ? { ...p, tempHp: 5 } : p); + const enc = runningEnc({ participants, effects: [effect({ id: 'fx' })] }); + + const out = await applyHpChange(enc, 'p2', 'damage', 2, ctx); + expect(out.participants.find(p => p.id === 'p2').currentHp).toBe(10); + expect(out.effects).toEqual([]); + + const undone = await undoLast(ctx, out); + expect(undone.effects).toHaveLength(1); + expect(undone.effects[0].id).toBe('fx'); + }); + + test('direct HP reduction expires targeted effect; increase does not', async () => { + const { ctx } = mockCtx(); + let enc = runningEnc({ effects: [effect({ id: 'fx' })] }); + enc = await updateParticipant(enc, 'p2', { currentHp: 8 }, ctx); + expect(enc.effects).toEqual([]); + + enc = { ...enc, effects: [effect({ id: 'fx2' })] }; + enc = await updateParticipant(enc, 'p2', { currentHp: 9 }, ctx); + expect(enc.effects).toHaveLength(1); + }); + + test('damage leaves encounter-wide and non-expiring effects active', async () => { + const { ctx } = mockCtx(); + const enc = runningEnc({ effects: [ + effect({ id: 'weapon', presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', targetParticipantId: null, expiresOnDamage: false }), + effect({ id: 'bless', name: 'Bless', expiresOnDamage: false }), + ] }); + const out = await applyHpChange(enc, 'p2', 'damage', 1, ctx); + expect(out.effects.map(e => e.id)).toEqual(['weapon', 'bless']); + }); +}); diff --git a/shared/tests/turn.generic.test.js b/shared/tests/turn.generic.test.js index e4f537e..1901204 100644 --- a/shared/tests/turn.generic.test.js +++ b/shared/tests/turn.generic.test.js @@ -1,9 +1,9 @@ // Generic (non-5e) ruleset: no death saves, negative HP allowed, down status. const shared = require('@ttrpg/shared'); -const { mockCtx } = require('./_helpers'); +const { mockCtx, undoLast } = require('./_helpers'); const { buildCharacterParticipant, buildMonsterParticipant, - startEncounter, applyHpChange, deathSave, markDead, reviveParticipant, + startEncounter, applyHpChange, deathSave, markDead, reviveParticipant, healFullParticipant, } = shared; function char(id, hp = 100) { @@ -121,25 +121,48 @@ describe('generic ruleset', () => { expect(p.isActive).toBe(true); }); - test('markDead sets status dead (character, stays active)', async () => { + test('markDead kills and disables character', async () => { const { ctx } = mockCtx(); - let e = enc([char('a', 10)]); + let e = enc([{ ...char('a', 10), tempHp: 4, deathSaveSuccesses: 2, deathSaveFailures: 1 }]); e = await startEncounter(e, ctx); - e = await applyHpChange(e, 'a', 'damage', 10, ctx); // down const newEnc = await markDead(e, 'a', ctx); const p = newEnc.participants.find(x => x.id === 'a'); - expect(p.status).toBe('dead'); - expect(p.isActive).toBe(true); + expect(p).toMatchObject({ + currentHp: 0, tempHp: 0, status: 'dead', isActive: false, + deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null, + }); + + const undone = await undoLast(ctx, newEnc); + expect(undone.participants.find(x => x.id === 'a')).toMatchObject({ + currentHp: 10, tempHp: 4, status: 'conscious', isActive: true, + deathSaveSuccesses: 2, deathSaveFailures: 1, + }); }); - test('markDead on monster = dead + inactive', async () => { + test('healFullParticipant restores dead participant to full, active, conscious; undo restores death', async () => { + const { ctx } = mockCtx(); + let e = enc([{ ...char('a', 20), currentHp: 0, status: 'dead', isActive: false, deathSaveSuccesses: 2, deathSaveFailures: 1, conditions: ['unconscious'], stableRegainHours: 3 }]); + const healed = await healFullParticipant(e, 'a', ctx); + expect(healed.participants[0]).toMatchObject({ + currentHp: 20, status: 'conscious', isActive: true, + deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null, + }); + expect(healed.participants[0].conditions).not.toContain('unconscious'); + + const undone = await undoLast(ctx, healed); + expect(undone.participants[0]).toMatchObject({ currentHp: 0, status: 'dead', isActive: false, stableRegainHours: 3 }); + expect(undone.participants[0].conditions).toContain('unconscious'); + }); + + test('markDead on monster = 0 HP + dead + inactive', async () => { const { ctx } = mockCtx(); let e = enc([mon('m', 10)]); e = await startEncounter(e, ctx); - e = await applyHpChange(e, 'm', 'damage', 5, ctx); // down (5hp) + e = await applyHpChange(e, 'm', 'damage', 5, ctx); // 5 HP remain const newEnc = await markDead(e, e.participants[0].id, ctx); const p = newEnc.participants[0]; expect(p.status).toBe('dead'); + expect(p.currentHp).toBe(0); expect(p.isActive).toBe(false); }); diff --git a/shared/tests/turn.rerollall.test.js b/shared/tests/turn.rerollall.test.js new file mode 100644 index 0000000..0d33d8b --- /dev/null +++ b/shared/tests/turn.rerollall.test.js @@ -0,0 +1,77 @@ +'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); + + 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); + }); +}); diff --git a/shared/tests/turn.stablehours.test.js b/shared/tests/turn.stablehours.test.js new file mode 100644 index 0000000..0787b73 --- /dev/null +++ b/shared/tests/turn.stablehours.test.js @@ -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); + }); +}); diff --git a/shared/tests/turn.writeback.test.js b/shared/tests/turn.writeback.test.js index 542796d..abe7d7d 100644 --- a/shared/tests/turn.writeback.test.js +++ b/shared/tests/turn.writeback.test.js @@ -93,6 +93,48 @@ describe('character writeback on endEncounter', () => { expect(cleric.defaultCurrentHp).toBe(22); }); + test('one-time ctx override enables writeback without persistent campaign setting', async () => { + const storage = makeMockStorage(); + storage._docs.set('campaigns/camp1', { + id: 'camp1', name: 'Camp', syncCharacters: false, players: [ + { id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 }, + ], + }); + const enc = makeEncounter({ participants: [ + { id: 'p1', name: 'Fighter', type: 'character', originalCharacterId: 'char1', initiative: 15, maxHp: 28, currentHp: 11, ac: 19 }, + ] }); + const ctx = { + storage, + encounterPath: 'campaigns/camp1/encounters/enc1', + logPath: 'logs/log1', + syncCharacters: true, + }; + + await endEncounter(enc, ctx); + + const campWrite = storage._writes.find(w => w.path === 'campaigns/camp1'); + expect(campWrite).toBeDefined(); + expect(campWrite.patch.players[0]).toMatchObject({ defaultMaxHp: 28, defaultCurrentHp: 11, defaultAc: 19 }); + expect(storage._docs.get('campaigns/camp1').syncCharacters).toBe(false); + }); + + test('one-time ctx override disables writeback despite persistent campaign setting', async () => { + const storage = makeMockStorage(); + storage._docs.set('campaigns/camp1', { + id: 'camp1', name: 'Camp', syncCharacters: true, players: [ + { id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 }, + ], + }); + await endEncounter(makeEncounter(), { + storage, + encounterPath: 'campaigns/camp1/encounters/enc1', + logPath: 'logs/log1', + syncCharacters: false, + }); + + expect(storage._writes.find(w => w.path === 'campaigns/camp1')).toBeUndefined(); + }); + test('writeback skips monsters (no originalCharacterId)', async () => { const storage = makeMockStorage(); const players = [{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17 }]; @@ -204,3 +246,71 @@ describe('character writeback on endEncounter', () => { 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(); + }); +}); diff --git a/shared/turn.js b/shared/turn.js index 1bf119f..5d6ef14 100644 --- a/shared/turn.js +++ b/shared/turn.js @@ -27,6 +27,7 @@ const generateId = () => : `id_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`; 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. // 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))] }, }; } + 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': { const p = u.participant; const turnState = {}; @@ -222,9 +233,11 @@ function expandUndo(entry, currentEnc) { } case 'damage': case 'heal': + case 'hp_change': case 'death_save': case 'stabilize': case 'revive': + case 'heal_full': case 'mark_dead': case 'deactivate_dead_monster': { // Full death-state restore: currentHp, status, death-save counters, @@ -237,17 +250,34 @@ function expandUndo(entry, currentEnc) { const restoreFields = (vals) => { const out = {}; if (vals.currentHp !== undefined) out.currentHp = vals.currentHp; + if (vals.tempHp !== undefined) out.tempHp = vals.tempHp; if (vals.status !== undefined) out.status = vals.status; if (vals.deathSaveSuccesses !== undefined) out.deathSaveSuccesses = vals.deathSaveSuccesses; 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.conditions !== undefined) out.conditions = vals.conditions; return out; }; return { encounterPath: encPath, - updates: { participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(oldVals) } : p) }, - redo: { participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(newVals) } : p) }, + updates: { + participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(oldVals) } : p), + ...(u.oldEffects ? { effects: u.oldEffects } : {}), + }, + redo: { + participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(newVals) } : p), + ...(u.newEffects ? { effects: u.newEffects } : {}), + }, + }; + } + case 'add_effect': + case 'update_effect': + case 'remove_effect': { + return { + encounterPath: encPath, + updates: { effects: u.oldEffects || [] }, + redo: { effects: u.newEffects || [] }, }; } case 'add_condition': @@ -305,22 +335,22 @@ function expandUndo(entry, currentEnc) { const redoOrdered = u.newTurnOrderIds.map(id => redoPool.get(id)).filter(Boolean); return { encounterPath: encPath, - updates: { participants: undoOrdered, turnOrderIds: u.oldTurnOrderIds }, - redo: { participants: redoOrdered, turnOrderIds: u.newTurnOrderIds }, + updates: { participants: undoOrdered, turnOrderIds: u.oldTurnOrderIds, ...(u.oldEffects ? { effects: u.oldEffects } : {}) }, + redo: { participants: redoOrdered, turnOrderIds: u.newTurnOrderIds, ...(u.newEffects ? { effects: u.newEffects } : {}) }, }; } return { encounterPath: encPath, - updates: { participants: applyFields(oldVals) }, - redo: { participants: applyFields(newVals), ...(u.newTurnOrderIds ? { turnOrderIds: u.newTurnOrderIds } : {}) }, + updates: { participants: applyFields(oldVals), ...(u.oldEffects ? { effects: u.oldEffects } : {}) }, + redo: { participants: applyFields(newVals), ...(u.newTurnOrderIds ? { turnOrderIds: u.newTurnOrderIds } : {}), ...(u.newEffects ? { effects: u.newEffects } : {}) }, }; } case 'next_turn': case 'auto_end': { return { encounterPath: encPath, - updates: { currentTurnParticipantId: u.currentTurnParticipantId, round: u.round, ...(u.turnOrderIds ? { turnOrderIds: u.turnOrderIds } : {}) }, - redo: { currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [] }, + updates: { currentTurnParticipantId: u.currentTurnParticipantId, round: u.round, ...(u.turnOrderIds ? { turnOrderIds: u.turnOrderIds } : {}), ...(u.oldEffects ? { effects: u.oldEffects } : {}) }, + redo: { currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [], ...(u.newEffects ? { effects: u.newEffects } : {}) }, }; } case 'start_encounter': { @@ -346,6 +376,41 @@ function expandUndo(entry, currentEnc) { // Participant factories (pure — no write) // ---------------------------------------------------------------------------- +function makeEffect(opts = {}) { + const rounds = Number(opts.remainingRounds); + return { + id: opts.id || generateId(), + presetId: opts.presetId || 'custom', + name: String(opts.name || 'Effect').trim() || 'Effect', + scope: opts.scope === 'encounter' ? 'encounter' : 'participant', + targetParticipantId: opts.scope === 'encounter' ? null : (opts.targetParticipantId || null), + ownerParticipantId: opts.ownerParticipantId || null, + remainingRounds: Number.isFinite(rounds) ? Math.max(1, Math.floor(rounds)) : 1, + expiresOnDamage: !!opts.expiresOnDamage, + playerDisplay: ['hidden', 'compact', 'prominent'].includes(opts.playerDisplay) ? opts.playerDisplay : 'compact', + notes: String(opts.notes || '').trim(), + createdRound: Number.isFinite(Number(opts.createdRound)) ? Number(opts.createdRound) : 0, + }; +} + +function tickRoundEffects(effects) { + return (effects || []) + .map(effect => ({ ...effect, remainingRounds: Math.max(0, (effect.remainingRounds || 0) - 1) })) + .filter(effect => effect.remainingRounds > 0); +} + +function expireDamageEffects(effects, participantId) { + return (effects || []).filter(effect => !( + effect.scope === 'participant' && + effect.targetParticipantId === participantId && + effect.expiresOnDamage + )); +} + +function effectsChanged(before, after) { + return JSON.stringify(before || []) !== JSON.stringify(after || []); +} + function makeParticipant(opts) { return { id: opts.id || generateId(), @@ -353,6 +418,7 @@ function makeParticipant(opts) { type: opts.type, originalCharacterId: opts.originalCharacterId || null, initiative: opts.initiative, + initMod: opts.initMod !== undefined ? opts.initMod : null, maxHp: opts.maxHp, currentHp: opts.currentHp, conditions: opts.conditions || [], @@ -360,26 +426,32 @@ function makeParticipant(opts) { status: opts.status || (opts.currentHp === 0 ? 'dying' : 'conscious'), deathSaveSuccesses: opts.deathSaveSuccesses || 0, deathSaveFailures: opts.deathSaveFailures || 0, + stableRegainHours: opts.stableRegainHours !== undefined ? opts.stableRegainHours : null, hpFormula: opts.hpFormula || null, ac: opts.ac !== undefined ? opts.ac : null, tempHp: opts.tempHp !== undefined ? opts.tempHp : 0, }; } -function buildCharacterParticipant(character) { - const initiativeRoll = rollD20(); +function buildCharacterParticipant(character, initiativeRoll = rollD20()) { const modifier = character.defaultInitMod || 0; const finalInitiative = initiativeRoll + modifier; const maxHp = character.defaultMaxHp || DEFAULT_MAX_HP; 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 { participant: makeParticipant({ name: character.name, type: character.isNpc ? 'npc' : 'character', originalCharacterId: character.id, initiative: finalInitiative, + initMod: modifier, maxHp, currentHp, + status: isStable ? 'stable' : undefined, + stableRegainHours: isStable ? character.stableRegainHours : null, + conditions: isStable ? ['unconscious'] : [], ac: character.defaultAc !== undefined ? character.defaultAc : null, }), roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative }, @@ -407,6 +479,7 @@ function buildMonsterParticipant({ name, maxHp, initMod, asNpc, hpFormula, ac }) name, type: asNpc ? 'npc' : 'monster', initiative: finalInitiative, + initMod: modifier, maxHp: hp, currentHp: hp, hpFormula: hpFormula || null, @@ -480,13 +553,25 @@ async function nextTurn(encounter, ctx) { if (!nextId) throw new Error('Could not determine next participant.'); if (wrapped) nextRound += 1; const nextParticipant = encounter.participants.find(p => p.id === nextId); - const patch = { currentTurnParticipantId: nextParticipant.id, round: nextRound, turnOrderIds: encounter.turnOrderIds }; + const oldEffects = [...(encounter.effects || [])]; + const newEffects = wrapped ? tickRoundEffects(oldEffects) : oldEffects; + const patch = { + currentTurnParticipantId: nextParticipant.id, + round: nextRound, + turnOrderIds: encounter.turnOrderIds, + ...(wrapped && effectsChanged(oldEffects, newEffects) ? { effects: newEffects } : {}), + }; const log = { type: 'next_turn', participantId: nextParticipant.id, participantName: nextParticipant.name, message: `${nextParticipant.name}'s turn (Round ${nextRound})`, delta: { wrapped, prevRound: encounter.round }, - undo: { currentTurnParticipantId: encounter.currentTurnParticipantId, round: encounter.round, turnOrderIds: [...encounter.turnOrderIds] }, + undo: { + currentTurnParticipantId: encounter.currentTurnParticipantId, + round: encounter.round, + turnOrderIds: [...encounter.turnOrderIds], + ...(wrapped ? { oldEffects, newEffects } : {}), + }, }; return commit(encounter, patch, log, ctx); } @@ -551,29 +636,35 @@ async function updateParticipant(encounter, participantId, updatedData, ctx) { let patch; const oldValues = {}; for (const k of Object.keys(updatedData)) oldValues[k] = target[k]; + const oldEffects = [...(encounter.effects || [])]; + const hpReduced = updatedData.currentHp !== undefined && Number(updatedData.currentHp) < Number(target.currentHp); + const newEffects = hpReduced ? expireDamageEffects(oldEffects, participantId) : oldEffects; + const effectChanged = effectsChanged(oldEffects, newEffects); + const effectPatch = effectChanged ? { effects: newEffects } : {}; + const effectUndo = effectChanged ? { oldEffects, newEffects } : {}; if (!('initiative' in updatedData) || updatedData.initiative === target.initiative) { const sameSlot = existing.map(p => p.id === participantId ? merged : p); const fields = Object.keys(updatedData).join(', '); - patch = { participants: sameSlot, ...syncTurnOrder(sameSlot) }; + patch = { participants: sameSlot, ...syncTurnOrder(sameSlot), ...effectPatch }; const log = { type: 'update_participant', participantId, participantName: target.name, message: `${target.name} updated (${fields})`, delta: { changedFields: Object.keys(updatedData) }, - undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds }, + undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds, ...effectUndo }, }; return commit(encounter, patch, log, ctx); } else { const without = existing.filter(p => p.id !== participantId); const idx = slotIndexForInit(without, merged.initiative); without.splice(idx, 0, merged); - patch = { participants: without, ...syncTurnOrder(without) }; + patch = { participants: without, ...syncTurnOrder(without), ...effectPatch }; const log = { type: 'update_participant', participantId, participantName: target.name, message: `${target.name} updated (initiative: ${merged.initiative})`, delta: { changedFields: Object.keys(updatedData), initiative: merged.initiative }, - undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds }, + undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds, ...effectUndo }, }; return commit(encounter, patch, log, ctx); } @@ -661,9 +752,15 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio status: participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious'), deathSaveSuccesses: participant.deathSaveSuccesses || 0, deathSaveFailures: participant.deathSaveFailures || 0, + stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null, isActive: participant.isActive, conditions: [...(participant.conditions || [])], }; + const oldEffects = [...(encounter.effects || [])]; + const newEffects = changeType === 'damage' ? expireDamageEffects(oldEffects, participantId) : oldEffects; + const effectChanged = effectsChanged(oldEffects, newEffects); + const withEffectPatch = patch => effectChanged ? { ...patch, effects: newEffects } : patch; + const withEffectUndo = undo => effectChanged ? { ...undo, oldEffects, newEffects } : undo; let updates = {}; let message = ''; @@ -698,9 +795,9 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio participantName: participant.name, message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`, delta: { amount, from: participant.currentHp, to: participant.currentHp, tempHp: tempAfter }, - undo: { oldValues, newValues: { ...oldValues, tempHp: tempAfter } }, + undo: withEffectUndo({ oldValues, newValues: { ...oldValues, tempHp: tempAfter } }), }; - return commit(encounter, { participants: updatedParticipants0 }, log0, ctx); + return commit(encounter, withEffectPatch({ participants: updatedParticipants0 }), log0, ctx); } amount = remainingDmg; const tempBefore = currentTemp; @@ -727,9 +824,9 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio participantName: participant.name, message: `${participant.name} marked inactive (dead monster)`, delta: { status: 'dead', isActive: false }, - undo: { oldValues, newValues }, + undo: withEffectUndo({ oldValues, newValues }), }; - return commit(encounter, patch, log, ctx); + return commit(encounter, withEffectPatch(patch), log, ctx); } return encounter; } @@ -738,7 +835,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio if (failures >= 3) { updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, tempHp: tempFinal, ...(participant.type === 'monster' ? { isActive: false } : {}) }; } 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'}`; logDelta = { ...logDelta, to: 0, status: updates.status, deathSaveFailures: updates.deathSaveFailures }; @@ -760,7 +857,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio } else if (changeType === 'heal') { if (status === 'dead') return encounter; 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)`; logDelta = { ...logDelta, to: newHp, status: 'conscious', deathSavesCleared: true }; } else { @@ -770,7 +867,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio const updatedParticipants = (encounter.participants || []).map(p => p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p ); - const patch = { participants: updatedParticipants }; + const patch = withEffectPatch({ participants: updatedParticipants }); const undoAmount = changeType === 'damage' ? amount : -amount; const newP = updatedParticipants.find(p => p.id === participantId); const newValues = { @@ -778,6 +875,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio status: newP.status, deathSaveSuccesses: newP.deathSaveSuccesses || 0, deathSaveFailures: newP.deathSaveFailures || 0, + stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null, isActive: newP.isActive, conditions: [...(newP.conditions || [])], }; @@ -786,7 +884,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio participantId, participantName: participant.name, message, delta: logDelta, - undo: { amount: undoAmount, oldValues, newValues }, + undo: withEffectUndo({ amount: undoAmount, oldValues, newValues }), }; return commit(encounter, patch, log, ctx); } @@ -797,6 +895,11 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount, const participantId = participant.id; let updates, message, logDelta = { amount, from: participant.currentHp }; const currentTemp = participant.tempHp || 0; + const oldEffects = [...(encounter.effects || [])]; + const newEffects = changeType === 'damage' ? expireDamageEffects(oldEffects, participantId) : oldEffects; + const effectChanged = effectsChanged(oldEffects, newEffects); + const withEffectPatch = patch => effectChanged ? { ...patch, effects: newEffects } : patch; + const withEffectUndo = undo => effectChanged ? { ...undo, oldEffects, newEffects } : undo; if (changeType === 'damage') { // Temp HP absorbs damage first. @@ -815,9 +918,9 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount, type: 'hp_change', participantId, participantName: participant.name, message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`, delta: { amount, from: participant.currentHp, to: participant.currentHp, tempHp: tempAfter }, - undo: { oldValues, newValues: { ...oldValues, tempHp: tempAfter } }, + undo: withEffectUndo({ oldValues, newValues: { ...oldValues, tempHp: tempAfter } }), }; - return commit(encounter, { participants: updatedParticipants0 }, log0, ctx); + return commit(encounter, withEffectPatch({ participants: updatedParticipants0 }), log0, ctx); } amount = remainingDmg; const tempFinal = tempAfter; @@ -832,11 +935,11 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount, deathSaveSuccesses: 0, deathSaveFailures: 0, isActive: newP.isActive, conditions: [...(newP.conditions || [])], }; - return commit(encounter, { participants: updatedParticipants }, { + return commit(encounter, withEffectPatch({ participants: updatedParticipants }), { type: 'deactivate_dead_monster', participantId, participantName: participant.name, message: `${participant.name} marked inactive (dead monster)`, delta: { status: 'dead', isActive: false }, - undo: { oldValues, newValues }, + undo: withEffectUndo({ oldValues, newValues }), }, ctx); } return encounter; @@ -873,10 +976,10 @@ async function applyHpChangeGeneric(encounter, participant, changeType, amount, isActive: newP.isActive, conditions: [...(newP.conditions || [])], }; const undoAmount = changeType === 'damage' ? amount : -amount; - return commit(encounter, { participants: updatedParticipants }, { + return commit(encounter, withEffectPatch({ participants: updatedParticipants }), { type: changeType, participantId, participantName: participant.name, message, delta: logDelta, - undo: { amount: undoAmount, oldValues, newValues }, + undo: withEffectUndo({ amount: undoAmount, oldValues, newValues }), }, ctx); } @@ -897,6 +1000,7 @@ async function deathSave(encounter, participantId, outcome, ctx) { status: statusBefore, deathSaveSuccesses: participant.deathSaveSuccesses || 0, deathSaveFailures: participant.deathSaveFailures || 0, + stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null, isActive: participant.isActive, conditions: [...(participant.conditions || [])], }; @@ -907,8 +1011,8 @@ async function deathSave(encounter, participantId, outcome, ctx) { } else { const successes = (participant.deathSaveSuccesses || 0) + (outcome === 'success' ? 1 : 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 }; - else if (successes >= 3) updates = { currentHp: 0, status: 'stable', 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, stableRegainHours: rollD4() }; else updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: successes, deathSaveFailures: failures }; } @@ -928,6 +1032,7 @@ async function deathSave(encounter, participantId, outcome, ctx) { status: newP.status, deathSaveSuccesses: newP.deathSaveSuccesses || 0, deathSaveFailures: newP.deathSaveFailures || 0, + stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null, isActive: newP.isActive, conditions: [...(newP.conditions || [])], }; @@ -963,6 +1068,52 @@ async function toggleCondition(encounter, participantId, conditionId, ctx) { return commit(encounter, patch, log, ctx); } +async function addEffect(encounter, effect, ctx) { + const normalized = makeEffect({ ...effect, createdRound: effect.createdRound ?? encounter.round ?? 0 }); + const oldEffects = [...(encounter.effects || [])]; + if (oldEffects.some(e => e.id === normalized.id)) throw new Error(`Effect "${normalized.id}" already exists.`); + if (normalized.scope === 'participant' && !normalized.targetParticipantId) throw new Error('Participant effect requires targetParticipantId.'); + const newEffects = [...oldEffects, normalized]; + const target = (encounter.participants || []).find(p => p.id === normalized.targetParticipantId); + return commit(encounter, { effects: newEffects }, { + type: 'add_effect', + participantId: normalized.targetParticipantId, + participantName: target?.name || null, + message: `${normalized.name} added${target ? ` to ${target.name}` : ''} (${normalized.remainingRounds} rounds)`, + delta: { effectId: normalized.id, name: normalized.name, remainingRounds: normalized.remainingRounds }, + undo: { oldEffects, newEffects }, + }, ctx); +} + +async function updateEffect(encounter, effectId, updates, ctx) { + const oldEffects = [...(encounter.effects || [])]; + const existing = oldEffects.find(e => e.id === effectId); + if (!existing) throw new Error('Effect not found.'); + const merged = makeEffect({ ...existing, ...updates, id: existing.id }); + const newEffects = oldEffects.map(e => e.id === effectId ? merged : e); + return commit(encounter, { effects: newEffects }, { + type: 'update_effect', + participantId: merged.targetParticipantId, + message: `${merged.name} updated (${merged.remainingRounds} rounds)`, + delta: { effectId, remainingRounds: merged.remainingRounds }, + undo: { oldEffects, newEffects }, + }, ctx); +} + +async function removeEffect(encounter, effectId, ctx) { + const oldEffects = [...(encounter.effects || [])]; + const existing = oldEffects.find(e => e.id === effectId); + if (!existing) throw new Error('Effect not found.'); + const newEffects = oldEffects.filter(e => e.id !== effectId); + return commit(encounter, { effects: newEffects }, { + type: 'remove_effect', + participantId: existing.targetParticipantId, + message: `${existing.name} removed`, + delta: { effectId, name: existing.name }, + undo: { oldEffects, newEffects }, + }, ctx); +} + async function stabilizeParticipant(encounter, participantId, ctx) { if ((encounter.ruleset || '5e') === 'generic') { throw new Error('Stabilize not available in generic ruleset.'); @@ -974,7 +1125,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) { if (status === 'dead') throw new Error('Cannot stabilize dead participant.'); 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 => p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p ); @@ -985,6 +1136,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) { status, deathSaveSuccesses: participant.deathSaveSuccesses || 0, deathSaveFailures: participant.deathSaveFailures || 0, + stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null, isActive: participant.isActive, conditions: [...(participant.conditions || [])], }; @@ -994,6 +1146,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) { status: newP.status, deathSaveSuccesses: newP.deathSaveSuccesses || 0, deathSaveFailures: newP.deathSaveFailures || 0, + stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null, isActive: newP.isActive, conditions: [...(newP.conditions || [])], }; @@ -1019,7 +1172,7 @@ async function reviveParticipant(encounter, participantId, ctx) { // 5e: dead→stable at 0 HP, unconscious, clears death-save counters. const updates = ruleset === 'generic' ? { 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 => p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p ); @@ -1030,6 +1183,7 @@ async function reviveParticipant(encounter, participantId, ctx) { status, deathSaveSuccesses: participant.deathSaveSuccesses || 0, deathSaveFailures: participant.deathSaveFailures || 0, + stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null, isActive: participant.isActive, conditions: [...(participant.conditions || [])], }; @@ -1039,6 +1193,7 @@ async function reviveParticipant(encounter, participantId, ctx) { status: newP.status, deathSaveSuccesses: newP.deathSaveSuccesses || 0, deathSaveFailures: newP.deathSaveFailures || 0, + stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null, isActive: newP.isActive, conditions: [...(newP.conditions || [])], }; @@ -1053,30 +1208,90 @@ async function reviveParticipant(encounter, participantId, ctx) { return commit(encounter, patch, log, ctx); } -// markDead: DM manually sets status dead. Both rulesets. Monster = auto-inactive. +async function healFullParticipant(encounter, participantId, ctx) { + const participant = (encounter.participants || []).find(p => p.id === participantId); + if (!participant) throw new Error('Participant not found.'); + const status = participant.status || (participant.currentHp <= 0 ? 'down' : 'conscious'); + const oldValues = { + currentHp: participant.currentHp, + status, + deathSaveSuccesses: participant.deathSaveSuccesses || 0, + deathSaveFailures: participant.deathSaveFailures || 0, + stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null, + isActive: participant.isActive, + conditions: [...(participant.conditions || [])], + }; + const updates = { + currentHp: participant.maxHp, + status: 'conscious', + deathSaveSuccesses: 0, + deathSaveFailures: 0, + stableRegainHours: null, + isActive: true, + }; + const updatedParticipants = (encounter.participants || []).map(p => + p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p + ); + const newP = updatedParticipants.find(p => p.id === participantId); + const newValues = { + currentHp: newP.currentHp, + status: newP.status, + deathSaveSuccesses: newP.deathSaveSuccesses || 0, + deathSaveFailures: newP.deathSaveFailures || 0, + stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null, + isActive: newP.isActive, + conditions: [...(newP.conditions || [])], + }; + return commit(encounter, { participants: updatedParticipants }, { + type: 'heal_full', participantId, participantName: participant.name, + message: `${participant.name} healed to full (${participant.maxHp} HP)`, + delta: { currentHp: participant.maxHp, status: 'conscious', isActive: true }, + undo: { oldValues, newValues }, + }, ctx); +} + +// markDead: DM manually kills participant. Sets 0 HP + inactive. async function markDead(encounter, participantId, ctx) { const participant = (encounter.participants || []).find(p => p.id === participantId); if (!participant) throw new Error('Participant not found.'); if (participant.status === 'dead') return encounter; const oldValues = { currentHp: participant.currentHp, + tempHp: participant.tempHp || 0, status: participant.status || 'conscious', + deathSaveSuccesses: participant.deathSaveSuccesses || 0, + deathSaveFailures: participant.deathSaveFailures || 0, + stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null, isActive: participant.isActive, conditions: [...(participant.conditions || [])], }; - const updates = { status: 'dead', ...(participant.type === 'monster' ? { isActive: false } : {}) }; + const updates = { + currentHp: 0, + tempHp: 0, + status: 'dead', + deathSaveSuccesses: 0, + deathSaveFailures: 0, + stableRegainHours: null, + isActive: false, + }; const updatedParticipants = (encounter.participants || []).map(p => p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p ); const newP = updatedParticipants.find(p => p.id === participantId); const newValues = { - currentHp: newP.currentHp, status: newP.status, - isActive: newP.isActive, conditions: [...(newP.conditions || [])], + currentHp: newP.currentHp, + tempHp: newP.tempHp || 0, + status: newP.status, + deathSaveSuccesses: newP.deathSaveSuccesses || 0, + deathSaveFailures: newP.deathSaveFailures || 0, + stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null, + isActive: newP.isActive, + conditions: [...(newP.conditions || [])], }; return commit(encounter, { participants: updatedParticipants }, { type: 'mark_dead', participantId, participantName: participant.name, - message: `${participant.name} marked dead`, - delta: { status: 'dead' }, + message: `${participant.name} killed`, + delta: { status: 'dead', currentHp: 0, isActive: false }, undo: { oldValues, newValues }, }, ctx); } @@ -1139,7 +1354,10 @@ async function endEncounter(encounter, ctx) { try { campaign = ctx.campaign || await ctx.storage.getDoc(campaignPath); } catch { campaign = null; } - if (campaign && campaign.syncCharacters && Array.isArray(campaign.players)) { + const syncCharacters = ctx.syncCharacters !== undefined + ? ctx.syncCharacters + : campaign?.syncCharacters; + if (campaign && syncCharacters && Array.isArray(campaign.players)) { const charParticipants = (encounter.participants || []).filter(p => p.originalCharacterId); const oldValues = []; let changed = false; @@ -1149,11 +1367,15 @@ async function endEncounter(encounter, ctx) { const oldMaxHp = player.defaultMaxHp; const oldAc = player.defaultAc; 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 }; 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.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; }); if (changed) { @@ -1170,6 +1392,40 @@ async function endEncounter(encounter, 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. // ctx.displayPath required. @@ -1192,10 +1448,11 @@ module.exports = { generateId, rollD20, rollHpFormula, formatInitMod, sortParticipantsByInitiative, syncTurnOrder, computeTurnOrderAfterRemoval, snapshotOf, buildEntry, expandUndo, - makeParticipant, buildCharacterParticipant, buildMonsterParticipant, + makeEffect, makeParticipant, buildCharacterParticipant, buildMonsterParticipant, startEncounter, nextTurn, togglePause, addParticipant, addParticipants, updateParticipant, removeParticipant, - toggleParticipantActive, applyHpChange, setTempHp, deathSave, stabilizeParticipant, reviveParticipant, markDead, toggleCondition, - reorderParticipants, endEncounter, + toggleParticipantActive, applyHpChange, setTempHp, deathSave, stabilizeParticipant, reviveParticipant, healFullParticipant, markDead, toggleCondition, + addEffect, updateEffect, removeEffect, + reorderParticipants, endEncounter, rerollAllInitiatives, activateDisplay, clearDisplay, toggleHidePlayerHp, }; diff --git a/src/App.js b/src/App.js index 7712fd2..cd61bdf 100644 --- a/src/App.js +++ b/src/App.js @@ -8,8 +8,8 @@ import { UserCheck, UserX, HeartCrack, HeartPulse, Zap, EyeOff, ExternalLink, AlertTriangle, Play as PlayIcon, Pause as PauseIcon, SkipForward as SkipForwardIcon, StopCircle as StopCircleIcon, Users2, Dices, ChevronDown, ScrollText, - Maximize2, Minimize2, PanelTopOpen, PanelTopClose, Moon, Coffee, Clock, ChevronRight, X, - Undo2, Redo2, Crosshair + Maximize2, Minimize2, PanelTopOpen, PanelTopClose, Coffee, Clock, ChevronRight, X, + Undo2, Redo2, Crosshair, Pencil } from 'lucide-react'; // ----- UI feedback: toast (transient) + info modal (persistent) ----- @@ -127,9 +127,13 @@ const { deathSave: combatDeathSave, stabilizeParticipant, reviveParticipant, + healFullParticipant, markDead, toggleCondition: combatToggleCondition, reorderParticipants, + addEffect: combatAddEffect, + updateEffect: combatUpdateEffect, + removeEffect: combatRemoveEffect, } = shared; const ROLL_DISPLAY_DURATION = 5000; @@ -338,6 +342,28 @@ function useFirestoreCollection(collectionPath, queryConstraints = []) { // REUSABLE COMPONENTS // ============================================================================ +function CaffeineButton({ enabled, onToggle, compact = false }) { + const label = `Caffeine ${enabled ? 'ON' : 'OFF'}`; + const size = compact ? 18 : 20; + return ( + + ); +} + function Modal({ onClose, title, children }) { useEffect(() => { const handleEsc = (event) => { @@ -363,7 +389,7 @@ function Modal({ onClose, title, children }) { ); } -function ConfirmationModal({ isOpen, onClose, onConfirm, title, message }) { +function ConfirmationModal({ isOpen, onClose, onConfirm, title, message, children }) { const [pending, setPending] = useState(false); const [error, setError] = useState(null); @@ -400,7 +426,8 @@ function ConfirmationModal({ isOpen, onClose, onConfirm, title, message }) {

{title || "Confirm Action"}

-

{message || "Are you sure you want to proceed?"}

+

{message || "Are you sure you want to proceed?"}

+ {children &&
{children}
} {error && (

{error}

)} @@ -450,16 +477,14 @@ function ErrorDisplay({ message, critical = false }) { // FORM COMPONENTS // ============================================================================ -function CreateCampaignForm({ onCreate, onCancel }) { - const [name, setName] = useState(''); - const [backgroundUrl, setBackgroundUrl] = useState(''); - const [ruleset, setRuleset] = useState('5e'); +function CampaignForm({ campaign, onSave, onCancel }) { + const [name, setName] = useState(campaign?.name || ''); + const [backgroundUrl, setBackgroundUrl] = useState(campaign?.playerDisplayBackgroundUrl || ''); + const [ruleset, setRuleset] = useState(campaign?.ruleset || '5e'); const handleSubmit = (e) => { e.preventDefault(); - if (name.trim()) { - onCreate(name, backgroundUrl, ruleset); - } + if (name.trim()) onSave(name.trim(), backgroundUrl.trim(), ruleset); }; return ( @@ -502,6 +527,7 @@ function CreateCampaignForm({ onCreate, onCancel }) { Generic (no death saves, negative HP) + {campaign &&

Default for new encounters. Existing encounters keep their ruleset.

}
@@ -514,9 +540,10 @@ function CreateCampaignForm({ onCreate, onCancel }) {
@@ -584,6 +611,7 @@ function CreateEncounterForm({ onCreate, onCancel, defaultRuleset = '5e' }) { function EditParticipantModal({ participant, onClose, onSave }) { const [name, setName] = useState(participant.name); const [initiative, setInitiative] = useState(participant.initiative); + const [initMod, setInitMod] = useState(participant.initMod != null ? participant.initMod : ''); const [currentHp, setCurrentHp] = useState(participant.currentHp); const [maxHp, setMaxHp] = useState(participant.maxHp); const [hpFormula, setHpFormula] = useState(participant.hpFormula || ''); @@ -605,6 +633,7 @@ function EditParticipantModal({ participant, onClose, onSave }) { onSave({ name: name.trim(), initiative: parseInt(initiative, 10), + initMod: initMod !== '' ? parseInt(initMod, 10) : null, currentHp: finalCurrentHp, maxHp: finalMaxHp, hpFormula: (participant.type === 'monster' || participant.type === 'npc') ? (hpFormula.trim() || null) : null, @@ -628,15 +657,37 @@ function EditParticipantModal({ participant, onClose, onSave }) {
- + setInitiative(e.target.value)} + id="edit-initmod" + value={initMod} + onChange={(e) => setInitMod(e.target.value)} + placeholder="0" className="mt-1 block w-full px-3 py-2 bg-stone-800 border border-stone-700 rounded-md shadow-sm focus:outline-none focus:ring-amber-600 focus:border-amber-600 sm:text-sm text-white" />
+
+ +
+ setInitiative(e.target.value)} + className="block w-full px-3 py-2 bg-stone-800 border border-stone-700 rounded-md shadow-sm focus:outline-none focus:ring-amber-600 focus:border-amber-600 sm:text-sm text-white" + /> + +
+
- c.id === characterId - ? { ...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) } - : c - ); + const updatedCharacters = campaignCharacters.map(c => { + if (c.id !== characterId) return c; + const nextCurrentHp = newDefaultCurrentHp !== undefined && newDefaultCurrentHp !== '' ? parseInt(newDefaultCurrentHp, 10) : null; + // 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 { await storage.updateDoc(getPath.campaign(campaignId), { players: updatedCharacters }); @@ -1078,6 +1140,9 @@ function CharacterManager({ campaignId, campaignCharacters, syncCharacters }) { {character.defaultCurrentHp != null && character.defaultCurrentHp !== character.defaultMaxHp && ( Current HP {character.defaultCurrentHp} )} + {character.stableRegainHours != null && ( + Stable — regains 1 HP after {character.stableRegainHours} hour{character.stableRegainHours > 1 ? 's' : ''} + )} {character.defaultAc != null && ( AC {character.defaultAc} )} @@ -1128,6 +1193,214 @@ function CharacterManager({ campaignId, campaignCharacters, syncCharacters }) { ); } +function EffectModal({ encounter, defaultScope, defaultTargetParticipantId, onClose, onAdd }) { + const is5e = (encounter.ruleset || '5e') === '5e'; + const participants = encounter.participants || []; + const [presetId, setPresetId] = useState('custom'); + const [name, setName] = useState(''); + const [scope, setScope] = useState(defaultScope || 'participant'); + const [targetParticipantId, setTargetParticipantId] = useState(defaultTargetParticipantId || participants[0]?.id || ''); + const [ownerParticipantId, setOwnerParticipantId] = useState(encounter.currentTurnParticipantId || ''); + const [duration, setDuration] = useState('10'); + const [durationUnit, setDurationUnit] = useState('rounds'); + const [expiresOnDamage, setExpiresOnDamage] = useState(false); + const [playerDisplay, setPlayerDisplay] = useState('compact'); + const [notes, setNotes] = useState(''); + + const selectPreset = (value) => { + setPresetId(value); + if (value === 'turned') { + setName('Turned'); + setScope('participant'); + setTargetParticipantId(defaultTargetParticipantId || participants[0]?.id || ''); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(true); + setPlayerDisplay('prominent'); + } else if (value === 'spiritual_weapon') { + setName('Spiritual Weapon'); + setScope('encounter'); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(false); + setPlayerDisplay('prominent'); + } else { + setName(''); + setScope(defaultScope || 'participant'); + setTargetParticipantId(defaultTargetParticipantId || participants[0]?.id || ''); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(false); + setPlayerDisplay('compact'); + } + }; + + const submit = (e) => { + e.preventDefault(); + const n = Math.max(1, parseInt(duration, 10) || 1); + if (!name.trim() || (scope === 'participant' && !targetParticipantId)) return; + onAdd({ + presetId, + name: name.trim(), + scope, + targetParticipantId: scope === 'participant' ? targetParticipantId : null, + ownerParticipantId: ownerParticipantId || null, + remainingRounds: durationUnit === 'minutes' && is5e ? n * 10 : n, + expiresOnDamage, + playerDisplay, + notes, + createdRound: encounter.round || 0, + }); + }; + + return ( + +
+ + +
+ + {scope === 'participant' && ( + + )} +
+ +
+ + +
+ + + +
+ + +
+
+
+ ); +} + +function EffectControlRow({ effect, participants, onAdjust, onSet, onSetOwner, onRemove }) { + const [draftRounds, setDraftRounds] = useState(String(effect.remainingRounds)); + useEffect(() => setDraftRounds(String(effect.remainingRounds)), [effect.remainingRounds]); + const commitRounds = () => { + const value = Math.max(1, parseInt(draftRounds, 10) || 1); + setDraftRounds(String(value)); + if (value !== effect.remainingRounds) onSet(effect, value); + }; + return ( +
+ {effect.name.toUpperCase()} + + + {effect.expiresOnDamage && Ends on damage} + + + + + +
+ ); +} + +function PlayerEffectDisplay({ effect, ownerName }) { + if (!effect || effect.playerDisplay === 'hidden') return null; + const testId = effect.scope === 'encounter' ? `encounter-effect-${effect.id}` : `prominent-effect-${effect.id}`; + if (effect.playerDisplay === 'prominent') { + return ( +
+
{effect.name.toUpperCase()}
+
+ {ownerName && {ownerName} · }{effect.remainingRounds} rounds remaining + {effect.expiresOnDamage && · Ends on damage} +
+ {effect.notes &&
{effect.notes}
} +
+ ); + } + return ( + + {effect.name} · {effect.remainingRounds} rounds{ownerName ? ` · ${ownerName}` : ''} + + ); +} + // ============================================================================ // PARTICIPANT MANAGER COMPONENT // ============================================================================ @@ -1145,14 +1418,17 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp const [asNpc, setAsNpc] = useState(false); const combatActive = encounter.isStarted && !encounter.isPaused; const [addSectionOpen, setAddSectionOpen] = useState(!combatActive); + const [showRerollConfirm, setShowRerollConfirm] = useState(false); const [editingParticipant, setEditingParticipant] = useState(null); const [hpChangeValues, setHpChangeValues] = useState({}); const [draggedItemId, setDraggedItemId] = useState(null); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [itemToDelete, setItemToDelete] = useState(null); + const [killTarget, setKillTarget] = useState(null); const [lastRollDetails, setLastRollDetails] = useState(null); const [openConditionsId, setOpenConditionsId] = useState(null); const [customConditionInput, setCustomConditionInput] = useState(''); + const [effectModal, setEffectModal] = useState(null); // Per-campaign custom conditions (DM-added freeform strings). const { data: campaignDoc } = useFirestoreDocument(campaignId ? getPath.campaign(campaignId) : null); @@ -1165,6 +1441,16 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp ]; const participants = encounter.participants || []; + const isDeadParticipant = p => p.status === 'dead' || ((encounter.ruleset || '5e') === '5e' && p.type === 'monster' && p.currentHp === 0); + // Independent filters: Hide Disabled applies to every inactive participant, + // including dead PCs. Hide Dead applies only to dead monsters/NPCs. + const deadParticipants = participants.filter(p => isDeadParticipant(p) && p.type !== 'character'); + const disabledParticipants = participants.filter(p => p.isActive === false); + const visibleParticipants = participants.filter(p => { + if (encounter.hideDisabledParticipants && p.isActive === false) return false; + if (encounter.hideDeadParticipants && isDeadParticipant(p) && p.type !== 'character') return false; + return true; + }); const [editingField, setEditingField] = useState(null); const [editingId, setEditingId] = useState(null); const blurTimeoutRef = useRef(null); @@ -1202,6 +1488,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp let modifier = 0; let currentMaxHp = parseInt(maxHp, 10) || DEFAULT_MAX_HP; let participantAsNpc = false; + let characterParticipant = null; const manualInit = manualInitiative !== '' && !isNaN(parseInt(manualInitiative, 10)); const finalInitiative = manualInit ? parseInt(manualInitiative, 10) : null; @@ -1210,13 +1497,15 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp if (!character) { return; } - if (participants.some(p => p.type === 'character' && p.originalCharacterId === selectedCharacterId)) { + if (participants.some(p => p.originalCharacterId === selectedCharacterId)) { showInfo(`${character.name} is already in this encounter.`); return; } - nameToAdd = character.name; - currentMaxHp = character.defaultMaxHp || currentMaxHp; - modifier = character.defaultInitMod || 0; + const built = shared.buildCharacterParticipant(character, initiativeRoll); + characterParticipant = built.participant; + nameToAdd = characterParticipant.name; + currentMaxHp = characterParticipant.maxHp; + modifier = characterParticipant.initMod || 0; } else { modifier = parseInt(monsterInitMod, 10) || 0; participantAsNpc = asNpc; @@ -1227,23 +1516,32 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp } } + let finalType = participantType; + if (participantType === 'monster' && participantAsNpc) finalType = 'npc'; + if (participantType === 'character') { + const character = campaignCharacters.find(c => c.id === selectedCharacterId); + if (character?.isNpc) finalType = 'npc'; + } const computedInitiative = manualInit ? finalInitiative : (initiativeRoll + modifier); - const newParticipant = { - id: generateId(), - name: nameToAdd, - type: participantType === 'monster' && participantAsNpc ? 'npc' : participantType, - originalCharacterId: participantType === 'character' ? selectedCharacterId : null, - initiative: computedInitiative, - maxHp: currentMaxHp, - currentHp: currentMaxHp, - hpFormula: participantType === 'monster' ? (hpFormula.trim() || null) : null, - ac: participantType === 'monster' && monsterAc !== '' ? parseInt(monsterAc, 10) : (participantType === 'character' ? (campaignCharacters.find(c => c.id === selectedCharacterId)?.defaultAc ?? null) : null), - conditions: [], - isActive: true, - status: 'conscious', - deathSaveSuccesses: 0, - deathSaveFailures: 0, - }; + const newParticipant = characterParticipant + ? { ...characterParticipant, initiative: computedInitiative } + : { + id: generateId(), + name: nameToAdd, + type: finalType, + originalCharacterId: ['character', 'npc'].includes(finalType) ? selectedCharacterId : null, + initiative: computedInitiative, + initMod: modifier, + maxHp: currentMaxHp, + currentHp: currentMaxHp, + hpFormula: hpFormula.trim() || null, + ac: monsterAc !== '' ? parseInt(monsterAc, 10) : null, + conditions: [], + isActive: true, + status: 'conscious', + deathSaveSuccesses: 0, + deathSaveFailures: 0, + }; try { await addParticipant(encounter, newParticipant, buildCtx(encounterPath)); @@ -1279,25 +1577,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp const newParticipants = campaignCharacters .filter(char => !existingCharacterIds.includes(char.id)) - .map(char => { - const initiativeRoll = rollD20(); - const modifier = char.defaultInitMod || 0; - const finalInitiative = initiativeRoll + modifier; - return { - id: generateId(), - name: char.name, - type: 'character', - originalCharacterId: char.id, - initiative: finalInitiative, - maxHp: char.defaultMaxHp || DEFAULT_MAX_HP, - currentHp: char.defaultMaxHp || DEFAULT_MAX_HP, - conditions: [], - isActive: true, - status: 'conscious', - deathSaveSuccesses: 0, - deathSaveFailures: 0, - }; - }); + .map(char => shared.buildCharacterParticipant(char).participant); if (newParticipants.length === 0) { showInfo("All campaign characters are already in this encounter."); return; @@ -1338,6 +1618,16 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp 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 () => { if (!db || !itemToDelete) return; try { @@ -1386,7 +1676,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp if (isGeneric) { patch = { currentHp: n, status: n > 0 ? 'conscious' : 'down' }; } else { - patch = { currentHp: n, deathSaveSuccesses: 0, deathSaveFailures: 0 }; + patch = { currentHp: n, deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null }; if (n > 0) { patch.status = 'conscious'; } else if (p.type === 'monster') { patch.status = 'dead'; patch.isActive = false; } else { patch.status = 'dying'; } @@ -1461,6 +1751,15 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp } }; + const handleHealFull = async (participantId) => { + if (!db) return; + try { + await healFullParticipant(encounter, participantId, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message); + } + }; + const handleMarkDead = async (participantId) => { if (!db) return; try { @@ -1470,6 +1769,20 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp } }; + const confirmKill = async () => { + if (!killTarget) return; + await handleMarkDead(killTarget.id); + setKillTarget(null); + }; + + const toggleParticipantVisibility = async (field) => { + try { + await storage.updateDoc(encounterPath, { [field]: !encounter[field] }); + } catch (err) { + showToast('Failed to update participant visibility.'); + } + }; + const handleCritDamage = async (participantId) => { if (!db) return; try { @@ -1489,6 +1802,84 @@ 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: encounter.currentTurnParticipantId || 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 handleSetEffectOwner = async (effect, ownerParticipantId) => { + if (!db) return; + try { + await combatUpdateEffect(encounter, effect.id, { ownerParticipantId }, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message || 'Failed to update effect owner.'); + } + }; + + const handleRemoveEffect = async (effect) => { + if (!db) return; + try { + await combatRemoveEffect(encounter, effect.id, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message || 'Failed to remove effect.'); + } + }; + // Add freeform condition: persist to campaign palette + apply to current participant. const addCustomCondition = async (label, participantId = null) => { const trimmed = (label || '').trim(); @@ -1534,8 +1925,9 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp setDraggedItemId(null); }; - // 1-list model: participants[] IS the display order. No re-sort. - const sortedParticipants = participants; + // 1-list model: participants[] IS display order. Visibility filters only render; + // encounter data/order remain untouched. + const sortedParticipants = visibleParticipants; const initiativeGroups = participants.reduce((acc, p) => { acc[p.initiative] = (acc[p.initiative] || 0) + 1; @@ -1551,28 +1943,45 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp {(() => { const open = addSectionOpen && !combatActive; return ( -
- { if (!combatActive) { e.preventDefault(); setAddSectionOpen(v => !v); } else { e.preventDefault(); } }} - className="cursor-pointer text-lg font-medium text-amber-200 font-cinzel tracking-wide flex items-center gap-2 select-none" - > - {open ? : } - Add Participants - {combatActive && (pause to add)} - - {open && ( - <> -
+
+
+ +
+ {!combatActive && (participants || []).length > 0 && ( + + )}
- +
+ {open && ( + <> {/* Warning when combat is active */} {encounter.isStarted && !encounter.isPaused && (
@@ -1752,11 +2161,41 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp )} -
+
); })()} + {(encounter.effects || []).some(effect => effect.scope === 'encounter' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId))) && ( +
+

Encounter Effects

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

No participants added yet.

} + {participants.length > 0 && visibleParticipants.length === 0 &&

All participants hidden.

}
    @@ -1780,6 +2219,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp return (
  • handleDragStart(e, p.id) : undefined} onDragOver={isDraggable ? handleDragOver : undefined} @@ -1889,20 +2329,26 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp {participantStatus === 'dead' && ( - - )} - {isGeneric && !isDead && ( - + + + + )} +
{hasDeathSaves && participantStatus === 'stable' && ( -
Stable — regains 1 HP after 1d4 hours
+
Stable — regains 1 HP after {p.stableRegainHours ? `${p.stableRegainHours} hour${p.stableRegainHours > 1 ? 's' : ''}` : '1d4 hours'}
)} {/* Death saves - D&D 5e status state machine */} @@ -1984,6 +2430,13 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp )} + {(encounter.effects || []).filter(effect => + (effect.scope === 'participant' && effect.targetParticipantId === p.id) || + (effect.scope === 'encounter' && effect.ownerParticipantId === p.id) + ).map(effect => ( + + ))} + {/* Expandable conditions picker */} {openConditionsId === p.id && (
@@ -2003,6 +2456,48 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp ); })}
+ {(encounter.ruleset || '5e') === '5e' && ( + <> +

Tracked Effects

+
+ {(() => { + const active = (encounter.effects || []).some(effect => effect.presetId === 'turned' && effect.targetParticipantId === p.id); + return ( + + ); + })()} + {(() => { + const active = (encounter.effects || []).some(effect => effect.presetId === 'spiritual_weapon' && effect.ownerParticipantId === p.id); + return ( + + ); + })()} +
+ + )} + + {/* Add custom condition (per-campaign, freeform string) */}
)} + {!isDead && ( + + )} +
+ + +
{(!encounters || encounters.length === 0) && (

No encounters yet.

)} -
- {sortedEncounters.map(encounter => { + {/* Encounter groups: In Progress / Ready / Completed. */} + {(() => { + const inProgress = sortedEncounters.filter(e => e.isStarted && !e.endedAt); + const completed = sortedEncounters.filter(e => e.endedAt); + const ready = sortedEncounters.filter(e => !(e.isStarted && !e.endedAt) && !e.endedAt); + const renderCard = (encounter) => { const isLive = activeDisplayInfo && activeDisplayInfo.activeCampaignId === campaignId && activeDisplayInfo.activeEncounterId === encounter.id; @@ -2660,8 +3296,41 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac className={`p-3 rounded-md shadow transition-all ${selectedEncounterId === encounter.id ? 'bg-amber-900 ring-2 ring-amber-500' : 'bg-stone-800 hover:bg-stone-700'} ${isLive ? 'ring-2 ring-green-500 shadow-md shadow-green-500/30' : ''} ${encounter.isStarted && !encounter.endedAt ? 'ring-2 ring-red-500' : ''} ${draggedEncounterId === encounter.id ? 'opacity-50 ring-2 ring-yellow-400' : ''} cursor-grab`} >
-
setSelectedEncounterId(encounter.id)} className="cursor-pointer flex-grow"> +
openEncounter(encounter.id)} className="cursor-pointer flex-grow"> + {renamingId === encounter.id ? ( +
{ e.preventDefault(); commitRename(encounter.id); }} + className="flex items-center gap-1" + onClick={(e) => e.stopPropagation()} + > + setRenameValue(e.target.value)} + onKeyDown={(e) => { if (e.key === 'Escape') cancelRename(); }} + autoFocus + aria-label="Encounter name" + className="font-medium text-white bg-stone-950 border border-amber-500 rounded px-1 py-0.5 w-full min-w-0" + /> + + +
+ ) : (

{encounter.name} {encounter.ruleset === 'generic' ? 'GEN' : '5e'}{encounter.isStarted && !encounter.endedAt && ⚔ IN PROGRESS}

+ )}

{encounter.createdAt && `${new Date(encounter.createdAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false })} · `}Participants: {encounter.participants?.length || 0}

@@ -2689,6 +3358,16 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac > {isLive ? : } +
); - })} -
+ }; + + const Group = ({ label, count, items, collapsible, open, onToggle }) => ( +
+ + {(!collapsible || open) && items} +
+ ); + + const wrap = (encounter) => ( +
{renderCard(encounter)}
+ ); + + const groups = []; + if (inProgress.length > 0) { + groups.push(); + } + if (ready.length > 0) { + groups.push(); + } + if (completed.length > 0) { + groups.push( setCompletedOpen(v => !v)} />); + } + return
{groups}
; + })()} {showCreateModal && ( setShowCreateModal(false)} title="Create New Encounter"> @@ -2718,18 +3429,11 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac )} {selectedEncounter && ( -
-

+
+

Managing Encounter: {selectedEncounter.name} - +

@@ -2755,6 +3460,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac campaignId={campaignId} encounter={selectedEncounter} encounterPath={getPath.encounter(campaignId, selectedEncounter.id)} + syncCharacters={!!campaignDoc?.syncCharacters} />
@@ -2927,6 +3633,7 @@ function AdminView({ userId }) { } }, [initialActiveInfo]); const [showCreateModal, setShowCreateModal] = useState(false); + const [editingCampaignId, setEditingCampaignId] = useState(null); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [itemToDelete, setItemToDelete] = useState(null); const [campaignsCollapsed, setCampaignsCollapsed] = useState(() => { @@ -3033,6 +3740,21 @@ function AdminView({ userId }) { showToast("Failed to create campaign. Please try again."); } }; + const handleUpdateCampaign = async (campaignId, name, backgroundUrl, ruleset) => { + if (!db || !name.trim()) return; + try { + await storage.updateDoc(getPath.campaign(campaignId), { + name: name.trim(), + playerDisplayBackgroundUrl: backgroundUrl.trim(), + ruleset, + }); + setEditingCampaignId(null); + } catch (err) { + console.error('Error updating campaign:', err); + showToast('Failed to update campaign. Please try again.'); + } + }; + const requestDeleteCampaign = (campaignId, campaignName) => { setItemToDelete({ id: campaignId, name: campaignName }); setShowDeleteConfirm(true); @@ -3120,6 +3842,7 @@ function AdminView({ userId }) { }; const selectedCampaign = campaignsWithDetails.find(c => c.id === selectedCampaignId); + const editingCampaign = campaignsWithDetails.find(c => c.id === editingCampaignId); if (isLoadingCampaigns) { return

Loading campaigns...

; @@ -3157,13 +3880,10 @@ function AdminView({ userId }) { Create Campaign
- + setWakeLockEnabled(v => { localStorage.setItem('ttrpg.wakeLock', String(!v)); return !v; })} + />
- +
+ + +
setShowCreateModal(false)} title="Create New Campaign"> - setShowCreateModal(false)} /> )} + {editingCampaign && ( + setEditingCampaignId(null)} title="Edit Campaign"> + handleUpdateCampaign(editingCampaign.id, name, backgroundUrl, ruleset)} + onCancel={() => setEditingCampaignId(null)} + /> + + )} + {selectedCampaign && (

@@ -3382,6 +4126,7 @@ function PlayerParticipantCard({ id, isActive, status, onExit, className, childr return (
{children} @@ -3596,13 +4341,10 @@ function DisplayView() { return (
- + setWakeLockEnabled(v => { localStorage.setItem('ttrpg.wakeLock', String(!v)); return !v; })} + /> + setWakeLockEnabled(v => { localStorage.setItem('ttrpg.wakeLock', String(!v)); return !v; })} + />