Compare commits

..
22 Commits
Author SHA1 Message Date
LukasandClaude Opus 5 c029c0ca8d Add the whole party to an encounter from the player menu
CI / check (push) Successful in 2m53s
CI / build-image (push) Successful in 20s
Starting an encounter meant searching for each party member by name, one
at a time. The management view now carries an "Add party to encounter"
button that puts all of them on the board in one click and closes, so the
initiative list is what you see next.

Members already in the encounter are skipped. Matching is on
playerCharacterId, not on name — otherwise a second click would hand you
"Thorin 2" via the auto-numbering, and renaming a combatant to match a
mini (the reason the rename feature exists) would break the check. Rows
for those members show a muted swords icon, and the button disables once
nothing is left to add, so the greyed-out state has a visible cause.

The whole batch pushes a single undo entry rather than one per combatant:
undoing a four-person party should not take four keystrokes. That is why
the reducer loops internally instead of the UI dispatching N times, and
why addOneFromPlayerCharacter is now split out of the single-add handler
for both paths to share.

Spec 005 gains story PC-8, FR-020..FR-023, SC-010/SC-011 and the edge
cases around partial parties, renamed combatants and orphaned ones. The
existing "multiple copies of the same PC are allowed" edge case is marked
as still true for individual adds — the party button is the deliberate
exception. Key Entities now documents the combatant/PC link the dedup
relies on, which had never been written down.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 17:58:14 +02:00
LukasandClaude Opus 5 2e4865d5fc Upgrade Knip back to 6, with raw transfer disabled
CI / check (push) Successful in 2m46s
CI / build-image (push) Successful in 47s
Knip 5 is effectively frozen: 5.88.1 (2026-03-19) was its last release,
with only three patches after 6.0.0 shipped and none since.

The reason for the earlier downgrade (968cc72) was misdiagnosed. The 6 GiB
allocation is not the Rust-side arena tracked in oxc-project/oxc#20513, but
a JS-side `new ArrayBuffer(BLOCK_SIZE + BLOCK_ALIGN)` in oxc-parser's
raw-transfer path, allocated by V8. Linux refuses it under heuristic
overcommit on the CI runner (3.7 GB RAM, no swap). The upstream allocator
work that has landed does not touch this path, so waiting on it would not
have helped.

Set KNIP_DISABLE_RAW_TRANSFER=1 in the `knip` script instead, and route
lefthook and `check` through the script rather than the bare binary — the
default path would otherwise crash with an opaque RangeError. Raw transfer
is worth ~5% on a repo this size (3.1s vs 3.15s); the upstream 2-4x figure
applies to large codebases. Knip 6 is still ~20% faster than 5 overall.

No change in unused-code detection. Verified under overcommit_memory=0 on
Linux as well as locally.

Closes #11

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 17:24:20 +02:00
LukasandClaude Opus 5 be3778a0c9 Add min/max hit point variants for D&D creatures
A D&D stat block opened for a combatant now offers a Min/Avg/Max toggle
below the Hit Points line, deriving both ends from the Hit Dice formula
(3d6 + 6 -> 9 / 16 / 24). The switch is applied as a delta, so manual HP
edits and damage already taken survive it. Unlike the PF2e weak/elite
adjustment this is a convenience tool, not a rules mechanic: nothing but
HP changes and the combatant is not renamed. The toggle is hidden when
the HP field carries prose instead of a dice pool.

Also extracts a SegmentedControl primitive. Game system, theme and the
PF2e weak/elite toggle were three hand-rolled copies of the same markup,
which is why the D&D toggle first came out chunkier and in the wrong
accent color. All four now share one definition, and segments expose
aria-pressed instead of signalling the active state by color alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 17:06:01 +02:00
LukasandClaude Opus 5 7b599e9ad9 Portal the HP adjust popover out of the dimmed row subtree
CI / check (push) Successful in 2m55s
CI / build-image (push) Skipped
A combatant at 0 HP renders its row sections with opacity-50, and the HP
popover lived inside the HP section. CSS opacity applies to the whole
subtree, so position: fixed did not escape it — the popover you need to
heal a downed creature came up half-transparent.

Render it through createPortal into document.body, matching what
ConditionPicker and DetailPopover already do. Positioning now takes an
anchorRef instead of reading parentElement, since the portal's parent is
the body, and the z-index moves to z-50 alongside the other portaled
popovers.

The standalone popover test has to mount the anchor before the popover:
React attaches a parent's ref after its children's layout effects run, so
a same-mount anchorRef is still null when the popover measures itself.
That matches the app, where the popover only opens on click.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 14:47:24 +02:00
LukasandClaude Opus 5 5d99764e14 Make jscpd actually scan, and tighten its threshold to 3%
.jscpd.json set pattern to an array, but jscpd's --pattern takes a single
glob string. An array matches nothing, so the gate had reported success
without reading a file since 2793a66 introduced it — its 0.074ms
"detection time" and absent stats table were the tell. Bisecting the
config confirmed that key alone reduces the run to zero files.

The ignore entries were also bare names rather than globs, so once the
pattern worked it swept apps/web/dist and .pnpm-store — 948 files.

Excludes __tests__, matching what .jsinspectrc already does. Duplication
between test cases is usually deliberate: parallel arrange/act/assert
blocks read better than shared setup, and the factories under
apps/web/src/__tests__/factories cover the deduplication worth having.

Real duplication is 1.72% across 209 source files, so the threshold drops
from 5% to 3%. jscpd measures a ratio rather than blocking each new clone,
and a 5% budget left roughly 3x headroom before it would ever fire.

Gives jscpd explicit paths behind `pnpm jscpd`, so lefthook and the check
script share one invocation, as jsinspect already does.

Also guards the pattern key in check-gates.mjs, since an array there fails
silently rather than erroring.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 14:27:51 +02:00
LukasandClaude Opus 5 67c398d3a2 Make the test gate fail when no tests match
vitest.config.ts set passWithNoTests: true, added in the 7dd4abb
scaffolding commit when the repo genuinely had no tests yet. Once tests
existed it became the same hazard as the oxlint bugs fixed in 91f46ff:
if the include globs ever stopped matching, the suite would exit 0
having run nothing.

Vitest already defaults to failing in that case, so removing the line is
the whole fix — a broken glob now reports "No test files found, exiting
with code 1". Verified by pointing the globs at a nonexistent directory.

Extends the gate check to flag the option coming back, and renames it
from check-lint-gate to check-gates now that it covers more than oxlint.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 14:16:04 +02:00
LukasandClaude Opus 5 8204122bd0 Lint the scripts directory
`scripts` sat in oxlint's ignorePatterns since c94c30e, grouped with
dist, coverage and .pnpm-store. Those are build artifacts; scripts holds
the quality gates themselves, which went unlinted as a result.

Removing it raises coverage from 265 to 273 files and surfaced four
findings:

prefer-regexp-exec in three files — swapped String#match for RegExp#exec.
All three patterns are non-global, where the two methods return the same
result, so behaviour is unchanged.

require-array-sort-compare in generate-bestiary-index.mjs — the rule
skips string arrays, and fired only because `new Set()` infers Set<any>.
Typed it Set<string>, which it already is, rather than adding a
comparator the bare sort does not need.

Also anchors the lint-gate probe's no-console canary to CLI scripts that
exist to write to the console, rather than to app error paths that could
reasonably be removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 14:11:23 +02:00
LukasandClaude Opus 5 685526d53b Add a regression test for the oxlint gate
A gate that checks nothing exits 0, which is indistinguishable from a
clean run — that is why the two invocation bugs fixed in 91f46ff went
unnoticed across 49 commits.

The check runs the configured oxlint command with one rule forced to
warn and requires a non-zero exit. That single probe covers a missing
--deny-warnings, a command that discovers no files, a broken tsconfig
path, and an upstream flag rename. Two things the probe cannot see get
their own assertions: that every gate invokes `pnpm oxlint` with nothing
appended, and that --type-aware is still enabled, since the canary rule
is not type-aware.

Verified against four reconstructed states: the b6ee4c8 and 9b0cb38
configurations, --type-aware removed, and a tsconfig path that matches
no files. Each fails; the current configuration passes.

Follows the existing check-layer-boundaries.mjs pattern — an exported
function driven by a Vitest case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 14:10:59 +02:00
LukasandClaude Opus 5 91f46ff3c8 Fix oxlint gate invocations that silently linted nothing
Two separate defects, both of which made the gate pass without checking:

lefthook ran `pnpm oxlint -- --deny warnings`. pnpm forwards arguments
after `--` to the script, so oxlint received its own `--` terminator and
read the rest as file paths — the pre-commit oxlint job linted 0 files.

The check script used `--deny warnings` rather than `--deny-warnings`.
`--deny` takes a rule or category and `warnings` is neither, so it was
accepted and ignored. Without `--deny-warnings` the run reports warnings
but still exits 0, so CI was equally non-blocking.

Both now call `pnpm oxlint`, keeping the flags in one place.

Introduced 2026-03-29 in b6ee4c8, which claimed warnings would fail the
build. 9b0cb38 diagnosed the invalid flag but fixed only the npm script,
leaving both actual gates broken.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 14:10:31 +02:00
LukasandClaude Opus 5 90eb39b227 Restore green merge gate: pnpm settings, deps, unbound-method
pnpm 10.32 stopped reading the "pnpm" field from package.json, so the
undici/picomatch overrides and the three GHSA suppressions had silently
stopped applying — only the stale lockfile still held undici at 7.24.8.
Move the surviving picomatch override to pnpm-workspace.yaml.

With the config live again, two high advisories surfaced:
- postcss was stuck at 8.5.15 (GHSA-r28c-9q8g-f849, patched in 8.5.18);
  nothing pinned it, so refresh to 8.5.25 within vite's range.
- undici GHSA-4cwx-7wf7-3272 needed >=7.29.0, but our ~7.24.0 pin existed
  because jsdom 29 crashed on undici 7.28+. jsdom 30 moved to undici ^8.9,
  so bump jsdom and drop both the pin and all three suppressions.

15 vulnerabilities (5 high, 3 suppressed) down to 1 moderate (smol-toml
via knip, below the --audit-level=high gate).

Separately, ports.ts declared its members with method shorthand, which
TypeScript treats as this-dependent, so oxlint's unbound-method fired
wherever a port was passed by reference (use-bestiary.ts:236). The ports
are bags of plain module functions, so declare them as readonly function
properties instead of suppressing the one call site. This makes parameter
types contravariant rather than bivariant; typecheck passes unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 13:24:13 +02:00
LukasandClaude Fable 5 78079bf1b2 Break import cycle in domain persistent-damage modules
Extract persistent damage types and definitions into a leaf module so
events.ts and types.ts no longer import back into persistent-damage.ts.
Enable oxlint import/no-cycle (whole workspace via root tsconfig) to
keep cycles out.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 13:35:14 +02:00
LukasandClaude Fable 5 aa5555ef86 Fix encounter difficulty tier classification for 5.5e and PF2e
CI / build-image (push) Successful in 37s
CI / check (push) Successful in 2m43s
The 2024 DMG and PF2e GM Core define XP budgets as ceilings ("spend as
much of your XP budget as you can without going over"), not floors like
the 2014 DMG thresholds. The tier is now the lowest budget the XP does
not exceed: an encounter over the Moderate budget is High even if below
the High budget. PF2e now also uses the Trivial budget (40 or less),
GM Core remaster party-size adjustments (Low +20), and counts creatures
more than 4 levels below the party as 0 XP. 2014 rules are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 13:32:07 +02:00
Lukas a045e3a0f9 Unmount Dialog children when closed
CI / build-image (push) Successful in 38s
CI / check (push) Successful in 2m50s
The native <dialog> wrapper rendered its children unconditionally
and only called dialog.close() on the underlying element when
open went false. The React subtree stayed mounted, so component
state (e.g. a ConfirmButton mid-confirm with a red checkmark
showing) survived a close/reopen cycle and reappeared the next
time the user opened the same dialog.

Gate children on open so the subtree unmounts on close. Next open
gets a fresh tree with default state.
2026-06-19 16:52:17 +02:00
Lukas 934d98025e chore(deps): suppress two new unreachable undici advisories
GHSA-vxpw-j846-p89q (WebSocket DoS via fragment count bypass) and
GHSA-hm92-r4w5-c3mj (SOCKS5 proxy pool cross-origin reuse) just
landed in the registry. Both are fixed in undici>=7.28.0 and both
sit in code paths we don't exercise from tests (no WebSocket
client, no SOCKS5 proxy). Same blocker as GHSA-vmh5-mc38-953g:
jsdom@29.1.1 reaches into undici 7's private module layout, so
we can't move the pin to 7.28+. Added them to the existing
ignoreGhsas list and consolidated the per-entry notes.
2026-06-19 16:51:56 +02:00
Lukas 3b2fb99b37 Fix duplicate player character ids after page reload
The PC id counter lived in a module-level let that reset to 0 on
every page load. After rehydrating PCs from localStorage, the next
create would hand out pc-1 again, colliding with an existing id.
That broke React's keyed reconciliation and caused the wrong PC
to be deleted (deletePlayerCharacter matches the first occurrence
of the id, so deleting the new pc-1 would remove the rehydrated
one instead).

Derive the next id from the max numeric suffix of existing
characters at the moment of creation. No more shared counter, so
no more reset on reload and no collision after import.
2026-06-19 16:36:20 +02:00
Lukas 111b464da5 Add Centaur Youth to bundled bestiary under Homebrew source
CR 1/4 Medium Fey with Gallop (advantage-cancelling skirmisher
trait) and Charge (bonus 1d6 on a 15 ft. straight-line melee),
matching the centaur PC traits players already have access to.
2026-06-19 16:30:01 +02:00
Lukas a97ffe5ed1 chore(deps): bump vite, jsdom; pin undici and suppress unreachable advisory
Bumps vite ^8.0.5 → ^8.0.16 (GHSA-fx2h-pf6j-xcff, server.fs.deny
bypass on Windows) and jsdom ^29.0.1 → ^29.1.1 to unblock the
pre-commit audit gate.

