V1.21.0: a DM's toolkit: the battle at a glance, subclasses, character state, rolls, XP

Seven steps in one commit, 1.15.0 to 1.21.0. They change the same files
and were not saved apart, so they go in together.

- The battle at a glance (1.15). A strip across the top of an encounter
  lists everyone in turn order and stays in view; a click goes to that
  card. On a wide screen the stat block of whoever is on turn stays
  beside the cards, and Pin keeps anyone else's there. Saving throws,
  every skill and passive Perception, Investigation and Insight are on
  encounter cards and in the character panel, which "Sheet" on a card
  and a button on the party overview open. For the DM, N is Next Turn
  and S opens the sheet of whoever is on turn. The party overview shows
  passive scores and spell save DC.
- Subclasses (1.16). Three per class, picked in the level-up checklist
  at level 2 (cleric, druid, wizard) or 3, shown beside the class
  everywhere, and changed by the DM from the sheet: the old one's lines
  come out of Special Abilities and the new one's go in. Characters
  already at that level keep the path they were on.
- Character state (1.17). Inspiration, exhaustion and conditions on the
  sheet and in the panel, and counters for what a class does a set
  number of times (Rage, Ki, Channel Divinity...), which the player
  spends and a rest gives back. A long rest takes a level of exhaustion
  off. A character's conditions are their own now: they stay from one
  encounter to the next.
- Faster battles (1.18). Up to 20 of a monster added at once, numbered.
  One button rolls initiative for the monsters and NPCs. A condition can
  be given a number of rounds and then comes off by itself. Hovering
  over a condition shows its rule, and damaging someone who is
  Concentrating shows the save to call for.
- Rolls from the sheet (1.19). A number with a dotted underline rolls
  when clicked, with its bonus: skills, saves, ability checks, attacks,
  damage, spell dice, and a monster's attack, damage and abilities. The
  dice roller has advantage and disadvantage. "Call for a roll" rolls
  one check or save for the whole party. Rolls stay in the browser.
- XP and difficulty (1.20). An encounter shows the DM how hard it is,
  Trivial to Deadly, from the monsters' challenge ratings against the
  characters in it, and what it is worth in XP; one button shares that
  out, once. The sheet and the party overview show XP and when a level
  is due. Levelling up stays the DM's decision.
- Subclasses are optional per campaign (1.21). With "Characters choose a
  subclass" unticked in the campaign's Settings nobody is asked, each
  class follows its first subclass, and none is named.
- Conditions, exhaustion, counters and subclass features are reminders
  for the table: none of them changes a number on the sheet.
- The docs cover all of it, with generated tables of what each subclass
  adds.
- New migrations: a character's subclass; inspiration, exhaustion,
  conditions and spent counters on a character; the rounds left on a
  combatant's conditions; the XP awarded for an encounter; the
  campaign's subclass setting.
