import { useState, type ReactNode } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { useBuildBack, useBuildChoose, useBuildFinalize, useBuildOptions, useBuildRoll, useCampaign, useCampaignItems, useCampaignSpells, useCampaignWeapons, useCharacter, usePatchDiceMode } from '../api/queries'; import { Spinner, ErrorBanner } from '../components/Spinner'; import { NumberInput } from '../components/NumberInput'; import { InfoTip } from '../components/InfoTip'; import { ABILITY_LABELS, CLASS_LABELS, SKILL_LABELS, SPECIES_LABELS, extractErrorMessage, fmtMod, spellLevelLabel } from '../lib/format'; import { SPECIES_ABILITY_BONUSES, abilityModifier, speciesBonusFor } from '../lib/speciesData'; import { CLASS_SPELLCASTING_ABILITY, CLASS_HIT_DIE, CLASS_SAVE_PROFICIENCIES } from '../lib/classData'; import { ABILITY_GUIDE, CLASS_GUIDE, SKILL_GUIDE, SPECIES_GUIDE, SPECIES_SPEED, STEP_GUIDE, STEP_NAMES, hitDieToughness } from '../lib/guide'; import { speciesIcon } from '../lib/speciesIcons'; import { armorClass, hpMax, passivePerception, proficiencyBonus, saveBonus, spellAttackBonus, spellSaveDC } from '../lib/previewCalc'; import type { Ability, BuildOptions, CharacterClass, DiceMode, NamedAbility, PickGroup, Picks, Species } from '../api/types'; interface SpeciesChoices { type: 'choice' | 'wildcard'; options: string[]; } interface ClassChoices { type: 'choice' | 'wildcard' | 'reroll'; options: string[]; } interface AbilityRoll { dice: number[]; dropped: number; total: number; } interface BuildState { speciesRoll?: number; speciesChoices?: SpeciesChoices; species?: Species; halfElfBonusAbilities?: Ability[]; classRoll?: number; classChoices?: ClassChoices; characterClass?: CharacterClass; motivationRoll?: number; motivationText?: string | null; abilityRolls?: AbilityRoll[]; abilityAssignments?: Record; skillProficiencies?: { skill: string; proficient: boolean; expertise: boolean }[]; motivationChoice?: number; talents?: string[]; backgroundPicks?: Picks; appearancePicks?: Picks; equipment?: { weaponIds: string[]; itemIds: string[]; spellIds: string[] }; } const ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']; const HALF_ELF_ELIGIBLE: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS']; const ALL_SKILLS = Object.keys(SKILL_LABELS); // The six steps, in order, matching STEP_NAMES. const STEP_STAGES = [ 'ROLLING_SPECIES', 'ROLLING_CLASS', 'ROLLING_MOTIVATION', 'ASSIGNING_SCORES', 'ASSIGNING_PROFICIENCIES', 'CHOOSING_ABILITIES', 'CHOOSING_BACKGROUND', 'CHOOSING_APPEARANCE', 'CHOOSING_EQUIPMENT', ]; function randomOf(list: T[]): T { return list[Math.floor(Math.random() * list.length)]; } // `count` different entries of `list`, in random order. function randomSample(list: T[], count: number): T[] { const pool = [...list]; const picked: T[] = []; while (picked.length < count && pool.length > 0) picked.push(pool.splice(Math.floor(Math.random() * pool.length), 1)[0]); return picked; } function groupsComplete(groups: PickGroup[], picks: Picks): boolean { return groups.every((g) => { const count = (picks[g.key] || []).length; return count >= g.min && count <= g.max; }); } // How the picks will read on the sheet. Mirrors composeFromPicks on the // server, which writes the real text at finalize. function composePreview(groups: PickGroup[], picks: Picks): string[] { return groups.flatMap((g) => { const chosen = g.options.filter((o) => (picks[g.key] || []).includes(o.key)); if (chosen.length === 0) return []; const detail = chosen.length === 1 && chosen[0].text ? ` — ${chosen[0].text}` : ''; return [`${g.label}: ${chosen.map((o) => o.label).join(', ')}${detail}`]; }); } export function CharacterBuilderPage() { const { characterId = '' } = useParams(); const navigate = useNavigate(); const { data: character, isLoading, error } = useCharacter(characterId); const roll = useBuildRoll(characterId); const choose = useBuildChoose(characterId); const finalize = useBuildFinalize(characterId); const back = useBuildBack(characterId); const patchDiceMode = usePatchDiceMode(characterId); const [formError, setFormError] = useState(null); const [halfElfTouched, setHalfElfPick] = useState(null); // Species and class are picked first and only sent to the server on "Next", // so a player can click around and watch the preview before committing. const [pendingSpecies, setPendingSpecies] = useState(null); const [pendingClass, setPendingClass] = useState(null); const [assignmentsTouched, setAssignments] = useState> | null>(null); const [pendingMotivation, setPendingMotivation] = useState(null); const [talentsTouched, setTalents] = useState(null); const [backgroundTouched, setBackgroundPicks] = useState(null); const [appearanceTouched, setAppearancePicks] = useState(null); const [equipWeapons, setEquipWeapons] = useState([]); const [equipItems, setEquipItems] = useState([]); const [equipSpells, setEquipSpells] = useState([]); const [diceModeConfirmed, setDiceModeConfirmed] = useState(false); const [adjustingSkills, setAdjustingSkills] = useState(false); const [skillPicks, setSkillPicks] = useState>({}); const [expertisePicks, setExpertisePicks] = useState>({}); const campaignId = character?.campaignId; const { data: campaignData } = useCampaign(campaignId); const { data: weapons } = useCampaignWeapons(campaignId); const { data: spells } = useCampaignSpells(campaignId); const { data: items } = useCampaignItems(campaignId); const { data: options } = useBuildOptions(); if (isLoading) return ; if (error || !character) return ; if (character.buildStage === 'COMPLETE') { navigate(`/characters/${characterId}`, { replace: true }); return null; } const bs = (character.buildState || {}) as BuildState; const stage = character.buildStage; const diceMode = character.diceMode; const isDM = campaignData?.campaign.role === 'DM'; // Until the player touches a step they have come back to, it shows what // they chose last time. const halfElfPick = halfElfTouched ?? bs.halfElfBonusAbilities ?? []; const assignments = assignmentsTouched ?? bs.abilityAssignments ?? {}; const motivationPick = pendingMotivation ?? bs.motivationChoice ?? null; const talents = talentsTouched ?? bs.talents ?? []; const backgroundPicks = backgroundTouched ?? bs.backgroundPicks ?? {}; const appearancePicks = appearanceTouched ?? bs.appearancePicks ?? {}; async function safeRoll(body?: { value?: number; abilitySets?: number[][] }) { setFormError(null); try { await roll.mutateAsync(body); } catch (err) { setFormError(extractErrorMessage(err)); } } async function safeChoose(body: Record) { setFormError(null); try { await choose.mutateAsync(body); } catch (err) { setFormError(extractErrorMessage(err)); } } async function chooseDiceMode(mode: DiceMode) { setFormError(null); try { await patchDiceMode.mutateAsync(mode); setDiceModeConfirmed(true); } catch (err) { setFormError(extractErrorMessage(err)); } } const needsDiceModeChoice = stage === 'ROLLING_SPECIES' && !bs.speciesRoll && !diceModeConfirmed; // On its own step, the current pick is whatever was clicked, falling back to // what was chosen before (when the player has come back to change it). const onSpeciesStep = stage === 'ROLLING_SPECIES'; const onClassStep = stage === 'ROLLING_CLASS'; const speciesPick = pendingSpecies ?? bs.species ?? null; const classPick = pendingClass ?? bs.characterClass ?? null; const pickedSpecies = onSpeciesStep && speciesPick && bs.speciesChoices?.options.includes(speciesPick) ? speciesPick : null; const pickedClass = onClassStep && classPick && bs.classChoices?.options.includes(classPick) ? classPick : null; const speciesReady = Boolean(pickedSpecies) && (pickedSpecies !== 'HALF_ELF' || halfElfPick.length === 2); // What the preview shows: everything already locked in, with the step being // worked on replaced by whatever is currently picked there. const previewBs: BuildState = { ...bs, species: onSpeciesStep ? (pickedSpecies ?? undefined) : bs.species, halfElfBonusAbilities: onSpeciesStep ? (pickedSpecies === 'HALF_ELF' ? halfElfPick : undefined) : bs.halfElfBonusAbilities, characterClass: onClassStep ? (pickedClass ?? undefined) : bs.characterClass, abilityAssignments: stage === 'ASSIGNING_SCORES' ? undefined : bs.abilityAssignments, }; // Where Back leads from here, if anywhere. const stepOrder = STEP_STAGES.filter((s) => s !== 'ROLLING_MOTIVATION' || !campaignData?.campaign.skipMotivationRoll); const stepIndex = stepOrder.indexOf(stage); const backLabel = stage === 'CHOOSING_EQUIPMENT' && bs.equipment ? '← Change equipment' : stepIndex > 0 ? `← Back to ${STEP_NAMES[STEP_STAGES.indexOf(stepOrder[stepIndex - 1])]}` : null; async function goBack() { setFormError(null); try { await back.mutateAsync(); } catch (err) { setFormError(extractErrorMessage(err)); } } return (

