fix: carry roster stats into encounters and add one-time sync choice
- use shared character participant builder for single-add and Add All so saved current HP, Max HP, AC, and stable state carry forward - add End Encounter checkbox to override character writeback for one action - default transient checkbox from campaign preference without persisting changes - support explicit writeback override in shared endEncounter logic - cover both add paths and modal enable/disable/reset behavior
This commit is contained in:
1 parent
8d71f0ba4b
commit
bca406fca9
5 files changed
+257
-34
No files matched your search
@@ -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 }];
|
||||
|
||||
+5
-3
@@ -380,8 +380,7 @@ function makeParticipant(opts) {
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -1168,7 +1167,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;
|
||||
|
||||
+38
-31
@@ -385,7 +385,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);
|
||||
|
||||
@@ -422,7 +422,8 @@ function ConfirmationModal({ isOpen, onClose, onConfirm, title, message }) {
|
||||
<AlertTriangle size={24} className="text-yellow-400 mr-3 flex-shrink-0" />
|
||||
<h2 className="text-xl font-semibold text-yellow-300">{title || "Confirm Action"}</h2>
|
||||
</div>
|
||||
<p className="text-stone-300 mb-6">{message || "Are you sure you want to proceed?"}</p>
|
||||
<p className={`text-stone-300 ${children ? 'mb-4' : 'mb-6'}`}>{message || "Are you sure you want to proceed?"}</p>
|
||||
{children && <div className="mb-6">{children}</div>}
|
||||
{error && (
|
||||
<p className="text-red-400 text-sm mb-4">{error}</p>
|
||||
)}
|
||||
@@ -1263,6 +1264,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;
|
||||
|
||||
@@ -1275,9 +1277,11 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
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;
|
||||
@@ -1295,7 +1299,9 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
if (character?.isNpc) finalType = 'npc';
|
||||
}
|
||||
const computedInitiative = manualInit ? finalInitiative : (initiativeRoll + modifier);
|
||||
const newParticipant = {
|
||||
const newParticipant = characterParticipant
|
||||
? { ...characterParticipant, initiative: computedInitiative }
|
||||
: {
|
||||
id: generateId(),
|
||||
name: nameToAdd,
|
||||
type: finalType,
|
||||
@@ -1304,8 +1310,8 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
initMod: modifier,
|
||||
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),
|
||||
hpFormula: hpFormula.trim() || null,
|
||||
ac: monsterAc !== '' ? parseInt(monsterAc, 10) : null,
|
||||
conditions: [],
|
||||
isActive: true,
|
||||
status: 'conscious',
|
||||
@@ -1347,26 +1353,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,
|
||||
initMod: modifier,
|
||||
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;
|
||||
@@ -2242,9 +2229,10 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
// INITIATIVE CONTROLS COMPONENT
|
||||
// ============================================================================
|
||||
|
||||
function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
function InitiativeControls({ campaignId, encounter, encounterPath, syncCharacters }) {
|
||||
const { showToast, showInfo } = useUIFeedback();
|
||||
const [showEndConfirm, setShowEndConfirm] = useState(false);
|
||||
const [endSyncCharacters, setEndSyncCharacters] = useState(false);
|
||||
const { data: activeDisplayData } = useFirestoreDocument(getPath.activeDisplay());
|
||||
const hidePlayerHp = activeDisplayData?.hidePlayerHp ?? true;
|
||||
const hideNpcHp = activeDisplayData?.hideNpcHp ?? false;
|
||||
@@ -2380,10 +2368,15 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
}
|
||||
};
|
||||
|
||||
const openEndConfirm = () => {
|
||||
setEndSyncCharacters(!!syncCharacters);
|
||||
setShowEndConfirm(true);
|
||||
};
|
||||
|
||||
const confirmEndEncounter = async () => {
|
||||
if (!db) return;
|
||||
try {
|
||||
const ctx = { ...buildCtx(encounterPath), campaignId };
|
||||
const ctx = { ...buildCtx(encounterPath), campaignId, syncCharacters: endSyncCharacters };
|
||||
if (campaignId) {
|
||||
ctx.campaignPath = getPath.campaign(campaignId);
|
||||
try {
|
||||
@@ -2439,7 +2432,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
<SkipForwardIcon size={16} className="mr-1 flex-shrink-0" /> <span className="truncate hidden lg:inline">Next Turn</span><span className="inline lg:hidden truncate">Next</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowEndConfirm(true)}
|
||||
onClick={openEndConfirm}
|
||||
className="w-full min-w-0 px-3 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-md transition-colors flex items-center justify-center"
|
||||
>
|
||||
<StopCircleIcon size={16} className="mr-1 flex-shrink-0" /> <span className="truncate hidden lg:inline">End Combat</span><span className="inline lg:hidden truncate">End</span>
|
||||
@@ -2508,7 +2501,20 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
onConfirm={confirmEndEncounter}
|
||||
title="End Encounter?"
|
||||
message="Are you sure you want to end this encounter? Turn position and round counter will reset (initiative values are kept). It will be removed from the Player Display."
|
||||
>
|
||||
<label className="flex items-start gap-3 p-3 rounded-md bg-stone-800 border border-stone-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={endSyncCharacters}
|
||||
onChange={(e) => setEndSyncCharacters(e.target.checked)}
|
||||
className="mt-0.5 h-4 w-4 text-amber-600 border-stone-400 rounded focus:ring-amber-500"
|
||||
/>
|
||||
<span>
|
||||
<span className="block text-sm font-medium text-stone-200">Update campaign characters with encounter HP, Max HP, and AC</span>
|
||||
<span className="block text-xs text-stone-400 mt-1">Applies only to this End Combat action.</span>
|
||||
</span>
|
||||
</label>
|
||||
</ConfirmationModal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -3012,6 +3018,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
|
||||
campaignId={campaignId}
|
||||
encounter={selectedEncounter}
|
||||
encounterPath={getPath.encounter(campaignId, selectedEncounter.id)}
|
||||
syncCharacters={!!campaignDoc?.syncCharacters}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Character encounter adds must use roster values written back at encounter end.
|
||||
// Both single-add and Add All previously reset Current HP to Max HP; Add All also lost AC.
|
||||
|
||||
import { screen, fireEvent, waitFor, within, act } from '@testing-library/react';
|
||||
import '@testing-library/jest-dom';
|
||||
import {
|
||||
renderApp, createCampaignViaUI, selectCampaignByName,
|
||||
createEncounterViaUI, selectEncounterByName, getParticipantForm, MOCK_DB,
|
||||
} from './testHelpers';
|
||||
|
||||
const campPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`;
|
||||
const encPath = (cid, eid) => `${campPath(cid)}/encounters/${eid}`;
|
||||
|
||||
async function setup(name) {
|
||||
await renderApp();
|
||||
const cid = await createCampaignViaUI(`${name} Camp`);
|
||||
await selectCampaignByName(`${name} Camp`);
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Wounded Hero' } });
|
||||
fireEvent.change(screen.getByLabelText('HP', { selector: '#defaultMaxHp' }), { target: { value: '30' } });
|
||||
fireEvent.change(screen.getByLabelText('AC', { selector: '#defaultAc' }), { target: { value: '18' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||
await screen.findByText('Wounded Hero');
|
||||
|
||||
// Values equivalent to end-encounter writeback.
|
||||
const campaign = MOCK_DB.get(campPath(cid));
|
||||
campaign.players = campaign.players.map(p => p.name === 'Wounded Hero'
|
||||
? { ...p, defaultMaxHp: 30, defaultCurrentHp: 11, defaultAc: 18 }
|
||||
: p);
|
||||
MOCK_DB.set(campPath(cid), campaign);
|
||||
await screen.findByText('Current HP 11');
|
||||
|
||||
const eid = await createEncounterViaUI(`${name} Encounter`);
|
||||
await selectEncounterByName(`${name} Encounter`);
|
||||
return { cid, eid };
|
||||
}
|
||||
|
||||
function expectWrittenDefaults(cid, eid) {
|
||||
const participant = MOCK_DB.get(encPath(cid, eid)).participants.find(p => p.name === 'Wounded Hero');
|
||||
expect(participant).toBeDefined();
|
||||
expect(participant.maxHp).toBe(30);
|
||||
expect(participant.currentHp).toBe(11);
|
||||
expect(participant.ac).toBe(18);
|
||||
}
|
||||
|
||||
describe('roster defaults used when adding character to encounter', () => {
|
||||
test('single character add uses written-back Current HP and AC', async () => {
|
||||
const { cid, eid } = await setup('Single Defaults');
|
||||
|
||||
await act(async () => { await new Promise(r => setTimeout(r, 250)); });
|
||||
let form = within(getParticipantForm());
|
||||
const typeSelect = form.getAllByRole('combobox').find(s => [...s.options].some(o => o.value === 'character'));
|
||||
fireEvent.change(typeSelect, { target: { value: 'character' } });
|
||||
|
||||
await act(async () => { await new Promise(r => setTimeout(r, 100)); });
|
||||
form = within(getParticipantForm());
|
||||
const characterSelect = form.getAllByRole('combobox').find(s => [...s.options].some(o => o.textContent.includes('Wounded Hero')));
|
||||
const option = [...characterSelect.options].find(o => o.textContent.includes('Wounded Hero'));
|
||||
fireEvent.change(characterSelect, { target: { value: option.value } });
|
||||
|
||||
await act(async () => { await new Promise(r => setTimeout(r, 250)); });
|
||||
fireEvent.click(within(getParticipantForm()).getByRole('button', { name: /Add to Encounter/i }));
|
||||
|
||||
await waitFor(() => expectWrittenDefaults(cid, eid));
|
||||
});
|
||||
|
||||
test('Add All uses written-back Current HP and AC', async () => {
|
||||
const { cid, eid } = await setup('Bulk Defaults');
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Add All \(Roll Init\)/i }));
|
||||
|
||||
await waitFor(() => expectWrittenDefaults(cid, eid));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
// End Encounter modal offers one-time character writeback choice.
|
||||
// Choice defaults from campaign preference but never changes that preference.
|
||||
|
||||
import { screen, fireEvent, waitFor, within } from '@testing-library/react';
|
||||
import '@testing-library/jest-dom';
|
||||
import {
|
||||
renderApp, createCampaignViaUI, selectCampaignByName,
|
||||
createEncounterViaUI, selectEncounterByName, startCombatViaUI, MOCK_DB,
|
||||
} from './testHelpers';
|
||||
|
||||
const campPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`;
|
||||
const encPath = (cid, eid) => `${campPath(cid)}/encounters/${eid}`;
|
||||
const syncLabel = /Update campaign characters with encounter HP, Max HP, and AC/i;
|
||||
|
||||
async function setup(name, persistentSync) {
|
||||
await renderApp();
|
||||
const cid = await createCampaignViaUI(`${name} Camp`);
|
||||
await selectCampaignByName(`${name} Camp`);
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Hero' } });
|
||||
fireEvent.change(screen.getByLabelText('HP', { selector: '#defaultMaxHp' }), { target: { value: '30' } });
|
||||
fireEvent.change(screen.getByLabelText('AC', { selector: '#defaultAc' }), { target: { value: '17' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||
await screen.findByText('Hero');
|
||||
|
||||
if (persistentSync) {
|
||||
fireEvent.click(screen.getByLabelText(/Sync character changes on encounter end/i));
|
||||
await waitFor(() => expect(MOCK_DB.get(campPath(cid)).syncCharacters).toBe(true));
|
||||
}
|
||||
|
||||
const eid = await createEncounterViaUI(`${name} Encounter`);
|
||||
await selectEncounterByName(`${name} Encounter`);
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Add All \(Roll Init\)/i }));
|
||||
await waitFor(() => expect(MOCK_DB.get(encPath(cid, eid)).participants).toHaveLength(1));
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Edit participant' }));
|
||||
const editModal = (await screen.findByRole('heading', { name: 'Edit Hero' })).closest('.fixed');
|
||||
const currentHp = within(editModal).getByText('Current HP', { selector: 'label' }).parentElement.querySelector('input');
|
||||
const ac = within(editModal).getByText('AC', { selector: 'label' }).parentElement.querySelector('input');
|
||||
fireEvent.change(currentHp, { target: { value: '11' } });
|
||||
fireEvent.change(ac, { target: { value: '19' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => {
|
||||
const hero = MOCK_DB.get(encPath(cid, eid)).participants[0];
|
||||
expect(hero.currentHp).toBe(11);
|
||||
expect(hero.ac).toBe(19);
|
||||
});
|
||||
|
||||
await startCombatViaUI();
|
||||
return { cid, eid };
|
||||
}
|
||||
|
||||
function openEndModal() {
|
||||
fireEvent.click(screen.getByRole('button', { name: /End Combat/i }));
|
||||
return screen.getByLabelText(syncLabel);
|
||||
}
|
||||
|
||||
describe('End Encounter one-time character sync choice', () => {
|
||||
test('defaults off, resets after cancel, can sync once without persisting preference', async () => {
|
||||
const { cid } = await setup('One Time Sync', false);
|
||||
|
||||
let checkbox = openEndModal();
|
||||
expect(checkbox).not.toBeChecked();
|
||||
fireEvent.click(checkbox);
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Cancel$/ }));
|
||||
expect(MOCK_DB.get(campPath(cid)).syncCharacters).not.toBe(true);
|
||||
|
||||
checkbox = openEndModal();
|
||||
expect(checkbox).not.toBeChecked();
|
||||
fireEvent.click(checkbox);
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Confirm$/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
const campaign = MOCK_DB.get(campPath(cid));
|
||||
const hero = campaign.players.find(p => p.name === 'Hero');
|
||||
expect(hero.defaultCurrentHp).toBe(11);
|
||||
expect(hero.defaultAc).toBe(19);
|
||||
expect(campaign.syncCharacters).not.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test('defaults on from preference; unchecking skips once without changing preference', async () => {
|
||||
const { cid } = await setup('Skip Once Sync', true);
|
||||
|
||||
const checkbox = openEndModal();
|
||||
expect(checkbox).toBeChecked();
|
||||
fireEvent.click(checkbox);
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Confirm$/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
const campaign = MOCK_DB.get(campPath(cid));
|
||||
const hero = campaign.players.find(p => p.name === 'Hero');
|
||||
expect(hero.defaultCurrentHp).not.toBe(11);
|
||||
expect(hero.defaultAc).toBe(17);
|
||||
expect(campaign.syncCharacters).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user