Files
the-sunken-reach/frontend/src/components/campaign/PoolSections.tsx
T
joshuaandClaude Opus 5.5 16b5ac05ca V1.30.0: class features that change a number are worked out on the sheet
- Unarmored Defense (barbarian, monk), Draconic Resilience, Fast Movement,
  Unarmored Movement, Aura of Protection, Diamond Soul, Slippery Mind and
  Jack of All Trades are counted, by level in the class that gives them
- Armor and shields are items marked with what kind they are, so the sheet
  knows when a character is unarmored or in heavy armor; the library's and
  the seeds' are marked
- The sheet lists the class features in force; a speed the DM set is final
- A cantrip can be cast with every spell slot spent (tested end to end)

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

589 lines
24 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 FormEvent, type ReactNode } from 'react';
import {
useAddItemFromLibrary,
useAddMonsterFromLibrary,
useAddSpellFromLibrary,
useAddWeaponFromLibrary,
useCampaignLibrary,
useCreateItem,
useCreateMonster,
useCreateNpc,
useCreateSpell,
useCreateWeapon,
} from '../../api/queries';
import { Modal } from '../Modal';
import { NumberInput } from '../NumberInput';
import { ErrorBanner, Spinner } from '../Spinner';
import { effectsSummary } from '../../lib/gear';
import { extractErrorMessage, fmtMod, spellLevelLabel, spellRequirementLabel } from '../../lib/format';
import { MAX_GEAR_LEVEL } from '../../lib/previewCalc';
import { abilityLine, rateLabel, type EntryRef } from '../../lib/campaignEntries';
import { EntryList, Field, LibraryPicker, MonsterForm, ScalingSelect, SpellDamageSelect, SpellLandingSelect, StartLevelSelect } from './parts';
import { landingFrom } from '../../lib/campaignEntries';
import type { CampaignLibrary, Item, LibraryItem, LibraryMonster, LibrarySpell, LibraryWeapon, Monster, Npc, NpcDisposition, Spell, Weapon } from '../../api/types';
interface SectionProps<T> {
campaignId: string;
entries: T[] | undefined;
onOpen: (entry: EntryRef) => void;
// The "add by hand" pop-out is wanted from outside: "add another", pressed
// in the pop-out of the one just added.
formRequested: boolean;
onFormClosed: () => void;
}
// Which of a list's two "add" pop-outs is open: the form, or the library.
type Adding = 'form' | 'library' | null;
// Which "add" pop-out a list has open, and what went wrong in it.
function useAdding(formRequested: boolean, onFormClosed: () => void) {
const [adding, setAdding] = useState<Adding>(null);
const [error, setError] = useState<string | null>(null);
return {
adding: formRequested ? ('form' as const) : adding,
error,
setError,
open: (next: Adding) => {
setError(null);
setAdding(next);
},
close: () => {
setError(null);
setAdding(null);
onFormClosed();
},
};
}
function SectionCard({
title,
addLabel,
hasLibrary = true,
onAdd,
intro,
children,
}: {
title: string;
addLabel: string;
hasLibrary?: boolean;
onAdd: (adding: Adding) => void;
intro: ReactNode;
children: ReactNode;
}) {
return (
<div className="card">
<div className="card-title">
<span>{title}</span>
<div className="flex-row gap-sm">
{hasLibrary && (
<button className="btn" onClick={() => onAdd('library')}>
📚 From Library
</button>
)}
<button className="btn btn-primary" onClick={() => onAdd('form')}>
{addLabel}
</button>
</div>
</div>
<p className="subtitle" style={{ marginTop: 0 }}>
{intro}
</p>
{children}
</div>
);
}
// The built-in library in a pop-out. It is a large download, so it is only
// asked for once one of these is opened.
function LibraryModal<T extends { key: string; name: string }>({
campaignId,
title,
pick,
taken,
adding,
onAdd,
placeholder,
renderMeta,
renderDetail,
error,
onClose,
}: {
campaignId: string;
title: string;
pick: (library: CampaignLibrary) => T[];
taken: { name: string }[] | undefined;
adding: boolean;
onAdd: (key: string) => void;
placeholder: string;
renderMeta: (item: T) => string;
renderDetail?: (item: T) => string | null;
error: string | null;
onClose: () => void;
}) {
const { data: library, isError } = useCampaignLibrary(campaignId);
return (
<Modal title={title} subtitle="Each entry can be added once. This stays open so you can add several." wide onClose={onClose}>
{error && <ErrorBanner message={error} />}
{isError && <ErrorBanner message="Could not load the library." />}
{!library && !isError && <Spinner label="Fetching the library…" />}
{library && (
<LibraryPicker<T> items={pick(library)} taken={taken} adding={adding} onAdd={onAdd} placeholder={placeholder} renderMeta={renderMeta} renderDetail={renderDetail} />
)}
</Modal>
);
}
const StartingOption = () => (
<label className="checkbox-row" style={{ alignSelf: 'end', paddingBottom: '0.6rem' }}>
<input type="checkbox" name="isStartingOption" />
Starting option (a player may pick it while building a character)
</label>
);
const startingBadge = (entry: { isStartingOption: boolean }) => entry.isStartingOption && <span className="badge">Starting</span>;
export function WeaponsSection({ campaignId, entries, onOpen, formRequested, onFormClosed }: SectionProps<Weapon>) {
const createWeapon = useCreateWeapon(campaignId);
const addFromLibrary = useAddWeaponFromLibrary(campaignId);
const { adding, error, setError, open, close } = useAdding(formRequested, onFormClosed);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
const fd = new FormData(e.target as HTMLFormElement);
setError(null);
try {
const weapon = await createWeapon.mutateAsync({
name: String(fd.get('name')).trim(),
damageDice: String(fd.get('damageDice')).trim(),
damageType: String(fd.get('damageType')).trim(),
attackAbility: fd.get('attackAbility') as Weapon['attackAbility'],
properties: [],
rangeNormal: null,
rangeLong: null,
damageScaling: Number(fd.get('damageScaling')),
minLevel: Number(fd.get('minLevel')),
isStartingOption: fd.get('isStartingOption') === 'on',
effects: [],
effectNote: null,
});
close();
onOpen({ kind: 'weapon', id: weapon.id, isNew: true });
} catch (err) {
setError(extractErrorMessage(err));
}
}
return (
<SectionCard
title="Weapons"
addLabel="+ Add Weapon"
onAdd={open}
intro={
<>
The weapons you hand out on each character's sheet. Open one to set the level it starts at, how fast its damage grows
(levels 1–{MAX_GEAR_LEVEL}), whether a new character may start with it, and what it does while equipped.
</>
}
>
<EntryList
entries={entries}
noun="weapons"
emptyText="No weapons yet. Add one by hand, or copy some from the library."
searchText={(w) => [w.name, w.damageDice, w.damageType, effectsSummary(w.effects, w.effectNote)]}
renderMeta={(w) => [`${w.damageDice} ${w.damageType}`, `Lv ${w.minLevel}`, effectsSummary(w.effects, w.effectNote) && `✦ ${effectsSummary(w.effects, w.effectNote)}`].filter(Boolean).join(' · ')}
renderBadges={startingBadge}
onOpen={(id) => onOpen({ kind: 'weapon', id })}
/>
{adding === 'library' && (
<LibraryModal<LibraryWeapon>
campaignId={campaignId}
title="Weapon library"
pick={(library) => library.weapons}
taken={entries}
adding={addFromLibrary.isPending}
onAdd={(key) => addFromLibrary.mutate(key, { onError: (err) => setError(extractErrorMessage(err)) })}
placeholder="Search the weapon library…"
renderMeta={(w) => `${w.category} · ${w.damageDice} ${w.damageType} · starts at level 1`}
renderDetail={(w) => effectsSummary(w.effects, w.effectNote)}
error={error}
onClose={close}
/>
)}
{adding === 'form' && (
<Modal title="Add a weapon" subtitle="What it does while equipped is set once it is added." onClose={close}>
{error && <ErrorBanner message={error} />}
<form onSubmit={handleSubmit}>
<div className="grid grid-cols-2">
<Field label="Name">{(id) => <input id={id} name="name" required maxLength={80} />}</Field>
<Field label="Damage at its starting level">{(id) => <input id={id} name="damageDice" placeholder="e.g. 1d8" required />}</Field>
<Field label="Damage type">{(id) => <input id={id} name="damageType" placeholder="e.g. slashing" required />}</Field>
<Field label="Attacks with">
{(id) => (
<select id={id} name="attackAbility" defaultValue="STR">
<option value="STR">STR</option>
<option value="DEX">DEX</option>
<option value="FINESSE">Finesse (the better of the two)</option>
</select>
)}
</Field>
<Field label="Level it starts at">{(id) => <StartLevelSelect id={id} name="minLevel" />}</Field>
<Field label="Growth per level">{(id) => <ScalingSelect id={id} name="damageScaling" />}</Field>
<StartingOption />
</div>
<button type="submit" className="btn btn-primary mt-md" disabled={createWeapon.isPending}>
Add Weapon
</button>
</form>
</Modal>
)}
</SectionCard>
);
}
export function ItemsSection({ campaignId, entries, onOpen, formRequested, onFormClosed }: SectionProps<Item>) {
const createItem = useCreateItem(campaignId);
const addFromLibrary = useAddItemFromLibrary(campaignId);
const { adding, error, setError, open, close } = useAdding(formRequested, onFormClosed);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
const fd = new FormData(e.target as HTMLFormElement);
setError(null);
try {
const item = await createItem.mutateAsync({
name: String(fd.get('name')).trim(),
description: String(fd.get('description') || '').trim() || null,
damageDice: String(fd.get('damageDice') || '').trim() || null,
damageScaling: Number(fd.get('damageScaling')),
minLevel: Number(fd.get('minLevel')),
isStartingOption: fd.get('isStartingOption') === 'on',
effects: [],
effectNote: null,
armorType: null,
});
close();
onOpen({ kind: 'item', id: item.id, isNew: true });
} catch (err) {
setError(extractErrorMessage(err));
}
}
return (
<SectionCard
title="Items"
addLabel="+ Add Item"
onAdd={open}
intro={
<>
Rope, potions, armor, quest items. Armor, shields, rings and the like are items with effects: open the item and set
what it does while equipped (chain mail: +6 AC, −10 Speed).
</>
}
>
<EntryList
entries={entries}
noun="items"
emptyText="No items yet. Add rope, potions, armor, quest items…"
searchText={(i) => [i.name, i.description, i.damageDice, effectsSummary(i.effects, i.effectNote)]}
renderMeta={(i) => [effectsSummary(i.effects, i.effectNote) && `✦ ${effectsSummary(i.effects, i.effectNote)}`, i.damageDice, i.description].filter(Boolean).join(' · ') || `Lv ${i.minLevel}`}
renderBadges={startingBadge}
onOpen={(id) => onOpen({ kind: 'item', id })}
/>
{adding === 'library' && (
<LibraryModal<LibraryItem>
campaignId={campaignId}
title="Item library"
pick={(library) => library.items}
taken={entries}
adding={addFromLibrary.isPending}
onAdd={(key) => addFromLibrary.mutate(key, { onError: (err) => setError(extractErrorMessage(err)) })}
placeholder="Search the item library: armor, shields, worn gear, supplies…"
renderMeta={(i) => [i.category, effectsSummary(i.effects, i.effectNote), i.damageDice].filter(Boolean).join(' · ')}
renderDetail={(i) => i.description}
error={error}
onClose={close}
/>
)}
{adding === 'form' && (
<Modal title="Add an item" subtitle="What it does while equipped is set once it is added." onClose={close}>
{error && <ErrorBanner message={error} />}
<form onSubmit={handleSubmit}>
<div className="grid grid-cols-2">
<Field label="Name">{(id) => <input id={id} name="name" required maxLength={80} />}</Field>
<Field label="Dice (optional)">{(id) => <input id={id} name="damageDice" placeholder="e.g. 2d4+2" maxLength={20} />}</Field>
<Field label="Description (optional)" style={{ gridColumn: '1 / -1' }}>
{(id) => <input id={id} name="description" />}
</Field>
<Field label="Level it starts at">{(id) => <StartLevelSelect id={id} name="minLevel" />}</Field>
<Field label="Growth of its dice per level">{(id) => <ScalingSelect id={id} name="damageScaling" />}</Field>
<StartingOption />
</div>
<button type="submit" className="btn btn-primary mt-md" disabled={createItem.isPending}>
Add Item
</button>
</form>
</Modal>
)}
</SectionCard>
);
}
export function SpellsSection({ campaignId, entries, onOpen, formRequested, onFormClosed }: SectionProps<Spell>) {
const createSpell = useCreateSpell(campaignId);
const addFromLibrary = useAddSpellFromLibrary(campaignId);
const { adding, error, setError, open, close } = useAdding(formRequested, onFormClosed);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
const fd = new FormData(e.target as HTMLFormElement);
setError(null);
try {
const spell = await createSpell.mutateAsync({
name: String(fd.get('name')).trim(),
level: Number(fd.get('level')),
school: String(fd.get('school') || '').trim() || null,
castingTime: null,
range: null,
duration: null,
description: String(fd.get('description') || '').trim() || null,
damageDice: String(fd.get('damageDice') || '') || null,
isStartingOption: fd.get('isStartingOption') === 'on',
revives: fd.get('revives') === 'on',
...landingFrom(String(fd.get('landing') || '')),
});
close();
onOpen({ kind: 'spell', id: spell.id, isNew: true });
} catch (err) {
setError(extractErrorMessage(err));
}
}
return (
<SectionCard
title="Spells"
addLabel="+ Add Spell"
onAdd={open}
intro="The spells you hand out on each character's sheet. A character must be at least a spell's level to cast it. Open one to change its damage, or whether a new character may start with it."
>
<EntryList
entries={entries}
noun="spells"
emptyText="No spells yet. Add one by hand, or copy some from the library."
searchText={(s) => [s.name, s.school, s.description, spellLevelLabel(s.level)]}
renderMeta={(s) => [spellLevelLabel(s.level), s.damageDice && `${s.damageDice} damage`, s.description].filter(Boolean).join(' · ')}
renderBadges={(s) => (
<>
{s.revives && <span className="badge">Revives</span>}
{startingBadge(s)}
</>
)}
onOpen={(id) => onOpen({ kind: 'spell', id })}
/>
{adding === 'library' && (
<LibraryModal<LibrarySpell>
campaignId={campaignId}
title="Spell library"
pick={(library) => library.spells}
taken={entries}
adding={addFromLibrary.isPending}
onAdd={(key) => addFromLibrary.mutate(key, { onError: (err) => setError(extractErrorMessage(err)) })}
placeholder="Search the spell library…"
renderMeta={(s) =>
[spellLevelLabel(s.level), spellRequirementLabel(s.level), s.damageDice ? `${s.damageDice} damage` : 'no damage', s.school].filter(Boolean).join(' · ')
}
renderDetail={(s) => s.description}
error={error}
onClose={close}
/>
)}
{adding === 'form' && (
<Modal title="Add a spell" onClose={close}>
{error && <ErrorBanner message={error} />}
<form onSubmit={handleSubmit}>
<div className="grid grid-cols-2">
<Field label="Name">{(id) => <input id={id} name="name" required maxLength={80} />}</Field>
<Field label="Level">
{(id) => (
<select id={id} name="level" defaultValue={0}>
{[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((level) => (
<option key={level} value={level}>
{spellLevelLabel(level)}
</option>
))}
</select>
)}
</Field>
<Field label="School (optional)">{(id) => <input id={id} name="school" />}</Field>
<Field label="Damage">{(id) => <SpellDamageSelect id={id} name="damageDice" />}</Field>
<Field label="In a battle" style={{ gridColumn: '1 / -1' }}>{(id) => <SpellLandingSelect id={id} name="landing" />}</Field>
<Field label="What it does (one sentence)" style={{ gridColumn: '1 / -1' }}>
{(id) => <input id={id} name="description" maxLength={4000} required />}
</Field>
<StartingOption />
<label className="checkbox-row" style={{ alignSelf: 'end', paddingBottom: '0.6rem' }}>
<input type="checkbox" name="revives" />
Revives the dead (its caster may revive a dead ally on their turn in a battle)
</label>
</div>
<button type="submit" className="btn btn-primary mt-md" disabled={createSpell.isPending}>
Add Spell
</button>
</form>
</Modal>
)}
</SectionCard>
);
}
export function MonstersSection({ campaignId, entries, onOpen, formRequested, onFormClosed }: SectionProps<Monster>) {
const createMonster = useCreateMonster(campaignId);
const addFromLibrary = useAddMonsterFromLibrary(campaignId);
const { adding, error, setError, open, close } = useAdding(formRequested, onFormClosed);
return (
<SectionCard
title="Monsters"
addLabel="+ Add Monster"
onAdd={open}
intro="The stat blocks you bring into battles. Players never see them. Open one for the whole block, or to change it."
>
<EntryList
entries={entries}
noun="monsters"
emptyText="No monsters yet. Add one by hand, or copy some from the library."
searchText={(m) => [m.name, m.challengeRating && `CR ${m.challengeRating}`, m.specialTrait, m.notes]}
renderMeta={(m) => `CR ${m.challengeRating || '—'} · AC ${m.ac} · HP ${m.maxHp} · attack ${fmtMod(m.attackBonus)}${m.damageDice ? ` for ${m.damageDice}` : ''}`}
onOpen={(id) => onOpen({ kind: 'monster', id })}
/>
{adding === 'library' && (
<LibraryModal<LibraryMonster>
campaignId={campaignId}
title="Monster library"
pick={(library) => library.monsters}
taken={entries}
adding={addFromLibrary.isPending}
onAdd={(key) => addFromLibrary.mutate(key, { onError: (err) => setError(extractErrorMessage(err)) })}
placeholder="Search the monster library…"
renderMeta={(m) =>
`CR ${m.challengeRating ?? '—'} · AC ${m.ac} · HP ${m.maxHp} · speed ${m.speed} · attack ${fmtMod(m.attackBonus)}${m.damageDice ? ` for ${m.damageDice}` : ''} · ${abilityLine(m)}`
}
renderDetail={(m) => [m.specialTrait, m.notes].filter(Boolean).join(' — ') || null}
error={error}
onClose={close}
/>
)}
{adding === 'form' && (
<Modal title="Add a monster" wide onClose={close}>
{error && <ErrorBanner message={error} />}
<MonsterForm
saving={createMonster.isPending}
onSave={async (stats) => {
setError(null);
try {
const monster = await createMonster.mutateAsync(stats);
close();
onOpen({ kind: 'monster', id: monster.id, isNew: true });
} catch (err) {
setError(extractErrorMessage(err));
throw err;
}
}}
/>
</Modal>
)}
</SectionCard>
);
}
export function NpcsSection({ campaignId, entries, onOpen, formRequested, onFormClosed }: SectionProps<Npc>) {
const createNpc = useCreateNpc(campaignId);
const { adding, error, setError, open, close } = useAdding(formRequested, onFormClosed);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
const fd = new FormData(e.target as HTMLFormElement);
const text = (key: string) => String(fd.get(key) || '').trim() || null;
const num = (key: string) => (fd.get(key) ? Number(fd.get(key)) : null);
setError(null);
try {
const npc = await createNpc.mutateAsync({
name: String(fd.get('name')).trim(),
role: text('role'),
disposition: fd.get('disposition') as NpcDisposition,
description: text('description'),
dmNotes: text('dmNotes'),
ac: num('ac'),
maxHp: num('maxHp'),
attackBonus: num('attackBonus'),
damageDice: text('damageDice'),
});
close();
onOpen({ kind: 'npc', id: npc.id, isNew: true });
} catch (err) {
setError(extractErrorMessage(err));
}
}
return (
<SectionCard
title="NPCs"
addLabel="+ Add NPC"
hasLibrary={false}
onAdd={open}
intro="The people your party meets. Add them to an encounter to bring them into a scene. Players never see your notes or an NPC's stats. Open one to set what they sell and the rate they change gold and cash at; players see both when they meet the NPC in a quest."
>
<EntryList
entries={entries}
noun="NPCs"
emptyText="No NPCs yet."
searchText={(n) => [n.name, n.role, n.disposition, n.description, n.dmNotes]}
renderMeta={(n) => [n.role, n.description].filter(Boolean).join(' · ')}
renderBadges={(n) => (
<>
{rateLabel(n) && <span className="badge">💱 {rateLabel(n)}</span>}
{(n.wares?.length ?? 0) > 0 && <span className="badge">🛒 {n.wares?.length}</span>}
<span className={`badge badge-${n.disposition.toLowerCase()}`}>{n.disposition}</span>
</>
)}
onOpen={(id) => onOpen({ kind: 'npc', id })}
/>
{adding === 'form' && (
<Modal title="Add an NPC" subtitle="Only the name is needed. What they sell is set once they are added." onClose={close}>
{error && <ErrorBanner message={error} />}
<form onSubmit={handleSubmit}>
<div className="grid grid-cols-2">
<Field label="Name">{(id) => <input id={id} name="name" required maxLength={80} />}</Field>
<Field label="Role">{(id) => <input id={id} name="role" placeholder="innkeeper, captain…" maxLength={80} />}</Field>
<Field label="Attitude toward the party">
{(id) => (
<select id={id} name="disposition" defaultValue="NEUTRAL">
<option value="FRIENDLY">Friendly</option>
<option value="NEUTRAL">Neutral</option>
<option value="HOSTILE">Hostile</option>
</select>
)}
</Field>
</div>
<Field label="What the party sees and knows (shown to players)" style={{ marginTop: '0.75rem' }}>
{(id) => <textarea id={id} name="description" rows={2} className="textarea-block" />}
</Field>
<Field label="Secrets and motives (only you see this)" style={{ marginTop: '0.75rem' }}>
{(id) => <textarea id={id} name="dmNotes" rows={2} className="textarea-block" />}
</Field>
<div className="section-label mt-md">Combat stats (optional)</div>
<div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(110px, 1fr))' }}>
<Field label="AC">{(id) => <NumberInput id={id} name="ac" min={0} max={50} />}</Field>
<Field label="HP">{(id) => <NumberInput id={id} name="maxHp" min={1} max={100000} />}</Field>
<Field label="Attack bonus">{(id) => <NumberInput id={id} name="attackBonus" min={-20} max={50} />}</Field>
<Field label="Damage">{(id) => <input id={id} name="damageDice" placeholder="e.g. 1d6" maxLength={20} />}</Field>
</div>
<button type="submit" className="btn btn-primary mt-md" disabled={createNpc.isPending}>
Add NPC
</button>
</form>
</Modal>
)}
</SectionCard>
);
}