Rolling Up {character.name}

Dice rolls are final once made. Your choices are not: click around, watch the preview change, and press Next when you are happy. You can go Back to change an earlier choice.

{formError && } {needsDiceModeChoice ? (
Before you roll — digital or physical dice?

Pick how this character's dice get rolled. This can't be changed once rolling starts.

) : ( <> {stage === 'ROLLING_SPECIES' && (
Step 1 — Species

{STEP_GUIDE.SPECIES}

{!bs.speciesRoll ? ( ) : ( <>
{bs.speciesRoll}

{bs.speciesChoices?.type === 'wildcard' ? ( <> Wildcard! Pick any species ) : ( 'Your roll offers these two. Click one to try it on:' )}

{bs.speciesChoices?.options.map((option) => { const s = option as Species; const bonuses = ABILITIES.filter((a) => SPECIES_ABILITY_BONUSES[s][a]).map((a) => `+${SPECIES_ABILITY_BONUSES[s][a]} ${ABILITY_LABELS[a]}`); return ( { if (pickedSpecies !== s) setHalfElfPick([]); setPendingSpecies(s); }} > {SPECIES_GUIDE[s].blurb} {SPECIES_GUIDE[s].goodFor} {bonuses.join(' · ')} {s === 'HALF_ELF' && ' · +1 to two of your choice'} · Speed {SPECIES_SPEED[s]} ft {options && Grants: {options.speciesTraits[s].map((t) => t.name).join(', ')}} ); })}
{pickedSpecies === 'HALF_ELF' && (

Half-Elves get +2 Charisma, plus +1 to two other abilities of your choice. Pick two:

{HALF_ELF_ELIGIBLE.map((a) => ( ))}
)} safeChoose(pickedSpecies === 'HALF_ELF' ? { species: pickedSpecies, halfElfBonusAbilities: halfElfPick } : { species: pickedSpecies }) } /> )}
)} {stage === 'ROLLING_CLASS' && (
Step 2 — Class

{STEP_GUIDE.CLASS}

{!bs.classRoll || bs.classChoices?.type === 'reroll' ? ( <> {bs.classChoices?.type === 'reroll' && (
{bs.classRoll}
)} ) : ( <>
{bs.classRoll}

{bs.classChoices?.type === 'wildcard' ? ( <> Wildcard! Pick any class ) : ( 'Your roll offers these two. Click one to try it on:' )}

{bs.classChoices?.options.map((option) => { const c = option as CharacterClass; const guide = CLASS_GUIDE[c]; const spellAbility = CLASS_SPELLCASTING_ABILITY[c]; return ( setPendingClass(c)} > {guide.blurb} {guide.playsLike} {hitDieToughness(CLASS_HIT_DIE[c])} (d{CLASS_HIT_DIE[c]} hit die) · Best abilities:{' '} {guide.keyAbilities.map((a) => ABILITY_LABELS[a]).join(', ')} {spellAbility ? `Casts spells with ${ABILITY_LABELS[spellAbility]}` : 'No spellcasting'} · {guide.skillCount} skills · Saves: {CLASS_SAVE_PROFICIENCIES[c].map((a) => ABILITY_LABELS[a]).join(', ')} {options && Grants: {options.classFeatures[c].map((f) => f.name).join(', ')}} ); })}

Hit die · Best abilities · Spellcasting{' '} · Saves

safeChoose({ characterClass: pickedClass })} /> )}
)} {stage === 'ROLLING_MOTIVATION' && (
Step 3 — Motivation {options && ( )}

{STEP_GUIDE.MOTIVATION}

{!options ? ( ) : ( <>
{options.motivations.map((m) => ( setPendingMotivation(m.key)}> {null} ))}
safeChoose({ motivation: motivationPick })} /> )}
)} {stage === 'ASSIGNING_SCORES' && ( safeChoose({ assignments })} rolling={roll.isPending} submitting={choose.isPending} /> )} {stage === 'ASSIGNING_PROFICIENCIES' && (
Step 5 — Skill Proficiencies

{STEP_GUIDE.SKILLS}

These were picked at random from your class's skill list. Your saving throws are set by your class too.

{!adjustingSkills ? ( <> {(bs.skillProficiencies || []).map((sp) => (
{SKILL_LABELS[sp.skill]}{' '} {ABILITY_LABELS[SKILL_GUIDE[sp.skill].ability]} {sp.expertise && expertise}
{SKILL_GUIDE[sp.skill].what}
))}
A skill is rolled with the ability shown beside it. {isDM && ( )}
) : ( <>
{ALL_SKILLS.map((skill) => ( ))}
)}
)} {stage === 'CHOOSING_ABILITIES' && (options ? ( safeChoose({ talents })} /> ) : ( ))} {stage === 'CHOOSING_BACKGROUND' && (options ? ( safeChoose({ picks: backgroundPicks })} /> ) : ( ))} {stage === 'CHOOSING_APPEARANCE' && (options ? ( safeChoose({ picks: appearancePicks })} /> ) : ( ))} {stage === 'CHOOSING_EQUIPMENT' && ( w.isStartingOption && w.minLevel <= character.level)} items={items?.filter((i) => i.isStartingOption && i.minLevel <= character.level)} spells={spells?.filter((s) => s.isStartingOption && s.level <= character.level)} equipWeapons={equipWeapons} setEquipWeapons={setEquipWeapons} equipItems={equipItems} setEquipItems={setEquipItems} equipSpells={equipSpells} setEquipSpells={setEquipSpells} onSubmit={() => safeChoose({ weaponIds: equipWeapons, itemIds: equipItems, // Spells ticked before a change of class don't carry over to a class that can't cast. spellIds: bs.characterClass && CLASS_SPELLCASTING_ABILITY[bs.characterClass] ? equipSpells : [], }) } onFinalize={async () => { try { const finalized = await finalize.mutateAsync(); navigate(`/characters/${finalized.id}`); } catch (err) { setFormError(extractErrorMessage(err)); } }} finalizing={finalize.isPending} /> )} {backLabel && (
)} )}
); } // One option the player can click to try on. Selecting it changes nothing on // the server — the step's Next button does that. function ChoiceCard({ title, tag, selected, onSelect, children, }: { title: string; tag?: string; selected: boolean; onSelect: () => void; children: ReactNode; }) { return ( ); } function StepFooter({ hint, disabled, onNext, label = 'Next →' }: { hint: string; disabled: boolean; onNext: () => void; label?: string }) { return (
{hint}
); } function GrantedAbilities({ heading, abilities }: { heading: string; abilities: NamedAbility[] }) { return (
{heading}
{abilities.map((a) => (
{a.name} automatic
{a.text}
))}
); } // Special abilities: what species and class grant, plus talents the player picks. function TalentsStep({ options, species, characterClass, talents, setTalents, submitting, onNext, }: { options: BuildOptions; species: Species | null; characterClass: CharacterClass | null; talents: string[]; setTalents: (keys: string[]) => void; submitting: boolean; onNext: () => void; }) { const need = options.talentPicks; const full = talents.length >= need; return (
Step 6 — Special Abilities

