- Turn-order track: names coloured by PC, NPC or monster, this round, a flag where it ends, and the next round - Target by clicking a name on the track, the card, or keys 1-9; whoever is on turn and every target show what they have in hand - Attacks and spells are declared, rolled and applied: type or roll the d20 and the app says hit, miss or critical; a save spell asks each target for its save against the caster's DC; the DM overrules anything and applies - Critical damage by the campaign's rule; a spell spends its slot; a concentration save is called for - Auto-rolled monster and NPC attacks: aimed (weighted), rolled, and offered to the DM to accept, edit or discard; hidden from players until accepted - Monsters can have named attacks and multiattacks; spells say how they land - A "What now" line tells the DM (and each player) what the scene waits on Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
434 lines
17 KiB
TypeScript
434 lines
17 KiB
TypeScript
import { useId, useState, type CSSProperties, type ReactNode } from 'react';
|
||
import { Link } from 'react-router-dom';
|
||
import { NumberInput } from '../NumberInput';
|
||
import { Pagination } from '../Paginated';
|
||
import { usePagination } from '../../hooks/usePagination';
|
||
import { SPELL_DAMAGE_GROUPS, SPELL_DAMAGE_SPECIALS } from '../../lib/format';
|
||
import { ABILITY_ORDER, DAMAGE_SCALING_LABELS, MAX_GEAR_LEVEL } from '../../lib/previewCalc';
|
||
import { landingFrom, matchesSearch, scoreField, type MonsterInput, type SpellLanding } from '../../lib/campaignEntries';
|
||
import type { Ability, Monster, MonsterAttack } from '../../api/types';
|
||
|
||
// A labelled field in a pop-out form. The child is handed the id its label points at.
|
||
export function Field({ label, style, children }: { label: string; style?: CSSProperties; children: (id: string) => ReactNode }) {
|
||
const id = useId();
|
||
return (
|
||
<div className="field" style={{ marginBottom: 0, ...style }}>
|
||
<label htmlFor={id}>{label}</label>
|
||
{children(id)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const LANDING_ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
|
||
const ABILITY_NAMES: Record<Ability, string> = { STR: 'Strength', DEX: 'Dexterity', CON: 'Constitution', INT: 'Intelligence', WIS: 'Wisdom', CHA: 'Charisma' };
|
||
|
||
// How a spell lands in a battle, as one choice (lib/campaignEntries.ts, SpellLanding).
|
||
export function SpellLandingSelect({ id, name, value, onChange }: { id?: string; name?: string; value?: string; onChange?: (landing: SpellLanding) => void }) {
|
||
return (
|
||
<select
|
||
id={id}
|
||
name={name}
|
||
title="In a battle: whether the caster rolls to hit, each target makes a saving throw, or it simply happens"
|
||
{...(onChange ? { value, onChange: (e) => onChange(landingFrom(e.target.value)) } : { defaultValue: '' })}
|
||
>
|
||
<option value="">It just takes effect (no roll)</option>
|
||
<option value="ATTACK">The caster rolls a spell attack</option>
|
||
{LANDING_ABILITIES.map((a) => (
|
||
<optgroup key={a} label={`${ABILITY_NAMES[a]} save`}>
|
||
<option value={`${a}:HALF`}>{ABILITY_NAMES[a]} save, half damage on a success</option>
|
||
<option value={`${a}:NONE`}>{ABILITY_NAMES[a]} save, nothing on a success</option>
|
||
</optgroup>
|
||
))}
|
||
</select>
|
||
);
|
||
}
|
||
|
||
// How fast a weapon's or item's dice grow as the DM levels a held copy up.
|
||
export function ScalingSelect({ id, name, value, onChange }: { id?: string; name?: string; value?: number; onChange?: (scaling: number) => void }) {
|
||
return (
|
||
<select
|
||
id={id}
|
||
name={name}
|
||
aria-label="How fast the dice grow per level"
|
||
title="How fast the dice grow each time a held copy is levelled up"
|
||
{...(onChange ? { value, onChange: (e) => onChange(Number(e.target.value)) } : { defaultValue: 1 })}
|
||
>
|
||
{Object.entries(DAMAGE_SCALING_LABELS).map(([scaling, label]) => (
|
||
<option key={scaling} value={scaling}>
|
||
{label}
|
||
</option>
|
||
))}
|
||
</select>
|
||
);
|
||
}
|
||
|
||
const GEAR_LEVELS = Array.from({ length: MAX_GEAR_LEVEL }, (_, i) => i + 1);
|
||
|
||
// The level a weapon or item starts at. A held copy is never below it, and a
|
||
// character must be at least this level to use it.
|
||
export function StartLevelSelect({ id, name, value, onChange }: { id?: string; name?: string; value?: number; onChange?: (minLevel: number) => void }) {
|
||
return (
|
||
<select
|
||
id={id}
|
||
name={name}
|
||
aria-label="Level it starts at"
|
||
title="The level this starts at — a character must be at least this level to use it"
|
||
{...(onChange ? { value, onChange: (e) => onChange(Number(e.target.value)) } : { defaultValue: 1 })}
|
||
>
|
||
{GEAR_LEVELS.map((level) => (
|
||
<option key={level} value={level}>
|
||
Starts at Lv {level}
|
||
</option>
|
||
))}
|
||
</select>
|
||
);
|
||
}
|
||
|
||
// A spell's damage is picked from a list rather than typed. A value that is
|
||
// not in the list (set through the API, say) is still shown and kept.
|
||
export function SpellDamageSelect({
|
||
id,
|
||
name,
|
||
spellName,
|
||
value,
|
||
onChange,
|
||
}: {
|
||
id?: string;
|
||
name?: string;
|
||
spellName?: string;
|
||
value?: string | null;
|
||
onChange?: (damageDice: string | null) => void;
|
||
}) {
|
||
const known = [...SPELL_DAMAGE_GROUPS.flatMap((g) => g.options), ...SPELL_DAMAGE_SPECIALS];
|
||
const others = value && !known.includes(value) ? [...SPELL_DAMAGE_SPECIALS, value] : SPELL_DAMAGE_SPECIALS;
|
||
return (
|
||
<select
|
||
id={id}
|
||
name={name}
|
||
aria-label={spellName ? `${spellName} damage` : 'Damage'}
|
||
{...(onChange ? { value: value ?? '', onChange: (e) => onChange(e.target.value || null) } : { defaultValue: '' })}
|
||
>
|
||
<option value="">No damage</option>
|
||
{SPELL_DAMAGE_GROUPS.map((group) => (
|
||
<optgroup key={group.label} label={group.label}>
|
||
{group.options.map((dice) => (
|
||
<option key={dice} value={dice}>
|
||
{dice}
|
||
</option>
|
||
))}
|
||
</optgroup>
|
||
))}
|
||
<optgroup label="Other">
|
||
{others.map((dice) => (
|
||
<option key={dice} value={dice}>
|
||
{dice}
|
||
</option>
|
||
))}
|
||
</optgroup>
|
||
</select>
|
||
);
|
||
}
|
||
|
||
// The whole stat block, field for field as a printed one gives it. Adds a
|
||
// monster, or edits one when `monster` is passed (its values fill the form).
|
||
export function MonsterForm({
|
||
monster,
|
||
saving,
|
||
onSave,
|
||
onCancel,
|
||
}: {
|
||
monster?: Monster;
|
||
saving: boolean;
|
||
// Rejects if the save failed, so the form keeps what was typed.
|
||
onSave: (data: MonsterInput) => Promise<void>;
|
||
onCancel?: () => void;
|
||
}) {
|
||
// Named attacks, as typed: kept as text until saved.
|
||
const [attacks, setAttacks] = useState<{ name: string; attackBonus: string; damageDice: string; damageType: string; count: string }[]>(() =>
|
||
(monster?.attacks ?? []).map((a) => ({
|
||
name: a.name,
|
||
attackBonus: String(a.attackBonus),
|
||
damageDice: a.damageDice ?? '',
|
||
damageType: a.damageType ?? '',
|
||
count: String(a.count ?? 1),
|
||
}))
|
||
);
|
||
const setAttack = (index: number, change: Partial<(typeof attacks)[number]>) => setAttacks((rows) => rows.map((row, i) => (i === index ? { ...row, ...change } : row)));
|
||
const field = (name: string, label: string, input: ReactNode, style?: CSSProperties) => (
|
||
<div className="field" style={{ marginBottom: 0, ...style }}>
|
||
<label htmlFor={`monster-${name}`}>{label}</label>
|
||
{input}
|
||
</div>
|
||
);
|
||
const number = (name: keyof MonsterInput, label: string, min: number, max: number, fallback?: number) =>
|
||
field(
|
||
name,
|
||
label,
|
||
<NumberInput
|
||
id={`monster-${name}`}
|
||
name={name}
|
||
min={min}
|
||
max={max}
|
||
defaultValue={(monster?.[name] as number | undefined) ?? fallback}
|
||
keepValue={fallback !== undefined}
|
||
required
|
||
/>
|
||
);
|
||
|
||
return (
|
||
<form
|
||
onSubmit={async (e) => {
|
||
e.preventDefault();
|
||
const fd = new FormData(e.target as HTMLFormElement);
|
||
const text = (key: string) => String(fd.get(key) || '').trim() || null;
|
||
const num = (key: string) => Number(fd.get(key));
|
||
try {
|
||
await onSave({
|
||
name: String(fd.get('name')).trim(),
|
||
challengeRating: text('challengeRating'),
|
||
ac: num('ac'),
|
||
maxHp: num('maxHp'),
|
||
speed: num('speed'),
|
||
attackBonus: num('attackBonus'),
|
||
damageDice: text('damageDice'),
|
||
strScore: num('strScore'),
|
||
dexScore: num('dexScore'),
|
||
conScore: num('conScore'),
|
||
intScore: num('intScore'),
|
||
wisScore: num('wisScore'),
|
||
chaScore: num('chaScore'),
|
||
specialTrait: text('specialTrait'),
|
||
notes: text('notes'),
|
||
attacks: attacks
|
||
.filter((a) => a.name.trim())
|
||
.map(
|
||
(a): MonsterAttack => ({
|
||
name: a.name.trim(),
|
||
attackBonus: Math.trunc(Number(a.attackBonus)) || 0,
|
||
damageDice: a.damageDice.trim() || null,
|
||
damageType: a.damageType.trim() || null,
|
||
count: Math.min(10, Math.max(1, Math.trunc(Number(a.count)) || 1)),
|
||
})
|
||
),
|
||
});
|
||
} catch {
|
||
// Whoever opened the form shows the error; what was typed stays.
|
||
}
|
||
}}
|
||
>
|
||
<div className="grid grid-cols-3">
|
||
{field('name', 'Name', <input id="monster-name" name="name" defaultValue={monster?.name} required maxLength={80} />)}
|
||
{field(
|
||
'challengeRating',
|
||
'CR (Challenge Rating)',
|
||
<input id="monster-challengeRating" name="challengeRating" defaultValue={monster?.challengeRating ?? ''} placeholder="e.g. 1/4 or 3" maxLength={10} />
|
||
)}
|
||
{number('ac', 'AC (Armor Class)', 0, 50)}
|
||
{number('maxHp', 'HP (Hit Points)', 1, 100000)}
|
||
{number('speed', 'Speed (feet)', 0, 1000, 30)}
|
||
{number('attackBonus', 'Attack bonus', -20, 50, 0)}
|
||
{field(
|
||
'damageDice',
|
||
'Damage',
|
||
<input id="monster-damageDice" name="damageDice" defaultValue={monster?.damageDice ?? ''} placeholder="e.g. 1d6+2 necrotic" maxLength={60} />
|
||
)}
|
||
</div>
|
||
<div className="grid mt-sm" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(80px, 1fr))' }}>
|
||
{ABILITY_ORDER.map((a) => number(scoreField(a), a, 1, 30, 10))}
|
||
</div>
|
||
<div className="field" style={{ marginTop: '0.5rem', marginBottom: 0 }}>
|
||
<label>Named attacks (optional)</label>
|
||
<p className="combatant-sub" style={{ margin: '0 0 0.3rem' }}>
|
||
For a creature with more than the one attack above: each with its own bonus and damage, and how many times it is made each turn (a multiattack).
|
||
With any listed here, these are what it attacks with.
|
||
</p>
|
||
{attacks.map((a, i) => (
|
||
<div key={i} className="flex-row flex-wrap gap-sm" style={{ marginBottom: '0.3rem' }}>
|
||
<input aria-label="Attack name" placeholder="Claw" value={a.name} maxLength={40} onChange={(e) => setAttack(i, { name: e.target.value })} style={{ flex: '2 1 110px' }} />
|
||
<NumberInput aria-label="Attack bonus" placeholder="+hit" min={-20} max={50} value={a.attackBonus} onChange={(e) => setAttack(i, { attackBonus: e.target.value })} style={{ width: 70 }} />
|
||
<input aria-label="Damage dice" placeholder="2d6+3" value={a.damageDice} maxLength={60} onChange={(e) => setAttack(i, { damageDice: e.target.value })} style={{ flex: '1 1 80px' }} />
|
||
<input aria-label="Damage type" placeholder="slashing" value={a.damageType} maxLength={30} onChange={(e) => setAttack(i, { damageType: e.target.value })} style={{ flex: '1 1 80px' }} />
|
||
<NumberInput aria-label="Times per turn" title="How many times it is made each turn" min={1} max={10} value={a.count} onChange={(e) => setAttack(i, { count: e.target.value })} style={{ width: 60 }} />
|
||
<button type="button" className="btn btn-ghost" aria-label={`Remove attack ${a.name || i + 1}`} onClick={() => setAttacks((rows) => rows.filter((_, at) => at !== i))}>
|
||
✕
|
||
</button>
|
||
</div>
|
||
))}
|
||
{attacks.length < 8 && (
|
||
<button type="button" className="btn btn-sm" onClick={() => setAttacks((rows) => [...rows, { name: '', attackBonus: String(monster?.attackBonus ?? 0), damageDice: '', damageType: '', count: '1' }])}>
|
||
+ Add an attack
|
||
</button>
|
||
)}
|
||
</div>
|
||
{field(
|
||
'specialTrait',
|
||
'Special trait',
|
||
<input
|
||
id="monster-specialTrait"
|
||
name="specialTrait"
|
||
defaultValue={monster?.specialTrait ?? ''}
|
||
placeholder="The one thing that makes it different"
|
||
maxLength={500}
|
||
/>,
|
||
{ marginTop: '0.5rem' }
|
||
)}
|
||
{field(
|
||
'notes',
|
||
'Notes',
|
||
<textarea
|
||
id="monster-notes"
|
||
name="notes"
|
||
rows={3}
|
||
className="textarea-block"
|
||
defaultValue={monster?.notes ?? ''}
|
||
placeholder="Everything else: other speeds (fly 30, swim 40), extra attacks, spells, tactics, resistances, senses, what it drops"
|
||
maxLength={2000}
|
||
/>,
|
||
{ marginTop: '0.5rem' }
|
||
)}
|
||
<div className="flex-row mt-md">
|
||
<button type="submit" className="btn btn-primary" disabled={saving}>
|
||
{monster ? 'Save Changes' : 'Add Monster'}
|
||
</button>
|
||
{onCancel && (
|
||
<button type="button" className="btn btn-ghost" onClick={onCancel}>
|
||
Cancel
|
||
</button>
|
||
)}
|
||
</div>
|
||
</form>
|
||
);
|
||
}
|
||
|
||
// The built-in library, searched by name, with what the campaign already
|
||
// holds left out. It stays open after an add, for adding several in a row.
|
||
export function LibraryPicker<T extends { key: string; name: string }>({
|
||
items,
|
||
taken,
|
||
onAdd,
|
||
adding,
|
||
renderMeta,
|
||
renderDetail,
|
||
placeholder,
|
||
}: {
|
||
items: T[];
|
||
// What the campaign already holds: a library entry by one of these names is
|
||
// left out, since each can be added once.
|
||
taken: { name: string }[] | undefined;
|
||
onAdd: (key: string) => void;
|
||
adding: boolean;
|
||
renderMeta: (item: T) => string;
|
||
// A sentence on what the entry is or does, shown under its name.
|
||
renderDetail?: (item: T) => string | null;
|
||
placeholder: string;
|
||
}) {
|
||
const [query, setQuery] = useState('');
|
||
const takenNames = new Set((taken ?? []).map((t) => t.name.toLowerCase()));
|
||
const available = items.filter((i) => !takenNames.has(i.name.toLowerCase()));
|
||
const filtered = available.filter((i) => matchesSearch(query, i.name));
|
||
const { pageItems, page, pageCount, prevPage, nextPage, setPage } = usePagination(filtered, 8);
|
||
|
||
return (
|
||
<div>
|
||
<input type="search" placeholder={placeholder} aria-label={placeholder} value={query} onChange={(e) => setQuery(e.target.value)} style={{ width: '100%' }} />
|
||
<div className="mt-sm">
|
||
{pageItems.map((item) => (
|
||
<div key={item.key} className="flex-between" style={{ padding: '0.45rem 0', borderBottom: '1px solid var(--border-soft)', flexWrap: 'nowrap' }}>
|
||
<div style={{ minWidth: 0 }}>
|
||
<strong>{item.name}</strong>
|
||
<span style={{ color: 'var(--text-muted)', marginLeft: 6, fontSize: '0.85rem' }}>{renderMeta(item)}</span>
|
||
{renderDetail?.(item) && <div style={{ fontSize: '0.9rem' }}>{renderDetail(item)}</div>}
|
||
</div>
|
||
<button className="btn" style={{ flex: 'none' }} disabled={adding} aria-label={`Add ${item.name}`} onClick={() => onAdd(item.key)}>
|
||
+ Add
|
||
</button>
|
||
</div>
|
||
))}
|
||
{filtered.length === 0 && (
|
||
<p style={{ color: 'var(--text-muted)' }}>
|
||
{available.length === 0 ? 'Everything in the library is already in this campaign.' : 'No matches.'}
|
||
</p>
|
||
)}
|
||
</div>
|
||
<Pagination page={page} pageCount={pageCount} onPrev={prevPage} onNext={nextPage} onJump={setPage} />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// One line of a list: what it is and a few words about it. The rest is in
|
||
// the pop-out it opens, or on the page it links to when given `to`.
|
||
export function EntryRow({ name, meta, badges, onOpen, to }: { name: string; meta?: ReactNode; badges?: ReactNode; onOpen?: () => void; to?: string }) {
|
||
const inner = (
|
||
<>
|
||
<span className="entry-row-main">
|
||
<span className="entry-row-name">{name}</span>
|
||
{meta && <span className="entry-row-meta">{meta}</span>}
|
||
</span>
|
||
{badges && <span className="entry-row-badges">{badges}</span>}
|
||
<span className="entry-row-chevron" aria-hidden>
|
||
›
|
||
</span>
|
||
</>
|
||
);
|
||
return to ? (
|
||
<Link to={to} className="entry-row">
|
||
{inner}
|
||
</Link>
|
||
) : (
|
||
<button type="button" className="entry-row" onClick={onOpen}>
|
||
{inner}
|
||
</button>
|
||
);
|
||
}
|
||
|
||
// A campaign list as short rows: searched by a box of its own, paged, and
|
||
// each row opening its pop-out.
|
||
export function EntryList<T extends { id: string; name: string }>({
|
||
entries,
|
||
noun,
|
||
emptyText,
|
||
searchText,
|
||
renderMeta,
|
||
renderBadges,
|
||
onOpen,
|
||
}: {
|
||
entries: T[] | undefined;
|
||
// What the list holds, in the plural: "weapons".
|
||
noun: string;
|
||
emptyText: string;
|
||
// Everything about an entry that a search should find it by.
|
||
searchText: (entry: T) => (string | number | null | undefined)[];
|
||
renderMeta: (entry: T) => ReactNode;
|
||
renderBadges?: (entry: T) => ReactNode;
|
||
onOpen: (id: string) => void;
|
||
}) {
|
||
const [query, setQuery] = useState('');
|
||
const filtered = (entries ?? []).filter((entry) => matchesSearch(query, ...searchText(entry)));
|
||
const { pageItems, page, pageCount, prevPage, nextPage, setPage } = usePagination(filtered, 10);
|
||
|
||
if (entries && entries.length === 0) return <p className="mt-sm" style={{ color: 'var(--text-muted)' }}>{emptyText}</p>;
|
||
return (
|
||
<>
|
||
<input
|
||
type="search"
|
||
className="mt-sm"
|
||
style={{ width: '100%' }}
|
||
placeholder={`Search the ${noun} in this campaign…`}
|
||
aria-label={`Search the ${noun} in this campaign`}
|
||
value={query}
|
||
onChange={(e) => {
|
||
setQuery(e.target.value);
|
||
setPage(1);
|
||
}}
|
||
/>
|
||
<div className="entry-list mt-sm">
|
||
{pageItems.map((entry) => (
|
||
<EntryRow key={entry.id} name={entry.name} meta={renderMeta(entry)} badges={renderBadges?.(entry)} onOpen={() => onOpen(entry.id)} />
|
||
))}
|
||
</div>
|
||
{entries && filtered.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No {noun} match "{query}".</p>}
|
||
<Pagination page={page} pageCount={pageCount} onPrev={prevPage} onNext={nextPage} onJump={setPage} />
|
||
</>
|
||
);
|
||
}
|