V1.1.0: gear levels, encounter overhaul, guided builder, trading, docs

Characters
- Builder: pick-then-Next on every step with live preview, Back button,
  plain-language help throughout, and "Suggest for me" for ability scores
- Motivation is picked from a list; new steps for special abilities,
  background and appearance, all composed from fixed lists and DM-only
  to edit afterwards
- Copy a character to another campaign
- Characters can give gold, weapons, items and spells to each other
- Money tracker: gold only changes through a logged ledger
- Fixes: level/XP/location are DM-only, HP stays within 0..max, physical
  dice ability rolls, every die is rolled once

Gear
- DM-managed item pool; weapons, items and spells are handed out by the DM
- Starting-option flag per pool entry
- Gear levels 1-9 per held copy with a damage ladder, growth rate and
  starting level; spells gated by spell level with a fixed damage value
- Spell library carries default damage; damage is picked from a list

Encounters
- Battle and NPC quest modes, turn tracking, scene description, DM notes
- NPCs, richer combatant cards, conditions from a list
- Rewards (gold, weapons, items) lined up and awarded, with gold splitting
- Character HP is shared between the sheet and the encounter
- Monster stat blocks and NPC secrets are never sent to players

Other
- Dice roller on every page
- Docs for characters, weapons, spells, items, encounters, monsters and
  NPCs, with full lists generated from the data (npm run docs:lists)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-05 16:47:28 +02:00
