V1.1.0: gear levels, encounter overhaul, guided builder, trading, docs

Characters
- Builder: pick-then-Next on every step with live preview, Back button,
  plain-language help throughout, and "Suggest for me" for ability scores
- Motivation is picked from a list; new steps for special abilities,
  background and appearance, all composed from fixed lists and DM-only
  to edit afterwards
- Copy a character to another campaign
- Characters can give gold, weapons, items and spells to each other
- Money tracker: gold only changes through a logged ledger
- Fixes: level/XP/location are DM-only, HP stays within 0..max, physical
  dice ability rolls, every die is rolled once

Gear
- DM-managed item pool; weapons, items and spells are handed out by the DM
- Starting-option flag per pool entry
- Gear levels 1-9 per held copy with a damage ladder, growth rate and
  starting level; spells gated by spell level with a fixed damage value
- Spell library carries default damage; damage is picked from a list

Encounters
- Battle and NPC quest modes, turn tracking, scene description, DM notes
- NPCs, richer combatant cards, conditions from a list
- Rewards (gold, weapons, items) lined up and awarded, with gold splitting
- Character HP is shared between the sheet and the encounter
- Monster stat blocks and NPC secrets are never sent to players

Other
- Dice roller on every page
- Docs for characters, weapons, spells, items, encounters, monsters and
  NPCs, with full lists generated from the data (npm run docs:lists)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-05 16:47:28 +02:00
