- Hollowcrown: The Rift Between Worlds as its own seed (npm run seed:hollowcrown), built from the campaign book: pools, 58 monsters, 57 NPCs, 28 locations, 72 encounters with rewards, and DM notes. Shared seeding logic moved to prisma/seedCampaign.js. - What players can see: only encounters their own character is in; only the pool entries their character holds (plus starting options while building); only locations their character has been to; no invite code; no gold, inventory or money log of other players' characters. Socket events carry ids only and campaign rooms are members-only. - Encounters have a location; while one is in progress its characters are there, and visits are remembered. - Campaign setting to show players a health bar only for monsters and NPCs. - Initiative is entered as the d20 roll (1-20) and the bonus is added; players can enter their own character's roll. - Number fields enforce their limits when typing, and the API enforces the same limits. - Temp HP shows on HP bars and absorbs damage before real HP. - All packages at version 1.3.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1466 lines
59 KiB
TypeScript
1466 lines
59 KiB
TypeScript
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<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'];
|
||
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<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);
|
||
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 [halfElfTouched, setHalfElfPick] = useState<Ability[] | null>(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<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 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<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));
|
||
}
|
||
}
|
||
|
||
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 (
|
||
<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} />
|
||
|
||
{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">Step 1 — Species</div>
|
||
<p className="step-intro">{STEP_GUIDE.SPECIES}</p>
|
||
{!bs.speciesRoll ? (
|
||
<RollControl sides={6} diceMode={diceMode} onRoll={safeRoll} rolling={roll.isPending} label="Roll a d6 to see which species you can choose between." />
|
||
) : (
|
||
<>
|
||
<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 two. 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) setHalfElfPick([]);
|
||
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(' · ')}
|
||
{s === 'HALF_ELF' && ' · +1 to two of your choice'} · 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 === 'HALF_ELF' && (
|
||
<div className="card mt-md" style={{ textAlign: 'left' }}>
|
||
<p style={{ marginTop: 0 }}>
|
||
Half-Elves get +2 Charisma, plus +1 to two other abilities of your choice. Pick two:
|
||
</p>
|
||
<div className="flex-row flex-wrap">
|
||
{HALF_ELF_ELIGIBLE.map((a) => (
|
||
<label key={a} className="checkbox-row">
|
||
<input
|
||
type="checkbox"
|
||
checked={halfElfPick.includes(a)}
|
||
disabled={!halfElfPick.includes(a) && halfElfPick.length >= 2}
|
||
onChange={(e) =>
|
||
setHalfElfPick(e.target.checked ? [...halfElfPick, a] : halfElfPick.filter((x) => x !== a))
|
||
}
|
||
/>
|
||
{ABILITY_LABELS[a]} <InfoTip text={ABILITY_GUIDE[a].affects} label={`What ${ABILITY_LABELS[a]} affects`} />
|
||
</label>
|
||
))}
|
||
</div>
|
||
</div>
|
||
)}
|
||
<StepFooter
|
||
hint={
|
||
!pickedSpecies
|
||
? 'Nothing is locked in until you press Next.'
|
||
: pickedSpecies === 'HALF_ELF' && halfElfPick.length !== 2
|
||
? 'Pick two abilities for the Half-Elf bonus.'
|
||
: `${SPECIES_LABELS[pickedSpecies]} selected — you can still change your mind.`
|
||
}
|
||
disabled={!speciesReady || choose.isPending}
|
||
onNext={() =>
|
||
safeChoose(pickedSpecies === 'HALF_ELF' ? { species: pickedSpecies, halfElfBonusAbilities: halfElfPick } : { species: pickedSpecies })
|
||
}
|
||
/>
|
||
</>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
{stage === 'ROLLING_CLASS' && (
|
||
<div className="card mt-md text-center">
|
||
<div className="card-title">Step 2 — 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" />
|
||
</>
|
||
) : (
|
||
'Your roll offers these two. 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>
|
||
<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 === 'ROLLING_MOTIVATION' && (
|
||
<div className="card mt-md text-center">
|
||
<div className="card-title">
|
||
<span>Step 3 — 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}
|
||
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">
|
||
Step 5 — 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="Step 7 — 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="Step 8 — 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>Step 6 — 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 }: { stage: string }) {
|
||
const steps = STEP_STAGES;
|
||
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[i]}
|
||
</li>
|
||
))}
|
||
</ol>
|
||
);
|
||
}
|
||
|
||
function AssignScoresStep({
|
||
bs,
|
||
diceMode,
|
||
assignments,
|
||
setAssignments,
|
||
onRoll,
|
||
onSubmit,
|
||
rolling,
|
||
submitting,
|
||
}: {
|
||
bs: BuildState;
|
||
diceMode: DiceMode;
|
||
assignments: Partial<Record<Ability, number>>;
|
||
setAssignments: (a: Partial<Record<Ability, number>>) => void;
|
||
onRoll: (body?: { abilitySets?: number[][] }) => void;
|
||
onSubmit: () => void;
|
||
rolling: boolean;
|
||
submitting: boolean;
|
||
}) {
|
||
if (!bs.abilityRolls) {
|
||
if (diceMode === 'PHYSICAL') {
|
||
return <PhysicalAbilityRollForm onRoll={onRoll} rolling={rolling} />;
|
||
}
|
||
return (
|
||
<div className="card mt-md text-center">
|
||
<div className="card-title">Step 4 — 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 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<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">Step 4 — 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.join('+')} (drop {r.dropped}) = {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, halfElfBonusAbilities);
|
||
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>
|
||
);
|
||
}
|
||
|
||
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">Step 4 — 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>
|
||
Step 9 — 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 halfElfBonusAbilities = bs.halfElfBonusAbilities || [];
|
||
const characterClass = bs.characterClass ?? null;
|
||
|
||
const abilityFinals: Partial<Record<Ability, number>> = {};
|
||
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 (
|
||
<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, halfElfBonusAbilities)] 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>
|
||
)}
|
||
</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>
|
||
);
|
||
}
|