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
+413 -20
View File
@@ -14,6 +14,12 @@ import {
useCreateWeapon,
useCampaignSpells,
useCreateSpell,
useCampaignItems,
useCreateItem,
usePatchPoolEntry,
useDeletePoolEntry,
useCampaignNpcs,
useCreateNpc,
useCampaignNotes,
useCreateNote,
useUpdateCampaign,
@@ -30,9 +36,10 @@ import { useAuth } from '../auth/AuthContext';
import { useCampaignSocket } from '../hooks/useCampaignSocket';
import { Spinner, ErrorBanner } from '../components/Spinner';
import { usePagination, Pagination } from '../components/Paginated';
import { extractErrorMessage } from '../lib/format';
import { SPELL_DAMAGE_GROUPS, SPELL_DAMAGE_SPECIALS, extractErrorMessage, spellLevelLabel, spellRequirementLabel } from '../lib/format';
import { speciesIcon } from '../lib/speciesIcons';
import type { CharacterSummary, LibraryMonster, LibrarySpell, LibraryWeapon } from '../api/types';
import { DAMAGE_SCALING_LABELS, MAX_GEAR_LEVEL } from '../lib/previewCalc';
import type { CharacterSummary, EncounterMode, LibraryMonster, LibrarySpell, LibraryWeapon, NpcDisposition } from '../api/types';
function CharacterRow({ character, isDM, onDelete }: { character: CharacterSummary; isDM: boolean; onDelete: () => void }) {
const inProgress = character.buildStage !== 'COMPLETE';
@@ -71,17 +78,137 @@ function CharacterRow({ character, isDM, onDelete }: { character: CharacterSumma
);
}
// The two trailing cells every pool table row shares: the "offered at
// character creation" toggle and the remove button.
function PoolRowControls({
entry,
onToggleStarting,
onDelete,
}: {
entry: { name: string; isStartingOption: boolean };
onToggleStarting: (isStartingOption: boolean) => void;
onDelete: () => void;
}) {
return (
<>
<td>
<input
type="checkbox"
aria-label={`${entry.name} is a starting option`}
checked={entry.isStartingOption}
onChange={(e) => onToggleStarting(e.target.checked)}
/>
</td>
<td>
<button
className="btn btn-ghost"
aria-label={`Remove ${entry.name}`}
onClick={() => window.confirm(`Remove ${entry.name}? Any character holding it loses it.`) && onDelete()}
>
✕
</button>
</td>
</>
);
}
// How fast a weapon's or item's dice grow as the DM levels a held copy up.
function ScalingSelect({ name, value, onChange }: { name?: string; value?: number; onChange?: (scaling: number) => void }) {
return (
<select
name={name}
aria-label="How fast the dice grow per level"
title="How fast the dice grow each time a held copy is levelled up"
{...(onChange ? { value, onChange: (e) => onChange(Number(e.target.value)) } : { defaultValue: 1 })}
>
{Object.entries(DAMAGE_SCALING_LABELS).map(([scaling, label]) => (
<option key={scaling} value={scaling}>
{label}
</option>
))}
</select>
);
}
const GEAR_LEVELS = Array.from({ length: MAX_GEAR_LEVEL }, (_, i) => i + 1);
// The level a weapon or item starts at. A held copy is never below it, and a
// character must be at least this level to use it.
function StartLevelSelect({ name, value, onChange }: { name?: string; value?: number; onChange?: (minLevel: number) => void }) {
return (
<select
name={name}
aria-label="Level it starts at"
title="The level this starts at — a character must be at least this level to use it"
{...(onChange ? { value, onChange: (e) => onChange(Number(e.target.value)) } : { defaultValue: 1 })}
>
{GEAR_LEVELS.map((level) => (
<option key={level} value={level}>
Starts at Lv {level}
</option>
))}
</select>
);
}
const MODE_LABELS: Record<EncounterMode, string> = { BATTLE: '⚔ Battle', QUEST: '📜 Quest' };
// A spell's damage is picked from a list rather than typed. A value that is
// not in the list (set through the API, say) is still shown and kept.
function SpellDamageSelect({
name,
spellName,
value,
onChange,
}: {
name?: string;
spellName?: string;
value?: string | null;
onChange?: (damageDice: string | null) => void;
}) {
const known = [...SPELL_DAMAGE_GROUPS.flatMap((g) => g.options), ...SPELL_DAMAGE_SPECIALS];
const others = value && !known.includes(value) ? [...SPELL_DAMAGE_SPECIALS, value] : SPELL_DAMAGE_SPECIALS;
return (
<select
name={name}
aria-label={spellName ? `${spellName} damage` : 'Damage'}
{...(onChange ? { value: value ?? '', onChange: (e) => onChange(e.target.value || null) } : { defaultValue: '' })}
>
<option value="">No damage</option>
{SPELL_DAMAGE_GROUPS.map((group) => (
<optgroup key={group.label} label={group.label}>
{group.options.map((dice) => (
<option key={dice} value={dice}>
{dice}
</option>
))}
</optgroup>
))}
<optgroup label="Other">
{others.map((dice) => (
<option key={dice} value={dice}>
{dice}
</option>
))}
</optgroup>
</select>
);
}
function LibraryPicker<T extends { key: string; name: string }>({
items,
onAdd,
adding,
renderMeta,
renderDetail,
placeholder,
}: {
items: T[];
onAdd: (key: string) => void;
adding: boolean;
renderMeta: (item: T) => string;
// A sentence on what the entry is or does, shown under its name.
renderDetail?: (item: T) => string | null;
placeholder: string;
}) {
const [query, setQuery] = useState('');
@@ -97,6 +224,7 @@ function LibraryPicker<T extends { key: string; name: string }>({
<div>
<strong>{item.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6, fontSize: '0.85rem' }}>{renderMeta(item)}</span>
{renderDetail?.(item) && <div style={{ fontSize: '0.9rem' }}>{renderDetail(item)}</div>}
</div>
<button className="btn btn-ghost" disabled={adding} onClick={() => onAdd(item.key)}>
+ Add
@@ -119,9 +247,11 @@ export function CampaignHomePage() {
const { data, isLoading, error } = useCampaign(campaignId);
const { data: characters } = useCampaignCharacters(campaignId);
const { data: encounters } = useCampaignEncounters(campaignId);
const { data: monsters } = useCampaignMonsters(campaignId);
const { data: monsters } = useCampaignMonsters(campaignId, data?.campaign.role === 'DM');
const { data: weapons } = useCampaignWeapons(campaignId);
const { data: spells } = useCampaignSpells(campaignId);
const { data: items } = useCampaignItems(campaignId);
const { data: npcs } = useCampaignNpcs(campaignId, data?.campaign.role === 'DM');
const { data: notes } = useCampaignNotes(campaignId);
const { data: locations } = useCampaignLocations(campaignId);
const { data: library } = useCampaignLibrary(campaignId);
@@ -133,6 +263,15 @@ export function CampaignHomePage() {
const deleteMonster = useDeleteMonster(campaignId);
const createWeapon = useCreateWeapon(campaignId);
const createSpell = useCreateSpell(campaignId);
const createItem = useCreateItem(campaignId);
const createNpc = useCreateNpc(campaignId);
const deleteNpc = useDeletePoolEntry(campaignId, 'npcs');
const patchWeapon = usePatchPoolEntry(campaignId, 'weapons');
const deleteWeapon = useDeletePoolEntry(campaignId, 'weapons');
const patchSpell = usePatchPoolEntry(campaignId, 'spells');
const deleteSpell = useDeletePoolEntry(campaignId, 'spells');
const patchItem = usePatchPoolEntry(campaignId, 'items');
const deleteItem = useDeletePoolEntry(campaignId, 'items');
const createNote = useCreateNote();
const updateCampaign = useUpdateCampaign(campaignId);
const regenerateInvite = useRegenerateInvite(campaignId);
@@ -144,6 +283,8 @@ export function CampaignHomePage() {
const [newCharName, setNewCharName] = useState('');
const [newEncounterName, setNewEncounterName] = useState('');
const [newEncounterMode, setNewEncounterMode] = useState<EncounterMode>('BATTLE');
const [showNpcForm, setShowNpcForm] = useState(false);
const [noteBody, setNoteBody] = useState('');
const [dmNoteBody, setDmNoteBody] = useState('');
const [newLocationName, setNewLocationName] = useState('');
@@ -152,12 +293,15 @@ export function CampaignHomePage() {
const [showMonsterForm, setShowMonsterForm] = useState(false);
const [showWeaponForm, setShowWeaponForm] = useState(false);
const [showSpellForm, setShowSpellForm] = useState(false);
const [showItemForm, setShowItemForm] = useState(false);
const [showWeaponLibrary, setShowWeaponLibrary] = useState(false);
const [showSpellLibrary, setShowSpellLibrary] = useState(false);
const [showMonsterLibrary, setShowMonsterLibrary] = useState(false);
const weaponsPage = usePagination(weapons, 8);
const spellsPage = usePagination(spells, 8);
const itemsPage = usePagination(items, 8);
const npcsPage = usePagination(npcs, 8);
const monstersPage = usePagination(monsters, 8);
const sharedNotes = notes?.filter((n) => n.visibility === 'SHARED');
const dmNotes = notes?.filter((n) => n.visibility === 'DM_ONLY');
@@ -187,7 +331,10 @@ export function CampaignHomePage() {
async function handleCreateEncounter(e: FormEvent) {
e.preventDefault();
try {
const encounter = await createEncounter.mutateAsync(newEncounterName || 'New Encounter');
const encounter = await createEncounter.mutateAsync({
name: newEncounterName || (newEncounterMode === 'QUEST' ? 'New Quest' : 'New Encounter'),
mode: newEncounterMode,
});
navigate(`/encounters/${encounter.id}`);
} catch (err) {
setFormError(extractErrorMessage(err));
@@ -265,7 +412,7 @@ export function CampaignHomePage() {
<input name="startingGold" type="number" min={0} defaultValue={campaign.startingGold} />
</div>
<div className="field">
<label>Starting items</label>
<label>Starting items (weapons + items)</label>
<input name="startingItemCount" type="number" min={0} defaultValue={campaign.startingItemCount} />
</div>
<div className="field">
@@ -275,7 +422,7 @@ export function CampaignHomePage() {
</div>
<label className="checkbox-row">
<input type="checkbox" name="skipMotivationRoll" defaultChecked={campaign.skipMotivationRoll} />
Skip the motivation roll for this campaign
Skip the motivation step when building a character
</label>
<button type="submit" className="btn btn-primary mt-md" disabled={updateCampaign.isPending}>
Save Settings
@@ -346,20 +493,113 @@ export function CampaignHomePage() {
onChange={(e) => setNewEncounterName(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<select aria-label="Encounter type" value={newEncounterMode} onChange={(e) => setNewEncounterMode(e.target.value as EncounterMode)}>
<option value="BATTLE">Battle</option>
<option value="QUEST">NPC quest</option>
</select>
<button type="submit" className="btn btn-primary" disabled={createEncounter.isPending}>
⚔ Start Encounter
{newEncounterMode === 'QUEST' ? '📜 Start Quest' : '⚔ Start Encounter'}
</button>
</form>
)}
{encounters?.length === 0 && <div className="empty-state">No encounters yet.</div>}
{encounters?.map((enc) => (
<Link key={enc.id} to={`/encounters/${enc.id}`} className="card flex-between" style={{ display: 'flex' }}>
<span>{enc.name}</span>
<span className="badge">{enc.status} · Round {enc.currentRound}</span>
<span>
<span className="badge" style={{ marginRight: 8 }}>{MODE_LABELS[enc.mode]}</span>
{enc.name}
</span>
<span className="badge">
{enc.status}
{enc.mode === 'BATTLE' && ` · Round ${enc.currentRound}`}
</span>
</Link>
))}
</div>
{isDM && (
<div className="mt-lg card">
<div className="card-title">
<span>NPCs</span>
<button className="btn btn-ghost" onClick={() => setShowNpcForm((s) => !s)}>
{showNpcForm ? 'Close' : '+ Add NPC'}
</button>
</div>
<p className="subtitle" style={{ marginTop: 0 }}>
The people your party meets. Add them to an encounter to bring them into a scene. Players never see your notes or an
NPC's stats.
</p>
{showNpcForm && (
<form
onSubmit={async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const fd = new FormData(form);
const text = (key: string) => String(fd.get(key) || '').trim() || null;
const num = (key: string) => (fd.get(key) ? Number(fd.get(key)) : null);
try {
await createNpc.mutateAsync({
name: String(fd.get('name')),
role: text('role'),
disposition: fd.get('disposition') as NpcDisposition,
description: text('description'),
dmNotes: text('dmNotes'),
ac: num('ac'),
maxHp: num('maxHp'),
attackBonus: num('attackBonus'),
damageDice: text('damageDice'),
});
form.reset();
} catch (err) {
setFormError(extractErrorMessage(err));
}
}}
>
<div className="grid grid-cols-3">
<input name="name" placeholder="Name" required maxLength={80} />
<input name="role" placeholder="Role (innkeeper, captain…)" maxLength={80} />
<select name="disposition" defaultValue="NEUTRAL" aria-label="Attitude toward the party">
<option value="FRIENDLY">Friendly</option>
<option value="NEUTRAL">Neutral</option>
<option value="HOSTILE">Hostile</option>
</select>
</div>
<textarea name="description" rows={2} className="textarea-block mt-sm" placeholder="What the party sees and knows (shown to players)" />
<textarea name="dmNotes" rows={2} className="textarea-block mt-sm" placeholder="Secrets and motives (only you see this)" />
<div className="grid grid-cols-3 mt-sm">
<input name="ac" type="number" min={0} placeholder="AC (optional)" />
<input name="maxHp" type="number" min={1} placeholder="HP (optional)" />
<input name="attackBonus" type="number" placeholder="Attack bonus (optional)" />
<input name="damageDice" placeholder="Damage (optional, e.g. 1d6)" maxLength={20} />
<button type="submit" className="btn btn-primary" disabled={createNpc.isPending}>Add NPC</button>
</div>
</form>
)}
<div className="mt-sm">
{npcs?.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No NPCs yet.</p>}
{npcsPage.pageItems.map((npc) => (
<div key={npc.id} className="flex-between" style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<div>
<strong>{npc.name}</strong>
{npc.role && <span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>{npc.role}</span>}
<span className={`badge badge-${npc.disposition.toLowerCase()}`} style={{ marginLeft: 8 }}>{npc.disposition}</span>
{npc.description && <div style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>{npc.description}</div>}
{npc.dmNotes && <div style={{ color: 'var(--text-dim)', fontSize: '0.85rem' }}>🔒 {npc.dmNotes}</div>}
</div>
<button
className="btn btn-ghost"
aria-label={`Remove ${npc.name}`}
onClick={() => window.confirm(`Remove ${npc.name}?`) && deleteNpc.mutate(npc.id)}
>
✕
</button>
</div>
))}
</div>
<Pagination page={npcsPage.page} pageCount={npcsPage.pageCount} onPrev={npcsPage.prevPage} onNext={npcsPage.nextPage} />
</div>
)}
{isDM && (
<div className="mt-lg card">
<div className="card-title">
@@ -389,7 +629,20 @@ export function CampaignHomePage() {
{isDM && (
<>
<div className="mt-lg card">
<div className="mt-lg">
<h2 style={{ fontSize: '1.1rem', margin: 0 }}>Gear Pools</h2>
<p className="subtitle">
You hand out weapons, items and spells from these pools on each character's sheet. Tick "Starting" for the ones a
player may pick while building a new character.
</p>
<p className="subtitle">
Weapons and items have levels 1–{MAX_GEAR_LEVEL}. The damage you enter is the damage at the level it starts at
(level 1 unless you pick a higher one). When you level up a character's copy, its dice grow one small step per
level (1d4 → 1d6 → 1d8 → 1d10 → 1d12 → 2d6 → …) — two steps for Powerful gear, three for Legendary. A character
must be at least a weapon's or item's level to use it, and at least a spell's level to cast it.
</p>
</div>
<div className="mt-sm card">
<div className="card-title">
<span>Weapons Pool</span>
<div className="flex-row gap-sm">
@@ -407,7 +660,7 @@ export function CampaignHomePage() {
adding={addWeaponFromLibrary.isPending}
onAdd={(key) => addWeaponFromLibrary.mutate(key)}
placeholder="Search the weapon library…"
renderMeta={(w) => `${w.category} · ${w.damageDice} ${w.damageType}`}
renderMeta={(w) => `${w.category} · ${w.damageDice} ${w.damageType} · starts at level 1`}
/>
)}
{showWeaponForm && (
@@ -423,19 +676,28 @@ export function CampaignHomePage() {
properties: [],
rangeNormal: null,
rangeLong: null,
damageScaling: Number(fd.get('damageScaling')),
minLevel: Number(fd.get('minLevel')),
isStartingOption: fd.get('isStartingOption') === 'on',
});
(e.target as HTMLFormElement).reset();
}}
className="grid grid-cols-3"
>
<input name="name" placeholder="Name" required />
<input name="damageDice" placeholder="Damage dice (1d8)" required />
<input name="damageDice" placeholder="Damage at its starting level (1d8)" required />
<input name="damageType" placeholder="Damage type" required />
<select name="attackAbility" defaultValue="STR">
<option value="STR">STR</option>
<option value="DEX">DEX</option>
<option value="FINESSE">Finesse</option>
</select>
<ScalingSelect name="damageScaling" />
<StartLevelSelect name="minLevel" />
<label className="checkbox-row">
<input type="checkbox" name="isStartingOption" />
Starting option
</label>
<button type="submit" className="btn btn-primary">Add</button>
</form>
)}
@@ -444,7 +706,11 @@ export function CampaignHomePage() {
<thead>
<tr>
<th>Name</th>
<th>Damage</th>
<th>Base damage</th>
<th>Level</th>
<th>Growth</th>
<th>Starting</th>
<th />
</tr>
</thead>
<tbody>
@@ -452,6 +718,17 @@ export function CampaignHomePage() {
<tr key={w.id}>
<td>{w.name}</td>
<td>{w.damageDice} {w.damageType}</td>
<td>
<StartLevelSelect value={w.minLevel} onChange={(minLevel) => patchWeapon.mutate({ id: w.id, minLevel })} />
</td>
<td>
<ScalingSelect value={w.damageScaling} onChange={(damageScaling) => patchWeapon.mutate({ id: w.id, damageScaling })} />
</td>
<PoolRowControls
entry={w}
onToggleStarting={(isStartingOption) => patchWeapon.mutate({ id: w.id, isStartingOption })}
onDelete={() => deleteWeapon.mutate(w.id)}
/>
</tr>
))}
</tbody>
@@ -460,6 +737,88 @@ export function CampaignHomePage() {
<Pagination page={weaponsPage.page} pageCount={weaponsPage.pageCount} onPrev={weaponsPage.prevPage} onNext={weaponsPage.nextPage} />
</div>
<div className="mt-md card">
<div className="card-title">
<span>Items Pool</span>
<button className="btn btn-ghost" onClick={() => setShowItemForm((s) => !s)}>
{showItemForm ? 'Close' : '+ Add Item'}
</button>
</div>
{showItemForm && (
<form
onSubmit={async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const fd = new FormData(form);
await createItem.mutateAsync({
name: String(fd.get('name')),
description: String(fd.get('description') || '') || null,
damageDice: String(fd.get('damageDice') || '').trim() || null,
damageScaling: Number(fd.get('damageScaling')),
minLevel: Number(fd.get('minLevel')),
isStartingOption: fd.get('isStartingOption') === 'on',
});
form.reset();
}}
className="grid grid-cols-3"
>
<input name="name" placeholder="Name" required />
<input name="description" placeholder="Description (optional)" />
<input name="damageDice" placeholder="Dice (optional, e.g. 2d4+2)" maxLength={20} />
<ScalingSelect name="damageScaling" />
<StartLevelSelect name="minLevel" />
<label className="checkbox-row">
<input type="checkbox" name="isStartingOption" />
Starting option
</label>
<button type="submit" className="btn btn-primary">Add</button>
</form>
)}
{items?.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No items yet. Add rope, potions, quest items…</p>}
{items && items.length > 0 && (
<div className="table-wrap mt-sm">
<table className="data-table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Base dice</th>
<th>Level</th>
<th>Growth</th>
<th>Starting</th>
<th />
</tr>
</thead>
<tbody>
{itemsPage.pageItems.map((item) => (
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.description}</td>
<td>{item.damageDice || '—'}</td>
<td>
<StartLevelSelect value={item.minLevel} onChange={(minLevel) => patchItem.mutate({ id: item.id, minLevel })} />
</td>
<td>
{item.damageDice ? (
<ScalingSelect value={item.damageScaling} onChange={(damageScaling) => patchItem.mutate({ id: item.id, damageScaling })} />
) : (
'—'
)}
</td>
<PoolRowControls
entry={item}
onToggleStarting={(isStartingOption) => patchItem.mutate({ id: item.id, isStartingOption })}
onDelete={() => deleteItem.mutate(item.id)}
/>
</tr>
))}
</tbody>
</table>
</div>
)}
<Pagination page={itemsPage.page} pageCount={itemsPage.pageCount} onPrev={itemsPage.prevPage} onNext={itemsPage.nextPage} />
</div>
<div className="mt-md card">
<div className="card-title">
<span>Spell List</span>
@@ -478,7 +837,12 @@ export function CampaignHomePage() {
adding={addSpellFromLibrary.isPending}
onAdd={(key) => addSpellFromLibrary.mutate(key)}
placeholder="Search the spell library…"
renderMeta={(s) => `${s.level === 0 ? 'Cantrip' : `Lv ${s.level}`} · ${s.school || ''}`}
renderMeta={(s) =>
[spellLevelLabel(s.level), spellRequirementLabel(s.level), s.damageDice ? `${s.damageDice} damage` : 'no damage', s.school]
.filter(Boolean)
.join(' · ')
}
renderDetail={(s) => s.description}
/>
)}
{showSpellForm && (
@@ -493,15 +857,29 @@ export function CampaignHomePage() {
castingTime: null,
range: null,
duration: null,
description: null,
description: String(fd.get('description') || '').trim() || null,
damageDice: String(fd.get('damageDice') || '') || null,
isStartingOption: fd.get('isStartingOption') === 'on',
});
(e.target as HTMLFormElement).reset();
}}
className="grid grid-cols-3"
>
<input name="name" placeholder="Name" required />
<input name="level" type="number" min={0} max={9} placeholder="Level (0=cantrip)" required />
<select name="level" defaultValue={0} aria-label="Spell level">
{[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((level) => (
<option key={level} value={level}>
{spellLevelLabel(level)}
</option>
))}
</select>
<input name="school" placeholder="School" />
<SpellDamageSelect name="damageDice" />
<input name="description" placeholder="What it does (one sentence)" maxLength={4000} required style={{ gridColumn: '1 / -1' }} />
<label className="checkbox-row">
<input type="checkbox" name="isStartingOption" />
Starting option
</label>
<button type="submit" className="btn btn-primary">Add</button>
</form>
)}
@@ -509,15 +887,29 @@ export function CampaignHomePage() {
<table className="data-table">
<thead>
<tr>
<th>Name</th>
<th>Spell</th>
<th>Level</th>
<th>Damage</th>
<th>Starting</th>
<th />
</tr>
</thead>
<tbody>
{spellsPage.pageItems.map((s) => (
<tr key={s.id}>
<td>{s.name}</td>
<td>{s.level === 0 ? 'Cantrip' : s.level}</td>
<td>
<strong>{s.name}</strong>
<div style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>{s.description || 'No description.'}</div>
</td>
<td style={{ whiteSpace: 'nowrap' }}>{spellLevelLabel(s.level)}</td>
<td>
<SpellDamageSelect spellName={s.name} value={s.damageDice} onChange={(damageDice) => patchSpell.mutate({ id: s.id, damageDice })} />
</td>
<PoolRowControls
entry={s}
onToggleStarting={(isStartingOption) => patchSpell.mutate({ id: s.id, isStartingOption })}
onDelete={() => deleteSpell.mutate(s.id)}
/>
</tr>
))}
</tbody>
@@ -544,7 +936,8 @@ export function CampaignHomePage() {
adding={addMonsterFromLibrary.isPending}
onAdd={(key) => addMonsterFromLibrary.mutate(key)}
placeholder="Search the monster library…"
renderMeta={(m) => `CR ${m.challengeRating} · AC ${m.ac} · HP ${m.maxHp}`}
renderMeta={(m) => `CR ${m.challengeRating} · AC ${m.ac} · HP ${m.maxHp} · attack +${m.attackBonus}${m.damageDice ? ` for ${m.damageDice}` : ''}`}
renderDetail={(m) => [m.specialTrait, m.notes].filter(Boolean).join(' — ') || null}
/>
)}
{showMonsterForm && (
File diff suppressed because it is too large Load Diff
+452 -89
View File
@@ -1,20 +1,30 @@
import { useState, type FormEvent } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Link, useNavigate, useParams } from 'react-router-dom';
import {
useCharacter,
usePatchCharacter,
useCampaignWeapons,
useAssignWeapon,
usePatchCharacterWeapon,
useAddInventoryItem,
useRemoveCharacterWeapon,
useCampaignItems,
useAssignItem,
usePatchInventoryItem,
useDeleteInventoryItem,
useRemoveInventoryItem,
useCampaignSpells,
useAssignSpell,
usePatchCharacterSpell,
useRemoveCharacterSpell,
useGoldLedger,
useAdjustGold,
useCampaignCharacters,
useGive,
type Gift,
useCharacterNotes,
useCreateNote,
useCampaign,
useCampaigns,
useCopyCharacter,
useCampaignLocations,
} from '../api/queries';
import { useAuth } from '../auth/AuthContext';
@@ -23,11 +33,173 @@ import { Spinner, ErrorBanner } from '../components/Spinner';
import { QuickStatsFab } from '../components/QuickStatsDrawer';
import { InfoTip } from '../components/InfoTip';
import { usePagination, Pagination } from '../components/Paginated';
import { ABILITY_LABELS, CLASS_LABELS, SKILL_LABELS, SPECIES_LABELS, fmtMod, hpBarClass, extractErrorMessage } from '../lib/format';
import { ABILITY_LABELS, CLASS_LABELS, SKILL_LABELS, SPECIES_LABELS, fmtMod, hpBarClass, extractErrorMessage, spellLevelLabel } from '../lib/format';
import { speciesIcon } from '../lib/speciesIcons';
import { hpMax as previewHpMax } from '../lib/previewCalc';
import { hpMax as previewHpMax, scaledDamageDice, MAX_GEAR_LEVEL } from '../lib/previewCalc';
import { CLASS_HIT_DIE } from '../lib/classData';
import type { Ability } from '../api/types';
import type { Ability, CharacterDetail } from '../api/types';
// The DM's level picker for one held weapon or item, from the level the gear
// starts at up to the maximum. Each option shows what the dice become at that
// level, so the step up is visible before choosing.
function GearLevelSelect({
name,
level,
entry,
onChange,
}: {
name: string;
level: number;
entry: { damageDice: string | null; damageScaling: number; minLevel: number };
onChange: (level: number) => void;
}) {
const levels = Array.from({ length: MAX_GEAR_LEVEL - entry.minLevel + 1 }, (_, i) => entry.minLevel + i);
return (
<select aria-label={`${name} level`} value={level} onChange={(e) => onChange(Number(e.target.value))}>
{levels.map((l) => (
<option key={l} value={l}>
Lv {l}
{entry.damageDice ? ` · ${scaledDamageDice(entry.damageDice, l, entry.damageScaling, entry.minLevel)}` : ''}
</option>
))}
</select>
);
}
function RequiresLevel({ level }: { level: number }) {
return (
<span className="badge" style={{ marginLeft: 6 }} title="Held, but can't be used until the character reaches this level">
Requires level {level}
</span>
);
}
// Lets the owner (or DM) hand something this character holds to another
// character in the campaign. Giving moves it: the giver no longer has it.
function GiveCard({ character, onError }: { character: CharacterDetail; onError: (err: unknown) => void }) {
const { data: characters } = useCampaignCharacters(character.campaignId);
const give = useGive(character.id);
const [what, setWhat] = useState('');
const [amount, setAmount] = useState('1');
const [toCharacterId, setToCharacterId] = useState('');
const [done, setDone] = useState<string | null>(null);
const others = characters?.filter((c) => c.id !== character.id && c.buildStage === 'COMPLETE') ?? [];
if (others.length === 0) return null;
// "kind:id" identifies the thing picked; gold has no id.
const [kind, id] = what.split(':');
const heldWeapon = character.weapons.find((w) => w.weaponId === id);
const heldItem = character.inventoryItems.find((i) => i.itemId === id);
const max = kind === 'gold' ? character.gold : kind === 'weapon' ? (heldWeapon?.quantity ?? 0) : kind === 'item' ? (heldItem?.quantity ?? 0) : 1;
const count = Math.floor(Number(amount));
const countOk = kind === 'spell' || (count >= 1 && count <= max);
const nothingToGive = character.gold === 0 && character.weapons.length + character.inventoryItems.length + character.spells.length === 0;
function handleGive() {
const gift: Gift | null =
kind === 'gold'
? { kind, amount: count }
: kind === 'weapon' || kind === 'item'
? { kind, id, quantity: count }
: kind === 'spell'
? { kind, id }
: null;
if (!gift || !toCharacterId) return;
setDone(null);
give.mutate(
{ ...gift, toCharacterId },
{
onError,
onSuccess: () => {
setDone(`Given to ${others.find((c) => c.id === toCharacterId)?.name}.`);
setWhat('');
setAmount('1');
},
}
);
}
return (
<div className="card mt-md">
<div className="card-title">Give to Another Character</div>
<p className="subtitle" style={{ marginTop: 0 }}>
Hand gold, a weapon, an item or a spell to someone else in the party. Giving moves it — {character.name} no longer has
it afterwards.
</p>
{nothingToGive ? (
<p style={{ color: 'var(--text-muted)', margin: 0 }}>{character.name} has nothing to give yet.</p>
) : (
<div className="flex-row flex-wrap">
<select
aria-label="What to give"
value={what}
onChange={(e) => {
setWhat(e.target.value);
setAmount('1');
setDone(null);
}}
style={{ flex: 2, minWidth: 160 }}
>
<option value="">What to give…</option>
{character.gold > 0 && <option value="gold:">Gold ({character.gold} gp)</option>}
{character.weapons.length > 0 && (
<optgroup label="Weapons">
{character.weapons.map((w) => (
<option key={w.weaponId} value={`weapon:${w.weaponId}`}>
{w.weapon.name} (Lv {w.level}, x{w.quantity})
</option>
))}
</optgroup>
)}
{character.inventoryItems.length > 0 && (
<optgroup label="Items">
{character.inventoryItems.map((i) => (
<option key={i.itemId} value={`item:${i.itemId}`}>
{i.item.name} (Lv {i.level}, x{i.quantity})
</option>
))}
</optgroup>
)}
{character.spells.length > 0 && (
<optgroup label="Spells">
{character.spells.map((s) => (
<option key={s.spellId} value={`spell:${s.spellId}`}>
{s.spell.name} ({spellLevelLabel(s.spell.level)})
</option>
))}
</optgroup>
)}
</select>
{what && kind !== 'spell' && (
<input
type="number"
min={1}
max={max}
aria-label={kind === 'gold' ? 'How much gold' : 'How many'}
title={kind === 'gold' ? 'How much gold' : `How many (up to ${max})`}
value={amount}
onChange={(e) => setAmount(e.target.value)}
style={{ width: 90 }}
/>
)}
<select aria-label="Who to give it to" value={toCharacterId} onChange={(e) => setToCharacterId(e.target.value)} style={{ flex: 1, minWidth: 130 }}>
<option value="">To whom…</option>
{others.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<button className="btn" onClick={handleGive} disabled={!what || !toCharacterId || !countOk || give.isPending}>
Give
</button>
</div>
)}
{done && <p className="subtitle">✓ {done}</p>}
</div>
);
}
export function CharacterSheetPage() {
const { characterId = '' } = useParams();
@@ -39,29 +211,41 @@ export function CharacterSheetPage() {
const { data: campaignData } = useCampaign(character?.campaignId);
const { data: campaignWeapons } = useCampaignWeapons(character?.campaignId);
const { data: campaignSpells } = useCampaignSpells(character?.campaignId);
const { data: campaignItems } = useCampaignItems(character?.campaignId);
const { data: goldLedger } = useGoldLedger(characterId);
const { data: locations } = useCampaignLocations(character?.campaignId);
const { data: notes } = useCharacterNotes(characterId);
const assignWeapon = useAssignWeapon(characterId);
const patchWeapon = usePatchCharacterWeapon(characterId);
const addItem = useAddInventoryItem(characterId);
const removeWeapon = useRemoveCharacterWeapon(characterId);
const assignItem = useAssignItem(characterId);
const patchItem = usePatchInventoryItem(characterId);
const deleteItem = useDeleteInventoryItem(characterId);
const removeItem = useRemoveInventoryItem(characterId);
const assignSpell = useAssignSpell(characterId);
const patchSpell = usePatchCharacterSpell(characterId);
const removeSpell = useRemoveCharacterSpell(characterId);
const adjustGold = useAdjustGold(characterId);
const createNote = useCreateNote();
const { data: campaigns } = useCampaigns();
const copyCharacter = useCopyCharacter(characterId);
const navigate = useNavigate();
const [hpDelta, setHpDelta] = useState('');
const [newItemName, setNewItemName] = useState('');
const [pickedItemId, setPickedItemId] = useState('');
const [goldAmount, setGoldAmount] = useState('');
const [goldReason, setGoldReason] = useState('');
const [noteBody, setNoteBody] = useState('');
const [pickedWeaponId, setPickedWeaponId] = useState('');
const [pickedSpellId, setPickedSpellId] = useState('');
const [copyTargetId, setCopyTargetId] = useState('');
const [formError, setFormError] = useState<string | null>(null);
const weaponsPage = usePagination(character?.weapons, 8);
const spellsPage = usePagination(character?.spells, 8);
const itemsPage = usePagination(character?.inventoryItems, 8);
const notesPage = usePagination(notes, 6);
const ledgerPage = usePagination(goldLedger, 6);
if (isLoading) return <Spinner label="Unfurling the character sheet…" />;
if (error || !character) return <ErrorBanner message="Could not load this character." />;
@@ -99,11 +283,27 @@ export function CharacterSheetPage() {
patchCharacter.mutate({ currentHp: newMax });
}
async function handleAddItem(e: FormEvent) {
e.preventDefault();
if (!newItemName.trim()) return;
await addItem.mutateAsync({ name: newItemName });
setNewItemName('');
async function handleAssignItem() {
if (!pickedItemId) return;
try {
await assignItem.mutateAsync({ itemId: pickedItemId });
setPickedItemId('');
} catch (err) {
setFormError(extractErrorMessage(err));
}
}
async function handleGold(sign: 1 | -1) {
const amount = Math.floor(Number(goldAmount));
if (!(amount > 0)) return;
setFormError(null);
try {
await adjustGold.mutateAsync({ amount: sign * amount, reason: goldReason.trim() || undefined });
setGoldAmount('');
setGoldReason('');
} catch (err) {
setFormError(extractErrorMessage(err));
}
}
async function handleAddNote(e: FormEvent) {
@@ -133,6 +333,19 @@ export function CharacterSheetPage() {
}
}
async function handleCopy() {
if (!copyTargetId) return;
try {
const copy = await copyCharacter.mutateAsync(copyTargetId);
setCopyTargetId('');
navigate(`/campaigns/${copy.campaignId}`);
} catch (err) {
setFormError(extractErrorMessage(err));
}
}
const otherCampaigns = campaigns?.filter((c) => c.id !== character.campaignId) ?? [];
const assignedWeaponIds = new Set(character.weapons.map((w) => w.weaponId));
const assignedSpellIds = new Set(character.spells.map((s) => s.spellId));
@@ -349,26 +562,44 @@ export function CharacterSheetPage() {
<div>
<strong>{cw.weapon.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>
{cw.weapon.damageDice} {cw.weapon.damageType} · x{cw.quantity}
Lv {cw.level} · {cw.scaledDamageDice} {cw.weapon.damageType} · x{cw.quantity}
</span>
{!cw.usable && <RequiresLevel level={cw.level} />}
</div>
{canEdit && (
<label className="flex-row gap-sm">
Equipped
<input
type="checkbox"
checked={cw.equipped}
onChange={(e) => patchWeapon.mutate({ weaponId: cw.weaponId, equipped: e.target.checked })}
/>
</label>
<div className="flex-row gap-sm">
<label className="flex-row gap-sm">
Equipped
<input
type="checkbox"
checked={cw.equipped}
disabled={!cw.usable}
onChange={(e) => patchWeapon.mutate({ weaponId: cw.weaponId, equipped: e.target.checked })}
/>
</label>
{isDM && (
<>
<GearLevelSelect
name={cw.weapon.name}
level={cw.level}
entry={cw.weapon}
onChange={(level) => patchWeapon.mutate({ weaponId: cw.weaponId, level })}
/>
<button className="btn btn-ghost" aria-label={`Take away ${cw.weapon.name}`} onClick={() => removeWeapon.mutate(cw.weaponId)}>
✕
</button>
</>
)}
</div>
)}
</div>
))}
{character.weapons.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No weapons. The DM hands these out.</p>}
<Pagination page={weaponsPage.page} pageCount={weaponsPage.pageCount} onPrev={weaponsPage.prevPage} onNext={weaponsPage.nextPage} />
{canEdit && (
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<select value={pickedWeaponId} onChange={(e) => setPickedWeaponId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Add a weapon from the campaign pool…</option>
<option value="">Give a weapon from the campaign pool…</option>
{campaignWeapons
?.filter((w) => !assignedWeaponIds.has(w.id))
.map((w) => (
@@ -378,7 +609,7 @@ export function CharacterSheetPage() {
))}
</select>
<button className="btn" onClick={handleAssignWeapon} disabled={!pickedWeaponId}>
Add
Give
</button>
</div>
)}
@@ -391,35 +622,49 @@ export function CharacterSheetPage() {
<div key={cs.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<div>
<strong>{cs.spell.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>Lv {cs.spell.level}</span>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>
{spellLevelLabel(cs.spell.level)}
{cs.spell.damageDice && ` · ${cs.spell.damageDice} damage`}
</span>
{!cs.usable && <RequiresLevel level={cs.spell.level} />}
{cs.spell.description && <div style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>{cs.spell.description}</div>}
</div>
{canEdit && (
<label className="flex-row gap-sm">
Prepared
<input
type="checkbox"
checked={cs.prepared}
onChange={(e) => patchSpell.mutate({ spellId: cs.spellId, prepared: e.target.checked })}
/>
</label>
<div className="flex-row gap-sm">
<label className="flex-row gap-sm">
Prepared
<input
type="checkbox"
checked={cs.prepared}
disabled={!cs.usable}
onChange={(e) => patchSpell.mutate({ spellId: cs.spellId, prepared: e.target.checked })}
/>
</label>
{isDM && (
<button className="btn btn-ghost" aria-label={`Take away ${cs.spell.name}`} onClick={() => removeSpell.mutate(cs.spellId)}>
✕
</button>
)}
</div>
)}
</div>
))}
{character.spells.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No spells known. The DM grants these.</p>}
<Pagination page={spellsPage.page} pageCount={spellsPage.pageCount} onPrev={spellsPage.prevPage} onNext={spellsPage.nextPage} />
{canEdit && (
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<select value={pickedSpellId} onChange={(e) => setPickedSpellId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Add a spell from the campaign list…</option>
<option value="">Grant a spell from the campaign list…</option>
{campaignSpells
.filter((s) => !assignedSpellIds.has(s.id))
.map((s) => (
<option key={s.id} value={s.id}>
{s.name} (Lv {s.level})
{s.name} ({spellLevelLabel(s.level)})
</option>
))}
</select>
<button className="btn" onClick={handleAssignSpell} disabled={!pickedSpellId}>
Add
Grant
</button>
</div>
)}
@@ -428,11 +673,18 @@ export function CharacterSheetPage() {
<div className="card mt-md">
<div className="card-title">Inventory</div>
{itemsPage.pageItems.map((item) => (
<div key={item.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
{itemsPage.pageItems.map((held) => (
<div key={held.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<div>
<strong>{item.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>x{item.quantity}</span>
<strong>{held.item.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>
Lv {held.level}
{held.scaledDamageDice && ` · ${held.scaledDamageDice}`} · x{held.quantity}
</span>
{!held.usable && <RequiresLevel level={held.level} />}
{held.item.description && (
<div style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>{held.item.description}</div>
)}
</div>
{canEdit && (
<div className="flex-row gap-sm">
@@ -440,67 +692,178 @@ export function CharacterSheetPage() {
Equipped
<input
type="checkbox"
checked={item.equipped}
onChange={(e) => patchItem.mutate({ itemId: item.id, equipped: e.target.checked })}
checked={held.equipped}
disabled={!held.usable}
onChange={(e) => patchItem.mutate({ itemId: held.itemId, equipped: e.target.checked })}
/>
</label>
<button className="btn btn-ghost" onClick={() => deleteItem.mutate(item.id)}>
✕
</button>
{isDM && (
<>
<GearLevelSelect
name={held.item.name}
level={held.level}
entry={held.item}
onChange={(level) => patchItem.mutate({ itemId: held.itemId, level })}
/>
<button
className="btn btn-ghost"
aria-label={`One fewer ${held.item.name}`}
disabled={held.quantity <= 1}
onClick={() => patchItem.mutate({ itemId: held.itemId, quantity: held.quantity - 1 })}
>
−
</button>
<button
className="btn btn-ghost"
aria-label={`One more ${held.item.name}`}
onClick={() => patchItem.mutate({ itemId: held.itemId, quantity: held.quantity + 1 })}
>
+
</button>
<button className="btn btn-ghost" aria-label={`Take away ${held.item.name}`} onClick={() => removeItem.mutate(held.itemId)}>
✕
</button>
</>
)}
</div>
)}
</div>
))}
{character.inventoryItems.length === 0 && <p style={{ color: 'var(--text-muted)' }}>Nothing carried. The DM hands out items.</p>}
<Pagination page={itemsPage.page} pageCount={itemsPage.pageCount} onPrev={itemsPage.prevPage} onNext={itemsPage.nextPage} />
{canEdit && (
<form onSubmit={handleAddItem} className="flex-row mt-sm flex-wrap">
<input
placeholder="New item name"
value={newItemName}
onChange={(e) => setNewItemName(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<button type="submit" className="btn">
Add Item
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<select value={pickedItemId} onChange={(e) => setPickedItemId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Give an item from the campaign pool…</option>
{campaignItems?.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
<button className="btn" onClick={handleAssignItem} disabled={!pickedItemId}>
Give
</button>
</form>
</div>
)}
{isDM && campaignItems?.length === 0 && (
<p className="subtitle">The item pool is empty — add items on the campaign page first.</p>
)}
</div>
{canEdit && (
<div className="card mt-md">
<div className="card-title">
<span>Money</span>
<span className="mono">{character.gold} gp</span>
</div>
{canEdit && (
<div className="flex-row flex-wrap">
<input
type="number"
min={1}
placeholder="Amount"
aria-label="Gold amount"
value={goldAmount}
onChange={(e) => setGoldAmount(e.target.value)}
style={{ width: 100 }}
/>
<input
placeholder="What for? (optional)"
aria-label="Reason"
maxLength={200}
value={goldReason}
onChange={(e) => setGoldReason(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<button className="btn" onClick={() => handleGold(1)} disabled={!goldAmount || adjustGold.isPending}>
+ Gain
</button>
<button className="btn btn-danger" onClick={() => handleGold(-1)} disabled={!goldAmount || adjustGold.isPending}>
− Spend
</button>
</div>
)}
<div className="mt-sm">
{goldLedger?.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No transactions yet.</p>}
{ledgerPage.pageItems.map((t) => (
<div key={t.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<div>
<strong className="mono">{t.amount > 0 ? `+${t.amount}` : `−${Math.abs(t.amount)}`}</strong>
<span style={{ marginLeft: 8 }}>{t.reason || (t.amount > 0 ? 'Gained' : 'Spent')}</span>
<div style={{ fontSize: '0.75rem', color: 'var(--text-dim)' }}>
{t.createdBy ? `${t.createdBy.displayName} · ` : ''}
{new Date(t.createdAt).toLocaleString()}
</div>
</div>
<span className="mono" style={{ color: 'var(--text-muted)' }}>{t.balanceAfter} gp</span>
</div>
))}
</div>
<Pagination page={ledgerPage.page} pageCount={ledgerPage.pageCount} onPrev={ledgerPage.prevPage} onNext={ledgerPage.nextPage} />
</div>
{/* Composed by the character builder from the player's picks. Players
read them; only the DM can rewrite them (new abilities on level-up,
a scar earned in play). */}
{(
[
['specialAbilities', 'Special Abilities', 'One per line, e.g. “Reckless Attack — gained at level 2.”', 6],
['background', 'Background', 'Where this character came from, what drives them…', 5],
['appearance', 'Appearance', 'Height, build, notable features, typical outfit…', 5],
] as const
).map(([field, title, placeholder, rows]) => (
<div className="card mt-md" key={field}>
<div className="card-title">
<span>{title}</span>
{isDM && <span className="badge">DM can edit</span>}
</div>
{isDM ? (
<textarea
key={`${field}:${character[field] ?? ''}`}
className="textarea-block"
rows={rows}
defaultValue={character[field] ?? ''}
placeholder={placeholder}
aria-label={title}
onBlur={(e) => {
const value = e.target.value.trim() || null;
if (value !== (character[field] ?? null)) patchCharacter.mutate({ [field]: value });
}}
/>
) : character[field] ? (
<p className="composed-text">{character[field]}</p>
) : (
<p className="subtitle" style={{ margin: 0 }}>
Nothing here yet. Your DM can fill this in.
</p>
)}
</div>
))}
{canEdit && <GiveCard character={character} onError={(err) => setFormError(extractErrorMessage(err))} />}
{canEdit && otherCampaigns.length > 0 && (
<div className="card mt-md">
<div className="card-title">Special Abilities</div>
<textarea
rows={3}
defaultValue={character.specialAbilities || ''}
placeholder="Darkvision, Second Wind, Sneak Attack, etc."
onBlur={(e) => patchCharacter.mutate({ specialAbilities: e.target.value })}
/>
<div className="card-title">Copy to Another Campaign</div>
<p className="subtitle" style={{ marginTop: 0 }}>
Makes an independent copy at full HP with the same stats, gear and spells. This character stays here unchanged.
</p>
<div className="flex-row flex-wrap">
<select value={copyTargetId} onChange={(e) => setCopyTargetId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Choose a campaign…</option>
{otherCampaigns.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<button className="btn" onClick={handleCopy} disabled={!copyTargetId || copyCharacter.isPending}>
{copyCharacter.isPending ? 'Copying…' : 'Copy Character'}
</button>
</div>
</div>
)}
<div className="card mt-md">
<div className="card-title">Background</div>
<textarea
rows={4}
defaultValue={character.background || ''}
placeholder={canEdit ? "Where this character came from, what drives them…" : 'No background written yet.'}
readOnly={!canEdit}
onBlur={(e) => canEdit && patchCharacter.mutate({ background: e.target.value })}
/>
</div>
<div className="card mt-md">
<div className="card-title">Appearance</div>
<textarea
rows={3}
defaultValue={character.appearance || ''}
placeholder={canEdit ? 'Height, build, notable features, typical outfit…' : 'No appearance written yet.'}
readOnly={!canEdit}
onBlur={(e) => canEdit && patchCharacter.mutate({ appearance: e.target.value })}
/>
</div>
{isOwner && (
<div className="card mt-md">
<div className="card-title">Private Notes</div>
+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>
);
+2
View File
@@ -55,6 +55,7 @@ export function PartyOverviewPage() {
<th>
AC <InfoTip term="AC" />
</th>
<th>Gold</th>
<th>Location</th>
</tr>
</thead>
@@ -89,6 +90,7 @@ export function PartyOverviewPage() {
)}
</td>
<td>{c.armorClass ?? '—'}</td>
<td className="mono">{c.gold}</td>
<td>{c.currentLocationName ? `📍 ${c.currentLocationName}` : '—'}</td>
</tr>
);