{STEP_GUIDE.ABILITIES}

{species && } {characterClass && }
Your talents — pick {need} ({talents.length}/{need})
{options.talents.map((t) => { const selected = talents.includes(t.key); return ( { if (selected) setTalents(talents.filter((k) => k !== t.key)); else if (!full) setTalents([...talents, t.key]); }} > {t.text} ); })}
); } // Background and appearance: a handful of questions, each answered by picking // from a list. The text on the sheet is composed from the picks. function PickGroupsStep({ title, intro, groups, picks, setPicks, submitting, onNext, }: { title: string; intro: string; groups: PickGroup[]; picks: Picks; setPicks: (picks: Picks) => void; submitting: boolean; onNext: () => void; }) { const complete = groupsComplete(groups, picks); const preview = composePreview(groups, picks); function toggle(group: PickGroup, key: string) { const chosen = picks[group.key] || []; let next: string[]; if (chosen.includes(key)) next = chosen.filter((k) => k !== key); else if (group.max === 1) next = [key]; // single-answer questions swap straight over else if (chosen.length < group.max) next = [...chosen, key]; else return; setPicks({ ...picks, [group.key]: next }); } function surprise() { setPicks( Object.fromEntries( groups.map((g) => { const count = Math.max(g.min, Math.min(g.max, 1 + Math.floor(Math.random() * g.max))); return [g.key, randomSample(g.options, count).map((o) => o.key)]; }) ) ); } return (
{title}

