V1.14.0: spell slots, rests, and a level-up checklist

- Spell slots. Every class that casts has a slot tracker, worked out
  from class and level: the full-caster table for bards, clerics,
  druids, sorcerers and wizards, the half-caster table for paladins and
  rangers (from level 2), and a warlock's few slots of one level. It is
  in the Spellcasting card on the sheet and in the character panel, and
  the party overview has a column for it. A player presses Use to spend
  a slot; only the DM gives one back.
- Rests. The DM's "Rest…" button, beside the character list and on the
  party overview, rests any of the party at once. A short rest shows
  which Hit Dice each character can roll and heals from what they
  rolled (typed in, or rolled by the site), and gives a warlock their
  slots. A long rest puts back HP, every spell slot and half the level
  in Hit Dice, and clears temp HP.
- Hit Dice are counted: one per level, shown on the sheet, the panel
  and the party overview.
- Level Up. "Level Up…" on a sheet takes a character up one level with
  the whole checklist: the new max HP and a full heal, the class's new
  special abilities for levels 2 to 10, a Boon where the level grants
  one (Toughened raises Extra AC, Hardy gives temp HP now and after
  each long rest), fresh spell slots and new spells, and the free
  upgrade of one standard weapon.
- A level typed into the Level field still writes down what the class
  gains on the way up, and leaves a line where a Boon is owed.
- The docs cover all of it, with a generated list of what each class
  gains at each level. The Hollowcrown seed's note no longer says to
  track spell slots on paper.
