import { useState, type FormEvent } from 'react'; import { Link, useNavigate, useParams } from 'react-router-dom'; import { useCharacter, usePatchCharacter, useCampaignWeapons, useAssignWeapon, usePatchCharacterWeapon, useRemoveCharacterWeapon, useCampaignItems, useAssignItem, usePatchInventoryItem, useRemoveInventoryItem, useCampaignSpells, useAssignSpell, usePatchCharacterSpell, useRemoveCharacterSpell, useGoldLedger, useAdjustGold, useExchangeCoins, useCampaignCharacters, useGive, type Gift, useCharacterNotes, useCreateNote, useCampaign, useCampaigns, useCopyCharacter, useCampaignLocations, } from '../api/queries'; import { useAuth } from '../auth/AuthContext'; import { useCampaignSocket } from '../hooks/useCampaignSocket'; import { Spinner, ErrorBanner } from '../components/Spinner'; import { NumberInput } from '../components/NumberInput'; import { JumpNav } from '../components/JumpNav'; import { useRememberCampaign } from '../lib/lastCampaign'; import { HpBar } from '../components/HpBar'; import { DeathSaves } from '../components/DeathSaves'; import { GearInForce } from '../components/CharacterPanel'; import { effectsSummary } from '../lib/gear'; import { InfoTip } from '../components/InfoTip'; import { usePagination, Pagination } from '../components/Paginated'; import { ABILITY_LABELS, CLASS_LABELS, COINS, COIN_FIELD, COIN_LABELS, COIN_VALUE, CURRENCIES, SKILL_LABELS, SPECIES_LABELS, fmtMod, extractErrorMessage, formatMoney, formatPurse, purseWorthInGold, spellLevelLabel, } from '../lib/format'; import { speciesIcon } from '../lib/speciesIcons'; import { hpMax as previewHpMax, scaledDamageDice, MAX_GEAR_LEVEL } from '../lib/previewCalc'; import { CLASS_HIT_DIE } from '../lib/classData'; import type { Ability, CharacterDetail, Coin, Currency } 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 ( ); } function RequiresLevel({ level }: { level: number }) { return ( Requires level {level} ); } // 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(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; for coins the id is which coin. const [kind, id] = what.split(':'); const coin = (kind === 'gold' ? id : 'GOLD') as Currency; const heldWeapon = character.weapons.find((w) => w.weaponId === id); const heldItem = character.inventoryItems.find((i) => i.itemId === id); // A gift of coins is paid from the whole purse, with change, so any coin // the purse is worth at least one of can be given. Cash is only paid in cash. const held = (c: Currency) => character[COIN_FIELD[c]] ?? 0; const purseInCopper = COINS.reduce((sum, c) => sum + held(c) * COIN_VALUE[c], 0); const affordable = (c: Currency) => (c === 'CASH' ? held(c) : Math.floor(purseInCopper / COIN_VALUE[c])); const coinsHeld = CURRENCIES.filter((c) => affordable(c) > 0); const max = kind === 'gold' ? affordable(coin) : 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 = coinsHeld.length === 0 && character.weapons.length + character.inventoryItems.length + character.spells.length === 0; function handleGive() { const gift: Gift | null = kind === 'gold' ? { kind, amount: count, currency: coin } : 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 (
Give to Another Character

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.