co-authored by Claude Opus 5.5
parent 94067f1268
commit 4a6a09bae8
44 changed files with 9405 additions and 700 deletions
+245 -17
View File
@@ -1,6 +1,7 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { apiClient } from './client';
import type {
BuildOptions,
Campaign,
CampaignLibrary,
CampaignMemberSummary,
@@ -8,11 +9,14 @@ import type {
CharacterSummary,
DiceMode,
Encounter,
EncounterMode,
EncounterParticipant,
InventoryItem,
GoldTransaction,
Item,
Location,
Monster,
Note,
Npc,
QuickStats,
Spell,
Weapon,
@@ -120,10 +124,11 @@ export function useCharacter(characterId: string | undefined) {
});
}
// `gold` is deliberately not patchable — it only moves through useAdjustGold.
export function usePatchCharacter(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: Partial<CharacterDetail>) =>
mutationFn: async (data: Partial<Omit<CharacterDetail, 'gold'>>) =>
(await apiClient.patch<{ character: CharacterDetail }>(`/characters/${characterId}`, data)).data.character,
onSuccess: (character) => {
qc.setQueryData(['character', characterId], character);
@@ -140,6 +145,38 @@ export function useDeleteCharacter(campaignId: string) {
});
}
// What one character can hand to another. Whatever is given leaves the giver.
export type Gift =
| { kind: 'gold'; amount: number }
| { kind: 'weapon' | 'item'; id: string; quantity: number }
| { kind: 'spell'; id: string };
export function useGive(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (gift: Gift & { toCharacterId: string }) =>
(await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/give`, gift)).data.character,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['character'] }); // both sheets, and both money logs
qc.invalidateQueries({ queryKey: ['campaign'] });
},
});
}
export function useCopyCharacter(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (targetCampaignId: string) =>
(await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/copy`, { targetCampaignId })).data
.character,
onSuccess: (character) => {
qc.setQueryData(['character', character.id], character);
// The copy can add missing weapons/spells to the target campaign's pools.
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId] });
},
});
}
export function useQuickStats(characterId: string | undefined, enabled: boolean) {
return useQuery({
queryKey: ['character', characterId, 'quick-stats'],
@@ -153,6 +190,14 @@ export function useQuickStats(characterId: string | undefined, enabled: boolean)
// Character build flow
// --------------------------------------------------------------------------
export function useBuildOptions() {
return useQuery({
queryKey: ['build-options'],
staleTime: Infinity, // fixed lists — they never change while the app is open
queryFn: async () => (await apiClient.get<BuildOptions>('/characters/build/options')).data,
});
}
function invalidateCharacter(qc: ReturnType<typeof useQueryClient>, characterId: string) {
qc.invalidateQueries({ queryKey: ['character', characterId] });
}
@@ -191,6 +236,16 @@ export function useBuildChoose(characterId: string) {
});
}
// Steps back one step so its choice can be changed. Dice are never re-rolled.
export function useBuildBack(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async () =>
(await apiClient.post<{ buildStage: string; buildState: Record<string, unknown> }>(`/characters/${characterId}/build/back`)).data,
onSuccess: () => invalidateCharacter(qc, characterId),
});
}
export function useBuildFinalize(characterId: string) {
const qc = useQueryClient();
return useMutation({
@@ -208,6 +263,8 @@ export function useBuildFinalize(characterId: string) {
// Weapons / inventory / spells on a character
// --------------------------------------------------------------------------
// Handing out, removing and re-counting gear is DM-only on the server; the
// owning player can only toggle equipped / prepared.
export function useAssignWeapon(characterId: string) {
const qc = useQueryClient();
return useMutation({
@@ -217,20 +274,29 @@ export function useAssignWeapon(characterId: string) {
});
}
export function useRemoveCharacterWeapon(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (weaponId: string) => apiClient.delete(`/characters/${characterId}/weapons/${weaponId}`),
onSuccess: () => invalidateCharacter(qc, characterId),
});
}
export function usePatchCharacterWeapon(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ weaponId, ...data }: { weaponId: string; equipped?: boolean; quantity?: number }) =>
mutationFn: async ({ weaponId, ...data }: { weaponId: string; equipped?: boolean; quantity?: number; level?: number }) =>
(await apiClient.patch(`/characters/${characterId}/weapons/${weaponId}`, data)).data,
onSuccess: () => invalidateCharacter(qc, characterId),
});
}
export function useAddInventoryItem(characterId: string) {
// itemId here is the campaign pool item's id, as with weapons and spells.
export function useAssignItem(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { name: string; description?: string; quantity?: number }) =>
(await apiClient.post<{ item: InventoryItem }>(`/characters/${characterId}/inventory`, data)).data.item,
mutationFn: async (data: { itemId: string; quantity?: number }) =>
(await apiClient.post(`/characters/${characterId}/inventory`, data)).data,
onSuccess: () => invalidateCharacter(qc, characterId),
});
}
@@ -238,13 +304,13 @@ export function useAddInventoryItem(characterId: string) {
export function usePatchInventoryItem(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ itemId, ...data }: { itemId: string; quantity?: number; equipped?: boolean }) =>
mutationFn: async ({ itemId, ...data }: { itemId: string; quantity?: number; equipped?: boolean; level?: number }) =>
(await apiClient.patch(`/characters/${characterId}/inventory/${itemId}`, data)).data,
onSuccess: () => invalidateCharacter(qc, characterId),
});
}
export function useDeleteInventoryItem(characterId: string) {
export function useRemoveInventoryItem(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (itemId: string) => apiClient.delete(`/characters/${characterId}/inventory/${itemId}`),
@@ -270,6 +336,38 @@ export function usePatchCharacterSpell(characterId: string) {
});
}
export function useRemoveCharacterSpell(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (spellId: string) => apiClient.delete(`/characters/${characterId}/spells/${spellId}`),
onSuccess: () => invalidateCharacter(qc, characterId),
});
}
// --------------------------------------------------------------------------
// Money tracker
// --------------------------------------------------------------------------
export function useGoldLedger(characterId: string | undefined) {
return useQuery({
queryKey: ['character', characterId, 'gold'],
enabled: Boolean(characterId),
queryFn: async () =>
(await apiClient.get<{ gold: number; transactions: GoldTransaction[] }>(`/characters/${characterId}/gold`)).data
.transactions,
});
}
// amount is signed: positive = gained, negative = spent.
export function useAdjustGold(characterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { amount: number; reason?: string }) =>
(await apiClient.post<{ gold: number; transaction: GoldTransaction }>(`/characters/${characterId}/gold`, data)).data,
onSuccess: () => invalidateCharacter(qc, characterId), // prefix match also refreshes the ledger
});
}
// --------------------------------------------------------------------------
// Campaign weapons / spells / monsters pools
// --------------------------------------------------------------------------
@@ -291,6 +389,58 @@ export function useCreateWeapon(campaignId: string) {
});
}
// Edits (or, with useDeletePoolEntry, removes) one entry of a campaign pool.
// Used for the "starting option" toggle on weapons, spells and items.
type Pool = 'weapons' | 'spells' | 'items' | 'npcs';
export function usePatchPoolEntry(campaignId: string, pool: Pool) {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
id,
...data
}: {
id: string;
isStartingOption?: boolean;
damageDice?: string | null;
damageScaling?: number;
minLevel?: number;
name?: string;
description?: string | null;
}) =>
(await apiClient.patch(`/campaigns/${campaignId}/${pool}/${id}`, data)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, pool] }),
});
}
export function useDeletePoolEntry(campaignId: string, pool: Pool) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id: string) => apiClient.delete(`/campaigns/${campaignId}/${pool}/${id}`),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['campaign', campaignId, pool] });
qc.invalidateQueries({ queryKey: ['character'] }); // characters holding it just lost it
},
});
}
export function useCampaignItems(campaignId: string | undefined) {
return useQuery({
queryKey: ['campaign', campaignId, 'items'],
enabled: Boolean(campaignId),
queryFn: async () => (await apiClient.get<{ items: Item[] }>(`/campaigns/${campaignId}/items`)).data.items,
});
}
export function useCreateItem(campaignId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: Omit<Item, 'id' | 'campaignId'>) =>
(await apiClient.post<{ item: Item }>(`/campaigns/${campaignId}/items`, data)).data.item,
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'items'] }),
});
}
export function useCampaignSpells(campaignId: string | undefined) {
return useQuery({
queryKey: ['campaign', campaignId, 'spells'],
@@ -308,10 +458,11 @@ export function useCreateSpell(campaignId: string) {
});
}
export function useCampaignMonsters(campaignId: string | undefined) {
// Monster stat blocks are DM-only on the server, so only the DM asks for them.
export function useCampaignMonsters(campaignId: string | undefined, isDM: boolean) {
return useQuery({
queryKey: ['campaign', campaignId, 'monsters'],
enabled: Boolean(campaignId),
enabled: Boolean(campaignId) && isDM,
queryFn: async () =>
(await apiClient.get<{ monsters: Monster[] }>(`/campaigns/${campaignId}/monsters`)).data.monsters,
});
@@ -422,9 +573,8 @@ export function useCampaignEncounters(campaignId: string | undefined) {
export function useCreateEncounter(campaignId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (name: string) =>
(await apiClient.post<{ encounter: Encounter }>(`/campaigns/${campaignId}/encounters`, { name })).data
.encounter,
mutationFn: async (data: { name: string; mode?: EncounterMode }) =>
(await apiClient.post<{ encounter: Encounter }>(`/campaigns/${campaignId}/encounters`, data)).data.encounter,
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'encounters'] }),
});
}
@@ -440,7 +590,7 @@ export function useEncounter(encounterId: string | undefined) {
export function useAddParticipant(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { characterId?: string; monsterId?: string; displayName?: string; initiative?: number }) =>
mutationFn: async (data: { characterId?: string; monsterId?: string; npcId?: string; displayName?: string; initiative?: number }) =>
(await apiClient.post(`/encounters/${encounterId}/participants`, data)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
});
@@ -475,13 +625,91 @@ export function useAdvanceRound(encounterId: string) {
export function usePatchEncounter(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { status?: EncounterStatusInput; name?: string }) =>
(await apiClient.patch(`/encounters/${encounterId}`, data)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
mutationFn: async (data: {
status?: EncounterStatusInput;
mode?: EncounterMode;
name?: string;
description?: string | null;
dmNotes?: string | null;
}) => (await apiClient.patch(`/encounters/${encounterId}`, data)).data,
onSuccess: (_data, variables) => {
qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
// The campaign page lists encounters by name, mode and status.
if (variables.status || variables.mode || variables.name) qc.invalidateQueries({ queryKey: ['campaign'] });
},
});
}
type EncounterStatusInput = 'PLANNING' | 'ACTIVE' | 'COMPLETE';
export function useNextTurn(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => (await apiClient.post(`/encounters/${encounterId}/next-turn`)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
});
}
// --------------------------------------------------------------------------
// Encounter rewards — DM lines loot up, then awards it to a character
// --------------------------------------------------------------------------
export type NewReward =
| { type: 'GOLD'; gold: number; note?: string }
| { type: 'WEAPON'; weaponId: string; quantity?: number; level?: number; note?: string }
| { type: 'ITEM'; itemId: string; quantity?: number; level?: number; note?: string };
export function useAddReward(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: NewReward) => (await apiClient.post(`/encounters/${encounterId}/rewards`, data)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
});
}
export function useDeleteReward(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (rewardId: string) => apiClient.delete(`/encounters/${encounterId}/rewards/${rewardId}`),
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
});
}
// Awarding is what actually changes the character: a gold ledger entry, or
// the weapon/item added to what they hold.
export function useAwardReward(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ rewardId, ...target }: { rewardId: string } & ({ characterId: string } | { split: true })) =>
(await apiClient.post(`/encounters/${encounterId}/rewards/${rewardId}/award`, target)).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
qc.invalidateQueries({ queryKey: ['character'] });
qc.invalidateQueries({ queryKey: ['campaign'] });
},
});
}
// --------------------------------------------------------------------------
// NPCs — a DM-only pool; players meet them through encounters
// --------------------------------------------------------------------------
export function useCampaignNpcs(campaignId: string | undefined, isDM: boolean) {
return useQuery({
queryKey: ['campaign', campaignId, 'npcs'],
enabled: Boolean(campaignId) && isDM,
queryFn: async () => (await apiClient.get<{ npcs: Npc[] }>(`/campaigns/${campaignId}/npcs`)).data.npcs,
});
}
export function useCreateNpc(campaignId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: Partial<Omit<Npc, 'id'>> & { name: string }) =>
(await apiClient.post<{ npc: Npc }>(`/campaigns/${campaignId}/npcs`, data)).data.npc,
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'npcs'] }),
});
}
// --------------------------------------------------------------------------
// Notes
// --------------------------------------------------------------------------
+141 -3
View File
@@ -33,11 +33,50 @@ export type BuildStage =
| 'ROLLING_MOTIVATION'
| 'ASSIGNING_SCORES'
| 'ASSIGNING_PROFICIENCIES'
| 'CHOOSING_ABILITIES'
| 'CHOOSING_BACKGROUND'
| 'CHOOSING_APPEARANCE'
| 'CHOOSING_EQUIPMENT'
| 'COMPLETE';
export type DiceMode = 'DIGITAL' | 'PHYSICAL';
// The fixed lists the builder's story steps are made of (served by the API so
// the page never keeps its own copy).
export interface NamedAbility {
name: string;
text: string;
}
export interface PickOption {
key: string;
label: string;
text?: string;
}
// One question in the background or appearance step; the player picks between
// `min` and `max` of its options.
export interface PickGroup {
key: string;
label: string;
prompt: string;
min: number;
max: number;
options: PickOption[];
}
export type Picks = Record<string, string[]>;
export interface BuildOptions {
motivations: { key: number; label: string }[];
speciesTraits: Record<Species, NamedAbility[]>;
classFeatures: Record<CharacterClass, NamedAbility[]>;
talents: (NamedAbility & { key: string })[];
talentPicks: number;
background: PickGroup[];
appearance: PickGroup[];
}
export interface User {
id: string;
email: string;
@@ -77,6 +116,7 @@ export interface CharacterSummary {
buildStage: BuildStage;
currentHp: number;
tempHp: number;
gold: number;
maxHp: number | null;
armorClass: number | null;
currentLocationId: string | null;
@@ -121,6 +161,12 @@ export interface Weapon {
properties: string[];
rangeNormal: number | null;
rangeLong: number | null;
// damageDice is the damage at minLevel (the level the weapon starts at); a
// held copy climbs this many rungs of the damage ladder per level above
// that (1 standard, 2 powerful, 3 legendary).
damageScaling: number;
minLevel: number;
isStartingOption: boolean;
}
export interface CharacterWeapon {
@@ -129,6 +175,9 @@ export interface CharacterWeapon {
weaponId: string;
quantity: number;
equipped: boolean;
level: number;
scaledDamageDice: string; // the dice at this copy's level
usable: boolean; // false while the character is below this copy's level
weapon: Weapon;
}
@@ -142,6 +191,8 @@ export interface Spell {
range: string | null;
duration: string | null;
description: string | null;
damageDice: string | null;
isStartingOption: boolean;
}
export interface CharacterSpell {
@@ -149,16 +200,42 @@ export interface CharacterSpell {
characterId: string;
spellId: string;
prepared: boolean;
usable: boolean; // false while the character is below the spell's level
spell: Spell;
}
// An entry in the campaign's DM-managed item pool.
export interface Item {
id: string;
campaignId: string;
name: string;
description: string | null;
damageDice: string | null; // optional dice (damage, healing…) at its starting level
damageScaling: number;
minLevel: number;
isStartingOption: boolean;
}
export interface InventoryItem {
id: string;
characterId: string;
name: string;
description: string | null;
itemId: string;
quantity: number;
equipped: boolean;
level: number;
scaledDamageDice: string | null;
usable: boolean;
item: Item;
}
export interface GoldTransaction {
id: string;
characterId: string;
amount: number; // signed: positive = gained, negative = spent
balanceAfter: number;
reason: string | null;
createdAt: string;
createdBy: { displayName: string } | null;
}
export interface SkillProficiency {
@@ -230,10 +307,47 @@ export interface Monster {
}
export type EncounterStatus = 'PLANNING' | 'ACTIVE' | 'COMPLETE';
export type EncounterMode = 'BATTLE' | 'QUEST';
export type NpcDisposition = 'FRIENDLY' | 'NEUTRAL' | 'HOSTILE';
// What players see of an NPC in an encounter.
export interface NpcPublic {
id: string;
name: string;
role: string | null;
disposition: NpcDisposition;
description: string | null;
}
// The DM's full record. dmNotes and the combat stats never reach a player.
export interface Npc extends NpcPublic {
dmNotes: string | null;
ac: number | null;
maxHp: number | null;
attackBonus: number | null;
damageDice: string | null;
}
export interface EncounterReward {
id: string;
encounterId: string;
type: 'GOLD' | 'WEAPON' | 'ITEM';
gold: number | null;
weaponId: string | null;
itemId: string | null;
quantity: number;
level: number;
note: string | null;
awardedTo: string | null;
awardedAt: string | null;
weapon: Weapon | null;
item: Item | null;
}
export interface CombatWeapon {
characterWeaponId: string;
name: string;
level: number;
equipped: boolean;
quantity: number;
attackBonus: number;
@@ -246,11 +360,24 @@ export interface CombatSpell {
characterSpellId: string;
name: string;
level: number;
description: string | null;
damageDice: string | null;
prepared: boolean;
}
export interface CharacterCombatInfo {
level: number;
species: Species | null;
characterClass: CharacterClass | null;
armorClass: number;
tempHp: number;
speed: number;
initiativeBonus: number;
passivePerception: number;
proficiencyBonus: number;
abilities: Record<Ability, AbilityDetail>;
saves: Record<Ability, { proficient: boolean; bonus: number }>;
specialAbilities: string | null;
weapons: CombatWeapon[];
spells: CombatSpell[];
spellcasting: { ability: Ability; saveDC: number; attackBonus: number } | null;
@@ -267,8 +394,12 @@ export interface EncounterParticipant {
maxHp: number;
conditions: string[];
isMonster: boolean;
kind: 'CHARACTER' | 'MONSTER' | 'NPC';
npcId: string | null;
character?: { id: string; name: string } | null;
monster?: { id: string; name: string } | null;
// The DM gets the whole stat block; players only the id and name.
monster?: ({ id: string; name: string } & Partial<Monster>) | null;
npc?: (NpcPublic & Partial<Npc>) | null;
characterCombatInfo?: CharacterCombatInfo;
}
@@ -276,10 +407,15 @@ export interface Encounter {
id: string;
campaignId: string;
name: string;
mode: EncounterMode;
status: EncounterStatus;
currentRound: number;
activeParticipantId: string | null;
description: string | null;
dmNotes?: string | null; // DM only
createdAt: string;
participants?: EncounterParticipant[];
rewards?: EncounterReward[]; // players only receive the awarded ones
}
export interface Note {
@@ -314,6 +450,7 @@ export interface LibrarySpell {
range: string | null;
duration: string | null;
description: string | null;
damageDice?: string; // default damage; absent for spells that deal none
classes: CharacterClass[];
}
@@ -346,6 +483,7 @@ export interface QuickStatsWeapon {
characterWeaponId: string;
weaponId: string;
name: string;
level: number;
equipped: boolean;
quantity: number;
attackBonus: number;
+166
View File
@@ -0,0 +1,166 @@
import { useEffect, useState } from 'react';
import { fmtMod } from '../lib/format';
const DICE = [4, 6, 8, 10, 12, 20, 100];
const MAX_DICE = 20;
const HISTORY_LENGTH = 8;
interface Roll {
id: number;
sides: number;
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;
}
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.
export function DiceRoller() {
const [open, setOpen] = useState(false);
const [sides, setSides] = useState(20);
const [count, setCount] = useState(1);
const [modifier, setModifier] = useState(0);
const [history, setHistory] = useState<Roll[]>([]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [open]);
const latest = history[0];
function roll() {
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));
}
// 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;
return (
<>
<button
className="fab-dice"
onClick={() => setOpen((o) => !o)}
title="Roll dice"
aria-label={open ? 'Close the dice roller' : 'Open the dice roller'}
aria-expanded={open}
>
🎲
</button>
{open && (
<div className="dice-panel" role="dialog" aria-label="Dice roller">
<div className="flex-between">
<div className="card-title" style={{ margin: 0 }}>
Roll Dice
</div>
<button className="btn btn-ghost" onClick={() => setOpen(false)} aria-label="Close the dice roller">
✕
</button>
</div>
<div className="dice-choices mt-sm" role="group" aria-label="Which die">
{DICE.map((d) => (
<button key={d} className={`die-btn${d === sides ? ' is-selected' : ''}`} aria-pressed={d === sides} onClick={() => setSides(d)}>
d{d}
</button>
))}
</div>
<div className="flex-between mt-sm">
<div className="flex-row gap-sm">
<span className="dice-label">Dice</span>
<button className="btn" aria-label="One fewer die" disabled={count <= 1} onClick={() => setCount(count - 1)}>
−
</button>
<span className="mono" aria-live="polite" style={{ minWidth: '1.5ch', textAlign: 'center' }}>
{count}
</span>
<button className="btn" aria-label="One more die" disabled={count >= MAX_DICE} onClick={() => setCount(count + 1)}>
+
</button>
</div>
<label className="flex-row gap-sm">
<span className="dice-label">Bonus</span>
<input
type="number"
min={-99}
max={99}
value={modifier}
onChange={(e) => setModifier(Math.max(-99, Math.min(99, Math.trunc(Number(e.target.value)) || 0)))}
style={{ width: 70 }}
/>
</label>
</div>
<button className="btn btn-primary btn-block btn-lg mt-sm" onClick={roll}>
🎲 Roll {notation(count, sides, modifier)}
</button>
<div className="dice-result" aria-live="polite">
{latest ? (
<>
{/* 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) && (
<div className="dice-breakdown mono">
{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.
</p>
)}
</div>
{history.length > 1 && (
<>
<div className="flex-between">
<span className="dice-label">Earlier rolls</span>
<button className="btn btn-ghost" onClick={() => setHistory([])}>
Clear
</button>
</div>
{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.dice.length > 1 && <span className="dice-history-dice"> ({r.dice.join(', ')})</span>}
</span>
<strong className="mono">{r.total}</strong>
</div>
))}
</>
)}
</div>
)}
</>
);
}
+14 -2
View File
@@ -22,12 +22,24 @@ export 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.',
// 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.',
SPECIES_BONUS: 'Species bonus — points your species adds on top of the ability scores you roll. They are added automatically.',
SAVE_PROFICIENCY: 'Each class is trained in two saving throws. On those you add your proficiency bonus when resisting spells, traps and other effects.',
KEY_ABILITY: 'Key abilities — the scores this class leans on most. Put your best rolls here.',
SPELLCASTING: 'Spellcasting ability — the score that powers this class’s spells. A higher score makes your spells harder to resist and more accurate.',
ROLL_4D6: 'Roll four six-sided dice and add up the best three (the lowest is dropped). Do that six times to get six scores, usually between 8 and 16.',
STARTING_EQUIPMENT: 'Your DM chooses which weapons, items and spells are available to brand-new characters, and how many you may take.',
DAMAGE_DICE: 'Damage dice — what you roll when this weapon hits. “1d8” means one eight-sided die. Your Strength or Dexterity modifier is added on top.',
};
export function InfoTip({ term, label = 'What is this?' }: { term: keyof typeof STAT_HELP; label?: string }) {
// `term` looks up a standard explanation above; `text` supplies a one-off
// (a species, a skill, an ability) without adding it to the shared list.
export function InfoTip({ term, text: custom, label = 'What is this?' }: { term?: keyof typeof STAT_HELP; text?: string; label?: string }) {
const [open, setOpen] = useState(false);
const id = useId();
const text = STAT_HELP[term];
const text = custom ?? (term ? STAT_HELP[term] : undefined);
if (!text) return null;
return (
+2
View File
@@ -1,5 +1,6 @@
import { Link, Outlet } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext';
import { DiceRoller } from './DiceRoller';
export function Layout() {
const { user, logout } = useAuth();
@@ -27,6 +28,7 @@ export function Layout() {
<main className="page">
<Outlet />
</main>
<DiceRoller />
</div>
);
}
+1 -1
View File
@@ -72,7 +72,7 @@ export function QuickStatsDrawer({ characterId, onClose }: { characterId: string
<strong>{w.name}</strong>
{w.equipped && <span className="badge" style={{ marginLeft: 6 }}>equipped</span>}
<p style={{ margin: 0, fontSize: '0.85rem', color: 'var(--text-muted)' }}>
{w.damageDice} {w.damageType} {fmtMod(w.damageBonus)}
Lv {w.level} · {w.damageDice} {w.damageType} {fmtMod(w.damageBonus)}
</p>
</div>
<span className="stat-value" style={{ fontSize: '1.1rem' }}>
+1
View File
@@ -28,6 +28,7 @@ export function useCampaignSocket(campaignId: string | undefined) {
const onCharacterUpdated = () => {
qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] });
qc.invalidateQueries({ queryKey: ['character'] });
qc.invalidateQueries({ queryKey: ['encounter'] }); // a character combatant shows the sheet HP
};
const onCharacterCreated = () => {
qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] });
+453
View File
@@ -733,3 +733,456 @@ table.data-table tbody tr:hover {
font-size: 2.2rem;
}
}
/* ---------------------------------------------------------------------- */
/* Encounter screen */
/* ---------------------------------------------------------------------- */
.badge-friendly {
border-color: var(--success);
color: var(--success-strong);
}
.badge-neutral {
border-color: var(--border);
color: var(--text-muted);
}
.badge-hostile {
border-color: var(--danger);
color: var(--danger-strong);
}
.badge-live {
border-color: var(--success);
color: var(--success-strong);
}
.encounter-layout {
display: grid;
grid-template-columns: 1fr;
gap: 1.25rem;
align-items: start;
}
@media (min-width: 960px) {
.encounter-layout {
grid-template-columns: minmax(0, 1fr) 330px;
}
}
.section-label {
font-family: var(--font-display);
color: var(--text-muted);
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.1em;
margin: 0 0 0.5rem;
}
.card + .section-label,
.empty-state + .section-label {
margin-top: 1.5rem;
}
/* One combatant. The left edge is colour-coded by who it is. */
.combatant {
border-left: 4px solid var(--border);
padding: 1rem 1.1rem;
}
.combatant-character {
border-left-color: var(--arcane);
}
.combatant-monster {
border-left-color: var(--danger);
}
.combatant-npc {
border-left-color: var(--success);
}
.combatant.is-active {
border-color: var(--accent-strong);
box-shadow: 0 0 0 1px var(--accent-strong), 0 0 22px rgba(201, 162, 39, 0.25), var(--shadow-deep);
}
.combatant.is-down {
opacity: 0.6;
}
.combatant-name {
font-family: var(--font-display);
font-size: 1.1rem;
color: var(--text);
}
.combatant-sub {
color: var(--text-muted);
font-size: 0.85rem;
}
.turn-marker {
color: var(--accent-strong);
font-family: var(--font-display);
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.stat-chips {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.stat-chip {
display: inline-flex;
align-items: baseline;
gap: 0.35rem;
background: var(--bg-inset);
border: 1px solid var(--border-soft);
border-radius: 6px;
padding: 0.2rem 0.55rem;
font-size: 0.9rem;
}
.stat-chip span {
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-dim);
}
.stat-chip b {
color: var(--accent-strong);
font-weight: 600;
}
.condition-chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.15rem 0.5rem;
border-radius: 999px;
font-size: 0.8rem;
border: 1px solid var(--danger);
color: var(--danger-strong);
background: var(--danger-soft);
}
.condition-chip button {
background: none;
border: none;
color: inherit;
cursor: pointer;
padding: 0 0.1rem;
font-size: 0.85rem;
line-height: 1;
}
.combatant-details {
margin-top: 0.75rem;
padding-top: 0.75rem;
border-top: 1px solid var(--border-soft);
font-size: 0.92rem;
}
.combatant-details p {
margin: 0.3rem 0;
}
.detail-row {
display: flex;
justify-content: space-between;
gap: 0.5rem;
padding: 0.2rem 0;
}
.reward-row {
padding: 0.55rem 0;
border-bottom: 1px solid var(--border-soft);
}
.reward-row:last-child {
border-bottom: none;
}
.reward-row.is-awarded {
color: var(--text-muted);
}
.textarea-block {
display: block;
width: 100%;
resize: vertical;
}
/* ---------------------------------------------------------------------- */
/* Character builder: pick-then-confirm choices */
/* ---------------------------------------------------------------------- */
.step-intro {
color: var(--text-muted);
margin: 0 0 1rem;
}
.build-steps {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.build-steps .badge.is-done {
border-color: var(--accent);
color: var(--accent-strong);
}
.build-steps .badge.is-current {
border-color: var(--accent-strong);
background: var(--accent-soft);
color: var(--accent-strong);
font-weight: 700;
}
.choice-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
gap: 0.75rem;
text-align: left;
}
.choice-card {
display: flex;
flex-direction: column;
gap: 0.4rem;
text-align: left;
font-family: var(--font-body);
font-size: 0.95rem;
color: var(--text);
background: var(--bg-inset);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.9rem 1rem;
cursor: pointer;
transition: border-color 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease;
}
.choice-card:hover {
border-color: var(--accent);
transform: translateY(-1px);
}
.choice-card:focus-visible {
outline: none;
box-shadow: 0 0 0 3px var(--accent-soft);
}
.choice-card.is-selected {
border-color: var(--accent-strong);
box-shadow: 0 0 0 1px var(--accent-strong), 0 0 18px rgba(201, 162, 39, 0.25);
background: linear-gradient(160deg, var(--bg-card-hover) 0%, var(--bg-inset) 100%);
}
.choice-card-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
font-family: var(--font-display);
font-size: 1.1rem;
color: var(--accent-strong);
}
.choice-card-blurb {
color: var(--text-muted);
font-style: italic;
}
.choice-card-facts {
color: var(--text-muted);
font-size: 0.85rem;
}
.step-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
margin-top: 1.25rem;
padding-top: 1rem;
border-top: 1px solid var(--border-soft);
text-align: left;
}
.stat-block.is-key {
border-color: var(--accent);
}
.key-marker {
color: var(--accent-strong);
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 0.06em;
}
/* ---------------------------------------------------------------------- */
/* Dice roller — on every page, bottom-left (quick stats owns bottom-right) */
/* ---------------------------------------------------------------------- */
.fab-dice {
position: fixed;
bottom: 1.25rem;
left: 1.25rem;
z-index: 80;
border-radius: 999px;
width: 60px;
height: 60px;
display: flex;
align-items: center;
justify-content: center;
background: radial-gradient(circle at 35% 30%, #3a2e18, #1c160c 70%);
border: 2px solid var(--accent);
color: var(--accent-strong);
font-size: 1.6rem;
cursor: pointer;
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.5), 0 0 18px rgba(201, 162, 39, 0.3);
transition: transform 0.15s ease;
}
.fab-dice:hover {
transform: translateY(-2px) rotate(-8deg);
}
.dice-panel {
position: fixed;
bottom: calc(1.25rem + 60px + 0.75rem);
left: 1.25rem;
z-index: 85;
width: min(340px, calc(100vw - 2.5rem));
max-height: calc(100vh - 8rem);
overflow-y: auto;
background: linear-gradient(180deg, #1c160d 0%, #120e08 100%);
border: 1px solid var(--accent);
border-radius: var(--radius);
box-shadow: var(--shadow-deep);
padding: 1rem;
}
.dice-choices {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 0.4rem;
}
.die-btn {
font-family: var(--font-display);
font-size: 0.95rem;
padding: 0.55rem 0;
border-radius: 6px;
border: 1px solid var(--border);
background: var(--bg-inset);
color: var(--text);
cursor: pointer;
transition: border-color 0.15s ease, color 0.15s ease;
}
.die-btn:hover {
border-color: var(--accent);
color: var(--accent-strong);
}
.die-btn.is-selected {
border-color: var(--accent-strong);
background: var(--accent-soft);
color: var(--accent-strong);
font-weight: 700;
}
.dice-label {
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-dim);
}
.dice-result {
text-align: center;
min-height: 6.5rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0.75rem 0;
padding: 0.5rem;
background: var(--bg-inset);
border: 1px solid var(--border-soft);
border-radius: var(--radius);
}
.roll-result.is-crit {
color: var(--success-strong);
text-shadow: 0 0 20px rgba(122, 178, 102, 0.6);
}
.roll-result.is-fumble {
color: var(--danger-strong);
text-shadow: 0 0 20px rgba(216, 84, 84, 0.5);
}
.dice-callout {
font-family: var(--font-display);
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--success-strong);
}
.dice-callout.is-fumble {
color: var(--danger-strong);
}
.dice-breakdown {
color: var(--text-muted);
font-size: 0.85rem;
word-break: break-word;
}
.dice-history-row {
padding: 0.25rem 0;
border-top: 1px solid var(--border-soft);
font-size: 0.9rem;
}
.dice-history-dice {
color: var(--text-dim);
font-size: 0.8rem;
}
/* ---------------------------------------------------------------------- */
/* Character builder: story steps (motivation, abilities, background, look) */
/* ---------------------------------------------------------------------- */
.pick-group {
padding: 0.75rem 0;
border-top: 1px solid var(--border-soft);
}
.pick-group:first-of-type {
border-top: none;
}
.pick-group-label {
font-family: var(--font-display);
color: var(--accent);
font-size: 0.9rem;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.pick-chips {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin-top: 0.5rem;
}
.pick-chip {
font-family: var(--font-body);
font-size: 0.95rem;
padding: 0.35rem 0.8rem;
border-radius: 999px;
border: 1px solid var(--border);
background: var(--bg-inset);
color: var(--text);
cursor: pointer;
transition: border-color 0.15s ease, color 0.15s ease;
}
.pick-chip:hover:not(:disabled) {
border-color: var(--accent);
}
.pick-chip.is-selected {
border-color: var(--accent-strong);
background: var(--accent-soft);
color: var(--accent-strong);
font-weight: 600;
}
.pick-chip:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.pick-detail {
color: var(--text-muted);
font-style: italic;
margin: 0.4rem 0 0;
}
.granted-ability {
padding: 0.4rem 0;
border-bottom: 1px solid var(--border-soft);
}
.granted-ability:last-child {
border-bottom: none;
}
/* Text the builder composed, shown read-only on the sheet. */
.composed-text {
margin: 0;
white-space: pre-wrap;
}
+21
View File
@@ -86,3 +86,24 @@ export function extractErrorMessage(err: unknown): string {
if (err instanceof Error) return err.message;
return 'Something went wrong.';
}
// A cantrip is spell level 0. It is always called a cantrip, never "level 0"
// or "level 1".
export function spellLevelLabel(level: number): string {
return level === 0 ? 'Cantrip' : `Level ${level}`;
}
// 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}`;
}
// The damage values offered for a spell, grouped by how many dice are rolled.
const SPELL_DIE_SIZES = [4, 6, 8, 10, 12];
const SPELL_DIE_COUNTS = [1, 2, 3, 4, 5, 6, 8, 10];
export const SPELL_DAMAGE_GROUPS: { label: string; options: string[] }[] = SPELL_DIE_COUNTS.map((count) => ({
label: count === 1 ? '1 die' : `${count} dice`,
options: SPELL_DIE_SIZES.map((size) => `${count}d${size}`),
}));
// Values the spell library uses that don't fit the pattern above.
export const SPELL_DAMAGE_SPECIALS = ['3d4+3', '2d8+4d6', '20'];
+229
View File
@@ -0,0 +1,229 @@
import type { Ability, CharacterClass, Species } from '../api/types';
// Plain-language explanations for someone building their first character.
// Everything here describes what a choice does to the *numbers* — plus a line
// of flavour. The special abilities a species or class grants are listed
// separately, from the server's own lists (useBuildOptions).
export const SPECIES_SPEED: Record<Species, number> = {
HUMAN: 30,
HALF_ELF: 30,
ELF: 30,
GNOME: 25,
DWARF: 25,
HALFLING: 25,
DRAGONBORN: 30,
TIEFLING: 30,
HALF_ORC: 30,
ORC: 30,
};
export const SPECIES_GUIDE: Record<Species, { blurb: string; goodFor: string }> = {
HUMAN: {
blurb: 'Adaptable and ambitious, found in every corner of the world.',
goodFor: 'A little better at everything (+1 to all six abilities). A safe pick for any class.',
},
HALF_ELF: {
blurb: 'Walks between two worlds, with human drive and elven grace.',
goodFor: 'Very charming (+2 Charisma), and you choose two more abilities to raise by 1. Great for talkers and Charisma spellcasters.',
},
ELF: {
blurb: 'Graceful, long-lived and quick on their feet.',
goodFor: 'Nimble (+2 Dexterity): harder to hit, acts sooner in a fight, better with bows and light blades.',
},
GNOME: {
blurb: 'Small, curious tinkerers with sharp minds.',
goodFor: 'Clever (+2 Intelligence): ideal for Wizards and knowledge skills. A little slower on foot.',
},
DWARF: {
blurb: 'Stout, stubborn mountain folk who are hard to put down.',
goodFor: 'Tough (+2 Constitution): more hit points at every level. A little slower on foot.',
},
HALFLING: {
blurb: 'Small, cheerful and surprisingly brave.',
goodFor: 'Nimble (+2 Dexterity): harder to hit and good at sneaking. A little slower on foot.',
},
DRAGONBORN: {
blurb: 'Proud, scaled warriors with dragon blood.',
goodFor: 'Strong (+2 Strength) with presence (+1 Charisma): hits hard up close. Great for Paladins and Fighters.',
},
TIEFLING: {
blurb: 'Marked by an infernal bloodline, and used to being stared at.',
goodFor: 'Magnetic (+2 Charisma) and bright (+1 Intelligence): great for Warlocks, Sorcerers and Bards.',
},
HALF_ORC: {
blurb: 'Fierce and enduring, with something to prove.',
goodFor: 'Strong (+2 Strength) and hardy (+1 Constitution): hits hard and takes hits. Great for Barbarians and Fighters.',
},
ORC: {
blurb: 'Powerful and relentless, raised to survive.',
goodFor: 'Strong (+2 Strength) and hardy (+1 Constitution): built for the front line.',
},
};
export type Toughness = 'Fragile' | 'Average' | 'Sturdy' | 'Very tough';
export const CLASS_GUIDE: Record<
CharacterClass,
{ blurb: string; playsLike: string; keyAbilities: Ability[]; skillCount: number; difficulty: 'Easy' | 'Medium' | 'Tricky' }
> = {
FIGHTER: {
blurb: 'A trained warrior, at home with any weapon.',
playsLike: 'Stand at the front, hit things, take hits. The simplest class to play well.',
keyAbilities: ['STR', 'DEX', 'CON'],
skillCount: 2,
difficulty: 'Easy',
},
BARBARIAN: {
blurb: 'A fierce warrior driven by raw fury.',
playsLike: 'Charge in and soak up damage — you have the most hit points of any class.',
keyAbilities: ['STR', 'CON'],
skillCount: 2,
difficulty: 'Easy',
},
ROGUE: {
blurb: 'A sneak, scout and scoundrel who relies on cunning.',
playsLike: 'Strike from the shadows and solve problems with skills — you get more skills than anyone.',
keyAbilities: ['DEX'],
skillCount: 4,
difficulty: 'Medium',
},
RANGER: {
blurb: 'A hunter and tracker of the wild places.',
playsLike: 'Fight from range or up close, with a little nature magic and plenty of outdoor skills.',
keyAbilities: ['DEX', 'WIS'],
skillCount: 3,
difficulty: 'Medium',
},
WIZARD: {
blurb: 'A scholar who has studied magic from books.',
playsLike: 'Stay back and cast spells. Powerful but fragile — the fewest hit points of any class.',
keyAbilities: ['INT'],
skillCount: 2,
difficulty: 'Tricky',
},
SORCERER: {
blurb: 'Born with magic in the blood.',
playsLike: 'Stay back and cast spells through sheer force of personality. Powerful but fragile.',
keyAbilities: ['CHA'],
skillCount: 2,
difficulty: 'Tricky',
},
CLERIC: {
blurb: 'A priest who channels the power of a god.',
playsLike: 'Heal and protect the party, and hold your own in a fight. Every group is glad to have one.',
keyAbilities: ['WIS'],
skillCount: 2,
difficulty: 'Medium',
},
PALADIN: {
blurb: 'A holy knight sworn to an oath.',
playsLike: 'A front-line fighter with a little divine magic to back up the sword.',
keyAbilities: ['STR', 'CHA'],
skillCount: 2,
difficulty: 'Medium',
},
BARD: {
blurb: 'A performer whose words and music carry magic.',
playsLike: 'The party’s talker and helper: spells, skills, and a way out of trouble.',
keyAbilities: ['CHA'],
skillCount: 3,
difficulty: 'Medium',
},
WARLOCK: {
blurb: 'Made a pact with a powerful being in exchange for magic.',
playsLike: 'A spellcaster with a few strong tricks used often, rather than many used rarely.',
keyAbilities: ['CHA'],
skillCount: 2,
difficulty: 'Medium',
},
DRUID: {
blurb: 'A guardian of nature who draws magic from the wild.',
playsLike: 'A flexible spellcaster: healing, nature magic and control of the battlefield.',
keyAbilities: ['WIS'],
skillCount: 2,
difficulty: 'Tricky',
},
MONK: {
blurb: 'A martial artist who has trained body and mind.',
playsLike: 'Fast and precise: dart around the fight striking quickly, with little need for gear.',
keyAbilities: ['DEX', 'WIS'],
skillCount: 2,
difficulty: 'Medium',
},
};
export function hitDieToughness(hitDie: number): Toughness {
if (hitDie <= 6) return 'Fragile';
if (hitDie <= 8) return 'Average';
if (hitDie <= 10) return 'Sturdy';
return 'Very tough';
}
// What each ability changes on the sheet this app builds.
export const ABILITY_GUIDE: Record<Ability, { short: string; affects: string }> = {
STR: {
short: 'Physical power',
affects: 'Strength — hitting and damage with heavy melee weapons, the Athletics skill (climbing, jumping, grappling), and Strength saves.',
},
DEX: {
short: 'Agility and reflexes',
affects:
'Dexterity — your Armor Class (how hard you are to hit), your Initiative (how early you act), attacks with bows and light blades, and Acrobatics, Sleight of Hand and Stealth.',
},
CON: {
short: 'Health and stamina',
affects: 'Constitution — your hit points, at level 1 and again every level after. Also Constitution saves. Useful for everyone.',
},
INT: {
short: 'Memory and reasoning',
affects: 'Intelligence — the Arcana, History, Investigation, Nature and Religion skills, and a Wizard’s spells.',
},
WIS: {
short: 'Awareness and intuition',
affects:
'Wisdom — noticing things (Perception and Passive Perception), plus Insight, Medicine, Survival and Animal Handling, and the spells of Clerics, Druids and Rangers.',
},
CHA: {
short: 'Force of personality',
affects: 'Charisma — Persuasion, Deception, Intimidation and Performance, and the spells of Bards, Paladins, Sorcerers and Warlocks.',
},
};
export const SKILL_GUIDE: Record<string, { ability: Ability; what: string }> = {
ACROBATICS: { ability: 'DEX', what: 'Staying on your feet: balancing, tumbling, flips.' },
ANIMAL_HANDLING: { ability: 'WIS', what: 'Calming, controlling or reading the mood of an animal.' },
ARCANA: { ability: 'INT', what: 'Knowing about magic, spells and magical creatures.' },
ATHLETICS: { ability: 'STR', what: 'Climbing, jumping, swimming and wrestling.' },
DECEPTION: { ability: 'CHA', what: 'Lying convincingly and hiding the truth.' },
HISTORY: { ability: 'INT', what: 'Recalling past events, kingdoms, wars and legends.' },
INSIGHT: { ability: 'WIS', what: 'Reading people: spotting lies and sensing intentions.' },
INTIMIDATION: { ability: 'CHA', what: 'Getting your way through threats and menace.' },
INVESTIGATION: { ability: 'INT', what: 'Searching for clues and working out what they mean.' },
MEDICINE: { ability: 'WIS', what: 'Steadying the dying and diagnosing illness.' },
NATURE: { ability: 'INT', what: 'Knowing about plants, animals, weather and terrain.' },
PERCEPTION: { ability: 'WIS', what: 'Noticing things: hidden enemies, traps, faint sounds. Rolled more than any other skill.' },
PERFORMANCE: { ability: 'CHA', what: 'Entertaining a crowd with music, acting or storytelling.' },
PERSUASION: { ability: 'CHA', what: 'Winning people over with honest charm and good arguments.' },
RELIGION: { ability: 'INT', what: 'Knowing about gods, rites, holy symbols and cults.' },
SLEIGHT_OF_HAND: { ability: 'DEX', what: 'Picking pockets, palming objects, planting things unseen.' },
STEALTH: { ability: 'DEX', what: 'Moving quietly and staying hidden.' },
SURVIVAL: { ability: 'WIS', what: 'Tracking, finding food and shelter, not getting lost.' },
};
// One line under each step heading: what this step is and why it matters.
export const STEP_GUIDE = {
SPECIES: 'Your species is who your character was born as. It nudges a few ability scores up and sets how fast you move.',
CLASS: 'Your class is what your character does — warrior, spellcaster, sneak. It sets your hit points, which saves you are good at, your skills, and whether you cast spells.',
MOTIVATION: 'Why is your character out adventuring? This is pure story — it changes no numbers, but it gives you something to play.',
SCORES:
'Six numbers that describe your character. Higher is better: 10 is average, and every 2 points above 10 adds +1 to related rolls. You roll six scores, then decide which ability gets which.',
SKILLS: 'Skills are things your character is trained in. When you roll for one of these, you add your proficiency bonus on top.',
ABILITIES:
'Special abilities are the tricks that make your character more than numbers. Your species and class each grant some automatically, and you pick a couple of talents of your own. Your DM applies them at the table.',
BACKGROUND: 'Who was your character before the adventure began? Pick one answer to each question. It changes no numbers — it tells you and your DM who you are playing.',
APPEARANCE: 'What do people see when your character walks in? Pick from each list to build the description.',
EQUIPMENT: 'What you set out with. Your DM decides what is on offer here, and can hand out more as you play.',
} as const;
export const STEP_NAMES = ['Species', 'Class', 'Motivation', 'Scores', 'Skills', 'Abilities', 'Background', 'Appearance', 'Equipment'] as const;
+67
View File
@@ -62,3 +62,70 @@ export interface PreviewAbilities {
}
export const ABILITY_ORDER: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
// --------------------------------------------------------------------------
// Gear levels — mirrors scaledDamageDice in backend/src/game/calculations.js.
// Used only to label the DM's level pickers ("Lv 3 · 1d10"); the dice actually
// shown for held gear always come from the server.
// --------------------------------------------------------------------------
export const MAX_GEAR_LEVEL = 9;
export const DAMAGE_SCALING_LABELS: Record<number, string> = { 1: 'Standard', 2: 'Powerful', 3: 'Legendary' };
const DIE_SIZES = [4, 6, 8, 10, 12];
function formatDice(sizes: number[]): string {
const counts = new Map<number, number>();
for (const size of sizes) counts.set(size, (counts.get(size) || 0) + 1);
return [...counts].map(([size, count]) => `${count}d${size}`).join('+');
}
function buildDamageLadder(rungs: number): { dice: string; average: number }[] {
const ladder: { dice: string; average: number }[] = [];
let k = 1;
let steps = 0;
while (ladder.length < rungs) {
if (steps > k * (DIE_SIZES.length - 1)) {
const previousAverage = ladder[ladder.length - 1].average;
k += 1;
steps = Math.floor(previousAverage - k * 2.5) + 1;
continue;
}
const sizes: number[] = [];
for (let i = 0; i < k; i++) sizes.push(DIE_SIZES[Math.floor(steps / k) + (i >= k - (steps % k) ? 1 : 0)]);
ladder.push({ dice: formatDice(sizes), average: k * 2.5 + steps });
steps += 1;
}
return ladder;
}
const DAMAGE_LADDER = buildDamageLadder(120);
function diceAverage(expression: string | null): number | null {
if (!expression || !expression.trim()) return null;
let total = 0;
for (const term of expression.replace(/\s+/g, '').toLowerCase().replace(/-/g, '+-').split('+')) {
if (!term) continue;
const die = /^(-?)(\d*)d(\d+)$/.exec(term);
if (die) total += (die[1] ? -1 : 1) * (Number(die[2]) || 1) * ((Number(die[3]) + 1) / 2);
else if (/^-?\d+$/.test(term)) total += Number(term);
else return null;
}
return total;
}
function clampGearLevel(level: number): number {
return Math.min(Math.max(Math.round(level || 1), 1), MAX_GEAR_LEVEL);
}
// `minLevel` is the level the gear starts at; baseDice is its damage there.
export function scaledDamageDice(baseDice: string, level = 1, scaling = 1, minLevel = 1): string {
const levelsGained = clampGearLevel(level) - clampGearLevel(minLevel);
if (levelsGained <= 0) return baseDice;
const baseAverage = diceAverage(baseDice);
if (baseAverage === null) return baseDice;
let baseRung = -1;
while (baseRung + 1 < DAMAGE_LADDER.length && DAMAGE_LADDER[baseRung + 1].average <= baseAverage) baseRung += 1;
const rungsPerLevel = Math.min(Math.max(Math.round(scaling || 1), 1), 3);
return DAMAGE_LADDER[Math.min(baseRung + levelsGained * rungsPerLevel, DAMAGE_LADDER.length - 1)].dice;
}
+413 -20
View File
@@ -14,6 +14,12 @@ import {
useCreateWeapon,
useCampaignSpells,
useCreateSpell,
useCampaignItems,
useCreateItem,
usePatchPoolEntry,
useDeletePoolEntry,
useCampaignNpcs,
useCreateNpc,
useCampaignNotes,
useCreateNote,
useUpdateCampaign,
@@ -30,9 +36,10 @@ import { useAuth } from '../auth/AuthContext';
import { useCampaignSocket } from '../hooks/useCampaignSocket';
import { Spinner, ErrorBanner } from '../components/Spinner';
import { usePagination, Pagination } from '../components/Paginated';
import { extractErrorMessage } from '../lib/format';
import { SPELL_DAMAGE_GROUPS, SPELL_DAMAGE_SPECIALS, extractErrorMessage, spellLevelLabel, spellRequirementLabel } from '../lib/format';
import { speciesIcon } from '../lib/speciesIcons';
import type { CharacterSummary, LibraryMonster, LibrarySpell, LibraryWeapon } from '../api/types';
import { DAMAGE_SCALING_LABELS, MAX_GEAR_LEVEL } from '../lib/previewCalc';
import type { CharacterSummary, EncounterMode, LibraryMonster, LibrarySpell, LibraryWeapon, NpcDisposition } from '../api/types';
function CharacterRow({ character, isDM, onDelete }: { character: CharacterSummary; isDM: boolean; onDelete: () => void }) {
const inProgress = character.buildStage !== 'COMPLETE';
@@ -71,17 +78,137 @@ function CharacterRow({ character, isDM, onDelete }: { character: CharacterSumma
);
}
// The two trailing cells every pool table row shares: the "offered at
// character creation" toggle and the remove button.
function PoolRowControls({
entry,
onToggleStarting,
onDelete,
}: {
entry: { name: string; isStartingOption: boolean };
onToggleStarting: (isStartingOption: boolean) => void;
onDelete: () => void;
}) {
return (
<>
<td>
<input
type="checkbox"
aria-label={`${entry.name} is a starting option`}
checked={entry.isStartingOption}
onChange={(e) => onToggleStarting(e.target.checked)}
/>
</td>
<td>
<button
className="btn btn-ghost"
aria-label={`Remove ${entry.name}`}
onClick={() => window.confirm(`Remove ${entry.name}? Any character holding it loses it.`) && onDelete()}
>
✕
</button>
</td>
</>
);
}
// How fast a weapon's or item's dice grow as the DM levels a held copy up.
function ScalingSelect({ name, value, onChange }: { name?: string; value?: number; onChange?: (scaling: number) => void }) {
return (
<select
name={name}
aria-label="How fast the dice grow per level"
title="How fast the dice grow each time a held copy is levelled up"
{...(onChange ? { value, onChange: (e) => onChange(Number(e.target.value)) } : { defaultValue: 1 })}
>
{Object.entries(DAMAGE_SCALING_LABELS).map(([scaling, label]) => (
<option key={scaling} value={scaling}>
{label}
</option>
))}
</select>
);
}
const GEAR_LEVELS = Array.from({ length: MAX_GEAR_LEVEL }, (_, i) => i + 1);
// The level a weapon or item starts at. A held copy is never below it, and a
// character must be at least this level to use it.
function StartLevelSelect({ name, value, onChange }: { name?: string; value?: number; onChange?: (minLevel: number) => void }) {
return (
<select
name={name}
aria-label="Level it starts at"
title="The level this starts at — a character must be at least this level to use it"
{...(onChange ? { value, onChange: (e) => onChange(Number(e.target.value)) } : { defaultValue: 1 })}
>
{GEAR_LEVELS.map((level) => (
<option key={level} value={level}>
Starts at Lv {level}
</option>
))}
</select>
);
}
const MODE_LABELS: Record<EncounterMode, string> = { BATTLE: '⚔ Battle', QUEST: '📜 Quest' };
// A spell's damage is picked from a list rather than typed. A value that is
// not in the list (set through the API, say) is still shown and kept.
function SpellDamageSelect({
name,
spellName,
value,
onChange,
}: {
name?: string;
spellName?: string;
value?: string | null;
onChange?: (damageDice: string | null) => void;
}) {
const known = [...SPELL_DAMAGE_GROUPS.flatMap((g) => g.options), ...SPELL_DAMAGE_SPECIALS];
const others = value && !known.includes(value) ? [...SPELL_DAMAGE_SPECIALS, value] : SPELL_DAMAGE_SPECIALS;
return (
<select
name={name}
aria-label={spellName ? `${spellName} damage` : 'Damage'}
{...(onChange ? { value: value ?? '', onChange: (e) => onChange(e.target.value || null) } : { defaultValue: '' })}
>
<option value="">No damage</option>
{SPELL_DAMAGE_GROUPS.map((group) => (
<optgroup key={group.label} label={group.label}>
{group.options.map((dice) => (
<option key={dice} value={dice}>
{dice}
</option>
))}
</optgroup>
))}
<optgroup label="Other">
{others.map((dice) => (
<option key={dice} value={dice}>
{dice}
</option>
))}
</optgroup>
</select>
);
}
function LibraryPicker<T extends { key: string; name: string }>({
items,
onAdd,
adding,
renderMeta,
renderDetail,
placeholder,
}: {
items: T[];
onAdd: (key: string) => void;
adding: boolean;
renderMeta: (item: T) => string;
// A sentence on what the entry is or does, shown under its name.
renderDetail?: (item: T) => string | null;
placeholder: string;
}) {
const [query, setQuery] = useState('');
@@ -97,6 +224,7 @@ function LibraryPicker<T extends { key: string; name: string }>({
<div>
<strong>{item.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6, fontSize: '0.85rem' }}>{renderMeta(item)}</span>
{renderDetail?.(item) && <div style={{ fontSize: '0.9rem' }}>{renderDetail(item)}</div>}
</div>
<button className="btn btn-ghost" disabled={adding} onClick={() => onAdd(item.key)}>
+ Add
@@ -119,9 +247,11 @@ export function CampaignHomePage() {
const { data, isLoading, error } = useCampaign(campaignId);
const { data: characters } = useCampaignCharacters(campaignId);
const { data: encounters } = useCampaignEncounters(campaignId);
const { data: monsters } = useCampaignMonsters(campaignId);
const { data: monsters } = useCampaignMonsters(campaignId, data?.campaign.role === 'DM');
const { data: weapons } = useCampaignWeapons(campaignId);
const { data: spells } = useCampaignSpells(campaignId);
const { data: items } = useCampaignItems(campaignId);
const { data: npcs } = useCampaignNpcs(campaignId, data?.campaign.role === 'DM');
const { data: notes } = useCampaignNotes(campaignId);
const { data: locations } = useCampaignLocations(campaignId);
const { data: library } = useCampaignLibrary(campaignId);
@@ -133,6 +263,15 @@ export function CampaignHomePage() {
const deleteMonster = useDeleteMonster(campaignId);
const createWeapon = useCreateWeapon(campaignId);
const createSpell = useCreateSpell(campaignId);
const createItem = useCreateItem(campaignId);
const createNpc = useCreateNpc(campaignId);
const deleteNpc = useDeletePoolEntry(campaignId, 'npcs');
const patchWeapon = usePatchPoolEntry(campaignId, 'weapons');
const deleteWeapon = useDeletePoolEntry(campaignId, 'weapons');
const patchSpell = usePatchPoolEntry(campaignId, 'spells');
const deleteSpell = useDeletePoolEntry(campaignId, 'spells');
const patchItem = usePatchPoolEntry(campaignId, 'items');
const deleteItem = useDeletePoolEntry(campaignId, 'items');
const createNote = useCreateNote();
const updateCampaign = useUpdateCampaign(campaignId);
const regenerateInvite = useRegenerateInvite(campaignId);
@@ -144,6 +283,8 @@ export function CampaignHomePage() {
const [newCharName, setNewCharName] = useState('');
const [newEncounterName, setNewEncounterName] = useState('');
const [newEncounterMode, setNewEncounterMode] = useState<EncounterMode>('BATTLE');
const [showNpcForm, setShowNpcForm] = useState(false);
const [noteBody, setNoteBody] = useState('');
const [dmNoteBody, setDmNoteBody] = useState('');
const [newLocationName, setNewLocationName] = useState('');
@@ -152,12 +293,15 @@ export function CampaignHomePage() {
const [showMonsterForm, setShowMonsterForm] = useState(false);
const [showWeaponForm, setShowWeaponForm] = useState(false);
const [showSpellForm, setShowSpellForm] = useState(false);
const [showItemForm, setShowItemForm] = useState(false);
const [showWeaponLibrary, setShowWeaponLibrary] = useState(false);
const [showSpellLibrary, setShowSpellLibrary] = useState(false);
const [showMonsterLibrary, setShowMonsterLibrary] = useState(false);
const weaponsPage = usePagination(weapons, 8);
const spellsPage = usePagination(spells, 8);
const itemsPage = usePagination(items, 8);
const npcsPage = usePagination(npcs, 8);
const monstersPage = usePagination(monsters, 8);
const sharedNotes = notes?.filter((n) => n.visibility === 'SHARED');
const dmNotes = notes?.filter((n) => n.visibility === 'DM_ONLY');
@@ -187,7 +331,10 @@ export function CampaignHomePage() {
async function handleCreateEncounter(e: FormEvent) {
e.preventDefault();
try {
const encounter = await createEncounter.mutateAsync(newEncounterName || 'New Encounter');
const encounter = await createEncounter.mutateAsync({
name: newEncounterName || (newEncounterMode === 'QUEST' ? 'New Quest' : 'New Encounter'),
mode: newEncounterMode,
});
navigate(`/encounters/${encounter.id}`);
} catch (err) {
setFormError(extractErrorMessage(err));
@@ -265,7 +412,7 @@ export function CampaignHomePage() {
<input name="startingGold" type="number" min={0} defaultValue={campaign.startingGold} />
</div>
<div className="field">
<label>Starting items</label>
<label>Starting items (weapons + items)</label>
<input name="startingItemCount" type="number" min={0} defaultValue={campaign.startingItemCount} />
</div>
<div className="field">
@@ -275,7 +422,7 @@ export function CampaignHomePage() {
</div>
<label className="checkbox-row">
<input type="checkbox" name="skipMotivationRoll" defaultChecked={campaign.skipMotivationRoll} />
Skip the motivation roll for this campaign
Skip the motivation step when building a character
</label>
<button type="submit" className="btn btn-primary mt-md" disabled={updateCampaign.isPending}>
Save Settings
@@ -346,20 +493,113 @@ export function CampaignHomePage() {
onChange={(e) => setNewEncounterName(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<select aria-label="Encounter type" value={newEncounterMode} onChange={(e) => setNewEncounterMode(e.target.value as EncounterMode)}>
<option value="BATTLE">Battle</option>
<option value="QUEST">NPC quest</option>
</select>
<button type="submit" className="btn btn-primary" disabled={createEncounter.isPending}>
⚔ Start Encounter
{newEncounterMode === 'QUEST' ? '📜 Start Quest' : '⚔ Start Encounter'}
</button>
</form>
)}
{encounters?.length === 0 && <div className="empty-state">No encounters yet.</div>}
{encounters?.map((enc) => (
<Link key={enc.id} to={`/encounters/${enc.id}`} className="card flex-between" style={{ display: 'flex' }}>
<span>{enc.name}</span>
<span className="badge">{enc.status} · Round {enc.currentRound}</span>
<span>
<span className="badge" style={{ marginRight: 8 }}>{MODE_LABELS[enc.mode]}</span>
{enc.name}
</span>
<span className="badge">
{enc.status}
{enc.mode === 'BATTLE' && ` · Round ${enc.currentRound}`}
</span>
</Link>
))}
</div>
{isDM && (
<div className="mt-lg card">
<div className="card-title">
<span>NPCs</span>
<button className="btn btn-ghost" onClick={() => setShowNpcForm((s) => !s)}>
{showNpcForm ? 'Close' : '+ Add NPC'}
</button>
</div>
<p className="subtitle" style={{ marginTop: 0 }}>
The people your party meets. Add them to an encounter to bring them into a scene. Players never see your notes or an
NPC's stats.
</p>
{showNpcForm && (
<form
onSubmit={async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const fd = new FormData(form);
const text = (key: string) => String(fd.get(key) || '').trim() || null;
const num = (key: string) => (fd.get(key) ? Number(fd.get(key)) : null);
try {
await createNpc.mutateAsync({
name: String(fd.get('name')),
role: text('role'),
disposition: fd.get('disposition') as NpcDisposition,
description: text('description'),
dmNotes: text('dmNotes'),
ac: num('ac'),
maxHp: num('maxHp'),
attackBonus: num('attackBonus'),
damageDice: text('damageDice'),
});
form.reset();
} catch (err) {
setFormError(extractErrorMessage(err));
}
}}
>
<div className="grid grid-cols-3">
<input name="name" placeholder="Name" required maxLength={80} />
<input name="role" placeholder="Role (innkeeper, captain…)" maxLength={80} />
<select name="disposition" defaultValue="NEUTRAL" aria-label="Attitude toward the party">
<option value="FRIENDLY">Friendly</option>
<option value="NEUTRAL">Neutral</option>
<option value="HOSTILE">Hostile</option>
</select>
</div>
<textarea name="description" rows={2} className="textarea-block mt-sm" placeholder="What the party sees and knows (shown to players)" />
<textarea name="dmNotes" rows={2} className="textarea-block mt-sm" placeholder="Secrets and motives (only you see this)" />
<div className="grid grid-cols-3 mt-sm">
<input name="ac" type="number" min={0} placeholder="AC (optional)" />
<input name="maxHp" type="number" min={1} placeholder="HP (optional)" />
<input name="attackBonus" type="number" placeholder="Attack bonus (optional)" />
<input name="damageDice" placeholder="Damage (optional, e.g. 1d6)" maxLength={20} />
<button type="submit" className="btn btn-primary" disabled={createNpc.isPending}>Add NPC</button>
</div>
</form>
)}
<div className="mt-sm">
{npcs?.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No NPCs yet.</p>}
{npcsPage.pageItems.map((npc) => (
<div key={npc.id} className="flex-between" style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<div>
<strong>{npc.name}</strong>
{npc.role && <span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>{npc.role}</span>}
<span className={`badge badge-${npc.disposition.toLowerCase()}`} style={{ marginLeft: 8 }}>{npc.disposition}</span>
{npc.description && <div style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>{npc.description}</div>}
{npc.dmNotes && <div style={{ color: 'var(--text-dim)', fontSize: '0.85rem' }}>🔒 {npc.dmNotes}</div>}
</div>
<button
className="btn btn-ghost"
aria-label={`Remove ${npc.name}`}
onClick={() => window.confirm(`Remove ${npc.name}?`) && deleteNpc.mutate(npc.id)}
>
✕
</button>
</div>
))}
</div>
<Pagination page={npcsPage.page} pageCount={npcsPage.pageCount} onPrev={npcsPage.prevPage} onNext={npcsPage.nextPage} />
</div>
)}
{isDM && (
<div className="mt-lg card">
<div className="card-title">
@@ -389,7 +629,20 @@ export function CampaignHomePage() {
{isDM && (
<>
<div className="mt-lg card">
<div className="mt-lg">
<h2 style={{ fontSize: '1.1rem', margin: 0 }}>Gear Pools</h2>
<p className="subtitle">
You hand out weapons, items and spells from these pools on each character's sheet. Tick "Starting" for the ones a
player may pick while building a new character.
</p>
<p className="subtitle">
Weapons and items have levels 1–{MAX_GEAR_LEVEL}. The damage you enter is the damage at the level it starts at
(level 1 unless you pick a higher one). When you level up a character's copy, its dice grow one small step per
level (1d4 → 1d6 → 1d8 → 1d10 → 1d12 → 2d6 → …) — two steps for Powerful gear, three for Legendary. A character
must be at least a weapon's or item's level to use it, and at least a spell's level to cast it.
</p>
</div>
<div className="mt-sm card">
<div className="card-title">
<span>Weapons Pool</span>
<div className="flex-row gap-sm">
@@ -407,7 +660,7 @@ export function CampaignHomePage() {
adding={addWeaponFromLibrary.isPending}
onAdd={(key) => addWeaponFromLibrary.mutate(key)}
placeholder="Search the weapon library…"
renderMeta={(w) => `${w.category} · ${w.damageDice} ${w.damageType}`}
renderMeta={(w) => `${w.category} · ${w.damageDice} ${w.damageType} · starts at level 1`}
/>
)}
{showWeaponForm && (
@@ -423,19 +676,28 @@ export function CampaignHomePage() {
properties: [],
rangeNormal: null,
rangeLong: null,
damageScaling: Number(fd.get('damageScaling')),
minLevel: Number(fd.get('minLevel')),
isStartingOption: fd.get('isStartingOption') === 'on',
});
(e.target as HTMLFormElement).reset();
}}
className="grid grid-cols-3"
>
<input name="name" placeholder="Name" required />
<input name="damageDice" placeholder="Damage dice (1d8)" required />
<input name="damageDice" placeholder="Damage at its starting level (1d8)" required />
<input name="damageType" placeholder="Damage type" required />
<select name="attackAbility" defaultValue="STR">
<option value="STR">STR</option>
<option value="DEX">DEX</option>
<option value="FINESSE">Finesse</option>
</select>
<ScalingSelect name="damageScaling" />
<StartLevelSelect name="minLevel" />
<label className="checkbox-row">
<input type="checkbox" name="isStartingOption" />
Starting option
</label>
<button type="submit" className="btn btn-primary">Add</button>
</form>
)}
@@ -444,7 +706,11 @@ export function CampaignHomePage() {
<thead>
<tr>
<th>Name</th>
<th>Damage</th>
<th>Base damage</th>
<th>Level</th>
<th>Growth</th>
<th>Starting</th>
<th />
</tr>
</thead>
<tbody>
@@ -452,6 +718,17 @@ export function CampaignHomePage() {
<tr key={w.id}>
<td>{w.name}</td>
<td>{w.damageDice} {w.damageType}</td>
<td>
<StartLevelSelect value={w.minLevel} onChange={(minLevel) => patchWeapon.mutate({ id: w.id, minLevel })} />
</td>
<td>
<ScalingSelect value={w.damageScaling} onChange={(damageScaling) => patchWeapon.mutate({ id: w.id, damageScaling })} />
</td>
<PoolRowControls
entry={w}
onToggleStarting={(isStartingOption) => patchWeapon.mutate({ id: w.id, isStartingOption })}
onDelete={() => deleteWeapon.mutate(w.id)}
/>
</tr>
))}
</tbody>
@@ -460,6 +737,88 @@ export function CampaignHomePage() {
<Pagination page={weaponsPage.page} pageCount={weaponsPage.pageCount} onPrev={weaponsPage.prevPage} onNext={weaponsPage.nextPage} />
</div>
<div className="mt-md card">
<div className="card-title">
<span>Items Pool</span>
<button className="btn btn-ghost" onClick={() => setShowItemForm((s) => !s)}>
{showItemForm ? 'Close' : '+ Add Item'}
</button>
</div>
{showItemForm && (
<form
onSubmit={async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const fd = new FormData(form);
await createItem.mutateAsync({
name: String(fd.get('name')),
description: String(fd.get('description') || '') || null,
damageDice: String(fd.get('damageDice') || '').trim() || null,
damageScaling: Number(fd.get('damageScaling')),
minLevel: Number(fd.get('minLevel')),
isStartingOption: fd.get('isStartingOption') === 'on',
});
form.reset();
}}
className="grid grid-cols-3"
>
<input name="name" placeholder="Name" required />
<input name="description" placeholder="Description (optional)" />
<input name="damageDice" placeholder="Dice (optional, e.g. 2d4+2)" maxLength={20} />
<ScalingSelect name="damageScaling" />
<StartLevelSelect name="minLevel" />
<label className="checkbox-row">
<input type="checkbox" name="isStartingOption" />
Starting option
</label>
<button type="submit" className="btn btn-primary">Add</button>
</form>
)}
{items?.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No items yet. Add rope, potions, quest items…</p>}
{items && items.length > 0 && (
<div className="table-wrap mt-sm">
<table className="data-table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Base dice</th>
<th>Level</th>
<th>Growth</th>
<th>Starting</th>
<th />
</tr>
</thead>
<tbody>
{itemsPage.pageItems.map((item) => (
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.description}</td>
<td>{item.damageDice || '—'}</td>
<td>
<StartLevelSelect value={item.minLevel} onChange={(minLevel) => patchItem.mutate({ id: item.id, minLevel })} />
</td>
<td>
{item.damageDice ? (
<ScalingSelect value={item.damageScaling} onChange={(damageScaling) => patchItem.mutate({ id: item.id, damageScaling })} />
) : (
'—'
)}
</td>
<PoolRowControls
entry={item}
onToggleStarting={(isStartingOption) => patchItem.mutate({ id: item.id, isStartingOption })}
onDelete={() => deleteItem.mutate(item.id)}
/>
</tr>
))}
</tbody>
</table>
</div>
)}
<Pagination page={itemsPage.page} pageCount={itemsPage.pageCount} onPrev={itemsPage.prevPage} onNext={itemsPage.nextPage} />
</div>
<div className="mt-md card">
<div className="card-title">
<span>Spell List</span>
@@ -478,7 +837,12 @@ export function CampaignHomePage() {
adding={addSpellFromLibrary.isPending}
onAdd={(key) => addSpellFromLibrary.mutate(key)}
placeholder="Search the spell library…"
renderMeta={(s) => `${s.level === 0 ? 'Cantrip' : `Lv ${s.level}`} · ${s.school || ''}`}
renderMeta={(s) =>
[spellLevelLabel(s.level), spellRequirementLabel(s.level), s.damageDice ? `${s.damageDice} damage` : 'no damage', s.school]
.filter(Boolean)
.join(' · ')
}
renderDetail={(s) => s.description}
/>
)}
{showSpellForm && (
@@ -493,15 +857,29 @@ export function CampaignHomePage() {
castingTime: null,
range: null,
duration: null,
description: null,
description: String(fd.get('description') || '').trim() || null,
damageDice: String(fd.get('damageDice') || '') || null,
isStartingOption: fd.get('isStartingOption') === 'on',
});
(e.target as HTMLFormElement).reset();
}}
className="grid grid-cols-3"
>
<input name="name" placeholder="Name" required />
<input name="level" type="number" min={0} max={9} placeholder="Level (0=cantrip)" required />
<select name="level" defaultValue={0} aria-label="Spell level">
{[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((level) => (
<option key={level} value={level}>
{spellLevelLabel(level)}
</option>
))}
</select>
<input name="school" placeholder="School" />
<SpellDamageSelect name="damageDice" />
<input name="description" placeholder="What it does (one sentence)" maxLength={4000} required style={{ gridColumn: '1 / -1' }} />
<label className="checkbox-row">
<input type="checkbox" name="isStartingOption" />
Starting option
</label>
<button type="submit" className="btn btn-primary">Add</button>
</form>
)}
@@ -509,15 +887,29 @@ export function CampaignHomePage() {
<table className="data-table">
<thead>
<tr>
<th>Name</th>
<th>Spell</th>
<th>Level</th>
<th>Damage</th>
<th>Starting</th>
<th />
</tr>
</thead>
<tbody>
{spellsPage.pageItems.map((s) => (
<tr key={s.id}>
<td>{s.name}</td>
<td>{s.level === 0 ? 'Cantrip' : s.level}</td>
<td>
<strong>{s.name}</strong>
<div style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>{s.description || 'No description.'}</div>
</td>
<td style={{ whiteSpace: 'nowrap' }}>{spellLevelLabel(s.level)}</td>
<td>
<SpellDamageSelect spellName={s.name} value={s.damageDice} onChange={(damageDice) => patchSpell.mutate({ id: s.id, damageDice })} />
</td>
<PoolRowControls
entry={s}
onToggleStarting={(isStartingOption) => patchSpell.mutate({ id: s.id, isStartingOption })}
onDelete={() => deleteSpell.mutate(s.id)}
/>
</tr>
))}
</tbody>
@@ -544,7 +936,8 @@ export function CampaignHomePage() {
adding={addMonsterFromLibrary.isPending}
onAdd={(key) => addMonsterFromLibrary.mutate(key)}
placeholder="Search the monster library…"
renderMeta={(m) => `CR ${m.challengeRating} · AC ${m.ac} · HP ${m.maxHp}`}
renderMeta={(m) => `CR ${m.challengeRating} · AC ${m.ac} · HP ${m.maxHp} · attack +${m.attackBonus}${m.damageDice ? ` for ${m.damageDice}` : ''}`}
renderDetail={(m) => [m.specialTrait, m.notes].filter(Boolean).join(' — ') || null}
/>
)}
{showMonsterForm && (
File diff suppressed because it is too large Load Diff
+452 -89
View File
@@ -1,20 +1,30 @@
import { useState, type FormEvent } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Link, useNavigate, useParams } from 'react-router-dom';
import {
useCharacter,
usePatchCharacter,
useCampaignWeapons,
useAssignWeapon,
usePatchCharacterWeapon,
useAddInventoryItem,
useRemoveCharacterWeapon,
useCampaignItems,
useAssignItem,
usePatchInventoryItem,
useDeleteInventoryItem,
useRemoveInventoryItem,
useCampaignSpells,
useAssignSpell,
usePatchCharacterSpell,
useRemoveCharacterSpell,
useGoldLedger,
useAdjustGold,
useCampaignCharacters,
useGive,
type Gift,
useCharacterNotes,
useCreateNote,
useCampaign,
useCampaigns,
useCopyCharacter,
useCampaignLocations,
} from '../api/queries';
import { useAuth } from '../auth/AuthContext';
@@ -23,11 +33,173 @@ import { Spinner, ErrorBanner } from '../components/Spinner';
import { QuickStatsFab } from '../components/QuickStatsDrawer';
import { InfoTip } from '../components/InfoTip';
import { usePagination, Pagination } from '../components/Paginated';
import { ABILITY_LABELS, CLASS_LABELS, SKILL_LABELS, SPECIES_LABELS, fmtMod, hpBarClass, extractErrorMessage } from '../lib/format';
import { ABILITY_LABELS, CLASS_LABELS, SKILL_LABELS, SPECIES_LABELS, fmtMod, hpBarClass, extractErrorMessage, spellLevelLabel } from '../lib/format';
import { speciesIcon } from '../lib/speciesIcons';
import { hpMax as previewHpMax } from '../lib/previewCalc';
import { hpMax as previewHpMax, scaledDamageDice, MAX_GEAR_LEVEL } from '../lib/previewCalc';
import { CLASS_HIT_DIE } from '../lib/classData';
import type { Ability } from '../api/types';
import type { Ability, CharacterDetail } from '../api/types';
// The DM's level picker for one held weapon or item, from the level the gear
// starts at up to the maximum. Each option shows what the dice become at that
// level, so the step up is visible before choosing.
function GearLevelSelect({
name,
level,
entry,
onChange,
}: {
name: string;
level: number;
entry: { damageDice: string | null; damageScaling: number; minLevel: number };
onChange: (level: number) => void;
}) {
const levels = Array.from({ length: MAX_GEAR_LEVEL - entry.minLevel + 1 }, (_, i) => entry.minLevel + i);
return (
<select aria-label={`${name} level`} value={level} onChange={(e) => onChange(Number(e.target.value))}>
{levels.map((l) => (
<option key={l} value={l}>
Lv {l}
{entry.damageDice ? ` · ${scaledDamageDice(entry.damageDice, l, entry.damageScaling, entry.minLevel)}` : ''}
</option>
))}
</select>
);
}
function RequiresLevel({ level }: { level: number }) {
return (
<span className="badge" style={{ marginLeft: 6 }} title="Held, but can't be used until the character reaches this level">
Requires level {level}
</span>
);
}
// Lets the owner (or DM) hand something this character holds to another
// character in the campaign. Giving moves it: the giver no longer has it.
function GiveCard({ character, onError }: { character: CharacterDetail; onError: (err: unknown) => void }) {
const { data: characters } = useCampaignCharacters(character.campaignId);
const give = useGive(character.id);
const [what, setWhat] = useState('');
const [amount, setAmount] = useState('1');
const [toCharacterId, setToCharacterId] = useState('');
const [done, setDone] = useState<string | null>(null);
const others = characters?.filter((c) => c.id !== character.id && c.buildStage === 'COMPLETE') ?? [];
if (others.length === 0) return null;
// "kind:id" identifies the thing picked; gold has no id.
const [kind, id] = what.split(':');
const heldWeapon = character.weapons.find((w) => w.weaponId === id);
const heldItem = character.inventoryItems.find((i) => i.itemId === id);
const max = kind === 'gold' ? character.gold : kind === 'weapon' ? (heldWeapon?.quantity ?? 0) : kind === 'item' ? (heldItem?.quantity ?? 0) : 1;
const count = Math.floor(Number(amount));
const countOk = kind === 'spell' || (count >= 1 && count <= max);
const nothingToGive = character.gold === 0 && character.weapons.length + character.inventoryItems.length + character.spells.length === 0;
function handleGive() {
const gift: Gift | null =
kind === 'gold'
? { kind, amount: count }
: kind === 'weapon' || kind === 'item'
? { kind, id, quantity: count }
: kind === 'spell'
? { kind, id }
: null;
if (!gift || !toCharacterId) return;
setDone(null);
give.mutate(
{ ...gift, toCharacterId },
{
onError,
onSuccess: () => {
setDone(`Given to ${others.find((c) => c.id === toCharacterId)?.name}.`);
setWhat('');
setAmount('1');
},
}
);
}
return (
<div className="card mt-md">
<div className="card-title">Give to Another Character</div>
<p className="subtitle" style={{ marginTop: 0 }}>
Hand gold, a weapon, an item or a spell to someone else in the party. Giving moves it — {character.name} no longer has
it afterwards.
</p>
{nothingToGive ? (
<p style={{ color: 'var(--text-muted)', margin: 0 }}>{character.name} has nothing to give yet.</p>
) : (
<div className="flex-row flex-wrap">
<select
aria-label="What to give"
value={what}
onChange={(e) => {
setWhat(e.target.value);
setAmount('1');
setDone(null);
}}
style={{ flex: 2, minWidth: 160 }}
>
<option value="">What to give…</option>
{character.gold > 0 && <option value="gold:">Gold ({character.gold} gp)</option>}
{character.weapons.length > 0 && (
<optgroup label="Weapons">
{character.weapons.map((w) => (
<option key={w.weaponId} value={`weapon:${w.weaponId}`}>
{w.weapon.name} (Lv {w.level}, x{w.quantity})
</option>
))}
</optgroup>
)}
{character.inventoryItems.length > 0 && (
<optgroup label="Items">
{character.inventoryItems.map((i) => (
<option key={i.itemId} value={`item:${i.itemId}`}>
{i.item.name} (Lv {i.level}, x{i.quantity})
</option>
))}
</optgroup>
)}
{character.spells.length > 0 && (
<optgroup label="Spells">
{character.spells.map((s) => (
<option key={s.spellId} value={`spell:${s.spellId}`}>
{s.spell.name} ({spellLevelLabel(s.spell.level)})
</option>
))}
</optgroup>
)}
</select>
{what && kind !== 'spell' && (
<input
type="number"
min={1}
max={max}
aria-label={kind === 'gold' ? 'How much gold' : 'How many'}
title={kind === 'gold' ? 'How much gold' : `How many (up to ${max})`}
value={amount}
onChange={(e) => setAmount(e.target.value)}
style={{ width: 90 }}
/>
)}
<select aria-label="Who to give it to" value={toCharacterId} onChange={(e) => setToCharacterId(e.target.value)} style={{ flex: 1, minWidth: 130 }}>
<option value="">To whom…</option>
{others.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<button className="btn" onClick={handleGive} disabled={!what || !toCharacterId || !countOk || give.isPending}>
Give
</button>
</div>
)}
{done && <p className="subtitle">✓ {done}</p>}
</div>
);
}
export function CharacterSheetPage() {
const { characterId = '' } = useParams();
@@ -39,29 +211,41 @@ export function CharacterSheetPage() {
const { data: campaignData } = useCampaign(character?.campaignId);
const { data: campaignWeapons } = useCampaignWeapons(character?.campaignId);
const { data: campaignSpells } = useCampaignSpells(character?.campaignId);
const { data: campaignItems } = useCampaignItems(character?.campaignId);
const { data: goldLedger } = useGoldLedger(characterId);
const { data: locations } = useCampaignLocations(character?.campaignId);
const { data: notes } = useCharacterNotes(characterId);
const assignWeapon = useAssignWeapon(characterId);
const patchWeapon = usePatchCharacterWeapon(characterId);
const addItem = useAddInventoryItem(characterId);
const removeWeapon = useRemoveCharacterWeapon(characterId);
const assignItem = useAssignItem(characterId);
const patchItem = usePatchInventoryItem(characterId);
const deleteItem = useDeleteInventoryItem(characterId);
const removeItem = useRemoveInventoryItem(characterId);
const assignSpell = useAssignSpell(characterId);
const patchSpell = usePatchCharacterSpell(characterId);
const removeSpell = useRemoveCharacterSpell(characterId);
const adjustGold = useAdjustGold(characterId);
const createNote = useCreateNote();
const { data: campaigns } = useCampaigns();
const copyCharacter = useCopyCharacter(characterId);
const navigate = useNavigate();
const [hpDelta, setHpDelta] = useState('');
const [newItemName, setNewItemName] = useState('');
const [pickedItemId, setPickedItemId] = useState('');
const [goldAmount, setGoldAmount] = useState('');
const [goldReason, setGoldReason] = useState('');
const [noteBody, setNoteBody] = useState('');
const [pickedWeaponId, setPickedWeaponId] = useState('');
const [pickedSpellId, setPickedSpellId] = useState('');
const [copyTargetId, setCopyTargetId] = useState('');
const [formError, setFormError] = useState<string | null>(null);
const weaponsPage = usePagination(character?.weapons, 8);
const spellsPage = usePagination(character?.spells, 8);
const itemsPage = usePagination(character?.inventoryItems, 8);
const notesPage = usePagination(notes, 6);
const ledgerPage = usePagination(goldLedger, 6);
if (isLoading) return <Spinner label="Unfurling the character sheet…" />;
if (error || !character) return <ErrorBanner message="Could not load this character." />;
@@ -99,11 +283,27 @@ export function CharacterSheetPage() {
patchCharacter.mutate({ currentHp: newMax });
}
async function handleAddItem(e: FormEvent) {
e.preventDefault();
if (!newItemName.trim()) return;
await addItem.mutateAsync({ name: newItemName });
setNewItemName('');
async function handleAssignItem() {
if (!pickedItemId) return;
try {
await assignItem.mutateAsync({ itemId: pickedItemId });
setPickedItemId('');
} catch (err) {
setFormError(extractErrorMessage(err));
}
}
async function handleGold(sign: 1 | -1) {
const amount = Math.floor(Number(goldAmount));
if (!(amount > 0)) return;
setFormError(null);
try {
await adjustGold.mutateAsync({ amount: sign * amount, reason: goldReason.trim() || undefined });
setGoldAmount('');
setGoldReason('');
} catch (err) {
setFormError(extractErrorMessage(err));
}
}
async function handleAddNote(e: FormEvent) {
@@ -133,6 +333,19 @@ export function CharacterSheetPage() {
}
}
async function handleCopy() {
if (!copyTargetId) return;
try {
const copy = await copyCharacter.mutateAsync(copyTargetId);
setCopyTargetId('');
navigate(`/campaigns/${copy.campaignId}`);
} catch (err) {
setFormError(extractErrorMessage(err));
}
}
const otherCampaigns = campaigns?.filter((c) => c.id !== character.campaignId) ?? [];
const assignedWeaponIds = new Set(character.weapons.map((w) => w.weaponId));
const assignedSpellIds = new Set(character.spells.map((s) => s.spellId));
@@ -349,26 +562,44 @@ export function CharacterSheetPage() {
<div>
<strong>{cw.weapon.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>
{cw.weapon.damageDice} {cw.weapon.damageType} · x{cw.quantity}
Lv {cw.level} · {cw.scaledDamageDice} {cw.weapon.damageType} · x{cw.quantity}
</span>
{!cw.usable && <RequiresLevel level={cw.level} />}
</div>
{canEdit && (
<label className="flex-row gap-sm">
Equipped
<input
type="checkbox"
checked={cw.equipped}
onChange={(e) => patchWeapon.mutate({ weaponId: cw.weaponId, equipped: e.target.checked })}
/>
</label>
<div className="flex-row gap-sm">
<label className="flex-row gap-sm">
Equipped
<input
type="checkbox"
checked={cw.equipped}
disabled={!cw.usable}
onChange={(e) => patchWeapon.mutate({ weaponId: cw.weaponId, equipped: e.target.checked })}
/>
</label>
{isDM && (
<>
<GearLevelSelect
name={cw.weapon.name}
level={cw.level}
entry={cw.weapon}
onChange={(level) => patchWeapon.mutate({ weaponId: cw.weaponId, level })}
/>
<button className="btn btn-ghost" aria-label={`Take away ${cw.weapon.name}`} onClick={() => removeWeapon.mutate(cw.weaponId)}>
✕
</button>
</>
)}
</div>
)}
</div>
))}
{character.weapons.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No weapons. The DM hands these out.</p>}
<Pagination page={weaponsPage.page} pageCount={weaponsPage.pageCount} onPrev={weaponsPage.prevPage} onNext={weaponsPage.nextPage} />
{canEdit && (
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<select value={pickedWeaponId} onChange={(e) => setPickedWeaponId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Add a weapon from the campaign pool…</option>
<option value="">Give a weapon from the campaign pool…</option>
{campaignWeapons
?.filter((w) => !assignedWeaponIds.has(w.id))
.map((w) => (
@@ -378,7 +609,7 @@ export function CharacterSheetPage() {
))}
</select>
<button className="btn" onClick={handleAssignWeapon} disabled={!pickedWeaponId}>
Add
Give
</button>
</div>
)}
@@ -391,35 +622,49 @@ export function CharacterSheetPage() {
<div key={cs.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<div>
<strong>{cs.spell.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>Lv {cs.spell.level}</span>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>
{spellLevelLabel(cs.spell.level)}
{cs.spell.damageDice && ` · ${cs.spell.damageDice} damage`}
</span>
{!cs.usable && <RequiresLevel level={cs.spell.level} />}
{cs.spell.description && <div style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>{cs.spell.description}</div>}
</div>
{canEdit && (
<label className="flex-row gap-sm">
Prepared
<input
type="checkbox"
checked={cs.prepared}
onChange={(e) => patchSpell.mutate({ spellId: cs.spellId, prepared: e.target.checked })}
/>
</label>
<div className="flex-row gap-sm">
<label className="flex-row gap-sm">
Prepared
<input
type="checkbox"
checked={cs.prepared}
disabled={!cs.usable}
onChange={(e) => patchSpell.mutate({ spellId: cs.spellId, prepared: e.target.checked })}
/>
</label>
{isDM && (
<button className="btn btn-ghost" aria-label={`Take away ${cs.spell.name}`} onClick={() => removeSpell.mutate(cs.spellId)}>
✕
</button>
)}
</div>
)}
</div>
))}
{character.spells.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No spells known. The DM grants these.</p>}
<Pagination page={spellsPage.page} pageCount={spellsPage.pageCount} onPrev={spellsPage.prevPage} onNext={spellsPage.nextPage} />
{canEdit && (
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<select value={pickedSpellId} onChange={(e) => setPickedSpellId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Add a spell from the campaign list…</option>
<option value="">Grant a spell from the campaign list…</option>
{campaignSpells
.filter((s) => !assignedSpellIds.has(s.id))
.map((s) => (
<option key={s.id} value={s.id}>
{s.name} (Lv {s.level})
{s.name} ({spellLevelLabel(s.level)})
</option>
))}
</select>
<button className="btn" onClick={handleAssignSpell} disabled={!pickedSpellId}>
Add
Grant
</button>
</div>
)}
@@ -428,11 +673,18 @@ export function CharacterSheetPage() {
<div className="card mt-md">
<div className="card-title">Inventory</div>
{itemsPage.pageItems.map((item) => (
<div key={item.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
{itemsPage.pageItems.map((held) => (
<div key={held.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<div>
<strong>{item.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>x{item.quantity}</span>
<strong>{held.item.name}</strong>
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>
Lv {held.level}
{held.scaledDamageDice && ` · ${held.scaledDamageDice}`} · x{held.quantity}
</span>
{!held.usable && <RequiresLevel level={held.level} />}
{held.item.description && (
<div style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>{held.item.description}</div>
)}
</div>
{canEdit && (
<div className="flex-row gap-sm">
@@ -440,67 +692,178 @@ export function CharacterSheetPage() {
Equipped
<input
type="checkbox"
checked={item.equipped}
onChange={(e) => patchItem.mutate({ itemId: item.id, equipped: e.target.checked })}
checked={held.equipped}
disabled={!held.usable}
onChange={(e) => patchItem.mutate({ itemId: held.itemId, equipped: e.target.checked })}
/>
</label>
<button className="btn btn-ghost" onClick={() => deleteItem.mutate(item.id)}>
✕
</button>
{isDM && (
<>
<GearLevelSelect
name={held.item.name}
level={held.level}
entry={held.item}
onChange={(level) => patchItem.mutate({ itemId: held.itemId, level })}
/>
<button
className="btn btn-ghost"
aria-label={`One fewer ${held.item.name}`}
disabled={held.quantity <= 1}
onClick={() => patchItem.mutate({ itemId: held.itemId, quantity: held.quantity - 1 })}
>
−
</button>
<button
className="btn btn-ghost"
aria-label={`One more ${held.item.name}`}
onClick={() => patchItem.mutate({ itemId: held.itemId, quantity: held.quantity + 1 })}
>
+
</button>
<button className="btn btn-ghost" aria-label={`Take away ${held.item.name}`} onClick={() => removeItem.mutate(held.itemId)}>
✕
</button>
</>
)}
</div>
)}
</div>
))}
{character.inventoryItems.length === 0 && <p style={{ color: 'var(--text-muted)' }}>Nothing carried. The DM hands out items.</p>}
<Pagination page={itemsPage.page} pageCount={itemsPage.pageCount} onPrev={itemsPage.prevPage} onNext={itemsPage.nextPage} />
{canEdit && (
<form onSubmit={handleAddItem} className="flex-row mt-sm flex-wrap">
<input
placeholder="New item name"
value={newItemName}
onChange={(e) => setNewItemName(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<button type="submit" className="btn">
Add Item
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<select value={pickedItemId} onChange={(e) => setPickedItemId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Give an item from the campaign pool…</option>
{campaignItems?.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
<button className="btn" onClick={handleAssignItem} disabled={!pickedItemId}>
Give
</button>
</form>
</div>
)}
{isDM && campaignItems?.length === 0 && (
<p className="subtitle">The item pool is empty — add items on the campaign page first.</p>
)}
</div>
{canEdit && (
<div className="card mt-md">
<div className="card-title">
<span>Money</span>
<span className="mono">{character.gold} gp</span>
</div>
{canEdit && (
<div className="flex-row flex-wrap">
<input
type="number"
min={1}
placeholder="Amount"
aria-label="Gold amount"
value={goldAmount}
onChange={(e) => setGoldAmount(e.target.value)}
style={{ width: 100 }}
/>
<input
placeholder="What for? (optional)"
aria-label="Reason"
maxLength={200}
value={goldReason}
onChange={(e) => setGoldReason(e.target.value)}
style={{ flex: 1, minWidth: 160 }}
/>
<button className="btn" onClick={() => handleGold(1)} disabled={!goldAmount || adjustGold.isPending}>
+ Gain
</button>
<button className="btn btn-danger" onClick={() => handleGold(-1)} disabled={!goldAmount || adjustGold.isPending}>
− Spend
</button>
</div>
)}
<div className="mt-sm">
{goldLedger?.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No transactions yet.</p>}
{ledgerPage.pageItems.map((t) => (
<div key={t.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
<div>
<strong className="mono">{t.amount > 0 ? `+${t.amount}` : `−${Math.abs(t.amount)}`}</strong>
<span style={{ marginLeft: 8 }}>{t.reason || (t.amount > 0 ? 'Gained' : 'Spent')}</span>
<div style={{ fontSize: '0.75rem', color: 'var(--text-dim)' }}>
{t.createdBy ? `${t.createdBy.displayName} · ` : ''}
{new Date(t.createdAt).toLocaleString()}
</div>
</div>
<span className="mono" style={{ color: 'var(--text-muted)' }}>{t.balanceAfter} gp</span>
</div>
))}
</div>
<Pagination page={ledgerPage.page} pageCount={ledgerPage.pageCount} onPrev={ledgerPage.prevPage} onNext={ledgerPage.nextPage} />
</div>
{/* Composed by the character builder from the player's picks. Players
read them; only the DM can rewrite them (new abilities on level-up,
a scar earned in play). */}
{(
[
['specialAbilities', 'Special Abilities', 'One per line, e.g. “Reckless Attack — gained at level 2.”', 6],
['background', 'Background', 'Where this character came from, what drives them…', 5],
['appearance', 'Appearance', 'Height, build, notable features, typical outfit…', 5],
] as const
).map(([field, title, placeholder, rows]) => (
<div className="card mt-md" key={field}>
<div className="card-title">
<span>{title}</span>
{isDM && <span className="badge">DM can edit</span>}
</div>
{isDM ? (
<textarea
key={`${field}:${character[field] ?? ''}`}
className="textarea-block"
rows={rows}
defaultValue={character[field] ?? ''}
placeholder={placeholder}
aria-label={title}
onBlur={(e) => {
const value = e.target.value.trim() || null;
if (value !== (character[field] ?? null)) patchCharacter.mutate({ [field]: value });
}}
/>
) : character[field] ? (
<p className="composed-text">{character[field]}</p>
) : (
<p className="subtitle" style={{ margin: 0 }}>
Nothing here yet. Your DM can fill this in.
</p>
)}
</div>
))}
{canEdit && <GiveCard character={character} onError={(err) => setFormError(extractErrorMessage(err))} />}
{canEdit && otherCampaigns.length > 0 && (
<div className="card mt-md">
<div className="card-title">Special Abilities</div>
<textarea
rows={3}
defaultValue={character.specialAbilities || ''}
placeholder="Darkvision, Second Wind, Sneak Attack, etc."
onBlur={(e) => patchCharacter.mutate({ specialAbilities: e.target.value })}
/>
<div className="card-title">Copy to Another Campaign</div>
<p className="subtitle" style={{ marginTop: 0 }}>
Makes an independent copy at full HP with the same stats, gear and spells. This character stays here unchanged.
</p>
<div className="flex-row flex-wrap">
<select value={copyTargetId} onChange={(e) => setCopyTargetId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Choose a campaign…</option>
{otherCampaigns.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<button className="btn" onClick={handleCopy} disabled={!copyTargetId || copyCharacter.isPending}>
{copyCharacter.isPending ? 'Copying…' : 'Copy Character'}
</button>
</div>
</div>
)}
<div className="card mt-md">
<div className="card-title">Background</div>
<textarea
rows={4}
defaultValue={character.background || ''}
placeholder={canEdit ? "Where this character came from, what drives them…" : 'No background written yet.'}
readOnly={!canEdit}
onBlur={(e) => canEdit && patchCharacter.mutate({ background: e.target.value })}
/>
</div>
<div className="card mt-md">
<div className="card-title">Appearance</div>
<textarea
rows={3}
defaultValue={character.appearance || ''}
placeholder={canEdit ? 'Height, build, notable features, typical outfit…' : 'No appearance written yet.'}
readOnly={!canEdit}
onBlur={(e) => canEdit && patchCharacter.mutate({ appearance: e.target.value })}
/>
</div>
{isOwner && (
<div className="card mt-md">
<div className="card-title">Private Notes</div>
+715 -158
View File
@@ -1,150 +1,572 @@
import { useState } from 'react';
import { useState, type ReactNode } from 'react';
import { Link, useParams } from 'react-router-dom';
import {
useEncounter,
useCampaign,
useCampaignCharacters,
useCampaignMonsters,
useCampaignNpcs,
useCampaignWeapons,
useCampaignItems,
useAddParticipant,
usePatchParticipant,
useRemoveParticipant,
useAdvanceRound,
useNextTurn,
usePatchEncounter,
useAddReward,
useDeleteReward,
useAwardReward,
type NewReward,
} from '../api/queries';
import { useCampaignSocket } from '../hooks/useCampaignSocket';
import { Spinner, ErrorBanner } from '../components/Spinner';
import { extractErrorMessage, fmtMod, hpBarClass } from '../lib/format';
import type { EncounterParticipant } from '../api/types';
import { ABILITY_LABELS, CLASS_LABELS, SPECIES_LABELS, extractErrorMessage, fmtMod, hpBarClass, spellLevelLabel } from '../lib/format';
import { abilityModifier, scaledDamageDice, MAX_GEAR_LEVEL } from '../lib/previewCalc';
import type {
Ability,
CharacterSummary,
Encounter,
EncounterMode,
EncounterParticipant,
EncounterReward,
Item,
Weapon,
} from '../api/types';
function ParticipantRow({
participant,
const ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
const CONDITIONS = [
'Blinded',
'Charmed',
'Deafened',
'Frightened',
'Grappled',
'Incapacitated',
'Invisible',
'Paralyzed',
'Petrified',
'Poisoned',
'Prone',
'Restrained',
'Stunned',
'Unconscious',
'Concentrating',
];
const KIND_LABELS = { CHARACTER: 'PC', MONSTER: 'Monster', NPC: 'NPC' } as const;
const KIND_BADGES = { CHARACTER: 'badge-player', MONSTER: 'badge-hostile', NPC: 'badge-friendly' } as const;
const MODE_LABELS: Record<EncounterMode, string> = { BATTLE: '⚔ Battle', QUEST: '📜 Quest' };
const STATUS_LABELS = { PLANNING: 'Planning', ACTIVE: 'In progress', COMPLETE: 'Complete' } as const;
function StatChip({ label, children }: { label: string; children: ReactNode }) {
return (
<span className="stat-chip">
<span>{label}</span>
<b>{children}</b>
</span>
);
}
// Who this combatant is, in one muted line under the name.
function subline(p: EncounterParticipant): string {
const info = p.characterCombatInfo;
if (info) {
return [
`Level ${info.level}`,
info.species && SPECIES_LABELS[info.species],
info.characterClass && CLASS_LABELS[info.characterClass],
]
.filter(Boolean)
.join(' ');
}
if (p.kind === 'NPC') return p.npc?.role || 'Non-player character';
if (p.monster?.challengeRating) return `Challenge ${p.monster.challengeRating}`;
return '';
}
function CombatantCard({
participant: p,
isDM,
mode,
isActive,
onPatch,
onRemove,
}: {
participant: EncounterParticipant;
isDM: boolean;
mode: EncounterMode;
isActive: boolean;
onPatch: (data: Partial<EncounterParticipant>) => void;
onRemove: () => void;
}) {
const [hpDelta, setHpDelta] = useState('');
const [showCombatInfo, setShowCombatInfo] = useState(false);
const pct = Math.max(0, Math.min(100, (participant.currentHp / participant.maxHp) * 100));
const combatInfo = participant.characterCombatInfo;
// Details start open for the DM (who runs the scene from this screen) and
// closed for players; null = "not toggled yet", so it follows isDM once the
// campaign role has loaded.
const [detailsToggled, setDetailsToggled] = useState<boolean | null>(null);
const showDetails = detailsToggled ?? isDM;
const info = p.characterCombatInfo;
const monster = p.monster;
const npc = p.npc;
const tracksHp = p.maxHp > 0;
const isDown = tracksHp && p.currentHp <= 0;
const pct = tracksHp ? Math.max(0, Math.min(100, (p.currentHp / p.maxHp) * 100)) : 0;
// Players get a monster's name and health bar only; the stat block is the DM's.
const monsterStats = monster && monster.ac !== undefined ? monster : null;
const hasDetails = Boolean(info || monsterStats || npc?.dmNotes);
function applyDelta(sign: 1 | -1) {
const amount = Number(hpDelta);
if (!amount) return;
onPatch({ currentHp: participant.currentHp + sign * amount });
onPatch({ currentHp: p.currentHp + sign * amount });
setHpDelta('');
}
function addCondition(condition: string) {
const name = condition.trim();
if (!name || p.conditions.includes(name)) return;
onPatch({ conditions: [...p.conditions, name] });
}
return (
<div className="card">
<div className={`card combatant combatant-${p.kind.toLowerCase()}${isActive ? ' is-active' : ''}${isDown ? ' is-down' : ''}`}>
<div className="flex-between flex-wrap">
<div className="flex-row">
<span className={`badge ${participant.isMonster ? 'badge-dm' : 'badge-player'}`}>
{participant.isMonster ? 'Monster' : 'PC'}
</span>
<strong>{participant.displayName}</strong>
</div>
{isDM && (
<label className="flex-row gap-sm">
Init
<input
type="number"
defaultValue={participant.initiative}
style={{ width: 60 }}
onBlur={(e) => onPatch({ initiative: Number(e.target.value) })}
/>
</label>
)}
</div>
<div className="hp-bar-track mt-sm">
<div className={hpBarClass(participant.currentHp, participant.maxHp)} style={{ width: `${pct}%` }} />
</div>
<div className="flex-between mt-sm flex-wrap">
<span>
HP {participant.currentHp}/{participant.maxHp}
</span>
{isDM && (
<div className="flex-row gap-sm">
<input type="number" placeholder="Amt" value={hpDelta} onChange={(e) => setHpDelta(e.target.value)} style={{ width: 70 }} />
<button className="btn btn-danger" onClick={() => applyDelta(-1)}>
−
</button>
<button className="btn" onClick={() => applyDelta(1)}>
+
</button>
<div>
{isActive && <div className="turn-marker">▶ On turn</div>}
<div className="flex-row flex-wrap">
<span className={`badge ${KIND_BADGES[p.kind]}`}>{KIND_LABELS[p.kind]}</span>
{p.character ? (
<Link to={`/characters/${p.character.id}`} className="combatant-name">
{p.displayName}
</Link>
) : (
<span className="combatant-name">{p.displayName}</span>
)}
{npc && <span className={`badge badge-${npc.disposition.toLowerCase()}`}>{npc.disposition}</span>}
{isDown && <span className="badge badge-hostile">Down</span>}
</div>
)}
</div>
{isDM && (
<div className="flex-row mt-sm flex-wrap">
<input
placeholder="Conditions, comma separated"
defaultValue={participant.conditions.join(', ')}
style={{ flex: 1, minWidth: 160 }}
onBlur={(e) =>
onPatch({
conditions: e.target.value
.split(',')
.map((c) => c.trim())
.filter(Boolean),
})
}
/>
<button className="btn btn-ghost" onClick={onRemove}>
Remove
</button>
<div className="combatant-sub">{subline(p)}</div>
</div>
{mode === 'BATTLE' &&
(isDM ? (
<label className="flex-row gap-sm">
Initiative
<input
key={`${p.id}:${p.initiative}`}
type="number"
defaultValue={p.initiative}
style={{ width: 64 }}
onBlur={(e) => Number(e.target.value) !== p.initiative && onPatch({ initiative: Number(e.target.value) })}
/>
</label>
) : (
<StatChip label="Initiative">{p.initiative}</StatChip>
))}
</div>
<div className="stat-chips mt-sm">
{tracksHp && (
<StatChip label="HP">
{p.currentHp}/{p.maxHp}
{info && info.tempHp > 0 && ` +${info.tempHp}`}
</StatChip>
)}
{info && (
<>
<StatChip label="AC">{info.armorClass}</StatChip>
<StatChip label="Speed">{info.speed}</StatChip>
<StatChip label="Init">{fmtMod(info.initiativeBonus)}</StatChip>
<StatChip label="Passive Perc.">{info.passivePerception}</StatChip>
<StatChip label="Prof.">{fmtMod(info.proficiencyBonus)}</StatChip>
{info.spellcasting && <StatChip label="Spell DC">{info.spellcasting.saveDC}</StatChip>}
</>
)}
{monsterStats && (
<>
<StatChip label="AC">{monsterStats.ac}</StatChip>
<StatChip label="Speed">{monsterStats.speed}</StatChip>
<StatChip label="Attack">{fmtMod(monsterStats.attackBonus ?? 0)}</StatChip>
{monsterStats.damageDice && <StatChip label="Damage">{monsterStats.damageDice}</StatChip>}
</>
)}
{npc && npc.ac != null && <StatChip label="AC">{npc.ac}</StatChip>}
{npc && npc.attackBonus != null && <StatChip label="Attack">{fmtMod(npc.attackBonus)}</StatChip>}
{npc && npc.damageDice && <StatChip label="Damage">{npc.damageDice}</StatChip>}
</div>
{/* An NPC's description is what players are here for, so it is never tucked away. */}
{npc?.description && <p style={{ margin: '0.5rem 0 0', whiteSpace: 'pre-wrap' }}>{npc.description}</p>}
{tracksHp && (
<>
<div className="hp-bar-track mt-sm">
<div className={hpBarClass(p.currentHp, p.maxHp)} style={{ width: `${pct}%` }} />
</div>
{isDM && (
<div className="flex-row gap-sm mt-sm">
<input
type="number"
min={1}
placeholder="Amount"
aria-label={`HP change for ${p.displayName}`}
value={hpDelta}
onChange={(e) => setHpDelta(e.target.value)}
style={{ width: 90 }}
/>
<button className="btn btn-danger" onClick={() => applyDelta(-1)} disabled={!hpDelta}>
− Damage
</button>
<button className="btn" onClick={() => applyDelta(1)} disabled={!hpDelta}>
+ Heal
</button>
</div>
)}
</>
)}
{!isDM && participant.conditions.length > 0 && (
<div className="flex-row flex-wrap mt-sm">
{participant.conditions.map((c) => (
<span key={c} className="badge">
{(p.conditions.length > 0 || isDM) && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{p.conditions.map((c) => (
<span key={c} className="condition-chip">
{c}
{isDM && (
<button aria-label={`Remove ${c}`} onClick={() => onPatch({ conditions: p.conditions.filter((x) => x !== c) })}>
✕
</button>
)}
</span>
))}
{isDM && (
<select
aria-label={`Add a condition to ${p.displayName}`}
value=""
onChange={(e) => addCondition(e.target.value)}
style={{ width: 'auto' }}
>
<option value="">+ Condition</option>
{CONDITIONS.filter((c) => !p.conditions.includes(c)).map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
)}
</div>
)}
{combatInfo && (
<div className="mt-sm">
<button className="btn btn-ghost" onClick={() => setShowCombatInfo((s) => !s)}>
{showCombatInfo ? 'Hide' : '⚔ Show'} Weapons & Spells
</button>
{showCombatInfo && (
<div className="mt-sm">
{combatInfo.weapons.length === 0 && combatInfo.spells.length === 0 && (
<p style={{ color: 'var(--text-muted)', margin: 0 }}>Nothing equipped or prepared.</p>
)}
{combatInfo.weapons.map((w) => (
<div key={w.characterWeaponId} className="flex-between" style={{ padding: '0.2rem 0' }}>
{(hasDetails || isDM) && (
<div className="flex-between mt-sm">
{hasDetails ? (
<button className="btn btn-ghost" onClick={() => setDetailsToggled(!showDetails)}>
{showDetails ? '▾ Hide details' : '▸ Show details'}
</button>
) : (
<span />
)}
{isDM && (
<button className="btn btn-ghost" onClick={onRemove}>
Remove
</button>
)}
</div>
)}
{hasDetails && showDetails && (
<div className="combatant-details">
{info && (
<>
<div className="stat-chips">
{ABILITIES.map((a) => (
<StatChip key={a} label={a}>
{info.abilities[a].final} ({fmtMod(info.abilities[a].modifier)})
</StatChip>
))}
</div>
<p className="combatant-sub">
Saves:{' '}
{ABILITIES.map((a) => `${a} ${fmtMod(info.saves[a].bonus)}${info.saves[a].proficient ? '*' : ''}`).join(' · ')}{' '}
<span title="Proficient">(* proficient)</span>
</p>
{info.weapons.length === 0 && info.spells.length === 0 && <p className="combatant-sub">No usable weapons or spells.</p>}
{info.weapons.map((w) => (
<div key={w.characterWeaponId} className="detail-row">
<span>
{w.name} {w.equipped && <span className="badge">equipped</span>}
<span style={{ color: 'var(--text-muted)', marginLeft: 6, fontSize: '0.85rem' }}>
{w.damageDice} {w.damageType} {fmtMod(w.damageBonus)}
<span className="combatant-sub" style={{ marginLeft: 6 }}>
Lv {w.level} · {w.damageDice} {fmtMod(w.damageBonus)} {w.damageType}
</span>
</span>
<span className="mono">{fmtMod(w.attackBonus)}</span>
<span className="mono" title="Attack bonus">
{fmtMod(w.attackBonus)} to hit
</span>
</div>
))}
{combatInfo.spells.length > 0 && (
<div className="flex-row flex-wrap mt-sm">
{combatInfo.spells.map((s) => (
<span key={s.characterSpellId} className={`badge ${s.prepared ? 'badge-dm' : ''}`}>
{s.name} (Lv {s.level})
{info.spells.length > 0 && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{info.spells.map((s) => (
<span
key={s.characterSpellId}
className={`badge ${s.prepared ? 'badge-dm' : ''}`}
title={[s.prepared ? 'Prepared' : 'Known, not prepared', s.description].filter(Boolean).join(' — ')}
>
{s.name} ({spellLevelLabel(s.level)}
{s.damageDice ? ` · ${s.damageDice}` : ''})
</span>
))}
</div>
)}
{combatInfo.spellcasting && (
<p style={{ margin: '0.4rem 0 0', fontSize: '0.85rem', color: 'var(--text-muted)' }}>
Spell Save DC {combatInfo.spellcasting.saveDC} · Attack {fmtMod(combatInfo.spellcasting.attackBonus)}
{info.spellcasting && (
<p className="combatant-sub">
Spellcasting ({ABILITY_LABELS[info.spellcasting.ability]}): save DC {info.spellcasting.saveDC} ·{' '}
{fmtMod(info.spellcasting.attackBonus)} to hit
</p>
)}
</div>
{info.specialAbilities && <p style={{ whiteSpace: 'pre-wrap' }}>{info.specialAbilities}</p>}
</>
)}
{monsterStats && (
<>
<div className="stat-chips">
{ABILITIES.map((a) => {
const score = monsterStats[`${a.toLowerCase()}Score` as 'strScore'] ?? 10;
return (
<StatChip key={a} label={a}>
{score} ({fmtMod(abilityModifier(score))})
</StatChip>
);
})}
</div>
{monsterStats.specialTrait && (
<p>
<strong>Trait:</strong> {monsterStats.specialTrait}
</p>
)}
{monsterStats.notes && <p style={{ whiteSpace: 'pre-wrap' }}>{monsterStats.notes}</p>}
</>
)}
{npc?.dmNotes && (
<p style={{ whiteSpace: 'pre-wrap', color: 'var(--text-muted)' }} title="Only you can see this">
🔒 {npc.dmNotes}
</p>
)}
</div>
)}
</div>
);
}
function rewardLabel(r: EncounterReward): string {
if (r.type === 'GOLD') return `${r.gold} gold`;
const entry = r.type === 'WEAPON' ? r.weapon : r.item;
return `${entry?.name ?? 'Removed from the pool'}${r.quantity > 1 ? ` ×${r.quantity}` : ''} · Lv ${r.level}`;
}
function RewardsPanel({
encounter,
isDM,
characters,
weapons,
items,
onError,
}: {
encounter: Encounter;
isDM: boolean;
characters: CharacterSummary[];
weapons: Weapon[];
items: Item[];
onError: (err: unknown) => void;
}) {
const addReward = useAddReward(encounter.id);
const deleteReward = useDeleteReward(encounter.id);
const awardReward = useAwardReward(encounter.id);
const [type, setType] = useState<NewReward['type']>('GOLD');
const [gold, setGold] = useState('');
const [poolId, setPoolId] = useState('');
const [quantity, setQuantity] = useState('1');
const [level, setLevel] = useState('');
const [note, setNote] = useState('');
const [recipients, setRecipients] = useState<Record<string, string>>({});
const rewards = encounter.rewards ?? [];
const pool: (Weapon | Item)[] = type === 'WEAPON' ? weapons : items;
const picked = pool.find((entry) => entry.id === poolId);
const partySize = (encounter.participants ?? []).filter((p) => p.kind === 'CHARACTER' && p.characterId).length;
if (!isDM && rewards.length === 0) return null;
function handleAdd() {
const shared = { note: note.trim() || undefined };
let reward: NewReward;
if (type === 'GOLD') {
const amount = Math.floor(Number(gold));
if (!(amount > 0)) return;
reward = { type, gold: amount, ...shared };
} else {
if (!picked) return;
const gear = { quantity: Math.max(1, Math.floor(Number(quantity)) || 1), level: level ? Number(level) : undefined, ...shared };
reward = type === 'WEAPON' ? { type, weaponId: picked.id, ...gear } : { type, itemId: picked.id, ...gear };
}
addReward.mutate(reward, {
onError,
onSuccess: () => {
setGold('');
setPoolId('');
setQuantity('1');
setLevel('');
setNote('');
},
});
}
return (
<div className="card">
<div className="card-title">Rewards</div>
{isDM && rewards.length === 0 && (
<p className="combatant-sub" style={{ marginTop: 0 }}>
Line up gold, weapons and items here. Players only see a reward once you award it.
</p>
)}
{rewards.map((r) => (
<div key={r.id} className={`reward-row${r.awardedAt ? ' is-awarded' : ''}`}>
<div className="flex-between">
<strong>
{r.type === 'GOLD' ? '🪙' : r.type === 'WEAPON' ? '🗡' : '🎒'} {rewardLabel(r)}
</strong>
{isDM && (
<button className="btn btn-ghost" aria-label={`Remove reward ${rewardLabel(r)}`} onClick={() => deleteReward.mutate(r.id, { onError })}>
✕
</button>
)}
</div>
{r.note && <div className="combatant-sub">{r.note}</div>}
{r.awardedAt ? (
<div className="combatant-sub">✓ Awarded to {r.awardedTo}</div>
) : (
isDM && (
<div className="flex-row flex-wrap gap-sm mt-sm">
<select
aria-label={`Who receives ${rewardLabel(r)}`}
value={recipients[r.id] ?? ''}
onChange={(e) => setRecipients({ ...recipients, [r.id]: e.target.value })}
style={{ flex: 1, minWidth: 110 }}
>
<option value="">Award to…</option>
{characters.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<button
className="btn"
disabled={!recipients[r.id] || awardReward.isPending}
onClick={() => awardReward.mutate({ rewardId: r.id, characterId: recipients[r.id] }, { onError })}
>
Award
</button>
{r.type === 'GOLD' && (
<button
className="btn"
disabled={partySize === 0 || awardReward.isPending}
title="Share evenly between the characters in this encounter"
onClick={() => awardReward.mutate({ rewardId: r.id, split: true }, { onError })}
>
Split
</button>
)}
</div>
)
)}
</div>
))}
{isDM && (
<div className="mt-md">
<div className="section-label">Add a reward</div>
<div className="flex-row flex-wrap gap-sm">
<select
aria-label="Reward type"
value={type}
onChange={(e) => {
setType(e.target.value as NewReward['type']);
setPoolId('');
setLevel('');
}}
>
<option value="GOLD">Gold</option>
<option value="WEAPON">Weapon</option>
<option value="ITEM">Item</option>
</select>
{type === 'GOLD' ? (
<input
type="number"
min={1}
placeholder="Amount"
aria-label="Gold amount"
value={gold}
onChange={(e) => setGold(e.target.value)}
style={{ flex: 1, minWidth: 90 }}
/>
) : (
<>
<select
aria-label={type === 'WEAPON' ? 'Weapon' : 'Item'}
value={poolId}
onChange={(e) => {
setPoolId(e.target.value);
setLevel('');
}}
style={{ flex: 1, minWidth: 110 }}
>
<option value="">{pool.length ? 'Choose…' : 'The pool is empty'}</option>
{pool.map((entry) => (
<option key={entry.id} value={entry.id}>
{entry.name}
</option>
))}
</select>
{picked && (
<>
<select aria-label="Level" value={level || picked.minLevel} onChange={(e) => setLevel(e.target.value)}>
{Array.from({ length: MAX_GEAR_LEVEL - picked.minLevel + 1 }, (_, i) => picked.minLevel + i).map((l) => (
<option key={l} value={l}>
Lv {l}
{picked.damageDice ? ` · ${scaledDamageDice(picked.damageDice, l, picked.damageScaling, picked.minLevel)}` : ''}
</option>
))}
</select>
<input
type="number"
min={1}
aria-label="Quantity"
title="Quantity"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
style={{ width: 64 }}
/>
</>
)}
</>
)}
</div>
<div className="flex-row gap-sm mt-sm">
<input
placeholder="Note (optional)"
aria-label="Reward note"
maxLength={200}
value={note}
onChange={(e) => setNote(e.target.value)}
style={{ flex: 1, minWidth: 0 }}
/>
<button className="btn btn-primary" onClick={handleAdd} disabled={addReward.isPending || (type === 'GOLD' ? !gold : !picked)}>
Add
</button>
</div>
</div>
)}
</div>
@@ -157,72 +579,125 @@ export function EncounterPage() {
useCampaignSocket(encounter?.campaignId);
const { data: campaignData } = useCampaign(encounter?.campaignId);
const isDM = campaignData?.campaign.role === 'DM';
const { data: characters } = useCampaignCharacters(encounter?.campaignId);
const { data: monsters } = useCampaignMonsters(encounter?.campaignId);
const { data: monsters } = useCampaignMonsters(encounter?.campaignId, isDM);
const { data: npcs } = useCampaignNpcs(encounter?.campaignId, isDM);
const { data: weapons } = useCampaignWeapons(encounter?.campaignId);
const { data: items } = useCampaignItems(encounter?.campaignId);
const addParticipant = useAddParticipant(encounterId);
const patchParticipant = usePatchParticipant(encounterId);
const removeParticipant = useRemoveParticipant(encounterId);
const advanceRound = useAdvanceRound(encounterId);
const nextTurn = useNextTurn(encounterId);
const patchEncounter = usePatchEncounter(encounterId);
const [pickType, setPickType] = useState<'character' | 'monster'>('character');
const [pickType, setPickType] = useState<'character' | 'monster' | 'npc'>('character');
const [pickId, setPickId] = useState('');
const [initiative, setInitiative] = useState('0');
const [initiative, setInitiative] = useState('');
const [formError, setFormError] = useState<string | null>(null);
if (isLoading) return <Spinner label="Setting the battlefield…" />;
if (isLoading) return <Spinner label="Setting the scene…" />;
if (error || !encounter) return <ErrorBanner message="Could not load this encounter." />;
const isDM = campaignData?.campaign.role === 'DM';
const sorted = [...(encounter.participants || [])].sort((a, b) => b.initiative - a.initiative);
const availableCharacters = characters?.filter((c) => !encounter.participants?.some((p) => p.characterId === c.id) && c.buildStage === 'COMPLETE');
const availableMonsters = monsters;
const isBattle = encounter.mode === 'BATTLE';
const participants = encounter.participants ?? []; // already in initiative order
const active = isBattle && encounter.status === 'ACTIVE' ? participants.find((p) => p.id === encounter.activeParticipantId) : undefined;
const builtCharacters = characters?.filter((c) => c.buildStage === 'COMPLETE') ?? [];
const onError = (err: unknown) => setFormError(extractErrorMessage(err));
const fail = { onError };
async function handleAdd() {
const pickOptions: { id: string; name: string }[] =
pickType === 'character'
? builtCharacters.filter((c) => !participants.some((p) => p.characterId === c.id))
: pickType === 'monster'
? (monsters ?? [])
: (npcs ?? []).filter((n) => !participants.some((p) => p.npcId === n.id));
function handleAdd() {
if (!pickId) return;
setFormError(null);
try {
await addParticipant.mutateAsync({
[pickType === 'character' ? 'characterId' : 'monsterId']: pickId,
initiative: Number(initiative) || 0,
});
setPickId('');
} catch (err) {
setFormError(extractErrorMessage(err));
}
addParticipant.mutate(
{ [`${pickType}Id`]: pickId, initiative: Number(initiative) || 0 },
{ onError, onSuccess: () => setPickId('') }
);
}
const card = (p: EncounterParticipant) => (
<CombatantCard
key={p.id}
participant={p}
isDM={isDM}
mode={encounter.mode}
isActive={p.id === active?.id}
onPatch={(data) => patchParticipant.mutate({ participantId: p.id, ...data }, fail)}
onRemove={() => removeParticipant.mutate(p.id, fail)}
/>
);
// A quest scene is grouped by who is there rather than by initiative.
const groups: [string, EncounterParticipant[]][] = isBattle
? [['Initiative order', participants]]
: [
['People you meet', participants.filter((p) => p.kind === 'NPC')],
['The party', participants.filter((p) => p.kind === 'CHARACTER')],
['Creatures', participants.filter((p) => p.kind === 'MONSTER')],
];
return (
<div>
<div className="page-header">
<div>
<h1>⚔ {encounter.name}</h1>
<p className="subtitle">
{encounter.status} · Round {encounter.currentRound}
</p>
<h1>
{isBattle ? '⚔' : '📜'} {encounter.name}
</h1>
<div className="flex-row flex-wrap">
<span className="badge badge-dm">{MODE_LABELS[encounter.mode]}</span>
<span className={`badge ${encounter.status === 'ACTIVE' ? 'badge-live' : ''}`}>{STATUS_LABELS[encounter.status]}</span>
{isBattle && <span className="badge">Round {encounter.currentRound}</span>}
{active && <span className="turn-marker">▶ {active.displayName}'s turn</span>}
</div>
</div>
<div className="flex-row">
<div className="flex-row flex-wrap">
<Link to={`/campaigns/${encounter.campaignId}`} className="btn btn-ghost">
← Campaign
</Link>
{isDM && (
<>
<select
aria-label="Encounter type"
value={encounter.mode}
onChange={(e) => patchEncounter.mutate({ mode: e.target.value as EncounterMode }, fail)}
>
<option value="BATTLE">Battle</option>
<option value="QUEST">NPC quest</option>
</select>
{encounter.status === 'PLANNING' && (
<button className="btn btn-primary" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' })}>
Begin Combat
<button className="btn btn-primary" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' }, fail)}>
{isBattle ? 'Begin Battle' : 'Begin Quest'}
</button>
)}
{encounter.status === 'ACTIVE' && (
{encounter.status === 'ACTIVE' && isBattle && (
<>
<button className="btn btn-primary" onClick={() => advanceRound.mutate()}>
Advance Round
<button className="btn btn-primary" onClick={() => nextTurn.mutate(undefined, fail)} disabled={nextTurn.isPending}>
Next Turn ▶
</button>
<button className="btn btn-danger" onClick={() => patchEncounter.mutate({ status: 'COMPLETE' })}>
End Encounter
<button className="btn" onClick={() => advanceRound.mutate(undefined, fail)} title="Skip straight to the top of the next round">
Next Round
</button>
</>
)}
{encounter.status === 'ACTIVE' && (
<button className="btn btn-danger" onClick={() => patchEncounter.mutate({ status: 'COMPLETE' }, fail)}>
{isBattle ? 'End Battle' : 'Complete Quest'}
</button>
)}
{encounter.status === 'COMPLETE' && (
<button className="btn" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' }, fail)}>
Reopen
</button>
)}
</>
)}
</div>
@@ -230,47 +705,129 @@ export function EncounterPage() {
{formError && <ErrorBanner message={formError} />}
{isDM && (
<div className="card mt-md">
<div className="card-title">Add Combatant</div>
<div className="flex-row flex-wrap">
<select value={pickType} onChange={(e) => setPickType(e.target.value as 'character' | 'monster')}>
<option value="character">Character</option>
<option value="monster">Monster</option>
</select>
<select value={pickId} onChange={(e) => setPickId(e.target.value)} style={{ flex: 1, minWidth: 160 }}>
<option value="">Select…</option>
{(pickType === 'character' ? availableCharacters : availableMonsters)?.map((entity) => (
<option key={entity.id} value={entity.id}>
{entity.name}
</option>
))}
</select>
<input
type="number"
placeholder="Initiative"
value={initiative}
onChange={(e) => setInitiative(e.target.value)}
style={{ width: 100 }}
{(isDM || encounter.description) && (
<div className="card">
<div className="card-title">{isBattle ? 'The Scene' : 'Quest'}</div>
{isDM ? (
<textarea
key={`description:${encounter.description ?? ''}`}
rows={3}
className="textarea-block"
defaultValue={encounter.description ?? ''}
aria-label="Scene description, shown to players"
placeholder={
isBattle
? 'Describe the battlefield: terrain, cover, hazards… (shown to players)'
: 'What is being asked of the party, and by whom? (shown to players)'
}
onBlur={(e) => {
const description = e.target.value.trim() || null;
if (description !== encounter.description) patchEncounter.mutate({ description }, fail);
}}
/>
<button className="btn btn-primary" onClick={handleAdd} disabled={!pickId}>
Add
</button>
</div>
) : (
<p style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{encounter.description}</p>
)}
</div>
)}
<div className="mt-lg">
{sorted.length === 0 && <div className="empty-state">No combatants yet.</div>}
{sorted.map((p) => (
<ParticipantRow
key={p.id}
participant={p}
isDM={Boolean(isDM)}
onPatch={(data) => patchParticipant.mutate({ participantId: p.id, ...data })}
onRemove={() => removeParticipant.mutate(p.id)}
<div className="encounter-layout mt-md">
<div>
{participants.length === 0 && (
<div className="empty-state card">
{isDM
? 'Nobody here yet. Add characters, monsters or NPCs from the panel alongside.'
: 'The DM is still setting the scene.'}
</div>
)}
{groups
.filter(([, members]) => members.length > 0)
.map(([label, members]) => (
<div key={label} className="mt-md">
<div className="section-label">
{label} · {members.length}
</div>
{members.map(card)}
</div>
))}
</div>
<div>
{isDM && (
<div className="card">
<div className="card-title">Add to the scene</div>
<div className="flex-row flex-wrap gap-sm">
<select
aria-label="What to add"
value={pickType}
onChange={(e) => {
setPickType(e.target.value as typeof pickType);
setPickId('');
}}
>
<option value="character">Character</option>
<option value="monster">Monster</option>
<option value="npc">NPC</option>
</select>
<select aria-label="Who to add" value={pickId} onChange={(e) => setPickId(e.target.value)} style={{ flex: 1, minWidth: 110 }}>
<option value="">{pickOptions.length ? 'Choose…' : 'None left to add'}</option>
{pickOptions.map((entity) => (
<option key={entity.id} value={entity.id}>
{entity.name}
</option>
))}
</select>
</div>
<div className="flex-row gap-sm mt-sm">
{isBattle && (
<input
type="number"
placeholder="Initiative"
aria-label="Initiative"
value={initiative}
onChange={(e) => setInitiative(e.target.value)}
style={{ flex: 1, minWidth: 0 }}
/>
)}
<button className="btn btn-primary" onClick={handleAdd} disabled={!pickId || addParticipant.isPending}>
Add
</button>
</div>
{pickType !== 'character' && pickOptions.length === 0 && (
<p className="combatant-sub">
Create {pickType === 'npc' ? 'NPCs' : 'monsters'} on the <Link to={`/campaigns/${encounter.campaignId}`}>campaign page</Link> first.
</p>
)}
</div>
)}
<RewardsPanel
encounter={encounter}
isDM={isDM}
characters={builtCharacters}
weapons={weapons ?? []}
items={items ?? []}
onError={onError}
/>
))}
{isDM && (
<div className="card">
<div className="card-title">DM Notes</div>
<textarea
key={`dmNotes:${encounter.dmNotes ?? ''}`}
rows={5}
className="textarea-block"
defaultValue={encounter.dmNotes ?? ''}
aria-label="DM notes, never shown to players"
placeholder="Tactics, secrets, what happens if they fail… (only you see this)"
onBlur={(e) => {
const dmNotes = e.target.value.trim() || null;
if (dmNotes !== (encounter.dmNotes ?? null)) patchEncounter.mutate({ dmNotes }, fail);
}}
/>
</div>
)}
</div>
</div>
</div>
);
+2
View File
@@ -55,6 +55,7 @@ export function PartyOverviewPage() {
<th>
AC <InfoTip term="AC" />
</th>
<th>Gold</th>
<th>Location</th>
</tr>
</thead>
@@ -89,6 +90,7 @@ export function PartyOverviewPage() {
)}
</td>
<td>{c.armorClass ?? '—'}</td>
<td className="mono">{c.gold}</td>
<td>{c.currentLocationName ? `📍 ${c.currentLocationName}` : '—'}</td>
</tr>
);