Initial commit

This commit is contained in:
2026-09-22 16:27:53 +02:00
commit 9b29dc8253
70 changed files with 14726 additions and 0 deletions
+499
View File
@@ -0,0 +1,499 @@
import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useBuildChoose, useBuildFinalize, useBuildRoll, useCampaign, useCampaignSpells, useCampaignWeapons, useCharacter } from '../api/queries';
import { Spinner, ErrorBanner } from '../components/Spinner';
import { ABILITY_LABELS, CLASS_LABELS, SKILL_LABELS, SPECIES_LABELS, extractErrorMessage } from '../lib/format';
import { abilityModifier, speciesBonusFor } from '../lib/speciesData';
import { CLASS_SPELLCASTING_ABILITY } from '../lib/classData';
import type { Ability, CharacterClass, 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 }[];
equipment?: { weaponIds: 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);
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 [formError, setFormError] = useState<string | null>(null);
const [halfElfPick, setHalfElfPick] = useState<Ability[]>([]);
const [pendingSpecies, setPendingSpecies] = useState<Species | null>(null);
const [assignments, setAssignments] = useState<Partial<Record<Ability, number>>>({});
const [skillPicks, setSkillPicks] = useState<Record<string, boolean>>({});
const [expertisePicks, setExpertisePicks] = useState<Record<string, boolean>>({});
const [equipWeapons, setEquipWeapons] = useState<string[]>([]);
const [equipSpells, setEquipSpells] = useState<string[]>([]);
const campaignId = character?.campaignId;
const { data: campaignData } = useCampaign(campaignId);
const { data: weapons } = useCampaignWeapons(campaignId);
const { data: spells } = useCampaignSpells(campaignId);
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;
async function safeRoll() {
setFormError(null);
try {
await roll.mutateAsync();
} catch (err) {
setFormError(extractErrorMessage(err));
}
}
async function safeChoose(body: Record<string, unknown>) {
setFormError(null);
try {
await choose.mutateAsync(body);
} catch (err) {
setFormError(extractErrorMessage(err));
}
}
return (
<div>
<div className="page-header">
<div>
<h1>Rolling Up {character.name}</h1>
<p className="subtitle">Roll the dice at the table — every result is locked in server-side.</p>
</div>
</div>
<BuildProgress stage={stage} />
{formError && <ErrorBanner message={formError} />}
{stage === 'ROLLING_SPECIES' && (
<div className="card mt-md text-center">
<div className="card-title">Step 1 — Species</div>
{!bs.speciesRoll ? (
<>
<p>Roll a d6 to see which species you can choose between.</p>
<button className="btn-roll" onClick={safeRoll} disabled={roll.isPending}>
🎲 Roll d6
</button>
</>
) : (
<>
<div className="roll-result animate">{bs.speciesRoll}</div>
<p className="mt-sm">
{bs.speciesChoices?.type === 'wildcard' ? 'Wildcard! Pick any species:' : 'Choose your species:'}
</p>
<div className="flex-row flex-wrap" style={{ justifyContent: 'center' }}>
{bs.speciesChoices?.options.map((s) => (
<button
key={s}
className={`btn ${pendingSpecies === s ? 'btn-primary' : ''}`}
onClick={() => {
setPendingSpecies(s as Species);
setHalfElfPick([]);
if (s !== 'HALF_ELF') safeChoose({ species: s });
}}
>
{SPECIES_LABELS[s]}
</button>
))}
</div>
{pendingSpecies === 'HALF_ELF' && (
<div className="card mt-md" style={{ textAlign: 'left' }}>
<p>Half-Elf gets a fixed +2 CHA, plus +1/+1 to two other abilities of your choice:</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((prev) =>
e.target.checked ? [...prev, a] : prev.filter((x) => x !== a)
)
}
/>
{ABILITY_LABELS[a]}
</label>
))}
</div>
<button
className="btn btn-primary mt-sm"
disabled={halfElfPick.length !== 2}
onClick={() => safeChoose({ species: 'HALF_ELF', halfElfBonusAbilities: halfElfPick })}
>
Confirm Half-Elf
</button>
</div>
)}
</>
)}
</div>
)}
{stage === 'ROLLING_CLASS' && (
<div className="card mt-md text-center">
<div className="card-title">Step 2 — Class</div>
{!bs.classRoll || bs.classChoices?.type === 'reroll' ? (
<>
{bs.classChoices?.type === 'reroll' && (
<div className="roll-result animate mb-2">{bs.classRoll}</div>
)}
<p>{bs.classChoices?.type === 'reroll' ? 'You rolled a 7 — reroll once!' : 'Roll a d8 to see which classes you can choose between.'}</p>
<button className="btn-roll" onClick={safeRoll} disabled={roll.isPending}>
🎲 Roll d8
</button>
</>
) : (
<>
<div className="roll-result animate">{bs.classRoll}</div>
<p className="mt-sm">
{bs.classChoices?.type === 'wildcard' ? 'Wildcard! Pick any class:' : 'Choose your class:'}
</p>
<div className="flex-row flex-wrap" style={{ justifyContent: 'center' }}>
{bs.classChoices?.options.map((c) => (
<button key={c} className="btn" onClick={() => safeChoose({ characterClass: c })}>
{CLASS_LABELS[c]}
</button>
))}
</div>
</>
)}
</div>
)}
{stage === 'ROLLING_MOTIVATION' && (
<div className="card mt-md text-center">
<div className="card-title">Step 3 — Motivation (Flavor)</div>
{!bs.motivationRoll ? (
<>
<p>Roll a d6 for your character's driving motivation.</p>
<button className="btn-roll" onClick={safeRoll} disabled={roll.isPending}>
🎲 Roll d6
</button>
</>
) : (
<>
<div className="roll-result animate">{bs.motivationRoll}</div>
<p className="mt-sm" style={{ fontStyle: 'italic' }}>
"{bs.motivationText}"
</p>
<button className="btn btn-primary mt-sm" onClick={() => safeChoose({})}>
Confirm & Continue
</button>
</>
)}
</div>
)}
{stage === 'ASSIGNING_SCORES' && (
<AssignScoresStep
bs={bs}
assignments={assignments}
setAssignments={setAssignments}
onRoll={safeRoll}
onSubmit={() => safeChoose({ assignments })}
rolling={roll.isPending}
/>
)}
{stage === 'ASSIGNING_PROFICIENCIES' && (
<div className="card mt-md">
<div className="card-title">Step 5 — Skill Proficiencies</div>
<p className="subtitle">Saving throw proficiencies are fixed by class and were set automatically.</p>
<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]}
</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={() =>
safeChoose({
skillProficiencies: ALL_SKILLS.filter((s) => skillPicks[s]).map((s) => ({
skill: s,
proficient: true,
expertise: Boolean(expertisePicks[s]),
})),
})
}
>
Confirm Skills
</button>
</div>
)}
{stage === 'CHOOSING_EQUIPMENT' && (
<EquipmentStep
bs={bs}
campaignData={campaignData}
weapons={weapons}
spells={spells}
equipWeapons={equipWeapons}
setEquipWeapons={setEquipWeapons}
equipSpells={equipSpells}
setEquipSpells={setEquipSpells}
onSubmit={() => safeChoose({ weaponIds: equipWeapons, spellIds: equipSpells })}
onFinalize={async () => {
try {
const finalized = await finalize.mutateAsync();
navigate(`/characters/${finalized.id}`);
} catch (err) {
setFormError(extractErrorMessage(err));
}
}}
finalizing={finalize.isPending}
/>
)}
</div>
);
}
function BuildProgress({ stage }: { stage: string }) {
const steps = ['ROLLING_SPECIES', 'ROLLING_CLASS', 'ROLLING_MOTIVATION', 'ASSIGNING_SCORES', 'ASSIGNING_PROFICIENCIES', 'CHOOSING_EQUIPMENT'];
const idx = steps.indexOf(stage);
return (
<div className="flex-row flex-wrap gap-sm">
{steps.map((s, i) => (
<span key={s} className="badge" style={i <= idx ? { borderColor: 'var(--accent)', color: 'var(--accent-strong)' } : undefined}>
{i + 1}
</span>
))}
</div>
);
}
function AssignScoresStep({
bs,
assignments,
setAssignments,
onRoll,
onSubmit,
rolling,
}: {
bs: BuildState;
assignments: Partial<Record<Ability, number>>;
setAssignments: (a: Partial<Record<Ability, number>>) => void;
onRoll: () => void;
onSubmit: () => void;
rolling: boolean;
}) {
if (!bs.abilityRolls) {
return (
<div className="card mt-md text-center">
<div className="card-title">Step 4 — Ability Scores</div>
<p>Roll 4d6 (drop the lowest) six times — one set per ability.</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;
return (
<div className="card mt-md">
<div className="card-title">Step 4 — Assign Ability Scores</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" key={ability}>
<span className="stat-label">{ABILITY_LABELS[ability]}</span>
<select
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>
<button className="btn btn-primary mt-md" disabled={!complete} onClick={onSubmit}>
Confirm Ability Scores
</button>
</div>
);
}
function EquipmentStep({
bs,
campaignData,
weapons,
spells,
equipWeapons,
setEquipWeapons,
equipSpells,
setEquipSpells,
onSubmit,
onFinalize,
finalizing,
}: {
bs: BuildState;
campaignData: { campaign: { startingItemCount: number; startingSpellCount: number } } | undefined;
weapons: { id: string; name: string; damageDice: string }[] | undefined;
spells: { id: string; name: string; level: number }[] | undefined;
equipWeapons: string[];
setEquipWeapons: (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);
function toggle(list: string[], set: (ids: string[]) => void, id: string, max: number) {
if (list.includes(id)) set(list.filter((x) => x !== id));
else if (list.length < max) set([...list, id]);
}
if (chosen) {
return (
<div className="card mt-md text-center">
<div className="card-title">Step 7 — Finalize</div>
<p>Equipment chosen. Ready to compute HP, AC, and lock in your character.</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">Step 6 — Starting Equipment</div>
<p className="subtitle">
Pick up to {maxItems} item{maxItems === 1 ? '' : 's'}
{hasSpellcasting ? ` and up to ${maxSpells} spell${maxSpells === 1 ? '' : 's'}` : ''}.
</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) && equipWeapons.length >= maxItems}
onChange={() => toggle(equipWeapons, setEquipWeapons, w.id, maxItems)}
/>
{w.name} ({w.damageDice})
</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, maxSpells)}
/>
{s.name} (Lv {s.level})
</label>
))}
{(!spells || spells.length === 0) && <p style={{ color: 'var(--text-muted)' }}>No spells in this campaign's list yet — the DM can add some.</p>}
</div>
</>
)}
<button className="btn btn-primary mt-md" onClick={onSubmit}>
Confirm Equipment
</button>
</div>
);
}