Files
the-sunken-reach/frontend/src/pages/CharacterBuilderPage.tsx
T
joshuaandClaude Opus 5.5 18d9e7301c V1.23.0: every subclass, 43 species, the Artificer, and the road to level 20
- All 123 official subclasses (2014 books and the 2024 Player's Handbook), each
  with its book and features up to level 20; one file per class
- The builder has a subclass step after the class: pick one, let a die suggest
  one, or decide later; its gifts arrive at the class's choice level
- 2024 updates (Wild Heart, Warrior of the Elements) offer a one-click switch
- The Road Ahead: a level 1-20 timeline on every sheet and in the builder
- 33 new species (2024 Aasimar and Goliath, Monsters of the Multiverse) with
  chosen +2/+1 or +1/+1/+1 bonuses; species roll is now a d8 by family
- The Artificer: class, half-caster slots from level 1, features, Flash of Genius
- Class tables and counters run to level 20; a fifth Boon, Resolve

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:02:51 +02:00

1769 lines
72 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, type ReactNode } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useRememberCampaign } from '../lib/lastCampaign';
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, SPECIES_FLEXIBLE_BONUS, abilityModifier, bonusChoicesValid, speciesBonusFor, type BonusChoices } 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 { ProgressionTimeline } from '../components/ProgressionTimeline';
import { armorClass, hpMax, passivePerception, proficiencyBonus, saveBonus, spellAttackBonus, spellSaveDC } from '../lib/previewCalc';
import type { Ability, BuildOptions, CharacterClass, DiceMode, NamedAbility, PickGroup, Picks, ScoreMethod, Species, SubclassSummary } from '../api/types';
interface SpeciesChoices {
type: 'choice' | 'wildcard';
options: string[];
}
interface ClassChoices {
type: 'choice' | 'wildcard' | 'reroll';
options: string[];
canReroll?: boolean; // a 7: the Artificer, or one reroll
}
// A rolled score; the standard array and point buy come as scores alone, no dice.
interface AbilityRoll {
dice: number[];
dropped: number | null;
total: number;
}
interface BuildState {
speciesRoll?: number;
speciesChoices?: SpeciesChoices;
species?: Species;
halfElfBonusAbilities?: Ability[]; // a build begun before chosen bonuses were general
speciesBonusChoices?: BonusChoices;
classRoll?: number;
classChoices?: ClassChoices;
characterClass?: CharacterClass;
subclassRoll?: number;
subclassSuggestion?: string;
subclass?: string | null;
motivationRoll?: number;
motivationText?: string | null;
abilityRolls?: AbilityRoll[];
abilityAssignments?: Record<Ability, number>;
pointBuy?: Record<Ability, number>;
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'];
// Point buy, as the server checks it (game/buildFlow.js): every score starts
// at 8, and raising it to 15 at most spends from a budget of 27.
const POINT_BUY_BUDGET = 27;
const POINT_BUY_COSTS: Record<number, number> = { 8: 0, 9: 1, 10: 2, 11: 3, 12: 4, 13: 5, 14: 7, 15: 9 };
const ALL_SKILLS = Object.keys(SKILL_LABELS);
// The steps, in order, matching STEP_NAMES.
const STEP_STAGES = [
'ROLLING_SPECIES',
'ROLLING_CLASS',
'CHOOSING_SUBCLASS',
'ROLLING_MOTIVATION',
'ASSIGNING_SCORES',
'ASSIGNING_PROFICIENCIES',
'CHOOSING_ABILITIES',
'CHOOSING_BACKGROUND',
'CHOOSING_APPEARANCE',
'CHOOSING_EQUIPMENT',
];
function randomOf<T>(list: T[]): T {
return list[Math.floor(Math.random() * list.length)];
}
// `count` different entries of `list`, in random order.
function randomSample<T>(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);
useRememberCampaign(character?.campaignId);
const roll = useBuildRoll(characterId);
const choose = useBuildChoose(characterId);
const finalize = useBuildFinalize(characterId);
const back = useBuildBack(characterId);
const patchDiceMode = usePatchDiceMode(characterId);
const [formError, setFormError] = useState<string | null>(null);
const [bonusTouched, setBonusPick] = useState<BonusChoices | null>(null);
const [pendingSubclass, setPendingSubclass] = useState<string | null | undefined>(undefined);
// 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<Species | null>(null);
const [pendingClass, setPendingClass] = useState<CharacterClass | null>(null);
const [assignmentsTouched, setAssignments] = useState<Partial<Record<Ability, number>> | null>(null);
const [pendingMotivation, setPendingMotivation] = useState<number | null>(null);
const [talentsTouched, setTalents] = useState<string[] | null>(null);
const [backgroundTouched, setBackgroundPicks] = useState<Picks | null>(null);
const [appearanceTouched, setAppearancePicks] = useState<Picks | null>(null);
const [equipWeapons, setEquipWeapons] = useState<string[]>([]);
const [equipItems, setEquipItems] = useState<string[]>([]);
const [equipSpells, setEquipSpells] = useState<string[]>([]);
const [diceModeConfirmed, setDiceModeConfirmed] = useState(false);
const [adjustingSkills, setAdjustingSkills] = useState(false);
const [skillPicks, setSkillPicks] = useState<Record<string, boolean>>({});
const [expertisePicks, setExpertisePicks] = useState<Record<string, boolean>>({});
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 <Spinner label="Preparing the dice…" />;
if (error || !character) return <ErrorBanner message="Could not load this character." />;
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 savedBonuses: BonusChoices = bs.speciesBonusChoices ?? Object.fromEntries((bs.halfElfBonusAbilities ?? []).map((a) => [a, 1]));
const bonusPick = bonusTouched ?? savedBonuses;
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<string, unknown>) {
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));
}
}
// Only asked when the campaign leaves the dice to each character.
const needsDiceModeChoice = character.diceModeChoosable && 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) && bonusChoicesValid(pickedSpecies, bonusPick);
// 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,
speciesBonusChoices: onSpeciesStep ? bonusPick : savedBonuses,
characterClass: onClassStep ? (pickedClass ?? undefined) : bs.characterClass,
abilityAssignments: stage === 'ASSIGNING_SCORES' ? undefined : bs.abilityAssignments,
};
// Where Back leads from here, if anywhere. A campaign can leave the
// subclass and the motivation out.
const stepOrder = STEP_STAGES.filter(
(s) =>
(s !== 'ROLLING_MOTIVATION' || !campaignData?.campaign.skipMotivationRoll) &&
(s !== 'CHOOSING_SUBCLASS' || campaignData?.campaign.subclassesEnabled !== false)
);
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 (
<div className="build-layout">
<div>
<div className="page-header">
<div>
<h1>Rolling Up {character.name}</h1>
<p className="subtitle">
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.
</p>
</div>
</div>
<BuildProgress stage={stage} steps={stepOrder} />
{formError && <ErrorBanner message={formError} />}
{needsDiceModeChoice ? (
<div className="card mt-md text-center">
<div className="card-title">
<span>
Before you roll — digital or physical dice? <InfoTip term="DICE_MODE" />
</span>
</div>
<p>Pick how this character's dice get rolled. This can't be changed once rolling starts.</p>
<div className="flex-row flex-wrap" style={{ justifyContent: 'center' }}>
<button className="btn btn-primary btn-lg" onClick={() => chooseDiceMode('DIGITAL')} disabled={patchDiceMode.isPending}>
🎲 Digital Dice
<span className="subtitle" style={{ display: 'block', fontSize: '0.75rem' }}>The app rolls for you</span>
</button>
<button className="btn btn-lg" onClick={() => chooseDiceMode('PHYSICAL')} disabled={patchDiceMode.isPending}>
🎯 Physical Dice
<span className="subtitle" style={{ display: 'block', fontSize: '0.75rem' }}>You roll at the table, type in the result</span>
</button>
</div>
</div>
) : (
<>
{stage === 'ROLLING_SPECIES' && (
<div className="card mt-md text-center">
<div className="card-title">Species</div>
<p className="step-intro">{STEP_GUIDE.SPECIES}</p>
{!bs.speciesRoll ? (
<RollControl sides={8} diceMode={diceMode} onRoll={safeRoll} rolling={roll.isPending} label="Roll a d8 to see which family of species you can choose from." />
) : (
<>
<div className="roll-result animate">{bs.speciesRoll}</div>
<p className="mt-sm">
{bs.speciesChoices?.type === 'wildcard' ? (
<>
Wildcard! Pick any species <InfoTip term="WILDCARD" />
</>
) : (
'Your roll offers these. Click one to try it on:'
)}
</p>
<div className="choice-grid">
{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 (
<ChoiceCard
key={s}
title={`${speciesIcon(s)} ${SPECIES_LABELS[s]}`}
selected={pickedSpecies === s}
onSelect={() => {
if (pickedSpecies !== s) setBonusPick({});
setPendingSpecies(s);
}}
>
<span className="choice-card-blurb">{SPECIES_GUIDE[s].blurb}</span>
<span>{SPECIES_GUIDE[s].goodFor}</span>
<span className="choice-card-facts">
{bonuses.join(' · ')}
{SPECIES_FLEXIBLE_BONUS[s] && `${bonuses.length ? ' · ' : ''}${flexibleLabel(s)}`} · Speed {SPECIES_SPEED[s]} ft
</span>
{options && <span className="choice-card-facts">Grants: {options.speciesTraits[s].map((t) => t.name).join(', ')}</span>}
</ChoiceCard>
);
})}
</div>
{pickedSpecies && SPECIES_FLEXIBLE_BONUS[pickedSpecies] && (
<SpeciesBonusPicker key={pickedSpecies} species={pickedSpecies} value={bonusPick} onChange={setBonusPick} />
)}
<StepFooter
hint={
!pickedSpecies
? 'Nothing is locked in until you press Next.'
: !speciesReady
? `Choose where the ${SPECIES_LABELS[pickedSpecies]} bonuses go.`
: `${SPECIES_LABELS[pickedSpecies]} selected — you can still change your mind.`
}
disabled={!speciesReady || choose.isPending}
onNext={() =>
safeChoose(
pickedSpecies && SPECIES_FLEXIBLE_BONUS[pickedSpecies] ? { species: pickedSpecies, bonusChoices: bonusPick } : { species: pickedSpecies }
)
}
/>
</>
)}
</div>
)}
{stage === 'ROLLING_CLASS' && (
<div className="card mt-md text-center">
<div className="card-title">Class</div>
<p className="step-intro">{STEP_GUIDE.CLASS}</p>
{!bs.classRoll || bs.classChoices?.type === 'reroll' ? (
<>
{bs.classChoices?.type === 'reroll' && (
<div className="roll-result animate mb-2">{bs.classRoll}</div>
)}
<RollControl
sides={8}
diceMode={diceMode}
onRoll={safeRoll}
rolling={roll.isPending}
label={bs.classChoices?.type === 'reroll' ? 'You rolled a 7 — reroll once!' : 'Roll a d8 to see which classes you can choose between.'}
/>
</>
) : (
<>
<div className="roll-result animate">{bs.classRoll}</div>
<p className="mt-sm">
{bs.classChoices?.type === 'wildcard' ? (
<>
Wildcard! Pick any class <InfoTip term="WILDCARD" />
</>
) : (
bs.classChoices?.canReroll
? 'A 7: the Artificer is yours to take, or you may roll once more (and keep what that gives).'
: 'Your roll offers these. Click one to try it on:'
)}
</p>
<div className="choice-grid">
{bs.classChoices?.options.map((option) => {
const c = option as CharacterClass;
const guide = CLASS_GUIDE[c];
const spellAbility = CLASS_SPELLCASTING_ABILITY[c];
return (
<ChoiceCard
key={c}
title={CLASS_LABELS[c]}
tag={`${guide.difficulty} to play`}
selected={pickedClass === c}
onSelect={() => setPendingClass(c)}
>
<span className="choice-card-blurb">{guide.blurb}</span>
<span>{guide.playsLike}</span>
<span className="choice-card-facts">
{hitDieToughness(CLASS_HIT_DIE[c])} (d{CLASS_HIT_DIE[c]} hit die) · Best abilities:{' '}
{guide.keyAbilities.map((a) => ABILITY_LABELS[a]).join(', ')}
</span>
<span className="choice-card-facts">
{spellAbility ? `Casts spells with ${ABILITY_LABELS[spellAbility]}` : 'No spellcasting'} · {guide.skillCount} skills ·
Saves: {CLASS_SAVE_PROFICIENCIES[c].map((a) => ABILITY_LABELS[a]).join(', ')}
</span>
{options && <span className="choice-card-facts">Grants: {options.classFeatures[c].map((f) => f.name).join(', ')}</span>}
</ChoiceCard>
);
})}
</div>
{bs.classChoices?.canReroll && (
<div className="mt-md">
<RollControl sides={8} diceMode={diceMode} onRoll={safeRoll} rolling={roll.isPending} label="Or reroll the d8 — the new roll stands." />
</div>
)}
<p className="subtitle" style={{ textAlign: 'left' }}>
Hit die <InfoTip term="HIT_DICE" /> · Best abilities <InfoTip term="KEY_ABILITY" /> · Spellcasting{' '}
<InfoTip term="SPELLCASTING" /> · Saves <InfoTip term="SAVE_PROFICIENCY" />
</p>
<StepFooter
hint={
pickedClass
? `${CLASS_LABELS[pickedClass]} selected — you can still change your mind.`
: 'Nothing is locked in until you press Next.'
}
disabled={!pickedClass || choose.isPending}
onNext={() => safeChoose({ characterClass: pickedClass })}
/>
</>
)}
</div>
)}
{stage === 'CHOOSING_SUBCLASS' && bs.characterClass && (
<SubclassStep
characterClass={bs.characterClass}
subclasses={options?.subclasses[bs.characterClass] ?? []}
subclassLevel={options?.subclassLevels[bs.characterClass] ?? 3}
roll={bs.subclassRoll}
suggestion={bs.subclassSuggestion}
picked={pendingSubclass !== undefined ? pendingSubclass : (bs.subclass ?? null)}
onPick={setPendingSubclass}
diceMode={diceMode}
onRoll={safeRoll}
rolling={roll.isPending}
submitting={choose.isPending}
onSubmit={(subclass) => safeChoose({ subclass })}
/>
)}
{stage === 'ROLLING_MOTIVATION' && (
<div className="card mt-md text-center">
<div className="card-title">
<span>Motivation</span>
{options && (
<button className="btn" onClick={() => setPendingMotivation(randomOf(options.motivations.filter((m) => m.key !== motivationPick)).key)}>
🎲 Surprise me
</button>
)}
</div>
<p className="step-intro">{STEP_GUIDE.MOTIVATION}</p>
{!options ? (
<Spinner label="Fetching the options…" />
) : (
<>
<div className="choice-grid">
{options.motivations.map((m) => (
<ChoiceCard key={m.key} title={m.label} tag="Pick" selected={motivationPick === m.key} onSelect={() => setPendingMotivation(m.key)}>
{null}
</ChoiceCard>
))}
</div>
<StepFooter
hint={motivationPick ? 'You can still change your mind.' : 'Pick one, or let “Surprise me” choose.'}
disabled={!motivationPick || choose.isPending}
onNext={() => safeChoose({ motivation: motivationPick })}
/>
</>
)}
</div>
)}
{stage === 'ASSIGNING_SCORES' && (
<AssignScoresStep
bs={bs}
diceMode={diceMode}
method={campaignData?.campaign.abilityScoreMethod ?? 'ROLL_4D6'}
onPointBuy={(pointBuy) => safeChoose({ pointBuy })}
assignments={assignments}
setAssignments={setAssignments}
onRoll={safeRoll}
onSubmit={() => safeChoose({ assignments })}
rolling={roll.isPending}
submitting={choose.isPending}
/>
)}
{stage === 'ASSIGNING_PROFICIENCIES' && (
<div className="card mt-md">
<div className="card-title">
Skill Proficiencies <InfoTip term="SKILL_BONUS" />
</div>
<p className="step-intro">{STEP_GUIDE.SKILLS}</p>
<p className="subtitle">
These were picked at random from your class's skill list. Your saving throws are set by your class too.
</p>
{!adjustingSkills ? (
<>
{(bs.skillProficiencies || []).map((sp) => (
<div key={sp.skill} style={{ padding: '0.35rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<strong>{SKILL_LABELS[sp.skill]}</strong>{' '}
<span className="badge">{ABILITY_LABELS[SKILL_GUIDE[sp.skill].ability]}</span>
{sp.expertise && <span className="badge badge-dm" style={{ marginLeft: 4 }}>expertise</span>}
<InfoTip text={ABILITY_GUIDE[SKILL_GUIDE[sp.skill].ability].affects} label={`What ${ABILITY_LABELS[SKILL_GUIDE[sp.skill].ability]} affects`} />
<div style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>{SKILL_GUIDE[sp.skill].what}</div>
</div>
))}
<div className="step-footer">
<span className="subtitle">A skill is rolled with the ability shown beside it.</span>
<span className="flex-row">
{isDM && (
<button
className="btn btn-ghost"
onClick={() => {
const picks: Record<string, boolean> = {};
const expertise: Record<string, boolean> = {};
for (const sp of bs.skillProficiencies || []) {
picks[sp.skill] = true;
expertise[sp.skill] = sp.expertise;
}
setSkillPicks(picks);
setExpertisePicks(expertise);
setAdjustingSkills(true);
}}
>
DM: Adjust picks
</button>
)}
<button className="btn btn-primary btn-lg" onClick={() => safeChoose({})} disabled={choose.isPending}>
Next →
</button>
</span>
</div>
</>
) : (
<>
<div className="grid grid-cols-3">
{ALL_SKILLS.map((skill) => (
<label key={skill} className="checkbox-row" style={{ flexDirection: 'column', alignItems: 'flex-start', gap: 2 }}>
<span className="flex-row">
<input
type="checkbox"
checked={Boolean(skillPicks[skill])}
onChange={(e) => setSkillPicks((p) => ({ ...p, [skill]: e.target.checked }))}
/>
{SKILL_LABELS[skill]} <InfoTip text={SKILL_GUIDE[skill].what} label={`What ${SKILL_LABELS[skill]} is`} />
</span>
{skillPicks[skill] && (
<span className="flex-row" style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginLeft: '1.5rem' }}>
<input
type="checkbox"
checked={Boolean(expertisePicks[skill])}
onChange={(e) => setExpertisePicks((p) => ({ ...p, [skill]: e.target.checked }))}
/>
expertise
</span>
)}
</label>
))}
</div>
<button
className="btn btn-primary mt-md"
onClick={async () => {
await safeChoose({
skillProficiencies: ALL_SKILLS.filter((s) => skillPicks[s]).map((s) => ({
skill: s,
proficient: true,
expertise: Boolean(expertisePicks[s]),
})),
});
setAdjustingSkills(false); // coming back to this step shows the saved picks
}}
>
Save Skills & Next →
</button>
</>
)}
</div>
)}
{stage === 'CHOOSING_ABILITIES' &&
(options ? (
<TalentsStep
options={options}
species={bs.species ?? null}
characterClass={bs.characterClass ?? null}
talents={talents}
setTalents={setTalents}
submitting={choose.isPending}
onNext={() => safeChoose({ talents })}
/>
) : (
<Spinner label="Fetching the options…" />
))}
{stage === 'CHOOSING_BACKGROUND' &&
(options ? (
<PickGroupsStep
title="Background"
intro={STEP_GUIDE.BACKGROUND}
groups={options.background}
picks={backgroundPicks}
setPicks={setBackgroundPicks}
submitting={choose.isPending}
onNext={() => safeChoose({ picks: backgroundPicks })}
/>
) : (
<Spinner label="Fetching the options…" />
))}
{stage === 'CHOOSING_APPEARANCE' &&
(options ? (
<PickGroupsStep
title="Appearance"
intro={STEP_GUIDE.APPEARANCE}
groups={options.appearance}
picks={appearancePicks}
setPicks={setAppearancePicks}
submitting={choose.isPending}
onNext={() => safeChoose({ picks: appearancePicks })}
/>
) : (
<Spinner label="Fetching the options…" />
))}
{stage === 'CHOOSING_EQUIPMENT' && (
<EquipmentStep
bs={bs}
campaignData={campaignData}
weapons={weapons?.filter((w) => 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 && (
<div className="mt-sm">
<button
className="btn btn-ghost"
onClick={goBack}
disabled={back.isPending}
title="Your dice rolls are kept. You can change what you chose."
>
{backLabel}
</button>
</div>
)}
</>
)}
</div>
<aside className="build-preview">
<BuildPreview
bs={previewBs}
level={character.level}
armorBonus={character.armorBonus}
assignments={assignments}
options={options}
// On their own steps the preview follows what is picked right now.
motivation={(stage === 'ROLLING_MOTIVATION' ? options?.motivations.find((m) => m.key === motivationPick)?.label : bs.motivationText) ?? null}
talents={stage === 'CHOOSING_ABILITIES' ? talents : (bs.talents ?? [])}
/>
</aside>
</div>
);
}
// 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 (
<button type="button" className={`choice-card${selected ? ' is-selected' : ''}`} aria-pressed={selected} onClick={onSelect}>
<span className="choice-card-title">
{title}
<span className={`badge ${selected ? 'badge-dm' : ''}`}>{selected ? '✓ Selected' : tag || 'Click to try'}</span>
</span>
{children}
</button>
);
}
function StepFooter({ hint, disabled, onNext, label = 'Next →' }: { hint: string; disabled: boolean; onNext: () => void; label?: string }) {
return (
<div className="step-footer">
<span className="subtitle">{hint}</span>
<button className="btn btn-primary btn-lg" disabled={disabled} onClick={onNext}>
{label}
</button>
</div>
);
}
function GrantedAbilities({ heading, abilities }: { heading: string; abilities: NamedAbility[] }) {
return (
<div className="mt-md">
<div className="pick-group-label">{heading}</div>
{abilities.map((a) => (
<div key={a.name} className="granted-ability">
<strong>{a.name}</strong> <span className="badge">automatic</span>
<div style={{ color: 'var(--text-muted)' }}>{a.text}</div>
</div>
))}
</div>
);
}
// 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 (
<div className="card mt-md">
<div className="card-title">
<span>Special Abilities</span>
<button className="btn" onClick={() => setTalents(randomSample(options.talents, need).map((t) => t.key))}>
🎲 Surprise me
</button>
</div>
<p className="step-intro">{STEP_GUIDE.ABILITIES}</p>
{species && <GrantedAbilities heading={`From being a ${SPECIES_LABELS[species]}`} abilities={options.speciesTraits[species]} />}
{characterClass && <GrantedAbilities heading={`From being a ${CLASS_LABELS[characterClass]}`} abilities={options.classFeatures[characterClass]} />}
<div className="pick-group-label mt-md">
Your talents — pick {need} ({talents.length}/{need})
</div>
<div className="choice-grid mt-sm">
{options.talents.map((t) => {
const selected = talents.includes(t.key);
return (
<ChoiceCard
key={t.key}
title={t.name}
tag={full ? 'Full' : 'Pick'}
selected={selected}
onSelect={() => {
if (selected) setTalents(talents.filter((k) => k !== t.key));
else if (!full) setTalents([...talents, t.key]);
}}
>
<span>{t.text}</span>
</ChoiceCard>
);
})}
</div>
<StepFooter
hint={talents.length === need ? 'Click a selected talent to swap it for another.' : `Pick ${need - talents.length} more.`}
disabled={talents.length !== need || submitting}
onNext={onNext}
/>
</div>
);
}
// 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 (
<div className="card mt-md">
<div className="card-title">
<span>{title}</span>
<button className="btn" onClick={surprise}>
🎲 Surprise me
</button>
</div>
<p className="step-intro">{intro}</p>
{groups.map((g) => {
const chosen = picks[g.key] || [];
const only = g.max === 1 ? g.options.find((o) => o.key === chosen[0]) : undefined;
return (
<div key={g.key} className="pick-group">
<span className="pick-group-label">{g.label}</span>
<span className="subtitle" style={{ marginLeft: 8 }}>
{g.prompt}
</span>
<div className="pick-chips" role="group" aria-label={g.label}>
{g.options.map((o) => {
const selected = chosen.includes(o.key);
return (
<button
key={o.key}
type="button"
className={`pick-chip${selected ? ' is-selected' : ''}`}
aria-pressed={selected}
title={o.text}
disabled={!selected && g.max > 1 && chosen.length >= g.max}
onClick={() => toggle(g, o.key)}
>
{o.label}
</button>
);
})}
</div>
{only?.text && <p className="pick-detail">{only.text}</p>}
</div>
);
})}
{preview.length > 0 && (
<div className="mt-md">
<div className="pick-group-label">How it will read on your sheet</div>
<p className="composed-text mt-sm">{preview.join('\n')}</p>
</div>
)}
<StepFooter
hint={complete ? 'Change any answer you like, then press Next.' : 'Answer each question to continue.'}
disabled={!complete || submitting}
onNext={onNext}
/>
</div>
);
}
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 (
<>
<p>{label} Roll it at the table, then type the result in below.</p>
<div className="flex-row" style={{ justifyContent: 'center' }}>
<NumberInput
min={1}
max={sides}
placeholder={`1–${sides}`}
value={value}
onChange={(e) => setValue(e.target.value)}
style={{ width: 80 }}
/>
<button
className="btn btn-primary"
disabled={rolling || !value}
onClick={() => onRoll({ value: Number(value) })}
>
Submit d{sides} Roll
</button>
</div>
</>
);
}
return (
<>
<p>{label}</p>
<button className="btn-roll" onClick={() => onRoll()} disabled={rolling}>
🎲 Roll d{sides}
</button>
</>
);
}
function BuildProgress({ stage, steps }: { stage: string; steps: string[] }) {
const idx = steps.indexOf(stage);
return (
<ol className="build-steps" style={{ listStyle: 'none', padding: 0, margin: 0 }} aria-label="Build steps">
{steps.map((s, i) => (
<li key={s} className={`badge${i < idx ? ' is-done' : i === idx ? ' is-current' : ''}`} aria-current={i === idx ? 'step' : undefined}>
{i < idx ? '✓' : i + 1} {STEP_NAMES[STEP_STAGES.indexOf(s)]}
</li>
))}
</ol>
);
}
function AssignScoresStep({
bs,
diceMode,
method,
onPointBuy,
assignments,
setAssignments,
onRoll,
onSubmit,
rolling,
submitting,
}: {
bs: BuildState;
diceMode: DiceMode;
method: ScoreMethod;
onPointBuy: (scores: Record<Ability, number>) => void;
assignments: Partial<Record<Ability, number>>;
setAssignments: (a: Partial<Record<Ability, number>>) => void;
onRoll: (body?: { abilitySets?: number[][] }) => void;
onSubmit: () => void;
rolling: boolean;
submitting: boolean;
}) {
if (method === 'POINT_BUY') {
return <PointBuyStep bs={bs} onSubmit={onPointBuy} submitting={submitting} />;
}
if (!bs.abilityRolls && method === 'STANDARD_ARRAY') {
return (
<div className="card mt-md text-center">
<div className="card-title">Ability Scores</div>
<p className="step-intro">{STEP_GUIDE.SCORES}</p>
<p>This campaign uses the standard array: the six scores 15, 14, 13, 12, 10 and 8, for you to place.</p>
<button className="btn btn-primary" onClick={() => onRoll()} disabled={rolling}>
Use the standard array
</button>
</div>
);
}
if (!bs.abilityRolls) {
if (diceMode === 'PHYSICAL') {
return <PhysicalAbilityRollForm onRoll={onRoll} rolling={rolling} />;
}
return (
<div className="card mt-md text-center">
<div className="card-title">Ability Scores</div>
<p className="step-intro">{STEP_GUIDE.SCORES}</p>
<p>
Roll 4d6 (drop the lowest) six times — one set per ability. <InfoTip term="ROLL_4D6" />
</p>
<button className="btn-roll" onClick={() => onRoll()} disabled={rolling}>
🎲 Roll Ability Scores
</button>
</div>
);
}
const usedIndexes = new Set(Object.values(assignments));
const species = bs.species ?? null;
const bonusChoices = bs.speciesBonusChoices ?? {};
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<Ability>([...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 (
<div className="card mt-md">
<div className="card-title">Assign Ability Scores</div>
<p className="step-intro">{STEP_GUIDE.SCORES}</p>
<div className="flex-between flex-wrap">
<span className="subtitle">
Your six rolls <InfoTip term="ROLL_4D6" />
{bs.characterClass && (
<>
{' '}
· ★ marks what a {CLASS_LABELS[bs.characterClass]} leans on most <InfoTip term="KEY_ABILITY" />
</>
)}
</span>
<button className="btn" onClick={suggest} title="Puts your best rolls where your class needs them. You can still change any of them.">
✨ Suggest for me
</button>
</div>
<div className="flex-row flex-wrap gap-sm mt-sm">
{bs.abilityRolls.map((r, i) => (
<span key={i} className="badge" style={usedIndexes.has(i) ? { opacity: 0.4 } : { borderColor: 'var(--accent)' }}>
{r.dice.length > 0 ? `${r.dice.join('+')} (drop ${r.dropped}) = ${r.total}` : r.total}
</span>
))}
</div>
<div className="grid grid-cols-3 mt-md">
{ABILITIES.map((ability) => {
const assignedIndex = assignments[ability];
const rolledTotal = assignedIndex !== undefined ? bs.abilityRolls![assignedIndex].total : null;
const bonus = speciesBonusFor(species, ability, bonusChoices);
const final = rolledTotal !== null ? rolledTotal + bonus : null;
return (
<div className={`stat-block${keyAbilities.includes(ability) ? ' is-key' : ''}`} key={ability}>
<span className="stat-label">
{ABILITY_LABELS[ability]} <InfoTip text={ABILITY_GUIDE[ability].affects} label={`What ${ABILITY_LABELS[ability]} affects`} />
</span>
<span className="stat-sub">{ABILITY_GUIDE[ability].short}</span>
{keyAbilities.includes(ability) && <span className="key-marker">★ Key for your class</span>}
<select
aria-label={`Score for ${ABILITY_LABELS[ability]}`}
value={assignedIndex ?? ''}
onChange={(e) => {
const val = e.target.value === '' ? undefined : Number(e.target.value);
const next = { ...assignments };
if (val === undefined) delete next[ability];
else next[ability] = val;
setAssignments(next);
}}
>
<option value="">—</option>
{bs.abilityRolls!.map((r, i) => (
<option key={i} value={i} disabled={usedIndexes.has(i) && assignedIndex !== i}>
{r.total}
</option>
))}
</select>
{final !== null && (
<span className="stat-sub">
{rolledTotal} {bonus ? `+${bonus}` : ''} = {final} ({abilityModifier(final) >= 0 ? '+' : ''}
{abilityModifier(final)})
</span>
)}
</div>
);
})}
</div>
<p className="subtitle">
Each line reads: your roll + species bonus <InfoTip term="SPECIES_BONUS" /> = final score (modifier{' '}
<InfoTip term="ABILITY_MODIFIER" />
). The modifier is the number you actually add to dice rolls.
</p>
<StepFooter
hint={complete ? 'Rearrange as much as you like, then press Next.' : 'Give every ability one of your six rolls.'}
disabled={!complete || submitting}
onNext={onSubmit}
/>
</div>
);
}
// Point buy: each ability starts at 8 and is raised with points from the
// budget. The scores go straight to their abilities; nothing is rolled.
function PointBuyStep({ bs, onSubmit, submitting }: { bs: BuildState; onSubmit: (scores: Record<Ability, number>) => void; submitting: boolean }) {
const [scores, setScores] = useState<Record<Ability, number>>(() => {
const bought = bs.pointBuy;
return Object.fromEntries(ABILITIES.map((a) => [a, bought?.[a] ?? 8])) as Record<Ability, number>;
});
const spent = ABILITIES.reduce((sum, a) => sum + POINT_BUY_COSTS[scores[a]], 0);
const left = POINT_BUY_BUDGET - spent;
const species = bs.species ?? null;
const keyAbilities = bs.characterClass ? CLASS_GUIDE[bs.characterClass].keyAbilities : [];
const canRaise = (a: Ability) => scores[a] < 15 && POINT_BUY_COSTS[scores[a] + 1] - POINT_BUY_COSTS[scores[a]] <= left;
return (
<div className="card mt-md">
<div className="card-title">
<span>Buy Ability Scores</span>
<span className={`badge${left < 0 ? ' badge-hostile' : ''}`}>
{left} of {POINT_BUY_BUDGET} points left
</span>
</div>
<p className="step-intro">
Every score starts at 8. Raising one costs a point a step up to 13, and two a step for 14 and 15. Spend up to {POINT_BUY_BUDGET}.
</p>
<div className="grid grid-cols-3 mt-md">
{ABILITIES.map((ability) => {
const bonus = speciesBonusFor(species, ability, bs.speciesBonusChoices ?? {});
const final = scores[ability] + bonus;
return (
<div className={`stat-block${keyAbilities.includes(ability) ? ' is-key' : ''}`} key={ability}>
<span className="stat-label">{ABILITY_LABELS[ability]}</span>
<span className="stat-sub">{ABILITY_GUIDE[ability].short}</span>
{keyAbilities.includes(ability) && <span className="key-marker">★ Key for your class</span>}
<div className="flex-row gap-sm" style={{ justifyContent: 'center' }}>
<button
className="btn btn-sm"
aria-label={`Lower ${ABILITY_LABELS[ability]}`}
disabled={scores[ability] <= 8}
onClick={() => setScores({ ...scores, [ability]: scores[ability] - 1 })}
>
−
</button>
<span className="stat-value">{scores[ability]}</span>
<button
className="btn btn-sm"
aria-label={`Raise ${ABILITY_LABELS[ability]}`}
disabled={!canRaise(ability)}
onClick={() => setScores({ ...scores, [ability]: scores[ability] + 1 })}
>
+
</button>
</div>
<span className="stat-sub">
{scores[ability]} {bonus ? `+${bonus}` : ''} = {final} ({fmtMod(abilityModifier(final))})
</span>
</div>
);
})}
</div>
<StepFooter
hint={left > 0 ? `You still have ${left} point${left === 1 ? '' : 's'} to spend (or keep them).` : 'All points spent. Press Next.'}
disabled={left < 0 || submitting}
onNext={() => onSubmit(scores)}
/>
</div>
);
}
// "Choose +2/+1 or +1/+1/+1": a species' flexible bonuses in a few words.
function flexibleLabel(species: Species): string {
const flexible = SPECIES_FLEXIBLE_BONUS[species];
if (!flexible) return '';
return `Choose ${flexible.patterns.map((pattern) => pattern.map((n) => `+${n}`).join('/')).join(' or ')}`;
}
// Where a species' flexible bonuses go: one of its patterns (+2/+1, or
// +1/+1/+1), each amount to a different ability.
function SpeciesBonusPicker({ species, value, onChange }: { species: Species; value: BonusChoices; onChange: (value: BonusChoices) => void }) {
const flexible = SPECIES_FLEXIBLE_BONUS[species]!;
const amountsOf = (choices: BonusChoices) => Object.values(choices).filter(Boolean).sort((a, b) => (b ?? 0) - (a ?? 0)).join(',');
const matching = flexible.patterns.findIndex((pattern) => pattern.join(',') === amountsOf(value));
const [patternIndex, setPatternIndex] = useState(Math.max(0, matching));
const pattern = flexible.patterns[patternIndex];
const eligible = ABILITIES.filter((a) => !flexible.exclude?.includes(a));
// Which ability fills each slot of the pattern, read back from the value.
const slots: (Ability | '')[] = [];
const used = new Set<Ability>();
for (const amount of pattern) {
const found = ABILITIES.find((a) => value[a] === amount && !used.has(a));
if (found) used.add(found);
slots.push(found ?? '');
}
function setSlot(index: number, ability: Ability | '') {
const next = [...slots];
next[index] = ability;
const choices: BonusChoices = {};
next.forEach((a, i) => {
if (a) choices[a] = pattern[i];
});
onChange(choices);
}
return (
<div className="card mt-md" style={{ textAlign: 'left' }}>
<p style={{ marginTop: 0 }}>
{SPECIES_LABELS[species]} choose their own ability bonuses
{flexible.exclude?.length ? ` (besides ${flexible.exclude.map((a) => ABILITY_LABELS[a]).join(', ')})` : ''}.
</p>
{flexible.patterns.length > 1 && (
<div className="flex-row flex-wrap gap-sm">
{flexible.patterns.map((p, i) => (
<label key={i} className="checkbox-row">
<input
type="radio"
name="bonus-pattern"
checked={patternIndex === i}
onChange={() => {
setPatternIndex(i);
onChange({});
}}
/>
{p.map((n) => `+${n}`).join(' / ')}
</label>
))}
</div>
)}
<div className="flex-row flex-wrap gap-sm mt-sm">
{pattern.map((amount, i) => (
<label key={`${patternIndex}-${i}`} className="flex-row gap-sm">
+{amount} to
<select value={slots[i]} onChange={(e) => setSlot(i, e.target.value as Ability | '')} aria-label={`Ability for the +${amount}`}>
<option value="">—</option>
{eligible.map((a) => (
<option key={a} value={a} disabled={slots.includes(a) && slots[i] !== a}>
{ABILITY_LABELS[a]}
</option>
))}
</select>
</label>
))}
</div>
</div>
);
}
// The subclass step: a die with a face per subclass suggests one, and the
// player picks freely, or leaves it until the class chooses at its level.
function SubclassStep({
characterClass,
subclasses,
subclassLevel,
roll,
suggestion,
picked,
onPick,
diceMode,
onRoll,
rolling,
submitting,
onSubmit,
}: {
characterClass: CharacterClass;
subclasses: SubclassSummary[];
subclassLevel: number;
roll?: number;
suggestion?: string;
picked: string | null;
onPick: (key: string | null) => void;
diceMode: DiceMode;
onRoll: (body?: { value?: number }) => void;
rolling: boolean;
submitting: boolean;
onSubmit: (subclass: string | null) => void;
}) {
const [previewing, setPreviewing] = useState<string | null>(null);
const pickedName = subclasses.find((sub) => sub.key === picked)?.name;
return (
<div className="card mt-md">
<div className="card-title">Subclass</div>
<p className="step-intro">
Your subclass is the path you take within your class. Choose it now and its gifts arrive at level {subclassLevel}; or decide
later, when you get there. Every {CLASS_LABELS[characterClass]} path is here, from the 2014 books and the 2024 Player’s Handbook.
</p>
{subclasses.length > 0 && !roll && (
<div className="text-center">
<RollControl sides={subclasses.length} diceMode={diceMode} onRoll={onRoll} rolling={rolling} label={`Can’t decide? Roll a d${subclasses.length} for a suggestion.`} />
</div>
)}
{roll && suggestion && (
<p className="text-center">
<span className="roll-result animate">{roll}</span>
<br />
The dice suggest <strong>{subclasses.find((sub) => sub.key === suggestion)?.name}</strong>. You are free to pick any.
</p>
)}
<div className="choice-grid mt-md">
{subclasses.map((sub) => (
<ChoiceCard
key={sub.key}
title={sub.name}
tag={sub.key === suggestion ? '🎲 Suggested' : sub.edition === '2024' ? '2024 rules' : undefined}
selected={picked === sub.key}
onSelect={() => onPick(sub.key)}
>
<span className="choice-card-blurb">{sub.summary}</span>
<span className="choice-card-facts">{sub.source}</span>
<span
className="btn btn-ghost btn-sm"
role="button"
tabIndex={0}
onClick={(e) => {
e.stopPropagation();
setPreviewing(previewing === sub.key ? null : sub.key);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
e.stopPropagation();
setPreviewing(previewing === sub.key ? null : sub.key);
}
}}
>
{previewing === sub.key ? 'Hide the road' : 'Levels 1–20 →'}
</span>
</ChoiceCard>
))}
</div>
{previewing && (
<div className="card mt-md">
<div className="card-title">{subclasses.find((sub) => sub.key === previewing)?.name}: levels 1 to 20</div>
<ProgressionTimeline characterClass={characterClass} subclass={previewing} subclassName={subclasses.find((sub) => sub.key === previewing)?.name} />
</div>
)}
<div className="flex-between flex-wrap mt-md">
<button className="btn" onClick={() => onSubmit(null)} disabled={submitting}>
Decide at level {subclassLevel}
</button>
<StepFooter
hint={pickedName ? `${pickedName} selected — you can still change your mind.` : 'Pick a path, or decide later.'}
disabled={!picked || submitting}
onNext={() => onSubmit(picked)}
/>
</div>
</div>
);
}
function PhysicalAbilityRollForm({ onRoll, rolling }: { onRoll: (body?: { abilitySets?: number[][] }) => void; rolling: boolean }) {
const [sets, setSets] = useState<string[][]>(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 (
<div className="card mt-md">
<div className="card-title">Ability Scores (Physical Dice)</div>
<p>Roll 4d6 six times at the table, then enter each set's four results below (drop-the-lowest is applied automatically).</p>
{sets.map((set, i) => (
<div key={i} className="flex-row flex-wrap mt-sm">
<span className="badge">Set {i + 1}</span>
{set.map((v, j) => (
<NumberInput
key={j}
min={1}
max={6}
value={v}
onChange={(e) => updateDie(i, j, e.target.value)}
style={{ width: 60 }}
/>
))}
</div>
))}
<button
className="btn btn-primary mt-md"
disabled={!allFilled || rolling}
onClick={() => onRoll({ abilitySets: sets.map((set) => set.map(Number)) })}
>
Submit All Six Sets
</button>
</div>
);
}
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 (
<div className="card mt-md text-center">
<div className="card-title">Last step — Finalize</div>
<p>
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.
</p>
<button className="btn btn-primary btn-lg" onClick={onFinalize} disabled={finalizing}>
{finalizing ? 'Finalizing…' : '✦ Finalize Character'}
</button>
</div>
);
}
return (
<div className="card mt-md">
<div className="card-title">
<span>
Starting Equipment <InfoTip term="STARTING_EQUIPMENT" />
</span>
</div>
<p className="step-intro">{STEP_GUIDE.EQUIPMENT}</p>
<p className="subtitle">
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.
</p>
{nothingOffered && <p style={{ color: 'var(--text-muted)' }}>The DM hasn't marked any weapons or items as starting options yet.</p>}
<div className="flex-row flex-wrap">
{weapons?.map((w) => (
<label key={w.id} className="checkbox-row">
<input
type="checkbox"
checked={equipWeapons.includes(w.id)}
disabled={!equipWeapons.includes(w.id) && itemsFull}
onChange={() => toggle(equipWeapons, setEquipWeapons, w.id, itemsFull)}
/>
{w.name} ({w.damageDice} {w.damageType}) <InfoTip term="DAMAGE_DICE" />
</label>
))}
{items?.map((item) => (
<label key={item.id} className="checkbox-row" title={item.description ?? undefined}>
<input
type="checkbox"
checked={equipItems.includes(item.id)}
disabled={!equipItems.includes(item.id) && itemsFull}
onChange={() => toggle(equipItems, setEquipItems, item.id, itemsFull)}
/>
{item.name}
{item.description && <InfoTip text={item.description} label={`About ${item.name}`} />}
</label>
))}
</div>
{hasSpellcasting && (
<>
<div className="divider" />
<div className="flex-row flex-wrap">
{spells?.map((s) => (
<label key={s.id} className="checkbox-row">
<input
type="checkbox"
checked={equipSpells.includes(s.id)}
disabled={!equipSpells.includes(s.id) && equipSpells.length >= maxSpells}
onChange={() => toggle(equipSpells, setEquipSpells, s.id, equipSpells.length >= maxSpells)}
/>
{s.name} ({spellLevelLabel(s.level)}
{s.damageDice ? ` · ${s.damageDice}` : ''}){s.description && <InfoTip text={s.description} label={`What ${s.name} does`} />}
</label>
))}
{(!spells || spells.length === 0) && <p style={{ color: 'var(--text-muted)' }}>The DM hasn't marked any spells as starting options yet.</p>}
</div>
</>
)}
<StepFooter hint="Tick and untick freely. Next takes you to the final check." disabled={false} onNext={onSubmit} />
</div>
);
}
// 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<Record<Ability, number>>;
options: BuildOptions | undefined;
motivation: string | null;
talents: string[];
}) {
const species = bs.species ?? null;
const bonusChoices = bs.speciesBonusChoices ?? {};
const characterClass = bs.characterClass ?? null;
const abilityFinals: Partial<Record<Ability, number>> = {};
for (const ability of ABILITIES) {
const bonus = speciesBonusFor(species, ability, bonusChoices);
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 (
<div className="card">
<div className="card-title">Live Preview</div>
{!species && !characterClass && (
<p className="subtitle" style={{ marginTop: 0 }}>
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.
</p>
)}
{species && (
<p style={{ marginTop: 0 }}>
<strong>{SPECIES_LABELS[species]}</strong>
{Object.entries({ STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHA: 0 })
.map(([a]) => [a as Ability, speciesBonusFor(species, a as Ability, bonusChoices)] as const)
.filter(([, bonus]) => bonus !== 0)
.map(([a, bonus]) => (
<span key={a} className="preview-highlight" style={{ marginLeft: 6 }}>
{fmtMod(bonus)} {a}
</span>
))}
</p>
)}
{characterClass && (
<p>
<strong>{CLASS_LABELS[characterClass]}</strong>
<span style={{ color: 'var(--text-muted)' }}> · d{hitDie} hit die</span>
{saveProfs && saveProfs.length > 0 && (
<span style={{ color: 'var(--text-muted)' }}> · {saveProfs.map((a) => ABILITY_LABELS[a]).join('/')} saves</span>
)}
{bs.subclass && options && (
<span className="preview-highlight" style={{ display: 'block' }}>
Path: {options.subclasses[characterClass]?.find((sub) => sub.key === bs.subclass)?.name} (from level {options.subclassLevels[characterClass]})
</span>
)}
</p>
)}
{Object.keys(abilityFinals).length > 0 && (
<div className="grid grid-cols-3 mt-sm">
{ABILITIES.map((a) =>
abilityFinals[a] !== undefined ? (
<div className="stat-block" key={a}>
<span className="stat-label">
{a} <InfoTip text={ABILITY_GUIDE[a].affects} label={`What ${ABILITY_LABELS[a]} affects`} />
</span>
<span className="stat-value">{abilityFinals[a]}</span>
<span className="stat-sub">{fmtMod(abilityModifier(abilityFinals[a]!))}</span>
</div>
) : null
)}
</div>
)}
<div className="divider" />
<div className="grid grid-cols-2">
<div>
<span className="stat-label">
AC <InfoTip term="AC" />
</span>
<div className="stat-value">{dexMod !== null ? armorClass(dexMod, armorBonus) : '—'}</div>
</div>
<div>
<span className="stat-label">
Max HP <InfoTip term="HP" />
</span>
<div className="stat-value">{hitDie && conMod !== null ? hpMax(level || 1, hitDie, conMod) : '—'}</div>
</div>
<div>
<span className="stat-label">
Initiative <InfoTip term="INITIATIVE" />
</span>
<div className="stat-value">{dexMod !== null ? fmtMod(dexMod) : '—'}</div>
</div>
<div>
<span className="stat-label">
Prof. Bonus <InfoTip term="PROFICIENCY_BONUS" />
</span>
<div className="stat-value">{fmtMod(profBonus)}</div>
</div>
<div>
<span className="stat-label">
Speed <InfoTip term="SPEED" />
</span>
<div className="stat-value">{species ? SPECIES_SPEED[species] : '—'}</div>
</div>
</div>
{characterClass && saveProfs.length > 0 && (
<>
<div className="divider" />
<div className="card-title" style={{ fontSize: '0.85rem' }}>
<span>
Saving Throws <InfoTip term="SAVING_THROW" />
</span>
</div>
{ABILITIES.map((a) => {
const mod = abilityFinals[a] !== undefined ? abilityModifier(abilityFinals[a]!) : null;
if (mod === null) return null;
const proficient = saveProfs.includes(a);
return (
<div key={a} className="flex-between" style={{ padding: '0.15rem 0', fontSize: '0.85rem' }}>
<span>
{ABILITY_LABELS[a]} {proficient && <span className="badge">prof</span>}
</span>
<span className="mono">{fmtMod(saveBonus(mod, proficient, profBonus))}</span>
</div>
);
})}
</>
)}
{wisMod !== null && (
<>
<div className="divider" />
<div className="flex-between" style={{ fontSize: '0.85rem' }}>
<span>
Passive Perception <InfoTip term="PASSIVE_PERCEPTION" />
</span>
<span className="mono">{passivePerception(perceptionProficient ? profBonus + wisMod : wisMod)}</span>
</div>
</>
)}
{spellAbility && abilityFinals[spellAbility] !== undefined && (
<>
<div className="divider" />
<div className="card-title" style={{ fontSize: '0.85rem' }}>
<span>
Spellcasting ({ABILITY_LABELS[spellAbility]}) <InfoTip term="SPELL_SAVE_DC" />
</span>
</div>
<p style={{ margin: 0, fontSize: '0.85rem' }}>
Save DC {spellSaveDC(profBonus, abilityModifier(abilityFinals[spellAbility]!))} · Attack{' '}
{fmtMod(spellAttackBonus(profBonus, abilityModifier(abilityFinals[spellAbility]!)))}
</p>
</>
)}
{bs.skillProficiencies && bs.skillProficiencies.length > 0 && (
<>
<div className="divider" />
<div className="card-title" style={{ fontSize: '0.85rem' }}>Skills</div>
<div className="flex-row flex-wrap gap-sm">
{bs.skillProficiencies.map((sp) => (
<span key={sp.skill} className="badge">{SKILL_LABELS[sp.skill]}</span>
))}
</div>
</>
)}
{abilityList.length > 0 && (
<>
<div className="divider" />
<div className="card-title" style={{ fontSize: '0.85rem' }}>Special Abilities</div>
<div className="flex-row flex-wrap gap-sm">
{abilityList.map((a) => (
<span key={a.name} className="badge" title={a.text}>
{a.name}
</span>
))}
</div>
</>
)}
{motivation && (
<>
<div className="divider" />
<div className="card-title" style={{ fontSize: '0.85rem' }}>Motivation</div>
<p style={{ margin: 0, fontSize: '0.9rem', fontStyle: 'italic' }}>{motivation}</p>
</>
)}
</div>
);
}