- All packages at version 1.21.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-10 17:36:27 +02:00
co-authored by Claude Opus 5.5
parent 61221f262c
commit 57fba68a48
50 changed files with 4706 additions and 592 deletions
+65 -18
View File
@@ -3,13 +3,17 @@ import { useCampaign, useCampaignCharacters, usePatchCharacterWeapon, usePatchIn
import { useAuth } from '../auth/useAuth';
import { useLastCampaignId } from '../lib/lastCampaign';
import { closeCharacterPanel, openCharacterPanel, useCharacterPanelId } from '../lib/characterPanel';
import { CLASS_LABELS, SPECIES_LABELS, fmtMod, formatPurse, spellLevelLabel } from '../lib/format';
import { SPECIES_LABELS, classLabel, fmtMod, formatPurse, spellLevelLabel } from '../lib/format';
import { effectLabel, effectsSummary } from '../lib/gear';
import { speciesIcon } from '../lib/speciesIcons';
import { Spinner, ErrorBanner } from './Spinner';
import { HpBar } from './HpBar';
import { DeathSaves } from './DeathSaves';
import { SpellSlotTracker } from './SpellSlots';
import { SheetNumbers } from './SheetNumbers';
import { CharacterState } from './CharacterState';
import { Rollable } from './Rollable';
import { withBonus } from '../lib/diceRoller';
import { useState } from 'react';
import { extractErrorMessage } from '../lib/format';
import type { ActiveGear } from '../api/types';
@@ -73,7 +77,7 @@ function PanelBody({ characterId, isDM }: { characterId: string; isDM: boolean }
<span aria-hidden="true">{speciesIcon(data.species)}</span> {data.name}
</h3>
<div className="combatant-sub">
{data.species && SPECIES_LABELS[data.species]} {data.characterClass && CLASS_LABELS[data.characterClass]} · Level {data.level}
{data.species && SPECIES_LABELS[data.species]} {classLabel(data.characterClass, data.subclassName)} · Level {data.level}
</div>
</div>
<Link to={`/characters/${data.id}`} className="btn" onClick={closeCharacterPanel}>
@@ -113,6 +117,37 @@ function PanelBody({ characterId, isDM }: { characterId: string; isDM: boolean }
))}
</div>
<div className="mt-sm">
<CharacterState
characterId={characterId}
name={data.name}
inspiration={data.inspiration}
exhaustion={data.exhaustion}
conditions={data.conditions}
resources={data.resources}
canUse={!data.restricted}
isDM={isDM}
onError={(err) => setEquipError(extractErrorMessage(err))}
/>
</div>
<details className="card mt-md" open>
<summary className="card-title">Saves and skills</summary>
<SheetNumbers
who={data.name}
saves={data.saves}
skills={data.skills}
passives={{ perception: data.passivePerception, investigation: data.passiveInvestigation, insight: data.passiveInsight }}
/>
</details>
{data.specialAbilities && (
<details className="card mt-md" open>
<summary className="card-title">Special Abilities</summary>
<p style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{data.specialAbilities}</p>
</details>
)}
{(data.gear.effects.length > 0 || data.gear.notes.length > 0) && (
<div className="card mt-md">
<div className="card-title">From equipped gear</div>
@@ -125,7 +160,10 @@ function PanelBody({ characterId, isDM }: { characterId: string; isDM: boolean }
<div className="card mt-md">
<div className="card-title">Spellcasting</div>
<p style={{ margin: 0 }}>
Save DC {data.spellcasting.saveDC} · Attack {fmtMod(data.spellcasting.attackBonus)}
Save DC {data.spellcasting.saveDC} ·{' '}
<Rollable label={`${data.name}: spell attack`} modifier={data.spellcasting.attackBonus}>
Attack {fmtMod(data.spellcasting.attackBonus)}
</Rollable>
</p>
{/* The character's own player and the DM spend slots here; the DM can also give them back. */}
{data.spellSlots && (
@@ -158,7 +196,15 @@ function PanelBody({ characterId, isDM }: { characterId: string; isDM: boolean }
{w.quantity > 1 && <span className="combatant-sub"> ×{w.quantity}</span>}
<Flags equipped={w.equipped} usable={w.usable} level={w.level} />
<div className="combatant-sub">
Lv {w.level} · attack {fmtMod(w.attackBonus)} · {w.damageDice} {fmtMod(w.damageBonus)} {w.damageType}
Lv {w.level} ·{' '}
<Rollable label={`${data.name}: ${w.name} attack`} modifier={w.attackBonus}>
attack {fmtMod(w.attackBonus)}
</Rollable>{' '}
·{' '}
<Rollable label={`${data.name}: ${w.name} damage`} dice={withBonus(w.damageDice, w.damageBonus)}>
{w.damageDice} {fmtMod(w.damageBonus)}
</Rollable>{' '}
{w.damageType}
</div>
{effectsSummary(w.effects, w.effectNote) && <div className="combatant-sub">✦ {effectsSummary(w.effects, w.effectNote)}</div>}
</div>
@@ -181,8 +227,8 @@ function PanelBody({ characterId, isDM }: { characterId: string; isDM: boolean }
<p className="combatant-sub mt-md">Their pack, spells and purse are their own business.</p>
) : (
<>
<div className="card mt-md">
<div className="card-title">Inventory · {data.inventory.length}</div>
<details className="card mt-md" open>
<summary className="card-title">Inventory · {data.inventory.length}</summary>
{data.inventory.length === 0 && <p className="combatant-sub" style={{ margin: 0 }}>Nothing carried.</p>}
{data.inventory.map((item) => (
<div key={item.inventoryItemId} className="reward-row">
@@ -209,7 +255,7 @@ function PanelBody({ characterId, isDM }: { characterId: string; isDM: boolean }
</div>
</div>
))}
</div>
</details>
<div className="card mt-md">
<div className="card-title">
@@ -219,32 +265,33 @@ function PanelBody({ characterId, isDM }: { characterId: string; isDM: boolean }
</div>
{data.spells.length > 0 && (
<div className="card mt-md">
<div className="card-title">Spells · {data.spells.length}</div>
<details className="card mt-md" open>
<summary className="card-title">Spells · {data.spells.length}</summary>
{data.spells.map((s) => (
<div key={s.characterSpellId} className="reward-row">
<strong>{s.name}</strong>
<span className="combatant-sub">
{' '}
{spellLevelLabel(s.level)}
{s.damageDice && ` · ${s.damageDice}`}
{s.damageDice && (
<>
{' · '}
<Rollable label={`${data.name}: ${s.name}`} dice={s.damageDice}>
{s.damageDice}
</Rollable>
</>
)}
</span>
{s.prepared && <span className="badge badge-live" style={{ marginLeft: 6 }}>prepared</span>}
{!s.usable && <span className="badge badge-hostile" style={{ marginLeft: 6 }}>needs level {s.level}</span>}
{s.description && <div className="combatant-sub">{s.description}</div>}
</div>
))}
</div>
</details>
)}
</>
)}
{data.specialAbilities && (
<div className="card mt-md">
<div className="card-title">Special Abilities</div>
<p style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{data.specialAbilities}</p>
</div>
)}
</div>
);
}
@@ -275,7 +322,7 @@ export function CharacterPanel() {
<button
className="fab-quickstats"
onClick={() => openCharacterPanel(fallback.id)}
title={isDM ? 'Characters: stats and inventory' : 'Your character: stats and inventory'}
title={isDM ? 'Characters: stats, skills and inventory' : 'Your character: stats, skills and inventory'}
aria-label="Open the character panel"
>
🧙
+257
View File
@@ -0,0 +1,257 @@
import { useState } from 'react';
import { useCharacterState, useResources } from '../api/queries';
import { CONDITIONS, MAX_EXHAUSTION, conditionRule, exhaustionRule } from '../lib/conditions';
import { NumberInput } from './NumberInput';
import type { ClassResource } from '../api/types';
// A counter with more uses than this is a pool (Lay on Hands, a high-level
// monk's Ki): it gets a number to spend in place of a row of pips.
const MOST_PIPS = 10;
// One condition, with its rule a hover away. `onRemove` adds the ✕.
export function ConditionChip({ name, note, onRemove }: { name: string; note?: string; onRemove?: () => void }) {
return (
<span className="condition-chip" title={conditionRule(name) || undefined}>
{name}
{note && <span className="condition-note">{note}</span>}
{onRemove && (
<button aria-label={`Remove ${name}`} onClick={onRemove}>
✕
</button>
)}
</span>
);
}
// The "+ Condition" menu: every condition not already in force.
export function ConditionPicker({ who, current, onAdd }: { who: string; current: string[]; onAdd: (condition: string) => void }) {
return (
<select aria-label={`Add a condition to ${who}`} value="" onChange={(e) => e.target.value && onAdd(e.target.value)} style={{ width: 'auto' }}>
<option value="">+ Condition</option>
{CONDITIONS.filter((c) => !current.includes(c)).map((c) => (
<option key={c} value={c} title={conditionRule(c)}>
{c}
</option>
))}
</select>
);
}
// Inspiration and exhaustion as badges, for places that only show them.
export function StateBadges({ inspiration, exhaustion }: { inspiration: boolean; exhaustion: number }) {
return (
<>
{inspiration && (
<span className="badge badge-live" title="Inspiration: spend it for advantage on one attack, check or save">
✨ Inspired
</span>
)}
{exhaustion > 0 && (
<span className="badge badge-hostile" title={exhaustionRule(exhaustion)}>
Exhaustion {exhaustion}
</span>
)}
</>
);
}
// The class counters (Rage, Ki, Channel Divinity...): pips that are filled
// while a use is left, and "Use" to spend one. `canUse` is the character's own
// player or the DM. Getting a use back is the DM's alone: for them each pip
// sets how many are left, and "All back" refills the lot.
export function ResourceTracker({
characterId,
name,
resources,
canUse,
isDM,
onError,
}: {
characterId: string;
name: string;
resources: ClassResource[];
canUse: boolean;
isDM: boolean;
onError?: (err: unknown) => void;
}) {
const mutation = useResources(characterId);
const send = (action: Parameters<typeof mutation.mutate>[0]) => mutation.mutate(action, { onError });
// What is typed into a pool's box, by counter.
const [amounts, setAmounts] = useState<Record<string, string>>({});
if (resources.length === 0) return null;
return (
<div className="resource-tracker">
{isDM && resources.some((r) => r.used > 0) && (
<div className="flex-between">
<span />
<button className="btn btn-ghost" onClick={() => send({ action: 'restore' })} disabled={mutation.isPending} title={`Give ${name} every use back`}>
All back
</button>
</div>
)}
{resources.map((r) => {
const rest = r.restoresOn === 'SHORT' ? 'short or long rest' : 'long rest';
const isPool = r.max > MOST_PIPS;
const amount = Math.max(1, Math.floor(Number(amounts[r.key])) || 1);
return (
<div key={r.key} className="slot-row">
<span className="resource-name" title={`Back on a ${rest}`}>
{r.name}
<span className="resource-rest">{r.restoresOn === 'SHORT' ? 'short rest' : 'long rest'}</span>
</span>
{isPool ? (
<span className="slot-pips" />
) : (
<span className="slot-pips" role="group" aria-label={`${r.remaining} of ${r.max} ${r.name} left`}>
{Array.from({ length: r.max }, (_, i) => i + 1).map((n) => {
const className = `slot-pip${n <= r.remaining ? ' is-filled' : ''}`;
const left = n === r.remaining ? n - 1 : n;
return isDM ? (
<button
key={n}
type="button"
className={className}
aria-label={`Set ${r.name} left to ${left}`}
disabled={mutation.isPending}
onClick={() => send({ action: 'set', key: r.key, used: r.max - left })}
/>
) : (
<span key={n} className={className} />
);
})}
</span>
)}
<span className="mono slot-count">
{r.remaining}/{r.max}
</span>
{canUse && isPool && (
<NumberInput
min={1}
max={r.max}
placeholder="1"
aria-label={`How much ${r.name} to spend`}
value={amounts[r.key] ?? ''}
onChange={(e) => setAmounts({ ...amounts, [r.key]: e.target.value })}
style={{ width: 60 }}
/>
)}
{canUse && (
<button
className="btn"
onClick={() => send({ action: 'use', key: r.key, amount: isPool ? amount : 1 })}
disabled={r.remaining === 0 || mutation.isPending}
title={r.remaining === 0 ? `None left. Back on a ${rest}` : `Spend ${isPool ? amount : 'one'}. Back on a ${rest}`}
aria-label={`Use ${r.name}`}
>
Use
</button>
)}
{isDM && isPool && (
<button
className="btn btn-ghost"
onClick={() => send({ action: 'set', key: r.key, used: Math.max(0, r.used - amount) })}
disabled={r.used === 0 || mutation.isPending}
title={`Give ${amount} back`}
aria-label={`Give ${r.name} back`}
>
+ Back
</button>
)}
</div>
);
})}
{canUse && !isDM && <p className="combatant-sub" style={{ margin: '0.3rem 0 0' }}>Once used, a rest or the DM gives it back.</p>}
</div>
);
}
// How a character is doing beyond hit points: inspiration, exhaustion,
// conditions and class counters. The DM gives and takes away all of it. The
// character's own player spends inspiration and counters. Everyone else reads.
// With `conditions` left out that row is not drawn (an encounter card has its
// own).
export function CharacterState({
characterId,
name,
inspiration,
exhaustion,
conditions,
resources,
canUse,
isDM,
onError,
}: {
characterId: string;
name: string;
inspiration: boolean;
exhaustion: number;
conditions?: string[];
resources: ClassResource[];
canUse: boolean;
isDM: boolean;
onError?: (err: unknown) => void;
}) {
const state = useCharacterState(characterId);
const set = (data: Parameters<typeof state.mutate>[0]) => state.mutate(data, { onError });
return (
<div className="character-state">
<div className="flex-row flex-wrap gap-sm">
{isDM ? (
<button
className={`btn btn-target${inspiration ? ' is-lit' : ''}`}
aria-pressed={inspiration}
disabled={state.isPending}
title={inspiration ? `Take ${name}'s inspiration away` : `Give ${name} inspiration: advantage on one attack, check or save of their choice`}
onClick={() => set({ inspiration: !inspiration })}
>
✨ {inspiration ? 'Inspired' : 'Give inspiration'}
</button>
) : inspiration ? (
<>
<StateBadges inspiration exhaustion={0} />
{canUse && (
<button className="btn btn-target" disabled={state.isPending} title="Spend it for advantage on one attack, check or save" onClick={() => set({ inspiration: false })}>
Spend
</button>
)}
</>
) : (
<span className="combatant-sub">No inspiration</span>
)}
{isDM ? (
<label className="flex-row gap-sm" title={exhaustionRule(exhaustion)}>
Exhaustion
<select
value={exhaustion}
disabled={state.isPending}
onChange={(e) => set({ exhaustion: Number(e.target.value) })}
style={{ width: 'auto' }}
>
{Array.from({ length: MAX_EXHAUSTION + 1 }, (_, level) => (
<option key={level} value={level}>
{level === 0 ? 'None' : `Level ${level}`}
</option>
))}
</select>
</label>
) : (
<StateBadges inspiration={false} exhaustion={exhaustion} />
)}
</div>
{exhaustion > 0 && <p className="combatant-sub" style={{ margin: '0.3rem 0 0', whiteSpace: 'pre-wrap' }}>{exhaustionRule(exhaustion)}</p>}
{conditions && (conditions.length > 0 || isDM) && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{conditions.map((c) => (
<ConditionChip key={c} name={c} onRemove={isDM ? () => set({ conditions: conditions.filter((x) => x !== c) }) : undefined} />
))}
{isDM && <ConditionPicker who={name} current={conditions} onAdd={(c) => set({ conditions: [...conditions, c] })} />}
</div>
)}
<ResourceTracker characterId={characterId} name={name} resources={resources} canUse={canUse} isDM={isDM} onError={onError} />
</div>
);
}
+87 -25
View File
@@ -1,43 +1,88 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { fmtMod } from '../lib/format';
import { onRollRequest, parseDice, rollD20, rollDie, type RollMode, type RollRequest } from '../lib/diceRoller';
const DICE = [4, 6, 8, 10, 12, 20, 100];
const MAX_DICE = 20;
const HISTORY_LENGTH = 8;
const MODES: { mode: RollMode; label: string; title: string }[] = [
{ mode: 'DISADVANTAGE', label: 'Disadv.', title: 'Disadvantage: roll two d20s and keep the lower' },
{ mode: 'NORMAL', label: 'Normal', title: 'One d20' },
{ mode: 'ADVANTAGE', label: 'Adv.', title: 'Advantage: roll two d20s and keep the higher' },
];
interface Roll {
id: number;
sides: number;
label?: string; // what it was for, when it was asked for from a sheet
notation: string; // "1d20+3", "1d8+1d6+2"
dice: number[]; // every die rolled, in order
modifier: number;
dice: number[];
total: number;
}
// One fair roll of an n-sided die. Uses the browser's cryptographic random
// source, discarding values that would make some faces slightly likelier.
function rollDie(sides: number): number {
const limit = Math.floor(0x100000000 / sides) * sides;
const buffer = new Uint32Array(1);
do {
crypto.getRandomValues(buffer);
} while (buffer[0] >= limit);
return (buffer[0] % sides) + 1;
// The d20 that counted, for a roll of a single d20 (a natural 20 or 1 means something).
natural: number | null;
mode: RollMode; // how a single d20 was rolled
}
function notation(count: number, sides: number, modifier: number): string {
return `${count}d${sides}${modifier ? fmtMod(modifier) : ''}`;
}
// A table-side dice roller, reachable from every page. These rolls are for
// the player's own use at the table: they are not sent to the server and do
// not feed the character builder, whose dice stay locked in server-side.
// A d20 plus a bonus, with advantage or disadvantage as chosen.
function d20Roll(modifier: number, mode: RollMode, label?: string): Omit<Roll, 'id'> {
const { kept, dice } = rollD20(mode);
return { label, notation: notation(1, 20, modifier), dice, modifier, total: kept + modifier, natural: kept, mode };
}
// What a request from a sheet comes to; null for dice that cannot be read.
function answer(request: RollRequest, mode: RollMode): Omit<Roll, 'id'> | null {
if (request.kind === 'check') return d20Roll(request.modifier, mode, request.label);
const parsed = parseDice(request.expression);
if (!parsed) return null;
const dice: number[] = [];
let total = parsed.flat;
for (const term of parsed.dice) {
for (let i = 0; i < term.count; i++) {
const die = rollDie(term.sides);
dice.push(die);
total += term.sign * die;
}
}
return { label: request.label, notation: request.expression.replace(/\s+/g, ''), dice, modifier: parsed.flat, total, natural: null, mode: 'NORMAL' };
}
// A table-side dice roller, reachable from every page. It rolls what is set
// up here, and whatever is clicked on a sheet or an encounter card (a skill,
// a save, an attack, damage: lib/diceRoller.ts), with the bonus already in.
// These rolls are for the table: they are not sent to the server and do not
// feed the character builder, whose dice stay locked in server-side.
export function DiceRoller() {
const [open, setOpen] = useState(false);
const [sides, setSides] = useState(20);
const [count, setCount] = useState(1);
const [modifier, setModifier] = useState(0);
const [mode, setMode] = useState<RollMode>('NORMAL');
const [history, setHistory] = useState<Roll[]>([]);
const push = (roll: Omit<Roll, 'id'>) => setHistory((prev) => [{ ...roll, id: (prev[0]?.id ?? 0) + 1 }, ...prev].slice(0, HISTORY_LENGTH));
// A roll asked for from elsewhere on the page: rolled, and shown. It is
// rolled the way the roller is set at that moment.
const currentMode = useRef(mode);
useEffect(() => {
currentMode.current = mode;
});
useEffect(
() =>
onRollRequest((request) => {
const roll = answer(request, currentMode.current);
if (!roll) return;
push(roll);
setOpen(true);
}),
[]
);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
@@ -46,15 +91,16 @@ export function DiceRoller() {
}, [open]);
const latest = history[0];
const singleD20 = sides === 20 && count === 1;
function roll() {
if (singleD20) return push(d20Roll(modifier, mode));
const dice = Array.from({ length: count }, () => rollDie(sides));
const total = dice.reduce((sum, d) => sum + d, 0) + modifier;
setHistory((prev) => [{ id: (prev[0]?.id ?? 0) + 1, sides, modifier, dice, total }, ...prev].slice(0, HISTORY_LENGTH));
push({ notation: notation(count, sides, modifier), dice, modifier, total: dice.reduce((sum, d) => sum + d, 0) + modifier, natural: null, mode: 'NORMAL' });
}
// The natural 20 and natural 1 only mean something on a single d20.
const natural = latest && latest.sides === 20 && latest.dice.length === 1 ? latest.dice[0] : null;
const natural = latest?.natural ?? null;
const modeNote = (r: Roll) => (r.mode === 'ADVANTAGE' ? 'advantage' : r.mode === 'DISADVANTAGE' ? 'disadvantage' : '');
return (
<>
@@ -113,29 +159,44 @@ export function DiceRoller() {
</label>
</div>
{/* For any single d20: one rolled here, and every check, save and attack clicked on a sheet. */}
<div className="dice-choices mt-sm" role="group" aria-label="How a d20 is rolled">
{MODES.map((m) => (
<button key={m.mode} className={`die-btn${m.mode === mode ? ' is-selected' : ''}`} aria-pressed={m.mode === mode} title={m.title} onClick={() => setMode(m.mode)}>
{m.label}
</button>
))}
</div>
<button className="btn btn-primary btn-block btn-lg mt-sm" onClick={roll}>
🎲 Roll {notation(count, sides, modifier)}
{singleD20 && mode !== 'NORMAL' && ` (${modeNote({ mode } as Roll)})`}
</button>
<div className="dice-result" aria-live="polite">
{latest ? (
<>
{latest.label && <div className="dice-label roll-label">{latest.label}</div>}
{/* Keyed on the roll so the pop animation replays every time, even on a repeat result. */}
<div key={latest.id} className={`roll-result animate${natural === 20 ? ' is-crit' : natural === 1 ? ' is-fumble' : ''}`}>
{latest.total}
</div>
{natural === 20 && <div className="dice-callout">Natural 20!</div>}
{natural === 1 && <div className="dice-callout is-fumble">Natural 1</div>}
{(latest.dice.length > 1 || latest.modifier !== 0) && (
{(latest.dice.length > 1 || latest.modifier !== 0 || latest.label) && (
<div className="dice-breakdown mono">
{latest.dice.join(' + ')}
{latest.natural != null && latest.dice.length > 1
? `${latest.dice.join(' / ')} → ${latest.natural} (${modeNote(latest)})`
: latest.natural != null
? latest.natural
: `${latest.notation}: ${latest.dice.join(', ')}`}
{latest.modifier !== 0 && ` ${latest.modifier > 0 ? '+' : '−'} ${Math.abs(latest.modifier)}`} = {latest.total}
</div>
)}
</>
) : (
<p className="subtitle" style={{ margin: 0 }}>
Pick a die and roll.
Pick a die and roll, or click a skill, save or attack on a sheet.
</p>
)}
</div>
@@ -151,7 +212,8 @@ export function DiceRoller() {
{history.slice(1).map((r) => (
<div key={r.id} className="flex-between dice-history-row">
<span>
{notation(r.dice.length, r.sides, r.modifier)}
{r.label ? `${r.label} · ` : ''}
{r.notation}
{r.dice.length > 1 && <span className="dice-history-dice"> ({r.dice.join(', ')})</span>}
</span>
<strong className="mono">{r.total}</strong>
+175
View File
@@ -0,0 +1,175 @@
import { useState } from 'react';
import { Modal } from './Modal';
import { NumberInput } from './NumberInput';
import { ABILITY_LABELS, SKILL_LABELS, fmtMod } from '../lib/format';
import { rollD20, type RollMode } from '../lib/diceRoller';
import type { Ability, AbilityDetail, SaveBonuses, SkillBonuses } from '../api/types';
const ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
// What the modal needs to know about each character who might roll.
export interface Checker {
id: string;
name: string;
abilities: Record<Ability, AbilityDetail>;
saves: SaveBonuses;
skills: SkillBonuses;
}
interface Result {
id: string;
name: string;
dice: number[];
kept: number;
bonus: number;
total: number;
}
// A check is "SKILL:STEALTH", "SAVE:DEX" or "ABILITY:STR".
function describe(check: string): string {
const [kind, key] = check.split(':');
if (kind === 'SKILL') return SKILL_LABELS[key];
return `${ABILITY_LABELS[key]} ${kind === 'SAVE' ? 'save' : 'check'}`;
}
function bonusFor(c: Checker, check: string): number {
const [kind, key] = check.split(':');
if (kind === 'SKILL') return c.skills[key].bonus;
if (kind === 'SAVE') return c.saves[key as Ability].bonus;
return c.abilities[key as Ability].modifier;
}
// The DM calling for a roll from several characters at once: everyone makes
// a Stealth check, or a Dexterity save against a fireball. Pick the roll and
// who makes it; each gets their own d20 with their own bonus, and with a DC
// the list says who made it. Rolled in the browser, like every table roll.
export function GroupCheckModal({ characters, onClose }: { characters: Checker[]; onClose: () => void }) {
const [check, setCheck] = useState('SKILL:PERCEPTION');
const [dc, setDc] = useState('');
const [mode, setMode] = useState<RollMode>('NORMAL');
const [left, setLeft] = useState<Set<string>>(new Set()); // who sits this one out
const [results, setResults] = useState<{ check: string; dc: number | null; rows: Result[] } | null>(null);
const rolling = characters.filter((c) => !left.has(c.id));
const target = dc === '' ? null : Number(dc);
function roll() {
setResults({
check,
dc: target,
rows: rolling.map((c) => {
const { kept, dice } = rollD20(mode);
const bonus = bonusFor(c, check);
return { id: c.id, name: c.name, dice, kept, bonus, total: kept + bonus };
}),
});
}
const passed = results && results.dc != null ? results.rows.filter((r) => r.total >= results.dc!).length : 0;
return (
<Modal title="Call for a roll" subtitle="One d20 each, with each character's own bonus" onClose={onClose}>
<div className="flex-row flex-wrap gap-sm">
<select aria-label="What to roll" value={check} onChange={(e) => setCheck(e.target.value)} style={{ flex: 1, minWidth: 180 }}>
<optgroup label="Skills">
{Object.keys(SKILL_LABELS).map((skill) => (
<option key={skill} value={`SKILL:${skill}`}>
{SKILL_LABELS[skill]}
</option>
))}
</optgroup>
<optgroup label="Saving throws">
{ABILITIES.map((a) => (
<option key={a} value={`SAVE:${a}`}>
{ABILITY_LABELS[a]} save
</option>
))}
</optgroup>
<optgroup label="Ability checks">
{ABILITIES.map((a) => (
<option key={a} value={`ABILITY:${a}`}>
{ABILITY_LABELS[a]} check
</option>
))}
</optgroup>
</select>
<NumberInput
min={1}
max={40}
placeholder="DC"
title="The number to reach. Leave empty to just see the totals."
aria-label="Difficulty class"
value={dc}
onChange={(e) => setDc(e.target.value)}
style={{ width: 70 }}
/>
<select aria-label="How the d20s are rolled" value={mode} onChange={(e) => setMode(e.target.value as RollMode)} style={{ width: 'auto' }}>
<option value="NORMAL">Normal</option>
<option value="ADVANTAGE">Advantage</option>
<option value="DISADVANTAGE">Disadvantage</option>
</select>
</div>
<div className="level-spells mt-sm">
{characters.map((c) => (
<label key={c.id} className="checkbox-row level-choice">
<input
type="checkbox"
checked={!left.has(c.id)}
onChange={(e) => {
const next = new Set(left);
if (e.target.checked) next.delete(c.id);
else next.add(c.id);
setLeft(next);
}}
/>
<span>
{c.name} <span className="combatant-sub mono">{fmtMod(bonusFor(c, check))}</span>
</span>
</label>
))}
</div>
<button className="btn btn-primary btn-block mt-sm" onClick={roll} disabled={rolling.length === 0}>
🎲 Roll {describe(check)} for {rolling.length}
</button>
{results && (
<div className="mt-md" aria-live="polite">
<div className="section-label">
{describe(results.check)}
{results.dc != null && ` · DC ${results.dc} · ${passed} of ${results.rows.length} made it`}
</div>
{results.rows.map((r) => {
const made = results.dc == null ? null : r.total >= results.dc;
return (
<div key={r.id} className="detail-row">
<span>
{r.name}{' '}
<span className="combatant-sub mono">
{r.dice.length > 1 ? `${r.dice.join(' / ')} → ${r.kept}` : r.kept} {r.bonus >= 0 ? '+' : '−'} {Math.abs(r.bonus)}
{r.kept === 20 && ' · natural 20'}
{r.kept === 1 && ' · natural 1'}
</span>
</span>
<span>
<strong className="mono">{r.total}</strong>
{made != null && (
<span className={`badge ${made ? 'badge-live' : 'badge-hostile'}`} style={{ marginLeft: 6 }}>
{made ? 'made it' : 'failed'}
</span>
)}
</span>
</div>
);
})}
{results.dc != null && (
<p className="combatant-sub" style={{ margin: '0.4rem 0 0' }}>
A group check succeeds when at least half make it{passed * 2 >= results.rows.length ? ': this one does.' : ': this one does not.'}
</p>
)}
</div>
)}
</Modal>
);
}
+38 -7
View File
@@ -25,12 +25,13 @@ function allowance(spells: NonNullable<LevelUpPlan['spells']>): string {
}
// The levelling-up checklist for one character, one level at a time: the
// level, HP, the class's new special abilities (and a Boon where the level
// grants one), new spells and fresh slots, and the free weapon upgrade. The
// level, HP, the class's new special abilities (with a subclass or a Boon
// where the level calls for one), new spells and fresh slots, and the free weapon upgrade. The
// site does every step; the DM makes the choices and says yes.
export function LevelUpModal({ character, campaignSpells, onClose }: { character: CharacterDetail; campaignSpells: Spell[]; onClose: () => void }) {
const { data: plan, isLoading, error: planError } = useLevelUpPlan(character.id, true);
const levelUp = useLevelUp(character.id);
const [subclass, setSubclass] = useState('');
const [boon, setBoon] = useState('');
// undefined until picked: the equipped weapon is offered first.
const [weaponChoice, setWeaponChoice] = useState<string | undefined>(undefined);
@@ -51,6 +52,8 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
? campaignSpells.filter((s) => !known.has(s.id) && s.level <= plan.spells!.maxSpellLevel).sort((a, b) => a.level - b.level || a.name.localeCompare(b.name))
: [];
const pickedBoon = plan.boon?.find((b) => b.key === boon);
const pickedSubclass = plan.subclass?.options.find((option) => option.key === subclass);
const owed = plan.subclass && !subclass ? 'Choose a subclass first' : plan.boon && !boon ? 'Choose a Boon first' : null;
function toggleSpell(id: string) {
setSpellIds((current) => {
@@ -63,7 +66,7 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
async function handleLevelUp() {
setError(null);
try {
await levelUp.mutateAsync({ boon: plan!.boon ? boon : undefined, weaponId: weaponId || null, spellIds: [...spellIds] });
await levelUp.mutateAsync({ subclass: plan!.subclass ? subclass : undefined, boon: plan!.boon ? boon : undefined, weaponId: weaponId || null, spellIds: [...spellIds] });
onClose();
} catch (err) {
setError(extractErrorMessage(err));
@@ -87,7 +90,35 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
</Step>
<Step n={3} title="Special abilities">
{plan.features.length === 0 && !plan.boon && (
{plan.subclass && (
<div role="radiogroup" aria-label="Subclass" style={{ marginBottom: '0.6rem' }}>
<p style={{ margin: '0 0 0.3rem' }}>
<strong>Subclass</strong>{' '}
<span className="combatant-sub">
{plan.subclass.level === plan.toLevel
? `chosen at level ${plan.subclass.level}. Choose one:`
: `owed since level ${plan.subclass.level}; everything it has given so far is written now. Choose one:`}
</span>
</p>
{plan.subclass.options.map((option) => (
<label key={option.key} className="checkbox-row level-choice">
<input type="radio" name="subclass" value={option.key} checked={subclass === option.key} onChange={() => setSubclass(option.key)} />
<span>
<strong>{option.name}</strong>
<span className="combatant-sub" style={{ display: 'block' }}>{option.summary}</span>
</span>
</label>
))}
{pickedSubclass?.features.map((feature) => (
<div key={feature.name + feature.text} className="reward-row">
<strong>{feature.name}</strong>
<span className="badge" style={{ marginLeft: 6 }}>{pickedSubclass.name}</span>
<div className="combatant-sub">{feature.text}</div>
</div>
))}
</div>
)}
{plan.features.length === 0 && !plan.boon && !plan.subclass && (
<p className="combatant-sub">
{plan.beyondTables ? 'The class tables stop at level 10. Add anything new to the special abilities by hand.' : 'No new feature at this level.'}
</p>
@@ -118,7 +149,7 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
{pickedBoon?.key === 'HARDY' && <p className="combatant-sub">The Temp HP is given now, and again after every long rest taken with the Rest button.</p>}
</div>
)}
{(plan.features.length > 0 || plan.boon) && (
{(plan.features.length > 0 || plan.boon || plan.subclass) && (
<p className="combatant-sub">Written into Special Abilities for you. Where a line says "choose", edit it there once the player has.</p>
)}
</Step>
@@ -179,8 +210,8 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
</Step>
<div className="modal-foot">
<button className="btn btn-primary" onClick={handleLevelUp} disabled={levelUp.isPending || Boolean(plan.boon && !boon)}>
{levelUp.isPending ? 'Levelling…' : plan.boon && !boon ? 'Choose a Boon first' : `Level up to ${plan.toLevel}`}
<button className="btn btn-primary" onClick={handleLevelUp} disabled={levelUp.isPending || Boolean(owed)}>
{levelUp.isPending ? 'Levelling…' : (owed ?? `Level up to ${plan.toLevel}`)}
</button>
</div>
</Modal>
+34
View File
@@ -0,0 +1,34 @@
import type { ReactNode } from 'react';
import { leadingDice, rollCheck, rollDice } from '../lib/diceRoller';
// A number that rolls when clicked: a d20 plus `modifier` (a check, a save,
// an attack), or the dice in `dice` (damage). The roll opens in the dice
// roller under `label`. Of dice written with more after them ("2d8+3 fire")
// the dice are rolled; text that does not start with dice (a DM may type
// anything) is shown as it is.
export function Rollable({
label,
modifier,
dice,
className = '',
children,
}: {
label: string;
modifier?: number;
dice?: string;
className?: string;
children: ReactNode;
}) {
const readable = dice === undefined ? null : leadingDice(dice);
if (dice !== undefined && !readable) return <span className={className}>{children}</span>;
return (
<button
type="button"
className={`rollable ${className}`}
title={readable ? `Roll ${readable}: ${label}` : `Roll a d20 for ${label}`}
onClick={() => (readable ? rollDice(label, readable) : rollCheck(label, modifier ?? 0))}
>
{children}
</button>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { ABILITY_LABELS, SKILL_LABELS, fmtMod } from '../lib/format';
import type { Ability, SaveBonuses, SkillBonuses } from '../api/types';
import { Rollable } from './Rollable';
const ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
// Saving throws, skills and passive scores in one compact block: what the DM
// asks for mid-fight. Proficient lines are marked ● and expertise ◆. Used by
// the character panel and the encounter screen, so they always agree. A click
// on a line rolls it in the dice roller, under `who`'s name.
export function SheetNumbers({
who,
saves,
skills,
passives,
}: {
who: string;
saves: SaveBonuses;
skills: SkillBonuses;
passives: { perception: number; investigation: number; insight: number };
}) {
return (
<div className="sheet-numbers">
<div className="section-label">Saving throws</div>
<div className="number-grid is-saves">
{ABILITIES.map((a) => (
<Rollable key={a} label={`${who}: ${ABILITY_LABELS[a]} save`} modifier={saves[a].bonus} className={`number-row${saves[a].proficient ? ' is-proficient' : ''}`}>
<span>
<span className="prof-mark" aria-hidden="true">{saves[a].proficient ? '●' : '○'}</span> {a}
</span>
<b className="mono">{fmtMod(saves[a].bonus)}</b>
</Rollable>
))}
</div>
<div className="section-label">Skills</div>
<div className="number-grid">
{Object.entries(skills).map(([skill, detail]) => (
<Rollable key={skill} label={`${who}: ${SKILL_LABELS[skill]}`} modifier={detail.bonus} className={`number-row${detail.proficient ? ' is-proficient' : ''}`}>
<span>
<span className="prof-mark" aria-hidden="true">{detail.expertise ? '◆' : detail.proficient ? '●' : '○'}</span> {SKILL_LABELS[skill]}{' '}
<span className="number-ability">{detail.ability}</span>
</span>
<b className="mono">{fmtMod(detail.bonus)}</b>
</Rollable>
))}
</div>
<div className="stat-chips mt-sm">
<span className="stat-chip">
<span>Passive Perception</span>
<b>{passives.perception}</b>
</span>
<span className="stat-chip">
<span>Passive Investigation</span>
<b>{passives.investigation}</b>
</span>
<span className="stat-chip">
<span>Passive Insight</span>
<b>{passives.insight}</b>
</span>
</div>
<p className="combatant-sub" style={{ margin: '0.4rem 0 0' }}>● proficient · ◆ expertise · click a line to roll it</p>
</div>
);
}