import { useState, type FormEvent } from 'react'; import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useCampaign, useCampaignCharacters, useCreateCharacter, useDeleteCharacter, useCampaignEncounters, useCreateEncounter, useReorderEncounters, useSetEncounterArchived, useDeleteEncounter, useCampaignMonsters, useCampaignWeapons, useCampaignSpells, useCampaignItems, useCampaignNpcs, useCampaignNotes, useCreateNote, useUpdateCampaign, useSetCampaignArchived, useDeleteCampaign, useRegenerateInvite, useCampaignLocations, useCreateLocation, useDeleteLocation, } from '../api/queries'; import { useAuth } from '../auth/useAuth'; import { useCampaignSocket } from '../hooks/useCampaignSocket'; import { Spinner, ErrorBanner } from '../components/Spinner'; import { NumberInput } from '../components/NumberInput'; import { SectionNav, type Section } from '../components/SectionNav'; import { LifeBadge } from '../components/DeathSaves'; import { RestModal } from '../components/RestModal'; import { Pagination } from '../components/Paginated'; import { usePagination } from '../hooks/usePagination'; import { CampaignSearch, type SearchGroup } from '../components/campaign/CampaignSearch'; import { EntryDetail } from '../components/campaign/EntryDetail'; import { ItemsSection, MonstersSection, NpcsSection, SpellsSection, WeaponsSection } from '../components/campaign/PoolSections'; import { effectsSummary } from '../lib/gear'; import { extractErrorMessage, spellLevelLabel } from '../lib/format'; import { matchesSearch, type EntryKind, type EntryRef } from '../lib/campaignEntries'; import { speciesIcon } from '../lib/speciesIcons'; import type { CampaignDiceMode, CharacterSummary, CritRule, Encounter, EncounterMode, HpMethod, RollVisibility, ScoreMethod } from '../api/types'; // How the encounter list can be ordered. "custom" is the campaign's own order, // which the DM arranges; the rest only change what this browser shows. type EncounterSort = 'custom' | 'name' | 'status' | 'type' | 'newest' | 'oldest'; const ENCOUNTER_SORT_LABELS: Record = { custom: 'Campaign order', name: 'Name (A–Z)', status: 'Status (in progress first)', type: 'Type (battles first)', newest: 'Newest first', oldest: 'Oldest first', }; const ENCOUNTER_SORT_KEY = 'dnd_encounter_sort'; const STATUS_RANK = { ACTIVE: 0, PLANNING: 1, COMPLETE: 2 }; function storedEncounterSort(): EncounterSort { const stored = localStorage.getItem(ENCOUNTER_SORT_KEY); return stored && stored in ENCOUNTER_SORT_LABELS ? (stored as EncounterSort) : 'custom'; } // Where a new encounter goes in the campaign's order: the bottom, the top, or // straight after another one ("after:"). Top or bottom is remembered. const ENCOUNTER_PLACE_KEY = 'dnd_encounter_place'; const AFTER = 'after:'; function storedEncounterPlace(): string { return localStorage.getItem(ENCOUNTER_PLACE_KEY) === 'TOP' ? 'TOP' : 'BOTTOM'; } // `encounters` arrives in campaign order, and the sort is stable, so ties // (same status, same type) stay in that order. function sortEncounters(encounters: Encounter[], sort: EncounterSort): Encounter[] { const time = (e: Encounter) => new Date(e.createdAt).getTime(); const compare: Record number> = { custom: () => 0, name: (a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }), status: (a, b) => STATUS_RANK[a.status] - STATUS_RANK[b.status], type: (a, b) => Number(a.mode === 'QUEST') - Number(b.mode === 'QUEST'), newest: (a, b) => time(b) - time(a), oldest: (a, b) => time(a) - time(b), }; return [...encounters].sort(compare[sort]); } function CharacterRow({ character, isDM, onDelete }: { character: CharacterSummary; isDM: boolean; onDelete: () => void }) { const inProgress = character.buildStage !== 'COMPLETE'; return (
{character.name} {inProgress && Building…}

