Files
the-sunken-reach/frontend/src/pages/CampaignHomePage.tsx
T
joshuaandClaude Opus 5.5 e7b6e0065a V1.22.0: campaign settings for dice, scores, multiclassing, auto-rolls, XP and crits
- Settings grouped into Characters, Dice & rolls, Combat and Progression
- Dice: digital, physical or both; a campaign's own choice applies to every character
- Ability scores by 4d6, the standard array or point buy (27 points, 8 to 15)
- Track XP can be turned off for milestone levelling: XP is hidden and not awarded
- New settings saved ahead of their features: multiclassing, auto-rolled monster
  and NPC attacks, roll visibility, hidden monster rolls, HP on level up, crit rule
- docs/CAMPAIGN_SETTINGS.md lists every setting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:12:05 +02:00

1037 lines
49 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<EncounterSort, string> = {
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:<id>"). 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<EncounterSort, (a: Encounter, b: Encounter) => 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 (
<div className="card flex-between flex-wrap">
<div>
<div className="flex-row">
<span aria-hidden="true">{speciesIcon(character.species)}</span>
<Link to={`/characters/${character.id}`} style={{ fontFamily: 'var(--font-display)', color: 'var(--accent-strong)', fontSize: '1.05rem' }}>
{character.name}
</Link>
{inProgress && <span className="badge">Building…</span>}
</div>
<p style={{ margin: 0, color: 'var(--text-muted)', fontSize: '0.9rem' }}>
{character.species ? `${character.species} ` : ''}
{character.characterClass || (inProgress ? 'Not yet built' : '')}{character.subclassName && ` (${character.subclassName})`} · Level {character.level}
{character.currentLocationName && ` · 📍 ${character.currentLocationName}`}
</p>
</div>
<div className="flex-row">
{!inProgress && (
<div style={{ textAlign: 'right', fontSize: '0.85rem', color: 'var(--text-muted)' }}>
<LifeBadge deathSaves={character.deathSaves} /> HP {character.currentHp}/{character.maxHp} · AC {character.armorClass}
</div>
)}
<Link to={inProgress ? `/characters/${character.id}/build` : `/characters/${character.id}`} className="btn">
{inProgress ? 'Continue Build' : 'Open Sheet'}
</Link>
{isDM && (
<button className="btn btn-ghost" onClick={onDelete}>
✕
</button>
)}
</div>
</div>
);
}
const MODE_LABELS: Record<EncounterMode, string> = { 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<EntryRef | null>(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<EntryKind | null>(null);
const [newCharName, setNewCharName] = useState('');
const [newEncounterName, setNewEncounterName] = useState('');
const [newEncounterMode, setNewEncounterMode] = useState<EncounterMode>('BATTLE');
const [newEncounterPlace, setNewEncounterPlace] = useState(storedEncounterPlace);
const [encounterSort, setEncounterSort] = useState<EncounterSort>(storedEncounterSort);
const [showArchivedEncounters, setShowArchivedEncounters] = useState(false);
const [noteBody, setNoteBody] = useState('');
const [dmNoteBody, setDmNoteBody] = useState('');
const [newLocationName, setNewLocationName] = useState('');
const [formError, setFormError] = useState<string | null>(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 <Spinner label="Unrolling the campaign map…" />;
if (error || !data) return <ErrorBanner message="Could not load this campaign." />;
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 (
<div>
<div className="page-header">
<div>
<h1>{campaign.name}</h1>
<p className="subtitle">{campaign.description}</p>
</div>
<div className="flex-row">
<Link to={`/campaigns/${campaignId}/party`} className="btn">
📊 Party Overview
</Link>
{campaign.archivedAt && <span className="badge">Archived</span>}
<span className={`badge ${isDM ? 'badge-dm' : 'badge-player'}`}>{isDM ? 'Dungeon Master' : 'Player'}</span>
</div>
</div>
<input
type="search"
className="campaign-search"
placeholder={isDM ? 'Search this campaign: characters, encounters, NPCs, gear, spells, monsters, notes…' : 'Search this campaign: characters, encounters, places, notes…'}
aria-label="Search this campaign"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<SectionNav sections={sections} current={search ? '' : (view ?? 'overview')} onSelect={selectView} />
{formError && <div style={{ marginBottom: '1rem' }}><ErrorBanner message={formError} /></div>}
{search && <CampaignSearch query={search} groups={searchGroups} />}
{show('overview') && !isDM && myCharacters.length > 0 && (
<div className="section-block">
<h2 style={{ fontSize: '1.1rem' }}>Your Character{myCharacters.length > 1 ? 's' : ''}</h2>
{myCharacters.map((c) => (
<CharacterRow key={c.id} character={c} isDM={false} onDelete={() => {}} />
))}
</div>
)}
{show('overview') && (
<div className="section-block">
<div className="page-header" style={{ marginBottom: '0.75rem' }}>
<h2 style={{ fontSize: '1.1rem', margin: 0 }}>{isDM ? 'Characters' : 'Rest of the Party'}</h2>
{isDM && characters?.some((c) => c.buildStage === 'COMPLETE') && (
<button className="btn" onClick={() => setResting(true)} title="A short or long rest for any of the party: Hit Dice, HP and spell slots">
🛏 Rest…
</button>
)}
</div>
<form onSubmit={handleCreateCharacter} className="flex-row flex-wrap mt-sm" style={{ marginBottom: '0.75rem' }}>
<input
placeholder="New character name"
value={newCharName}
onChange={(e) => setNewCharName(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<button type="submit" className="btn btn-primary" disabled={!newCharName || createCharacter.isPending}>
Roll a New Character
</button>
</form>
{(isDM ? characters : partyCharacters)?.length === 0 && (
<div className="empty-state">{isDM || myCharacters.length === 0 ? 'No characters yet. Roll one up above.' : 'Nobody else has a character yet.'}</div>
)}
{(isDM ? characters : partyCharacters)?.map((c) => (
<CharacterRow
key={c.id}
character={c}
isDM={isDM}
onDelete={() => window.confirm(`Delete ${c.name}?`) && deleteCharacter.mutate(c.id)}
/>
))}
</div>
)}
{show('overview') && (
<div className="section-block">
<div className="page-header" style={{ marginBottom: '0.75rem' }}>
<h2 style={{ fontSize: '1.1rem', margin: 0 }}>Encounters</h2>
{liveEncounters.length > 1 && (
<label className="flex-row subtitle">
Sort by
<select
value={encounterSort}
onChange={(e) => {
const sort = e.target.value as EncounterSort;
setEncounterSort(sort);
localStorage.setItem(ENCOUNTER_SORT_KEY, sort);
}}
>
{(Object.keys(ENCOUNTER_SORT_LABELS) as EncounterSort[]).map((sort) => (
<option key={sort} value={sort}>
{ENCOUNTER_SORT_LABELS[sort]}
</option>
))}
</select>
</label>
)}
</div>
{isDM && (
<form onSubmit={handleCreateEncounter} className="flex-row flex-wrap" style={{ marginBottom: '0.75rem' }}>
<input
placeholder="Encounter name"
value={newEncounterName}
onChange={(e) => setNewEncounterName(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<select aria-label="Encounter type" value={newEncounterMode} onChange={(e) => setNewEncounterMode(e.target.value as EncounterMode)}>
<option value="BATTLE">Battle</option>
<option value="QUEST">NPC quest</option>
</select>
{liveEncounters.length > 0 && (
<select
aria-label="Where the new encounter goes in the list"
title="Where it goes in the campaign's order. ▲ and ▼ move it afterwards."
value={encounterPlace}
onChange={(e) => {
setNewEncounterPlace(e.target.value);
if (!e.target.value.startsWith(AFTER)) localStorage.setItem(ENCOUNTER_PLACE_KEY, e.target.value);
}}
style={{ maxWidth: 220 }}
>
<option value="BOTTOM">At the bottom of the list</option>
<option value="TOP">At the top of the list</option>
<optgroup label="Straight after…">
{liveEncounters.map((e) => (
<option key={e.id} value={AFTER + e.id}>
After {e.name}
</option>
))}
</optgroup>
</select>
)}
<button type="submit" className="btn btn-primary" disabled={createEncounter.isPending}>
{newEncounterMode === 'QUEST' ? '📜 Start Quest' : '⚔ Start Encounter'}
</button>
</form>
)}
{isDM && encounterSort === 'custom' && liveEncounters.length > 1 && (
<p className="subtitle" style={{ marginTop: 0 }}>
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.
</p>
)}
{encounters && liveEncounters.length === 0 && (
<div className="empty-state">{archivedEncounters.length > 0 ? 'Every encounter is archived.' : 'No encounters yet.'}</div>
)}
{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 (
<div key={enc.id} className="card flex-between flex-wrap">
<Link to={`/encounters/${enc.id}`} style={{ flex: 1, minWidth: 200 }}>
<span className="badge" style={{ marginRight: 8 }}>{MODE_LABELS[enc.mode]}</span>
{enc.name}
</Link>
<span className="flex-row">
<span className="badge">
{enc.status}
{enc.mode === 'BATTLE' && ` · Round ${enc.currentRound}`}
</span>
{isDM && encounterSort === 'custom' && (
<>
<button
className="btn btn-ghost"
aria-label={`Move ${enc.name} up`}
title="Move up"
disabled={index === 0 || reorderEncounters.isPending}
onClick={() => moveEncounter(index, -1)}
>
▲
</button>
<button
className="btn btn-ghost"
aria-label={`Move ${enc.name} down`}
title="Move down"
disabled={index === shownEncounters.length - 1 || reorderEncounters.isPending}
onClick={() => moveEncounter(index, 1)}
>
▼
</button>
</>
)}
{isDM && (
<button
className="btn btn-ghost"
title="Archive: take it off the list without deleting it"
disabled={setEncounterArchived.isPending}
onClick={() => setEncounterArchived.mutate({ encounterId: enc.id, archived: true })}
>
Archive
</button>
)}
</span>
</div>
);
})}
<Pagination page={encountersPage.page} pageCount={encountersPage.pageCount} onPrev={encountersPage.prevPage} onNext={encountersPage.nextPage} onJump={encountersPage.setPage} />
{isDM && archivedEncounters.length > 0 && (
<div className="mt-md">
<div className="flex-between">
<h3 className="section-label" style={{ margin: 0 }}>Archived ({archivedEncounters.length})</h3>
<button className="btn btn-ghost" onClick={() => setShowArchivedEncounters((s) => !s)}>
{showArchivedEncounters ? 'Hide' : 'Show'}
</button>
</div>
{showArchivedEncounters && (
<>
<p className="subtitle" style={{ marginTop: 0 }}>Players don't see these in their list.</p>
{archivedEncountersPage.pageItems.map((enc) => (
<div key={enc.id} className="card flex-between flex-wrap">
<Link to={`/encounters/${enc.id}`} style={{ flex: 1, minWidth: 200 }}>
<span className="badge" style={{ marginRight: 8 }}>{MODE_LABELS[enc.mode]}</span>
{enc.name}
</Link>
<span className="flex-row">
<button
className="btn"
disabled={setEncounterArchived.isPending}
onClick={() => setEncounterArchived.mutate({ encounterId: enc.id, archived: false })}
>
Restore
</button>
<button
className="btn btn-danger"
disabled={deleteEncounter.isPending}
onClick={() =>
window.confirm(`Delete "${enc.name}" for good? Rewards already handed out stay with the characters.`) &&
deleteEncounter.mutate(enc.id)
}
>
Delete
</button>
</span>
</div>
))}
<Pagination
page={archivedEncountersPage.page}
pageCount={archivedEncountersPage.pageCount}
onPrev={archivedEncountersPage.prevPage}
onNext={archivedEncountersPage.nextPage}
onJump={archivedEncountersPage.setPage}
/>
</>
)}
</div>
)}
</div>
)}
{show('places') && !isDM && locations && locations.length > 0 && (
<div className="card">
<div className="card-title">Places You've Been</div>
{locations.map((loc) => (
<div key={loc.id} style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<strong>📍 {loc.name}</strong>
{loc.description && <p className="subtitle" style={{ margin: '0.2rem 0 0', whiteSpace: 'pre-wrap' }}>{loc.description}</p>}
</div>
))}
</div>
)}
{show('places') && isDM && (
<div className="card">
<div className="card-title">
<span>Locations</span>
</div>
<p className="subtitle" style={{ marginTop: 0 }}>
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.
</p>
<form onSubmit={handleCreateLocation} className="flex-row flex-wrap">
<input
placeholder="Location name (e.g. The Rusty Tankard)"
value={newLocationName}
onChange={(e) => setNewLocationName(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<button type="submit" className="btn btn-primary">Add Location</button>
</form>
<div className="mt-sm">
{locations?.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No locations yet.</p>}
{locations?.map((loc) => (
<div key={loc.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<span>📍 {loc.name}</span>
<button className="btn btn-ghost" onClick={() => deleteLocation.mutate(loc.id)}>✕</button>
</div>
))}
</div>
</div>
)}
{isDM && show('npcs') && <NpcsSection campaignId={campaignId} entries={npcs} onOpen={setOpened} formRequested={addingKind === 'npc'} onFormClosed={() => setAddingKind(null)} />}
{isDM && show('weapons') && <WeaponsSection campaignId={campaignId} entries={weapons} onOpen={setOpened} formRequested={addingKind === 'weapon'} onFormClosed={() => setAddingKind(null)} />}
{isDM && show('items') && <ItemsSection campaignId={campaignId} entries={items} onOpen={setOpened} formRequested={addingKind === 'item'} onFormClosed={() => setAddingKind(null)} />}
{isDM && show('spells') && <SpellsSection campaignId={campaignId} entries={spells} onOpen={setOpened} formRequested={addingKind === 'spell'} onFormClosed={() => setAddingKind(null)} />}
{isDM && show('monsters') && <MonstersSection campaignId={campaignId} entries={monsters} onOpen={setOpened} formRequested={addingKind === 'monster'} onFormClosed={() => setAddingKind(null)} />}
{show('notes') && (
<div className="card">
<div className="card-title">Shared Notes</div>
<form onSubmit={handleCreateNote} className="flex-row flex-wrap">
<textarea
placeholder="Add a shared note for the party…"
rows={2}
value={noteBody}
onChange={(e) => setNoteBody(e.target.value)}
style={{ flex: 1, minWidth: 200 }}
/>
<button type="submit" className="btn btn-primary">Add Note</button>
</form>
<div className="mt-sm">
{sharedNotesPage.pageItems.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No notes yet.</p>}
{sharedNotesPage.pageItems.map((n) => (
<div key={n.id} style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<p style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{n.body}</p>
<span style={{ fontSize: '0.75rem', color: 'var(--text-dim)' }}>
— {n.author?.displayName} · {new Date(n.createdAt).toLocaleString()}
</span>
</div>
))}
</div>
<Pagination page={sharedNotesPage.page} pageCount={sharedNotesPage.pageCount} onPrev={sharedNotesPage.prevPage} onNext={sharedNotesPage.nextPage} onJump={sharedNotesPage.setPage} />
</div>
)}
{show('notes') && isDM && (
<div className="card">
<div className="card-title">DM Notes</div>
<p className="subtitle" style={{ marginTop: 0 }}>Only you can see these — plot threads, secrets, NPC tracking.</p>
<form onSubmit={handleCreateDmNote} className="flex-row flex-wrap">
<textarea
placeholder="Add a private note…"
rows={2}
value={dmNoteBody}
onChange={(e) => setDmNoteBody(e.target.value)}
style={{ flex: 1, minWidth: 200 }}
/>
<button type="submit" className="btn btn-primary">Add</button>
</form>
<div className="mt-sm">
{dmNotesPage.pageItems.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No DM notes yet.</p>}
{dmNotesPage.pageItems.map((n) => (
<div key={n.id} style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<p style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{n.body}</p>
<span style={{ fontSize: '0.75rem', color: 'var(--text-dim)' }}>
{new Date(n.createdAt).toLocaleString()}
</span>
</div>
))}
</div>
<Pagination page={dmNotesPage.page} pageCount={dmNotesPage.pageCount} onPrev={dmNotesPage.prevPage} onNext={dmNotesPage.nextPage} onJump={dmNotesPage.setPage} />
</div>
)}
{show('settings') && isDM && (
<div className="card">
<div className="card-title">
<span>Campaign Settings</span>
<button className="btn btn-ghost" onClick={() => setShowSettings((s) => !s)}>
{showSettings ? 'Hide' : 'Edit'}
</button>
</div>
<div className="flex-row flex-wrap">
<span className="badge">Invite code: <strong className="mono">{campaign.inviteCode}</strong></span>
<button className="btn btn-ghost" onClick={() => regenerateInvite.mutate()}>
Regenerate code
</button>
</div>
{showSettings && (
<form
className="mt-md"
onSubmit={(e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const fd = new FormData(form);
updateCampaign.mutate({
startingGold: Number(fd.get('startingGold')),
startingItemCount: Number(fd.get('startingItemCount')),
startingSpellCount: Number(fd.get('startingSpellCount')),
skipMotivationRoll: fd.get('skipMotivationRoll') === 'on',
abilityScoreMethod: fd.get('abilityScoreMethod') as ScoreMethod,
showMonsterHp: fd.get('showMonsterHp') === 'on',
subclassesEnabled: fd.get('subclassesEnabled') === 'on',
multiclassEnabled: fd.get('multiclassEnabled') === 'on',
areaAttackAcPenalty: Number(fd.get('areaAttackAcPenalty')),
maxEquipped: Number(fd.get('maxEquipped')),
maxEquippedWeapons: Number(fd.get('maxEquippedWeapons')),
diceMode: fd.get('diceMode') as CampaignDiceMode,
rollVisibility: fd.get('rollVisibility') as RollVisibility,
hideMonsterRolls: fd.get('hideMonsterRolls') === 'on',
autoRollMonsters: fd.get('autoRollMonsters') === 'on',
autoRollNpcs: fd.get('autoRollNpcs') === 'on',
critRule: fd.get('critRule') as CritRule,
trackXp: fd.get('trackXp') === 'on',
hpOnLevelUp: fd.get('hpOnLevelUp') as HpMethod,
});
}}
>
<fieldset className="settings-group">
<legend>Characters</legend>
<div className="grid grid-cols-3">
<div className="field">
<label>Starting gold</label>
<NumberInput name="startingGold" min={0} max={1000000} keepValue defaultValue={campaign.startingGold} />
</div>
<div className="field">
<label>Starting items (weapons + items)</label>
<NumberInput name="startingItemCount" min={0} max={50} keepValue defaultValue={campaign.startingItemCount} />
</div>
<div className="field">
<label>Starting spells</label>
<NumberInput name="startingSpellCount" min={0} max={50} keepValue defaultValue={campaign.startingSpellCount} />
</div>
</div>
<div className="field">
<label>Ability scores are made by</label>
<select name="abilityScoreMethod" defaultValue={campaign.abilityScoreMethod}>
<option value="ROLL_4D6">Rolling 4d6 and dropping the lowest, six times</option>
<option value="STANDARD_ARRAY">The standard array: 15, 14, 13, 12, 10, 8</option>
<option value="POINT_BUY">Point buy: 27 points, scores 8 to 15</option>
</select>
</div>
<label className="checkbox-row">
<input type="checkbox" name="skipMotivationRoll" defaultChecked={campaign.skipMotivationRoll} />
Skip the motivation step when building a character
</label>
<label className="checkbox-row mt-sm">
<input type="checkbox" name="subclassesEnabled" defaultChecked={campaign.subclassesEnabled} />
Characters choose a subclass (untick and every class follows one path, with nothing to choose)
</label>
<label className="checkbox-row mt-sm">
<input type="checkbox" name="multiclassEnabled" defaultChecked={campaign.multiclassEnabled} />
Multiclassing: on a level up a character may take a level in another class whose ability requirements they meet
</label>
<label className="flex-row flex-wrap gap-sm mt-sm">
Equipped at once
<NumberInput
name="maxEquipped"
min={1}
max={20}
keepValue
defaultValue={campaign.maxEquipped}
style={{ width: 70 }}
title="How many weapons and items a character can have equipped together. Only equipped gear can be used in an encounter or gives its effects."
/>
things, of which
<NumberInput
name="maxEquippedWeapons"
min={0}
max={20}
keepValue
defaultValue={campaign.maxEquippedWeapons}
style={{ width: 70 }}
title="How many of those can be weapons. A weapon for each hand, like a pair of daggers, is made as one weapon."
/>
<span className="combatant-sub">
can be weapons. Armor and shields are items and count. Lowering these takes nothing off anyone; they are checked when
something is put on.
</span>
</label>
</fieldset>
<fieldset className="settings-group">
<legend>Dice &amp; rolls</legend>
<div className="grid grid-cols-2">
<div className="field">
<label>Dice at this table</label>
<select name="diceMode" defaultValue={campaign.diceMode}>
<option value="BOTH">Both: digital, or type in what a real die shows</option>
<option value="DIGITAL">Digital only: the app rolls</option>
<option value="PHYSICAL">Physical only: real dice, results typed in</option>
</select>
</div>
<div className="field">
<label>Who sees a roll</label>
<select name="rollVisibility" defaultValue={campaign.rollVisibility}>
<option value="ALL">Everyone sees every roll</option>
<option value="OWN">Players see their own; the DM sees all</option>
</select>
</div>
</div>
<label className="checkbox-row">
<input type="checkbox" name="hideMonsterRolls" defaultChecked={campaign.hideMonsterRolls} />
Keep my rolls for monsters and NPCs to myself until they are put into play
</label>
</fieldset>
<fieldset className="settings-group">
<legend>Combat</legend>
<label className="checkbox-row">
<input type="checkbox" name="autoRollMonsters" defaultChecked={campaign.autoRollMonsters} />
Auto-roll monster attacks: on a monster&apos;s turn its target, to-hit and damage are rolled for me to accept or change
</label>
<label className="checkbox-row mt-sm">
<input type="checkbox" name="autoRollNpcs" defaultChecked={campaign.autoRollNpcs} />
Auto-roll NPC attacks the same way (friendly NPCs attack monsters, hostile ones the party)
</label>
<label className="checkbox-row mt-sm">
<input type="checkbox" name="showMonsterHp" defaultChecked={campaign.showMonsterHp} />
Players see the exact hit points of monsters and NPCs in encounters (untick for a health bar only)
</label>
<div className="field mt-sm">
<label>A critical hit</label>
<select name="critRule" defaultValue={campaign.critRule}>
<option value="DOUBLE_DICE">Rolls the damage dice twice (the rule)</option>
<option value="MAX_PLUS_ROLL">Takes the dice at their maximum, plus one roll of them</option>
</select>
</div>
<label className="flex-row flex-wrap gap-sm mt-sm">
Area attack AC penalty
<NumberInput
name="areaAttackAcPenalty"
min={0}
max={10}
keepValue
defaultValue={campaign.areaAttackAcPenalty}
style={{ width: 70 }}
title="An attack on several targets is harder to land: each target's AC counts as this much higher for every target beyond the first. 0 turns the penalty off."
/>
<span className="combatant-sub">added to each target&apos;s AC for every target beyond the first (0 for none)</span>
</label>
</fieldset>
<fieldset className="settings-group">
<legend>Progression</legend>
<label className="checkbox-row">
<input type="checkbox" name="trackXp" defaultChecked={campaign.trackXp} />
Track experience points (untick for milestone levelling: no XP, and you decide when the party levels)
</label>
<div className="field mt-sm">
<label>Hit points on a level up</label>
<select name="hpOnLevelUp" defaultValue={campaign.hpOnLevelUp}>
<option value="AVERAGE">The hit die&apos;s average (rounded up) + Constitution</option>
<option value="ROLL">Roll the hit die + Constitution</option>
</select>
</div>
</fieldset>
<button type="submit" className="btn btn-primary mt-md" disabled={updateCampaign.isPending}>
Save Settings
</button>
</form>
)}
<div className="mt-md">
<div className="card-title" style={{ marginBottom: '0.4rem' }}>Party</div>
<div className="flex-row flex-wrap">
{members.map((m) => (
<span key={m.userId} className={`badge ${m.role === 'DM' ? 'badge-dm' : 'badge-player'}`}>
{m.displayName}
</span>
))}
</div>
</div>
<div className="mt-md">
<div className="card-title" style={{ marginBottom: '0.4rem' }}>Archive or Delete</div>
<p className="subtitle" style={{ marginTop: 0 }}>
{campaign.archivedAt
? 'This campaign is archived: it sits under “Archived” on your campaign list and its invite code is switched off. Nothing in it has been removed.'
: 'Archiving moves the campaign off everyone’s main list and switches off its invite code. Nothing is removed, and you can restore it at any time.'}
</p>
<div className="flex-row flex-wrap">
<button className="btn" disabled={setArchived.isPending} onClick={() => handleSetArchived(!campaign.archivedAt)}>
{campaign.archivedAt ? 'Restore Campaign' : 'Archive Campaign'}
</button>
{campaign.ownerId === user?.id && (
<button
className="btn btn-danger"
onClick={() => {
setShowDelete((s) => !s);
setDeleteConfirmName('');
}}
>
{showDelete ? 'Cancel' : 'Delete Campaign…'}
</button>
)}
</div>
{showDelete && (
<form className="mt-md" onSubmit={handleDeleteCampaign}>
<div className="field">
<label htmlFor="deleteConfirmName">
This permanently deletes every character, encounter, note and pool entry in the campaign, for
every player. There is no undo. Type <strong>{campaign.name}</strong> to confirm.
</label>
<input
id="deleteConfirmName"
autoComplete="off"
value={deleteConfirmName}
onChange={(e) => setDeleteConfirmName(e.target.value)}
/>
</div>
<button
type="submit"
className="btn btn-danger"
disabled={deleteCampaign.isPending || deleteConfirmName.trim() !== campaign.name.trim()}
>
{deleteCampaign.isPending ? 'Deleting…' : 'Delete Forever'}
</button>
</form>
)}
</div>
</div>
)}
{isDM && resting && <RestModal campaignId={campaignId} characters={characters ?? []} onClose={() => setResting(false)} />}
{isDM && opened && (
<EntryDetail
campaignId={campaignId}
entry={opened}
weapons={weapons ?? []}
items={items ?? []}
spells={spells ?? []}
monsters={monsters ?? []}
npcs={npcs ?? []}
onAddAnother={
opened.isNew
? () => {
setAddingKind(opened.kind);
setOpened(null);
}
: undefined
}
onClose={() => setOpened(null)}
/>
)}
</div>
);
}