co-authored by Claude Opus 5.5
parent 94067f1268
commit 4a6a09bae8
44 changed files with 9405 additions and 700 deletions
+715 -158
View File
@@ -1,150 +1,572 @@
import { useState } from 'react';
import { useState, type ReactNode } from 'react';
import { Link, useParams } from 'react-router-dom';
import {
useEncounter,
useCampaign,
useCampaignCharacters,
useCampaignMonsters,
useCampaignNpcs,
useCampaignWeapons,
useCampaignItems,
useAddParticipant,
usePatchParticipant,
useRemoveParticipant,
useAdvanceRound,
useNextTurn,
usePatchEncounter,
useAddReward,
useDeleteReward,
useAwardReward,
type NewReward,
} from '../api/queries';
import { useCampaignSocket } from '../hooks/useCampaignSocket';
import { Spinner, ErrorBanner } from '../components/Spinner';
import { extractErrorMessage, fmtMod, hpBarClass } from '../lib/format';
import type { EncounterParticipant } from '../api/types';
import { ABILITY_LABELS, CLASS_LABELS, SPECIES_LABELS, extractErrorMessage, fmtMod, hpBarClass, spellLevelLabel } from '../lib/format';
import { abilityModifier, scaledDamageDice, MAX_GEAR_LEVEL } from '../lib/previewCalc';
import type {
Ability,
CharacterSummary,
Encounter,
EncounterMode,
EncounterParticipant,
EncounterReward,
Item,
Weapon,
} from '../api/types';
function ParticipantRow({
participant,
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',
];
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,
mode,
isActive,
onPatch,
onRemove,
}: {
participant: EncounterParticipant;
isDM: boolean;
mode: EncounterMode;
isActive: boolean;
onPatch: (data: Partial<EncounterParticipant>) => void;
onRemove: () => void;
}) {
const [hpDelta, setHpDelta] = useState('');
const [showCombatInfo, setShowCombatInfo] = useState(false);
const pct = Math.max(0, Math.min(100, (participant.currentHp / participant.maxHp) * 100));
const combatInfo = participant.characterCombatInfo;
// 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;
const tracksHp = p.maxHp > 0;
const isDown = tracksHp && p.currentHp <= 0;
const pct = tracksHp ? Math.max(0, Math.min(100, (p.currentHp / p.maxHp) * 100)) : 0;
// 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: participant.currentHp + sign * amount });
onPatch({ currentHp: p.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">
<div className={`card combatant combatant-${p.kind.toLowerCase()}${isActive ? ' is-active' : ''}${isDown ? ' is-down' : ''}`}>
<div className="flex-between flex-wrap">
<div className="flex-row">
<span className={`badge ${participant.isMonster ? 'badge-dm' : 'badge-player'}`}>
{participant.isMonster ? 'Monster' : 'PC'}
</span>
<strong>{participant.displayName}</strong>
</div>
{isDM && (
<label className="flex-row gap-sm">
Init
<input
type="number"
defaultValue={participant.initiative}
style={{ width: 60 }}
onBlur={(e) => onPatch({ initiative: Number(e.target.value) })}
/>
</label>
)}
</div>
<div className="hp-bar-track mt-sm">
<div className={hpBarClass(participant.currentHp, participant.maxHp)} style={{ width: `${pct}%` }} />
</div>
<div className="flex-between mt-sm flex-wrap">
<span>
HP {participant.currentHp}/{participant.maxHp}
</span>
{isDM && (
<div className="flex-row gap-sm">
<input type="number" placeholder="Amt" value={hpDelta} onChange={(e) => setHpDelta(e.target.value)} style={{ width: 70 }} />
<button className="btn btn-danger" onClick={() => applyDelta(-1)}>
−
</button>
<button className="btn" onClick={() => applyDelta(1)}>
+
</button>
<div>
{isActive && <div className="turn-marker">▶ On turn</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 && <span className="badge badge-hostile">Down</span>}
</div>
)}
</div>
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<input
placeholder="Conditions, comma separated"
defaultValue={participant.conditions.join(', ')}
style={{ flex: 1, minWidth: 160 }}
onBlur={(e) =>
onPatch({
conditions: e.target.value
.split(',')
.map((c) => c.trim())
.filter(Boolean),
})
}
/>
<button className="btn btn-ghost" onClick={onRemove}>
Remove
</button>
<div className="combatant-sub">{subline(p)}</div>
</div>
{mode === 'BATTLE' &&
(isDM ? (
<label className="flex-row gap-sm">
Initiative
<input
key={`${p.id}:${p.initiative}`}
type="number"
defaultValue={p.initiative}
style={{ width: 64 }}
onBlur={(e) => Number(e.target.value) !== p.initiative && onPatch({ initiative: Number(e.target.value) })}
/>
</label>
) : (
<StatChip label="Initiative">{p.initiative}</StatChip>
))}
</div>
<div className="stat-chips mt-sm">
{tracksHp && (
<StatChip label="HP">
{p.currentHp}/{p.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 && (
<>
<div className="hp-bar-track mt-sm">
<div className={hpBarClass(p.currentHp, p.maxHp)} style={{ width: `${pct}%` }} />
</div>
{isDM && (
<div className="flex-row gap-sm mt-sm">
<input
type="number"
min={1}
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>
)}
</>
)}
{!isDM && participant.conditions.length > 0 && (
<div className="flex-row flex-wrap mt-sm">
{participant.conditions.map((c) => (
<span key={c} className="badge">
{(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>
)}
{combatInfo && (
<div className="mt-sm">
<button className="btn btn-ghost" onClick={() => setShowCombatInfo((s) => !s)}>
{showCombatInfo ? 'Hide' : '⚔ Show'} Weapons & Spells
</button>
{showCombatInfo && (
<div className="mt-sm">
{combatInfo.weapons.length === 0 && combatInfo.spells.length === 0 && (
<p style={{ color: 'var(--text-muted)', margin: 0 }}>Nothing equipped or prepared.</p>
)}
{combatInfo.weapons.map((w) => (
<div key={w.characterWeaponId} className="flex-between" style={{ padding: '0.2rem 0' }}>
{(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 style={{ color: 'var(--text-muted)', marginLeft: 6, fontSize: '0.85rem' }}>
{w.damageDice} {w.damageType} {fmtMod(w.damageBonus)}
<span className="combatant-sub" style={{ marginLeft: 6 }}>
Lv {w.level} · {w.damageDice} {fmtMod(w.damageBonus)} {w.damageType}
</span>
</span>
<span className="mono">{fmtMod(w.attackBonus)}</span>
<span className="mono" title="Attack bonus">
{fmtMod(w.attackBonus)} to hit
</span>
</div>
))}
{combatInfo.spells.length > 0 && (
<div className="flex-row flex-wrap mt-sm">
{combatInfo.spells.map((s) => (
<span key={s.characterSpellId} className={`badge ${s.prepared ? 'badge-dm' : ''}`}>
{s.name} (Lv {s.level})
{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>
)}
{combatInfo.spellcasting && (
<p style={{ margin: '0.4rem 0 0', fontSize: '0.85rem', color: 'var(--text-muted)' }}>
Spell Save DC {combatInfo.spellcasting.saveDC} · Attack {fmtMod(combatInfo.spellcasting.attackBonus)}
{info.spellcasting && (
<p className="combatant-sub">
Spellcasting ({ABILITY_LABELS[info.spellcasting.ability]}): save DC {info.spellcasting.saveDC} ·{' '}
{fmtMod(info.spellcasting.attackBonus)} to hit
</p>
)}
</div>
{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>
);
}
function rewardLabel(r: EncounterReward): string {
if (r.type === 'GOLD') return `${r.gold} gold`;
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 [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, ...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 gold, 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">Gold</option>
<option value="WEAPON">Weapon</option>
<option value="ITEM">Item</option>
</select>
{type === 'GOLD' ? (
<input
type="number"
min={1}
placeholder="Amount"
aria-label="Gold amount"
value={gold}
onChange={(e) => setGold(e.target.value)}
style={{ flex: 1, minWidth: 90 }}
/>
) : (
<>
<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>
<input
type="number"
min={1}
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>
@@ -157,72 +579,125 @@ export function EncounterPage() {
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);
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 addParticipant = useAddParticipant(encounterId);
const patchParticipant = usePatchParticipant(encounterId);
const removeParticipant = useRemoveParticipant(encounterId);
const advanceRound = useAdvanceRound(encounterId);
const nextTurn = useNextTurn(encounterId);
const patchEncounter = usePatchEncounter(encounterId);
const [pickType, setPickType] = useState<'character' | 'monster'>('character');
const [pickType, setPickType] = useState<'character' | 'monster' | 'npc'>('character');
const [pickId, setPickId] = useState('');
const [initiative, setInitiative] = useState('0');
const [initiative, setInitiative] = useState('');
const [formError, setFormError] = useState<string | null>(null);
if (isLoading) return <Spinner label="Setting the battlefield…" />;
if (isLoading) return <Spinner label="Setting the scene…" />;
if (error || !encounter) return <ErrorBanner message="Could not load this encounter." />;
const isDM = campaignData?.campaign.role === 'DM';
const sorted = [...(encounter.participants || [])].sort((a, b) => b.initiative - a.initiative);
const availableCharacters = characters?.filter((c) => !encounter.participants?.some((p) => p.characterId === c.id) && c.buildStage === 'COMPLETE');
const availableMonsters = monsters;
const isBattle = encounter.mode === 'BATTLE';
const participants = encounter.participants ?? []; // already in initiative order
const active = isBattle && encounter.status === 'ACTIVE' ? participants.find((p) => p.id === encounter.activeParticipantId) : undefined;
const builtCharacters = characters?.filter((c) => c.buildStage === 'COMPLETE') ?? [];
const onError = (err: unknown) => setFormError(extractErrorMessage(err));
const fail = { onError };
async function handleAdd() {
const pickOptions: { id: string; name: string }[] =
pickType === 'character'
? builtCharacters.filter((c) => !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);
try {
await addParticipant.mutateAsync({
[pickType === 'character' ? 'characterId' : 'monsterId']: pickId,
initiative: Number(initiative) || 0,
});
setPickId('');
} catch (err) {
setFormError(extractErrorMessage(err));
}
addParticipant.mutate(
{ [`${pickType}Id`]: pickId, initiative: Number(initiative) || 0 },
{ onError, onSuccess: () => setPickId('') }
);
}
const card = (p: EncounterParticipant) => (
<CombatantCard
key={p.id}
participant={p}
isDM={isDM}
mode={encounter.mode}
isActive={p.id === active?.id}
onPatch={(data) => patchParticipant.mutate({ participantId: p.id, ...data }, fail)}
onRemove={() => removeParticipant.mutate(p.id, fail)}
/>
);
// A quest scene is grouped by who is there rather than by initiative.
const groups: [string, EncounterParticipant[]][] = isBattle
? [['Initiative order', participants]]
: [
['People you meet', participants.filter((p) => p.kind === 'NPC')],
['The party', participants.filter((p) => p.kind === 'CHARACTER')],
['Creatures', participants.filter((p) => p.kind === 'MONSTER')],
];
return (
<div>
<div className="page-header">
<div>
<h1>⚔ {encounter.name}</h1>
<p className="subtitle">
{encounter.status} · Round {encounter.currentRound}
</p>
<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>}
{active && <span className="turn-marker">▶ {active.displayName}'s turn</span>}
</div>
</div>
<div className="flex-row">
<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>
{encounter.status === 'PLANNING' && (
<button className="btn btn-primary" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' })}>
Begin Combat
<button className="btn btn-primary" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' }, fail)}>
{isBattle ? 'Begin Battle' : 'Begin Quest'}
</button>
)}
{encounter.status === 'ACTIVE' && (
{encounter.status === 'ACTIVE' && isBattle && (
<>
<button className="btn btn-primary" onClick={() => advanceRound.mutate()}>
Advance Round
<button className="btn btn-primary" onClick={() => nextTurn.mutate(undefined, fail)} disabled={nextTurn.isPending}>
Next Turn ▶
</button>
<button className="btn btn-danger" onClick={() => patchEncounter.mutate({ status: 'COMPLETE' })}>
End Encounter
<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>
)}
</>
)}
</div>
@@ -230,47 +705,129 @@ export function EncounterPage() {
{formError && <ErrorBanner message={formError} />}
{isDM && (
<div className="card mt-md">
<div className="card-title">Add Combatant</div>
<div className="flex-row flex-wrap">
<select value={pickType} onChange={(e) => setPickType(e.target.value as 'character' | 'monster')}>
<option value="character">Character</option>
<option value="monster">Monster</option>
</select>
<select value={pickId} onChange={(e) => setPickId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Select…</option>
{(pickType === 'character' ? availableCharacters : availableMonsters)?.map((entity) => (
<option key={entity.id} value={entity.id}>
{entity.name}
</option>
))}
</select>
<input
type="number"
placeholder="Initiative"
value={initiative}
onChange={(e) => setInitiative(e.target.value)}
style={{ width: 100 }}
{(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);
}}
/>
<button className="btn btn-primary" onClick={handleAdd} disabled={!pickId}>
Add
</button>
</div>
) : (
<p style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{encounter.description}</p>
)}
</div>
)}
<div className="mt-lg">
{sorted.length === 0 && <div className="empty-state">No combatants yet.</div>}
{sorted.map((p) => (
<ParticipantRow
key={p.id}
participant={p}
isDM={Boolean(isDM)}
onPatch={(data) => patchParticipant.mutate({ participantId: p.id, ...data })}
onRemove={() => removeParticipant.mutate(p.id)}
<div className="encounter-layout mt-md">
<div>
{participants.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">
{isBattle && (
<input
type="number"
placeholder="Initiative"
aria-label="Initiative"
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>
);