{character.species ? `${character.species} ` : ''} {character.characterClass || (inProgress ? 'Not yet built' : '')}{character.subclassName && ` (${character.subclassName})`} · Level {character.level} {character.currentLocationName && ` · 📍 ${character.currentLocationName}`}

{!inProgress && (
HP {character.currentHp}/{character.maxHp} · AC {character.armorClass}
)} {inProgress ? 'Continue Build' : 'Open Sheet'} {isDM && ( )}
); } const MODE_LABELS: Record = { BATTLE: '⚔ Battle', QUEST: '📜 Quest' }; // A long note, cut down to a line for a search result. const snippet = (text: string) => (text.length > 110 ? `${text.slice(0, 110).trimEnd()}…` : text); export function CampaignHomePage() { const { campaignId = '' } = useParams(); const { user } = useAuth(); const navigate = useNavigate(); useCampaignSocket(campaignId); const { data, isLoading, error } = useCampaign(campaignId); const { data: characters } = useCampaignCharacters(campaignId); const { data: encounters } = useCampaignEncounters(campaignId); const { data: monsters } = useCampaignMonsters(campaignId, data?.campaign.role === 'DM'); const { data: weapons } = useCampaignWeapons(campaignId); const { data: spells } = useCampaignSpells(campaignId); const { data: items } = useCampaignItems(campaignId); const { data: npcs } = useCampaignNpcs(campaignId, data?.campaign.role === 'DM'); const { data: notes } = useCampaignNotes(campaignId); const { data: locations } = useCampaignLocations(campaignId); const createCharacter = useCreateCharacter(campaignId); const deleteCharacter = useDeleteCharacter(campaignId); const createEncounter = useCreateEncounter(campaignId); const reorderEncounters = useReorderEncounters(campaignId); const setEncounterArchived = useSetEncounterArchived(campaignId); const deleteEncounter = useDeleteEncounter(campaignId); const createNote = useCreateNote(); const updateCampaign = useUpdateCampaign(campaignId); const regenerateInvite = useRegenerateInvite(campaignId); const setArchived = useSetCampaignArchived(); const deleteCampaign = useDeleteCampaign(); const createLocation = useCreateLocation(campaignId); const deleteLocation = useDeleteLocation(campaignId); // Which part of the campaign is showing is in the address (?view=weapons), // so it can be linked to and the back button steps through the parts. const [searchParams, setSearchParams] = useSearchParams(); const [query, setQuery] = useState(''); // The weapon, item, spell, monster or NPC whose pop-out is open. const [opened, setOpened] = useState(null); // The list whose "add by hand" pop-out was asked for from the pop-out of the one just added. const [addingKind, setAddingKind] = useState(null); const [newCharName, setNewCharName] = useState(''); const [newEncounterName, setNewEncounterName] = useState(''); const [newEncounterMode, setNewEncounterMode] = useState('BATTLE'); const [newEncounterPlace, setNewEncounterPlace] = useState(storedEncounterPlace); const [encounterSort, setEncounterSort] = useState(storedEncounterSort); const [showArchivedEncounters, setShowArchivedEncounters] = useState(false); const [noteBody, setNoteBody] = useState(''); const [dmNoteBody, setDmNoteBody] = useState(''); const [newLocationName, setNewLocationName] = useState(''); const [formError, setFormError] = useState(null); const [showSettings, setShowSettings] = useState(false); const [showDelete, setShowDelete] = useState(false); const [resting, setResting] = useState(false); const [deleteConfirmName, setDeleteConfirmName] = useState(''); const liveEncounters = encounters?.filter((e) => !e.archivedAt) || []; // An encounter picked to go after may have been archived or deleted since. const encounterPlace = newEncounterPlace.startsWith(AFTER) && !liveEncounters.some((e) => AFTER + e.id === newEncounterPlace) ? 'BOTTOM' : newEncounterPlace; const archivedEncounters = encounters?.filter((e) => e.archivedAt) || []; const shownEncounters = sortEncounters(liveEncounters, encounterSort); const encountersPage = usePagination(shownEncounters, 10); const archivedEncountersPage = usePagination(archivedEncounters, 10); const sharedNotes = notes?.filter((n) => n.visibility === 'SHARED'); const dmNotes = notes?.filter((n) => n.visibility === 'DM_ONLY'); const sharedNotesPage = usePagination(sharedNotes, 6); const dmNotesPage = usePagination(dmNotes, 6); if (isLoading) return ; if (error || !data) return ; const { campaign, members } = data; const isDM = campaign.role === 'DM'; const myCharacters = characters?.filter((c) => c.userId === user?.id) || []; const partyCharacters = characters?.filter((c) => c.userId !== user?.id) || []; async function handleCreateCharacter(e: FormEvent) { e.preventDefault(); setFormError(null); try { const character = await createCharacter.mutateAsync({ name: newCharName }); setNewCharName(''); navigate(`/characters/${character.id}/build`); } catch (err) { setFormError(extractErrorMessage(err)); } } async function handleCreateEncounter(e: FormEvent) { e.preventDefault(); try { const encounter = await createEncounter.mutateAsync({ name: newEncounterName || (newEncounterMode === 'QUEST' ? 'New Quest' : 'New Encounter'), mode: newEncounterMode, ...(encounterPlace.startsWith(AFTER) ? { afterEncounterId: encounterPlace.slice(AFTER.length) } : { position: encounterPlace === 'TOP' ? ('TOP' as const) : ('BOTTOM' as const) }), }); navigate(`/encounters/${encounter.id}`); } catch (err) { setFormError(extractErrorMessage(err)); } } // Swaps an encounter with its neighbour in the campaign's own order. function moveEncounter(index: number, step: -1 | 1) { const ids = liveEncounters.map((e) => e.id); const target = index + step; if (target < 0 || target >= ids.length) return; [ids[index], ids[target]] = [ids[target], ids[index]]; reorderEncounters.mutate([...ids, ...archivedEncounters.map((e) => e.id)], { onError: (err) => setFormError(extractErrorMessage(err)), }); } async function handleCreateNote(e: FormEvent) { e.preventDefault(); if (!noteBody.trim()) return; await createNote.mutateAsync({ campaignId, body: noteBody, visibility: 'SHARED' }); setNoteBody(''); } async function handleCreateDmNote(e: FormEvent) { e.preventDefault(); if (!dmNoteBody.trim()) return; await createNote.mutateAsync({ campaignId, body: dmNoteBody, visibility: 'DM_ONLY' }); setDmNoteBody(''); } async function handleSetArchived(archived: boolean) { setFormError(null); try { await setArchived.mutateAsync({ campaignId, archived }); } catch (err) { setFormError(extractErrorMessage(err)); } } async function handleDeleteCampaign(e: FormEvent) { e.preventDefault(); setFormError(null); try { await deleteCampaign.mutateAsync(campaignId); navigate('/campaigns'); } catch (err) { setFormError(extractErrorMessage(err)); } } async function handleCreateLocation(e: FormEvent) { e.preventDefault(); if (!newLocationName.trim()) return; await createLocation.mutateAsync({ name: newLocationName }); setNewLocationName(''); } // The page shows one part at a time. Players have no lists to manage, so // they get a short row; the DM gets one for every list. const sections: Section[] = isDM ? [ { id: 'overview', label: 'Overview', icon: '🏰' }, { id: 'npcs', label: 'NPCs', icon: '🧑', count: npcs?.length }, { id: 'places', label: 'Locations', icon: '📍', count: locations?.length }, { id: 'weapons', label: 'Weapons', icon: '⚔', count: weapons?.length }, { id: 'items', label: 'Items', icon: '🎒', count: items?.length }, { id: 'spells', label: 'Spells', icon: '✨', count: spells?.length }, { id: 'monsters', label: 'Monsters', icon: '🐉', count: monsters?.length }, { id: 'notes', label: 'Notes', icon: '📝', count: notes?.length }, { id: 'settings', label: 'Settings', icon: '⚙' }, ] : [ { id: 'overview', label: 'Overview', icon: '🏰' }, ...(locations?.length ? [{ id: 'places', label: 'Places', icon: '📍', count: locations.length }] : []), { id: 'notes', label: 'Notes', icon: '📝', count: sharedNotes?.length }, ]; const requestedView = searchParams.get('view'); const view = sections.some((s) => s.id === requestedView) ? requestedView : 'overview'; const search = query.trim(); // A search takes the place of whichever part was showing. const show = (id: string) => !search && view === id; function selectView(id: string) { setQuery(''); setFormError(null); setSearchParams(id === 'overview' ? {} : { view: id }); } const openEntry = (kind: EntryKind, id: string) => () => setOpened({ kind, id }); const searchGroups: SearchGroup[] = !search ? [] : [ { label: 'Characters', icon: '🧙', hits: (characters ?? []) .filter((c) => matchesSearch(search, c.name, c.species, c.characterClass, c.currentLocationName)) .map((c) => ({ key: c.id, title: c.name, detail: [c.species, c.characterClass, `Level ${c.level}`, c.currentLocationName && `📍 ${c.currentLocationName}`].filter(Boolean).join(' · '), to: c.buildStage === 'COMPLETE' ? `/characters/${c.id}` : `/characters/${c.id}/build`, })), }, { label: 'Encounters', icon: '⚔', hits: [...liveEncounters, ...(isDM ? archivedEncounters : [])] .filter((e) => matchesSearch(search, e.name, e.mode, e.status)) .map((e) => ({ key: e.id, title: e.name, detail: `${MODE_LABELS[e.mode]} · ${e.status}${e.archivedAt ? ' · archived' : ''}`, to: `/encounters/${e.id}`, })), }, ...(isDM ? [ { label: 'NPCs', icon: '🧑', hits: (npcs ?? []) .filter((n) => matchesSearch(search, n.name, n.role, n.disposition, n.description, n.dmNotes)) .map((n) => ({ key: n.id, title: n.name, detail: [n.role, n.description].filter(Boolean).join(' · '), onPick: openEntry('npc', n.id) })), }, { label: 'Weapons', icon: '⚔', hits: (weapons ?? []) .filter((w) => matchesSearch(search, w.name, w.damageDice, w.damageType, effectsSummary(w.effects, w.effectNote))) .map((w) => ({ key: w.id, title: w.name, detail: `${w.damageDice} ${w.damageType} · Lv ${w.minLevel}`, onPick: openEntry('weapon', w.id) })), }, { label: 'Items', icon: '🎒', hits: (items ?? []) .filter((i) => matchesSearch(search, i.name, i.description, i.damageDice, effectsSummary(i.effects, i.effectNote))) .map((i) => ({ key: i.id, title: i.name, detail: [effectsSummary(i.effects, i.effectNote), i.damageDice, i.description].filter(Boolean).join(' · '), onPick: openEntry('item', i.id), })), }, { label: 'Spells', icon: '✨', hits: (spells ?? []) .filter((s) => matchesSearch(search, s.name, s.school, s.description, spellLevelLabel(s.level))) .map((s) => ({ key: s.id, title: s.name, detail: [spellLevelLabel(s.level), s.description].filter(Boolean).join(' · '), onPick: openEntry('spell', s.id) })), }, { label: 'Monsters', icon: '🐉', hits: (monsters ?? []) .filter((m) => matchesSearch(search, m.name, m.challengeRating && `CR ${m.challengeRating}`, m.specialTrait, m.notes)) .map((m) => ({ key: m.id, title: m.name, detail: `CR ${m.challengeRating || '—'} · AC ${m.ac} · HP ${m.maxHp}`, onPick: openEntry('monster', m.id) })), }, ] : []), { label: isDM ? 'Locations' : 'Places', icon: '📍', hits: (locations ?? []) .filter((l) => matchesSearch(search, l.name, l.description)) .map((l) => ({ key: l.id, title: l.name, detail: l.description, onPick: () => selectView('places') })), }, { label: 'Notes', icon: '📝', hits: (notes ?? []) .filter((n) => matchesSearch(search, n.body, n.author?.displayName)) .map((n) => ({ key: n.id, title: snippet(n.body), detail: [n.visibility === 'DM_ONLY' ? '🔒 DM note' : 'Shared note', n.author?.displayName, new Date(n.createdAt).toLocaleDateString()].filter(Boolean).join(' · '), onPick: () => selectView('notes'), })), }, ]; return (