- New migration: spent spell slots and Hit Dice on a character.
- All packages at version 1.14.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-10 10:47:56 +02:00
co-authored by Claude Opus 5.5
parent 3a867fd1a1
commit e9f8169286
34 changed files with 2855 additions and 61 deletions
+60 -1
View File
@@ -15,12 +15,15 @@ import type {
GearEffect,
GoldTransaction,
Item,
LevelUpPlan,
Location,
Monster,
Note,
Npc,
SaleOffer,
QuickStats,
RestResult,
RestType,
Spell,
Weapon,
} from './types';
@@ -166,7 +169,7 @@ export function useCharacter(characterId: string | undefined) {
export function usePatchCharacter(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: Partial<Omit<CharacterDetail, 'gold'>>) =>
mutationFn: async (data: Partial<Omit<CharacterDetail, 'gold'>> & { hitDiceUsed?: number }) =>
(await apiClient.patch<{ character: CharacterDetail }>(`/characters/${characterId}`, data)).data.character,
onSuccess: (character) => {
qc.setQueryData(['character', characterId], character);
@@ -197,6 +200,62 @@ export function useDeathSave(characterId: string) {
});
}
// The slot tracker. Spending a slot is the player's (or the DM's); setting how
// many are spent, and giving them all back, are the DM's alone.
export type SpellSlotAction = { action: 'use'; level: number } | { action: 'set'; level: number; used: number } | { action: 'restore' };
export function useSpellSlots(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: SpellSlotAction) =>
(await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/spell-slots`, data)).data.character,
onSuccess: (character) => {
invalidateCharacter(qc, characterId); // the sheet and its quick stats
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
},
});
}
// What a character's next level brings. DM only.
export function useLevelUpPlan(characterId: string, enabled: boolean) {
return useQuery({
queryKey: ['character', characterId, 'level-up'],
enabled,
gcTime: 0, // never open on the plan for a level the character has already reached
queryFn: async () => (await apiClient.get<{ plan: LevelUpPlan }>(`/characters/${characterId}/level-up`)).data.plan,
});
}
// Takes the character up one level, with the choices that go with it.
export function useLevelUp(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { boon?: string; weaponId?: string | null; spellIds?: string[] }) =>
(await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/level-up`, data)).data.character,
onSuccess: (character) => {
invalidateCharacter(qc, characterId);
qc.invalidateQueries({ queryKey: ['encounter'] }); // a character combatant shows the sheet's HP
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
},
});
}
// A short or long rest for any of the party at once. On a short rest each
// character spends `hitDice` Hit Dice; `rolled` is what they added up to at
// the table, and left out the site rolls them.
export function useRest(campaignId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { type: RestType; characters: { characterId: string; hitDice?: number; rolled?: number | null }[] }) =>
(await apiClient.post<{ type: RestType; results: RestResult[] }>(`/campaigns/${campaignId}/rest`, data)).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['character'] });
qc.invalidateQueries({ queryKey: ['encounter'] });
qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] });
},
});
}
export function useDeleteCharacter(campaignId: string) {
const qc = useQueryClient();
return useMutation({
+84 -1
View File
@@ -127,6 +127,31 @@ export interface DeathSaves {
failures: number;
}
// One slot level on the slot tracker: how many slots there are, and how many
// are spent.
export interface SpellSlotLevel {
level: number; // 1 is a 1st-level slot
max: number;
used: number;
remaining: number;
}
// A character's spell slots, from class and level. A warlock's (PACT) are all
// of one slot level and come back on a short rest; everyone else's on a long one.
export interface SpellSlots {
kind: 'FULL' | 'HALF' | 'PACT';
restoresOn: 'SHORT' | 'LONG';
levels: SpellSlotLevel[];
}
// One Hit Die per level, of the class's size, spent on short rests to heal.
export interface HitDice {
size: number;
count: number;
used: number;
remaining: number;
}
export interface CharacterSummary {
id: string;
campaignId: string;
@@ -148,6 +173,9 @@ export interface CharacterSummary {
cash: number | null;
maxHp: number | null;
armorClass: number | null;
// What is left before the next rest; both null until the character is built.
spellSlots: SpellSlots | null; // also null for a character with no spell slots
hitDice: (HitDice & { conModifier: number }) | null; // each die heals its roll plus this
currentLocationId: string | null;
currentLocationName: string | null;
}
@@ -188,11 +216,12 @@ export interface CharacterSheet {
initiative: number;
speed: number;
hp: { max: number };
hitDice: { size: number; count: number };
hitDice: HitDice;
saves: Record<Ability, { proficient: boolean; bonus: number }>;
skills: Record<string, { ability: Ability; proficient: boolean; expertise: boolean; bonus: number }>;
passivePerception: number;
spellcasting: { ability: Ability; saveDC: number; attackBonus: number } | null;
spellSlots: SpellSlots | null; // null for a character with no spell slots
gear: ActiveGear;
}
@@ -667,6 +696,8 @@ export interface QuickStats {
speed: number;
proficiencyBonus: number;
spellcasting: { ability: Ability; saveDC: number; attackBonus: number } | null;
spellSlots: SpellSlots | null;
hitDice: HitDice;
passivePerception: number;
abilities: Record<Ability, AbilityDetail>;
specialAbilities: string | null;
@@ -677,3 +708,55 @@ export interface QuickStats {
spells: QuickStatsSpell[];
purse: { gold: number; silver: number; copper: number; cash: number } | null;
}
// One of the four Boons that stand in for an ability score increase.
export interface BoonOption {
key: string;
name: string;
text: string; // the line taking it now would write
taken: number; // how many times this character already has
max: number;
available: boolean;
}
// The checklist for a character's next level (GET /characters/:id/level-up).
export interface LevelUpPlan {
fromLevel: number;
toLevel: number;
maxHp: { from: number; to: number };
// What the class gains. An upgrade rewrites the line that has its name.
features: { name: string; text: string; upgrade: boolean }[];
boon: BoonOption[] | null; // null at a level that grants no Boon
// What the book lets a caster be granted now; null for a class with no spells.
spells: { maxSpellLevel: number; unlocksSpellLevel: number | null; newSpells: number; newCantrips: number } | null;
spellSlots: SpellSlots | null; // the slots at the new level
// Held weapons that can take the free upgrade of one level.
weapons: { weaponId: string; name: string; equipped: boolean; level: number; damageDice: string; nextDamageDice: string }[];
beyondTables: boolean; // past level 10, where the class tables stop
}
export type RestType = 'SHORT' | 'LONG';
// What a rest did for one character (POST /campaigns/:id/rest).
export interface RestResult {
characterId: string;
name: string;
skipped: string | null; // why the rest did nothing for them; the rest is absent then
hpBefore: number;
hpAfter: number;
maxHp: number;
tempHp: number;
hitDice: {
size: number;
spent: number;
rolls: number[] | null; // what each die showed, when the site rolled them
total: number;
conBonus: number;
healed: number;
left: number;
of: number;
regained: number;
};
slotsRestored: boolean;
notes: string[];
}
+15 -2
View File
@@ -9,6 +9,7 @@ import { speciesIcon } from '../lib/speciesIcons';
import { Spinner, ErrorBanner } from './Spinner';
import { HpBar } from './HpBar';
import { DeathSaves } from './DeathSaves';
import { SpellSlotTracker } from './SpellSlots';
import { useState } from 'react';
import { extractErrorMessage } from '../lib/format';
import type { ActiveGear } from '../api/types';
@@ -43,7 +44,7 @@ function Flags({ equipped, usable, level }: { equipped: boolean; usable: boolean
// One character at a glance: the numbers for a fight, and everything they
// hold. The pack, spells and purse are there for the character's own player
// and the DM, who can also put gear on and take it off from here.
function PanelBody({ characterId }: { characterId: string }) {
function PanelBody({ characterId, isDM }: { characterId: string; isDM: boolean }) {
const { data, isLoading, error } = useQuickStats(characterId, true);
const patchWeapon = usePatchCharacterWeapon(characterId);
const patchItem = usePatchInventoryItem(characterId);
@@ -61,6 +62,7 @@ function PanelBody({ characterId }: { characterId: string }) {
['Speed', data.speed],
['Prof.', fmtMod(data.proficiencyBonus)],
['Passive Perc.', data.passivePerception],
['Hit Dice', `${data.hitDice.remaining}/${data.hitDice.count} d${data.hitDice.size}`],
];
return (
@@ -125,6 +127,17 @@ function PanelBody({ characterId }: { characterId: string }) {
<p style={{ margin: 0 }}>
Save DC {data.spellcasting.saveDC} · Attack {fmtMod(data.spellcasting.attackBonus)}
</p>
{/* The character's own player and the DM spend slots here; the DM can also give them back. */}
{data.spellSlots && (
<SpellSlotTracker
characterId={characterId}
name={data.name}
slots={data.spellSlots}
canUse={!data.restricted}
isDM={isDM}
onError={(err) => setEquipError(extractErrorMessage(err))}
/>
)}
</div>
)}
@@ -289,7 +302,7 @@ export function CharacterPanel() {
✕
</button>
</div>
<PanelBody key={shown} characterId={shown} />
<PanelBody key={shown} characterId={shown} isDM={isDM} />
</div>
</>
)}
+2
View File
@@ -24,6 +24,8 @@ const STAT_HELP: Record<string, string> = {
DAMAGE_BONUS: 'Damage Bonus — added to the weapon’s damage dice on a hit. Same ability modifier as the attack bonus.',
CHALLENGE_RATING: 'Challenge Rating — a rough measure of how dangerous a monster is on its own, used to gauge encounter difficulty.',
HIT_DICE: 'Hit Dice — the die your class rolls (or uses the fixed average of) when your HP increases at each level.',
HIT_DICE_LEFT: 'Hit Dice — you have one per level. On a short rest you can spend any you have left: roll each one, add your Constitution modifier, and heal that much. A long rest gives back half your level in spent dice (at least one).',
SPELL_SLOTS: 'Spell slots — each one is one casting of a spell of that level or lower. Cantrips never use a slot. How many you have comes from your class and level. Spent slots come back on a long rest (a warlock’s on a short rest too).',
// Character builder
DICE_MODE: 'Digital dice are rolled by the app. Physical dice are rolled by you at the table, and you type in what came up. Either way a roll is final once it is made.',
WILDCARD: 'Wildcard — the luckiest result. Instead of choosing between two options you may pick any of them.',
+188
View File
@@ -0,0 +1,188 @@
import { useState, type ReactNode } from 'react';
import { useLevelUp, useLevelUpPlan } from '../api/queries';
import { extractErrorMessage, slotLevelLabel, slotsSummary, spellLevelLabel } from '../lib/format';
import { Modal } from './Modal';
import { Spinner, ErrorBanner } from './Spinner';
import type { CharacterDetail, LevelUpPlan, Spell } from '../api/types';
// One numbered step of the checklist.
function Step({ n, title, children }: { n: number; title: string; children: ReactNode }) {
return (
<div className="level-step">
<h3 className="section-label" style={{ margin: 0 }}>
{n}. {title}
</h3>
{children}
</div>
);
}
function allowance(spells: NonNullable<LevelUpPlan['spells']>): string {
const parts = [];
if (spells.newSpells > 0) parts.push(`${spells.newSpells} new spell${spells.newSpells === 1 ? '' : 's'} of up to ${slotLevelLabel(spells.maxSpellLevel)} level`);
if (spells.newCantrips > 0) parts.push(`${spells.newCantrips} extra cantrip`);
return parts.length > 0 ? `The book allows ${parts.join(' and ')}.` : 'No new spell at this level.';
}
// 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
// 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 [boon, setBoon] = useState('');
// undefined until picked: the equipped weapon is offered first.
const [weaponChoice, setWeaponChoice] = useState<string | undefined>(undefined);
const [spellIds, setSpellIds] = useState<Set<string>>(new Set());
const [error, setError] = useState<string | null>(null);
if (isLoading || !plan) {
return (
<Modal title={`Level up ${character.name}`} onClose={onClose}>
{planError ? <ErrorBanner message={extractErrorMessage(planError)} /> : <Spinner label="Reading the class tables…" />}
</Modal>
);
}
const weaponId = weaponChoice ?? plan.weapons.find((w) => w.equipped)?.weaponId ?? plan.weapons[0]?.weaponId ?? '';
const known = new Set(character.spells.map((s) => s.spellId));
const grantable = plan.spells
? 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);
function toggleSpell(id: string) {
setSpellIds((current) => {
const next = new Set(current);
if (!next.delete(id)) next.add(id);
return next;
});
}
async function handleLevelUp() {
setError(null);
try {
await levelUp.mutateAsync({ boon: plan!.boon ? boon : undefined, weaponId: weaponId || null, spellIds: [...spellIds] });
onClose();
} catch (err) {
setError(extractErrorMessage(err));
}
}
return (
<Modal title={`Level up ${character.name}`} subtitle={`Level ${plan.fromLevel} → ${plan.toLevel} · the levelling-up checklist`} wide onClose={onClose}>
{error && <ErrorBanner message={error} />}
<Step n={1} title="Level">
<p>
Level <strong>{plan.fromLevel}</strong> → <strong>{plan.toLevel}</strong>. Proficiency bonus, saves, skills and spell DC follow by themselves.
</p>
</Step>
<Step n={2} title="Hit points">
<p>
Max HP <strong>{plan.maxHp.from}</strong> → <strong>{plan.maxHp.to}</strong>, and healed to full. One more Hit Die.
</p>
</Step>
<Step n={3} title="Special abilities">
{plan.features.length === 0 && !plan.boon && (
<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>
)}
{plan.features.map((feature) => (
<div key={feature.name + feature.text} className="reward-row">
<strong>{feature.name}</strong>
{feature.upgrade && <span className="badge" style={{ marginLeft: 6 }}>replaces the line it has now</span>}
<div className="combatant-sub">{feature.text}</div>
</div>
))}
{plan.boon && (
<div className="mt-sm" role="radiogroup" aria-label="Boon">
<p style={{ margin: '0 0 0.3rem' }}>
<strong>Boon</strong> <span className="combatant-sub">in place of an ability score increase. Choose one:</span>
</p>
{plan.boon.map((option) => (
<label key={option.key} className="checkbox-row level-choice" style={option.available ? undefined : { opacity: 0.55 }}>
<input type="radio" name="boon" value={option.key} checked={boon === option.key} disabled={!option.available} onChange={() => setBoon(option.key)} />
<span>
<strong>{option.name}</strong>
{option.taken > 0 && <span className="badge" style={{ marginLeft: 6 }}>{option.available ? `taken ${option.taken} of ${option.max}` : 'already taken'}</span>}
<span className="combatant-sub" style={{ display: 'block' }}>{option.text}</span>
</span>
</label>
))}
{pickedBoon?.key === 'TOUGHENED' && <p className="combatant-sub">Extra AC goes up by 1 with it.</p>}
{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) && (
<p className="combatant-sub">Written into Special Abilities for you. Where a line says "choose", edit it there once the player has.</p>
)}
</Step>
<Step n={4} title="Spells">
{!plan.spells ? (
<p className="combatant-sub">This class has no spells.</p>
) : (
<>
<p>
{plan.spellSlots ? (
<>
Fresh spell slots: <strong>{slotsSummary(plan.spellSlots)}</strong>.
</>
) : (
'No spell slots yet.'
)}{' '}
{plan.spells.unlocksSpellLevel && <strong>{slotLevelLabel(plan.spells.unlocksSpellLevel)}-level spells unlock. </strong>}
{allowance(plan.spells)}
</p>
{grantable.length === 0 ? (
<p className="combatant-sub">Nothing in the campaign's spell list to grant that {character.name} does not already know. Spells can be granted on the sheet later.</p>
) : (
<div className="level-spells">
{grantable.map((spell) => (
<label key={spell.id} className="checkbox-row level-choice">
<input type="checkbox" checked={spellIds.has(spell.id)} onChange={() => toggleSpell(spell.id)} />
<span>
{spell.name} <span className="combatant-sub">{spellLevelLabel(spell.level)}</span>
</span>
</label>
))}
</div>
)}
<p className="combatant-sub">
{spellIds.size > 0 && `${spellIds.size} picked. `}A player may also swap one known spell for another: take the old one away on the sheet.
</p>
</>
)}
</Step>
<Step n={5} title="Gear">
{plan.weapons.length === 0 ? (
<p className="combatant-sub">No weapon can take the free upgrade: it goes to a held weapon of standard growth that is below level {plan.toLevel}.</p>
) : (
<label className="flex-row flex-wrap gap-sm">
Free upgrade for the main weapon
<select value={weaponId} onChange={(e) => setWeaponChoice(e.target.value)} style={{ flex: 1, minWidth: 180 }}>
{plan.weapons.map((w) => (
<option key={w.weaponId} value={w.weaponId}>
{w.name}: Lv {w.level} → {w.level + 1} ({w.damageDice} → {w.nextDamageDice}){w.equipped ? ' · equipped' : ''}
</option>
))}
<option value="">No upgrade</option>
</select>
</label>
)}
</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>
</div>
</Modal>
);
}
+234
View File
@@ -0,0 +1,234 @@
import { useState } from 'react';
import { useRest } from '../api/queries';
import { CLASS_LABELS, extractErrorMessage, fmtMod, slotsSummary } from '../lib/format';
import { Modal } from './Modal';
import { NumberInput } from './NumberInput';
import { ErrorBanner } from './Spinner';
import { LifeBadge } from './DeathSaves';
import type { CharacterSummary, RestResult, RestType } from '../api/types';
const REST_LABELS: Record<RestType, string> = { SHORT: 'Short rest', LONG: 'Long rest' };
// What a rest did for one character, in a line or two.
function ResultRow({ result, type }: { result: RestResult; type: RestType }) {
if (result.skipped) {
return (
<div className="reward-row">
<strong>{result.name}</strong>
<div className="combatant-sub">{result.skipped}</div>
</div>
);
}
const { hitDice } = result;
const lines: string[] = [];
if (hitDice.spent > 0) {
const dice = `${hitDice.spent}d${hitDice.size}`;
const rolled = hitDice.rolls ? `the site rolled ${hitDice.rolls.join(' + ')}` : `rolled ${hitDice.total}`;
const con = hitDice.conBonus === 0 ? '' : ` ${hitDice.conBonus > 0 ? '+' : '−'} ${Math.abs(hitDice.conBonus)} Constitution`;
lines.push(`Spent ${dice}: ${rolled}${con}, healing ${hitDice.healed}.`);
}
if (hitDice.regained > 0) lines.push(`${hitDice.regained} Hit ${hitDice.regained === 1 ? 'Die' : 'Dice'} back.`);
lines.push(`Hit Dice left: ${hitDice.left} of ${hitDice.of}.`);
if (result.slotsRestored) lines.push('All spell slots back.');
if (type === 'SHORT' && hitDice.spent === 0 && !result.slotsRestored) lines.unshift('Rested, with no Hit Dice spent.');
return (
<div className="reward-row">
<div className="flex-between">
<strong>{result.name}</strong>
<span className="mono">
HP {result.hpBefore === result.hpAfter ? result.hpAfter : `${result.hpBefore} → ${result.hpAfter}`}/{result.maxHp}
{result.tempHp > 0 && ` +${result.tempHp}`}
</span>
</div>
<div className="combatant-sub">{lines.join(' ')}</div>
{result.notes.map((note) => (
<div key={note} className="combatant-sub">
✦ {note}
</div>
))}
</div>
);
}
// The DM's rest button: pick who rests and for how long. A long rest is
// worked out by the site. A short rest says which Hit Dice each character can
// roll; the DM types how many they spend and what they rolled (or leaves the
// roll to the site), and the healing is added up from that.
export function RestModal({ campaignId, characters, onClose }: { campaignId: string; characters: CharacterSummary[]; onClose: () => void }) {
const rest = useRest(campaignId);
const party = characters.filter((c) => c.buildStage === 'COMPLETE');
const [type, setType] = useState<RestType>('SHORT');
// The dead are left out to begin with: a rest does nothing for them.
const [picked, setPicked] = useState<Set<string>>(() => new Set(party.filter((c) => c.deathSaves.state !== 'DEAD').map((c) => c.id)));
const [dice, setDice] = useState<Record<string, string>>({});
const [rolled, setRolled] = useState<Record<string, string>>({});
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState<{ type: RestType; results: RestResult[] } | null>(null);
function toggle(id: string) {
setPicked((current) => {
const next = new Set(current);
if (!next.delete(id)) next.add(id);
return next;
});
}
async function handleRest() {
setError(null);
try {
const resting = party.filter((c) => picked.has(c.id));
setDone(
await rest.mutateAsync({
type,
characters: resting.map((c) => {
const spent = type === 'SHORT' ? Number(dice[c.id]) || 0 : 0;
return { characterId: c.id, hitDice: spent, rolled: spent > 0 && rolled[c.id] ? Number(rolled[c.id]) : null };
}),
})
);
} catch (err) {
setError(extractErrorMessage(err));
}
}
if (done) {
return (
<Modal title={`${REST_LABELS[done.type]} taken`} subtitle="What it did for each character" onClose={onClose}>
{done.results.map((result) => (
<ResultRow key={result.characterId} result={result} type={done.type} />
))}
{done.type === 'SHORT' && (
<p className="combatant-sub mt-md" style={{ marginBottom: 0 }}>
Also back on a short rest, for the players to note: a fighter's Second Wind and Action Surge, a monk's ki, a cleric's Channel
Divinity, a druid's Wild Shape.
</p>
)}
{done.type === 'LONG' && (
<p className="combatant-sub mt-md" style={{ marginBottom: 0 }}>
"Per day" abilities are back too. One long rest per 24 hours.
</p>
)}
<div className="modal-foot">
<button className="btn btn-primary" onClick={onClose}>
Done
</button>
</div>
</Modal>
);
}
return (
<Modal title="Rest" subtitle="Pick who rests, and for how long" wide onClose={onClose}>
<div className="flex-row flex-wrap" role="radiogroup" aria-label="Rest type">
{(['SHORT', 'LONG'] as const).map((option) => (
<button
key={option}
type="button"
role="radio"
aria-checked={type === option}
className={`btn ${type === option ? 'btn-primary' : ''}`}
onClick={() => setType(option)}
>
{option === 'SHORT' ? '☕ Short rest (1 hour)' : '🛏 Long rest (8 hours)'}
</button>
))}
</div>
<p className="subtitle">
{type === 'SHORT'
? 'Each character can spend Hit Dice to heal: they roll each die and add their Constitution modifier. Type how many dice they spend and what the dice added up to, or leave the total empty and the site rolls them. A warlock gets every spell slot back.'
: 'Everyone resting goes to full HP, gets every spell slot back, and regains spent Hit Dice up to half their level (at least one). Temp HP is gone, except what the Hardy Boon gives.'}
</p>
{error && <ErrorBanner message={error} />}
<div className="flex-between">
<h3 className="section-label" style={{ margin: 0 }}>
Who rests ({party.filter((c) => picked.has(c.id)).length} of {party.length})
</h3>
<span className="flex-row gap-sm">
<button className="btn btn-ghost" onClick={() => setPicked(new Set(party.map((c) => c.id)))}>
All
</button>
<button className="btn btn-ghost" onClick={() => setPicked(new Set())}>
None
</button>
</span>
</div>
{party.length === 0 && <p className="combatant-sub">No finished characters in this campaign yet.</p>}
{party.map((c) => {
const isPicked = picked.has(c.id);
const hitDice = c.hitDice;
const spent = Math.min(Number(dice[c.id]) || 0, hitDice?.remaining ?? 0);
const slots = slotsSummary(c.spellSlots);
return (
<div key={c.id} className={`reward-row${isPicked ? '' : ' is-awarded'}`}>
<label className="checkbox-row" style={{ margin: 0 }}>
<input type="checkbox" checked={isPicked} onChange={() => toggle(c.id)} />
<span style={{ flex: 1, minWidth: 0 }}>
<strong>{c.name}</strong>{' '}
<span className="combatant-sub">
{c.characterClass && CLASS_LABELS[c.characterClass]} · Level {c.level}
</span>{' '}
<LifeBadge deathSaves={c.deathSaves} />
<span className="combatant-sub" style={{ display: 'block' }}>
HP {c.currentHp}/{c.maxHp}
{c.tempHp > 0 && ` +${c.tempHp}`}
{hitDice && ` · Hit Dice ${hitDice.remaining} of ${hitDice.count} (d${hitDice.size}) left`}
{slots && ` · Slots ${slots}`}
</span>
</span>
</label>
{type === 'SHORT' && isPicked && hitDice && (
<div className="flex-row flex-wrap gap-sm mt-sm rest-dice">
{hitDice.remaining === 0 ? (
<span className="combatant-sub">No Hit Dice left to spend until a long rest.</span>
) : (
<>
<label className="flex-row gap-sm">
Spend
<NumberInput
min={0}
max={hitDice.remaining}
placeholder="0"
aria-label={`Hit Dice ${c.name} spends`}
value={dice[c.id] ?? ''}
onChange={(e) => setDice((d) => ({ ...d, [c.id]: e.target.value }))}
style={{ width: 64 }}
/>
of {hitDice.remaining} d{hitDice.size}
</label>
{spent > 0 && (
<label className="flex-row gap-sm">
Roll {spent}d{hitDice.size}:
<NumberInput
min={spent}
max={spent * hitDice.size}
placeholder="site rolls"
aria-label={`What ${c.name}'s Hit Dice added up to`}
title={`What the ${spent}d${hitDice.size} added up to (${spent} to ${spent * hitDice.size}). Leave empty and the site rolls.`}
value={rolled[c.id] ?? ''}
onChange={(e) => setRolled((r) => ({ ...r, [c.id]: e.target.value }))}
style={{ width: 96 }}
/>
<span className="combatant-sub">
{fmtMod(spent * hitDice.conModifier)} Constitution ({fmtMod(hitDice.conModifier)} a die)
</span>
</label>
)}
</>
)}
</div>
)}
</div>
);
})}
<div className="modal-foot">
<button className="btn btn-primary" onClick={handleRest} disabled={picked.size === 0 || rest.isPending}>
{rest.isPending ? 'Resting…' : `Take the ${REST_LABELS[type].toLowerCase()}`}
</button>
</div>
</Modal>
);
}
+90
View File
@@ -0,0 +1,90 @@
import { useSpellSlots } from '../api/queries';
import { slotLevelLabel } from '../lib/format';
import { InfoTip } from './InfoTip';
import type { SpellSlots as SpellSlotsInfo } from '../api/types';
// The slot tracker: a row of pips for each level of slot the character has,
// filled while the slot is still there to spend. `canUse` is the character's
// own player or the DM: "Use" spends one. Getting a slot back is the DM's
// alone: for them each pip is a button that sets how many are left (clicking
// the last filled one takes it off), and "All back" refills the lot.
export function SpellSlotTracker({
characterId,
name,
slots,
canUse,
isDM,
onError,
}: {
characterId: string;
name: string;
slots: SpellSlotsInfo;
canUse: boolean;
isDM: boolean;
onError?: (err: unknown) => void;
}) {
const spellSlots = useSpellSlots(characterId);
const send = (action: Parameters<typeof spellSlots.mutate>[0]) => spellSlots.mutate(action, { onError });
const anySpent = slots.levels.some((slot) => slot.used > 0);
return (
<div className="spell-slots">
<div className="flex-between flex-wrap">
<span className="death-tally">
Spell slots <InfoTip term="SPELL_SLOTS" />
</span>
{isDM && anySpent && (
<button className="btn btn-ghost" onClick={() => send({ action: 'restore' })} disabled={spellSlots.isPending} title={`Give ${name} every spell slot back`}>
All back
</button>
)}
</div>
{slots.levels.map((slot) => {
const label = slotLevelLabel(slot.level);
return (
<div key={slot.level} className="slot-row">
<span className="slot-level">{label}</span>
<span className="slot-pips" role="group" aria-label={`${slot.remaining} of ${slot.max} ${label}-level slots left`}>
{Array.from({ length: slot.max }, (_, i) => i + 1).map((n) => {
const className = `slot-pip${n <= slot.remaining ? ' is-filled' : ''}`;
const left = n === slot.remaining ? n - 1 : n;
return isDM ? (
<button
key={n}
type="button"
className={className}
aria-label={`Set ${label}-level slots left to ${left}`}
disabled={spellSlots.isPending}
onClick={() => send({ action: 'set', level: slot.level, used: slot.max - left })}
/>
) : (
<span key={n} className={className} />
);
})}
</span>
<span className="mono slot-count">
{slot.remaining}/{slot.max}
</span>
{canUse && (
<button
className="btn"
onClick={() => send({ action: 'use', level: slot.level })}
disabled={slot.remaining === 0 || spellSlots.isPending}
title={slot.remaining === 0 ? `No ${label}-level slots left` : `Spend one ${label}-level slot`}
aria-label={`Use a ${label}-level slot`}
>
Use
</button>
)}
</div>
);
})}
<p className="combatant-sub" style={{ margin: '0.4rem 0 0' }}>
{slots.kind === 'PACT'
? 'Every spell cast with one of these is cast at that level. They all come back on a short or long rest.'
: 'A higher slot can cast a lower spell. Cantrips need no slot. They all come back on a long rest.'}
{canUse && !isDM && ' Once used, only the DM can give one back.'}
</p>
</div>
);
}
+93
View File
@@ -1911,6 +1911,99 @@ table.data-table tbody tr.is-mine:hover {
display: flex;
justify-content: flex-end;
}
/* ---------------------------------------------------------------------- */
/* Spell slots, rests and levelling up */
/* ---------------------------------------------------------------------- */
.spell-slots {
margin-top: 0.75rem;
padding-top: 0.6rem;
border-top: 1px solid var(--border-soft);
}
.slot-row {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.3rem 0;
}
.slot-level {
width: 2.2rem;
font-family: var(--font-display);
color: var(--accent-strong);
}
.slot-pips {
display: inline-flex;
flex-wrap: wrap;
gap: 0.3rem;
flex: 1;
min-width: 0;
}
/* A slot still there to spend is filled; a spent one is an empty ring. */
.slot-pip {
width: 1rem;
height: 1rem;
padding: 0;
border-radius: 3px;
border: 2px solid var(--accent);
background: transparent;
transform: rotate(45deg);
margin: 0.15rem;
}
.slot-pip.is-filled {
background: var(--accent-strong);
}
button.slot-pip {
cursor: pointer;
}
button.slot-pip:disabled {
cursor: default;
}
.slot-count {
color: var(--text-muted);
}
.slot-row .btn {
padding: 0.25rem 0.7rem;
}
.rest-dice {
padding-left: 1.75rem;
}
.level-step {
padding: 0.75rem 0;
border-bottom: 1px solid var(--border-soft);
}
.level-step:last-of-type {
border-bottom: none;
}
.level-step p {
margin: 0.4rem 0 0;
}
.level-choice {
align-items: flex-start;
margin: 0.35rem 0;
}
.level-choice input {
margin-top: 0.25rem;
}
.level-spells {
max-height: 14rem;
overflow-y: auto;
margin-top: 0.4rem;
padding: 0.2rem 0.6rem;
border: 1px solid var(--border-soft);
border-radius: 6px;
}
@media (max-width: 900px) {
.slot-pip {
width: 1.3rem;
height: 1.3rem;
}
.rest-dice {
padding-left: 0;
}
}
.pagination .pagination-status > select {
min-width: 0 !important;
padding: 0.3rem 0.5rem;
+11
View File
@@ -127,6 +127,17 @@ export function spellLevelLabel(level: number): string {
return level === 0 ? 'Cantrip' : `Level ${level}`;
}
// A spell slot's level: "1st", "2nd"…
const ORDINALS = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th'];
export function slotLevelLabel(level: number): string {
return ORDINALS[level - 1] ?? `${level}th`;
}
// A character's spell slots in a few words: "1st 3/4 · 2nd 2/2" (left / in all).
export function slotsSummary(slots: { levels: { level: number; max: number; remaining: number }[] } | null): string {
return slots ? slots.levels.map((s) => `${slotLevelLabel(s.level)} ${s.remaining}/${s.max}`).join(' · ') : '';
}
// Who can use a spell: a character of at least its level; cantrips, anyone.
export function spellRequirementLabel(level: number): string {
return level === 0 ? 'any character can use it' : `needs character level ${level}`;
+9
View File
@@ -31,6 +31,7 @@ import { Spinner, ErrorBanner } from '../components/Spinner';
import { NumberInput } from '../components/NumberInput';
import { SectionNav, type Section } from '../components/SectionNav';
import { LifeBadge } from '../components/DeathSaves';
import { RestModal } from '../components/RestModal';
import { Pagination } from '../components/Paginated';
import { usePagination } from '../hooks/usePagination';
import { CampaignSearch, type SearchGroup } from '../components/campaign/CampaignSearch';
@@ -168,6 +169,7 @@ export function CampaignHomePage() {
const [formError, setFormError] = useState<string | null>(null);
const [showSettings, setShowSettings] = useState(false);
const [showDelete, setShowDelete] = useState(false);
const [resting, setResting] = useState(false);
const [deleteConfirmName, setDeleteConfirmName] = useState('');
const liveEncounters = encounters?.filter((e) => !e.archivedAt) || [];
@@ -432,6 +434,11 @@ export function CampaignHomePage() {
<div className="section-block">
<div className="page-header" style={{ marginBottom: '0.75rem' }}>
<h2 style={{ fontSize: '1.1rem', margin: 0 }}>{isDM ? 'Characters' : 'Rest of the Party'}</h2>
{isDM && characters?.some((c) => c.buildStage === 'COMPLETE') && (
<button className="btn" onClick={() => setResting(true)} title="A short or long rest for any of the party: Hit Dice, HP and spell slots">
🛏 Rest…
</button>
)}
</div>
<form onSubmit={handleCreateCharacter} className="flex-row flex-wrap mt-sm" style={{ marginBottom: '0.75rem' }}>
<input
@@ -876,6 +883,8 @@ export function CampaignHomePage() {
</div>
)}
{isDM && resting && <RestModal campaignId={campaignId} characters={characters ?? []} onClose={() => setResting(false)} />}
{isDM && opened && (
<EntryDetail
campaignId={campaignId}
+48 -3
View File
@@ -36,6 +36,8 @@ import { JumpNav } from '../components/JumpNav';
import { useRememberCampaign } from '../lib/lastCampaign';
import { HpBar } from '../components/HpBar';
import { DeathSaves } from '../components/DeathSaves';
import { SpellSlotTracker } from '../components/SpellSlots';
import { LevelUpModal } from '../components/LevelUpModal';
import { GearInForce } from '../components/CharacterPanel';
import { effectsSummary } from '../lib/gear';
import { InfoTip } from '../components/InfoTip';
@@ -280,6 +282,7 @@ export function CharacterSheetPage() {
const [pickedSpellId, setPickedSpellId] = useState('');
const [copyTargetId, setCopyTargetId] = useState('');
const [formError, setFormError] = useState<string | null>(null);
const [levellingUp, setLevellingUp] = useState(false);
const weaponsPage = usePagination(character?.weapons, 8);
const spellsPage = usePagination(character?.spells, 8);
@@ -485,6 +488,10 @@ export function CharacterSheetPage() {
isDM={isDM}
onError={(err) => setFormError(extractErrorMessage(err))}
/>
<p className="subtitle mt-sm" style={{ marginBottom: 0 }}>
Hit Dice: <strong>{sheet.hitDice.remaining}</strong> of {sheet.hitDice.count} left (d{sheet.hitDice.size}{' '}
{fmtMod(sheet.abilities.CON.modifier)} each) <InfoTip term="HIT_DICE_LEFT" />
</p>
{/* HP is the DM's to change; a player reads it. */}
{isDM && (
@@ -534,7 +541,8 @@ export function CharacterSheetPage() {
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<label className="flex-row gap-sm">
{/* Typing a level sets it outright; the button walks the checklist, one level at a time. */}
<label className="flex-row gap-sm" title="Set the level by hand. A higher level still adds the class's new special abilities; use Level Up for the full checklist.">
Level
<NumberInput
key={`level:${character.level}`}
@@ -543,7 +551,30 @@ export function CharacterSheetPage() {
keepValue
defaultValue={character.level}
style={{ width: 60 }}
onBlur={(e) => patchCharacter.mutate({ level: Number(e.target.value) })}
onBlur={(e) => Number(e.target.value) !== character.level && patchCharacter.mutate({ level: Number(e.target.value) })}
/>
</label>
<button
className="btn btn-primary"
onClick={() => setLevellingUp(true)}
disabled={character.level >= 20}
title="Go up one level with the levelling-up checklist: HP, new special abilities, spells and the free weapon upgrade"
>
⬆ Level Up…
</button>
<label className="flex-row gap-sm" title="Hit Dice this character still has to spend on a short rest. The Rest button on the campaign page keeps count for you.">
Hit Dice left
<NumberInput
key={`hitdice:${sheet.hitDice.remaining}:${sheet.hitDice.count}`}
min={0}
max={sheet.hitDice.count}
keepValue
defaultValue={sheet.hitDice.remaining}
style={{ width: 60 }}
onBlur={(e) => {
const left = Number(e.target.value);
if (left !== sheet.hitDice.remaining) patchCharacter.mutate({ hitDiceUsed: sheet.hitDice.count - left });
}}
/>
</label>
<button className="btn btn-ghost" onClick={recomputeMaxHp} title="Recompute max HP from the current level and Constitution">
@@ -633,7 +664,7 @@ export function CharacterSheetPage() {
</div>
{sheet.spellcasting && (
<div className="card mt-md">
<div data-jump="Spellcasting" className="card mt-md">
<div className="card-title">
Spellcasting ({ABILITY_LABELS[sheet.spellcasting.ability]}) <InfoTip term="SPELL_SAVE_DC" />
</div>
@@ -641,6 +672,18 @@ export function CharacterSheetPage() {
Save DC <strong>{sheet.spellcasting.saveDC}</strong> · Attack Bonus{' '}
<strong>{fmtMod(sheet.spellcasting.attackBonus)}</strong> <InfoTip term="SPELL_ATTACK_BONUS" />
</p>
{sheet.spellSlots ? (
<SpellSlotTracker
characterId={characterId}
name={character.name}
slots={sheet.spellSlots}
canUse={canEdit}
isDM={isDM}
onError={(err) => setFormError(extractErrorMessage(err))}
/>
) : (
<p className="subtitle" style={{ margin: '0.4rem 0 0' }}>No spell slots yet: they come at level 2.</p>
)}
</div>
)}
@@ -1062,6 +1105,8 @@ export function CharacterSheetPage() {
<Pagination page={notesPage.page} pageCount={notesPage.pageCount} onPrev={notesPage.prevPage} onNext={notesPage.nextPage} onJump={notesPage.setPage} />
</div>
{isDM && levellingUp && <LevelUpModal character={character} campaignSpells={campaignSpells ?? []} onClose={() => setLevellingUp(false)} />}
</div>
);
}
+23 -4
View File
@@ -1,3 +1,4 @@
import { useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { useAuth } from '../auth/useAuth';
import { useCampaign, useCampaignCharacters } from '../api/queries';
@@ -6,7 +7,8 @@ import { Spinner, ErrorBanner } from '../components/Spinner';
import { Pagination } from '../components/Paginated';
import { usePagination } from '../hooks/usePagination';
import { InfoTip } from '../components/InfoTip';
import { CLASS_LABELS, SPECIES_LABELS, formatPurse } from '../lib/format';
import { CLASS_LABELS, SPECIES_LABELS, formatPurse, slotsSummary } from '../lib/format';
import { RestModal } from '../components/RestModal';
import { HpBar } from '../components/HpBar';
import { LifeBadge } from '../components/DeathSaves';
import { speciesIcon } from '../lib/speciesIcons';
@@ -23,6 +25,7 @@ export function PartyOverviewPage() {
const { data, isLoading: campaignLoading, error: campaignError } = useCampaign(campaignId);
const { data: characters, isLoading: charsLoading, error: charsError } = useCampaignCharacters(campaignId);
const { pageItems, page, pageCount, prevPage, nextPage, setPage } = usePagination(characters, 12);
const [resting, setResting] = useState(false);
if (campaignLoading || charsLoading) return <Spinner label="Gathering the party…" />;
if (campaignError || charsError || !data) return <ErrorBanner message="Could not load the party overview." />;
@@ -36,9 +39,16 @@ export function PartyOverviewPage() {
<h1>Party Overview</h1>
<p className="subtitle">{isDM ? 'Every character in this campaign, at a glance.' : 'Your party.'}</p>
</div>
<Link to={`/campaigns/${campaignId}`} className="btn btn-ghost">
← Back to Campaign
</Link>
<div className="flex-row">
{isDM && characters?.some((c) => c.buildStage === 'COMPLETE') && (
<button className="btn" onClick={() => setResting(true)} title="A short or long rest for any of the party: Hit Dice, HP and spell slots">
🛏 Rest…
</button>
)}
<Link to={`/campaigns/${campaignId}`} className="btn btn-ghost">
← Back to Campaign
</Link>
</div>
</div>
{characters?.length === 0 && <div className="empty-state">No characters yet.</div>}
@@ -58,6 +68,12 @@ export function PartyOverviewPage() {
<th>
AC <InfoTip term="AC" />
</th>
<th>
Hit Dice <InfoTip term="HIT_DICE_LEFT" />
</th>
<th>
Spell slots <InfoTip term="SPELL_SLOTS" />
</th>
<th>Coins</th>
<th>Location</th>
</tr>
@@ -92,6 +108,8 @@ export function PartyOverviewPage() {
)}
</td>
<td data-label="AC">{c.armorClass ?? '—'}</td>
<td data-label="Hit Dice" className="mono">{c.hitDice ? `${c.hitDice.remaining}/${c.hitDice.count} d${c.hitDice.size}` : '—'}</td>
<td data-label="Spell slots" className="mono">{slotsSummary(c.spellSlots) || '—'}</td>
<td data-label="Coins" className="mono">{c.gold == null ? '—' : formatPurse(c)}</td>
<td data-label="Location">{c.currentLocationName ? `📍 ${c.currentLocationName}` : '—'}</td>
</tr>
@@ -102,6 +120,7 @@ export function PartyOverviewPage() {
</div>
)}
<Pagination page={page} pageCount={pageCount} onPrev={prevPage} onNext={nextPage} onJump={setPage} />
{isDM && resting && <RestModal campaignId={campaignId} characters={characters ?? []} onClose={() => setResting(false)} />}
</div>
);
}