feat(ui): replace all alert() with toast + info modal
Native alert() vanished instantly (browser focus loss when player display window or devtools steals focus). Replaced all 23 alert() calls with two in-app feedback paths via React context: - ToastStack: bottom-right stack, 6s auto-dismiss + manual X. For transient failures (storage throws, catch blocks). - InfoModal: yellow notice modal with OK button, persistent until dismissed. For validations (dup-add, empty/invalid fields). UIFeedbackProvider wraps all 3 App branches (admin/player/logs). useUIFeedback() hook in 6 components (CharacterManager, ParticipantManager, InitiativeControls, EncounterManager, LogsView, AdminView). 244 tests green (App 84, shared 133, server 27).
This commit is contained in:
+114
-52
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useRef, useMemo } from 'react';
|
||||
import React, { useState, useEffect, useRef, useMemo, createContext, useContext, useCallback } from 'react';
|
||||
import * as shared from '@ttrpg/shared';
|
||||
import { initializeApp, getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken, getFirestore, orderBy, limit, getStorage, getStorageMode } from './storage';
|
||||
import {
|
||||
@@ -6,9 +6,78 @@ import {
|
||||
UserCheck, UserX, HeartCrack, HeartPulse, Zap, EyeOff, ExternalLink, AlertTriangle,
|
||||
Play as PlayIcon, Pause as PauseIcon, SkipForward as SkipForwardIcon,
|
||||
StopCircle as StopCircleIcon, Users2, Dices, ChevronUp, ChevronDown, ScrollText,
|
||||
Maximize2, Minimize2, Moon, Coffee, Clock, ChevronRight
|
||||
Maximize2, Minimize2, Moon, Coffee, Clock, ChevronRight, CheckCircle2, X
|
||||
} from 'lucide-react';
|
||||
|
||||
// ----- UI feedback: toast (transient) + info modal (persistent) -----
|
||||
const UIFeedbackContext = createContext(null);
|
||||
const useUIFeedback = () => useContext(UIFeedbackContext);
|
||||
|
||||
function ToastStack({ toasts, onDismiss }) {
|
||||
if (!toasts.length) return null;
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-[60] flex flex-col gap-2 max-w-sm">
|
||||
{toasts.map(t => (
|
||||
<div key={t.id} className="flex items-start gap-2 bg-stone-800 border border-red-600 text-stone-100 px-3 py-2 rounded-md shadow-lg">
|
||||
<AlertTriangle size={16} className="text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<span className="text-sm flex-grow">{t.message}</span>
|
||||
<button onClick={() => onDismiss(t.id)} className="text-stone-400 hover:text-stone-200 flex-shrink-0" aria-label="Dismiss">
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoModal({ message, onClose }) {
|
||||
if (!message) return null;
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-stone-900 p-6 rounded-lg shadow-xl w-full max-w-md">
|
||||
<div className="flex items-center mb-4">
|
||||
<AlertTriangle size={24} className="text-yellow-400 mr-3 flex-shrink-0" />
|
||||
<h2 className="text-xl font-semibold text-yellow-300">Notice</h2>
|
||||
</div>
|
||||
<p className="text-stone-300 mb-6">{message}</p>
|
||||
<div className="flex justify-end">
|
||||
<button onClick={onClose} className="px-4 py-2 text-sm font-medium text-stone-900 bg-amber-400 hover:bg-amber-300 rounded-md transition-colors">
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UIFeedbackProvider({ children }) {
|
||||
const [toasts, setToasts] = useState([]);
|
||||
const [info, setInfo] = useState(null);
|
||||
const nextId = useRef(1);
|
||||
|
||||
const showToast = useCallback((message) => {
|
||||
const id = nextId.current++;
|
||||
setToasts(prev => [...prev, { id, message }]);
|
||||
setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 6000);
|
||||
}, []);
|
||||
|
||||
const showInfo = useCallback((message) => {
|
||||
setInfo(message);
|
||||
}, []);
|
||||
|
||||
const dismissToast = useCallback((id) => {
|
||||
setToasts(prev => prev.filter(t => t.id !== id));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<UIFeedbackContext.Provider value={{ showToast, showInfo }}>
|
||||
{children}
|
||||
<ToastStack toasts={toasts} onDismiss={dismissToast} />
|
||||
<InfoModal message={info} onClose={() => setInfo(null)} />
|
||||
</UIFeedbackContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// Custom CSS for death animation (player view only)
|
||||
const deathAnimationStyles = `
|
||||
@keyframes death-dissolve {
|
||||
@@ -533,6 +602,7 @@ function EditParticipantModal({ participant, onClose, onSave }) {
|
||||
// ============================================================================
|
||||
|
||||
function CharacterManager({ campaignId, campaignCharacters }) {
|
||||
const { showToast, showInfo } = useUIFeedback();
|
||||
const [characterName, setCharacterName] = useState('');
|
||||
const [defaultMaxHp, setDefaultMaxHp] = useState(DEFAULT_MAX_HP);
|
||||
const [defaultInitMod, setDefaultInitMod] = useState(DEFAULT_INIT_MOD);
|
||||
@@ -548,12 +618,10 @@ function CharacterManager({ campaignId, campaignCharacters }) {
|
||||
const initMod = parseInt(defaultInitMod, 10);
|
||||
|
||||
if (isNaN(hp) || hp <= 0) {
|
||||
alert("Please enter a valid positive number for Default Max HP.");
|
||||
return;
|
||||
showInfo("Please enter a valid positive number for Default Max HP."); return;
|
||||
}
|
||||
if (isNaN(initMod)) {
|
||||
alert("Please enter a valid number for Default Initiative Modifier.");
|
||||
return;
|
||||
showInfo("Please enter a valid number for Default Initiative Modifier."); return;
|
||||
}
|
||||
|
||||
const newCharacter = {
|
||||
@@ -572,8 +640,7 @@ function CharacterManager({ campaignId, campaignCharacters }) {
|
||||
setDefaultInitMod(DEFAULT_INIT_MOD);
|
||||
} catch (err) {
|
||||
console.error("Error adding character:", err);
|
||||
alert("Failed to add character. Please try again.");
|
||||
}
|
||||
showToast("Failed to add character. Please try again."); }
|
||||
};
|
||||
|
||||
const handleUpdateCharacter = async (characterId, newName, newDefaultMaxHp, newDefaultInitMod) => {
|
||||
@@ -583,13 +650,11 @@ function CharacterManager({ campaignId, campaignCharacters }) {
|
||||
const initMod = parseInt(newDefaultInitMod, 10);
|
||||
|
||||
if (isNaN(hp) || hp <= 0) {
|
||||
alert("Please enter a valid positive number for Default Max HP.");
|
||||
setEditingCharacter(null);
|
||||
showInfo("Please enter a valid positive number for Default Max HP."); setEditingCharacter(null);
|
||||
return;
|
||||
}
|
||||
if (isNaN(initMod)) {
|
||||
alert("Please enter a valid number for Default Initiative Modifier.");
|
||||
setEditingCharacter(null);
|
||||
showInfo("Please enter a valid number for Default Initiative Modifier."); setEditingCharacter(null);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -604,8 +669,7 @@ function CharacterManager({ campaignId, campaignCharacters }) {
|
||||
setEditingCharacter(null);
|
||||
} catch (err) {
|
||||
console.error("Error updating character:", err);
|
||||
alert("Failed to update character. Please try again.");
|
||||
}
|
||||
showToast("Failed to update character. Please try again."); }
|
||||
};
|
||||
|
||||
const requestDeleteCharacter = (characterId, charName) => {
|
||||
@@ -622,8 +686,7 @@ function CharacterManager({ campaignId, campaignCharacters }) {
|
||||
await storage.updateDoc(getPath.campaign(campaignId), { players: updatedCharacters });
|
||||
} catch (err) {
|
||||
console.error("Error deleting character:", err);
|
||||
alert("Failed to delete character. Please try again.");
|
||||
}
|
||||
showToast("Failed to delete character. Please try again."); }
|
||||
|
||||
setShowDeleteConfirm(false);
|
||||
setItemToDelete(null);
|
||||
@@ -798,6 +861,7 @@ function CharacterManager({ campaignId, campaignCharacters }) {
|
||||
// ============================================================================
|
||||
|
||||
function ParticipantManager({ encounter, encounterPath, campaignCharacters, campaignId }) {
|
||||
const { showToast, showInfo } = useUIFeedback();
|
||||
const [participantName, setParticipantName] = useState('');
|
||||
const [participantType, setParticipantType] = useState('monster');
|
||||
const [selectedCharacterId, setSelectedCharacterId] = useState('');
|
||||
@@ -860,7 +924,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
return;
|
||||
}
|
||||
if (participants.some(p => p.type === 'character' && p.originalCharacterId === selectedCharacterId)) {
|
||||
alert(`${character.name} is already in this encounter.`);
|
||||
showInfo(`${character.name} is already in this encounter.`);
|
||||
return;
|
||||
}
|
||||
nameToAdd = character.name;
|
||||
@@ -914,8 +978,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
setIsNpc(false);
|
||||
setManualInitiative('');
|
||||
} catch (err) {
|
||||
alert("Failed to add participant. Please try again.");
|
||||
}
|
||||
showToast("Failed to add participant. Please try again."); }
|
||||
};
|
||||
|
||||
const handleAddAllCampaignCharacters = async () => {
|
||||
@@ -950,8 +1013,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
});
|
||||
|
||||
if (newParticipants.length === 0) {
|
||||
alert("All campaign characters are already in this encounter.");
|
||||
return;
|
||||
showInfo("All campaign characters are already in this encounter."); return;
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -964,8 +1026,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
alert("Failed to add all characters. Please try again.");
|
||||
}
|
||||
showToast("Failed to add all characters. Please try again."); }
|
||||
};
|
||||
|
||||
const handleUpdateParticipant = async (updatedData) => {
|
||||
@@ -981,8 +1042,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
}
|
||||
setEditingParticipant(null);
|
||||
} catch (err) {
|
||||
alert("Failed to update participant. Please try again.");
|
||||
}
|
||||
showToast("Failed to update participant. Please try again."); }
|
||||
};
|
||||
|
||||
// Inline initiative edit (FEAT-3): blur/Enter commits. Reslots participant
|
||||
@@ -1022,8 +1082,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
updates: log.undo,
|
||||
});
|
||||
} catch (err) {
|
||||
alert("Failed to delete participant. Please try again.");
|
||||
}
|
||||
showToast("Failed to delete participant. Please try again."); }
|
||||
setShowDeleteConfirm(false);
|
||||
setItemToDelete(null);
|
||||
};
|
||||
@@ -1612,6 +1671,7 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters, camp
|
||||
// ============================================================================
|
||||
|
||||
function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
const { showToast, showInfo } = useUIFeedback();
|
||||
const [showEndConfirm, setShowEndConfirm] = useState(false);
|
||||
const { data: activeDisplayData } = useFirestoreDocument(getPath.activeDisplay());
|
||||
const hidePlayerHp = activeDisplayData?.hidePlayerHp ?? true;
|
||||
@@ -1637,8 +1697,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
|
||||
const handleStartEncounter = async () => {
|
||||
if (!db || !encounter.participants || encounter.participants.length === 0) {
|
||||
alert("Add participants first.");
|
||||
return;
|
||||
showInfo("Add participants first."); return;
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -1650,8 +1709,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
updates: log.undo,
|
||||
});
|
||||
} catch (err) {
|
||||
alert(err.message || "Failed to start encounter. Please try again.");
|
||||
}
|
||||
showToast(err.message || "Failed to start encounter. Please try again."); }
|
||||
};
|
||||
|
||||
const handleTogglePause = async () => {
|
||||
@@ -1682,8 +1740,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
} catch (err) {
|
||||
// nextTurn throws if no active participants — auto-end combat
|
||||
if (err.message === 'Encounter not running.' || err.message === 'No active turn.') return;
|
||||
alert("No active participants left.");
|
||||
await storage.updateDoc(encounterPath, {
|
||||
showInfo("No active participants left."); await storage.updateDoc(encounterPath, {
|
||||
isStarted: false,
|
||||
isPaused: false,
|
||||
currentTurnParticipantId: null,
|
||||
@@ -1703,8 +1760,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
updates: log.undo,
|
||||
});
|
||||
} catch (err) {
|
||||
alert("Failed to end encounter. Please try again.");
|
||||
}
|
||||
showToast("Failed to end encounter. Please try again."); }
|
||||
|
||||
setShowEndConfirm(false);
|
||||
};
|
||||
@@ -1805,6 +1861,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
|
||||
// ============================================================================
|
||||
|
||||
function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharacters }) {
|
||||
const { showToast, showInfo } = useUIFeedback();
|
||||
const { data: encountersData, isLoading: isLoadingEncounters } = useFirestoreCollection(
|
||||
campaignId ? getPath.encounters(campaignId) : null
|
||||
);
|
||||
@@ -1871,8 +1928,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
|
||||
setSelectedEncounterId(newEncounterId);
|
||||
} catch (err) {
|
||||
console.error("Error creating encounter:", err);
|
||||
alert("Failed to create encounter. Please try again.");
|
||||
}
|
||||
showToast("Failed to create encounter. Please try again."); }
|
||||
};
|
||||
|
||||
const requestDeleteEncounter = (encounterId, encounterName) => {
|
||||
@@ -1897,8 +1953,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error deleting encounter:", err);
|
||||
alert("Failed to delete encounter. Please try again.");
|
||||
}
|
||||
showToast("Failed to delete encounter. Please try again."); }
|
||||
|
||||
setShowDeleteConfirm(false);
|
||||
setItemToDelete(null);
|
||||
@@ -2051,6 +2106,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
|
||||
// ============================================================================
|
||||
|
||||
function AdminView({ userId }) {
|
||||
const { showToast, showInfo } = useUIFeedback();
|
||||
const { data: campaignsData, isLoading: isLoadingCampaigns, error: campaignsError } = useFirestoreCollection(
|
||||
getPath.campaigns()
|
||||
);
|
||||
@@ -2124,8 +2180,7 @@ function AdminView({ userId }) {
|
||||
setSelectedCampaignId(newCampaignId);
|
||||
} catch (err) {
|
||||
console.error("Error creating campaign:", err);
|
||||
alert("Failed to create campaign. Please try again.");
|
||||
}
|
||||
showToast("Failed to create campaign. Please try again."); }
|
||||
};
|
||||
|
||||
const requestDeleteCampaign = (campaignId, campaignName) => {
|
||||
@@ -2160,8 +2215,7 @@ function AdminView({ userId }) {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error deleting campaign:", err);
|
||||
alert("Failed to delete campaign. Please try again.");
|
||||
}
|
||||
showToast("Failed to delete campaign. Please try again."); }
|
||||
|
||||
setShowDeleteConfirm(false);
|
||||
setItemToDelete(null);
|
||||
@@ -2619,6 +2673,7 @@ function DisplayView() {
|
||||
// ============================================================================
|
||||
|
||||
function LogsView() {
|
||||
const { showToast } = useUIFeedback();
|
||||
const { data: logs, isLoading } = useFirestoreCollection(getPath.logs(), LOG_QUERY);
|
||||
const [showClearConfirm, setShowClearConfirm] = useState(false);
|
||||
const [undoingId, setUndoingId] = useState(null);
|
||||
@@ -2647,8 +2702,7 @@ function LogsView() {
|
||||
await storage.updateDoc(`${getPath.logs()}/${entry.id}`, { undone: true });
|
||||
} catch (err) {
|
||||
console.error('Error undoing action:', err);
|
||||
alert('Failed to roll back. The encounter may have changed or no longer exists.');
|
||||
}
|
||||
showToast("Failed to roll back. The encounter may have changed or no longer exists."); }
|
||||
setUndoingId(null);
|
||||
};
|
||||
|
||||
@@ -2825,19 +2879,26 @@ function App() {
|
||||
|
||||
if (isPlayerViewOnlyMode) {
|
||||
return (
|
||||
<div className="min-h-screen bg-stone-950 text-stone-100 font-garamond">
|
||||
{isAuthReady && <DisplayView />}
|
||||
{!isAuthReady && !error && <p>Authenticating for Player Display...</p>}
|
||||
</div>
|
||||
<UIFeedbackProvider>
|
||||
<div className="min-h-screen bg-stone-950 text-stone-100 font-garamond">
|
||||
{isAuthReady && <DisplayView />}
|
||||
{!isAuthReady && !error && <p>Authenticating for Player Display...</p>}
|
||||
</div>
|
||||
</UIFeedbackProvider>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLogsMode) {
|
||||
return isAuthReady ? <LogsView /> : <LoadingSpinner message="Authenticating..." />;
|
||||
return (
|
||||
<UIFeedbackProvider>
|
||||
{isAuthReady ? <LogsView /> : <LoadingSpinner message="Authenticating..." />}
|
||||
</UIFeedbackProvider>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-stone-950 text-stone-100 font-garamond">
|
||||
<UIFeedbackProvider>
|
||||
<div className="min-h-screen bg-stone-950 text-stone-100 font-garamond">
|
||||
<header className="bg-stone-950 p-4 shadow-lg border-b border-amber-900">
|
||||
<div className="container mx-auto flex justify-between items-center">
|
||||
<h1 className="text-3xl font-bold text-amber-400 font-cinzel tracking-wide">TTRPG Initiative Tracker</h1>
|
||||
@@ -2868,7 +2929,8 @@ function App() {
|
||||
<footer className="bg-stone-950 p-4 text-center text-sm text-stone-400 mt-8">
|
||||
TTRPG Initiative Tracker {APP_VERSION}
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</UIFeedbackProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user