{campaign.name}

{campaign.description}

📊 Party Overview {campaign.archivedAt && Archived} {isDM ? 'Dungeon Master' : 'Player'}
setQuery(e.target.value)} /> {formError &&
} {search && } {show('overview') && !isDM && myCharacters.length > 0 && (

Your Character{myCharacters.length > 1 ? 's' : ''}

{myCharacters.map((c) => ( {}} /> ))}
)} {show('overview') && (

{isDM ? 'Characters' : 'Rest of the Party'}

{isDM && characters?.some((c) => c.buildStage === 'COMPLETE') && ( )}
setNewCharName(e.target.value)} style={{ flex: 1, minWidth: 160 }} />
{(isDM ? characters : partyCharacters)?.length === 0 && (
{isDM || myCharacters.length === 0 ? 'No characters yet. Roll one up above.' : 'Nobody else has a character yet.'}
)} {(isDM ? characters : partyCharacters)?.map((c) => ( window.confirm(`Delete ${c.name}?`) && deleteCharacter.mutate(c.id)} /> ))}
)} {show('overview') && (

Encounters

{liveEncounters.length > 1 && ( )}
{isDM && (
setNewEncounterName(e.target.value)} style={{ flex: 1, minWidth: 160 }} /> {liveEncounters.length > 0 && ( )}
)} {isDM && encounterSort === 'custom' && liveEncounters.length > 1 && (

This is the campaign's own order, which everyone sees by default. Use ▲ and ▼ to rearrange it; moving past the top or bottom of a page carries an encounter onto the next one.

)} {encounters && liveEncounters.length === 0 && (
{archivedEncounters.length > 0 ? 'Every encounter is archived.' : 'No encounters yet.'}
)} {encountersPage.pageItems.map((enc) => { // Its place in the whole list, not on this page: that is what moving it changes. const index = shownEncounters.indexOf(enc); return (
{MODE_LABELS[enc.mode]} {enc.name} {enc.status} {enc.mode === 'BATTLE' && ` · Round ${enc.currentRound}`} {isDM && encounterSort === 'custom' && ( <> )} {isDM && ( )}
); })} {isDM && archivedEncounters.length > 0 && (

Archived ({archivedEncounters.length})

{showArchivedEncounters && ( <>

Players don't see these in their list.

{archivedEncountersPage.pageItems.map((enc) => (
{MODE_LABELS[enc.mode]} {enc.name}
))} )}
)}
)} {show('places') && !isDM && locations && locations.length > 0 && (
Places You've Been
{locations.map((loc) => (
📍 {loc.name} {loc.description &&

{loc.description}

}
))}
)} {show('places') && isDM && (
Locations

Track where each character currently is. Give an encounter a location and its characters move there when it begins. Players only see the places their own characters have been.

setNewLocationName(e.target.value)} style={{ flex: 1, minWidth: 160 }} />
{locations?.length === 0 &&

No locations yet.

} {locations?.map((loc) => (
📍 {loc.name}
))}
)} {isDM && show('npcs') && setAddingKind(null)} />} {isDM && show('weapons') && setAddingKind(null)} />} {isDM && show('items') && setAddingKind(null)} />} {isDM && show('spells') && setAddingKind(null)} />} {isDM && show('monsters') && setAddingKind(null)} />} {show('notes') && (
Shared Notes