Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8a0ba2b60 | ||
|
|
3b166403e8 | ||
|
|
6122c19cf1 | ||
|
|
83693d4aa9 | ||
|
|
09cf9291eb | ||
|
|
ea17c5e26e | ||
|
|
23aa99ba0a | ||
|
|
dc0a1f1633 | ||
|
|
119d252d02 | ||
|
|
30712f0e1e | ||
|
|
7d0ea883b0 | ||
|
|
5c062bf944 |
No files matched your search
@@ -1,3 +1,4 @@
|
|||||||
|
TODO.md
|
||||||
node_modules
|
node_modules
|
||||||
**/node_modules
|
**/node_modules
|
||||||
.git
|
.git
|
||||||
|
|||||||
@@ -2,44 +2,51 @@
|
|||||||
|
|
||||||
Backlog of bugs + long-term items. Milestones live in REWORK_PLAN.md.
|
Backlog of bugs + long-term items. Milestones live in REWORK_PLAN.md.
|
||||||
|
|
||||||
|
|
||||||
## Open
|
## Open
|
||||||
|
|
||||||
|
x caff doent work on fron tpage or big tablet
|
||||||
|
|
||||||
|
x max/caff need to float or at least be availabe in combagt popout
|
||||||
|
|
||||||
|
x save needs bigger save button on char editor
|
||||||
|
|
||||||
|
|
||||||
x fullscreen and dont lock on main app dm view and the no-game-player view ...and doesnt actually prevent lock on android
|
x fullscreen and dont lock on main app dm view and the no-game-player view ...and doesnt actually prevent lock on android
|
||||||
|
|
||||||
also better vert tab layout - labelt friendly
|
x also better vert tab layout - labelt friendly
|
||||||
|
|
||||||
x needs AC for players dude
|
x needs AC for players dude
|
||||||
|
|
||||||
x and quick entry hp
|
x and quick entry hp
|
||||||
|
|
||||||
hp do not carry from encounter to ecnounter!!!
|
x hp do not carry from encounter to ecnounter!!!
|
||||||
^feature to add back to campaign character after encounter?
|
^feature to add back to campaign character after encounter?
|
||||||
maybe campaign toggle in charc section (choosing each end is DM overload will be missed forgotten done wront)
|
maybe campaign toggle in charc section (choosing each end is DM overload will be missed forgotten done wront)
|
||||||
|
|
||||||
hp wont go over max and no temp hp support
|
|
||||||
|
|
||||||
|
|
||||||
x refresh/reload/code update causes UI to update to top unselected cambpaign have to drill all the way back down to active encounter....every time. siemtmes?
|
x refresh/reload/code update causes UI to update to top unselected cambpaign have to drill all the way back down to active encounter....every time. siemtmes?
|
||||||
|
|
||||||
|
x encounters cards need clear "in progress"...
|
||||||
|
|
||||||
I wonder...if a charcter-list-character should have a isNPC option vailble to them - for longer lived
|
|
||||||
|
|
||||||
|
x I wonder...if a charcter-list-character should have a isNPC option vailble to them - for longer lived
|
||||||
npcs.....
|
npcs.....
|
||||||
|
|
||||||
|
x hp wont go over max and no temp hp support
|
||||||
|
|
||||||
|
|
||||||
|
## monsters per campaign and npcs
|
||||||
|
## or/and ....copy from encoubnter?
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### dm list - keep active particpant in view (scroll)
|
|
||||||
not sure good way to do this
|
|
||||||
|
|
||||||
|
|
||||||
### npm install warnings cleanup pass
|
### npm install warnings cleanup pass
|
||||||
lots of updates
|
lots of updates
|
||||||
|
|
||||||
|
|
||||||
## monsters per campaign and npcs
|
|
||||||
## or/and ....copy from encoubnter?
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Executable
+4
@@ -0,0 +1,4 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
export DOCKER_CONTEXT=bee
|
||||||
|
exec "$(dirname "$0")/restart.sh"
|
||||||
@@ -1,27 +1,25 @@
|
|||||||
{
|
{
|
||||||
|
"id": "/display",
|
||||||
"short_name": "TTRPG Display",
|
"short_name": "TTRPG Display",
|
||||||
"name": "TTRPG Initiative Tracker — Player Display",
|
"name": "TTRPG Initiative Tracker - Player Display",
|
||||||
"icons": [
|
"icons": [
|
||||||
{
|
{
|
||||||
"src": "favicon.ico",
|
"src": "player-favicon.ico",
|
||||||
"sizes": "64x64 32x32 24x24 16x16",
|
"sizes": "64x64 32x32 24x24 16x16",
|
||||||
"type": "image/x-icon"
|
"type": "image/x-icon"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "logo192.png",
|
"src": "player-logo192.png",
|
||||||
|
"note": "this image intentionally missing from filesystem - keeping manfiest and having broken icon allows android to _shortcut_ which user can control name of.",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"sizes": "192x192"
|
"sizes": "192x192"
|
||||||
},
|
|
||||||
{
|
|
||||||
"src": "logo512.png",
|
|
||||||
"type": "image/png",
|
|
||||||
"sizes": "512x512"
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"start_url": "/display",
|
"start_url": "/display",
|
||||||
"scope": "/",
|
"scope": "/display",
|
||||||
"display": "standalone",
|
"note:" "none of the display stuff actually works, even when it properly installs a pwa (which user cant control name of...)",
|
||||||
"orientation": "landscape",
|
"display": "fullscreen",
|
||||||
|
"orientation": "portrait",
|
||||||
"theme_color": "#1A202C",
|
"theme_color": "#1A202C",
|
||||||
"background_color": "#1A202C"
|
"background_color": "#1A202C"
|
||||||
}
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 7.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
@@ -1,4 +1,5 @@
|
|||||||
{
|
{
|
||||||
|
"id": "/",
|
||||||
"short_name": "TTRPG Tracker",
|
"short_name": "TTRPG Tracker",
|
||||||
"name": "TTRPG Initiative Tracker",
|
"name": "TTRPG Initiative Tracker",
|
||||||
"icons": [
|
"icons": [
|
||||||
@@ -9,17 +10,16 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "logo192.png",
|
"src": "logo192.png",
|
||||||
|
"note": "this image intentionally missing from filesystem - keeping manfiest and having broken icon allows android to _shortcut_ which user can control name of.",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"sizes": "192x192"
|
"sizes": "192x192"
|
||||||
},
|
|
||||||
{
|
|
||||||
"src": "logo512.png",
|
|
||||||
"type": "image/png",
|
|
||||||
"sizes": "512x512"
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"start_url": ".",
|
"start_url": "/",
|
||||||
"display": "standalone",
|
"scope": "/",
|
||||||
|
"note:" "none of the display stuff actually works, even when it properly installs a pwa (which user cant control name of...)",
|
||||||
|
"display": "fullscreen",
|
||||||
|
"orientation": "portrait",
|
||||||
"theme_color": "#2D3748",
|
"theme_color": "#2D3748",
|
||||||
"background_color": "#1A202C"
|
"background_color": "#1A202C"
|
||||||
}
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 7.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 5.1 KiB |
@@ -1,21 +1,30 @@
|
|||||||
// STATIC GUARD: prod source must pass eslint with zero errors/warnings.
|
// STATIC GUARD: prod source must pass eslint with zero errors/warnings.
|
||||||
// Scans App.js + storage adapters + shared modules. Catches unused imports,
|
// Scans ALL .js/.jsx in src/ + shared/ (excl tests/mocks). Catches unused imports,
|
||||||
// dead code, undefined vars before they hit the browser console.
|
// dead code, undefined vars before they hit the browser console.
|
||||||
// Run via: npx eslint <files> --format json -> parse -> fail on any problem.
|
// Run via: npx eslint <files> --format json -> parse -> fail on any problem.
|
||||||
const { execSync } = require('child_process');
|
const { execSync } = require('child_process');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
const ROOT = path.resolve(__dirname, '..', '..');
|
const ROOT = path.resolve(__dirname, '..', '..');
|
||||||
|
|
||||||
|
function walkJs(dir) {
|
||||||
|
let out = [];
|
||||||
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
const full = path.join(dir, entry.name);
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
if (entry.name === 'node_modules' || entry.name === 'tests' || entry.name === '__mocks__') continue;
|
||||||
|
out = out.concat(walkJs(full));
|
||||||
|
} else if (/\.(js|jsx)$/.test(entry.name)) {
|
||||||
|
out.push(full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
const TARGETS = [
|
const TARGETS = [
|
||||||
'src/App.js',
|
...walkJs(path.join(ROOT, 'src')),
|
||||||
'src/storage/contract.js',
|
...walkJs(path.join(ROOT, 'shared')),
|
||||||
'src/storage/firebase.js',
|
|
||||||
'src/storage/index.js',
|
|
||||||
'src/storage/server.js',
|
|
||||||
'shared/index.js',
|
|
||||||
'shared/logEvent.js',
|
|
||||||
'shared/turn.js',
|
|
||||||
];
|
];
|
||||||
|
|
||||||
function runEslint(files) {
|
function runEslint(files) {
|
||||||
|
|||||||
@@ -139,6 +139,55 @@ describe('character writeback on endEncounter', () => {
|
|||||||
expect(fighterOld.defaultCurrentHp).toBe(30);
|
expect(fighterOld.defaultCurrentHp).toBe(30);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('writeback uses ctx.campaignPath when provided (firebase prefixed paths)', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 }];
|
||||||
|
const prefixed = 'artifacts/app1/public/data/campaigns/camp1';
|
||||||
|
storage._docs.set(prefixed, { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
campaignPath: prefixed,
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
await endEncounter(enc, ctx);
|
||||||
|
expect(storage._writes.find(w => w.path === 'campaigns/camp1')).toBeUndefined();
|
||||||
|
const campWrite = storage._writes.find(w => w.path === prefixed);
|
||||||
|
expect(campWrite).toBeDefined();
|
||||||
|
expect(campWrite.patch.players.find(p => p.id === 'char1').defaultMaxHp).toBe(28);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('writeback failure does not block ending combat', 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 });
|
||||||
|
storage.updateDoc = jest.fn(async (p, patch) => {
|
||||||
|
if (p === 'campaigns/camp1') throw new Error('No document to update');
|
||||||
|
storage._writes.push({ path: p, patch });
|
||||||
|
});
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
encPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
const newEnc = await endEncounter(enc, ctx);
|
||||||
|
expect(newEnc.isStarted).toBe(false);
|
||||||
|
expect(newEnc.currentTurnParticipantId).toBe(null);
|
||||||
|
// participants are preserved — ending combat never clears the roster
|
||||||
|
expect(newEnc.participants).toHaveLength(3);
|
||||||
|
const encWrite = storage._writes.find(w => w.path === 'campaigns/camp1/encounters/enc1');
|
||||||
|
expect(encWrite).toBeDefined();
|
||||||
|
expect(encWrite.patch.isStarted).toBe(false);
|
||||||
|
expect(encWrite.patch.participants).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
test('writeback no-op if character missing from campaign', async () => {
|
test('writeback no-op if character missing from campaign', async () => {
|
||||||
const storage = makeMockStorage();
|
const storage = makeMockStorage();
|
||||||
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players: [], syncCharacters: true });
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players: [], syncCharacters: true });
|
||||||
|
|||||||
+11
-3
@@ -1129,11 +1129,15 @@ async function endEncounter(encounter, ctx) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Character writeback: sync maxHp/ac/currentHp to campaign players if enabled.
|
// Character writeback: sync maxHp/ac/currentHp to campaign players if enabled.
|
||||||
|
// ctx.campaignPath: adapter-specific doc path (firebase needs the full
|
||||||
|
// artifacts/{APP_ID}/public/data prefix); bare campaigns/{id} fallback for
|
||||||
|
// server/test adapters. Writeback failure must not block ending combat.
|
||||||
const wbCampaignId = encounter.campaignId || ctx.campaignId;
|
const wbCampaignId = encounter.campaignId || ctx.campaignId;
|
||||||
if ((wbCampaignId || ctx.campaign) && ctx.storage) {
|
if ((wbCampaignId || ctx.campaign) && ctx.storage) {
|
||||||
|
const campaignPath = ctx.campaignPath || `campaigns/${wbCampaignId}`;
|
||||||
let campaign;
|
let campaign;
|
||||||
try {
|
try {
|
||||||
campaign = ctx.campaign || await ctx.storage.getDoc(`campaigns/${wbCampaignId}`);
|
campaign = ctx.campaign || await ctx.storage.getDoc(campaignPath);
|
||||||
} catch { campaign = null; }
|
} catch { campaign = null; }
|
||||||
if (campaign && campaign.syncCharacters && Array.isArray(campaign.players)) {
|
if (campaign && campaign.syncCharacters && Array.isArray(campaign.players)) {
|
||||||
const charParticipants = (encounter.participants || []).filter(p => p.originalCharacterId);
|
const charParticipants = (encounter.participants || []).filter(p => p.originalCharacterId);
|
||||||
@@ -1153,8 +1157,12 @@ async function endEncounter(encounter, ctx) {
|
|||||||
return newPlayer;
|
return newPlayer;
|
||||||
});
|
});
|
||||||
if (changed) {
|
if (changed) {
|
||||||
await ctx.storage.updateDoc(`campaigns/${wbCampaignId}`, { players: updatedPlayers });
|
try {
|
||||||
log.undo.characterWriteback = oldValues;
|
await ctx.storage.updateDoc(campaignPath, { players: updatedPlayers });
|
||||||
|
log.undo.characterWriteback = oldValues;
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`endEncounter: character writeback failed (${campaignPath}):`, err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+296
-48
@@ -8,8 +8,8 @@ import {
|
|||||||
UserCheck, UserX, HeartCrack, HeartPulse, Zap, EyeOff, ExternalLink, AlertTriangle,
|
UserCheck, UserX, HeartCrack, HeartPulse, Zap, EyeOff, ExternalLink, AlertTriangle,
|
||||||
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, 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) -----
|
||||||
@@ -1051,8 +1051,12 @@ function CharacterManager({ campaignId, campaignCharacters, syncCharacters }) {
|
|||||||
/>
|
/>
|
||||||
NPC
|
NPC
|
||||||
</label>
|
</label>
|
||||||
<button type="submit" className="p-1 text-green-400 hover:text-green-300">
|
<button
|
||||||
<Save size={18} />
|
type="submit"
|
||||||
|
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-md bg-green-700 hover:bg-green-600 text-white font-semibold text-sm min-h-[40px]"
|
||||||
|
aria-label="Save character"
|
||||||
|
>
|
||||||
|
<Save size={18} /> Save
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -1763,7 +1767,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
const isGeneric = (encounter.ruleset || '5e') === 'generic';
|
const isGeneric = (encounter.ruleset || '5e') === 'generic';
|
||||||
const hasDeathSaves = !isGeneric && (p.type === 'character' || p.type === 'npc');
|
const hasDeathSaves = !isGeneric && (p.type === 'character' || p.type === 'npc');
|
||||||
|
|
||||||
let bgColor = p.type === 'character' ? 'bg-indigo-950' : 'bg-[#8e351c]';
|
let bgColor = !p.isActive ? 'bg-stone-800' : (p.type === 'character' ? 'bg-indigo-950' : 'bg-[#8e351c]');
|
||||||
if (isCurrentTurn && !encounter.isPaused) bgColor = 'bg-green-600';
|
if (isCurrentTurn && !encounter.isPaused) bgColor = 'bg-green-600';
|
||||||
|
|
||||||
const participantStatus = p.status || (isGeneric
|
const participantStatus = p.status || (isGeneric
|
||||||
@@ -1781,7 +1785,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
onDragOver={isDraggable ? handleDragOver : undefined}
|
onDragOver={isDraggable ? handleDragOver : undefined}
|
||||||
onDrop={isDraggable ? (e) => handleDrop(e, p.id) : undefined}
|
onDrop={isDraggable ? (e) => handleDrop(e, p.id) : undefined}
|
||||||
onDragEnd={() => setDraggedItemId(null)}
|
onDragEnd={() => setDraggedItemId(null)}
|
||||||
className={`relative p-3 rounded-md flex flex-col sm:flex-row justify-between items-start sm:items-center gap-2 transition-all duration-300 ${bgColor} ${isCurrentTurn && !encounter.isPaused ? 'ring-2 ring-green-300 shadow-lg' : ''} ${!p.isActive ? 'opacity-35 grayscale' : (isDead ? 'opacity-90 brightness-75 saturate-125' : '')} ${isDraggable ? 'cursor-grab' : ''} ${draggedItemId === p.id ? 'opacity-50 ring-2 ring-yellow-400' : ''} ${editingId === p.id ? 'ring-2 ring-amber-400' : ''}`}
|
className={`relative p-3 rounded-md flex flex-col sm:flex-row justify-between items-start sm:items-center gap-2 transition-all duration-300 ${bgColor} ${isCurrentTurn && !encounter.isPaused ? 'ring-2 ring-green-300 shadow-lg' : ''} ${!p.isActive ? 'ring-2 ring-stone-500' : (isDead ? 'opacity-90 brightness-75 saturate-125' : '')} ${isDraggable ? 'cursor-grab' : ''} ${draggedItemId === p.id ? 'opacity-50 ring-2 ring-yellow-400' : ''} ${editingId === p.id ? 'ring-2 ring-amber-400' : ''}`}
|
||||||
>
|
>
|
||||||
{editingId === p.id && (
|
{editingId === p.id && (
|
||||||
<span className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center">
|
<span className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center">
|
||||||
@@ -2062,22 +2066,28 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
|||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => toggleParticipantActive(p.id)}
|
onClick={() => toggleParticipantActive(p.id)}
|
||||||
className={`p-1 rounded transition-colors ${p.isActive ? 'text-yellow-400 hover:text-yellow-300' : 'text-stone-400 hover:text-stone-300'} bg-stone-700 hover:bg-stone-600`}
|
className={`p-1 rounded transition-all ring-2 ${p.isActive ? 'bg-emerald-700 hover:bg-emerald-600 text-white ring-emerald-300' : 'bg-red-900 hover:bg-red-800 text-red-100 ring-red-500'}`}
|
||||||
title={p.isActive ? "Mark Inactive" : "Mark Active"}
|
title={p.isActive ? "Participant active — click to disable" : "Participant inactive — click to enable"}
|
||||||
|
aria-label={p.isActive ? "Disable participant" : "Enable participant"}
|
||||||
|
aria-pressed={p.isActive}
|
||||||
>
|
>
|
||||||
{p.isActive ? <UserCheck size={18} /> : <UserX size={18} />}
|
{p.isActive ? <UserCheck size={18} /> : <UserX size={18} />}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => setOpenConditionsId(openConditionsId === p.id ? null : p.id)}
|
onClick={() => setOpenConditionsId(openConditionsId === p.id ? null : p.id)}
|
||||||
className={`p-1 rounded transition-colors bg-stone-700 hover:bg-stone-600 ${openConditionsId === p.id || (p.conditions || []).length > 0 ? 'text-purple-400 hover:text-purple-300' : 'text-stone-400 hover:text-stone-300'}`}
|
className={`p-1 rounded transition-all ${openConditionsId === p.id ? 'bg-purple-700 text-white ring-2 ring-purple-300' : (p.conditions || []).length > 0 ? 'bg-stone-700 text-purple-300 ring-1 ring-purple-500 hover:bg-stone-600' : 'bg-stone-700 text-stone-300 hover:bg-stone-600'}`}
|
||||||
title="Conditions"
|
title={openConditionsId === p.id ? 'Conditions open — click to close' : 'Open conditions'}
|
||||||
|
aria-label={openConditionsId === p.id ? 'Close conditions' : 'Open conditions'}
|
||||||
|
aria-expanded={openConditionsId === p.id}
|
||||||
>
|
>
|
||||||
<span className="text-base leading-none">✨</span>
|
<span className="text-base leading-none">✨</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => setEditingParticipant(p)}
|
onClick={() => setEditingParticipant(editingParticipant?.id === p.id ? null : p)}
|
||||||
className="p-1 rounded transition-colors text-yellow-400 hover:text-yellow-300 bg-stone-700 hover:bg-stone-600"
|
className={`p-1 rounded transition-all ${editingParticipant?.id === p.id ? 'bg-amber-500 text-stone-950 ring-2 ring-amber-200' : 'text-yellow-300 bg-stone-700 hover:bg-stone-600'}`}
|
||||||
title="Edit"
|
title={editingParticipant?.id === p.id ? 'Editing — click to close' : 'Edit participant'}
|
||||||
|
aria-label={editingParticipant?.id === p.id ? 'Close participant editor' : 'Edit participant'}
|
||||||
|
aria-pressed={editingParticipant?.id === p.id}
|
||||||
>
|
>
|
||||||
<Edit3 size={18} />
|
<Edit3 size={18} />
|
||||||
</button>
|
</button>
|
||||||
@@ -2271,8 +2281,9 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
|||||||
try {
|
try {
|
||||||
const ctx = { ...buildCtx(encounterPath), campaignId };
|
const ctx = { ...buildCtx(encounterPath), campaignId };
|
||||||
if (campaignId) {
|
if (campaignId) {
|
||||||
|
ctx.campaignPath = getPath.campaign(campaignId);
|
||||||
try {
|
try {
|
||||||
ctx.campaign = await storage.getDoc(getPath.campaign(campaignId));
|
ctx.campaign = await storage.getDoc(ctx.campaignPath);
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
await endEncounter(encounter, ctx);
|
await endEncounter(encounter, ctx);
|
||||||
@@ -2402,7 +2413,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
|||||||
// ENCOUNTER MANAGER COMPONENT
|
// ENCOUNTER MANAGER COMPONENT
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharacters, encounterStartedRef, encounterActiveRef }) {
|
function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharacters, encounterStartedRef, encounterActiveRef, wakeLockEnabled, onToggleWakeLock, isBrowserFullscreen, onToggleBrowserFullscreen }) {
|
||||||
const { showToast } = useUIFeedback();
|
const { showToast } = useUIFeedback();
|
||||||
const { data: encountersData, isLoading: isLoadingEncounters } = useFirestoreCollection(
|
const { data: encountersData, isLoading: isLoadingEncounters } = useFirestoreCollection(
|
||||||
campaignId ? getPath.encounters(campaignId) : null
|
campaignId ? getPath.encounters(campaignId) : null
|
||||||
@@ -2417,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;
|
||||||
@@ -2494,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 (
|
||||||
@@ -2627,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;
|
||||||
@@ -2649,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>
|
||||||
@@ -2678,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();
|
||||||
@@ -2692,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">
|
||||||
@@ -2707,16 +2877,36 @@ 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">
|
<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>Managing Encounter: {selectedEncounter.name}</span>
|
<span className="min-w-0 truncate">Managing Encounter: {selectedEncounter.name}</span>
|
||||||
<button
|
<span className="flex items-center gap-1 flex-shrink-0">
|
||||||
onClick={() => setEncounterFullscreen(v => !v)}
|
<button
|
||||||
className="ml-2 p-1.5 rounded-md text-stone-300 bg-stone-700 hover:bg-stone-600 transition-colors flex-shrink-0"
|
onClick={onToggleWakeLock}
|
||||||
title={encounterFullscreen ? 'Exit fullscreen encounter' : 'Fullscreen encounter'}
|
className={`p-1.5 rounded-md transition-colors ${wakeLockEnabled ? 'bg-amber-600 text-white hover:bg-amber-700' : 'bg-stone-700 text-stone-300 hover:bg-stone-600'}`}
|
||||||
>
|
title={wakeLockEnabled ? 'Allow sleep' : 'Prevent sleep'}
|
||||||
{encounterFullscreen ? <Minimize2 size={18} /> : <Maximize2 size={18} />}
|
aria-label={wakeLockEnabled ? 'Allow sleep' : 'Prevent sleep'}
|
||||||
</button>
|
>
|
||||||
|
{wakeLockEnabled ? <Coffee size={18} /> : <Moon size={18} />}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={onToggleBrowserFullscreen}
|
||||||
|
className="p-1.5 rounded-md text-stone-300 bg-stone-700 hover:bg-stone-600 transition-colors"
|
||||||
|
title={isBrowserFullscreen ? 'Exit browser fullscreen' : 'Enter browser fullscreen'}
|
||||||
|
aria-label={isBrowserFullscreen ? 'Exit browser fullscreen' : 'Enter browser fullscreen'}
|
||||||
|
>
|
||||||
|
{isBrowserFullscreen ? <Minimize2 size={18} /> : <Maximize2 size={18} />}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={encounterFullscreen ? closeEncounter : () => setEncounterFullscreen(true)}
|
||||||
|
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 ? 'Back to encounters' : 'Expand encounter to full page'}
|
||||||
|
aria-label={encounterFullscreen ? 'Back to encounters' : 'Expand encounter to full page'}
|
||||||
|
>
|
||||||
|
{encounterFullscreen ? <PanelTopClose size={18} /> : <PanelTopOpen size={18} />}
|
||||||
|
{encounterFullscreen && <span className="ml-1 text-sm">Back to encounters</span>}
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
</h3>
|
</h3>
|
||||||
<div className="flex flex-row gap-4">
|
<div className="flex flex-row gap-4">
|
||||||
{/* Combat Controls - always left */}
|
{/* Combat Controls - always left */}
|
||||||
@@ -2770,21 +2960,43 @@ function AdminView({ userId }) {
|
|||||||
catch { return false; }
|
catch { return false; }
|
||||||
});
|
});
|
||||||
const wakeLockRef = useRef(null);
|
const wakeLockRef = useRef(null);
|
||||||
|
const fullscreenWantedRef = useRef(false);
|
||||||
|
|
||||||
const toggleFullscreen = () => {
|
const toggleFullscreen = async () => {
|
||||||
if (!document.fullscreenElement) {
|
try {
|
||||||
document.documentElement.requestFullscreen();
|
if (!document.fullscreenElement) {
|
||||||
} else {
|
fullscreenWantedRef.current = true;
|
||||||
document.exitFullscreen();
|
await document.documentElement.requestFullscreen();
|
||||||
|
} else {
|
||||||
|
fullscreenWantedRef.current = false;
|
||||||
|
await document.exitFullscreen();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showToast('Fullscreen failed. Tap fullscreen again.');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onFsChange = () => setIsFullscreen(!!document.fullscreenElement);
|
const onFsChange = () => {
|
||||||
|
const active = !!document.fullscreenElement;
|
||||||
|
setIsFullscreen(active);
|
||||||
|
if (active) fullscreenWantedRef.current = true;
|
||||||
|
else if (document.visibilityState === 'visible') fullscreenWantedRef.current = false;
|
||||||
|
};
|
||||||
document.addEventListener('fullscreenchange', onFsChange);
|
document.addEventListener('fullscreenchange', onFsChange);
|
||||||
return () => document.removeEventListener('fullscreenchange', onFsChange);
|
return () => document.removeEventListener('fullscreenchange', onFsChange);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const restoreFullscreen = async () => {
|
||||||
|
if (document.visibilityState === 'visible' && fullscreenWantedRef.current && !document.fullscreenElement) {
|
||||||
|
try { await document.documentElement.requestFullscreen(); } catch (e) { /* browser may require tap */ }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', restoreFullscreen);
|
||||||
|
return () => document.removeEventListener('visibilitychange', restoreFullscreen);
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!wakeLockEnabled) {
|
if (!wakeLockEnabled) {
|
||||||
wakeLockRef.current?.release();
|
wakeLockRef.current?.release();
|
||||||
@@ -2792,8 +3004,13 @@ function AdminView({ userId }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const acquire = async () => {
|
const acquire = async () => {
|
||||||
try { wakeLockRef.current = await navigator.wakeLock.request('screen'); }
|
if (document.visibilityState !== 'visible' || wakeLockRef.current?.released === false) return;
|
||||||
catch (e) {
|
try {
|
||||||
|
if (!navigator.wakeLock?.request) throw new Error('Wake Lock API unavailable');
|
||||||
|
const sentinel = await navigator.wakeLock.request('screen');
|
||||||
|
wakeLockRef.current = sentinel;
|
||||||
|
sentinel.addEventListener?.('release', () => { wakeLockRef.current = null; });
|
||||||
|
} catch (e) {
|
||||||
console.error('Wake lock failed:', e);
|
console.error('Wake lock failed:', e);
|
||||||
showToast('Prevent Sleep failed. Requires HTTPS or Chrome flag: chrome://flags/#unsafely-treat-insecure-origin-as-secure');
|
showToast('Prevent Sleep failed. Requires HTTPS or Chrome flag: chrome://flags/#unsafely-treat-insecure-origin-as-secure');
|
||||||
}
|
}
|
||||||
@@ -3250,6 +3467,10 @@ function AdminView({ userId }) {
|
|||||||
campaignCharacters={selectedCampaign.characters || []}
|
campaignCharacters={selectedCampaign.characters || []}
|
||||||
encounterStartedRef={encounterStartedRef}
|
encounterStartedRef={encounterStartedRef}
|
||||||
encounterActiveRef={encounterActiveRef}
|
encounterActiveRef={encounterActiveRef}
|
||||||
|
wakeLockEnabled={wakeLockEnabled}
|
||||||
|
onToggleWakeLock={() => setWakeLockEnabled(v => { localStorage.setItem('ttrpg.wakeLock', String(!v)); return !v; })}
|
||||||
|
isBrowserFullscreen={isFullscreen}
|
||||||
|
onToggleBrowserFullscreen={toggleFullscreen}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -3350,6 +3571,7 @@ function DisplayView() {
|
|||||||
});
|
});
|
||||||
const [displayParticipants, setDisplayParticipants] = useState([]);
|
const [displayParticipants, setDisplayParticipants] = useState([]);
|
||||||
const wakeLockRef = useRef(null);
|
const wakeLockRef = useRef(null);
|
||||||
|
const fullscreenWantedRef = useRef(false);
|
||||||
const currentParticipantRef = useRef(null);
|
const currentParticipantRef = useRef(null);
|
||||||
|
|
||||||
// Player display transition state. Active participants render normally.
|
// Player display transition state. Active participants render normally.
|
||||||
@@ -3380,19 +3602,40 @@ function DisplayView() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onFsChange = () => setIsFullscreen(!!document.fullscreenElement);
|
const onFsChange = () => {
|
||||||
|
const active = !!document.fullscreenElement;
|
||||||
|
setIsFullscreen(active);
|
||||||
|
if (active) fullscreenWantedRef.current = true;
|
||||||
|
else if (document.visibilityState === 'visible') fullscreenWantedRef.current = false;
|
||||||
|
};
|
||||||
document.addEventListener('fullscreenchange', onFsChange);
|
document.addEventListener('fullscreenchange', onFsChange);
|
||||||
return () => document.removeEventListener('fullscreenchange', onFsChange);
|
return () => document.removeEventListener('fullscreenchange', onFsChange);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const toggleFullscreen = () => {
|
const toggleFullscreen = async () => {
|
||||||
if (!document.fullscreenElement) {
|
try {
|
||||||
document.documentElement.requestFullscreen();
|
if (!document.fullscreenElement) {
|
||||||
} else {
|
fullscreenWantedRef.current = true;
|
||||||
document.exitFullscreen();
|
await document.documentElement.requestFullscreen();
|
||||||
|
} else {
|
||||||
|
fullscreenWantedRef.current = false;
|
||||||
|
await document.exitFullscreen();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Fullscreen failed:', e);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const restoreFullscreen = async () => {
|
||||||
|
if (document.visibilityState === 'visible' && fullscreenWantedRef.current && !document.fullscreenElement) {
|
||||||
|
try { await document.documentElement.requestFullscreen(); } catch (e) { /* browser may require tap */ }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', restoreFullscreen);
|
||||||
|
return () => document.removeEventListener('visibilitychange', restoreFullscreen);
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!wakeLockEnabled) {
|
if (!wakeLockEnabled) {
|
||||||
wakeLockRef.current?.release();
|
wakeLockRef.current?.release();
|
||||||
@@ -3401,8 +3644,12 @@ function DisplayView() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const acquire = async () => {
|
const acquire = async () => {
|
||||||
|
if (document.visibilityState !== 'visible' || wakeLockRef.current?.released === false) return;
|
||||||
try {
|
try {
|
||||||
wakeLockRef.current = await navigator.wakeLock.request('screen');
|
if (!navigator.wakeLock?.request) throw new Error('Wake Lock API unavailable');
|
||||||
|
const sentinel = await navigator.wakeLock.request('screen');
|
||||||
|
wakeLockRef.current = sentinel;
|
||||||
|
sentinel.addEventListener?.('release', () => { wakeLockRef.current = null; });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Wake lock failed:', e);
|
console.error('Wake lock failed:', e);
|
||||||
}
|
}
|
||||||
@@ -3410,10 +3657,9 @@ function DisplayView() {
|
|||||||
|
|
||||||
acquire();
|
acquire();
|
||||||
|
|
||||||
// Re-acquire after tab becomes visible again (browser auto-releases on hide)
|
// Re-acquire after tab becomes visible again (browser auto-releases on hide).
|
||||||
const onVisChange = () => { if (document.visibilityState === 'visible') acquire(); };
|
const onVisChange = () => { if (document.visibilityState === 'visible') acquire(); };
|
||||||
document.addEventListener('visibilitychange', onVisChange);
|
document.addEventListener('visibilitychange', onVisChange);
|
||||||
// Re-acquire on fullscreen change (Android discards wakeLock on screen off)
|
|
||||||
const onFsChange = () => { if (document.fullscreenElement) acquire(); };
|
const onFsChange = () => { if (document.fullscreenElement) acquire(); };
|
||||||
document.addEventListener('fullscreenchange', onFsChange);
|
document.addEventListener('fullscreenchange', onFsChange);
|
||||||
return () => {
|
return () => {
|
||||||
@@ -4057,6 +4303,8 @@ function App() {
|
|||||||
// swap manifest so Android home-screen installs launch /display
|
// swap manifest so Android home-screen installs launch /display
|
||||||
const link = document.querySelector('link[rel="manifest"]');
|
const link = document.querySelector('link[rel="manifest"]');
|
||||||
if (link) link.href = `${process.env.PUBLIC_URL || ''}/display-manifest.json`;
|
if (link) link.href = `${process.env.PUBLIC_URL || ''}/display-manifest.json`;
|
||||||
|
const favicon = document.querySelector('link[rel="icon"]');
|
||||||
|
if (favicon) favicon.href = `${process.env.PUBLIC_URL || ''}/player-favicon.ico`;
|
||||||
}
|
}
|
||||||
if (window.location.pathname === '/logs') {
|
if (window.location.pathname === '/logs') {
|
||||||
setIsLogsMode(true);
|
setIsLogsMode(true);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// Dev-tools gate. Explicit opt-in via REACT_APP_DEV_TOOLS=1.
|
// Dev-tools gate. Explicit opt-in via REACT_APP_DEV_TOOLS=1.
|
||||||
// Safe default: any value other than exactly '1' = off.
|
// Safe default: any value other than exactly '1' = off.
|
||||||
// Dynamic key access so react-scripts DefinePlugin does NOT inline the value
|
// Dynamic key access (process.env[KEY]) so react-scripts DefinePlugin does NOT
|
||||||
// at build time — allows tests + runtime env changes to take effect.
|
// inline the value at build time — allows tests + runtime env changes to take
|
||||||
const KEY = 'REACT_APP_' + 'DEV_TOOLS';
|
// effect. DefinePlugin only replaces static member access, never computed lookups.
|
||||||
|
const KEY = 'REACT_APP_DEV_TOOLS';
|
||||||
export const isDevToolsEnabled = () => process.env[KEY] === '1';
|
export const isDevToolsEnabled = () => process.env[KEY] === '1';
|
||||||
@@ -39,6 +39,10 @@ function participant(status) {
|
|||||||
|
|
||||||
describe('DisplayView characterization', () => {
|
describe('DisplayView characterization', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
const favicon = document.createElement('link');
|
||||||
|
favicon.rel = 'icon';
|
||||||
|
favicon.href = '/favicon.ico';
|
||||||
|
document.head.appendChild(favicon);
|
||||||
window.history.replaceState({}, '', '/display');
|
window.history.replaceState({}, '', '/display');
|
||||||
global.alert = jest.fn();
|
global.alert = jest.fn();
|
||||||
window.open = jest.fn();
|
window.open = jest.fn();
|
||||||
@@ -46,9 +50,18 @@ describe('DisplayView characterization', () => {
|
|||||||
Element.prototype.scrollIntoView = jest.fn();
|
Element.prototype.scrollIntoView = jest.fn();
|
||||||
});
|
});
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
document.querySelectorAll('link[rel="icon"]').forEach(link => link.remove());
|
||||||
window.history.replaceState({}, '', '/');
|
window.history.replaceState({}, '', '/');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('display route swaps browser favicon to player icon', async () => {
|
||||||
|
seedActiveDisplay();
|
||||||
|
render(<App />);
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(document.querySelector('link[rel="icon"]')).toHaveAttribute('href', '/player-favicon.ico');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test('DisplayView subscribes via adapter.subscribeDoc (not raw SDK)', async () => {
|
test('DisplayView subscribes via adapter.subscribeDoc (not raw SDK)', async () => {
|
||||||
seedActiveDisplay();
|
seedActiveDisplay();
|
||||||
render(<App />);
|
render(<App />);
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -70,7 +70,7 @@ describe('Participant -> Firebase', () => {
|
|||||||
test('toggleActive: updateDoc flips isActive', async () => {
|
test('toggleActive: updateDoc flips isActive', async () => {
|
||||||
await setupReady();
|
await setupReady();
|
||||||
await addMonsterViaUI('Toggle', 10, 0);
|
await addMonsterViaUI('Toggle', 10, 0);
|
||||||
fireEvent.click(screen.getByTitle('Mark Inactive'));
|
fireEvent.click(screen.getByRole('button', { name: 'Disable participant' }));
|
||||||
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.isActive === false);
|
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.isActive === false);
|
||||||
expect(lastEncCall().data.participants[0].isActive).toBe(false);
|
expect(lastEncCall().data.participants[0].isActive).toBe(false);
|
||||||
});
|
});
|
||||||
@@ -116,7 +116,7 @@ describe('Participant -> Firebase', () => {
|
|||||||
test('toggleCondition: updateDoc adds condition to array', async () => {
|
test('toggleCondition: updateDoc adds condition to array', async () => {
|
||||||
await setupReady();
|
await setupReady();
|
||||||
await addMonsterViaUI('Cond', 10, 0);
|
await addMonsterViaUI('Cond', 10, 0);
|
||||||
fireEvent.click(screen.getByTitle('Conditions'));
|
fireEvent.click(screen.getByRole('button', { name: 'Open conditions' }));
|
||||||
await waitFor(() => screen.getByRole('button', { name: /Blinded/i }));
|
await waitFor(() => screen.getByRole('button', { name: /Blinded/i }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: /Blinded/i }));
|
fireEvent.click(screen.getByRole('button', { name: /Blinded/i }));
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { screen, fireEvent } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { setupReady, addMonsterViaUI } from './testHelpers';
|
||||||
|
|
||||||
|
describe('participant action selected states', () => {
|
||||||
|
test('active toggle clearly changes to selected inactive state', async () => {
|
||||||
|
await setupReady('ActionCamp1', 'ActionEnc1');
|
||||||
|
await addMonsterViaUI('Toggle Orc', 15, 3);
|
||||||
|
|
||||||
|
const disable = screen.getByRole('button', { name: 'Disable participant' });
|
||||||
|
expect(disable).toHaveAttribute('aria-pressed', 'true');
|
||||||
|
expect(disable).toHaveClass('bg-emerald-700');
|
||||||
|
fireEvent.click(disable);
|
||||||
|
|
||||||
|
const enable = await screen.findByRole('button', { name: 'Enable participant' });
|
||||||
|
expect(enable).toHaveAttribute('aria-pressed', 'false');
|
||||||
|
expect(enable).toHaveClass('bg-red-900', 'ring-red-500');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('conditions toggle highlights open state and gives close action', async () => {
|
||||||
|
await setupReady('ActionCamp2', 'ActionEnc2');
|
||||||
|
await addMonsterViaUI('Condition Orc', 15, 3);
|
||||||
|
|
||||||
|
const open = screen.getByRole('button', { name: 'Open conditions' });
|
||||||
|
expect(open).toHaveAttribute('aria-expanded', 'false');
|
||||||
|
fireEvent.click(open);
|
||||||
|
|
||||||
|
const close = screen.getByRole('button', { name: 'Close conditions' });
|
||||||
|
expect(close).toHaveAttribute('aria-expanded', 'true');
|
||||||
|
expect(close).toHaveClass('bg-purple-700', 'ring-purple-300');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('edit toggle exposes selected state while editor is open', async () => {
|
||||||
|
await setupReady('ActionCamp3', 'ActionEnc3');
|
||||||
|
await addMonsterViaUI('Edit Orc', 15, 3);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Edit participant' }));
|
||||||
|
const closeEditor = screen.getByRole('button', { name: 'Close participant editor' });
|
||||||
|
expect(closeEditor).toHaveAttribute('aria-pressed', 'true');
|
||||||
|
expect(closeEditor).toHaveClass('bg-amber-500', 'ring-amber-200');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -57,7 +57,7 @@ describe('reslot on all mutation paths', () => {
|
|||||||
expect(lastParticipantsUpdate().map(p => p.name)).toEqual(['Orc', 'Goblin']);
|
expect(lastParticipantsUpdate().map(p => p.name)).toEqual(['Orc', 'Goblin']);
|
||||||
|
|
||||||
// open edit modal for Goblin, bump init to 8
|
// open edit modal for Goblin, bump init to 8
|
||||||
const editBtns = screen.getAllByTitle('Edit');
|
const editBtns = screen.getAllByRole('button', { name: 'Edit participant' });
|
||||||
const goblinEdit = editBtns.find(b => b.closest('li')?.textContent.includes('Goblin'));
|
const goblinEdit = editBtns.find(b => b.closest('li')?.textContent.includes('Goblin'));
|
||||||
fireEvent.click(goblinEdit);
|
fireEvent.click(goblinEdit);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { setupReady } from './testHelpers';
|
||||||
|
|
||||||
|
describe('screen controls', () => {
|
||||||
|
let originalRequestFullscreen;
|
||||||
|
let originalExitFullscreen;
|
||||||
|
let originalFullscreenElement;
|
||||||
|
let originalVisibilityState;
|
||||||
|
let originalWakeLock;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
originalRequestFullscreen = document.documentElement.requestFullscreen;
|
||||||
|
originalExitFullscreen = document.exitFullscreen;
|
||||||
|
originalFullscreenElement = Object.getOwnPropertyDescriptor(document, 'fullscreenElement');
|
||||||
|
originalVisibilityState = Object.getOwnPropertyDescriptor(document, 'visibilityState');
|
||||||
|
originalWakeLock = Object.getOwnPropertyDescriptor(navigator, 'wakeLock');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
document.documentElement.requestFullscreen = originalRequestFullscreen;
|
||||||
|
document.exitFullscreen = originalExitFullscreen;
|
||||||
|
if (originalFullscreenElement) Object.defineProperty(document, 'fullscreenElement', originalFullscreenElement);
|
||||||
|
else Object.defineProperty(document, 'fullscreenElement', { configurable: true, value: null });
|
||||||
|
if (originalVisibilityState) Object.defineProperty(document, 'visibilityState', originalVisibilityState);
|
||||||
|
if (originalWakeLock) Object.defineProperty(navigator, 'wakeLock', originalWakeLock);
|
||||||
|
else Object.defineProperty(navigator, 'wakeLock', { configurable: true, value: undefined });
|
||||||
|
localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('encounter header exposes prevent-sleep, browser-fullscreen, and popout controls', async () => {
|
||||||
|
await setupReady('ScreenCamp', 'ScreenEnc');
|
||||||
|
|
||||||
|
expect(screen.getAllByRole('button', { name: 'Prevent sleep' }).length).toBeGreaterThanOrEqual(2);
|
||||||
|
expect(screen.getAllByRole('button', { name: 'Enter browser fullscreen' })).toHaveLength(1);
|
||||||
|
expect(screen.getByRole('button', { name: 'Expand encounter to full page' })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('re-acquires wake lock when tablet becomes visible after browser release', async () => {
|
||||||
|
let releaseListener;
|
||||||
|
const sentinel = {
|
||||||
|
released: false,
|
||||||
|
release: jest.fn().mockResolvedValue(undefined),
|
||||||
|
addEventListener: jest.fn((event, callback) => { if (event === 'release') releaseListener = callback; }),
|
||||||
|
};
|
||||||
|
const request = jest.fn().mockResolvedValue(sentinel);
|
||||||
|
Object.defineProperty(navigator, 'wakeLock', { configurable: true, value: { request } });
|
||||||
|
let visibility = 'visible';
|
||||||
|
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
|
||||||
|
|
||||||
|
await setupReady('WakeCamp', 'WakeEnc');
|
||||||
|
fireEvent.click(screen.getAllByRole('button', { name: 'Prevent sleep' })[0]);
|
||||||
|
await waitFor(() => expect(request).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
visibility = 'hidden';
|
||||||
|
releaseListener();
|
||||||
|
visibility = 'visible';
|
||||||
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
|
||||||
|
await waitFor(() => expect(request).toHaveBeenCalledTimes(2));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('character editor has labeled tablet-sized save button', async () => {
|
||||||
|
await setupReady('SaveCamp', 'SaveEnc');
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Tablet Hero' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText('Tablet Hero');
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Edit character' }));
|
||||||
|
const save = screen.getByRole('button', { name: 'Save character' });
|
||||||
|
expect(save).toHaveTextContent('Save');
|
||||||
|
expect(save).toHaveClass('min-h-[40px]');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('attempts to restore fullscreen when tablet becomes visible after lock', async () => {
|
||||||
|
const requestFullscreen = jest.fn().mockResolvedValue(undefined);
|
||||||
|
document.documentElement.requestFullscreen = requestFullscreen;
|
||||||
|
document.exitFullscreen = jest.fn().mockResolvedValue(undefined);
|
||||||
|
Object.defineProperty(document, 'fullscreenElement', { configurable: true, get: () => null });
|
||||||
|
let visibility = 'visible';
|
||||||
|
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
|
||||||
|
|
||||||
|
await setupReady('RestoreCamp', 'RestoreEnc');
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Enter browser fullscreen' }));
|
||||||
|
await waitFor(() => expect(requestFullscreen).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
visibility = 'hidden';
|
||||||
|
document.dispatchEvent(new Event('fullscreenchange'));
|
||||||
|
visibility = 'visible';
|
||||||
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
|
||||||
|
await waitFor(() => expect(requestFullscreen).toHaveBeenCalledTimes(2));
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user