{intro}

{groups.map((g) => { const chosen = picks[g.key] || []; const only = g.max === 1 ? g.options.find((o) => o.key === chosen[0]) : undefined; return (
{g.label} {g.prompt}
{g.options.map((o) => { const selected = chosen.includes(o.key); return ( ); })}
{only?.text &&

{only.text}

}
); })} {preview.length > 0 && (
How it will read on your sheet

{preview.join('\n')}

)}
); } function RollControl({ sides, diceMode, onRoll, rolling, label, }: { sides: number; diceMode: DiceMode; onRoll: (body?: { value?: number }) => void; rolling: boolean; label: string; }) { const [value, setValue] = useState(''); if (diceMode === 'PHYSICAL') { return ( <>

{label} Roll it at the table, then type the result in below.

setValue(e.target.value)} style={{ width: 80 }} />
); } return ( <>

{label}

); } function BuildProgress({ stage }: { stage: string }) { const steps = STEP_STAGES; const idx = steps.indexOf(stage); return (
    {steps.map((s, i) => (
  1. {i < idx ? '✓' : i + 1} {STEP_NAMES[i]}
  2. ))}
); } function AssignScoresStep({ bs, diceMode, assignments, setAssignments, onRoll, onSubmit, rolling, submitting, }: { bs: BuildState; diceMode: DiceMode; assignments: Partial>; setAssignments: (a: Partial>) => void; onRoll: (body?: { abilitySets?: number[][] }) => void; onSubmit: () => void; rolling: boolean; submitting: boolean; }) { if (!bs.abilityRolls) { if (diceMode === 'PHYSICAL') { return ; } return (
Step 4 — Ability Scores

{STEP_GUIDE.SCORES}

Roll 4d6 (drop the lowest) six times — one set per ability.

); } const usedIndexes = new Set(Object.values(assignments)); const species = bs.species ?? null; const halfElfBonusAbilities = bs.halfElfBonusAbilities || []; const complete = ABILITIES.every((a) => assignments[a] !== undefined) && usedIndexes.size === 6; const keyAbilities = bs.characterClass ? CLASS_GUIDE[bs.characterClass].keyAbilities : []; // Best rolls to the class's key abilities, then the ones everybody benefits // from. A starting point the player is free to rearrange. function suggest() { const order = [...new Set([...keyAbilities, 'CON', 'DEX', 'WIS', 'STR', 'INT', 'CHA'])]; const bestFirst = bs.abilityRolls!.map((r, i) => ({ i, total: r.total })).sort((a, b) => b.total - a.total); setAssignments(Object.fromEntries(order.map((ability, rank) => [ability, bestFirst[rank].i]))); } return (
Step 4 — Assign Ability Scores

{STEP_GUIDE.SCORES}

Your six rolls {bs.characterClass && ( <> {' '} · ★ marks what a {CLASS_LABELS[bs.characterClass]} leans on most )}
{bs.abilityRolls.map((r, i) => ( {r.dice.join('+')} (drop {r.dropped}) = {r.total} ))}
{ABILITIES.map((ability) => { const assignedIndex = assignments[ability]; const rolledTotal = assignedIndex !== undefined ? bs.abilityRolls![assignedIndex].total : null; const bonus = speciesBonusFor(species, ability, halfElfBonusAbilities); const final = rolledTotal !== null ? rolledTotal + bonus : null; return (
{ABILITY_LABELS[ability]} {ABILITY_GUIDE[ability].short} {keyAbilities.includes(ability) && ★ Key for your class} {final !== null && ( {rolledTotal} {bonus ? `+${bonus}` : ''} = {final} ({abilityModifier(final) >= 0 ? '+' : ''} {abilityModifier(final)}) )}
); })}

Each line reads: your roll + species bonus = final score (modifier{' '} ). The modifier is the number you actually add to dice rolls.

); } function PhysicalAbilityRollForm({ onRoll, rolling }: { onRoll: (body?: { abilitySets?: number[][] }) => void; rolling: boolean }) { const [sets, setSets] = useState(Array.from({ length: 6 }, () => ['', '', '', ''])); const allFilled = sets.every((set) => set.every((v) => v !== '' && Number(v) >= 1 && Number(v) <= 6)); function updateDie(setIdx: number, dieIdx: number, value: string) { setSets((prev) => prev.map((set, i) => (i === setIdx ? set.map((d, j) => (j === dieIdx ? value : d)) : set))); } return (
Step 4 — Ability Scores (Physical Dice)

Roll 4d6 six times at the table, then enter each set's four results below (drop-the-lowest is applied automatically).

{sets.map((set, i) => (
Set {i + 1} {set.map((v, j) => ( updateDie(i, j, e.target.value)} style={{ width: 60 }} /> ))}
))}
); } function EquipmentStep({ bs, campaignData, weapons, items, spells, equipWeapons, setEquipWeapons, equipItems, setEquipItems, equipSpells, setEquipSpells, onSubmit, onFinalize, finalizing, }: { bs: BuildState; campaignData: { campaign: { startingItemCount: number; startingSpellCount: number } } | undefined; // All three lists arrive already narrowed to the DM's starting options. weapons: { id: string; name: string; damageDice: string; damageType: string }[] | undefined; items: { id: string; name: string; description: string | null }[] | undefined; spells: { id: string; name: string; level: number; damageDice: string | null; description: string | null }[] | undefined; equipWeapons: string[]; setEquipWeapons: (ids: string[]) => void; equipItems: string[]; setEquipItems: (ids: string[]) => void; equipSpells: string[]; setEquipSpells: (ids: string[]) => void; onSubmit: () => void; onFinalize: () => void; finalizing: boolean; }) { const maxItems = campaignData?.campaign.startingItemCount ?? 0; const maxSpells = campaignData?.campaign.startingSpellCount ?? 0; const hasSpellcasting = bs.characterClass ? Boolean(CLASS_SPELLCASTING_ABILITY[bs.characterClass]) : false; const chosen = Boolean(bs.equipment); // Weapons and items draw on the same allowance. const itemsFull = equipWeapons.length + equipItems.length >= maxItems; const nothingOffered = (weapons?.length ?? 0) + (items?.length ?? 0) === 0; function toggle(list: string[], set: (ids: string[]) => void, id: string, full: boolean) { if (list.includes(id)) set(list.filter((x) => x !== id)); else if (!full) set([...list, id]); } if (chosen) { return (
Last step — Finalize

Everything is chosen. Finalizing works out your HP and AC and locks the character in — after this there is no going back, and your special abilities, background and appearance can only be changed by your DM.

); } return (
Step 9 — Starting Equipment

{STEP_GUIDE.EQUIPMENT}

Pick up to {maxItems} item{maxItems === 1 ? '' : 's'} (weapons count) {hasSpellcasting ? ` and up to ${maxSpells} spell${maxSpells === 1 ? '' : 's'}` : ''}. The DM can give you more later.

{nothingOffered &&

The DM hasn't marked any weapons or items as starting options yet.

}
{weapons?.map((w) => ( ))} {items?.map((item) => ( ))}
{hasSpellcasting && ( <>
{spells?.map((s) => ( ))} {(!spells || spells.length === 0) &&

The DM hasn't marked any spells as starting options yet.

}
)}
); } // Live "what does this change" preview — recomputes the projected sheet as // species/class/scores/skills firm up, using the same pure formulas as the // server's calculation engine (ported in lib/previewCalc.ts). Display-only; // the server remains authoritative at finalize. function BuildPreview({ bs, level, armorBonus, assignments, options, motivation, talents, }: { bs: BuildState; level: number; armorBonus: number; assignments: Partial>; options: BuildOptions | undefined; motivation: string | null; talents: string[]; }) { const species = bs.species ?? null; const halfElfBonusAbilities = bs.halfElfBonusAbilities || []; const characterClass = bs.characterClass ?? null; const abilityFinals: Partial> = {}; for (const ability of ABILITIES) { const bonus = speciesBonusFor(species, ability, halfElfBonusAbilities); const assignedIndex = assignments[ability] ?? bs.abilityAssignments?.[ability]; const rolledTotal = assignedIndex !== undefined ? bs.abilityRolls?.[assignedIndex]?.total : undefined; if (rolledTotal !== undefined) { abilityFinals[ability] = rolledTotal + bonus; } else if (species) { abilityFinals[ability] = 10 + bonus; // baseline preview before rolling } } const dexMod = abilityFinals.DEX !== undefined ? abilityModifier(abilityFinals.DEX) : null; const conMod = abilityFinals.CON !== undefined ? abilityModifier(abilityFinals.CON) : null; const profBonus = proficiencyBonus(level || 1); const hitDie = characterClass ? CLASS_HIT_DIE[characterClass] : null; const saveProfs = characterClass ? CLASS_SAVE_PROFICIENCIES[characterClass] : []; const spellAbility = characterClass ? CLASS_SPELLCASTING_ABILITY[characterClass] : null; const perceptionProficient = Boolean(bs.skillProficiencies?.some((s) => s.skill === 'PERCEPTION')); // Species traits, class features, then picked talents — each name once, as on the sheet. const abilityList: NamedAbility[] = []; if (options) { const all = [ ...(species ? options.speciesTraits[species] : []), ...(characterClass ? options.classFeatures[characterClass] : []), ...options.talents.filter((t) => talents.includes(t.key)), ]; for (const ability of all) if (!abilityList.some((a) => a.name === ability.name)) abilityList.push(ability); } const wisMod = abilityFinals.WIS !== undefined ? abilityModifier(abilityFinals.WIS) : null; return (
Live Preview
{!species && !characterClass && (

This fills in as you go. Click a species or class to see what it would do — nothing is locked in until you press Next.

)} {species && (

{SPECIES_LABELS[species]} {Object.entries({ STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 }) .map(([a]) => [a as Ability, speciesBonusFor(species, a as Ability, halfElfBonusAbilities)] as const) .filter(([, bonus]) => bonus !== 0) .map(([a, bonus]) => ( {fmtMod(bonus)} {a} ))}

)} {characterClass && (

{CLASS_LABELS[characterClass]} · d{hitDie} hit die {saveProfs && saveProfs.length > 0 && ( · {saveProfs.map((a) => ABILITY_LABELS[a]).join('/')} saves )}

)} {Object.keys(abilityFinals).length > 0 && (
{ABILITIES.map((a) => abilityFinals[a] !== undefined ? (
{a} {abilityFinals[a]} {fmtMod(abilityModifier(abilityFinals[a]!))}
) : null )}
)}
AC
{dexMod !== null ? armorClass(dexMod, armorBonus) : '—'}
Max HP
{hitDie && conMod !== null ? hpMax(level || 1, hitDie, conMod) : '—'}
Initiative
{dexMod !== null ? fmtMod(dexMod) : '—'}
Prof. Bonus
{fmtMod(profBonus)}
Speed
{species ? SPECIES_SPEED[species] : '—'}
{characterClass && saveProfs.length > 0 && ( <>
Saving Throws
{ABILITIES.map((a) => { const mod = abilityFinals[a] !== undefined ? abilityModifier(abilityFinals[a]!) : null; if (mod === null) return null; const proficient = saveProfs.includes(a); return (
{ABILITY_LABELS[a]} {proficient && prof} {fmtMod(saveBonus(mod, proficient, profBonus))}
); })} )} {wisMod !== null && ( <>
Passive Perception {passivePerception(perceptionProficient ? profBonus + wisMod : wisMod)}
)} {spellAbility && abilityFinals[spellAbility] !== undefined && ( <>
Spellcasting ({ABILITY_LABELS[spellAbility]})

Save DC {spellSaveDC(profBonus, abilityModifier(abilityFinals[spellAbility]!))} · Attack{' '} {fmtMod(spellAttackBonus(profBonus, abilityModifier(abilityFinals[spellAbility]!)))}

)} {bs.skillProficiencies && bs.skillProficiencies.length > 0 && ( <>
Skills
{bs.skillProficiencies.map((sp) => ( {SKILL_LABELS[sp.skill]} ))}
)} {abilityList.length > 0 && ( <>
Special Abilities
{abilityList.map((a) => ( {a.name} ))}
)} {motivation && ( <>
Motivation

{motivation}

)}
); }