Author SHA1 Message Date
david raistrick e8a0ba2b60 chore: add bee-targeted Docker restart wrapper 2026-09-23 14:38:19 -04:00
david raistrick 3b166403e8 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.
2026-09-23 12:20:18 -04:00
david raistrick 6122c19cf1 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.
2026-09-23 10:57:09 -04:00
david raistrick 83693d4aa9 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.
2026-09-23 10:56:51 -04:00
robertandClaude Fable 5 09cf9291eb Merge branch 'fix/end-combat-writeback-path': fix end combat failing when character sync enabled
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-31 16:30:58 -04:00
6 changed files with 484 additions and 13 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
export DOCKER_CONTEXT=bee
exec "$(dirname "$0")/restart.sh"
+173 -13
View File
@@ -9,7 +9,7 @@ import {
Play as PlayIcon, Pause as PauseIcon, SkipForward as SkipForwardIcon, Play as PlayIcon, Pause as PauseIcon, SkipForward as SkipForwardIcon,
StopCircle as StopCircleIcon, Users2, Dices, ChevronDown, ScrollText, StopCircle as StopCircleIcon, Users2, Dices, ChevronDown, ScrollText,
Maximize2, Minimize2, PanelTopOpen, PanelTopClose, Moon, Coffee, Clock, ChevronRight, X, Maximize2, Minimize2, PanelTopOpen, PanelTopClose, Moon, Coffee, Clock, ChevronRight, X,
Undo2, Redo2, Crosshair Undo2, Redo2, Crosshair, Pencil
} from 'lucide-react'; } from 'lucide-react';
// ----- UI feedback: toast (transient) + info modal (persistent) ----- // ----- UI feedback: toast (transient) + info modal (persistent) -----
@@ -2428,14 +2428,84 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
}); });
const [showCreateModal, setShowCreateModal] = useState(false); const [showCreateModal, setShowCreateModal] = useState(false);
const [encounterFullscreen, setEncounterFullscreen] = 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('');
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 [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [itemToDelete, setItemToDelete] = useState(null); const [itemToDelete, setItemToDelete] = useState(null);
const [draggedEncounterId, setDraggedEncounterId] = useState(null); const [draggedEncounterId, setDraggedEncounterId] = useState(null);
const selectedEncounterIdRef = useRef(selectedEncounterId); 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. // Restore scoped encounter selection when campaign changes.
useEffect(() => { useEffect(() => {
closedEncounterRef.current = false;
setEncounterFullscreen(false);
if (!campaignId) { setSelectedEncounterId(null); return; } if (!campaignId) { setSelectedEncounterId(null); return; }
try { try {
const saved = localStorage.getItem(`ttrpg.selectedEncounter.${campaignId}`) || null; const saved = localStorage.getItem(`ttrpg.selectedEncounter.${campaignId}`) || null;
@@ -2505,7 +2575,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
if (encounters && encounters.length > 0) { if (encounters && encounters.length > 0) {
const currentSelection = selectedEncounterIdRef.current; 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)) { if (initialActiveEncounterId && encounters.some(e => e.id === initialActiveEncounterId)) {
setSelectedEncounterId(initialActiveEncounterId); setSelectedEncounterId(initialActiveEncounterId);
} else if ( } else if (
@@ -2638,13 +2708,27 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
<PlusCircle size={18} className="mr-1" /> Create Encounter <PlusCircle size={18} className="mr-1" /> Create Encounter
</button> </button>
</div> </div>
<div className="flex flex-wrap items-center gap-x-5 gap-y-1 mb-3 text-sm text-stone-300">
<label className="inline-flex items-center gap-2 min-h-[36px] cursor-pointer">
<input type="checkbox" role="switch" checked={openOnTop} onChange={toggleOpenOnTop} className="h-4 w-4 accent-amber-500" />
Open on top
</label>
<label className="inline-flex items-center gap-2 min-h-[36px] cursor-pointer">
<input type="checkbox" role="switch" checked={collapseCompleted} onChange={toggleCollapseCompleted} className="h-4 w-4 accent-amber-500" />
Collapse completed
</label>
</div>
{(!encounters || encounters.length === 0) && ( {(!encounters || encounters.length === 0) && (
<p className="text-sm text-stone-400">No encounters yet.</p> <p className="text-sm text-stone-400">No encounters yet.</p>
)} )}
<div className="space-y-3"> {/* Encounter groups: In Progress / Ready / Completed. */}
{sortedEncounters.map(encounter => { {(() => {
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 && const isLive = activeDisplayInfo &&
activeDisplayInfo.activeCampaignId === campaignId && activeDisplayInfo.activeCampaignId === campaignId &&
activeDisplayInfo.activeEncounterId === encounter.id; activeDisplayInfo.activeEncounterId === encounter.id;
@@ -2660,8 +2744,41 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
className={`p-3 rounded-md shadow transition-all ${selectedEncounterId === encounter.id ? 'bg-amber-900 ring-2 ring-amber-500' : 'bg-stone-800 hover:bg-stone-700'} ${isLive ? 'ring-2 ring-green-500 shadow-md shadow-green-500/30' : ''} ${encounter.isStarted && !encounter.endedAt ? 'ring-2 ring-red-500' : ''} ${draggedEncounterId === encounter.id ? 'opacity-50 ring-2 ring-yellow-400' : ''} cursor-grab`} 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`}
> >
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<div onClick={() => setSelectedEncounterId(encounter.id)} className="cursor-pointer flex-grow"> <div onClick={() => openEncounter(encounter.id)} className="cursor-pointer flex-grow">
{renamingId === encounter.id ? (
<form
onSubmit={(e) => { e.preventDefault(); commitRename(encounter.id); }}
className="flex items-center gap-1"
onClick={(e) => e.stopPropagation()}
>
<input
type="text"
value={renameValue}
onChange={(e) => 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"
/>
<button
type="submit"
className="p-1 rounded bg-emerald-700 hover:bg-emerald-600 text-white"
title="Save Name"
>
<Save size={14} />
</button>
<button
type="button"
onClick={cancelRename}
className="p-1 rounded bg-stone-700 hover:bg-stone-600 text-white"
title="Cancel Rename"
>
<X size={14} />
</button>
</form>
) : (
<h4 className="font-medium text-white">{encounter.name} <span className={`ml-1 px-1.5 py-0.5 rounded text-xs font-bold tracking-wide ${encounter.ruleset === 'generic' ? 'bg-purple-900/80 text-purple-200 border border-purple-500' : 'bg-amber-900/80 text-amber-200 border border-amber-500'}`}>{encounter.ruleset === 'generic' ? 'GEN' : '5e'}</span>{encounter.isStarted && !encounter.endedAt && <span className="ml-1 px-1.5 py-0.5 rounded text-xs font-bold bg-red-600 text-white animate-pulse">⚔ IN PROGRESS</span>}</h4> <h4 className="font-medium text-white">{encounter.name} <span className={`ml-1 px-1.5 py-0.5 rounded text-xs font-bold tracking-wide ${encounter.ruleset === 'generic' ? 'bg-purple-900/80 text-purple-200 border border-purple-500' : 'bg-amber-900/80 text-amber-200 border border-amber-500'}`}>{encounter.ruleset === 'generic' ? 'GEN' : '5e'}</span>{encounter.isStarted && !encounter.endedAt && <span className="ml-1 px-1.5 py-0.5 rounded text-xs font-bold bg-red-600 text-white animate-pulse">⚔ IN PROGRESS</span>}</h4>
)}
<p className="text-xs text-stone-300"> <p className="text-xs text-stone-300">
{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} {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}
</p> </p>
@@ -2689,6 +2806,16 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
> >
{isLive ? <EyeOff size={18} /> : <Eye size={18} />} {isLive ? <EyeOff size={18} /> : <Eye size={18} />}
</button> </button>
<button
onClick={(e) => {
e.stopPropagation();
startRename(encounter);
}}
className="p-1 rounded transition-colors text-amber-400 hover:text-amber-300 bg-stone-700 hover:bg-stone-600"
title="Rename Encounter"
>
<Pencil size={18} />
</button>
<button <button
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
@@ -2703,8 +2830,40 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
</div> </div>
</div> </div>
); );
})} };
</div>
const Group = ({ label, count, items, collapsible, open, onToggle }) => (
<div className="space-y-3">
<button
type="button"
onClick={collapsible ? onToggle : undefined}
aria-expanded={collapsible ? open : undefined}
className="flex items-center gap-2 text-sm font-semibold text-stone-300 font-cinzel tracking-wide w-full text-left"
>
{collapsible ? (open ? <ChevronDown size={16} /> : <ChevronRight size={16} />) : null}
{label}
<span className="px-1.5 py-0.5 rounded bg-stone-700 text-stone-300 text-xs font-bold">{count}</span>
</button>
{(!collapsible || open) && items}
</div>
);
const wrap = (encounter) => (
<div key={encounter.id} className="space-y-3">{renderCard(encounter)}</div>
);
const groups = [];
if (inProgress.length > 0) {
groups.push(<Group key="g-prog" label="⚔ In Progress" count={inProgress.length} items={inProgress.map(wrap)} collapsible={false} open />);
}
if (ready.length > 0) {
groups.push(<Group key="g-ready" label="Ready" count={ready.length} items={ready.map(wrap)} collapsible={false} open />);
}
if (completed.length > 0) {
groups.push(<Group key="g-done" label="Completed" count={completed.length} items={completed.map(wrap)} collapsible={collapseCompleted} open={!collapseCompleted || completedOpen} onToggle={() => setCompletedOpen(v => !v)} />);
}
return <div className="space-y-4">{groups}</div>;
})()}
{showCreateModal && ( {showCreateModal && (
<Modal onClose={() => setShowCreateModal(false)} title="Create New Encounter"> <Modal onClose={() => setShowCreateModal(false)} title="Create New Encounter">
@@ -2718,8 +2877,8 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
)} )}
{selectedEncounter && ( {selectedEncounter && (
<div className={`mt-3 md:mt-6 p-2 md:p-4 bg-stone-900 rounded-lg shadow-inner ${encounterFullscreen ? 'fixed inset-0 z-50 m-0 rounded-none overflow-y-auto' : ''}`}> <div data-testid={encounterFullscreen ? 'encounter-popout' : undefined} className={`mt-3 md:mt-6 p-2 md:p-4 bg-stone-900 rounded-lg shadow-inner ${encounterFullscreen ? 'fixed inset-0 z-50 m-0 rounded-none overflow-y-auto overscroll-contain' : ''}`}>
<h3 className="text-xl font-semibold text-amber-300 mb-3 font-cinzel tracking-wide flex items-center justify-between gap-2"> <h3 className={`text-xl font-semibold text-amber-300 mb-3 font-cinzel tracking-wide flex items-center justify-between gap-2 ${encounterFullscreen ? 'sticky top-0 z-10 bg-stone-900 py-2' : ''}`}>
<span className="min-w-0 truncate">Managing Encounter: {selectedEncounter.name}</span> <span className="min-w-0 truncate">Managing Encounter: {selectedEncounter.name}</span>
<span className="flex items-center gap-1 flex-shrink-0"> <span className="flex items-center gap-1 flex-shrink-0">
<button <button
@@ -2739,12 +2898,13 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
{isBrowserFullscreen ? <Minimize2 size={18} /> : <Maximize2 size={18} />} {isBrowserFullscreen ? <Minimize2 size={18} /> : <Maximize2 size={18} />}
</button> </button>
<button <button
onClick={() => setEncounterFullscreen(v => !v)} onClick={encounterFullscreen ? closeEncounter : () => setEncounterFullscreen(true)}
className="p-1.5 rounded-md text-stone-300 bg-stone-700 hover:bg-stone-600 transition-colors" className={`p-1.5 rounded-md text-stone-300 bg-stone-700 hover:bg-stone-600 transition-colors ${encounterFullscreen ? 'min-h-[40px] px-2 flex items-center' : ''}`}
title={encounterFullscreen ? 'Exit encounter popout' : 'Expand encounter to full page'} title={encounterFullscreen ? 'Back to encounters' : 'Expand encounter to full page'}
aria-label={encounterFullscreen ? 'Exit encounter popout' : 'Expand encounter to full page'} aria-label={encounterFullscreen ? 'Back to encounters' : 'Expand encounter to full page'}
> >
{encounterFullscreen ? <PanelTopClose size={18} /> : <PanelTopOpen size={18} />} {encounterFullscreen ? <PanelTopClose size={18} /> : <PanelTopOpen size={18} />}
{encounterFullscreen && <span className="ml-1 text-sm">Back to encounters</span>}
</button> </button>
</span> </span>
</h3> </h3>
+79
View File
@@ -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();
});
});
+69
View File
@@ -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();
});
});
+81
View File
@@ -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();
});
});
+78
View File
@@ -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();
});
});