Implement the 021-bestiary-statblock feature that adds a searchable D&D 2024 Monster Manual creature library with inline autocomplete suggestions, full stat block display in a fixed side panel, auto-numbering of duplicate creature names, HP/AC pre-fill from bestiary data, and automatic stat block display on turn change for wide viewports
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
62
apps/web/src/hooks/use-bestiary.ts
Normal file
62
apps/web/src/hooks/use-bestiary.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { Creature, CreatureId } from "@initiative/domain";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { normalizeBestiary } from "../adapters/bestiary-adapter.js";
|
||||
|
||||
interface BestiaryHook {
|
||||
search: (query: string) => Creature[];
|
||||
getCreature: (id: CreatureId) => Creature | undefined;
|
||||
allCreatures: Creature[];
|
||||
isLoaded: boolean;
|
||||
}
|
||||
|
||||
export function useBestiary(): BestiaryHook {
|
||||
const [creatures, setCreatures] = useState<Creature[]>([]);
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
const creatureMapRef = useRef<Map<string, Creature>>(new Map());
|
||||
const loadAttempted = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (loadAttempted.current) return;
|
||||
loadAttempted.current = true;
|
||||
|
||||
import("../../../../data/bestiary/xmm.json")
|
||||
// biome-ignore lint/suspicious/noExplicitAny: raw JSON shape varies per entry
|
||||
.then((mod: any) => {
|
||||
const raw = mod.default ?? mod;
|
||||
try {
|
||||
const normalized = normalizeBestiary(raw);
|
||||
const map = new Map<string, Creature>();
|
||||
for (const c of normalized) {
|
||||
map.set(c.id, c);
|
||||
}
|
||||
creatureMapRef.current = map;
|
||||
setCreatures(normalized);
|
||||
setIsLoaded(true);
|
||||
} catch {
|
||||
// Normalization failed — bestiary unavailable
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// Import failed — bestiary unavailable
|
||||
});
|
||||
}, []);
|
||||
|
||||
const search = useMemo(() => {
|
||||
return (query: string): Creature[] => {
|
||||
if (query.length < 2) return [];
|
||||
const lower = query.toLowerCase();
|
||||
return creatures
|
||||
.filter((c) => c.name.toLowerCase().includes(lower))
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.slice(0, 10);
|
||||
};
|
||||
}, [creatures]);
|
||||
|
||||
const getCreature = useMemo(() => {
|
||||
return (id: CreatureId): Creature | undefined => {
|
||||
return creatureMapRef.current.get(id);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { search, getCreature, allCreatures: creatures, isLoaded };
|
||||
}
|
||||
Reference in New Issue
Block a user