import { useState, type ReactNode } from 'react'; import { Link, useNavigate, useParams } from 'react-router-dom'; import { useEncounter, useCampaign, useCampaignCharacters, useCampaignMonsters, useCampaignNpcs, useCampaignWeapons, useCampaignItems, useCampaignLocations, useAddParticipant, usePatchParticipant, useRemoveParticipant, useAdvanceRound, useRollInitiative, useAwardXp, useNextTurn, useSetTargets, useReviveParticipant, usePatchEncounter, useSetEncounterArchived, useDeleteEncounter, useAddReward, useDeleteReward, useAwardReward, useRolls, useApplyAction, type NewReward, } from '../api/queries'; import { useCampaignSocket } from '../hooks/useCampaignSocket'; import { useAuth } from '../auth/useAuth'; import { RollFeed } from '../components/RollFeed'; import { InitiativeTrack } from '../components/encounter/InitiativeTrack'; import { ActionCard, ActionComposer, RecentActions } from '../components/encounter/ActionPanel'; import { FreeRoamPanel } from '../components/encounter/FreeRoam'; import { Spinner, ErrorBanner } from '../components/Spinner'; import { NumberInput } from '../components/NumberInput'; import { HpBar } from '../components/HpBar'; import { DeathSaves } from '../components/DeathSaves'; import { TradePanel } from '../components/TradePanel'; import { useRememberCampaign } from '../lib/lastCampaign'; import { openCharacterPanel } from '../lib/characterPanel'; import { GearInForce } from '../components/CharacterPanel'; import { SheetNumbers } from '../components/SheetNumbers'; import { ConditionChip, ConditionPicker, ResourceTracker, StateBadges } from '../components/CharacterState'; import { useHotkeys } from '../hooks/useHotkeys'; import { Rollable } from '../components/Rollable'; import { GroupCheckModal } from '../components/GroupCheckModal'; import { withBonus } from '../lib/diceRoller'; import { ABILITY_LABELS, classLabel, COIN_LABELS, CURRENCIES, SPECIES_LABELS, extractErrorMessage, fmtMod, formatMoney, slotsSummary, spellLevelLabel } from '../lib/format'; import { abilityModifier, scaledDamageDice, MAX_GEAR_LEVEL } from '../lib/previewCalc'; import type { Ability, CharacterSummary, Currency, Encounter, EncounterAction, EncounterMode, EncounterParticipant, EncounterReward, EncounterDifficulty, Item, Weapon, } from '../api/types'; const ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']; // An attack on more than one target is an area attack, and harder to land: // every target's AC counts as `step` higher for each target beyond the first. // The step is the campaign's "area attack AC penalty" setting. const areaPenalty = (targetCount: number, step: number) => Math.max(0, targetCount - 1) * step; const KIND_LABELS = { CHARACTER: 'PC', MONSTER: 'Monster', NPC: 'NPC' } as const; const KIND_BADGES = { CHARACTER: 'badge-player', MONSTER: 'badge-hostile', NPC: 'badge-friendly' } as const; const MODE_LABELS: Record = { BATTLE: '⚔ Battle', QUEST: '📜 Quest', FREE_ROAM: '🧭 Free roam' }; const STATUS_LABELS = { PLANNING: 'Planning', ACTIVE: 'In progress', COMPLETE: 'Complete' } as const; function StatChip({ label, children }: { label: string; children: ReactNode }) { return ( {label} {children} ); } // Who this combatant is, in one muted line under the name. function subline(p: EncounterParticipant): string { const info = p.characterCombatInfo; if (info) { return [ `Level ${info.level}`, info.species && SPECIES_LABELS[info.species], classLabel(info.characterClass, info.subclassName), ] .filter(Boolean) .join(' '); } if (p.kind === 'NPC') return p.npc?.role || 'Non-player character'; if (p.monster?.challengeRating) return `Challenge ${p.monster.challengeRating}`; return ''; } // How much health a combatant has left, for a bar: a percentage, and whether // there is anything to track at all. A player may be sent only the percentage. function healthOf(p: EncounterParticipant) { const currentHp = p.currentHp ?? 0; const maxHp = p.maxHp ?? 0; const barOnly = p.maxHp == null && p.hpPercent != null; const tracksHp = barOnly || maxHp > 0; const pct = barOnly ? (p.hpPercent ?? 0) : tracksHp ? Math.max(0, Math.min(100, (currentHp / maxHp) * 100)) : 0; return { currentHp, maxHp, barOnly, tracksHp, pct }; } // Everything behind a combatant's headline numbers: a character's abilities, // what they fight with, their saves and skills and what they can do; a // monster's stat block; an NPC's secrets. Shown in a card's details and in the // spotlight. Only what the viewer was sent is drawn, so a player gets nothing // here for a monster. function CombatantDetails({ participant: p, isDM, canUse, onError, }: { participant: EncounterParticipant; isDM: boolean; // The DM, or the player whose character this is: they may spend its counters. canUse: boolean; onError: (err: unknown) => void; }) { const info = p.characterCombatInfo; const npc = p.npc; const monsterStats = p.monster && p.monster.ac !== undefined ? p.monster : null; return ( <> {info && ( <>
{ABILITIES.map((a) => ( {info.abilities[a].final} ({fmtMod(info.abilities[a].modifier)}) ))}
{info.weapons.length === 0 && (

No weapon equipped. A weapon has to be equipped to be used: open 📋 Sheet to put one on.

)} {info.items.length > 0 && (

Equipped: {info.items.map((i) => `${i.name}${i.damageDice ? ` (${i.damageDice})` : ''}`).join(' · ')}

)} {info.weapons.map((w) => (
{w.name} Lv {w.level} ·{' '} {w.damageDice} {fmtMod(w.damageBonus)} {' '} {w.damageType} {fmtMod(w.attackBonus)} to hit
))} {info.spellcasting && (

Spellcasting ({ABILITY_LABELS[info.spellcasting.ability]}): save DC {info.spellcasting.saveDC} ·{' '} {fmtMod(info.spellcasting.attackBonus)} to hit {info.spellSlots && ` · slots left ${slotsSummary(info.spellSlots)}`}

)} {info.spells.length > 0 && (
{info.spells.map((s) => ( {s.name} ({spellLevelLabel(s.level)} {s.damageDice ? ` · ${s.damageDice}` : ''}) ))}
)} {p.character && info.resources.length > 0 && ( <>
Counters
)} {info.specialAbilities && ( <>
Special abilities

{info.specialAbilities}

)} )} {monsterStats && ( <>
{ABILITIES.map((a) => { const score = monsterStats[`${a.toLowerCase()}Score` as 'strScore'] ?? 10; return ( {score} ({fmtMod(abilityModifier(score))}) ); })}
{monsterStats.specialTrait && (

Trait: {monsterStats.specialTrait}

)} {monsterStats.notes &&

{monsterStats.notes}

} )} {npc?.dmNotes && (

🔒 {npc.dmNotes}

)} ); } // A combatant's headline numbers, as chips. function HeadlineChips({ participant: p }: { participant: EncounterParticipant }) { const info = p.characterCombatInfo; const npc = p.npc; const monsterStats = p.monster && p.monster.ac !== undefined ? p.monster : null; const { currentHp, maxHp, barOnly, tracksHp } = healthOf(p); return (
{tracksHp && !barOnly && ( {currentHp}/{maxHp} {info && info.tempHp > 0 && ` +${info.tempHp}`} )} {info && ( <> {info.armorClass} {info.speed} {fmtMod(info.initiativeBonus)} {info.passivePerception} {fmtMod(info.proficiencyBonus)} {info.spellcasting && {info.spellcasting.saveDC}} )} {monsterStats && ( <> {monsterStats.ac} {monsterStats.speed} {fmtMod(monsterStats.attackBonus ?? 0)} {monsterStats.damageDice && ( {monsterStats.damageDice} )} )} {npc && npc.ac != null && {npc.ac}} {npc && npc.attackBonus != null && ( {fmtMod(npc.attackBonus)} )} {npc && npc.damageDice && ( {npc.damageDice} )}
); } // What a combatant is fighting with right now, set apart so it catches the // eye: a character's equipped weapons, or a creature's attacks. Shown on the // card of whoever is on turn and of anyone targeted. A player is not sent a // monster's attacks, so for them a monster shows nothing here. function InHand({ participant: p }: { participant: EncounterParticipant }) { const info = p.characterCombatInfo; if (info) { return (
In hand {info.weapons.length === 0 && nothing equipped} {info.weapons.map((w) => ( ⚔ {w.name}{' '} {fmtMod(w.attackBonus)} · {w.damageDice} {fmtMod(w.damageBonus)} {w.damageType} ))}
); } const named = (p.monster?.attacks ?? []).filter((a) => a.name); const stats = p.monster ?? p.npc; const single = stats && (stats.attackBonus != null || stats.damageDice) ? [{ name: 'Attack', attackBonus: stats.attackBonus ?? 0, damageDice: stats.damageDice, count: 1 }] : []; const attacks = named.length > 0 ? named : single; if (attacks.length === 0) return null; return (
Attacks {attacks.map((a, i) => ( ⚔ {a.name} {(a.count ?? 1) > 1 ? ` ×${a.count}` : ''}{' '} {fmtMod(a.attackBonus)} {a.damageDice ? ` · ${a.damageDice}` : ''} ))}
); } // "2 rd" on a condition that wears off by itself. function roundsNote(p: EncounterParticipant, condition: string): string | undefined { const left = p.conditionRounds?.[condition]; return left ? `${left} rd` : undefined; } // What the DM is told when someone holding a spell is hurt: the save to keep it. function concentrationCheck(p: EncounterParticipant, damage: number): string { const info = p.characterCombatInfo; const bonus = info ? info.saves.CON.bonus : p.monster?.conScore != null ? abilityModifier(p.monster.conScore) : null; return `${p.displayName} is concentrating and took ${damage} damage: Constitution save, DC ${Math.max(10, Math.floor(damage / 2))}${ bonus == null ? '' : ` (they roll with ${fmtMod(bonus)})` }. On a failure the spell ends: remove Concentrating.`; } const jumpToCard = (participantId: string) => document.getElementById(`combatant-${participantId}`)?.scrollIntoView({ behavior: 'smooth', block: 'center' }); // Everyone in the scene on one line, in the order they act. It stays at the // top of the screen while the cards scroll, and a click goes to that card. function TurnStrip({ participants, activeId, targetIds, userId, hasActed, }: { participants: EncounterParticipant[]; activeId: string | undefined; targetIds: string[]; userId: string | undefined; hasActed: (p: EncounterParticipant) => boolean; }) { return ( ); } // One combatant's whole stat block, kept in view beside the cards: whoever is // on turn, or whoever was pinned there. function Spotlight({ participant: p, isPinned, isOnTurn, isDM, canOpenSheet, onUnpin, onError, }: { participant: EncounterParticipant; isPinned: boolean; isOnTurn: boolean; isDM: boolean; canOpenSheet: boolean; // the DM, or the player whose character this is onUnpin: () => void; onError: (err: unknown) => void; }) { const info = p.characterCombatInfo; return (
{isPinned ? '📌 Pinned' : '▶ On turn'} {isPinned && ( )}
{p.character && canOpenSheet && ( )}
{subline(p)} {isPinned && isOnTurn && ' · on turn'}
{(p.conditions.length > 0 || info?.inspiration || (info?.exhaustion ?? 0) > 0) && (
{info && } {p.conditions.map((c) => ( ))}
)} {p.npc?.description &&

{p.npc.description}

}
); } function CombatantCard({ participant: p, isDM, isMine, isActive, onPatch, canRollInitiative, targetedBy, acPenalty, onTarget, isPinned, onPin, onRemove, onError, }: { participant: EncounterParticipant; isDM: boolean; // The viewer's own character: its card is marked so it is easy to find. isMine: boolean; isActive: boolean; onPatch: (data: Partial) => void; // The DM for anyone; a player for their own character. The same goes for // that character's death saves. canRollInitiative: boolean; // Set while this combatant is a target: who is going for them, or '' when // nobody is on turn. targetedBy?: string; // What an area attack adds to this target's AC; 0 when they are the only one. acPenalty: number; // Marks this combatant as a target, or unmarks them. Absent for someone who // may not pick targets right now, and on the card of whoever is on turn. onTarget?: () => void; // Whether this combatant's stats are the ones kept in view, and the switch for it. isPinned: boolean; onPin: () => void; onRemove: () => void; onError: (err: unknown) => void; }) { const [hpDelta, setHpDelta] = useState(''); // How many rounds the next condition added lasts; empty for until removed. const [rounds, setRounds] = useState(''); // Details start open for the DM (who runs the scene from this screen) and // closed for players; null = "not toggled yet", so it follows isDM once the // campaign role has loaded. const [detailsToggled, setDetailsToggled] = useState(null); const showDetails = detailsToggled ?? isDM; const info = p.characterCombatInfo; const monster = p.monster; const npc = p.npc; // A player may get a percentage in place of a monster's or NPC's numbers. const { currentHp, maxHp, tracksHp, pct } = healthOf(p); const isDown = tracksHp && pct <= 0; // A dying character still has something to do each turn, so its card stays lit. const isDying = info?.deathSaves.state === 'DYING'; const isTargeted = targetedBy !== undefined; // Players get a monster's name and health bar only; the stat block is the DM's. const monsterStats = monster && monster.ac !== undefined ? monster : null; const hasDetails = Boolean(info || monsterStats || npc?.dmNotes); function applyDelta(sign: 1 | -1) { const amount = Number(hpDelta); if (!amount) return; onPatch({ currentHp: currentHp + sign * amount }); setHpDelta(''); } function addCondition(condition: string) { const name = condition.trim(); if (!name || p.conditions.includes(name)) return; const lasts = Math.floor(Number(rounds)); onPatch({ conditions: [...p.conditions, name], ...(lasts > 0 ? { conditionRounds: { ...p.conditionRounds, [name]: lasts } } : {}) }); setRounds(''); } return (
{isMine &&
★ Your character
} {isActive &&
▶ On turn
} {isTargeted && (
🎯 Targeted{targetedBy && ` by ${targetedBy}`} {acPenalty > 0 && ` · area attack, AC +${acPenalty}`}
)}
{KIND_LABELS[p.kind]} {p.character ? ( {p.displayName} ) : ( {p.displayName} )} {npc && {npc.disposition}} {p.character && (isDM || isMine) && ( )} {hasDetails && ( )} {isDown && !info && Down} {p.hidden && ( Hidden from players )} {onTarget && ( )}
{subline(p)}
{/* Battles and quests both take initiative: who speaks or acts first matters in either. */} {canRollInitiative ? ( ) : ( {p.initiativeRoll == null ? '—' : p.initiative} )}
{(isActive || isTargeted) && } {/* An NPC's description is what players are here for, so it is never tucked away. */} {npc?.description &&

{npc.description}

} {tracksHp && ( <> 0 ? (info.tempHp / maxHp) * 100 : 0} /> {isDM && (
setHpDelta(e.target.value)} style={{ width: 90 }} />
)} {info && p.character && ( )} )} {(p.conditions.length > 0 || isDM || info?.inspiration || (info?.exhaustion ?? 0) > 0) && (
{info && } {p.conditions.map((c) => ( onPatch({ conditions: p.conditions.filter((x) => x !== c) }) : undefined} /> ))} {isDM && ( <> setRounds(e.target.value)} style={{ width: 84 }} /> )}
)} {(hasDetails || isDM) && (
{hasDetails ? ( ) : ( )} {isDM && ( )}
)} {hasDetails && showDetails && (
)}
); } // What a combatant hits with, one line per attack: a character's weapons // (the equipped ones, when any are) and damaging spells, or the single attack // of a monster or NPC. function attackLines(p: EncounterParticipant): string[] { const info = p.characterCombatInfo; if (info) { const weapons = info.weapons.map( (w) => `${w.name}: ${fmtMod(w.attackBonus)} to hit · ${w.damageDice} ${fmtMod(w.damageBonus)} ${w.damageType}` ); const spells = info.spells .filter((s) => s.damageDice) .map((s) => `${s.name}: ${s.damageDice}${info.spellcasting ? ` · ${fmtMod(info.spellcasting.attackBonus)} to hit / DC ${info.spellcasting.saveDC}` : ''}`); return [...weapons, ...spells]; } const stats = p.monster ?? p.npc; if (!stats || (stats.attackBonus == null && !stats.damageDice)) return []; return [[stats.attackBonus != null && `${fmtMod(stats.attackBonus)} to hit`, stats.damageDice].filter(Boolean).join(' · ')]; } type AreaMode = 'SPLIT' | 'EACH'; // How `amount` lands on `count` targets: all of it on each, or shared out // evenly, any remainder going one point each to the first targets picked // (7 between three is 3, 2 and 2). function shares(amount: number, count: number, mode: AreaMode): number[] { if (mode === 'EACH') return Array.from({ length: count }, () => amount); const base = Math.floor(amount / count); return Array.from({ length: count }, (_, i) => base + (i < amount % count ? 1 : 0)); } // The DM's shortcut once targets are marked: who is attacking whom, the // numbers needed to call the hit, and a box to apply the damage without // hunting for each target's card. With more than one target it is an area // attack: each AC is shown with the penalty added, the DM ticks who was hit, // and the amount is split between them or dealt to each in full. function AttackBar({ attacker, targets, acStep, onApply, onRemove, onClear, }: { attacker: EncounterParticipant | undefined; targets: EncounterParticipant[]; acStep: number; // the campaign's area attack AC penalty onApply: (changes: { participantId: string; currentHp: number }[]) => void; onRemove: (participantId: string) => void; onClear: () => void; }) { const [amount, setAmount] = useState(''); const [mode, setMode] = useState('SPLIT'); const [missed, setMissed] = useState([]); const isArea = targets.length > 1; const penalty = areaPenalty(targets.length, acStep); const tracksHp = (t: EncounterParticipant) => (t.maxHp ?? 0) > 0; const hit = targets.filter((t) => tracksHp(t) && !missed.includes(t.id)); const value = Number(amount) || 0; const portions = shares(value, hit.length, isArea ? mode : 'EACH'); const attacks = attacker ? attackLines(attacker) : []; function apply(sign: 1 | -1) { if (!value || hit.length === 0) return; onApply(hit.map((t, i) => ({ participantId: t.id, currentHp: (t.currentHp ?? 0) + sign * portions[i] }))); setAmount(''); setMissed([]); } return (
{attacker && <>{attacker.displayName} → }🎯 {isArea ? `${targets.length} targets` : targets[0].displayName}
{isArea && (

Area attack{penalty > 0 && `: every target's AC counts as ${penalty} higher (+${acStep} for each target beyond the first)`}. Untick anyone the roll missed.

)} {targets.map((t) => { const info = t.characterCombatInfo; const ac = info?.armorClass ?? t.monster?.ac ?? t.npc?.ac; const portion = portions[hit.indexOf(t)]; return (
{isArea && ( )}
{ac != null && ( {ac + penalty} {penalty > 0 && ` (${ac} +${penalty})`} )} {tracksHp(t) ? ( {t.currentHp ?? 0}/{t.maxHp} {info && info.tempHp > 0 && ` +${info.tempHp}`} ) : ( No hit points to track. )} {isArea && value > 0 && portion !== undefined && {portion}}
{isArea && ( )}
); })} {attacks.map((line) => (
⚔ {line}
))} {targets.some(tracksHp) && (
{/* Remounted when the targets change, so the cursor lands here as soon as one is marked. */} t.id).join()} autoFocus min={1} max={99999} placeholder={isArea ? 'Total' : 'Amount'} aria-label={isArea ? 'HP change for the targets hit' : `HP change for ${targets[0].displayName}`} value={amount} onChange={(e) => setAmount(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && apply(-1)} style={{ width: 90 }} /> {isArea && ( )}
)}
); } // The one thing the scene is waiting on, in a sentence: for the DM, what to // do next; for a player, what is theirs to do. `urgent` when it is a roll or a // ruling that holds the fight up. Null when there is nothing to say. function whatNow({ encounter, isDM, active, targets, actions, myTurn, unrolled, userId, }: { encounter: Encounter; isDM: boolean; active: EncounterParticipant | undefined; targets: EncounterParticipant[]; actions: EncounterAction[]; myTurn: boolean; unrolled: number; userId: string | undefined; }): { text: string; urgent: boolean } | null { if (encounter.mode !== 'BATTLE') return null; const names = (list: { name: string }[]) => list.map((t) => t.name).join(', '); if (!isDM) { const mine = (encounter.participants ?? []).filter((p) => p.character?.userId === userId).map((p) => p.id); const save = actions.find((a) => a.kind === 'SAVE' && a.targets.some((t) => t.d20 == null && mine.includes(t.participantId))); if (save) return { text: `${save.actorName}'s ${save.name}: make a ${save.detail.saveAbility} saving throw and enter your d20.`, urgent: true }; const own = actions.find((a) => a.actorParticipantId != null && mine.includes(a.actorParticipantId)); if (own?.needsRolls) return { text: `Roll your d20 for ${own.name} against ${names(own.targets.filter((t) => t.d20 == null))}.`, urgent: true }; if (own?.needsDamage) return { text: `It hits! Roll the damage for ${own.name}.`, urgent: true }; if (own?.ready) return { text: `${own.name} is ready: your DM lets it land.`, urgent: false }; if (myTurn) return targets.length === 0 ? { text: 'Your turn! Pick a target: click a name on the track above.', urgent: true } : { text: `Your turn: choose what you attack ${names(targets.map((t) => ({ name: t.displayName })))} with.`, urgent: true }; return null; } if (encounter.status === 'PLANNING') { return { text: unrolled > 0 ? `Setting up: ${unrolled} still to roll initiative. Then press Begin Battle.` : 'Everyone has rolled initiative. Press Begin Battle.', urgent: false }; } if (encounter.status !== 'ACTIVE') return null; const pending = actions[0]; if (pending) { const who = `${pending.actorName}'s ${pending.name}`; const waiting = pending.targets.filter((t) => !t.outcome); if (pending.needsRolls > 0) { return pending.kind === 'SAVE' ? { text: `${who}: ${waiting.length} saving throw${waiting.length === 1 ? '' : 's'} to enter (${pending.detail.saveAbility}, DC ${pending.detail.saveDC}) for ${names(waiting)}.`, urgent: true } : { text: `${who}: enter the d20 against ${names(waiting)}${waiting[0]?.ac != null ? ` (AC ${waiting[0].ac + waiting[0].penalty})` : ''}.`, urgent: true }; } if (pending.needsDamage) return { text: `${who} hits: roll or enter the damage.`, urgent: true }; const result = pending.targets.map((t) => `${t.name}: ${t.outcome?.toLowerCase() ?? '—'}${t.finalDamage ? ` for ${t.finalDamage}` : ''}`).join('; '); return { text: `${who} is ready (${result}). ${pending.auto ? 'Accept, change or discard it.' : 'Apply it, or overrule anything first.'}`, urgent: true }; } if (unrolled > 0) return { text: `${unrolled} combatant${unrolled === 1 ? ' has' : 's have'} no initiative roll yet.`, urgent: false }; if (!active) return null; if (targets.length === 0) { return active.character ? { text: `${active.displayName}'s turn: waiting for them to pick a target (or pick one for them: click a name).`, urgent: false } : { text: `${active.displayName}'s turn: click a name to pick its target, or press Next Turn.`, urgent: false }; } return { text: `${active.displayName} → ${names(targets.map((t) => ({ name: t.displayName })))}: choose the attack below, or apply damage by hand.`, urgent: false }; } const RATING_LABELS = { TRIVIAL: 'Trivial', EASY: 'Easy', MEDIUM: 'Medium', HARD: 'Hard', DEADLY: 'Deadly' } as const; const RATING_BADGES = { TRIVIAL: '', EASY: 'badge-friendly', MEDIUM: 'badge-dm', HARD: 'badge-hostile', DEADLY: 'badge-hostile' } as const; // The DM's read on the fight, and the XP for it: what the monsters are worth, // how that sits against what the party can take, and the button that hands it // out, in equal shares, once. function ExperiencePanel({ encounterId, difficulty, xpAwarded, partySize, onError, }: { encounterId: string; difficulty: EncounterDifficulty; xpAwarded: number | null; partySize: number; onError: (err: unknown) => void; }) { const awardXp = useAwardXp(encounterId); const [amount, setAmount] = useState(''); const xp = amount === '' ? difficulty.xp : Math.floor(Number(amount)) || 0; const { thresholds, rating } = difficulty; return (
Experience {rating && {RATING_LABELS[rating]}}
{difficulty.monsters === 0 ? (

No monster here has a challenge rating, so there is nothing to judge the difficulty by. XP can still be awarded: type an amount.

) : ( <>
{difficulty.xp.toLocaleString()} XP {difficulty.multiplier !== 1 && ( {difficulty.adjustedXp.toLocaleString()} XP )}
{thresholds ? (

For this party: Easy {thresholds.easy.toLocaleString()} · Medium {thresholds.medium.toLocaleString()} · Hard {thresholds.hard.toLocaleString()} · Deadly{' '} {thresholds.deadly.toLocaleString()}

) : (

Add the characters to see how hard this is for them.

)} )} {difficulty.unrated > 0 && (

{difficulty.unrated} monster{difficulty.unrated === 1 ? ' has' : 's have'} no challenge rating and {difficulty.unrated === 1 ? 'is' : 'are'} not counted.

)} {xpAwarded != null ? (

✓ {xpAwarded.toLocaleString()} XP awarded{partySize > 0 && `: ${Math.floor(xpAwarded / partySize).toLocaleString()} each`}.

) : (
0 ? String(difficulty.xp) : 'XP'} title="The XP to share out. Left empty, what the monsters are worth." aria-label="XP to award" value={amount} onChange={(e) => setAmount(e.target.value)} style={{ width: 110 }} />
)}
); } function rewardLabel(r: EncounterReward): string { if (r.type === 'GOLD') return formatMoney(r.gold ?? 0, r.currency ?? 'GOLD', true); const entry = r.type === 'WEAPON' ? r.weapon : r.item; return `${entry?.name ?? 'Removed from the pool'}${r.quantity > 1 ? ` ×${r.quantity}` : ''} · Lv ${r.level}`; } function RewardsPanel({ encounter, isDM, characters, weapons, items, onError, }: { encounter: Encounter; isDM: boolean; characters: CharacterSummary[]; weapons: Weapon[]; items: Item[]; onError: (err: unknown) => void; }) { const addReward = useAddReward(encounter.id); const deleteReward = useDeleteReward(encounter.id); const awardReward = useAwardReward(encounter.id); const [type, setType] = useState('GOLD'); const [gold, setGold] = useState(''); const [currency, setCurrency] = useState('GOLD'); const [poolId, setPoolId] = useState(''); const [quantity, setQuantity] = useState('1'); const [level, setLevel] = useState(''); const [note, setNote] = useState(''); const [recipients, setRecipients] = useState>({}); const rewards = encounter.rewards ?? []; const pool: (Weapon | Item)[] = type === 'WEAPON' ? weapons : items; const picked = pool.find((entry) => entry.id === poolId); const partySize = (encounter.participants ?? []).filter((p) => p.kind === 'CHARACTER' && p.characterId).length; if (!isDM && rewards.length === 0) return null; function handleAdd() { const shared = { note: note.trim() || undefined }; let reward: NewReward; if (type === 'GOLD') { const amount = Math.floor(Number(gold)); if (!(amount > 0)) return; reward = { type, gold: amount, currency, ...shared }; } else { if (!picked) return; const gear = { quantity: Math.max(1, Math.floor(Number(quantity)) || 1), level: level ? Number(level) : undefined, ...shared }; reward = type === 'WEAPON' ? { type, weaponId: picked.id, ...gear } : { type, itemId: picked.id, ...gear }; } addReward.mutate(reward, { onError, onSuccess: () => { setGold(''); setPoolId(''); setQuantity('1'); setLevel(''); setNote(''); }, }); } return (
Rewards
{isDM && rewards.length === 0 && (

Line up coins, weapons and items here. Players only see a reward once you award it.

)} {rewards.map((r) => (
{r.type === 'GOLD' ? '🪙' : r.type === 'WEAPON' ? '🗡' : '🎒'} {rewardLabel(r)} {isDM && ( )}
{r.note &&
{r.note}
} {r.awardedAt ? (
✓ Awarded to {r.awardedTo}
) : ( isDM && (
{r.type === 'GOLD' && ( )}
) )}
))} {isDM && (
Add a reward
{type === 'GOLD' ? ( <> setGold(e.target.value)} style={{ flex: 1, minWidth: 90 }} /> ) : ( <> {picked && ( <> setQuantity(e.target.value)} style={{ width: 64 }} /> )} )}
setNote(e.target.value)} style={{ flex: 1, minWidth: 0 }} />
)}
); } export function EncounterPage() { const { encounterId = '' } = useParams(); const { user } = useAuth(); const { data: encounter, isLoading, error } = useEncounter(encounterId); useCampaignSocket(encounter?.campaignId); useRememberCampaign(encounter?.campaignId); const { data: campaignData } = useCampaign(encounter?.campaignId); // The table's rolls, for the DM to watch beside the fight. const { data: rolls } = useRolls(encounter?.campaignId); const isDM = campaignData?.campaign.role === 'DM'; const { data: characters } = useCampaignCharacters(encounter?.campaignId); const { data: monsters } = useCampaignMonsters(encounter?.campaignId, isDM); const { data: npcs } = useCampaignNpcs(encounter?.campaignId, isDM); const { data: weapons } = useCampaignWeapons(encounter?.campaignId); const { data: items } = useCampaignItems(encounter?.campaignId); const { data: locations } = useCampaignLocations(encounter?.campaignId); const addParticipant = useAddParticipant(encounterId); const patchParticipant = usePatchParticipant(encounterId); const removeParticipant = useRemoveParticipant(encounterId); const advanceRound = useAdvanceRound(encounterId); const rollInitiative = useRollInitiative(encounterId); const nextTurn = useNextTurn(encounterId); const setTargets = useSetTargets(encounterId); const revive = useReviveParticipant(encounterId); const applyAction = useApplyAction(encounterId); const patchEncounter = usePatchEncounter(encounterId); const setArchived = useSetEncounterArchived(encounter?.campaignId ?? ''); const deleteEncounter = useDeleteEncounter(encounter?.campaignId ?? ''); const navigate = useNavigate(); const [pickType, setPickType] = useState<'character' | 'monster' | 'npc'>('character'); const [pickId, setPickId] = useState(''); const [initiative, setInitiative] = useState(''); const [count, setCount] = useState('1'); // Things the DM should know that are nobody's error: a condition wearing // off, a concentration save to call for. const [checking, setChecking] = useState(false); const [notices, setNotices] = useState([]); const notify = (...lines: string[]) => lines.length > 0 && setNotices((current) => [...current, ...lines].slice(-6)); // A new round can end timed conditions; the answer says which. const turnPassed = { onError: (err: unknown) => setFormError(extractErrorMessage(err)), onSuccess: (data: { expired?: { name: string; condition: string }[] }) => notify(...(data.expired ?? []).map((e) => `${e.condition} wore off ${e.name}.`)), }; const [formError, setFormError] = useState(null); // The DM's own screen leaves the fallen out too, until asked for. const [showDead, setShowDead] = useState(false); // The combatant whose stats are kept in view in place of whoever is on turn. const [pinnedId, setPinnedId] = useState(null); // The DM's keys: N passes the turn, S opens the sheet of whoever is on turn, // A accepts the first attack that is ready. For whoever may pick targets // (the DM, or a player on their own turn), 1 to 9 mark the combatants in // turn order, leaving out whoever is on turn. const onTurn = encounter?.participants?.find((p) => p.id === encounter.activeParticipantId); const running = encounter?.mode === 'BATTLE' && encounter.status === 'ACTIVE'; const dmRunning = isDM && running; const marked = encounter?.targetParticipantIds ?? []; const mayMark = isDM || (running && onTurn?.character != null && onTurn.character.userId === user?.id); const byKey = (encounter?.participants ?? []).filter((p) => !p.hidden && !(running && p.id === encounter?.activeParticipantId)).slice(0, 9); const readyAction = (encounter?.actions ?? []).find((a) => a.ready); useHotkeys({ n: dmRunning && !nextTurn.isPending ? () => nextTurn.mutate(undefined, turnPassed) : undefined, s: dmRunning && onTurn ? () => (onTurn.character ? openCharacterPanel(onTurn.character.id) : setPinnedId(onTurn.id)) : undefined, a: isDM && readyAction && !applyAction.isPending ? () => applyAction.mutate(readyAction.id, { onError: (err: unknown) => setFormError(extractErrorMessage(err)), onSuccess: (data) => notify( ...data.concentration.map((c) => `${c.name} is concentrating and took ${c.damage} damage: Constitution save, DC ${c.dc}. On a failure the spell ends: remove Concentrating.`), ...(data.slotNote ? [data.slotNote] : []) ), }) : undefined, ...Object.fromEntries( byKey.map((p, i) => [ String(i + 1), mayMark ? () => setTargets.mutate(marked.includes(p.id) ? marked.filter((id) => id !== p.id) : [...marked, p.id], { onError: (err: unknown) => setFormError(extractErrorMessage(err)) }) : undefined, ]) ), }); if (isLoading) return ; if (error || !encounter) return ; const isBattle = encounter.mode === 'BATTLE'; const isRoam = encounter.mode === 'FREE_ROAM'; const participants = encounter.participants ?? []; // already in initiative order // The fallen: dead characters, and monsters and NPCs at 0 HP. Only the DM is // sent their cards, and they sit apart from those still in the fight. const standing = participants.filter((p) => !p.hidden); const outOfTheFight = participants.filter((p) => p.hidden); const fallen = encounter.fallen ?? []; const active = isBattle && encounter.status === 'ACTIVE' ? participants.find((p) => p.id === encounter.activeParticipantId) : undefined; const targetIds = encounter.targetParticipantIds ?? []; const targets = targetIds.map((id) => participants.find((p) => p.id === id)).filter((p): p is EncounterParticipant => p !== undefined); // The DM marks targets whenever they like; a player while their own character is on turn. const acStep = campaignData?.campaign.areaAttackAcPenalty ?? 0; const canTarget = isDM || (active?.character != null && active.character.userId === user?.id); // A player whose own character is on turn, on their feet and able to raise the dead. const canTryRevive = active?.character != null && active.character.userId === user?.id && active.characterCombatInfo?.deathSaves.state === 'UP' && active.characterCombatInfo.canRevive; const builtCharacters = characters?.filter((c) => c.buildStage === 'COMPLETE') ?? []; const onError = (err: unknown) => setFormError(extractErrorMessage(err)); const fail = { onError }; const toggleTarget = (participantId: string) => setTargets.mutate(targetIds.includes(participantId) ? targetIds.filter((id) => id !== participantId) : [...targetIds, participantId], fail); // Attacks and spells being resolved, and whether it is this viewer's own character's turn. const actions = encounter.actions ?? []; const myTurn = active?.character != null && active.character.userId === user?.id; const diceMode = campaignData?.campaign.diceMode ?? 'BOTH'; // What the DM is waiting on right now, in one line; for a player, what is theirs to do. const cue = whatNow({ encounter, isDM, active, targets, actions, myTurn, unrolled: participants.filter((p) => p.initiativeRoll == null && !p.hidden).length, userId: user?.id }); const pickOptions: { id: string; name: string }[] = pickType === 'character' ? // The dead join no new scene until they are revived. builtCharacters.filter((c) => c.deathSaves.state !== 'DEAD' && !participants.some((p) => p.characterId === c.id)) : pickType === 'monster' ? (monsters ?? []) : (npcs ?? []).filter((n) => !participants.some((p) => p.npcId === n.id)); function handleAdd() { if (!pickId) return; setFormError(null); const howMany = pickType === 'monster' ? Math.min(20, Math.max(1, Math.floor(Number(count)) || 1)) : 1; addParticipant.mutate( { [`${pickType}Id`]: pickId, initiativeRoll: initiative ? Number(initiative) : undefined, count: howMany }, { onError, onSuccess: () => { setPickId(''); setCount('1'); }, } ); } // HP changes go through here, so that damage to someone holding a spell // reminds the DM of the save. function changeHp(changes: { participantId: string; currentHp: number }[]) { for (const change of changes) { const p = participants.find((x) => x.id === change.participantId); const lost = p ? (p.currentHp ?? 0) - change.currentHp : 0; if (p && lost > 0 && p.conditions.includes('Concentrating')) notify(concentrationCheck(p, lost)); } return Promise.all(changes.map((change) => patchParticipant.mutateAsync(change))).catch(onError); } // The characters still up, for a roll the DM calls for from all of them. const checkers = standing.flatMap((p) => p.character && p.characterCombatInfo ? [{ id: p.character.id, name: p.displayName, abilities: p.characterCombatInfo.abilities, saves: p.characterCombatInfo.saves, skills: p.characterCombatInfo.skills }] : [] ); const unrolled = participants.filter((p) => p.kind !== 'CHARACTER' && p.initiativeRoll == null).length; const card = (p: EncounterParticipant) => ( (data.currentHp == null ? patchParticipant.mutate({ participantId: p.id, ...data }, fail) : changeHp([{ participantId: p.id, currentHp: data.currentHp }]))} canRollInitiative={isDM || (p.character != null && p.character.userId === user?.id)} targetedBy={targetIds.includes(p.id) ? (active?.displayName ?? '') : undefined} acPenalty={areaPenalty(targets.length, acStep)} onTarget={ // Nobody targets themselves: the combatant on turn has no button. canTarget && p.id !== active?.id ? () => toggleTarget(p.id) : undefined } isPinned={p.id === pinnedId} onPin={() => setPinnedId(p.id === pinnedId ? null : p.id)} onRemove={() => removeParticipant.mutate(p.id, fail)} onError={onError} /> ); // In a battle under way the turn passes down the initiative order, so // everyone above whoever is on turn has had their go this round. They drop // to "Next Round" at the bottom, which leaves the combatant on turn at the // top with those still to act beneath them. A new round puts everyone back. const turnIndex = active ? participants.indexOf(active) : -1; const hasActed = (p: EncounterParticipant) => participants.indexOf(p) < turnIndex; // A quest scene is grouped by who is there; within each group the order is // still initiative, highest first. const groups: [string, EncounterParticipant[]][] = isBattle ? [ ['Initiative order', standing.filter((p) => !hasActed(p))], ['Next Round', standing.filter(hasActed)], ] : [ ['People you meet', standing.filter((p) => p.kind === 'NPC')], ['The party', standing.filter((p) => p.kind === 'CHARACTER')], ['Creatures', standing.filter((p) => p.kind === 'MONSTER')], ]; if (showDead) groups.push(['Out of the fight, hidden from players', outOfTheFight]); // Whose stats stay in view: the pinned combatant, or else whoever is on turn. const pinned = participants.find((p) => p.id === pinnedId); const spotlit = pinned ?? active; const hasStats = (p: EncounterParticipant) => Boolean(p.characterCombatInfo || p.monster?.ac !== undefined || p.npc); return (

{isBattle ? '⚔' : isRoam ? '🧭' : '📜'} {encounter.name}

{MODE_LABELS[encounter.mode]} {STATUS_LABELS[encounter.status]} {isBattle && Round {encounter.currentRound}} {encounter.difficulty?.rating && ( {RATING_LABELS[encounter.difficulty.rating]} · {encounter.difficulty.xp.toLocaleString()} XP )} {encounter.location && 📍 {encounter.location.name}} {encounter.archivedAt && Archived} {active && ▶ {active.displayName}'s turn}
← Campaign {isDM && ( <> {checkers.length > 0 && ( )} {encounter.status === 'PLANNING' && ( )} {encounter.status === 'ACTIVE' && isBattle && ( <> )} {encounter.status === 'ACTIVE' && ( )} {encounter.status === 'COMPLETE' && ( )} )}
{isDM && checking && setChecking(false)} />} {formError && } {isDM && notices.length > 0 && (
{notices.map((line, i) => (

{line}

))}
)} {active ? ( ) : ( standing.length > 1 && )} {cue && (
{isDM ? 'What now' : 'Your move'} {cue.text} {isDM && running && Keys: 1–9 target · A accept · N next turn · S sheet}
)} {(isDM || encounter.description) && (
{isBattle ? 'The Scene' : isRoam ? 'Where the party is' : 'Quest'}
{isDM ? (