From 8ecd31d57027d644bc4afd3972710b86537cf4d2 Mon Sep 17 00:00:00 2001
From: david raistrick <1108844+keen99@users.noreply.github.com>
Date: Wed, 23 Sep 2026 16:24:46 -0400
Subject: [PATCH] feat: reroll initiative in participant editor with persisted
init mod
Add a dice button beside the Initiative field in the participant edit modal that rolls d20 + Init Mod; Cancel/Save guard accidental changes. Persist initMod on participant creation (quick-add monster, roster character/NPC, Add All) and expose it as an editable field in the modal. Roster NPCs added via the character dropdown now enter as npc type, and the duplicate guard keys on originalCharacterId regardless of type.
---
shared/turn.js | 3 +
src/App.js | 46 ++++++++++++---
src/tests/RerollInitiative.test.js | 92 ++++++++++++++++++++++++++++++
3 files changed, 134 insertions(+), 7 deletions(-)
create mode 100644 src/tests/RerollInitiative.test.js
diff --git a/shared/turn.js b/shared/turn.js
index 1bf119f..cdf94de 100644
--- a/shared/turn.js
+++ b/shared/turn.js
@@ -353,6 +353,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 || [],
@@ -378,6 +379,7 @@ function buildCharacterParticipant(character) {
type: character.isNpc ? 'npc' : 'character',
originalCharacterId: character.id,
initiative: finalInitiative,
+ initMod: modifier,
maxHp,
currentHp,
ac: character.defaultAc !== undefined ? character.defaultAc : null,
@@ -407,6 +409,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,
diff --git a/src/App.js b/src/App.js
index c699056..3e1fff3 100644
--- a/src/App.js
+++ b/src/App.js
@@ -606,6 +606,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 || '');
@@ -627,6 +628,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,
@@ -650,15 +652,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"
+ />
+
+
+
p.type === 'character' && p.originalCharacterId === selectedCharacterId)) {
+ if (participants.some(p => p.originalCharacterId === selectedCharacterId)) {
showInfo(`${character.name} is already in this encounter.`);
return;
}
@@ -1249,13 +1273,20 @@ 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,
+ type: finalType,
+ originalCharacterId: ['character', 'npc'].includes(finalType) ? selectedCharacterId : null,
initiative: computedInitiative,
+ initMod: modifier,
maxHp: currentMaxHp,
currentHp: currentMaxHp,
hpFormula: participantType === 'monster' ? (hpFormula.trim() || null) : null,
@@ -1311,6 +1342,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
type: 'character',
originalCharacterId: char.id,
initiative: finalInitiative,
+ initMod: modifier,
maxHp: char.defaultMaxHp || DEFAULT_MAX_HP,
currentHp: char.defaultMaxHp || DEFAULT_MAX_HP,
conditions: [],
diff --git a/src/tests/RerollInitiative.test.js b/src/tests/RerollInitiative.test.js
new file mode 100644
index 0000000..e2d90e7
--- /dev/null
+++ b/src/tests/RerollInitiative.test.js
@@ -0,0 +1,92 @@
+// Reroll initiative: per-participant dice button for non-player (monster/npc).
+// Player characters keep manual initiative only.
+
+import { screen, fireEvent, waitFor, within, act } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import { getCalls } from '../__mocks__/firebase/_mock-db';
+import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, addMonsterViaUI, setupReady, getParticipantForm } from './testHelpers';
+
+function lastParticipantWrite(name) {
+ const calls = getCalls().filter(c => c.path.includes('/encounters/'));
+ const withFn = getCalls().filter(c => (c.fn === 'setDoc' || c.fn === 'updateDoc' || c.fn === 'batchWrite') && c.path.includes('/encounters/'));
+ const latest = withFn[withFn.length - 1];
+ const parts = latest?.data?.participants || [];
+ return parts.find(p => p.name === name);
+}
+
+async function addCharacterViaUI(name = 'Hero', initMod = 2) {
+ fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: name } });
+ fireEvent.change(screen.getByLabelText(/Init Mod/i, { selector: '#defaultInitMod' }), { target: { value: String(initMod) } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
+ await screen.findByText(name);
+}
+
+describe('reroll initiative button', () => {
+ test('monster card has reroll; character card does not; reroll writes d20+mod', async () => {
+ await setupReady('RerollCamp', 'RerollEnc');
+ await addMonsterViaUI('Dire Wolf', 30, 5);
+ await addCharacterViaUI('Hero', 2);
+ fireEvent.click(screen.getByRole('button', { name: /Add All \(Roll Init\)/i }));
+
+ // NO reroll button on card
+ expect(screen.queryByTitle('Reroll initiative for Dire Wolf')).not.toBeInTheDocument();
+ });
+
+ test('editor reroll rolls d20+mod, saves on Save; card stays clean', async () => {
+ await setupReady('RerollCamp2', 'RerollEnc2');
+ await addMonsterViaUI('Goblin', 7, 2);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit participant' }));
+ const modInput = await screen.findByLabelText('Init Mod', { selector: '#edit-initmod' });
+ const initInput = screen.getByLabelText('Initiative', { selector: '#edit-initiative' });
+ const before = parseInt(initInput.value, 10);
+
+ const rerollBtn = screen.getByRole('button', { name: 'Reroll initiative' });
+ for (let i = 0; i < 10 && parseInt(initInput.value, 10) === before; i++) {
+ fireEvent.click(rerollBtn);
+ }
+ const rolled = parseInt(initInput.value, 10);
+ const mod = parseInt(modInput.value || '0', 10);
+ expect(rolled).not.toBe(before);
+ expect(rolled).toBeGreaterThanOrEqual(mod + 1);
+ expect(rolled).toBeLessThanOrEqual(mod + 20);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => {
+ const p = lastParticipantWrite('Goblin');
+ expect(p.initiative).toBe(rolled);
+ });
+ // still nothing on card after save
+ expect(screen.queryByTitle(/Reroll initiative for Goblin/)).not.toBeInTheDocument();
+ });
+
+ test('npc from roster keeps default init mod for reroll', async () => {
+ await renderApp();
+ await createCampaignViaUI('NpcCamp');
+ await selectCampaignByName('NpcCamp');
+ await createEncounterViaUI('NpcEnc');
+
+ // roster NPC: name + init mod + isNpc checkbox
+ fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Bartender' } });
+ fireEvent.change(screen.getByLabelText(/Init Mod/i, { selector: '#defaultInitMod' }), { target: { value: '1' } });
+ fireEvent.click(screen.getByLabelText(/Long-lived NPC/i));
+ fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
+ await screen.findByText('Bartender');
+ // Add All skips roster NPCs — add via character dropdown instead.
+ // Background rerenders replace form nodes mid-test; settle, then re-query fresh.
+ await act(async () => { await new Promise(r => setTimeout(r, 250)); });
+ const selects = within(getParticipantForm()).getAllByRole('combobox');
+ const typeSel = selects.find(s => [...s.options].some(o => o.value === 'character'));
+ fireEvent.change(typeSel, { target: { value: 'character' } });
+ await act(async () => { await new Promise(r => setTimeout(r, 50)); });
+ const charSel = within(getParticipantForm()).getAllByRole('combobox').find(s => [...s.options].some(o => o.textContent.includes('Bartender')));
+ fireEvent.change(charSel, { target: { value: [...charSel.options].find(o => o.textContent.includes('Bartender')).value } });
+ await act(async () => { await new Promise(r => setTimeout(r, 300)); });
+ const addBtn = within(getParticipantForm()).getByRole('button', { name: /Add to Encounter \(Roll Init\)/i });
+ await act(async () => { fireEvent.click(addBtn); });
+
+ // no reroll button on card for NPC either
+ expect(screen.queryByTitle(/Reroll initiative for Bartender/)).not.toBeInTheDocument();
+ });
+
+});