Files
the-sunken-reach/frontend/src/pages/EncounterPage.tsx
T
joshuaandClaude Opus 5.5 f764878960 V1.8.1: combatants who have had their turn move to "Next Round"
- In a battle in progress, whoever is on turn is at the top of the list
  with those still to act beneath them. Each combatant whose turn has
  passed drops to a "Next Round" section at the bottom, and a new round
  puts everyone back.
- All packages at version 1.8.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 14:49:44 +02:00

1215 lines
49 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, type ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import {
useEncounter,
useCampaign,
useCampaignCharacters,
useCampaignMonsters,
useCampaignNpcs,
useCampaignWeapons,
useCampaignItems,
useCampaignLocations,
useAddParticipant,
usePatchParticipant,
useRemoveParticipant,
useAdvanceRound,
useNextTurn,
useSetTargets,
useReviveParticipant,
usePatchEncounter,
useSetEncounterArchived,
useDeleteEncounter,
useAddReward,
useDeleteReward,
useAwardReward,
type NewReward,
} from '../api/queries';
import { useCampaignSocket } from '../hooks/useCampaignSocket';
import { useAuth } from '../auth/AuthContext';
import { Spinner, ErrorBanner } from '../components/Spinner';
import { NumberInput } from '../components/NumberInput';
import { HpBar } from '../components/HpBar';
import { DeathSaves } from '../components/DeathSaves';
import { ABILITY_LABELS, CLASS_LABELS, COIN_LABELS, CURRENCIES, SPECIES_LABELS, extractErrorMessage, fmtMod, spellLevelLabel } from '../lib/format';
import { abilityModifier, scaledDamageDice, MAX_GEAR_LEVEL } from '../lib/previewCalc';
import type {
Ability,
CharacterSummary,
Currency,
Encounter,
EncounterMode,
EncounterParticipant,
EncounterReward,
Item,
Weapon,
} from '../api/types';
const ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
const CONDITIONS = [
'Blinded',
'Charmed',
'Deafened',
'Frightened',
'Grappled',
'Incapacitated',
'Invisible',
'Paralyzed',
'Petrified',
'Poisoned',
'Prone',
'Restrained',
'Stunned',
'Unconscious',
'Concentrating',
];
// 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' };
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],
info.characterClass && CLASS_LABELS[info.characterClass],
]
.filter(Boolean)
.join(' ');
}
if (p.kind === 'NPC') return p.npc?.role || 'Non-player character';
if (p.monster?.challengeRating) return `Challenge ${p.monster.challengeRating}`;
return '';
}
function CombatantCard({
participant: p,
isDM,
isActive,
onPatch,
canRollInitiative,
targetedBy,
acPenalty,
onTarget,
onRemove,
onError,
}: {
participant: EncounterParticipant;
isDM: 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;
onRemove: () => void;
onError: (err: unknown) => void;
}) {
const [hpDelta, setHpDelta] = 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 = 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;
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;
onPatch({ conditions: [...p.conditions, name] });
}
return (
<div className={`card combatant combatant-${p.kind.toLowerCase()}${isActive ? ' is-active' : ''}${isDown && !isDying ? ' is-down' : ''}${isTargeted ? ' is-targeted' : ''}`}>
<div className="flex-between flex-wrap">
<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>}
{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>
<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>
<StatChip label="Init">{fmtMod(info.initiativeBonus)}</StatChip>
<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>
<StatChip label="Attack">{fmtMod(monsterStats.attackBonus ?? 0)}</StatChip>
{monsterStats.damageDice && <StatChip label="Damage">{monsterStats.damageDice}</StatChip>}
</>
)}
{npc && npc.ac != null && <StatChip label="AC">{npc.ac}</StatChip>}
{npc && npc.attackBonus != null && <StatChip label="Attack">{fmtMod(npc.attackBonus)}</StatChip>}
{npc && npc.damageDice && <StatChip label="Damage">{npc.damageDice}</StatChip>}
</div>
{/* 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) && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{p.conditions.map((c) => (
<span key={c} className="condition-chip">
{c}
{isDM && (
<button aria-label={`Remove ${c}`} onClick={() => onPatch({ conditions: p.conditions.filter((x) => x !== c) })}>
✕
</button>
)}
</span>
))}
{isDM && (
<select
aria-label={`Add a condition to ${p.displayName}`}
value=""
onChange={(e) => addCondition(e.target.value)}
style={{ width: 'auto' }}
>
<option value="">+ Condition</option>
{CONDITIONS.filter((c) => !p.conditions.includes(c)).map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
)}
</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">
{info && (
<>
<div className="stat-chips">
{ABILITIES.map((a) => (
<StatChip key={a} label={a}>
{info.abilities[a].final} ({fmtMod(info.abilities[a].modifier)})
</StatChip>
))}
</div>
<p className="combatant-sub">
Saves:{' '}
{ABILITIES.map((a) => `${a} ${fmtMod(info.saves[a].bonus)}${info.saves[a].proficient ? '*' : ''}`).join(' · ')}{' '}
<span title="Proficient">(* proficient)</span>
</p>
{info.weapons.length === 0 && info.spells.length === 0 && <p className="combatant-sub">No usable weapons or spells.</p>}
{info.weapons.map((w) => (
<div key={w.characterWeaponId} className="detail-row">
<span>
{w.name} {w.equipped && <span className="badge">equipped</span>}
<span className="combatant-sub" style={{ marginLeft: 6 }}>
Lv {w.level} · {w.damageDice} {fmtMod(w.damageBonus)} {w.damageType}
</span>
</span>
<span className="mono" title="Attack bonus">
{fmtMod(w.attackBonus)} to hit
</span>
</div>
))}
{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>
)}
{info.spellcasting && (
<p className="combatant-sub">
Spellcasting ({ABILITY_LABELS[info.spellcasting.ability]}): save DC {info.spellcasting.saveDC} ·{' '}
{fmtMod(info.spellcasting.attackBonus)} to hit
</p>
)}
{info.specialAbilities && <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 (
<StatChip key={a} label={a}>
{score} ({fmtMod(abilityModifier(score))})
</StatChip>
);
})}
</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>
)}
</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 equipped = info.weapons.filter((w) => w.equipped);
const weapons = (equipped.length ? equipped : 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>
);
}
function rewardLabel(r: EncounterReward): string {
if (r.type === 'GOLD') return `${r.gold} ${COIN_LABELS[r.currency ?? 'GOLD'].toLowerCase()}`;
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);
const { data: campaignData } = useCampaign(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 nextTurn = useNextTurn(encounterId);
const setTargets = useSetTargets(encounterId);
const revive = useReviveParticipant(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 [formError, setFormError] = useState<string | null>(null);
// The DM's own screen leaves the fallen out too, until asked for.
const [showDead, setShowDead] = useState(false);
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 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 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);
addParticipant.mutate(
{ [`${pickType}Id`]: pickId, initiativeRoll: initiative ? Number(initiative) : undefined },
{ onError, onSuccess: () => setPickId('') }
);
}
const card = (p: EncounterParticipant) => (
<CombatantCard
key={p.id}
participant={p}
isDM={isDM}
isActive={p.id === active?.id}
onPatch={(data) => patchParticipant.mutate({ participantId: p.id, ...data }, fail)}
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
? () => setTargets.mutate(targetIds.includes(p.id) ? targetIds.filter((id) => id !== p.id) : [...targetIds, p.id], fail)
: undefined
}
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]);
return (
<div>
<div className="page-header">
<div>
<h1>
{isBattle ? '⚔' : '📜'} {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.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>
</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>
{encounter.status === 'PLANNING' && (
<button className="btn btn-primary" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' }, fail)}>
{isBattle ? 'Begin Battle' : 'Begin Quest'}
</button>
)}
{encounter.status === 'ACTIVE' && isBattle && (
<>
<button className="btn btn-primary" onClick={() => nextTurn.mutate(undefined, fail)} disabled={nextTurn.isPending}>
Next Turn ▶
</button>
<button className="btn" onClick={() => advanceRound.mutate(undefined, fail)} 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' : '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>
{formError && <ErrorBanner message={formError} />}
{(isDM || encounter.description) && (
<div className="card">
<div className="card-title">{isBattle ? 'The Scene' : '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)'
: '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>
)}
<div className="encounter-layout mt-md">
<div>
{isDM && targets.length > 0 && (
<AttackBar
attacker={active}
targets={targets}
acStep={acStep}
onApply={(changes) => Promise.all(changes.map((change) => patchParticipant.mutateAsync(change))).catch(onError)}
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>
{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 }}
/>
<button className="btn btn-primary" onClick={handleAdd} disabled={!pickId || addParticipant.isPending}>
Add
</button>
</div>
{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>
)}
<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>
);
}