Files
the-sunken-reach/frontend/src/pages/EncounterPage.tsx
T
joshuaandClaude Opus 5.5 555765916f V1.28.0: free roam, and completed encounters out of the way
- Free roam: a third kind of encounter. The DM ticks the nearby locations,
  the whole party is in it from the start, and each player sends their own
  character to a place
- A place shows who is found there and what is for sale; a character shops
  (a place's own shop, or an NPC's wares and exchange) only where they stand
- Locations can have a shop of their own; an NPC can be "found at" a location
- Completed encounters are hidden from the campaign's list until "Show
  completed" is ticked; moving an encounter works on the list as shown

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 09:30:16 +02:00

1933 lines
81 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 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<EncounterMode, string> = { 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 (
<span className="stat-chip">
<span>{label}</span>
<b>{children}</b>
</span>
);
}
// 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 && (
<>
<div className="stat-chips">
{ABILITIES.map((a) => (
<Rollable key={a} label={`${p.displayName}: ${ABILITY_LABELS[a]} check`} modifier={info.abilities[a].modifier}>
<StatChip label={a}>
{info.abilities[a].final} ({fmtMod(info.abilities[a].modifier)})
</StatChip>
</Rollable>
))}
</div>
<GearInForce gear={info.gear} />
{info.weapons.length === 0 && (
<p className="combatant-sub">No weapon equipped. A weapon has to be equipped to be used: open 📋 Sheet to put one on.</p>
)}
{info.items.length > 0 && (
<p className="combatant-sub">
Equipped: {info.items.map((i) => `${i.name}${i.damageDice ? ` (${i.damageDice})` : ''}`).join(' · ')}
</p>
)}
{info.weapons.map((w) => (
<div key={w.characterWeaponId} className="detail-row">
<span>
{w.name}
<span className="combatant-sub" style={{ marginLeft: 6 }}>
Lv {w.level} ·{' '}
<Rollable label={`${p.displayName}: ${w.name} damage`} dice={withBonus(w.damageDice, w.damageBonus)}>
{w.damageDice} {fmtMod(w.damageBonus)}
</Rollable>{' '}
{w.damageType}
</span>
</span>
<Rollable label={`${p.displayName}: ${w.name} attack`} modifier={w.attackBonus} className="mono">
{fmtMod(w.attackBonus)} to hit
</Rollable>
</div>
))}
{info.spellcasting && (
<p className="combatant-sub">
Spellcasting ({ABILITY_LABELS[info.spellcasting.ability]}): save DC {info.spellcasting.saveDC} ·{' '}
<Rollable label={`${p.displayName}: spell attack`} modifier={info.spellcasting.attackBonus}>
{fmtMod(info.spellcasting.attackBonus)} to hit
</Rollable>
{info.spellSlots && ` · slots left ${slotsSummary(info.spellSlots)}`}
</p>
)}
{info.spells.length > 0 && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{info.spells.map((s) => (
<span
key={s.characterSpellId}
className={`badge ${s.prepared ? 'badge-dm' : ''}`}
title={[s.prepared ? 'Prepared' : 'Known, not prepared', s.description].filter(Boolean).join(' — ')}
>
{s.name} ({spellLevelLabel(s.level)}
{s.damageDice ? ` · ${s.damageDice}` : ''})
</span>
))}
</div>
)}
{p.character && info.resources.length > 0 && (
<>
<div className="section-label">Counters</div>
<ResourceTracker characterId={p.character.id} name={p.displayName} resources={info.resources} canUse={canUse} isDM={isDM} onError={onError} />
</>
)}
<SheetNumbers
who={p.displayName}
saves={info.saves}
skills={info.skills}
passives={{ perception: info.passivePerception, investigation: info.passiveInvestigation, insight: info.passiveInsight }}
/>
{info.specialAbilities && (
<>
<div className="section-label">Special abilities</div>
<p style={{ whiteSpace: 'pre-wrap' }}>{info.specialAbilities}</p>
</>
)}
</>
)}
{monsterStats && (
<>
<div className="stat-chips">
{ABILITIES.map((a) => {
const score = monsterStats[`${a.toLowerCase()}Score` as 'strScore'] ?? 10;
return (
<Rollable key={a} label={`${p.displayName}: ${ABILITY_LABELS[a]} check or save`} modifier={abilityModifier(score)}>
<StatChip label={a}>
{score} ({fmtMod(abilityModifier(score))})
</StatChip>
</Rollable>
);
})}
</div>
{monsterStats.specialTrait && (
<p>
<strong>Trait:</strong> {monsterStats.specialTrait}
</p>
)}
{monsterStats.notes && <p style={{ whiteSpace: 'pre-wrap' }}>{monsterStats.notes}</p>}
</>
)}
{npc?.dmNotes && (
<p style={{ whiteSpace: 'pre-wrap', color: 'var(--text-muted)' }} title="Only you can see this">
🔒 {npc.dmNotes}
</p>
)}
</>
);
}
// 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 (
<div className="stat-chips mt-sm">
{tracksHp && !barOnly && (
<StatChip label="HP">
{currentHp}/{maxHp}
{info && info.tempHp > 0 && ` +${info.tempHp}`}
</StatChip>
)}
{info && (
<>
<StatChip label="AC">{info.armorClass}</StatChip>
<StatChip label="Speed">{info.speed}</StatChip>
<Rollable label={`${p.displayName}: initiative`} modifier={info.initiativeBonus}>
<StatChip label="Init">{fmtMod(info.initiativeBonus)}</StatChip>
</Rollable>
<StatChip label="Passive Perc.">{info.passivePerception}</StatChip>
<StatChip label="Prof.">{fmtMod(info.proficiencyBonus)}</StatChip>
{info.spellcasting && <StatChip label="Spell DC">{info.spellcasting.saveDC}</StatChip>}
</>
)}
{monsterStats && (
<>
<StatChip label="AC">{monsterStats.ac}</StatChip>
<StatChip label="Speed">{monsterStats.speed}</StatChip>
<Rollable label={`${p.displayName}: attack`} modifier={monsterStats.attackBonus ?? 0}>
<StatChip label="Attack">{fmtMod(monsterStats.attackBonus ?? 0)}</StatChip>
</Rollable>
{monsterStats.damageDice && (
<Rollable label={`${p.displayName}: damage`} dice={monsterStats.damageDice}>
<StatChip label="Damage">{monsterStats.damageDice}</StatChip>
</Rollable>
)}
</>
)}
{npc && npc.ac != null && <StatChip label="AC">{npc.ac}</StatChip>}
{npc && npc.attackBonus != null && (
<Rollable label={`${p.displayName}: attack`} modifier={npc.attackBonus}>
<StatChip label="Attack">{fmtMod(npc.attackBonus)}</StatChip>
</Rollable>
)}
{npc && npc.damageDice && (
<Rollable label={`${p.displayName}: damage`} dice={npc.damageDice}>
<StatChip label="Damage">{npc.damageDice}</StatChip>
</Rollable>
)}
</div>
);
}
// 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 (
<div className="in-hand" title="Equipped: what they fight with">
<span className="in-hand-label">In hand</span>
{info.weapons.length === 0 && <span className="combatant-sub">nothing equipped</span>}
{info.weapons.map((w) => (
<span key={w.characterWeaponId} className="in-hand-weapon">
⚔ {w.name}{' '}
<span className="mono">
{fmtMod(w.attackBonus)} · {w.damageDice} {fmtMod(w.damageBonus)} {w.damageType}
</span>
</span>
))}
</div>
);
}
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 (
<div className="in-hand" title="What it attacks with">
<span className="in-hand-label">Attacks</span>
{attacks.map((a, i) => (
<span key={i} className="in-hand-weapon">
⚔ {a.name}
{(a.count ?? 1) > 1 ? ` ×${a.count}` : ''}{' '}
<span className="mono">
{fmtMod(a.attackBonus)}
{a.damageDice ? ` · ${a.damageDice}` : ''}
</span>
</span>
))}
</div>
);
}
// "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 (
<nav className="turn-strip" aria-label="Everyone in the scene, in turn order">
{participants.map((p) => {
const { currentHp, maxHp, barOnly, tracksHp, pct } = healthOf(p);
const isMine = p.character != null && p.character.userId === userId;
const isActive = p.id === activeId;
const isTargeted = targetIds.includes(p.id);
const dying = p.characterCombatInfo?.deathSaves.state === 'DYING';
return (
<button
key={p.id}
type="button"
className={`turn-chip${isActive ? ' is-active' : ''}${isMine ? ' is-mine' : ''}${isTargeted ? ' is-targeted' : ''}${hasActed(p) ? ' has-acted' : ''}`}
aria-current={isActive ? 'true' : undefined}
title={[
p.displayName,
isActive && 'on turn',
isTargeted && 'targeted',
tracksHp && !barOnly && `${currentHp}/${maxHp} HP`,
p.conditions.length > 0 && p.conditions.join(', '),
]
.filter(Boolean)
.join(' · ')}
onClick={() => jumpToCard(p.id)}
>
<span className="turn-chip-name">
{isActive && '▶ '}
{isMine && '★ '}
{isTargeted && '🎯 '}
{p.displayName}
</span>
<span className="turn-chip-sub">
{dying ? 'dying' : tracksHp && !barOnly ? `${currentHp}/${maxHp}` : p.initiativeRoll == null ? 'no roll' : `init ${p.initiative}`}
{p.conditions.length > 0 && ` · ⚑${p.conditions.length}`}
</span>
{tracksHp && <HpBar current={pct} max={100} height={3} />}
</button>
);
})}
</nav>
);
}
// 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 (
<div className="card spotlight">
<div className="card-title">
<span>{isPinned ? '📌 Pinned' : '▶ On turn'}</span>
{isPinned && (
<button className="btn btn-ghost" onClick={onUnpin} title="Go back to showing whoever is on turn">
✕ Unpin
</button>
)}
</div>
<div className="flex-between flex-wrap">
<button type="button" className="combatant-name link-button" onClick={() => jumpToCard(p.id)} title="Go to their card">
{p.displayName}
</button>
{p.character && canOpenSheet && (
<button className="btn btn-target" onClick={() => p.character && openCharacterPanel(p.character.id)}>
📋 Sheet
</button>
)}
</div>
<div className="combatant-sub">
{subline(p)}
{isPinned && isOnTurn && ' · on turn'}
</div>
<HeadlineChips participant={p} />
{(p.conditions.length > 0 || info?.inspiration || (info?.exhaustion ?? 0) > 0) && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{info && <StateBadges inspiration={info.inspiration} exhaustion={info.exhaustion} />}
{p.conditions.map((c) => (
<ConditionChip key={c} name={c} note={roundsNote(p, c)} />
))}
</div>
)}
{p.npc?.description && <p style={{ margin: '0.5rem 0 0', whiteSpace: 'pre-wrap' }}>{p.npc.description}</p>}
<div className="combatant-details">
<CombatantDetails participant={p} isDM={isDM} canUse={canOpenSheet} onError={onError} />
</div>
</div>
);
}
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<EncounterParticipant>) => 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<boolean | null>(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 (
<div
id={`combatant-${p.id}`}
className={`card combatant combatant-${p.kind.toLowerCase()}${isMine ? ' is-mine' : ''}${isActive ? ' is-active' : ''}${isDown && !isDying ? ' is-down' : ''}${isTargeted ? ' is-targeted' : ''}`}
>
<div className="flex-between flex-wrap">
<div>
{isMine && <div className="mine-marker">★ Your character</div>}
{isActive && <div className="turn-marker">▶ On turn</div>}
{isTargeted && (
<div className="target-marker">
🎯 Targeted{targetedBy && ` by ${targetedBy}`}
{acPenalty > 0 && ` · area attack, AC +${acPenalty}`}
</div>
)}
<div className="flex-row flex-wrap">
<span className={`badge ${KIND_BADGES[p.kind]}`}>{KIND_LABELS[p.kind]}</span>
{p.character ? (
<Link to={`/characters/${p.character.id}`} className="combatant-name">
{p.displayName}
</Link>
) : (
<span className="combatant-name">{p.displayName}</span>
)}
{npc && <span className={`badge badge-${npc.disposition.toLowerCase()}`}>{npc.disposition}</span>}
{p.character && (isDM || isMine) && (
<button
className="btn btn-target"
title={`${p.displayName}'s sheet beside this screen: saves, skills, weapons, items, spells and money`}
onClick={() => p.character && openCharacterPanel(p.character.id)}
>
📋 Sheet
</button>
)}
{hasDetails && (
<button
className={`btn btn-target btn-pin${isPinned ? ' is-on' : ''}`}
aria-pressed={isPinned}
title={isPinned ? 'Stop keeping these stats in view' : `Keep ${p.displayName}'s stats in view while you scroll`}
onClick={onPin}
>
📌 {isPinned ? 'Pinned' : 'Pin'}
</button>
)}
{isDown && !info && <span className="badge badge-hostile">Down</span>}
{p.hidden && (
<span className="badge" title="Out of the fight. Players no longer see this card, and it has no turn.">
Hidden from players
</span>
)}
{onTarget && (
<button
className={`btn btn-target${isTargeted ? ' is-on' : ''}`}
aria-pressed={isTargeted}
title={isTargeted ? 'Stop targeting' : `Mark ${p.displayName} as a target. Marking more than one makes it an area attack.`}
onClick={onTarget}
>
🎯 {isTargeted ? 'Targeted' : 'Target'}
</button>
)}
</div>
<div className="combatant-sub">{subline(p)}</div>
</div>
{/* Battles and quests both take initiative: who speaks or acts first matters in either. */}
{canRollInitiative ? (
<label className="flex-row gap-sm" title="Type what the d20 showed (1 to 20). The initiative bonus is added for you.">
Initiative roll
<NumberInput
key={`${p.id}:${p.initiativeRoll}`}
min={1}
max={20}
placeholder="d20"
aria-label={`Initiative roll for ${p.displayName}`}
defaultValue={p.initiativeRoll ?? ''}
style={{ width: 64 }}
onBlur={(e) => {
const roll = e.target.value === '' ? null : Number(e.target.value);
if (roll !== p.initiativeRoll) onPatch({ initiativeRoll: roll });
}}
/>
<span className="mono">
{p.initiativeBonus !== undefined && fmtMod(p.initiativeBonus)}
{p.initiativeRoll != null && ` = ${p.initiative}`}
</span>
</label>
) : (
<StatChip label="Initiative">{p.initiativeRoll == null ? '—' : p.initiative}</StatChip>
)}
</div>
<HeadlineChips participant={p} />
{(isActive || isTargeted) && <InHand participant={p} />}
{/* An NPC's description is what players are here for, so it is never tucked away. */}
{npc?.description && <p style={{ margin: '0.5rem 0 0', whiteSpace: 'pre-wrap' }}>{npc.description}</p>}
{tracksHp && (
<>
<HpBar current={pct} max={100} temp={info && maxHp > 0 ? (info.tempHp / maxHp) * 100 : 0} />
{isDM && (
<div className="flex-row gap-sm mt-sm">
<NumberInput
min={1}
max={99999}
placeholder="Amount"
aria-label={`HP change for ${p.displayName}`}
value={hpDelta}
onChange={(e) => setHpDelta(e.target.value)}
style={{ width: 90 }}
/>
<button className="btn btn-danger" onClick={() => applyDelta(-1)} disabled={!hpDelta}>
− Damage
</button>
<button className="btn" onClick={() => applyDelta(1)} disabled={!hpDelta}>
+ Heal
</button>
</div>
)}
{info && p.character && (
<DeathSaves
characterId={p.character.id}
name={p.displayName}
deathSaves={info.deathSaves}
canAct={canRollInitiative}
isDM={isDM}
onError={onError}
/>
)}
</>
)}
{(p.conditions.length > 0 || isDM || info?.inspiration || (info?.exhaustion ?? 0) > 0) && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{info && <StateBadges inspiration={info.inspiration} exhaustion={info.exhaustion} />}
{p.conditions.map((c) => (
<ConditionChip
key={c}
name={c}
note={roundsNote(p, c)}
onRemove={isDM ? () => onPatch({ conditions: p.conditions.filter((x) => x !== c) }) : undefined}
/>
))}
{isDM && (
<>
<ConditionPicker who={p.displayName} current={p.conditions} onAdd={addCondition} />
<NumberInput
min={1}
max={100}
placeholder="rounds"
title="How many rounds the next condition you add lasts. It counts down as each round begins and comes off by itself. Leave empty for one that stays until you remove it."
aria-label={`Rounds the next condition on ${p.displayName} lasts`}
value={rounds}
onChange={(e) => setRounds(e.target.value)}
style={{ width: 84 }}
/>
</>
)}
</div>
)}
{(hasDetails || isDM) && (
<div className="flex-between mt-sm">
{hasDetails ? (
<button className="btn btn-ghost" onClick={() => setDetailsToggled(!showDetails)}>
{showDetails ? '▾ Hide details' : '▸ Show details'}
</button>
) : (
<span />
)}
{isDM && (
<button className="btn btn-ghost" onClick={onRemove}>
Remove
</button>
)}
</div>
)}
{hasDetails && showDetails && (
<div className="combatant-details">
<CombatantDetails participant={p} isDM={isDM} canUse={isDM || isMine} onError={onError} />
</div>
)}
</div>
);
}
// 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<AreaMode>('SPLIT');
const [missed, setMissed] = useState<string[]>([]);
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 (
<div className="card attack-bar">
<div className="flex-between flex-wrap">
<div className="attack-bar-title">
{attacker && <>{attacker.displayName} → </>}🎯 {isArea ? `${targets.length} targets` : targets[0].displayName}
</div>
<button className="btn btn-ghost" onClick={onClear}>
✕ Clear {isArea ? 'targets' : 'target'}
</button>
</div>
{isArea && (
<p className="combatant-sub" style={{ margin: '0.25rem 0 0' }}>
Area attack{penalty > 0 && `: every target's AC counts as ${penalty} higher (+${acStep} for each target beyond the first)`}. Untick anyone the
roll missed.
</p>
)}
{targets.map((t) => {
const info = t.characterCombatInfo;
const ac = info?.armorClass ?? t.monster?.ac ?? t.npc?.ac;
const portion = portions[hit.indexOf(t)];
return (
<div key={t.id} className="attack-target">
{isArea && (
<label className="flex-row gap-sm">
<input
type="checkbox"
aria-label={`${t.displayName} was hit`}
disabled={!tracksHp(t)}
checked={hit.includes(t)}
onChange={(e) => setMissed(e.target.checked ? missed.filter((id) => id !== t.id) : [...missed, t.id])}
/>
<span className="attack-target-name">{t.displayName}</span>
</label>
)}
<div className="stat-chips">
{ac != null && (
<StatChip label={isArea ? 'AC to beat' : 'Target AC'}>
{ac + penalty}
{penalty > 0 && ` (${ac} +${penalty})`}
</StatChip>
)}
{tracksHp(t) ? (
<StatChip label={isArea ? 'HP' : 'Target HP'}>
{t.currentHp ?? 0}/{t.maxHp}
{info && info.tempHp > 0 && ` +${info.tempHp}`}
</StatChip>
) : (
<span className="combatant-sub">No hit points to track.</span>
)}
{isArea && value > 0 && portion !== undefined && <StatChip label="Share">{portion}</StatChip>}
</div>
{isArea && (
<button className="btn btn-ghost" aria-label={`Stop targeting ${t.displayName}`} onClick={() => onRemove(t.id)}>
✕
</button>
)}
</div>
);
})}
{attacks.map((line) => (
<div key={line} className="combatant-sub mt-sm">
⚔ {line}
</div>
))}
{targets.some(tracksHp) && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{/* Remounted when the targets change, so the cursor lands here as soon as one is marked. */}
<NumberInput
key={targets.map((t) => 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 && (
<select aria-label="How the amount is shared" value={mode} onChange={(e) => setMode(e.target.value as AreaMode)} style={{ width: 'auto' }}>
<option value="SPLIT">Split between those hit</option>
<option value="EACH">Full amount to each</option>
</select>
)}
<button className="btn btn-danger" onClick={() => apply(-1)} disabled={!value || hit.length === 0}>
− Damage
</button>
<button className="btn" onClick={() => apply(1)} disabled={!value || hit.length === 0}>
+ Heal
</button>
</div>
)}
</div>
);
}
// 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 (
<div className="card">
<div className="card-title">
<span>Experience</span>
{rating && <span className={`badge ${RATING_BADGES[rating]}`}>{RATING_LABELS[rating]}</span>}
</div>
{difficulty.monsters === 0 ? (
<p className="combatant-sub" style={{ marginTop: 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.
</p>
) : (
<>
<div className="stat-chips">
<StatChip label="Monsters are worth">{difficulty.xp.toLocaleString()} XP</StatChip>
{difficulty.multiplier !== 1 && (
<StatChip label={`Counts as (×${difficulty.multiplier} for ${difficulty.monsters})`}>{difficulty.adjustedXp.toLocaleString()} XP</StatChip>
)}
</div>
{thresholds ? (
<p className="combatant-sub" style={{ margin: '0.4rem 0 0' }}>
For this party: Easy {thresholds.easy.toLocaleString()} · Medium {thresholds.medium.toLocaleString()} · Hard {thresholds.hard.toLocaleString()} · Deadly{' '}
{thresholds.deadly.toLocaleString()}
</p>
) : (
<p className="combatant-sub" style={{ margin: '0.4rem 0 0' }}>Add the characters to see how hard this is for them.</p>
)}
</>
)}
{difficulty.unrated > 0 && (
<p className="combatant-sub" style={{ margin: '0.4rem 0 0' }}>
{difficulty.unrated} monster{difficulty.unrated === 1 ? ' has' : 's have'} no challenge rating and {difficulty.unrated === 1 ? 'is' : 'are'} not counted.
</p>
)}
{xpAwarded != null ? (
<p style={{ margin: '0.6rem 0 0' }}>
✓ {xpAwarded.toLocaleString()} XP awarded{partySize > 0 && `: ${Math.floor(xpAwarded / partySize).toLocaleString()} each`}.
</p>
) : (
<div className="flex-row flex-wrap gap-sm mt-sm">
<NumberInput
min={1}
max={10000000}
placeholder={difficulty.xp > 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 }}
/>
<button
className="btn btn-primary"
disabled={!(xp > 0) || partySize === 0 || awardXp.isPending}
title={partySize === 0 ? 'There are no characters here to award it to' : 'Shared evenly between the characters in this encounter. It can be awarded once.'}
onClick={() => awardXp.mutate(amount === '' ? undefined : xp, { onError })}
>
Award{xp > 0 && partySize > 0 ? ` ${Math.floor(xp / partySize).toLocaleString()} XP each` : ' XP'}
</button>
</div>
)}
</div>
);
}
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<NewReward['type']>('GOLD');
const [gold, setGold] = useState('');
const [currency, setCurrency] = useState<Currency>('GOLD');
const [poolId, setPoolId] = useState('');
const [quantity, setQuantity] = useState('1');
const [level, setLevel] = useState('');
const [note, setNote] = useState('');
const [recipients, setRecipients] = useState<Record<string, string>>({});
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 (
<div className="card">
<div className="card-title">Rewards</div>
{isDM && rewards.length === 0 && (
<p className="combatant-sub" style={{ marginTop: 0 }}>
Line up coins, weapons and items here. Players only see a reward once you award it.
</p>
)}
{rewards.map((r) => (
<div key={r.id} className={`reward-row${r.awardedAt ? ' is-awarded' : ''}`}>
<div className="flex-between">
<strong>
{r.type === 'GOLD' ? '🪙' : r.type === 'WEAPON' ? '🗡' : '🎒'} {rewardLabel(r)}
</strong>
{isDM && (
<button className="btn btn-ghost" aria-label={`Remove reward ${rewardLabel(r)}`} onClick={() => deleteReward.mutate(r.id, { onError })}>
✕
</button>
)}
</div>
{r.note && <div className="combatant-sub">{r.note}</div>}
{r.awardedAt ? (
<div className="combatant-sub">✓ Awarded to {r.awardedTo}</div>
) : (
isDM && (
<div className="flex-row flex-wrap gap-sm mt-sm">
<select
aria-label={`Who receives ${rewardLabel(r)}`}
value={recipients[r.id] ?? ''}
onChange={(e) => setRecipients({ ...recipients, [r.id]: e.target.value })}
style={{ flex: 1, minWidth: 110 }}
>
<option value="">Award to…</option>
{characters.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<button
className="btn"
disabled={!recipients[r.id] || awardReward.isPending}
onClick={() => awardReward.mutate({ rewardId: r.id, characterId: recipients[r.id] }, { onError })}
>
Award
</button>
{r.type === 'GOLD' && (
<button
className="btn"
disabled={partySize === 0 || awardReward.isPending}
title="Share evenly between the characters in this encounter"
onClick={() => awardReward.mutate({ rewardId: r.id, split: true }, { onError })}
>
Split
</button>
)}
</div>
)
)}
</div>
))}
{isDM && (
<div className="mt-md">
<div className="section-label">Add a reward</div>
<div className="flex-row flex-wrap gap-sm">
<select
aria-label="Reward type"
value={type}
onChange={(e) => {
setType(e.target.value as NewReward['type']);
setPoolId('');
setLevel('');
}}
>
<option value="GOLD">Coins</option>
<option value="WEAPON">Weapon</option>
<option value="ITEM">Item</option>
</select>
{type === 'GOLD' ? (
<>
<NumberInput
min={1}
max={1000000}
placeholder="Amount"
aria-label="Coin amount"
value={gold}
onChange={(e) => setGold(e.target.value)}
style={{ flex: 1, minWidth: 90 }}
/>
<select aria-label="Coin" value={currency} onChange={(e) => setCurrency(e.target.value as Currency)}>
{CURRENCIES.map((c) => (
<option key={c} value={c}>
{COIN_LABELS[c]}
</option>
))}
</select>
</>
) : (
<>
<select
aria-label={type === 'WEAPON' ? 'Weapon' : 'Item'}
value={poolId}
onChange={(e) => {
setPoolId(e.target.value);
setLevel('');
}}
style={{ flex: 1, minWidth: 110 }}
>
<option value="">{pool.length ? 'Choose…' : 'The pool is empty'}</option>
{pool.map((entry) => (
<option key={entry.id} value={entry.id}>
{entry.name}
</option>
))}
</select>
{picked && (
<>
<select aria-label="Level" value={level || picked.minLevel} onChange={(e) => setLevel(e.target.value)}>
{Array.from({ length: MAX_GEAR_LEVEL - picked.minLevel + 1 }, (_, i) => picked.minLevel + i).map((l) => (
<option key={l} value={l}>
Lv {l}
{picked.damageDice ? ` · ${scaledDamageDice(picked.damageDice, l, picked.damageScaling, picked.minLevel)}` : ''}
</option>
))}
</select>
<NumberInput
min={1}
max={999}
aria-label="Quantity"
title="Quantity"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
style={{ width: 64 }}
/>
</>
)}
</>
)}
</div>
<div className="flex-row gap-sm mt-sm">
<input
placeholder="Note (optional)"
aria-label="Reward note"
maxLength={200}
value={note}
onChange={(e) => setNote(e.target.value)}
style={{ flex: 1, minWidth: 0 }}
/>
<button className="btn btn-primary" onClick={handleAdd} disabled={addReward.isPending || (type === 'GOLD' ? !gold : !picked)}>
Add
</button>
</div>
</div>
)}
</div>
);
}
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<string[]>([]);
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<string | null>(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<string | null>(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 <Spinner label="Setting the scene…" />;
if (error || !encounter) return <ErrorBanner message="Could not load this encounter." />;
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) => (
<CombatantCard
key={p.id}
participant={p}
isDM={isDM}
isMine={p.character != null && p.character.userId === user?.id}
isActive={p.id === active?.id}
onPatch={(data) => (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 (
<div>
<div className="page-header">
<div>
<h1>
{isBattle ? '⚔' : isRoam ? '🧭' : '📜'} {encounter.name}
</h1>
<div className="flex-row flex-wrap">
<span className="badge badge-dm">{MODE_LABELS[encounter.mode]}</span>
<span className={`badge ${encounter.status === 'ACTIVE' ? 'badge-live' : ''}`}>{STATUS_LABELS[encounter.status]}</span>
{isBattle && <span className="badge">Round {encounter.currentRound}</span>}
{encounter.difficulty?.rating && (
<span
className={`badge ${RATING_BADGES[encounter.difficulty.rating]}`}
title={`How hard this is for the characters in it: its monsters count as ${encounter.difficulty.adjustedXp.toLocaleString()} XP. Only you see this.`}
>
{RATING_LABELS[encounter.difficulty.rating]} · {encounter.difficulty.xp.toLocaleString()} XP
</span>
)}
{encounter.location && <span className="badge">📍 {encounter.location.name}</span>}
{encounter.archivedAt && <span className="badge">Archived</span>}
{active && <span className="turn-marker">▶ {active.displayName}'s turn</span>}
</div>
</div>
<div className="flex-row flex-wrap">
<Link to={`/campaigns/${encounter.campaignId}`} className="btn btn-ghost">
← Campaign
</Link>
{isDM && (
<>
<select
aria-label="Encounter type"
value={encounter.mode}
onChange={(e) => patchEncounter.mutate({ mode: e.target.value as EncounterMode }, fail)}
>
<option value="BATTLE">Battle</option>
<option value="QUEST">NPC quest</option>
<option value="FREE_ROAM">Free roam</option>
</select>
<select
aria-label="Location"
title="Where this scene takes place. Its characters move here when it begins."
value={encounter.locationId ?? ''}
onChange={(e) => patchEncounter.mutate({ locationId: e.target.value || null }, fail)}
>
<option value="">No location</option>
{locations?.map((loc) => (
<option key={loc.id} value={loc.id}>
📍 {loc.name}
</option>
))}
</select>
{checkers.length > 0 && (
<button className="btn" title="Call for a check or a save from the characters here, and roll it for all of them at once" onClick={() => setChecking(true)}>
🎲 Call for a roll…
</button>
)}
{encounter.status === 'PLANNING' && (
<button className="btn btn-primary" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' }, fail)}>
{isBattle ? 'Begin Battle' : isRoam ? 'Begin Roaming' : 'Begin Quest'}
</button>
)}
{encounter.status === 'ACTIVE' && isBattle && (
<>
<button
className="btn btn-primary"
title="Pass the turn to the next combatant still standing. Shortcut: N (S opens the sheet of whoever is on turn)"
onClick={() => nextTurn.mutate(undefined, turnPassed)}
disabled={nextTurn.isPending}
>
Next Turn ▶
</button>
<button className="btn" onClick={() => advanceRound.mutate(undefined, turnPassed)} title="Skip straight to the top of the next round">
Next Round
</button>
</>
)}
{encounter.status === 'ACTIVE' && (
<button className="btn btn-danger" onClick={() => patchEncounter.mutate({ status: 'COMPLETE' }, fail)}>
{isBattle ? 'End Battle' : isRoam ? 'End Free Roam' : 'Complete Quest'}
</button>
)}
{encounter.status === 'COMPLETE' && (
<button className="btn" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' }, fail)}>
Reopen
</button>
)}
<button
className="btn btn-ghost"
title={encounter.archivedAt ? 'Put it back on the campaign list' : 'Take it off the campaign list without deleting it'}
disabled={setArchived.isPending}
onClick={() => setArchived.mutate({ encounterId, archived: !encounter.archivedAt }, fail)}
>
{encounter.archivedAt ? 'Restore' : 'Archive'}
</button>
<button
className="btn btn-ghost"
disabled={deleteEncounter.isPending}
onClick={() =>
window.confirm(`Delete "${encounter.name}" for good? Rewards already handed out stay with the characters.`) &&
deleteEncounter.mutate(encounterId, { ...fail, onSuccess: () => navigate(`/campaigns/${encounter.campaignId}`) })
}
>
Delete
</button>
</>
)}
</div>
</div>
{isDM && checking && <GroupCheckModal characters={checkers} onClose={() => setChecking(false)} />}
{formError && <ErrorBanner message={formError} />}
{isDM && notices.length > 0 && (
<div className="card notice-card" role="status">
<div className="flex-between">
<div>
{notices.map((line, i) => (
<p key={`${i}:${line}`} style={{ margin: 0 }}>
{line}
</p>
))}
</div>
<button className="btn btn-ghost" aria-label="Dismiss" onClick={() => setNotices([])}>
✕
</button>
</div>
</div>
)}
{active ? (
<InitiativeTrack
participants={standing}
activeId={active.id}
round={encounter.currentRound}
targetIds={targetIds}
userId={user?.id}
canTarget={canTarget}
onTarget={toggleTarget}
onJump={jumpToCard}
/>
) : (
standing.length > 1 && <TurnStrip participants={standing} activeId={undefined} targetIds={targetIds} userId={user?.id} hasActed={hasActed} />
)}
{cue && (
<div className={`card cue-card${cue.urgent ? ' is-urgent' : ''}`} role="status">
<span className="cue-label">{isDM ? 'What now' : 'Your move'}</span>
<span>{cue.text}</span>
{isDM && running && <span className="combatant-sub cue-keys">Keys: 1–9 target · A accept · N next turn · S sheet</span>}
</div>
)}
{(isDM || encounter.description) && (
<div className="card">
<div className="card-title">{isBattle ? 'The Scene' : isRoam ? 'Where the party is' : 'Quest'}</div>
{isDM ? (
<textarea
key={`description:${encounter.description ?? ''}`}
rows={3}
className="textarea-block"
defaultValue={encounter.description ?? ''}
aria-label="Scene description, shown to players"
placeholder={
isBattle
? 'Describe the battlefield: terrain, cover, hazards… (shown to players)'
: isRoam
? 'Where the party finds itself, and what is around to visit… (shown to players)'
: 'What is being asked of the party, and by whom? (shown to players)'
}
onBlur={(e) => {
const description = e.target.value.trim() || null;
if (description !== encounter.description) patchEncounter.mutate({ description }, fail);
}}
/>
) : (
<p style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{encounter.description}</p>
)}
</div>
)}
{isRoam && (
<FreeRoamPanel
encounter={encounter}
isDM={isDM}
userId={user?.id}
characters={builtCharacters}
locations={locations ?? []}
weapons={weapons ?? []}
items={items ?? []}
onError={onError}
/>
)}
<div className="encounter-layout mt-md">
<div>
{actions.map((action) => (
<ActionCard
key={action.id}
action={action}
participants={participants}
isDM={isDM}
userId={user?.id}
diceMode={diceMode}
encounterId={encounterId}
onNotice={notify}
onError={onError}
/>
))}
{encounter.status === 'ACTIVE' && isBattle && (isDM || myTurn) && (active || isDM) && (
<ActionComposer actor={active} targetCount={targets.length} isDM={isDM} encounterId={encounterId} onError={onError} />
)}
{isDM && targets.length > 0 && (
<AttackBar
attacker={active}
targets={targets}
acStep={acStep}
onApply={changeHp}
onRemove={(id) => setTargets.mutate(targetIds.filter((x) => x !== id), fail)}
onClear={() => setTargets.mutate([], fail)}
/>
)}
{!isDM && fallen.length > 0 && (
<div className="card fallen-bar">
<div className="card-title">☠ Fallen</div>
{fallen.map((f) => (
<div key={f.participantId} className="flex-between flex-wrap">
<span className="combatant-name">{f.name}</span>
{canTryRevive && (
<button
className="btn"
title={`${active?.displayName} tries to bring ${f.name} back, at 1 HP.`}
disabled={revive.isPending}
onClick={() => {
setFormError(null);
revive.mutate(f.participantId, fail);
}}
>
Try revive
</button>
)}
</div>
))}
<p className="combatant-sub" style={{ margin: '0.4rem 0 0' }}>
{canTryRevive
? `${active?.displayName} has a spell that can bring back the dead.`
: 'A character with a spell that brings back the dead can try to revive them on their own turn.'}
</p>
</div>
)}
{isDM && outOfTheFight.length > 0 && (
<label className="checkbox-row mt-md" title="Dead characters, and monsters and NPCs at 0 HP. Players never see them.">
<input type="checkbox" checked={showDead} onChange={(e) => setShowDead(e.target.checked)} />
Show dead ({outOfTheFight.length})
</label>
)}
{participants.length === 0 && fallen.length === 0 && (
<div className="empty-state card">
{isDM
? 'Nobody here yet. Add characters, monsters or NPCs from the panel alongside.'
: 'The DM is still setting the scene.'}
</div>
)}
{groups
.filter(([, members]) => members.length > 0)
.map(([label, members]) => (
<div key={label} className="mt-md">
<div className="section-label">
{label} · {members.length}
</div>
{members.map(card)}
</div>
))}
</div>
<div className="encounter-side">
{spotlit && hasStats(spotlit) && (
<Spotlight
participant={spotlit}
isPinned={spotlit === pinned}
isOnTurn={spotlit.id === active?.id}
isDM={isDM}
canOpenSheet={isDM || (spotlit.character != null && spotlit.character.userId === user?.id)}
onUnpin={() => setPinnedId(null)}
onError={onError}
/>
)}
{isDM && (
<div className="card">
<div className="card-title">Add to the scene</div>
<div className="flex-row flex-wrap gap-sm">
<select
aria-label="What to add"
value={pickType}
onChange={(e) => {
setPickType(e.target.value as typeof pickType);
setPickId('');
}}
>
<option value="character">Character</option>
<option value="monster">Monster</option>
<option value="npc">NPC</option>
</select>
<select aria-label="Who to add" value={pickId} onChange={(e) => setPickId(e.target.value)} style={{ flex: 1, minWidth: 110 }}>
<option value="">{pickOptions.length ? 'Choose…' : 'None left to add'}</option>
{pickOptions.map((entity) => (
<option key={entity.id} value={entity.id}>
{entity.name}
</option>
))}
</select>
</div>
<div className="flex-row gap-sm mt-sm">
<NumberInput
min={1}
max={20}
placeholder="Initiative roll (d20)"
title="What the d20 showed, 1 to 20. Leave empty to roll later; the bonus is added for you."
aria-label="Initiative roll"
value={initiative}
onChange={(e) => setInitiative(e.target.value)}
style={{ flex: 1, minWidth: 0 }}
/>
{pickType === 'monster' && (
<NumberInput
min={1}
max={20}
title="How many to add. Several at once are numbered: Goblin 1, Goblin 2…"
aria-label="How many to add"
value={count}
onChange={(e) => setCount(e.target.value)}
style={{ width: 56 }}
/>
)}
<button className="btn btn-primary" onClick={handleAdd} disabled={!pickId || addParticipant.isPending}>
Add
</button>
</div>
{unrolled > 0 && (
<button
className="btn btn-block mt-sm"
title="Roll a d20 for every monster and NPC that has no initiative roll yet. Players roll for their own characters."
disabled={rollInitiative.isPending}
onClick={() => rollInitiative.mutate(undefined, fail)}
>
🎲 Roll initiative for {unrolled} monster{unrolled === 1 ? '' : 's'} and NPCs
</button>
)}
{pickType !== 'character' && pickOptions.length === 0 && (
<p className="combatant-sub">
Create {pickType === 'npc' ? 'NPCs' : 'monsters'} on the <Link to={`/campaigns/${encounter.campaignId}`}>campaign page</Link> first.
</p>
)}
</div>
)}
{isBattle && (encounter.recentActions ?? []).length > 0 && (
<details className="card" open>
<summary className="card-title" style={{ cursor: 'pointer', marginBottom: 0 }}>
⚔ What just happened
</summary>
<div className="mt-sm">
<RecentActions actions={encounter.recentActions ?? []} />
</div>
</details>
)}
{isDM && (
<details className="card" open={(rolls ?? []).length > 0}>
<summary className="card-title" style={{ cursor: 'pointer', marginBottom: 0 }}>
🎲 Rolls at the table
</summary>
<div className="mt-sm">
<RollFeed rolls={(rolls ?? []).slice(0, 8)} userId={user?.id} empty="Nobody has rolled yet. Every roll made in the dice roller shows here." />
</div>
</details>
)}
<TradePanel
encounter={encounter}
isDM={isDM}
userId={user?.id}
characters={builtCharacters}
weapons={weapons ?? []}
items={items ?? []}
onError={onError}
/>
{isDM && encounter.difficulty && campaignData?.campaign.trackXp && (
<ExperiencePanel
encounterId={encounterId}
difficulty={encounter.difficulty}
xpAwarded={encounter.xpAwarded ?? null}
partySize={participants.filter((p) => p.kind === 'CHARACTER' && p.character).length}
onError={onError}
/>
)}
<RewardsPanel
encounter={encounter}
isDM={isDM}
characters={builtCharacters}
weapons={weapons ?? []}
items={items ?? []}
onError={onError}
/>
{isDM && (
<div className="card">
<div className="card-title">DM Notes</div>
<textarea
key={`dmNotes:${encounter.dmNotes ?? ''}`}
rows={5}
className="textarea-block"
defaultValue={encounter.dmNotes ?? ''}
aria-label="DM notes, never shown to players"
placeholder="Tactics, secrets, what happens if they fail… (only you see this)"
onBlur={(e) => {
const dmNotes = e.target.value.trim() || null;
if (dmNotes !== (encounter.dmNotes ?? null)) patchEncounter.mutate({ dmNotes }, fail);
}}
/>
</div>
)}
</div>
</div>
</div>
);
}