V1.25.0: the DM approves a level, each player takes their own

- "Level up..." beside Rest approves a level for any of the party at once;
  with XP tracked, those who have the XP start ticked
- Each player is told with a notice and picks for themselves in the checklist:
  class (multiclass), subclass, Boon, spells within the level's allowance,
  the weapon upgrade; a waiting level shows on the sheet and campaign page
- The DM sees who still has picks to make, and can finish or take back any
- Hit points on a level up can be rolled (campaign setting): by the site, or
  at the table and typed in with physical dice
- Toasts: notices that slide in over any page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 08:30:31 +02:00
co-authored by Claude Opus 5.5
parent 86ef106969
commit c3f2b0dfa7
24 changed files with 782 additions and 66 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "1.24.0",
"version": "1.25.0",
"type": "module",
"scripts": {
"dev": "vite",
+18 -3
View File
@@ -16,6 +16,7 @@ import type {
GearEffect,
GoldTransaction,
Item,
LevelUpApproval,
LevelUpPlan,
Location,
MulticlassReference,
@@ -268,9 +269,9 @@ export function useLevelUpPlan(characterId: string, enabled: boolean, toClass: C
export function useLevelUp(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { characterClass?: CharacterClass; subclass?: string; boon?: string; weaponId?: string | null; spellIds?: string[] }) =>
(await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/level-up`, data)).data.character,
onSuccess: (character) => {
mutationFn: async (data: { characterClass?: CharacterClass; subclass?: string; boon?: string; weaponId?: string | null; spellIds?: string[]; hpRoll?: number }) =>
(await apiClient.post<{ character: CharacterDetail; hpRolled: number | null }>(`/characters/${characterId}/level-up`, data)).data,
onSuccess: ({ character }) => {
invalidateCharacter(qc, characterId);
qc.invalidateQueries({ queryKey: ['encounter'] }); // a character combatant shows the sheet's HP
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
@@ -294,6 +295,20 @@ export function useRest(campaignId: string) {
});
}
// The DM approves a level for any of the party at once (or takes an approval
// back); each character's player then takes theirs.
export function useApproveLevelUps(campaignId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { characterIds: string[]; revoke?: boolean }) =>
(await apiClient.post<{ revoke: boolean; results: LevelUpApproval[] }>(`/campaigns/${campaignId}/level-up`, data)).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['character'] });
qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] });
},
});
}
export function useDeleteCharacter(campaignId: string) {
const qc = useQueryClient();
return useMutation({
+18
View File
@@ -303,6 +303,7 @@ export interface CharacterSummary extends CharacterCondition {
characterClass: CharacterClass | null;
subclassName: string | null;
level: number;
levelUpsPending: number; // levels the DM has approved, still to be taken
classes: ClassLevel[];
xp: number;
xpProgress: XpProgress;
@@ -508,6 +509,7 @@ export interface CharacterDetail extends CharacterCondition {
// The 2024 subclass that updates the one followed, if there is one.
subclassUpgrade: SubclassSummary | null;
level: number;
levelUpsPending: number; // levels the DM has approved, still to be taken
classes: ClassLevel[];
xp: number;
xpProgress: XpProgress;
@@ -922,6 +924,9 @@ export interface LevelUpPlan {
// With multiclassing on: every class the level could go to, and why not.
classChoice: { options: { characterClass: CharacterClass; level: number; eligible: boolean; problems: string[] }[] } | null;
maxHp: { from: number; to: number };
// How the level's hit points are come by: the average, or a roll of the
// class's die (typed in from the table when `physical`).
hp: { method: HpMethod; die: number; average: number; physical: boolean };
// Set when a subclass has to be picked on the way to this level: the level
// the class chooses at, and each option with everything it would write.
subclass: { level: number; options: { key: string; name: string; summary: string; features: { name: string; text: string }[] }[] } | null;
@@ -934,11 +939,24 @@ export interface LevelUpPlan {
// 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
// The campaign's spells that could be granted now: of a level the class can
// cast, and not yet known.
spellOptions: { id: string; name: string; level: number; school: string | null; description: string | null }[];
// 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 20, where the class tables stop
}
// What approving (or taking back) a level did for one character (POST /campaigns/:id/level-up).
export interface LevelUpApproval {
characterId: string;
name: string;
userId: string | null;
level: number;
levelUpsPending: number;
skipped: string | null; // why nothing changed for them
}
export type RestType = 'SHORT' | 'LONG';
// What a rest did for one character (POST /campaigns/:id/rest).
+2
View File
@@ -4,6 +4,7 @@ import { useAuth } from '../auth/useAuth';
import { useLastCampaignId, useRememberCampaign } from '../lib/lastCampaign';
import { DiceRoller } from './DiceRoller';
import { CharacterPanel } from './CharacterPanel';
import { Toasts } from './Toasts';
export function Layout() {
const { user, logout } = useAuth();
@@ -70,6 +71,7 @@ export function Layout() {
)}
<DiceRoller />
{user && <CharacterPanel />}
<Toasts />
</div>
);
}
@@ -0,0 +1,135 @@
import { useState } from 'react';
import { useApproveLevelUps } from '../api/queries';
import { classLabel, extractErrorMessage } from '../lib/format';
import { Modal } from './Modal';
import { ErrorBanner } from './Spinner';
import type { CharacterSummary, LevelUpApproval } from '../api/types';
const MAX_LEVEL = 20;
// The DM's level-up button: approve a level for any of the party at once.
// Each approval is a checklist waiting for its character: their player is
// told and makes the picks themselves, so nobody queues for the DM. A
// character without a player is the DM's to finish, from its sheet.
// `trackXp`: with XP kept, those who have the XP for their next level start
// ticked; without it (milestones) the DM ticks who levels.
export function LevelUpBulkModal({
campaignId,
characters,
trackXp,
onClose,
}: {
campaignId: string;
characters: CharacterSummary[];
trackXp: boolean;
onClose: () => void;
}) {
const approve = useApproveLevelUps(campaignId);
const party = characters.filter((c) => c.buildStage === 'COMPLETE');
const canLevel = (c: CharacterSummary) => c.level + c.levelUpsPending < MAX_LEVEL;
const [picked, setPicked] = useState<Set<string>>(() => new Set(party.filter((c) => trackXp && c.xpProgress.levelUpDue && canLevel(c)).map((c) => c.id)));
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState<LevelUpApproval[] | null>(null);
function toggle(id: string) {
setPicked((current) => {
const next = new Set(current);
if (!next.delete(id)) next.add(id);
return next;
});
}
async function send(characterIds: string[], revoke = false) {
setError(null);
try {
const { results } = await approve.mutateAsync({ characterIds, revoke });
if (!revoke) setDone(results);
} catch (err) {
setError(extractErrorMessage(err));
}
}
if (done) {
return (
<Modal title="Level ups approved" subtitle="Each player makes their own picks" onClose={onClose}>
{done.map((result) => (
<div key={result.characterId} className="reward-row">
<strong>{result.name}</strong>
{result.skipped ? (
<div className="combatant-sub">{result.skipped}</div>
) : (
<div className="combatant-sub">
Level {result.level} → {result.level + 1} is theirs to take.{' '}
{result.userId ? 'Their player has been told and chooses what they gain.' : 'No player: finish it from the sheet.'}
</div>
)}
</div>
))}
<div className="modal-foot">
<button className="btn btn-primary" onClick={onClose}>
Done
</button>
</div>
</Modal>
);
}
return (
<Modal title="Level up" subtitle="Approve a level for the party; each player then picks what they gain" wide onClose={onClose}>
{error && <ErrorBanner message={error} />}
<div className="flex-row flex-wrap gap-sm">
<button className="btn" onClick={() => setPicked(new Set(party.filter(canLevel).map((c) => c.id)))}>
Everyone
</button>
{trackXp && (
<button className="btn" onClick={() => setPicked(new Set(party.filter((c) => c.xpProgress.levelUpDue && canLevel(c)).map((c) => c.id)))}>
Those with the XP
</button>
)}
<button className="btn btn-ghost" onClick={() => setPicked(new Set())}>
Nobody
</button>
</div>
<div className="mt-md">
{party.length === 0 && <p className="combatant-sub">No finished characters yet.</p>}
{party.map((c) => (
<label key={c.id} className="checkbox-row level-choice" style={canLevel(c) ? undefined : { opacity: 0.55 }}>
<input type="checkbox" checked={picked.has(c.id)} disabled={!canLevel(c)} onChange={() => toggle(c.id)} />
<span style={{ flex: 1 }}>
<strong>{c.name}</strong>{' '}
<span className="combatant-sub">
{classLabel(c.characterClass, c.subclassName, c.classes)} · Level {c.level}
</span>
{trackXp && c.xpProgress.levelUpDue && <span className="badge badge-live" style={{ marginLeft: 6 }}>has the XP</span>}
{c.levelUpsPending > 0 && (
<span className="badge" style={{ marginLeft: 6 }}>
{c.levelUpsPending} waiting on their picks
</span>
)}
{!c.userId && <span className="badge" style={{ marginLeft: 6 }}>no player: yours to finish</span>}
</span>
{c.levelUpsPending > 0 && (
<button
type="button"
className="btn btn-ghost btn-sm"
title="Takes back one approved level that has not been taken yet"
disabled={approve.isPending}
onClick={(e) => {
e.preventDefault();
send([c.id], true);
}}
>
Take one back
</button>
)}
</label>
))}
</div>
<div className="modal-foot">
<button className="btn btn-primary" disabled={picked.size === 0 || approve.isPending} onClick={() => send([...picked])}>
{approve.isPending ? 'Approving…' : `Approve a level for ${picked.size} character${picked.size === 1 ? '' : 's'}`}
</button>
</div>
</Modal>
);
}
+61 -17
View File
@@ -2,8 +2,10 @@ import { useState, type ReactNode } from 'react';
import { useLevelUp, useLevelUpPlan } from '../api/queries';
import { CLASS_LABELS, classLabel, extractErrorMessage, slotLevelLabel, slotsSummary, spellLevelLabel } from '../lib/format';
import { Modal } from './Modal';
import { NumberInput } from './NumberInput';
import { Spinner, ErrorBanner } from './Spinner';
import type { CharacterClass, CharacterDetail, LevelUpPlan, Spell } from '../api/types';
import { showToast } from '../lib/toasts';
import type { CharacterClass, CharacterDetail, LevelUpPlan } from '../api/types';
// One numbered step of the checklist.
function Step({ n, title, children }: { n: number; title: string; children: ReactNode }) {
@@ -27,8 +29,10 @@ 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 (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 }) {
// site does every step; whoever is levelling makes the choices and says yes:
// the DM, or the character's own player once the DM has approved the level.
// A player picks spells within what the level allows; the DM grants freely.
export function LevelUpModal({ character, isDM, onClose }: { character: CharacterDetail; isDM: boolean; onClose: () => void }) {
// The class taking the level: the first one, unless another is picked (multiclassing).
const [toClass, setToClass] = useState<CharacterClass | null>(null);
const { data: plan, isLoading, error: planError } = useLevelUpPlan(character.id, true, toClass);
@@ -38,6 +42,7 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
// 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 [hpRoll, setHpRoll] = useState('');
const [error, setError] = useState<string | null>(null);
if (isLoading || !plan) {
@@ -49,13 +54,16 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
}
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 grantable = plan.spellOptions;
// A player picks up to the level's allowance; the DM is not held to it.
const spellAllowance = plan.spells ? plan.spells.newSpells + plan.spells.newCantrips : 0;
const spellsFull = !isDM && spellIds.size >= spellAllowance;
const needsHpRoll = plan.hp.method === 'ROLL' && plan.hp.physical;
const hpRollValid = Number.isInteger(Number(hpRoll)) && Number(hpRoll) >= 1 && Number(hpRoll) <= plan.hp.die;
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;
const owed =
plan.subclass && !subclass ? 'Choose a subclass first' : plan.boon && !boon ? 'Choose a Boon first' : needsHpRoll && !hpRollValid ? `Roll your d${plan.hp.die} for hit points` : null;
function toggleSpell(id: string) {
setSpellIds((current) => {
@@ -68,9 +76,14 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
async function handleLevelUp() {
setError(null);
try {
await levelUp.mutateAsync({
const { hpRolled } = await levelUp.mutateAsync({
hpRoll: needsHpRoll ? Number(hpRoll) : undefined,
characterClass: plan!.characterClass,
subclass: plan!.subclass ? subclass : undefined, boon: plan!.boon ? boon : undefined, weaponId: weaponId || null, spellIds: [...spellIds] });
showToast({
tone: 'good',
text: `${character.name} is level ${plan!.toLevel}!${hpRolled != null ? ` The d${plan!.hp.die} for hit points came up ${hpRolled}.` : ''}`,
});
onClose();
} catch (err) {
setError(extractErrorMessage(err));
@@ -124,9 +137,32 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
</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>
{plan.hp.method === 'AVERAGE' ? (
<p>
Max HP <strong>{plan.maxHp.from}</strong> → <strong>{plan.maxHp.to}</strong>, and healed to full. One more Hit Die (d{plan.hp.die}).
</p>
) : needsHpRoll ? (
<div>
<p style={{ marginBottom: '0.3rem' }}>
This campaign rolls for hit points. Roll a <strong>d{plan.hp.die}</strong> at the table and enter what it shows; your Constitution
modifier is added for you. Healed to full, and one more Hit Die.
</p>
<label className="flex-row gap-sm">
I rolled
<NumberInput min={1} max={plan.hp.die} placeholder={`1–${plan.hp.die}`} value={hpRoll} onChange={(e) => setHpRoll(e.target.value)} style={{ width: 80 }} />
{hpRollValid && (
<span className="combatant-sub">
Max HP {plan.maxHp.from} → {plan.maxHp.to - plan.hp.average + Number(hpRoll)}
</span>
)}
</label>
</div>
) : (
<p>
This campaign rolls for hit points: a <strong>d{plan.hp.die}</strong> is rolled when you confirm (between {plan.maxHp.to - plan.hp.average + 1} and{' '}
{plan.maxHp.to - plan.hp.average + plan.hp.die} max HP), plus healing to full and one more Hit Die.
</p>
)}
</Step>
<Step n={3} title="Special abilities">
@@ -190,7 +226,9 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
</div>
)}
{(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>
<p className="combatant-sub">
Written into Special Abilities for you. {isDM ? 'Where a line says "choose", edit it there once the player has.' : 'Where a line says "choose", agree it with your DM.'}
</p>
)}
</Step>
@@ -216,16 +254,22 @@ export function LevelUpModal({ character, campaignSpells, onClose }: { character
<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>
<input type="checkbox" checked={spellIds.has(spell.id)} disabled={spellsFull && !spellIds.has(spell.id)} onChange={() => toggleSpell(spell.id)} />
<span title={spell.description ?? undefined}>
{spell.name}{' '}
<span className="combatant-sub">
{spellLevelLabel(spell.level)}
{spell.school ? ` · ${spell.school}` : ''}
</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.
{isDM
? `${spellIds.size > 0 ? `${spellIds.size} picked. ` : ''}A player may also swap one known spell for another: take the old one away on the sheet.`
: `${spellIds.size} of ${spellAllowance} picked. Hover a spell to read what it does.`}
</p>
</>
)}
+27
View File
@@ -0,0 +1,27 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { dismissToast, subscribeToasts, type Toast } from '../lib/toasts';
// The stack of toasts (lib/toasts.ts), mounted once in the layout.
export function Toasts() {
const [toasts, setToasts] = useState<Toast[]>([]);
useEffect(() => subscribeToasts(setToasts), []);
if (toasts.length === 0) return null;
return (
<div className="toasts" role="status" aria-live="polite">
{toasts.map((toast) => (
<div key={toast.id} className={`toast${toast.tone ? ` toast-${toast.tone}` : ''}`}>
<span className="toast-text">{toast.text}</span>
{toast.action && (
<Link to={toast.action.to} className="btn btn-primary btn-sm" onClick={() => dismissToast(toast.id)}>
{toast.action.label}
</Link>
)}
<button className="btn btn-ghost btn-sm" aria-label="Dismiss" onClick={() => dismissToast(toast.id)}>
✕
</button>
</div>
))}
</div>
);
}
+14 -2
View File
@@ -3,6 +3,8 @@ import { useQueryClient, type QueryKey } from '@tanstack/react-query';
import { io, type Socket } from 'socket.io-client';
import { API_URL } from '../api/client';
import { useAuth } from '../auth/useAuth';
import { showToast } from '../lib/toasts';
import type { CharacterDetail } from '../api/types';
let sharedSocket: Socket | null = null;
@@ -24,8 +26,9 @@ const FLUSH_MS = 50;
// sync with server-pushed events (HP/condition changes, encounter rounds,
// new characters) so every open tab in the campaign updates live.
export function useCampaignSocket(campaignId: string | undefined) {
const { token } = useAuth();
const { token, user } = useAuth();
const qc = useQueryClient();
const userId = user?.id;
useEffect(() => {
if (!campaignId || !token) return;
@@ -56,6 +59,13 @@ export function useCampaignSocket(campaignId: string | undefined) {
// A character arriving somewhere new adds it to the places their player can see.
invalidate(['campaign', campaignId, 'locations']);
};
// The DM approved a level for a character: its player is told, wherever
// in the campaign they are, with a way straight to the checklist.
const onLevelUpGranted = ({ characterId, userId: ownerId }: { characterId?: string; userId?: string | null } = {}) => {
if (!characterId || !ownerId || ownerId !== userId) return;
const name = qc.getQueryData<CharacterDetail>(['character', characterId])?.name ?? 'Your character';
showToast({ text: `⬆ ${name} can level up! See what you gain and make your picks.`, tone: 'good', action: { label: 'Level up', to: `/characters/${characterId}?levelup=1` } });
};
const onCharacterCreated = () => {
invalidate(['campaign', campaignId, 'characters']);
};
@@ -74,6 +84,7 @@ export function useCampaignSocket(campaignId: string | undefined) {
socket.on('character:updated', onCharacterUpdated);
socket.on('character:created', onCharacterCreated);
socket.on('character:level-up-granted', onLevelUpGranted);
socket.on('encounter:participant-updated', onParticipantUpdated);
socket.on('encounter:round-advanced', onRoundAdvanced);
socket.on('campaign:deleted', onCampaignDeleted);
@@ -86,9 +97,10 @@ export function useCampaignSocket(campaignId: string | undefined) {
socket.emit('campaign:leave', campaignId);
socket.off('character:updated', onCharacterUpdated);
socket.off('character:created', onCharacterCreated);
socket.off('character:level-up-granted', onLevelUpGranted);
socket.off('encounter:participant-updated', onParticipantUpdated);
socket.off('encounter:round-advanced', onRoundAdvanced);
socket.off('campaign:deleted', onCampaignDeleted);
};
}, [campaignId, token, qc]);
}, [campaignId, token, qc, userId]);
}
+59
View File
@@ -403,6 +403,65 @@ input[type='radio'] {
font-size: 0.9rem;
}
/* Toasts: notices that slide in over any page (components/Toasts.tsx). */
.toasts {
position: fixed;
top: 4.2rem;
right: 1rem;
z-index: 1200;
display: flex;
flex-direction: column;
gap: 0.5rem;
max-width: min(26rem, calc(100vw - 2rem));
}
.toast {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.6rem 0.8rem;
background: var(--bg-card);
border: 1px solid var(--accent);
border-radius: var(--radius);
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.45);
animation: toastIn 0.25s ease-out;
}
.toast-good {
border-color: var(--accent-strong);
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.45), 0 0 14px rgba(201, 162, 39, 0.3);
}
.toast-text {
flex: 1;
font-size: 0.92rem;
}
@keyframes toastIn {
from {
opacity: 0;
transform: translateX(1.5rem);
}
to {
opacity: 1;
transform: none;
}
}
@media (prefers-reduced-motion: reduce) {
.toast {
animation: none;
}
}
/* A notice across the top of a card or page that something is waiting. */
.notice-banner {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.6rem;
padding: 0.6rem 0.9rem;
margin-bottom: 0.9rem;
border: 1px solid var(--accent-strong);
border-radius: var(--radius);
background: linear-gradient(160deg, var(--bg-card-hover) 0%, var(--bg-inset) 100%);
}
/* A group of campaign settings under its own heading. */
.settings-group {
border: 1px solid var(--border);
+45
View File
@@ -0,0 +1,45 @@
// Toasts: short notices that slide in over any page ("Aria can level up").
// A tiny store of its own, so anything can raise one (a socket event, a
// mutation) without being inside a particular component. <Toasts />
// (components/Toasts.tsx), mounted once in the layout, shows them.
export interface Toast {
id: number;
text: string;
// Where "tone" is 'good' the toast is a piece of good news; default is neutral.
tone?: 'good' | 'warn';
// A link to follow up on it: its label and where it goes.
action?: { label: string; to: string };
}
type Listener = (toasts: Toast[]) => void;
let toasts: Toast[] = [];
let nextId = 1;
const listeners = new Set<Listener>();
const publish = () => listeners.forEach((listener) => listener(toasts));
// How long a toast stays before it goes by itself.
const TOAST_MS = 12000;
export function showToast(toast: Omit<Toast, 'id'>): number {
const id = nextId++;
toasts = [...toasts, { ...toast, id }].slice(-5);
publish();
setTimeout(() => dismissToast(id), TOAST_MS);
return id;
}
export function dismissToast(id: number) {
if (!toasts.some((toast) => toast.id === id)) return;
toasts = toasts.filter((toast) => toast.id !== id);
publish();
}
export function subscribeToasts(listener: Listener): () => void {
listeners.add(listener);
listener(toasts);
return () => {
listeners.delete(listener);
};
}
+38 -8
View File
@@ -32,13 +32,14 @@ import { NumberInput } from '../components/NumberInput';
import { SectionNav, type Section } from '../components/SectionNav';
import { LifeBadge } from '../components/DeathSaves';
import { RestModal } from '../components/RestModal';
import { LevelUpBulkModal } from '../components/LevelUpBulkModal';
import { Pagination } from '../components/Paginated';
import { usePagination } from '../hooks/usePagination';
import { CampaignSearch, type SearchGroup } from '../components/campaign/CampaignSearch';
import { EntryDetail } from '../components/campaign/EntryDetail';
import { ItemsSection, MonstersSection, NpcsSection, SpellsSection, WeaponsSection } from '../components/campaign/PoolSections';
import { effectsSummary } from '../lib/gear';
import { extractErrorMessage, spellLevelLabel } from '../lib/format';
import { SPECIES_LABELS, classLabel, extractErrorMessage, spellLevelLabel } from '../lib/format';
import { matchesSearch, type EntryKind, type EntryRef } from '../lib/campaignEntries';
import { speciesIcon } from '../lib/speciesIcons';
import type { CampaignDiceMode, CharacterSummary, CritRule, Encounter, EncounterMode, HpMethod, RollVisibility, ScoreMethod } from '../api/types';
@@ -86,7 +87,8 @@ function sortEncounters(encounters: Encounter[], sort: EncounterSort): Encounter
return [...encounters].sort(compare[sort]);
}
function CharacterRow({ character, isDM, onDelete }: { character: CharacterSummary; isDM: boolean; onDelete: () => void }) {
// `mine`: the viewer's own character, who gets the way into a level up that is waiting.
function CharacterRow({ character, isDM, mine = false, onDelete }: { character: CharacterSummary; isDM: boolean; mine?: boolean; onDelete: () => void }) {
const inProgress = character.buildStage !== 'COMPLETE';
return (
<div className="card flex-between flex-wrap">
@@ -97,10 +99,15 @@ function CharacterRow({ character, isDM, onDelete }: { character: CharacterSumma
{character.name}
</Link>
{inProgress && <span className="badge">Building…</span>}
{character.levelUpsPending > 0 && (isDM || mine) && (
<span className="badge badge-live" title={mine ? 'Your DM has approved a level: open the sheet to choose what you gain' : 'Approved, and waiting for the picks to be made'}>
⬆ Level up {mine ? 'ready' : 'waiting on picks'}
</span>
)}
</div>
<p style={{ margin: 0, color: 'var(--text-muted)', fontSize: '0.9rem' }}>
{character.species ? `${character.species} ` : ''}
{character.characterClass || (inProgress ? 'Not yet built' : '')}{character.subclassName && ` (${character.subclassName})`} · Level {character.level}
{character.species ? `${SPECIES_LABELS[character.species] ?? character.species} ` : ''}
{character.characterClass ? classLabel(character.characterClass, character.subclassName, character.classes) : inProgress ? 'Not yet built' : ''} · Level {character.level}
{character.currentLocationName && ` · 📍 ${character.currentLocationName}`}
</p>
</div>
@@ -110,6 +117,11 @@ function CharacterRow({ character, isDM, onDelete }: { character: CharacterSumma
<LifeBadge deathSaves={character.deathSaves} /> HP {character.currentHp}/{character.maxHp} · AC {character.armorClass}
</div>
)}
{mine && character.levelUpsPending > 0 && !inProgress && (
<Link to={`/characters/${character.id}?levelup=1`} className="btn btn-primary">
⬆ Level up
</Link>
)}
<Link to={inProgress ? `/characters/${character.id}/build` : `/characters/${character.id}`} className="btn">
{inProgress ? 'Continue Build' : 'Open Sheet'}
</Link>
@@ -180,6 +192,7 @@ export function CampaignHomePage() {
const [showSettings, setShowSettings] = useState(false);
const [showDelete, setShowDelete] = useState(false);
const [resting, setResting] = useState(false);
const [levelling, setLevelling] = useState(false);
const [deleteConfirmName, setDeleteConfirmName] = useState('');
const liveEncounters = encounters?.filter((e) => !e.archivedAt) || [];
@@ -440,7 +453,7 @@ export function CampaignHomePage() {
<div className="section-block">
<h2 style={{ fontSize: '1.1rem' }}>Your Character{myCharacters.length > 1 ? 's' : ''}</h2>
{myCharacters.map((c) => (
<CharacterRow key={c.id} character={c} isDM={false} onDelete={() => {}} />
<CharacterRow key={c.id} character={c} isDM={false} mine onDelete={() => {}} />
))}
</div>
)}
@@ -450,9 +463,23 @@ export function CampaignHomePage() {
<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 className="flex-row flex-wrap">
<button
className="btn"
onClick={() => setLevelling(true)}
title="Approve a level for any of the party at once: each player is told, and picks what they gain themselves"
>
⬆ Level up…
{campaign.trackXp && characters.some((c) => c.xpProgress.levelUpDue) && (
<span className="badge badge-live" style={{ marginLeft: 6 }}>
{characters.filter((c) => c.xpProgress.levelUpDue).length} due
</span>
)}
</button>
<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>
)}
</div>
<form onSubmit={handleCreateCharacter} className="flex-row flex-wrap mt-sm" style={{ marginBottom: '0.75rem' }}>
@@ -1010,6 +1037,9 @@ export function CampaignHomePage() {
)}
{isDM && resting && <RestModal campaignId={campaignId} characters={characters ?? []} onClose={() => setResting(false)} />}
{isDM && levelling && (
<LevelUpBulkModal campaignId={campaignId} characters={characters ?? []} trackXp={campaign.trackXp} onClose={() => setLevelling(false)} />
)}
{isDM && opened && (
<EntryDetail
+45 -6
View File
@@ -1,5 +1,5 @@
import { useState, type FormEvent } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import {
useCharacter,
usePatchCharacter,
@@ -27,6 +27,7 @@ import {
useCampaigns,
useCopyCharacter,
useCampaignLocations,
useApproveLevelUps,
} from '../api/queries';
import { useAuth } from '../auth/useAuth';
import { useCampaignSocket } from '../hooks/useCampaignSocket';
@@ -251,6 +252,7 @@ export function CharacterSheetPage() {
const { data: character, isLoading, error } = useCharacter(characterId);
useRememberCampaign(character?.campaignId);
const patchCharacter = usePatchCharacter(characterId);
const approveLevelUp = useApproveLevelUps(character?.campaignId ?? '');
useCampaignSocket(character?.campaignId);
const { data: campaignData } = useCampaign(character?.campaignId);
@@ -292,7 +294,9 @@ export function CharacterSheetPage() {
const [pickedSpellId, setPickedSpellId] = useState('');
const [copyTargetId, setCopyTargetId] = useState('');
const [formError, setFormError] = useState<string | null>(null);
const [levellingUp, setLevellingUp] = useState(false);
// ?levelup=1 (the link in the "can level up" notice) opens the checklist straight away.
const [searchParams, setSearchParams] = useSearchParams();
const [levellingUp, setLevellingUp] = useState(searchParams.get('levelup') === '1');
const weaponsPage = usePagination(character?.weapons, 8);
const spellsPage = usePagination(character?.spells, 8);
@@ -428,6 +432,22 @@ export function CharacterSheetPage() {
return (
<div>
{character.levelUpsPending > 0 && canEdit && (
<div className="notice-banner" role="status">
<span style={{ flex: 1 }}>
<strong>⬆ {isOwner ? 'You can level up!' : `${character.name} has a level up waiting.`}</strong>{' '}
{isOwner
? `Level ${character.level} → ${character.level + 1}: see what you gain and make your picks.`
: character.userId
? 'Their player has been told; you can also finish it for them.'
: 'No player: it is yours to finish.'}
{character.levelUpsPending > 1 && ` (${character.levelUpsPending} levels approved.)`}
</span>
<button className="btn btn-primary" onClick={() => setLevellingUp(true)}>
{isOwner ? 'Choose what you gain' : 'Open the checklist'}
</button>
</div>
)}
<div className="page-header">
<div>
<h1>
@@ -606,13 +626,23 @@ export function CharacterSheetPage() {
/>
</label>
)}
{character.userId && character.userId !== user?.id && (
<button
className="btn btn-primary"
onClick={() => approveLevelUp.mutate({ characterIds: [character.id] }, { onError: (err) => setFormError(extractErrorMessage(err)) })}
disabled={character.level + character.levelUpsPending >= 20 || approveLevelUp.isPending}
title="Approves one level: their player is told, sees what they gain and makes the picks themselves"
>
⬆ Approve a level up{character.levelUpsPending > 0 ? ` (${character.levelUpsPending} waiting)` : ''}
</button>
)}
<button
className="btn btn-primary"
className="btn"
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"
title="Go up one level yourself with the levelling-up checklist: HP, new special abilities, spells and the free weapon upgrade"
>
⬆ Level Up…
⬆ Level up now…
</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
@@ -1288,7 +1318,16 @@ 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)} />}
{(isDM || (isOwner && character.levelUpsPending > 0)) && levellingUp && (
<LevelUpModal
character={character}
isDM={isDM}
onClose={() => {
setLevellingUp(false);
if (searchParams.has('levelup')) setSearchParams({}, { replace: true });
}}
/>
)}
</div>
);
+23
View File
@@ -9,6 +9,7 @@ import { usePagination } from '../hooks/usePagination';
import { InfoTip } from '../components/InfoTip';
import { SPECIES_LABELS, classLabel, formatPurse, slotsSummary, xpLabel } from '../lib/format';
import { RestModal } from '../components/RestModal';
import { LevelUpBulkModal } from '../components/LevelUpBulkModal';
import { HpBar } from '../components/HpBar';
import { LifeBadge } from '../components/DeathSaves';
import { ConditionChip, StateBadges } from '../components/CharacterState';
@@ -29,6 +30,7 @@ export function PartyOverviewPage() {
const { data: characters, isLoading: charsLoading, error: charsError } = useCampaignCharacters(campaignId);
const { pageItems, page, pageCount, prevPage, nextPage, setPage } = usePagination(characters, 12);
const [resting, setResting] = useState(false);
const [levelling, setLevelling] = useState(false);
const [checking, setChecking] = useState(false);
if (campaignLoading || charsLoading) return <Spinner label="Gathering the party…" />;
@@ -51,6 +53,11 @@ export function PartyOverviewPage() {
🎲 Call for a roll…
</button>
)}
{isDM && characters?.some((c) => c.buildStage === 'COMPLETE') && (
<button className="btn" onClick={() => setLevelling(true)} title="Approve a level for any of the party at once: each player is told, and picks what they gain themselves">
⬆ Level up…
</button>
)}
{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…
@@ -64,6 +71,18 @@ export function PartyOverviewPage() {
{characters?.length === 0 && <div className="empty-state">No characters yet.</div>}
{isDM && characters?.some((c) => c.levelUpsPending > 0) && (
<div className="notice-banner" role="status">
<span style={{ flex: 1 }}>
<strong>⬆ Level ups waiting on picks:</strong>{' '}
{characters
.filter((c) => c.levelUpsPending > 0)
.map((c) => `${c.name}${c.userId ? '' : ' (no player: yours to finish)'}`)
.join(', ')}
</span>
</div>
)}
{characters && characters.length > 0 && (
<div className="table-wrap">
<table className="data-table">
@@ -125,6 +144,7 @@ export function PartyOverviewPage() {
<td data-label="Class">{c.characterClass ? classLabel(c.characterClass, c.subclassName, c.classes) : inProgress ? 'Building…' : '—'}</td>
<td data-label="Level">
{c.level}
{c.levelUpsPending > 0 && <span title="A level up is approved and waiting for its picks"> ⬆</span>}
{!inProgress && data?.campaign.trackXp && (
<div className="combatant-sub mono" style={{ whiteSpace: 'nowrap' }}>
{xpLabel(c.xp, c.xpProgress)}
@@ -167,6 +187,9 @@ export function PartyOverviewPage() {
<Pagination page={page} pageCount={pageCount} onPrev={prevPage} onNext={nextPage} onJump={setPage} />
{isDM && checking && <GroupCheckModal characters={checkers} onClose={() => setChecking(false)} />}
{isDM && resting && <RestModal campaignId={campaignId} characters={characters ?? []} onClose={() => setResting(false)} />}
{isDM && levelling && (
<LevelUpBulkModal campaignId={campaignId} characters={characters ?? []} trackXp={data?.campaign.trackXp ?? true} onClose={() => setLevelling(false)} />
)}
</div>
);
}