Initial commit
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import { Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { Layout } from './components/Layout';
|
||||
import { ProtectedRoute } from './components/ProtectedRoute';
|
||||
import { LoginPage } from './pages/LoginPage';
|
||||
import { RegisterPage } from './pages/RegisterPage';
|
||||
import { CampaignListPage } from './pages/CampaignListPage';
|
||||
import { CampaignHomePage } from './pages/CampaignHomePage';
|
||||
import { CharacterSheetPage } from './pages/CharacterSheetPage';
|
||||
import { CharacterBuilderPage } from './pages/CharacterBuilderPage';
|
||||
import { EncounterPage } from './pages/EncounterPage';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/register" element={<RegisterPage />} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route element={<Layout />}>
|
||||
<Route path="/" element={<Navigate to="/campaigns" replace />} />
|
||||
<Route path="/campaigns" element={<CampaignListPage />} />
|
||||
<Route path="/campaigns/:campaignId" element={<CampaignHomePage />} />
|
||||
<Route path="/characters/:characterId" element={<CharacterSheetPage />} />
|
||||
<Route path="/characters/:characterId/build" element={<CharacterBuilderPage />} />
|
||||
<Route path="/encounters/:encounterId" element={<EncounterPage />} />
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,19 @@
|
||||
import axios from 'axios';
|
||||
|
||||
export const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:4000';
|
||||
|
||||
export const apiClient = axios.create({ baseURL: API_URL });
|
||||
|
||||
export function setAuthToken(token: string | null) {
|
||||
if (token) {
|
||||
apiClient.defaults.headers.common.Authorization = `Bearer ${token}`;
|
||||
localStorage.setItem('dnd_token', token);
|
||||
} else {
|
||||
delete apiClient.defaults.headers.common.Authorization;
|
||||
localStorage.removeItem('dnd_token');
|
||||
}
|
||||
}
|
||||
|
||||
export function getStoredToken(): string | null {
|
||||
return localStorage.getItem('dnd_token');
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiClient } from './client';
|
||||
import type {
|
||||
Campaign,
|
||||
CampaignMemberSummary,
|
||||
CharacterDetail,
|
||||
CharacterSummary,
|
||||
Encounter,
|
||||
EncounterParticipant,
|
||||
InventoryItem,
|
||||
Monster,
|
||||
Note,
|
||||
QuickStats,
|
||||
Spell,
|
||||
Weapon,
|
||||
} from './types';
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Campaigns
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export function useCampaigns() {
|
||||
return useQuery({
|
||||
queryKey: ['campaigns'],
|
||||
queryFn: async () => (await apiClient.get<{ campaigns: Campaign[] }>('/campaigns')).data.campaigns,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCampaign(campaignId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['campaign', campaignId],
|
||||
enabled: Boolean(campaignId),
|
||||
queryFn: async () =>
|
||||
(
|
||||
await apiClient.get<{ campaign: Campaign; members: CampaignMemberSummary[] }>(`/campaigns/${campaignId}`)
|
||||
).data,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateCampaign() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
startingGold?: number;
|
||||
startingItemCount?: number;
|
||||
startingSpellCount?: number;
|
||||
skipMotivationRoll?: boolean;
|
||||
}) => (await apiClient.post<{ campaign: Campaign }>('/campaigns', data)).data.campaign,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaigns'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateCampaign(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: Partial<Campaign>) =>
|
||||
(await apiClient.patch<{ campaign: Campaign }>(`/campaigns/${campaignId}`, data)).data.campaign,
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['campaign', campaignId] });
|
||||
qc.invalidateQueries({ queryKey: ['campaigns'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useJoinCampaign() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (inviteCode: string) =>
|
||||
(await apiClient.post<{ campaign: Campaign }>(`/campaigns/join/${inviteCode}`)).data.campaign,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaigns'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useRegenerateInvite(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async () =>
|
||||
(await apiClient.post<{ inviteCode: string }>(`/campaigns/${campaignId}/invite`, { regenerate: true })).data
|
||||
.inviteCode,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId] }),
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Characters
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export function useCampaignCharacters(campaignId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['campaign', campaignId, 'characters'],
|
||||
enabled: Boolean(campaignId),
|
||||
queryFn: async () =>
|
||||
(await apiClient.get<{ characters: CharacterSummary[] }>(`/campaigns/${campaignId}/characters`)).data
|
||||
.characters,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateCharacter(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { name: string; userId?: string }) =>
|
||||
(await apiClient.post<{ character: CharacterSummary }>(`/campaigns/${campaignId}/characters`, data)).data
|
||||
.character,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCharacter(characterId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['character', characterId],
|
||||
enabled: Boolean(characterId),
|
||||
refetchInterval: false,
|
||||
queryFn: async () => (await apiClient.get<{ character: CharacterDetail }>(`/characters/${characterId}`)).data
|
||||
.character,
|
||||
});
|
||||
}
|
||||
|
||||
export function usePatchCharacter(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: Partial<CharacterDetail>) =>
|
||||
(await apiClient.patch<{ character: CharacterDetail }>(`/characters/${characterId}`, data)).data.character,
|
||||
onSuccess: (character) => {
|
||||
qc.setQueryData(['character', characterId], character);
|
||||
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteCharacter(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (characterId: string) => apiClient.delete(`/characters/${characterId}`),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useQuickStats(characterId: string | undefined, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: ['character', characterId, 'quick-stats'],
|
||||
enabled: Boolean(characterId) && enabled,
|
||||
queryFn: async () =>
|
||||
(await apiClient.get<{ quickStats: QuickStats }>(`/characters/${characterId}/quick-stats`)).data.quickStats,
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Character build flow
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
function invalidateCharacter(qc: ReturnType<typeof useQueryClient>, characterId: string) {
|
||||
qc.invalidateQueries({ queryKey: ['character', characterId] });
|
||||
}
|
||||
|
||||
export function useBuildRoll(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async () =>
|
||||
(await apiClient.post<{ buildStage: string; buildState: Record<string, unknown> }>(
|
||||
`/characters/${characterId}/build/roll`
|
||||
)).data,
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useBuildChoose(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (body: Record<string, unknown>) =>
|
||||
(await apiClient.post<{ buildStage: string; buildState: Record<string, unknown> }>(
|
||||
`/characters/${characterId}/build/choose`,
|
||||
body
|
||||
)).data,
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useBuildFinalize(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async () =>
|
||||
(await apiClient.post<{ character: CharacterDetail }>(`/characters/${characterId}/build/finalize`)).data
|
||||
.character,
|
||||
onSuccess: (character) => {
|
||||
qc.setQueryData(['character', characterId], character);
|
||||
qc.invalidateQueries({ queryKey: ['campaign', character.campaignId, 'characters'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Weapons / inventory / spells on a character
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export function useAssignWeapon(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { weaponId: string; quantity?: number }) =>
|
||||
(await apiClient.post(`/characters/${characterId}/weapons`, data)).data,
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
export function usePatchCharacterWeapon(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({ weaponId, ...data }: { weaponId: string; equipped?: boolean; quantity?: number }) =>
|
||||
(await apiClient.patch(`/characters/${characterId}/weapons/${weaponId}`, data)).data,
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAddInventoryItem(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,
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
export function usePatchInventoryItem(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({ itemId, ...data }: { itemId: string; quantity?: number; equipped?: boolean }) =>
|
||||
(await apiClient.patch(`/characters/${characterId}/inventory/${itemId}`, data)).data,
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteInventoryItem(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (itemId: string) => apiClient.delete(`/characters/${characterId}/inventory/${itemId}`),
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssignSpell(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { spellId: string; prepared?: boolean }) =>
|
||||
(await apiClient.post(`/characters/${characterId}/spells`, data)).data,
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
export function usePatchCharacterSpell(characterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({ spellId, prepared }: { spellId: string; prepared: boolean }) =>
|
||||
(await apiClient.patch(`/characters/${characterId}/spells/${spellId}`, { prepared })).data,
|
||||
onSuccess: () => invalidateCharacter(qc, characterId),
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Campaign weapons / spells / monsters pools
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export function useCampaignWeapons(campaignId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['campaign', campaignId, 'weapons'],
|
||||
enabled: Boolean(campaignId),
|
||||
queryFn: async () => (await apiClient.get<{ weapons: Weapon[] }>(`/campaigns/${campaignId}/weapons`)).data.weapons,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateWeapon(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: Omit<Weapon, 'id' | 'campaignId'>) =>
|
||||
(await apiClient.post<{ weapon: Weapon }>(`/campaigns/${campaignId}/weapons`, data)).data.weapon,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'weapons'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCampaignSpells(campaignId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['campaign', campaignId, 'spells'],
|
||||
enabled: Boolean(campaignId),
|
||||
queryFn: async () => (await apiClient.get<{ spells: Spell[] }>(`/campaigns/${campaignId}/spells`)).data.spells,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateSpell(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: Omit<Spell, 'id' | 'campaignId'>) =>
|
||||
(await apiClient.post<{ spell: Spell }>(`/campaigns/${campaignId}/spells`, data)).data.spell,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'spells'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCampaignMonsters(campaignId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['campaign', campaignId, 'monsters'],
|
||||
enabled: Boolean(campaignId),
|
||||
queryFn: async () =>
|
||||
(await apiClient.get<{ monsters: Monster[] }>(`/campaigns/${campaignId}/monsters`)).data.monsters,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateMonster(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: Omit<Monster, 'id' | 'campaignId'>) =>
|
||||
(await apiClient.post<{ monster: Monster }>(`/campaigns/${campaignId}/monsters`, data)).data.monster,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'monsters'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteMonster(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (monsterId: string) => apiClient.delete(`/campaigns/${campaignId}/monsters/${monsterId}`),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'monsters'] }),
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Encounters
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export function useCampaignEncounters(campaignId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['campaign', campaignId, 'encounters'],
|
||||
enabled: Boolean(campaignId),
|
||||
queryFn: async () =>
|
||||
(await apiClient.get<{ encounters: Encounter[] }>(`/campaigns/${campaignId}/encounters`)).data.encounters,
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'encounters'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useEncounter(encounterId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['encounter', encounterId],
|
||||
enabled: Boolean(encounterId),
|
||||
queryFn: async () => (await apiClient.get<{ encounter: Encounter }>(`/encounters/${encounterId}`)).data.encounter,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAddParticipant(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { characterId?: string; monsterId?: string; displayName?: string; initiative?: number }) =>
|
||||
(await apiClient.post(`/encounters/${encounterId}/participants`, data)).data,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function usePatchParticipant(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({ participantId, ...data }: Partial<EncounterParticipant> & { participantId: string }) =>
|
||||
(await apiClient.patch(`/encounters/${encounterId}/participants/${participantId}`, data)).data,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useRemoveParticipant(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (participantId: string) =>
|
||||
apiClient.delete(`/encounters/${encounterId}/participants/${participantId}`),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAdvanceRound(encounterId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async () => (await apiClient.post(`/encounters/${encounterId}/advance-round`)).data,
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
|
||||
});
|
||||
}
|
||||
|
||||
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] }),
|
||||
});
|
||||
}
|
||||
type EncounterStatusInput = 'PLANNING' | 'ACTIVE' | 'COMPLETE';
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Notes
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export function useCampaignNotes(campaignId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['campaign', campaignId, 'notes'],
|
||||
enabled: Boolean(campaignId),
|
||||
queryFn: async () => (await apiClient.get<{ notes: Note[] }>(`/campaigns/${campaignId}/notes`)).data.notes,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCharacterNotes(characterId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['character', characterId, 'notes'],
|
||||
enabled: Boolean(characterId),
|
||||
queryFn: async () => (await apiClient.get<{ notes: Note[] }>(`/characters/${characterId}/notes`)).data.notes,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateNote() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (data: { campaignId?: string; characterId?: string; body: string; visibility?: 'DM_ONLY' | 'SHARED' }) =>
|
||||
(await apiClient.post<{ note: Note }>('/notes', data)).data.note,
|
||||
onSuccess: (note) => {
|
||||
if (note.campaignId) qc.invalidateQueries({ queryKey: ['campaign', note.campaignId, 'notes'] });
|
||||
if (note.characterId) qc.invalidateQueries({ queryKey: ['character', note.characterId, 'notes'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
export type Ability = 'STR' | 'DEX' | 'CON' | 'INT' | 'WIS' | 'CHA';
|
||||
|
||||
export type Species =
|
||||
| 'HUMAN'
|
||||
| 'HALF_ELF'
|
||||
| 'ELF'
|
||||
| 'GNOME'
|
||||
| 'DWARF'
|
||||
| 'HALFLING'
|
||||
| 'DRAGONBORN'
|
||||
| 'TIEFLING'
|
||||
| 'HALF_ORC'
|
||||
| 'ORC';
|
||||
|
||||
export type CharacterClass =
|
||||
| 'FIGHTER'
|
||||
| 'BARBARIAN'
|
||||
| 'ROGUE'
|
||||
| 'RANGER'
|
||||
| 'WIZARD'
|
||||
| 'SORCERER'
|
||||
| 'CLERIC'
|
||||
| 'PALADIN'
|
||||
| 'BARD'
|
||||
| 'WARLOCK'
|
||||
| 'DRUID'
|
||||
| 'MONK';
|
||||
|
||||
export type BuildStage =
|
||||
| 'NOT_STARTED'
|
||||
| 'ROLLING_SPECIES'
|
||||
| 'ROLLING_CLASS'
|
||||
| 'ROLLING_MOTIVATION'
|
||||
| 'ASSIGNING_SCORES'
|
||||
| 'ASSIGNING_PROFICIENCIES'
|
||||
| 'CHOOSING_EQUIPMENT'
|
||||
| 'COMPLETE';
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
export interface Campaign {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
inviteCode: string;
|
||||
startingGold: number;
|
||||
startingItemCount: number;
|
||||
startingSpellCount: number;
|
||||
skipMotivationRoll: boolean;
|
||||
ownerId: string;
|
||||
role: 'DM' | 'PLAYER';
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface CampaignMemberSummary {
|
||||
userId: string;
|
||||
displayName: string;
|
||||
role: 'DM' | 'PLAYER';
|
||||
}
|
||||
|
||||
export interface CharacterSummary {
|
||||
id: string;
|
||||
campaignId: string;
|
||||
userId: string | null;
|
||||
createdById: string;
|
||||
name: string;
|
||||
species: Species | null;
|
||||
characterClass: CharacterClass | null;
|
||||
level: number;
|
||||
xp: number;
|
||||
buildStage: BuildStage;
|
||||
currentHp: number;
|
||||
tempHp: number;
|
||||
maxHp: number | null;
|
||||
armorClass: number | null;
|
||||
}
|
||||
|
||||
export interface AbilityDetail {
|
||||
rolled: number;
|
||||
final: number;
|
||||
modifier: number;
|
||||
}
|
||||
|
||||
export interface CharacterSheet {
|
||||
abilities: Record<Ability, AbilityDetail>;
|
||||
proficiencyBonus: number;
|
||||
armorClass: number;
|
||||
initiative: number;
|
||||
speed: number;
|
||||
hp: { max: number };
|
||||
hitDice: { size: number; count: number };
|
||||
saves: Record<Ability, { proficient: boolean; bonus: number }>;
|
||||
skills: Record<string, { ability: Ability; proficient: boolean; expertise: boolean; bonus: number }>;
|
||||
passivePerception: number;
|
||||
spellcasting: { ability: Ability; saveDC: number; attackBonus: number } | null;
|
||||
}
|
||||
|
||||
export interface Weapon {
|
||||
id: string;
|
||||
campaignId: string;
|
||||
name: string;
|
||||
damageDice: string;
|
||||
damageType: string;
|
||||
attackAbility: 'STR' | 'DEX' | 'FINESSE';
|
||||
properties: string[];
|
||||
rangeNormal: number | null;
|
||||
rangeLong: number | null;
|
||||
}
|
||||
|
||||
export interface CharacterWeapon {
|
||||
id: string;
|
||||
characterId: string;
|
||||
weaponId: string;
|
||||
quantity: number;
|
||||
equipped: boolean;
|
||||
weapon: Weapon;
|
||||
}
|
||||
|
||||
export interface Spell {
|
||||
id: string;
|
||||
campaignId: string;
|
||||
name: string;
|
||||
level: number;
|
||||
school: string | null;
|
||||
castingTime: string | null;
|
||||
range: string | null;
|
||||
duration: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
export interface CharacterSpell {
|
||||
id: string;
|
||||
characterId: string;
|
||||
spellId: string;
|
||||
prepared: boolean;
|
||||
spell: Spell;
|
||||
}
|
||||
|
||||
export interface InventoryItem {
|
||||
id: string;
|
||||
characterId: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
quantity: number;
|
||||
equipped: boolean;
|
||||
}
|
||||
|
||||
export interface SkillProficiency {
|
||||
skill: string;
|
||||
proficient: boolean;
|
||||
expertise: boolean;
|
||||
}
|
||||
|
||||
export interface SaveProficiency {
|
||||
ability: Ability;
|
||||
proficient: boolean;
|
||||
}
|
||||
|
||||
export interface CharacterDetail {
|
||||
id: string;
|
||||
campaignId: string;
|
||||
userId: string | null;
|
||||
createdById: string;
|
||||
name: string;
|
||||
species: Species | null;
|
||||
characterClass: CharacterClass | null;
|
||||
level: number;
|
||||
xp: number;
|
||||
motivation: string | null;
|
||||
halfElfBonusAbility1: Ability | null;
|
||||
halfElfBonusAbility2: Ability | null;
|
||||
rolledScores: Record<Ability, number>;
|
||||
currentHp: number;
|
||||
tempHp: number;
|
||||
armorBonus: number;
|
||||
specialAbilities: string | null;
|
||||
gold: number;
|
||||
buildStage: BuildStage;
|
||||
buildState: Record<string, unknown> | null;
|
||||
skillProficiencies: SkillProficiency[];
|
||||
saveProficiencies: SaveProficiency[];
|
||||
inventoryItems: InventoryItem[];
|
||||
weapons: CharacterWeapon[];
|
||||
spells: CharacterSpell[];
|
||||
sheet: CharacterSheet | null;
|
||||
}
|
||||
|
||||
export interface Monster {
|
||||
id: string;
|
||||
campaignId: string;
|
||||
name: string;
|
||||
ac: number;
|
||||
maxHp: number;
|
||||
speed: number;
|
||||
strScore: number;
|
||||
dexScore: number;
|
||||
conScore: number;
|
||||
intScore: number;
|
||||
wisScore: number;
|
||||
chaScore: number;
|
||||
attackBonus: number;
|
||||
damageDice: string | null;
|
||||
challengeRating: string | null;
|
||||
specialTrait: string | null;
|
||||
notes: string | null;
|
||||
}
|
||||
|
||||
export type EncounterStatus = 'PLANNING' | 'ACTIVE' | 'COMPLETE';
|
||||
|
||||
export interface EncounterParticipant {
|
||||
id: string;
|
||||
encounterId: string;
|
||||
characterId: string | null;
|
||||
monsterId: string | null;
|
||||
displayName: string;
|
||||
initiative: number;
|
||||
currentHp: number;
|
||||
maxHp: number;
|
||||
conditions: string[];
|
||||
isMonster: boolean;
|
||||
character?: { id: string; name: string } | null;
|
||||
monster?: { id: string; name: string } | null;
|
||||
}
|
||||
|
||||
export interface Encounter {
|
||||
id: string;
|
||||
campaignId: string;
|
||||
name: string;
|
||||
status: EncounterStatus;
|
||||
currentRound: number;
|
||||
createdAt: string;
|
||||
participants?: EncounterParticipant[];
|
||||
}
|
||||
|
||||
export interface Note {
|
||||
id: string;
|
||||
campaignId: string | null;
|
||||
characterId: string | null;
|
||||
authorId: string;
|
||||
body: string;
|
||||
visibility: 'DM_ONLY' | 'SHARED';
|
||||
createdAt: string;
|
||||
author?: { displayName: string };
|
||||
}
|
||||
|
||||
export interface QuickStatsWeapon {
|
||||
characterWeaponId: string;
|
||||
weaponId: string;
|
||||
name: string;
|
||||
equipped: boolean;
|
||||
quantity: number;
|
||||
attackBonus: number;
|
||||
damageBonus: number;
|
||||
damageDice: string;
|
||||
damageType: string;
|
||||
}
|
||||
|
||||
export interface QuickStats {
|
||||
name: string;
|
||||
currentHp: number;
|
||||
maxHp: number;
|
||||
tempHp: number;
|
||||
armorClass: number;
|
||||
initiative: number;
|
||||
speed: number;
|
||||
proficiencyBonus: number;
|
||||
spellcasting: { ability: Ability; saveDC: number; attackBonus: number } | null;
|
||||
specialAbilities: string | null;
|
||||
weapons: QuickStatsWeapon[];
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { apiClient, getStoredToken, setAuthToken } from '../api/client';
|
||||
import type { User } from '../api/types';
|
||||
|
||||
interface AuthContextValue {
|
||||
user: User | null;
|
||||
token: string | null;
|
||||
loading: boolean;
|
||||
login: (token: string, user: User) => void;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [token, setToken] = useState<string | null>(getStoredToken());
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const stored = getStoredToken();
|
||||
if (!stored) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setAuthToken(stored);
|
||||
apiClient
|
||||
.get<{ user: User }>('/auth/me')
|
||||
.then((res) => {
|
||||
setUser(res.data.user);
|
||||
setToken(stored);
|
||||
})
|
||||
.catch(() => {
|
||||
setAuthToken(null);
|
||||
setToken(null);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const login = (newToken: string, newUser: User) => {
|
||||
setAuthToken(newToken);
|
||||
setToken(newToken);
|
||||
setUser(newUser);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
setAuthToken(null);
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
const value = useMemo(() => ({ user, token, loading, login, logout }), [user, token, loading]);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Link, Outlet } from 'react-router-dom';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
|
||||
export function Layout() {
|
||||
const { user, logout } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<header className="topbar">
|
||||
<Link to="/campaigns" className="topbar-brand">
|
||||
<span className="die" aria-hidden>
|
||||
⚄
|
||||
</span>
|
||||
The Sunken Reach
|
||||
</Link>
|
||||
<nav className="topbar-nav">
|
||||
{user && (
|
||||
<div className="topbar-user">
|
||||
<span>{user.displayName}</span>
|
||||
<button className="btn btn-ghost" onClick={logout}>
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</nav>
|
||||
</header>
|
||||
<main className="page">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Navigate, Outlet } from 'react-router-dom';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import { Spinner } from './Spinner';
|
||||
|
||||
export function ProtectedRoute() {
|
||||
const { user, loading } = useAuth();
|
||||
if (loading) return <Spinner label="Checking your credentials…" />;
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuickStats } from '../api/queries';
|
||||
import { Spinner, ErrorBanner } from './Spinner';
|
||||
import { fmtMod } from '../lib/format';
|
||||
|
||||
export function QuickStatsFab({ characterId }: { characterId: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<button className="fab-quickstats" onClick={() => setOpen(true)} title="Quick Stats" aria-label="Open quick stats">
|
||||
⚡
|
||||
</button>
|
||||
{open && <QuickStatsDrawer characterId={characterId} onClose={() => setOpen(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function QuickStatsDrawer({ characterId, onClose }: { characterId: string; onClose: () => void }) {
|
||||
const { data, isLoading, error } = useQuickStats(characterId, true);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="drawer-backdrop" onClick={onClose} />
|
||||
<div className="drawer">
|
||||
<div className="flex-between">
|
||||
<h2 style={{ margin: 0 }}>Quick Stats</h2>
|
||||
<button className="btn btn-ghost" onClick={onClose}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
{isLoading && <Spinner label="Reading the sheet…" />}
|
||||
{error && <ErrorBanner message="Could not load quick stats." />}
|
||||
{data && (
|
||||
<div className="mt-md">
|
||||
<h3 style={{ margin: 0 }}>{data.name}</h3>
|
||||
<div className="grid grid-cols-3 mt-sm">
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">HP</span>
|
||||
<span className="stat-value">
|
||||
{data.currentHp}/{data.maxHp}
|
||||
</span>
|
||||
{data.tempHp > 0 && <span className="stat-sub">+{data.tempHp} temp</span>}
|
||||
</div>
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">AC</span>
|
||||
<span className="stat-value">{data.armorClass}</span>
|
||||
</div>
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">Initiative</span>
|
||||
<span className="stat-value">{fmtMod(data.initiative)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="hp-bar-track mt-sm">
|
||||
<div className="hp-bar-fill" style={{ width: `${Math.max(0, Math.min(100, (data.currentHp / data.maxHp) * 100))}%` }} />
|
||||
</div>
|
||||
|
||||
{data.spellcasting && (
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Spellcasting</div>
|
||||
<p style={{ margin: 0 }}>
|
||||
Save DC {data.spellcasting.saveDC} · Attack {fmtMod(data.spellcasting.attackBonus)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Weapons</div>
|
||||
{data.weapons.length === 0 && <p style={{ color: 'var(--text-muted)', margin: 0 }}>No weapons equipped.</p>}
|
||||
{data.weapons.map((w) => (
|
||||
<div key={w.characterWeaponId} className="flex-between mt-sm">
|
||||
<div>
|
||||
<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)}
|
||||
</p>
|
||||
</div>
|
||||
<span className="stat-value" style={{ fontSize: '1.1rem' }}>
|
||||
{fmtMod(w.attackBonus)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{data.specialAbilities && (
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Special Abilities</div>
|
||||
<p style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{data.specialAbilities}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export function Spinner({ label = 'Loading…' }: { label?: string }) {
|
||||
return (
|
||||
<div className="flex-row" style={{ padding: '2rem', color: 'var(--text-muted)' }}>
|
||||
<span className="spinner" aria-hidden />
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBanner({ message }: { message: string }) {
|
||||
return (
|
||||
<div className="card" style={{ borderColor: 'var(--danger)' }}>
|
||||
<p className="error-text" style={{ margin: 0 }}>
|
||||
{message}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import { API_URL } from '../api/client';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
|
||||
let sharedSocket: Socket | null = null;
|
||||
|
||||
function getSocket(token: string): Socket {
|
||||
if (!sharedSocket) {
|
||||
sharedSocket = io(API_URL, { auth: { token }, transports: ['websocket', 'polling'] });
|
||||
}
|
||||
return sharedSocket;
|
||||
}
|
||||
|
||||
// Joins the Socket.io room for a campaign and keeps React Query's cache in
|
||||
// sync with server-pushed events (HP/condition changes, encounter rounds,
|
||||
// new characters) so every open tab in the campaign updates live.
|
||||
export function useCampaignSocket(campaignId: string | undefined) {
|
||||
const { token } = useAuth();
|
||||
const qc = useQueryClient();
|
||||
|
||||
useEffect(() => {
|
||||
if (!campaignId || !token) return;
|
||||
const socket = getSocket(token);
|
||||
socket.emit('campaign:join', campaignId);
|
||||
|
||||
const onCharacterUpdated = () => {
|
||||
qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] });
|
||||
qc.invalidateQueries({ queryKey: ['character'] });
|
||||
};
|
||||
const onCharacterCreated = () => {
|
||||
qc.invalidateQueries({ queryKey: ['campaign', campaignId, 'characters'] });
|
||||
};
|
||||
const onParticipantUpdated = () => {
|
||||
qc.invalidateQueries({ queryKey: ['encounter'] });
|
||||
};
|
||||
const onRoundAdvanced = () => {
|
||||
qc.invalidateQueries({ queryKey: ['encounter'] });
|
||||
};
|
||||
|
||||
socket.on('character:updated', onCharacterUpdated);
|
||||
socket.on('character:created', onCharacterCreated);
|
||||
socket.on('encounter:participant-updated', onParticipantUpdated);
|
||||
socket.on('encounter:round-advanced', onRoundAdvanced);
|
||||
|
||||
return () => {
|
||||
socket.emit('campaign:leave', campaignId);
|
||||
socket.off('character:updated', onCharacterUpdated);
|
||||
socket.off('character:created', onCharacterCreated);
|
||||
socket.off('encounter:participant-updated', onParticipantUpdated);
|
||||
socket.off('encounter:round-advanced', onRoundAdvanced);
|
||||
};
|
||||
}, [campaignId, token, qc]);
|
||||
}
|
||||
@@ -0,0 +1,585 @@
|
||||
:root {
|
||||
--bg: #131009;
|
||||
--bg-elevated: #1b160e;
|
||||
--bg-card: #221b12;
|
||||
--bg-card-hover: #2a2116;
|
||||
--bg-inset: #0e0b07;
|
||||
--border: #4a3a24;
|
||||
--border-soft: #362a1a;
|
||||
--text: #ece1c8;
|
||||
--text-muted: #b2a284;
|
||||
--text-dim: #7c7159;
|
||||
--accent: #c9a227;
|
||||
--accent-strong: #e6c34a;
|
||||
--accent-soft: rgba(201, 162, 39, 0.15);
|
||||
--danger: #b23a3a;
|
||||
--danger-strong: #d85454;
|
||||
--danger-soft: rgba(178, 58, 58, 0.18);
|
||||
--success: #5f8a4f;
|
||||
--success-strong: #7ab266;
|
||||
--arcane: #5c7fb0;
|
||||
--arcane-strong: #7fa3d6;
|
||||
--shadow-deep: 0 10px 30px rgba(0, 0, 0, 0.55);
|
||||
--radius: 8px;
|
||||
--font-display: 'Cinzel', Georgia, serif;
|
||||
--font-body: 'Crimson Pro', Georgia, 'Times New Roman', serif;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
/* This app is intentionally dark-themed only (D&D tavern-at-night aesthetic). */
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
background: radial-gradient(ellipse at top, #1a1510 0%, var(--bg) 55%, #0d0a06 100%);
|
||||
color: var(--text);
|
||||
font-family: var(--font-body);
|
||||
font-size: 16px;
|
||||
line-height: 1.5;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
#root {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4 {
|
||||
font-family: var(--font-display);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--accent-strong);
|
||||
margin: 0 0 0.5em 0;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--arcane-strong);
|
||||
text-decoration: none;
|
||||
}
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0 0 0.75em 0;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font-family: var(--font-body);
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--bg-inset);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--border);
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------- */
|
||||
/* Layout primitives */
|
||||
/* ---------------------------------------------------------------------- */
|
||||
|
||||
.app-shell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.75rem 1.25rem;
|
||||
background: linear-gradient(180deg, #1e1810 0%, #171209 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 30;
|
||||
}
|
||||
|
||||
.topbar-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
font-family: var(--font-display);
|
||||
color: var(--accent-strong);
|
||||
font-size: 1.15rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.topbar-brand .die {
|
||||
font-size: 1.4rem;
|
||||
filter: drop-shadow(0 0 6px rgba(201, 162, 39, 0.5));
|
||||
}
|
||||
|
||||
.topbar-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.topbar-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.page {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
max-width: 1080px;
|
||||
margin: 0 auto;
|
||||
padding: 1.5rem 1.25rem 4rem;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.page-header h1 {
|
||||
margin-bottom: 0.15em;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------- */
|
||||
/* Cards & ornamentation */
|
||||
/* ---------------------------------------------------------------------- */
|
||||
|
||||
.card {
|
||||
background: linear-gradient(160deg, var(--bg-card) 0%, var(--bg-elevated) 100%);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 1.25rem;
|
||||
box-shadow: var(--shadow-deep);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.card::before,
|
||||
.card::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border: 2px solid var(--accent);
|
||||
opacity: 0.55;
|
||||
}
|
||||
.card::before {
|
||||
top: -1px;
|
||||
left: -1px;
|
||||
border-right: none;
|
||||
border-bottom: none;
|
||||
}
|
||||
.card::after {
|
||||
bottom: -1px;
|
||||
right: -1px;
|
||||
border-left: none;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.card + .card {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-family: var(--font-display);
|
||||
color: var(--accent);
|
||||
font-size: 1rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
margin-bottom: 0.75rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
.grid-cols-2 {
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
}
|
||||
.grid-cols-3 {
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------- */
|
||||
/* Buttons */
|
||||
/* ---------------------------------------------------------------------- */
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
font-family: var(--font-display);
|
||||
font-size: 0.85rem;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
padding: 0.6rem 1.1rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent-strong);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: linear-gradient(160deg, var(--accent) 0%, #a8811c 100%);
|
||||
border-color: var(--accent-strong);
|
||||
color: #1a1410;
|
||||
font-weight: 700;
|
||||
}
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
color: #1a1410;
|
||||
box-shadow: 0 0 16px rgba(201, 162, 39, 0.45);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: linear-gradient(160deg, var(--danger) 0%, #7a2626 100%);
|
||||
border-color: var(--danger-strong);
|
||||
color: #fbeaea;
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.btn-ghost:hover:not(:disabled) {
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
.btn-block {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.btn-lg {
|
||||
padding: 0.9rem 1.5rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
/* Big dice-roll button for the character builder */
|
||||
.btn-roll {
|
||||
font-family: var(--font-display);
|
||||
font-size: 1.3rem;
|
||||
padding: 1.3rem 2rem;
|
||||
border-radius: 12px;
|
||||
background: radial-gradient(circle at 30% 20%, #3a2e18, #1c160c 70%);
|
||||
border: 2px solid var(--accent);
|
||||
color: var(--accent-strong);
|
||||
box-shadow: 0 0 24px rgba(201, 162, 39, 0.25), inset 0 0 20px rgba(0, 0, 0, 0.5);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.btn-roll:hover:not(:disabled) {
|
||||
box-shadow: 0 0 32px rgba(201, 162, 39, 0.45), inset 0 0 20px rgba(0, 0, 0, 0.5);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
.btn-roll:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------- */
|
||||
/* Forms */
|
||||
/* ---------------------------------------------------------------------- */
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.field label {
|
||||
font-size: 0.8rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
input[type='text'],
|
||||
input[type='email'],
|
||||
input[type='password'],
|
||||
input[type='number'],
|
||||
select,
|
||||
textarea {
|
||||
background: var(--bg-inset);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 0.6rem 0.75rem;
|
||||
color: var(--text);
|
||||
}
|
||||
input:focus,
|
||||
select:focus,
|
||||
textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-soft);
|
||||
}
|
||||
|
||||
.checkbox-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------- */
|
||||
/* Badges / stat blocks */
|
||||
/* ---------------------------------------------------------------------- */
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border-radius: 999px;
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.badge-dm {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent-strong);
|
||||
}
|
||||
.badge-player {
|
||||
border-color: var(--arcane);
|
||||
color: var(--arcane-strong);
|
||||
}
|
||||
|
||||
.stat-block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.15rem;
|
||||
background: var(--bg-inset);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 8px;
|
||||
padding: 0.6rem 0.4rem;
|
||||
min-width: 64px;
|
||||
}
|
||||
.stat-block .stat-label {
|
||||
font-size: 0.65rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.stat-block .stat-value {
|
||||
font-family: var(--font-display);
|
||||
font-size: 1.4rem;
|
||||
color: var(--accent-strong);
|
||||
}
|
||||
.stat-block .stat-sub {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.hp-bar-track {
|
||||
width: 100%;
|
||||
height: 10px;
|
||||
background: var(--bg-inset);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.hp-bar-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, var(--danger) 0%, var(--success) 100%);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.divider {
|
||||
border: none;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.error-text {
|
||||
color: var(--danger-strong);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 2.5rem 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
width: 1.4rem;
|
||||
height: 1.4rem;
|
||||
border: 3px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.roll-result {
|
||||
font-family: var(--font-display);
|
||||
font-size: 3rem;
|
||||
color: var(--accent-strong);
|
||||
text-shadow: 0 0 20px rgba(201, 162, 39, 0.5);
|
||||
}
|
||||
|
||||
@keyframes rollPop {
|
||||
0% {
|
||||
transform: scale(0.4) rotate(-15deg);
|
||||
opacity: 0;
|
||||
}
|
||||
60% {
|
||||
transform: scale(1.1) rotate(5deg);
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
transform: scale(1) rotate(0deg);
|
||||
}
|
||||
}
|
||||
.roll-result.animate {
|
||||
animation: rollPop 0.4s ease-out;
|
||||
}
|
||||
|
||||
/* Quick stats drawer */
|
||||
.drawer-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
z-index: 90;
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
.drawer {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: min(420px, 100vw);
|
||||
background: linear-gradient(180deg, #1c160d 0%, #120e08 100%);
|
||||
border-left: 1px solid var(--border);
|
||||
box-shadow: -12px 0 40px rgba(0, 0, 0, 0.6);
|
||||
z-index: 91;
|
||||
overflow-y: auto;
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.fab-quickstats {
|
||||
position: fixed;
|
||||
bottom: 1.25rem;
|
||||
right: 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);
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: 'Courier New', monospace;
|
||||
}
|
||||
|
||||
.text-center {
|
||||
text-align: center;
|
||||
}
|
||||
.flex-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.flex-between {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.flex-wrap {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.gap-sm {
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.mt-sm {
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
.mt-md {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
.mt-lg {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.page {
|
||||
padding: 1rem 0.85rem 5rem;
|
||||
}
|
||||
.topbar {
|
||||
padding: 0.6rem 0.85rem;
|
||||
}
|
||||
.roll-result {
|
||||
font-size: 2.2rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Ability, CharacterClass } from '../api/types';
|
||||
|
||||
// Mirrors backend/src/game/data/classes.js spellcastingAbility column — used
|
||||
// only to decide whether the builder's equipment step offers spell picks.
|
||||
export const CLASS_SPELLCASTING_ABILITY: Record<CharacterClass, Ability | null> = {
|
||||
FIGHTER: null,
|
||||
BARBARIAN: null,
|
||||
ROGUE: null,
|
||||
RANGER: 'WIS',
|
||||
WIZARD: 'INT',
|
||||
SORCERER: 'CHA',
|
||||
CLERIC: 'WIS',
|
||||
PALADIN: 'CHA',
|
||||
BARD: 'CHA',
|
||||
WARLOCK: 'CHA',
|
||||
DRUID: 'WIS',
|
||||
MONK: null,
|
||||
};
|
||||
@@ -0,0 +1,78 @@
|
||||
export const SPECIES_LABELS: Record<string, string> = {
|
||||
HUMAN: 'Human',
|
||||
HALF_ELF: 'Half-Elf',
|
||||
ELF: 'Elf',
|
||||
GNOME: 'Gnome',
|
||||
DWARF: 'Dwarf',
|
||||
HALFLING: 'Halfling',
|
||||
DRAGONBORN: 'Dragonborn',
|
||||
TIEFLING: 'Tiefling',
|
||||
HALF_ORC: 'Half-Orc',
|
||||
ORC: 'Orc',
|
||||
};
|
||||
|
||||
export const CLASS_LABELS: Record<string, string> = {
|
||||
FIGHTER: 'Fighter',
|
||||
BARBARIAN: 'Barbarian',
|
||||
ROGUE: 'Rogue',
|
||||
RANGER: 'Ranger',
|
||||
WIZARD: 'Wizard',
|
||||
SORCERER: 'Sorcerer',
|
||||
CLERIC: 'Cleric',
|
||||
PALADIN: 'Paladin',
|
||||
BARD: 'Bard',
|
||||
WARLOCK: 'Warlock',
|
||||
DRUID: 'Druid',
|
||||
MONK: 'Monk',
|
||||
};
|
||||
|
||||
export const SKILL_LABELS: Record<string, string> = {
|
||||
ACROBATICS: 'Acrobatics',
|
||||
ANIMAL_HANDLING: 'Animal Handling',
|
||||
ARCANA: 'Arcana',
|
||||
ATHLETICS: 'Athletics',
|
||||
DECEPTION: 'Deception',
|
||||
HISTORY: 'History',
|
||||
INSIGHT: 'Insight',
|
||||
INTIMIDATION: 'Intimidation',
|
||||
INVESTIGATION: 'Investigation',
|
||||
MEDICINE: 'Medicine',
|
||||
NATURE: 'Nature',
|
||||
PERCEPTION: 'Perception',
|
||||
PERFORMANCE: 'Performance',
|
||||
PERSUASION: 'Persuasion',
|
||||
RELIGION: 'Religion',
|
||||
SLEIGHT_OF_HAND: 'Sleight of Hand',
|
||||
STEALTH: 'Stealth',
|
||||
SURVIVAL: 'Survival',
|
||||
};
|
||||
|
||||
export const ABILITY_LABELS: Record<string, string> = {
|
||||
STR: 'Strength',
|
||||
DEX: 'Dexterity',
|
||||
CON: 'Constitution',
|
||||
INT: 'Intelligence',
|
||||
WIS: 'Wisdom',
|
||||
CHA: 'Charisma',
|
||||
};
|
||||
|
||||
export function fmtMod(mod: number): string {
|
||||
return mod >= 0 ? `+${mod}` : `${mod}`;
|
||||
}
|
||||
|
||||
export function extractErrorMessage(err: unknown): string {
|
||||
const anyErr = err as { response?: { data?: { error?: unknown } } };
|
||||
const apiError = anyErr?.response?.data?.error;
|
||||
if (typeof apiError === 'string') return apiError;
|
||||
if (apiError && typeof apiError === 'object') {
|
||||
const flat = apiError as { formErrors?: string[]; fieldErrors?: Record<string, string[]> };
|
||||
const messages = [
|
||||
...(flat.formErrors || []),
|
||||
...Object.values(flat.fieldErrors || {}).flat(),
|
||||
];
|
||||
if (messages.length) return messages.join(', ');
|
||||
return JSON.stringify(apiError);
|
||||
}
|
||||
if (err instanceof Error) return err.message;
|
||||
return 'Something went wrong.';
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Ability, Species } from '../api/types';
|
||||
|
||||
// Mirrors backend/src/game/data/species.js — used only to preview the running
|
||||
// math live during the builder. The server recomputes authoritatively at
|
||||
// finalize, so this duplication is display-only and never gameplay-deciding.
|
||||
export const SPECIES_ABILITY_BONUSES: Record<Species, Partial<Record<Ability, number>>> = {
|
||||
HUMAN: { STR: 1, DEX: 1, CON: 1, INT: 1, WIS: 1, CHA: 1 },
|
||||
HALF_ELF: { CHA: 2 },
|
||||
ELF: { DEX: 2 },
|
||||
GNOME: { INT: 2 },
|
||||
DWARF: { CON: 2 },
|
||||
HALFLING: { DEX: 2 },
|
||||
DRAGONBORN: { STR: 2, CHA: 1 },
|
||||
TIEFLING: { INT: 1, CHA: 2 },
|
||||
HALF_ORC: { STR: 2, CON: 1 },
|
||||
ORC: { STR: 2, CON: 1 },
|
||||
};
|
||||
|
||||
export function speciesBonusFor(species: Species | null, ability: Ability, halfElfBonusAbilities: Ability[] = []): number {
|
||||
if (!species) return 0;
|
||||
let bonus = SPECIES_ABILITY_BONUSES[species][ability] || 0;
|
||||
if (species === 'HALF_ELF' && halfElfBonusAbilities.includes(ability)) bonus += 1;
|
||||
return bonus;
|
||||
}
|
||||
|
||||
export function abilityModifier(score: number): number {
|
||||
return Math.floor((score - 10) / 2);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import './index.css';
|
||||
import App from './App.tsx';
|
||||
import { AuthProvider } from './auth/AuthContext';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
staleTime: 15_000,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,436 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import {
|
||||
useCampaign,
|
||||
useCampaignCharacters,
|
||||
useCreateCharacter,
|
||||
useDeleteCharacter,
|
||||
useCampaignEncounters,
|
||||
useCreateEncounter,
|
||||
useCampaignMonsters,
|
||||
useCreateMonster,
|
||||
useDeleteMonster,
|
||||
useCampaignWeapons,
|
||||
useCreateWeapon,
|
||||
useCampaignSpells,
|
||||
useCreateSpell,
|
||||
useCampaignNotes,
|
||||
useCreateNote,
|
||||
useUpdateCampaign,
|
||||
useRegenerateInvite,
|
||||
} from '../api/queries';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import { useCampaignSocket } from '../hooks/useCampaignSocket';
|
||||
import { Spinner, ErrorBanner } from '../components/Spinner';
|
||||
import { extractErrorMessage } from '../lib/format';
|
||||
import type { CharacterSummary } from '../api/types';
|
||||
|
||||
function CharacterRow({ character, isDM, onDelete }: { character: CharacterSummary; isDM: boolean; onDelete: () => void }) {
|
||||
const inProgress = character.buildStage !== 'COMPLETE';
|
||||
return (
|
||||
<div className="card flex-between flex-wrap">
|
||||
<div>
|
||||
<div className="flex-row">
|
||||
<Link to={`/characters/${character.id}`} style={{ fontFamily: 'var(--font-display)', color: 'var(--accent-strong)', fontSize: '1.05rem' }}>
|
||||
{character.name}
|
||||
</Link>
|
||||
{inProgress && <span className="badge">Building…</span>}
|
||||
</div>
|
||||
<p style={{ margin: 0, color: 'var(--text-muted)', fontSize: '0.9rem' }}>
|
||||
{character.species ? `${character.species} ` : ''}
|
||||
{character.characterClass || (inProgress ? 'Not yet built' : '')} · Level {character.level}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex-row">
|
||||
{!inProgress && (
|
||||
<div style={{ textAlign: 'right', fontSize: '0.85rem', color: 'var(--text-muted)' }}>
|
||||
HP {character.currentHp}/{character.maxHp} · AC {character.armorClass}
|
||||
</div>
|
||||
)}
|
||||
<Link to={inProgress ? `/characters/${character.id}/build` : `/characters/${character.id}`} className="btn">
|
||||
{inProgress ? 'Continue Build' : 'Open Sheet'}
|
||||
</Link>
|
||||
{isDM && (
|
||||
<button className="btn btn-ghost" onClick={onDelete}>
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CampaignHomePage() {
|
||||
const { campaignId = '' } = useParams();
|
||||
const { user } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
useCampaignSocket(campaignId);
|
||||
|
||||
const { data, isLoading, error } = useCampaign(campaignId);
|
||||
const { data: characters } = useCampaignCharacters(campaignId);
|
||||
const { data: encounters } = useCampaignEncounters(campaignId);
|
||||
const { data: monsters } = useCampaignMonsters(campaignId);
|
||||
const { data: weapons } = useCampaignWeapons(campaignId);
|
||||
const { data: spells } = useCampaignSpells(campaignId);
|
||||
const { data: notes } = useCampaignNotes(campaignId);
|
||||
|
||||
const createCharacter = useCreateCharacter(campaignId);
|
||||
const deleteCharacter = useDeleteCharacter(campaignId);
|
||||
const createEncounter = useCreateEncounter(campaignId);
|
||||
const createMonster = useCreateMonster(campaignId);
|
||||
const deleteMonster = useDeleteMonster(campaignId);
|
||||
const createWeapon = useCreateWeapon(campaignId);
|
||||
const createSpell = useCreateSpell(campaignId);
|
||||
const createNote = useCreateNote();
|
||||
const updateCampaign = useUpdateCampaign(campaignId);
|
||||
const regenerateInvite = useRegenerateInvite(campaignId);
|
||||
|
||||
const [newCharName, setNewCharName] = useState('');
|
||||
const [newEncounterName, setNewEncounterName] = useState('');
|
||||
const [noteBody, setNoteBody] = useState('');
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
const [showMonsterForm, setShowMonsterForm] = useState(false);
|
||||
const [showWeaponForm, setShowWeaponForm] = useState(false);
|
||||
const [showSpellForm, setShowSpellForm] = useState(false);
|
||||
|
||||
if (isLoading) return <Spinner label="Unrolling the campaign map…" />;
|
||||
if (error || !data) return <ErrorBanner message="Could not load this campaign." />;
|
||||
|
||||
const { campaign, members } = data;
|
||||
const isDM = campaign.role === 'DM';
|
||||
const myCharacters = characters?.filter((c) => c.userId === user?.id) || [];
|
||||
const partyCharacters = characters?.filter((c) => !isDM || c.userId !== user?.id) || [];
|
||||
|
||||
async function handleCreateCharacter(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
try {
|
||||
const character = await createCharacter.mutateAsync({ name: newCharName });
|
||||
setNewCharName('');
|
||||
navigate(`/characters/${character.id}/build`);
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateEncounter(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const encounter = await createEncounter.mutateAsync(newEncounterName || 'New Encounter');
|
||||
navigate(`/encounters/${encounter.id}`);
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateNote(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!noteBody.trim()) return;
|
||||
await createNote.mutateAsync({ campaignId, body: noteBody, visibility: 'SHARED' });
|
||||
setNoteBody('');
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1>{campaign.name}</h1>
|
||||
<p className="subtitle">{campaign.description}</p>
|
||||
</div>
|
||||
<span className={`badge ${isDM ? 'badge-dm' : 'badge-player'}`}>{isDM ? 'Dungeon Master' : 'Player'}</span>
|
||||
</div>
|
||||
|
||||
{isDM && (
|
||||
<div className="card">
|
||||
<div className="card-title">
|
||||
<span>Campaign Settings</span>
|
||||
<button className="btn btn-ghost" onClick={() => setShowSettings((s) => !s)}>
|
||||
{showSettings ? 'Hide' : 'Edit'}
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-row flex-wrap">
|
||||
<span className="badge">Invite code: <strong className="mono">{campaign.inviteCode}</strong></span>
|
||||
<button className="btn btn-ghost" onClick={() => regenerateInvite.mutate()}>
|
||||
Regenerate code
|
||||
</button>
|
||||
</div>
|
||||
{showSettings && (
|
||||
<form
|
||||
className="mt-md"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const form = e.target as HTMLFormElement;
|
||||
const fd = new FormData(form);
|
||||
updateCampaign.mutate({
|
||||
startingGold: Number(fd.get('startingGold')),
|
||||
startingItemCount: Number(fd.get('startingItemCount')),
|
||||
startingSpellCount: Number(fd.get('startingSpellCount')),
|
||||
skipMotivationRoll: fd.get('skipMotivationRoll') === 'on',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-3">
|
||||
<div className="field">
|
||||
<label>Starting gold</label>
|
||||
<input name="startingGold" type="number" min={0} defaultValue={campaign.startingGold} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Starting items</label>
|
||||
<input name="startingItemCount" type="number" min={0} defaultValue={campaign.startingItemCount} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Starting spells</label>
|
||||
<input name="startingSpellCount" type="number" min={0} defaultValue={campaign.startingSpellCount} />
|
||||
</div>
|
||||
</div>
|
||||
<label className="checkbox-row">
|
||||
<input type="checkbox" name="skipMotivationRoll" defaultChecked={campaign.skipMotivationRoll} />
|
||||
Skip the motivation roll for this campaign
|
||||
</label>
|
||||
<button type="submit" className="btn btn-primary mt-md" disabled={updateCampaign.isPending}>
|
||||
Save Settings
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<div className="mt-md">
|
||||
<div className="card-title" style={{ marginBottom: '0.4rem' }}>Party</div>
|
||||
<div className="flex-row flex-wrap">
|
||||
{members.map((m) => (
|
||||
<span key={m.userId} className={`badge ${m.role === 'DM' ? 'badge-dm' : 'badge-player'}`}>
|
||||
{m.displayName}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{formError && <div className="mt-md"><ErrorBanner message={formError} /></div>}
|
||||
|
||||
{!isDM && myCharacters.length > 0 && (
|
||||
<div className="mt-lg">
|
||||
<h2 style={{ fontSize: '1.1rem' }}>Your Character{myCharacters.length > 1 ? 's' : ''}</h2>
|
||||
{myCharacters.map((c) => (
|
||||
<CharacterRow key={c.id} character={c} isDM={false} onDelete={() => {}} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-lg">
|
||||
<div className="page-header" style={{ marginBottom: '0.75rem' }}>
|
||||
<h2 style={{ fontSize: '1.1rem', margin: 0 }}>{isDM ? 'Characters' : 'Rest of the Party'}</h2>
|
||||
</div>
|
||||
<form onSubmit={handleCreateCharacter} className="flex-row flex-wrap mt-sm" style={{ marginBottom: '0.75rem' }}>
|
||||
<input
|
||||
placeholder="New character name"
|
||||
value={newCharName}
|
||||
onChange={(e) => setNewCharName(e.target.value)}
|
||||
style={{ flex: 1, minWidth: 160 }}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary" disabled={!newCharName || createCharacter.isPending}>
|
||||
Roll a New Character
|
||||
</button>
|
||||
</form>
|
||||
{(isDM ? characters : partyCharacters)?.length === 0 && (
|
||||
<div className="empty-state">No characters yet. Roll one up above.</div>
|
||||
)}
|
||||
{(isDM ? characters : partyCharacters)?.map((c) => (
|
||||
<CharacterRow
|
||||
key={c.id}
|
||||
character={c}
|
||||
isDM={isDM}
|
||||
onDelete={() => window.confirm(`Delete ${c.name}?`) && deleteCharacter.mutate(c.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-lg">
|
||||
<div className="page-header" style={{ marginBottom: '0.75rem' }}>
|
||||
<h2 style={{ fontSize: '1.1rem', margin: 0 }}>Encounters</h2>
|
||||
</div>
|
||||
{isDM && (
|
||||
<form onSubmit={handleCreateEncounter} className="flex-row flex-wrap" style={{ marginBottom: '0.75rem' }}>
|
||||
<input
|
||||
placeholder="Encounter name"
|
||||
value={newEncounterName}
|
||||
onChange={(e) => setNewEncounterName(e.target.value)}
|
||||
style={{ flex: 1, minWidth: 160 }}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary" disabled={createEncounter.isPending}>
|
||||
⚔ 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>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{isDM && (
|
||||
<>
|
||||
<div className="mt-lg card">
|
||||
<div className="card-title">
|
||||
<span>Weapons Pool</span>
|
||||
<button className="btn btn-ghost" onClick={() => setShowWeaponForm((s) => !s)}>
|
||||
{showWeaponForm ? 'Close' : '+ Add Weapon'}
|
||||
</button>
|
||||
</div>
|
||||
{showWeaponForm && (
|
||||
<form
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.target as HTMLFormElement);
|
||||
await createWeapon.mutateAsync({
|
||||
name: String(fd.get('name')),
|
||||
damageDice: String(fd.get('damageDice')),
|
||||
damageType: String(fd.get('damageType')),
|
||||
attackAbility: fd.get('attackAbility') as 'STR' | 'DEX' | 'FINESSE',
|
||||
properties: [],
|
||||
rangeNormal: null,
|
||||
rangeLong: null,
|
||||
});
|
||||
(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="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>
|
||||
<button type="submit" className="btn btn-primary">Add</button>
|
||||
</form>
|
||||
)}
|
||||
<div className="mt-sm flex-row flex-wrap">
|
||||
{weapons?.map((w) => (
|
||||
<span key={w.id} className="badge">{w.name} ({w.damageDice})</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-md card">
|
||||
<div className="card-title">
|
||||
<span>Spell List</span>
|
||||
<button className="btn btn-ghost" onClick={() => setShowSpellForm((s) => !s)}>
|
||||
{showSpellForm ? 'Close' : '+ Add Spell'}
|
||||
</button>
|
||||
</div>
|
||||
{showSpellForm && (
|
||||
<form
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.target as HTMLFormElement);
|
||||
await createSpell.mutateAsync({
|
||||
name: String(fd.get('name')),
|
||||
level: Number(fd.get('level')),
|
||||
school: String(fd.get('school') || '') || null,
|
||||
castingTime: null,
|
||||
range: null,
|
||||
duration: null,
|
||||
description: null,
|
||||
});
|
||||
(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 />
|
||||
<input name="school" placeholder="School" />
|
||||
<button type="submit" className="btn btn-primary">Add</button>
|
||||
</form>
|
||||
)}
|
||||
<div className="mt-sm flex-row flex-wrap">
|
||||
{spells?.map((s) => (
|
||||
<span key={s.id} className="badge">{s.name} (Lv{s.level})</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-md card">
|
||||
<div className="card-title">
|
||||
<span>Monsters</span>
|
||||
<button className="btn btn-ghost" onClick={() => setShowMonsterForm((s) => !s)}>
|
||||
{showMonsterForm ? 'Close' : '+ Add Monster'}
|
||||
</button>
|
||||
</div>
|
||||
{showMonsterForm && (
|
||||
<form
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.target as HTMLFormElement);
|
||||
await createMonster.mutateAsync({
|
||||
name: String(fd.get('name')),
|
||||
ac: Number(fd.get('ac')),
|
||||
maxHp: Number(fd.get('maxHp')),
|
||||
speed: 30,
|
||||
strScore: 10,
|
||||
dexScore: 10,
|
||||
conScore: 10,
|
||||
intScore: 10,
|
||||
wisScore: 10,
|
||||
chaScore: 10,
|
||||
attackBonus: Number(fd.get('attackBonus') || 0),
|
||||
damageDice: String(fd.get('damageDice') || '') || null,
|
||||
challengeRating: null,
|
||||
specialTrait: null,
|
||||
notes: null,
|
||||
});
|
||||
(e.target as HTMLFormElement).reset();
|
||||
}}
|
||||
className="grid grid-cols-3"
|
||||
>
|
||||
<input name="name" placeholder="Name" required />
|
||||
<input name="ac" type="number" placeholder="AC" required />
|
||||
<input name="maxHp" type="number" placeholder="Max HP" required />
|
||||
<input name="attackBonus" type="number" placeholder="Attack bonus" />
|
||||
<input name="damageDice" placeholder="Damage dice" />
|
||||
<button type="submit" className="btn btn-primary">Add</button>
|
||||
</form>
|
||||
)}
|
||||
<div className="mt-sm">
|
||||
{monsters?.map((m) => (
|
||||
<div key={m.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
|
||||
<span>{m.name} — AC {m.ac}, HP {m.maxHp}</span>
|
||||
<button className="btn btn-ghost" onClick={() => deleteMonster.mutate(m.id)}>✕</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="mt-lg card">
|
||||
<div className="card-title">Campaign Notes</div>
|
||||
<form onSubmit={handleCreateNote} className="flex-row flex-wrap">
|
||||
<textarea
|
||||
placeholder="Add a shared note for the party…"
|
||||
rows={2}
|
||||
value={noteBody}
|
||||
onChange={(e) => setNoteBody(e.target.value)}
|
||||
style={{ flex: 1, minWidth: 200 }}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary">Add Note</button>
|
||||
</form>
|
||||
<div className="mt-sm">
|
||||
{notes?.length === 0 && <p style={{ color: 'var(--text-muted)' }}>No notes yet.</p>}
|
||||
{notes?.map((n) => (
|
||||
<div key={n.id} style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--border-soft)' }}>
|
||||
<p style={{ margin: 0 }}>{n.body}</p>
|
||||
<span style={{ fontSize: '0.75rem', color: 'var(--text-dim)' }}>
|
||||
— {n.author?.displayName} · {new Date(n.createdAt).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useCampaigns, useCreateCampaign, useJoinCampaign } from '../api/queries';
|
||||
import { Spinner, ErrorBanner } from '../components/Spinner';
|
||||
import { extractErrorMessage } from '../lib/format';
|
||||
|
||||
export function CampaignListPage() {
|
||||
const { data: campaigns, isLoading, error } = useCampaigns();
|
||||
const createCampaign = useCreateCampaign();
|
||||
const joinCampaign = useJoinCampaign();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [inviteCode, setInviteCode] = useState('');
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
async function handleCreate(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
try {
|
||||
const campaign = await createCampaign.mutateAsync({ name, description: description || undefined });
|
||||
navigate(`/campaigns/${campaign.id}`);
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleJoin(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
try {
|
||||
const campaign = await joinCampaign.mutateAsync(inviteCode.trim().toUpperCase());
|
||||
navigate(`/campaigns/${campaign.id}`);
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1>Your Campaigns</h1>
|
||||
<p className="subtitle">The tales you're telling, and the ones you're living.</p>
|
||||
</div>
|
||||
<button className="btn btn-primary" onClick={() => setShowCreate((s) => !s)}>
|
||||
{showCreate ? 'Cancel' : '+ New Campaign'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showCreate && (
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Found a New Campaign</div>
|
||||
<form onSubmit={handleCreate}>
|
||||
<div className="field">
|
||||
<label htmlFor="name">Campaign name</label>
|
||||
<input id="name" required value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="description">Description (optional)</label>
|
||||
<textarea id="description" rows={3} value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</div>
|
||||
{formError && <ErrorBanner message={formError} />}
|
||||
<button type="submit" className="btn btn-primary" disabled={createCampaign.isPending}>
|
||||
{createCampaign.isPending ? 'Founding…' : 'Found Campaign'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Join With an Invite Code</div>
|
||||
<form onSubmit={handleJoin} className="flex-row flex-wrap">
|
||||
<input
|
||||
placeholder="e.g. AB3XQ9"
|
||||
value={inviteCode}
|
||||
onChange={(e) => setInviteCode(e.target.value)}
|
||||
style={{ flex: 1, minWidth: 160, textTransform: 'uppercase' }}
|
||||
/>
|
||||
<button type="submit" className="btn" disabled={joinCampaign.isPending || !inviteCode}>
|
||||
{joinCampaign.isPending ? 'Joining…' : 'Join'}
|
||||
</button>
|
||||
</form>
|
||||
{formError && <div className="mt-sm"><ErrorBanner message={formError} /></div>}
|
||||
</div>
|
||||
|
||||
<div className="mt-lg">
|
||||
{isLoading && <Spinner label="Consulting the tavern board…" />}
|
||||
{error && <ErrorBanner message="Could not load your campaigns." />}
|
||||
{campaigns && campaigns.length === 0 && (
|
||||
<div className="empty-state">No campaigns yet — found one, or join with an invite code above.</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2">
|
||||
{campaigns?.map((c) => (
|
||||
<Link key={c.id} to={`/campaigns/${c.id}`} className="card" style={{ display: 'block' }}>
|
||||
<div className="card-title">
|
||||
<span>{c.name}</span>
|
||||
<span className={`badge ${c.role === 'DM' ? 'badge-dm' : 'badge-player'}`}>{c.role}</span>
|
||||
</div>
|
||||
<p style={{ color: 'var(--text-muted)', margin: 0 }}>{c.description || 'No description yet.'}</p>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useBuildChoose, useBuildFinalize, useBuildRoll, useCampaign, useCampaignSpells, useCampaignWeapons, useCharacter } from '../api/queries';
|
||||
import { Spinner, ErrorBanner } from '../components/Spinner';
|
||||
import { ABILITY_LABELS, CLASS_LABELS, SKILL_LABELS, SPECIES_LABELS, extractErrorMessage } from '../lib/format';
|
||||
import { abilityModifier, speciesBonusFor } from '../lib/speciesData';
|
||||
import { CLASS_SPELLCASTING_ABILITY } from '../lib/classData';
|
||||
import type { Ability, CharacterClass, Species } from '../api/types';
|
||||
|
||||
interface SpeciesChoices {
|
||||
type: 'choice' | 'wildcard';
|
||||
options: string[];
|
||||
}
|
||||
interface ClassChoices {
|
||||
type: 'choice' | 'wildcard' | 'reroll';
|
||||
options: string[];
|
||||
}
|
||||
interface AbilityRoll {
|
||||
dice: number[];
|
||||
dropped: number;
|
||||
total: number;
|
||||
}
|
||||
interface BuildState {
|
||||
speciesRoll?: number;
|
||||
speciesChoices?: SpeciesChoices;
|
||||
species?: Species;
|
||||
halfElfBonusAbilities?: Ability[];
|
||||
classRoll?: number;
|
||||
classChoices?: ClassChoices;
|
||||
characterClass?: CharacterClass;
|
||||
motivationRoll?: number;
|
||||
motivationText?: string | null;
|
||||
abilityRolls?: AbilityRoll[];
|
||||
abilityAssignments?: Record<Ability, number>;
|
||||
skillProficiencies?: { skill: string; proficient: boolean; expertise: boolean }[];
|
||||
equipment?: { weaponIds: string[]; spellIds: string[] };
|
||||
}
|
||||
|
||||
const ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA'];
|
||||
const HALF_ELF_ELIGIBLE: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS'];
|
||||
const ALL_SKILLS = Object.keys(SKILL_LABELS);
|
||||
|
||||
export function CharacterBuilderPage() {
|
||||
const { characterId = '' } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { data: character, isLoading, error } = useCharacter(characterId);
|
||||
const roll = useBuildRoll(characterId);
|
||||
const choose = useBuildChoose(characterId);
|
||||
const finalize = useBuildFinalize(characterId);
|
||||
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [halfElfPick, setHalfElfPick] = useState<Ability[]>([]);
|
||||
const [pendingSpecies, setPendingSpecies] = useState<Species | null>(null);
|
||||
const [assignments, setAssignments] = useState<Partial<Record<Ability, number>>>({});
|
||||
const [skillPicks, setSkillPicks] = useState<Record<string, boolean>>({});
|
||||
const [expertisePicks, setExpertisePicks] = useState<Record<string, boolean>>({});
|
||||
const [equipWeapons, setEquipWeapons] = useState<string[]>([]);
|
||||
const [equipSpells, setEquipSpells] = useState<string[]>([]);
|
||||
|
||||
const campaignId = character?.campaignId;
|
||||
const { data: campaignData } = useCampaign(campaignId);
|
||||
const { data: weapons } = useCampaignWeapons(campaignId);
|
||||
const { data: spells } = useCampaignSpells(campaignId);
|
||||
|
||||
if (isLoading) return <Spinner label="Preparing the dice…" />;
|
||||
if (error || !character) return <ErrorBanner message="Could not load this character." />;
|
||||
|
||||
if (character.buildStage === 'COMPLETE') {
|
||||
navigate(`/characters/${characterId}`, { replace: true });
|
||||
return null;
|
||||
}
|
||||
|
||||
const bs = (character.buildState || {}) as BuildState;
|
||||
const stage = character.buildStage;
|
||||
|
||||
async function safeRoll() {
|
||||
setFormError(null);
|
||||
try {
|
||||
await roll.mutateAsync();
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function safeChoose(body: Record<string, unknown>) {
|
||||
setFormError(null);
|
||||
try {
|
||||
await choose.mutateAsync(body);
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1>Rolling Up {character.name}</h1>
|
||||
<p className="subtitle">Roll the dice at the table — every result is locked in server-side.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BuildProgress stage={stage} />
|
||||
|
||||
{formError && <ErrorBanner message={formError} />}
|
||||
|
||||
{stage === 'ROLLING_SPECIES' && (
|
||||
<div className="card mt-md text-center">
|
||||
<div className="card-title">Step 1 — Species</div>
|
||||
{!bs.speciesRoll ? (
|
||||
<>
|
||||
<p>Roll a d6 to see which species you can choose between.</p>
|
||||
<button className="btn-roll" onClick={safeRoll} disabled={roll.isPending}>
|
||||
🎲 Roll d6
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="roll-result animate">{bs.speciesRoll}</div>
|
||||
<p className="mt-sm">
|
||||
{bs.speciesChoices?.type === 'wildcard' ? 'Wildcard! Pick any species:' : 'Choose your species:'}
|
||||
</p>
|
||||
<div className="flex-row flex-wrap" style={{ justifyContent: 'center' }}>
|
||||
{bs.speciesChoices?.options.map((s) => (
|
||||
<button
|
||||
key={s}
|
||||
className={`btn ${pendingSpecies === s ? 'btn-primary' : ''}`}
|
||||
onClick={() => {
|
||||
setPendingSpecies(s as Species);
|
||||
setHalfElfPick([]);
|
||||
if (s !== 'HALF_ELF') safeChoose({ species: s });
|
||||
}}
|
||||
>
|
||||
{SPECIES_LABELS[s]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{pendingSpecies === 'HALF_ELF' && (
|
||||
<div className="card mt-md" style={{ textAlign: 'left' }}>
|
||||
<p>Half-Elf gets a fixed +2 CHA, plus +1/+1 to two other abilities of your choice:</p>
|
||||
<div className="flex-row flex-wrap">
|
||||
{HALF_ELF_ELIGIBLE.map((a) => (
|
||||
<label key={a} className="checkbox-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={halfElfPick.includes(a)}
|
||||
disabled={!halfElfPick.includes(a) && halfElfPick.length >= 2}
|
||||
onChange={(e) =>
|
||||
setHalfElfPick((prev) =>
|
||||
e.target.checked ? [...prev, a] : prev.filter((x) => x !== a)
|
||||
)
|
||||
}
|
||||
/>
|
||||
{ABILITY_LABELS[a]}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
className="btn btn-primary mt-sm"
|
||||
disabled={halfElfPick.length !== 2}
|
||||
onClick={() => safeChoose({ species: 'HALF_ELF', halfElfBonusAbilities: halfElfPick })}
|
||||
>
|
||||
Confirm Half-Elf
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'ROLLING_CLASS' && (
|
||||
<div className="card mt-md text-center">
|
||||
<div className="card-title">Step 2 — Class</div>
|
||||
{!bs.classRoll || bs.classChoices?.type === 'reroll' ? (
|
||||
<>
|
||||
{bs.classChoices?.type === 'reroll' && (
|
||||
<div className="roll-result animate mb-2">{bs.classRoll}</div>
|
||||
)}
|
||||
<p>{bs.classChoices?.type === 'reroll' ? 'You rolled a 7 — reroll once!' : 'Roll a d8 to see which classes you can choose between.'}</p>
|
||||
<button className="btn-roll" onClick={safeRoll} disabled={roll.isPending}>
|
||||
🎲 Roll d8
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="roll-result animate">{bs.classRoll}</div>
|
||||
<p className="mt-sm">
|
||||
{bs.classChoices?.type === 'wildcard' ? 'Wildcard! Pick any class:' : 'Choose your class:'}
|
||||
</p>
|
||||
<div className="flex-row flex-wrap" style={{ justifyContent: 'center' }}>
|
||||
{bs.classChoices?.options.map((c) => (
|
||||
<button key={c} className="btn" onClick={() => safeChoose({ characterClass: c })}>
|
||||
{CLASS_LABELS[c]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'ROLLING_MOTIVATION' && (
|
||||
<div className="card mt-md text-center">
|
||||
<div className="card-title">Step 3 — Motivation (Flavor)</div>
|
||||
{!bs.motivationRoll ? (
|
||||
<>
|
||||
<p>Roll a d6 for your character's driving motivation.</p>
|
||||
<button className="btn-roll" onClick={safeRoll} disabled={roll.isPending}>
|
||||
🎲 Roll d6
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="roll-result animate">{bs.motivationRoll}</div>
|
||||
<p className="mt-sm" style={{ fontStyle: 'italic' }}>
|
||||
"{bs.motivationText}"
|
||||
</p>
|
||||
<button className="btn btn-primary mt-sm" onClick={() => safeChoose({})}>
|
||||
Confirm & Continue
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'ASSIGNING_SCORES' && (
|
||||
<AssignScoresStep
|
||||
bs={bs}
|
||||
assignments={assignments}
|
||||
setAssignments={setAssignments}
|
||||
onRoll={safeRoll}
|
||||
onSubmit={() => safeChoose({ assignments })}
|
||||
rolling={roll.isPending}
|
||||
/>
|
||||
)}
|
||||
|
||||
{stage === 'ASSIGNING_PROFICIENCIES' && (
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Step 5 — Skill Proficiencies</div>
|
||||
<p className="subtitle">Saving throw proficiencies are fixed by class and were set automatically.</p>
|
||||
<div className="grid grid-cols-3">
|
||||
{ALL_SKILLS.map((skill) => (
|
||||
<label key={skill} className="checkbox-row" style={{ flexDirection: 'column', alignItems: 'flex-start', gap: 2 }}>
|
||||
<span className="flex-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(skillPicks[skill])}
|
||||
onChange={(e) => setSkillPicks((p) => ({ ...p, [skill]: e.target.checked }))}
|
||||
/>
|
||||
{SKILL_LABELS[skill]}
|
||||
</span>
|
||||
{skillPicks[skill] && (
|
||||
<span className="flex-row" style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginLeft: '1.5rem' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(expertisePicks[skill])}
|
||||
onChange={(e) => setExpertisePicks((p) => ({ ...p, [skill]: e.target.checked }))}
|
||||
/>
|
||||
expertise
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
className="btn btn-primary mt-md"
|
||||
onClick={() =>
|
||||
safeChoose({
|
||||
skillProficiencies: ALL_SKILLS.filter((s) => skillPicks[s]).map((s) => ({
|
||||
skill: s,
|
||||
proficient: true,
|
||||
expertise: Boolean(expertisePicks[s]),
|
||||
})),
|
||||
})
|
||||
}
|
||||
>
|
||||
Confirm Skills
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'CHOOSING_EQUIPMENT' && (
|
||||
<EquipmentStep
|
||||
bs={bs}
|
||||
campaignData={campaignData}
|
||||
weapons={weapons}
|
||||
spells={spells}
|
||||
equipWeapons={equipWeapons}
|
||||
setEquipWeapons={setEquipWeapons}
|
||||
equipSpells={equipSpells}
|
||||
setEquipSpells={setEquipSpells}
|
||||
onSubmit={() => safeChoose({ weaponIds: equipWeapons, spellIds: equipSpells })}
|
||||
onFinalize={async () => {
|
||||
try {
|
||||
const finalized = await finalize.mutateAsync();
|
||||
navigate(`/characters/${finalized.id}`);
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}}
|
||||
finalizing={finalize.isPending}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BuildProgress({ stage }: { stage: string }) {
|
||||
const steps = ['ROLLING_SPECIES', 'ROLLING_CLASS', 'ROLLING_MOTIVATION', 'ASSIGNING_SCORES', 'ASSIGNING_PROFICIENCIES', 'CHOOSING_EQUIPMENT'];
|
||||
const idx = steps.indexOf(stage);
|
||||
return (
|
||||
<div className="flex-row flex-wrap gap-sm">
|
||||
{steps.map((s, i) => (
|
||||
<span key={s} className="badge" style={i <= idx ? { borderColor: 'var(--accent)', color: 'var(--accent-strong)' } : undefined}>
|
||||
{i + 1}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AssignScoresStep({
|
||||
bs,
|
||||
assignments,
|
||||
setAssignments,
|
||||
onRoll,
|
||||
onSubmit,
|
||||
rolling,
|
||||
}: {
|
||||
bs: BuildState;
|
||||
assignments: Partial<Record<Ability, number>>;
|
||||
setAssignments: (a: Partial<Record<Ability, number>>) => void;
|
||||
onRoll: () => void;
|
||||
onSubmit: () => void;
|
||||
rolling: boolean;
|
||||
}) {
|
||||
if (!bs.abilityRolls) {
|
||||
return (
|
||||
<div className="card mt-md text-center">
|
||||
<div className="card-title">Step 4 — Ability Scores</div>
|
||||
<p>Roll 4d6 (drop the lowest) six times — one set per ability.</p>
|
||||
<button className="btn-roll" onClick={onRoll} disabled={rolling}>
|
||||
🎲 Roll Ability Scores
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const usedIndexes = new Set(Object.values(assignments));
|
||||
const species = bs.species ?? null;
|
||||
const halfElfBonusAbilities = bs.halfElfBonusAbilities || [];
|
||||
const complete = ABILITIES.every((a) => assignments[a] !== undefined) && usedIndexes.size === 6;
|
||||
|
||||
return (
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Step 4 — Assign Ability Scores</div>
|
||||
<div className="flex-row flex-wrap gap-sm mt-sm">
|
||||
{bs.abilityRolls.map((r, i) => (
|
||||
<span key={i} className="badge" style={usedIndexes.has(i) ? { opacity: 0.4 } : { borderColor: 'var(--accent)' }}>
|
||||
{r.dice.join('+')} (drop {r.dropped}) = {r.total}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-3 mt-md">
|
||||
{ABILITIES.map((ability) => {
|
||||
const assignedIndex = assignments[ability];
|
||||
const rolledTotal = assignedIndex !== undefined ? bs.abilityRolls![assignedIndex].total : null;
|
||||
const bonus = speciesBonusFor(species, ability, halfElfBonusAbilities);
|
||||
const final = rolledTotal !== null ? rolledTotal + bonus : null;
|
||||
return (
|
||||
<div className="stat-block" key={ability}>
|
||||
<span className="stat-label">{ABILITY_LABELS[ability]}</span>
|
||||
<select
|
||||
value={assignedIndex ?? ''}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value === '' ? undefined : Number(e.target.value);
|
||||
const next = { ...assignments };
|
||||
if (val === undefined) delete next[ability];
|
||||
else next[ability] = val;
|
||||
setAssignments(next);
|
||||
}}
|
||||
>
|
||||
<option value="">—</option>
|
||||
{bs.abilityRolls!.map((r, i) => (
|
||||
<option key={i} value={i} disabled={usedIndexes.has(i) && assignedIndex !== i}>
|
||||
{r.total}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{final !== null && (
|
||||
<span className="stat-sub">
|
||||
{rolledTotal} {bonus ? `+${bonus}` : ''} = {final} ({abilityModifier(final) >= 0 ? '+' : ''}
|
||||
{abilityModifier(final)})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<button className="btn btn-primary mt-md" disabled={!complete} onClick={onSubmit}>
|
||||
Confirm Ability Scores
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EquipmentStep({
|
||||
bs,
|
||||
campaignData,
|
||||
weapons,
|
||||
spells,
|
||||
equipWeapons,
|
||||
setEquipWeapons,
|
||||
equipSpells,
|
||||
setEquipSpells,
|
||||
onSubmit,
|
||||
onFinalize,
|
||||
finalizing,
|
||||
}: {
|
||||
bs: BuildState;
|
||||
campaignData: { campaign: { startingItemCount: number; startingSpellCount: number } } | undefined;
|
||||
weapons: { id: string; name: string; damageDice: string }[] | undefined;
|
||||
spells: { id: string; name: string; level: number }[] | undefined;
|
||||
equipWeapons: string[];
|
||||
setEquipWeapons: (ids: string[]) => void;
|
||||
equipSpells: string[];
|
||||
setEquipSpells: (ids: string[]) => void;
|
||||
onSubmit: () => void;
|
||||
onFinalize: () => void;
|
||||
finalizing: boolean;
|
||||
}) {
|
||||
const maxItems = campaignData?.campaign.startingItemCount ?? 0;
|
||||
const maxSpells = campaignData?.campaign.startingSpellCount ?? 0;
|
||||
const hasSpellcasting = bs.characterClass ? Boolean(CLASS_SPELLCASTING_ABILITY[bs.characterClass]) : false;
|
||||
const chosen = Boolean(bs.equipment);
|
||||
|
||||
function toggle(list: string[], set: (ids: string[]) => void, id: string, max: number) {
|
||||
if (list.includes(id)) set(list.filter((x) => x !== id));
|
||||
else if (list.length < max) set([...list, id]);
|
||||
}
|
||||
|
||||
if (chosen) {
|
||||
return (
|
||||
<div className="card mt-md text-center">
|
||||
<div className="card-title">Step 7 — Finalize</div>
|
||||
<p>Equipment chosen. Ready to compute HP, AC, and lock in your character.</p>
|
||||
<button className="btn btn-primary btn-lg" onClick={onFinalize} disabled={finalizing}>
|
||||
{finalizing ? 'Finalizing…' : '✦ Finalize Character'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Step 6 — Starting Equipment</div>
|
||||
<p className="subtitle">
|
||||
Pick up to {maxItems} item{maxItems === 1 ? '' : 's'}
|
||||
{hasSpellcasting ? ` and up to ${maxSpells} spell${maxSpells === 1 ? '' : 's'}` : ''}.
|
||||
</p>
|
||||
<div className="flex-row flex-wrap">
|
||||
{weapons?.map((w) => (
|
||||
<label key={w.id} className="checkbox-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={equipWeapons.includes(w.id)}
|
||||
disabled={!equipWeapons.includes(w.id) && equipWeapons.length >= maxItems}
|
||||
onChange={() => toggle(equipWeapons, setEquipWeapons, w.id, maxItems)}
|
||||
/>
|
||||
{w.name} ({w.damageDice})
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{hasSpellcasting && (
|
||||
<>
|
||||
<div className="divider" />
|
||||
<div className="flex-row flex-wrap">
|
||||
{spells?.map((s) => (
|
||||
<label key={s.id} className="checkbox-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={equipSpells.includes(s.id)}
|
||||
disabled={!equipSpells.includes(s.id) && equipSpells.length >= maxSpells}
|
||||
onChange={() => toggle(equipSpells, setEquipSpells, s.id, maxSpells)}
|
||||
/>
|
||||
{s.name} (Lv {s.level})
|
||||
</label>
|
||||
))}
|
||||
{(!spells || spells.length === 0) && <p style={{ color: 'var(--text-muted)' }}>No spells in this campaign's list yet — the DM can add some.</p>}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<button className="btn btn-primary mt-md" onClick={onSubmit}>
|
||||
Confirm Equipment
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import {
|
||||
useCharacter,
|
||||
usePatchCharacter,
|
||||
useCampaignWeapons,
|
||||
useAssignWeapon,
|
||||
usePatchCharacterWeapon,
|
||||
useAddInventoryItem,
|
||||
usePatchInventoryItem,
|
||||
useDeleteInventoryItem,
|
||||
useCampaignSpells,
|
||||
useAssignSpell,
|
||||
usePatchCharacterSpell,
|
||||
useCharacterNotes,
|
||||
useCreateNote,
|
||||
useCampaign,
|
||||
} from '../api/queries';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import { useCampaignSocket } from '../hooks/useCampaignSocket';
|
||||
import { Spinner, ErrorBanner } from '../components/Spinner';
|
||||
import { QuickStatsFab } from '../components/QuickStatsDrawer';
|
||||
import { ABILITY_LABELS, CLASS_LABELS, SKILL_LABELS, SPECIES_LABELS, fmtMod, extractErrorMessage } from '../lib/format';
|
||||
import type { Ability } from '../api/types';
|
||||
|
||||
export function CharacterSheetPage() {
|
||||
const { characterId = '' } = useParams();
|
||||
const { user } = useAuth();
|
||||
const { data: character, isLoading, error } = useCharacter(characterId);
|
||||
const patchCharacter = usePatchCharacter(characterId);
|
||||
useCampaignSocket(character?.campaignId);
|
||||
|
||||
const { data: campaignData } = useCampaign(character?.campaignId);
|
||||
const { data: campaignWeapons } = useCampaignWeapons(character?.campaignId);
|
||||
const { data: campaignSpells } = useCampaignSpells(character?.campaignId);
|
||||
const { data: notes } = useCharacterNotes(characterId);
|
||||
|
||||
const assignWeapon = useAssignWeapon(characterId);
|
||||
const patchWeapon = usePatchCharacterWeapon(characterId);
|
||||
const addItem = useAddInventoryItem(characterId);
|
||||
const patchItem = usePatchInventoryItem(characterId);
|
||||
const deleteItem = useDeleteInventoryItem(characterId);
|
||||
const assignSpell = useAssignSpell(characterId);
|
||||
const patchSpell = usePatchCharacterSpell(characterId);
|
||||
const createNote = useCreateNote();
|
||||
|
||||
const [hpDelta, setHpDelta] = useState('');
|
||||
const [newItemName, setNewItemName] = useState('');
|
||||
const [noteBody, setNoteBody] = useState('');
|
||||
const [pickedWeaponId, setPickedWeaponId] = useState('');
|
||||
const [pickedSpellId, setPickedSpellId] = useState('');
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
if (isLoading) return <Spinner label="Unfurling the character sheet…" />;
|
||||
if (error || !character) return <ErrorBanner message="Could not load this character." />;
|
||||
|
||||
const isDM = campaignData?.campaign.role === 'DM';
|
||||
const isOwner = character.userId === user?.id;
|
||||
const canEdit = isDM || isOwner;
|
||||
|
||||
if (character.buildStage !== 'COMPLETE') {
|
||||
return (
|
||||
<div className="empty-state card">
|
||||
<p>{character.name} hasn't finished being built yet.</p>
|
||||
<Link to={`/characters/${characterId}/build`} className="btn btn-primary">
|
||||
Continue Build
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const sheet = character.sheet!;
|
||||
|
||||
function applyHpDelta(sign: 1 | -1) {
|
||||
const amount = Number(hpDelta);
|
||||
if (!amount) return;
|
||||
const next = character!.currentHp + sign * amount;
|
||||
patchCharacter.mutate({ currentHp: next });
|
||||
setHpDelta('');
|
||||
}
|
||||
|
||||
async function handleAddItem(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!newItemName.trim()) return;
|
||||
await addItem.mutateAsync({ name: newItemName });
|
||||
setNewItemName('');
|
||||
}
|
||||
|
||||
async function handleAddNote(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!noteBody.trim()) return;
|
||||
await createNote.mutateAsync({ characterId, body: noteBody, visibility: 'SHARED' });
|
||||
setNoteBody('');
|
||||
}
|
||||
|
||||
async function handleAssignWeapon() {
|
||||
if (!pickedWeaponId) return;
|
||||
try {
|
||||
await assignWeapon.mutateAsync({ weaponId: pickedWeaponId });
|
||||
setPickedWeaponId('');
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAssignSpell() {
|
||||
if (!pickedSpellId) return;
|
||||
try {
|
||||
await assignSpell.mutateAsync({ spellId: pickedSpellId });
|
||||
setPickedSpellId('');
|
||||
} catch (err) {
|
||||
setFormError(extractErrorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
const assignedWeaponIds = new Set(character.weapons.map((w) => w.weaponId));
|
||||
const assignedSpellIds = new Set(character.spells.map((s) => s.spellId));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1>{character.name}</h1>
|
||||
<p className="subtitle">
|
||||
{character.species && SPECIES_LABELS[character.species]} {character.characterClass && CLASS_LABELS[character.characterClass]} · Level{' '}
|
||||
{character.level}
|
||||
{character.motivation && ` · "${character.motivation}"`}
|
||||
</p>
|
||||
</div>
|
||||
<Link to={`/campaigns/${character.campaignId}`} className="btn btn-ghost">
|
||||
← Back to Campaign
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{formError && <ErrorBanner message={formError} />}
|
||||
|
||||
<div className="grid grid-cols-3">
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">HP</span>
|
||||
<span className="stat-value">
|
||||
{character.currentHp}/{sheet.hp.max}
|
||||
</span>
|
||||
{character.tempHp > 0 && <span className="stat-sub">+{character.tempHp} temp</span>}
|
||||
</div>
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">AC</span>
|
||||
<span className="stat-value">{sheet.armorClass}</span>
|
||||
</div>
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">Initiative</span>
|
||||
<span className="stat-value">{fmtMod(sheet.initiative)}</span>
|
||||
</div>
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">Speed</span>
|
||||
<span className="stat-value">{sheet.speed}</span>
|
||||
</div>
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">Prof. Bonus</span>
|
||||
<span className="stat-value">{fmtMod(sheet.proficiencyBonus)}</span>
|
||||
</div>
|
||||
<div className="stat-block">
|
||||
<span className="stat-label">Passive Perception</span>
|
||||
<span className="stat-value">{sheet.passivePerception}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="hp-bar-track mt-sm">
|
||||
<div className="hp-bar-fill" style={{ width: `${Math.max(0, Math.min(100, (character.currentHp / sheet.hp.max) * 100))}%` }} />
|
||||
</div>
|
||||
|
||||
{canEdit && (
|
||||
<div className="flex-row mt-sm flex-wrap">
|
||||
<input
|
||||
type="number"
|
||||
placeholder="Amount"
|
||||
value={hpDelta}
|
||||
onChange={(e) => setHpDelta(e.target.value)}
|
||||
style={{ width: 100 }}
|
||||
/>
|
||||
<button className="btn btn-danger" onClick={() => applyHpDelta(-1)}>
|
||||
− Damage
|
||||
</button>
|
||||
<button className="btn" onClick={() => applyHpDelta(1)}>
|
||||
+ Heal
|
||||
</button>
|
||||
<label className="flex-row gap-sm" style={{ marginLeft: '1rem' }}>
|
||||
Temp HP
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
defaultValue={character.tempHp}
|
||||
style={{ width: 70 }}
|
||||
onBlur={(e) => patchCharacter.mutate({ tempHp: Number(e.target.value) })}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex-row gap-sm">
|
||||
Armor Bonus
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
defaultValue={character.armorBonus}
|
||||
style={{ width: 70 }}
|
||||
onBlur={(e) => patchCharacter.mutate({ armorBonus: Number(e.target.value) })}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Ability Scores</div>
|
||||
<div className="grid grid-cols-3">
|
||||
{(Object.keys(sheet.abilities) as Ability[]).map((ability) => (
|
||||
<div className="stat-block" key={ability}>
|
||||
<span className="stat-label">{ABILITY_LABELS[ability]}</span>
|
||||
<span className="stat-value">{sheet.abilities[ability].final}</span>
|
||||
<span className="stat-sub">{fmtMod(sheet.abilities[ability].modifier)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 mt-md">
|
||||
<div className="card">
|
||||
<div className="card-title">Saving Throws</div>
|
||||
{(Object.keys(sheet.saves) as Ability[]).map((ability) => (
|
||||
<div key={ability} className="flex-between" style={{ padding: '0.3rem 0' }}>
|
||||
<span>
|
||||
{ABILITY_LABELS[ability]} {sheet.saves[ability].proficient && <span className="badge">prof</span>}
|
||||
</span>
|
||||
<span className="mono">{fmtMod(sheet.saves[ability].bonus)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-title">Skills</div>
|
||||
<div style={{ maxHeight: 320, overflowY: 'auto' }}>
|
||||
{Object.entries(sheet.skills).map(([skill, detail]) => (
|
||||
<div key={skill} className="flex-between" style={{ padding: '0.25rem 0' }}>
|
||||
<span>
|
||||
{SKILL_LABELS[skill]}{' '}
|
||||
{detail.expertise ? (
|
||||
<span className="badge badge-dm">expertise</span>
|
||||
) : detail.proficient ? (
|
||||
<span className="badge">prof</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="mono">{fmtMod(detail.bonus)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sheet.spellcasting && (
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Spellcasting ({ABILITY_LABELS[sheet.spellcasting.ability]})</div>
|
||||
<p style={{ margin: 0 }}>
|
||||
Save DC <strong>{sheet.spellcasting.saveDC}</strong> · Attack Bonus{' '}
|
||||
<strong>{fmtMod(sheet.spellcasting.attackBonus)}</strong>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Weapons</div>
|
||||
{character.weapons.map((cw) => (
|
||||
<div key={cw.id} className="flex-between" style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
|
||||
<div>
|
||||
<strong>{cw.weapon.name}</strong>
|
||||
<span style={{ color: 'var(--text-muted)', marginLeft: 6 }}>
|
||||
{cw.weapon.damageDice} {cw.weapon.damageType} · x{cw.quantity}
|
||||
</span>
|
||||
</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>
|
||||
))}
|
||||
{canEdit && (
|
||||
<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>
|
||||
{campaignWeapons
|
||||
?.filter((w) => !assignedWeaponIds.has(w.id))
|
||||
.map((w) => (
|
||||
<option key={w.id} value={w.id}>
|
||||
{w.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="btn" onClick={handleAssignWeapon} disabled={!pickedWeaponId}>
|
||||
Add
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{campaignSpells && campaignSpells.length > 0 && (
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Spells Known</div>
|
||||
{character.spells.map((cs) => (
|
||||
<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>
|
||||
</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>
|
||||
))}
|
||||
{canEdit && (
|
||||
<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>
|
||||
{campaignSpells
|
||||
.filter((s) => !assignedSpellIds.has(s.id))
|
||||
.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name} (Lv {s.level})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="btn" onClick={handleAssignSpell} disabled={!pickedSpellId}>
|
||||
Add
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Inventory</div>
|
||||
{character.inventoryItems.map((item) => (
|
||||
<div key={item.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>
|
||||
</div>
|
||||
{canEdit && (
|
||||
<div className="flex-row gap-sm">
|
||||
<label className="flex-row gap-sm">
|
||||
Equipped
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={item.equipped}
|
||||
onChange={(e) => patchItem.mutate({ itemId: item.id, equipped: e.target.checked })}
|
||||
/>
|
||||
</label>
|
||||
<button className="btn btn-ghost" onClick={() => deleteItem.mutate(item.id)}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{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
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{canEdit && (
|
||||
<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>
|
||||
)}
|
||||
|
||||
<div className="card mt-md">
|
||||
<div className="card-title">Notes</div>
|
||||
<form onSubmit={handleAddNote} className="flex-row flex-wrap">
|
||||
<textarea
|
||||
placeholder="Add a note…"
|
||||
rows={2}
|
||||
value={noteBody}
|
||||
onChange={(e) => setNoteBody(e.target.value)}
|
||||
style={{ flex: 1, minWidth: 200 }}
|
||||
/>
|
||||
<button type="submit" className="btn">
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
<div className="mt-sm">
|
||||
{notes?.map((n) => (
|
||||
<div key={n.id} style={{ padding: '0.4rem 0', borderBottom: '1px solid var(--border-soft)' }}>
|
||||
<p style={{ margin: 0 }}>{n.body}</p>
|
||||
<span style={{ fontSize: '0.75rem', color: 'var(--text-dim)' }}>
|
||||
— {n.author?.displayName} · {new Date(n.createdAt).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<QuickStatsFab characterId={characterId} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import {
|
||||
useEncounter,
|
||||
useCampaign,
|
||||
useCampaignCharacters,
|
||||
useCampaignMonsters,
|
||||
useAddParticipant,
|
||||
usePatchParticipant,
|
||||
useRemoveParticipant,
|
||||
useAdvanceRound,
|
||||
usePatchEncounter,
|
||||
} from '../api/queries';
|
||||
import { useCampaignSocket } from '../hooks/useCampaignSocket';
|
||||
import { Spinner, ErrorBanner } from '../components/Spinner';
|
||||
import { extractErrorMessage } from '../lib/format';
|
||||
import type { EncounterParticipant } from '../api/types';
|
||||
|
||||
function ParticipantRow({
|
||||
participant,
|
||||
isDM,
|
||||
onPatch,
|
||||
onRemove,
|
||||
}: {
|
||||
participant: EncounterParticipant;
|
||||
isDM: boolean;
|
||||
onPatch: (data: Partial<EncounterParticipant>) => void;
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
const [hpDelta, setHpDelta] = useState('');
|
||||
const pct = Math.max(0, Math.min(100, (participant.currentHp / participant.maxHp) * 100));
|
||||
|
||||
function applyDelta(sign: 1 | -1) {
|
||||
const amount = Number(hpDelta);
|
||||
if (!amount) return;
|
||||
onPatch({ currentHp: participant.currentHp + sign * amount });
|
||||
setHpDelta('');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<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="hp-bar-fill" 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>
|
||||
)}
|
||||
</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>
|
||||
)}
|
||||
{!isDM && participant.conditions.length > 0 && (
|
||||
<div className="flex-row flex-wrap mt-sm">
|
||||
{participant.conditions.map((c) => (
|
||||
<span key={c} className="badge">
|
||||
{c}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EncounterPage() {
|
||||
const { encounterId = '' } = useParams();
|
||||
const { data: encounter, isLoading, error } = useEncounter(encounterId);
|
||||
useCampaignSocket(encounter?.campaignId);
|
||||
|
||||
const { data: campaignData } = useCampaign(encounter?.campaignId);
|
||||
const { data: characters } = useCampaignCharacters(encounter?.campaignId);
|
||||
const { data: monsters } = useCampaignMonsters(encounter?.campaignId);
|
||||
|
||||
const addParticipant = useAddParticipant(encounterId);
|
||||
const patchParticipant = usePatchParticipant(encounterId);
|
||||
const removeParticipant = useRemoveParticipant(encounterId);
|
||||
const advanceRound = useAdvanceRound(encounterId);
|
||||
const patchEncounter = usePatchEncounter(encounterId);
|
||||
|
||||
const [pickType, setPickType] = useState<'character' | 'monster'>('character');
|
||||
const [pickId, setPickId] = useState('');
|
||||
const [initiative, setInitiative] = useState('0');
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
if (isLoading) return <Spinner label="Setting the battlefield…" />;
|
||||
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;
|
||||
|
||||
async 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));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1>⚔ {encounter.name}</h1>
|
||||
<p className="subtitle">
|
||||
{encounter.status} · Round {encounter.currentRound}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex-row">
|
||||
<Link to={`/campaigns/${encounter.campaignId}`} className="btn btn-ghost">
|
||||
← Campaign
|
||||
</Link>
|
||||
{isDM && (
|
||||
<>
|
||||
{encounter.status === 'PLANNING' && (
|
||||
<button className="btn btn-primary" onClick={() => patchEncounter.mutate({ status: 'ACTIVE' })}>
|
||||
Begin Combat
|
||||
</button>
|
||||
)}
|
||||
{encounter.status === 'ACTIVE' && (
|
||||
<>
|
||||
<button className="btn btn-primary" onClick={() => advanceRound.mutate()}>
|
||||
Advance Round
|
||||
</button>
|
||||
<button className="btn btn-danger" onClick={() => patchEncounter.mutate({ status: 'COMPLETE' })}>
|
||||
End Encounter
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{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 }}
|
||||
/>
|
||||
<button className="btn btn-primary" onClick={handleAdd} disabled={!pickId}>
|
||||
Add
|
||||
</button>
|
||||
</div>
|
||||
</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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { apiClient } from '../api/client';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import type { User } from '../api/types';
|
||||
import { extractErrorMessage } from '../lib/format';
|
||||
import { ErrorBanner } from '../components/Spinner';
|
||||
|
||||
export function LoginPage() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await apiClient.post<{ token: string; user: User }>('/auth/login', { email, password });
|
||||
login(res.data.token, res.data.user);
|
||||
navigate('/campaigns');
|
||||
} catch (err) {
|
||||
setError(extractErrorMessage(err));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-center" style={{ maxWidth: 420, margin: '3rem auto' }}>
|
||||
<h1>⚔ The Sunken Reach</h1>
|
||||
<p className="subtitle">Gather at the tavern table. Log in to continue your campaign.</p>
|
||||
<div className="card" style={{ textAlign: 'left', marginTop: '1.5rem' }}>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="field">
|
||||
<label htmlFor="email">Email</label>
|
||||
<input id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="password">Password</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error && <ErrorBanner message={error} />}
|
||||
<button type="submit" className="btn btn-primary btn-block btn-lg mt-md" disabled={submitting}>
|
||||
{submitting ? 'Entering…' : 'Enter the Tavern'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<p className="subtitle mt-md">
|
||||
New adventurer? <Link to="/register">Create an account</Link>
|
||||
</p>
|
||||
<p className="subtitle" style={{ fontSize: '0.8rem' }}>
|
||||
Demo: dm@example.com / player@example.com — password123
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { apiClient } from '../api/client';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import type { User } from '../api/types';
|
||||
import { extractErrorMessage } from '../lib/format';
|
||||
import { ErrorBanner } from '../components/Spinner';
|
||||
|
||||
export function RegisterPage() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [displayName, setDisplayName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await apiClient.post<{ token: string; user: User }>('/auth/register', {
|
||||
displayName,
|
||||
email,
|
||||
password,
|
||||
});
|
||||
login(res.data.token, res.data.user);
|
||||
navigate('/campaigns');
|
||||
} catch (err) {
|
||||
setError(extractErrorMessage(err));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-center" style={{ maxWidth: 420, margin: '3rem auto' }}>
|
||||
<h1>Create Your Legend</h1>
|
||||
<p className="subtitle">Every hero needs a name before the dice are rolled.</p>
|
||||
<div className="card" style={{ textAlign: 'left', marginTop: '1.5rem' }}>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="field">
|
||||
<label htmlFor="displayName">Display name</label>
|
||||
<input
|
||||
id="displayName"
|
||||
type="text"
|
||||
required
|
||||
value={displayName}
|
||||
onChange={(e) => setDisplayName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="email">Email</label>
|
||||
<input id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="password">Password</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
required
|
||||
minLength={8}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error && <ErrorBanner message={error} />}
|
||||
<button type="submit" className="btn btn-primary btn-block btn-lg mt-md" disabled={submitting}>
|
||||
{submitting ? 'Forging…' : 'Begin Your Legend'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<p className="subtitle mt-md">
|
||||
Already have an account? <Link to="/login">Log in</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
Reference in New Issue
Block a user