The existing >=7.24.0 undici override was floating to 8.x, which
broke jsdom (it reaches into undici 7's private module layout).
Tightened to ~7.24.0 to keep jsdom working. That leaves
GHSA-vmh5-mc38-953g (undici SOCKS5 ProxyAgent TLS bypass) open —
patched in 7.28+ but we can't move there until jsdom updates its
pin. We never use a SOCKS5 proxy in tests, so the vulnerable code
path is unreachable. Added an auditConfig.ignoreGhsas entry with
a note explaining the rationale and the condition for removing it.
2026-06-19 16:29:42 +02:00
LukasandClaude Opus 4.7 1930473753 Bundle The Great Labors bestiary (27 creatures)
CI / check (push) Successful in 2m54s
CI / build-image (push) Successful in 36s
Adds the monsters from appendix B (pages 163-199) of The Great Labors:
Anarch Boar, Blemys, Bronze Automaton/Strategos, Cerberus/Young Cerberus,
Empusa, Goatling/Trickster, Gygan, Keledone, Maenad, Thylean Manticore,
Marble Golem, Minotaur Berserker/Warrior, the three mythic beasts
(White Stag, Golden Lion, Golden Ram), the five nymph lineages
(Aurae, Naiad, Nereid, Oceanid, Oread), Satyr Minstrel, and
Soldier/Soldier Captain.

Generated by scripts/extract-great-labors.py from the source PDF.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 15:50:15 +02:00
LukasandClaude Opus 4.7 c343fd3cd0 Add bundled-bestiary mechanism for shipping creatures with the app
D&D creatures listed in data/bestiary/dnd-bundled.json are now merged into
the search index and pre-loaded into creatureMap, so they appear alongside
5etools creatures with no "Load source" step. Source codes are derived from
the JSON itself (each creature carries source + sourceDisplayName), so adding
a new book is a pure data change. Bundled sources are excluded from
getAllSourceCodes() so bulk-import skips them, and they never appear in the
source manager (which only lists cached sources).

Includes a reference extractor (scripts/extract-great-labors.py) for the
5.5e revised stat-block format and a /bundle-bestiary skill that future
agents can follow to add monsters from other PDF books.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 15:49:34 +02:00
LukasandClaude Opus 4.6 d9fb271607 Add PF2e encounter difficulty calculation with 5-tier budget system
CI / check (push) Successful in 2m39s
CI / build-image (push) Successful in 18s
Implements PF2e encounter difficulty alongside the existing D&D system.
PF2e uses creature level vs party level to derive XP, compares against
5-tier budgets (Trivial/Low/Moderate/Severe/Extreme), and adjusts
thresholds for party size. The indicator shows 4 bars in PF2e mode.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 15:24:18 +02:00
LukasandClaude Opus 4.6 064af16f95 Fix persistent damage tag ordering and differentiate condition icons
CI / check (push) Successful in 2m39s
CI / build-image (push) Successful in 18s
- Render persistent damage tags before the "+" button, not after
- Use insertion order for conditions on the row instead of definition order
- Differentiate Undetected condition (EyeClosed/slate) from Invisible (Ghost/violet)
- Use purple for void persistent damage to distinguish from violet conditions

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 13:06:31 +02:00
LukasandClaude Opus 4.6 0f640601b6 Add force, void, spirit, vitality, and piercing persistent damage types
CI / check (push) Successful in 2m39s
CI / build-image (push) Successful in 19s
Expands persistent damage from 7 to 12 types to cover all PF2e damage
types that have verified persistent damage sources in published content.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 12:44:03 +02:00
82 changed files with 7016 additions and 705 deletions
+148
View File
@@ -0,0 +1,148 @@
---
name: bundle-bestiary
description: Bundle creatures from a third-party PDF into the app's D&D bestiary so they appear in search alongside 5etools creatures, with no "Load source" step. Use when the user asks to add monsters from a PDF book / adventure / supplement to the bundled bestiary.
---
## Instructions
Add the creatures from a PDF to `data/bestiary/dnd-bundled.json` so they appear in the D&D search index and render as normal stat blocks. Bundled creatures bypass the fetch/cache flow — they're shipped in the JS bundle and pre-loaded into `creatureMap` on startup.
### How the bundling works
- `data/bestiary/dnd-bundled.json` is an array of normalized `Creature` objects (the same shape produced by `bestiary-adapter.ts` for 5etools creatures).
- `apps/web/src/adapters/dnd-bundled-adapter.ts` static-imports the JSON and derives:
- `loadBundledDndCreatures()` — full stat blocks for the in-memory creature map
- `loadBundledDndIndexEntries()` — compact summaries for the search index
- `getBundledDndSources()` — source code → display name map, **derived from the JSON itself** (each creature carries its own `source` + `sourceDisplayName`)
- `bestiary-index-adapter.ts` merges the bundled entries into the search index and excludes bundled sources from `getAllSourceCodes()` (so bulk-import skips them).
- `use-bestiary.ts` merges bundled full creatures into `creatureMap` on init/refresh.
This means **adding a new bundled book is purely a data change**: append creatures to `dnd-bundled.json` with the new source's code and display name. No adapter or index code needs editing.
### Step 1 — Confirm scope and source code
Ask the user (don't guess):
1. **PDF path** and the **page range** containing the stat blocks. Many PDFs have hundreds of pages; only a slice has the bestiary.
2. **Source code abbreviation** — short uppercase letters, e.g., `TGL` for *The Great Labors*. Used in creature IDs and the index.
3. **Display name** — the human-readable book title shown in the source column.
4. **Edition / system** — confirm this is D&D (5e or 5.5e). Bundled creatures show in both 5e and 5.5e modes (the bestiary index only differentiates pf2e vs not). PF2e isn't currently supported by the bundled flow — if requested, this would need a parallel `pf2e-bundled-adapter.ts`.
5. **Licensing** — verify the user has the right to bundle the book's content. Don't make assumptions.
### Step 2 — Inspect the PDF
Check Python's PyPDF2 is available:
```bash
python3 -c "from PyPDF2 import PdfReader; print('ok')"
```
If not, the user has `pdftotext`-equivalent tooling configured at `~/Nextcloud/dnd/D&D/PROMPT_prep.md` worth checking.
Then dump and skim the target pages to learn the stat-block format:
```bash
python3 - <<'EOF'
from PyPDF2 import PdfReader
import os
r = PdfReader(os.path.expanduser('PATH/TO/PDF'))
for i in range(START-1, END):
print(f"\n===PAGE {i+1}===\n{r.pages[i].extract_text()}")
EOF
```
Look for the layout — the existing extractor (`scripts/extract-great-labors.py`) assumes the 5.5e/2024 revised format:
- `<Name>` line, then
- `<Size> <Type>(optional subtype), <Alignment>`, then
- `AC X Initiative ±Y (Z)`, then
- `HP N (NdN + N)`, then
- `Speed X ft., …`, then
- A `MOD SAVE MOD SAVE MOD SAVE` header followed by two ability-score rows, then
- Optional meta lines: `Skills`, `Saving Throws`, `Resistances`, `Immunities`, `Vulnerabilities`, `Senses`, `Languages`, then
- `Challenge X (NN XP; PB +N)`, then
- Section blocks: `Traits` / `Actions` / `Bonus Actions` / `Reactions` / `Legendary Actions`, each containing entries shaped like `Name. body...`.
If the PDF format matches, adapt the existing extractor. If it's a different format (5e 2014 with `STR DEX CON …` column layout, an older publisher's layout, a homebrew layout), expect to rework the parser more substantively.
### Step 3 — Adapt or extend the extractor
Copy `scripts/extract-great-labors.py` to a new script per book (e.g., `scripts/extract-<book-slug>.py`) and update:
- `SOURCE_CODE`, `SOURCE_DISPLAY`, `PAGE_START`, `PAGE_END` constants.
- The output path (`data/bestiary/dnd-bundled.json`). **Don't overwrite — merge.** The simplest pattern: read the existing file, drop any entries with the same `source`, then append the new ones.
- The `PROSE_TAIL_PATTERNS` list — every book has its own running headers (`<PageNumber>APPENDIX B … MONSTERS`-style), section-header phrases, and quote-attribution dashes. Run the extractor, audit the output (see Step 4), and add curated trim patterns for any prose tails that bleed in.
Run it:
```bash
python3 scripts/extract-<book-slug>.py PATH/TO/PDF
```
### Step 4 — Audit the output
PyPDF text extraction is messy. Always audit before claiming done:
```bash
python3 - <<'EOF'
import json, re
data = json.load(open('data/bestiary/dnd-bundled.json'))
new = [c for c in data if c['source'] == 'XXX'] # replace XXX with your code
for c in new:
print(f"{c['name']}: CR {c['cr']}, AC {c['ac']}, HP {c['hp']['average']} ({c['hp']['formula']})")
abs_ = c['abilities']
print(f" STR {abs_['str']} DEX {abs_['dex']} CON {abs_['con']} INT {abs_['int']} WIS {abs_['wis']} CHA {abs_['cha']}, PP {c['passive']}")
# Then audit bodies for prose-tail bleed and weird splits.
for c in new:
for sec in ('traits', 'actions', 'bonusActions', 'reactions'):
for e in c.get(sec, []):
body = e['segments'][0]['value']
issues = []
if len(body) > 600: issues.append(f"long({len(body)})")
if re.search(r'\.[A-Z][a-z]', body): issues.append("dot-Capital")
if 'APPENDIX' in body: issues.append("APPENDIX")
if re.search(r'—\s*[A-Z]\w+,\s', body): issues.append("attribution")
if issues:
print(f" {c['name']} [{sec}] {e['name']}: {', '.join(issues)}")
print(f" ...{body[-200:]}")
EOF
```
Common PDF extraction problems to fix in the parser:
- **PDF kerning quirks**: multi-digit values rendered with spaces (e.g., "Passive Perception 1 1" → 11, "Wis 81 1" with no space before negative). The existing parser handles most; check for new ones.
- **Smushed section headers**: lines like `...plants.Actions` where the section header for the next block was concatenated. Handle via `SECTION_HEADER_SMUSH_RE` preprocessing.
- **Cross-page prose bleed**: text from the next page's flavor prose absorbed into the last entry's body. Catch via `PROSE_TAIL_PATTERNS` — add curated phrases observed in this specific book.
- **Sibling-entry inline smush**: `damage.Ram. Melee Attack Roll: …` where two entries got concatenated. Already handled by the mid-line entry boundary regex in the existing parser.
- **Title-cased false positives**: words like `Bloodied.`, `Restrained.`, `Frightened.` at sentence ends would otherwise match the entry-name pattern. Filtered via `NAME_FALSE_POSITIVES` — add to it if the new book uses condition names you haven't seen yet.
### Step 5 — Verify in the app
```bash
pnpm check
```
Then start the dev server and search for one of the new creatures by name:
```bash
pnpm --filter web dev
```
Confirm in the browser:
1. Search finds the creature with the right book name as the source label.
2. Clicking it shows the full stat block immediately — **no "Load source" prompt**.
3. The source manager UI does **not** list the bundled book (it only shows cached sources).
4. Bulk import skips the bundled book.
### Notes for future agents
- **No need to edit `dnd-bundled-adapter.ts` or `bestiary-index-adapter.ts`** when adding a new book — the adapter derives source codes from the JSON.
- `data/bestiary/index.json` is regenerated from 5etools and should **not** be edited to add bundled entries. The merge happens at runtime in `bestiary-index-adapter.ts`.
- Each bundled creature must have:
- A unique `id` like `<sourcecode>:<slug>` (e.g., `tgl:anarch-boar`).
- `source` field matching the source code (e.g., `"TGL"`).
- `sourceDisplayName` field matching the book's display name (e.g., `"The Great Labors"`).
- All the required `Creature` fields from `packages/domain/src/creature-types.ts`.
- The script approach is preferred over hand-editing JSON for >5 creatures. For a single creature or two, hand-editing the JSON is reasonable; just match an existing entry's shape exactly.
- After any change to `dnd-bundled.json`, run `pnpm typecheck` — the static import in the adapter will catch shape mismatches at compile time.
+9 -3
View File
@@ -1,8 +1,14 @@
{
"threshold": 5,
"threshold": 3,
"minLines": 5,
"minTokens": 50,
"pattern": ["**/*.ts", "**/*.tsx"],
"ignore": ["node_modules", "dist", "build", "coverage", ".specify", "specs"],
"pattern": "**/*.{ts,tsx}",
"ignore": [
"**/node_modules/**",
"**/dist/**",
"**/build/**",
"**/coverage/**",
"**/__tests__/**"
],
"reporters": ["console"]
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://raw.githubusercontent.com/nicolo-ribaudo/tc39-proposal-type-annotations/refs/heads/main/packages/oxlint/configuration_file_schema.json",
"plugins": ["typescript", "unicorn", "jest"],
"plugins": ["typescript", "unicorn", "jest", "import"],
"categories": {},
"rules": {
"typescript/no-unnecessary-type-assertion": "error",
@@ -8,6 +8,7 @@
"typescript/prefer-regexp-exec": "error",
"unicorn/prefer-string-replace-all": "error",
"unicorn/prefer-string-raw": "error",
"import/no-cycle": "error",
"jest/expect-expect": [
"error",
{
@@ -21,7 +22,6 @@
".claude",
".specify",
"specs",
".pnpm-store",
"scripts"
".pnpm-store"
]
}
+2 -2
View File
@@ -27,8 +27,8 @@
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^6.0.1",
"jsdom": "^29.0.1",
"jsdom": "^30.0.1",
"tailwindcss": "^4.2.2",
"vite": "^8.0.5"
"vite": "^8.0.16"
}
}
@@ -266,6 +266,45 @@ describe("round-trip: export then import", () => {
expect(imported.encounter.combatants[1].side).toBe("enemy");
});
it("round-trips a combatant with hpVariant field", () => {
const encounterWithVariant: Encounter = {
combatants: [
{
id: combatantId("c-1"),
name: "Ogre",
maxHp: 24,
currentHp: 24,
hpVariant: "max",
},
{
id: combatantId("c-2"),
name: "Goblin",
maxHp: 2,
currentHp: 2,
hpVariant: "min",
},
],
activeIndex: 0,
roundNumber: 1,
};
const emptyUndoRedo: UndoRedoState = {
undoStack: [],
redoStack: [],
};
const bundle = assembleExportBundle(
encounterWithVariant,
emptyUndoRedo,
[],
);
const serialized = JSON.parse(JSON.stringify(bundle));
const result = validateImportBundle(serialized);
expect(typeof result).toBe("object");
const imported = result as ExportBundle;
expect(imported.encounter.combatants[0].hpVariant).toBe("max");
expect(imported.encounter.combatants[1].hpVariant).toBe("min");
});
it("round-trips a combatant without side field as undefined", () => {
const encounterNoSide: Encounter = {
combatants: [{ id: combatantId("c-1"), name: "Custom" }],
@@ -0,0 +1,28 @@
import type { Pf2eCreature } from "@initiative/domain";
import { creatureId } from "@initiative/domain";
let counter = 0;
export function buildPf2eCreature(
overrides?: Partial<Pf2eCreature>,
): Pf2eCreature {
const id = ++counter;
return {
system: "pf2e",
id: creatureId(`pf2e-creature-${id}`),
name: `PF2e Creature ${id}`,
source: "crb",
sourceDisplayName: "Core Rulebook",
level: 1,
traits: ["humanoid"],
perception: 5,
abilityMods: { str: 2, dex: 1, con: 2, int: 0, wis: 1, cha: -1 },
ac: 15,
saveFort: 7,
saveRef: 4,
saveWill: 5,
hp: 20,
speed: "25 ft.",
...overrides,
};
}
@@ -0,0 +1,16 @@
import type { PlayerCharacter } from "@initiative/domain";
import { playerCharacterId } from "@initiative/domain";
let counter = 0;
export function buildPlayerCharacter(
overrides?: Partial<PlayerCharacter>,
): PlayerCharacter {
return {
id: playerCharacterId(`pc-${++counter}`),
name: "Player Character",
ac: 15,
maxHp: 25,
...overrides,
};
}
@@ -1,3 +1,5 @@
export { buildCombatant } from "./build-combatant.js";
export { buildCreature } from "./build-creature.js";
export { buildEncounter } from "./build-encounter.js";
export { buildPf2eCreature } from "./build-pf2e-creature.js";
export { buildPlayerCharacter } from "./build-player-character.js";
@@ -49,10 +49,9 @@ describe("loadBestiaryIndex", () => {
});
describe("getAllSourceCodes", () => {
it("returns all keys from the index sources", () => {
it("returns all index sources except bundled ones", () => {
const codes = getAllSourceCodes();
const index = loadBestiaryIndex();
expect(codes).toEqual(Object.keys(index.sources));
expect(codes).not.toContain("TGL");
});
it("returns only strings", () => {
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import {
getBundledDndSources,
loadBundledDndCreatures,
loadBundledDndIndexEntries,
} from "../dnd-bundled-adapter.js";
describe("dnd-bundled-adapter", () => {
it("loads bundled creatures with a valid shape", () => {
const creatures = loadBundledDndCreatures();
const sources = getBundledDndSources();
for (const c of creatures) {
expect(sources.has(c.source)).toBe(true);
expect(c.sourceDisplayName).toBe(sources.get(c.source));
expect(c.id.startsWith(`${c.source.toLowerCase()}:`)).toBe(true);
}
});
it("derives source codes from the creature data", () => {
const creatures = loadBundledDndCreatures();
const sources = getBundledDndSources();
const seen = new Set(creatures.map((c) => c.source));
expect(sources.size).toBe(seen.size);
for (const s of seen) {
expect(sources.has(s)).toBe(true);
}
});
it("derives index entries that match the bundled creatures", () => {
const creatures = loadBundledDndCreatures();
const entries = loadBundledDndIndexEntries();
expect(entries.length).toBe(creatures.length);
const entryNames = new Set(entries.map((e) => e.name));
for (const c of creatures) {
expect(entryNames.has(c.name)).toBe(true);
}
});
it("abbreviates sizes to single-letter codes in index entries", () => {
const entries = loadBundledDndIndexEntries();
for (const e of entries) {
expect(["T", "S", "M", "L", "H", "G"]).toContain(e.size);
}
});
});
@@ -1,6 +1,10 @@
import type { BestiaryIndex, BestiaryIndexEntry } from "@initiative/domain";
import rawIndex from "../../../../data/bestiary/index.json";
import {
getBundledDndSources,
loadBundledDndIndexEntries,
} from "./dnd-bundled-adapter.js";
interface CompactCreature {
readonly n: string;
@@ -55,23 +59,32 @@ export function loadBestiaryIndex(): BestiaryIndex {
if (cachedIndex) return cachedIndex;
const compact = rawIndex as unknown as CompactIndex;
const sources = Object.fromEntries(
const sources: Record<string, string> = Object.fromEntries(
Object.entries(compact.sources).filter(
([code]) => !EXCLUDED_SOURCES.has(code),
),
);
for (const [code, name] of getBundledDndSources()) {
sources[code] = name;
}
cachedIndex = {
sources,
creatures: compact.creatures
.filter((c) => !EXCLUDED_SOURCES.has(c.s))
.map(mapCreature),
creatures: [
...compact.creatures
.filter((c) => !EXCLUDED_SOURCES.has(c.s))
.map(mapCreature),
...loadBundledDndIndexEntries(),
],
};
return cachedIndex;
}
export function getAllSourceCodes(): string[] {
const index = loadBestiaryIndex();
return Object.keys(index.sources).filter((c) => !EXCLUDED_SOURCES.has(c));
const bundled = getBundledDndSources();
return Object.keys(index.sources).filter(
(c) => !EXCLUDED_SOURCES.has(c) && !bundled.has(c),
);
}
function sourceCodeToFilename(sourceCode: string): string {
@@ -0,0 +1,53 @@
import type { BestiaryIndexEntry, Creature } from "@initiative/domain";
import { creatureId } from "@initiative/domain";
import rawBundled from "../../../../data/bestiary/dnd-bundled.json";
type RawBundledCreature = Omit<Creature, "id"> & { id: string };
const SIZE_TO_CODE: Record<string, string> = {
Tiny: "T",
Small: "S",
Medium: "M",
Large: "L",
Huge: "H",
Gargantuan: "G",
};
/** Full normalized stat blocks for bundled D&D creatures. */
export function loadBundledDndCreatures(): Creature[] {
return (rawBundled as RawBundledCreature[]).map((c) => ({
...c,
id: creatureId(c.id),
}));
}
/** Index entries derived from the bundled creatures, in the compact shape
* used by the search index. */
export function loadBundledDndIndexEntries(): BestiaryIndexEntry[] {
return (rawBundled as RawBundledCreature[]).map((c) => ({
name: c.name,
source: c.source,
ac: c.ac,
hp: c.hp.average,
dex: c.abilities.dex,
cr: c.cr,
initiativeProficiency: c.initiativeProficiency,
size: SIZE_TO_CODE[c.size.split(" ")[0]] ?? "M",
type: c.type.split(" ")[0].toLowerCase(),
}));
}
/** Source codes → display names, derived from the bundled creatures' own
* `source` and `sourceDisplayName` fields. Adding a new book just means
* appending creatures with the right `source` field to dnd-bundled.json;
* no code change is required here. */
export function getBundledDndSources(): ReadonlyMap<string, string> {
const map = new Map<string, string>();
for (const c of rawBundled as RawBundledCreature[]) {
if (!map.has(c.source)) {
map.set(c.source, c.sourceDisplayName);
}
}
return map;
}
+26 -23
View File
@@ -9,18 +9,18 @@ import type {
} from "@initiative/domain";
export interface EncounterPersistence {
load(): Encounter | null;
save(encounter: Encounter): void;
readonly load: () => Encounter | null;
readonly save: (encounter: Encounter) => void;
}
export interface UndoRedoPersistence {
load(): UndoRedoState;
save(state: UndoRedoState): void;
readonly load: () => UndoRedoState;
readonly save: (state: UndoRedoState) => void;
}
export interface PlayerCharacterPersistence {
load(): PlayerCharacter[];
save(characters: PlayerCharacter[]): void;
readonly load: () => PlayerCharacter[];
readonly save: (characters: PlayerCharacter[]) => void;
}
export interface CachedSourceInfo {
@@ -31,31 +31,34 @@ export interface CachedSourceInfo {
}
export interface BestiaryCachePort {
cacheSource(
readonly cacheSource: (
system: string,
sourceCode: string,
displayName: string,
creatures: AnyCreature[],
): Promise<void>;
isSourceCached(system: string, sourceCode: string): Promise<boolean>;
getCachedSources(system?: string): Promise<CachedSourceInfo[]>;
clearSource(system: string, sourceCode: string): Promise<void>;
clearAll(): Promise<void>;
loadAllCachedCreatures(): Promise<Map<CreatureId, AnyCreature>>;
) => Promise<void>;
readonly isSourceCached: (
system: string,
sourceCode: string,
) => Promise<boolean>;
readonly getCachedSources: (system?: string) => Promise<CachedSourceInfo[]>;
readonly clearSource: (system: string, sourceCode: string) => Promise<void>;
readonly clearAll: () => Promise<void>;
readonly loadAllCachedCreatures: () => Promise<Map<CreatureId, AnyCreature>>;
}
export interface BestiaryIndexPort {
loadIndex(): BestiaryIndex;
getAllSourceCodes(): string[];
getDefaultFetchUrl(sourceCode: string, baseUrl?: string): string;
getSourceDisplayName(sourceCode: string): string;
readonly loadIndex: () => BestiaryIndex;
readonly getAllSourceCodes: () => string[];
readonly getDefaultFetchUrl: (sourceCode: string, baseUrl?: string) => string;
readonly getSourceDisplayName: (sourceCode: string) => string;
}
export interface Pf2eBestiaryIndexPort {
loadIndex(): Pf2eBestiaryIndex;
getAllSourceCodes(): string[];
getDefaultFetchUrl(sourceCode: string, baseUrl?: string): string;
getSourceDisplayName(sourceCode: string): string;
getCreaturePathsForSource(sourceCode: string): string[];
getCreatureNamesByPaths(paths: string[]): Map<string, string>;
readonly loadIndex: () => Pf2eBestiaryIndex;
readonly getAllSourceCodes: () => string[];
readonly getDefaultFetchUrl: (sourceCode: string, baseUrl?: string) => string;
readonly getSourceDisplayName: (sourceCode: string) => string;
readonly getCreaturePathsForSource: (sourceCode: string) => string[];
readonly getCreatureNamesByPaths: (paths: string[]) => Map<string, string>;
}
@@ -373,6 +373,26 @@ describe("CombatantRow", () => {
).toBeInTheDocument();
});
it("popover is not dimmed when the combatant is downed", async () => {
const user = userEvent.setup();
renderRow({
combatant: {
id: combatantId("1"),
name: "Goblin",
maxHp: 10,
currentHp: 0,
},
});
await user.click(screen.getByLabelText(CURRENT_HP_REGEX));
// The row dims downed combatants with opacity-50, which would cascade
// to the popover if it rendered inside the dimmed subtree.
const popover = screen
.getByRole("button", { name: "Apply damage" })
.closest(".opacity-50");
expect(popover).toBeNull();
});
it("HP section is absent when maxHp is undefined", () => {
renderRow({
combatant: {
@@ -38,6 +38,22 @@ describe("Dialog", () => {
expect(dialog?.hasAttribute("open")).toBe(false);
});
it("unmounts children when closed so internal state does not persist", () => {
const { rerender } = render(
<Dialog open={true} onClose={() => {}}>
<span>Body</span>
</Dialog>,
);
expect(screen.queryByText("Body")).not.toBeNull();
rerender(
<Dialog open={false} onClose={() => {}}>
<span>Body</span>
</Dialog>,
);
expect(screen.queryByText("Body")).toBeNull();
});
it("calls onClose on cancel event", () => {
const onClose = vi.fn();
render(
@@ -1,7 +1,11 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import type { Creature, CreatureId, PlayerCharacter } from "@initiative/domain";
import type {
AnyCreature,
CreatureId,
PlayerCharacter,
} from "@initiative/domain";
import { combatantId, creatureId, playerCharacterId } from "@initiative/domain";
import {
cleanup,
@@ -17,6 +21,7 @@ import {
buildCombatant,
buildCreature,
buildEncounter,
buildPf2eCreature,
} from "../../__tests__/factories/index.js";
import { AllProviders } from "../../__tests__/test-providers.js";
import { useRulesEdition } from "../../hooks/use-rules-edition.js";
@@ -52,7 +57,7 @@ const goblinCreature = buildCreature({
function renderPanel(options: {
encounter: ReturnType<typeof buildEncounter>;
playerCharacters?: PlayerCharacter[];
creatures?: Map<CreatureId, Creature>;
creatures?: Map<CreatureId, AnyCreature>;
onClose?: () => void;
}) {
const adapters = createTestAdapters({
@@ -357,4 +362,157 @@ describe("DifficultyBreakdownPanel", () => {
expect(onClose).toHaveBeenCalledOnce();
});
describe("PF2e edition", () => {
const orcWarrior = buildPf2eCreature({
id: creatureId("pf2e:orc-warrior"),
name: "Orc Warrior",
level: 3,
source: "crb",
sourceDisplayName: "Core Rulebook",
});
function pf2eEncounter() {
return buildEncounter({
combatants: [
buildCombatant({
id: combatantId("c-1"),
name: "Hero",
playerCharacterId: pcId1,
}),
buildCombatant({
id: combatantId("c-2"),
name: "Orc Warrior",
creatureId: orcWarrior.id,
}),
],
});
}
it("shows PF2e tier label", async () => {
const { result: editionResult } = renderHook(() => useRulesEdition());
editionResult.current.setEdition("pf2e");
try {
renderPanel({
encounter: pf2eEncounter(),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
creatures: new Map([[orcWarrior.id, orcWarrior]]),
});
await waitFor(() => {
expect(
screen.getByText("Encounter Difficulty:", { exact: false }),
).toBeInTheDocument();
});
} finally {
editionResult.current.setEdition("5.5e");
}
});
it("shows party level", async () => {
const { result: editionResult } = renderHook(() => useRulesEdition());
editionResult.current.setEdition("pf2e");
try {
renderPanel({
encounter: pf2eEncounter(),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
creatures: new Map([[orcWarrior.id, orcWarrior]]),
});
await waitFor(() => {
expect(
screen.getByText("Party Level: 5", { exact: false }),
).toBeInTheDocument();
});
} finally {
editionResult.current.setEdition("5.5e");
}
});
it("shows creature level and level difference", async () => {
const { result: editionResult } = renderHook(() => useRulesEdition());
editionResult.current.setEdition("pf2e");
try {
renderPanel({
encounter: pf2eEncounter(),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
creatures: new Map([[orcWarrior.id, orcWarrior]]),
});
await waitFor(() => {
// Orc Warrior level 3, party level 5 → diff 2
expect(
screen.getByText("Lv 3 (-2)", { exact: false }),
).toBeInTheDocument();
});
} finally {
editionResult.current.setEdition("5.5e");
}
});
it("shows 5 thresholds with short labels", async () => {
const { result: editionResult } = renderHook(() => useRulesEdition());
editionResult.current.setEdition("pf2e");
try {
renderPanel({
encounter: pf2eEncounter(),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
creatures: new Map([[orcWarrior.id, orcWarrior]]),
});
await waitFor(() => {
expect(
screen.getByText("Triv:", { exact: false }),
).toBeInTheDocument();
expect(
screen.getByText("Low:", { exact: false }),
).toBeInTheDocument();
expect(
screen.getByText("Mod:", { exact: false }),
).toBeInTheDocument();
expect(
screen.getByText("Sev:", { exact: false }),
).toBeInTheDocument();
expect(
screen.getByText("Ext:", { exact: false }),
).toBeInTheDocument();
});
} finally {
editionResult.current.setEdition("5.5e");
}
});
it("shows Net Creature XP label in PF2e mode", async () => {
const { result: editionResult } = renderHook(() => useRulesEdition());
editionResult.current.setEdition("pf2e");
try {
renderPanel({
encounter: pf2eEncounter(),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
creatures: new Map([[orcWarrior.id, orcWarrior]]),
});
await waitFor(() => {
expect(screen.getByText("Net Creature XP")).toBeInTheDocument();
});
} finally {
editionResult.current.setEdition("5.5e");
}
});
});
});
@@ -7,6 +7,7 @@ import {
DifficultyIndicator,
TIER_LABELS_5_5E,
TIER_LABELS_2014,
TIER_LABELS_PF2E,
} from "../difficulty-indicator.js";
afterEach(cleanup);
@@ -23,6 +24,7 @@ function makeResult(tier: DifficultyResult["tier"]): DifficultyResult {
encounterMultiplier: undefined,
adjustedXp: undefined,
partySizeAdjusted: undefined,
partyLevel: undefined,
};
}
@@ -125,4 +127,64 @@ describe("DifficultyIndicator", () => {
const element = container.querySelector("[role='img']");
expect(element?.tagName).toBe("BUTTON");
});
it("renders 4 bars when barCount is 4", () => {
const { container } = render(
<DifficultyIndicator
result={makeResult(2)}
labels={TIER_LABELS_PF2E}
barCount={4}
/>,
);
const bars = container.querySelectorAll("[class*='rounded-sm']");
expect(bars).toHaveLength(4);
});
it("shows 0 filled bars for tier 0 with 4 bars", () => {
const { container } = render(
<DifficultyIndicator
result={makeResult(0)}
labels={TIER_LABELS_PF2E}
barCount={4}
/>,
);
const bars = container.querySelectorAll("[class*='rounded-sm']");
for (const bar of bars) {
expect(bar.className).toContain("bg-muted");
}
});
it("shows correct PF2e tooltip for Severe tier", () => {
render(
<DifficultyIndicator
result={makeResult(3)}
labels={TIER_LABELS_PF2E}
barCount={4}
/>,
);
expect(
screen.getByRole("img", { name: "Severe encounter difficulty" }),
).toBeDefined();
});
it("shows correct PF2e tooltip for Extreme tier", () => {
render(
<DifficultyIndicator
result={makeResult(4)}
labels={TIER_LABELS_PF2E}
barCount={4}
/>,
);
expect(
screen.getByRole("img", { name: "Extreme encounter difficulty" }),
).toBeDefined();
});
it("D&D indicator still renders 3 bars (no regression)", () => {
const { container } = render(
<DifficultyIndicator result={makeResult(3)} labels={TIER_LABELS_5_5E} />,
);
const bars = container.querySelectorAll("[class*='rounded-sm']");
expect(bars).toHaveLength(3);
});
});
@@ -3,11 +3,41 @@ import "@testing-library/jest-dom/vitest";
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useEffect, useRef, useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { HpAdjustPopover } from "../hp-adjust-popover";
afterEach(cleanup);
function AnchoredPopover({
onAdjust,
onSetTempHp,
onClose,
}: Readonly<{
onAdjust: (delta: number) => void;
onSetTempHp: (value: number) => void;
onClose: () => void;
}>) {
const anchorRef = useRef<HTMLDivElement>(null);
// The popover opens on click in the app, so its anchor is always mounted
// first. Mirror that here — otherwise the anchor ref is still null when the
// popover measures its position and it renders hidden.
const [open, setOpen] = useState(false);
useEffect(() => setOpen(true), []);
return (
<div ref={anchorRef}>
{!!open && (
<HpAdjustPopover
anchorRef={anchorRef}
onAdjust={onAdjust}
onSetTempHp={onSetTempHp}
onClose={onClose}
/>
)}
</div>
);
}
function renderPopover(
overrides: Partial<{
onAdjust: (delta: number) => void;
@@ -19,7 +49,7 @@ function renderPopover(
const onSetTempHp = overrides.onSetTempHp ?? vi.fn();
const onClose = overrides.onClose ?? vi.fn();
const result = render(
<HpAdjustPopover
<AnchoredPopover
onAdjust={onAdjust}
onSetTempHp={onSetTempHp}
onClose={onClose}
@@ -1,10 +1,13 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import type { PlayerCharacter } from "@initiative/domain";
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { createRef } from "react";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { createTestAdapters } from "../../__tests__/adapters/in-memory-adapters.js";
import { buildPlayerCharacter } from "../../__tests__/factories/index.js";
import { polyfillDialog } from "../../__tests__/polyfill-dialog.js";
import { AllProviders } from "../../__tests__/test-providers.js";
import {
@@ -13,6 +16,7 @@ import {
} from "../player-character-section.js";
const CREATE_FIRST_PC_REGEX = /create your first player character/i;
const ADD_PARTY_REGEX = /add party to encounter/i;
beforeAll(() => {
polyfillDialog();
@@ -33,21 +37,28 @@ beforeAll(() => {
afterEach(cleanup);
function renderSection() {
function renderSection(playerCharacters?: PlayerCharacter[]) {
const ref = createRef<PlayerCharacterSectionHandle>();
const adapters = createTestAdapters({ playerCharacters });
const result = render(<PlayerCharacterSection ref={ref} />, {
wrapper: AllProviders,
wrapper: ({ children }) => (
<AllProviders adapters={adapters}>{children}</AllProviders>
),
});
return { ...result, ref };
}
function openManagement(ref: { current: PlayerCharacterSectionHandle | null }) {
const handle = ref.current;
if (!handle) throw new Error("ref not set");
act(() => handle.openManagement());
}
describe("PlayerCharacterSection", () => {
it("openManagement ref handle opens the management dialog", async () => {
const { ref } = renderSection();
const handle = ref.current;
if (!handle) throw new Error("ref not set");
act(() => handle.openManagement());
openManagement(ref);
// Management dialog should now be open with its title visible
await waitFor(() => {
@@ -63,9 +74,7 @@ describe("PlayerCharacterSection", () => {
const user = userEvent.setup();
const { ref } = renderSection();
const handle = ref.current;
if (!handle) throw new Error("ref not set");
act(() => handle.openManagement());
openManagement(ref);
await user.click(
screen.getByRole("button", {
@@ -83,9 +92,7 @@ describe("PlayerCharacterSection", () => {
const user = userEvent.setup();
const { ref } = renderSection();
const handle = ref.current;
if (!handle) throw new Error("ref not set");
act(() => handle.openManagement());
openManagement(ref);
await user.click(
screen.getByRole("button", {
@@ -105,4 +112,25 @@ describe("PlayerCharacterSection", () => {
expect(screen.getByText("Aria")).toBeInTheDocument();
});
});
it("adding the party puts every character into the encounter", async () => {
const user = userEvent.setup();
const party = [
buildPlayerCharacter({ name: "Thorin" }),
buildPlayerCharacter({ name: "Gandalf" }),
];
const { ref } = renderSection(party);
openManagement(ref);
await user.click(screen.getByRole("button", { name: ADD_PARTY_REGEX }));
// Dialog closes; reopening shows both characters marked as in the encounter
openManagement(ref);
await waitFor(() => {
expect(screen.getAllByLabelText("Already in encounter")).toHaveLength(2);
});
expect(
screen.getByRole("button", { name: ADD_PARTY_REGEX }),
).toBeDisabled();
});
});
@@ -1,7 +1,11 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { type PlayerCharacter, playerCharacterId } from "@initiative/domain";
import {
type PlayerCharacter,
type PlayerCharacterId,
playerCharacterId,
} from "@initiative/domain";
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
@@ -11,6 +15,7 @@ afterEach(cleanup);
const CREATE_FIRST_PC_REGEX = /create your first player character/i;
const LEVEL_REGEX = /^Lv /;
const ADD_PARTY_REGEX = /add party to encounter/i;
import { PlayerManagement } from "../player-management.js";
@@ -47,6 +52,8 @@ function renderManagement(
onEdit: vi.fn(),
onDelete: vi.fn(),
onCreate: vi.fn(),
inEncounterIds: new Set<PlayerCharacterId>(),
onAddParty: vi.fn(),
...overrides,
};
return { ...render(<PlayerManagement {...props} />), props };
@@ -117,4 +124,52 @@ describe("PlayerManagement", () => {
await user.click(screen.getByRole("button", { name: "Add" }));
expect(props.onCreate).toHaveBeenCalled();
});
it("party button calls onAddParty", async () => {
const user = userEvent.setup();
const { props } = renderManagement({
characters: [PC_WARRIOR, PC_WIZARD],
});
await user.click(screen.getByRole("button", { name: ADD_PARTY_REGEX }));
expect(props.onAddParty).toHaveBeenCalled();
});
it("party button stays enabled while some characters are missing", () => {
renderManagement({
characters: [PC_WARRIOR, PC_WIZARD],
inEncounterIds: new Set([PC_WARRIOR.id]),
});
expect(screen.getByRole("button", { name: ADD_PARTY_REGEX })).toBeEnabled();
});
it("party button is disabled when every character is in the encounter", () => {
renderManagement({
characters: [PC_WARRIOR, PC_WIZARD],
inEncounterIds: new Set([PC_WARRIOR.id, PC_WIZARD.id]),
});
expect(
screen.getByRole("button", { name: ADD_PARTY_REGEX }),
).toBeDisabled();
});
it("marks only the characters already in the encounter", () => {
renderManagement({
characters: [PC_WARRIOR, PC_WIZARD],
inEncounterIds: new Set([PC_WIZARD.id]),
});
const markers = screen.getAllByLabelText("Already in encounter");
expect(markers).toHaveLength(1);
expect(markers[0].closest("div")).toHaveTextContent("Gandalf");
});
it("has no party button in the empty state", () => {
renderManagement();
expect(
screen.queryByRole("button", { name: ADD_PARTY_REGEX }),
).not.toBeInTheDocument();
});
});
@@ -63,8 +63,11 @@ describe("SettingsModal", () => {
renderModal();
const btn5e = screen.getByRole("button", { name: "5e (2014)" });
await user.click(btn5e);
// After clicking 5e, it should have the active style
expect(btn5e.className).toContain("bg-accent");
expect(btn5e).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("button", { name: "5.5e (2024)" })).toHaveAttribute(
"aria-pressed",
"false",
);
});
it("clicking a theme button switches the active theme", async () => {
@@ -72,7 +75,7 @@ describe("SettingsModal", () => {
renderModal();
const darkBtn = screen.getByRole("button", { name: "Dark" });
await user.click(darkBtn);
expect(darkBtn.className).toContain("bg-accent");
expect(darkBtn).toHaveAttribute("aria-pressed", "true");
});
it("close button calls onClose", async () => {
@@ -1,9 +1,11 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import type { Creature } from "@initiative/domain";
import { creatureId } from "@initiative/domain";
import type { Creature, HpVariant } from "@initiative/domain";
import { combatantId, creatureId } from "@initiative/domain";
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { afterEach, describe, expect, it } from "vitest";
import { DndStatBlock as StatBlock } from "../dnd-stat-block.js";
@@ -128,6 +130,19 @@ function renderStatBlock(creature: Creature) {
return render(<StatBlock creature={creature} />);
}
/** Owns the variant the way the encounter state does in the real app. */
function HpVariantHarness({ creature }: Readonly<{ creature: Creature }>) {
const [variant, setVariant] = useState<HpVariant | undefined>(undefined);
return (
<StatBlock
creature={creature}
combatantId={combatantId("c-1")}
hpVariant={variant}
onSetHpVariant={(_id, next) => setVariant(next)}
/>
);
}
describe("StatBlock", () => {
describe("header", () => {
it("renders creature name", () => {
@@ -175,6 +190,81 @@ describe("StatBlock", () => {
});
});
describe("hit point variant", () => {
it("offers no variant buttons while browsing without a combatant", () => {
renderStatBlock(GOBLIN);
expect(
screen.queryByRole("button", { name: "Max" }),
).not.toBeInTheDocument();
});
it("hides the variant buttons when the HP formula is not a dice pool", () => {
render(
<HpVariantHarness
creature={{
...GOBLIN,
hp: { average: 50, formula: "special" },
}}
/>,
);
expect(
screen.queryByRole("button", { name: "Max" }),
).not.toBeInTheDocument();
expect(screen.getByText("50")).toBeInTheDocument();
});
it("shows the printed average until a variant is picked", () => {
render(<HpVariantHarness creature={GOBLIN} />);
expect(screen.getByText("7")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Avg" })).toHaveAttribute(
"aria-pressed",
"true",
);
});
it("shows the maximum roll after picking Max", async () => {
const user = userEvent.setup();
render(<HpVariantHarness creature={GOBLIN} />);
await user.click(screen.getByRole("button", { name: "Max" }));
expect(screen.getByText("12")).toBeInTheDocument();
expect(screen.queryByText("7")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Max" })).toHaveAttribute(
"aria-pressed",
"true",
);
});
it("shows the minimum roll after picking Min", async () => {
const user = userEvent.setup();
render(<HpVariantHarness creature={GOBLIN} />);
await user.click(screen.getByRole("button", { name: "Min" }));
expect(screen.getByText("2")).toBeInTheDocument();
});
it("returns to the average after picking Avg again", async () => {
const user = userEvent.setup();
render(<HpVariantHarness creature={GOBLIN} />);
await user.click(screen.getByRole("button", { name: "Max" }));
await user.click(screen.getByRole("button", { name: "Avg" }));
expect(screen.getByText("7")).toBeInTheDocument();
});
it("keeps showing the formula for every variant", async () => {
const user = userEvent.setup();
render(<HpVariantHarness creature={GOBLIN} />);
await user.click(screen.getByRole("button", { name: "Min" }));
expect(screen.getByText("(2d6)")).toBeInTheDocument();
});
});
describe("ability scores", () => {
it("renders all 6 ability labels", () => {
renderStatBlock(GOBLIN);
+13 -8
View File
@@ -202,6 +202,7 @@ function ClickableHp({
onSetTempHp: (value: number) => void;
}>) {
const [popoverOpen, setPopoverOpen] = useState(false);
const anchorRef = useRef<HTMLDivElement>(null);
const status = deriveHpStatus(currentHp, maxHp);
if (maxHp === undefined) {
@@ -209,7 +210,7 @@ function ClickableHp({
}
return (
<div className="relative flex items-center">
<div ref={anchorRef} className="relative flex items-center">
<button
type="button"
onClick={() => setPopoverOpen(true)}
@@ -230,6 +231,7 @@ function ClickableHp({
)}
{!!popoverOpen && (
<HpAdjustPopover
anchorRef={anchorRef}
onAdjust={onAdjust}
onSetTempHp={onSetTempHp}
onClose={() => setPopoverOpen(false)}
@@ -618,14 +620,17 @@ export function CombatantRow({
onRemove={(conditionId) => toggleCondition(id, conditionId)}
onDecrement={(conditionId) => decrementCondition(id, conditionId)}
onOpenPicker={() => setPickerOpen((prev) => !prev)}
/>
>
{isPf2e && (
<PersistentDamageTags
entries={combatant.persistentDamage}
onRemove={(damageType) =>
removePersistentDamage(id, damageType)
}
/>
)}
</ConditionTags>
</div>
{isPf2e && (
<PersistentDamageTags
entries={combatant.persistentDamage}
onRemove={(damageType) => removePersistentDamage(id, damageType)}
/>
)}
{!!pickerOpen && (
<ConditionPicker
anchorRef={conditionAnchorRef}
@@ -11,7 +11,9 @@ import {
Droplet,
Droplets,
EarOff,
Eclipse,
Eye,
EyeClosed,
EyeOff,
Flame,
FlaskConical,
@@ -24,6 +26,7 @@ import {
HeartPulse,
Link,
Moon,
Orbit,
PersonStanding,
ShieldMinus,
ShieldOff,
@@ -31,9 +34,12 @@ import {
Skull,
Snail,
Snowflake,
Sparkle,
Sparkles,
Sun,
Sword,
TrendingDown,
Wind,
Zap,
ZapOff,
} from "lucide-react";
@@ -50,7 +56,9 @@ export const CONDITION_ICON_MAP: Record<string, LucideIcon> = {
Droplet,
Droplets,
EarOff,
Eclipse,
Eye,
EyeClosed,
EyeOff,
Flame,
FlaskConical,
@@ -63,6 +71,7 @@ export const CONDITION_ICON_MAP: Record<string, LucideIcon> = {
HeartPulse,
Link,
Moon,
Orbit,
PersonStanding,
ShieldMinus,
ShieldOff,
@@ -70,9 +79,12 @@ export const CONDITION_ICON_MAP: Record<string, LucideIcon> = {
Skull,
Snail,
Snowflake,
Sparkle,
Sparkles,
Sun,
Sword,
TrendingDown,
Wind,
Zap,
ZapOff,
};
@@ -82,6 +94,7 @@ export const CONDITION_COLOR_CLASSES: Record<string, string> = {
pink: "text-pink-400",
amber: "text-amber-400",
orange: "text-orange-400",
purple: "text-purple-400",
gray: "text-gray-400",
violet: "text-violet-400",
yellow: "text-yellow-400",
@@ -5,6 +5,7 @@ import {
getConditionDescription,
} from "@initiative/domain";
import { Plus } from "lucide-react";
import type { ReactNode } from "react";
import { useRulesEditionContext } from "../contexts/rules-edition-context.js";
import { cn } from "../lib/utils.js";
import {
@@ -18,6 +19,7 @@ interface ConditionTagsProps {
onRemove: (conditionId: ConditionId) => void;
onDecrement: (conditionId: ConditionId) => void;
onOpenPicker: () => void;
children?: ReactNode;
}
export function ConditionTags({
@@ -25,6 +27,7 @@ export function ConditionTags({
onRemove,
onDecrement,
onOpenPicker,
children,
}: Readonly<ConditionTagsProps>) {
const { edition } = useRulesEditionContext();
return (
@@ -69,6 +72,7 @@ export function ConditionTags({
</Tooltip>
);
})}
{children}
<button
type="button"
title="Add condition"
@@ -19,12 +19,21 @@ const TIER_LABEL_MAP: Partial<
1: { label: "Low", color: "text-green-500" },
2: { label: "Moderate", color: "text-yellow-500" },
3: { label: "High", color: "text-red-500" },
4: { label: "High", color: "text-red-500" },
},
"5e": {
0: { label: "Easy", color: "text-muted-foreground" },
1: { label: "Medium", color: "text-green-500" },
2: { label: "Hard", color: "text-yellow-500" },
3: { label: "Deadly", color: "text-red-500" },
4: { label: "Deadly", color: "text-red-500" },
},
pf2e: {
0: { label: "Trivial", color: "text-muted-foreground" },
1: { label: "Low", color: "text-green-500" },
2: { label: "Moderate", color: "text-yellow-500" },
3: { label: "Severe", color: "text-orange-500" },
4: { label: "Extreme", color: "text-red-500" },
},
};
@@ -32,6 +41,9 @@ const TIER_LABEL_MAP: Partial<
const SHORT_LABELS: Readonly<Record<string, string>> = {
Moderate: "Mod",
Medium: "Med",
Trivial: "Triv",
Severe: "Sev",
Extreme: "Ext",
};
function shortLabel(label: string): string {
@@ -107,6 +119,54 @@ function NpcRow({
);
}
function Pf2eNpcRow({
entry,
onToggleSide,
}: {
entry: BreakdownCombatant;
onToggleSide: () => void;
}) {
const isParty = entry.side === "party";
const targetSide = isParty ? "enemy" : "party";
let xpDisplay: string;
if (entry.xp == null) {
xpDisplay = "\u2014";
} else if (isParty) {
xpDisplay = `\u2212${formatXp(entry.xp)}`;
} else {
xpDisplay = formatXp(entry.xp);
}
let levelDisplay: string;
if (entry.creatureLevel === undefined) {
levelDisplay = "\u2014";
} else if (entry.levelDifference === undefined) {
levelDisplay = `Lv ${entry.creatureLevel}`;
} else {
const sign = entry.levelDifference >= 0 ? "+" : "";
levelDisplay = `Lv ${entry.creatureLevel} (${sign}${entry.levelDifference})`;
}
return (
<div className="col-span-4 grid grid-cols-subgrid items-center text-xs">
<span className="min-w-0 truncate" title={entry.combatant.name}>
{entry.combatant.name}
</span>
<Button
variant="ghost"
size="icon-sm"
onClick={onToggleSide}
aria-label={`Move ${entry.combatant.name} to ${targetSide} side`}
>
<ArrowLeftRight className="h-3 w-3" />
</Button>
<span className="text-muted-foreground">{levelDisplay}</span>
<span className="text-right tabular-nums">{xpDisplay}</span>
</div>
);
}
export function DifficultyBreakdownPanel({ onClose }: { onClose: () => void }) {
const ref = useRef<HTMLDivElement>(null);
useClickOutside(ref, onClose);
@@ -128,6 +188,8 @@ export function DifficultyBreakdownPanel({ onClose }: { onClose: () => void }) {
const isPC = (entry: BreakdownCombatant) =>
entry.combatant.playerCharacterId != null;
const CreatureRow = edition === "pf2e" ? Pf2eNpcRow : NpcRow;
return (
<div
ref={ref}
@@ -142,6 +204,9 @@ export function DifficultyBreakdownPanel({ onClose }: { onClose: () => void }) {
<div className="mb-1 text-muted-foreground text-xs">
Party Budget ({breakdown.pcCount}{" "}
{breakdown.pcCount === 1 ? "PC" : "PCs"})
{breakdown.partyLevel !== undefined && (
<> &middot; Party Level: {breakdown.partyLevel}</>
)}
</div>
<div className="flex gap-3 text-xs">
{breakdown.thresholds.map((t) => (
@@ -166,7 +231,7 @@ export function DifficultyBreakdownPanel({ onClose }: { onClose: () => void }) {
isPC(entry) ? (
<PcRow key={entry.combatant.id} entry={entry} />
) : (
<NpcRow
<CreatureRow
key={entry.combatant.id}
entry={entry}
onToggleSide={() => handleToggle(entry)}
@@ -186,7 +251,7 @@ export function DifficultyBreakdownPanel({ onClose }: { onClose: () => void }) {
isPC(entry) ? (
<PcRow key={entry.combatant.id} entry={entry} />
) : (
<NpcRow
<CreatureRow
key={entry.combatant.id}
entry={entry}
onToggleSide={() => handleToggle(entry)}
@@ -218,7 +283,9 @@ export function DifficultyBreakdownPanel({ onClose }: { onClose: () => void }) {
</div>
) : (
<div className="mt-2 flex justify-between border-border border-t pt-2 font-medium text-xs">
<span>Net Monster XP</span>
<span>
{edition === "pf2e" ? "Net Creature XP" : "Net Monster XP"}
</span>
<span className="tabular-nums">
{formatXp(breakdown.totalMonsterXp)}
</span>
@@ -6,6 +6,7 @@ export const TIER_LABELS_5_5E: Record<DifficultyTier, string> = {
1: "Low",
2: "Moderate",
3: "High",
4: "High",
};
export const TIER_LABELS_2014: Record<DifficultyTier, string> = {
@@ -13,30 +14,49 @@ export const TIER_LABELS_2014: Record<DifficultyTier, string> = {
1: "Medium",
2: "Hard",
3: "Deadly",
4: "Deadly",
};
const TIER_COLORS: Record<
DifficultyTier,
{ filledBars: number; color: string }
> = {
0: { filledBars: 0, color: "" },
1: { filledBars: 1, color: "bg-green-500" },
2: { filledBars: 2, color: "bg-yellow-500" },
3: { filledBars: 3, color: "bg-red-500" },
export const TIER_LABELS_PF2E: Record<DifficultyTier, string> = {
0: "Trivial",
1: "Low",
2: "Moderate",
3: "Severe",
4: "Extreme",
};
const BAR_HEIGHTS = ["h-2", "h-3", "h-4"] as const;
const BAR_HEIGHTS_3 = ["h-2", "h-3", "h-4"] as const;
const BAR_HEIGHTS_4 = ["h-1.5", "h-2", "h-3", "h-4"] as const;
/** Color for the Nth filled bar (1-indexed) in 4-bar mode. */
const BAR_COLORS: Record<number, string> = {
1: "bg-green-500",
2: "bg-yellow-500",
3: "bg-orange-500",
4: "bg-red-500",
};
/** For 3-bar mode, bar 3 uses red directly (skip orange). */
const BAR_COLORS_3: Record<number, string> = {
1: "bg-green-500",
2: "bg-yellow-500",
3: "bg-red-500",
};
export function DifficultyIndicator({
result,
labels,
barCount = 3,
onClick,
}: {
result: DifficultyResult;
labels: Record<DifficultyTier, string>;
barCount?: 3 | 4;
onClick?: () => void;
}) {
const config = TIER_COLORS[result.tier];
const barHeights = barCount === 4 ? BAR_HEIGHTS_4 : BAR_HEIGHTS_3;
const colorMap = barCount === 4 ? BAR_COLORS : BAR_COLORS_3;
const filledBars = result.tier;
const label = labels[result.tier];
const tooltip = `${label} encounter difficulty`;
@@ -54,13 +74,13 @@ export function DifficultyIndicator({
onClick={onClick}
type={onClick ? "button" : undefined}
>
{BAR_HEIGHTS.map((height, i) => (
{barHeights.map((height, i) => (
<div
key={height}
className={cn(
"w-1 rounded-sm",
height,
i < config.filledBars ? config.color : "bg-muted",
i < filledBars ? colorMap[i + 1] : "bg-muted",
)}
/>
))}
+63 -3
View File
@@ -1,17 +1,34 @@
import type { Creature } from "@initiative/domain";
import type {
CombatantId,
Creature,
HpRange,
HpVariant,
} from "@initiative/domain";
import {
calculateInitiative,
formatInitiativeModifier,
hpForVariant,
hpRange,
} from "@initiative/domain";
import { cn } from "../lib/utils.js";
import {
PropertyLine,
SectionDivider,
TraitEntry,
TraitSection,
} from "./stat-block-parts.js";
import type { SegmentedOption } from "./ui/segmented-control.js";
import { SegmentedControl } from "./ui/segmented-control.js";
interface DndStatBlockProps {
creature: Creature;
combatantId?: CombatantId;
hpVariant?: HpVariant;
onSetHpVariant?: (
id: CombatantId,
variant: HpVariant | undefined,
range: HpRange,
) => void;
}
function abilityMod(score: number): string {
@@ -19,7 +36,25 @@ function abilityMod(score: number): string {
return mod >= 0 ? `+${mod}` : `${mod}`;
}
export function DndStatBlock({ creature }: Readonly<DndStatBlockProps>) {
/** Text color for a max HP that no longer shows the printed average. */
function hpVariantColor(variant: HpVariant | undefined): string {
if (variant === "max") return "text-blue-400";
if (variant === "min") return "text-red-400";
return "";
}
const HP_VARIANT_OPTIONS: SegmentedOption<HpVariant | undefined>[] = [
{ value: "min", label: "Min" },
{ value: undefined, label: "Avg" },
{ value: "max", label: "Max" },
];
export function DndStatBlock({
creature,
combatantId,
hpVariant,
onSetHpVariant,
}: Readonly<DndStatBlockProps>) {
const abilities = [
{ label: "STR", score: creature.abilities.str },
{ label: "DEX", score: creature.abilities.dex },
@@ -35,6 +70,17 @@ export function DndStatBlock({ creature }: Readonly<DndStatBlockProps>) {
initiativeProficiency: creature.initiativeProficiency,
});
// Only offer min/max HP when the formula is a real dice pool with a spread.
const range = hpRange(creature.hp);
const canPickVariant =
range !== null &&
range.min !== range.max &&
combatantId != null &&
onSetHpVariant != null;
const displayedHp = range
? hpForVariant(range, hpVariant)
: creature.hp.average;
return (
<div className="space-y-1 text-foreground">
{/* Header */}
@@ -68,8 +114,22 @@ export function DndStatBlock({ creature }: Readonly<DndStatBlockProps>) {
</div>
<div>
<span className="font-semibold">Hit Points</span>{" "}
{creature.hp.average}{" "}
<span className={cn("font-semibold", hpVariantColor(hpVariant))}>
{displayedHp}
</span>{" "}
<span className="text-muted-foreground">({creature.hp.formula})</span>
{canPickVariant ? (
<SegmentedControl
options={HP_VARIANT_OPTIONS}
value={hpVariant}
onChange={(variant) =>
onSetHpVariant(combatantId, variant, range)
}
size="xs"
label="Hit point variant"
className="mt-1"
/>
) : null}
</div>
<div>
<span className="font-semibold">Speed</span> {creature.speed}
+11 -8
View File
@@ -6,18 +6,21 @@ import {
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { useClickOutside } from "../hooks/use-click-outside.js";
import { Input } from "./ui/input";
const DIGITS_ONLY_REGEX = /^\d+$/;
interface HpAdjustPopoverProps {
readonly anchorRef: React.RefObject<HTMLElement | null>;
readonly onAdjust: (delta: number) => void;
readonly onSetTempHp: (value: number) => void;
readonly onClose: () => void;
}
export function HpAdjustPopover({
anchorRef,
onAdjust,
onSetTempHp,
onClose,
@@ -29,10 +32,9 @@ export function HpAdjustPopover({
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const parent = el.parentElement;
if (!parent) return;
const trigger = parent.getBoundingClientRect();
const anchor = anchorRef.current;
if (!el || !anchor) return;
const trigger = anchor.getBoundingClientRect();
const popover = el.getBoundingClientRect();
const vw = document.documentElement.clientWidth;
let left = trigger.left;
@@ -43,7 +45,7 @@ export function HpAdjustPopover({
left = 8;
}
setPos({ top: trigger.bottom + 4, left });
}, []);
}, [anchorRef]);
useEffect(() => {
requestAnimationFrame(() => inputRef.current?.focus());
@@ -82,10 +84,10 @@ export function HpAdjustPopover({
[applyDelta, onClose],
);
return (
return createPortal(
<div
ref={ref}
className="card-glow fixed z-10 rounded-lg border border-border bg-background p-2"
className="card-glow fixed z-50 rounded-lg border border-border bg-background p-2"
style={
pos
? { top: pos.top, left: pos.left }
@@ -144,6 +146,7 @@ export function HpAdjustPopover({
<ShieldPlus size={14} />
</button>
</div>
</div>
</div>,
document.body,
);
}
+18 -23
View File
@@ -15,6 +15,8 @@ import {
SectionDivider,
TraitSection,
} from "./stat-block-parts.js";
import type { SegmentedOption } from "./ui/segmented-control.js";
import { SegmentedControl } from "./ui/segmented-control.js";
interface Pf2eStatBlockProps {
creature: Pf2eCreature;
@@ -52,6 +54,12 @@ function formatMod(mod: number): string {
return mod >= 0 ? `+${mod}` : `${mod}`;
}
const ADJUSTMENT_OPTIONS: SegmentedOption<"weak" | "elite" | undefined>[] = [
{ value: "weak", label: "Weak" },
{ value: undefined, label: "Normal" },
{ value: "elite", label: "Elite" },
];
/** Returns the text color class for stats affected by weak/elite adjustment. */
function adjustmentColor(adjustment: "weak" | "elite" | undefined): string {
if (adjustment === "elite") return "text-blue-400";
@@ -213,29 +221,16 @@ export function Pf2eStatBlock({
{combatantId != null &&
onSetAdjustment != null &&
baseCreature != null && (
<div className="mt-1 flex gap-1">
{(["weak", "normal", "elite"] as const).map((opt) => {
const value = opt === "normal" ? undefined : opt;
const isActive = adjustment === value;
return (
<button
key={opt}
type="button"
className={cn(
"rounded px-2 py-0.5 font-medium text-xs capitalize",
isActive
? "bg-accent text-primary-foreground"
: "bg-card text-muted-foreground hover:bg-accent/30",
)}
onClick={() =>
onSetAdjustment(combatantId, value, baseCreature)
}
>
{opt}
</button>
);
})}
</div>
<SegmentedControl
options={ADJUSTMENT_OPTIONS}
value={adjustment}
onChange={(value) =>
onSetAdjustment(combatantId, value, baseCreature)
}
size="xs"
label="Creature adjustment"
className="mt-1"
/>
)}
<div className="mt-1 flex flex-wrap gap-1">
{displayTraits(creature.traits).map((trait) => (
@@ -1,5 +1,6 @@
import type { PlayerCharacter } from "@initiative/domain";
import { type RefObject, useImperativeHandle, useState } from "react";
import type { PlayerCharacter, PlayerCharacterId } from "@initiative/domain";
import { type RefObject, useImperativeHandle, useMemo, useState } from "react";
import { useEncounterContext } from "../contexts/encounter-context.js";
import { usePlayerCharactersContext } from "../contexts/player-characters-context.js";
import { CreatePlayerModal } from "./create-player-modal.js";
import { PlayerManagement } from "./player-management.js";
@@ -15,6 +16,15 @@ export const PlayerCharacterSection = function PlayerCharacterSectionInner({
}) {
const { characters, createCharacter, editCharacter, deleteCharacter } =
usePlayerCharactersContext();
const { encounter, addParty } = useEncounterContext();
const inEncounterIds = useMemo(() => {
const ids = new Set<PlayerCharacterId>();
for (const c of encounter.combatants) {
if (c.playerCharacterId) ids.add(c.playerCharacterId);
}
return ids;
}, [encounter.combatants]);
const [managementOpen, setManagementOpen] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
@@ -66,6 +76,11 @@ export const PlayerCharacterSection = function PlayerCharacterSectionInner({
setCreateOpen(true);
setManagementOpen(false);
}}
inEncounterIds={inEncounterIds}
onAddParty={() => {
addParty(characters);
setManagementOpen(false);
}}
/>
</>
);
+34 -2
View File
@@ -1,5 +1,5 @@
import type { PlayerCharacter, PlayerCharacterId } from "@initiative/domain";
import { Pencil, Plus, Trash2 } from "lucide-react";
import { Pencil, Plus, Swords, Trash2 } from "lucide-react";
import { PLAYER_COLOR_HEX, PLAYER_ICON_MAP } from "./player-icon-map";
import { Button } from "./ui/button";
import { ConfirmButton } from "./ui/confirm-button";
@@ -12,8 +12,12 @@ interface PlayerManagementProps {
onEdit: (pc: PlayerCharacter) => void;
onDelete: (id: PlayerCharacterId) => void;
onCreate: () => void;
inEncounterIds: ReadonlySet<PlayerCharacterId>;
onAddParty: () => void;
}
const IN_ENCOUNTER_LABEL = "Already in encounter";
export function PlayerManagement({
open,
onClose,
@@ -21,7 +25,13 @@ export function PlayerManagement({
onEdit,
onDelete,
onCreate,
inEncounterIds,
onAddParty,
}: Readonly<PlayerManagementProps>) {
const addableCount = characters.filter(
(pc) => !inEncounterIds.has(pc.id),
).length;
return (
<Dialog open={open} onClose={onClose} className="card-glow w-full max-w-md">
<DialogHeader title="Player Characters" onClose={onClose} />
@@ -61,6 +71,16 @@ export function PlayerManagement({
Lv {pc.level}
</span>
)}
{inEncounterIds.has(pc.id) && (
<span
role="img"
aria-label={IN_ENCOUNTER_LABEL}
title={IN_ENCOUNTER_LABEL}
className="text-muted-foreground"
>
<Swords size={14} />
</span>
)}
<Button
variant="ghost"
size="icon-sm"
@@ -80,7 +100,19 @@ export function PlayerManagement({
</div>
);
})}
<div className="mt-2 flex justify-end">
<div className="mt-2 flex items-center justify-between gap-2">
<Button
onClick={onAddParty}
disabled={addableCount === 0}
title={
addableCount === 0
? "All player characters are already in the encounter"
: undefined
}
>
<Swords size={16} />
Add party to encounter
</Button>
<Button onClick={onCreate} variant="ghost">
<Plus size={16} />
Add
+47 -48
View File
@@ -2,28 +2,51 @@ import type { RulesEdition } from "@initiative/domain";
import { Monitor, Moon, Sun } from "lucide-react";
import { useRulesEditionContext } from "../contexts/rules-edition-context.js";
import { useThemeContext } from "../contexts/theme-context.js";
import { cn } from "../lib/utils.js";
import { Dialog, DialogHeader } from "./ui/dialog.js";
import type { SegmentedOption } from "./ui/segmented-control.js";
import { SegmentedControl } from "./ui/segmented-control.js";
interface SettingsModalProps {
open: boolean;
onClose: () => void;
}
const EDITION_OPTIONS: { value: RulesEdition; label: string }[] = [
const EDITION_OPTIONS: SegmentedOption<RulesEdition>[] = [
{ value: "5e", label: "5e (2014)" },
{ value: "5.5e", label: "5.5e (2024)" },
{ value: "pf2e", label: "Pathfinder 2e" },
];
const THEME_OPTIONS: {
value: "system" | "light" | "dark";
label: string;
icon: typeof Sun;
}[] = [
{ value: "system", label: "System", icon: Monitor },
{ value: "light", label: "Light", icon: Sun },
{ value: "dark", label: "Dark", icon: Moon },
type ThemePreference = "system" | "light" | "dark";
const THEME_OPTIONS: SegmentedOption<ThemePreference>[] = [
{
value: "system",
label: (
<>
<Monitor size={14} />
System
</>
),
},
{
value: "light",
label: (
<>
<Sun size={14} />
Light
</>
),
},
{
value: "dark",
label: (
<>
<Moon size={14} />
Dark
</>
),
},
];
export function SettingsModal({ open, onClose }: Readonly<SettingsModalProps>) {
@@ -39,50 +62,26 @@ export function SettingsModal({ open, onClose }: Readonly<SettingsModalProps>) {
<span className="mb-2 block font-medium text-muted-foreground text-sm">
Game System
</span>
<div className="flex gap-1">
{EDITION_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
className={cn(
"flex-1 rounded-md px-3 py-1.5 text-sm transition-colors",
edition === opt.value
? "bg-accent text-primary-foreground"
: "bg-card text-muted-foreground hover:bg-hover-neutral-bg hover:text-foreground",
)}
onClick={() => setEdition(opt.value)}
>
{opt.label}
</button>
))}
</div>
<SegmentedControl
options={EDITION_OPTIONS}
value={edition}
onChange={setEdition}
stretch
label="Game System"
/>
</div>
<div>
<span className="mb-2 block font-medium text-muted-foreground text-sm">
Theme
</span>
<div className="flex gap-1">
{THEME_OPTIONS.map((opt) => {
const Icon = opt.icon;
return (
<button
key={opt.value}
type="button"
className={cn(
"flex flex-1 items-center justify-center gap-1.5 rounded-md px-3 py-1.5 text-sm transition-colors",
preference === opt.value
? "bg-accent text-primary-foreground"
: "bg-card text-muted-foreground hover:bg-hover-neutral-bg hover:text-foreground",
)}
onClick={() => setPreference(opt.value)}
>
<Icon size={14} />
{opt.label}
</button>
);
})}
</div>
<SegmentedControl
options={THEME_OPTIONS}
value={preference}
onChange={setPreference}
stretch
label="Theme"
/>
</div>
</div>
</Dialog>
+32 -8
View File
@@ -4,6 +4,8 @@ import type {
CombatantId,
Creature,
CreatureId,
HpRange,
HpVariant,
Pf2eCreature,
} from "@initiative/domain";
import { applyPf2eAdjustment } from "@initiative/domain";
@@ -225,7 +227,8 @@ function MobileDrawer({
function usePanelRole(panelRole: "browse" | "pinned") {
const sidePanel = useSidePanelContext();
const { getCreature } = useBestiaryContext();
const { encounter, setCreatureAdjustment } = useEncounterContext();
const { encounter, setCreatureAdjustment, setHpVariant } =
useEncounterContext();
const creatureId =
panelRole === "browse"
@@ -245,6 +248,7 @@ function usePanelRole(panelRole: "browse" | "pinned") {
creature,
combatant,
setCreatureAdjustment,
setHpVariant,
isCollapsed: isBrowse ? sidePanel.isRightPanelCollapsed : false,
onToggleCollapse: isBrowse ? sidePanel.toggleCollapse : () => {},
onDismiss: isBrowse ? sidePanel.dismissPanel : () => {},
@@ -256,14 +260,23 @@ function usePanelRole(panelRole: "browse" | "pinned") {
};
}
function renderStatBlock(
creature: AnyCreature,
combatant: Combatant | null,
interface StatBlockHandlers {
setCreatureAdjustment: (
id: CombatantId,
adj: "weak" | "elite" | undefined,
base: Pf2eCreature,
) => void,
) => void;
setHpVariant: (
id: CombatantId,
variant: HpVariant | undefined,
range: HpRange,
) => void;
}
function renderStatBlock(
creature: AnyCreature,
combatant: Combatant | null,
handlers: StatBlockHandlers,
) {
if ("system" in creature && creature.system === "pf2e") {
const baseCreature = creature;
@@ -276,11 +289,18 @@ function renderStatBlock(
adjustment={combatant?.creatureAdjustment}
combatantId={combatant?.id}
baseCreature={baseCreature}
onSetAdjustment={setCreatureAdjustment}
onSetAdjustment={handlers.setCreatureAdjustment}
/>
);
}
return <DndStatBlock creature={creature as Creature} />;
return (
<DndStatBlock
creature={creature as Creature}
combatantId={combatant?.id}
hpVariant={combatant?.hpVariant}
onSetHpVariant={handlers.setHpVariant}
/>
);
}
export function StatBlockPanel({
@@ -292,6 +312,7 @@ export function StatBlockPanel({
creature,
combatant,
setCreatureAdjustment,
setHpVariant,
isCollapsed,
onToggleCollapse,
onDismiss,
@@ -363,7 +384,10 @@ export function StatBlockPanel({
}
if (creature) {
return renderStatBlock(creature, combatant, setCreatureAdjustment);
return renderStatBlock(creature, combatant, {
setCreatureAdjustment,
setHpVariant,
});
}
if (needsFetch && sourceCode) {
+9 -1
View File
@@ -8,6 +8,7 @@ import {
DifficultyIndicator,
TIER_LABELS_5_5E,
TIER_LABELS_2014,
TIER_LABELS_PF2E,
} from "./difficulty-indicator.js";
import { Button } from "./ui/button.js";
import { ConfirmButton } from "./ui/confirm-button.js";
@@ -26,7 +27,13 @@ export function TurnNavigation() {
const difficulty = useDifficulty();
const { edition } = useRulesEditionContext();
const tierLabels = edition === "5e" ? TIER_LABELS_2014 : TIER_LABELS_5_5E;
const TIER_LABELS_BY_EDITION = {
pf2e: TIER_LABELS_PF2E,
"5e": TIER_LABELS_2014,
"5.5e": TIER_LABELS_5_5E,
} as const;
const tierLabels = TIER_LABELS_BY_EDITION[edition];
const barCount = edition === "pf2e" ? 4 : 3;
const [showBreakdown, setShowBreakdown] = useState(false);
const hasCombatants = encounter.combatants.length > 0;
const isAtStart = encounter.roundNumber === 1 && encounter.activeIndex === 0;
@@ -87,6 +94,7 @@ export function TurnNavigation() {
<DifficultyIndicator
result={difficulty}
labels={tierLabels}
barCount={barCount}
onClick={() => setShowBreakdown((prev) => !prev)}
/>
{showBreakdown ? (
+1 -1
View File
@@ -46,7 +46,7 @@ export function Dialog({ open, onClose, className, children }: DialogProps) {
className,
)}
>
<div className="p-6">{children}</div>
{open ? <div className="p-6">{children}</div> : null}
</dialog>
);
}
@@ -0,0 +1,59 @@
import type { ReactNode } from "react";
import { cn } from "../../lib/utils.js";
export interface SegmentedOption<T> {
readonly value: T;
readonly label: ReactNode;
}
interface SegmentedControlProps<T> {
options: readonly SegmentedOption<T>[];
value: T;
onChange: (value: T) => void;
/** "sm" for standalone controls, "xs" for controls inline in a stat block. */
size?: "sm" | "xs";
/** Segments share the full width of the row instead of hugging their label. */
stretch?: boolean;
label?: string;
className?: string;
}
/**
* A row of mutually exclusive options where exactly one is active — game
* system, theme, PF2e adjustment, D&D hit point variant.
*/
export function SegmentedControl<T>({
options,
value,
onChange,
size = "sm",
stretch = false,
label,
className,
}: Readonly<SegmentedControlProps<T>>) {
return (
<fieldset aria-label={label} className={cn("flex gap-1", className)}>
{options.map((option) => {
const isActive = option.value === value;
return (
<button
key={String(option.value)}
type="button"
aria-pressed={isActive}
className={cn(
"flex items-center justify-center gap-1.5 rounded-md font-medium transition-colors",
size === "xs" ? "px-2 py-0.5 text-xs" : "px-3 py-1.5 text-sm",
stretch ? "flex-1" : "",
isActive
? "bg-accent text-primary-foreground"
: "bg-card text-muted-foreground hover:bg-hover-neutral-bg hover:text-foreground",
)}
onClick={() => onChange(option.value)}
>
{option.label}
</button>
);
})}
</fieldset>
);
}
@@ -1,5 +1,9 @@
// @vitest-environment jsdom
import type { Creature, CreatureId, PlayerCharacter } from "@initiative/domain";
import type {
AnyCreature,
CreatureId,
PlayerCharacter,
} from "@initiative/domain";
import { combatantId, creatureId, playerCharacterId } from "@initiative/domain";
import { renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
@@ -9,6 +13,7 @@ import {
buildCombatant,
buildCreature,
buildEncounter,
buildPf2eCreature,
} from "../../__tests__/factories/index.js";
import { AllProviders } from "../../__tests__/test-providers.js";
import { useDifficultyBreakdown } from "../use-difficulty-breakdown.js";
@@ -42,7 +47,7 @@ const goblinCreature = buildCreature({
function makeWrapper(options: {
encounter: ReturnType<typeof buildEncounter>;
playerCharacters?: PlayerCharacter[];
creatures?: Map<CreatureId, Creature>;
creatures?: Map<CreatureId, AnyCreature>;
}) {
const adapters = createTestAdapters({
encounter: options.encounter,
@@ -345,4 +350,115 @@ describe("useDifficultyBreakdown", () => {
editionResult.current.setEdition("5.5e");
}
});
describe("PF2e edition", () => {
const orcWarrior = buildPf2eCreature({
id: creatureId("pf2e:orc-warrior"),
name: "Orc Warrior",
level: 3,
source: "crb",
sourceDisplayName: "Core Rulebook",
});
it("returns breakdown with creatureLevel, levelDifference, and XP for PF2e creatures", async () => {
const wrapper = makeWrapper({
encounter: buildEncounter({
combatants: [
buildCombatant({
id: combatantId("c-1"),
name: "Hero",
playerCharacterId: pcId1,
}),
buildCombatant({
id: combatantId("c-2"),
name: "Orc Warrior",
creatureId: orcWarrior.id,
}),
],
}),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
creatures: new Map([[orcWarrior.id, orcWarrior]]),
});
const { result: editionResult } = renderHook(() => useRulesEdition(), {
wrapper,
});
editionResult.current.setEdition("pf2e");
try {
const { result } = renderHook(() => useDifficultyBreakdown(), {
wrapper,
});
await waitFor(() => {
const breakdown = result.current;
expect(breakdown).not.toBeNull();
// Party level should be 5
expect(breakdown?.partyLevel).toBe(5);
// Orc Warrior: level 3, party level 5 → diff 2 → 20 XP
const orc = breakdown?.enemyCombatants[0];
expect(orc?.creatureLevel).toBe(3);
expect(orc?.levelDifference).toBe(-2);
expect(orc?.xp).toBe(20);
expect(orc?.cr).toBeNull();
expect(orc?.source).toBe("Core Rulebook");
// PC should have no creature level
const pc = breakdown?.partyCombatants[0];
expect(pc?.creatureLevel).toBeUndefined();
expect(pc?.levelDifference).toBeUndefined();
});
} finally {
editionResult.current.setEdition("5.5e");
}
});
it("returns partyLevel in result", async () => {
const wrapper = makeWrapper({
encounter: buildEncounter({
combatants: [
buildCombatant({
id: combatantId("c-1"),
name: "Hero",
playerCharacterId: pcId1,
}),
buildCombatant({
id: combatantId("c-2"),
name: "Orc Warrior",
creatureId: orcWarrior.id,
}),
],
}),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
creatures: new Map([[orcWarrior.id, orcWarrior]]),
});
const { result: editionResult } = renderHook(() => useRulesEdition(), {
wrapper,
});
editionResult.current.setEdition("pf2e");
try {
const { result } = renderHook(() => useDifficultyBreakdown(), {
wrapper,
});
await waitFor(() => {
expect(result.current).not.toBeNull();
expect(result.current?.partyLevel).toBe(5);
// 5 thresholds for PF2e
expect(result.current?.thresholds).toHaveLength(5);
expect(result.current?.thresholds[0].label).toBe("Trivial");
});
} finally {
editionResult.current.setEdition("5.5e");
}
});
});
});
@@ -1,5 +1,9 @@
// @vitest-environment jsdom
import type { Creature, CreatureId, PlayerCharacter } from "@initiative/domain";
import type {
AnyCreature,
CreatureId,
PlayerCharacter,
} from "@initiative/domain";
import { combatantId, creatureId, playerCharacterId } from "@initiative/domain";
import { renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
@@ -9,6 +13,7 @@ import {
buildCombatant,
buildCreature,
buildEncounter,
buildPf2eCreature,
} from "../../__tests__/factories/index.js";
import { AllProviders } from "../../__tests__/test-providers.js";
import { useDifficulty } from "../use-difficulty.js";
@@ -43,7 +48,7 @@ const goblinCreature = buildCreature({
function makeWrapper(options: {
encounter: ReturnType<typeof buildEncounter>;
playerCharacters?: PlayerCharacter[];
creatures?: Map<CreatureId, Creature>;
creatures?: Map<CreatureId, AnyCreature>;
}) {
const adapters = createTestAdapters({
encounter: options.encounter,
@@ -336,10 +341,10 @@ describe("useDifficulty", () => {
await waitFor(() => {
expect(result.current).not.toBeNull();
// Level 3 budget: low=150, mod=225, high=400
// CR 1/4 = 50 XP -> trivial
// CR 1/4 = 50 XP ≤ 150 Low budget -> Low
expect(result.current?.thresholds[0].value).toBe(150);
expect(result.current?.totalMonsterXp).toBe(50);
expect(result.current?.tier).toBe(0);
expect(result.current?.tier).toBe(1);
});
});
@@ -424,4 +429,134 @@ describe("useDifficulty", () => {
expect(result.current?.totalMonsterXp).toBe(0);
});
});
describe("PF2e edition", () => {
const pf2eCreature = buildPf2eCreature({
id: creatureId("pf2e:orc-warrior"),
name: "Orc Warrior",
level: 5,
});
function makePf2eWrapper(options: {
encounter: ReturnType<typeof buildEncounter>;
playerCharacters?: PlayerCharacter[];
creatures?: Map<CreatureId, AnyCreature>;
}) {
const adapters = createTestAdapters({
encounter: options.encounter,
playerCharacters: options.playerCharacters ?? [],
creatures: options.creatures,
});
return ({ children }: { children: ReactNode }) => (
<AllProviders adapters={adapters}>{children}</AllProviders>
);
}
it("returns result for PF2e with leveled PCs and PF2e creatures", async () => {
const wrapper = makePf2eWrapper({
encounter: buildEncounter({
combatants: [
buildCombatant({
id: combatantId("c1"),
name: "Hero",
playerCharacterId: pcId1,
}),
buildCombatant({
id: combatantId("c2"),
name: "Orc Warrior",
creatureId: pf2eCreature.id,
}),
],
}),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
creatures: new Map([[pf2eCreature.id, pf2eCreature]]),
});
const { result: editionResult } = renderHook(() => useRulesEdition(), {
wrapper,
});
editionResult.current.setEdition("pf2e");
try {
const { result } = renderHook(() => useDifficulty(), { wrapper });
await waitFor(() => {
expect(result.current).not.toBeNull();
// Creature level 5, party level 5 → diff 0 → 40 XP
expect(result.current?.totalMonsterXp).toBe(40);
expect(result.current?.partyLevel).toBe(5);
});
} finally {
editionResult.current.setEdition("5.5e");
}
});
it("returns null for PF2e when no PF2e creatures with level", () => {
const wrapper = makePf2eWrapper({
encounter: buildEncounter({
combatants: [
buildCombatant({
id: combatantId("c1"),
name: "Hero",
playerCharacterId: pcId1,
}),
buildCombatant({
id: combatantId("c2"),
name: "Custom Monster",
}),
],
}),
playerCharacters: [
{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 },
],
});
const { result: editionResult } = renderHook(() => useRulesEdition(), {
wrapper,
});
editionResult.current.setEdition("pf2e");
try {
const { result } = renderHook(() => useDifficulty(), { wrapper });
expect(result.current).toBeNull();
} finally {
editionResult.current.setEdition("5.5e");
}
});
it("returns null for PF2e when no PCs with level", () => {
const wrapper = makePf2eWrapper({
encounter: buildEncounter({
combatants: [
buildCombatant({
id: combatantId("c1"),
name: "Hero",
playerCharacterId: pcId1,
}),
buildCombatant({
id: combatantId("c2"),
name: "Orc Warrior",
creatureId: pf2eCreature.id,
}),
],
}),
playerCharacters: [{ id: pcId1, name: "Hero", ac: 15, maxHp: 30 }],
creatures: new Map([[pf2eCreature.id, pf2eCreature]]),
});
const { result: editionResult } = renderHook(() => useRulesEdition(), {
wrapper,
});
editionResult.current.setEdition("pf2e");
try {
const { result } = renderHook(() => useDifficulty(), { wrapper });
expect(result.current).toBeNull();
} finally {
editionResult.current.setEdition("5.5e");
}
});
});
});
@@ -0,0 +1,95 @@
import type { HpRange, HpVariant } from "@initiative/domain";
import {
combatantId,
creatureId,
EMPTY_UNDO_REDO_STATE,
} from "@initiative/domain";
import { describe, expect, it } from "vitest";
import { type EncounterState, encounterReducer } from "../use-encounter.js";
// An ogre with 3d6 + 6 hit points.
const RANGE: HpRange = { min: 9, average: 16, max: 24 };
function stateWithCreature(
maxHp: number,
currentHp: number,
hpVariant?: HpVariant,
): EncounterState {
return {
encounter: {
combatants: [
{
id: combatantId("c-1"),
name: "Ogre",
maxHp,
currentHp,
creatureId: creatureId("mm:ogre"),
...(hpVariant !== undefined && { hpVariant }),
},
],
activeIndex: 0,
roundNumber: 1,
},
undoRedoState: EMPTY_UNDO_REDO_STATE,
events: [],
nextId: 1,
lastCreatureId: null,
};
}
function setVariant(state: EncounterState, variant: HpVariant | undefined) {
return encounterReducer(state, {
type: "set-hp-variant",
id: combatantId("c-1"),
variant,
range: RANGE,
});
}
describe("set-hp-variant", () => {
it("raises max HP to the maximum roll and stores the variant", () => {
const next = setVariant(stateWithCreature(16, 16), "max");
const c = next.encounter.combatants[0];
expect(c.maxHp).toBe(24);
expect(c.currentHp).toBe(24);
expect(c.hpVariant).toBe("max");
});
it("lowers max HP to the minimum roll", () => {
const next = setVariant(stateWithCreature(16, 16), "min");
const c = next.encounter.combatants[0];
expect(c.maxHp).toBe(9);
expect(c.hpVariant).toBe("min");
});
it("returns to the average and clears the variant", () => {
const next = setVariant(stateWithCreature(24, 24, "max"), undefined);
const c = next.encounter.combatants[0];
expect(c.maxHp).toBe(16);
expect(c.hpVariant).toBeUndefined();
});
it("does not rename the combatant", () => {
const next = setVariant(stateWithCreature(16, 16), "max");
expect(next.encounter.combatants[0].name).toBe("Ogre");
});
it("is undoable", () => {
const start = stateWithCreature(16, 16);
const next = setVariant(start, "max");
const undone = encounterReducer(next, { type: "undo" });
expect(undone.encounter.combatants[0].maxHp).toBe(16);
expect(undone.encounter.combatants[0].hpVariant).toBeUndefined();
});
it("leaves state untouched for an unknown combatant", () => {
const start = stateWithCreature(16, 16);
const next = encounterReducer(start, {
type: "set-hp-variant",
id: combatantId("c-99"),
variant: "max",
range: RANGE,
});
expect(next).toBe(start);
});
});
@@ -5,6 +5,7 @@ import { act, renderHook } from "@testing-library/react";
import type { ReactNode } from "react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { createTestAdapters } from "../../__tests__/adapters/in-memory-adapters.js";
import { buildPlayerCharacter } from "../../__tests__/factories/index.js";
import { AllProviders } from "../../__tests__/test-providers.js";
import type { SearchResult } from "../use-bestiary.js";
import { useEncounter } from "../use-encounter.js";
@@ -256,4 +257,54 @@ describe("useEncounter", () => {
expect(combatant.icon).toBe("sword");
expect(combatant.playerCharacterId).toBe(playerCharacterId("pc-1"));
});
it("addParty adds every party member", () => {
const { result } = renderHook(() => useEncounter(), { wrapper });
const party = [
buildPlayerCharacter({ name: "Aria" }),
buildPlayerCharacter({ name: "Borin" }),
];
act(() => result.current.addParty(party));
const names = result.current.encounter.combatants.map((c) => c.name);
expect(names).toEqual(["Aria", "Borin"]);
});
it("addParty skips members already in the encounter", () => {
const { result } = renderHook(() => useEncounter(), { wrapper });
const aria = buildPlayerCharacter({ name: "Aria" });
const borin = buildPlayerCharacter({ name: "Borin" });
act(() => result.current.addFromPlayerCharacter(aria));
act(() => result.current.addParty([aria, borin]));
const names = result.current.encounter.combatants.map((c) => c.name);
expect(names).toEqual(["Aria", "Borin"]);
});
it("addParty is undone in a single step", () => {
const { result } = renderHook(() => useEncounter(), { wrapper });
const party = [
buildPlayerCharacter({ name: "Aria" }),
buildPlayerCharacter({ name: "Borin" }),
];
act(() => result.current.addParty(party));
act(() => result.current.undo());
expect(result.current.encounter.combatants).toEqual([]);
expect(result.current.canUndo).toBe(false);
});
it("addParty does nothing when the whole party is already present", () => {
const { result } = renderHook(() => useEncounter(), { wrapper });
const aria = buildPlayerCharacter({ name: "Aria" });
act(() => result.current.addParty([aria]));
act(() => result.current.addParty([aria]));
act(() => result.current.undo());
expect(result.current.encounter.combatants).toEqual([]);
});
});
@@ -112,6 +112,49 @@ describe("usePlayerCharacters", () => {
expect(result.current.characters[0].name).toBe("Vex'ahlia");
});
it("createCharacter assigns a fresh id after rehydration from persistence", () => {
const stored = [
{
id: playerCharacterId("pc-1"),
name: "Mikka",
ac: 12,
maxHp: 58,
color: undefined,
icon: undefined,
},
{
id: playerCharacterId("pc-3"),
name: "Bob",
ac: 14,
maxHp: 40,
color: undefined,
icon: undefined,
},
];
const adapters = createTestAdapters({ playerCharacters: stored });
const { result } = renderHook(() => usePlayerCharacters(), {
wrapper: ({ children }: { children: ReactNode }) => (
<AllProviders adapters={adapters}>{children}</AllProviders>
),
});
act(() => {
result.current.createCharacter(
"Charlie",
13,
25,
undefined,
undefined,
undefined,
);
});
const ids = result.current.characters.map((pc) => pc.id);
expect(new Set(ids).size).toBe(ids.length);
expect(ids).toContain(playerCharacterId("pc-4"));
});
it("deleteCharacter removes character and persists", () => {
const { result } = renderHook(() => usePlayerCharacters(), { wrapper });
+9 -1
View File
@@ -9,6 +9,7 @@ import {
normalizeBestiary,
setSourceDisplayNames,
} from "../adapters/bestiary-adapter.js";
import { loadBundledDndCreatures } from "../adapters/dnd-bundled-adapter.js";
import { normalizeFoundryCreatures } from "../adapters/pf2e-bestiary-adapter.js";
import { useAdapters } from "../contexts/adapter-context.js";
import { useRulesEditionContext } from "../contexts/rules-edition-context.js";
@@ -160,7 +161,11 @@ export function useBestiary(): BestiaryHook {
}
void bestiaryCache.loadAllCachedCreatures().then((map) => {
setCreatureMap(map);
const merged = new Map(map);
for (const c of loadBundledDndCreatures()) {
merged.set(c.id, c);
}
setCreatureMap(merged);
});
}, [bestiaryCache, bestiaryIndex, pf2eBestiaryIndex]);
@@ -300,6 +305,9 @@ export function useBestiary(): BestiaryHook {
const refreshCache = useCallback(async (): Promise<void> => {
const map = await bestiaryCache.loadAllCachedCreatures();
for (const c of loadBundledDndCreatures()) {
map.set(c.id, c);
}
setCreatureMap(map);
}, [bestiaryCache]);
+113 -14
View File
@@ -1,11 +1,17 @@
import type {
AnyCreature,
Combatant,
CreatureId,
DifficultyThreshold,
DifficultyTier,
PlayerCharacter,
} from "@initiative/domain";
import { calculateEncounterDifficulty, crToXp } from "@initiative/domain";
import {
calculateEncounterDifficulty,
crToXp,
derivePartyLevel,
pf2eCreatureXp,
} from "@initiative/domain";
import { useMemo } from "react";
import { useBestiaryContext } from "../contexts/bestiary-context.js";
import { useEncounterContext } from "../contexts/encounter-context.js";
@@ -21,6 +27,10 @@ export interface BreakdownCombatant {
readonly editable: boolean;
readonly side: "party" | "enemy";
readonly level: number | undefined;
/** PF2e only: the creature's level from bestiary data. */
readonly creatureLevel: number | undefined;
/** PF2e only: creature level minus party level. */
readonly levelDifference: number | undefined;
}
interface DifficultyBreakdown {
@@ -30,6 +40,7 @@ interface DifficultyBreakdown {
readonly encounterMultiplier: number | undefined;
readonly adjustedXp: number | undefined;
readonly partySizeAdjusted: boolean | undefined;
readonly partyLevel: number | undefined;
readonly pcCount: number;
readonly partyCombatants: readonly BreakdownCombatant[];
readonly enemyCombatants: readonly BreakdownCombatant[];
@@ -48,9 +59,16 @@ export function useDifficultyBreakdown(): DifficultyBreakdown | null {
const hasPartyLevel = descriptors.some(
(d) => d.side === "party" && d.level !== undefined,
);
const hasCr = descriptors.some((d) => d.cr !== undefined);
if (!hasPartyLevel || !hasCr) return null;
if (edition === "pf2e") {
const hasCreatureLevel = descriptors.some(
(d) => d.creatureLevel !== undefined,
);
if (!hasPartyLevel || !hasCreatureLevel) return null;
} else {
const hasCr = descriptors.some((d) => d.cr !== undefined);
if (!hasPartyLevel || !hasCr) return null;
}
const result = calculateEncounterDifficulty(descriptors, edition);
@@ -65,6 +83,7 @@ export function useDifficultyBreakdown(): DifficultyBreakdown | null {
type CreatureInfo = {
cr?: string;
creatureLevel?: number;
source: string;
sourceDisplayName: string;
};
@@ -74,6 +93,7 @@ function buildBreakdownEntry(
side: "party" | "enemy",
level: number | undefined,
creature: CreatureInfo | undefined,
partyLevel: number | undefined,
): BreakdownCombatant {
if (c.playerCharacterId) {
return {
@@ -84,6 +104,29 @@ function buildBreakdownEntry(
editable: false,
side,
level,
creatureLevel: undefined,
levelDifference: undefined,
};
}
if (creature && creature.creatureLevel !== undefined) {
const levelDiff =
partyLevel === undefined
? undefined
: creature.creatureLevel - partyLevel;
const xp =
partyLevel === undefined
? null
: pf2eCreatureXp(creature.creatureLevel, partyLevel);
return {
combatant: c,
cr: null,
xp,
source: creature.sourceDisplayName ?? creature.source,
editable: false,
side,
level: undefined,
creatureLevel: creature.creatureLevel,
levelDifference: levelDiff,
};
}
if (creature) {
@@ -96,6 +139,8 @@ function buildBreakdownEntry(
editable: false,
side,
level: undefined,
creatureLevel: undefined,
levelDifference: undefined,
};
}
if (c.cr) {
@@ -107,6 +152,8 @@ function buildBreakdownEntry(
editable: true,
side,
level: undefined,
creatureLevel: undefined,
levelDifference: undefined,
};
}
return {
@@ -117,6 +164,8 @@ function buildBreakdownEntry(
editable: !c.creatureId,
side,
level: undefined,
creatureLevel: undefined,
levelDifference: undefined,
};
}
@@ -128,41 +177,91 @@ function resolveLevel(
return characters.find((p) => p.id === c.playerCharacterId)?.level;
}
function resolveCr(
function resolveCreatureInfo(
c: Combatant,
getCreature: (id: CreatureId) => CreatureInfo | undefined,
): { cr: string | null; creature: CreatureInfo | undefined } {
const creature = c.creatureId ? getCreature(c.creatureId) : undefined;
const cr = creature?.cr ?? c.cr ?? null;
return { cr, creature };
getCreature: (id: CreatureId) => AnyCreature | undefined,
): {
cr: string | null;
creatureLevel: number | undefined;
creature: CreatureInfo | undefined;
} {
const rawCreature = c.creatureId ? getCreature(c.creatureId) : undefined;
if (!rawCreature) {
return {
cr: c.cr ?? null,
creatureLevel: undefined,
creature: undefined,
};
}
if ("system" in rawCreature && rawCreature.system === "pf2e") {
return {
cr: null,
creatureLevel: rawCreature.level,
creature: {
creatureLevel: rawCreature.level,
source: rawCreature.source,
sourceDisplayName: rawCreature.sourceDisplayName,
},
};
}
const cr = "cr" in rawCreature ? rawCreature.cr : undefined;
return {
cr: cr ?? c.cr ?? null,
creatureLevel: undefined,
creature: {
cr,
source: rawCreature.source,
sourceDisplayName: rawCreature.sourceDisplayName,
},
};
}
function collectPartyLevel(
combatants: readonly Combatant[],
characters: readonly PlayerCharacter[],
): number | undefined {
const partyLevels: number[] = [];
for (const c of combatants) {
if (resolveSide(c) !== "party") continue;
const level = resolveLevel(c, characters);
if (level !== undefined) partyLevels.push(level);
}
return partyLevels.length > 0 ? derivePartyLevel(partyLevels) : undefined;
}
function classifyCombatants(
combatants: readonly Combatant[],
characters: readonly PlayerCharacter[],
getCreature: (id: CreatureId) => CreatureInfo | undefined,
getCreature: (id: CreatureId) => AnyCreature | undefined,
) {
const partyCombatants: BreakdownCombatant[] = [];
const enemyCombatants: BreakdownCombatant[] = [];
const descriptors: {
level?: number;
cr?: string;
creatureLevel?: number;
side: "party" | "enemy";
}[] = [];
let pcCount = 0;
const partyLevel = collectPartyLevel(combatants, characters);
for (const c of combatants) {
const side = resolveSide(c);
const level = resolveLevel(c, characters);
if (level !== undefined) pcCount++;
const { cr, creature } = resolveCr(c, getCreature);
const { cr, creatureLevel, creature } = resolveCreatureInfo(c, getCreature);
if (level !== undefined || cr != null) {
descriptors.push({ level, cr: cr ?? undefined, side });
if (level !== undefined || cr != null || creatureLevel !== undefined) {
descriptors.push({
level,
cr: cr ?? undefined,
creatureLevel,
side,
});
}
const entry = buildBreakdownEntry(c, side, level, creature);
const entry = buildBreakdownEntry(c, side, level, creature, partyLevel);
const target = side === "party" ? partyCombatants : enemyCombatants;
target.push(entry);
}
+19 -6
View File
@@ -33,9 +33,17 @@ function buildDescriptors(
const creatureCr =
creature && !("system" in creature) ? creature.cr : undefined;
const cr = creatureCr ?? c.cr ?? undefined;
const creatureLevel =
creature && "system" in creature && creature.system === "pf2e"
? creature.level
: undefined;
if (level !== undefined || cr !== undefined) {
descriptors.push({ level, cr, side });
if (
level !== undefined ||
cr !== undefined ||
creatureLevel !== undefined
) {
descriptors.push({ level, cr, creatureLevel, side });
}
}
return descriptors;
@@ -48,8 +56,6 @@ export function useDifficulty(): DifficultyResult | null {
const { edition } = useRulesEditionContext();
return useMemo(() => {
if (edition === "pf2e") return null;
const descriptors = buildDescriptors(
encounter.combatants,
characters,
@@ -59,9 +65,16 @@ export function useDifficulty(): DifficultyResult | null {
const hasPartyLevel = descriptors.some(
(d) => d.side === "party" && d.level !== undefined,
);
const hasCr = descriptors.some((d) => d.cr !== undefined);
if (!hasPartyLevel || !hasCr) return null;
if (edition === "pf2e") {
const hasCreatureLevel = descriptors.some(
(d) => d.creatureLevel !== undefined,
);
if (!hasPartyLevel || !hasCreatureLevel) return null;
} else {
const hasCr = descriptors.some((d) => d.cr !== undefined);
if (!hasPartyLevel || !hasCr) return null;
}
return calculateEncounterDifficulty(descriptors, edition);
}, [encounter.combatants, characters, getCreature, edition]);
+78 -7
View File
@@ -15,6 +15,7 @@ import {
setConditionValueUseCase,
setCrUseCase,
setHpUseCase,
setHpVariantUseCase,
setInitiativeUseCase,
setSideUseCase,
setTempHpUseCase,
@@ -30,6 +31,8 @@ import type {
DomainError,
DomainEvent,
Encounter,
HpRange,
HpVariant,
PersistentDamageType,
Pf2eCreature,
PlayerCharacter,
@@ -59,6 +62,12 @@ type EncounterAction =
| { type: "edit-combatant"; id: CombatantId; newName: string }
| { type: "set-initiative"; id: CombatantId; value: number | undefined }
| { type: "set-hp"; id: CombatantId; maxHp: number | undefined }
| {
type: "set-hp-variant";
id: CombatantId;
variant: HpVariant | undefined;
range: HpRange;
}
| { type: "adjust-hp"; id: CombatantId; delta: number }
| { type: "set-temp-hp"; id: CombatantId; tempHp: number | undefined }
| { type: "set-ac"; id: CombatantId; value: number | undefined }
@@ -108,6 +117,7 @@ type EncounterAction =
baseCreature: Pf2eCreature;
}
| { type: "add-from-player-character"; pc: PlayerCharacter }
| { type: "add-party"; pcs: readonly PlayerCharacter[] }
| {
type: "import";
encounter: Encounter;
@@ -277,13 +287,13 @@ function handleAddFromBestiary(
};
}
function handleAddFromPlayerCharacter(
state: EncounterState,
function addOneFromPlayerCharacter(
store: EncounterStore,
pc: PlayerCharacter,
): EncounterState {
const { store, getEncounter } = makeStoreFromState(state);
nextId: number,
): DomainEvent[] | null {
const newName = resolveAndRename(store, pc.name);
const id = combatantId(`c-${state.nextId + 1}`);
const id = combatantId(`c-${nextId + 1}`);
const result = addCombatantUseCase(store, id, newName, {
maxHp: pc.maxHp,
ac: pc.ac > 0 ? pc.ac : undefined,
@@ -291,17 +301,58 @@ function handleAddFromPlayerCharacter(
icon: pc.icon,
playerCharacterId: pc.id,
});
if (isDomainError(result)) return state;
return isDomainError(result) ? null : result;
}
function handleAddFromPlayerCharacter(
state: EncounterState,
pc: PlayerCharacter,
): EncounterState {
const { store, getEncounter } = makeStoreFromState(state);
const events = addOneFromPlayerCharacter(store, pc, state.nextId);
if (!events) return state;
return {
...state,
encounter: getEncounter(),
undoRedoState: pushUndo(state.undoRedoState, state.encounter),
events: [...state.events, ...result],
events: [...state.events, ...events],
nextId: state.nextId + 1,
lastCreatureId: null,
};
}
/** Adds every party member that is not already in the encounter, as one undo step. */
function handleAddParty(
state: EncounterState,
pcs: readonly PlayerCharacter[],
): EncounterState {
const present = new Set(
state.encounter.combatants.map((c) => c.playerCharacterId),
);
const missing = pcs.filter((pc) => !present.has(pc.id));
if (missing.length === 0) return state;
const { store, getEncounter } = makeStoreFromState(state);
const allEvents: DomainEvent[] = [];
let nextId = state.nextId;
for (const pc of missing) {
const events = addOneFromPlayerCharacter(store, pc, nextId);
if (!events) return state;
allEvents.push(...events);
nextId += 1;
}
return {
...state,
encounter: getEncounter(),
undoRedoState: pushUndo(state.undoRedoState, state.encounter),
events: [...state.events, ...allEvents],
nextId,
lastCreatureId: null,
};
}
function applyNamePrefix(
name: string,
oldAdj: "weak" | "elite" | undefined,
@@ -416,6 +467,8 @@ export function encounterReducer(
return handleAddFromBestiary(state, action.entry, action.count);
case "add-from-player-character":
return handleAddFromPlayerCharacter(state, action.pc);
case "add-party":
return handleAddParty(state, action.pcs);
default:
return dispatchEncounterAction(state, action);
}
@@ -432,6 +485,7 @@ function dispatchEncounterAction(
| { type: "edit-combatant" }
| { type: "set-initiative" }
| { type: "set-hp" }
| { type: "set-hp-variant" }
| { type: "adjust-hp" }
| { type: "set-temp-hp" }
| { type: "set-ac" }
@@ -472,6 +526,14 @@ function dispatchEncounterAction(
case "set-hp":
result = setHpUseCase(store, action.id, action.maxHp);
break;
case "set-hp-variant":
result = setHpVariantUseCase(
store,
action.id,
action.variant,
action.range,
);
break;
case "adjust-hp":
result = adjustHpUseCase(store, action.id, action.delta);
break;
@@ -706,6 +768,11 @@ export function useEncounter() {
}),
[],
),
setHpVariant: useCallback(
(id: CombatantId, variant: HpVariant | undefined, range: HpRange) =>
dispatch({ type: "set-hp-variant", id, variant, range }),
[],
),
clearEncounter: useCallback(
() => dispatch({ type: "clear-encounter" }),
[],
@@ -730,6 +797,10 @@ export function useEncounter() {
dispatch({ type: "add-from-player-character", pc }),
[],
),
addParty: useCallback(
(pcs: readonly PlayerCharacter[]) => dispatch({ type: "add-party", pcs }),
[],
),
undo: useCallback(() => dispatch({ type: "undo" }), []),
redo: useCallback(() => dispatch({ type: "redo" }), []),
setEncounter: useCallback(
+12 -4
View File
@@ -9,10 +9,18 @@ import { isDomainError, playerCharacterId } from "@initiative/domain";
import { useCallback, useEffect, useRef, useState } from "react";
import { useAdapters } from "../contexts/adapter-context.js";
let nextPcId = 0;
const PC_ID_PATTERN = /^pc-(\d+)$/;
function generatePcId(): PlayerCharacterId {
return playerCharacterId(`pc-${++nextPcId}`);
function generatePcId(existing: readonly PlayerCharacter[]): PlayerCharacterId {
let max = 0;
for (const pc of existing) {
const match = PC_ID_PATTERN.exec(pc.id);
if (match) {
const n = Number(match[1]);
if (n > max) max = n;
}
}
return playerCharacterId(`pc-${max + 1}`);
}
interface EditFields {
@@ -55,7 +63,7 @@ export function usePlayerCharacters() {
icon: string | undefined,
level: number | undefined,
) => {
const id = generatePcId();
const id = generatePcId(charactersRef.current);
const result = createPlayerCharacterUseCase(
makeStore(),
id,
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,5 +1,5 @@
{
"$schema": "https://unpkg.com/knip@5/schema.json",
"$schema": "https://unpkg.com/knip@6/schema.json",
"workspaces": {
".": {
"entry": ["scripts/*.mjs"]
+7 -3
View File
@@ -3,8 +3,12 @@ pre-commit:
jobs:
- name: audit
run: pnpm audit --audit-level=high
# Must go through the npm script, not `pnpm exec knip`: the script sets
# KNIP_DISABLE_RAW_TRANSFER=1. Knip 6's default oxc-parser raw-transfer path
# allocates a 6 GiB ArrayBuffer, which Linux refuses under heuristic
# overcommit on the CI runner (3.7 GB RAM, no swap). See issue #11.
- name: knip
run: pnpm exec knip
run: pnpm knip
- name: biome
run: pnpm exec biome check .
- name: check-ignores
@@ -14,7 +18,7 @@ pre-commit:
- name: check-props
run: node scripts/check-component-props.mjs
- name: jscpd
run: pnpm exec jscpd
run: pnpm jscpd
- name: jsinspect
run: pnpm jsinspect
- name: typecheck-oxlint-test
@@ -24,6 +28,6 @@ pre-commit:
- name: typecheck
run: pnpm exec tsc --build
- name: oxlint
run: pnpm oxlint -- --deny warnings
run: pnpm oxlint
- name: test
run: pnpm vitest run --reporter=dot --coverage.reporter=text-summary
+5 -11
View File
@@ -1,18 +1,12 @@
{
"private": true,
"packageManager": "pnpm@10.32.1+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be",
"pnpm": {
"overrides": {
"undici": ">=7.24.0",
"picomatch": ">=4.0.4"
}
},
"devDependencies": {
"@biomejs/biome": "2.4.8",
"@vitest/coverage-v8": "^4.1.0",
"jscpd": "^4.0.8",
"jsinspect-plus": "^3.1.3",
"knip": "^5.88.1",
"knip": "^6.31.0",
"lefthook": "^2.1.4",
"oxlint": "^1.56.0",
"oxlint-tsgolint": "^0.17.1",
@@ -28,13 +22,13 @@
"typecheck": "tsc --build",
"test": "vitest run",
"test:watch": "vitest",
"knip": "knip",
"jscpd": "jscpd",
"knip": "KNIP_DISABLE_RAW_TRANSFER=1 knip",
"jscpd": "jscpd apps/web/src packages/domain/src packages/application/src",
"jsinspect": "jsinspect -c .jsinspectrc apps/web/src packages/domain/src packages/application/src",
"oxlint": "oxlint --tsconfig apps/web/tsconfig.json --type-aware --deny-warnings",
"oxlint": "oxlint --tsconfig tsconfig.json --type-aware --deny-warnings",
"check:ignores": "node scripts/check-lint-ignores.mjs",
"check:classnames": "node scripts/check-cn-classnames.mjs",
"check:props": "node scripts/check-component-props.mjs",
"check": "pnpm audit --audit-level=high && knip && biome check . && node scripts/check-lint-ignores.mjs && node scripts/check-cn-classnames.mjs && node scripts/check-component-props.mjs && jscpd && pnpm jsinspect && tsc --build && oxlint --tsconfig apps/web/tsconfig.json --type-aware --deny warnings && vitest run"
"check": "pnpm audit --audit-level=high && pnpm knip && biome check . && node scripts/check-lint-ignores.mjs && node scripts/check-cn-classnames.mjs && node scripts/check-component-props.mjs && pnpm jscpd && pnpm jsinspect && tsc --build && pnpm oxlint && vitest run"
}
}
+1
View File
@@ -27,6 +27,7 @@ export { setAcUseCase } from "./set-ac-use-case.js";
export { setConditionValueUseCase } from "./set-condition-value-use-case.js";
export { setCrUseCase } from "./set-cr-use-case.js";
export { setHpUseCase } from "./set-hp-use-case.js";
export { setHpVariantUseCase } from "./set-hp-variant-use-case.js";
export { setInitiativeUseCase } from "./set-initiative-use-case.js";
export { setSideUseCase } from "./set-side-use-case.js";
export { setTempHpUseCase } from "./set-temp-hp-use-case.js";
@@ -0,0 +1,21 @@
import {
type CombatantId,
type DomainError,
type DomainEvent,
type HpRange,
type HpVariant,
setHpVariant,
} from "@initiative/domain";
import type { EncounterStore } from "./ports.js";
import { runEncounterAction } from "./run-encounter-action.js";
export function setHpVariantUseCase(
store: EncounterStore,
combatantId: CombatantId,
variant: HpVariant | undefined,
range: HpRange,
): DomainEvent[] | DomainError {
return runEncounterAction(store, (encounter) =>
setHpVariant(encounter, combatantId, variant, range),
);
}
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import {
calculateEncounterDifficulty,
crToXp,
derivePartyLevel,
pf2eCreatureXp,
} from "../encounter-difficulty.js";
describe("crToXp", () => {
@@ -47,9 +49,9 @@ function enemy(cr: string) {
}
describe("calculateEncounterDifficulty — 5.5e edition", () => {
it("returns tier 0 when monster XP is below Low threshold", () => {
it("returns tier 0 when monster XP is 0", () => {
// 4x level 1: Low = 200, Moderate = 300, High = 400
// 1x CR 0 = 0 XP -> tier 0
// 1x CR 0 = 0 XP -> tier 0 (5.5e has no Trivial tier; 0 bars only at 0 XP)
const result = calculateEncounterDifficulty(
[party(1), party(1), party(1), party(1), enemy("0")],
"5.5e",
@@ -75,9 +77,29 @@ describe("calculateEncounterDifficulty — 5.5e edition", () => {
expect(result.totalMonsterXp).toBe(200);
});
it("returns tier 2 for 5x level 3 vs 1150 XP", () => {
it("returns tier 2 when XP spends exactly the Moderate budget", () => {
// 5x level 3: Low = 750, Moderate = 1125, High = 2000
// CR 3 (700) + CR 2 (450) = 1150 XP >= 1125 Moderate
// CR 4 (1100) + CR 1/8 (25) = 1125 XP = Moderate budget
const result = calculateEncounterDifficulty(
[
party(3),
party(3),
party(3),
party(3),
party(3),
enemy("4"),
enemy("1/8"),
],
"5.5e",
);
expect(result.tier).toBe(2);
expect(result.totalMonsterXp).toBe(1125);
expect(result.thresholds[1].value).toBe(1125);
});
it("returns tier 3 when XP exceeds the Moderate budget", () => {
// 5x level 3: Low = 750, Moderate = 1125, High = 2000
// CR 3 (700) + CR 2 (450) = 1150 XP > 1125 Moderate → High
const result = calculateEncounterDifficulty(
[
party(3),
@@ -90,14 +112,24 @@ describe("calculateEncounterDifficulty — 5.5e edition", () => {
],
"5.5e",
);
expect(result.tier).toBe(2);
expect(result.tier).toBe(3);
expect(result.totalMonsterXp).toBe(1150);
expect(result.thresholds[1].value).toBe(1125);
});
it("returns tier 3 when XP meets High threshold", () => {
// 4x level 1: High = 400
// 2x CR 1 = 400 XP -> tier 3
it("returns tier 3 for 5x level 5 vs 5000 XP (over Moderate budget)", () => {
// 5x level 5: Low = 2500, Moderate = 3750, High = 5500
// CR 9 = 5000 XP > 3750 Moderate → High, even though below the High budget
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), party(5), enemy("9")],
"5.5e",
);
expect(result.tier).toBe(3);
expect(result.totalMonsterXp).toBe(5000);
});
it("returns tier 3 when XP exceeds the Moderate budget", () => {
// 4x level 1: Moderate = 300
// 2x CR 1 = 400 XP > 300 -> tier 3
const result = calculateEncounterDifficulty(
[party(1), party(1), party(1), party(1), enemy("1"), enemy("1")],
"5.5e",
@@ -118,6 +150,7 @@ describe("calculateEncounterDifficulty — 5.5e edition", () => {
it("handles mixed party levels", () => {
// 3x level 3 + 1x level 2
// Total: low=550, mod=825, high=1400
// 700 XP > 550 Low, ≤ 825 Moderate → Moderate
const result = calculateEncounterDifficulty(
[party(3), party(3), party(3), party(2), enemy("3")],
"5.5e",
@@ -128,7 +161,7 @@ describe("calculateEncounterDifficulty — 5.5e edition", () => {
{ label: "High", value: 1400 },
]);
expect(result.totalMonsterXp).toBe(700);
expect(result.tier).toBe(1);
expect(result.tier).toBe(2);
});
it("returns tier 0 with no enemies", () => {
@@ -162,7 +195,7 @@ describe("calculateEncounterDifficulty — 5.5e edition", () => {
"5.5e",
);
expect(result.totalMonsterXp).toBe(175); // 25 + 50 + 100
expect(result.tier).toBe(0); // 175 < 200 Low
expect(result.tier).toBe(1); // 175 200 Low budget → Low
});
it("ignores unknown CRs (0 XP)", () => {
@@ -189,7 +222,7 @@ describe("calculateEncounterDifficulty — 5.5e edition", () => {
"5.5e",
);
expect(result.totalMonsterXp).toBe(250);
expect(result.tier).toBe(1); // 250 >= 200 Low, < 300 Moderate
expect(result.tier).toBe(2); // 250 > 200 Low budget, 300 Moderate → Moderate
});
it("floors net monster XP at 0", () => {
@@ -252,7 +285,7 @@ describe("calculateEncounterDifficulty — 5.5e edition", () => {
{ label: "High", value: 800 },
]);
expect(result.totalMonsterXp).toBe(700);
expect(result.tier).toBe(2); // 700 >= 450 Moderate, < 800 High
expect(result.tier).toBe(3); // 700 > 450 Moderate budget → High
});
});
@@ -386,3 +419,263 @@ describe("calculateEncounterDifficulty — 2014 edition", () => {
expect(result.adjustedXp).toBeUndefined();
});
});
/** Helper to build a PF2e enemy-side descriptor with creature level. */
function pf2eEnemy(creatureLevel: number) {
return { creatureLevel, side: "enemy" as const };
}
/** Helper to build a PF2e party-side creature descriptor. */
function pf2eAlly(creatureLevel: number) {
return { creatureLevel, side: "party" as const };
}
describe("derivePartyLevel", () => {
it("returns 0 for empty array", () => {
expect(derivePartyLevel([])).toBe(0);
});
it("returns the level for a single PC", () => {
expect(derivePartyLevel([7])).toBe(7);
});
it("returns the unanimous level", () => {
expect(derivePartyLevel([5, 5, 5, 5])).toBe(5);
});
it("returns the mode when one level is most common", () => {
expect(derivePartyLevel([3, 3, 3, 5])).toBe(3);
});
it("returns rounded average when mode is tied", () => {
// 3,3,5,5 → average 4
expect(derivePartyLevel([3, 3, 5, 5])).toBe(4);
});
it("returns rounded average when all levels are different", () => {
// 2,4,6,8 → average 5
expect(derivePartyLevel([2, 4, 6, 8])).toBe(5);
});
it("rounds average to nearest integer", () => {
// 1,2 → average 1.5 → rounds to 2
expect(derivePartyLevel([1, 2])).toBe(2);
});
});
describe("pf2eCreatureXp", () => {
it.each([
[-4, 10],
[-3, 15],
[-2, 20],
[-1, 30],
[0, 40],
[1, 60],
[2, 80],
[3, 120],
[4, 160],
])("level diff %i returns %i XP", (diff, expectedXp) => {
// partyLevel 5, creatureLevel = 5 + diff
expect(pf2eCreatureXp(5 + diff, 5)).toBe(expectedXp);
});
it("returns 0 XP for creatures more than 4 levels below the party", () => {
expect(pf2eCreatureXp(0, 10)).toBe(0);
});
it("clamps level diff above +4 to +4 (160 XP)", () => {
expect(pf2eCreatureXp(15, 5)).toBe(160);
});
});
describe("calculateEncounterDifficulty — pf2e edition", () => {
it("returns Trivial (tier 0) for 40 XP with party of 4", () => {
// 1 creature at party level = 40 XP, within the Trivial band (40 or less)
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(5)],
"pf2e",
);
expect(result.tier).toBe(0);
expect(result.totalMonsterXp).toBe(40);
expect(result.partyLevel).toBe(5);
expect(result.thresholds).toEqual([
{ label: "Trivial", value: 40 },
{ label: "Low", value: 60 },
{ label: "Moderate", value: 80 },
{ label: "Severe", value: 120 },
{ label: "Extreme", value: 160 },
]);
});
it("returns Low (tier 1) for 60 XP", () => {
// 1 creature at party level +1 = 60 XP
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(6)],
"pf2e",
);
expect(result.tier).toBe(1);
expect(result.totalMonsterXp).toBe(60);
});
it("returns Moderate (tier 2) for 80 XP", () => {
// 1 creature at +2 = 80 XP
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(7)],
"pf2e",
);
expect(result.tier).toBe(2);
expect(result.totalMonsterXp).toBe(80);
});
it("returns Severe (tier 3) for 120 XP", () => {
// 1 creature at +3 = 120 XP
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(8)],
"pf2e",
);
expect(result.tier).toBe(3);
expect(result.totalMonsterXp).toBe(120);
});
it("returns Extreme (tier 4) for 160 XP", () => {
// 1 creature at +4 = 160 XP > Severe budget (120)
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(9)],
"pf2e",
);
expect(result.tier).toBe(4);
expect(result.totalMonsterXp).toBe(160);
});
it("returns Moderate (tier 2) for XP between the Low and Moderate budgets", () => {
// +1 (60) + 4 (10) = 70 XP > Low (60), ≤ Moderate (80)
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(6), pf2eEnemy(1)],
"pf2e",
);
expect(result.tier).toBe(2);
expect(result.totalMonsterXp).toBe(70);
});
it("returns Extreme (tier 4) for XP just over the Severe budget", () => {
// +3 (120) + 4 (10) = 130 XP > Severe (120)
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(8), pf2eEnemy(1)],
"pf2e",
);
expect(result.tier).toBe(4);
expect(result.totalMonsterXp).toBe(130);
});
it("returns tier 0 when XP is within the Trivial band", () => {
// 1 creature at 4 = 10 XP ≤ Trivial (40)
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(1)],
"pf2e",
);
expect(result.tier).toBe(0);
expect(result.totalMonsterXp).toBe(10);
});
it("counts creatures more than 4 levels below the party as 0 XP", () => {
// Party level 6: a level-1 creature is 5 below → 0 XP
const result = calculateEncounterDifficulty(
[party(6), party(6), party(6), party(6), pf2eEnemy(1), pf2eEnemy(6)],
"pf2e",
);
expect(result.totalMonsterXp).toBe(40); // only the at-level creature counts
});
it("adjusts thresholds for 5 PCs (increases by adjustment)", () => {
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), party(5), pf2eEnemy(5)],
"pf2e",
);
expect(result.thresholds).toEqual([
{ label: "Trivial", value: 50 },
{ label: "Low", value: 80 },
{ label: "Moderate", value: 100 },
{ label: "Severe", value: 150 },
{ label: "Extreme", value: 200 },
]);
});
it("adjusts thresholds for 3 PCs (decreases by adjustment)", () => {
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), pf2eEnemy(5)],
"pf2e",
);
expect(result.thresholds).toEqual([
{ label: "Trivial", value: 30 },
{ label: "Low", value: 40 },
{ label: "Moderate", value: 60 },
{ label: "Severe", value: 90 },
{ label: "Extreme", value: 120 },
]);
});
it("floors thresholds at 0 for very small parties", () => {
const result = calculateEncounterDifficulty(
[party(5), pf2eEnemy(5)],
"pf2e",
);
// 1 PC: adjustment = 3
// Trivial: 40 + (3 * 10) = 10
// Low: 60 + (3 * 20) = 0
expect(result.thresholds[0].value).toBe(10);
expect(result.thresholds[1].value).toBe(0);
expect(result.thresholds[2].value).toBe(20); // 80 60
expect(result.thresholds[3].value).toBe(30); // 120 90
expect(result.thresholds[4].value).toBe(40); // 160 120
});
it("subtracts XP for party-side creatures", () => {
// 2 enemies at party level = 80 XP, 1 ally at party level = 40 XP
// Net = 80 40 = 40 XP
const result = calculateEncounterDifficulty(
[
party(5),
party(5),
party(5),
party(5),
pf2eEnemy(5),
pf2eEnemy(5),
pf2eAlly(5),
],
"pf2e",
);
expect(result.totalMonsterXp).toBe(40);
});
it("floors net creature XP at 0", () => {
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(1), pf2eAlly(9)],
"pf2e",
);
expect(result.totalMonsterXp).toBe(0);
});
it("derives party level using mode", () => {
// 3x level 3, 1x level 5 → mode is 3
const result = calculateEncounterDifficulty(
[party(3), party(3), party(3), party(5), pf2eEnemy(3)],
"pf2e",
);
expect(result.partyLevel).toBe(3);
});
it("has no encounterMultiplier, adjustedXp, or partySizeAdjusted", () => {
const result = calculateEncounterDifficulty(
[party(5), party(5), party(5), party(5), pf2eEnemy(5)],
"pf2e",
);
expect(result.encounterMultiplier).toBeUndefined();
expect(result.adjustedXp).toBeUndefined();
expect(result.partySizeAdjusted).toBeUndefined();
});
it("returns partyLevel undefined for D&D editions", () => {
const result = calculateEncounterDifficulty([party(1), enemy("1")], "5.5e");
expect(result.partyLevel).toBeUndefined();
});
});
@@ -0,0 +1,14 @@
import { describe, expect, it } from "vitest";
import { checkGates } from "../../../../scripts/check-gates.mjs";
describe("quality gates", () => {
it("fail on violations instead of silently passing", () => {
const violations = checkGates();
if (violations.length > 0) {
throw new Error(
`Gate integrity violations:\n ${violations.join("\n ")}`,
);
}
expect(violations).toHaveLength(0);
});
});
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import { hpForVariant, hpRange } from "../hp-range.js";
describe("hpRange", () => {
it("derives min and max from a formula with a positive modifier", () => {
const range = hpRange({ average: 16, formula: "3d6 + 6" });
expect(range).toEqual({ min: 9, average: 16, max: 24 });
});
it("derives min and max from a formula without a modifier", () => {
const range = hpRange({ average: 40, formula: "9d8" });
expect(range).toEqual({ min: 9, average: 40, max: 72 });
});
it("subtracts a negative modifier", () => {
const range = hpRange({ average: 45, formula: "10d8 - 5" });
expect(range).toEqual({ min: 5, average: 45, max: 75 });
});
it("treats an en dash as a minus sign", () => {
// Bundled bestiary data contains e.g. "2d6 2" (U+2013).
const range = hpRange({ average: 5, formula: "2d6 2" });
expect(range).toEqual({ min: 1, average: 5, max: 10 });
});
it("never drops below 1 HP when the modifier exceeds the dice", () => {
const range = hpRange({ average: 1, formula: "1d4 - 10" });
expect(range?.min).toBe(1);
expect(range?.max).toBe(1);
});
it("handles large pools without whitespace", () => {
expect(hpRange({ average: 256, formula: "19d12+133" })).toEqual({
min: 152,
average: 256,
max: 361,
});
});
it("returns null for a missing formula", () => {
expect(hpRange({ average: 7, formula: "" })).toBeNull();
});
it("returns null for prose instead of a dice pool", () => {
expect(
hpRange({ average: 0, formula: "equal to the summoner's" }),
).toBeNull();
});
it("returns null for a flat number", () => {
expect(hpRange({ average: 50, formula: "50" })).toBeNull();
});
it("returns null for a pool with zero dice or zero sides", () => {
expect(hpRange({ average: 0, formula: "0d6" })).toBeNull();
expect(hpRange({ average: 0, formula: "2d0" })).toBeNull();
});
it("returns null for compound formulas it cannot reason about", () => {
expect(hpRange({ average: 20, formula: "2d6 + 2d8" })).toBeNull();
});
});
describe("hpForVariant", () => {
const range = { min: 9, average: 16, max: 24 };
it("returns the average when no variant is set", () => {
expect(hpForVariant(range, undefined)).toBe(16);
});
it("returns the minimum for the min variant", () => {
expect(hpForVariant(range, "min")).toBe(9);
});
it("returns the maximum for the max variant", () => {
expect(hpForVariant(range, "max")).toBe(24);
});
});
@@ -301,6 +301,34 @@ describe("rehydrateCombatant", () => {
expect(result?.side).toBeUndefined();
});
it("preserves valid hpVariant field", () => {
for (const hpVariant of ["min", "max"]) {
const result = rehydrateCombatant({
...minimalCombatant(),
hpVariant,
});
expect(result).not.toBeNull();
expect(result?.hpVariant).toBe(hpVariant);
}
});
it("drops invalid hpVariant field", () => {
for (const hpVariant of ["average", "", 42, null, true]) {
const result = rehydrateCombatant({
...minimalCombatant(),
hpVariant,
});
expect(result).not.toBeNull();
expect(result?.hpVariant).toBeUndefined();
}
});
it("combatant without hpVariant rehydrates as before", () => {
const result = rehydrateCombatant(minimalCombatant());
expect(result).not.toBeNull();
expect(result?.hpVariant).toBeUndefined();
});
it("preserves valid persistent damage entries", () => {
const result = rehydrateCombatant({
...minimalCombatant(),
@@ -0,0 +1,159 @@
import { describe, expect, it } from "vitest";
import type { HpRange, HpVariant } from "../hp-range.js";
import { setHpVariant } from "../set-hp-variant.js";
import type { Combatant, Encounter } from "../types.js";
import { combatantId, isDomainError } from "../types.js";
import { expectDomainError } from "./test-helpers.js";
// A 3d6 + 6 creature: 9 / 16 / 24.
const RANGE: HpRange = { min: 9, average: 16, max: 24 };
function makeCombatant(opts?: Partial<Combatant>): Combatant {
return {
id: combatantId("c-1"),
name: "Ogre",
maxHp: 16,
currentHp: 16,
...opts,
};
}
function enc(combatants: Combatant[]): Encounter {
return { combatants, activeIndex: 0, roundNumber: 1 };
}
function apply(
encounter: Encounter,
variant: HpVariant | undefined,
range: HpRange = RANGE,
) {
const result = setHpVariant(encounter, combatantId("c-1"), variant, range);
if (isDomainError(result)) {
throw new Error(`Expected success, got error: ${result.message}`);
}
return result;
}
describe("setHpVariant", () => {
describe("acceptance scenarios", () => {
it("average → max raises maxHp and currentHp to the maximum roll", () => {
const { encounter } = apply(enc([makeCombatant()]), "max");
const c = encounter.combatants[0];
expect(c.maxHp).toBe(24);
expect(c.currentHp).toBe(24);
expect(c.hpVariant).toBe("max");
});
it("average → min lowers maxHp and currentHp to the minimum roll", () => {
const { encounter } = apply(enc([makeCombatant()]), "min");
const c = encounter.combatants[0];
expect(c.maxHp).toBe(9);
expect(c.currentHp).toBe(9);
expect(c.hpVariant).toBe("min");
});
it("max → average restores the printed average", () => {
const start = enc([
makeCombatant({ maxHp: 24, currentHp: 24, hpVariant: "max" }),
]);
const { encounter } = apply(start, undefined);
const c = encounter.combatants[0];
expect(c.maxHp).toBe(16);
expect(c.currentHp).toBe(16);
expect(c.hpVariant).toBeUndefined();
});
it("min → max spans the full range in one step", () => {
const start = enc([
makeCombatant({ maxHp: 9, currentHp: 9, hpVariant: "min" }),
]);
const { encounter } = apply(start, "max");
expect(encounter.combatants[0].maxHp).toBe(24);
});
});
describe("damage already taken", () => {
it("keeps the amount of damage taken when raising max HP", () => {
// 5 damage taken: 11/16 → 19/24
const start = enc([makeCombatant({ maxHp: 16, currentHp: 11 })]);
const { encounter } = apply(start, "max");
const c = encounter.combatants[0];
expect(c.maxHp).toBe(24);
expect(c.currentHp).toBe(19);
});
it("floors currentHp at 0 when lowering max HP past the damage taken", () => {
const start = enc([makeCombatant({ maxHp: 16, currentHp: 3 })]);
const { encounter } = apply(start, "min");
const c = encounter.combatants[0];
expect(c.maxHp).toBe(9);
expect(c.currentHp).toBe(0);
});
it("clamps currentHp to the new maxHp", () => {
const start = enc([makeCombatant({ maxHp: 100, currentHp: 100 })]);
const { encounter } = apply(start, "min");
const c = encounter.combatants[0];
expect(c.maxHp).toBe(93);
expect(c.currentHp).toBe(93);
});
});
describe("edge cases", () => {
it("preserves a manual max HP edit as an offset", () => {
// User bumped the ogre to 20 HP; max is 8 above average.
const start = enc([makeCombatant({ maxHp: 20, currentHp: 20 })]);
const { encounter } = apply(start, "max");
expect(encounter.combatants[0].maxHp).toBe(28);
});
it("never lets maxHp drop below 1", () => {
const start = enc([makeCombatant({ maxHp: 2, currentHp: 2 })]);
const { encounter } = apply(start, "min");
expect(encounter.combatants[0].maxHp).toBe(1);
});
it("leaves a combatant without HP untouched but records the variant", () => {
const start = enc([
makeCombatant({ maxHp: undefined, currentHp: undefined }),
]);
const { encounter } = apply(start, "max");
const c = encounter.combatants[0];
expect(c.maxHp).toBeUndefined();
expect(c.currentHp).toBeUndefined();
expect(c.hpVariant).toBe("max");
});
it("is a no-op when the variant is already active", () => {
const start = enc([
makeCombatant({ maxHp: 24, currentHp: 20, hpVariant: "max" }),
]);
const { encounter, events } = apply(start, "max");
expect(encounter.combatants[0].currentHp).toBe(20);
expect(events).toEqual([]);
});
it("returns a domain error for an unknown combatant", () => {
const result = setHpVariant(
enc([makeCombatant()]),
combatantId("c-99"),
"max",
RANGE,
);
expectDomainError(result, "combatant-not-found");
});
});
it("emits an HpVariantSet event carrying the HP change", () => {
const { events } = apply(enc([makeCombatant()]), "max");
expect(events).toEqual([
{
type: "HpVariantSet",
combatantId: combatantId("c-1"),
variant: "max",
previousMaxHp: 16,
newMaxHp: 24,
},
]);
});
});
@@ -60,13 +60,13 @@ describe("toggleCondition", () => {
]);
});
it("maintains definition order when adding conditions", () => {
it("appends new conditions to the end (insertion order)", () => {
const e = enc([makeCombatant("A", [{ id: "poisoned" }])]);
const { encounter } = success(e, "A", "blinded");
expect(encounter.combatants[0].conditions).toEqual([
{ id: "blinded" },
{ id: "poisoned" },
{ id: "blinded" },
]);
});
@@ -109,15 +109,16 @@ describe("toggleCondition", () => {
expect(encounter.combatants[0].conditions).toBeUndefined();
});
it("preserves order across all conditions", () => {
it("preserves insertion order across all conditions", () => {
const order = CONDITION_DEFINITIONS.map((d) => d.id);
// Add in reverse order
// Add in reverse order — result should be reverse order (insertion order)
const reversed = [...order].reverse();
let e = enc([makeCombatant("A")]);
for (const cond of [...order].reverse()) {
for (const cond of reversed) {
const result = success(e, "A", cond);
e = result.encounter;
}
expect(e.combatants[0].conditions).toEqual(order.map((id) => ({ id })));
expect(e.combatants[0].conditions).toEqual(reversed.map((id) => ({ id })));
});
});
+2 -2
View File
@@ -500,8 +500,8 @@ export const CONDITION_DEFINITIONS: readonly ConditionDefinition[] = [
description5e: "",
descriptionPf2e:
"Location unknown. Must pick a square to target; DC 11 flat check. Attacker is off-guard against your attacks.",
iconName: "Ghost",
color: "violet",
iconName: "EyeClosed",
color: "slate",
systems: ["pf2e"],
},
{
+205 -9
View File
@@ -1,7 +1,7 @@
import type { RulesEdition } from "./rules-edition.js";
/** Abstract difficulty severity: 0 = negligible, 3 = maximum. Maps to filled bar count. */
export type DifficultyTier = 0 | 1 | 2 | 3;
/** Abstract difficulty severity: 0 = negligible, up to 4 (PF2e Extreme). Maps to filled bar count. */
export type DifficultyTier = 0 | 1 | 2 | 3 | 4;
export interface DifficultyThreshold {
readonly label: string;
@@ -18,6 +18,8 @@ export interface DifficultyResult {
readonly adjustedXp: number | undefined;
/** 2014 only: true when the multiplier was shifted due to party size (<3 or 6+). */
readonly partySizeAdjusted: boolean | undefined;
/** PF2e only: the derived party level used for XP calculation. */
readonly partyLevel: number | undefined;
}
/** Maps challenge rating strings to XP values (standard 5e). */
@@ -160,6 +162,143 @@ function getEncounterMultiplier(
};
}
/**
* PF2e: XP granted by a creature based on its level relative to party level.
* Key is (creature level party level), clamped to [4, +4].
*/
const PF2E_LEVEL_DIFF_XP: Readonly<Record<number, number>> = {
[-4]: 10,
[-3]: 15,
[-2]: 20,
[-1]: 30,
0: 40,
1: 60,
2: 80,
3: 120,
4: 160,
};
/** PF2e base encounter budget thresholds for a party of 4. */
const PF2E_THRESHOLDS_BASE = {
trivial: 40,
low: 60,
moderate: 80,
severe: 120,
extreme: 160,
} as const;
/**
* PF2e per-PC adjustment to each threshold (added per PC beyond 4, subtracted
* per PC fewer). GM Core remaster values Low is 20 there, not the
* pre-remaster CRB's 15.
*/
const PF2E_THRESHOLD_ADJUSTMENTS = {
trivial: 10,
low: 20,
moderate: 20,
severe: 30,
extreme: 40,
} as const;
/**
* Derives PF2e party level from PC levels.
* Returns the mode (most common level). If no unique mode, returns
* the average rounded to the nearest integer.
*/
export function derivePartyLevel(levels: readonly number[]): number {
if (levels.length === 0) return 0;
if (levels.length === 1) return levels[0];
const counts = new Map<number, number>();
for (const l of levels) {
counts.set(l, (counts.get(l) ?? 0) + 1);
}
let maxCount = 0;
let mode: number | undefined;
let isTied = false;
for (const [level, count] of counts) {
if (count > maxCount) {
maxCount = count;
mode = level;
isTied = false;
} else if (count === maxCount) {
isTied = true;
}
}
if (!isTied && mode !== undefined) return mode;
const sum = levels.reduce((a, b) => a + b, 0);
return Math.round(sum / levels.length);
}
/**
* Returns PF2e XP for a creature given its level and the party level.
* Creatures more than 4 levels below the party have no row in the GM Core
* table and pose no meaningful threat they are worth 0 XP. Creatures more
* than 4 levels above are counted as the +4 row (160 XP).
*/
export function pf2eCreatureXp(
creatureLevel: number,
partyLevel: number,
): number {
const diff = creatureLevel - partyLevel;
if (diff < -4) return 0;
return PF2E_LEVEL_DIFF_XP[Math.min(4, diff)] ?? 0;
}
function calculatePf2eBudget(partySize: number) {
const adjustment = partySize - 4;
return {
trivial: Math.max(
0,
PF2E_THRESHOLDS_BASE.trivial +
adjustment * PF2E_THRESHOLD_ADJUSTMENTS.trivial,
),
low: Math.max(
0,
PF2E_THRESHOLDS_BASE.low + adjustment * PF2E_THRESHOLD_ADJUSTMENTS.low,
),
moderate: Math.max(
0,
PF2E_THRESHOLDS_BASE.moderate +
adjustment * PF2E_THRESHOLD_ADJUSTMENTS.moderate,
),
severe: Math.max(
0,
PF2E_THRESHOLDS_BASE.severe +
adjustment * PF2E_THRESHOLD_ADJUSTMENTS.severe,
),
extreme: Math.max(
0,
PF2E_THRESHOLDS_BASE.extreme +
adjustment * PF2E_THRESHOLD_ADJUSTMENTS.extreme,
),
};
}
function scanCombatantsPf2e(
combatants: readonly CombatantDescriptor[],
partyLevel: number,
) {
let totalCreatureXp = 0;
for (const c of combatants) {
if (c.creatureLevel !== undefined) {
const xp = pf2eCreatureXp(c.creatureLevel, partyLevel);
if (c.side === "enemy") {
totalCreatureXp += xp;
} else {
totalCreatureXp -= xp;
}
}
}
return { totalCreatureXp: Math.max(0, totalCreatureXp) };
}
/** All standard 5e challenge rating strings, in ascending order. */
export const VALID_CR_VALUES: readonly string[] = Object.keys(CR_TO_XP);
@@ -171,10 +310,15 @@ export function crToXp(cr: string): number {
export interface CombatantDescriptor {
readonly level?: number;
readonly cr?: string;
readonly creatureLevel?: number;
readonly side: "party" | "enemy";
}
function determineTier(
/**
* 2014 DMG: thresholds are floors "the closest threshold that is lower
* than the adjusted XP value determines the encounter's difficulty".
*/
function tierFromThresholds(
xp: number,
tierThresholds: readonly number[],
): DifficultyTier {
@@ -184,6 +328,23 @@ function determineTier(
return 0;
}
/**
* 2024 DMG / PF2e: budgets are ceilings an encounter belongs to the lowest
* tier whose budget it does not exceed ("spend as much of your XP budget as
* you can without going over"; PF2e Trivial is "40 XP or less"). XP above the
* last budget falls into the tier beyond it (5.5e High / PF2e Extreme have no
* upper bound).
*/
function tierFromBudgets(
xp: number,
budgets: readonly number[],
): DifficultyTier {
for (let i = 0; i < budgets.length; i++) {
if (xp <= budgets[i]) return i as DifficultyTier;
}
return budgets.length as DifficultyTier;
}
function accumulateBudget5_5e(levels: readonly number[]) {
const budget = { low: 0, moderate: 0, high: 0 };
for (const level of levels) {
@@ -247,6 +408,41 @@ export function calculateEncounterDifficulty(
combatants: readonly CombatantDescriptor[],
edition: RulesEdition,
): DifficultyResult {
if (edition === "pf2e") {
const partyLevels: number[] = [];
for (const c of combatants) {
if (c.level !== undefined && c.side === "party") {
partyLevels.push(c.level);
}
}
const partyLevel = derivePartyLevel(partyLevels);
const { totalCreatureXp } = scanCombatantsPf2e(combatants, partyLevel);
const budget = calculatePf2eBudget(partyLevels.length);
const thresholds: DifficultyThreshold[] = [
{ label: "Trivial", value: budget.trivial },
{ label: "Low", value: budget.low },
{ label: "Moderate", value: budget.moderate },
{ label: "Severe", value: budget.severe },
{ label: "Extreme", value: budget.extreme },
];
return {
tier: tierFromBudgets(totalCreatureXp, [
budget.trivial,
budget.low,
budget.moderate,
budget.severe,
]),
totalMonsterXp: totalCreatureXp,
thresholds,
encounterMultiplier: undefined,
adjustedXp: undefined,
partySizeAdjusted: undefined,
partyLevel,
};
}
const { totalMonsterXp, monsterCount, partyLevels } =
scanCombatants(combatants);
@@ -258,16 +454,15 @@ export function calculateEncounterDifficulty(
{ label: "High", value: budget.high },
];
return {
tier: determineTier(totalMonsterXp, [
budget.low,
budget.moderate,
budget.high,
]),
// 5.5e has no tier below Low, so tier 0 (empty bars) only at 0 XP.
// The High budget is display-only: anything over Moderate is High.
tier: tierFromBudgets(totalMonsterXp, [0, budget.low, budget.moderate]),
totalMonsterXp,
thresholds,
encounterMultiplier: undefined,
adjustedXp: undefined,
partySizeAdjusted: undefined,
partyLevel: undefined,
};
}
@@ -284,7 +479,7 @@ export function calculateEncounterDifficulty(
];
return {
tier: determineTier(adjustedXp, [
tier: tierFromThresholds(adjustedXp, [
budget.medium,
budget.hard,
budget.deadly,
@@ -294,5 +489,6 @@ export function calculateEncounterDifficulty(
encounterMultiplier,
adjustedXp,
partySizeAdjusted,
partyLevel: undefined,
};
}
+10 -1
View File
@@ -1,6 +1,6 @@
import type { ConditionId } from "./conditions.js";
import type { CreatureId } from "./creature-types.js";
import type { PersistentDamageType } from "./persistent-damage.js";
import type { PersistentDamageType } from "./persistent-damage-types.js";
import type { PlayerCharacterId } from "./player-character-types.js";
import type { CombatantId } from "./types.js";
@@ -152,6 +152,14 @@ export interface CreatureAdjustmentSet {
readonly adjustment: "weak" | "elite" | undefined;
}
export interface HpVariantSet {
readonly type: "HpVariantSet";
readonly combatantId: CombatantId;
readonly variant: "min" | "max" | undefined;
readonly previousMaxHp: number | undefined;
readonly newMaxHp: number | undefined;
}
export interface EncounterCleared {
readonly type: "EncounterCleared";
readonly combatantCount: number;
@@ -198,6 +206,7 @@ export type DomainEvent =
| PersistentDamageAdded
| PersistentDamageRemoved
| CreatureAdjustmentSet
| HpVariantSet
| EncounterCleared
| PlayerCharacterCreated
| PlayerCharacterUpdated
+58
View File
@@ -0,0 +1,58 @@
/** Which end of a creature's Hit Dice range its max HP is taken from. */
export type HpVariant = "min" | "max";
export const VALID_HP_VARIANTS: ReadonlySet<string> = new Set(["min", "max"]);
export interface HpRange {
/** Every Hit Die rolls a 1 (never below 1 HP). */
readonly min: number;
/** The statblock's printed average. */
readonly average: number;
/** Every Hit Die rolls its maximum. */
readonly max: number;
}
/**
* Matches a plain Hit Dice pool: "9d8", "3d6 + 6", "2d6 - 2".
* Bestiary data uses several dash characters, so hyphen, minus sign, en dash
* and em dash all count as a negative modifier.
*/
const DICE_FORMULA_REGEX =
/^\s*(\d+)\s*[dD]\s*(\d+)\s*(?:([-+−–—])\s*(\d+))?\s*$/;
/**
* Derives the min/average/max HP of a creature from its Hit Dice formula.
* Returns null when the formula is not a plain dice pool some sources carry
* prose (`hp.special`) or an empty string instead.
*/
export function hpRange(
hp: Readonly<{ average: number; formula: string }>,
): HpRange | null {
const match = DICE_FORMULA_REGEX.exec(hp.formula);
if (!match) return null;
const count = Number(match[1]);
const sides = Number(match[2]);
if (count < 1 || sides < 1) return null;
const modifier =
match[4] === undefined
? 0
: (match[3] === "+" ? 1 : -1) * Number.parseInt(match[4], 10);
return {
min: Math.max(1, count + modifier),
average: hp.average,
max: Math.max(1, count * sides + modifier),
};
}
/** The HP value a variant selects; undefined means the printed average. */
export function hpForVariant(
range: HpRange,
variant: HpVariant | undefined,
): number {
if (variant === "min") return range.min;
if (variant === "max") return range.max;
return range.average;
}
+14
View File
@@ -64,6 +64,8 @@ export {
type DifficultyResult,
type DifficultyThreshold,
type DifficultyTier,
derivePartyLevel,
pf2eCreatureXp,
VALID_CR_VALUES,
} from "./encounter-difficulty.js";
export type {
@@ -80,6 +82,7 @@ export type {
CurrentHpAdjusted,
DomainEvent,
EncounterCleared,
HpVariantSet,
InitiativeSet,
MaxHpSet,
PersistentDamageAdded,
@@ -95,6 +98,13 @@ export type {
TurnRetreated,
} from "./events.js";
export type { ExportBundle } from "./export-bundle.js";
export {
type HpRange,
type HpVariant,
hpForVariant,
hpRange,
VALID_HP_VARIANTS,
} from "./hp-range.js";
export { deriveHpStatus, type HpStatus } from "./hp-status.js";
export {
calculateInitiative,
@@ -151,6 +161,10 @@ export type { RulesEdition } from "./rules-edition.js";
export { type SetAcSuccess, setAc } from "./set-ac.js";
export { type SetCrSuccess, setCr } from "./set-cr.js";
export { type SetHpSuccess, setHp } from "./set-hp.js";
export {
type SetHpVariantSuccess,
setHpVariant,
} from "./set-hp-variant.js";
export {
type SetInitiativeSuccess,
setInitiative,
@@ -0,0 +1,78 @@
export const PERSISTENT_DAMAGE_TYPES = [
"fire",
"bleed",
"acid",
"cold",
"electricity",
"poison",
"mental",
"force",
"void",
"spirit",
"vitality",
"piercing",
] as const;
export type PersistentDamageType = (typeof PERSISTENT_DAMAGE_TYPES)[number];
export const VALID_PERSISTENT_DAMAGE_TYPES: ReadonlySet<string> = new Set(
PERSISTENT_DAMAGE_TYPES,
);
export interface PersistentDamageEntry {
readonly type: PersistentDamageType;
readonly formula: string;
}
export interface PersistentDamageDefinition {
readonly type: PersistentDamageType;
readonly label: string;
readonly iconName: string;
readonly color: string;
}
export const PERSISTENT_DAMAGE_DEFINITIONS: readonly PersistentDamageDefinition[] =
[
{ type: "fire", label: "Fire", iconName: "Flame", color: "orange" },
{ type: "bleed", label: "Bleed", iconName: "Droplets", color: "red" },
{
type: "acid",
label: "Acid",
iconName: "FlaskConical",
color: "lime",
},
{ type: "cold", label: "Cold", iconName: "Snowflake", color: "sky" },
{
type: "electricity",
label: "Electricity",
iconName: "Zap",
color: "yellow",
},
{
type: "poison",
label: "Poison",
iconName: "Droplet",
color: "green",
},
{
type: "mental",
label: "Mental",
iconName: "BrainCog",
color: "pink",
},
{ type: "force", label: "Force", iconName: "Orbit", color: "indigo" },
{ type: "void", label: "Void", iconName: "Eclipse", color: "purple" },
{ type: "spirit", label: "Spirit", iconName: "Wind", color: "neutral" },
{
type: "vitality",
label: "Vitality",
iconName: "Sparkle",
color: "amber",
},
{
type: "piercing",
label: "Piercing",
iconName: "Sword",
color: "neutral",
},
];
+13 -57
View File
@@ -1,4 +1,10 @@
import type { DomainEvent } from "./events.js";
import {
PERSISTENT_DAMAGE_DEFINITIONS,
type PersistentDamageEntry,
type PersistentDamageType,
VALID_PERSISTENT_DAMAGE_TYPES,
} from "./persistent-damage-types.js";
import {
type CombatantId,
type DomainError,
@@ -7,64 +13,14 @@ import {
isDomainError,
} from "./types.js";
export const PERSISTENT_DAMAGE_TYPES = [
"fire",
"bleed",
"acid",
"cold",
"electricity",
"poison",
"mental",
] as const;
export type PersistentDamageType = (typeof PERSISTENT_DAMAGE_TYPES)[number];
export const VALID_PERSISTENT_DAMAGE_TYPES: ReadonlySet<string> = new Set(
export {
PERSISTENT_DAMAGE_DEFINITIONS,
PERSISTENT_DAMAGE_TYPES,
);
export interface PersistentDamageEntry {
readonly type: PersistentDamageType;
readonly formula: string;
}
export interface PersistentDamageDefinition {
readonly type: PersistentDamageType;
readonly label: string;
readonly iconName: string;
readonly color: string;
}
export const PERSISTENT_DAMAGE_DEFINITIONS: readonly PersistentDamageDefinition[] =
[
{ type: "fire", label: "Fire", iconName: "Flame", color: "orange" },
{ type: "bleed", label: "Bleed", iconName: "Droplets", color: "red" },
{
type: "acid",
label: "Acid",
iconName: "FlaskConical",
color: "lime",
},
{ type: "cold", label: "Cold", iconName: "Snowflake", color: "sky" },
{
type: "electricity",
label: "Electricity",
iconName: "Zap",
color: "yellow",
},
{
type: "poison",
label: "Poison",
iconName: "Droplet",
color: "green",
},
{
type: "mental",
label: "Mental",
iconName: "BrainCog",
color: "pink",
},
];
type PersistentDamageDefinition,
type PersistentDamageEntry,
type PersistentDamageType,
VALID_PERSISTENT_DAMAGE_TYPES,
} from "./persistent-damage-types.js";
export interface PersistentDamageSuccess {
readonly encounter: Encounter;
+7 -2
View File
@@ -2,8 +2,10 @@ import type { ConditionEntry, ConditionId } from "./conditions.js";
import { VALID_CONDITION_IDS } from "./conditions.js";
import { creatureId } from "./creature-types.js";
import { VALID_CR_VALUES } from "./encounter-difficulty.js";
import type { PersistentDamageEntry } from "./persistent-damage.js";
import { VALID_PERSISTENT_DAMAGE_TYPES } from "./persistent-damage.js";
import type { HpVariant } from "./hp-range.js";
import { VALID_HP_VARIANTS } from "./hp-range.js";
import type { PersistentDamageEntry } from "./persistent-damage-types.js";
import { VALID_PERSISTENT_DAMAGE_TYPES } from "./persistent-damage-types.js";
import {
playerCharacterId,
VALID_PLAYER_COLORS,
@@ -144,6 +146,9 @@ function parseOptionalFields(entry: Record<string, unknown>) {
entry.creatureAdjustment,
VALID_ADJUSTMENTS,
) as "weak" | "elite" | undefined,
hpVariant: validateSetMember(entry.hpVariant, VALID_HP_VARIANTS) as
| HpVariant
| undefined,
cr: validateCr(entry.cr),
side: validateSide(entry.side),
color: validateSetMember(entry.color, VALID_PLAYER_COLORS),
+73
View File
@@ -0,0 +1,73 @@
import type { DomainEvent } from "./events.js";
import { type HpRange, type HpVariant, hpForVariant } from "./hp-range.js";
import {
type CombatantId,
type DomainError,
type Encounter,
findCombatant,
isDomainError,
} from "./types.js";
export interface SetHpVariantSuccess {
readonly encounter: Encounter;
readonly events: DomainEvent[];
}
/**
* Switches a combatant's max HP between the minimum, average and maximum roll
* of its Hit Dice.
*
* The shift is applied as a delta so manual HP edits and damage already taken
* survive the switch: a creature missing 5 HP still misses 5 HP afterwards.
*/
export function setHpVariant(
encounter: Encounter,
combatantId: CombatantId,
variant: HpVariant | undefined,
range: HpRange,
): SetHpVariantSuccess | DomainError {
const found = findCombatant(encounter, combatantId);
if (isDomainError(found)) return found;
const { combatant } = found;
if (combatant.hpVariant === variant) {
return { encounter, events: [] };
}
const delta =
hpForVariant(range, variant) - hpForVariant(range, combatant.hpVariant);
const newMaxHp =
combatant.maxHp === undefined
? undefined
: Math.max(1, combatant.maxHp + delta);
const newCurrentHp =
combatant.currentHp === undefined || newMaxHp === undefined
? combatant.currentHp
: Math.max(0, Math.min(combatant.currentHp + delta, newMaxHp));
return {
encounter: {
...encounter,
combatants: encounter.combatants.map((c) =>
c.id === combatantId
? {
...c,
maxHp: newMaxHp,
currentHp: newCurrentHp,
hpVariant: variant,
}
: c,
),
},
events: [
{
type: "HpVariantSet",
combatantId,
variant,
previousMaxHp: combatant.maxHp,
newMaxHp,
},
],
};
}
+2 -12
View File
@@ -14,12 +14,6 @@ export interface ToggleConditionSuccess {
readonly events: DomainEvent[];
}
function sortByDefinitionOrder(entries: ConditionEntry[]): ConditionEntry[] {
const order = CONDITION_DEFINITIONS.map((d) => d.id);
entries.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
return entries;
}
function validateConditionId(conditionId: ConditionId): DomainError | null {
if (!VALID_CONDITION_IDS.has(conditionId)) {
return {
@@ -67,8 +61,7 @@ export function toggleCondition(
newConditions = filtered.length > 0 ? filtered : undefined;
event = { type: "ConditionRemoved", combatantId, condition: conditionId };
} else {
const added = sortByDefinitionOrder([...current, { id: conditionId }]);
newConditions = added;
newConditions = [...current, { id: conditionId }];
event = { type: "ConditionAdded", combatantId, condition: conditionId };
}
@@ -125,10 +118,7 @@ export function setConditionValue(
};
}
const added = sortByDefinitionOrder([
...current,
{ id: conditionId, value: clampedValue },
]);
const added = [...current, { id: conditionId, value: clampedValue }];
return {
encounter: applyConditions(encounter, combatantId, added),
events: [
+3 -1
View File
@@ -7,7 +7,8 @@ export function combatantId(id: string): CombatantId {
import type { ConditionEntry } from "./conditions.js";
import type { CreatureId } from "./creature-types.js";
import type { PersistentDamageEntry } from "./persistent-damage.js";
import type { HpVariant } from "./hp-range.js";
import type { PersistentDamageEntry } from "./persistent-damage-types.js";
import type { PlayerCharacterId } from "./player-character-types.js";
export interface Combatant {
@@ -23,6 +24,7 @@ export interface Combatant {
readonly isConcentrating?: boolean;
readonly creatureId?: CreatureId;
readonly creatureAdjustment?: "weak" | "elite";
readonly hpVariant?: HpVariant;
readonly cr?: string;
readonly side?: "party" | "enemy";
readonly color?: string;
+641 -351
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -4,3 +4,8 @@ packages:
onlyBuiltDependencies:
- lefthook
# pnpm >= 10.32 reads overrides/auditConfig from here; the "pnpm" field in
# package.json is no longer honoured.
overrides:
picomatch: ">=4.0.4"
+83
View File
@@ -0,0 +1,83 @@
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { join } from "node:path";
const ROOT = new URL("..", import.meta.url).pathname.replace(/\/$/, "");
const RUN_LINE_RE = /^\s*run:\s*(.+?)\s*$/;
/** @param {string} path */
const read = (path) => readFileSync(join(ROOT, path), "utf-8");
/**
* Gates must invoke `pnpm oxlint` with no extra arguments: pnpm forwards them
* after `--`, where oxlint reads them as file paths and lints nothing.
* @param {Record<string, string>} scripts
*/
function findGatesWithOwnFlags(scripts) {
const commands = Object.entries(scripts)
.filter(([name]) => name !== "oxlint")
.flatMap(([name, body]) =>
body.split("&&").map((c) => [`scripts.${name}`, c.trim()]),
);
for (const line of read("lefthook.yml").split("\n")) {
const command = RUN_LINE_RE.exec(line)?.[1];
if (command) commands.push(["lefthook.yml", command]);
}
return commands
.filter(([, c]) => c.includes("oxlint") && c !== "pnpm oxlint")
.map(([source, c]) => `${source} runs "${c}" instead of "pnpm oxlint"`);
}
/**
* Runs the configured command with one rule forced to warn. A working gate
* exits non-zero; exiting 0 means it lints nothing, or does not fail on
* warnings.
* @param {string} oxlintScript
*/
function failsOnWarnings(oxlintScript) {
const args = [...oxlintScript.split(" ").slice(1), "-W", "no-console"];
try {
execFileSync(join(ROOT, "node_modules/.bin/oxlint"), args, {
cwd: ROOT,
stdio: "ignore",
});
return false;
} catch {
return true;
}
}
/**
* Reports ways a quality gate could pass without checking anything, which is
* indistinguishable from a clean run.
* @returns {string[]}
*/
export function checkGates() {
/** @type {Record<string, string>} */
const scripts = JSON.parse(read("package.json")).scripts;
const violations = findGatesWithOwnFlags(scripts);
// Vitest defaults to failing when no test file matches. Setting this puts
// the test gate back to exiting 0 if the include globs ever stop matching.
if (read("vitest.config.ts").includes("passWithNoTests")) {
violations.push("vitest.config.ts sets passWithNoTests");
}
// jscpd's pattern is a single glob string. An array matches no files, and
// the run then reports success having read nothing.
if (Array.isArray(JSON.parse(read(".jscpd.json")).pattern)) {
violations.push(".jscpd.json sets pattern to an array, not a glob string");
}
// The canary rule below is not type-aware, so the probe alone cannot
// detect type-aware rules being switched off.
if (!scripts.oxlint.includes("--type-aware")) {
violations.push("scripts.oxlint is missing --type-aware");
}
if (!failsOnWarnings(scripts.oxlint)) {
violations.push(
`scripts.oxlint exits 0 despite no-console violations: "${scripts.oxlint}"`,
);
}
return violations;
}
+1 -1
View File
@@ -63,7 +63,7 @@ function checkFile(file, forbidden) {
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(IMPORT_RE);
const match = IMPORT_RE.exec(lines[i]);
if (!match) continue;
const importPath = match[1] || match[2];
+1 -1
View File
@@ -23,7 +23,7 @@ for (const file of findFiles()) {
const lines = readFileSync(file, "utf-8").split("\n");
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(IGNORE_PATTERN);
const match = IGNORE_PATTERN.exec(lines[i]);
if (!match) continue;
count++;
+561
View File
@@ -0,0 +1,561 @@
#!/usr/bin/env python3
"""Extract D&D 5.5e stat blocks from The Great Labors PDF.
Usage:
python3 scripts/extract-great-labors.py <path-to-pdf>
Reads pages 163-199 (Appendix B: Monsters) and emits
data/bestiary/dnd-bundled.json in the Creature[] shape from
packages/domain/src/creature-types.ts.
Requires: PyPDF2 (pip install PyPDF2)
"""
import json
import os
import re
import sys
from pathlib import Path
from PyPDF2 import PdfReader
# --- Constants ---
SOURCE_CODE = "TGL"
SOURCE_DISPLAY = "The Great Labors"
PAGE_START = 163 # 1-indexed
PAGE_END = 199
SIZE_RE = r"(Tiny|Small|Medium|Large|Huge|Gargantuan)"
TYPE_PIECE = r"[A-Za-z][A-Za-z\- ]*?"
ALIGN_PIECE = r"[A-Za-z][A-Za-z ()]*?"
HEADER_RE = re.compile(
rf"^{SIZE_RE}\s+({TYPE_PIECE}(?:\s+\([^)]+\))?),\s+({ALIGN_PIECE})\s*$"
)
AC_RE = re.compile(r"^AC\s+(\d+)\s+Initiative\s+([+\-]\s*\d+|[+\-]?\d+)")
HP_RE = re.compile(r"^HP\s+(\d+)\s*\(([^)]+)\)")
SPEED_RE = re.compile(r"^Speed\s+(.+?)\s*$")
ABILITY_ROW_RE = re.compile(
r"^(Str|Dex|Con|Int|Wis|Cha)\s+(\d+)\s*([+\-]?\s*\d+)\s+([+\-]?\s*\d+)\s+"
r"(Str|Dex|Con|Int|Wis|Cha)\s+(\d+)\s*([+\-]?\s*\d+)\s+([+\-]?\s*\d+)\s+"
r"(Str|Dex|Con|Int|Wis|Cha)\s+(\d+)\s*([+\-]?\s*\d+)\s+([+\-]?\s*\d+)\s*$"
)
CR_RE = re.compile(
r"^Challenge\s+([\d/]+)\s*\(([\d,]+)\s*XP;\s*PB\s+\+(\d+)\)"
)
SECTION_HEADERS = ("Traits", "Actions", "Bonus Actions", "Reactions",
"Legendary Actions", "Mythic Actions")
# Page running header like "166APPENDIX B MONSTERS..." -- marks the
# transition from stat-block content into prose on the next page.
RUNNING_HEADER_RE = re.compile(r"^\d+APPENDIX B\b")
# Condition / status-word false positives that the title-case entry regex
# would otherwise mistake for a new entry name. These names commonly end a
# sentence inside an entry's body (e.g. "...while it is Bloodied.").
NAME_FALSE_POSITIVES = {
"Bloodied", "Restrained", "Grappled", "Charmed", "Frightened",
"Prone", "Incapacitated", "Stunned", "Paralyzed", "Petrified",
"Poisoned", "Blinded", "Deafened", "Invisible", "Unconscious",
"Exhaustion", "Surprised", "Furious",
"Failure", "Success", "Trigger", "Response", "Hit", "Miss",
"Habitat", "Treasure", "Bonus Actions", "Reactions", "Traits", "Actions",
"Disadvantage", "Advantage",
}
# --- Helpers ---
def norm_dash(s: str) -> str:
return s.replace("", "-").replace("", "-").replace("", "-")
def proficiency_bonus(cr_str: str) -> int:
if "/" in cr_str:
n, d = cr_str.split("/")
cr = int(n) / int(d)
else:
cr = int(cr_str)
if cr <= 4:
return 2
if cr <= 8:
return 3
if cr <= 12:
return 4
if cr <= 16:
return 5
if cr <= 20:
return 6
if cr <= 24:
return 7
if cr <= 28:
return 8
return 9
def make_creature_id(source: str, name: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
return f"{source.lower()}:{slug}"
def parse_passive_perception(senses_text: str) -> int | None:
# The PDF sometimes renders multi-digit values with a kerning space
# (e.g. "Passive Perception 1 1" meaning 11). Collapse those.
m = re.search(r"Passive Perception\s+(\d(?:\s*\d)*)\s*$", senses_text)
if not m:
m = re.search(r"Passive Perception\s+(\d+)", senses_text)
return int(m.group(1).replace(" ", "")) if m else None
# --- Page extraction ---
def extract_pages(pdf_path: Path) -> str:
reader = PdfReader(str(pdf_path))
parts = []
for i in range(PAGE_START - 1, PAGE_END):
parts.append(reader.pages[i].extract_text())
return "\n".join(parts)
# --- Block splitting ---
def find_stat_block_starts(lines: list[str]) -> list[int]:
starts = []
for i, line in enumerate(lines):
if AC_RE.match(line.strip()):
header_idx = None
for j in range(i - 1, max(-1, i - 5), -1):
if HEADER_RE.match(lines[j].strip()):
header_idx = j
break
if header_idx is None:
continue
name_idx = header_idx - 1
if name_idx >= 0 and lines[name_idx].strip():
starts.append(name_idx)
return starts
SECTION_HEADER_SMUSH_RE = re.compile(
r"^(?P<body>.+?)\.(?P<hdr>Actions|Bonus Actions|Reactions|Legendary Actions|Traits)\s*$"
)
def block_for(lines: list[str], start: int, next_start: int | None) -> list[str]:
"""Build the line list for one stat block.
Drops page markers and everything from the first running-header line
onward (which marks the transition to a new prose page). Splits PDF
smush lines like "...plants.Actions" into two lines so section header
detection works.
"""
end = next_start if next_start is not None else len(lines)
out: list[str] = []
for ln in lines[start:end]:
if ln.startswith("===PAGE"):
continue
if RUNNING_HEADER_RE.match(ln.strip()):
break
m = SECTION_HEADER_SMUSH_RE.match(ln.strip())
if m:
out.append(m.group("body") + ".")
out.append(m.group("hdr"))
else:
out.append(ln)
return out
# --- Vitals parsing ---
def parse_header(block: list[str]) -> dict:
name = block[0].strip()
header = block[1].strip()
m = HEADER_RE.match(header)
if not m:
raise ValueError(f"Bad header for {name!r}: {header!r}")
size, ctype, alignment = m.group(1), m.group(2).strip(), m.group(3).strip()
return {"name": name, "size": size, "type": ctype, "alignment": alignment}
def parse_ac(line: str) -> int:
m = AC_RE.match(line.strip())
if not m:
raise ValueError(f"Bad AC line: {line!r}")
return int(m.group(1))
def parse_hp(line: str) -> dict:
m = HP_RE.match(line.strip())
if not m:
raise ValueError(f"Bad HP line: {line!r}")
return {"average": int(m.group(1)), "formula": m.group(2).strip()}
def parse_speed(line: str) -> str:
m = SPEED_RE.match(line.strip())
if not m:
raise ValueError(f"Bad Speed line: {line!r}")
speed = m.group(1).rstrip(".").strip()
# Normalize "30 ft" → "30 ft." to match 5etools adapter output style.
speed = re.sub(r"(\d+)\s+ft\b\.?", r"\1 ft.", speed)
return speed
def parse_abilities(row1: str, row2: str) -> dict:
out = {}
for row in (row1, row2):
m = ABILITY_ROW_RE.match(row.strip())
if not m:
raise ValueError(f"Bad ability row: {row!r}")
for off in (0, 4, 8):
ab = m.group(off + 1).lower()
score = int(m.group(off + 2))
out[ab] = score
return out
# --- Meta lines ---
META_KEYS = ("Skills", "Saving Throws", "Resistances", "Immunities",
"Vulnerabilities", "Senses", "Languages", "Gear")
def is_meta_start(line: str) -> str | None:
for key in META_KEYS:
if line.startswith(key + " ") or line.startswith(key + " "):
return key
return None
def parse_meta(lines: list[str], start: int) -> tuple[dict, int]:
meta: dict[str, str] = {}
i = start
current_key: str | None = None
current_val_parts: list[str] = []
def flush() -> None:
nonlocal current_key, current_val_parts
if current_key is not None:
meta[current_key] = " ".join(p.strip() for p in current_val_parts).strip()
current_key = None
current_val_parts = []
while i < len(lines):
line = lines[i].strip()
if not line:
i += 1
continue
if line.startswith("Challenge "):
flush()
return meta, i
key = is_meta_start(line)
if key:
flush()
current_key = key
current_val_parts.append(line[len(key):].strip())
elif current_key is not None:
current_val_parts.append(line)
i += 1
flush()
return meta, i
# --- Section discovery ---
def find_section_starts(block: list[str], start_idx: int) -> list[tuple[str, int]]:
starts = []
for i in range(start_idx, len(block)):
ln = block[i].strip()
if ln in SECTION_HEADERS:
starts.append((ln, i))
return starts
def collect_section_lines(block: list[str], start: int, end: int) -> list[str]:
"""Collect the raw lines for one section (between header indices)."""
out: list[str] = []
for line in block[start:end]:
if not line.strip():
continue
out.append(line.rstrip())
return out
def join_section_text(lines: list[str]) -> str:
"""Join section lines into a single text blob, repairing wrap hyphens."""
text = " ".join(line.strip() for line in lines if line.strip())
text = re.sub(r"\s+", " ", text)
# Repair "civi -li zation" → "civilization" (PDF column-wrap hyphens).
text = re.sub(r"(\w)\s*-\s+(\w)", r"\1\2", text)
return text.strip()
# --- Entry splitting ---
# Entry name: title-case phrase, where each "word" is either a Capitalized
# word, a lowercase connector (of/the/and/or/in/at/on/to/with/from), a roman
# numeral, etc. Optionally followed by parenthesized modifier.
ENTRY_NAME_INNER = (
r"[A-Z][A-Za-z']*"
r"(?:[ \-](?:[A-Z][A-Za-z']*|of|the|and|or|in|at|on|to|with|from))*"
r"(?:\s*\([^)]+\))?"
)
# An entry boundary occurs at the start of the joined section text, or
# immediately after a sentence-ending punctuation. The PDF sometimes drops
# the space between the period and the new entry name, so `\s*` is fine.
ENTRY_BOUNDARY = re.compile(
rf"(?:^|(?<=[\.\?\!]))\s*(?P<name>{ENTRY_NAME_INNER})\.\s+(?=[A-Z“\"(])"
)
# Trim attribution quotes / page-header bleed-through from entry bodies.
PROSE_TAIL_PATTERNS = (
# Em-dash attribution: " —Chondrus, Priest of Lutheria"
re.compile(r"\s+—\s*[A-Z][^—]*$"),
# Smushed section header at end ("...plants.Actions").
re.compile(
r"\.\s*(?:Actions|Bonus\s+Actions|Reactions|Legendary\s+Actions|Traits)\s*$"
),
# Curated prose subheadings / phrase markers that follow stat blocks in
# this book. PDF reflow often merges prose onto the same logical line
# as the last action body, so the leading whitespace is optional.
re.compile(
r"\.?\s*(?:Random Trapped Creature|Maenad Bacchanal|The Phalanx Formation"
r"|Reinforced Portal|TRAPPED|HUNGER FOR|PURSUIT OF|RITUAL|MyTHIC|BRON"
r"|GOlDEN|NyMPH|MARBlE|KElEDONE|SOlDIER|MINOTAUR|SATyRS|GOATlING|EMPUS"
r"|ANARCH|GyGAN|CERBERUS|WHITE STAG|STORM|FEy|VOlKAN).*",
re.DOTALL,
),
# Specific prose sentence-starts observed leaking in.
re.compile(
r"\.(?:will gleefully|Some report that|Storm Dory|This magic weapon"
r"|Thylean soldiers|Some claim|These leaders).*",
re.DOTALL,
),
# All-caps run of 3+ uppercase letters in a word, then a space, then
# another word with 3+ uppercase letters (PDF small-caps section header
# like "BRON zE STRATEGOS", "MyTHIC BEAST", "GOlDEN RAM").
re.compile(r"(?<=[\.\s])[A-Z]{2}\w*\s+[\w ]{0,12}[A-Z]{3}[A-Z\w ]*"),
)
def trim_prose_tail(body: str) -> str:
out = body
for pat in PROSE_TAIL_PATTERNS:
m = pat.search(out)
if m:
out = out[:m.start()].rstrip().rstrip(".") + "."
return out.strip()
def is_valid_entry_name(name: str) -> bool:
"""Filter false-positive matches that aren't really entry names."""
if name in NAME_FALSE_POSITIVES:
return False
# Single short capitalized word that's a common condition or noun is
# usually a false positive when followed by a period. Real entry names
# almost always have either multiple words or a parenthesized modifier.
bare = re.sub(r"\s*\([^)]+\)\s*", "", name).strip()
if bare in NAME_FALSE_POSITIVES:
return False
return True
def split_text_into_entries(text: str) -> list[tuple[str, str]]:
"""Split section text into (name, body) entries by scanning for entry-name
boundaries (start-of-text or after a sentence period)."""
matches: list[tuple[int, int, str]] = []
for m in ENTRY_BOUNDARY.finditer(text):
name = m.group("name").strip()
if is_valid_entry_name(name):
matches.append((m.start(), m.end(), name))
if not matches:
return []
entries: list[tuple[str, str]] = []
for i, (_, body_start, name) in enumerate(matches):
body_end = matches[i + 1][0] if i + 1 < len(matches) else len(text)
body = text[body_start:body_end].strip()
entries.append((name, body))
return entries
def parse_section_traits(lines: list[str]) -> list[dict]:
text = join_section_text(lines)
entries = split_text_into_entries(text)
out = []
for name, body in entries:
body = trim_prose_tail(body)
if body or name:
out.append({"name": name,
"segments": [{"type": "text", "value": body}]})
return out
def parse_legendary(lines: list[str], creature_name: str) -> dict | None:
"""Parse the Legendary Actions section. Text before the first entry whose
body contains action vocabulary forms the preamble.
"""
text = join_section_text(lines)
all_matches: list[tuple[int, int, str]] = []
for m in ENTRY_BOUNDARY.finditer(text):
name = m.group("name").strip()
if is_valid_entry_name(name):
all_matches.append((m.start(), m.end(), name))
action_anchors = ("Saving Throw", "Attack Roll", "Trigger", "Recharge",
"Melee", "Ranged", "Constitution", "Dexterity",
"Strength", "Intelligence", "Wisdom", "Charisma")
first_action_idx = None
for i, (_, body_start, _) in enumerate(all_matches):
body_end = all_matches[i + 1][0] if i + 1 < len(all_matches) else len(text)
body_head = text[body_start:min(body_end, body_start + 100)]
if any(a in body_head for a in action_anchors):
first_action_idx = i
break
if first_action_idx is None:
return None
preamble = text[:all_matches[first_action_idx][0]].strip()
if not preamble:
preamble = f"{creature_name} can take Legendary Actions."
entries = []
for i in range(first_action_idx, len(all_matches)):
_, body_start, name = all_matches[i]
body_end = all_matches[i + 1][0] if i + 1 < len(all_matches) else len(text)
body = text[body_start:body_end].strip()
entries.append((name, body))
if not entries:
return None
return {
"preamble": preamble,
"entries": [
{"name": name,
"segments": [{"type": "text", "value": trim_prose_tail(body)}]}
for name, body in entries if body
],
}
# --- Top-level parse ---
def parse_block(block: list[str]) -> dict:
head = parse_header(block)
ac = parse_ac(block[2])
hp = parse_hp(block[3])
speed = parse_speed(block[4])
if not block[5].strip().startswith("MOD"):
raise ValueError(f"Expected MOD header, got: {block[5]!r}")
abilities = parse_abilities(block[6], block[7])
meta, ch_idx = parse_meta(block, 8)
cr_match = CR_RE.match(block[ch_idx].strip())
if not cr_match:
raise ValueError(f"Bad Challenge line: {block[ch_idx]!r}")
cr_str = cr_match.group(1)
section_starts = find_section_starts(block, ch_idx + 1)
sections: dict[str, list[str]] = {}
for i, (name, idx) in enumerate(section_starts):
end = section_starts[i + 1][1] if i + 1 < len(section_starts) else len(block)
sections[name] = collect_section_lines(block, idx + 1, end)
creature: dict = {
"id": make_creature_id(SOURCE_CODE, head["name"]),
"name": head["name"],
"source": SOURCE_CODE,
"sourceDisplayName": SOURCE_DISPLAY,
"size": head["size"],
"type": head["type"],
"alignment": head["alignment"],
"ac": ac,
"hp": hp,
"speed": speed,
"abilities": abilities,
"cr": cr_str,
"initiativeProficiency": 0,
"proficiencyBonus": proficiency_bonus(cr_str),
"passive": parse_passive_perception(meta.get("Senses", "")) or 10,
}
if "Saving Throws" in meta:
creature["savingThrows"] = meta["Saving Throws"]
if "Skills" in meta:
creature["skills"] = meta["Skills"]
if "Resistances" in meta:
creature["resist"] = meta["Resistances"]
if "Immunities" in meta:
creature["immune"] = meta["Immunities"]
if "Vulnerabilities" in meta:
creature["vulnerable"] = meta["Vulnerabilities"]
if "Senses" in meta:
senses = re.sub(r"[;,]?\s*Passive Perception\s+\d+\s*$", "", meta["Senses"])
senses = senses.strip().rstrip(";").strip()
if senses:
creature["senses"] = senses
if "Languages" in meta:
creature["languages"] = meta["Languages"]
if "Traits" in sections:
creature["traits"] = parse_section_traits(sections["Traits"])
if "Actions" in sections:
creature["actions"] = parse_section_traits(sections["Actions"])
if "Bonus Actions" in sections:
creature["bonusActions"] = parse_section_traits(sections["Bonus Actions"])
if "Reactions" in sections:
creature["reactions"] = parse_section_traits(sections["Reactions"])
if "Legendary Actions" in sections:
leg = parse_legendary(sections["Legendary Actions"], head["name"])
if leg:
creature["legendaryActions"] = leg
return creature
def main() -> int:
if len(sys.argv) != 2:
print("Usage: python3 extract-great-labors.py <path-to-pdf>",
file=sys.stderr)
return 1
pdf_path = Path(os.path.expanduser(sys.argv[1]))
if not pdf_path.exists():
print(f"PDF not found: {pdf_path}", file=sys.stderr)
return 1
text = extract_pages(pdf_path)
lines = text.split("\n")
starts = find_stat_block_starts(lines)
print(f"Detected {len(starts)} stat blocks", file=sys.stderr)
creatures = []
failures = []
for i, s in enumerate(starts):
next_s = starts[i + 1] if i + 1 < len(starts) else None
block = block_for(lines, s, next_s)
try:
creatures.append(parse_block(block))
except Exception as e:
failures.append((block[0] if block else "<empty>", str(e)))
if failures:
print(f"\n{len(failures)} parse failures:", file=sys.stderr)
for name, err in failures:
print(f" - {name}: {err}", file=sys.stderr)
out_path = Path(__file__).resolve().parent.parent / "data" / "bestiary" / "dnd-bundled.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w") as f:
json.dump(creatures, f, indent="\t", ensure_ascii=False)
f.write("\n")
print(f"Wrote {len(creatures)} creatures to {out_path}", file=sys.stderr)
return 0 if not failures else 2
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -108,6 +108,7 @@ const files = readdirSync(BESTIARY_DIR).filter(
);
const creatures = [];
/** @type {Set<string>} */
const unmappedSources = new Set();
for (const file of files.sort()) {
+2 -2
View File
@@ -356,7 +356,7 @@ Acceptance scenarios:
As a DM running a PF2e encounter, I want to apply persistent damage to a combatant as a compact tag showing a damage type icon and formula so I can track ongoing damage effects without manual bookkeeping.
Acceptance scenarios:
1. **Given** the game system is Pathfinder 2e and the condition picker is open, **When** the user clicks "Persistent Damage", **Then** a sub-picker opens with a damage type dropdown (fire, bleed, acid, cold, electricity, poison, mental) and a formula text input.
1. **Given** the game system is Pathfinder 2e and the condition picker is open, **When** the user clicks "Persistent Damage", **Then** a sub-picker opens with a damage type dropdown (fire, bleed, acid, cold, electricity, poison, mental, force, void, spirit, vitality, piercing) and a formula text input.
2. **Given** the sub-picker is open, **When** the user selects "fire" and types "2d6" and confirms, **Then** a compact tag appears on the combatant row showing a fire icon and "2d6".
3. **Given** a combatant has persistent fire 2d6, **When** the user adds persistent bleed 1d4, **Then** both tags appear on the row simultaneously.
4. **Given** a combatant has persistent fire 2d6, **When** the user adds persistent fire 3d6, **Then** the existing fire entry is replaced with 3d6 (one instance per type).
@@ -421,7 +421,7 @@ Acceptance scenarios:
- **FR-111**: When Pathfinder 2e is the active game system, the concentration UI (Brain icon toggle, purple left border accent, damage pulse animation) MUST be hidden entirely. The Brain icon MUST NOT be shown on hover or at rest, and the concentration toggle MUST NOT be interactive.
- **FR-112**: Switching the game system MUST NOT clear or modify `isConcentrating` state on any combatant. The state MUST be preserved in storage and restored to the UI when switching back to a D&D game system.
- **FR-117**: When Pathfinder 2e is active, the condition picker MUST include a "Persistent Damage" entry that opens a sub-picker instead of toggling directly.
- **FR-118**: The persistent damage sub-picker MUST contain a dropdown of common PF2e damage types (fire, bleed, acid, cold, electricity, poison, mental) and a text input for the damage formula (e.g., "2d6").
- **FR-118**: The persistent damage sub-picker MUST contain a dropdown of PF2e damage types (fire, bleed, acid, cold, electricity, poison, mental, force, void, spirit, vitality, piercing) and a text input for the damage formula (e.g., "2d6").
- **FR-119**: Each persistent damage entry MUST be displayed as a compact tag on the combatant row showing a damage type icon and the formula text (e.g., fire icon + "2d6").
- **FR-120**: Only one persistent damage entry per damage type is allowed per combatant. Adding the same damage type MUST replace the existing formula.
- **FR-121**: Clicking a persistent damage tag on the combatant row MUST remove that entry.
+22 -1
View File
@@ -118,6 +118,11 @@ As a DM running a PF2e encounter, I want to toggle a weak or elite adjustment on
When viewing a PF2e creature's stat block, a Weak/Normal/Elite toggle appears in the header. Selecting "Elite" or "Weak" applies the standard PF2e adjustments: ±2 to AC, saves, Perception, attack rolls, and strike damage; HP adjusted by the standard level bracket table; level shifted. The combatant's stored HP and AC update accordingly (see `specs/003-combatant-state/spec.md`, FR-113FR-116), and its name gains a prefix (see `specs/001-combatant-management/spec.md`, FR-041FR-042). The toggle defaults to "Normal" and is not shown for D&D creatures. A visual indicator (the same icon used in the toggle) appears next to the creature name in the header.
**US-D8 — Set a D&D Combatant to Minimum or Maximum Hit Points (P2)**
As a DM running a D&D encounter, I want to switch a bestiary-linked combatant between the minimum, average and maximum result of its Hit Dice so I can make a single monster tougher or flimsier without hand-editing HP.
When viewing a D&D creature's stat block for a combatant, a Min/Avg/Max toggle appears under the Hit Points line. The stat block shows the printed average by default; selecting "Min" or "Max" shows the value the Hit Dice would produce if every die rolled its lowest or highest face (e.g., `3d6 + 6` → 9 or 24) and updates the combatant's stored max HP by the same delta. This is a convenience tool, not a rules mechanic — no other stat changes and the combatant is not renamed.
### Requirements
- **FR-016**: The system MUST display a stat block panel with full creature information when a creature is selected.
@@ -151,6 +156,12 @@ When viewing a PF2e creature's stat block, a Weak/Normal/Elite toggle appears in
- **FR-106**: Toggling the adjustment MUST update the combatant's name with the appropriate prefix — "Weak" or "Elite" — or remove the prefix when returning to "Normal" (see `specs/001-combatant-management/spec.md`, FR-041FR-042).
- **FR-107**: The stat block header MUST display a visual indicator (the same icon used in the toggle) next to the creature name when the creature has a weak or elite adjustment.
- **FR-108**: The adjustment MUST be stored on the combatant as a `creatureAdjustment` field and persist across page reloads.
- **FR-109**: D&D stat blocks MUST include a Min/Avg/Max hit point toggle below the Hit Points line, defaulting to "Avg".
- **FR-110**: The Min/Avg/Max toggle MUST only be shown for a bestiary-linked combatant whose HP formula is a plain Hit Dice pool (`NdM`, optionally `± K`) with a spread — it MUST NOT be shown while browsing a creature without a combatant, for PF2e creatures, or when the HP field carries prose instead of dice.
- **FR-111**: "Min" MUST use the result of every Hit Die rolling 1 (dice count + modifier); "Max" MUST use the result of every Hit Die rolling its highest face (dice count × faces + modifier). Both MUST be at least 1. "Avg" MUST use the printed average.
- **FR-112**: Selecting a variant MUST shift the combatant's stored maxHp by the delta between the previously selected and newly selected value, preserving manual HP edits. The combatant's currentHp MUST shift by the same delta, clamped to [0, new maxHp].
- **FR-113**: Selecting a variant MUST NOT change the combatant's name or any stat other than HP.
- **FR-114**: The selected variant MUST be stored on the combatant as an `hpVariant` field (`"min" | "max"`, absent for average) and persist across page reloads and JSON export/import.
### Acceptance Scenarios
@@ -194,6 +205,11 @@ When viewing a PF2e creature's stat block, a Weak/Normal/Elite toggle appears in
38. **Given** a PF2e creature with level 1 stat block is open, **When** the DM selects "Weak", **Then** the level decreases by 2 (to 1, not 0).
39. **Given** a PF2e combatant was set to "Elite" and the page is reloaded, **When** the DM opens the stat block, **Then** the toggle shows "Elite" and the stat block displays adjusted stats.
40. **Given** a PF2e combatant was set to "Elite", **When** the DM toggles back to "Normal", **Then** the stat block reverts to base stats, the combatant's HP/AC revert, and the name prefix is removed.
41. **Given** a D&D combatant's stat block is open, **When** the DM views the Hit Points line, **Then** a Min/Avg/Max toggle is visible, set to "Avg".
42. **Given** a D&D combatant with `3d6 + 6` hit points (average 16) is at full health, **When** the DM selects "Max", **Then** the stat block shows 24 hit points and the combatant's HP becomes 24/24.
43. **Given** the same combatant, **When** the DM selects "Min", **Then** the stat block shows 9 hit points and the combatant's HP becomes 9/9.
44. **Given** a D&D combatant set to "Max" has taken 5 damage (19/24), **When** the DM selects "Avg", **Then** the combatant's HP becomes 11/16 — the damage taken is preserved.
45. **Given** a D&D combatant was set to "Max" and the page is reloaded, **When** the DM opens the stat block, **Then** the toggle shows "Max" and the maximum hit points are displayed.
### Edge Cases
@@ -216,6 +232,11 @@ When viewing a PF2e creature's stat block, a Weak/Normal/Elite toggle appears in
- 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.
- HP formula that is not a dice pool (empty, prose such as "equal to the summoner's", or a flat number): the Min/Avg/Max toggle is omitted and the printed average is shown unchanged.
- HP formula written with an en dash or em dash instead of a hyphen (present in bundled source data, e.g. `2d6 2`): parsed as a negative modifier.
- Hit Dice modifier larger than the dice pool (e.g. `1d4 - 10`): the resulting hit points are floored at 1.
- Toggling from Min to Max: applies the full swing in a single operation.
- Combatant whose max HP was edited by hand before toggling: the edit is preserved as an offset, since the toggle applies the delta between variants rather than an absolute value.
---
@@ -396,7 +417,7 @@ As a DM with a creature pinned, I want to collapse the right (browse) panel inde
- **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").
- **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. PF2e bestiary-linked combatants may also carry a `creatureAdjustment` (`"weak" | "elite"`) indicating the active PF2e weak/elite adjustment, persisted across reloads.
- **Combatant** (extended): Gains an optional `creatureId` reference to a `Creature`, enabling stat block lookup and stat pre-fill on creation. PF2e bestiary-linked combatants may also carry a `creatureAdjustment` (`"weak" | "elite"`) indicating the active PF2e weak/elite adjustment, persisted across reloads. D&D bestiary-linked combatants may carry an `hpVariant` (`"min" | "max"`) indicating that their max HP was set to the lowest or highest possible Hit Dice result instead of the printed average, likewise persisted across reloads.
- **Queued Creature**: Transient UI-only state representing a bestiary creature selected for batch-add, containing the creature reference and a count (1+). Not persisted.
- **Bulk Import Operation**: Tracks total sources, completed count, failed count, and current status (idle / loading / complete / partial-failure).
- **Toast Notification**: Lightweight custom UI element at bottom-center of screen with text, optional progress bar, and optional dismiss button.
+43 -1
View File
@@ -75,6 +75,30 @@ When adding combatants to an encounter, the GM can search for their saved player
---
**Story PC-8 — Add the whole party to an encounter (Priority: P1)**
At the start of a session the GM wants the entire party in the initiative tracker. Instead of searching for each character by name, they open the player character management view and add every saved character to the encounter in one action.
**Why this priority**: Putting the party on the board is how nearly every encounter starts. Doing it one character at a time is the main friction in the setup flow.
**Independent Test**: Can be tested by creating several player characters, triggering the add-party action, and verifying every character is present as a combatant.
**Acceptance Scenarios**:
1. **Given** player characters "Aragorn", "Legolas", and "Gimli" exist and none are in the encounter, **When** the user triggers the add-party action from the management view, **Then** a combatant is created for each of them, with the same stats, color, and icon an individual add would produce.
2. **Given** "Aragorn" is already a combatant in the encounter and "Legolas" is not, **When** the user triggers the add-party action, **Then** only "Legolas" is added — "Aragorn" gets no second copy and is not renamed.
3. **Given** the user has just added the party, **When** the user undoes once, **Then** every combatant created by that action is removed together.
4. **Given** every saved player character is already in the encounter, **When** the user opens the management view, **Then** the add-party action is unavailable and communicates why.
5. **Given** some player characters are already in the encounter, **When** the user opens the management view, **Then** those characters are marked as already present and the add-party action remains available for the rest.
6. **Given** no player characters exist, **When** the user opens the management view, **Then** the empty state is shown without an add-party action.
---
### Displaying Player Characters in Encounters
**Story PC-4 — Visual distinction for player character combatants (Priority: P2)**
@@ -152,7 +176,10 @@ The GM no longer needs a player character and wants to remove it from their save
### Edge Cases
- **Duplicate player character names**: Permitted. Player characters are identified by a unique internal ID, not by name.
- **Adding the same player character to an encounter multiple times**: Each addition creates an independent combatant copy. Multiple copies of the same PC in one encounter are allowed.
- **Adding the same player character to an encounter multiple times**: Each addition creates an independent combatant copy. Multiple copies of the same PC in one encounter are allowed. The add-party action is the deliberate exception — it skips characters that are already present (see PC-8).
- **Adding the party when part of it is already present**: Only the missing characters are added. Membership is determined by player character identity, not by name.
- **Adding the party after a PC-derived combatant was renamed**: The combatant is still recognised as that player character, so the party add does not produce a duplicate.
- **Adding the party after the source player character was deleted**: The orphaned combatant matches no saved character; it is left alone and the remaining party members add normally.
- **Editing a player character while it is also a combatant in the active encounter**: The active combatant is not affected; only future additions use the updated stats.
- **Deleting a player character while it is a combatant in the active encounter**: The combatant remains in the encounter unchanged.
- **Very long player character names**: The UI should truncate or ellipsize names that exceed the available space.
@@ -224,10 +251,23 @@ The system MUST allow deleting a player character with two-step confirmation (Co
#### FR-019 — Management: Delete does not affect active combatants
Deleting a player character MUST NOT remove or modify any combatants currently in an encounter.
#### FR-020 — Add to encounter: Add the whole party
The management view MUST provide an action that adds all saved player characters to the current encounter in a single interaction.
#### FR-021 — Add to encounter: Party add skips present members
Adding the party MUST skip player characters that already have a combatant in the current encounter. Membership MUST be determined by player character identity, not by combatant name.
#### FR-022 — Add to encounter: Party add is one undo step
Adding the party MUST be reversible as a single undo step, regardless of how many combatants it created.
#### FR-023 — Management: Indicate encounter membership
The management view MUST indicate which saved player characters are already in the current encounter, and MUST disable the add-party action when none remain to be added.
### Key Entities
- **PlayerCharacter**: A persistent, reusable character template with a unique `PlayerCharacterId` (branded string), required `name`, `ac` (number), `maxHp` (number), `color` (string from predefined set), `icon` (string identifier from preset icon set), and optional `level` (integer 1-20, added by spec 008 for encounter difficulty calculation).
- **PlayerCharacterStore** (port): Interface for loading, saving, and deleting player characters. Implemented as a browser storage adapter.
- **Combatant → PlayerCharacter link**: A combatant created from a player character retains that character's `PlayerCharacterId`. The link drives display (color, icon) and encounter-membership detection (FR-021). It does not make the combatant a live view of the character — the combatant remains an independent copy (FR-014).
---
@@ -244,6 +284,8 @@ Deleting a player character MUST NOT remove or modify any combatants currently i
- **SC-007**: All player character domain operations (create, edit, delete) are pure functions with no I/O, consistent with the project's deterministic domain core.
- **SC-008**: The player character domain module has zero imports from application, adapter, or UI layers.
- **SC-009**: Corrupt or missing player character data never causes a crash — the application gracefully falls back to an empty player character list.
- **SC-010**: Users can put their entire party into an encounter with one interaction, and reverse it with one undo — no matter how large the party is.
- **SC-011**: Repeating the add-party action never produces duplicate or auto-renamed copies of a player character already in the encounter.
---
+114 -13
View File
@@ -3,7 +3,7 @@
**Feature Branch**: `008-encounter-difficulty`
**Created**: 2026-03-27
**Status**: Draft
**Input**: Gitea issue #18 — "Encounter difficulty indicator (5.5e XP budget)", Gitea issue #22 — "Combatant side assignment for encounter difficulty", Gitea issue #23 — "2014 DMG encounter difficulty calculation"
**Input**: Gitea issue #18 — "Encounter difficulty indicator (5.5e XP budget)", Gitea issue #22 — "Combatant side assignment for encounter difficulty", Gitea issue #23 — "2014 DMG encounter difficulty calculation", Gitea issue #28 — "PF2e encounter difficulty calculation"
## User Scenarios & Testing *(mandatory)*
@@ -19,15 +19,15 @@ A game master is building an encounter by adding monsters and player characters.
**Acceptance Scenarios**:
1. **Given** an encounter with at least one PC combatant whose player character has a level and at least one bestiary-linked combatant, **When** the total monster XP is below the Low threshold, **Then** the indicator shows three empty bars (trivial difficulty).
1. **Given** an encounter with at least one PC combatant whose player character has a level and at least one bestiary-linked combatant, **When** the total monster XP is 0, **Then** the indicator shows three empty bars (the 2024 rules define no tier below Low, so empty bars appear only at 0 XP).
2. **Given** an encounter where total monster XP meets or exceeds the Low threshold but is below Moderate, **When** the indicator renders, **Then** it shows one filled green bar and the tooltip reads "Low encounter difficulty".
2. **Given** an encounter where total monster XP is greater than 0 and within the Low budget, **When** the indicator renders, **Then** it shows one filled green bar and the tooltip reads "Low encounter difficulty".
3. **Given** an encounter where total monster XP meets or exceeds the Moderate threshold but is below High, **When** the indicator renders, **Then** it shows two filled yellow bars and the tooltip reads "Moderate encounter difficulty".
3. **Given** an encounter where total monster XP exceeds the Low budget but is within the Moderate budget, **When** the indicator renders, **Then** it shows two filled yellow bars and the tooltip reads "Moderate encounter difficulty".
4. **Given** an encounter where total monster XP meets or exceeds the High threshold, **When** the indicator renders, **Then** it shows three filled red bars and the tooltip reads "High encounter difficulty".
4. **Given** an encounter where total monster XP exceeds the Moderate budget, **When** the indicator renders, **Then** it shows three filled red bars and the tooltip reads "High encounter difficulty" (per the 2024 DMG, budgets are maximums — an encounter over the Moderate budget is a High encounter even if it is below the High budget).
5. **Given** an encounter where total monster XP exceeds the High threshold by a large margin, **When** the indicator renders, **Then** it still shows three filled red bars (High is the cap — there is no "above High" tier).
5. **Given** an encounter where total monster XP exceeds the High budget by a large margin, **When** the indicator renders, **Then** it still shows three filled red bars (High is the cap — there is no "above High" tier).
6. **Given** the difficulty indicator is visible, **When** a bestiary-linked combatant is added or removed, **Then** the indicator updates immediately to reflect the new difficulty tier.
@@ -39,6 +39,12 @@ A game master is building an encounter by adding monsters and player characters.
10. **Given** the user switches the rules edition in settings, **When** returning to the encounter, **Then** the indicator tooltip reflects the new edition's labels immediately.
11. **Given** the rules edition is set to PF2e, **When** the indicator renders, **Then** it displays four bars instead of three, supporting five visual states: zero filled bars for Trivial, one green bar for Low, two yellow bars for Moderate, three orange bars for Severe, four red bars for Extreme.
12. **Given** the rules edition is set to PF2e, **When** the indicator tooltip renders, **Then** it uses PF2e tier labels (e.g., "Severe encounter difficulty").
13. **Given** the user switches the rules edition to or from PF2e, **When** returning to the encounter, **Then** the indicator bar count (3 vs 4) and tier labels update immediately.
---
### Indicator Visibility
@@ -63,6 +69,10 @@ The difficulty indicator only appears when meaningful calculation is possible. I
5. **Given** an encounter with one leveled PC combatant and one bestiary-linked monster, **When** the last bestiary-linked monster is removed and the remaining custom combatants have no `cr` assigned, **Then** the indicator disappears.
6. **Given** the rules edition is set to PF2e and an encounter has leveled PC combatants and creatures with a creature level (from bestiary data), **When** the top bar renders, **Then** the difficulty indicator is shown. CR is not required — PF2e uses creature level, not CR.
7. **Given** the rules edition is set to PF2e and an encounter has bestiary-linked PF2e creatures but no PC combatants with levels, **When** the top bar renders, **Then** the difficulty indicator is hidden.
---
### Player Character Level
@@ -93,7 +103,7 @@ The game master can set an optional level (1-20) when creating or editing a play
**Story ED-4 — Correct XP budget from 5.5e rules (Priority: P1)**
The difficulty calculation uses the 2024 5.5e XP Budget per Character table and a standard CR-to-XP mapping. The party's XP budget is the sum of per-character budgets for each PC combatant that has a level. The total monster XP is the sum of XP values for each bestiary-linked combatant's CR. The difficulty tier is determined by comparing total monster XP against the Low, Moderate, and High budget thresholds.
The difficulty calculation uses the 2024 5.5e XP Budget per Character table and a standard CR-to-XP mapping. The party's XP budget is the sum of per-character budgets for each PC combatant that has a level. The total monster XP is the sum of XP values for each bestiary-linked combatant's CR. The difficulty tier is determined by comparing total monster XP against the Low, Moderate, and High budgets, where each budget is the tier's maximum ("spend as much of your XP budget as you can without going over" — 2024 DMG).
**Why this priority**: Incorrect calculation would make the feature misleading — the math must match the published rules.
@@ -101,9 +111,9 @@ The difficulty calculation uses the 2024 5.5e XP Budget per Character table and
**Acceptance Scenarios**:
1. **Given** a party of four level 1 PCs (Low budget: 50 each = 200 total), **When** facing a single Bugbear (CR 1, 200 XP), **Then** the difficulty is Low (200 XP meets the Low threshold of 200 but is below Moderate at 300).
1. **Given** a party of four level 1 PCs (Low budget: 50 each = 200 total), **When** facing a single Bugbear (CR 1, 200 XP), **Then** the difficulty is Low (200 XP spends exactly the Low budget without going over).
2. **Given** a party of five level 3 PCs (Moderate budget: 225 each = 1,125 total), **When** facing monsters totaling 1,125 XP, **Then** the difficulty is Moderate.
2. **Given** a party of five level 3 PCs (Moderate budget: 225 each = 1,125 total), **When** facing monsters totaling 1,125 XP, **Then** the difficulty is Moderate. **When** facing monsters totaling 1,150 XP (over the Moderate budget), **Then** the difficulty is High.
3. **Given** a party with PCs at different levels (e.g., three level 3 and one level 2), **When** the budget is calculated, **Then** each PC's budget is looked up individually by level and summed (not averaged).
@@ -151,6 +161,12 @@ The game master taps the difficulty indicator to open a breakdown panel. The pan
9. **Given** the rules edition is set to 5e (2014) and the breakdown panel is open, **When** viewing the party budget section, **Then** the panel shows four threshold columns (Easy, Medium, Hard, Deadly) instead of three (Low, Moderate, High).
10. **Given** the rules edition is set to PF2e and the breakdown panel is open, **When** viewing the creature list, **Then** each creature shows its level, level difference from party level, and XP contribution — not CR.
11. **Given** the rules edition is set to PF2e and the breakdown panel is open, **When** viewing the party budget section, **Then** the panel shows five threshold columns (Trivial/Low/Moderate/Severe/Extreme) and indicates the derived party level.
12. **Given** the rules edition is set to PF2e and the party size differs from 4, **When** the breakdown panel is open, **Then** the panel shows the adjusted thresholds and a brief explanation of the party size adjustment.
---
### Manual CR Assignment
@@ -253,10 +269,46 @@ A game master who runs games using the 2014 (original 5e) rules selects "5e (201
---
### PF2e Rules Edition
**Story ED-10 — PF2e encounter difficulty calculation (Priority: P2)**
A game master running Pathfinder 2e selects "Pathfinder 2e" in the Rules Edition setting. The difficulty indicator uses PF2e's level-based calculation: each creature's XP contribution is determined by its level relative to the party level using a standard XP table, and the total is compared against Trivial/Low/Moderate/Severe/Extreme budget thresholds. Party level is auto-derived from the PCs' levels. No encounter multiplier is used — creature XP is summed directly.
**Why this priority**: The core indicator (ED-1) and 5.5e calculation (ED-4) must work first. PF2e support extends the existing system with a fundamentally different calculation paradigm (level-based instead of CR-based).
**Independent Test**: Can be tested by setting rules edition to PF2e, creating an encounter with leveled PCs and PF2e bestiary creatures, and verifying the indicator uses PF2e thresholds, XP table, and labels.
**Acceptance Scenarios**:
1. **Given** the rules edition is set to PF2e and an encounter has leveled PCs and PF2e bestiary creatures, **When** the difficulty is calculated, **Then** the system derives each creature's XP from the PF2e creature level vs party level XP table and compares the total against Trivial/Low/Moderate/Severe/Extreme thresholds.
2. **Given** a party of four level 3 PCs and a creature at level 3 (level difference 0), **When** the XP is calculated, **Then** the creature contributes 40 XP. The total (40) is within the Trivial band ("40 XP or less") — difficulty is Trivial.
3. **Given** a party of four level 5 PCs and a creature at level 9 (level difference +4), **When** the XP is calculated, **Then** the creature contributes 160 XP. The total (160) exceeds the Severe budget (120) — difficulty is Extreme.
4. **Given** PCs at levels 3, 3, 3, and 5, **When** the party level is derived, **Then** it is 3 (the most common level among PCs).
5. **Given** PCs at levels 2, 4, 6, and 8 (all different), **When** the party level is derived, **Then** it is 5 (the average, rounded to the nearest integer).
6. **Given** a party of 5 PCs (one more than the base of 4) at the Moderate tier, **When** the budget thresholds are calculated, **Then** each threshold is increased by its per-tier adjustment: Trivial +10, Low +20, Moderate +20, Severe +30, Extreme +40.
7. **Given** a party of 3 PCs (one fewer than the base of 4) at the Moderate tier, **When** the budget thresholds are calculated, **Then** each threshold is decreased by its per-tier adjustment: Trivial 10, Low 20, Moderate 20, Severe 30, Extreme 40.
8. **Given** the rules edition is set to PF2e, **When** the indicator visual states are rendered, **Then** 0 bars = Trivial, 1 green bar = Low, 2 yellow bars = Moderate, 3 orange bars = Severe, 4 red bars = Extreme.
9. **Given** the user changes the rules edition from 5.5e to PF2e while an encounter is open, **When** the setting is saved, **Then** the difficulty indicator updates immediately to reflect the PF2e calculation, labels, and 4-bar layout.
10. **Given** the rules edition is set to PF2e and a creature has a level difference below 4, **When** XP is calculated, **Then** the creature contributes 0 XP (the GM Core table has no row below 4; such creatures pose no meaningful threat).
11. **Given** the rules edition is set to PF2e and a creature has a level difference above +4, **When** XP is calculated, **Then** the creature contributes 160 XP (the maximum in the table — level difference +4).
---
### Edge Cases
- **All bars empty (trivial)**: When total monster XP is greater than 0 but below the Low threshold, the indicator shows three empty bars. This communicates "we can calculate, but it's trivial."
- **Zero monster XP**: If all combatants with `creatureId` have CR 0 (0 XP), the indicator shows three empty bars (trivial).
- **All bars empty (5.5e)**: Only when total monster XP is exactly 0 — the 2024 rules define no tier below Low, so any nonzero XP within the Low budget is a Low encounter. (For 2014, adjusted XP below the Easy threshold shows empty bars.)
- **Zero monster XP**: If all combatants with `creatureId` have CR 0 (0 XP), the indicator shows three empty bars.
- **Mixed party levels**: PCs at different levels each contribute their own budget — the system handles heterogeneous parties correctly.
- **Duplicate PC combatants**: If the same player character is added to the encounter multiple times, each copy contributes to the party budget independently (each counts as a party member).
- **CR fractions**: Bestiary creatures can have fractional CRs (e.g., "1/4", "1/2"). The CR-to-XP lookup must handle these string formats.
@@ -274,6 +326,14 @@ A game master who runs games using the 2014 (original 5e) rules selects "5e (201
- **2014 multiplier floor (×0.5)**: A single monster with 6+ PCs uses ×0.5 per the 2014 DMG party size adjustment rule.
- **2014 multiplier ceiling (×5)**: 15+ monsters with fewer than 3 PCs shifts ×4 upward to ×5 per the 2014 DMG party size adjustment rule.
- **Edition switch with breakdown panel open**: If the breakdown panel is open when the user switches editions in settings, the panel content updates to reflect the new edition's labels, thresholds, and (for 2014) the encounter multiplier.
- **PF2e creature level outside table range**: A creature more than 4 levels below the party contributes 0 XP (no row in the GM Core table — no meaningful threat). A creature more than 4 levels above the party contributes 160 XP (the +4 row).
- **PF2e party level derivation — tie in mode**: If two levels are equally common among PCs (e.g., two level 3 and two level 5), the party level is the average of all PC levels, rounded to the nearest integer.
- **PF2e party level — single PC**: With one PC, the party level equals that PC's level.
- **PF2e budget thresholds floored at 0**: If party size adjustment would reduce a threshold below 0, it is floored at 0.
- **PF2e no encounter multiplier**: Unlike D&D 5e (2014), PF2e never applies an encounter multiplier. Total creature XP is used directly.
- **PF2e creatures without level**: Custom combatants without `creatureId` (and thus no creature level) are excluded from PF2e XP calculation. Only bestiary-linked PF2e creatures with a level contribute.
- **PF2e 4-bar indicator in edition switch**: When switching from a D&D edition (3 bars) to PF2e (4 bars) or vice versa, the indicator bar count updates immediately along with the tier labels.
- **PF2e side assignment**: Side assignment (party/enemy) works identically to D&D — enemy-side creatures add XP, party-side creatures subtract XP. Net XP is floored at 0.
---
@@ -294,7 +354,12 @@ The system MUST calculate the party's XP budget by summing the per-character bud
The system MUST calculate the net monster XP by summing the XP value (derived from CR) for each enemy-side combatant that has a CR and subtracting the XP value for each party-side combatant that has a CR. For bestiary-linked combatants, CR is derived from the creature data via `creatureId`. For custom combatants, CR comes from the optional `cr` field. Combatants with neither `creatureId` nor `cr` are excluded. The net monster XP MUST be floored at 0.
#### FR-005 — Difficulty tier determination
The system MUST determine the encounter difficulty tier by comparing total monster XP (adjusted XP for 2014) against the party's thresholds. For 5.5e: Low, Moderate, and High (3 tiers). For 2014: Easy, Medium, Hard, and Deadly (4 tiers). The tier is the highest threshold that the total XP meets or exceeds. If below the lowest threshold, the encounter is trivial (5.5e) or easy (2014). The visual indicator maps identically across editions: 0 bars = Trivial/Easy, 1 green = Low/Medium, 2 yellow = Moderate/Hard, 3 red = High/Deadly.
The system MUST determine the encounter difficulty tier by comparing total monster XP (adjusted XP for 2014) against the party's thresholds. The comparison direction differs by edition, matching each DMG's rules:
- **2014 (Easy/Medium/Hard/Deadly)**: thresholds are floors — "the closest threshold that is lower than the adjusted XP value determines the encounter's difficulty" (2014 DMG). The tier is the highest threshold the adjusted XP meets or exceeds; below the Easy threshold the encounter is effectively trivial (0 bars).
- **5.5e (Low/Moderate/High)**: budgets are ceilings — "spend as much of your XP budget as you can without going over" (2024 DMG). The tier is the lowest budget the total XP does not exceed: XP within the Low budget is Low, over Low but within Moderate is Moderate, over Moderate is High. The High budget is display-only guidance; it does not gate the High tier. The 2024 rules define no tier below Low, so 0 bars appear only at 0 net XP.
The visual indicator maps identically across editions: 0 bars = 0 XP/Easy, 1 green = Low/Medium, 2 yellow = Moderate/Hard, 3 red = High/Deadly.
#### FR-006 — Difficulty indicator in top bar
The system MUST display a 3-bar difficulty indicator in the top bar, positioned to the right of the active combatant name.
@@ -321,7 +386,7 @@ The player character create and edit forms MUST include an optional level field
The player character level MUST be persisted and restored across sessions, consistent with existing player character persistence behavior.
#### FR-014 — High is the cap
When total monster XP exceeds the High threshold, the indicator MUST display the High state (three red bars). There is no tier above High.
When total monster XP exceeds the High budget, the indicator MUST display the High state (three red bars). There is no tier above High.
#### FR-015 — Optional CR and side fields on Combatant
The `Combatant` entity MUST support an optional `cr` field accepting standard 5e challenge rating strings ("0", "1/8", "1/4", "1/2", "1""30") and an optional `side` field accepting `"party"` or `"enemy"`.
@@ -377,6 +442,33 @@ Switching the rules edition in settings MUST immediately update the difficulty i
#### FR-032 — Settings label reflects broader scope
The settings modal section currently labeled "Conditions" MUST be relabeled to "Rules Edition" to reflect that the edition toggle controls both condition descriptions and difficulty calculation. This supersedes spec 003 FR-096 which scoped the label to conditions only.
#### FR-033 — PF2e creature level-to-XP table
The system MUST contain the PF2e creature level vs party level XP lookup table: level difference 4=10, 3=15, 2=20, 1=30, 0=40, +1=60, +2=80, +3=120, +4=160. Creatures more than 4 levels below the party have no row in the GM Core table and contribute 0 XP (no meaningful threat). Creatures more than 4 levels above the party are counted as the +4 row (160 XP).
#### FR-034 — PF2e budget thresholds
The system MUST contain the PF2e encounter budget thresholds for a party of 4: Trivial=40, Low=60, Moderate=80, Severe=120, Extreme=160.
#### FR-035 — PF2e party size budget adjustment
The system MUST adjust PF2e budget thresholds for party size using the GM Core (remaster) Character Adjustment values. For each PC beyond 4, add per-tier adjustments: Trivial +10, Low +20, Moderate +20, Severe +30, Extreme +40. For each PC fewer than 4, subtract the same amounts. Thresholds are floored at 0. (The pre-remaster Core Rulebook listed Low as 15; this spec follows the remaster.)
#### FR-036 — PF2e party level derivation
The system MUST derive the party level from PC combatant levels. The party level is the most common (mode) level among PCs with levels. If there is no unique mode (tie or all different), the party level is the average of all PC levels, rounded to the nearest integer.
#### FR-037 — PF2e XP calculation
The system MUST calculate PF2e encounter XP by summing per-creature XP for all enemy-side bestiary-linked creatures with a level, subtracting per-creature XP for party-side creatures with a level, and flooring the net at 0. No encounter multiplier is applied.
#### FR-038 — PF2e difficulty tier determination
The system MUST determine the PF2e difficulty tier by comparing total creature XP against the adjusted budget thresholds. The five tiers are Trivial, Low, Moderate, Severe, and Extreme. Budgets are ceilings (GM Core defines Trivial as "40 XP or less"): the tier is the lowest budget the total XP does not exceed — XP within the Trivial budget is Trivial, over Trivial but within Low is Low, and so on; XP over the Severe budget is Extreme. The Extreme budget is display-only guidance; it does not gate the Extreme tier.
#### FR-039 — PF2e 4-bar indicator
When the rules edition is PF2e, the difficulty indicator MUST display four bars instead of three. Visual states: 0 filled = Trivial, 1 green = Low, 2 yellow = Moderate, 3 orange = Severe, 4 red = Extreme.
#### FR-040 — PF2e breakdown panel content
When the rules edition is PF2e, the breakdown panel MUST show creature levels and level differences (not CR), per-creature XP based on level difference, the derived party level, and five threshold columns (Trivial/Low/Moderate/Severe/Extreme). Party size adjustments MUST be explained when active.
#### FR-041 — PF2e indicator visibility
When the rules edition is PF2e, the difficulty indicator MUST be shown when the encounter has at least one PC combatant with a level and at least one bestiary-linked creature with a level. CR is not relevant for PF2e visibility.
### Key Entities
- **XP Budget Table**: A lookup mapping character level (1-20) to three XP thresholds (Low, Moderate, High), sourced from the 2024 5.5e DMG.
@@ -388,6 +480,9 @@ The settings modal section currently labeled "Conditions" MUST be relabeled to "
- **Combatant.side**: An optional string field (`"party"` | `"enemy"`) on the existing `Combatant` entity. When undefined, defaults are resolved by the hook layer: PC combatants default to `"party"`, all others to `"enemy"`.
- **2014 XP Thresholds Table**: A lookup mapping character level (1-20) to four XP thresholds (Easy, Medium, Hard, Deadly), sourced from the 2014 DMG.
- **EncounterMultiplier**: A lookup mapping monster count ranges to base multiplier values (×1 through ×4), with party size adjustment shifting the multiplier up or down one step (full range ×0.5 through ×5).
- **PF2e Level Difference XP Table**: A lookup mapping creature level difference from party level (4 to +4) to XP values (10160).
- **PF2e Budget Thresholds**: Base thresholds for a party of 4: Trivial=40, Low=60, Moderate=80, Severe=120, Extreme=160, with per-tier adjustments for party size.
- **Party Level**: Derived value — the mode of PC levels, or the rounded average when no unique mode exists.
---
@@ -407,6 +502,7 @@ The settings modal section currently labeled "Conditions" MUST be relabeled to "
- **SC-010**: Party-side combatants with CR correctly subtract their XP from the monster total, and the net XP is never negative.
- **SC-011**: The 2014 difficulty calculation correctly applies encounter multipliers and party size adjustments per the 2014 DMG rules.
- **SC-012**: Switching rules edition immediately updates the indicator with no page reload required.
- **SC-013**: The PF2e difficulty calculation correctly derives party level, computes per-creature XP from level differences, adjusts budgets for party size, and assigns the correct tier for all combinations.
---
@@ -424,3 +520,8 @@ The settings modal section currently labeled "Conditions" MUST be relabeled to "
- The CR-to-XP lookup table is shared between both editions — only the budget thresholds and multiplier logic differ.
- MVP baseline does not include the 2014 Adventuring Day XP budget or multipart encounter rules.
- MVP baseline does not include per-combatant level overrides — level is always derived from the player character template.
- The PF2e level difference XP table and budget thresholds are static data that do not change at runtime.
- PF2e creatures always have a `level` field in their bestiary data (already present on `Pf2eCreature`).
- Custom combatants without `creatureId` cannot contribute to PF2e XP calculation — there is no manual "creature level" assignment equivalent to the manual CR picker. This may be addressed in a future issue.
- Level differences below 4 contribute 0 XP (strict reading of the GM Core table); above +4 they are counted as the +4 row (160 XP).
- PF2e does not use CR at all — the CR field on combatants is irrelevant when in PF2e mode.
-1
View File
@@ -3,7 +3,6 @@ import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
include: ["packages/*/src/**/*.test.ts", "apps/*/src/**/*.test.{ts,tsx}"],
passWithNoTests: true,
coverage: {
provider: "v8",
enabled: true,