Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e44e56b09b |
@@ -116,7 +116,6 @@ export function createTestAdapters(options?: {
|
|||||||
`https://example.com/creatures-${sourceCode.toLowerCase()}.json`,
|
`https://example.com/creatures-${sourceCode.toLowerCase()}.json`,
|
||||||
getSourceDisplayName: (sourceCode) => sourceCode,
|
getSourceDisplayName: (sourceCode) => sourceCode,
|
||||||
getCreaturePathsForSource: () => [],
|
getCreaturePathsForSource: () => [],
|
||||||
getCreatureNamesByPaths: () => new Map(),
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -131,39 +131,6 @@ describe("normalizeFoundryCreature", () => {
|
|||||||
);
|
);
|
||||||
expect(creature.senses).toBe("Scent 60 feet");
|
expect(creature.senses).toBe("Scent 60 feet");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("extracts perception details", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
system: {
|
|
||||||
...minimalCreature().system,
|
|
||||||
perception: {
|
|
||||||
mod: 35,
|
|
||||||
details: "smoke vision",
|
|
||||||
senses: [{ type: "darkvision" }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(creature.perceptionDetails).toBe("smoke vision");
|
|
||||||
expect(creature.senses).toBe("Darkvision");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("omits perception details when empty", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
system: {
|
|
||||||
...minimalCreature().system,
|
|
||||||
perception: {
|
|
||||||
mod: 8,
|
|
||||||
details: "",
|
|
||||||
senses: [{ type: "darkvision" }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(creature.perceptionDetails).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("languages formatting", () => {
|
describe("languages formatting", () => {
|
||||||
@@ -419,101 +386,6 @@ describe("normalizeFoundryCreature", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("includes attack effects in damage text", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
_id: "atk1",
|
|
||||||
name: "talon",
|
|
||||||
type: "melee",
|
|
||||||
system: {
|
|
||||||
bonus: { value: 14 },
|
|
||||||
damageRolls: {
|
|
||||||
abc: {
|
|
||||||
damage: "1d10+6",
|
|
||||||
damageType: "piercing",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
traits: { value: [] },
|
|
||||||
attackEffects: { value: ["grab"] },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const attack = creature.attacks?.[0];
|
|
||||||
expect(attack?.segments[0]).toEqual({
|
|
||||||
type: "text",
|
|
||||||
value: "+14, 1d10+6 piercing plus Grab",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("joins multiple attack effects with 'and'", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
_id: "atk1",
|
|
||||||
name: "claw",
|
|
||||||
type: "melee",
|
|
||||||
system: {
|
|
||||||
bonus: { value: 18 },
|
|
||||||
damageRolls: {
|
|
||||||
abc: {
|
|
||||||
damage: "2d8+6",
|
|
||||||
damageType: "slashing",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
traits: { value: [] },
|
|
||||||
attackEffects: {
|
|
||||||
value: ["grab", "knockdown"],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const attack = creature.attacks?.[0];
|
|
||||||
expect(attack?.segments[0]).toEqual({
|
|
||||||
type: "text",
|
|
||||||
value: "+18, 2d8+6 slashing plus Grab and Knockdown",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("strips creature-name prefix from attack effect slugs", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
name: "Lich",
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
_id: "atk1",
|
|
||||||
name: "hand",
|
|
||||||
type: "melee",
|
|
||||||
system: {
|
|
||||||
bonus: { value: 24 },
|
|
||||||
damageRolls: {
|
|
||||||
abc: {
|
|
||||||
damage: "2d12+7",
|
|
||||||
damageType: "negative",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
traits: { value: [] },
|
|
||||||
attackEffects: {
|
|
||||||
value: ["lich-siphon-life"],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const attack = creature.attacks?.[0];
|
|
||||||
expect(attack?.segments[0]).toEqual({
|
|
||||||
type: "text",
|
|
||||||
value: "+24, 2d12+7 negative plus Siphon Life",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("ability normalization", () => {
|
describe("ability normalization", () => {
|
||||||
@@ -667,114 +539,6 @@ describe("normalizeFoundryCreature", () => {
|
|||||||
: undefined,
|
: undefined,
|
||||||
).toBe("(Concentrate, Polymorph) Takes a new form.");
|
).toBe("(Concentrate, Polymorph) Takes a new form.");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("extracts frequency from ability", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
_id: "a1",
|
|
||||||
name: "Drain Soul Cage",
|
|
||||||
type: "action",
|
|
||||||
system: {
|
|
||||||
category: "offensive",
|
|
||||||
actionType: { value: "free" },
|
|
||||||
actions: { value: null },
|
|
||||||
traits: { value: [] },
|
|
||||||
description: { value: "<p>Drains the soul.</p>" },
|
|
||||||
frequency: { max: 1, per: "day" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(creature.abilitiesBot?.[0]?.frequency).toBe("1/day");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("strips redundant frequency line from description", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
_id: "a1",
|
|
||||||
name: "Consult the Text",
|
|
||||||
type: "action",
|
|
||||||
system: {
|
|
||||||
category: "offensive",
|
|
||||||
actionType: { value: "action" },
|
|
||||||
actions: { value: 1 },
|
|
||||||
traits: { value: [] },
|
|
||||||
description: {
|
|
||||||
value:
|
|
||||||
"<p><strong>Frequency</strong> once per day</p>\n<hr />\n<p><strong>Effect</strong> The lich opens their spell tome.</p>",
|
|
||||||
},
|
|
||||||
frequency: { max: 1, per: "day" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const text =
|
|
||||||
creature.abilitiesBot?.[0]?.segments[0]?.type === "text"
|
|
||||||
? creature.abilitiesBot[0].segments[0].value
|
|
||||||
: "";
|
|
||||||
expect(text).not.toContain("Frequency");
|
|
||||||
expect(text).toContain("The lich opens their spell tome.");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("strips frequency line even when preceded by other text", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
_id: "a1",
|
|
||||||
name: "Drain Soul Cage",
|
|
||||||
type: "action",
|
|
||||||
system: {
|
|
||||||
category: "offensive",
|
|
||||||
actionType: { value: "free" },
|
|
||||||
actions: { value: null },
|
|
||||||
traits: { value: [] },
|
|
||||||
description: {
|
|
||||||
value:
|
|
||||||
"<p>6th rank</p>\n<hr />\n<p><strong>Frequency</strong> once per day</p>\n<hr />\n<p><strong>Effect</strong> The lich taps into their soul cage.</p>",
|
|
||||||
},
|
|
||||||
frequency: { max: 1, per: "day" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const text =
|
|
||||||
creature.abilitiesBot?.[0]?.segments[0]?.type === "text"
|
|
||||||
? creature.abilitiesBot[0].segments[0].value
|
|
||||||
: "";
|
|
||||||
expect(text).not.toContain("Frequency");
|
|
||||||
expect(text).toContain("6th rank");
|
|
||||||
expect(text).toContain("The lich taps into their soul cage.");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("omits frequency when not present", () => {
|
|
||||||
const creature = normalizeFoundryCreature(
|
|
||||||
minimalCreature({
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
_id: "a1",
|
|
||||||
name: "Strike",
|
|
||||||
type: "action",
|
|
||||||
system: {
|
|
||||||
category: "offensive",
|
|
||||||
actionType: { value: "action" },
|
|
||||||
actions: { value: 1 },
|
|
||||||
traits: { value: [] },
|
|
||||||
description: { value: "<p>Strikes.</p>" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(creature.abilitiesBot?.[0]?.frequency).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("equipment normalization", () => {
|
describe("equipment normalization", () => {
|
||||||
@@ -1115,8 +879,7 @@ describe("normalizeFoundryCreature", () => {
|
|||||||
expect(sc?.daily?.[0]?.spells.map((s) => s.name)).toEqual(["Earthquake"]);
|
expect(sc?.daily?.[0]?.spells.map((s) => s.name)).toEqual(["Earthquake"]);
|
||||||
expect(sc?.daily?.[1]?.spells.map((s) => s.name)).toEqual(["Heal"]);
|
expect(sc?.daily?.[1]?.spells.map((s) => s.name)).toEqual(["Heal"]);
|
||||||
expect(sc?.atWill?.map((s) => s.name)).toEqual(["Detect Magic"]);
|
expect(sc?.atWill?.map((s) => s.name)).toEqual(["Detect Magic"]);
|
||||||
// Cantrip rank auto-heightens to ceil(creatureLevel / 2) = ceil(3/2) = 2
|
expect(sc?.atWill?.[0]?.rank).toBe(1);
|
||||||
expect(sc?.atWill?.[0]?.rank).toBe(2);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("normalizes innate spells with uses", () => {
|
it("normalizes innate spells with uses", () => {
|
||||||
|
|||||||
@@ -99,15 +99,9 @@ describe("stripFoundryTags", () => {
|
|||||||
expect(stripFoundryTags("before<hr />after")).toBe("before\nafter");
|
expect(stripFoundryTags("before<hr />after")).toBe("before\nafter");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("preserves strong and em tags", () => {
|
it("strips strong and em tags", () => {
|
||||||
expect(stripFoundryTags("<strong>bold</strong> <em>italic</em>")).toBe(
|
expect(stripFoundryTags("<strong>bold</strong> <em>italic</em>")).toBe(
|
||||||
"<strong>bold</strong> <em>italic</em>",
|
"bold italic",
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves list tags", () => {
|
|
||||||
expect(stripFoundryTags("<ul><li>first</li><li>second</li></ul>")).toBe(
|
|
||||||
"<ul><li>first</li><li>second</li></ul>",
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import { type IDBPDatabase, openDB } from "idb";
|
|||||||
|
|
||||||
const DB_NAME = "initiative-bestiary";
|
const DB_NAME = "initiative-bestiary";
|
||||||
const STORE_NAME = "sources";
|
const STORE_NAME = "sources";
|
||||||
// v8 (2026-04-10): Attack effects, ability frequency, perception details added to PF2e creatures
|
// v7 (2026-04-10): Equipment items added to PF2e creatures; old caches are cleared
|
||||||
const DB_VERSION = 8;
|
const DB_VERSION = 7;
|
||||||
|
|
||||||
interface CachedSourceInfo {
|
interface CachedSourceInfo {
|
||||||
readonly sourceCode: string;
|
readonly sourceCode: string;
|
||||||
|
|||||||
@@ -63,7 +63,6 @@ interface MeleeSystem {
|
|||||||
bonus?: { value: number };
|
bonus?: { value: number };
|
||||||
damageRolls?: Record<string, { damage: string; damageType: string }>;
|
damageRolls?: Record<string, { damage: string; damageType: string }>;
|
||||||
traits?: { value: string[] };
|
traits?: { value: string[] };
|
||||||
attackEffects?: { value: string[] };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ActionSystem {
|
interface ActionSystem {
|
||||||
@@ -72,7 +71,6 @@ interface ActionSystem {
|
|||||||
actions?: { value: number | null };
|
actions?: { value: number | null };
|
||||||
traits?: { value: string[] };
|
traits?: { value: string[] };
|
||||||
description?: { value: string };
|
description?: { value: string };
|
||||||
frequency?: { max: number; per: string };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SpellcastingEntrySystem {
|
interface SpellcastingEntrySystem {
|
||||||
@@ -344,17 +342,7 @@ function formatSpeed(speed: {
|
|||||||
|
|
||||||
// -- Attack normalization --
|
// -- Attack normalization --
|
||||||
|
|
||||||
/** Format an attack effect slug to display text: "grab" → "Grab", "lich-siphon-life" → "Siphon Life". */
|
function normalizeAttack(item: RawFoundryItem): TraitBlock {
|
||||||
function formatAttackEffect(slug: string, creatureName: string): string {
|
|
||||||
const prefix = `${creatureName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-")}-`;
|
|
||||||
const stripped = slug.startsWith(prefix) ? slug.slice(prefix.length) : slug;
|
|
||||||
return stripped.split("-").map(capitalize).join(" ");
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeAttack(
|
|
||||||
item: RawFoundryItem,
|
|
||||||
creatureName: string,
|
|
||||||
): TraitBlock {
|
|
||||||
const sys = item.system as unknown as MeleeSystem;
|
const sys = item.system as unknown as MeleeSystem;
|
||||||
const bonus = sys.bonus?.value ?? 0;
|
const bonus = sys.bonus?.value ?? 0;
|
||||||
const traits = sys.traits?.value ?? [];
|
const traits = sys.traits?.value ?? [];
|
||||||
@@ -364,18 +352,13 @@ function normalizeAttack(
|
|||||||
.join(" plus ");
|
.join(" plus ");
|
||||||
const traitStr =
|
const traitStr =
|
||||||
traits.length > 0 ? ` (${traits.map(formatTrait).join(", ")})` : "";
|
traits.length > 0 ? ` (${traits.map(formatTrait).join(", ")})` : "";
|
||||||
const effects = sys.attackEffects?.value ?? [];
|
|
||||||
const effectStr =
|
|
||||||
effects.length > 0
|
|
||||||
? ` plus ${effects.map((e) => formatAttackEffect(e, creatureName)).join(" and ")}`
|
|
||||||
: "";
|
|
||||||
return {
|
return {
|
||||||
name: capitalize(item.name),
|
name: capitalize(item.name),
|
||||||
activity: { number: 1, unit: "action" },
|
activity: { number: 1, unit: "action" },
|
||||||
segments: [
|
segments: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: "text",
|
||||||
value: `+${bonus}${traitStr}, ${damage}${effectStr}`,
|
value: `+${bonus}${traitStr}, ${damage}`,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -399,31 +382,15 @@ function parseActivity(
|
|||||||
|
|
||||||
// -- Ability normalization --
|
// -- Ability normalization --
|
||||||
|
|
||||||
const FREQUENCY_LINE = /(<strong>)?Frequency(<\/strong>)?\s+[^\n]+\n*/i;
|
|
||||||
|
|
||||||
/** Strip the "Frequency once per day" line from ability descriptions when structured frequency data exists. */
|
|
||||||
function stripFrequencyLine(text: string): string {
|
|
||||||
return text.replace(FREQUENCY_LINE, "").trimStart();
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeAbility(item: RawFoundryItem): TraitBlock {
|
function normalizeAbility(item: RawFoundryItem): TraitBlock {
|
||||||
const sys = item.system as unknown as ActionSystem;
|
const sys = item.system as unknown as ActionSystem;
|
||||||
const actionType = sys.actionType?.value;
|
const actionType = sys.actionType?.value;
|
||||||
const actionCount = sys.actions?.value;
|
const actionCount = sys.actions?.value;
|
||||||
let description = stripFoundryTags(sys.description?.value ?? "");
|
const description = stripFoundryTags(sys.description?.value ?? "");
|
||||||
const traits = sys.traits?.value ?? [];
|
const traits = sys.traits?.value ?? [];
|
||||||
|
|
||||||
const activity = parseActivity(actionType, actionCount);
|
const activity = parseActivity(actionType, actionCount);
|
||||||
|
|
||||||
const frequency =
|
|
||||||
sys.frequency?.max != null && sys.frequency.per
|
|
||||||
? `${sys.frequency.max}/${sys.frequency.per}`
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
if (frequency) {
|
|
||||||
description = stripFrequencyLine(description);
|
|
||||||
}
|
|
||||||
|
|
||||||
const traitStr =
|
const traitStr =
|
||||||
traits.length > 0
|
traits.length > 0
|
||||||
? `(${traits.map((t) => capitalize(formatTrait(t))).join(", ")}) `
|
? `(${traits.map((t) => capitalize(formatTrait(t))).join(", ")}) `
|
||||||
@@ -434,7 +401,7 @@ function normalizeAbility(item: RawFoundryItem): TraitBlock {
|
|||||||
? [{ type: "text", value: text }]
|
? [{ type: "text", value: text }]
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
return { name: item.name, activity, frequency, segments };
|
return { name: item.name, activity, segments };
|
||||||
}
|
}
|
||||||
|
|
||||||
// -- Spellcasting normalization --
|
// -- Spellcasting normalization --
|
||||||
@@ -503,25 +470,16 @@ function formatOverlays(overlays: SpellSystem["overlays"]): string | undefined {
|
|||||||
*/
|
*/
|
||||||
const HEIGHTENED_SUFFIX = /\s*Heightened\s*\([^)]*\)[\s\S]*$/;
|
const HEIGHTENED_SUFFIX = /\s*Heightened\s*\([^)]*\)[\s\S]*$/;
|
||||||
|
|
||||||
function normalizeSpell(
|
function normalizeSpell(item: RawFoundryItem): SpellReference {
|
||||||
item: RawFoundryItem,
|
|
||||||
creatureLevel: number,
|
|
||||||
): SpellReference {
|
|
||||||
const sys = item.system as unknown as SpellSystem;
|
const sys = item.system as unknown as SpellSystem;
|
||||||
const usesMax = sys.location?.uses?.max;
|
const usesMax = sys.location?.uses?.max;
|
||||||
const isCantrip = sys.traits?.value?.includes("cantrip") ?? false;
|
const rank = sys.location?.heightenedLevel ?? sys.level?.value ?? 0;
|
||||||
const rank =
|
|
||||||
sys.location?.heightenedLevel ??
|
|
||||||
(isCantrip ? Math.ceil(creatureLevel / 2) : (sys.level?.value ?? 0));
|
|
||||||
const heightening =
|
const heightening =
|
||||||
formatHeightening(sys.heightening) ?? formatOverlays(sys.overlays);
|
formatHeightening(sys.heightening) ?? formatOverlays(sys.overlays);
|
||||||
|
|
||||||
let description: string | undefined;
|
let description: string | undefined;
|
||||||
if (sys.description?.value) {
|
if (sys.description?.value) {
|
||||||
let text = stripFoundryTags(sys.description.value);
|
let text = stripFoundryTags(sys.description.value);
|
||||||
// Resolve Foundry Roll formula references to the spell's actual rank.
|
|
||||||
// The parenthesized form (e.g., "(@item.level)d4") is most common.
|
|
||||||
text = text.replaceAll(/\(?@item\.(?:rank|level)\)?/g, String(rank));
|
|
||||||
if (heightening) {
|
if (heightening) {
|
||||||
text = text.replace(HEIGHTENED_SUFFIX, "").trim();
|
text = text.replace(HEIGHTENED_SUFFIX, "").trim();
|
||||||
}
|
}
|
||||||
@@ -549,7 +507,6 @@ function normalizeSpell(
|
|||||||
function normalizeSpellcastingEntry(
|
function normalizeSpellcastingEntry(
|
||||||
entry: RawFoundryItem,
|
entry: RawFoundryItem,
|
||||||
allSpells: readonly RawFoundryItem[],
|
allSpells: readonly RawFoundryItem[],
|
||||||
creatureLevel: number,
|
|
||||||
): SpellcastingBlock {
|
): SpellcastingBlock {
|
||||||
const sys = entry.system as unknown as SpellcastingEntrySystem;
|
const sys = entry.system as unknown as SpellcastingEntrySystem;
|
||||||
const tradition = capitalize(sys.tradition?.value ?? "");
|
const tradition = capitalize(sys.tradition?.value ?? "");
|
||||||
@@ -568,7 +525,7 @@ function normalizeSpellcastingEntry(
|
|||||||
const cantrips: SpellReference[] = [];
|
const cantrips: SpellReference[] = [];
|
||||||
|
|
||||||
for (const spell of linkedSpells) {
|
for (const spell of linkedSpells) {
|
||||||
const ref = normalizeSpell(spell, creatureLevel);
|
const ref = normalizeSpell(spell);
|
||||||
const isCantrip =
|
const isCantrip =
|
||||||
(spell.system as unknown as SpellSystem).traits?.value?.includes(
|
(spell.system as unknown as SpellSystem).traits?.value?.includes(
|
||||||
"cantrip",
|
"cantrip",
|
||||||
@@ -601,13 +558,10 @@ function normalizeSpellcastingEntry(
|
|||||||
|
|
||||||
function normalizeSpellcasting(
|
function normalizeSpellcasting(
|
||||||
items: readonly RawFoundryItem[],
|
items: readonly RawFoundryItem[],
|
||||||
creatureLevel: number,
|
|
||||||
): SpellcastingBlock[] {
|
): SpellcastingBlock[] {
|
||||||
const entries = items.filter((i) => i.type === "spellcastingEntry");
|
const entries = items.filter((i) => i.type === "spellcastingEntry");
|
||||||
const spells = items.filter((i) => i.type === "spell");
|
const spells = items.filter((i) => i.type === "spell");
|
||||||
return entries.map((entry) =>
|
return entries.map((entry) => normalizeSpellcastingEntry(entry, spells));
|
||||||
normalizeSpellcastingEntry(entry, spells, creatureLevel),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// -- Main normalization --
|
// -- Main normalization --
|
||||||
@@ -717,7 +671,6 @@ export function normalizeFoundryCreature(
|
|||||||
level: sys.details?.level?.value ?? 0,
|
level: sys.details?.level?.value ?? 0,
|
||||||
traits: buildTraits(sys.traits),
|
traits: buildTraits(sys.traits),
|
||||||
perception: sys.perception?.mod ?? 0,
|
perception: sys.perception?.mod ?? 0,
|
||||||
perceptionDetails: sys.perception?.details || undefined,
|
|
||||||
senses: formatSenses(sys.perception?.senses),
|
senses: formatSenses(sys.perception?.senses),
|
||||||
languages: formatLanguages(sys.details?.languages),
|
languages: formatLanguages(sys.details?.languages),
|
||||||
skills: formatSkills(sys.skills),
|
skills: formatSkills(sys.skills),
|
||||||
@@ -735,9 +688,7 @@ export function normalizeFoundryCreature(
|
|||||||
weaknesses: formatWeaknesses(sys.attributes.weaknesses),
|
weaknesses: formatWeaknesses(sys.attributes.weaknesses),
|
||||||
speed: formatSpeed(sys.attributes.speed),
|
speed: formatSpeed(sys.attributes.speed),
|
||||||
attacks: orUndefined(
|
attacks: orUndefined(
|
||||||
items
|
items.filter((i) => i.type === "melee").map(normalizeAttack),
|
||||||
.filter((i) => i.type === "melee")
|
|
||||||
.map((i) => normalizeAttack(i, r.name)),
|
|
||||||
),
|
),
|
||||||
abilitiesTop: orUndefined(actionsByCategory(items, "interaction")),
|
abilitiesTop: orUndefined(actionsByCategory(items, "interaction")),
|
||||||
abilitiesMid: orUndefined(
|
abilitiesMid: orUndefined(
|
||||||
@@ -749,9 +700,7 @@ export function normalizeFoundryCreature(
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
abilitiesBot: orUndefined(actionsByCategory(items, "offensive")),
|
abilitiesBot: orUndefined(actionsByCategory(items, "offensive")),
|
||||||
spellcasting: orUndefined(
|
spellcasting: orUndefined(normalizeSpellcasting(items)),
|
||||||
normalizeSpellcasting(items, sys.details?.level?.value ?? 0),
|
|
||||||
),
|
|
||||||
items:
|
items:
|
||||||
items
|
items
|
||||||
.filter(isMundaneItem)
|
.filter(isMundaneItem)
|
||||||
|
|||||||
@@ -69,18 +69,6 @@ export function getCreaturePathsForSource(sourceCode: string): string[] {
|
|||||||
return compact.creatures.filter((c) => c.s === sourceCode).map((c) => c.f);
|
return compact.creatures.filter((c) => c.s === sourceCode).map((c) => c.f);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCreatureNamesByPaths(paths: string[]): Map<string, string> {
|
|
||||||
const compact = rawIndex as unknown as CompactIndex;
|
|
||||||
const pathSet = new Set(paths);
|
|
||||||
const result = new Map<string, string>();
|
|
||||||
for (const c of compact.creatures) {
|
|
||||||
if (pathSet.has(c.f)) {
|
|
||||||
result.set(c.f, c.n);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getPf2eSourceDisplayName(sourceCode: string): string {
|
export function getPf2eSourceDisplayName(sourceCode: string): string {
|
||||||
const index = loadPf2eBestiaryIndex();
|
const index = loadPf2eBestiaryIndex();
|
||||||
return index.sources[sourceCode] ?? sourceCode;
|
return index.sources[sourceCode] ?? sourceCode;
|
||||||
|
|||||||
@@ -57,5 +57,4 @@ export interface Pf2eBestiaryIndexPort {
|
|||||||
getDefaultFetchUrl(sourceCode: string, baseUrl?: string): string;
|
getDefaultFetchUrl(sourceCode: string, baseUrl?: string): string;
|
||||||
getSourceDisplayName(sourceCode: string): string;
|
getSourceDisplayName(sourceCode: string): string;
|
||||||
getCreaturePathsForSource(sourceCode: string): string[];
|
getCreaturePathsForSource(sourceCode: string): string[];
|
||||||
getCreatureNamesByPaths(paths: string[]): Map<string, string>;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,5 @@ export const productionAdapters: Adapters = {
|
|||||||
getDefaultFetchUrl: pf2eBestiaryIndex.getDefaultPf2eFetchUrl,
|
getDefaultFetchUrl: pf2eBestiaryIndex.getDefaultPf2eFetchUrl,
|
||||||
getSourceDisplayName: pf2eBestiaryIndex.getPf2eSourceDisplayName,
|
getSourceDisplayName: pf2eBestiaryIndex.getPf2eSourceDisplayName,
|
||||||
getCreaturePathsForSource: pf2eBestiaryIndex.getCreaturePathsForSource,
|
getCreaturePathsForSource: pf2eBestiaryIndex.getCreaturePathsForSource,
|
||||||
getCreatureNamesByPaths: pf2eBestiaryIndex.getCreatureNamesByPaths,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -8,13 +8,7 @@
|
|||||||
|
|
||||||
function formatDamage(params: string): string {
|
function formatDamage(params: string): string {
|
||||||
// "3d6+10[fire]" → "3d6+10 fire"
|
// "3d6+10[fire]" → "3d6+10 fire"
|
||||||
// "d4[persistent,fire]" → "d4 persistent fire"
|
return params.replaceAll(/\[([^\]]*)\]/g, " $1").trim();
|
||||||
return params
|
|
||||||
.replaceAll(
|
|
||||||
/\[([^\]]*)\]/g,
|
|
||||||
(_, type: string) => ` ${type.replaceAll(",", " ")}`,
|
|
||||||
)
|
|
||||||
.trim();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatCheck(params: string): string {
|
function formatCheck(params: string): string {
|
||||||
@@ -86,11 +80,11 @@ export function stripFoundryTags(html: string): string {
|
|||||||
// Strip action-glyph spans (content is a number the renderer handles)
|
// Strip action-glyph spans (content is a number the renderer handles)
|
||||||
result = result.replaceAll(/<span class="action-glyph">[^<]*<\/span>/gi, "");
|
result = result.replaceAll(/<span class="action-glyph">[^<]*<\/span>/gi, "");
|
||||||
|
|
||||||
// Strip HTML tags (preserve <strong> for UI rendering)
|
// Strip HTML tags
|
||||||
result = result.replaceAll(/<br\s*\/?>/gi, "\n");
|
result = result.replaceAll(/<br\s*\/?>/gi, "\n");
|
||||||
result = result.replaceAll(/<hr\s*\/?>/gi, "\n");
|
result = result.replaceAll(/<hr\s*\/?>/gi, "\n");
|
||||||
result = result.replaceAll(/<\/p>\s*<p[^>]*>/gi, "\n");
|
result = result.replaceAll(/<\/p>\s*<p[^>]*>/gi, "\n");
|
||||||
result = result.replaceAll(/<(?!\/?(?:strong|em|ul|ol|li)\b)[^>]+>/g, "");
|
result = result.replaceAll(/<[^>]+>/g, "");
|
||||||
|
|
||||||
// Decode common HTML entities
|
// Decode common HTML entities
|
||||||
result = result.replaceAll("&", "&");
|
result = result.replaceAll("&", "&");
|
||||||
@@ -98,11 +92,6 @@ export function stripFoundryTags(html: string): string {
|
|||||||
result = result.replaceAll(">", ">");
|
result = result.replaceAll(">", ">");
|
||||||
result = result.replaceAll(""", '"');
|
result = result.replaceAll(""", '"');
|
||||||
|
|
||||||
// Collapse whitespace around list tags so they don't create extra
|
|
||||||
// line breaks when rendered with whitespace-pre-line
|
|
||||||
result = result.replaceAll(/\s*(<\/?(?:ul|ol)>)\s*/g, "$1");
|
|
||||||
result = result.replaceAll(/\s*(<\/?li>)\s*/g, "$1");
|
|
||||||
|
|
||||||
// Collapse whitespace
|
// Collapse whitespace
|
||||||
result = result.replaceAll(/[ \t]+/g, " ");
|
result = result.replaceAll(/[ \t]+/g, " ");
|
||||||
result = result.replaceAll(/\n\s*\n/g, "\n");
|
result = result.replaceAll(/\n\s*\n/g, "\n");
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ describe("SourceFetchPrompt", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("Load calls fetchAndCacheSource and onSourceLoaded on success", async () => {
|
it("Load calls fetchAndCacheSource and onSourceLoaded on success", async () => {
|
||||||
mockFetchAndCacheSource.mockResolvedValueOnce({ skippedNames: [] });
|
mockFetchAndCacheSource.mockResolvedValueOnce(undefined);
|
||||||
const user = userEvent.setup();
|
const user = userEvent.setup();
|
||||||
const { onSourceLoaded } = renderPrompt();
|
const { onSourceLoaded } = renderPrompt();
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { EquipmentItem } from "@initiative/domain";
|
import type { EquipmentItem } from "@initiative/domain";
|
||||||
import { DetailPopover } from "./detail-popover.js";
|
import { DetailPopover } from "./detail-popover.js";
|
||||||
import { RichDescription } from "./rich-description.js";
|
|
||||||
|
|
||||||
interface EquipmentDetailPopoverProps {
|
interface EquipmentDetailPopoverProps {
|
||||||
readonly item: EquipmentItem;
|
readonly item: EquipmentItem;
|
||||||
@@ -42,10 +41,9 @@ function EquipmentDetailContent({ item }: Readonly<{ item: EquipmentItem }>) {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
{item.description ? (
|
{item.description ? (
|
||||||
<RichDescription
|
<p className="whitespace-pre-line text-foreground">
|
||||||
text={item.description}
|
{item.description}
|
||||||
className="whitespace-pre-line text-foreground"
|
</p>
|
||||||
/>
|
|
||||||
) : (
|
) : (
|
||||||
<p className="text-muted-foreground italic">
|
<p className="text-muted-foreground italic">
|
||||||
No description available.
|
No description available.
|
||||||
|
|||||||
@@ -207,9 +207,7 @@ export function Pf2eStatBlock({ creature }: Readonly<Pf2eStatBlockProps>) {
|
|||||||
<div>
|
<div>
|
||||||
<span className="font-semibold">Perception</span>{" "}
|
<span className="font-semibold">Perception</span>{" "}
|
||||||
{formatInitiativeModifier(creature.perception)}
|
{formatInitiativeModifier(creature.perception)}
|
||||||
{creature.senses || creature.perceptionDetails
|
{creature.senses ? `; ${creature.senses}` : ""}
|
||||||
? `; ${[creature.senses, creature.perceptionDetails].filter(Boolean).join(", ")}`
|
|
||||||
: ""}
|
|
||||||
</div>
|
</div>
|
||||||
<PropertyLine label="Languages" value={creature.languages} />
|
<PropertyLine label="Languages" value={creature.languages} />
|
||||||
<PropertyLine label="Skills" value={creature.skills} />
|
<PropertyLine label="Skills" value={creature.skills} />
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import { cn } from "../lib/utils.js";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Renders text containing safe HTML formatting tags (strong, em, ul, ol, li)
|
|
||||||
* preserved by the stripFoundryTags pipeline. All other HTML is already
|
|
||||||
* stripped before reaching this component.
|
|
||||||
*/
|
|
||||||
export function RichDescription({
|
|
||||||
text,
|
|
||||||
className,
|
|
||||||
}: Readonly<{ text: string; className?: string }>) {
|
|
||||||
const props = {
|
|
||||||
className: cn(
|
|
||||||
"[&_ol]:list-decimal [&_ol]:pl-4 [&_ul]:list-disc [&_ul]:pl-4",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
dangerouslySetInnerHTML: { __html: text },
|
|
||||||
};
|
|
||||||
return <div {...props} />;
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,7 @@ import { Input } from "./ui/input.js";
|
|||||||
|
|
||||||
interface SourceFetchPromptProps {
|
interface SourceFetchPromptProps {
|
||||||
sourceCode: string;
|
sourceCode: string;
|
||||||
onSourceLoaded: (skippedNames: string[]) => void;
|
onSourceLoaded: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SourceFetchPrompt({
|
export function SourceFetchPrompt({
|
||||||
@@ -32,9 +32,8 @@ export function SourceFetchPrompt({
|
|||||||
setStatus("fetching");
|
setStatus("fetching");
|
||||||
setError("");
|
setError("");
|
||||||
try {
|
try {
|
||||||
const { skippedNames } = await fetchAndCacheSource(sourceCode, url);
|
await fetchAndCacheSource(sourceCode, url);
|
||||||
setStatus("idle");
|
onSourceLoaded();
|
||||||
onSourceLoaded(skippedNames);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setStatus("error");
|
setStatus("error");
|
||||||
setError(e instanceof Error ? e.message : "Failed to fetch source data");
|
setError(e instanceof Error ? e.message : "Failed to fetch source data");
|
||||||
@@ -52,7 +51,7 @@ export function SourceFetchPrompt({
|
|||||||
const text = await file.text();
|
const text = await file.text();
|
||||||
const json = JSON.parse(text);
|
const json = JSON.parse(text);
|
||||||
await uploadAndCacheSource(sourceCode, json);
|
await uploadAndCacheSource(sourceCode, json);
|
||||||
onSourceLoaded([]);
|
onSourceLoaded();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setStatus("error");
|
setStatus("error");
|
||||||
setError(
|
setError(
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { ActivityCost, SpellReference } from "@initiative/domain";
|
import type { ActivityCost, SpellReference } from "@initiative/domain";
|
||||||
import { DetailPopover } from "./detail-popover.js";
|
import { DetailPopover } from "./detail-popover.js";
|
||||||
import { RichDescription } from "./rich-description.js";
|
|
||||||
import { ActivityIcon } from "./stat-block-parts.js";
|
import { ActivityIcon } from "./stat-block-parts.js";
|
||||||
|
|
||||||
interface SpellDetailPopoverProps {
|
interface SpellDetailPopoverProps {
|
||||||
@@ -135,6 +134,24 @@ function SpellMeta({ spell }: Readonly<{ spell: SpellReference }>) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const SAVE_OUTCOME_REGEX =
|
||||||
|
/(Critical Success|Critical Failure|Success|Failure)/g;
|
||||||
|
|
||||||
|
function SpellDescription({ text }: Readonly<{ text: string }>) {
|
||||||
|
const parts = text.split(SAVE_OUTCOME_REGEX);
|
||||||
|
const elements: React.ReactNode[] = [];
|
||||||
|
let offset = 0;
|
||||||
|
for (const part of parts) {
|
||||||
|
if (SAVE_OUTCOME_REGEX.test(part)) {
|
||||||
|
elements.push(<strong key={`b-${offset}`}>{part}</strong>);
|
||||||
|
} else if (part) {
|
||||||
|
elements.push(<span key={`t-${offset}`}>{part}</span>);
|
||||||
|
}
|
||||||
|
offset += part.length;
|
||||||
|
}
|
||||||
|
return <p className="whitespace-pre-line text-foreground">{elements}</p>;
|
||||||
|
}
|
||||||
|
|
||||||
function SpellDetailContent({ spell }: Readonly<{ spell: SpellReference }>) {
|
function SpellDetailContent({ spell }: Readonly<{ spell: SpellReference }>) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2 text-sm">
|
<div className="space-y-2 text-sm">
|
||||||
@@ -142,20 +159,16 @@ function SpellDetailContent({ spell }: Readonly<{ spell: SpellReference }>) {
|
|||||||
<SpellTraits traits={spell.traits ?? []} />
|
<SpellTraits traits={spell.traits ?? []} />
|
||||||
<SpellMeta spell={spell} />
|
<SpellMeta spell={spell} />
|
||||||
{spell.description ? (
|
{spell.description ? (
|
||||||
<RichDescription
|
<SpellDescription text={spell.description} />
|
||||||
text={spell.description}
|
|
||||||
className="whitespace-pre-line text-foreground"
|
|
||||||
/>
|
|
||||||
) : (
|
) : (
|
||||||
<p className="text-muted-foreground italic">
|
<p className="text-muted-foreground italic">
|
||||||
No description available.
|
No description available.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{spell.heightening ? (
|
{spell.heightening ? (
|
||||||
<RichDescription
|
<p className="whitespace-pre-line text-foreground text-xs">
|
||||||
text={spell.heightening}
|
{spell.heightening}
|
||||||
className="whitespace-pre-line text-foreground text-xs"
|
</p>
|
||||||
/>
|
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import { DndStatBlock } from "./dnd-stat-block.js";
|
|||||||
import { Pf2eStatBlock } from "./pf2e-stat-block.js";
|
import { Pf2eStatBlock } from "./pf2e-stat-block.js";
|
||||||
import { SourceFetchPrompt } from "./source-fetch-prompt.js";
|
import { SourceFetchPrompt } from "./source-fetch-prompt.js";
|
||||||
import { SourceManager } from "./source-manager.js";
|
import { SourceManager } from "./source-manager.js";
|
||||||
import { Toast } from "./toast.js";
|
|
||||||
import { Button } from "./ui/button.js";
|
import { Button } from "./ui/button.js";
|
||||||
|
|
||||||
interface StatBlockPanelProps {
|
interface StatBlockPanelProps {
|
||||||
@@ -242,6 +241,7 @@ export function StatBlockPanel({
|
|||||||
panelRole,
|
panelRole,
|
||||||
side,
|
side,
|
||||||
}: Readonly<StatBlockPanelProps>) {
|
}: Readonly<StatBlockPanelProps>) {
|
||||||
|
const { isSourceCached } = useBestiaryContext();
|
||||||
const {
|
const {
|
||||||
creatureId,
|
creatureId,
|
||||||
creature,
|
creature,
|
||||||
@@ -260,7 +260,6 @@ export function StatBlockPanel({
|
|||||||
);
|
);
|
||||||
const [needsFetch, setNeedsFetch] = useState(false);
|
const [needsFetch, setNeedsFetch] = useState(false);
|
||||||
const [checkingCache, setCheckingCache] = useState(false);
|
const [checkingCache, setCheckingCache] = useState(false);
|
||||||
const [skippedToast, setSkippedToast] = useState<string | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const mq = globalThis.matchMedia("(min-width: 1024px)");
|
const mq = globalThis.matchMedia("(min-width: 1024px)");
|
||||||
@@ -281,23 +280,19 @@ export function StatBlockPanel({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show fetch prompt both when source is uncached AND when the source is
|
setCheckingCache(true);
|
||||||
// cached but this specific creature is missing (e.g. skipped by ad blocker).
|
void isSourceCached(sourceCode).then((cached) => {
|
||||||
setNeedsFetch(true);
|
setNeedsFetch(!cached);
|
||||||
setCheckingCache(false);
|
setCheckingCache(false);
|
||||||
}, [creatureId, creature]);
|
});
|
||||||
|
}, [creatureId, creature, isSourceCached]);
|
||||||
|
|
||||||
if (!creatureId && !bulkImportMode && !sourceManagerMode) return null;
|
if (!creatureId && !bulkImportMode && !sourceManagerMode) return null;
|
||||||
|
|
||||||
const sourceCode = creatureId ? extractSourceCode(creatureId) : "";
|
const sourceCode = creatureId ? extractSourceCode(creatureId) : "";
|
||||||
|
|
||||||
const handleSourceLoaded = (skippedNames: string[]) => {
|
const handleSourceLoaded = () => {
|
||||||
if (skippedNames.length > 0) {
|
setNeedsFetch(false);
|
||||||
const names = skippedNames.join(", ");
|
|
||||||
setSkippedToast(
|
|
||||||
`${skippedNames.length} creature(s) skipped (ad blocker?): ${names}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderContent = () => {
|
const renderContent = () => {
|
||||||
@@ -343,36 +338,24 @@ export function StatBlockPanel({
|
|||||||
else if (bulkImportMode) fallbackName = "Import All Sources";
|
else if (bulkImportMode) fallbackName = "Import All Sources";
|
||||||
const creatureName = creature?.name ?? fallbackName;
|
const creatureName = creature?.name ?? fallbackName;
|
||||||
|
|
||||||
const toast = skippedToast ? (
|
|
||||||
<Toast message={skippedToast} onDismiss={() => setSkippedToast(null)} />
|
|
||||||
) : null;
|
|
||||||
|
|
||||||
if (isDesktop) {
|
if (isDesktop) {
|
||||||
return (
|
return (
|
||||||
<>
|
<DesktopPanel
|
||||||
<DesktopPanel
|
isCollapsed={isCollapsed}
|
||||||
isCollapsed={isCollapsed}
|
side={side}
|
||||||
side={side}
|
creatureName={creatureName}
|
||||||
creatureName={creatureName}
|
panelRole={panelRole}
|
||||||
panelRole={panelRole}
|
showPinButton={showPinButton}
|
||||||
showPinButton={showPinButton}
|
onToggleCollapse={onToggleCollapse}
|
||||||
onToggleCollapse={onToggleCollapse}
|
onPin={onPin}
|
||||||
onPin={onPin}
|
onUnpin={onUnpin}
|
||||||
onUnpin={onUnpin}
|
>
|
||||||
>
|
{renderContent()}
|
||||||
{renderContent()}
|
</DesktopPanel>
|
||||||
</DesktopPanel>
|
|
||||||
{toast}
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (panelRole === "pinned" || isCollapsed) return null;
|
if (panelRole === "pinned" || isCollapsed) return null;
|
||||||
|
|
||||||
return (
|
return <MobileDrawer onDismiss={onDismiss}>{renderContent()}</MobileDrawer>;
|
||||||
<>
|
|
||||||
<MobileDrawer onDismiss={onDismiss}>{renderContent()}</MobileDrawer>
|
|
||||||
{toast}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import type {
|
|||||||
TraitBlock,
|
TraitBlock,
|
||||||
TraitSegment,
|
TraitSegment,
|
||||||
} from "@initiative/domain";
|
} from "@initiative/domain";
|
||||||
import { RichDescription } from "./rich-description.js";
|
|
||||||
|
|
||||||
export function PropertyLine({
|
export function PropertyLine({
|
||||||
label,
|
label,
|
||||||
@@ -40,22 +39,20 @@ function TraitSegments({
|
|||||||
{segments.map((seg, i) => {
|
{segments.map((seg, i) => {
|
||||||
if (seg.type === "text") {
|
if (seg.type === "text") {
|
||||||
return (
|
return (
|
||||||
<RichDescription
|
<span key={segmentKey(seg)}>
|
||||||
key={segmentKey(seg)}
|
{i === 0 ? ` ${seg.value}` : seg.value}
|
||||||
text={i === 0 ? ` ${seg.value}` : seg.value}
|
</span>
|
||||||
className="inline whitespace-pre-line"
|
|
||||||
/>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<div key={segmentKey(seg)} className="mt-1 space-y-0.5">
|
<div key={segmentKey(seg)} className="mt-1 space-y-0.5">
|
||||||
{seg.items.map((item) => (
|
{seg.items.map((item) => (
|
||||||
<div key={item.label ?? item.text}>
|
<p key={item.label ?? item.text}>
|
||||||
{item.label != null && (
|
{item.label != null && (
|
||||||
<span className="font-semibold">{item.label}. </span>
|
<span className="font-semibold">{item.label}. </span>
|
||||||
)}
|
)}
|
||||||
<RichDescription text={item.text} className="inline" />
|
{item.text}
|
||||||
</div>
|
</p>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -141,7 +138,6 @@ export function TraitEntry({ trait }: Readonly<{ trait: TraitBlock }>) {
|
|||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</span>
|
</span>
|
||||||
{trait.frequency ? ` (${trait.frequency})` : null}
|
|
||||||
{trait.trigger ? (
|
{trait.trigger ? (
|
||||||
<>
|
<>
|
||||||
{" "}
|
{" "}
|
||||||
|
|||||||
@@ -28,10 +28,7 @@ interface BestiaryHook {
|
|||||||
getCreature: (id: CreatureId) => AnyCreature | undefined;
|
getCreature: (id: CreatureId) => AnyCreature | undefined;
|
||||||
isLoaded: boolean;
|
isLoaded: boolean;
|
||||||
isSourceCached: (sourceCode: string) => Promise<boolean>;
|
isSourceCached: (sourceCode: string) => Promise<boolean>;
|
||||||
fetchAndCacheSource: (
|
fetchAndCacheSource: (sourceCode: string, url: string) => Promise<void>;
|
||||||
sourceCode: string,
|
|
||||||
url: string,
|
|
||||||
) => Promise<{ skippedNames: string[] }>;
|
|
||||||
uploadAndCacheSource: (
|
uploadAndCacheSource: (
|
||||||
sourceCode: string,
|
sourceCode: string,
|
||||||
jsonData: unknown,
|
jsonData: unknown,
|
||||||
@@ -39,108 +36,6 @@ interface BestiaryHook {
|
|||||||
refreshCache: () => Promise<void>;
|
refreshCache: () => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface BatchResult {
|
|
||||||
readonly responses: unknown[];
|
|
||||||
readonly failed: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchJson(url: string, path: string): Promise<unknown> {
|
|
||||||
const response = await fetch(url);
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(
|
|
||||||
`Failed to fetch ${path}: ${response.status} ${response.statusText}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return response.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchWithRetry(
|
|
||||||
url: string,
|
|
||||||
path: string,
|
|
||||||
retries = 2,
|
|
||||||
): Promise<unknown> {
|
|
||||||
try {
|
|
||||||
return await fetchJson(url, path);
|
|
||||||
} catch (error) {
|
|
||||||
if (retries <= 0) throw error;
|
|
||||||
await new Promise<void>((r) => setTimeout(r, 500));
|
|
||||||
return fetchWithRetry(url, path, retries - 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchBatch(
|
|
||||||
baseUrl: string,
|
|
||||||
paths: string[],
|
|
||||||
): Promise<BatchResult> {
|
|
||||||
const settled = await Promise.allSettled(
|
|
||||||
paths.map((path) => fetchWithRetry(`${baseUrl}${path}`, path)),
|
|
||||||
);
|
|
||||||
const responses: unknown[] = [];
|
|
||||||
const failed: string[] = [];
|
|
||||||
for (let i = 0; i < settled.length; i++) {
|
|
||||||
const result = settled[i];
|
|
||||||
if (result.status === "fulfilled") {
|
|
||||||
responses.push(result.value);
|
|
||||||
} else {
|
|
||||||
failed.push(paths[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { responses, failed };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchInBatches(
|
|
||||||
paths: string[],
|
|
||||||
baseUrl: string,
|
|
||||||
concurrency: number,
|
|
||||||
): Promise<BatchResult> {
|
|
||||||
const batches: string[][] = [];
|
|
||||||
for (let i = 0; i < paths.length; i += concurrency) {
|
|
||||||
batches.push(paths.slice(i, i + concurrency));
|
|
||||||
}
|
|
||||||
const accumulated = await batches.reduce<Promise<BatchResult>>(
|
|
||||||
async (prev, batch) => {
|
|
||||||
const acc = await prev;
|
|
||||||
const result = await fetchBatch(baseUrl, batch);
|
|
||||||
return {
|
|
||||||
responses: [...acc.responses, ...result.responses],
|
|
||||||
failed: [...acc.failed, ...result.failed],
|
|
||||||
};
|
|
||||||
},
|
|
||||||
Promise.resolve({ responses: [], failed: [] }),
|
|
||||||
);
|
|
||||||
return accumulated;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Pf2eFetchResult {
|
|
||||||
creatures: AnyCreature[];
|
|
||||||
skippedNames: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchPf2eSource(
|
|
||||||
paths: string[],
|
|
||||||
url: string,
|
|
||||||
sourceCode: string,
|
|
||||||
displayName: string,
|
|
||||||
resolveNames: (failedPaths: string[]) => Map<string, string>,
|
|
||||||
): Promise<Pf2eFetchResult> {
|
|
||||||
const baseUrl = url.endsWith("/") ? url : `${url}/`;
|
|
||||||
const { responses, failed } = await fetchInBatches(paths, baseUrl, 6);
|
|
||||||
if (responses.length === 0) {
|
|
||||||
throw new Error(
|
|
||||||
`Failed to fetch any creatures (${failed.length} failed). This may be caused by an ad blocker — try disabling it for this site or use file upload instead.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const nameMap = failed.length > 0 ? resolveNames(failed) : new Map();
|
|
||||||
const skippedNames = failed.map((p) => nameMap.get(p) ?? p);
|
|
||||||
if (skippedNames.length > 0) {
|
|
||||||
console.warn("Skipped creatures (ad blocker?):", skippedNames);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
creatures: normalizeFoundryCreatures(responses, sourceCode, displayName),
|
|
||||||
skippedNames,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useBestiary(): BestiaryHook {
|
export function useBestiary(): BestiaryHook {
|
||||||
const { bestiaryCache, bestiaryIndex, pf2eBestiaryIndex } = useAdapters();
|
const { bestiaryCache, bestiaryIndex, pf2eBestiaryIndex } = useAdapters();
|
||||||
const { edition } = useRulesEditionContext();
|
const { edition } = useRulesEditionContext();
|
||||||
@@ -213,25 +108,30 @@ export function useBestiary(): BestiaryHook {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const fetchAndCacheSource = useCallback(
|
const fetchAndCacheSource = useCallback(
|
||||||
async (
|
async (sourceCode: string, url: string): Promise<void> => {
|
||||||
sourceCode: string,
|
|
||||||
url: string,
|
|
||||||
): Promise<{ skippedNames: string[] }> => {
|
|
||||||
let creatures: AnyCreature[];
|
let creatures: AnyCreature[];
|
||||||
let skippedNames: string[] = [];
|
|
||||||
|
|
||||||
if (edition === "pf2e") {
|
if (edition === "pf2e") {
|
||||||
|
// PF2e: url is a base URL; fetch each creature file in parallel
|
||||||
const paths = pf2eBestiaryIndex.getCreaturePathsForSource(sourceCode);
|
const paths = pf2eBestiaryIndex.getCreaturePathsForSource(sourceCode);
|
||||||
|
const baseUrl = url.endsWith("/") ? url : `${url}/`;
|
||||||
|
const responses = await Promise.all(
|
||||||
|
paths.map(async (path) => {
|
||||||
|
const response = await fetch(`${baseUrl}${path}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(
|
||||||
|
`Failed to fetch ${path}: ${response.status} ${response.statusText}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}),
|
||||||
|
);
|
||||||
const displayName = pf2eBestiaryIndex.getSourceDisplayName(sourceCode);
|
const displayName = pf2eBestiaryIndex.getSourceDisplayName(sourceCode);
|
||||||
const result = await fetchPf2eSource(
|
creatures = normalizeFoundryCreatures(
|
||||||
paths,
|
responses,
|
||||||
url,
|
|
||||||
sourceCode,
|
sourceCode,
|
||||||
displayName,
|
displayName,
|
||||||
pf2eBestiaryIndex.getCreatureNamesByPaths,
|
|
||||||
);
|
);
|
||||||
creatures = result.creatures;
|
|
||||||
skippedNames = result.skippedNames;
|
|
||||||
} else {
|
} else {
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -260,7 +160,6 @@ export function useBestiary(): BestiaryHook {
|
|||||||
}
|
}
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
return { skippedNames };
|
|
||||||
},
|
},
|
||||||
[bestiaryCache, bestiaryIndex, pf2eBestiaryIndex, edition, system],
|
[bestiaryCache, bestiaryIndex, pf2eBestiaryIndex, edition, system],
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -22,10 +22,7 @@ interface BulkImportHook {
|
|||||||
state: BulkImportState;
|
state: BulkImportState;
|
||||||
startImport: (
|
startImport: (
|
||||||
baseUrl: string,
|
baseUrl: string,
|
||||||
fetchAndCacheSource: (
|
fetchAndCacheSource: (sourceCode: string, url: string) => Promise<void>,
|
||||||
sourceCode: string,
|
|
||||||
url: string,
|
|
||||||
) => Promise<{ skippedNames: string[] }>,
|
|
||||||
isSourceCached: (sourceCode: string) => Promise<boolean>,
|
isSourceCached: (sourceCode: string) => Promise<boolean>,
|
||||||
refreshCache: () => Promise<void>,
|
refreshCache: () => Promise<void>,
|
||||||
) => void;
|
) => void;
|
||||||
@@ -42,10 +39,7 @@ export function useBulkImport(): BulkImportHook {
|
|||||||
const startImport = useCallback(
|
const startImport = useCallback(
|
||||||
(
|
(
|
||||||
baseUrl: string,
|
baseUrl: string,
|
||||||
fetchAndCacheSource: (
|
fetchAndCacheSource: (sourceCode: string, url: string) => Promise<void>,
|
||||||
sourceCode: string,
|
|
||||||
url: string,
|
|
||||||
) => Promise<{ skippedNames: string[] }>,
|
|
||||||
isSourceCached: (sourceCode: string) => Promise<boolean>,
|
isSourceCached: (sourceCode: string) => Promise<boolean>,
|
||||||
refreshCache: () => Promise<void>,
|
refreshCache: () => Promise<void>,
|
||||||
) => {
|
) => {
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ export interface TraitBlock {
|
|||||||
readonly name: string;
|
readonly name: string;
|
||||||
readonly activity?: ActivityCost;
|
readonly activity?: ActivityCost;
|
||||||
readonly trigger?: string;
|
readonly trigger?: string;
|
||||||
readonly frequency?: string;
|
|
||||||
readonly segments: readonly TraitSegment[];
|
readonly segments: readonly TraitSegment[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,7 +185,6 @@ export interface Pf2eCreature {
|
|||||||
readonly level: number;
|
readonly level: number;
|
||||||
readonly traits: readonly string[];
|
readonly traits: readonly string[];
|
||||||
readonly perception: number;
|
readonly perception: number;
|
||||||
readonly perceptionDetails?: string;
|
|
||||||
readonly senses?: string;
|
readonly senses?: string;
|
||||||
readonly languages?: string;
|
readonly languages?: string;
|
||||||
readonly skills?: string;
|
readonly skills?: string;
|
||||||
|
|||||||
@@ -108,15 +108,10 @@ As a DM running a PF2e encounter, I want to see the Recall Knowledge DC and asso
|
|||||||
|
|
||||||
The Recall Knowledge line appears below the trait tags, showing the DC (calculated from the creature's level using the PF2e standard DC-by-level table, adjusted for rarity) and the skill determined by the creature's type trait. The line is omitted for creatures with no recognized type trait and never shown for D&D creatures.
|
The Recall Knowledge line appears below the trait tags, showing the DC (calculated from the creature's level using the PF2e standard DC-by-level table, adjusted for rarity) and the skill determined by the creature's type trait. The line is omitted for creatures with no recognized type trait and never shown for D&D creatures.
|
||||||
|
|
||||||
**US-D6 — View NPC Equipment and Consumables (P2)**
|
|
||||||
As a DM running a PF2e encounter, I want to see a creature's carried equipment — magic weapons, potions, scrolls, wands, and other items — displayed on its stat block so I can use these tactical options in combat without consulting external tools.
|
|
||||||
|
|
||||||
An "Equipment" section appears on the stat block listing each carried item with its name and relevant details (level, traits, activation description). Scrolls additionally show the embedded spell name and rank (e.g., "Scroll of Teleport (Rank 6)"). The section is omitted entirely for creatures that carry no equipment. Equipment data is extracted from the existing cached creature JSON — no additional fetch is required.
|
|
||||||
|
|
||||||
### Requirements
|
### Requirements
|
||||||
|
|
||||||
- **FR-016**: The system MUST display a stat block panel with full creature information when a creature is selected.
|
- **FR-016**: The system MUST display a stat block panel with full creature information when a creature is selected.
|
||||||
- **FR-017**: For D&D creatures, the stat block MUST include: name, size, type, alignment, AC (with armor source if applicable), HP (average + formula), speed, ability scores with modifiers, saving throws, skills, damage vulnerabilities, damage resistances, damage immunities, condition immunities, senses, languages, challenge rating, proficiency bonus, passive perception, traits, actions, bonus actions, reactions, spellcasting, and legendary actions. For PF2e creatures, the stat block MUST include: name, level, traits (as tags), Perception (with details text such as "smoke vision" alongside senses), languages, skills, ability modifiers (Str/Dex/Con/Int/Wis/Cha as modifiers, not scores), items, AC, saving throws (Fort/Ref/Will), HP (with optional immunities/resistances/weaknesses), speed, attacks (with inline on-hit effects), abilities with frequency limits where applicable, top abilities, mid abilities (reactions/auras), bot abilities (active), spellcasting, and equipment (weapons, consumables, and other carried items).
|
- **FR-017**: For D&D creatures, the stat block MUST include: name, size, type, alignment, AC (with armor source if applicable), HP (average + formula), speed, ability scores with modifiers, saving throws, skills, damage vulnerabilities, damage resistances, damage immunities, condition immunities, senses, languages, challenge rating, proficiency bonus, passive perception, traits, actions, bonus actions, reactions, spellcasting, and legendary actions. For PF2e creatures, the stat block MUST include: name, level, traits (as tags), Perception and senses, languages, skills, ability modifiers (Str/Dex/Con/Int/Wis/Cha as modifiers, not scores), items, AC, saving throws (Fort/Ref/Will), HP (with optional immunities/resistances/weaknesses), speed, attacks, top abilities, mid abilities (reactions/auras), bot abilities (active), and spellcasting.
|
||||||
- **FR-018**: Optional stat block sections (traits, legendary actions, bonus actions, reactions, etc.) MUST be omitted entirely when the creature has none.
|
- **FR-018**: Optional stat block sections (traits, legendary actions, bonus actions, reactions, etc.) MUST be omitted entirely when the creature has none.
|
||||||
- **FR-019**: The system MUST strip bestiary markup tags (spell references, dice notation, attack tags) and render them as plain readable text (e.g., `{@spell fireball|XPHB}` -> "fireball", `{@dice 3d6}` -> "3d6").
|
- **FR-019**: The system MUST strip bestiary markup tags (spell references, dice notation, attack tags) and render them as plain readable text (e.g., `{@spell fireball|XPHB}` -> "fireball", `{@dice 3d6}` -> "3d6").
|
||||||
- **FR-020**: On wide viewports (desktop), the layout MUST be side-by-side with the encounter tracker on the left and stat block on the right.
|
- **FR-020**: On wide viewports (desktop), the layout MUST be side-by-side with the encounter tracker on the left and stat block on the right.
|
||||||
@@ -162,17 +157,6 @@ An "Equipment" section appears on the stat block listing each carried item with
|
|||||||
19. **Given** a PF2e creature with rare rarity is displayed, **When** the DM views the stat block, **Then** the Recall Knowledge DC is the standard DC for its level +5.
|
19. **Given** a PF2e creature with rare rarity is displayed, **When** the DM views the stat block, **Then** the Recall Knowledge DC is the standard DC for its level +5.
|
||||||
20. **Given** a PF2e creature with the "Undead" type trait is displayed, **When** the DM views the stat block, **Then** the Recall Knowledge line shows "Religion" as the associated skill.
|
20. **Given** a PF2e creature with the "Undead" type trait is displayed, **When** the DM views the stat block, **Then** the Recall Knowledge line shows "Religion" as the associated skill.
|
||||||
21. **Given** a D&D creature is displayed, **When** the DM views the stat block, **Then** no Recall Knowledge line is shown.
|
21. **Given** a D&D creature is displayed, **When** the DM views the stat block, **Then** no Recall Knowledge line is shown.
|
||||||
22. **Given** a PF2e creature carrying a Staff of Fire and an Invisibility Potion is displayed, **When** the DM views the stat block, **Then** an "Equipment" section appears listing both items with their names and relevant details.
|
|
||||||
23. **Given** a PF2e creature carrying a Scroll of Teleport Rank 6 is displayed, **When** the DM views the stat block, **Then** the Equipment section shows the scroll with the embedded spell name and rank (e.g., "Scroll of Teleport (Rank 6)").
|
|
||||||
24. **Given** a PF2e creature with no equipment items is displayed, **When** the DM views the stat block, **Then** no Equipment section is shown.
|
|
||||||
25. **Given** a PF2e creature with equipment is displayed, **When** the DM views the stat block, **Then** equipment item descriptions have HTML tags stripped and render as plain readable text.
|
|
||||||
26. **Given** a D&D creature is displayed, **When** the DM views the stat block, **Then** no Equipment section is shown (equipment display is PF2e-only).
|
|
||||||
27. **Given** a PF2e creature with a melee attack that has `attackEffects: ["grab"]`, **When** the DM views the stat block, **Then** the attack line shows the damage followed by "plus Grab".
|
|
||||||
28. **Given** a PF2e creature with a melee attack that has no attack effects, **When** the DM views the stat block, **Then** the attack line shows only the damage with no "plus" suffix.
|
|
||||||
29. **Given** a PF2e creature with an ability that has `frequency: {max: 1, per: "day"}`, **When** the DM views the stat block, **Then** the ability name is followed by "(1/day)".
|
|
||||||
30. **Given** a PF2e creature with an ability that has no frequency limit, **When** the DM views the stat block, **Then** the ability name renders without any frequency annotation.
|
|
||||||
31. **Given** a PF2e creature with `perception.details: "smoke vision"`, **When** the DM views the stat block, **Then** the perception line shows "smoke vision" alongside the senses.
|
|
||||||
32. **Given** a PF2e creature with no perception details, **When** the DM views the stat block, **Then** the perception line shows only the modifier and senses as before.
|
|
||||||
|
|
||||||
### Edge Cases
|
### Edge Cases
|
||||||
|
|
||||||
@@ -180,14 +164,9 @@ An "Equipment" section appears on the stat block listing each carried item with
|
|||||||
- Very long content (e.g., a Lich with extensive spellcasting): the stat block panel scrolls independently of the encounter tracker.
|
- Very long content (e.g., a Lich with extensive spellcasting): the stat block panel scrolls independently of the encounter tracker.
|
||||||
- Viewport resized from wide to narrow while stat block is open: the layout transitions from panel to drawer.
|
- Viewport resized from wide to narrow while stat block is open: the layout transitions from panel to drawer.
|
||||||
- Embedded spell item missing description text: the popover/sheet shows the available metadata (level, traits, range, etc.) and a placeholder note for the missing description.
|
- Embedded spell item missing description text: the popover/sheet shows the available metadata (level, traits, range, etc.) and a placeholder note for the missing description.
|
||||||
- Scroll item with missing or empty `system.spell` data: the scroll is displayed by name only, without spell name or rank.
|
|
||||||
- Equipment item with empty description: the item is displayed with its name and metadata (level, traits) but no description text.
|
|
||||||
- Cached source data from before the spell description feature was added: existing cached entries lack the new per-spell data fields. The IndexedDB schema version MUST be bumped to invalidate old caches and trigger re-fetch (re-normalization from raw Foundry data is not possible because the original raw JSON is not retained).
|
- Cached source data from before the spell description feature was added: existing cached entries lack the new per-spell data fields. The IndexedDB schema version MUST be bumped to invalidate old caches and trigger re-fetch (re-normalization from raw Foundry data is not possible because the original raw JSON is not retained).
|
||||||
- Creature with no recognized type trait (e.g., a creature whose only traits are not in the type-to-skill mapping): the Recall Knowledge line is omitted entirely.
|
- Creature with no recognized type trait (e.g., a creature whose only traits are not in the type-to-skill mapping): the Recall Knowledge line is omitted entirely.
|
||||||
- Creature with a type trait that maps to multiple skills (e.g., Beast → Arcana/Nature): both skills are shown.
|
- Creature with a type trait that maps to multiple skills (e.g., Beast → Arcana/Nature): both skills are shown.
|
||||||
- Attack with multiple on-hit effects (e.g., `["grab", "knockdown"]`): all effects shown, joined with "and" (e.g., "plus Grab and Knockdown").
|
|
||||||
- Attack effect slug with creature-name prefix (e.g., `"lich-siphon-life"` on a Lich): the creature-name prefix is stripped, rendering as "Siphon Life".
|
|
||||||
- Frequency `per` value variations (e.g., "day", "round", "turn"): the value is rendered as-is in the "(N/per)" format.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -254,17 +233,6 @@ A DM wants to see which sources are cached, find a specific source, clear a spec
|
|||||||
- **FR-087**: The Recall Knowledge skill MUST be derived from the creature's type trait using the standard PF2e mapping (e.g., Aberration → Occultism, Animal → Nature, Astral → Occultism, Beast → Arcana/Nature, Celestial → Religion, Construct → Arcana/Crafting, Dragon → Arcana, Dream → Occultism, Elemental → Arcana/Nature, Ethereal → Occultism, Fey → Nature, Fiend → Religion, Fungus → Nature, Giant → Society, Humanoid → Society, Monitor → Religion, Ooze → Occultism, Plant → Nature, Undead → Religion).
|
- **FR-087**: The Recall Knowledge skill MUST be derived from the creature's type trait using the standard PF2e mapping (e.g., Aberration → Occultism, Animal → Nature, Astral → Occultism, Beast → Arcana/Nature, Celestial → Religion, Construct → Arcana/Crafting, Dragon → Arcana, Dream → Occultism, Elemental → Arcana/Nature, Ethereal → Occultism, Fey → Nature, Fiend → Religion, Fungus → Nature, Giant → Society, Humanoid → Society, Monitor → Religion, Ooze → Occultism, Plant → Nature, Undead → Religion).
|
||||||
- **FR-088**: Creatures with no recognized type trait MUST omit the Recall Knowledge line entirely rather than showing incorrect data.
|
- **FR-088**: Creatures with no recognized type trait MUST omit the Recall Knowledge line entirely rather than showing incorrect data.
|
||||||
- **FR-089**: The Recall Knowledge line MUST NOT be shown for D&D creatures.
|
- **FR-089**: The Recall Knowledge line MUST NOT be shown for D&D creatures.
|
||||||
- **FR-090**: The PF2e normalization pipeline MUST extract `weapon` and `consumable` item types from the Foundry VTT `items[]` array, in addition to the existing `melee`, `action`, `spell`, and `spellcastingEntry` types. Each extracted equipment item MUST include name, level, traits, and description text.
|
|
||||||
- **FR-091**: PF2e stat blocks MUST display an "Equipment" section listing all extracted equipment items. Each item MUST show its name and relevant details (e.g., level, traits, activation description).
|
|
||||||
- **FR-092**: For scroll items, the stat block MUST display the embedded spell name and rank derived from the `system.spell` data on the item (e.g., "Scroll of Teleport (Rank 6)").
|
|
||||||
- **FR-093**: The Equipment section MUST be omitted entirely when the creature has no equipment items, consistent with FR-018 (optional sections omitted when empty).
|
|
||||||
- **FR-094**: Equipment item descriptions MUST be processed through the existing Foundry tag-stripping utility before display, consistent with FR-068 and FR-081.
|
|
||||||
- **FR-095**: The PF2e normalization pipeline MUST extract `system.attackEffects.value` (an array of slug strings, e.g., `["grab"]`, `["lich-siphon-life"]`) from melee items and include them in the normalized attack data.
|
|
||||||
- **FR-096**: PF2e attack lines MUST display inline on-hit effects after the damage text (e.g., "2d12+7 piercing plus Grab"). Effect slugs MUST be converted to title case with hyphens replaced by spaces; creature-name prefixes (e.g., "lich-" in "lich-siphon-life") MUST be stripped. Multiple effects MUST be joined with "plus" (e.g., "plus Grab and Knockdown"). Attacks without on-hit effects MUST render unchanged.
|
|
||||||
- **FR-097**: The PF2e normalization pipeline MUST extract `system.frequency` (with `max` and `per` fields, e.g., `{max: 1, per: "day"}`) from action items and include it in the normalized ability data.
|
|
||||||
- **FR-098**: PF2e abilities with a frequency limit MUST display it alongside the ability name as "(N/per)" (e.g., "(1/day)", "(1/round)"). Abilities without a frequency limit MUST render unchanged.
|
|
||||||
- **FR-099**: The PF2e normalization pipeline MUST extract `system.perception.details` (a string, e.g., "smoke vision") and include it in the normalized creature perception data.
|
|
||||||
- **FR-100**: PF2e stat blocks MUST display perception details text on the perception line alongside senses (e.g., "Perception +12; darkvision, smoke vision"). When no perception details are present, the perception line MUST render unchanged.
|
|
||||||
|
|
||||||
### Acceptance Scenarios
|
### Acceptance Scenarios
|
||||||
|
|
||||||
@@ -366,7 +334,7 @@ As a DM with a creature pinned, I want to collapse the right (browse) panel inde
|
|||||||
- **Search Index (D&D)** (`BestiaryIndex`): Pre-shipped lightweight dataset keyed by name + source, containing mechanical facts (name, source code, AC, HP average, DEX score, CR, initiative proficiency multiplier, size, type) for all creatures. Sufficient for adding combatants; insufficient for rendering a full stat block.
|
- **Search Index (D&D)** (`BestiaryIndex`): Pre-shipped lightweight dataset keyed by name + source, containing mechanical facts (name, source code, AC, HP average, DEX score, CR, initiative proficiency multiplier, size, type) for all creatures. Sufficient for adding combatants; insufficient for rendering a full stat block.
|
||||||
- **Search Index (PF2e)** (`Pf2eBestiaryIndex`): Pre-shipped lightweight dataset for PF2e creatures, containing name, source code, AC, HP, level, Perception modifier, size, and creature type. Parallel to the D&D search index but with PF2e-specific fields (level instead of CR, Perception instead of DEX/proficiency).
|
- **Search Index (PF2e)** (`Pf2eBestiaryIndex`): Pre-shipped lightweight dataset for PF2e creatures, containing name, source code, AC, HP, level, Perception modifier, size, and creature type. Parallel to the D&D search index but with PF2e-specific fields (level instead of CR, Perception instead of DEX/proficiency).
|
||||||
- **Source** (`BestiarySource`): A D&D or PF2e publication identified by a code (e.g., "XMM") with a display name (e.g., "Monster Manual (2025)"). Caching and fetching operate at the source level.
|
- **Source** (`BestiarySource`): A D&D or PF2e publication identified by a code (e.g., "XMM") with a display name (e.g., "Monster Manual (2025)"). Caching and fetching operate at the source level.
|
||||||
- **Creature (Full)** (`Creature`): A complete creature record with all stat block data (traits, actions, legendary actions, spellcasting, etc.), available only after source data is fetched/uploaded and cached. Identified by a branded `CreatureId`. For PF2e creatures, each spell entry inside `spellcasting` carries full per-spell data (slug, level, traits, range, action cost, target/area, duration, defense, description, heightening) extracted from the embedded `items[type=spell]` data on the source NPC, enabling inline spell description display without additional fetches. PF2e creatures also carry an `equipment` list of carried items (weapons, consumables) extracted from `items[type=weapon]` and `items[type=consumable]` entries, each with name, level, traits, description, and (for scrolls) embedded spell data. PF2e attack entries carry an optional `attackEffects` list of on-hit effect names. PF2e ability entries carry an optional `frequency` with `max` and `per` fields. PF2e creature perception carries an optional `details` string (e.g., "smoke vision").
|
- **Creature (Full)** (`Creature`): A complete creature record with all stat block data (traits, actions, legendary actions, spellcasting, etc.), available only after source data is fetched/uploaded and cached. Identified by a branded `CreatureId`. For PF2e creatures, each spell entry inside `spellcasting` carries full per-spell data (slug, level, traits, range, action cost, target/area, duration, defense, description, heightening) extracted from the embedded `items[type=spell]` data on the source NPC, enabling inline spell description display without additional fetches.
|
||||||
- **Cached Source Data**: The full normalized bestiary data for a single source, stored in IndexedDB. Contains complete creature stat blocks.
|
- **Cached Source Data**: The full normalized bestiary data for a single source, stored in IndexedDB. Contains complete creature stat blocks.
|
||||||
- **Combatant** (extended): Gains an optional `creatureId` reference to a `Creature`, enabling stat block lookup and stat pre-fill on creation.
|
- **Combatant** (extended): Gains an optional `creatureId` reference to a `Creature`, enabling stat block lookup and stat pre-fill on creation.
|
||||||
- **Queued Creature**: Transient UI-only state representing a bestiary creature selected for batch-add, containing the creature reference and a count (1+). Not persisted.
|
- **Queued Creature**: Transient UI-only state representing a bestiary creature selected for batch-add, containing the creature reference and a count (1+). Not persisted.
|
||||||
|
|||||||
Reference in New Issue
Block a user