{nothingToGive ? (

{character.name} has nothing to give yet.

) : (
{what && kind !== 'spell' && ( setAmount(e.target.value)} style={{ width: 90 }} /> )}
)} {done &&

✓ {done}

}
); } export function CharacterSheetPage() { const { characterId = '' } = useParams(); const { user } = useAuth(); const { data: character, isLoading, error } = useCharacter(characterId); useRememberCampaign(character?.campaignId); const patchCharacter = usePatchCharacter(characterId); useCampaignSocket(character?.campaignId); 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, Boolean(character) && !character?.restricted); const { data: locations } = useCampaignLocations(character?.campaignId); const { data: notes } = useCharacterNotes(characterId); const assignWeapon = useAssignWeapon(characterId); const patchWeapon = usePatchCharacterWeapon(characterId); const removeWeapon = useRemoveCharacterWeapon(characterId); const assignItem = useAssignItem(characterId); const patchItem = usePatchInventoryItem(characterId); const removeItem = useRemoveInventoryItem(characterId); const assignSpell = useAssignSpell(characterId); const patchSpell = usePatchCharacterSpell(characterId); const removeSpell = useRemoveCharacterSpell(characterId); const adjustGold = useAdjustGold(characterId); const exchangeCoins = useExchangeCoins(characterId); const createNote = useCreateNote(); const { data: campaigns } = useCampaigns(); const copyCharacter = useCopyCharacter(characterId); const navigate = useNavigate(); const [hpDelta, setHpDelta] = useState(''); const [pickedItemId, setPickedItemId] = useState(''); const [goldAmount, setGoldAmount] = useState(''); const [goldReason, setGoldReason] = useState(''); const [goldCurrency, setGoldCurrency] = useState('GOLD'); const [exchangeAmount, setExchangeAmount] = useState(''); const [exchangeFrom, setExchangeFrom] = useState('GOLD'); const [exchangeTo, setExchangeTo] = useState('SILVER'); const [noteBody, setNoteBody] = useState(''); const [pickedWeaponId, setPickedWeaponId] = useState(''); const [pickedSpellId, setPickedSpellId] = useState(''); const [copyTargetId, setCopyTargetId] = useState(''); const [formError, setFormError] = useState(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 ; if (error || !character) return ; const isDM = campaignData?.campaign.role === 'DM'; const isOwner = character.userId === user?.id; const canEdit = isDM || isOwner; if (character.buildStage !== 'COMPLETE') { return (

{character.name} hasn't finished being built yet.

Continue Build
); } const sheet = character.sheet!; function applyHpDelta(sign: 1 | -1) { const amount = Number(hpDelta); if (!amount) return; const next = character!.currentHp + sign * amount; setFormError(null); // Healing is refused for a character who has died. patchCharacter.mutate({ currentHp: next }, { onError: (err) => setFormError(extractErrorMessage(err)) }); setHpDelta(''); } function recomputeMaxHp() { if (!character || !character.characterClass) return; const hitDie = CLASS_HIT_DIE[character.characterClass]; const conMod = sheet.abilities.CON.modifier; const newMax = previewHpMax(character.level, hitDie, conMod); patchCharacter.mutate({ currentHp: newMax }); } async function handleAssignItem() { if (!pickedItemId) return; try { await assignItem.mutateAsync({ itemId: pickedItemId }); setPickedItemId(''); } catch (err) { setFormError(extractErrorMessage(err)); } } // Equipping can be refused (too much on already). The reason goes in the // banner at the top, so the page goes there too. const equipResult = { onSuccess: () => setFormError(null), onError: (err: unknown) => { setFormError(extractErrorMessage(err)); window.scrollTo({ top: 0, behavior: 'smooth' }); }, }; 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, currency: goldCurrency, reason: goldReason.trim() || undefined }); setGoldAmount(''); setGoldReason(''); } catch (err) { setFormError(extractErrorMessage(err)); } } async function handleExchange() { const amount = Math.floor(Number(exchangeAmount)); if (!(amount > 0) || exchangeFrom === exchangeTo) return; setFormError(null); try { await exchangeCoins.mutateAsync({ from: exchangeFrom, to: exchangeTo, amount }); setExchangeAmount(''); } catch (err) { setFormError(extractErrorMessage(err)); } } async function handleAddNote(e: FormEvent) { e.preventDefault(); if (!noteBody.trim()) return; await createNote.mutateAsync({ characterId, body: noteBody, visibility: 'SHARED' }); setNoteBody(''); } async function handleAssignWeapon() { if (!pickedWeaponId) return; try { await assignWeapon.mutateAsync({ weaponId: pickedWeaponId }); setPickedWeaponId(''); } catch (err) { setFormError(extractErrorMessage(err)); } } async function handleAssignSpell() { if (!pickedSpellId) return; try { await assignSpell.mutateAsync({ spellId: pickedSpellId }); setPickedSpellId(''); } catch (err) { setFormError(extractErrorMessage(err)); } } 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 && !c.archivedAt) ?? []; const assignedWeaponIds = new Set(character.weapons.map((w) => w.weaponId)); const assignedSpellIds = new Set(character.spells.map((s) => s.spellId)); return (

{character.name}

{character.species && SPECIES_LABELS[character.species]} {character.characterClass && CLASS_LABELS[character.characterClass]} · Level{' '} {character.level} {character.motivation && ` · "${character.motivation}"`} {character.currentLocation && ` · 📍 ${character.currentLocation.name}`}

← Back to Campaign
{formError && }
HP {character.currentHp}/{sheet.hp.max} {character.tempHp > 0 && +{character.tempHp} temp}
AC {sheet.armorClass}
Initiative {fmtMod(sheet.initiative)}
Speed {sheet.speed}
Prof. Bonus {fmtMod(sheet.proficiencyBonus)}
Passive Perception {sheet.passivePerception}
setFormError(extractErrorMessage(err))} /> {canEdit && (
setHpDelta(e.target.value)} style={{ width: 100 }} /> {/* Armor is an equipped item now; this is the DM's own adjustment on top. */} {isDM && ( )}
)} {isDM && (
)} {!isDM && character.currentLocation && (

📍 Currently at: {character.currentLocation.name}

)} {(sheet.gear.effects.length > 0 || sheet.gear.notes.length > 0) && (
From Equipped Gear

Already counted in every number on this sheet. Take something off and its line goes.

)}
Ability Scores
{(Object.keys(sheet.abilities) as Ability[]).map((ability) => (
{ABILITY_LABELS[ability]} {sheet.abilities[ability].final} {fmtMod(sheet.abilities[ability].modifier)}
))}
Saving Throws
{(Object.keys(sheet.saves) as Ability[]).map((ability) => (
{ABILITY_LABELS[ability]} {sheet.saves[ability].proficient && prof} {fmtMod(sheet.saves[ability].bonus)}
))}
Skills
{Object.entries(sheet.skills).map(([skill, detail]) => (
{SKILL_LABELS[skill]}{' '} {detail.expertise ? ( expertise ) : detail.proficient ? ( prof ) : null} {fmtMod(detail.bonus)}
))}
{sheet.spellcasting && (
Spellcasting ({ABILITY_LABELS[sheet.spellcasting.ability]})

Save DC {sheet.spellcasting.saveDC} · Attack Bonus{' '} {fmtMod(sheet.spellcasting.attackBonus)}

)}
Weapons
{weaponsPage.pageItems.map((cw) => (
{cw.weapon.name} Lv {cw.level} · {cw.scaledDamageDice} {cw.weapon.damageType} · x{cw.quantity} {!cw.usable && } {effectsSummary(cw.weapon.effects, cw.weapon.effectNote) && (
✦ While equipped: {effectsSummary(cw.weapon.effects, cw.weapon.effectNote)}
)}
{canEdit && (
{isDM && ( <> patchWeapon.mutate({ weaponId: cw.weaponId, level })} /> )}
)}
))} {character.weapons.length === 0 &&

No weapons. The DM hands these out.

} {isDM && (
)}
{campaignSpells && campaignSpells.length > 0 && (
Spells Known
{spellsPage.pageItems.map((cs) => (
{cs.spell.name} {spellLevelLabel(cs.spell.level)} {cs.spell.damageDice && ` · ${cs.spell.damageDice} damage`} {!cs.usable && } {cs.spell.description &&
{cs.spell.description}
}
{canEdit && (
{isDM && ( )}
)}
))} {character.spells.length === 0 &&

No spells known. The DM grants these.

} {isDM && (
)}
)} {character.restricted && (

This is another player's character. You can see what the party sees across the table; what they carry and how much gold they have is theirs to share.

)} {!character.restricted && ( <>
Inventory
{itemsPage.pageItems.map((held) => (
{held.item.name} Lv {held.level} {held.scaledDamageDice && ` · ${held.scaledDamageDice}`} · x{held.quantity} {!held.usable && } {effectsSummary(held.item.effects, held.item.effectNote) && (
✦ While equipped: {effectsSummary(held.item.effects, held.item.effectNote)}
)} {held.item.description && (
{held.item.description}
)}
{canEdit && (
{isDM && ( <> patchItem.mutate({ itemId: held.itemId, level })} /> )}
)}
))} {character.inventoryItems.length === 0 &&

Nothing carried. The DM hands out items.

} {isDM && (
)} {isDM && campaignItems?.length === 0 && (

The item pool is empty — add items on the campaign page first.

)}
Money {formatPurse(character)}

1 gold = 10 silver = 100 copper. Worth {purseWorthInGold(character)} gold in all. Spending and giving make change for you: if you are short of a coin, a bigger one is broken. Cash ($) is kept apart: it is never exchanged for coins.

{canEdit && (
setGoldAmount(e.target.value)} style={{ width: 100 }} /> setGoldReason(e.target.value)} style={{ flex: 1, minWidth: 160 }} />
)} {canEdit && (
Exchange setExchangeAmount(e.target.value)} style={{ width: 100 }} /> into
)}
{goldLedger?.length === 0 &&

No transactions yet.

} {ledgerPage.pageItems.map((t) => (
{t.amount > 0 ? '+' : '−'} {formatMoney(Math.abs(t.amount), t.currency ?? 'GOLD')} {t.reason || (t.amount > 0 ? 'Gained' : 'Spent')}
{t.createdBy ? `${t.createdBy.displayName} · ` : ''} {new Date(t.createdAt).toLocaleString()}
{formatMoney(t.balanceAfter, t.currency ?? 'GOLD')}
))}
)} {/* 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]) => (
{title} {isDM && DM can edit}
{isDM ? (