From 83693d4aa9d079d045eb4fee2133a72bd673bb6d Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Wed, 23 Sep 2026 10:56:51 -0400 Subject: [PATCH 01/14] feat: group encounter list into In Progress / Ready / Completed sections Completed encounters collapse behind a toggle so reusable ended encounters stay reachable without cluttering the active list. Group headers show counts. Cards keep drag-reorder, player-display toggle, live badge, and delete controls. --- src/App.js | 115 ++++++++++++++++++++++++++++-- src/tests/EncounterGroups.test.js | 79 ++++++++++++++++++++ 2 files changed, 189 insertions(+), 5 deletions(-) create mode 100644 src/tests/EncounterGroups.test.js diff --git a/src/App.js b/src/App.js index 7712fd2..217da80 100644 --- a/src/App.js +++ b/src/App.js @@ -9,7 +9,7 @@ import { 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 + Undo2, Redo2, Crosshair, Pencil } from 'lucide-react'; // ----- UI feedback: toast (transient) + info modal (persistent) ----- @@ -2428,6 +2428,32 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac }); const [showCreateModal, setShowCreateModal] = useState(false); const [encounterFullscreen, setEncounterFullscreen] = useState(false); + const [completedOpen, setCompletedOpen] = useState(false); + const [renamingId, setRenamingId] = useState(null); + const [renameValue, setRenameValue] = useState(''); + + const startRename = (encounter) => { + setRenamingId(encounter.id); + setRenameValue(encounter.name); + }; + + const cancelRename = () => { + setRenamingId(null); + setRenameValue(''); + }; + + const commitRename = async (encounterId) => { + const trimmed = renameValue.trim(); + if (trimmed && db && campaignId) { + try { + await storage.updateDoc(`${getPath.campaigns()}/${campaignId}/encounters/${encounterId}`, { name: trimmed }); + } catch (err) { + console.error('Error renaming encounter:', err); + showToast('Failed to rename encounter. Please try again.'); + } + } + cancelRename(); + }; const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [itemToDelete, setItemToDelete] = useState(null); const [draggedEncounterId, setDraggedEncounterId] = useState(null); @@ -2643,8 +2669,12 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac

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; @@ -2661,7 +2691,40 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac >
setSelectedEncounterId(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 +2752,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"> diff --git a/src/tests/EncounterGroups.test.js b/src/tests/EncounterGroups.test.js new file mode 100644 index 0000000..b3297d4 --- /dev/null +++ b/src/tests/EncounterGroups.test.js @@ -0,0 +1,79 @@ +// Encounter list groups: In Progress / Ready / Completed. +// Completed collapsed by default. Group headers show counts. + +import { screen, fireEvent, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { MOCK_DB } from '../__mocks__/firebase/_mock-db'; +import { renderApp, createCampaignViaUI, selectCampaignByName } from './testHelpers'; + +const encPath = (cid, eid) => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`; + +async function seedEncounter(cid, eid, fields) { + act(() => { + MOCK_DB.set(encPath(cid, eid), { + id: eid, + name: fields.name, + participants: [], + round: 0, + isStarted: false, + isPaused: false, + createdAt: fields.createdAt || '2026-07-01T00:00:00Z', + order: fields.order, + ...fields, + }); + // touch collection so useFirestoreCollection snapshot re-emits + MOCK_DB.set(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}`, { name: cid, players: [] }); + }); +} + +describe('encounter list grouping', () => { + test('groups appear with counts: In Progress, Ready, Completed', async () => { + await renderApp(); + const cid = await createCampaignViaUI('GroupCamp'); + await selectCampaignByName('GroupCamp'); + + act(() => { + MOCK_DB.set(encPath(cid, 'e-ready'), { id: 'e-ready', name: 'Ready One', participants: [], round: 0, isStarted: false, isPaused: false, createdAt: '2026-07-01T00:00:00Z' }); + MOCK_DB.set(encPath(cid, 'e-prog'), { id: 'e-prog', name: 'Live One', participants: [], round: 0, isStarted: true, startedAt: 1, isPaused: false, createdAt: '2026-07-01T00:00:00Z' }); + MOCK_DB.set(encPath(cid, 'e-done'), { id: 'e-done', name: 'Old One', participants: [], round: 0, isStarted: false, startedAt: 1, endedAt: 2, isPaused: false, createdAt: '2026-07-01T00:00:00Z' }); + MOCK_DB.set(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}`, { name: cid, players: [] }); + }); + + // gate on card text first (groups render), then headers. + // 'Old One' lives in collapsed Completed group — assert after expanding. + await screen.findByText('Live One'); + await screen.findByText('Ready One'); + expect(screen.getByRole('button', { name: /⚔ In Progress/ })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^Ready/ })).toBeInTheDocument(); + const completedBtn = screen.getByRole('button', { name: /^Completed/ }); + expect(completedBtn).toBeInTheDocument(); + fireEvent.click(completedBtn); + expect(await screen.findByText('Old One')).toBeInTheDocument(); + }); + + test('completed encounters hidden until group expanded', async () => { + await renderApp(); + const cid = await createCampaignViaUI('GroupCamp2'); + await selectCampaignByName('GroupCamp2'); + + await seedEncounter(cid, 'e-done2', { name: 'Hidden Corpse', isStarted: false, startedAt: 1, endedAt: 2 }); + + expect(await screen.findByRole('button', { name: /^Completed/ })).toBeInTheDocument(); + expect(screen.queryByText('Hidden Corpse')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /^Completed/ })); + expect(await screen.findByText('Hidden Corpse')).toBeInTheDocument(); + }); + + test('in-progress and ready encounters visible by default', async () => { + await renderApp(); + const cid = await createCampaignViaUI('GroupCamp3'); + await selectCampaignByName('GroupCamp3'); + + await seedEncounter(cid, 'e-ready3', { name: 'Visible Ready', isStarted: false }); + await seedEncounter(cid, 'e-prog3', { name: 'Visible Live', isStarted: true, startedAt: 1 }); + + expect(await screen.findByText('Visible Ready')).toBeInTheDocument(); + expect(screen.getByText('Visible Live')).toBeInTheDocument(); + }); +}); -- 2.43.0 From 6122c19cf12b44445e8e0c76fd842bdfbdb546db Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Wed, 23 Sep 2026 10:57:09 -0400 Subject: [PATCH 02/14] feat: inline rename for encounters Pencil button on each encounter card opens an inline input prefilled with the current name. Enter or the save button commits via updateDoc; Escape or the cancel button discards. Empty/whitespace names are ignored. Covers save, cancel, and empty-name cases in tests. --- src/tests/EncounterRename.test.js | 78 +++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/tests/EncounterRename.test.js diff --git a/src/tests/EncounterRename.test.js b/src/tests/EncounterRename.test.js new file mode 100644 index 0000000..2478c32 --- /dev/null +++ b/src/tests/EncounterRename.test.js @@ -0,0 +1,78 @@ +// Encounter rename: pencil button on card opens inline input, saves via updateDoc. +// NOTE: background snapshot rerenders can replace the input/form DOM nodes mid-test, +// so every interaction re-queries the live node (fresh()). + +import { screen, fireEvent, act, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, MOCK_DB } from './testHelpers'; + +const encPath = (cid, eid) => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`; + +const fresh = () => screen.getByLabelText('Encounter name'); +const freshQuery = () => screen.queryByLabelText('Encounter name'); + +async function openRename() { + await screen.findByTitle('Rename Encounter'); + // settle async rerenders (fetchDetails etc.) so click hits live node + await act(async () => { await new Promise(r => setTimeout(r, 250)); }); + fireEvent.click(screen.getByTitle('Rename Encounter')); + await waitFor(() => expect(fresh()).toBeInTheDocument()); +} + +describe('encounter rename', () => { + test('pencil opens inline edit prefilled; Enter saves to Firestore doc', async () => { + await renderApp(); + const cid = await createCampaignViaUI('RenameCamp'); + await selectCampaignByName('RenameCamp'); + const eid = await createEncounterViaUI('Old Name'); + + await openRename(); + expect(await screen.findByDisplayValue('Old Name')).toBeInTheDocument(); + + fireEvent.change(fresh(), { target: { value: 'New Name' } }); + await waitFor(() => expect(fresh().value).toBe('New Name')); + // eslint-disable-next-line testing-library/no-node-access + fireEvent.submit(fresh().closest('form')); + + await screen.findByText('New Name'); + expect(MOCK_DB.get(encPath(cid, eid)).name).toBe('New Name'); + expect(freshQuery()).not.toBeInTheDocument(); + }); + + test('Escape cancels without changing doc', async () => { + await renderApp(); + const cid = await createCampaignViaUI('RenameCamp2'); + await selectCampaignByName('RenameCamp2'); + const eid = await createEncounterViaUI('Keep Me'); + + await openRename(); + expect(await screen.findByDisplayValue('Keep Me')).toBeInTheDocument(); + + fireEvent.change(fresh(), { target: { value: 'Discard' } }); + await waitFor(() => expect(fresh().value).toBe('Discard')); + fireEvent.keyDown(fresh(), { key: 'Escape', code: 'Escape' }); + + await screen.findByText('Keep Me'); + expect(MOCK_DB.get(encPath(cid, eid)).name).toBe('Keep Me'); + expect(screen.queryByDisplayValue('Discard')).not.toBeInTheDocument(); + }); + + test('empty name ignored on save', async () => { + await renderApp(); + const cid = await createCampaignViaUI('RenameCamp3'); + await selectCampaignByName('RenameCamp3'); + const eid = await createEncounterViaUI('Real Name'); + + await openRename(); + expect(await screen.findByDisplayValue('Real Name')).toBeInTheDocument(); + + fireEvent.change(fresh(), { target: { value: ' ' } }); + await waitFor(() => expect(fresh().value).toBe(' ')); + // eslint-disable-next-line testing-library/no-node-access + fireEvent.submit(fresh().closest('form')); + + await screen.findByText('Real Name'); + expect(MOCK_DB.get(encPath(cid, eid)).name).toBe('Real Name'); + expect(freshQuery()).not.toBeInTheDocument(); + }); +}); -- 2.43.0 From 3b166403e8ced89aa5495ae008237ec8df5b7e0c Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Wed, 23 Sep 2026 12:20:18 -0400 Subject: [PATCH 03/14] feat: add configurable encounter popout and completed collapse Open selected encounters in a focused full-page panel by default, with a Back control and scroll lock. Add per-device switches in the Encounters header to disable open-on-top or completed-group collapsing. Cover selection, return-to-list, display updates, and preference persistence. --- src/App.js | 73 ++++++++++++++++++++--- src/tests/EncounterPopout.test.js | 69 ++++++++++++++++++++++ src/tests/EncounterPreferences.test.js | 81 ++++++++++++++++++++++++++ 3 files changed, 214 insertions(+), 9 deletions(-) create mode 100644 src/tests/EncounterPopout.test.js create mode 100644 src/tests/EncounterPreferences.test.js diff --git a/src/App.js b/src/App.js index 217da80..0c56326 100644 --- a/src/App.js +++ b/src/App.js @@ -2428,7 +2428,28 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac }); const [showCreateModal, setShowCreateModal] = useState(false); const [encounterFullscreen, setEncounterFullscreen] = useState(false); + const [openOnTop, setOpenOnTop] = useState(() => { + try { return localStorage.getItem('ttrpg.openEncountersOnTop') !== 'false'; } + catch { return true; } + }); + const [collapseCompleted, setCollapseCompleted] = useState(() => { + try { return localStorage.getItem('ttrpg.collapseCompletedEncounters') !== 'false'; } + catch { return true; } + }); const [completedOpen, setCompletedOpen] = useState(false); + + const toggleOpenOnTop = () => { + const next = !openOnTop; + setOpenOnTop(next); + try { localStorage.setItem('ttrpg.openEncountersOnTop', String(next)); } catch {} + }; + + const toggleCollapseCompleted = () => { + const next = !collapseCompleted; + setCollapseCompleted(next); + setCompletedOpen(false); + try { localStorage.setItem('ttrpg.collapseCompletedEncounters', String(next)); } catch {} + }; const [renamingId, setRenamingId] = useState(null); const [renameValue, setRenameValue] = useState(''); @@ -2459,9 +2480,32 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac const [draggedEncounterId, setDraggedEncounterId] = useState(null); const selectedEncounterIdRef = useRef(selectedEncounterId); + const closedEncounterRef = useRef(false); + + const openEncounter = (encounterId) => { + closedEncounterRef.current = false; + setSelectedEncounterId(encounterId); + setEncounterFullscreen(openOnTop); + }; + + const closeEncounter = () => { + closedEncounterRef.current = true; + setEncounterFullscreen(false); + setSelectedEncounterId(null); + selectedEncounterIdRef.current = null; + }; + + useEffect(() => { + if (!encounterFullscreen) return undefined; + const previousOverflow = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + return () => { document.body.style.overflow = previousOverflow; }; + }, [encounterFullscreen]); // Restore scoped encounter selection when campaign changes. useEffect(() => { + closedEncounterRef.current = false; + setEncounterFullscreen(false); if (!campaignId) { setSelectedEncounterId(null); return; } try { const saved = localStorage.getItem(`ttrpg.selectedEncounter.${campaignId}`) || null; @@ -2531,7 +2575,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac if (encounters && encounters.length > 0) { const currentSelection = selectedEncounterIdRef.current; - if (currentSelection === null || !encounters.some(e => e.id === currentSelection)) { + if (!closedEncounterRef.current && (currentSelection === null || !encounters.some(e => e.id === currentSelection))) { if (initialActiveEncounterId && encounters.some(e => e.id === initialActiveEncounterId)) { setSelectedEncounterId(initialActiveEncounterId); } else if ( @@ -2664,6 +2708,16 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac Create Encounter +
+ + +
{(!encounters || encounters.length === 0) && (

No encounters yet.

@@ -2690,7 +2744,7 @@ 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); }} @@ -2806,7 +2860,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac groups.push(); } if (completed.length > 0) { - groups.push( setCompletedOpen(v => !v)} />); + groups.push( setCompletedOpen(v => !v)} />); } return
{groups}
; })()} @@ -2823,8 +2877,8 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac )} {selectedEncounter && ( -
-

+
+

Managing Encounter: {selectedEncounter.name}

diff --git a/src/tests/EncounterPopout.test.js b/src/tests/EncounterPopout.test.js new file mode 100644 index 0000000..b8a9a30 --- /dev/null +++ b/src/tests/EncounterPopout.test.js @@ -0,0 +1,69 @@ +import { screen, fireEvent, waitFor, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, MOCK_DB } from './testHelpers'; + +async function setup(name = 'Popout Enc') { + await renderApp(); + await createCampaignViaUI('Popout Camp'); + await selectCampaignByName('Popout Camp'); + await createEncounterViaUI(name); + await screen.findByText(name); +} + +describe('encounter open-on-top', () => { + test('clicking encounter card opens fixed overlay; back returns to list and clears selection', async () => { + await setup(); + fireEvent.click(screen.getByText('Popout Enc')); + + const popout = await screen.findByTestId('encounter-popout'); + expect(popout).toHaveClass('fixed', 'inset-0', 'overflow-y-auto'); + expect(document.body.style.overflow).toBe('hidden'); + const back = screen.getByRole('button', { name: 'Back to encounters' }); + expect(back).toHaveClass('min-h-[40px]'); + expect(screen.getByRole('heading', { level: 3, name: /Managing Encounter: Popout Enc/ })).toHaveClass('sticky', 'top-0'); + + fireEvent.click(screen.getByRole('button', { name: 'Back to encounters' })); + await waitFor(() => expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument()); + expect(document.body.style.overflow).toBe(''); + expect(screen.queryByText(/Managing Encounter:/)).not.toBeInTheDocument(); + expect(screen.getByText('Popout Enc')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^Ready/ })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Create Encounter/ })).toBeInTheDocument(); + }); + + test('creating encounter does not cover list; clicking card opens it', async () => { + await setup('Fresh Enc'); + expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument(); + fireEvent.click(screen.getByText('Fresh Enc')); + expect(await screen.findByTestId('encounter-popout')).toBeInTheDocument(); + }); + + test('Back stays on list when displayed encounter receives another snapshot', async () => { + await renderApp(); + const cid = await createCampaignViaUI('Live Popout Camp'); + await selectCampaignByName('Live Popout Camp'); + const eid = await createEncounterViaUI('Live Popout Enc'); + await screen.findByText('Live Popout Enc'); + + fireEvent.click(screen.getByTitle('Activate for Player Display')); + await waitFor(() => expect(MOCK_DB.get('artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status')?.activeEncounterId).toBe(eid)); + fireEvent.click(screen.getByText('Live Popout Enc')); + await screen.findByTestId('encounter-popout'); + fireEvent.click(screen.getByRole('button', { name: 'Back to encounters' })); + await waitFor(() => expect(screen.queryByText(/Managing Encounter:/)).not.toBeInTheDocument()); + + act(() => { + MOCK_DB.merge(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`, { round: 2 }); + }); + expect(screen.queryByText(/Managing Encounter:/)).not.toBeInTheDocument(); + expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument(); + expect(localStorage.getItem(`ttrpg.selectedEncounter.${cid}`)).toBeNull(); + }); + + test('rename action stays on list instead of opening popout', async () => { + await setup('Rename Me'); + fireEvent.click(screen.getByTitle('Rename Encounter')); + expect(await screen.findByDisplayValue('Rename Me')).toBeInTheDocument(); + expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument(); + }); +}); diff --git a/src/tests/EncounterPreferences.test.js b/src/tests/EncounterPreferences.test.js new file mode 100644 index 0000000..e069c1d --- /dev/null +++ b/src/tests/EncounterPreferences.test.js @@ -0,0 +1,81 @@ +import { screen, fireEvent, act, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, MOCK_DB } from './testHelpers'; + +const OPEN_KEY = 'ttrpg.openEncountersOnTop'; +const COLLAPSE_KEY = 'ttrpg.collapseCompletedEncounters'; + +beforeEach(() => { + localStorage.removeItem(OPEN_KEY); + localStorage.removeItem(COLLAPSE_KEY); +}); +afterEach(() => { + localStorage.removeItem(OPEN_KEY); + localStorage.removeItem(COLLAPSE_KEY); +}); + +async function setup(name = 'Preference Enc') { + await renderApp(); + const cid = await createCampaignViaUI('Preference Camp'); + await selectCampaignByName('Preference Camp'); + const eid = await createEncounterViaUI(name); + await screen.findByText(name); + return { cid, eid }; +} + +describe('encounter view preferences', () => { + test('Open on top switch defaults on; off keeps card selection inline; on restores popout', async () => { + await setup(); + const toggle = screen.getByRole('switch', { name: 'Open on top' }); + expect(toggle).toBeChecked(); + + fireEvent.click(toggle); + expect(toggle).not.toBeChecked(); + expect(localStorage.getItem(OPEN_KEY)).toBe('false'); + fireEvent.click(screen.getByText('Preference Enc')); + expect(screen.getByText(/Managing Encounter: Preference Enc/)).toBeInTheDocument(); + expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument(); + + fireEvent.click(toggle); + expect(toggle).toBeChecked(); + expect(localStorage.getItem(OPEN_KEY)).toBe('true'); + fireEvent.click(screen.getByText('Preference Enc')); + expect(await screen.findByTestId('encounter-popout')).toBeInTheDocument(); + }); + + test('Collapse completed switch defaults on; off shows completed cards; on collapses again', async () => { + const { cid, eid } = await setup('Finished Enc'); + act(() => { + MOCK_DB.merge(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`, { endedAt: 2 }); + }); + const toggle = screen.getByRole('switch', { name: 'Collapse completed' }); + expect(toggle).toBeChecked(); + expect(await screen.findByRole('button', { name: /^Completed/ })).toHaveAttribute('aria-expanded', 'false'); + expect(screen.queryByText('Finished Enc')).not.toBeInTheDocument(); + + fireEvent.click(toggle); + expect(toggle).not.toBeChecked(); + expect(localStorage.getItem(COLLAPSE_KEY)).toBe('false'); + expect(await screen.findByText('Finished Enc')).toBeInTheDocument(); + + fireEvent.click(toggle); + expect(toggle).toBeChecked(); + expect(localStorage.getItem(COLLAPSE_KEY)).toBe('true'); + await waitFor(() => expect(screen.queryByText('Finished Enc')).not.toBeInTheDocument()); + }); + + test('saved off preferences load on mount', async () => { + localStorage.setItem(OPEN_KEY, 'false'); + localStorage.setItem(COLLAPSE_KEY, 'false'); + const { cid, eid } = await setup('Saved Enc'); + expect(screen.getByRole('switch', { name: 'Open on top' })).not.toBeChecked(); + expect(screen.getByRole('switch', { name: 'Collapse completed' })).not.toBeChecked(); + + act(() => { + MOCK_DB.merge(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`, { endedAt: 3 }); + }); + expect(await screen.findByText('Saved Enc')).toBeInTheDocument(); + fireEvent.click(screen.getByText('Saved Enc')); + expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument(); + }); +}); -- 2.43.0 From e8a0ba2b60e876d68900745429018a5ad6c5ba6a Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:38:19 -0400 Subject: [PATCH 04/14] chore: add bee-targeted Docker restart wrapper --- docker/restart-bee.sh | 4 ++++ 1 file changed, 4 insertions(+) create mode 100755 docker/restart-bee.sh 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" -- 2.43.0 From f5b387beb5537fa5d206631d37c6e036c6c01398 Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Wed, 23 Sep 2026 15:07:23 -0400 Subject: [PATCH 05/14] feat: edit campaign creation settings Add an Edit action to campaign cards with a prefilled form for name, player-display background URL, and default ruleset. Update only those campaign fields, preserving roster and existing encounter rulesets. Cover save, clearing values, cancel, and invalid name. --- src/App.js | 81 +++++++++++++++++++++++++--------- src/tests/CampaignEdit.test.js | 77 ++++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+), 20 deletions(-) create mode 100644 src/tests/CampaignEdit.test.js diff --git a/src/App.js b/src/App.js index 0c56326..ad5d86b 100644 --- a/src/App.js +++ b/src/App.js @@ -450,16 +450,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 +500,7 @@ function CreateCampaignForm({ onCreate, onCancel }) { Generic (no death saves, negative HP)
+ {campaign &&

Default for new encounters. Existing encounters keep their ruleset.

}

@@ -514,9 +513,10 @@ function CreateCampaignForm({ onCreate, onCancel }) {
@@ -3087,6 +3087,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(() => { @@ -3193,6 +3194,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); @@ -3280,6 +3296,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...

; @@ -3401,15 +3418,28 @@ function AdminView({ userId }) {
)}
- +
+ + +
setShowCreateModal(false)} title="Create New Campaign"> - setShowCreateModal(false)} /> )} + {editingCampaign && ( + setEditingCampaignId(null)} title="Edit Campaign"> + handleUpdateCampaign(editingCampaign.id, name, backgroundUrl, ruleset)} + onCancel={() => setEditingCampaignId(null)} + /> + + )} + {selectedCampaign && (

diff --git a/src/tests/CampaignEdit.test.js b/src/tests/CampaignEdit.test.js new file mode 100644 index 0000000..f5ed2e6 --- /dev/null +++ b/src/tests/CampaignEdit.test.js @@ -0,0 +1,77 @@ +import { screen, fireEvent, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { renderApp, createCampaignViaUI, MOCK_DB } from './testHelpers'; + +const campaignPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`; + +async function setup(name = 'Original Camp') { + await renderApp(); + const id = await createCampaignViaUI(name); + await screen.findByRole('heading', { name: name, level: 3 }); + return id; +} + +async function openEditor(name = 'Original Camp') { + fireEvent.click(await screen.findByRole('button', { name: `Edit campaign ${name}` })); + await screen.findByRole('heading', { name: 'Edit Campaign' }); +} + +describe('edit campaign creation settings', () => { + test('prefills name, background URL, ruleset; saves only those fields', async () => { + const id = await setup(); + await openEditor(); + expect(screen.getByLabelText('Campaign Name')).toHaveValue('Original Camp'); + expect(screen.getByLabelText('Player Display Background URL (Optional)')).toHaveValue(''); + expect(screen.getByRole('radio', { name: /D&D 5e/ })).toBeChecked(); + + fireEvent.change(screen.getByLabelText('Campaign Name'), { target: { value: 'Renamed Camp' } }); + fireEvent.change(screen.getByLabelText('Player Display Background URL (Optional)'), { target: { value: 'https://example.com/bg.jpg' } }); + fireEvent.click(screen.getByRole('radio', { name: /Generic/ })); + fireEvent.click(screen.getByRole('button', { name: 'Save Campaign' })); + + await waitFor(() => expect(MOCK_DB.get(campaignPath(id))).toMatchObject({ + name: 'Renamed Camp', + playerDisplayBackgroundUrl: 'https://example.com/bg.jpg', + ruleset: 'generic', + players: [], + ownerId: expect.any(String), + createdAt: expect.any(String), + })); + expect(await screen.findByRole('heading', { name: 'Renamed Camp', level: 3 })).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'Edit Campaign' })).not.toBeInTheDocument(); + }); + + test('clears existing background and switches ruleset back, preserving roster', async () => { + const id = await setup('Changes Camp'); + // First save an existing background and generic ruleset through editor. + await openEditor('Changes Camp'); + fireEvent.change(screen.getByLabelText('Player Display Background URL (Optional)'), { target: { value: 'https://example.com/old.jpg' } }); + fireEvent.click(screen.getByRole('radio', { name: /Generic/ })); + fireEvent.click(screen.getByRole('button', { name: 'Save Campaign' })); + await waitFor(() => expect(MOCK_DB.get(campaignPath(id)).ruleset).toBe('generic')); + + await openEditor('Changes Camp'); + expect(screen.getByLabelText('Player Display Background URL (Optional)')).toHaveValue('https://example.com/old.jpg'); + expect(screen.getByRole('radio', { name: /Generic/ })).toBeChecked(); + fireEvent.change(screen.getByLabelText('Player Display Background URL (Optional)'), { target: { value: '' } }); + fireEvent.click(screen.getByRole('radio', { name: /D&D 5e/ })); + fireEvent.click(screen.getByRole('button', { name: 'Save Campaign' })); + + await waitFor(() => expect(MOCK_DB.get(campaignPath(id))).toMatchObject({ + playerDisplayBackgroundUrl: '', ruleset: '5e', players: [], + })); + }); + + test('Cancel leaves campaign unchanged; whitespace-only name cannot save', async () => { + const id = await setup('Keep Camp'); + await openEditor('Keep Camp'); + fireEvent.change(screen.getByLabelText('Campaign Name'), { target: { value: 'Discard Camp' } }); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(MOCK_DB.get(campaignPath(id)).name).toBe('Keep Camp'); + + await openEditor('Keep Camp'); + fireEvent.change(screen.getByLabelText('Campaign Name'), { target: { value: ' ' } }); + expect(screen.getByRole('button', { name: 'Save Campaign' })).toBeDisabled(); + expect(MOCK_DB.get(campaignPath(id)).name).toBe('Keep Camp'); + }); +}); -- 2.43.0 From 05e8c262b77f2268a5a5e21ec753a150b28c5db7 Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Wed, 23 Sep 2026 15:31:55 -0400 Subject: [PATCH 06/14] feat: stateful caffeine button with icon-only display Replace moon/coffee action-label toggle with coffee icon plus slash overlay. ON shows amber; OFF shows a slash with no color. Accessible name (Caffeine ON/OFF) and aria-pressed carry state. Applied to admin header, encounter header, and both player display states. --- src/App.js | 66 ++++++++++++++++-------------- src/tests/CaffeineControls.test.js | 59 ++++++++++++++++++++++++++ src/tests/ScreenControls.test.js | 4 +- 3 files changed, 97 insertions(+), 32 deletions(-) create mode 100644 src/tests/CaffeineControls.test.js diff --git a/src/App.js b/src/App.js index ad5d86b..c699056 100644 --- a/src/App.js +++ b/src/App.js @@ -8,7 +8,7 @@ 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, + Maximize2, Minimize2, PanelTopOpen, PanelTopClose, Coffee, Clock, ChevronRight, X, Undo2, Redo2, Crosshair, Pencil } from 'lucide-react'; @@ -338,6 +338,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) => { @@ -2881,14 +2903,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac

Managing Encounter: {selectedEncounter.name} - +
- + setWakeLockEnabled(v => { localStorage.setItem('ttrpg.wakeLock', String(!v)); return !v; })} + /> + setWakeLockEnabled(v => { localStorage.setItem('ttrpg.wakeLock', String(!v)); return !v; })} + /> + setWakeLockEnabled(v => { localStorage.setItem('ttrpg.wakeLock', String(!v)); return !v; })} + />
- + 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(); + }); + +}); -- 2.43.0 From 8d71f0ba4b7be5273a9a811070c22548115f4d80 Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Wed, 23 Sep 2026 20:39:28 -0400 Subject: [PATCH 08/14] feat: death-save display, stable-hour recovery, reroll-all initiative - Player display: death-save pips for dying participants (3 successes / 3 failures), stable shows note without pips - stableRegainHours: 1d4 hours rolled on natural stabilization (3rd save success, manual stabilize, revive-to-stable); cleared on heal, damage-while-stable, inline HP edit, and death; undo/redo round-trips through all paths - Roster writeback: end-of-encounter sync writes stable hours to characters (stable -> hours, conscious -> null); character card badge shows hours; stable state carried into new encounters via buildCharacterParticipant; editor Cur HP > 0 clears - End-combat message corrected: states turn position and round reset while initiative values are kept - Reroll All Initiative: d20 + initMod for every participant in a single write, undoable, pre-combat or paused only; confirmation modal in UI, hidden during active combat - Add All (Roll Init) hoisted to Add Participants header row so it stays visible when the section is collapsed; header title remains the collapse toggle --- shared/tests/turn.rerollall.test.js | 78 ++++++++++++ shared/tests/turn.stablehours.test.js | 99 +++++++++++++++ shared/tests/turn.writeback.test.js | 68 ++++++++++ shared/turn.js | 80 ++++++++++-- src/App.js | 152 +++++++++++++++++++---- src/tests/DisplayView.deathsaves.test.js | 88 +++++++++++++ src/tests/EncounterRerollAll.test.js | 77 ++++++++++++ src/tests/RosterStableState.test.js | 52 ++++++++ src/tests/testHelpers.js | 3 +- 9 files changed, 664 insertions(+), 33 deletions(-) create mode 100644 shared/tests/turn.rerollall.test.js create mode 100644 shared/tests/turn.stablehours.test.js create mode 100644 src/tests/DisplayView.deathsaves.test.js create mode 100644 src/tests/EncounterRerollAll.test.js create mode 100644 src/tests/RosterStableState.test.js diff --git a/shared/tests/turn.rerollall.test.js b/shared/tests/turn.rerollall.test.js new file mode 100644 index 0000000..002706e --- /dev/null +++ b/shared/tests/turn.rerollall.test.js @@ -0,0 +1,78 @@ +'use strict'; + +// rerollAllInitiatives: bulk d20+initMod for every participant. +// Single commit, single log, undo restores old values + order. + +const { + makeParticipant, + startEncounter, + rerollAllInitiatives, +} = require('@ttrpg/shared'); +const { mockCtx, undoLast } = require('./_helpers'); + +function part(id, init, initMod, extra = {}) { + return makeParticipant({ + id, name: id, type: initMod !== undefined ? 'monster' : 'character', + initiative: init, initMod, maxHp: 20, currentHp: 20, ...extra, + }); +} + +function enc(participants, extra = {}) { + return { + id: 'e1', name: 'reroll-all-test', participants, + isStarted: false, isPaused: false, round: 0, + currentTurnParticipantId: null, turnOrderIds: [], + ...extra, + }; +} + +const find = (e, id) => e.participants.find(p => p.id === id); + +describe('rerollAllInitiatives', () => { + test('rolls d20+initMod for every participant; single write', async () => { + const { ctx, storage } = mockCtx(); + const e = enc([part('a', 10, 5), part('b', 8, 2), part('c', 15, 0)]); + + const out = await rerollAllInitiatives(e, ctx); + + for (const id of ['a', 'b', 'c']) { + const p = find(out, id); + const mod = id === 'a' ? 5 : id === 'b' ? 2 : 0; + expect(p.initiative).toBeGreaterThanOrEqual(mod + 1); + expect(p.initiative).toBeLessThanOrEqual(mod + 20); + } + // one write for the whole operation + expect(storage.calls.filter(c => c.fn === 'updateDoc' && c.path === 'encounters/e1')).toHaveLength(1); + }); + + test('undo restores exact old initiatives and order', async () => { + const { ctx } = mockCtx(); + const e = enc([part('a', 10, 5), part('b', 8, 2)]); + const orderBefore = [...e.turnOrderIds]; + + const out = await rerollAllInitiatives(e, ctx); + expect(find(out, 'a').initiative).not.toBe(10); + + const undone = await undoLast(ctx, out); + expect(find(undone, 'a').initiative).toBe(10); + expect(find(undone, 'b').initiative).toBe(8); + expect(undone.turnOrderIds).toEqual(orderBefore); + }); + + test('inactive participants rerolled too (they stay inactive)', async () => { + const { ctx } = mockCtx(); + const e = enc([part('a', 10, 1), part('b', 9, 1, { isActive: false })]); + + const out = await rerollAllInitiatives(e, ctx); + expect(find(out, 'b').isActive).toBe(false); + expect(find(out, 'b').initiative).toBeGreaterThanOrEqual(2); + }); + + test('throws during active combat (not paused)', async () => { + const { ctx } = mockCtx(); + let e = enc([part('a', 10, 1)]); + e = await startEncounter(e, ctx); + + await expect(rerollAllInitiatives({ ...e, isPaused: false }, ctx)).rejects.toThrow(/paused/i); + }); +}); 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..9bd8637 100644 --- a/shared/tests/turn.writeback.test.js +++ b/shared/tests/turn.writeback.test.js @@ -204,3 +204,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 cdf94de..8707f15 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 = {}; @@ -240,6 +251,7 @@ function expandUndo(entry, currentEnc) { 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; @@ -361,6 +373,7 @@ 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, @@ -373,6 +386,8 @@ function buildCharacterParticipant(character) { 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, @@ -382,6 +397,9 @@ function buildCharacterParticipant(character) { 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 }, @@ -664,6 +682,7 @@ 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 || [])], }; @@ -741,7 +760,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 }; @@ -763,7 +782,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 { @@ -781,6 +800,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 || [])], }; @@ -900,6 +920,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 || [])], }; @@ -910,8 +931,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 }; } @@ -931,6 +952,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 || [])], }; @@ -977,7 +999,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 ); @@ -988,6 +1010,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 || [])], }; @@ -997,6 +1020,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 || [])], }; @@ -1022,7 +1046,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 ); @@ -1033,6 +1057,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 || [])], }; @@ -1042,6 +1067,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 || [])], }; @@ -1152,11 +1178,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) { @@ -1173,6 +1203,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. @@ -1199,6 +1263,6 @@ module.exports = { startEncounter, nextTurn, togglePause, addParticipant, addParticipants, updateParticipant, removeParticipant, toggleParticipantActive, applyHpChange, setTempHp, deathSave, stabilizeParticipant, reviveParticipant, markDead, toggleCondition, - reorderParticipants, endEncounter, + reorderParticipants, endEncounter, rerollAllInitiatives, activateDisplay, clearDisplay, toggleHidePlayerHp, }; diff --git a/src/App.js b/src/App.js index 3e1fff3..0369a3f 100644 --- a/src/App.js +++ b/src/App.js @@ -878,11 +878,22 @@ function CharacterManager({ campaignId, campaignCharacters, syncCharacters }) { return; } - const updatedCharacters = campaignCharacters.map(c => - 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 }); @@ -1124,6 +1135,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} )} @@ -1191,6 +1205,7 @@ 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); @@ -1392,6 +1407,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 { @@ -1440,7 +1465,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'; } @@ -1605,28 +1630,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 && (
@@ -1806,7 +1848,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp )} -
+
); })()} @@ -1956,7 +1998,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
{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 */} @@ -2184,6 +2226,14 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp title="Delete Participant?" message={`Are you sure you want to remove "${itemToDelete?.name}" from this encounter?`} /> + + setShowRerollConfirm(false)} + onConfirm={confirmRerollAll} + title="Reroll All Initiative?" + message={`Reroll initiative for all ${(participants || []).length} participants? Each rolls d20 + their init mod. Current values will be replaced. (Undo is available.)`} + /> ); } @@ -2236,7 +2286,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) { if (campDoc && Array.isArray(campDoc.players)) { const restored = campDoc.players.map(p => { const old = cw.find(c => c.id === p.id); - return old ? { ...p, defaultMaxHp: old.defaultMaxHp, defaultAc: old.defaultAc, defaultCurrentHp: old.defaultCurrentHp } : p; + return old ? { ...p, defaultMaxHp: old.defaultMaxHp, defaultAc: old.defaultAc, defaultCurrentHp: old.defaultCurrentHp, stableRegainHours: old.stableRegainHours !== undefined ? old.stableRegainHours : null } : p; }); await storage.updateDoc(getPath.campaign(wbId), { players: restored }); } @@ -2457,7 +2507,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) { onClose={() => setShowEndConfirm(false)} onConfirm={confirmEndEncounter} title="End Encounter?" - message="Are you sure you want to end this encounter? Initiative order will be reset and it will be removed from the Player Display." + message="Are you sure you want to end this encounter? Turn position and round counter will reset (initiative values are kept). It will be removed from the Player Display." /> ); @@ -3981,6 +4031,60 @@ function DisplayView() {

)} + {!isGeneric && (p.type === 'character' || p.type === 'npc') && status === 'dying' && ( +
+ Death Saves + + {[1, 2, 3].map(n => ( + = n)} + className={`w-6 h-6 md:w-7 md:h-7 rounded-full border-2 flex items-center justify-center text-sm md:text-base font-bold ${ + (p.deathSaveSuccesses || 0) >= n + ? 'bg-emerald-600 border-emerald-400 text-white' + : 'bg-stone-900/60 border-stone-500 text-stone-500' + }`} + aria-label={ + (p.deathSaveSuccesses || 0) >= n + ? `Death save success ${n} of 3` + : `Empty success slot ${n} of 3` + } + > + {(p.deathSaveSuccesses || 0) >= n ? '✓' : '·'} + + ))} + + + {[1, 2, 3].map(n => ( + = n)} + className={`w-6 h-6 md:w-7 md:h-7 rounded-full border-2 flex items-center justify-center text-sm md:text-base font-bold ${ + (p.deathSaveFailures || 0) >= n + ? 'bg-red-600 border-red-400 text-white' + : 'bg-stone-900/60 border-stone-500 text-stone-500' + }`} + aria-label={ + (p.deathSaveFailures || 0) >= n + ? `Death save failure ${n} of 3` + : `Empty failure slot ${n} of 3` + } + > + {(p.deathSaveFailures || 0) >= n ? '✕' : '·'} + + ))} + +
+ )} + + {!isGeneric && (p.type === 'character' || p.type === 'npc') && status === 'stable' && ( +
+ Stable — regains 1 HP after {p.stableRegainHours ? `${p.stableRegainHours} hour${p.stableRegainHours > 1 ? 's' : ''}` : '1d4 hours'} +
+ )} + {p.conditions?.length > 0 && (
{p.conditions.map(cId => { diff --git a/src/tests/DisplayView.deathsaves.test.js b/src/tests/DisplayView.deathsaves.test.js new file mode 100644 index 0000000..950af62 --- /dev/null +++ b/src/tests/DisplayView.deathsaves.test.js @@ -0,0 +1,88 @@ +// Player display death-save tracker: dying/stable characters show save pips. +// Admin already has pips; display showed only "(Dying)" label — players blind. + +import React from 'react'; +import { render, waitFor, screen } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import App from '../App'; +import { MOCK_DB } from '../__mocks__/firebase/_mock-db'; + +const campaignPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/c1'; +const encounterPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/c1/encounters/e1'; +const activeDisplayPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status'; + +function seed(participants, ruleset = '5e') { + MOCK_DB.set(campaignPath, { name: 'Camp', playerDisplayBackgroundUrl: '' }); + MOCK_DB.set(encounterPath, { name: 'Enc', participants, ruleset, isStarted: true, round: 2, currentTurnParticipantId: null }); + MOCK_DB.set(activeDisplayPath, { activeCampaignId: 'c1', activeEncounterId: 'e1', hidePlayerHp: false }); +} + +function char(overrides = {}) { + return { + id: 'p1', + name: 'Rogue', + type: 'character', + initiative: 18, + maxHp: 40, + currentHp: 0, + isActive: true, + status: 'dying', + deathSaveSuccesses: 0, + deathSaveFailures: 0, + conditions: ['unconscious'], + ...overrides, + }; +} + +beforeEach(() => { + const favicon = document.createElement('link'); + favicon.rel = 'icon'; + favicon.href = '/favicon.ico'; + document.head.appendChild(favicon); + window.history.replaceState({}, '', '/display'); + global.alert = jest.fn(); + window.open = jest.fn(); + Element.prototype.scrollIntoView = jest.fn(); +}); +afterEach(() => { + document.querySelectorAll('link[rel="icon"]').forEach(l => l.remove()); + window.history.replaceState({}, '', '/'); +}); + +describe('player display death saves', () => { + test('dying character shows success and failure pips with counts', async () => { + seed([char({ deathSaveSuccesses: 1, deathSaveFailures: 2 })]); + render(); + await screen.findByText('Rogue'); + + const row = screen.getByTestId('death-save-tracker'); + expect(row).toBeInTheDocument(); + expect(row.querySelectorAll('[data-save="success"]').length).toBe(3); + expect(row.querySelectorAll('[data-save="failure"]').length).toBe(3); + expect(row.querySelectorAll('[data-save="success"][data-filled="true"]').length).toBe(1); + expect(row.querySelectorAll('[data-save="failure"][data-filled="true"]').length).toBe(2); + }); + + test('stable character hides pips, shows stable/regains note', async () => { + seed([char({ status: 'stable', deathSaveSuccesses: 3 })]); + render(); + await screen.findByText('Rogue'); + + expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument(); + expect(screen.getByText(/Stable — regains 1 HP after 1d4 hours/i)).toBeInTheDocument(); + }); + + test('conscious character shows no pips', async () => { + seed([char({ status: 'conscious', currentHp: 10, conditions: [] })]); + render(); + await screen.findByText('Rogue'); + expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument(); + }); + + test('generic ruleset: no pips even at zero HP', async () => { + seed([char({ status: 'down' })], 'generic'); + render(); + await screen.findByText('Rogue'); + expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument(); + }); +}); diff --git a/src/tests/EncounterRerollAll.test.js b/src/tests/EncounterRerollAll.test.js new file mode 100644 index 0000000..5e2f197 --- /dev/null +++ b/src/tests/EncounterRerollAll.test.js @@ -0,0 +1,77 @@ +// Reroll-all-initiative: button in Add Participants header row, confirm modal, +// hidden during active combat. Toggle button persists when section collapsed. + +import { screen, fireEvent, waitFor, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, selectEncounterByName, addMonsterViaUI, MOCK_DB, startCombatViaUI } from './testHelpers'; + +const encPath = (cid, eid) => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`; + +async function setupTwoMonsters(camp = 'RerollAllCamp', enc = 'RerollEnc') { + await renderApp(); + const cid = await createCampaignViaUI(camp); + await selectCampaignByName(camp); + const eid = await createEncounterViaUI(enc); + await selectEncounterByName(enc); + await addMonsterViaUI('Alpha', 20, 3); + await addMonsterViaUI('Beta', 20, 5); + return { cid, eid }; +} + +const partDoc = (cid, eid) => MOCK_DB.get(encPath(cid, eid)); + +describe('reroll all initiative', () => { + test('button visible pre-combat; confirm rerolls every participant once', async () => { + const { cid, eid } = await setupTwoMonsters(); + + const btn = await screen.findByRole('button', { name: 'Reroll All Initiative' }); + expect(btn).toBeInTheDocument(); + + fireEvent.click(btn); + expect(await screen.findByText(/Reroll initiative for all/i)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Confirm/i })); + + await waitFor(() => { + const doc = partDoc(cid, eid); + expect(doc.participants).toHaveLength(2); + for (const p of doc.participants) { + const mod = p.name === 'Alpha' ? 3 : 5; + expect(p.initiative).toBeGreaterThanOrEqual(mod + 1); + expect(p.initiative).toBeLessThanOrEqual(mod + 20); + } + }); + await waitFor(() => expect(screen.queryByText(/Reroll initiative for all/i)).not.toBeInTheDocument()); + }); + + test('cancel leaves initiatives untouched', async () => { + const { cid, eid } = await setupTwoMonsters('RerollCancelCamp', 'RerollCancelEnc'); + const before = partDoc(cid, eid).participants.map(p => p.initiative); + + fireEvent.click(await screen.findByRole('button', { name: 'Reroll All Initiative' })); + fireEvent.click(await screen.findByRole('button', { name: /^Cancel$/ })); + + await waitFor(() => expect(screen.queryByText(/Reroll initiative for all/i)).not.toBeInTheDocument()); + expect(partDoc(cid, eid).participants.map(p => p.initiative)).toEqual(before); + }); + + test('hidden during active combat; toggle button still present', async () => { + await setupTwoMonsters('RerollCombatCamp', 'RerollCombatEnc'); + await startCombatViaUI(); + + expect(screen.queryByRole('button', { name: 'Reroll All Initiative' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Add Participants/i })).toBeInTheDocument(); + }); + + test('Add Participants toggle button persists when section collapsed', async () => { + await setupTwoMonsters('RerollToggleCamp', 'RerollToggleEnc'); + const toggle = await screen.findByRole('button', { name: /Add Participants/i }); + expect(toggle).toHaveAttribute('aria-expanded', 'true'); + fireEvent.click(toggle); + // form furled, toggle + Add All still visible + expect(screen.queryByPlaceholderText('e.g., Dire Wolf')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Add Participants/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Add All/i })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Add Participants/i })); + expect(screen.getByPlaceholderText('e.g., Dire Wolf')).toBeInTheDocument(); + }); +}); diff --git a/src/tests/RosterStableState.test.js b/src/tests/RosterStableState.test.js new file mode 100644 index 0000000..31d0557 --- /dev/null +++ b/src/tests/RosterStableState.test.js @@ -0,0 +1,52 @@ +// Roster stable state: badge on character card, cleared when Current HP raised. + +import { screen, fireEvent, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { renderApp, createCampaignViaUI, selectCampaignByName, MOCK_DB } from './testHelpers'; + +const campPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`; + +async function setupWithStableChar() { + await renderApp(); + const id = await createCampaignViaUI('StableCamp'); + await selectCampaignByName('StableCamp'); + + // character form + fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Fallen Hero' } }); + fireEvent.click(screen.getByRole('button', { name: 'Add Character' })); + await screen.findByText('Fallen Hero'); + + // writeback would have set these; seed directly + const doc = MOCK_DB.get(campPath(id)); + doc.players = doc.players.map(p => p.name === 'Fallen Hero' + ? { ...p, defaultCurrentHp: 0, stableRegainHours: 3 } + : p); + MOCK_DB.set(campPath(id), doc); + await screen.findByText(/Stable — regains 1 HP after 3 hours/); + return id; +} + +describe('roster stable state', () => { + test('character card shows stable badge with hours', async () => { + await setupWithStableChar(); + expect(screen.getByText(/Stable — regains 1 HP after 3 hours/)).toBeInTheDocument(); + }); + + test('raising Current HP in editor clears stable state', async () => { + const id = await setupWithStableChar(); + + fireEvent.click(screen.getByRole('button', { name: 'Edit character' })); + const curHpInput = await screen.findByTitle('Default Current HP'); + expect(curHpInput).toHaveValue(0); + fireEvent.change(curHpInput, { target: { value: '10' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save character' })); + + await waitFor(() => { + const doc = MOCK_DB.get(campPath(id)); + const hero = doc.players.find(p => p.name === 'Fallen Hero'); + expect(hero.defaultCurrentHp).toBe(10); + expect(hero.stableRegainHours).toBeNull(); + }); + await waitFor(() => expect(screen.queryByText(/Stable — regains/)).not.toBeInTheDocument()); + }); +}); diff --git a/src/tests/testHelpers.js b/src/tests/testHelpers.js index 365b8d3..aafb89a 100644 --- a/src/tests/testHelpers.js +++ b/src/tests/testHelpers.js @@ -9,7 +9,8 @@ export const fastWaitFor = (cb, opts) => waitFor(cb, { interval: 5, timeout: 100 // Scoped container: the "Add Participants" section (avoids label clashes with CharacterManager). export function getParticipantForm() { - const heading = screen.getByText('Add Participants'); + const heading = screen.getByText((content, element) => + element.tagName === 'BUTTON' && content.trim() === 'Add Participants'); // closest section/div wrapping the form let node = heading; for (let i = 0; i < 6; i++) { -- 2.43.0 From bca406fca915cec5def47125725d84d01d137718 Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:18:35 -0400 Subject: [PATCH 09/14] 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 --- shared/tests/turn.writeback.test.js | 42 ++++++++++ shared/turn.js | 8 +- src/App.js | 99 +++++++++++++----------- src/tests/CharacterDefaultsOnAdd.test.js | 74 ++++++++++++++++++ src/tests/EndEncounterSyncChoice.test.js | 98 +++++++++++++++++++++++ 5 files changed, 272 insertions(+), 49 deletions(-) create mode 100644 src/tests/CharacterDefaultsOnAdd.test.js create mode 100644 src/tests/EndEncounterSyncChoice.test.js diff --git a/shared/tests/turn.writeback.test.js b/shared/tests/turn.writeback.test.js index 9bd8637..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 }]; diff --git a/shared/turn.js b/shared/turn.js index 8707f15..5312e0d 100644 --- a/shared/turn.js +++ b/shared/turn.js @@ -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; diff --git a/src/App.js b/src/App.js index 0369a3f..b99b0ec 100644 --- a/src/App.js +++ b/src/App.js @@ -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 }) {

{title || "Confirm Action"}

-

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

+

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

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

{error}

)} @@ -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,23 +1299,25 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp if (character?.isNpc) finalType = 'npc'; } const computedInitiative = manualInit ? finalInitiative : (initiativeRoll + modifier); - const newParticipant = { - id: generateId(), - name: nameToAdd, - type: finalType, - originalCharacterId: ['character', 'npc'].includes(finalType) ? selectedCharacterId : null, - initiative: computedInitiative, - 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), - 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)); @@ -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 }) { Next TurnNext
diff --git a/src/tests/CharacterDefaultsOnAdd.test.js b/src/tests/CharacterDefaultsOnAdd.test.js new file mode 100644 index 0000000..b1462ed --- /dev/null +++ b/src/tests/CharacterDefaultsOnAdd.test.js @@ -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)); + }); +}); diff --git a/src/tests/EndEncounterSyncChoice.test.js b/src/tests/EndEncounterSyncChoice.test.js new file mode 100644 index 0000000..0b74159 --- /dev/null +++ b/src/tests/EndEncounterSyncChoice.test.js @@ -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); + }); + }); +}); -- 2.43.0 From 295c7e06b4e3b77d603dcd0b650f53644269e999 Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:09:56 -0400 Subject: [PATCH 10/14] feat: add round-based tracked effects - add generic encounter effects with round countdown, damage expiry, logs, and undo/redo - add 5e Turned and Spiritual Weapon presets inside existing Conditions panel - support custom participant or encounter effects with owner, notes, duration, and player visibility - convert 5e minute durations to rounds while keeping generic rules round-only - show prominent or compact effects on player and DM participant cards - attach owner-linked encounter effects to owner card with global fallback for ownerless effects - add direct turns-left editing plus step controls --- shared/tests/turn.effects.test.js | 115 ++++++++ shared/turn.js | 180 +++++++++++-- src/App.js | 361 +++++++++++++++++++++++++- src/tests/DisplayView.effects.test.js | 78 ++++++ src/tests/TrackedEffects.test.js | 108 ++++++++ 5 files changed, 814 insertions(+), 28 deletions(-) create mode 100644 shared/tests/turn.effects.test.js create mode 100644 src/tests/DisplayView.effects.test.js create mode 100644 src/tests/TrackedEffects.test.js 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/turn.js b/shared/turn.js index 5312e0d..0ba6775 100644 --- a/shared/turn.js +++ b/shared/turn.js @@ -233,6 +233,7 @@ function expandUndo(entry, currentEnc) { } case 'damage': case 'heal': + case 'hp_change': case 'death_save': case 'stabilize': case 'revive': @@ -258,8 +259,23 @@ function expandUndo(entry, currentEnc) { }; 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': @@ -317,22 +333,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': { @@ -358,6 +374,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(), @@ -500,13 +551,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); } @@ -571,29 +634,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); } @@ -685,6 +754,11 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio 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 = ''; @@ -719,9 +793,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; @@ -748,9 +822,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; } @@ -791,7 +865,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 = { @@ -808,7 +882,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); } @@ -819,6 +893,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. @@ -837,9 +916,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; @@ -854,11 +933,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; @@ -895,10 +974,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); } @@ -987,6 +1066,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.'); @@ -1261,10 +1386,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, + addEffect, updateEffect, removeEffect, reorderParticipants, endEncounter, rerollAllInitiatives, activateDisplay, clearDisplay, toggleHidePlayerHp, }; diff --git a/src/App.js b/src/App.js index b99b0ec..b6599bf 100644 --- a/src/App.js +++ b/src/App.js @@ -130,6 +130,9 @@ const { markDead, toggleCondition: combatToggleCondition, reorderParticipants, + addEffect: combatAddEffect, + updateEffect: combatUpdateEffect, + removeEffect: combatRemoveEffect, } = shared; const ROLL_DISPLAY_DURATION = 5000; @@ -1189,6 +1192,204 @@ function CharacterManager({ campaignId, campaignCharacters, syncCharacters }) { ); } +function EffectModal({ encounter, defaultScope, defaultTargetParticipantId, onClose, onAdd }) { + const is5e = (encounter.ruleset || '5e') === '5e'; + const participants = encounter.participants || []; + const [presetId, setPresetId] = useState('custom'); + const [name, setName] = useState(''); + const [scope, setScope] = useState(defaultScope || 'participant'); + const [targetParticipantId, setTargetParticipantId] = useState(defaultTargetParticipantId || participants[0]?.id || ''); + const [ownerParticipantId, setOwnerParticipantId] = useState(encounter.currentTurnParticipantId || ''); + const [duration, setDuration] = useState('10'); + const [durationUnit, setDurationUnit] = useState('rounds'); + const [expiresOnDamage, setExpiresOnDamage] = useState(false); + const [playerDisplay, setPlayerDisplay] = useState('compact'); + const [notes, setNotes] = useState(''); + + const selectPreset = (value) => { + setPresetId(value); + if (value === 'turned') { + setName('Turned'); + setScope('participant'); + setTargetParticipantId(defaultTargetParticipantId || participants[0]?.id || ''); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(true); + setPlayerDisplay('prominent'); + } else if (value === 'spiritual_weapon') { + setName('Spiritual Weapon'); + setScope('encounter'); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(false); + setPlayerDisplay('prominent'); + } else { + setName(''); + setScope(defaultScope || 'participant'); + setTargetParticipantId(defaultTargetParticipantId || participants[0]?.id || ''); + setDuration('10'); + setDurationUnit('rounds'); + setExpiresOnDamage(false); + setPlayerDisplay('compact'); + } + }; + + const submit = (e) => { + e.preventDefault(); + const n = Math.max(1, parseInt(duration, 10) || 1); + if (!name.trim() || (scope === 'participant' && !targetParticipantId)) return; + onAdd({ + presetId, + name: name.trim(), + scope, + targetParticipantId: scope === 'participant' ? targetParticipantId : null, + ownerParticipantId: ownerParticipantId || null, + remainingRounds: durationUnit === 'minutes' && is5e ? n * 10 : n, + expiresOnDamage, + playerDisplay, + notes, + createdRound: encounter.round || 0, + }); + }; + + return ( + +
+ + +
+ + {scope === 'participant' && ( + + )} +
+ +
+ + +
+ + + +
+ + +
+
+
+ ); +} + +function EffectControlRow({ effect, participants, onAdjust, onSet, onRemove }) { + const owner = participants.find(p => p.id === effect.ownerParticipantId); + const [draftRounds, setDraftRounds] = useState(String(effect.remainingRounds)); + useEffect(() => setDraftRounds(String(effect.remainingRounds)), [effect.remainingRounds]); + const commitRounds = () => { + const value = Math.max(1, parseInt(draftRounds, 10) || 1); + setDraftRounds(String(value)); + if (value !== effect.remainingRounds) onSet(effect, value); + }; + return ( +
+ {effect.name.toUpperCase()} + + {owner && Owner: {owner.name}} + {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 // ============================================================================ @@ -1215,6 +1416,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp 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); @@ -1555,6 +1757,75 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp } }; + const handleAddEffect = async (effect) => { + if (!db) return; + try { + await combatAddEffect(encounter, effect, buildCtx(encounterPath)); + setEffectModal(null); + } catch (err) { + showToast(err.message || 'Failed to add effect.'); + } + }; + + const togglePresetEffect = async (presetId, participant) => { + if (!db) return; + const existing = (encounter.effects || []).find(effect => presetId === 'turned' + ? effect.presetId === 'turned' && effect.targetParticipantId === participant.id + : effect.presetId === 'spiritual_weapon' && effect.ownerParticipantId === participant.id); + try { + if (existing) { + await combatRemoveEffect(encounter, existing.id, buildCtx(encounterPath)); + return; + } + if (presetId === 'turned') { + await combatAddEffect(encounter, { + presetId: 'turned', name: 'Turned', scope: 'participant', + targetParticipantId: participant.id, + ownerParticipantId: encounter.currentTurnParticipantId || null, + remainingRounds: 10, expiresOnDamage: true, + playerDisplay: 'prominent', createdRound: encounter.round || 0, + }, buildCtx(encounterPath)); + } else if (presetId === 'spiritual_weapon') { + await combatAddEffect(encounter, { + presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', + ownerParticipantId: participant.id, + remainingRounds: 10, expiresOnDamage: false, + playerDisplay: 'prominent', createdRound: encounter.round || 0, + }, buildCtx(encounterPath)); + } + } catch (err) { + showToast(err.message || 'Failed to update effect.'); + } + }; + + const handleAdjustEffect = async (effect, delta) => { + if (!db) return; + const next = Math.max(1, (effect.remainingRounds || 1) + delta); + try { + await combatUpdateEffect(encounter, effect.id, { remainingRounds: next }, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message || 'Failed to update effect.'); + } + }; + + const handleSetEffectDuration = async (effect, remainingRounds) => { + if (!db) return; + try { + await combatUpdateEffect(encounter, effect.id, { remainingRounds }, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message || 'Failed to update effect.'); + } + }; + + const handleRemoveEffect = async (effect) => { + if (!db) return; + try { + await combatRemoveEffect(encounter, effect.id, buildCtx(encounterPath)); + } catch (err) { + showToast(err.message || 'Failed to remove effect.'); + } + }; + // Add freeform condition: persist to campaign palette + apply to current participant. const addCustomCondition = async (label, participantId = null) => { const trimmed = (label || '').trim(); @@ -1839,6 +2110,15 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp ); })()} + {(encounter.effects || []).some(effect => effect.scope === 'encounter' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId))) && ( +
+

Encounter Effects

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

No participants added yet.

} @@ -1863,6 +2143,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp return (
  • handleDragStart(e, p.id) : undefined} onDragOver={isDraggable ? handleDragOver : undefined} @@ -2067,6 +2348,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 && (
    @@ -2086,6 +2374,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) */}
    + {effectModal && ( + setEffectModal(null)} + onAdd={handleAddEffect} + /> + )} + setShowDeleteConfirm(false)} @@ -3684,6 +4025,7 @@ function PlayerParticipantCard({ id, isActive, status, onExit, className, childr return (
    {children} @@ -3918,6 +4260,7 @@ function DisplayView() { } const { name, participants, round, currentTurnParticipantId, isStarted, isPaused } = activeEncounterData; + const trackedEffects = activeEncounterData.effects || []; const hidePlayerHp = activeDisplayData?.hidePlayerHp ?? true; const hideNpcHp = activeDisplayData?.hideNpcHp ?? false; @@ -3974,6 +4317,12 @@ function DisplayView() {

    No active participants.

    )} +
    + {trackedEffects + .filter(effect => effect.scope === 'encounter' && effect.playerDisplay !== 'hidden' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId))) + .map(effect => )} +
    +
    {participantsToRender.map(p => { const isGeneric = (activeEncounterData.ruleset || '5e') === 'generic'; @@ -4022,8 +4371,18 @@ function DisplayView() {
    + {trackedEffects + .filter(effect => ( + (effect.scope === 'participant' && effect.targetParticipantId === p.id) || + (effect.scope === 'encounter' && effect.ownerParticipantId === p.id) + ) && effect.playerDisplay !== 'hidden') + .map(effect => { + const owner = participants.find(ownerParticipant => ownerParticipant.id === effect.ownerParticipantId); + return ; + })} + {!(hidePlayerHp && p.type === 'character') && !(hideNpcHp && p.type !== 'character') && ( -
    +
    { + const favicon = document.createElement('link'); + favicon.rel = 'icon'; + favicon.href = '/favicon.ico'; + document.head.appendChild(favicon); + window.history.replaceState({}, '', '/display'); + global.alert = jest.fn(); + window.open = jest.fn(); + Element.prototype.scrollIntoView = jest.fn(); +}); + +afterEach(() => { + document.querySelectorAll('link[rel="icon"]').forEach(l => l.remove()); + window.history.replaceState({}, '', '/'); +}); + +describe('player display tracked effects', () => { + test('prominent participant effect renders clear banner with countdown', async () => { + seed([{ id: 'fx1', presetId: 'turned', name: 'Turned', scope: 'participant', targetParticipantId: 'p2', ownerParticipantId: 'p1', remainingRounds: 7, expiresOnDamage: true, playerDisplay: 'prominent' }]); + render(); + await screen.findByText('Zombie'); + expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('TURNED'); + expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('7 rounds remaining'); + expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('Ends on damage'); + }); + + test('compact participant effect renders badge; hidden effect does not render', async () => { + seed([ + { id: 'fx1', name: 'Bless', scope: 'participant', targetParticipantId: 'p2', remainingRounds: 3, playerDisplay: 'compact' }, + { id: 'fx2', name: 'Secret', scope: 'participant', targetParticipantId: 'p2', remainingRounds: 4, playerDisplay: 'hidden' }, + ]); + render(); + await screen.findByText('Zombie'); + expect(screen.getByText(/Bless · 3 rounds/i)).toBeInTheDocument(); + expect(screen.queryByText(/Secret/i)).not.toBeInTheDocument(); + }); + + test('owner-linked encounter effect renders prominently on owner card', async () => { + seed([{ id: 'fx3', presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', ownerParticipantId: 'p1', remainingRounds: 8, expiresOnDamage: false, playerDisplay: 'prominent' }]); + render(); + await screen.findByText('Zombie'); + const clericCard = screen.getByTestId('participant-card-p1'); + const banner = within(clericCard).getByTestId('encounter-effect-fx3'); + expect(banner).toHaveTextContent('SPIRITUAL WEAPON'); + expect(banner).toHaveTextContent('Cleric'); + expect(banner).toHaveTextContent('8 rounds remaining'); + }); + + test('ownerless encounter effect remains in global fallback area', async () => { + seed([{ id: 'fx4', name: 'Fog Cloud', scope: 'encounter', ownerParticipantId: null, remainingRounds: 5, playerDisplay: 'prominent' }]); + render(); + await screen.findByText('Zombie'); + const banner = screen.getByTestId('encounter-effect-fx4'); + expect(banner).toHaveTextContent('FOG CLOUD'); + expect(screen.getByTestId('participant-card-p1')).not.toContainElement(banner); + expect(screen.getByTestId('participant-card-p2')).not.toContainElement(banner); + }); +}); diff --git a/src/tests/TrackedEffects.test.js b/src/tests/TrackedEffects.test.js new file mode 100644 index 0000000..c6fd5d2 --- /dev/null +++ b/src/tests/TrackedEffects.test.js @@ -0,0 +1,108 @@ +import { screen, fireEvent, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { + setupReady, addMonsterViaUI, renderApp, createCampaignViaUI, + selectCampaignByName, selectEncounterByName, MOCK_DB, +} from './testHelpers'; + +function latestEncounter() { + const row = [...MOCK_DB._state.docs.entries()] + .filter(([path]) => path.includes('/encounters/')) + .pop(); + return row ? MOCK_DB.get(row[0]) : null; +} + +describe('tracked effects DM UI', () => { + test('5e Turned preset creates prominent 10-round damage-expiring participant effect', async () => { + await setupReady('Turned Camp', 'Turned Encounter'); + await addMonsterViaUI('Zombie', 22, -2); + + expect(screen.queryByRole('button', { name: 'Add effect to Zombie' })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + fireEvent.click(screen.getByRole('button', { name: 'Turned' })); + + await waitFor(() => { + const fx = latestEncounter().effects[0]; + expect(fx).toMatchObject({ + presetId: 'turned', name: 'Turned', scope: 'participant', + remainingRounds: 10, expiresOnDamage: true, playerDisplay: 'prominent', + }); + expect(fx.targetParticipantId).toBe(latestEncounter().participants.find(p => p.name === 'Zombie').id); + }); + expect(await screen.findByText('TURNED')).toBeInTheDocument(); + expect(screen.getByLabelText('Turns left for Turned')).toHaveValue(10); + }); + + test('custom encounter effect converts 5e minutes to rounds and supports prominent display', async () => { + await setupReady('Effect Camp', 'Effect Encounter'); + await addMonsterViaUI('Cleric', 30, 2); + + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + fireEvent.click(screen.getByRole('button', { name: 'Custom tracked effect' })); + fireEvent.change(screen.getByLabelText('Effect scope'), { target: { value: 'encounter' } }); + fireEvent.change(screen.getByLabelText('Effect name'), { target: { value: 'Spirit Guardians' } }); + fireEvent.change(screen.getByLabelText('Duration'), { target: { value: '2' } }); + fireEvent.change(screen.getByLabelText('Duration unit'), { target: { value: 'minutes' } }); + fireEvent.change(screen.getByLabelText('Player display'), { target: { value: 'prominent' } }); + fireEvent.click(screen.getByRole('button', { name: 'Add Effect' })); + + await waitFor(() => expect(latestEncounter().effects[0]).toMatchObject({ + name: 'Spirit Guardians', scope: 'encounter', remainingRounds: 20, + playerDisplay: 'prominent', + })); + expect(screen.getByText('SPIRIT GUARDIANS')).toBeInTheDocument(); + expect(screen.getByLabelText('Turns left for Spirit Guardians')).toHaveValue(20); + }); + + test('Spiritual Weapon preset creates 10-round encounter effect', async () => { + await setupReady('Weapon Camp', 'Weapon Encounter'); + await addMonsterViaUI('Cleric', 30, 2); + + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + fireEvent.click(screen.getByRole('button', { name: 'Spiritual Weapon' })); + + await waitFor(() => expect(latestEncounter().effects[0]).toMatchObject({ + presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', + remainingRounds: 10, expiresOnDamage: false, playerDisplay: 'prominent', + })); + const clericId = latestEncounter().participants.find(p => p.name === 'Cleric').id; + expect(within(screen.getByTestId(`admin-participant-card-${clericId}`)).getByText('SPIRITUAL WEAPON')).toBeInTheDocument(); + }); + + test('generic ruleset offers custom effects only and rounds only', async () => { + await renderApp(); + await createCampaignViaUI('Generic Effect Camp'); + await selectCampaignByName('Generic Effect Camp'); + fireEvent.click(screen.getByRole('button', { name: /Create Encounter/i })); + fireEvent.change(await screen.findByLabelText(/Encounter Name/i), { target: { value: 'Generic Effect Encounter' } }); + fireEvent.click(screen.getByRole('radio', { name: /Generic/i })); + fireEvent.click(screen.getByRole('button', { name: /^Create$/i })); + await selectEncounterByName('Generic Effect Encounter'); + await addMonsterViaUI('Generic Mob', 10, 0); + + expect(screen.queryByRole('button', { name: 'Add encounter effect' })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + expect(screen.queryByRole('button', { name: 'Turned' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Spiritual Weapon' })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Custom tracked effect' })); + const durationOptions = [...screen.getByLabelText('Duration unit').options].map(o => o.value); + expect(durationOptions).toEqual(['rounds']); + }); + + test('effect duration controls adjust and remove effect', async () => { + await setupReady('Control Camp', 'Control Encounter'); + await addMonsterViaUI('Ghoul', 18, 2); + fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + fireEvent.click(screen.getByRole('button', { name: 'Turned' })); + await screen.findByText('TURNED'); + + const turnsInput = screen.getByLabelText('Turns left for Turned'); + fireEvent.change(turnsInput, { target: { value: '3' } }); + fireEvent.blur(turnsInput); + await waitFor(() => expect(latestEncounter().effects[0].remainingRounds).toBe(3)); + fireEvent.click(screen.getByRole('button', { name: 'Decrease Turned duration' })); + await waitFor(() => expect(latestEncounter().effects[0].remainingRounds).toBe(2)); + fireEvent.click(screen.getByRole('button', { name: 'Remove Turned' })); + await waitFor(() => expect(latestEncounter().effects).toEqual([])); + }); +}); -- 2.43.0 From 0e7bc7c099d2f21645fdc176cc12b3edc9b5d69a Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:18:54 -0400 Subject: [PATCH 11/14] feat: make tracked effect owners editable Default effect ownership to active participant, allow inline reassignment or clearing, move owner-linked effects between participant cards, and add direct turns-left editing coverage. --- src/App.js | 31 +++++++++++++++++++++++++------ src/tests/TrackedEffects.test.js | 21 ++++++++++++++++----- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/src/App.js b/src/App.js index b6599bf..f5965a9 100644 --- a/src/App.js +++ b/src/App.js @@ -1329,8 +1329,7 @@ function EffectModal({ encounter, defaultScope, defaultTargetParticipantId, onCl ); } -function EffectControlRow({ effect, participants, onAdjust, onSet, onRemove }) { - const owner = participants.find(p => p.id === effect.ownerParticipantId); +function EffectControlRow({ effect, participants, onAdjust, onSet, onSetOwner, onRemove }) { const [draftRounds, setDraftRounds] = useState(String(effect.remainingRounds)); useEffect(() => setDraftRounds(String(effect.remainingRounds)), [effect.remainingRounds]); const commitRounds = () => { @@ -1357,7 +1356,18 @@ function EffectControlRow({ effect, participants, onAdjust, onSet, onRemove }) { /> rounds - {owner && Owner: {owner.name}} + {effect.expiresOnDamage && Ends on damage} @@ -1788,7 +1798,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp } else if (presetId === 'spiritual_weapon') { await combatAddEffect(encounter, { presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', - ownerParticipantId: participant.id, + ownerParticipantId: encounter.currentTurnParticipantId || participant.id, remainingRounds: 10, expiresOnDamage: false, playerDisplay: 'prominent', createdRound: encounter.round || 0, }, buildCtx(encounterPath)); @@ -1817,6 +1827,15 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp } }; + 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 { @@ -2114,7 +2133,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp

    Encounter Effects

    {(encounter.effects || []).filter(effect => effect.scope === 'encounter' && (!effect.ownerParticipantId || !participants.some(p => p.id === effect.ownerParticipantId))).map(effect => ( - + ))}
    )} @@ -2352,7 +2371,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp (effect.scope === 'participant' && effect.targetParticipantId === p.id) || (effect.scope === 'encounter' && effect.ownerParticipantId === p.id) ).map(effect => ( - + ))} {/* Expandable conditions picker */} diff --git a/src/tests/TrackedEffects.test.js b/src/tests/TrackedEffects.test.js index c6fd5d2..5605cf5 100644 --- a/src/tests/TrackedEffects.test.js +++ b/src/tests/TrackedEffects.test.js @@ -2,7 +2,7 @@ import { screen, fireEvent, waitFor, within } from '@testing-library/react'; import '@testing-library/jest-dom'; import { setupReady, addMonsterViaUI, renderApp, createCampaignViaUI, - selectCampaignByName, selectEncounterByName, MOCK_DB, + selectCampaignByName, selectEncounterByName, startCombatViaUI, MOCK_DB, } from './testHelpers'; function latestEncounter() { @@ -57,16 +57,27 @@ describe('tracked effects DM UI', () => { test('Spiritual Weapon preset creates 10-round encounter effect', async () => { await setupReady('Weapon Camp', 'Weapon Encounter'); await addMonsterViaUI('Cleric', 30, 2); + await addMonsterViaUI('Wizard', 24, 3); - fireEvent.click(screen.getByRole('button', { name: 'Open conditions' })); + await startCombatViaUI(); + const activeId = latestEncounter().currentTurnParticipantId; + const otherId = latestEncounter().participants.find(p => p.id !== activeId).id; + fireEvent.click(within(screen.getByTestId(`admin-participant-card-${otherId}`)).getByRole('button', { name: 'Open conditions' })); fireEvent.click(screen.getByRole('button', { name: 'Spiritual Weapon' })); await waitFor(() => expect(latestEncounter().effects[0]).toMatchObject({ presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', - remainingRounds: 10, expiresOnDamage: false, playerDisplay: 'prominent', + ownerParticipantId: activeId, remainingRounds: 10, + expiresOnDamage: false, playerDisplay: 'prominent', })); - const clericId = latestEncounter().participants.find(p => p.name === 'Cleric').id; - expect(within(screen.getByTestId(`admin-participant-card-${clericId}`)).getByText('SPIRITUAL WEAPON')).toBeInTheDocument(); + expect(within(screen.getByTestId(`admin-participant-card-${activeId}`)).getByText('SPIRITUAL WEAPON')).toBeInTheDocument(); + + const ownerSelect = screen.getByLabelText('Owner for Spiritual Weapon'); + expect(ownerSelect).toHaveValue(activeId); + fireEvent.change(ownerSelect, { target: { value: otherId } }); + await waitFor(() => expect(latestEncounter().effects[0].ownerParticipantId).toBe(otherId)); + expect(within(screen.getByTestId(`admin-participant-card-${otherId}`)).getByText('SPIRITUAL WEAPON')).toBeInTheDocument(); + expect(within(screen.getByTestId(`admin-participant-card-${activeId}`)).queryByText('SPIRITUAL WEAPON')).not.toBeInTheDocument(); }); test('generic ruleset offers custom effects only and rounds only', async () => { -- 2.43.0 From 15347bfdc8068d80dafa8e93e2f3c50680c5d30f Mon Sep 17 00:00:00 2001 From: david raistrick <1108844+keen99@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:11:03 -0500 Subject: [PATCH 12/14] feat: add encounter roster visibility and kill actions - persist independent Hide Disabled and Hide Dead encounter controls - keep dead PCs exempt from Hide Dead while allowing Hide Disabled to hide any inactive participant - add confirmed Kill action that sets zero HP, dead, and inactive without deleting - add undoable Heal Full action above Revive - fix random initiative reroll test flake --- shared/tests/turn.generic.test.js | 41 +++++-- shared/tests/turn.rerollall.test.js | 1 - shared/turn.js | 76 +++++++++++-- src/App.js | 102 +++++++++++++++-- .../EncounterParticipantVisibility.test.js | 107 ++++++++++++++++++ 5 files changed, 300 insertions(+), 27 deletions(-) create mode 100644 src/tests/EncounterParticipantVisibility.test.js 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 index 002706e..0d33d8b 100644 --- a/shared/tests/turn.rerollall.test.js +++ b/shared/tests/turn.rerollall.test.js @@ -51,7 +51,6 @@ describe('rerollAllInitiatives', () => { const orderBefore = [...e.turnOrderIds]; const out = await rerollAllInitiatives(e, ctx); - expect(find(out, 'a').initiative).not.toBe(10); const undone = await undoLast(ctx, out); expect(find(undone, 'a').initiative).toBe(10); diff --git a/shared/turn.js b/shared/turn.js index 0ba6775..5d6ef14 100644 --- a/shared/turn.js +++ b/shared/turn.js @@ -237,6 +237,7 @@ function expandUndo(entry, currentEnc) { 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, @@ -249,6 +250,7 @@ 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; @@ -1206,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); } @@ -1389,7 +1451,7 @@ module.exports = { makeEffect, makeParticipant, buildCharacterParticipant, buildMonsterParticipant, startEncounter, nextTurn, togglePause, addParticipant, addParticipants, updateParticipant, removeParticipant, - toggleParticipantActive, applyHpChange, setTempHp, deathSave, stabilizeParticipant, reviveParticipant, markDead, toggleCondition, + 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 f5965a9..cd61bdf 100644 --- a/src/App.js +++ b/src/App.js @@ -127,6 +127,7 @@ const { deathSave: combatDeathSave, stabilizeParticipant, reviveParticipant, + healFullParticipant, markDead, toggleCondition: combatToggleCondition, reorderParticipants, @@ -1423,6 +1424,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp 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(''); @@ -1439,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); @@ -1739,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 { @@ -1748,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 { @@ -1890,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; @@ -2138,7 +2174,28 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
    )} +
    + Roster visibility + + +
    + {participants.length === 0 &&

    No participants added yet.

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

    All participants hidden.

    }
      @@ -2272,15 +2329,21 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp {participantStatus === 'dead' && ( - - )} - {isGeneric && !isDead && ( - + + + + )} +
    @@ -2496,6 +2559,17 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
    )} + {!isDead && ( + + )}