Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c4fc8a88e | ||
|
|
dda8ed9790 | ||
|
|
15347bfdc8 | ||
|
|
0e7bc7c099 | ||
|
|
295c7e06b4 | ||
|
|
bca406fca9 | ||
|
|
8d71f0ba4b | ||
|
|
8ecd31d570 | ||
|
|
05e8c262b7 | ||
|
|
f5b387beb5 | ||
|
|
e8a0ba2b60 | ||
|
|
3b166403e8 | ||
|
|
6122c19cf1 | ||
|
|
83693d4aa9 | ||
|
|
09cf9291eb | ||
|
|
ea17c5e26e | ||
|
|
23aa99ba0a | ||
|
|
dc0a1f1633 | ||
|
|
119d252d02 | ||
|
|
30712f0e1e | ||
|
|
7d0ea883b0 | ||
|
|
5c062bf944 | ||
|
|
b5b339a5dd | ||
|
|
eef11c3b6e | ||
|
|
2c6dfdafc8 | ||
|
|
c05a283cf0 | ||
|
|
69ab0c35c0 | ||
|
|
91e23856b4 | ||
|
|
fd03ae48c8 | ||
|
|
96770099f6 | ||
|
|
ebd91ca42a | ||
|
|
41c1e48874 | ||
|
|
863e8b3719 | ||
|
|
4a92c667c5 | ||
|
|
6f11edab94 | ||
|
|
2dfa155469 | ||
|
|
0fa3928bf8 | ||
|
|
9870d4df0d | ||
|
|
43b1f6ce41 | ||
|
|
907484fc7f | ||
|
|
9dbbb88730 | ||
|
|
1078062b53 | ||
|
|
94126567e7 | ||
|
|
f3ed971592 | ||
|
|
95db6fdfdc | ||
|
|
a5b6d61e83 | ||
|
|
76f5dc09ab | ||
|
|
c2bb5cca29 | ||
|
|
7955bed4a9 | ||
|
|
66f3cc1380 | ||
|
|
19de9fcf75 | ||
|
|
c41a8aa994 | ||
|
|
02344eb3f5 | ||
|
|
e191aa5ad2 | ||
|
|
c544bc305a | ||
|
|
835a4663f7 | ||
|
|
995347d255 | ||
|
|
9159755846 | ||
|
|
dbe018825b | ||
|
|
3b75ec9b3d | ||
|
|
3646a9cf8e | ||
|
|
6991375afc | ||
|
|
77570097f8 | ||
|
|
8354d21fc6 |
No files matched your search
@@ -0,0 +1,335 @@
|
|||||||
|
---
|
||||||
|
name: ttrpg-encounter-builder
|
||||||
|
description: |
|
||||||
|
Seeds D&D encounter rosters into the TTRPG Initiative Tracker via its REST API
|
||||||
|
(no UI clicking). Use when the user asks to "set up encounters", "build
|
||||||
|
encounters", "add participants to a campaign", "seed this encounter list",
|
||||||
|
or provides a statblock list (name + HP + init) for a campaign running on a
|
||||||
|
self-hosted tracker instance running in SERVER MODE (bundled Express
|
||||||
|
backend). NOT for Firebase SDK mode — that has no HTTP backend; write path
|
||||||
|
differs entirely. Harness-agnostic: pi, Claude Code, and Codex all run the
|
||||||
|
same script + curl recipes.
|
||||||
|
---
|
||||||
|
|
||||||
|
# TTRPG Encounter Builder
|
||||||
|
|
||||||
|
Build encounter rosters directly via the tracker REST API. No UI clicking, no
|
||||||
|
browser automation. One batch write per session, then verify.
|
||||||
|
|
||||||
|
## When to use
|
||||||
|
|
||||||
|
User provides a campaign name + a list of encounters, each with named
|
||||||
|
participants carrying HP and initiative modifiers (or rolled initiative).
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- "set up these encounters in the 2026 D&D campaign on bee.icantclick.org:8080"
|
||||||
|
- "build encounter: Barrowdeep 1 - Ankheg HP 45 Init +0"
|
||||||
|
- "seed these statblocks into my tracker"
|
||||||
|
|
||||||
|
Do NOT use for: starting combat, rolling HP mid-fight, editing live combat
|
||||||
|
state, or driving the player display. Those are in-combat ops, not build ops.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- A running tracker instance in **SERVER MODE** (`REACT_APP_STORAGE=server`,
|
||||||
|
bundled Express backend mounted). Reachable over HTTP.
|
||||||
|
- **Firebase SDK mode NOT supported.** No `/api/*` endpoints exist; data
|
||||||
|
lives in Firestore via the in-browser SDK with different auth + write
|
||||||
|
paths. This skill cannot reach it. If the user is on firebase mode, tell
|
||||||
|
them: switch to server mode, or build encounters via the UI / a
|
||||||
|
firebase-admin script (out of scope here).
|
||||||
|
- Node.js 18+ (for `fetch` + `crypto.randomUUID`). Helper script uses only
|
||||||
|
builtins — no `npm install`.
|
||||||
|
- Campaign must already exist (created via UI or `POST /api/collection`).
|
||||||
|
This skill adds encounters to an existing campaign.
|
||||||
|
|
||||||
|
Confirm host reachable + server mode before building:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s <HOST>/api/collection?path=campaigns | head -c 200
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns JSON array of campaign docs = server mode confirmed. HTML (SPA shell)
|
||||||
|
= firebase mode OR backend not mounted. Either way, this skill won't work —
|
||||||
|
tell the user.
|
||||||
|
|
||||||
|
## Spec files
|
||||||
|
|
||||||
|
Spec files are EPHEMERAL. /tmp is fine — they get cleaned, that's expected.
|
||||||
|
|
||||||
|
- Source of truth for stats = the user's message at ask-time. Spec JSON is a
|
||||||
|
transit format, not an archive.
|
||||||
|
- If a spec is gone, rebuild it from the original message. Never reconstruct
|
||||||
|
from memory.
|
||||||
|
- **The durable record is the server DB.** Encounter docs are self-describing:
|
||||||
|
participant name, type, hpFormula, maxHp, ac, initiative, status all stored.
|
||||||
|
"Fix the thing from 2 weeks ago" → query `campaigns/{cid}/encounters`, read
|
||||||
|
the docs, reconstruct context from live data. `logs/{id}` entries add the
|
||||||
|
action history.
|
||||||
|
- Therefore: store enough in the DB to reconstruct later. hpFormula always
|
||||||
|
kept on monster/npc participants; never strip it. Never write campaign or
|
||||||
|
encounter data into the tracker repo.
|
||||||
|
|
||||||
|
## Spec vetting (before build)
|
||||||
|
|
||||||
|
Validate the spec before writing anything. Reject, don't guess:
|
||||||
|
|
||||||
|
- **Monster/npc with neither `maxHp` nor `hpFormula`** → hard error. A silent
|
||||||
|
default of 10 HP has caused real damage; never fall back to defaults.
|
||||||
|
Escape hatch: `--allow-defaults` flag permits it with a loud warning.
|
||||||
|
- **Missing `ac`** → warning (build continues).
|
||||||
|
- **Missing `initMod` and `initiative`** → warning; initMod defaults 0.
|
||||||
|
- **`type: "character"` in spec** → see PC rules below.
|
||||||
|
- **Duplicate participant names within one encounter** → allowed but warn
|
||||||
|
(numbered names preferred for display clarity).
|
||||||
|
|
||||||
|
## PC rules (hard)
|
||||||
|
|
||||||
|
- **Allowed:** add a PC to the campaign roster (`players[]`), or add a PC
|
||||||
|
from the roster into an encounter, copying stats verbatim from the roster.
|
||||||
|
- **Forbidden:** creating a `character` participant with invented stats, or
|
||||||
|
editing any existing character-type participant's HP, AC, formula,
|
||||||
|
conditions, or status. Player stat fixes happen in the UI or from the
|
||||||
|
user's explicit values — tooling never "repairs" PCs.
|
||||||
|
- A build spec containing `type: "character"` without `originalCharacterId`
|
||||||
|
resolving to a roster entry → hard error.
|
||||||
|
|
||||||
|
## Data model (read this before writing)
|
||||||
|
|
||||||
|
Three nested entities, all opaque JSON docs in a path-keyed KV store:
|
||||||
|
|
||||||
|
```
|
||||||
|
Campaign campaigns/{campaignId}
|
||||||
|
└─ Encounter campaigns/{campaignId}/encounters/{encounterId}
|
||||||
|
└─ Participant (inline array item on the encounter doc)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Participants are inline.** There is NO `participants` sub-collection. A
|
||||||
|
`participants` path returns empty. Each encounter doc carries its full roster
|
||||||
|
in a `participants[]` array.
|
||||||
|
|
||||||
|
### Path normalization (gotcha)
|
||||||
|
|
||||||
|
App code uses firebase-prefixed paths (`artifacts/{APP_ID}/public/data/campaigns/...`).
|
||||||
|
The REST API uses **bare canonical** paths (`campaigns/...`). The adapter
|
||||||
|
strips the prefix server-side.
|
||||||
|
|
||||||
|
- REST / scripts / direct DB → bare: `campaigns/{cid}/encounters/{eid}`
|
||||||
|
- If `GET /api/collection?path=artifacts/.../campaigns` returns `[]`, you used
|
||||||
|
the prefixed form. Drop the prefix.
|
||||||
|
|
||||||
|
### Encounter doc shape
|
||||||
|
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
name: 'Barrowdeep 1 - Antechamber',
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
participants: [], // inline roster
|
||||||
|
round: 0,
|
||||||
|
currentTurnParticipantId: null,
|
||||||
|
isStarted: false,
|
||||||
|
isPaused: false,
|
||||||
|
ruleset: '5e',
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Build encounters with `round: 0`, `isStarted: false`. Starting combat is a
|
||||||
|
separate in-combat op (UI Start button or a later skill).
|
||||||
|
|
||||||
|
### Participant object shape
|
||||||
|
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
id: <uuid>, // crypto.randomUUID(), client-generated
|
||||||
|
name: 'Ankheg',
|
||||||
|
type: 'monster', // 'monster' | 'npc' | 'character'
|
||||||
|
originalCharacterId: null, // set only if type === 'character'
|
||||||
|
initiative: <int>, // rolled ONCE at add; stored, not re-derived
|
||||||
|
maxHp: 45,
|
||||||
|
currentHp: 45, // start at full
|
||||||
|
conditions: [],
|
||||||
|
isActive: true,
|
||||||
|
status: 'conscious',
|
||||||
|
deathSaveSuccesses: 0, // character/npc only
|
||||||
|
deathSaveFailures: 0, // character/npc only
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### type field
|
||||||
|
|
||||||
|
- `monster` — DM-controlled, dead at 0 HP (auto-inactive). Default.
|
||||||
|
- `npc` — DM-controlled but keeps death saves (revivable). Use for named
|
||||||
|
allies/villains the DM runs.
|
||||||
|
- `character` — player character. Requires `originalCharacterId` linking to a
|
||||||
|
campaign roster entry. For build-from-statblock, use `monster` or `npc`,
|
||||||
|
not `character`.
|
||||||
|
|
||||||
|
### Initiative semantics
|
||||||
|
|
||||||
|
- Default: `initiative = rollD20() + initMod` (d20 ∈ [1,20], rolled fresh per
|
||||||
|
participant).
|
||||||
|
- Manual override: set `initiative` directly (pre-rolled values), skip the
|
||||||
|
roll. `initMod` is NOT stored on the participant — only the final
|
||||||
|
`initiative` value persists.
|
||||||
|
- Fixed at add time. Never re-derived after.
|
||||||
|
|
||||||
|
### id format
|
||||||
|
|
||||||
|
`generateId()` = `crypto.randomUUID()` (fallback `id_{Date.now()}_{rand10}`).
|
||||||
|
Generate participant ids client-side so they're stable across batch writes.
|
||||||
|
Server `POST /api/collection` auto-generates a UUID for the doc id — fine for
|
||||||
|
campaigns/encounters, but for inline participants you generate them yourself.
|
||||||
|
|
||||||
|
## REST endpoints
|
||||||
|
|
||||||
|
All paths bare canonical.
|
||||||
|
|
||||||
|
| Method | Path | Body / Query | Action |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `GET` | `/api/doc` | `?path=` | read one doc |
|
||||||
|
| `PUT` | `/api/doc` | `{path, data}` | replace doc |
|
||||||
|
| `PATCH` | `/api/doc` | `{path, patch}` | shallow merge, create-on-miss |
|
||||||
|
| `DELETE` | `/api/doc` | `?path=` | delete one doc |
|
||||||
|
| `GET` | `/api/collection` | `?path=` | list docs under collection |
|
||||||
|
| `POST` | `/api/collection` | `{path, data}` | addDoc: auto-id under collection |
|
||||||
|
| `POST` | `/api/batch` | `{ops:[{type, path, data?}]}` | atomic multi-write |
|
||||||
|
|
||||||
|
`POST /api/batch` is the workhorse for seeding. One batch, all encounters,
|
||||||
|
atomic.
|
||||||
|
|
||||||
|
## Build flow
|
||||||
|
|
||||||
|
### 1. Parse the user's request
|
||||||
|
|
||||||
|
Extract:
|
||||||
|
- **Host** — the running tracker URL (e.g. `http://bee.icantclick.org:8080`).
|
||||||
|
If omitted, ask. Do not guess.
|
||||||
|
- **Campaign name** — must match an existing campaign doc's `name` field.
|
||||||
|
- **Encounters** — list of `{name, participants:[{name, type?, maxHp, initMod?|initiative?}]}`.
|
||||||
|
|
||||||
|
A statblock line like `Ankheg - HP 45 - Init +0` parses to:
|
||||||
|
`{name:"Ankheg", type:"monster", maxHp:45, initMod:0}`.
|
||||||
|
|
||||||
|
### 2. Resolve the campaign id
|
||||||
|
|
||||||
|
Campaigns are keyed by id, not name. Look up by name:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s "<HOST>/api/collection?path=campaigns" \
|
||||||
|
| jq -r '.[] | select(.name=="<CAMPAIGN NAME>") | .id'
|
||||||
|
```
|
||||||
|
|
||||||
|
Exactly one match expected. Zero → campaign doesn't exist (tell user to create
|
||||||
|
it first). Multiple → ambiguous name, ask user which id.
|
||||||
|
|
||||||
|
### 3. Write encounters (two options)
|
||||||
|
|
||||||
|
#### Option A — helper script (recommended)
|
||||||
|
|
||||||
|
`scripts/build-encounters.js` handles id gen, initiative rolling, batch write,
|
||||||
|
and verification. Reads a spec file or stdin.
|
||||||
|
|
||||||
|
Spec format (JSON array):
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"name": "Optional Road/Trail Ankheg",
|
||||||
|
"participants": [
|
||||||
|
{ "name": "Ankheg", "type": "monster", "maxHp": 45, "initMod": 0 }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Barrowdeep 2 - Minor Burial Chamber",
|
||||||
|
"participants": [
|
||||||
|
{ "name": "Cult Fanatic", "type": "monster", "maxHp": 39, "initMod": 2 },
|
||||||
|
{ "name": "Cultist 1", "type": "monster", "maxHp": 9, "initMod": 2 },
|
||||||
|
{ "name": "Cultist 2", "type": "monster", "maxHp": 9, "initMod": 2 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
Run (resolve script path relative to this skill dir):
|
||||||
|
```bash
|
||||||
|
node scripts/build-encounters.js <HOST> "<CAMPAIGN NAME>" spec.json
|
||||||
|
# or stdin:
|
||||||
|
cat spec.json | node scripts/build-encounters.js <HOST> "<CAMPAIGN NAME>" -
|
||||||
|
```
|
||||||
|
|
||||||
|
Script prints each encounter id + participant init rolls, then verifies.
|
||||||
|
|
||||||
|
#### Option B — raw curl (any harness, no node)
|
||||||
|
|
||||||
|
Build the batch payload inline. Generate UUIDs and roll initiative yourself.
|
||||||
|
One `POST /api/batch` writes everything:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s -X POST "<HOST>/api/batch" \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{
|
||||||
|
"ops": [
|
||||||
|
{
|
||||||
|
"type": "set",
|
||||||
|
"path": "campaigns/CID/encounters/EID1",
|
||||||
|
"data": {
|
||||||
|
"name": "Optional Road/Trail Ankheg",
|
||||||
|
"createdAt": "2026-07-07T00:00:00.000Z",
|
||||||
|
"participants": [
|
||||||
|
{ "id": "UUID1", "name": "Ankheg", "type": "monster", "originalCharacterId": null, "initiative": 15, "maxHp": 45, "currentHp": 45, "conditions": [], "isActive": true, "status": "conscious", "deathSaveSuccesses": 0, "deathSaveFailures": 0 }
|
||||||
|
],
|
||||||
|
"round": 0, "currentTurnParticipantId": null, "isStarted": false, "isPaused": false, "ruleset": "5e"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Response: `{"ok":true}`. If you get an error, check path is bare (no
|
||||||
|
`artifacts/` prefix) and JSON is valid.
|
||||||
|
|
||||||
|
### 4. Verify
|
||||||
|
|
||||||
|
Always verify after write. Don't trust the batch `ok` alone.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s "<HOST>/api/collection?path=campaigns/CID/encounters" \
|
||||||
|
| jq '.[] | {name, participants: (.participants|length), started: .isStarted}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Expect one object per encounter with correct participant count and
|
||||||
|
`started: false`.
|
||||||
|
|
||||||
|
### 5. Report back to user
|
||||||
|
|
||||||
|
Tell the user:
|
||||||
|
- Host + campaign name resolved
|
||||||
|
- Per encounter: name, id, participant count, rolled initiatives
|
||||||
|
- Verification result (counts matched)
|
||||||
|
- That combat is NOT started (encounters sit at `round: 0, isStarted: false`).
|
||||||
|
User starts combat via the UI Start button when ready.
|
||||||
|
|
||||||
|
## Common mistakes
|
||||||
|
|
||||||
|
| Symptom | Cause | Fix |
|
||||||
|
|---|---|---|
|
||||||
|
| `GET /api/collection?path=artifacts/.../campaigns` returns `[]` | used firebase-prefixed path | drop `artifacts/{APP_ID}/public/data/` prefix, use bare `campaigns` |
|
||||||
|
| `GET /health` or collection returns HTML (SPA shell) | server in firebase mode, or backend not mounted | confirm `REACT_APP_STORAGE=server` + backend running on the instance |
|
||||||
|
| Batch returns `ok` but encounter missing | wrong campaign id, or path typo | re-resolve campaign id by name; check path segments |
|
||||||
|
| Participant count mismatch on verify | participant objects malformed / dropped in JSON | validate each has all required fields; use script to avoid hand-JSON errors |
|
||||||
|
| Initiative looks wrong | forgot `initiative` is stored value, not re-derived | roll `d20 + initMod` once at build, store the int. No `initMod` field on participant. |
|
||||||
|
| Duplicate cultist names across encounters | fine — names need only be unique WITHIN an encounter, not across | no fix needed |
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- Creating campaigns (use UI or `POST /api/collection` with a campaign doc)
|
||||||
|
- Starting combat / advancing turns / HP damage / death saves (in-combat ops)
|
||||||
|
- Player display control (`activeDisplay/status`)
|
||||||
|
- Firebase SDK mode (this skill is server-mode REST only)
|
||||||
|
- Campaign roster characters (`players[]` on campaign doc) — those are
|
||||||
|
templates; this skill adds inline combatants, not roster entries
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
Full entity model, combat flow, and storage paths: `docs/ENCOUNTER_BUILDER.md`
|
||||||
|
in the repo root. REST + DB internals: `docs/DEVELOPMENT.md` and
|
||||||
|
`server/index.js`.
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
// build-encounters.js — seed TTRPG encounters via REST API.
|
||||||
|
// Cross-harness: pi, claude, codex all call same script.
|
||||||
|
// No deps beyond node builtins. Reads spec JSON, writes batch, verifies.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
// node build-encounters.js <host> <campaignName> <specFile>
|
||||||
|
// cat spec.json | node build-encounters.js <host> <campaignName> -
|
||||||
|
//
|
||||||
|
// specFile = JSON array of encounters:
|
||||||
|
// [
|
||||||
|
// {
|
||||||
|
// "name": "Barrowdeep 1 - Antechamber",
|
||||||
|
// "participants": [
|
||||||
|
// { "name": "Ankheg", "type": "monster", "maxHp": 45, "initMod": 0 },
|
||||||
|
// { "name": "Boss", "type": "npc", "maxHp": 39, "initMod": 2, "initiative": 15 }
|
||||||
|
// ]
|
||||||
|
// }
|
||||||
|
// ]
|
||||||
|
//
|
||||||
|
// type: 'monster' | 'npc' | 'character'. Default 'monster'.
|
||||||
|
// initiative: optional manual override. If omitted, rolled d20 + initMod.
|
||||||
|
// initMod default 0. maxHp default 10.
|
||||||
|
//
|
||||||
|
// VALIDATION (hard rules):
|
||||||
|
// - monster/npc with neither maxHp nor hpFormula = FATAL. Defaults caused real
|
||||||
|
// damage once; never silently assume 10 HP. --allow-defaults to override.
|
||||||
|
// - character type in spec = FATAL unless --allow-pc-add, which requires
|
||||||
|
// originalCharacterId + copies stats from the campaign roster verbatim.
|
||||||
|
// - missing ac or initMod = warning, build continues.
|
||||||
|
//
|
||||||
|
// Output: written encounter ids + rolled initiatives. Exit 0 on success.
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const argv = process.argv.slice(2);
|
||||||
|
const FLAGS = new Set(argv.filter(a => a.startsWith('--')));
|
||||||
|
const ARGS = argv.filter(a => !a.startsWith('--'));
|
||||||
|
const warn = (msg) => console.error(`WARN: ${msg}`);
|
||||||
|
|
||||||
|
const genId = () =>
|
||||||
|
(typeof crypto !== 'undefined' && crypto.randomUUID)
|
||||||
|
? crypto.randomUUID()
|
||||||
|
: `id_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const rollD20 = () => Math.floor(Math.random() * 20) + 1;
|
||||||
|
|
||||||
|
function makeParticipant(spec) {
|
||||||
|
const type = spec.type || 'monster';
|
||||||
|
const maxHp = spec.maxHp || 10;
|
||||||
|
const initMod = spec.initMod || 0;
|
||||||
|
const manual = spec.initiative !== undefined && spec.initiative !== null;
|
||||||
|
return {
|
||||||
|
id: genId(),
|
||||||
|
name: spec.name,
|
||||||
|
type,
|
||||||
|
originalCharacterId: spec.originalCharacterId || null,
|
||||||
|
initiative: manual ? Number(spec.initiative) : rollD20() + initMod,
|
||||||
|
maxHp,
|
||||||
|
currentHp: maxHp,
|
||||||
|
conditions: [],
|
||||||
|
isActive: true,
|
||||||
|
status: 'conscious',
|
||||||
|
deathSaveSuccesses: 0,
|
||||||
|
deathSaveFailures: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getJson(url) {
|
||||||
|
const r = await fetch(url);
|
||||||
|
if (!r.ok) throw new Error(`GET ${url} -> ${r.status}: ${await r.text()}`);
|
||||||
|
return r.json();
|
||||||
|
}
|
||||||
|
async function postJson(url, body) {
|
||||||
|
const r = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
if (!r.ok) throw new Error(`POST ${url} -> ${r.status}: ${await r.text()}`);
|
||||||
|
return r.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findCampaignId(host, name) {
|
||||||
|
const list = await getJson(`${host}/api/collection?path=campaigns`);
|
||||||
|
const matches = list.filter(c => c.name === name);
|
||||||
|
if (matches.length === 0) {
|
||||||
|
console.error(`No campaign named "${name}". Existing:`);
|
||||||
|
list.forEach(c => console.error(` ${c.name}`));
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
if (matches.length > 1) {
|
||||||
|
console.error(`Multiple campaigns named "${name}". Use unique name or pass id.`);
|
||||||
|
matches.forEach(c => console.error(` ${c.id} ${c.name}`));
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
return matches[0].id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vetting. Returns {ok, errors[], warnings[]}. Never silent about missing data.
|
||||||
|
function vetSpec(encounters) {
|
||||||
|
const errors = [];
|
||||||
|
const warnings = [];
|
||||||
|
encounters.forEach((enc, ei) => {
|
||||||
|
const seen = new Set();
|
||||||
|
for (const p of enc.participants || []) {
|
||||||
|
const where = `encounter "${enc.name}", participant "${p.name}"`;
|
||||||
|
const type = p.type || 'monster';
|
||||||
|
const hasHp = p.maxHp !== undefined && p.maxHp !== null;
|
||||||
|
const hasFormula = typeof p.hpFormula === 'string' && p.hpFormula.trim();
|
||||||
|
if (type === 'character') {
|
||||||
|
errors.push(`${where}: character type not allowed in build spec (PC stats come from roster, via UI or explicit user values)`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!hasHp && !hasFormula) {
|
||||||
|
if (FLAGS.has('--allow-defaults')) {
|
||||||
|
warnings.push(`${where}: no maxHp/hpFormula — defaulting to 10 (--allow-defaults)`);
|
||||||
|
} else {
|
||||||
|
errors.push(`${where}: no maxHp and no hpFormula. Refusing to guess HP. Add the stat from the source or pass --allow-defaults.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (p.ac === undefined || p.ac === null) warnings.push(`${where}: no ac`);
|
||||||
|
if (p.initMod === undefined && p.initiative === undefined) warnings.push(`${where}: no initMod/initiative (defaulting mod 0)`);
|
||||||
|
if (seen.has(p.name)) warnings.push(`${where}: duplicate name in encounter (number them for display clarity)`);
|
||||||
|
seen.add(p.name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { ok: errors.length === 0, errors, warnings };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const [host, campaignName, specArg] = ARGS;
|
||||||
|
if (!host || !campaignName || !specArg) {
|
||||||
|
console.error('Usage: node build-encounters.js <host> <campaignName> <specFile|-> [--allow-defaults]');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const specRaw = specArg === '-'
|
||||||
|
? require('fs').readFileSync(0, 'utf8')
|
||||||
|
: require('fs').readFileSync(specArg, 'utf8');
|
||||||
|
const encounters = JSON.parse(specRaw);
|
||||||
|
if (!Array.isArray(encounters)) throw new Error('spec must be a JSON array of encounters');
|
||||||
|
|
||||||
|
const vet = vetSpec(encounters);
|
||||||
|
vet.warnings.forEach(warn);
|
||||||
|
if (!vet.ok) {
|
||||||
|
console.error('SPEC REJECTED:');
|
||||||
|
vet.errors.forEach(e => console.error(` - ${e}`));
|
||||||
|
process.exit(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cid = await findCampaignId(host, campaignName);
|
||||||
|
console.log(`campaign: "${campaignName}" -> ${cid}`);
|
||||||
|
|
||||||
|
const encPath = `campaigns/${cid}/encounters`;
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const ops = [];
|
||||||
|
const summary = [];
|
||||||
|
for (const enc of encounters) {
|
||||||
|
const id = genId();
|
||||||
|
const path = `${encPath}/${id}`;
|
||||||
|
const parts = (enc.participants || []).map(makeParticipant);
|
||||||
|
ops.push({
|
||||||
|
type: 'set',
|
||||||
|
path,
|
||||||
|
data: {
|
||||||
|
name: enc.name,
|
||||||
|
createdAt: now,
|
||||||
|
participants: parts,
|
||||||
|
round: 0,
|
||||||
|
currentTurnParticipantId: null,
|
||||||
|
isStarted: false,
|
||||||
|
isPaused: false,
|
||||||
|
ruleset: enc.ruleset || '5e',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
summary.push({ name: enc.name, id, parts });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await postJson(`${host}/api/batch`, { ops });
|
||||||
|
if (!res.ok) throw new Error(`batch failed: ${JSON.stringify(res)}`);
|
||||||
|
console.log(`batch: ${ops.length} encounter(s) written\n`);
|
||||||
|
|
||||||
|
// Verify
|
||||||
|
const written = await getJson(`${host}/api/collection?path=${encPath}`);
|
||||||
|
const byId = new Map(written.map(e => [e.id, e]));
|
||||||
|
|
||||||
|
for (const s of summary) {
|
||||||
|
const got = byId.get(s.id);
|
||||||
|
const ok = got && got.name === s.name && (got.participants || []).length === s.parts.length;
|
||||||
|
console.log(`${ok ? '✓' : '✗'} ${s.name}`);
|
||||||
|
console.log(` id: ${s.id}`);
|
||||||
|
if (!ok) { console.log(` VERIFY FAILED: got ${JSON.stringify(got && { name: got.name, n: (got.participants || []).length })}`); continue; }
|
||||||
|
s.parts.forEach(p => {
|
||||||
|
const i = p.initiative >= 0 ? `+${p.initiative}` : `${p.initiative}`;
|
||||||
|
console.log(` - ${p.name} (${p.type}, hp ${p.maxHp}, init ${i})`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log('\nDone.');
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch(e => { console.error('FAIL:', e.message); process.exit(1); });
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
TODO.md
|
||||||
|
node_modules
|
||||||
|
**/node_modules
|
||||||
|
.git
|
||||||
|
tmp
|
||||||
|
data
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
.DS_Store
|
||||||
|
coverage
|
||||||
|
.nyc_output
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
# Dockerfile
|
# Dockerfile
|
||||||
|
|
||||||
# Stage 1: Build the React application
|
# Stage 1: Build the React application
|
||||||
FROM node:18-alpine AS build
|
FROM node:22-alpine AS build
|
||||||
|
|
||||||
LABEL stage="build-local-testing"
|
LABEL stage="build-local-testing"
|
||||||
|
|
||||||
|
|||||||
Vendored
+172
@@ -0,0 +1,172 @@
|
|||||||
|
// Jenkinsfile — build + publish both images to the thinkserver:5000 registry.
|
||||||
|
//
|
||||||
|
// ttrpg-tracker-firebase : root Dockerfile, nginx serving the static SPA,
|
||||||
|
// Firebase storage (config baked in at build time).
|
||||||
|
// ttrpg-tracker-sqlite : docker/Dockerfile, Caddy + Node, server/SQLite
|
||||||
|
// storage (REACT_APP_STORAGE=server).
|
||||||
|
//
|
||||||
|
// Requirements on the Jenkins agent:
|
||||||
|
// * Docker CLI available, agent user in the docker group (or DooD socket).
|
||||||
|
// * thinkserver:5000 reachable and trusted by the Docker daemon. If it is a
|
||||||
|
// plain-HTTP registry, add it to /etc/docker/daemon.json on the AGENT host:
|
||||||
|
// { "insecure-registries": ["thinkserver:5000"] } (then restart docker)
|
||||||
|
//
|
||||||
|
// Jenkins credentials this pipeline expects:
|
||||||
|
// * ttrpg-firebase-env-local (Secret file) — the .env.local contents with
|
||||||
|
// REACT_APP_FIREBASE_* values. Baked into the firebase image at build time.
|
||||||
|
// * thinkserver-registry (Username/pw) — OPTIONAL. Only needed if the
|
||||||
|
// registry requires auth; the login stage is guarded below.
|
||||||
|
|
||||||
|
pipeline {
|
||||||
|
agent any
|
||||||
|
|
||||||
|
options {
|
||||||
|
timestamps()
|
||||||
|
disableConcurrentBuilds()
|
||||||
|
timeout(time: 30, unit: 'MINUTES')
|
||||||
|
}
|
||||||
|
|
||||||
|
parameters {
|
||||||
|
string(name: 'TRACKER_APP_ID',
|
||||||
|
defaultValue: 'ttrpg-initiative-tracker-default',
|
||||||
|
description: 'Firestore/app namespace baked into the SQLite image (REACT_APP_TRACKER_APP_ID).')
|
||||||
|
booleanParam(name: 'PUSH_LATEST', defaultValue: true,
|
||||||
|
description: 'Also tag and push :latest in addition to the commit-SHA tag.')
|
||||||
|
booleanParam(name: 'REGISTRY_AUTH', defaultValue: false,
|
||||||
|
description: 'Enable docker login using the thinkserver-registry credential.')
|
||||||
|
booleanParam(name: 'REDEPLOY_PORTAINER', defaultValue: true,
|
||||||
|
description: 'After pushing, POST to the Portainer stack webhooks to re-pull and redeploy.')
|
||||||
|
}
|
||||||
|
|
||||||
|
environment {
|
||||||
|
REGISTRY = 'thinkserver:5000'
|
||||||
|
FIREBASE_IMAGE = "${REGISTRY}/ttrpg-tracker-firebase"
|
||||||
|
SQLITE_IMAGE = "${REGISTRY}/ttrpg-tracker-sqlite"
|
||||||
|
DOCKER_BUILDKIT = '1'
|
||||||
|
}
|
||||||
|
|
||||||
|
stages {
|
||||||
|
stage('Checkout') {
|
||||||
|
steps {
|
||||||
|
checkout scm
|
||||||
|
script {
|
||||||
|
env.SHORT_SHA = sh(returnStdout: true, script: 'git rev-parse --short=8 HEAD').trim()
|
||||||
|
// Only build/push on main. BRANCH_NAME is set by Multibranch jobs; it
|
||||||
|
// is unset in a plain "Pipeline from SCM" job, which already only ever
|
||||||
|
// checks out main, so treat unset as main too.
|
||||||
|
env.IS_MAIN = (env.BRANCH_NAME == null || env.BRANCH_NAME == 'main').toString()
|
||||||
|
if (env.IS_MAIN != 'true') {
|
||||||
|
echo "Branch '${env.BRANCH_NAME}' is not main — skipping image build/push."
|
||||||
|
} else {
|
||||||
|
echo "Building tag ${env.SHORT_SHA} (build #${env.BUILD_NUMBER})"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Registry login') {
|
||||||
|
when { allOf { expression { env.IS_MAIN == 'true' }; expression { return params.REGISTRY_AUTH } } }
|
||||||
|
steps {
|
||||||
|
withCredentials([usernamePassword(credentialsId: 'thinkserver-registry',
|
||||||
|
usernameVariable: 'REG_USER',
|
||||||
|
passwordVariable: 'REG_PASS')]) {
|
||||||
|
sh 'echo "$REG_PASS" | docker login "$REGISTRY" -u "$REG_USER" --password-stdin'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Build firebase image') {
|
||||||
|
when { expression { env.IS_MAIN == 'true' } }
|
||||||
|
steps {
|
||||||
|
// Firebase config is compiled into the static bundle, so it must exist
|
||||||
|
// at build time. Inject .env.local from the Jenkins secret file, then
|
||||||
|
// the root Dockerfile's `COPY .env.local .env` picks it up.
|
||||||
|
withCredentials([file(credentialsId: 'ttrpg-firebase-env-local', variable: 'FIREBASE_ENV')]) {
|
||||||
|
sh '''
|
||||||
|
cp "$FIREBASE_ENV" .env.local
|
||||||
|
docker build \
|
||||||
|
-f Dockerfile \
|
||||||
|
-t "$FIREBASE_IMAGE:$SHORT_SHA" \
|
||||||
|
.
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Build sqlite image') {
|
||||||
|
when { expression { env.IS_MAIN == 'true' } }
|
||||||
|
steps {
|
||||||
|
// Server/SQLite build. BuildKit is required (syntax directive + cache
|
||||||
|
// mount in docker/Dockerfile). Context is the repo root.
|
||||||
|
sh '''
|
||||||
|
docker build \
|
||||||
|
-f docker/Dockerfile \
|
||||||
|
--build-arg REACT_APP_TRACKER_APP_ID="$TRACKER_APP_ID" \
|
||||||
|
-t "$SQLITE_IMAGE:$SHORT_SHA" \
|
||||||
|
.
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Tag latest') {
|
||||||
|
when { allOf { expression { env.IS_MAIN == 'true' }; expression { return params.PUSH_LATEST } } }
|
||||||
|
steps {
|
||||||
|
sh '''
|
||||||
|
docker tag "$FIREBASE_IMAGE:$SHORT_SHA" "$FIREBASE_IMAGE:latest"
|
||||||
|
docker tag "$SQLITE_IMAGE:$SHORT_SHA" "$SQLITE_IMAGE:latest"
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Push') {
|
||||||
|
when { expression { env.IS_MAIN == 'true' } }
|
||||||
|
steps {
|
||||||
|
sh '''
|
||||||
|
docker push "$FIREBASE_IMAGE:$SHORT_SHA"
|
||||||
|
docker push "$SQLITE_IMAGE:$SHORT_SHA"
|
||||||
|
'''
|
||||||
|
script {
|
||||||
|
if (params.PUSH_LATEST) {
|
||||||
|
sh '''
|
||||||
|
docker push "$FIREBASE_IMAGE:latest"
|
||||||
|
docker push "$SQLITE_IMAGE:latest"
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Redeploy (Portainer webhooks)') {
|
||||||
|
when { allOf { expression { env.IS_MAIN == 'true' }; expression { return params.REDEPLOY_PORTAINER } } }
|
||||||
|
steps {
|
||||||
|
// Webhook URLs are Secret-text credentials, so they never appear in the
|
||||||
|
// repo and Jenkins masks them in the console. They are bound to shell
|
||||||
|
// env vars and referenced inside a single-quoted sh block, so Groovy
|
||||||
|
// never interpolates the value into the pipeline log.
|
||||||
|
withCredentials([
|
||||||
|
string(credentialsId: 'portainer-webhook-firebase', variable: 'WEBHOOK_FIREBASE'),
|
||||||
|
string(credentialsId: 'portainer-webhook-sqlite', variable: 'WEBHOOK_SQLITE'),
|
||||||
|
]) {
|
||||||
|
sh '''
|
||||||
|
set +x
|
||||||
|
echo "Triggering Portainer redeploy (firebase stack)"
|
||||||
|
curl -fsS -X POST --retry 3 --retry-delay 5 "$WEBHOOK_FIREBASE"
|
||||||
|
echo "Triggering Portainer redeploy (sqlite stack)"
|
||||||
|
curl -fsS -X POST --retry 3 --retry-delay 5 "$WEBHOOK_SQLITE"
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
post {
|
||||||
|
always {
|
||||||
|
// Never leave Firebase secrets in the workspace or log out cleanly.
|
||||||
|
sh 'rm -f .env.local || true'
|
||||||
|
sh 'docker logout "$REGISTRY" || true'
|
||||||
|
}
|
||||||
|
success {
|
||||||
|
echo "Pushed ${FIREBASE_IMAGE}:${SHORT_SHA} and ${SQLITE_IMAGE}:${SHORT_SHA}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -307,6 +307,26 @@ ttrpg-initiative-tracker/
|
|||||||
* `docs/GLOSSARY.md` — domain terms (turn vs. round, etc.)
|
* `docs/GLOSSARY.md` — domain terms (turn vs. round, etc.)
|
||||||
* `TODO.md` — known bugs and backlog
|
* `TODO.md` — known bugs and backlog
|
||||||
|
|
||||||
|
## Prevent Sleep (Wake Lock)
|
||||||
|
|
||||||
|
DM and Player views have a Coffee/Moon toggle to keep screen awake during combat.
|
||||||
|
|
||||||
|
**Requires secure context** (HTTPS or localhost). The Screen Wake Lock API refuses
|
||||||
|
on plain HTTP.
|
||||||
|
|
||||||
|
- **Prod (HTTPS):** works automatically on all devices.
|
||||||
|
- **Local dev (localhost):** works automatically — localhost is a trusted origin.
|
||||||
|
- **LAN IP (phones, plain HTTP):** wake lock fails silently. Two options:
|
||||||
|
1. **Android Chrome flag (dev testing):** `chrome://flags/#unsafely-treat-insecure-origin-as-secure` → add full URL with port, e.g. `http://10.0.0.5:3999`. Enable flag, relaunch.
|
||||||
|
2. **mkcert local CA:** generate trusted cert for LAN IP. Heavier setup.
|
||||||
|
|
||||||
|
**iOS Safari:** Wake Lock API broken in standalone PWA mode (iOS 16.4–18.4, WebKit bug 254545). Fixed in 18.4+. Works in browser tab (not installed PWA).
|
||||||
|
|
||||||
|
**Troubleshooting:** if toggle shows active but screen still sleeps, check:
|
||||||
|
- Battery saver / power save mode (browser refuses)
|
||||||
|
- Chrome devtools console for `WakeLockError`
|
||||||
|
- Secure context: `window.isSecureContext` must be `true`
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
If you want to contribute, send me a message here: [https://discourse.draft13.com/c/ttrpg-initiative-tracker/16](https://discourse.draft13.com/c/ttrpg-initiative-tracker/16), and I can add to this Gitea instance and you can feel free to fork the repository and submit pull requests. For major changes, please pose a topic to the Discourse instance above linked above first to discuss what you would like to change.
|
If you want to contribute, send me a message here: [https://discourse.draft13.com/c/ttrpg-initiative-tracker/16](https://discourse.draft13.com/c/ttrpg-initiative-tracker/16), and I can add to this Gitea instance and you can feel free to fork the repository and submit pull requests. For major changes, please pose a topic to the Discourse instance above linked above first to discuss what you would like to change.
|
||||||
@@ -2,23 +2,83 @@
|
|||||||
|
|
||||||
Backlog of bugs + long-term items. Milestones live in REWORK_PLAN.md.
|
Backlog of bugs + long-term items. Milestones live in REWORK_PLAN.md.
|
||||||
|
|
||||||
|
|
||||||
## Open
|
## Open
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### dm list - keep active particpant in view (scroll)
|
|
||||||
not sure good way to do this
|
merge from one encoutner into another? option roll init for merged or use init
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### FEAT: player display fade transitions for inactive state
|
x init tracker - turned for 10 rounds... and maybe other stuff like spiritual weapon?
|
||||||
- Inactive is DM-triggered via Mark Inactive.
|
x also, conditiojns - no turned
|
||||||
- Player display should fade inactive participant out, then remove from display list.
|
|
||||||
- Reactivating should fade participant in.
|
x make cafinete button be yes caf no caf not caf/moon
|
||||||
- DM display keeps inactive participant visible.
|
|
||||||
- Dead state does not imply inactive/disabled.
|
x init reroll on edit npcdoes not work oh thats HP......
|
||||||
- Dying/stable must not fade out or leave layout holes.
|
|
||||||
- Dead can keep skull/Dead label; create some good visual cues, no removal - but a cool transition to death would be nice.
|
x player intexrface for death savers
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
tool. monsters know what they are doing
|
||||||
|
|
||||||
|
|
||||||
|
on tablet, input a) doesnt work on last char in list amd b) pops up stupid CC/pw input bar in middle of screen
|
||||||
|
init tracker tablet blacks every time edit hp snad submit, does not do it not in FS butdoes cause the tablet bottom bar to come up
|
||||||
|
and the damn UI kept blacking out on tablet. thats new. and the damn keyboar inpt still not sane.
|
||||||
|
- cant find a fix, dont use full screen on tablet
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
x caff doent work on fron tpage or big tablet
|
||||||
|
|
||||||
|
x max/caff need to float or at least be availabe in combagt popout
|
||||||
|
|
||||||
|
x save needs bigger save button on char editor
|
||||||
|
|
||||||
|
|
||||||
|
x fullscreen and dont lock on main app dm view and the no-game-player view ...and doesnt actually prevent lock on android
|
||||||
|
|
||||||
|
x also better vert tab layout - labelt friendly
|
||||||
|
|
||||||
|
x needs AC for players dude
|
||||||
|
|
||||||
|
x and quick entry hp
|
||||||
|
|
||||||
|
x hp do not carry from encounter to ecnounter!!!
|
||||||
|
^feature to add back to campaign character after encounter?
|
||||||
|
maybe campaign toggle in charc section (choosing each end is DM overload will be missed forgotten done wront)
|
||||||
|
|
||||||
|
x refresh/reload/code update causes UI to update to top unselected cambpaign have to drill all the way back down to active encounter....every time. siemtmes?
|
||||||
|
|
||||||
|
x encounters cards need clear "in progress"...
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
x I wonder...if a charcter-list-character should have a isNPC option vailble to them - for longer lived
|
||||||
|
npcs.....
|
||||||
|
|
||||||
|
x hp wont go over max and no temp hp support
|
||||||
|
|
||||||
|
|
||||||
|
## monsters per campaign and npcs
|
||||||
|
## or/and ....copy from encoubnter?
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### npm install warnings cleanup pass
|
||||||
|
lots of updates
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -59,43 +119,11 @@ not sure good way to do this
|
|||||||
- `isActive = id => updatedParticipants.find(p => p.id === id && p.isActive)`
|
- `isActive = id => updatedParticipants.find(p => p.id === id && p.isActive)`
|
||||||
- Returns participant obj (truthy) not boolean. Works by accident, fragile.
|
- Returns participant obj (truthy) not boolean. Works by accident, fragile.
|
||||||
|
|
||||||
### BUG: select campaign during active combat = screen flicker, no action
|
|
||||||
- In active encounter, click different campaign → flicker, no nav, no end.
|
|
||||||
- Either block (toast: end encounter first) or auto-end current + switch.
|
|
||||||
- Decide UX before fix.
|
|
||||||
|
|
||||||
|
|
||||||
### FEAT: generic/non-5e rules mode
|
|
||||||
- Campaign/encounter ruleset toggle: `5e` vs `generic`.
|
|
||||||
- Generic mode turns off death saves/state machine.
|
|
||||||
- Generic mode allows negative HP.
|
|
||||||
- 5e mode rejects negative damage/heal and clamps HP at 0.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### FEAT: clarify "Is NPC" in add-participant
|
### FEAT: clarify "Is NPC" in add-participant
|
||||||
- Ambiguous label. May expand work based on what NPC means here (ally? monster?
|
- Ambiguous label. May expand work based on what NPC means here (ally? monster?
|
||||||
display-only? skip in turn order?). Clarify intent before UX changes.
|
display-only? skip in turn order?). Clarify intent before UX changes.
|
||||||
|
|
||||||
### FEAT: first-class undo/redo UI buttons (B --- do now)
|
|
||||||
- Toolbar buttons ↶/↷ in AdminView header, not buried in /logs.
|
|
||||||
- Undo = revert latest non-undone log. Redo = re-apply latest undone.
|
|
||||||
- Uses current 2-write undo (non-tx). Race safety = log refactor later.
|
|
||||||
- Disabled when stack empty. Keyboard shortcuts (cmd+z / cmd+shift+z).
|
|
||||||
|
|
||||||
### FEAT-LOG: unified log refactor (was FEAT-2 + M6, batched)
|
|
||||||
- Single event schema, one source of truth:
|
|
||||||
`{ ts, type, payload, undo_payload, undone, encounterId,
|
|
||||||
snapshot:{ round, currentTurnParticipantId, turnOrderIds, activeIds } }`
|
|
||||||
- Common format consumed by: UI log view, download/copy export,
|
|
||||||
replay-combat, analyze-turns. One shape, four consumers.
|
|
||||||
- Transactional undo: server endpoint `POST /api/undo/:eventId`. Single
|
|
||||||
SQLite tx applies undo_payload + flips `undone`. Replaces fragile 2-write
|
|
||||||
(log update + encounter update as separate calls).
|
|
||||||
- Download/copy: exports event stream as JSON for offline analysis.
|
|
||||||
- replay-combat + analyze-turns rewritten to emit/consume same event shape.
|
|
||||||
- Migration: keep old log entries readable; new format for new writes.
|
|
||||||
|
|
||||||
|
|
||||||
### quality of life fix: 2. UI says "Campaign Characters", field is players --- naming mismatch (separate concern, flag for later)
|
### quality of life fix: 2. UI says "Campaign Characters", field is players --- naming mismatch (separate concern, flag for later)
|
||||||
|
|
||||||
@@ -107,133 +135,3 @@ not sure good way to do this
|
|||||||
## FEAT - clarify what end encounter does and what initiatives reset means
|
## FEAT - clarify what end encounter does and what initiatives reset means
|
||||||
|
|
||||||
## Done (history)
|
## Done (history)
|
||||||
|
|
||||||
### FEAT: first-class undo/redo UI buttons (DONE)
|
|
||||||
- ↶/↷ pills in InitiativeControls, always visible when encounter open.
|
|
||||||
- Undo = latest non-undone log (per encounter). Redo = latest undone.
|
|
||||||
- encounterPath added to all 14 log contexts (filter key).
|
|
||||||
- redo:patch (forward) added to undoData. Real redo replays forward state.
|
|
||||||
- Disabled when stack empty. Tooltip shows target action.
|
|
||||||
- Uses current 2-write undo (non-tx). Race safety = FEAT-LOG refactor.
|
|
||||||
|
|
||||||
### Architecture: 1-list turn order model (slot, never sort)
|
|
||||||
- Single source: turnOrderIds === participants.map(id). No re-sort after
|
|
||||||
startEncounter. nextTurn skips inactive (predicate), inactive stay in slot.
|
|
||||||
- Drag (reorder) = same-init tie-break only. Cross-init blocked.
|
|
||||||
- startEncounter sorts ALL participants by init once, then frozen.
|
|
||||||
- addParticipant/updateParticipant slot by init (slotIndexForInit), preserve
|
|
||||||
drag order. Display renders participants[] directly (no sort).
|
|
||||||
- Static guard test errs if `.sort(` reintroduced outside allowlist.
|
|
||||||
- Design doc: docs/INITIATIVE_ORDERING.md.
|
|
||||||
|
|
||||||
### Single source of truth: combat logic
|
|
||||||
- All 15 App.js handlers delegate to @ttrpg/shared. ~498 lines inline dupes deleted.
|
|
||||||
- shared/turn.js = only place turn logic lives.
|
|
||||||
|
|
||||||
### Storage parity (firebase + server adapters)
|
|
||||||
- Neutral queryConstraints ({__type:'orderBy'|'limit'}) honored by both adapters.
|
|
||||||
- Shared contract test runs both identically. Memory adapter deleted; factory
|
|
||||||
throws on unknown mode.
|
|
||||||
- ws storage mode renamed to server (env var + adapter name).
|
|
||||||
|
|
||||||
### Logging contract
|
|
||||||
- Every mutating op logs message + undo payload. No-op = null log.
|
|
||||||
- Structural enforcement: per-op contract test (turn.logging.test.js) +
|
|
||||||
static source-scan guard (static.no-unlogged.test.js).
|
|
||||||
|
|
||||||
### Custom conditions per campaign (DONE)
|
|
||||||
- Freeform per-campaign conditions. Add applies to participant + persists to
|
|
||||||
campaign palette in one step. Badge render uses merged allConditions
|
|
||||||
(built-ins + custom). toggleCondition accepts any string. Dedup
|
|
||||||
case-insensitive. maxLength 40. Combat + replay tests prove arbitrary
|
|
||||||
string ids survive round-trip.
|
|
||||||
|
|
||||||
### Death saves: D&D 5e status model (DONE)
|
|
||||||
- `status` is source of truth: conscious, dying, stable, dead.
|
|
||||||
- Characters and NPCs use death saves; monsters skip death saves and become dead/inactive at 0 HP.
|
|
||||||
- Death-save actions: Success, Fail, Nat1, Nat20, Stabilize.
|
|
||||||
- Revive: dead → 0 HP, stable/unconscious, active.
|
|
||||||
- Dead characters/NPCs stay in encounter/initiative until DM removes or marks inactive.
|
|
||||||
- Player display hides inactive participants; DM display keeps them visible.
|
|
||||||
|
|
||||||
### FEAT-3: initiative first-class entry (DONE)
|
|
||||||
- Initiative field at add-char, add-monster, edit participant.
|
|
||||||
- Inline edit wired. Tie-break = drag order.
|
|
||||||
|
|
||||||
### UI feedback: toast + info modal (DONE)
|
|
||||||
- All 23 native alert() replaced. ToastStack (6s auto-dismiss + manual X)
|
|
||||||
for transient failures. InfoModal (persistent OK) for validations.
|
|
||||||
React context provider wraps all 3 App branches.
|
|
||||||
- Fixed: native alert vanished instantly on browser focus loss.
|
|
||||||
|
|
||||||
### Filter dup chars from add-participant dropdown (DONE)
|
|
||||||
- Character dropdown excludes chars already in encounter. Prevents
|
|
||||||
dup-add at source. No more dup alert path needed.
|
|
||||||
|
|
||||||
### Test timeouts (DONE)
|
|
||||||
- jest.setTimeout(10000) in setupTests.js (CRA blocks config-level timeout).
|
|
||||||
|
|
||||||
### Warning = failure in tests (DONE)
|
|
||||||
- console.error/warn throw in test env.
|
|
||||||
|
|
||||||
### BUG-1: addParticipant + pause/resume corrupts rotation
|
|
||||||
- RESOLVED as side effect of BUG-2 fix.
|
|
||||||
|
|
||||||
### BUG-2: addParticipant allows duplicate id
|
|
||||||
- FIXED (addParticipant throws on dup id).
|
|
||||||
|
|
||||||
### BUG-4: hide-player-HP breaks display view
|
|
||||||
- FIXED --- mock honors setDoc{merge}, all 5 activeDisplay sites use merge.
|
|
||||||
|
|
||||||
### BUG-5: mid-round addParticipant/revive corrupts rotation
|
|
||||||
- FIXED --- slot-array + DRY advance core nextActiveAfter.
|
|
||||||
|
|
||||||
### BUG-6: reorderParticipants doesn't update turnOrderIds
|
|
||||||
- FIXED structurally by 1-list model.
|
|
||||||
|
|
||||||
### BUG-7: reorderParticipants not logged
|
|
||||||
- FIXED --- returns log:{message, undo}. Handler calls logAction. deathSave,
|
|
||||||
addParticipants, updateParticipant logging gaps also closed.
|
|
||||||
|
|
||||||
### BUG-8: server adapter has no reconnect
|
|
||||||
- FIXED --- onclose reconnects + re-subscribes existing paths.
|
|
||||||
|
|
||||||
### BUG-10: deact+reactivate same round double-acts participant
|
|
||||||
- FIXED --- 1-list model keeps slot position on toggle. Reactivate does not
|
|
||||||
grant second turn. Test: turn.bug10.test.js.
|
|
||||||
|
|
||||||
### BUG-11: FE Combat.scenario test crashes
|
|
||||||
- FIXED --- moved to shared/turn.combat.test.js, pure functions, 100 rounds.
|
|
||||||
|
|
||||||
### BUG-12: campaign selection follows activeDisplay
|
|
||||||
- FIXED.
|
|
||||||
|
|
||||||
### BUG-13: reorderParticipants crossing current pointer = ambiguous
|
|
||||||
- FIXED --- block cross-pointer reorder during active encounter (both dirs).
|
|
||||||
Full fix needs actedThisRound tracking. Pragmatic block prevents skip/double.
|
|
||||||
Pre-combat: free reorder. Test: turn.bug13.test.js.
|
|
||||||
|
|
||||||
### BUG-14: addParticipant init-insertion breaks after drag-reorder
|
|
||||||
- FIXED --- slotIndexForInit scans current list (post-drag aware).
|
|
||||||
|
|
||||||
### BUG-15: DisplayView re-sorts (drag order not preserved)
|
|
||||||
- FIXED --- display renders participants[] directly.
|
|
||||||
|
|
||||||
### BUG-16: subscribeCollection hook drops queryConstraints
|
|
||||||
- FIXED --- neutral builders, both adapters honor orderBy/limit.
|
|
||||||
|
|
||||||
### BUG-17: dead SDK imports in App.js
|
|
||||||
- FIXED --- trimmed (auth + getFirestore + getStorage remain).
|
|
||||||
|
|
||||||
### BUG-18: stale comments reference deleted memory adapter
|
|
||||||
- FIXED.
|
|
||||||
|
|
||||||
### FEAT-1: Dead characters/NPCs stay in turn order
|
|
||||||
- DONE --- character/NPC death does not auto-remove. DM controls inactive/remove.
|
|
||||||
- Non-NPC monsters still become inactive automatically at death.
|
|
||||||
|
|
||||||
### combat.scenario 100 rounds not turns
|
|
||||||
- DONE --- loops by actual round-wrap count.
|
|
||||||
|
|
||||||
### feat: add all characters to participants list
|
|
||||||
- DONE --- addParticipants bulk add wired.
|
|
||||||
+12
-11
@@ -1,34 +1,36 @@
|
|||||||
# docker/Dockerfile — single container: caddy (front) + node (back).
|
# syntax=docker/dockerfile:1
|
||||||
|
# docker/Dockerfile --- single container: caddy (front) + node (back).
|
||||||
# Build context = repo root.
|
# Build context = repo root.
|
||||||
# ---- build stage: frontend + install backend deps ----
|
# ---- build stage: frontend + install backend deps ----
|
||||||
FROM node:18-alpine AS build
|
FROM node:22-alpine AS build
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
COPY shared/package.json ./shared/
|
COPY shared/package.json ./shared/
|
||||||
COPY server/package.json ./server/
|
COPY server/package.json ./server/
|
||||||
RUN npm install --include-workspace-root
|
RUN --mount=type=cache,target=/root/.npm \
|
||||||
|
npm install --include-workspace-root --omit=dev --prefer-offline
|
||||||
|
|
||||||
|
# frontend code (changes often)
|
||||||
COPY shared/ ./shared/
|
COPY shared/ ./shared/
|
||||||
COPY server/ ./server/
|
|
||||||
COPY src/ ./src/
|
COPY src/ ./src/
|
||||||
COPY public/ ./public/
|
COPY public/ ./public/
|
||||||
COPY tailwind.config.js postcss.config.js ./
|
COPY tailwind.config.js postcss.config.js ./
|
||||||
|
|
||||||
# better-sqlite3 native build (alpine musl)
|
|
||||||
RUN cd server && npm rebuild better-sqlite3
|
|
||||||
|
|
||||||
# build frontend (server storage, same-origin /api + /ws via caddy)
|
# build frontend (server storage, same-origin /api + /ws via caddy)
|
||||||
ARG REACT_APP_TRACKER_APP_ID=ttrpg-initiative-tracker-default
|
ARG REACT_APP_TRACKER_APP_ID=ttrpg-initiative-tracker-default
|
||||||
ENV REACT_APP_STORAGE=server
|
ENV REACT_APP_STORAGE=server
|
||||||
ENV REACT_APP_TRACKER_APP_ID=$REACT_APP_TRACKER_APP_ID
|
ENV REACT_APP_TRACKER_APP_ID=$REACT_APP_TRACKER_APP_ID
|
||||||
RUN NODE_OPTIONS=--openssl-legacy-provider npm run build
|
RUN NODE_OPTIONS=--openssl-legacy-provider npm run build
|
||||||
|
|
||||||
# prune backend dev deps for runtime
|
# server after backend - it's fast. so changing server only doesnt invalidate slow frontend.
|
||||||
RUN npm prune --omit=dev
|
COPY server/ ./server/
|
||||||
|
# better-sqlite3 native build (alpine musl). Cached if server unchanged.
|
||||||
|
RUN cd server && npm rebuild better-sqlite3
|
||||||
|
|
||||||
|
|
||||||
# ---- runtime stage: caddy + node ----
|
# ---- runtime stage: caddy + node ----
|
||||||
FROM node:18-alpine
|
FROM node:22-alpine
|
||||||
RUN apk add --no-cache caddy
|
RUN apk add --no-cache caddy
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
@@ -38,7 +40,6 @@ COPY --from=build /app/server/node_modules ./server/node_modules
|
|||||||
COPY --from=build /app/package*.json ./
|
COPY --from=build /app/package*.json ./
|
||||||
COPY --from=build /app/shared/package.json ./shared/
|
COPY --from=build /app/shared/package.json ./shared/
|
||||||
COPY --from=build /app/server/package.json ./server/
|
COPY --from=build /app/server/package.json ./server/
|
||||||
COPY shared/ ./shared/
|
|
||||||
COPY server/ ./server/
|
COPY server/ ./server/
|
||||||
# built frontend served by caddy
|
# built frontend served by caddy
|
||||||
COPY --from=build /app/build /srv
|
COPY --from=build /app/build /srv
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# docker/portainer-stack.yml — Portainer stack for the SQLite/server build.
|
||||||
|
# Deploys the prebuilt image from the local registry (built + pushed by Jenkins).
|
||||||
|
# Paste into Portainer's web editor (Stacks -> Add stack -> Web editor).
|
||||||
|
#
|
||||||
|
# TLS is terminated by the external nginx, which should reverse_proxy to
|
||||||
|
# http://<docker-host>:8080 (and pass the WebSocket upgrade headers for /ws).
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: thinkserver:5000/ttrpg-tracker-sqlite:latest
|
||||||
|
container_name: ttrpg-tracker
|
||||||
|
ports:
|
||||||
|
- "8080:80" # host:container — nginx upstream is :8080
|
||||||
|
volumes:
|
||||||
|
- app-data:/data # SQLite DB lives here; back this up
|
||||||
|
environment:
|
||||||
|
- DB_PATH=/data/tracker.sqlite
|
||||||
|
- PORT=4001 # node backend port (internal; caddy proxies to it)
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "-qO-", "http://localhost:80/"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
app-data:
|
||||||
Executable
+4
@@ -0,0 +1,4 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
export DOCKER_CONTEXT=bee
|
||||||
|
exec "$(dirname "$0")/restart.sh"
|
||||||
Executable
+21
@@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# scripts/docker-restart.sh — rebuild + restart docker container.
|
||||||
|
# Usage: ./scripts/docker-restart.sh
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
echo "=== stopping existing container ==="
|
||||||
|
docker compose -f docker/docker-compose.yml down 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "=== rebuilding image ==="
|
||||||
|
docker compose -f docker/docker-compose.yml build
|
||||||
|
|
||||||
|
echo "=== starting container ==="
|
||||||
|
docker compose -f docker/docker-compose.yml up -d
|
||||||
|
|
||||||
|
echo "=== status ==="
|
||||||
|
docker compose -f docker/docker-compose.yml ps
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "app: http://localhost:${PORT:-8080}"
|
||||||
|
echo "logs: docker compose -f docker/docker-compose.yml logs -f"
|
||||||
@@ -63,6 +63,14 @@ git config core.hooksPath .githooks # enable pre-push test gate
|
|||||||
|
|
||||||
Idempotent: if port busy, leaves existing proc as-is.
|
Idempotent: if port busy, leaves existing proc as-is.
|
||||||
|
|
||||||
|
**LAN access (phones):** frontend binds 0.0.0.0, LAN IP auto-detected.
|
||||||
|
Other devices hit `http://<lan-ip>:3999`.
|
||||||
|
|
||||||
|
**Wake Lock (Prevent Sleep) on LAN IP:** requires secure context.
|
||||||
|
Plain HTTP on LAN IP = wake lock silently fails. Android Chrome flag workaround:
|
||||||
|
`chrome://flags/#unsafely-treat-insecure-origin-as-secure` → add
|
||||||
|
`http://<lan-ip>:3999` (with port), enable, relaunch. See README for full details.
|
||||||
|
|
||||||
Smoke check:
|
Smoke check:
|
||||||
```bash
|
```bash
|
||||||
curl http://127.0.0.1:4001/health # -> {"ok":true}
|
curl http://127.0.0.1:4001/health # -> {"ok":true}
|
||||||
|
|||||||
@@ -64,6 +64,15 @@ Object in `encounter.participants[]`:
|
|||||||
| `deathSaveSuccesses` | int | character/NPC only, 0-3 successes |
|
| `deathSaveSuccesses` | int | character/NPC only, 0-3 successes |
|
||||||
| `deathSaveFailures` | int | character/NPC only, 0-3 failures |
|
| `deathSaveFailures` | int | character/NPC only, 0-3 failures |
|
||||||
|
|
||||||
|
## Path normalization
|
||||||
|
|
||||||
|
App passes firebase-prefixed paths (`artifacts/{APP_ID}/public/data/campaigns/...`). Server-mode adapter `norm()` strips prefix → bare canonical (`campaigns/...`).
|
||||||
|
|
||||||
|
- **UI / app code** → prefixed paths (`getPath.*` helpers)
|
||||||
|
- **REST API / direct DB / scripts** → bare canonical paths (`campaigns/...`)
|
||||||
|
|
||||||
|
Mixing = empty results. If `GET /api/collection?path=artifacts/.../campaigns` returns `[]`, you used the prefixed form. Drop the prefix.
|
||||||
|
|
||||||
## Build flow (UI)
|
## Build flow (UI)
|
||||||
|
|
||||||
Admin view at `/`. Steps:
|
Admin view at `/`. Steps:
|
||||||
@@ -121,6 +130,101 @@ Pre-combat only (`!isStarted || isPaused`). Drag handles shown for **tied initia
|
|||||||
|
|
||||||
During active combat, cross-current-pointer drag is blocked to avoid skip/double-act ambiguity. Paused combat can reorder same-initiative ties freely.
|
During active combat, cross-current-pointer drag is blocked to avoid skip/double-act ambiguity. Paused combat can reorder same-initiative ties freely.
|
||||||
|
|
||||||
|
## Build flow (API / scripts)
|
||||||
|
|
||||||
|
Same logical steps as UI, via REST. For LLM agents or seed scripts.
|
||||||
|
|
||||||
|
**Server mode only.** REST endpoints (`/api/*`) exist only when tracker runs
|
||||||
|
with `REACT_APP_STORAGE=server` (bundled Express backend mounted). Firebase
|
||||||
|
SDK mode has no HTTP backend — data lives in Firestore via in-browser SDK,
|
||||||
|
different auth + write paths. This section does not apply to firebase mode.
|
||||||
|
|
||||||
|
Confirm server mode before scripting:
|
||||||
|
```bash
|
||||||
|
curl -s <HOST>/api/collection?path=campaigns | head -c 200
|
||||||
|
```
|
||||||
|
JSON array = server mode. HTML (SPA shell) = firebase mode or backend not
|
||||||
|
mounted — API path won't work.
|
||||||
|
|
||||||
|
### REST endpoints
|
||||||
|
|
||||||
|
| Method | Path | Body / Query | Action |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `GET` | `/api/doc` | `?path=` | read one doc |
|
||||||
|
| `PUT` | `/api/doc` | `{path, data}` | replace doc |
|
||||||
|
| `PATCH` | `/api/doc` | `{path, patch}` | shallow merge, create-on-miss |
|
||||||
|
| `DELETE` | `/api/doc` | `?path=` | delete one doc |
|
||||||
|
| `GET` | `/api/collection` | `?path=` | list docs under collection |
|
||||||
|
| `POST` | `/api/collection` | `{path, data}` | addDoc: auto-id under collection |
|
||||||
|
| `POST` | `/api/batch` | `{ops:[{type:'set'\|'update'\|'delete', path, data?}]}` | atomic multi-write |
|
||||||
|
|
||||||
|
All paths bare canonical (no `artifacts/...` prefix).
|
||||||
|
|
||||||
|
### id format
|
||||||
|
|
||||||
|
`generateId()` = `crypto.randomUUID()` (fallback `id_{Date.now()}_{rand10}`). Use either. Server `POST /api/collection` generates its own UUID — fine for campaigns/encounters. Participants are inline array items; generate their ids client-side so they're stable across batch writes.
|
||||||
|
|
||||||
|
### Object templates
|
||||||
|
|
||||||
|
Encounter doc (full, for `PUT` / batch `set`):
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
name: 'Barrowdeep 1 - Antechamber',
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
participants: [], // inline, NOT a sub-collection
|
||||||
|
round: 0,
|
||||||
|
currentTurnParticipantId: null,
|
||||||
|
isStarted: false,
|
||||||
|
isPaused: false,
|
||||||
|
ruleset: '5e',
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Participant object (item in `encounter.participants[]`):
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
id: generateId(),
|
||||||
|
name: 'Ankheg',
|
||||||
|
type: 'monster', // 'character' | 'npc' | 'monster'
|
||||||
|
originalCharacterId: null, // set only if type==='character'
|
||||||
|
initiative: rollD20() + initMod, // rolled ONCE at add; stored, not re-derived
|
||||||
|
maxHp: 45,
|
||||||
|
currentHp: 45, // start at full
|
||||||
|
conditions: [],
|
||||||
|
isActive: true,
|
||||||
|
status: 'conscious',
|
||||||
|
deathSaveSuccesses: 0, // character/npc only
|
||||||
|
deathSaveFailures: 0, // character/npc only
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Initiative semantics
|
||||||
|
|
||||||
|
- Default: `initiative = rollD20() + initMod` (d20 ∈ [1,20], roll fresh per participant).
|
||||||
|
- Manual override (e.g. pre-rolled values): set `initiative` directly, skip the roll.
|
||||||
|
- Fixed at add time. NOT re-derived from `initMod` after — `initMod` is not stored on participant.
|
||||||
|
|
||||||
|
### Recipe: build encounters for a campaign
|
||||||
|
|
||||||
|
1. **Find campaign id by name:**
|
||||||
|
```bash
|
||||||
|
curl -s "$HOST/api/collection?path=campaigns" \
|
||||||
|
| jq -r '.[] | select(.name=="2026 D&D") | .id'
|
||||||
|
```
|
||||||
|
2. **Build encounter docs + participants client-side** (object templates above), roll initiative per participant.
|
||||||
|
3. **Write all encounters in one batch:**
|
||||||
|
```bash
|
||||||
|
curl -s -X POST "$HOST/api/batch" \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"ops":[{"type":"set","path":"campaigns/CID/encounters/EID1","data":{...}},{"type":"set","path":"campaigns/CID/encounters/EID2","data":{...}}]}'
|
||||||
|
```
|
||||||
|
4. **Verify:**
|
||||||
|
```bash
|
||||||
|
curl -s "$HOST/api/collection?path=campaigns/CID/encounters" | jq '.[] | {name, count: (.participants|length)}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Participants go inline in the encounter doc — there is no `participants` sub-collection. A single batch `set` per encounter writes the whole roster atomically.
|
||||||
|
|
||||||
## Combat flow (UI)
|
## Combat flow (UI)
|
||||||
|
|
||||||
InitiativeControls panel (sticky, right side).
|
InitiativeControls panel (sticky, right side).
|
||||||
@@ -198,6 +302,8 @@ No re-sort after `startEncounter`.
|
|||||||
|
|
||||||
## Storage paths quick reference
|
## Storage paths quick reference
|
||||||
|
|
||||||
|
Bare canonical (server mode). App code prefixes these with `artifacts/{APP_ID}/public/data/` — adapter strips it.
|
||||||
|
|
||||||
```
|
```
|
||||||
campaigns/{cid} campaign doc
|
campaigns/{cid} campaign doc
|
||||||
campaigns/{cid}/encounters/{eid} encounter doc (participants[])
|
campaigns/{cid}/encounters/{eid} encounter doc (participants[])
|
||||||
@@ -206,6 +312,8 @@ activeDisplay/status player display control
|
|||||||
logs/{logId} action log entry
|
logs/{logId} action log entry
|
||||||
```
|
```
|
||||||
|
|
||||||
|
REST mapping: `campaigns/{cid}` doc → `GET/PUT/PATCH/DELETE /api/doc?path=campaigns/{cid}`. Collection parent (`campaigns`, `campaigns/{cid}/encounters`) → `GET/POST /api/collection?path=...`.
|
||||||
|
|
||||||
## DM tips
|
## DM tips
|
||||||
|
|
||||||
- Initiative rolled ONCE at add time. Stored. Edit via EditParticipantModal to override.
|
- Initiative rolled ONCE at add time. Stored. Edit via EditParticipantModal to override.
|
||||||
|
|||||||
Generated
+7
-21
@@ -7151,14 +7151,17 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/better-sqlite3": {
|
"node_modules/better-sqlite3": {
|
||||||
"version": "11.10.0",
|
"version": "12.11.1",
|
||||||
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz",
|
||||||
"integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==",
|
"integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==",
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bindings": "^1.5.0",
|
"bindings": "^1.5.0",
|
||||||
"prebuild-install": "^7.1.1"
|
"prebuild-install": "^7.1.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/bfj": {
|
"node_modules/bfj": {
|
||||||
@@ -21316,23 +21319,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tailwindcss/node_modules/yaml": {
|
|
||||||
"version": "2.9.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
|
|
||||||
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
|
|
||||||
"license": "ISC",
|
|
||||||
"optional": true,
|
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
|
||||||
"yaml": "bin.mjs"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 14.6"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/eemeli"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/tapable": {
|
"node_modules/tapable": {
|
||||||
"version": "2.3.0",
|
"version": "2.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz",
|
||||||
@@ -23021,7 +23007,7 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ttrpg/shared": "*",
|
"@ttrpg/shared": "*",
|
||||||
"better-sqlite3": "^11.3.0",
|
"better-sqlite3": "^12.0.0",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"express": "^4.19.2",
|
"express": "^4.19.2",
|
||||||
"nanoid": "^5.0.7",
|
"nanoid": "^5.0.7",
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"id": "/display",
|
||||||
|
"short_name": "TTRPG Display",
|
||||||
|
"name": "TTRPG Initiative Tracker - Player Display",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "player-favicon.ico",
|
||||||
|
"sizes": "64x64 32x32 24x24 16x16",
|
||||||
|
"type": "image/x-icon"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "player-logo192.png",
|
||||||
|
"note": "this image intentionally missing from filesystem - keeping manfiest and having broken icon allows android to _shortcut_ which user can control name of.",
|
||||||
|
"type": "image/png",
|
||||||
|
"sizes": "192x192"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"start_url": "/display",
|
||||||
|
"scope": "/display",
|
||||||
|
"note:" "none of the display stuff actually works, even when it properly installs a pwa (which user cant control name of...)",
|
||||||
|
"display": "fullscreen",
|
||||||
|
"orientation": "portrait",
|
||||||
|
"theme_color": "#1A202C",
|
||||||
|
"background_color": "#1A202C"
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 7.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
@@ -1,4 +1,5 @@
|
|||||||
{
|
{
|
||||||
|
"id": "/",
|
||||||
"short_name": "TTRPG Tracker",
|
"short_name": "TTRPG Tracker",
|
||||||
"name": "TTRPG Initiative Tracker",
|
"name": "TTRPG Initiative Tracker",
|
||||||
"icons": [
|
"icons": [
|
||||||
@@ -9,17 +10,16 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "logo192.png",
|
"src": "logo192.png",
|
||||||
|
"note": "this image intentionally missing from filesystem - keeping manfiest and having broken icon allows android to _shortcut_ which user can control name of.",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"sizes": "192x192"
|
"sizes": "192x192"
|
||||||
},
|
|
||||||
{
|
|
||||||
"src": "logo512.png",
|
|
||||||
"type": "image/png",
|
|
||||||
"sizes": "512x512"
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"start_url": ".",
|
"start_url": "/",
|
||||||
"display": "standalone",
|
"scope": "/",
|
||||||
|
"note:" "none of the display stuff actually works, even when it properly installs a pwa (which user cant control name of...)",
|
||||||
|
"display": "fullscreen",
|
||||||
|
"orientation": "portrait",
|
||||||
"theme_color": "#2D3748",
|
"theme_color": "#2D3748",
|
||||||
"background_color": "#1A202C"
|
"background_color": "#1A202C"
|
||||||
}
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 7.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 5.1 KiB |
+14
-3
@@ -27,10 +27,15 @@ fi
|
|||||||
|
|
||||||
# frontend: server storage, :3999
|
# frontend: server storage, :3999
|
||||||
if ! lsof -ti :3999 >/dev/null 2>&1; then
|
if ! lsof -ti :3999 >/dev/null 2>&1; then
|
||||||
echo "starting frontend :3999..."
|
# detect LAN ip so other devices (phones) can reach backend
|
||||||
|
LAN_IP=$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo 127.0.0.1)
|
||||||
|
echo "starting frontend :3999 (lan ip: $LAN_IP)..."
|
||||||
|
NODE_ENV=development REACT_APP_DEV_TOOLS=1 \
|
||||||
REACT_APP_STORAGE=server \
|
REACT_APP_STORAGE=server \
|
||||||
REACT_APP_BACKEND_URL=http://127.0.0.1:4001 \
|
REACT_APP_BACKEND_URL=http://${LAN_IP}:4001 \
|
||||||
REACT_APP_BACKEND_REALTIME_URL=ws://127.0.0.1:4001/ws \
|
REACT_APP_BACKEND_REALTIME_URL=ws://${LAN_IP}:4001/ws \
|
||||||
|
DANGEROUSLY_DISABLE_HOST_CHECK=true \
|
||||||
|
HOST=0.0.0.0 \
|
||||||
BROWSER=none PORT=3999 \
|
BROWSER=none PORT=3999 \
|
||||||
nohup npm start > tmp/fe.log 2>&1 &
|
nohup npm start > tmp/fe.log 2>&1 &
|
||||||
echo $! > tmp/fe.pid
|
echo $! > tmp/fe.pid
|
||||||
@@ -50,5 +55,11 @@ done
|
|||||||
echo ""
|
echo ""
|
||||||
echo "backend : http://127.0.0.1:4001 (curl http://127.0.0.1:4001/health)"
|
echo "backend : http://127.0.0.1:4001 (curl http://127.0.0.1:4001/health)"
|
||||||
echo "frontend : http://127.0.0.1:3999 (admin / player /display)"
|
echo "frontend : http://127.0.0.1:3999 (admin / player /display)"
|
||||||
|
echo "lan url : http://${LAN_IP}:3999 (phones/other devices on network)"
|
||||||
echo "logs : tmp/server.log tmp/fe.log"
|
echo "logs : tmp/server.log tmp/fe.log"
|
||||||
echo "stop : ./scripts/dev-stop.sh"
|
echo "stop : ./scripts/dev-stop.sh"
|
||||||
|
echo ""
|
||||||
|
echo "NOTE: Prevent Sleep (wake lock) requires secure context (HTTPS/localhost)."
|
||||||
|
echo " LAN IP (http) won't work unless Android Chrome flag set:"
|
||||||
|
echo " chrome://flags/#unsafely-treat-insecure-origin-as-secure"
|
||||||
|
echo " Add: http://${LAN_IP}:3999 (include port)"
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
// server/index.js — generic KV document store over HTTP + WebSocket.
|
// server/index.js — generic KV document store over HTTP + WebSocket.
|
||||||
// firebase mirror: doc-tree model. Thin REST, path-based WS push.
|
// firebase mirror: doc-tree model. Thin REST, path-based WS push.
|
||||||
// Adapter (src/storage/server.js) = passthrough, no shape translation.
|
// Adapter (src/storage/server.js) = passthrough, no shape translation.
|
||||||
|
// TEST: cache layer rebuild check.
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ttrpg/shared": "*",
|
"@ttrpg/shared": "*",
|
||||||
"better-sqlite3": "^11.3.0",
|
"better-sqlite3": "^12.0.0",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"express": "^4.19.2",
|
"express": "^4.19.2",
|
||||||
"nanoid": "^5.0.7",
|
"nanoid": "^5.0.7",
|
||||||
|
|||||||
@@ -1,21 +1,30 @@
|
|||||||
// STATIC GUARD: prod source must pass eslint with zero errors/warnings.
|
// STATIC GUARD: prod source must pass eslint with zero errors/warnings.
|
||||||
// Scans App.js + storage adapters + shared modules. Catches unused imports,
|
// Scans ALL .js/.jsx in src/ + shared/ (excl tests/mocks). Catches unused imports,
|
||||||
// dead code, undefined vars before they hit the browser console.
|
// dead code, undefined vars before they hit the browser console.
|
||||||
// Run via: npx eslint <files> --format json -> parse -> fail on any problem.
|
// Run via: npx eslint <files> --format json -> parse -> fail on any problem.
|
||||||
const { execSync } = require('child_process');
|
const { execSync } = require('child_process');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
const ROOT = path.resolve(__dirname, '..', '..');
|
const ROOT = path.resolve(__dirname, '..', '..');
|
||||||
|
|
||||||
|
function walkJs(dir) {
|
||||||
|
let out = [];
|
||||||
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
const full = path.join(dir, entry.name);
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
if (entry.name === 'node_modules' || entry.name === 'tests' || entry.name === '__mocks__') continue;
|
||||||
|
out = out.concat(walkJs(full));
|
||||||
|
} else if (/\.(js|jsx)$/.test(entry.name)) {
|
||||||
|
out.push(full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
const TARGETS = [
|
const TARGETS = [
|
||||||
'src/App.js',
|
...walkJs(path.join(ROOT, 'src')),
|
||||||
'src/storage/contract.js',
|
...walkJs(path.join(ROOT, 'shared')),
|
||||||
'src/storage/firebase.js',
|
|
||||||
'src/storage/index.js',
|
|
||||||
'src/storage/server.js',
|
|
||||||
'shared/index.js',
|
|
||||||
'shared/logEvent.js',
|
|
||||||
'shared/turn.js',
|
|
||||||
];
|
];
|
||||||
|
|
||||||
function runEslint(files) {
|
function runEslint(files) {
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// AC field on participant + builders.
|
||||||
|
const shared = require('@ttrpg/shared');
|
||||||
|
const { makeParticipant, buildMonsterParticipant, buildCharacterParticipant, rollHpFormula } = shared;
|
||||||
|
|
||||||
|
describe('AC field', () => {
|
||||||
|
test('makeParticipant accepts ac', () => {
|
||||||
|
const p = makeParticipant({ name: 'Orc', type: 'monster', initiative: 10, maxHp: 15, currentHp: 15, ac: 13 });
|
||||||
|
expect(p.ac).toBe(13);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('makeParticipant ac defaults null', () => {
|
||||||
|
const p = makeParticipant({ name: 'Orc', type: 'monster', initiative: 10, maxHp: 15, currentHp: 15 });
|
||||||
|
expect(p.ac).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildMonsterParticipant accepts ac', () => {
|
||||||
|
const { participant } = buildMonsterParticipant({ name: 'Goblin', maxHp: 7, initMod: 2, ac: 15 });
|
||||||
|
expect(participant.ac).toBe(15);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildMonsterParticipant ac defaults null', () => {
|
||||||
|
const { participant } = buildMonsterParticipant({ name: 'Goblin', maxHp: 7 });
|
||||||
|
expect(participant.ac).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildCharacterParticipant accepts character ac', () => {
|
||||||
|
const { participant } = buildCharacterParticipant({ id: 'c1', name: 'Fighter', defaultMaxHp: 30, defaultInitMod: 2, defaultAc: 18 });
|
||||||
|
expect(participant.ac).toBe(18);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildCharacterParticipant ac defaults null when unset', () => {
|
||||||
|
const { participant } = buildCharacterParticipant({ id: 'c1', name: 'Fighter', defaultMaxHp: 30 });
|
||||||
|
expect(participant.ac).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
// addParticipants (bulk) must slot by initiative, not append.
|
||||||
|
const shared = require('@ttrpg/shared');
|
||||||
|
const { mockCtx } = require('./_helpers');
|
||||||
|
const { buildCharacterParticipant, buildMonsterParticipant, addParticipants, makeParticipant } = shared;
|
||||||
|
|
||||||
|
function enc(ps = []) {
|
||||||
|
return { name:'t', participants: ps, isStarted: false, isPaused: false,
|
||||||
|
round: 0, currentTurnParticipantId: null, turnOrderIds: [] };
|
||||||
|
}
|
||||||
|
function p(id, init) {
|
||||||
|
return makeParticipant({ id, name: id, type: 'monster', initiative: init, maxHp: 10, currentHp: 10 });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('addParticipants slot order', () => {
|
||||||
|
test('bulk add slots by initiative desc', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([]);
|
||||||
|
e = await addParticipants(e, [p('a', 5), p('b', 20), p('c', 10)], ctx);
|
||||||
|
expect(e.participants.map(x => x.id)).toEqual(['b', 'c', 'a']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bulk add preserves existing order + slots new', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([p('a', 20), p('b', 5)]);
|
||||||
|
e = await addParticipants(e, [p('c', 10)], ctx);
|
||||||
|
expect(e.participants.map(x => x.id)).toEqual(['a', 'c', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bulk add same-init appends after existing (stable tie)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([p('a', 10)]);
|
||||||
|
e = await addParticipants(e, [p('b', 10), p('c', 10)], ctx);
|
||||||
|
expect(e.participants.map(x => x.id)).toEqual(['a', 'b', 'c']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bulk add mixed inits into existing list', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([p('a', 15), p('b', 5)]);
|
||||||
|
e = await addParticipants(e, [p('c', 20), p('d', 10), p('e', 15)], ctx);
|
||||||
|
expect(e.participants.map(x => x.id)).toEqual(['c', 'a', 'e', 'd', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bulk add updates turnOrderIds to match', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([]);
|
||||||
|
e = await addParticipants(e, [p('a', 5), p('b', 20)], ctx);
|
||||||
|
expect(e.turnOrderIds).toEqual(['b', 'a']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
const shared = require('@ttrpg/shared');
|
||||||
|
const { mockCtx, readyEnc, undoLast } = require('./_helpers');
|
||||||
|
|
||||||
|
const {
|
||||||
|
makeEffect, addEffect, updateEffect, removeEffect,
|
||||||
|
nextTurn, applyHpChange, updateParticipant,
|
||||||
|
} = shared;
|
||||||
|
|
||||||
|
function effect(overrides = {}) {
|
||||||
|
return makeEffect({
|
||||||
|
name: 'Turned', presetId: 'turned', scope: 'participant',
|
||||||
|
targetParticipantId: 'p2', remainingRounds: 10,
|
||||||
|
expiresOnDamage: true, playerDisplay: 'prominent',
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function runningEnc(overrides = {}) {
|
||||||
|
return {
|
||||||
|
...readyEnc(),
|
||||||
|
isStarted: true,
|
||||||
|
round: 2,
|
||||||
|
currentTurnParticipantId: 'p1',
|
||||||
|
turnOrderIds: ['p1', 'p2'],
|
||||||
|
effects: [],
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('tracked effects', () => {
|
||||||
|
test('makeEffect normalizes generic effect fields', () => {
|
||||||
|
const e = effect({ id: 'fx1', remainingRounds: 3.9 });
|
||||||
|
expect(e).toEqual(expect.objectContaining({
|
||||||
|
id: 'fx1', name: 'Turned', presetId: 'turned', scope: 'participant',
|
||||||
|
targetParticipantId: 'p2', remainingRounds: 3,
|
||||||
|
expiresOnDamage: true, playerDisplay: 'prominent',
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('add, update, remove effect are persisted and undoable', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let enc = readyEnc({ participants: readyEnc().participants });
|
||||||
|
enc.effects = [];
|
||||||
|
const fx = effect({ id: 'fx1' });
|
||||||
|
|
||||||
|
enc = await addEffect(enc, fx, ctx);
|
||||||
|
expect(enc.effects).toEqual([fx]);
|
||||||
|
enc = await updateEffect(enc, 'fx1', { remainingRounds: 6 }, ctx);
|
||||||
|
expect(enc.effects[0].remainingRounds).toBe(6);
|
||||||
|
const afterRemove = await removeEffect(enc, 'fx1', ctx);
|
||||||
|
expect(afterRemove.effects).toEqual([]);
|
||||||
|
const undone = await undoLast(ctx, afterRemove);
|
||||||
|
expect(undone.effects[0]).toEqual(expect.objectContaining({ id: 'fx1', remainingRounds: 6 }));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('round wrap decrements timed effects and removes expired effects', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
const enc = runningEnc({
|
||||||
|
currentTurnParticipantId: 'p2',
|
||||||
|
effects: [effect({ id: 'keep', remainingRounds: 2 }), effect({ id: 'expire', remainingRounds: 1 })],
|
||||||
|
});
|
||||||
|
|
||||||
|
const out = await nextTurn(enc, ctx);
|
||||||
|
expect(out.round).toBe(3);
|
||||||
|
expect(out.effects).toHaveLength(1);
|
||||||
|
expect(out.effects[0]).toEqual(expect.objectContaining({ id: 'keep', remainingRounds: 1 }));
|
||||||
|
|
||||||
|
const undone = await undoLast(ctx, out);
|
||||||
|
expect(undone.round).toBe(2);
|
||||||
|
expect(undone.effects.map(e => [e.id, e.remainingRounds])).toEqual([['keep', 2], ['expire', 1]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('same-round turn advance does not decrement effects', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
const enc = runningEnc({ effects: [effect({ id: 'fx', remainingRounds: 10 })] });
|
||||||
|
const out = await nextTurn(enc, ctx);
|
||||||
|
expect(out.round).toBe(2);
|
||||||
|
expect(out.effects[0].remainingRounds).toBe(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('damage expires targeted effect even when temp HP absorbs all damage; undo restores it', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
const participants = readyEnc().participants.map(p => p.id === 'p2' ? { ...p, tempHp: 5 } : p);
|
||||||
|
const enc = runningEnc({ participants, effects: [effect({ id: 'fx' })] });
|
||||||
|
|
||||||
|
const out = await applyHpChange(enc, 'p2', 'damage', 2, ctx);
|
||||||
|
expect(out.participants.find(p => p.id === 'p2').currentHp).toBe(10);
|
||||||
|
expect(out.effects).toEqual([]);
|
||||||
|
|
||||||
|
const undone = await undoLast(ctx, out);
|
||||||
|
expect(undone.effects).toHaveLength(1);
|
||||||
|
expect(undone.effects[0].id).toBe('fx');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('direct HP reduction expires targeted effect; increase does not', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let enc = runningEnc({ effects: [effect({ id: 'fx' })] });
|
||||||
|
enc = await updateParticipant(enc, 'p2', { currentHp: 8 }, ctx);
|
||||||
|
expect(enc.effects).toEqual([]);
|
||||||
|
|
||||||
|
enc = { ...enc, effects: [effect({ id: 'fx2' })] };
|
||||||
|
enc = await updateParticipant(enc, 'p2', { currentHp: 9 }, ctx);
|
||||||
|
expect(enc.effects).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('damage leaves encounter-wide and non-expiring effects active', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
const enc = runningEnc({ effects: [
|
||||||
|
effect({ id: 'weapon', presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', targetParticipantId: null, expiresOnDamage: false }),
|
||||||
|
effect({ id: 'bless', name: 'Bless', expiresOnDamage: false }),
|
||||||
|
] });
|
||||||
|
const out = await applyHpChange(enc, 'p2', 'damage', 1, ctx);
|
||||||
|
expect(out.effects.map(e => e.id)).toEqual(['weapon', 'bless']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
// Generic (non-5e) ruleset: no death saves, negative HP allowed, down status.
|
||||||
|
const shared = require('@ttrpg/shared');
|
||||||
|
const { mockCtx, undoLast } = require('./_helpers');
|
||||||
|
const {
|
||||||
|
buildCharacterParticipant, buildMonsterParticipant,
|
||||||
|
startEncounter, applyHpChange, deathSave, markDead, reviveParticipant, healFullParticipant,
|
||||||
|
} = shared;
|
||||||
|
|
||||||
|
function char(id, hp = 100) {
|
||||||
|
const { participant } = buildCharacterParticipant({ id: `orig-${id}`, name: id, defaultMaxHp: hp, defaultInitMod: 2 });
|
||||||
|
participant.id = id;
|
||||||
|
return participant;
|
||||||
|
}
|
||||||
|
function mon(id, hp = 100) {
|
||||||
|
const { participant } = buildMonsterParticipant({ name: id, maxHp: hp, initMod: 2 });
|
||||||
|
participant.id = id;
|
||||||
|
return participant;
|
||||||
|
}
|
||||||
|
function enc(ps, ruleset = 'generic') {
|
||||||
|
return {
|
||||||
|
name: 't', participants: ps, isStarted: false, isPaused: false,
|
||||||
|
round: 0, currentTurnParticipantId: null, turnOrderIds: [],
|
||||||
|
ruleset,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const snap = (e) => JSON.parse(JSON.stringify(e));
|
||||||
|
|
||||||
|
describe('generic ruleset', () => {
|
||||||
|
test('damage past 0 = negative HP, status down (character)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
const newEnc = await applyHpChange(e, 'a', 'damage', 15, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.currentHp).toBe(-5);
|
||||||
|
expect(p.status).toBe('down');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('damage exactly to 0 = status down', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
const newEnc = await applyHpChange(e, 'a', 'damage', 10, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.currentHp).toBe(0);
|
||||||
|
expect(p.status).toBe('down');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('heal from negative = conscious', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'a', 'damage', 15, ctx); // -5
|
||||||
|
const newEnc = await applyHpChange(e, 'a', 'heal', 10, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.currentHp).toBe(5);
|
||||||
|
expect(p.status).toBe('conscious');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('heal caps at maxHp', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'a', 'damage', 5, ctx); // 5
|
||||||
|
const newEnc = await applyHpChange(e, 'a', 'heal', 20, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.currentHp).toBe(10);
|
||||||
|
expect(p.status).toBe('conscious');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('monster death = auto-inactive (generic)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([mon('m', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
const newEnc = await applyHpChange(e, 'm', 'damage', 20, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id.startsWith('m'));
|
||||||
|
expect(p.currentHp).toBe(-10);
|
||||||
|
expect(p.status).toBe('dead');
|
||||||
|
expect(p.isActive).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('monster at exactly 0 = dead + inactive (generic)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([mon('m', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
const newEnc = await applyHpChange(e, 'm', 'damage', 10, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id.startsWith('m'));
|
||||||
|
expect(p.currentHp).toBe(0);
|
||||||
|
expect(p.status).toBe('dead');
|
||||||
|
expect(p.isActive).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deathSave throws in generic mode', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'a', 'damage', 10, ctx); // down
|
||||||
|
await expect(deathSave(e, 'a', 'fail', ctx)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('revive in generic mode: dead→conscious (no stable)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'a', 'damage', 10, ctx); // down
|
||||||
|
e = await markDead(e, 'a', ctx); // dead
|
||||||
|
const newEnc = await reviveParticipant(e, 'a', ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.status).toBe('conscious');
|
||||||
|
expect(p.currentHp).toBe(0); // HP unchanged from down
|
||||||
|
});
|
||||||
|
|
||||||
|
test('revive generic reactivates if inactive', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([mon('m', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await markDead(e, e.participants[0].id, ctx); // dead+inactive
|
||||||
|
const newEnc = await reviveParticipant(e, e.participants[0].id, ctx);
|
||||||
|
const p = newEnc.participants[0];
|
||||||
|
expect(p.status).toBe('conscious');
|
||||||
|
expect(p.isActive).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('markDead kills and disables character', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([{ ...char('a', 10), tempHp: 4, deathSaveSuccesses: 2, deathSaveFailures: 1 }]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
const newEnc = await markDead(e, 'a', ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p).toMatchObject({
|
||||||
|
currentHp: 0, tempHp: 0, status: 'dead', isActive: false,
|
||||||
|
deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const undone = await undoLast(ctx, newEnc);
|
||||||
|
expect(undone.participants.find(x => x.id === 'a')).toMatchObject({
|
||||||
|
currentHp: 10, tempHp: 4, status: 'conscious', isActive: true,
|
||||||
|
deathSaveSuccesses: 2, deathSaveFailures: 1,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('healFullParticipant restores dead participant to full, active, conscious; undo restores death', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([{ ...char('a', 20), currentHp: 0, status: 'dead', isActive: false, deathSaveSuccesses: 2, deathSaveFailures: 1, conditions: ['unconscious'], stableRegainHours: 3 }]);
|
||||||
|
const healed = await healFullParticipant(e, 'a', ctx);
|
||||||
|
expect(healed.participants[0]).toMatchObject({
|
||||||
|
currentHp: 20, status: 'conscious', isActive: true,
|
||||||
|
deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null,
|
||||||
|
});
|
||||||
|
expect(healed.participants[0].conditions).not.toContain('unconscious');
|
||||||
|
|
||||||
|
const undone = await undoLast(ctx, healed);
|
||||||
|
expect(undone.participants[0]).toMatchObject({ currentHp: 0, status: 'dead', isActive: false, stableRegainHours: 3 });
|
||||||
|
expect(undone.participants[0].conditions).toContain('unconscious');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('markDead on monster = 0 HP + dead + inactive', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([mon('m', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'm', 'damage', 5, ctx); // 5 HP remain
|
||||||
|
const newEnc = await markDead(e, e.participants[0].id, ctx);
|
||||||
|
const p = newEnc.participants[0];
|
||||||
|
expect(p.status).toBe('dead');
|
||||||
|
expect(p.currentHp).toBe(0);
|
||||||
|
expect(p.isActive).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('markDead on conscious = dead', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
const newEnc = await markDead(e, 'a', ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.status).toBe('dead');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('damage while down = more negative (no death saves)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'a', 'damage', 15, ctx); // -5 down
|
||||||
|
const newEnc = await applyHpChange(e, 'a', 'damage', 5, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.currentHp).toBe(-10);
|
||||||
|
expect(p.status).toBe('down');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no unconscious condition auto-added (generic)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
const newEnc = await applyHpChange(e, 'a', 'damage', 10, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.conditions).not.toContain('unconscious');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('down→conscious clears dead? no, dead is separate', async () => {
|
||||||
|
// sanity: down heal to conscious, dead untouched
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([char('a', 10)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'a', 'damage', 10, ctx); // down
|
||||||
|
const newEnc = await applyHpChange(e, 'a', 'heal', 10, ctx);
|
||||||
|
const p = newEnc.participants.find(x => x.id === 'a');
|
||||||
|
expect(p.status).toBe('conscious');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// HP formula roll: parse "2d6+9" style, roll, return total.
|
||||||
|
const shared = require('@ttrpg/shared');
|
||||||
|
const { rollHpFormula } = shared;
|
||||||
|
|
||||||
|
describe('rollHpFormula', () => {
|
||||||
|
test('basic NdM', () => {
|
||||||
|
const r = rollHpFormula('2d6');
|
||||||
|
expect(r).toBeGreaterThanOrEqual(2);
|
||||||
|
expect(r).toBeLessThanOrEqual(12);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('NdM+bonus', () => {
|
||||||
|
const r = rollHpFormula('2d6+9');
|
||||||
|
expect(r).toBeGreaterThanOrEqual(11);
|
||||||
|
expect(r).toBeLessThanOrEqual(21);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('NdM-bonus', () => {
|
||||||
|
const r = rollHpFormula('3d8-2');
|
||||||
|
expect(r).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(r).toBeLessThanOrEqual(22);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('single die', () => {
|
||||||
|
const r = rollHpFormula('1d20');
|
||||||
|
expect(r).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(r).toBeLessThanOrEqual(20);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('case insensitive', () => {
|
||||||
|
const r = rollHpFormula('2D6+5');
|
||||||
|
expect(r).toBeGreaterThanOrEqual(7);
|
||||||
|
expect(r).toBeLessThanOrEqual(17);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('whitespace tolerant', () => {
|
||||||
|
const r = rollHpFormula(' 2d6 + 9 ');
|
||||||
|
expect(r).toBeGreaterThanOrEqual(11);
|
||||||
|
expect(r).toBeLessThanOrEqual(21);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('large die', () => {
|
||||||
|
const r = rollHpFormula('4d12+10');
|
||||||
|
expect(r).toBeGreaterThanOrEqual(14);
|
||||||
|
expect(r).toBeLessThanOrEqual(58);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invalid returns null', () => {
|
||||||
|
expect(rollHpFormula('abc')).toBeNull();
|
||||||
|
expect(rollHpFormula('')).toBeNull();
|
||||||
|
expect(rollHpFormula(null)).toBeNull();
|
||||||
|
expect(rollHpFormula(undefined)).toBeNull();
|
||||||
|
expect(rollHpFormula('2d')).toBeNull();
|
||||||
|
expect(rollHpFormula('d6')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('zero dice invalid', () => {
|
||||||
|
expect(rollHpFormula('0d6')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// rerollAllInitiatives: bulk d20+initMod for every participant.
|
||||||
|
// Single commit, single log, undo restores old values + order.
|
||||||
|
|
||||||
|
const {
|
||||||
|
makeParticipant,
|
||||||
|
startEncounter,
|
||||||
|
rerollAllInitiatives,
|
||||||
|
} = require('@ttrpg/shared');
|
||||||
|
const { mockCtx, undoLast } = require('./_helpers');
|
||||||
|
|
||||||
|
function part(id, init, initMod, extra = {}) {
|
||||||
|
return makeParticipant({
|
||||||
|
id, name: id, type: initMod !== undefined ? 'monster' : 'character',
|
||||||
|
initiative: init, initMod, maxHp: 20, currentHp: 20, ...extra,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function enc(participants, extra = {}) {
|
||||||
|
return {
|
||||||
|
id: 'e1', name: 'reroll-all-test', participants,
|
||||||
|
isStarted: false, isPaused: false, round: 0,
|
||||||
|
currentTurnParticipantId: null, turnOrderIds: [],
|
||||||
|
...extra,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const find = (e, id) => e.participants.find(p => p.id === id);
|
||||||
|
|
||||||
|
describe('rerollAllInitiatives', () => {
|
||||||
|
test('rolls d20+initMod for every participant; single write', async () => {
|
||||||
|
const { ctx, storage } = mockCtx();
|
||||||
|
const e = enc([part('a', 10, 5), part('b', 8, 2), part('c', 15, 0)]);
|
||||||
|
|
||||||
|
const out = await rerollAllInitiatives(e, ctx);
|
||||||
|
|
||||||
|
for (const id of ['a', 'b', 'c']) {
|
||||||
|
const p = find(out, id);
|
||||||
|
const mod = id === 'a' ? 5 : id === 'b' ? 2 : 0;
|
||||||
|
expect(p.initiative).toBeGreaterThanOrEqual(mod + 1);
|
||||||
|
expect(p.initiative).toBeLessThanOrEqual(mod + 20);
|
||||||
|
}
|
||||||
|
// one write for the whole operation
|
||||||
|
expect(storage.calls.filter(c => c.fn === 'updateDoc' && c.path === 'encounters/e1')).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('undo restores exact old initiatives and order', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
const e = enc([part('a', 10, 5), part('b', 8, 2)]);
|
||||||
|
const orderBefore = [...e.turnOrderIds];
|
||||||
|
|
||||||
|
const out = await rerollAllInitiatives(e, ctx);
|
||||||
|
|
||||||
|
const undone = await undoLast(ctx, out);
|
||||||
|
expect(find(undone, 'a').initiative).toBe(10);
|
||||||
|
expect(find(undone, 'b').initiative).toBe(8);
|
||||||
|
expect(undone.turnOrderIds).toEqual(orderBefore);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('inactive participants rerolled too (they stay inactive)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
const e = enc([part('a', 10, 1), part('b', 9, 1, { isActive: false })]);
|
||||||
|
|
||||||
|
const out = await rerollAllInitiatives(e, ctx);
|
||||||
|
expect(find(out, 'b').isActive).toBe(false);
|
||||||
|
expect(find(out, 'b').initiative).toBeGreaterThanOrEqual(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws during active combat (not paused)', async () => {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([part('a', 10, 1)]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
|
||||||
|
await expect(rerollAllInitiatives({ ...e, isPaused: false }, ctx)).rejects.toThrow(/paused/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Stable regain hours: stabilization rolls 1d4, persists until healed/revived.
|
||||||
|
// 3rd death save -> stable; manual stabilize -> stable; revive dead -> stable (5e).
|
||||||
|
|
||||||
|
const {
|
||||||
|
makeParticipant,
|
||||||
|
startEncounter,
|
||||||
|
applyHpChange,
|
||||||
|
deathSave,
|
||||||
|
stabilizeParticipant,
|
||||||
|
reviveParticipant,
|
||||||
|
} = require('@ttrpg/shared');
|
||||||
|
const { mockCtx } = require('./_helpers');
|
||||||
|
|
||||||
|
function pc(id, extra = {}) {
|
||||||
|
return makeParticipant({
|
||||||
|
id,
|
||||||
|
name: id,
|
||||||
|
type: 'character',
|
||||||
|
initiative: 10,
|
||||||
|
maxHp: 100,
|
||||||
|
currentHp: 100,
|
||||||
|
...extra,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function enc(participants, extra = {}) {
|
||||||
|
return {
|
||||||
|
id: 'e1',
|
||||||
|
name: 'stable-hours-test',
|
||||||
|
participants,
|
||||||
|
isStarted: false,
|
||||||
|
isPaused: false,
|
||||||
|
round: 0,
|
||||||
|
currentTurnParticipantId: null,
|
||||||
|
turnOrderIds: [],
|
||||||
|
...extra,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const part = e => e.participants.find(p => p.id === 'a');
|
||||||
|
|
||||||
|
async function dyingEnc() {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
let e = enc([pc('a')]);
|
||||||
|
e = await startEncounter(e, ctx);
|
||||||
|
e = await applyHpChange(e, 'a', 'damage', 100, ctx);
|
||||||
|
return { e, ctx };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('stableRegainHours', () => {
|
||||||
|
test('3rd death save success rolls 1d4 and stores stableRegainHours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
let out = e;
|
||||||
|
for (let i = 0; i < 3; i++) out = (await deathSave(out, 'a', 'success', ctx)).enc;
|
||||||
|
const p = part(out);
|
||||||
|
expect(p.status).toBe('stable');
|
||||||
|
expect(p.stableRegainHours).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(p.stableRegainHours).toBeLessThanOrEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('manual stabilize also rolls and stores hours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
const out = await stabilizeParticipant(e, 'a', ctx);
|
||||||
|
const p = part(out);
|
||||||
|
expect(p.status).toBe('stable');
|
||||||
|
expect(p.stableRegainHours).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(p.stableRegainHours).toBeLessThanOrEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('heal clears stableRegainHours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
let out = await stabilizeParticipant(e, 'a', ctx);
|
||||||
|
expect(part(out).stableRegainHours).toBeGreaterThanOrEqual(1);
|
||||||
|
out = await applyHpChange(out, 'a', 'heal', 5, ctx);
|
||||||
|
expect(part(out).status).toBe('conscious');
|
||||||
|
expect(part(out).stableRegainHours == null).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reviveParticipant to stable rolls fresh hours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
let out = e;
|
||||||
|
for (let i = 0; i < 3; i++) out = (await deathSave(out, 'a', 'fail', ctx)).enc;
|
||||||
|
expect(part(out).status).toBe('dead');
|
||||||
|
out = await reviveParticipant(out, 'a', ctx);
|
||||||
|
const p = part(out);
|
||||||
|
expect(p.status).toBe('stable');
|
||||||
|
expect(p.stableRegainHours).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(p.stableRegainHours).toBeLessThanOrEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dying (not yet stable) has no stableRegainHours', async () => {
|
||||||
|
const { e, ctx } = await dyingEnc();
|
||||||
|
const out = (await deathSave(e, 'a', 'fail', ctx)).enc;
|
||||||
|
expect(part(out).status).toBe('dying');
|
||||||
|
expect(part(out).stableRegainHours == null).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
// Temp HP: damage hits temp first, then regular.
|
||||||
|
// setTempHp replaces (no stacking). Healing regular HP ignores temp.
|
||||||
|
const shared = require('@ttrpg/shared');
|
||||||
|
const { makeParticipant, applyHpChange, setTempHp, addParticipant } = shared;
|
||||||
|
const { mockCtx } = require('./_helpers');
|
||||||
|
|
||||||
|
function setupEnc() {
|
||||||
|
const { ctx } = mockCtx();
|
||||||
|
return {
|
||||||
|
enc: { id: 'enc1', name: 'TempEnc', participants: [], isStarted: false, isPaused: false, round: 0 },
|
||||||
|
ctx,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('temp HP', () => {
|
||||||
|
test('setTempHp sets tempHp on participant', async () => {
|
||||||
|
const { enc, ctx } = setupEnc();
|
||||||
|
const p = makeParticipant({
|
||||||
|
name: 'Hero', type: 'character', initiative: 10, maxHp: 20, currentHp: 20,
|
||||||
|
});
|
||||||
|
let e = await addParticipant(enc, p, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 5, ctx);
|
||||||
|
expect(e.participants[0].tempHp).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('setTempHp replaces existing temp (no stacking)', async () => {
|
||||||
|
const { enc, ctx } = setupEnc();
|
||||||
|
const p = makeParticipant({
|
||||||
|
name: 'Hero', type: 'character', initiative: 10, maxHp: 20, currentHp: 20,
|
||||||
|
});
|
||||||
|
let e = await addParticipant(enc, p, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 5, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 3, ctx);
|
||||||
|
expect(e.participants[0].tempHp).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('setTempHp to 0 clears temp', async () => {
|
||||||
|
const { enc, ctx } = setupEnc();
|
||||||
|
const p = makeParticipant({
|
||||||
|
name: 'Hero', type: 'character', initiative: 10, maxHp: 20, currentHp: 20,
|
||||||
|
});
|
||||||
|
let e = await addParticipant(enc, p, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 5, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 0, ctx);
|
||||||
|
expect(e.participants[0].tempHp).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('damage: temp absorbs before regular HP', async () => {
|
||||||
|
const { enc, ctx } = setupEnc();
|
||||||
|
const p = makeParticipant({
|
||||||
|
name: 'Hero', type: 'character', initiative: 10, maxHp: 20, currentHp: 20,
|
||||||
|
});
|
||||||
|
let e = await addParticipant(enc, p, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 5, ctx);
|
||||||
|
e = await applyHpChange(e, p.id, 'damage', 8, ctx);
|
||||||
|
expect(e.participants[0].tempHp).toBe(0);
|
||||||
|
expect(e.participants[0].currentHp).toBe(17);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('damage less than temp: only temp reduced', async () => {
|
||||||
|
const { enc, ctx } = setupEnc();
|
||||||
|
const p = makeParticipant({
|
||||||
|
name: 'Hero', type: 'character', initiative: 10, maxHp: 20, currentHp: 20,
|
||||||
|
});
|
||||||
|
let e = await addParticipant(enc, p, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 10, ctx);
|
||||||
|
e = await applyHpChange(e, p.id, 'damage', 4, ctx);
|
||||||
|
expect(e.participants[0].tempHp).toBe(6);
|
||||||
|
expect(e.participants[0].currentHp).toBe(20);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('heal: does not affect temp HP', async () => {
|
||||||
|
const { enc, ctx } = setupEnc();
|
||||||
|
const p = makeParticipant({
|
||||||
|
name: 'Hero', type: 'character', initiative: 10, maxHp: 20, currentHp: 10,
|
||||||
|
});
|
||||||
|
let e = await addParticipant(enc, p, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 5, ctx);
|
||||||
|
e = await applyHpChange(e, p.id, 'heal', 8, ctx);
|
||||||
|
expect(e.participants[0].tempHp).toBe(5);
|
||||||
|
expect(e.participants[0].currentHp).toBe(18);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('damage exactly equals temp: temp gone, regular intact', async () => {
|
||||||
|
const { enc, ctx } = setupEnc();
|
||||||
|
const p = makeParticipant({
|
||||||
|
name: 'Hero', type: 'character', initiative: 10, maxHp: 20, currentHp: 20,
|
||||||
|
});
|
||||||
|
let e = await addParticipant(enc, p, ctx);
|
||||||
|
e = await setTempHp(e, p.id, 5, ctx);
|
||||||
|
e = await applyHpChange(e, p.id, 'damage', 5, ctx);
|
||||||
|
expect(e.participants[0].tempHp).toBe(0);
|
||||||
|
expect(e.participants[0].currentHp).toBe(20);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('makeParticipant: tempHp defaults to 0', async () => {
|
||||||
|
const p = makeParticipant({
|
||||||
|
name: 'Hero', type: 'character', initiative: 10, maxHp: 20, currentHp: 20,
|
||||||
|
});
|
||||||
|
expect(p.tempHp).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -29,7 +29,13 @@ function enc(ps) {
|
|||||||
return { name:'t', participants:ps, isStarted:false, isPaused:false,
|
return { name:'t', participants:ps, isStarted:false, isPaused:false,
|
||||||
round:0, currentTurnParticipantId:null, turnOrderIds:[] };
|
round:0, currentTurnParticipantId:null, turnOrderIds:[] };
|
||||||
}
|
}
|
||||||
const snap = (e) => JSON.parse(JSON.stringify(e));
|
const snap = (e) => {
|
||||||
|
const o = JSON.parse(JSON.stringify(e));
|
||||||
|
// normalize nullable timestamp fields: null = absent (undo clears via null)
|
||||||
|
if (o.startedAt === null) delete o.startedAt;
|
||||||
|
if (o.endedAt === null) delete o.endedAt;
|
||||||
|
return o;
|
||||||
|
};
|
||||||
|
|
||||||
describe('undo + redo roundtrip', () => {
|
describe('undo + redo roundtrip', () => {
|
||||||
test('startEncounter', async () => {
|
test('startEncounter', async () => {
|
||||||
|
|||||||
@@ -0,0 +1,316 @@
|
|||||||
|
// Character writeback on endEncounter: sync maxHp/ac to campaign players.
|
||||||
|
const shared = require('@ttrpg/shared');
|
||||||
|
const { endEncounter } = shared;
|
||||||
|
|
||||||
|
function makeMockStorage() {
|
||||||
|
const docs = new Map();
|
||||||
|
const writes = [];
|
||||||
|
return {
|
||||||
|
getDoc: jest.fn(async (p) => docs.get(p) || null),
|
||||||
|
setDoc: jest.fn(async (p, d) => { docs.set(p, d); }),
|
||||||
|
updateDoc: jest.fn(async (p, patch) => {
|
||||||
|
writes.push({ path: p, patch });
|
||||||
|
const cur = docs.get(p) || {};
|
||||||
|
docs.set(p, { ...cur, ...patch });
|
||||||
|
}),
|
||||||
|
addDoc: jest.fn(async (p, data) => {
|
||||||
|
writes.push({ path: p, patch: data });
|
||||||
|
docs.set(p, data);
|
||||||
|
}),
|
||||||
|
deleteDoc: jest.fn(async () => {}),
|
||||||
|
getCollection: jest.fn(async () => []),
|
||||||
|
_docs: docs,
|
||||||
|
_writes: writes,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeEncounter(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: 'enc1',
|
||||||
|
name: 'Test',
|
||||||
|
campaignId: 'camp1',
|
||||||
|
isStarted: true,
|
||||||
|
isPaused: false,
|
||||||
|
currentTurnParticipantId: 'p1',
|
||||||
|
round: 3,
|
||||||
|
turnOrderIds: ['p1', 'p2'],
|
||||||
|
participants: [
|
||||||
|
{ id: 'p1', name: 'Fighter', type: 'character', originalCharacterId: 'char1', initiative: 15, maxHp: 28, currentHp: 20, ac: 18 },
|
||||||
|
{ id: 'p2', name: 'Goblin', type: 'monster', originalCharacterId: null, initiative: 12, maxHp: 7, currentHp: 7, ac: 13 },
|
||||||
|
{ id: 'p3', name: 'Cleric', type: 'character', originalCharacterId: 'char2', initiative: 10, maxHp: 22, currentHp: 22, ac: 16 },
|
||||||
|
],
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('character writeback on endEncounter', () => {
|
||||||
|
test('no writeback when syncCharacters false/missing', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
storage._docs.set('campaigns/camp1', {
|
||||||
|
id: 'camp1', name: 'Camp', players: [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
await endEncounter(enc, ctx);
|
||||||
|
// no campaign write
|
||||||
|
expect(storage._writes.find(w => w.path === 'campaigns/camp1')).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('writeback updates char maxHp + ac + currentHp when syncCharacters true', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 },
|
||||||
|
{ id: 'char2', name: 'Cleric', defaultMaxHp: 20, defaultAc: 14, defaultCurrentHp: 20 },
|
||||||
|
];
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
await endEncounter(enc, ctx);
|
||||||
|
const campWrite = storage._writes.find(w => w.path === 'campaigns/camp1');
|
||||||
|
expect(campWrite).toBeDefined();
|
||||||
|
const updated = campWrite.patch.players;
|
||||||
|
const fighter = updated.find(p => p.id === 'char1');
|
||||||
|
expect(fighter.defaultMaxHp).toBe(28);
|
||||||
|
expect(fighter.defaultAc).toBe(18);
|
||||||
|
expect(fighter.defaultCurrentHp).toBe(20);
|
||||||
|
const cleric = updated.find(p => p.id === 'char2');
|
||||||
|
expect(cleric.defaultMaxHp).toBe(22);
|
||||||
|
expect(cleric.defaultAc).toBe(16);
|
||||||
|
expect(cleric.defaultCurrentHp).toBe(22);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('one-time ctx override enables writeback without persistent campaign setting', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
storage._docs.set('campaigns/camp1', {
|
||||||
|
id: 'camp1', name: 'Camp', syncCharacters: false, players: [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const enc = makeEncounter({ participants: [
|
||||||
|
{ id: 'p1', name: 'Fighter', type: 'character', originalCharacterId: 'char1', initiative: 15, maxHp: 28, currentHp: 11, ac: 19 },
|
||||||
|
] });
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
syncCharacters: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
await endEncounter(enc, ctx);
|
||||||
|
|
||||||
|
const campWrite = storage._writes.find(w => w.path === 'campaigns/camp1');
|
||||||
|
expect(campWrite).toBeDefined();
|
||||||
|
expect(campWrite.patch.players[0]).toMatchObject({ defaultMaxHp: 28, defaultCurrentHp: 11, defaultAc: 19 });
|
||||||
|
expect(storage._docs.get('campaigns/camp1').syncCharacters).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('one-time ctx override disables writeback despite persistent campaign setting', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
storage._docs.set('campaigns/camp1', {
|
||||||
|
id: 'camp1', name: 'Camp', syncCharacters: true, players: [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await endEncounter(makeEncounter(), {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
syncCharacters: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(storage._writes.find(w => w.path === 'campaigns/camp1')).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('writeback skips monsters (no originalCharacterId)', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17 }];
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
await endEncounter(enc, ctx);
|
||||||
|
const campWrite = storage._writes.find(w => w.path === 'campaigns/camp1');
|
||||||
|
// players array still 1 entry, goblin not added
|
||||||
|
expect(campWrite.patch.players.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('undo payload includes old char values for restore', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 },
|
||||||
|
{ id: 'char2', name: 'Cleric', defaultMaxHp: 20, defaultAc: 14, defaultCurrentHp: 20 },
|
||||||
|
];
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
storage._docs.set('logs/log1', null);
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
await endEncounter(enc, ctx);
|
||||||
|
const logWrite = storage._writes.find(w => w.path === 'logs/log1');
|
||||||
|
expect(logWrite).toBeDefined();
|
||||||
|
const log = logWrite.patch;
|
||||||
|
expect(log.undo.characterWriteback).toBeDefined();
|
||||||
|
expect(log.undo.characterWriteback).toHaveLength(2);
|
||||||
|
const fighterOld = log.undo.characterWriteback.find(c => c.id === 'char1');
|
||||||
|
expect(fighterOld.defaultMaxHp).toBe(30);
|
||||||
|
expect(fighterOld.defaultAc).toBe(17);
|
||||||
|
expect(fighterOld.defaultCurrentHp).toBe(30);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('writeback uses ctx.campaignPath when provided (firebase prefixed paths)', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 }];
|
||||||
|
const prefixed = 'artifacts/app1/public/data/campaigns/camp1';
|
||||||
|
storage._docs.set(prefixed, { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
campaignPath: prefixed,
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
await endEncounter(enc, ctx);
|
||||||
|
expect(storage._writes.find(w => w.path === 'campaigns/camp1')).toBeUndefined();
|
||||||
|
const campWrite = storage._writes.find(w => w.path === prefixed);
|
||||||
|
expect(campWrite).toBeDefined();
|
||||||
|
expect(campWrite.patch.players.find(p => p.id === 'char1').defaultMaxHp).toBe(28);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('writeback failure does not block ending combat', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 }];
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
storage.updateDoc = jest.fn(async (p, patch) => {
|
||||||
|
if (p === 'campaigns/camp1') throw new Error('No document to update');
|
||||||
|
storage._writes.push({ path: p, patch });
|
||||||
|
});
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
encPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
const newEnc = await endEncounter(enc, ctx);
|
||||||
|
expect(newEnc.isStarted).toBe(false);
|
||||||
|
expect(newEnc.currentTurnParticipantId).toBe(null);
|
||||||
|
// participants are preserved — ending combat never clears the roster
|
||||||
|
expect(newEnc.participants).toHaveLength(3);
|
||||||
|
const encWrite = storage._writes.find(w => w.path === 'campaigns/camp1/encounters/enc1');
|
||||||
|
expect(encWrite).toBeDefined();
|
||||||
|
expect(encWrite.patch.isStarted).toBe(false);
|
||||||
|
expect(encWrite.patch.participants).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('writeback no-op if character missing from campaign', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players: [], syncCharacters: true });
|
||||||
|
const enc = makeEncounter();
|
||||||
|
const ctx = {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
await endEncounter(enc, ctx);
|
||||||
|
// no writeback (no matching chars = no change)
|
||||||
|
expect(storage._writes.find(w => w.path === 'campaigns/camp1')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('stable regain hours writeback', () => {
|
||||||
|
function ctxFor(storage) {
|
||||||
|
return {
|
||||||
|
storage,
|
||||||
|
encounterPath: 'campaigns/camp1/encounters/enc1',
|
||||||
|
logPath: 'logs/log1',
|
||||||
|
logCollection: 'logs',
|
||||||
|
displayPath: 'activeDisplay/status',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('stable char carries stableRegainHours to roster', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30 },
|
||||||
|
];
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
const enc = makeEncounter({
|
||||||
|
participants: [
|
||||||
|
{ id: 'p1', name: 'Fighter', type: 'character', originalCharacterId: 'char1', initiative: 15, maxHp: 30, currentHp: 0, ac: 17, status: 'stable', stableRegainHours: 3 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await endEncounter(enc, ctxFor(storage));
|
||||||
|
const campWrite = storage._writes.find(w => w.path === 'campaigns/camp1');
|
||||||
|
expect(campWrite).toBeDefined();
|
||||||
|
const fighter = campWrite.patch.players.find(p => p.id === 'char1');
|
||||||
|
expect(fighter.stableRegainHours).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('conscious char clears stale roster stableRegainHours', async () => {
|
||||||
|
const storage = makeMockStorage();
|
||||||
|
const players = [
|
||||||
|
{ id: 'char1', name: 'Fighter', defaultMaxHp: 30, defaultAc: 17, defaultCurrentHp: 30, stableRegainHours: 2 },
|
||||||
|
];
|
||||||
|
storage._docs.set('campaigns/camp1', { id: 'camp1', name: 'Camp', players, syncCharacters: true });
|
||||||
|
const enc = makeEncounter({
|
||||||
|
participants: [
|
||||||
|
{ id: 'p1', name: 'Fighter', type: 'character', originalCharacterId: 'char1', initiative: 15, maxHp: 30, currentHp: 12, ac: 17, status: 'conscious' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await endEncounter(enc, ctxFor(storage));
|
||||||
|
const campWrite = storage._writes.find(w => w.path === 'campaigns/camp1');
|
||||||
|
expect(campWrite).toBeDefined();
|
||||||
|
const fighter = campWrite.patch.players.find(p => p.id === 'char1');
|
||||||
|
expect(fighter.stableRegainHours).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('buildCharacterParticipant carries stable state', () => {
|
||||||
|
const { buildCharacterParticipant } = shared;
|
||||||
|
|
||||||
|
test('roster stable char becomes stable participant with hours', () => {
|
||||||
|
const char = { id: 'c1', name: 'Rogue', defaultMaxHp: 40, defaultCurrentHp: 0, defaultInitMod: 2, stableRegainHours: 4 };
|
||||||
|
const { participant } = buildCharacterParticipant(char);
|
||||||
|
expect(participant.currentHp).toBe(0);
|
||||||
|
expect(participant.status).toBe('stable');
|
||||||
|
expect(participant.stableRegainHours).toBe(4);
|
||||||
|
expect(participant.conditions).toContain('unconscious');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('healthy roster char stays conscious, no hours', () => {
|
||||||
|
const char = { id: 'c2', name: 'Cleric', defaultMaxHp: 30, defaultCurrentHp: 30, defaultInitMod: 1 };
|
||||||
|
const { participant } = buildCharacterParticipant(char);
|
||||||
|
expect(participant.status).toBe('conscious');
|
||||||
|
expect(participant.stableRegainHours).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
+580
-47
@@ -27,6 +27,23 @@ const generateId = () =>
|
|||||||
: `id_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
: `id_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
|
||||||
const rollD20 = () => Math.floor(Math.random() * 20) + 1;
|
const rollD20 = () => Math.floor(Math.random() * 20) + 1;
|
||||||
|
const rollD4 = () => Math.floor(Math.random() * 4) + 1;
|
||||||
|
|
||||||
|
// Parse HP formula like "2d6+9" or "3d8-2" or "1d20". Roll, return total.
|
||||||
|
// Returns null on invalid input. Whitespace/case tolerant.
|
||||||
|
function rollHpFormula(str) {
|
||||||
|
if (!str || typeof str !== 'string') return null;
|
||||||
|
const m = str.trim().toLowerCase().match(/^(\d+)d(\d+)\s*([+-]\s*\d+)?$/);
|
||||||
|
if (!m) return null;
|
||||||
|
const count = parseInt(m[1], 10);
|
||||||
|
const sides = parseInt(m[2], 10);
|
||||||
|
if (count === 0 || sides === 0) return null;
|
||||||
|
let bonus = 0;
|
||||||
|
if (m[3]) bonus = parseInt(m[3].replace(/\s/g, ''), 10);
|
||||||
|
let total = 0;
|
||||||
|
for (let i = 0; i < count; i++) total += Math.floor(Math.random() * sides) + 1;
|
||||||
|
return total + bonus;
|
||||||
|
}
|
||||||
|
|
||||||
const formatInitMod = (mod) => {
|
const formatInitMod = (mod) => {
|
||||||
if (mod === undefined || mod === null) return 'N/A';
|
if (mod === undefined || mod === null) return 'N/A';
|
||||||
@@ -102,6 +119,8 @@ function snapshotOf(enc) {
|
|||||||
currentTurnParticipantId: enc.currentTurnParticipantId ?? null,
|
currentTurnParticipantId: enc.currentTurnParticipantId ?? null,
|
||||||
turnOrderIds: [...(enc.turnOrderIds || [])],
|
turnOrderIds: [...(enc.turnOrderIds || [])],
|
||||||
activeIds: (enc.participants || []).filter(p => p.isActive).map(p => p.id),
|
activeIds: (enc.participants || []).filter(p => p.isActive).map(p => p.id),
|
||||||
|
startedAt: enc.startedAt ?? null,
|
||||||
|
endedAt: enc.endedAt ?? null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,6 +199,16 @@ function expandUndo(entry, currentEnc) {
|
|||||||
: { participants: [...parts, ...added.filter(p => !parts.some(x => x.id === p.id))] },
|
: { participants: [...parts, ...added.filter(p => !parts.some(x => x.id === p.id))] },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
case 'reroll_all_init': {
|
||||||
|
// undo: restore pre-reroll array + order. redo: re-apply rolled array.
|
||||||
|
return {
|
||||||
|
encounterPath: encPath,
|
||||||
|
updates: { participants: u.participants.map(p => ({ ...p })), turnOrderIds: u.turnOrderIds },
|
||||||
|
redo: u.newParticipants && u.newTurnOrderIds
|
||||||
|
? { participants: u.newParticipants.map(p => ({ ...p })), turnOrderIds: u.newTurnOrderIds }
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
case 'remove_participant': {
|
case 'remove_participant': {
|
||||||
const p = u.participant;
|
const p = u.participant;
|
||||||
const turnState = {};
|
const turnState = {};
|
||||||
@@ -204,9 +233,12 @@ function expandUndo(entry, currentEnc) {
|
|||||||
}
|
}
|
||||||
case 'damage':
|
case 'damage':
|
||||||
case 'heal':
|
case 'heal':
|
||||||
|
case 'hp_change':
|
||||||
case 'death_save':
|
case 'death_save':
|
||||||
case 'stabilize':
|
case 'stabilize':
|
||||||
case 'revive':
|
case 'revive':
|
||||||
|
case 'heal_full':
|
||||||
|
case 'mark_dead':
|
||||||
case 'deactivate_dead_monster': {
|
case 'deactivate_dead_monster': {
|
||||||
// Full death-state restore: currentHp, status, death-save counters,
|
// Full death-state restore: currentHp, status, death-save counters,
|
||||||
// isActive, conditions (unconscious added/removed by withDeathStatusConditions).
|
// isActive, conditions (unconscious added/removed by withDeathStatusConditions).
|
||||||
@@ -218,17 +250,34 @@ function expandUndo(entry, currentEnc) {
|
|||||||
const restoreFields = (vals) => {
|
const restoreFields = (vals) => {
|
||||||
const out = {};
|
const out = {};
|
||||||
if (vals.currentHp !== undefined) out.currentHp = vals.currentHp;
|
if (vals.currentHp !== undefined) out.currentHp = vals.currentHp;
|
||||||
|
if (vals.tempHp !== undefined) out.tempHp = vals.tempHp;
|
||||||
if (vals.status !== undefined) out.status = vals.status;
|
if (vals.status !== undefined) out.status = vals.status;
|
||||||
if (vals.deathSaveSuccesses !== undefined) out.deathSaveSuccesses = vals.deathSaveSuccesses;
|
if (vals.deathSaveSuccesses !== undefined) out.deathSaveSuccesses = vals.deathSaveSuccesses;
|
||||||
if (vals.deathSaveFailures !== undefined) out.deathSaveFailures = vals.deathSaveFailures;
|
if (vals.deathSaveFailures !== undefined) out.deathSaveFailures = vals.deathSaveFailures;
|
||||||
|
if (vals.stableRegainHours !== undefined) out.stableRegainHours = vals.stableRegainHours;
|
||||||
if (vals.isActive !== undefined) out.isActive = vals.isActive;
|
if (vals.isActive !== undefined) out.isActive = vals.isActive;
|
||||||
if (vals.conditions !== undefined) out.conditions = vals.conditions;
|
if (vals.conditions !== undefined) out.conditions = vals.conditions;
|
||||||
return out;
|
return out;
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
encounterPath: encPath,
|
encounterPath: encPath,
|
||||||
updates: { participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(oldVals) } : p) },
|
updates: {
|
||||||
redo: { participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(newVals) } : p) },
|
participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(oldVals) } : p),
|
||||||
|
...(u.oldEffects ? { effects: u.oldEffects } : {}),
|
||||||
|
},
|
||||||
|
redo: {
|
||||||
|
participants: parts.map(p => p.id === pid ? { ...p, ...restoreFields(newVals) } : p),
|
||||||
|
...(u.newEffects ? { effects: u.newEffects } : {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'add_effect':
|
||||||
|
case 'update_effect':
|
||||||
|
case 'remove_effect': {
|
||||||
|
return {
|
||||||
|
encounterPath: encPath,
|
||||||
|
updates: { effects: u.oldEffects || [] },
|
||||||
|
redo: { effects: u.newEffects || [] },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
case 'add_condition':
|
case 'add_condition':
|
||||||
@@ -286,30 +335,36 @@ function expandUndo(entry, currentEnc) {
|
|||||||
const redoOrdered = u.newTurnOrderIds.map(id => redoPool.get(id)).filter(Boolean);
|
const redoOrdered = u.newTurnOrderIds.map(id => redoPool.get(id)).filter(Boolean);
|
||||||
return {
|
return {
|
||||||
encounterPath: encPath,
|
encounterPath: encPath,
|
||||||
updates: { participants: undoOrdered, turnOrderIds: u.oldTurnOrderIds },
|
updates: { participants: undoOrdered, turnOrderIds: u.oldTurnOrderIds, ...(u.oldEffects ? { effects: u.oldEffects } : {}) },
|
||||||
redo: { participants: redoOrdered, turnOrderIds: u.newTurnOrderIds },
|
redo: { participants: redoOrdered, turnOrderIds: u.newTurnOrderIds, ...(u.newEffects ? { effects: u.newEffects } : {}) },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
encounterPath: encPath,
|
encounterPath: encPath,
|
||||||
updates: { participants: applyFields(oldVals) },
|
updates: { participants: applyFields(oldVals), ...(u.oldEffects ? { effects: u.oldEffects } : {}) },
|
||||||
redo: { participants: applyFields(newVals), ...(u.newTurnOrderIds ? { turnOrderIds: u.newTurnOrderIds } : {}) },
|
redo: { participants: applyFields(newVals), ...(u.newTurnOrderIds ? { turnOrderIds: u.newTurnOrderIds } : {}), ...(u.newEffects ? { effects: u.newEffects } : {}) },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
case 'next_turn':
|
case 'next_turn':
|
||||||
case 'auto_end': {
|
case 'auto_end': {
|
||||||
return {
|
return {
|
||||||
encounterPath: encPath,
|
encounterPath: encPath,
|
||||||
updates: { currentTurnParticipantId: u.currentTurnParticipantId, round: u.round, ...(u.turnOrderIds ? { turnOrderIds: u.turnOrderIds } : {}) },
|
updates: { currentTurnParticipantId: u.currentTurnParticipantId, round: u.round, ...(u.turnOrderIds ? { turnOrderIds: u.turnOrderIds } : {}), ...(u.oldEffects ? { effects: u.oldEffects } : {}) },
|
||||||
redo: { currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [] },
|
redo: { currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [], ...(u.newEffects ? { effects: u.newEffects } : {}) },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'start_encounter': {
|
||||||
|
return {
|
||||||
|
encounterPath: encPath,
|
||||||
|
updates: { ...u, startedAt: u.startedAt ?? null },
|
||||||
|
redo: { isStarted: true, isPaused: false, currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [], startedAt: snap.startedAt ?? Date.now() },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
case 'start_encounter':
|
|
||||||
case 'end_encounter': {
|
case 'end_encounter': {
|
||||||
return {
|
return {
|
||||||
encounterPath: encPath,
|
encounterPath: encPath,
|
||||||
updates: u,
|
updates: { ...u, endedAt: u.endedAt ?? null },
|
||||||
redo: { isStarted: entry.type === 'start_encounter', isPaused: false, currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [] },
|
redo: { isStarted: false, isPaused: false, currentTurnParticipantId: snap.currentTurnParticipantId, round: snap.round, turnOrderIds: snap.turnOrderIds || [], endedAt: snap.endedAt ?? Date.now() },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -321,6 +376,41 @@ function expandUndo(entry, currentEnc) {
|
|||||||
// Participant factories (pure — no write)
|
// Participant factories (pure — no write)
|
||||||
// ----------------------------------------------------------------------------
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function makeEffect(opts = {}) {
|
||||||
|
const rounds = Number(opts.remainingRounds);
|
||||||
|
return {
|
||||||
|
id: opts.id || generateId(),
|
||||||
|
presetId: opts.presetId || 'custom',
|
||||||
|
name: String(opts.name || 'Effect').trim() || 'Effect',
|
||||||
|
scope: opts.scope === 'encounter' ? 'encounter' : 'participant',
|
||||||
|
targetParticipantId: opts.scope === 'encounter' ? null : (opts.targetParticipantId || null),
|
||||||
|
ownerParticipantId: opts.ownerParticipantId || null,
|
||||||
|
remainingRounds: Number.isFinite(rounds) ? Math.max(1, Math.floor(rounds)) : 1,
|
||||||
|
expiresOnDamage: !!opts.expiresOnDamage,
|
||||||
|
playerDisplay: ['hidden', 'compact', 'prominent'].includes(opts.playerDisplay) ? opts.playerDisplay : 'compact',
|
||||||
|
notes: String(opts.notes || '').trim(),
|
||||||
|
createdRound: Number.isFinite(Number(opts.createdRound)) ? Number(opts.createdRound) : 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function tickRoundEffects(effects) {
|
||||||
|
return (effects || [])
|
||||||
|
.map(effect => ({ ...effect, remainingRounds: Math.max(0, (effect.remainingRounds || 0) - 1) }))
|
||||||
|
.filter(effect => effect.remainingRounds > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function expireDamageEffects(effects, participantId) {
|
||||||
|
return (effects || []).filter(effect => !(
|
||||||
|
effect.scope === 'participant' &&
|
||||||
|
effect.targetParticipantId === participantId &&
|
||||||
|
effect.expiresOnDamage
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
function effectsChanged(before, after) {
|
||||||
|
return JSON.stringify(before || []) !== JSON.stringify(after || []);
|
||||||
|
}
|
||||||
|
|
||||||
function makeParticipant(opts) {
|
function makeParticipant(opts) {
|
||||||
return {
|
return {
|
||||||
id: opts.id || generateId(),
|
id: opts.id || generateId(),
|
||||||
@@ -328,6 +418,7 @@ function makeParticipant(opts) {
|
|||||||
type: opts.type,
|
type: opts.type,
|
||||||
originalCharacterId: opts.originalCharacterId || null,
|
originalCharacterId: opts.originalCharacterId || null,
|
||||||
initiative: opts.initiative,
|
initiative: opts.initiative,
|
||||||
|
initMod: opts.initMod !== undefined ? opts.initMod : null,
|
||||||
maxHp: opts.maxHp,
|
maxHp: opts.maxHp,
|
||||||
currentHp: opts.currentHp,
|
currentHp: opts.currentHp,
|
||||||
conditions: opts.conditions || [],
|
conditions: opts.conditions || [],
|
||||||
@@ -335,41 +426,66 @@ function makeParticipant(opts) {
|
|||||||
status: opts.status || (opts.currentHp === 0 ? 'dying' : 'conscious'),
|
status: opts.status || (opts.currentHp === 0 ? 'dying' : 'conscious'),
|
||||||
deathSaveSuccesses: opts.deathSaveSuccesses || 0,
|
deathSaveSuccesses: opts.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: opts.deathSaveFailures || 0,
|
deathSaveFailures: opts.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: opts.stableRegainHours !== undefined ? opts.stableRegainHours : null,
|
||||||
|
hpFormula: opts.hpFormula || null,
|
||||||
|
ac: opts.ac !== undefined ? opts.ac : null,
|
||||||
|
tempHp: opts.tempHp !== undefined ? opts.tempHp : 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildCharacterParticipant(character) {
|
function buildCharacterParticipant(character, initiativeRoll = rollD20()) {
|
||||||
const initiativeRoll = rollD20();
|
|
||||||
const modifier = character.defaultInitMod || 0;
|
const modifier = character.defaultInitMod || 0;
|
||||||
const finalInitiative = initiativeRoll + modifier;
|
const finalInitiative = initiativeRoll + modifier;
|
||||||
const maxHp = character.defaultMaxHp || DEFAULT_MAX_HP;
|
const maxHp = character.defaultMaxHp || DEFAULT_MAX_HP;
|
||||||
|
const currentHp = character.defaultCurrentHp != null ? character.defaultCurrentHp : maxHp;
|
||||||
|
// Roster carried stable state (from writeback): still down at 0 HP, unconscious.
|
||||||
|
const isStable = currentHp === 0 && character.stableRegainHours != null;
|
||||||
return {
|
return {
|
||||||
participant: makeParticipant({
|
participant: makeParticipant({
|
||||||
name: character.name,
|
name: character.name,
|
||||||
type: 'character',
|
type: character.isNpc ? 'npc' : 'character',
|
||||||
originalCharacterId: character.id,
|
originalCharacterId: character.id,
|
||||||
initiative: finalInitiative,
|
initiative: finalInitiative,
|
||||||
|
initMod: modifier,
|
||||||
maxHp,
|
maxHp,
|
||||||
currentHp: maxHp,
|
currentHp,
|
||||||
|
status: isStable ? 'stable' : undefined,
|
||||||
|
stableRegainHours: isStable ? character.stableRegainHours : null,
|
||||||
|
conditions: isStable ? ['unconscious'] : [],
|
||||||
|
ac: character.defaultAc !== undefined ? character.defaultAc : null,
|
||||||
}),
|
}),
|
||||||
roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative },
|
roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildMonsterParticipant({ name, maxHp, initMod, asNpc }) {
|
function buildMonsterParticipant({ name, maxHp, initMod, asNpc, hpFormula, ac }) {
|
||||||
const initiativeRoll = rollD20();
|
const initiativeRoll = rollD20();
|
||||||
const modifier = initMod !== undefined ? initMod : MONSTER_DEFAULT_INIT_MOD;
|
const modifier = initMod !== undefined ? initMod : MONSTER_DEFAULT_INIT_MOD;
|
||||||
const finalInitiative = initiativeRoll + modifier;
|
const finalInitiative = initiativeRoll + modifier;
|
||||||
const hp = maxHp || DEFAULT_MAX_HP;
|
// maxHp wins if both set; else roll formula; else default.
|
||||||
|
let hp;
|
||||||
|
let hpRoll = null;
|
||||||
|
if (maxHp) {
|
||||||
|
hp = maxHp;
|
||||||
|
} else if (hpFormula) {
|
||||||
|
const rolled = rollHpFormula(hpFormula);
|
||||||
|
hp = rolled || DEFAULT_MAX_HP;
|
||||||
|
hpRoll = rolled;
|
||||||
|
} else {
|
||||||
|
hp = DEFAULT_MAX_HP;
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
participant: makeParticipant({
|
participant: makeParticipant({
|
||||||
name,
|
name,
|
||||||
type: asNpc ? 'npc' : 'monster',
|
type: asNpc ? 'npc' : 'monster',
|
||||||
initiative: finalInitiative,
|
initiative: finalInitiative,
|
||||||
|
initMod: modifier,
|
||||||
maxHp: hp,
|
maxHp: hp,
|
||||||
currentHp: hp,
|
currentHp: hp,
|
||||||
|
hpFormula: hpFormula || null,
|
||||||
|
ac: ac !== undefined ? ac : null,
|
||||||
}),
|
}),
|
||||||
roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative },
|
roll: { roll: initiativeRoll, mod: modifier, total: finalInitiative, hpRoll },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -390,6 +506,8 @@ async function startEncounter(encounter, ctx) {
|
|||||||
participants: sortedParticipants,
|
participants: sortedParticipants,
|
||||||
currentTurnParticipantId: firstActive.id,
|
currentTurnParticipantId: firstActive.id,
|
||||||
turnOrderIds: sortedParticipants.map(p => p.id),
|
turnOrderIds: sortedParticipants.map(p => p.id),
|
||||||
|
startedAt: Date.now(),
|
||||||
|
endedAt: null,
|
||||||
};
|
};
|
||||||
const log = {
|
const log = {
|
||||||
type: 'start_encounter',
|
type: 'start_encounter',
|
||||||
@@ -402,6 +520,8 @@ async function startEncounter(encounter, ctx) {
|
|||||||
round: encounter.round ?? 0,
|
round: encounter.round ?? 0,
|
||||||
currentTurnParticipantId: encounter.currentTurnParticipantId ?? null,
|
currentTurnParticipantId: encounter.currentTurnParticipantId ?? null,
|
||||||
turnOrderIds: [...(encounter.turnOrderIds || [])],
|
turnOrderIds: [...(encounter.turnOrderIds || [])],
|
||||||
|
startedAt: encounter.startedAt ?? null,
|
||||||
|
endedAt: encounter.endedAt ?? null,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
@@ -433,13 +553,25 @@ async function nextTurn(encounter, ctx) {
|
|||||||
if (!nextId) throw new Error('Could not determine next participant.');
|
if (!nextId) throw new Error('Could not determine next participant.');
|
||||||
if (wrapped) nextRound += 1;
|
if (wrapped) nextRound += 1;
|
||||||
const nextParticipant = encounter.participants.find(p => p.id === nextId);
|
const nextParticipant = encounter.participants.find(p => p.id === nextId);
|
||||||
const patch = { currentTurnParticipantId: nextParticipant.id, round: nextRound, turnOrderIds: encounter.turnOrderIds };
|
const oldEffects = [...(encounter.effects || [])];
|
||||||
|
const newEffects = wrapped ? tickRoundEffects(oldEffects) : oldEffects;
|
||||||
|
const patch = {
|
||||||
|
currentTurnParticipantId: nextParticipant.id,
|
||||||
|
round: nextRound,
|
||||||
|
turnOrderIds: encounter.turnOrderIds,
|
||||||
|
...(wrapped && effectsChanged(oldEffects, newEffects) ? { effects: newEffects } : {}),
|
||||||
|
};
|
||||||
const log = {
|
const log = {
|
||||||
type: 'next_turn',
|
type: 'next_turn',
|
||||||
participantId: nextParticipant.id, participantName: nextParticipant.name,
|
participantId: nextParticipant.id, participantName: nextParticipant.name,
|
||||||
message: `${nextParticipant.name}'s turn (Round ${nextRound})`,
|
message: `${nextParticipant.name}'s turn (Round ${nextRound})`,
|
||||||
delta: { wrapped, prevRound: encounter.round },
|
delta: { wrapped, prevRound: encounter.round },
|
||||||
undo: { currentTurnParticipantId: encounter.currentTurnParticipantId, round: encounter.round, turnOrderIds: [...encounter.turnOrderIds] },
|
undo: {
|
||||||
|
currentTurnParticipantId: encounter.currentTurnParticipantId,
|
||||||
|
round: encounter.round,
|
||||||
|
turnOrderIds: [...encounter.turnOrderIds],
|
||||||
|
...(wrapped ? { oldEffects, newEffects } : {}),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
@@ -478,14 +610,20 @@ async function addParticipant(encounter, participant, ctx) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function addParticipants(encounter, newParticipants, ctx) {
|
async function addParticipants(encounter, newParticipants, ctx) {
|
||||||
const updatedParticipants = [...(encounter.participants || []), ...newParticipants];
|
// Slot each new participant into list by initiative (desc), preserve
|
||||||
|
// existing order + drag-established ties. Matches addParticipant semantics.
|
||||||
|
let base = [...(encounter.participants || [])];
|
||||||
|
for (const np of newParticipants) {
|
||||||
|
const idx = slotIndexForInit(base, np.initiative);
|
||||||
|
base.splice(idx, 0, np);
|
||||||
|
}
|
||||||
const names = newParticipants.map(p => p.name).join(', ');
|
const names = newParticipants.map(p => p.name).join(', ');
|
||||||
const patch = { participants: updatedParticipants };
|
const patch = { participants: base, ...syncTurnOrder(base) };
|
||||||
const log = {
|
const log = {
|
||||||
type: 'add_participants',
|
type: 'add_participants',
|
||||||
message: `Added ${newParticipants.length} participant${newParticipants.length === 1 ? '' : 's'}: ${names}`,
|
message: `Added ${newParticipants.length} participant${newParticipants.length === 1 ? '' : 's'}: ${names}`,
|
||||||
delta: { count: newParticipants.length },
|
delta: { count: newParticipants.length },
|
||||||
undo: { participants: newParticipants },
|
undo: { participants: newParticipants, newTurnOrderIds: patch.turnOrderIds },
|
||||||
};
|
};
|
||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
@@ -498,29 +636,35 @@ async function updateParticipant(encounter, participantId, updatedData, ctx) {
|
|||||||
let patch;
|
let patch;
|
||||||
const oldValues = {};
|
const oldValues = {};
|
||||||
for (const k of Object.keys(updatedData)) oldValues[k] = target[k];
|
for (const k of Object.keys(updatedData)) oldValues[k] = target[k];
|
||||||
|
const oldEffects = [...(encounter.effects || [])];
|
||||||
|
const hpReduced = updatedData.currentHp !== undefined && Number(updatedData.currentHp) < Number(target.currentHp);
|
||||||
|
const newEffects = hpReduced ? expireDamageEffects(oldEffects, participantId) : oldEffects;
|
||||||
|
const effectChanged = effectsChanged(oldEffects, newEffects);
|
||||||
|
const effectPatch = effectChanged ? { effects: newEffects } : {};
|
||||||
|
const effectUndo = effectChanged ? { oldEffects, newEffects } : {};
|
||||||
if (!('initiative' in updatedData) || updatedData.initiative === target.initiative) {
|
if (!('initiative' in updatedData) || updatedData.initiative === target.initiative) {
|
||||||
const sameSlot = existing.map(p => p.id === participantId ? merged : p);
|
const sameSlot = existing.map(p => p.id === participantId ? merged : p);
|
||||||
const fields = Object.keys(updatedData).join(', ');
|
const fields = Object.keys(updatedData).join(', ');
|
||||||
patch = { participants: sameSlot, ...syncTurnOrder(sameSlot) };
|
patch = { participants: sameSlot, ...syncTurnOrder(sameSlot), ...effectPatch };
|
||||||
const log = {
|
const log = {
|
||||||
type: 'update_participant',
|
type: 'update_participant',
|
||||||
participantId, participantName: target.name,
|
participantId, participantName: target.name,
|
||||||
message: `${target.name} updated (${fields})`,
|
message: `${target.name} updated (${fields})`,
|
||||||
delta: { changedFields: Object.keys(updatedData) },
|
delta: { changedFields: Object.keys(updatedData) },
|
||||||
undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds },
|
undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds, ...effectUndo },
|
||||||
};
|
};
|
||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
} else {
|
} else {
|
||||||
const without = existing.filter(p => p.id !== participantId);
|
const without = existing.filter(p => p.id !== participantId);
|
||||||
const idx = slotIndexForInit(without, merged.initiative);
|
const idx = slotIndexForInit(without, merged.initiative);
|
||||||
without.splice(idx, 0, merged);
|
without.splice(idx, 0, merged);
|
||||||
patch = { participants: without, ...syncTurnOrder(without) };
|
patch = { participants: without, ...syncTurnOrder(without), ...effectPatch };
|
||||||
const log = {
|
const log = {
|
||||||
type: 'update_participant',
|
type: 'update_participant',
|
||||||
participantId, participantName: target.name,
|
participantId, participantName: target.name,
|
||||||
message: `${target.name} updated (initiative: ${merged.initiative})`,
|
message: `${target.name} updated (initiative: ${merged.initiative})`,
|
||||||
delta: { changedFields: Object.keys(updatedData), initiative: merged.initiative },
|
delta: { changedFields: Object.keys(updatedData), initiative: merged.initiative },
|
||||||
undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds },
|
undo: { oldValues, newValues: { ...updatedData }, oldTurnOrderIds: encounter.turnOrderIds || [], newTurnOrderIds: patch.turnOrderIds, ...effectUndo },
|
||||||
};
|
};
|
||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
@@ -571,9 +715,29 @@ async function toggleParticipantActive(encounter, participantId, ctx) {
|
|||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function setTempHp(encounter, participantId, tempHp, ctx) {
|
||||||
|
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||||
|
if (!participant) throw new Error('Participant not found.');
|
||||||
|
const value = Math.max(0, tempHp || 0);
|
||||||
|
const oldValues = { tempHp: participant.tempHp || 0 };
|
||||||
|
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||||
|
p.id === participantId ? { ...p, tempHp: value } : p
|
||||||
|
);
|
||||||
|
const log = {
|
||||||
|
type: 'set_temp_hp',
|
||||||
|
participantId,
|
||||||
|
participantName: participant.name,
|
||||||
|
message: `${participant.name} temp HP set to ${value}`,
|
||||||
|
delta: { tempHp: value, oldTempHp: oldValues.tempHp },
|
||||||
|
undo: { oldValues, newValues: { tempHp: value } },
|
||||||
|
};
|
||||||
|
return commit(encounter, { participants: updatedParticipants }, log, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
async function applyHpChange(encounter, participantId, changeType, amount, optionsOrCtx, maybeCtx) {
|
async function applyHpChange(encounter, participantId, changeType, amount, optionsOrCtx, maybeCtx) {
|
||||||
const ctx = maybeCtx || optionsOrCtx;
|
const ctx = maybeCtx || optionsOrCtx;
|
||||||
const options = maybeCtx ? (optionsOrCtx || {}) : {};
|
const options = maybeCtx ? (optionsOrCtx || {}) : {};
|
||||||
|
const ruleset = encounter.ruleset || '5e';
|
||||||
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||||
if (!participant) throw new Error('Participant not found.');
|
if (!participant) throw new Error('Participant not found.');
|
||||||
if (isNaN(amount) || amount === 0) return encounter;
|
if (isNaN(amount) || amount === 0) return encounter;
|
||||||
@@ -584,19 +748,60 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
|
|
||||||
const oldValues = {
|
const oldValues = {
|
||||||
currentHp: participant.currentHp,
|
currentHp: participant.currentHp,
|
||||||
|
tempHp: participant.tempHp || 0,
|
||||||
status: participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious'),
|
status: participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious'),
|
||||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
isActive: participant.isActive,
|
isActive: participant.isActive,
|
||||||
conditions: [...(participant.conditions || [])],
|
conditions: [...(participant.conditions || [])],
|
||||||
};
|
};
|
||||||
|
const oldEffects = [...(encounter.effects || [])];
|
||||||
|
const newEffects = changeType === 'damage' ? expireDamageEffects(oldEffects, participantId) : oldEffects;
|
||||||
|
const effectChanged = effectsChanged(oldEffects, newEffects);
|
||||||
|
const withEffectPatch = patch => effectChanged ? { ...patch, effects: newEffects } : patch;
|
||||||
|
const withEffectUndo = undo => effectChanged ? { ...undo, oldEffects, newEffects } : undo;
|
||||||
|
|
||||||
let updates = {};
|
let updates = {};
|
||||||
let message = '';
|
let message = '';
|
||||||
let logDelta = { amount, from: participant.currentHp };
|
let logDelta = { amount, from: participant.currentHp };
|
||||||
const status = oldValues.status;
|
const status = oldValues.status;
|
||||||
|
const currentTemp = participant.tempHp || 0;
|
||||||
|
|
||||||
|
// GENERIC ruleset: no death saves, negative HP allowed, down status at <=0.
|
||||||
|
// Monster death = dead + inactive. No unconscious auto-condition.
|
||||||
|
if (ruleset === 'generic') {
|
||||||
|
return applyHpChangeGeneric(encounter, participant, changeType, amount, oldValues, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
if (changeType === 'damage') {
|
if (changeType === 'damage') {
|
||||||
|
// Temp HP absorbs damage first.
|
||||||
|
let remainingDmg = amount;
|
||||||
|
let tempAfter = currentTemp;
|
||||||
|
if (tempAfter > 0) {
|
||||||
|
const absorbed = Math.min(tempAfter, remainingDmg);
|
||||||
|
tempAfter -= absorbed;
|
||||||
|
remainingDmg -= absorbed;
|
||||||
|
updates.tempHp = tempAfter;
|
||||||
|
}
|
||||||
|
// If fully absorbed by temp, no regular HP change.
|
||||||
|
if (remainingDmg === 0 && participant.currentHp > 0) {
|
||||||
|
const updatedParticipants0 = (encounter.participants || []).map(p =>
|
||||||
|
p.id === participantId ? { ...p, tempHp: tempAfter } : p
|
||||||
|
);
|
||||||
|
const log0 = {
|
||||||
|
type: 'hp_change',
|
||||||
|
participantId,
|
||||||
|
participantName: participant.name,
|
||||||
|
message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`,
|
||||||
|
delta: { amount, from: participant.currentHp, to: participant.currentHp, tempHp: tempAfter },
|
||||||
|
undo: withEffectUndo({ oldValues, newValues: { ...oldValues, tempHp: tempAfter } }),
|
||||||
|
};
|
||||||
|
return commit(encounter, withEffectPatch({ participants: updatedParticipants0 }), log0, ctx);
|
||||||
|
}
|
||||||
|
amount = remainingDmg;
|
||||||
|
const tempBefore = currentTemp;
|
||||||
|
const tempFinal = updates.tempHp !== undefined ? updates.tempHp : tempBefore;
|
||||||
if (participant.currentHp === 0) {
|
if (participant.currentHp === 0) {
|
||||||
if (status === 'dead') {
|
if (status === 'dead') {
|
||||||
if (participant.type === 'monster' && participant.isActive !== false) {
|
if (participant.type === 'monster' && participant.isActive !== false) {
|
||||||
@@ -619,32 +824,32 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
participantName: participant.name,
|
participantName: participant.name,
|
||||||
message: `${participant.name} marked inactive (dead monster)`,
|
message: `${participant.name} marked inactive (dead monster)`,
|
||||||
delta: { status: 'dead', isActive: false },
|
delta: { status: 'dead', isActive: false },
|
||||||
undo: { oldValues, newValues },
|
undo: withEffectUndo({ oldValues, newValues }),
|
||||||
};
|
};
|
||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, withEffectPatch(patch), log, ctx);
|
||||||
}
|
}
|
||||||
return encounter;
|
return encounter;
|
||||||
}
|
}
|
||||||
const add = options.isCriticalHit ? 2 : 1;
|
const add = options.isCriticalHit ? 2 : 1;
|
||||||
const failures = (status === 'stable' ? 0 : (participant.deathSaveFailures || 0)) + add;
|
const failures = (status === 'stable' ? 0 : (participant.deathSaveFailures || 0)) + add;
|
||||||
if (failures >= 3) {
|
if (failures >= 3) {
|
||||||
updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, ...(participant.type === 'monster' ? { isActive: false } : {}) };
|
updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, tempHp: tempFinal, ...(participant.type === 'monster' ? { isActive: false } : {}) };
|
||||||
} else {
|
} else {
|
||||||
updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: 0, deathSaveFailures: failures };
|
updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: 0, deathSaveFailures: failures, stableRegainHours: null, tempHp: tempFinal };
|
||||||
}
|
}
|
||||||
message = `${participant.name} took ${amount} damage while ${status === 'stable' ? 'stable' : 'dying'}`;
|
message = `${participant.name} took ${amount} damage while ${status === 'stable' ? 'stable' : 'dying'}`;
|
||||||
logDelta = { ...logDelta, to: 0, status: updates.status, deathSaveFailures: updates.deathSaveFailures };
|
logDelta = { ...logDelta, to: 0, status: updates.status, deathSaveFailures: updates.deathSaveFailures };
|
||||||
} else if (amount >= participant.currentHp + participant.maxHp) {
|
} else if (amount >= participant.currentHp + participant.maxHp) {
|
||||||
updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, ...(participant.type === 'monster' ? { isActive: false } : {}) };
|
updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, tempHp: tempFinal, ...(participant.type === 'monster' ? { isActive: false } : {}) };
|
||||||
message = `Massive damage! ${participant.name} instantly killed`;
|
message = `Massive damage! ${participant.name} instantly killed`;
|
||||||
logDelta = { ...logDelta, to: 0, status: 'dead', massive: true };
|
logDelta = { ...logDelta, to: 0, status: 'dead', massive: true };
|
||||||
} else {
|
} else {
|
||||||
const newHp = Math.max(0, participant.currentHp - amount);
|
const newHp = Math.max(0, participant.currentHp - amount);
|
||||||
if (newHp === 0) {
|
if (newHp === 0) {
|
||||||
const zeroStatus = participant.type === 'monster' ? 'dead' : 'dying';
|
const zeroStatus = participant.type === 'monster' ? 'dead' : 'dying';
|
||||||
updates = { currentHp: 0, status: zeroStatus, deathSaveSuccesses: 0, deathSaveFailures: 0, ...(zeroStatus === 'dead' ? { isActive: false } : {}) };
|
updates = { currentHp: 0, status: zeroStatus, deathSaveSuccesses: 0, deathSaveFailures: 0, tempHp: tempFinal, ...(zeroStatus === 'dead' ? { isActive: false } : {}) };
|
||||||
} else {
|
} else {
|
||||||
updates = { currentHp: newHp, status: 'conscious' };
|
updates = { currentHp: newHp, status: 'conscious', tempHp: tempFinal };
|
||||||
}
|
}
|
||||||
message = `${participant.name} took ${amount} damage (${participant.currentHp} → ${newHp} HP)`;
|
message = `${participant.name} took ${amount} damage (${participant.currentHp} → ${newHp} HP)`;
|
||||||
logDelta = { ...logDelta, to: newHp, status: updates.status };
|
logDelta = { ...logDelta, to: newHp, status: updates.status };
|
||||||
@@ -652,7 +857,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
} else if (changeType === 'heal') {
|
} else if (changeType === 'heal') {
|
||||||
if (status === 'dead') return encounter;
|
if (status === 'dead') return encounter;
|
||||||
const newHp = Math.min(participant.maxHp, Math.max(1, participant.currentHp + amount));
|
const newHp = Math.min(participant.maxHp, Math.max(1, participant.currentHp + amount));
|
||||||
updates = { currentHp: newHp, status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
updates = { currentHp: newHp, status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null };
|
||||||
message = `${participant.name} healed for ${amount} (${participant.currentHp} → ${newHp} HP)`;
|
message = `${participant.name} healed for ${amount} (${participant.currentHp} → ${newHp} HP)`;
|
||||||
logDelta = { ...logDelta, to: newHp, status: 'conscious', deathSavesCleared: true };
|
logDelta = { ...logDelta, to: newHp, status: 'conscious', deathSavesCleared: true };
|
||||||
} else {
|
} else {
|
||||||
@@ -662,7 +867,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
const updatedParticipants = (encounter.participants || []).map(p =>
|
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||||
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||||
);
|
);
|
||||||
const patch = { participants: updatedParticipants };
|
const patch = withEffectPatch({ participants: updatedParticipants });
|
||||||
const undoAmount = changeType === 'damage' ? amount : -amount;
|
const undoAmount = changeType === 'damage' ? amount : -amount;
|
||||||
const newP = updatedParticipants.find(p => p.id === participantId);
|
const newP = updatedParticipants.find(p => p.id === participantId);
|
||||||
const newValues = {
|
const newValues = {
|
||||||
@@ -670,6 +875,7 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
status: newP.status,
|
status: newP.status,
|
||||||
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: newP.deathSaveFailures || 0,
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
isActive: newP.isActive,
|
isActive: newP.isActive,
|
||||||
conditions: [...(newP.conditions || [])],
|
conditions: [...(newP.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -678,12 +884,109 @@ async function applyHpChange(encounter, participantId, changeType, amount, optio
|
|||||||
participantId, participantName: participant.name,
|
participantId, participantName: participant.name,
|
||||||
message,
|
message,
|
||||||
delta: logDelta,
|
delta: logDelta,
|
||||||
undo: { amount: undoAmount, oldValues, newValues },
|
undo: withEffectUndo({ amount: undoAmount, oldValues, newValues }),
|
||||||
};
|
};
|
||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GENERIC ruleset HP change: no death saves, negative HP, down status at <=0.
|
||||||
|
// Monster death = dead + inactive. No unconscious auto-condition.
|
||||||
|
async function applyHpChangeGeneric(encounter, participant, changeType, amount, oldValues, ctx) {
|
||||||
|
const participantId = participant.id;
|
||||||
|
let updates, message, logDelta = { amount, from: participant.currentHp };
|
||||||
|
const currentTemp = participant.tempHp || 0;
|
||||||
|
const oldEffects = [...(encounter.effects || [])];
|
||||||
|
const newEffects = changeType === 'damage' ? expireDamageEffects(oldEffects, participantId) : oldEffects;
|
||||||
|
const effectChanged = effectsChanged(oldEffects, newEffects);
|
||||||
|
const withEffectPatch = patch => effectChanged ? { ...patch, effects: newEffects } : patch;
|
||||||
|
const withEffectUndo = undo => effectChanged ? { ...undo, oldEffects, newEffects } : undo;
|
||||||
|
|
||||||
|
if (changeType === 'damage') {
|
||||||
|
// Temp HP absorbs damage first.
|
||||||
|
let remainingDmg = amount;
|
||||||
|
let tempAfter = currentTemp;
|
||||||
|
if (tempAfter > 0) {
|
||||||
|
const absorbed = Math.min(tempAfter, remainingDmg);
|
||||||
|
tempAfter -= absorbed;
|
||||||
|
remainingDmg -= absorbed;
|
||||||
|
}
|
||||||
|
if (remainingDmg === 0) {
|
||||||
|
const updatedParticipants0 = (encounter.participants || []).map(p =>
|
||||||
|
p.id === participantId ? { ...p, tempHp: tempAfter } : p
|
||||||
|
);
|
||||||
|
const log0 = {
|
||||||
|
type: 'hp_change', participantId, participantName: participant.name,
|
||||||
|
message: `${participant.name} took ${amount} damage (absorbed by temp HP, ${tempAfter} temp remaining)`,
|
||||||
|
delta: { amount, from: participant.currentHp, to: participant.currentHp, tempHp: tempAfter },
|
||||||
|
undo: withEffectUndo({ oldValues, newValues: { ...oldValues, tempHp: tempAfter } }),
|
||||||
|
};
|
||||||
|
return commit(encounter, withEffectPatch({ participants: updatedParticipants0 }), log0, ctx);
|
||||||
|
}
|
||||||
|
amount = remainingDmg;
|
||||||
|
const tempFinal = tempAfter;
|
||||||
|
if (oldValues.status === 'dead') {
|
||||||
|
if (participant.type === 'monster' && participant.isActive !== false) {
|
||||||
|
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||||
|
p.id === participantId ? { ...p, isActive: false } : p
|
||||||
|
);
|
||||||
|
const newP = updatedParticipants.find(p => p.id === participantId);
|
||||||
|
const newValues = {
|
||||||
|
currentHp: newP.currentHp, status: newP.status,
|
||||||
|
deathSaveSuccesses: 0, deathSaveFailures: 0,
|
||||||
|
isActive: newP.isActive, conditions: [...(newP.conditions || [])],
|
||||||
|
};
|
||||||
|
return commit(encounter, withEffectPatch({ participants: updatedParticipants }), {
|
||||||
|
type: 'deactivate_dead_monster', participantId, participantName: participant.name,
|
||||||
|
message: `${participant.name} marked inactive (dead monster)`,
|
||||||
|
delta: { status: 'dead', isActive: false },
|
||||||
|
undo: withEffectUndo({ oldValues, newValues }),
|
||||||
|
}, ctx);
|
||||||
|
}
|
||||||
|
return encounter;
|
||||||
|
}
|
||||||
|
const newHp = participant.currentHp - amount;
|
||||||
|
const isMonster = participant.type === 'monster';
|
||||||
|
if (newHp <= 0 && isMonster) {
|
||||||
|
updates = { currentHp: newHp, status: 'dead', isActive: false, tempHp: tempFinal };
|
||||||
|
} else if (newHp <= 0) {
|
||||||
|
updates = { currentHp: newHp, status: 'down', tempHp: tempFinal };
|
||||||
|
} else {
|
||||||
|
updates = { currentHp: newHp, status: 'conscious', tempHp: tempFinal };
|
||||||
|
}
|
||||||
|
message = `${participant.name} took ${amount} damage (${participant.currentHp} → ${newHp} HP)`;
|
||||||
|
logDelta = { ...logDelta, to: newHp, status: updates.status };
|
||||||
|
} else if (changeType === 'heal') {
|
||||||
|
if (oldValues.status === 'dead') return encounter;
|
||||||
|
const newHp = Math.min(participant.maxHp, participant.currentHp + amount);
|
||||||
|
updates = { currentHp: newHp, status: 'conscious' };
|
||||||
|
message = `${participant.name} healed for ${amount} (${participant.currentHp} → ${newHp} HP)`;
|
||||||
|
logDelta = { ...logDelta, to: newHp, status: 'conscious' };
|
||||||
|
} else {
|
||||||
|
throw new Error(`Unknown HP change type: ${changeType}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||||
|
p.id === participantId ? { ...p, ...updates } : p
|
||||||
|
);
|
||||||
|
const newP = updatedParticipants.find(p => p.id === participantId);
|
||||||
|
const newValues = {
|
||||||
|
currentHp: newP.currentHp, status: newP.status,
|
||||||
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
isActive: newP.isActive, conditions: [...(newP.conditions || [])],
|
||||||
|
};
|
||||||
|
const undoAmount = changeType === 'damage' ? amount : -amount;
|
||||||
|
return commit(encounter, withEffectPatch({ participants: updatedParticipants }), {
|
||||||
|
type: changeType, participantId, participantName: participant.name,
|
||||||
|
message, delta: logDelta,
|
||||||
|
undo: withEffectUndo({ amount: undoAmount, oldValues, newValues }),
|
||||||
|
}, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
async function deathSave(encounter, participantId, outcome, ctx) {
|
async function deathSave(encounter, participantId, outcome, ctx) {
|
||||||
|
if ((encounter.ruleset || '5e') === 'generic') {
|
||||||
|
throw new Error('Death saves not available in generic ruleset.');
|
||||||
|
}
|
||||||
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||||
if (!participant) throw new Error('Participant not found.');
|
if (!participant) throw new Error('Participant not found.');
|
||||||
const statusBefore = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
const statusBefore = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
||||||
@@ -697,6 +1000,7 @@ async function deathSave(encounter, participantId, outcome, ctx) {
|
|||||||
status: statusBefore,
|
status: statusBefore,
|
||||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
isActive: participant.isActive,
|
isActive: participant.isActive,
|
||||||
conditions: [...(participant.conditions || [])],
|
conditions: [...(participant.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -707,8 +1011,8 @@ async function deathSave(encounter, participantId, outcome, ctx) {
|
|||||||
} else {
|
} else {
|
||||||
const successes = (participant.deathSaveSuccesses || 0) + (outcome === 'success' ? 1 : 0);
|
const successes = (participant.deathSaveSuccesses || 0) + (outcome === 'success' ? 1 : 0);
|
||||||
const failures = (participant.deathSaveFailures || 0) + (outcome === 'fail' ? 1 : outcome === 'nat1' ? 2 : 0);
|
const failures = (participant.deathSaveFailures || 0) + (outcome === 'fail' ? 1 : outcome === 'nat1' ? 2 : 0);
|
||||||
if (failures >= 3) updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
if (failures >= 3) updates = { currentHp: 0, status: 'dead', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: null };
|
||||||
else if (successes >= 3) updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
else if (successes >= 3) updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: rollD4() };
|
||||||
else updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: successes, deathSaveFailures: failures };
|
else updates = { currentHp: 0, status: 'dying', deathSaveSuccesses: successes, deathSaveFailures: failures };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -728,6 +1032,7 @@ async function deathSave(encounter, participantId, outcome, ctx) {
|
|||||||
status: newP.status,
|
status: newP.status,
|
||||||
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: newP.deathSaveFailures || 0,
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
isActive: newP.isActive,
|
isActive: newP.isActive,
|
||||||
conditions: [...(newP.conditions || [])],
|
conditions: [...(newP.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -763,7 +1068,56 @@ async function toggleCondition(encounter, participantId, conditionId, ctx) {
|
|||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function addEffect(encounter, effect, ctx) {
|
||||||
|
const normalized = makeEffect({ ...effect, createdRound: effect.createdRound ?? encounter.round ?? 0 });
|
||||||
|
const oldEffects = [...(encounter.effects || [])];
|
||||||
|
if (oldEffects.some(e => e.id === normalized.id)) throw new Error(`Effect "${normalized.id}" already exists.`);
|
||||||
|
if (normalized.scope === 'participant' && !normalized.targetParticipantId) throw new Error('Participant effect requires targetParticipantId.');
|
||||||
|
const newEffects = [...oldEffects, normalized];
|
||||||
|
const target = (encounter.participants || []).find(p => p.id === normalized.targetParticipantId);
|
||||||
|
return commit(encounter, { effects: newEffects }, {
|
||||||
|
type: 'add_effect',
|
||||||
|
participantId: normalized.targetParticipantId,
|
||||||
|
participantName: target?.name || null,
|
||||||
|
message: `${normalized.name} added${target ? ` to ${target.name}` : ''} (${normalized.remainingRounds} rounds)`,
|
||||||
|
delta: { effectId: normalized.id, name: normalized.name, remainingRounds: normalized.remainingRounds },
|
||||||
|
undo: { oldEffects, newEffects },
|
||||||
|
}, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function updateEffect(encounter, effectId, updates, ctx) {
|
||||||
|
const oldEffects = [...(encounter.effects || [])];
|
||||||
|
const existing = oldEffects.find(e => e.id === effectId);
|
||||||
|
if (!existing) throw new Error('Effect not found.');
|
||||||
|
const merged = makeEffect({ ...existing, ...updates, id: existing.id });
|
||||||
|
const newEffects = oldEffects.map(e => e.id === effectId ? merged : e);
|
||||||
|
return commit(encounter, { effects: newEffects }, {
|
||||||
|
type: 'update_effect',
|
||||||
|
participantId: merged.targetParticipantId,
|
||||||
|
message: `${merged.name} updated (${merged.remainingRounds} rounds)`,
|
||||||
|
delta: { effectId, remainingRounds: merged.remainingRounds },
|
||||||
|
undo: { oldEffects, newEffects },
|
||||||
|
}, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeEffect(encounter, effectId, ctx) {
|
||||||
|
const oldEffects = [...(encounter.effects || [])];
|
||||||
|
const existing = oldEffects.find(e => e.id === effectId);
|
||||||
|
if (!existing) throw new Error('Effect not found.');
|
||||||
|
const newEffects = oldEffects.filter(e => e.id !== effectId);
|
||||||
|
return commit(encounter, { effects: newEffects }, {
|
||||||
|
type: 'remove_effect',
|
||||||
|
participantId: existing.targetParticipantId,
|
||||||
|
message: `${existing.name} removed`,
|
||||||
|
delta: { effectId, name: existing.name },
|
||||||
|
undo: { oldEffects, newEffects },
|
||||||
|
}, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
async function stabilizeParticipant(encounter, participantId, ctx) {
|
async function stabilizeParticipant(encounter, participantId, ctx) {
|
||||||
|
if ((encounter.ruleset || '5e') === 'generic') {
|
||||||
|
throw new Error('Stabilize not available in generic ruleset.');
|
||||||
|
}
|
||||||
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||||
if (!participant) throw new Error('Participant not found.');
|
if (!participant) throw new Error('Participant not found.');
|
||||||
const status = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
const status = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
||||||
@@ -771,7 +1125,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) {
|
|||||||
if (status === 'dead') throw new Error('Cannot stabilize dead participant.');
|
if (status === 'dead') throw new Error('Cannot stabilize dead participant.');
|
||||||
if (status === 'stable') return encounter;
|
if (status === 'stable') return encounter;
|
||||||
|
|
||||||
const updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0 };
|
const updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: rollD4() };
|
||||||
const updatedParticipants = (encounter.participants || []).map(p =>
|
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||||
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||||
);
|
);
|
||||||
@@ -782,6 +1136,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) {
|
|||||||
status,
|
status,
|
||||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
isActive: participant.isActive,
|
isActive: participant.isActive,
|
||||||
conditions: [...(participant.conditions || [])],
|
conditions: [...(participant.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -791,6 +1146,7 @@ async function stabilizeParticipant(encounter, participantId, ctx) {
|
|||||||
status: newP.status,
|
status: newP.status,
|
||||||
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: newP.deathSaveFailures || 0,
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
isActive: newP.isActive,
|
isActive: newP.isActive,
|
||||||
conditions: [...(newP.conditions || [])],
|
conditions: [...(newP.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -806,12 +1162,17 @@ async function stabilizeParticipant(encounter, participantId, ctx) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function reviveParticipant(encounter, participantId, ctx) {
|
async function reviveParticipant(encounter, participantId, ctx) {
|
||||||
|
const ruleset = encounter.ruleset || '5e';
|
||||||
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||||
if (!participant) throw new Error('Participant not found.');
|
if (!participant) throw new Error('Participant not found.');
|
||||||
const status = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
const status = participant.status || (participant.currentHp === 0 ? 'dying' : 'conscious');
|
||||||
if (status !== 'dead') return encounter;
|
if (status !== 'dead') return encounter;
|
||||||
|
|
||||||
const updates = { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, isActive: true };
|
// Generic: dead→conscious (no stable state). HP unchanged (may be negative).
|
||||||
|
// 5e: dead→stable at 0 HP, unconscious, clears death-save counters.
|
||||||
|
const updates = ruleset === 'generic'
|
||||||
|
? { status: 'conscious', ...(participant.type === 'monster' ? {} : {}), ...(participant.isActive === false ? { isActive: true } : {}) }
|
||||||
|
: { currentHp: 0, status: 'stable', deathSaveSuccesses: 0, deathSaveFailures: 0, stableRegainHours: rollD4(), isActive: true };
|
||||||
const updatedParticipants = (encounter.participants || []).map(p =>
|
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||||
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||||
);
|
);
|
||||||
@@ -822,6 +1183,7 @@ async function reviveParticipant(encounter, participantId, ctx) {
|
|||||||
status,
|
status,
|
||||||
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: participant.deathSaveFailures || 0,
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
isActive: participant.isActive,
|
isActive: participant.isActive,
|
||||||
conditions: [...(participant.conditions || [])],
|
conditions: [...(participant.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -831,6 +1193,7 @@ async function reviveParticipant(encounter, participantId, ctx) {
|
|||||||
status: newP.status,
|
status: newP.status,
|
||||||
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
deathSaveFailures: newP.deathSaveFailures || 0,
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
isActive: newP.isActive,
|
isActive: newP.isActive,
|
||||||
conditions: [...(newP.conditions || [])],
|
conditions: [...(newP.conditions || [])],
|
||||||
};
|
};
|
||||||
@@ -845,6 +1208,94 @@ async function reviveParticipant(encounter, participantId, ctx) {
|
|||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function healFullParticipant(encounter, participantId, ctx) {
|
||||||
|
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||||
|
if (!participant) throw new Error('Participant not found.');
|
||||||
|
const status = participant.status || (participant.currentHp <= 0 ? 'down' : 'conscious');
|
||||||
|
const oldValues = {
|
||||||
|
currentHp: participant.currentHp,
|
||||||
|
status,
|
||||||
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
|
isActive: participant.isActive,
|
||||||
|
conditions: [...(participant.conditions || [])],
|
||||||
|
};
|
||||||
|
const updates = {
|
||||||
|
currentHp: participant.maxHp,
|
||||||
|
status: 'conscious',
|
||||||
|
deathSaveSuccesses: 0,
|
||||||
|
deathSaveFailures: 0,
|
||||||
|
stableRegainHours: null,
|
||||||
|
isActive: true,
|
||||||
|
};
|
||||||
|
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||||
|
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||||
|
);
|
||||||
|
const newP = updatedParticipants.find(p => p.id === participantId);
|
||||||
|
const newValues = {
|
||||||
|
currentHp: newP.currentHp,
|
||||||
|
status: newP.status,
|
||||||
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
|
isActive: newP.isActive,
|
||||||
|
conditions: [...(newP.conditions || [])],
|
||||||
|
};
|
||||||
|
return commit(encounter, { participants: updatedParticipants }, {
|
||||||
|
type: 'heal_full', participantId, participantName: participant.name,
|
||||||
|
message: `${participant.name} healed to full (${participant.maxHp} HP)`,
|
||||||
|
delta: { currentHp: participant.maxHp, status: 'conscious', isActive: true },
|
||||||
|
undo: { oldValues, newValues },
|
||||||
|
}, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// markDead: DM manually kills participant. Sets 0 HP + inactive.
|
||||||
|
async function markDead(encounter, participantId, ctx) {
|
||||||
|
const participant = (encounter.participants || []).find(p => p.id === participantId);
|
||||||
|
if (!participant) throw new Error('Participant not found.');
|
||||||
|
if (participant.status === 'dead') return encounter;
|
||||||
|
const oldValues = {
|
||||||
|
currentHp: participant.currentHp,
|
||||||
|
tempHp: participant.tempHp || 0,
|
||||||
|
status: participant.status || 'conscious',
|
||||||
|
deathSaveSuccesses: participant.deathSaveSuccesses || 0,
|
||||||
|
deathSaveFailures: participant.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: participant.stableRegainHours !== undefined ? participant.stableRegainHours : null,
|
||||||
|
isActive: participant.isActive,
|
||||||
|
conditions: [...(participant.conditions || [])],
|
||||||
|
};
|
||||||
|
const updates = {
|
||||||
|
currentHp: 0,
|
||||||
|
tempHp: 0,
|
||||||
|
status: 'dead',
|
||||||
|
deathSaveSuccesses: 0,
|
||||||
|
deathSaveFailures: 0,
|
||||||
|
stableRegainHours: null,
|
||||||
|
isActive: false,
|
||||||
|
};
|
||||||
|
const updatedParticipants = (encounter.participants || []).map(p =>
|
||||||
|
p.id === participantId ? { ...p, ...withDeathStatusConditions(p, updates) } : p
|
||||||
|
);
|
||||||
|
const newP = updatedParticipants.find(p => p.id === participantId);
|
||||||
|
const newValues = {
|
||||||
|
currentHp: newP.currentHp,
|
||||||
|
tempHp: newP.tempHp || 0,
|
||||||
|
status: newP.status,
|
||||||
|
deathSaveSuccesses: newP.deathSaveSuccesses || 0,
|
||||||
|
deathSaveFailures: newP.deathSaveFailures || 0,
|
||||||
|
stableRegainHours: newP.stableRegainHours !== undefined ? newP.stableRegainHours : null,
|
||||||
|
isActive: newP.isActive,
|
||||||
|
conditions: [...(newP.conditions || [])],
|
||||||
|
};
|
||||||
|
return commit(encounter, { participants: updatedParticipants }, {
|
||||||
|
type: 'mark_dead', participantId, participantName: participant.name,
|
||||||
|
message: `${participant.name} killed`,
|
||||||
|
delta: { status: 'dead', currentHp: 0, isActive: false },
|
||||||
|
undo: { oldValues, newValues },
|
||||||
|
}, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
async function reorderParticipants(encounter, draggedId, targetId, ctx) {
|
async function reorderParticipants(encounter, draggedId, targetId, ctx) {
|
||||||
const participants = [...(encounter.participants || [])];
|
const participants = [...(encounter.participants || [])];
|
||||||
const dragged = participants.find(p => p.id === draggedId);
|
const dragged = participants.find(p => p.id === draggedId);
|
||||||
@@ -884,12 +1335,93 @@ async function reorderParticipants(encounter, draggedId, targetId, ctx) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function endEncounter(encounter, ctx) {
|
async function endEncounter(encounter, ctx) {
|
||||||
const patch = { isStarted: false, isPaused: false, currentTurnParticipantId: null, round: 0, turnOrderIds: [] };
|
const patch = { isStarted: false, isPaused: false, currentTurnParticipantId: null, round: 0, turnOrderIds: [], endedAt: Date.now() };
|
||||||
const log = {
|
const log = {
|
||||||
type: 'end_encounter',
|
type: 'end_encounter',
|
||||||
message: `Combat ended: "${encounter.name}"`,
|
message: `Combat ended: "${encounter.name}"`,
|
||||||
delta: {},
|
delta: {},
|
||||||
undo: { isStarted: encounter.isStarted ?? false, isPaused: encounter.isPaused ?? false, round: encounter.round ?? 0, currentTurnParticipantId: encounter.currentTurnParticipantId ?? null, turnOrderIds: [...(encounter.turnOrderIds || [])] },
|
undo: { isStarted: encounter.isStarted ?? false, isPaused: encounter.isPaused ?? false, round: encounter.round ?? 0, currentTurnParticipantId: encounter.currentTurnParticipantId ?? null, turnOrderIds: [...(encounter.turnOrderIds || [])], endedAt: encounter.endedAt ?? null },
|
||||||
|
};
|
||||||
|
|
||||||
|
// Character writeback: sync maxHp/ac/currentHp to campaign players if enabled.
|
||||||
|
// ctx.campaignPath: adapter-specific doc path (firebase needs the full
|
||||||
|
// artifacts/{APP_ID}/public/data prefix); bare campaigns/{id} fallback for
|
||||||
|
// server/test adapters. Writeback failure must not block ending combat.
|
||||||
|
const wbCampaignId = encounter.campaignId || ctx.campaignId;
|
||||||
|
if ((wbCampaignId || ctx.campaign) && ctx.storage) {
|
||||||
|
const campaignPath = ctx.campaignPath || `campaigns/${wbCampaignId}`;
|
||||||
|
let campaign;
|
||||||
|
try {
|
||||||
|
campaign = ctx.campaign || await ctx.storage.getDoc(campaignPath);
|
||||||
|
} catch { campaign = null; }
|
||||||
|
const syncCharacters = ctx.syncCharacters !== undefined
|
||||||
|
? ctx.syncCharacters
|
||||||
|
: campaign?.syncCharacters;
|
||||||
|
if (campaign && syncCharacters && Array.isArray(campaign.players)) {
|
||||||
|
const charParticipants = (encounter.participants || []).filter(p => p.originalCharacterId);
|
||||||
|
const oldValues = [];
|
||||||
|
let changed = false;
|
||||||
|
const updatedPlayers = campaign.players.map(player => {
|
||||||
|
const cp = charParticipants.find(p => p.originalCharacterId === player.id);
|
||||||
|
if (!cp) return player;
|
||||||
|
const oldMaxHp = player.defaultMaxHp;
|
||||||
|
const oldAc = player.defaultAc;
|
||||||
|
const oldCurrentHp = player.defaultCurrentHp;
|
||||||
|
const oldStableRegainHours = player.stableRegainHours !== undefined ? player.stableRegainHours : null;
|
||||||
|
oldValues.push({ id: player.id, defaultMaxHp: oldMaxHp, defaultAc: oldAc, defaultCurrentHp: oldCurrentHp, stableRegainHours: oldStableRegainHours });
|
||||||
|
const newPlayer = { ...player };
|
||||||
|
if (cp.maxHp != null && cp.maxHp !== oldMaxHp) { newPlayer.defaultMaxHp = cp.maxHp; changed = true; }
|
||||||
|
if (cp.ac != null && cp.ac !== oldAc) { newPlayer.defaultAc = cp.ac; changed = true; }
|
||||||
|
if (cp.currentHp != null && cp.currentHp !== oldCurrentHp) { newPlayer.defaultCurrentHp = cp.currentHp; changed = true; }
|
||||||
|
// Stable state: carried while stable, cleared once conscious again.
|
||||||
|
const cpStableRegainHours = cp.status === 'stable' ? (cp.stableRegainHours !== undefined ? cp.stableRegainHours : null) : null;
|
||||||
|
if (cpStableRegainHours !== oldStableRegainHours) { newPlayer.stableRegainHours = cpStableRegainHours; changed = true; }
|
||||||
|
return newPlayer;
|
||||||
|
});
|
||||||
|
if (changed) {
|
||||||
|
try {
|
||||||
|
await ctx.storage.updateDoc(campaignPath, { players: updatedPlayers });
|
||||||
|
log.undo.characterWriteback = oldValues;
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`endEncounter: character writeback failed (${campaignPath}):`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return commit(encounter, patch, log, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// rerollAllInitiatives: d20 + stored initMod for EVERY participant, one write.
|
||||||
|
// Allowed pre-combat or paused. Slot-based re-insertion preserves roll order.
|
||||||
|
// Single log entry; undo restores old array + order.
|
||||||
|
async function rerollAllInitiatives(encounter, ctx) {
|
||||||
|
if (encounter.isStarted && !encounter.isPaused) {
|
||||||
|
throw new Error('Reroll initiative only before combat or while paused.');
|
||||||
|
}
|
||||||
|
const oldParticipants = encounter.participants || [];
|
||||||
|
if (oldParticipants.length === 0) return encounter;
|
||||||
|
|
||||||
|
const rolled = oldParticipants.map(p => ({
|
||||||
|
...p,
|
||||||
|
initiative: rollD20() + (p.initMod != null ? p.initMod : 0),
|
||||||
|
}));
|
||||||
|
// slot re-insertion: each rolled participant placed above lower inits
|
||||||
|
const newList = [];
|
||||||
|
for (const p of rolled) {
|
||||||
|
newList.splice(slotIndexForInit(newList, p.initiative), 0, p);
|
||||||
|
}
|
||||||
|
const patch = { participants: newList, ...syncTurnOrder(newList) };
|
||||||
|
const log = {
|
||||||
|
type: 'reroll_all_init',
|
||||||
|
message: `Initiative rerolled for all ${newList.length} participants`,
|
||||||
|
delta: { count: newList.length },
|
||||||
|
undo: {
|
||||||
|
participants: oldParticipants.map(p => ({ ...p })),
|
||||||
|
turnOrderIds: [...(encounter.turnOrderIds || [])],
|
||||||
|
newParticipants: newList.map(p => ({ ...p })),
|
||||||
|
newTurnOrderIds: patch.turnOrderIds,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
return commit(encounter, patch, log, ctx);
|
return commit(encounter, patch, log, ctx);
|
||||||
}
|
}
|
||||||
@@ -913,13 +1445,14 @@ async function toggleHidePlayerHp(currentValue, ctx) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
DEFAULT_MAX_HP, DEFAULT_INIT_MOD, MONSTER_DEFAULT_INIT_MOD,
|
DEFAULT_MAX_HP, DEFAULT_INIT_MOD, MONSTER_DEFAULT_INIT_MOD,
|
||||||
generateId, rollD20, formatInitMod,
|
generateId, rollD20, rollHpFormula, formatInitMod,
|
||||||
sortParticipantsByInitiative, syncTurnOrder, computeTurnOrderAfterRemoval,
|
sortParticipantsByInitiative, syncTurnOrder, computeTurnOrderAfterRemoval,
|
||||||
snapshotOf, buildEntry, expandUndo,
|
snapshotOf, buildEntry, expandUndo,
|
||||||
makeParticipant, buildCharacterParticipant, buildMonsterParticipant,
|
makeEffect, makeParticipant, buildCharacterParticipant, buildMonsterParticipant,
|
||||||
startEncounter, nextTurn, togglePause,
|
startEncounter, nextTurn, togglePause,
|
||||||
addParticipant, addParticipants, updateParticipant, removeParticipant,
|
addParticipant, addParticipants, updateParticipant, removeParticipant,
|
||||||
toggleParticipantActive, applyHpChange, deathSave, stabilizeParticipant, reviveParticipant, toggleCondition,
|
toggleParticipantActive, applyHpChange, setTempHp, deathSave, stabilizeParticipant, reviveParticipant, healFullParticipant, markDead, toggleCondition,
|
||||||
reorderParticipants, endEncounter,
|
addEffect, updateEffect, removeEffect,
|
||||||
|
reorderParticipants, endEncounter, rerollAllInitiatives,
|
||||||
activateDisplay, clearDisplay, toggleHidePlayerHp,
|
activateDisplay, clearDisplay, toggleHidePlayerHp,
|
||||||
};
|
};
|
||||||
+2051
-317
File diff suppressed because it is too large.
Load diff
@@ -105,9 +105,9 @@ export function onSnapshot(refOrQuery, onSuccess, onError) {
|
|||||||
return unsub;
|
return unsub;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply Firestore-style query constraints (orderBy desc/asc, limit) to mock docs.
|
// Apply Firestore-style query constraints (orderBy desc/asc, limit, where)
|
||||||
// Mirrors real SDK semantics enough for contract tests. Only orderBy + limit
|
// to mock docs. Mirrors real SDK semantics for contract tests. Offset handled
|
||||||
// supported (App's LOG_QUERY uses exactly these).
|
// by adapter (firebase.js slices) — mock never sees it.
|
||||||
function applyConstraints(docs, constraints) {
|
function applyConstraints(docs, constraints) {
|
||||||
let out = [...docs];
|
let out = [...docs];
|
||||||
for (const c of constraints) {
|
for (const c of constraints) {
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// Dev-tools gate. Explicit opt-in via REACT_APP_DEV_TOOLS=1.
|
||||||
|
// Safe default: any value other than exactly '1' = off.
|
||||||
|
// Dynamic key access (process.env[KEY]) so react-scripts DefinePlugin does NOT
|
||||||
|
// inline the value at build time — allows tests + runtime env changes to take
|
||||||
|
// effect. DefinePlugin only replaces static member access, never computed lookups.
|
||||||
|
const KEY = 'REACT_APP_DEV_TOOLS';
|
||||||
|
export const isDevToolsEnabled = () => process.env[KEY] === '1';
|
||||||
@@ -294,6 +294,7 @@ function runStorageContract(name, factory) {
|
|||||||
describe('subscribeCollection queryConstraints', () => {
|
describe('subscribeCollection queryConstraints', () => {
|
||||||
const orderByC = (field, dir) => ({ __type: 'orderBy', field, dir });
|
const orderByC = (field, dir) => ({ __type: 'orderBy', field, dir });
|
||||||
const limitC = (n) => ({ __type: 'limit', n });
|
const limitC = (n) => ({ __type: 'limit', n });
|
||||||
|
const offsetC = (n) => ({ __type: 'offset', offset: n });
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
// seed 5 log docs, timestamps out of order
|
// seed 5 log docs, timestamps out of order
|
||||||
@@ -324,6 +325,23 @@ function runStorageContract(name, factory) {
|
|||||||
});
|
});
|
||||||
expect(result).toHaveLength(5);
|
expect(result).toHaveLength(5);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Log page pagination (LogsView pageQuery): orderBy + limit + offset.
|
||||||
|
// Server pushes offset to SQL; firebase adapter emulates (widen limit,
|
||||||
|
// slice). Both MUST return the same page.
|
||||||
|
test('offset skips first N after ordering (pagination)', async () => {
|
||||||
|
const result = await new Promise((resolve) => {
|
||||||
|
storage.subscribeCollection('logs', resolve, [orderByC('timestamp', 'desc'), limitC(2), offsetC(2)]);
|
||||||
|
});
|
||||||
|
expect(result.map(d => d.msg)).toEqual(['two', 'four']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('offset past end returns empty page', async () => {
|
||||||
|
const result = await new Promise((resolve) => {
|
||||||
|
storage.subscribeCollection('logs', resolve, [orderByC('timestamp', 'desc'), limitC(2), offsetC(10)]);
|
||||||
|
});
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-21
@@ -71,6 +71,27 @@ export function getAuthInstance() { return authInstance; }
|
|||||||
// App.js can now import { storage } and call storage.setDoc(path, data).
|
// App.js can now import { storage } and call storage.setDoc(path, data).
|
||||||
// Hooks (useFirestoreDocument etc) still use SDK directly for now.
|
// Hooks (useFirestoreDocument etc) still use SDK directly for now.
|
||||||
|
|
||||||
|
// Translate neutral {__type} constraints (src/storage/index.js builders) to
|
||||||
|
// SDK builders. The client SDK has no offset, so emulate it: widen limit to
|
||||||
|
// offset+limit and report offsetN for the caller to slice off the leading
|
||||||
|
// docs. Read cost matches native offset (admin SDK also bills skipped docs);
|
||||||
|
// the server adapter pushes offset into SQL instead. Unknown constraint types
|
||||||
|
// are dropped — a raw object handed to query() throws and white-screens.
|
||||||
|
function toSdkConstraints(queryConstraints) {
|
||||||
|
let offsetN = 0;
|
||||||
|
let limitN = null;
|
||||||
|
const fbConstraints = [];
|
||||||
|
for (const c of queryConstraints || []) {
|
||||||
|
if (!c || !c.__type) continue;
|
||||||
|
if (c.__type === 'where') fbConstraints.push(where(c.field, c.op, c.value));
|
||||||
|
else if (c.__type === 'orderBy') fbConstraints.push(orderBy(c.field, c.dir || 'asc'));
|
||||||
|
else if (c.__type === 'limit') limitN = c.n;
|
||||||
|
else if (c.__type === 'offset') offsetN = c.offset || 0;
|
||||||
|
}
|
||||||
|
if (limitN !== null) fbConstraints.push(limit(limitN + offsetN));
|
||||||
|
return { fbConstraints, offsetN };
|
||||||
|
}
|
||||||
|
|
||||||
export function createFirebaseStorage() {
|
export function createFirebaseStorage() {
|
||||||
const db = dbInstance;
|
const db = dbInstance;
|
||||||
if (!db) throw new Error('Firestore not initialized. Call initFirebase() first.');
|
if (!db) throw new Error('Firestore not initialized. Call initFirebase() first.');
|
||||||
@@ -101,18 +122,10 @@ export function createFirebaseStorage() {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async getCollection(collectionPath, queryConstraints = []) {
|
async getCollection(collectionPath, queryConstraints = []) {
|
||||||
// Translate neutral {__type} constraints to firebase SDK builders.
|
const { fbConstraints, offsetN } = toSdkConstraints(queryConstraints);
|
||||||
const fbConstraints = [];
|
|
||||||
for (const c of queryConstraints || []) {
|
|
||||||
if (!c || !c.__type) continue;
|
|
||||||
if (c.__type === 'where') fbConstraints.push(where(c.field, c.op, c.value));
|
|
||||||
else if (c.__type === 'orderBy') fbConstraints.push(orderBy(c.field, c.dir || 'asc'));
|
|
||||||
else if (c.__type === 'limit') fbConstraints.push(limit(c.n));
|
|
||||||
// firebase SDK has no offset; skip (UI uses server adapter in dev).
|
|
||||||
}
|
|
||||||
const q = fbConstraints.length ? query(collection(db, collectionPath), ...fbConstraints) : collection(db, collectionPath);
|
const q = fbConstraints.length ? query(collection(db, collectionPath), ...fbConstraints) : collection(db, collectionPath);
|
||||||
const snapshot = await getDocsReal(q);
|
const snapshot = await getDocsReal(q);
|
||||||
return snapshot.docs.map(d => ({ id: d.id, ...d.data() }));
|
return snapshot.docs.slice(offsetN).map(d => ({ id: d.id, ...d.data() }));
|
||||||
},
|
},
|
||||||
|
|
||||||
async countCollection(collectionPath) {
|
async countCollection(collectionPath) {
|
||||||
@@ -174,19 +187,12 @@ export function createFirebaseStorage() {
|
|||||||
|
|
||||||
subscribeCollection(collectionPath, cb, queryConstraints = [], errCb) {
|
subscribeCollection(collectionPath, cb, queryConstraints = [], errCb) {
|
||||||
recordAdapterCall({ fn: 'subscribeCollection', path: collectionPath });
|
recordAdapterCall({ fn: 'subscribeCollection', path: collectionPath });
|
||||||
// queryConstraints = neutral {__type} builders (from index.js).
|
const { fbConstraints, offsetN } = toSdkConstraints(queryConstraints);
|
||||||
// Translate to SDK orderBy/limit.
|
const q = fbConstraints.length > 0
|
||||||
const sdkConstraints = queryConstraints.map(c => {
|
? query(collection(db, collectionPath), ...fbConstraints)
|
||||||
if (c.__type === 'where') return where(c.field, c.op, c.value);
|
|
||||||
if (c.__type === 'orderBy') return orderBy(c.field, c.dir);
|
|
||||||
if (c.__type === 'limit') return limit(c.n);
|
|
||||||
return c; // pass-through (forward compat)
|
|
||||||
});
|
|
||||||
const q = sdkConstraints.length > 0
|
|
||||||
? query(collection(db, collectionPath), ...sdkConstraints)
|
|
||||||
: collection(db, collectionPath);
|
: collection(db, collectionPath);
|
||||||
return onSnapshot(q, (snap) => {
|
return onSnapshot(q, (snap) => {
|
||||||
cb(snap.docs.map(d => ({ id: d.id, ...d.data() })));
|
cb(snap.docs.slice(offsetN).map(d => ({ id: d.id, ...d.data() })));
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
console.error(`subscribeCollection ${collectionPath}:`, err);
|
console.error(`subscribeCollection ${collectionPath}:`, err);
|
||||||
if (typeof errCb === 'function') errCb(err);
|
if (typeof errCb === 'function') errCb(err);
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ describe('Campaign -> Firebase', () => {
|
|||||||
|
|
||||||
// CharacterManager form
|
// CharacterManager form
|
||||||
fireEvent.change(screen.getByPlaceholderText('Character name'), { target: { value: 'Brog' } });
|
fireEvent.change(screen.getByPlaceholderText('Character name'), { target: { value: 'Brog' } });
|
||||||
fireEvent.change(screen.getByLabelText(/Default HP/i), { target: { value: '25' } });
|
fireEvent.change(screen.getByLabelText(/^HP$/i), { target: { value: '25' } });
|
||||||
fireEvent.change(screen.getByLabelText(/Init Mod/i), { target: { value: '3' } });
|
fireEvent.change(screen.getByLabelText(/Init Mod/i), { target: { value: '3' } });
|
||||||
fireEvent.click(screen.getByRole('button', { name: /Add Character/i }));
|
fireEvent.click(screen.getByRole('button', { name: /Add Character/i }));
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { isDevToolsEnabled } from '../config/devTools';
|
||||||
|
|
||||||
|
describe('Bulk-delete-all dev-tools gate logic', () => {
|
||||||
|
const orig = process.env.REACT_APP_DEV_TOOLS;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (orig === undefined) delete process.env.REACT_APP_DEV_TOOLS;
|
||||||
|
else process.env.REACT_APP_DEV_TOOLS = orig;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('false when unset (safe default)', () => {
|
||||||
|
delete process.env.REACT_APP_DEV_TOOLS;
|
||||||
|
expect(isDevToolsEnabled()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('false when 0', () => {
|
||||||
|
process.env.REACT_APP_DEV_TOOLS = '0';
|
||||||
|
expect(isDevToolsEnabled()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('false when arbitrary string', () => {
|
||||||
|
process.env.REACT_APP_DEV_TOOLS = 'true';
|
||||||
|
expect(isDevToolsEnabled()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('true only when exactly 1', () => {
|
||||||
|
process.env.REACT_APP_DEV_TOOLS = '1';
|
||||||
|
expect(isDevToolsEnabled()).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react';
|
||||||
|
import App from '../App';
|
||||||
|
|
||||||
|
describe('Bulk-delete-all button render gating', () => {
|
||||||
|
const orig = process.env.REACT_APP_DEV_TOOLS;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
if (orig === undefined) delete process.env.REACT_APP_DEV_TOOLS;
|
||||||
|
else process.env.REACT_APP_DEV_TOOLS = orig;
|
||||||
|
});
|
||||||
|
|
||||||
|
async function renderAndCreateCampaign() {
|
||||||
|
window.history.replaceState({}, '', '/');
|
||||||
|
global.alert = jest.fn();
|
||||||
|
global.window.open = jest.fn();
|
||||||
|
render(<App />);
|
||||||
|
await waitFor(() => screen.getByRole('button', { name: /Create Campaign/i }));
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Create Campaign/i }));
|
||||||
|
});
|
||||||
|
await waitFor(() => screen.getByLabelText(/Campaign Name/i));
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.change(screen.getByLabelText(/Campaign Name/i), { target: { value: 'Gate Render Test' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Create$/i }));
|
||||||
|
await new Promise(r => setTimeout(r, 200));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('prod safety: button absent when DEV_TOOLS unset', async () => {
|
||||||
|
delete process.env.REACT_APP_DEV_TOOLS;
|
||||||
|
await renderAndCreateCampaign();
|
||||||
|
expect(screen.queryByText(/Delete All Campaigns/i)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react';
|
||||||
|
import App from '../App';
|
||||||
|
|
||||||
|
describe('Bulk-delete-all button dev feature', () => {
|
||||||
|
const orig = process.env.REACT_APP_DEV_TOOLS;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
if (orig === undefined) delete process.env.REACT_APP_DEV_TOOLS;
|
||||||
|
else process.env.REACT_APP_DEV_TOOLS = orig;
|
||||||
|
});
|
||||||
|
|
||||||
|
async function renderAndCreateCampaign() {
|
||||||
|
window.history.replaceState({}, '', '/');
|
||||||
|
global.alert = jest.fn();
|
||||||
|
global.window.open = jest.fn();
|
||||||
|
render(<App />);
|
||||||
|
await waitFor(() => screen.getByRole('button', { name: /Create Campaign/i }));
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Create Campaign/i }));
|
||||||
|
});
|
||||||
|
await waitFor(() => screen.getByLabelText(/Campaign Name/i));
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.change(screen.getByLabelText(/Campaign Name/i), { target: { value: 'Gate Render Test' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Create$/i }));
|
||||||
|
await new Promise(r => setTimeout(r, 200));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('dev: button present when DEV_TOOLS=1 and campaigns exist', async () => {
|
||||||
|
process.env.REACT_APP_DEV_TOOLS = '1';
|
||||||
|
await renderAndCreateCampaign();
|
||||||
|
await waitFor(() => screen.getByText(/Delete All Campaigns/i), { timeout: 5000 });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import App from '../App';
|
||||||
|
import { setupReady, MOCK_DB } from './testHelpers';
|
||||||
|
|
||||||
|
const statusPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status';
|
||||||
|
const campaignPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/caf-camp';
|
||||||
|
const encounterPath = `${campaignPath}/encounters/caf-enc`;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.removeItem('ttrpg.wakeLock');
|
||||||
|
Object.defineProperty(navigator, 'wakeLock', {
|
||||||
|
configurable: true,
|
||||||
|
value: { request: jest.fn().mockResolvedValue({ released: false, release: jest.fn(), addEventListener: jest.fn() }) },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
window.history.replaceState({}, '', '/');
|
||||||
|
localStorage.removeItem('ttrpg.wakeLock');
|
||||||
|
delete navigator.wakeLock;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('admin and encounter buttons: icon only, OFF slashed/plain, ON colored', async () => {
|
||||||
|
await setupReady('Caf Camp', 'Caf Enc');
|
||||||
|
const off = screen.getAllByRole('button', { name: 'Caffeine OFF' });
|
||||||
|
expect(off).toHaveLength(2);
|
||||||
|
off.forEach(button => {
|
||||||
|
expect(button).toHaveAttribute('aria-pressed', 'false');
|
||||||
|
expect(button.querySelector('.caf-slash')).toBeInTheDocument();
|
||||||
|
expect(button).not.toHaveClass('bg-amber-600');
|
||||||
|
});
|
||||||
|
fireEvent.click(off[0]);
|
||||||
|
await waitFor(() => expect(screen.getAllByRole('button', { name: 'Caffeine ON' })).toHaveLength(2));
|
||||||
|
screen.getAllByRole('button', { name: 'Caffeine ON' }).forEach(button => {
|
||||||
|
expect(button).toHaveAttribute('aria-pressed', 'true');
|
||||||
|
expect(button.querySelector('.caf-slash')).not.toBeInTheDocument();
|
||||||
|
expect(button).toHaveClass('bg-amber-600');
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getAllByRole('button', { name: 'Caffeine ON' })[0]);
|
||||||
|
expect(screen.getAllByRole('button', { name: 'Caffeine OFF' })).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([false, true])('player display button icon-only state (active=%s)', async active => {
|
||||||
|
window.history.replaceState({}, '', '/display');
|
||||||
|
if (active) {
|
||||||
|
MOCK_DB.set(campaignPath, { name: 'Caf Camp' });
|
||||||
|
MOCK_DB.set(encounterPath, { name: 'Caf Enc', participants: [], isStarted: false });
|
||||||
|
MOCK_DB.set(statusPath, { activeCampaignId: 'caf-camp', activeEncounterId: 'caf-enc' });
|
||||||
|
}
|
||||||
|
render(<App />);
|
||||||
|
const off = await screen.findByRole('button', { name: 'Caffeine OFF' });
|
||||||
|
expect(off).toHaveAttribute('aria-pressed', 'false');
|
||||||
|
expect(off.querySelector('.caf-slash')).toBeInTheDocument();
|
||||||
|
fireEvent.click(off);
|
||||||
|
const on = await screen.findByRole('button', { name: 'Caffeine ON' });
|
||||||
|
expect(on).toHaveAttribute('aria-pressed', 'true');
|
||||||
|
expect(on.querySelector('.caf-slash')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { renderApp, createCampaignViaUI, MOCK_DB } from './testHelpers';
|
||||||
|
|
||||||
|
const campaignPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`;
|
||||||
|
|
||||||
|
async function setup(name = 'Original Camp') {
|
||||||
|
await renderApp();
|
||||||
|
const id = await createCampaignViaUI(name);
|
||||||
|
await screen.findByRole('heading', { name: name, level: 3 });
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openEditor(name = 'Original Camp') {
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: `Edit campaign ${name}` }));
|
||||||
|
await screen.findByRole('heading', { name: 'Edit Campaign' });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('edit campaign creation settings', () => {
|
||||||
|
test('prefills name, background URL, ruleset; saves only those fields', async () => {
|
||||||
|
const id = await setup();
|
||||||
|
await openEditor();
|
||||||
|
expect(screen.getByLabelText('Campaign Name')).toHaveValue('Original Camp');
|
||||||
|
expect(screen.getByLabelText('Player Display Background URL (Optional)')).toHaveValue('');
|
||||||
|
expect(screen.getByRole('radio', { name: /D&D 5e/ })).toBeChecked();
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText('Campaign Name'), { target: { value: 'Renamed Camp' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Player Display Background URL (Optional)'), { target: { value: 'https://example.com/bg.jpg' } });
|
||||||
|
fireEvent.click(screen.getByRole('radio', { name: /Generic/ }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save Campaign' }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(MOCK_DB.get(campaignPath(id))).toMatchObject({
|
||||||
|
name: 'Renamed Camp',
|
||||||
|
playerDisplayBackgroundUrl: 'https://example.com/bg.jpg',
|
||||||
|
ruleset: 'generic',
|
||||||
|
players: [],
|
||||||
|
ownerId: expect.any(String),
|
||||||
|
createdAt: expect.any(String),
|
||||||
|
}));
|
||||||
|
expect(await screen.findByRole('heading', { name: 'Renamed Camp', level: 3 })).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('heading', { name: 'Edit Campaign' })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clears existing background and switches ruleset back, preserving roster', async () => {
|
||||||
|
const id = await setup('Changes Camp');
|
||||||
|
// First save an existing background and generic ruleset through editor.
|
||||||
|
await openEditor('Changes Camp');
|
||||||
|
fireEvent.change(screen.getByLabelText('Player Display Background URL (Optional)'), { target: { value: 'https://example.com/old.jpg' } });
|
||||||
|
fireEvent.click(screen.getByRole('radio', { name: /Generic/ }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save Campaign' }));
|
||||||
|
await waitFor(() => expect(MOCK_DB.get(campaignPath(id)).ruleset).toBe('generic'));
|
||||||
|
|
||||||
|
await openEditor('Changes Camp');
|
||||||
|
expect(screen.getByLabelText('Player Display Background URL (Optional)')).toHaveValue('https://example.com/old.jpg');
|
||||||
|
expect(screen.getByRole('radio', { name: /Generic/ })).toBeChecked();
|
||||||
|
fireEvent.change(screen.getByLabelText('Player Display Background URL (Optional)'), { target: { value: '' } });
|
||||||
|
fireEvent.click(screen.getByRole('radio', { name: /D&D 5e/ }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save Campaign' }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(MOCK_DB.get(campaignPath(id))).toMatchObject({
|
||||||
|
playerDisplayBackgroundUrl: '', ruleset: '5e', players: [],
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Cancel leaves campaign unchanged; whitespace-only name cannot save', async () => {
|
||||||
|
const id = await setup('Keep Camp');
|
||||||
|
await openEditor('Keep Camp');
|
||||||
|
fireEvent.change(screen.getByLabelText('Campaign Name'), { target: { value: 'Discard Camp' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||||
|
expect(MOCK_DB.get(campaignPath(id)).name).toBe('Keep Camp');
|
||||||
|
|
||||||
|
await openEditor('Keep Camp');
|
||||||
|
fireEvent.change(screen.getByLabelText('Campaign Name'), { target: { value: ' ' } });
|
||||||
|
expect(screen.getByRole('button', { name: 'Save Campaign' })).toBeDisabled();
|
||||||
|
expect(MOCK_DB.get(campaignPath(id)).name).toBe('Keep Camp');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// Character encounter adds must use roster values written back at encounter end.
|
||||||
|
// Both single-add and Add All previously reset Current HP to Max HP; Add All also lost AC.
|
||||||
|
|
||||||
|
import { screen, fireEvent, waitFor, within, act } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import {
|
||||||
|
renderApp, createCampaignViaUI, selectCampaignByName,
|
||||||
|
createEncounterViaUI, selectEncounterByName, getParticipantForm, MOCK_DB,
|
||||||
|
} from './testHelpers';
|
||||||
|
|
||||||
|
const campPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`;
|
||||||
|
const encPath = (cid, eid) => `${campPath(cid)}/encounters/${eid}`;
|
||||||
|
|
||||||
|
async function setup(name) {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI(`${name} Camp`);
|
||||||
|
await selectCampaignByName(`${name} Camp`);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Wounded Hero' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('HP', { selector: '#defaultMaxHp' }), { target: { value: '30' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('AC', { selector: '#defaultAc' }), { target: { value: '18' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText('Wounded Hero');
|
||||||
|
|
||||||
|
// Values equivalent to end-encounter writeback.
|
||||||
|
const campaign = MOCK_DB.get(campPath(cid));
|
||||||
|
campaign.players = campaign.players.map(p => p.name === 'Wounded Hero'
|
||||||
|
? { ...p, defaultMaxHp: 30, defaultCurrentHp: 11, defaultAc: 18 }
|
||||||
|
: p);
|
||||||
|
MOCK_DB.set(campPath(cid), campaign);
|
||||||
|
await screen.findByText('Current HP 11');
|
||||||
|
|
||||||
|
const eid = await createEncounterViaUI(`${name} Encounter`);
|
||||||
|
await selectEncounterByName(`${name} Encounter`);
|
||||||
|
return { cid, eid };
|
||||||
|
}
|
||||||
|
|
||||||
|
function expectWrittenDefaults(cid, eid) {
|
||||||
|
const participant = MOCK_DB.get(encPath(cid, eid)).participants.find(p => p.name === 'Wounded Hero');
|
||||||
|
expect(participant).toBeDefined();
|
||||||
|
expect(participant.maxHp).toBe(30);
|
||||||
|
expect(participant.currentHp).toBe(11);
|
||||||
|
expect(participant.ac).toBe(18);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('roster defaults used when adding character to encounter', () => {
|
||||||
|
test('single character add uses written-back Current HP and AC', async () => {
|
||||||
|
const { cid, eid } = await setup('Single Defaults');
|
||||||
|
|
||||||
|
await act(async () => { await new Promise(r => setTimeout(r, 250)); });
|
||||||
|
let form = within(getParticipantForm());
|
||||||
|
const typeSelect = form.getAllByRole('combobox').find(s => [...s.options].some(o => o.value === 'character'));
|
||||||
|
fireEvent.change(typeSelect, { target: { value: 'character' } });
|
||||||
|
|
||||||
|
await act(async () => { await new Promise(r => setTimeout(r, 100)); });
|
||||||
|
form = within(getParticipantForm());
|
||||||
|
const characterSelect = form.getAllByRole('combobox').find(s => [...s.options].some(o => o.textContent.includes('Wounded Hero')));
|
||||||
|
const option = [...characterSelect.options].find(o => o.textContent.includes('Wounded Hero'));
|
||||||
|
fireEvent.change(characterSelect, { target: { value: option.value } });
|
||||||
|
|
||||||
|
await act(async () => { await new Promise(r => setTimeout(r, 250)); });
|
||||||
|
fireEvent.click(within(getParticipantForm()).getByRole('button', { name: /Add to Encounter/i }));
|
||||||
|
|
||||||
|
await waitFor(() => expectWrittenDefaults(cid, eid));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Add All uses written-back Current HP and AC', async () => {
|
||||||
|
const { cid, eid } = await setup('Bulk Defaults');
|
||||||
|
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /Add All \(Roll Init\)/i }));
|
||||||
|
|
||||||
|
await waitFor(() => expectWrittenDefaults(cid, eid));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// Display guard: starting encounter does NOT steal display from another live encounter.
|
||||||
|
// Ending encounter does NOT clear display if different encounter showing.
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { getCalls, MOCK_DB } from '../__mocks__/firebase/_mock-db';
|
||||||
|
import { setupReady, addMonsterViaUI, startCombatViaUI } from './testHelpers';
|
||||||
|
|
||||||
|
const DISPLAY_PATH = 'artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status';
|
||||||
|
|
||||||
|
function findCallActiveDisplay(fn) {
|
||||||
|
return getCalls().filter(c => c.fn === fn && c.path.includes('activeDisplay/status'));
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Display guard', () => {
|
||||||
|
test('startEncounter: claims display when slot empty', async () => {
|
||||||
|
await setupReady('GuardCamp1', 'GuardEnc1');
|
||||||
|
await addMonsterViaUI('Goblin', 10, 5);
|
||||||
|
await startCombatViaUI();
|
||||||
|
const adCalls = findCallActiveDisplay('setDoc');
|
||||||
|
const last = adCalls[adCalls.length - 1];
|
||||||
|
expect(last).toBeTruthy();
|
||||||
|
expect(last.data.activeEncounterId).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('startEncounter: does NOT steal display from another live encounter', async () => {
|
||||||
|
// Pre-seed display as busy with a DIFFERENT encounter
|
||||||
|
MOCK_DB.set(DISPLAY_PATH, {
|
||||||
|
activeCampaignId: 'other-camp',
|
||||||
|
activeEncounterId: 'other-enc',
|
||||||
|
});
|
||||||
|
|
||||||
|
await setupReady('GuardCamp2', 'GuardEnc2');
|
||||||
|
await addMonsterViaUI('Orc', 15, 8);
|
||||||
|
await startCombatViaUI();
|
||||||
|
|
||||||
|
// Combat started on encounter doc
|
||||||
|
const encCalls = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/'));
|
||||||
|
expect(encCalls.some(c => c.data.isStarted === true)).toBe(true);
|
||||||
|
|
||||||
|
// But display setDoc should NOT have been called to claim this encounter
|
||||||
|
const adClaims = findCallActiveDisplay('setDoc').filter(
|
||||||
|
c => c.data && c.data.activeEncounterId && c.data.activeEncounterId !== 'other-enc'
|
||||||
|
);
|
||||||
|
expect(adClaims).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('endEncounter: clears display when ending the displayed encounter', async () => {
|
||||||
|
await setupReady('GuardCamp3', 'GuardEnc3');
|
||||||
|
await addMonsterViaUI('Wolf', 8, 3);
|
||||||
|
await startCombatViaUI();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /End Combat/i }));
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /Confirm/i }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const adCalls = findCallActiveDisplay('setDoc');
|
||||||
|
const last = adCalls[adCalls.length - 1];
|
||||||
|
return last && last.data && last.data.activeCampaignId === null;
|
||||||
|
});
|
||||||
|
const adCalls = findCallActiveDisplay('setDoc');
|
||||||
|
const last = adCalls[adCalls.length - 1];
|
||||||
|
expect(last.data).toMatchObject({ activeCampaignId: null, activeEncounterId: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('endEncounter: does NOT clear display when different encounter is live', async () => {
|
||||||
|
await setupReady('GuardCamp4', 'GuardEnc4');
|
||||||
|
await addMonsterViaUI('Bat', 4, 2);
|
||||||
|
await startCombatViaUI();
|
||||||
|
|
||||||
|
// Now hijack display to a different encounter (simulating eyeball toggle elsewhere)
|
||||||
|
MOCK_DB.set(DISPLAY_PATH, {
|
||||||
|
activeCampaignId: 'different-camp',
|
||||||
|
activeEncounterId: 'different-enc',
|
||||||
|
});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /End Combat/i }));
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /Confirm/i }));
|
||||||
|
|
||||||
|
// Wait for encounter to end
|
||||||
|
await waitFor(() => {
|
||||||
|
const encCalls = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/'));
|
||||||
|
const last = encCalls[encCalls.length - 1];
|
||||||
|
return last && last.data.isStarted === false;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Display should NOT have been cleared
|
||||||
|
const clearCalls = findCallActiveDisplay('setDoc').filter(
|
||||||
|
c => c.data && c.data.activeCampaignId === null
|
||||||
|
);
|
||||||
|
expect(clearCalls).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -39,6 +39,10 @@ function participant(status) {
|
|||||||
|
|
||||||
describe('DisplayView characterization', () => {
|
describe('DisplayView characterization', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
const favicon = document.createElement('link');
|
||||||
|
favicon.rel = 'icon';
|
||||||
|
favicon.href = '/favicon.ico';
|
||||||
|
document.head.appendChild(favicon);
|
||||||
window.history.replaceState({}, '', '/display');
|
window.history.replaceState({}, '', '/display');
|
||||||
global.alert = jest.fn();
|
global.alert = jest.fn();
|
||||||
window.open = jest.fn();
|
window.open = jest.fn();
|
||||||
@@ -46,9 +50,18 @@ describe('DisplayView characterization', () => {
|
|||||||
Element.prototype.scrollIntoView = jest.fn();
|
Element.prototype.scrollIntoView = jest.fn();
|
||||||
});
|
});
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
document.querySelectorAll('link[rel="icon"]').forEach(link => link.remove());
|
||||||
window.history.replaceState({}, '', '/');
|
window.history.replaceState({}, '', '/');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('display route swaps browser favicon to player icon', async () => {
|
||||||
|
seedActiveDisplay();
|
||||||
|
render(<App />);
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(document.querySelector('link[rel="icon"]')).toHaveAttribute('href', '/player-favicon.ico');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test('DisplayView subscribes via adapter.subscribeDoc (not raw SDK)', async () => {
|
test('DisplayView subscribes via adapter.subscribeDoc (not raw SDK)', async () => {
|
||||||
seedActiveDisplay();
|
seedActiveDisplay();
|
||||||
render(<App />);
|
render(<App />);
|
||||||
@@ -94,7 +107,7 @@ describe('DisplayView characterization', () => {
|
|||||||
expect(screen.getAllByText(/Dead/i).length).toBeGreaterThan(0);
|
expect(screen.getAllByText(/Dead/i).length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('DisplayView hides inactive participants for all types', async () => {
|
test('DisplayView hides inactive participants for all types after fade-out', async () => {
|
||||||
seedActiveDisplay([
|
seedActiveDisplay([
|
||||||
{ ...participant('conscious'), id: 'active-pc', name: 'Active PC', isActive: true },
|
{ ...participant('conscious'), id: 'active-pc', name: 'Active PC', isActive: true },
|
||||||
{ ...participant('conscious'), id: 'inactive-pc', name: 'Inactive PC', isActive: false },
|
{ ...participant('conscious'), id: 'inactive-pc', name: 'Inactive PC', isActive: false },
|
||||||
@@ -103,7 +116,8 @@ describe('DisplayView characterization', () => {
|
|||||||
render(<App />);
|
render(<App />);
|
||||||
|
|
||||||
await waitFor(() => expect(screen.getByText('Active PC')).toBeInTheDocument());
|
await waitFor(() => expect(screen.getByText('Active PC')).toBeInTheDocument());
|
||||||
expect(screen.queryByText('Inactive PC')).not.toBeInTheDocument();
|
// inactive held during exit animation, removed after transition
|
||||||
|
await waitFor(() => expect(screen.queryByText('Inactive PC')).not.toBeInTheDocument(), { timeout: 1500 });
|
||||||
expect(screen.queryByText('Inactive Monster')).not.toBeInTheDocument();
|
expect(screen.queryByText('Inactive Monster')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// Player display death-save tracker: dying/stable characters show save pips.
|
||||||
|
// Admin already has pips; display showed only "(Dying)" label — players blind.
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
import { render, waitFor, screen } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import App from '../App';
|
||||||
|
import { MOCK_DB } from '../__mocks__/firebase/_mock-db';
|
||||||
|
|
||||||
|
const campaignPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/c1';
|
||||||
|
const encounterPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/c1/encounters/e1';
|
||||||
|
const activeDisplayPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status';
|
||||||
|
|
||||||
|
function seed(participants, ruleset = '5e') {
|
||||||
|
MOCK_DB.set(campaignPath, { name: 'Camp', playerDisplayBackgroundUrl: '' });
|
||||||
|
MOCK_DB.set(encounterPath, { name: 'Enc', participants, ruleset, isStarted: true, round: 2, currentTurnParticipantId: null });
|
||||||
|
MOCK_DB.set(activeDisplayPath, { activeCampaignId: 'c1', activeEncounterId: 'e1', hidePlayerHp: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
function char(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: 'p1',
|
||||||
|
name: 'Rogue',
|
||||||
|
type: 'character',
|
||||||
|
initiative: 18,
|
||||||
|
maxHp: 40,
|
||||||
|
currentHp: 0,
|
||||||
|
isActive: true,
|
||||||
|
status: 'dying',
|
||||||
|
deathSaveSuccesses: 0,
|
||||||
|
deathSaveFailures: 0,
|
||||||
|
conditions: ['unconscious'],
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const favicon = document.createElement('link');
|
||||||
|
favicon.rel = 'icon';
|
||||||
|
favicon.href = '/favicon.ico';
|
||||||
|
document.head.appendChild(favicon);
|
||||||
|
window.history.replaceState({}, '', '/display');
|
||||||
|
global.alert = jest.fn();
|
||||||
|
window.open = jest.fn();
|
||||||
|
Element.prototype.scrollIntoView = jest.fn();
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
document.querySelectorAll('link[rel="icon"]').forEach(l => l.remove());
|
||||||
|
window.history.replaceState({}, '', '/');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('player display death saves', () => {
|
||||||
|
test('dying character shows success and failure pips with counts', async () => {
|
||||||
|
seed([char({ deathSaveSuccesses: 1, deathSaveFailures: 2 })]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Rogue');
|
||||||
|
|
||||||
|
const row = screen.getByTestId('death-save-tracker');
|
||||||
|
expect(row).toBeInTheDocument();
|
||||||
|
expect(row.querySelectorAll('[data-save="success"]').length).toBe(3);
|
||||||
|
expect(row.querySelectorAll('[data-save="failure"]').length).toBe(3);
|
||||||
|
expect(row.querySelectorAll('[data-save="success"][data-filled="true"]').length).toBe(1);
|
||||||
|
expect(row.querySelectorAll('[data-save="failure"][data-filled="true"]').length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stable character hides pips, shows stable/regains note', async () => {
|
||||||
|
seed([char({ status: 'stable', deathSaveSuccesses: 3 })]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Rogue');
|
||||||
|
|
||||||
|
expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Stable — regains 1 HP after 1d4 hours/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('conscious character shows no pips', async () => {
|
||||||
|
seed([char({ status: 'conscious', currentHp: 10, conditions: [] })]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Rogue');
|
||||||
|
expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('generic ruleset: no pips even at zero HP', async () => {
|
||||||
|
seed([char({ status: 'down' })], 'generic');
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Rogue');
|
||||||
|
expect(screen.queryByTestId('death-save-tracker')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { render, screen, within } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import App from '../App';
|
||||||
|
import { MOCK_DB } from '../__mocks__/firebase/_mock-db';
|
||||||
|
|
||||||
|
const campaignPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/c1';
|
||||||
|
const encounterPath = `${campaignPath}/encounters/e1`;
|
||||||
|
const activeDisplayPath = 'artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status';
|
||||||
|
|
||||||
|
function seed(effects) {
|
||||||
|
const participants = [
|
||||||
|
{ id: 'p1', name: 'Cleric', type: 'character', initiative: 18, maxHp: 30, currentHp: 30, isActive: true, conditions: [] },
|
||||||
|
{ id: 'p2', name: 'Zombie', type: 'monster', initiative: 8, maxHp: 22, currentHp: 22, isActive: true, conditions: [] },
|
||||||
|
];
|
||||||
|
MOCK_DB.set(campaignPath, { name: 'Camp', playerDisplayBackgroundUrl: '' });
|
||||||
|
MOCK_DB.set(encounterPath, { name: 'Enc', participants, effects, ruleset: '5e', isStarted: true, round: 2, currentTurnParticipantId: 'p1' });
|
||||||
|
MOCK_DB.set(activeDisplayPath, { activeCampaignId: 'c1', activeEncounterId: 'e1', hidePlayerHp: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const favicon = document.createElement('link');
|
||||||
|
favicon.rel = 'icon';
|
||||||
|
favicon.href = '/favicon.ico';
|
||||||
|
document.head.appendChild(favicon);
|
||||||
|
window.history.replaceState({}, '', '/display');
|
||||||
|
global.alert = jest.fn();
|
||||||
|
window.open = jest.fn();
|
||||||
|
Element.prototype.scrollIntoView = jest.fn();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
document.querySelectorAll('link[rel="icon"]').forEach(l => l.remove());
|
||||||
|
window.history.replaceState({}, '', '/');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('player display tracked effects', () => {
|
||||||
|
test('prominent participant effect renders clear banner with countdown', async () => {
|
||||||
|
seed([{ id: 'fx1', presetId: 'turned', name: 'Turned', scope: 'participant', targetParticipantId: 'p2', ownerParticipantId: 'p1', remainingRounds: 7, expiresOnDamage: true, playerDisplay: 'prominent' }]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Zombie');
|
||||||
|
expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('TURNED');
|
||||||
|
expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('7 rounds remaining');
|
||||||
|
expect(screen.getByTestId('prominent-effect-fx1')).toHaveTextContent('Ends on damage');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('compact participant effect renders badge; hidden effect does not render', async () => {
|
||||||
|
seed([
|
||||||
|
{ id: 'fx1', name: 'Bless', scope: 'participant', targetParticipantId: 'p2', remainingRounds: 3, playerDisplay: 'compact' },
|
||||||
|
{ id: 'fx2', name: 'Secret', scope: 'participant', targetParticipantId: 'p2', remainingRounds: 4, playerDisplay: 'hidden' },
|
||||||
|
]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Zombie');
|
||||||
|
expect(screen.getByText(/Bless · 3 rounds/i)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(/Secret/i)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('owner-linked encounter effect renders prominently on owner card', async () => {
|
||||||
|
seed([{ id: 'fx3', presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter', ownerParticipantId: 'p1', remainingRounds: 8, expiresOnDamage: false, playerDisplay: 'prominent' }]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Zombie');
|
||||||
|
const clericCard = screen.getByTestId('participant-card-p1');
|
||||||
|
const banner = within(clericCard).getByTestId('encounter-effect-fx3');
|
||||||
|
expect(banner).toHaveTextContent('SPIRITUAL WEAPON');
|
||||||
|
expect(banner).toHaveTextContent('Cleric');
|
||||||
|
expect(banner).toHaveTextContent('8 rounds remaining');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ownerless encounter effect remains in global fallback area', async () => {
|
||||||
|
seed([{ id: 'fx4', name: 'Fog Cloud', scope: 'encounter', ownerParticipantId: null, remainingRounds: 5, playerDisplay: 'prominent' }]);
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByText('Zombie');
|
||||||
|
const banner = screen.getByTestId('encounter-effect-fx4');
|
||||||
|
expect(banner).toHaveTextContent('FOG CLOUD');
|
||||||
|
expect(screen.getByTestId('participant-card-p1')).not.toContainElement(banner);
|
||||||
|
expect(screen.getByTestId('participant-card-p2')).not.toContainElement(banner);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
// Encounter list groups: In Progress / Ready / Completed.
|
||||||
|
// Completed collapsed by default. Group headers show counts.
|
||||||
|
|
||||||
|
import { screen, fireEvent, act } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { MOCK_DB } from '../__mocks__/firebase/_mock-db';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName } from './testHelpers';
|
||||||
|
|
||||||
|
const encPath = (cid, eid) => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`;
|
||||||
|
|
||||||
|
async function seedEncounter(cid, eid, fields) {
|
||||||
|
act(() => {
|
||||||
|
MOCK_DB.set(encPath(cid, eid), {
|
||||||
|
id: eid,
|
||||||
|
name: fields.name,
|
||||||
|
participants: [],
|
||||||
|
round: 0,
|
||||||
|
isStarted: false,
|
||||||
|
isPaused: false,
|
||||||
|
createdAt: fields.createdAt || '2026-07-01T00:00:00Z',
|
||||||
|
order: fields.order,
|
||||||
|
...fields,
|
||||||
|
});
|
||||||
|
// touch collection so useFirestoreCollection snapshot re-emits
|
||||||
|
MOCK_DB.set(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}`, { name: cid, players: [] });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('encounter list grouping', () => {
|
||||||
|
test('groups appear with counts: In Progress, Ready, Completed', async () => {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI('GroupCamp');
|
||||||
|
await selectCampaignByName('GroupCamp');
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
MOCK_DB.set(encPath(cid, 'e-ready'), { id: 'e-ready', name: 'Ready One', participants: [], round: 0, isStarted: false, isPaused: false, createdAt: '2026-07-01T00:00:00Z' });
|
||||||
|
MOCK_DB.set(encPath(cid, 'e-prog'), { id: 'e-prog', name: 'Live One', participants: [], round: 0, isStarted: true, startedAt: 1, isPaused: false, createdAt: '2026-07-01T00:00:00Z' });
|
||||||
|
MOCK_DB.set(encPath(cid, 'e-done'), { id: 'e-done', name: 'Old One', participants: [], round: 0, isStarted: false, startedAt: 1, endedAt: 2, isPaused: false, createdAt: '2026-07-01T00:00:00Z' });
|
||||||
|
MOCK_DB.set(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}`, { name: cid, players: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
// gate on card text first (groups render), then headers.
|
||||||
|
// 'Old One' lives in collapsed Completed group — assert after expanding.
|
||||||
|
await screen.findByText('Live One');
|
||||||
|
await screen.findByText('Ready One');
|
||||||
|
expect(screen.getByRole('button', { name: /⚔ In Progress/ })).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /^Ready/ })).toBeInTheDocument();
|
||||||
|
const completedBtn = screen.getByRole('button', { name: /^Completed/ });
|
||||||
|
expect(completedBtn).toBeInTheDocument();
|
||||||
|
fireEvent.click(completedBtn);
|
||||||
|
expect(await screen.findByText('Old One')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('completed encounters hidden until group expanded', async () => {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI('GroupCamp2');
|
||||||
|
await selectCampaignByName('GroupCamp2');
|
||||||
|
|
||||||
|
await seedEncounter(cid, 'e-done2', { name: 'Hidden Corpse', isStarted: false, startedAt: 1, endedAt: 2 });
|
||||||
|
|
||||||
|
expect(await screen.findByRole('button', { name: /^Completed/ })).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('Hidden Corpse')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Completed/ }));
|
||||||
|
expect(await screen.findByText('Hidden Corpse')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('in-progress and ready encounters visible by default', async () => {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI('GroupCamp3');
|
||||||
|
await selectCampaignByName('GroupCamp3');
|
||||||
|
|
||||||
|
await seedEncounter(cid, 'e-ready3', { name: 'Visible Ready', isStarted: false });
|
||||||
|
await seedEncounter(cid, 'e-prog3', { name: 'Visible Live', isStarted: true, startedAt: 1 });
|
||||||
|
|
||||||
|
expect(await screen.findByText('Visible Ready')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Visible Live')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { screen, fireEvent, waitFor, within } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import {
|
||||||
|
setupReady, addMonsterViaUI, startCombatViaUI, MOCK_DB,
|
||||||
|
} from './testHelpers';
|
||||||
|
|
||||||
|
function encounterRow() {
|
||||||
|
const row = [...MOCK_DB._state.docs.entries()].find(([path]) => path.includes('/encounters/'));
|
||||||
|
return row ? { path: row[0], doc: MOCK_DB.get(row[0]) } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function participant(name) {
|
||||||
|
return encounterRow().doc.participants.find(p => p.name === name);
|
||||||
|
}
|
||||||
|
|
||||||
|
function card(name) {
|
||||||
|
return screen.getByTestId(`admin-participant-card-${participant(name).id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('encounter participant visibility and kill', () => {
|
||||||
|
test('Kill confirms, sets 0 HP/dead/inactive, and does not delete participant', async () => {
|
||||||
|
await setupReady('Kill Camp', 'Kill Encounter');
|
||||||
|
await addMonsterViaUI('Ogre', 59, 1);
|
||||||
|
|
||||||
|
fireEvent.click(within(card('Ogre')).getByRole('button', { name: 'Kill Ogre' }));
|
||||||
|
expect(await screen.findByText('Kill Ogre?')).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Cancel$/ }));
|
||||||
|
expect(participant('Ogre')).toMatchObject({ currentHp: 59, isActive: true });
|
||||||
|
|
||||||
|
fireEvent.click(within(card('Ogre')).getByRole('button', { name: 'Kill Ogre' }));
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /^Confirm$/ }));
|
||||||
|
await waitFor(() => expect(participant('Ogre')).toMatchObject({ currentHp: 0, tempHp: 0, status: 'dead', isActive: false }));
|
||||||
|
expect(encounterRow().doc.participants).toHaveLength(1);
|
||||||
|
|
||||||
|
const deadCard = card('Ogre');
|
||||||
|
const healFull = within(deadCard).getByRole('button', { name: 'Heal Ogre to full' });
|
||||||
|
const revive = within(deadCard).getByRole('button', { name: /Revive/i });
|
||||||
|
expect(healFull.compareDocumentPosition(revive) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||||
|
fireEvent.click(healFull);
|
||||||
|
await waitFor(() => expect(participant('Ogre')).toMatchObject({ currentHp: 59, status: 'conscious', isActive: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Hide dead never hides player characters', async () => {
|
||||||
|
await setupReady('PC Visibility Camp', 'PC Visibility Encounter');
|
||||||
|
await addMonsterViaUI('Dead Monster', 10, 1);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Dead Hero' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText('Dead Hero');
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Add All \(Roll Init\)/i }));
|
||||||
|
await waitFor(() => expect(participant('Dead Hero')).toBeDefined());
|
||||||
|
|
||||||
|
for (const name of ['Dead Monster', 'Dead Hero']) {
|
||||||
|
fireEvent.click(within(card(name)).getByRole('button', { name: `Kill ${name}` }));
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /^Confirm$/ }));
|
||||||
|
await waitFor(() => expect(participant(name).status).toBe('dead'));
|
||||||
|
await waitFor(() => expect(screen.queryByText(`Kill ${name}?`)).not.toBeInTheDocument());
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(screen.getByRole('button', { name: /Hide dead \(1\)/i })).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Hide dead \(1\)/i }));
|
||||||
|
await waitFor(() => expect(screen.queryByText('Dead Monster')).not.toBeInTheDocument());
|
||||||
|
expect(screen.getByTestId(`admin-participant-card-${participant('Dead Hero').id}`)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Hide disabled and Hide dead are independent, persisted, and unchanged by pause', async () => {
|
||||||
|
await setupReady('Visibility Camp', 'Visibility Encounter');
|
||||||
|
await addMonsterViaUI('Alive', 10, 3);
|
||||||
|
await addMonsterViaUI('Disabled', 10, 2);
|
||||||
|
await addMonsterViaUI('Dead', 10, 1);
|
||||||
|
|
||||||
|
fireEvent.click(within(card('Disabled')).getByRole('button', { name: 'Disable participant' }));
|
||||||
|
await waitFor(() => expect(participant('Disabled').isActive).toBe(false));
|
||||||
|
fireEvent.click(within(card('Dead')).getByRole('button', { name: 'Kill Dead' }));
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /^Confirm$/ }));
|
||||||
|
await waitFor(() => expect(participant('Dead').status).toBe('dead'));
|
||||||
|
|
||||||
|
// Disabled count includes dead+inactive. Filters overlap independently.
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Hide disabled \(2\)/i }));
|
||||||
|
await waitFor(() => expect(encounterRow().doc.hideDisabledParticipants).toBe(true));
|
||||||
|
expect(screen.queryByText('Disabled')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('Dead')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Show disabled \(2\)/i }));
|
||||||
|
await waitFor(() => expect(screen.getByText('Disabled')).toBeInTheDocument());
|
||||||
|
expect(screen.getByText('Dead')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Hide dead \(1\)/i }));
|
||||||
|
await waitFor(() => expect(encounterRow().doc.hideDeadParticipants).toBe(true));
|
||||||
|
expect(screen.queryByText('Dead')).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Disabled')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Hide disabled \(2\)/i }));
|
||||||
|
await waitFor(() => expect(encounterRow().doc.hideDisabledParticipants).toBe(true));
|
||||||
|
await startCombatViaUI();
|
||||||
|
expect(screen.queryByText('Disabled')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('Dead')).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Pause Combat/i }));
|
||||||
|
expect(screen.queryByText('Disabled')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('Dead')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Show disabled \(2\)/i }));
|
||||||
|
await waitFor(() => expect(screen.getByText('Disabled')).toBeInTheDocument());
|
||||||
|
expect(screen.queryByText('Dead')).not.toBeInTheDocument();
|
||||||
|
expect(encounterRow().doc.hideDeadParticipants).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, MOCK_DB } from './testHelpers';
|
||||||
|
|
||||||
|
async function setup(name = 'Popout Enc') {
|
||||||
|
await renderApp();
|
||||||
|
await createCampaignViaUI('Popout Camp');
|
||||||
|
await selectCampaignByName('Popout Camp');
|
||||||
|
await createEncounterViaUI(name);
|
||||||
|
await screen.findByText(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('encounter open-on-top', () => {
|
||||||
|
test('clicking encounter card opens fixed overlay; back returns to list and clears selection', async () => {
|
||||||
|
await setup();
|
||||||
|
fireEvent.click(screen.getByText('Popout Enc'));
|
||||||
|
|
||||||
|
const popout = await screen.findByTestId('encounter-popout');
|
||||||
|
expect(popout).toHaveClass('fixed', 'inset-0', 'overflow-y-auto');
|
||||||
|
expect(document.body.style.overflow).toBe('hidden');
|
||||||
|
const back = screen.getByRole('button', { name: 'Back to encounters' });
|
||||||
|
expect(back).toHaveClass('min-h-[40px]');
|
||||||
|
expect(screen.getByRole('heading', { level: 3, name: /Managing Encounter: Popout Enc/ })).toHaveClass('sticky', 'top-0');
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Back to encounters' }));
|
||||||
|
await waitFor(() => expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument());
|
||||||
|
expect(document.body.style.overflow).toBe('');
|
||||||
|
expect(screen.queryByText(/Managing Encounter:/)).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Popout Enc')).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /^Ready/ })).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /Create Encounter/ })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('creating encounter does not cover list; clicking card opens it', async () => {
|
||||||
|
await setup('Fresh Enc');
|
||||||
|
expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByText('Fresh Enc'));
|
||||||
|
expect(await screen.findByTestId('encounter-popout')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Back stays on list when displayed encounter receives another snapshot', async () => {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI('Live Popout Camp');
|
||||||
|
await selectCampaignByName('Live Popout Camp');
|
||||||
|
const eid = await createEncounterViaUI('Live Popout Enc');
|
||||||
|
await screen.findByText('Live Popout Enc');
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByTitle('Activate for Player Display'));
|
||||||
|
await waitFor(() => expect(MOCK_DB.get('artifacts/ttrpg-initiative-tracker-default/public/data/activeDisplay/status')?.activeEncounterId).toBe(eid));
|
||||||
|
fireEvent.click(screen.getByText('Live Popout Enc'));
|
||||||
|
await screen.findByTestId('encounter-popout');
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Back to encounters' }));
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Managing Encounter:/)).not.toBeInTheDocument());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
MOCK_DB.merge(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`, { round: 2 });
|
||||||
|
});
|
||||||
|
expect(screen.queryByText(/Managing Encounter:/)).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument();
|
||||||
|
expect(localStorage.getItem(`ttrpg.selectedEncounter.${cid}`)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rename action stays on list instead of opening popout', async () => {
|
||||||
|
await setup('Rename Me');
|
||||||
|
fireEvent.click(screen.getByTitle('Rename Encounter'));
|
||||||
|
expect(await screen.findByDisplayValue('Rename Me')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { screen, fireEvent, act, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, MOCK_DB } from './testHelpers';
|
||||||
|
|
||||||
|
const OPEN_KEY = 'ttrpg.openEncountersOnTop';
|
||||||
|
const COLLAPSE_KEY = 'ttrpg.collapseCompletedEncounters';
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.removeItem(OPEN_KEY);
|
||||||
|
localStorage.removeItem(COLLAPSE_KEY);
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
localStorage.removeItem(OPEN_KEY);
|
||||||
|
localStorage.removeItem(COLLAPSE_KEY);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function setup(name = 'Preference Enc') {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI('Preference Camp');
|
||||||
|
await selectCampaignByName('Preference Camp');
|
||||||
|
const eid = await createEncounterViaUI(name);
|
||||||
|
await screen.findByText(name);
|
||||||
|
return { cid, eid };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('encounter view preferences', () => {
|
||||||
|
test('Open on top switch defaults on; off keeps card selection inline; on restores popout', async () => {
|
||||||
|
await setup();
|
||||||
|
const toggle = screen.getByRole('switch', { name: 'Open on top' });
|
||||||
|
expect(toggle).toBeChecked();
|
||||||
|
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
expect(toggle).not.toBeChecked();
|
||||||
|
expect(localStorage.getItem(OPEN_KEY)).toBe('false');
|
||||||
|
fireEvent.click(screen.getByText('Preference Enc'));
|
||||||
|
expect(screen.getByText(/Managing Encounter: Preference Enc/)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
expect(toggle).toBeChecked();
|
||||||
|
expect(localStorage.getItem(OPEN_KEY)).toBe('true');
|
||||||
|
fireEvent.click(screen.getByText('Preference Enc'));
|
||||||
|
expect(await screen.findByTestId('encounter-popout')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Collapse completed switch defaults on; off shows completed cards; on collapses again', async () => {
|
||||||
|
const { cid, eid } = await setup('Finished Enc');
|
||||||
|
act(() => {
|
||||||
|
MOCK_DB.merge(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`, { endedAt: 2 });
|
||||||
|
});
|
||||||
|
const toggle = screen.getByRole('switch', { name: 'Collapse completed' });
|
||||||
|
expect(toggle).toBeChecked();
|
||||||
|
expect(await screen.findByRole('button', { name: /^Completed/ })).toHaveAttribute('aria-expanded', 'false');
|
||||||
|
expect(screen.queryByText('Finished Enc')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
expect(toggle).not.toBeChecked();
|
||||||
|
expect(localStorage.getItem(COLLAPSE_KEY)).toBe('false');
|
||||||
|
expect(await screen.findByText('Finished Enc')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
expect(toggle).toBeChecked();
|
||||||
|
expect(localStorage.getItem(COLLAPSE_KEY)).toBe('true');
|
||||||
|
await waitFor(() => expect(screen.queryByText('Finished Enc')).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saved off preferences load on mount', async () => {
|
||||||
|
localStorage.setItem(OPEN_KEY, 'false');
|
||||||
|
localStorage.setItem(COLLAPSE_KEY, 'false');
|
||||||
|
const { cid, eid } = await setup('Saved Enc');
|
||||||
|
expect(screen.getByRole('switch', { name: 'Open on top' })).not.toBeChecked();
|
||||||
|
expect(screen.getByRole('switch', { name: 'Collapse completed' })).not.toBeChecked();
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
MOCK_DB.merge(`artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`, { endedAt: 3 });
|
||||||
|
});
|
||||||
|
expect(await screen.findByText('Saved Enc')).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByText('Saved Enc'));
|
||||||
|
expect(screen.queryByTestId('encounter-popout')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// Encounter rename: pencil button on card opens inline input, saves via updateDoc.
|
||||||
|
// NOTE: background snapshot rerenders can replace the input/form DOM nodes mid-test,
|
||||||
|
// so every interaction re-queries the live node (fresh()).
|
||||||
|
|
||||||
|
import { screen, fireEvent, act, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, MOCK_DB } from './testHelpers';
|
||||||
|
|
||||||
|
const encPath = (cid, eid) => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`;
|
||||||
|
|
||||||
|
const fresh = () => screen.getByLabelText('Encounter name');
|
||||||
|
const freshQuery = () => screen.queryByLabelText('Encounter name');
|
||||||
|
|
||||||
|
async function openRename() {
|
||||||
|
await screen.findByTitle('Rename Encounter');
|
||||||
|
// settle async rerenders (fetchDetails etc.) so click hits live node
|
||||||
|
await act(async () => { await new Promise(r => setTimeout(r, 250)); });
|
||||||
|
fireEvent.click(screen.getByTitle('Rename Encounter'));
|
||||||
|
await waitFor(() => expect(fresh()).toBeInTheDocument());
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('encounter rename', () => {
|
||||||
|
test('pencil opens inline edit prefilled; Enter saves to Firestore doc', async () => {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI('RenameCamp');
|
||||||
|
await selectCampaignByName('RenameCamp');
|
||||||
|
const eid = await createEncounterViaUI('Old Name');
|
||||||
|
|
||||||
|
await openRename();
|
||||||
|
expect(await screen.findByDisplayValue('Old Name')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.change(fresh(), { target: { value: 'New Name' } });
|
||||||
|
await waitFor(() => expect(fresh().value).toBe('New Name'));
|
||||||
|
// eslint-disable-next-line testing-library/no-node-access
|
||||||
|
fireEvent.submit(fresh().closest('form'));
|
||||||
|
|
||||||
|
await screen.findByText('New Name');
|
||||||
|
expect(MOCK_DB.get(encPath(cid, eid)).name).toBe('New Name');
|
||||||
|
expect(freshQuery()).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Escape cancels without changing doc', async () => {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI('RenameCamp2');
|
||||||
|
await selectCampaignByName('RenameCamp2');
|
||||||
|
const eid = await createEncounterViaUI('Keep Me');
|
||||||
|
|
||||||
|
await openRename();
|
||||||
|
expect(await screen.findByDisplayValue('Keep Me')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.change(fresh(), { target: { value: 'Discard' } });
|
||||||
|
await waitFor(() => expect(fresh().value).toBe('Discard'));
|
||||||
|
fireEvent.keyDown(fresh(), { key: 'Escape', code: 'Escape' });
|
||||||
|
|
||||||
|
await screen.findByText('Keep Me');
|
||||||
|
expect(MOCK_DB.get(encPath(cid, eid)).name).toBe('Keep Me');
|
||||||
|
expect(screen.queryByDisplayValue('Discard')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty name ignored on save', async () => {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI('RenameCamp3');
|
||||||
|
await selectCampaignByName('RenameCamp3');
|
||||||
|
const eid = await createEncounterViaUI('Real Name');
|
||||||
|
|
||||||
|
await openRename();
|
||||||
|
expect(await screen.findByDisplayValue('Real Name')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.change(fresh(), { target: { value: ' ' } });
|
||||||
|
await waitFor(() => expect(fresh().value).toBe(' '));
|
||||||
|
// eslint-disable-next-line testing-library/no-node-access
|
||||||
|
fireEvent.submit(fresh().closest('form'));
|
||||||
|
|
||||||
|
await screen.findByText('Real Name');
|
||||||
|
expect(MOCK_DB.get(encPath(cid, eid)).name).toBe('Real Name');
|
||||||
|
expect(freshQuery()).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// Reroll-all-initiative: button in Add Participants header row, confirm modal,
|
||||||
|
// hidden during active combat. Toggle button persists when section collapsed.
|
||||||
|
|
||||||
|
import { screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, selectEncounterByName, addMonsterViaUI, MOCK_DB, startCombatViaUI } from './testHelpers';
|
||||||
|
|
||||||
|
const encPath = (cid, eid) => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${cid}/encounters/${eid}`;
|
||||||
|
|
||||||
|
async function setupTwoMonsters(camp = 'RerollAllCamp', enc = 'RerollEnc') {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI(camp);
|
||||||
|
await selectCampaignByName(camp);
|
||||||
|
const eid = await createEncounterViaUI(enc);
|
||||||
|
await selectEncounterByName(enc);
|
||||||
|
await addMonsterViaUI('Alpha', 20, 3);
|
||||||
|
await addMonsterViaUI('Beta', 20, 5);
|
||||||
|
return { cid, eid };
|
||||||
|
}
|
||||||
|
|
||||||
|
const partDoc = (cid, eid) => MOCK_DB.get(encPath(cid, eid));
|
||||||
|
|
||||||
|
describe('reroll all initiative', () => {
|
||||||
|
test('button visible pre-combat; confirm rerolls every participant once', async () => {
|
||||||
|
const { cid, eid } = await setupTwoMonsters();
|
||||||
|
|
||||||
|
const btn = await screen.findByRole('button', { name: 'Reroll All Initiative' });
|
||||||
|
expect(btn).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(btn);
|
||||||
|
expect(await screen.findByText(/Reroll initiative for all/i)).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Confirm/i }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const doc = partDoc(cid, eid);
|
||||||
|
expect(doc.participants).toHaveLength(2);
|
||||||
|
for (const p of doc.participants) {
|
||||||
|
const mod = p.name === 'Alpha' ? 3 : 5;
|
||||||
|
expect(p.initiative).toBeGreaterThanOrEqual(mod + 1);
|
||||||
|
expect(p.initiative).toBeLessThanOrEqual(mod + 20);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Reroll initiative for all/i)).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cancel leaves initiatives untouched', async () => {
|
||||||
|
const { cid, eid } = await setupTwoMonsters('RerollCancelCamp', 'RerollCancelEnc');
|
||||||
|
const before = partDoc(cid, eid).participants.map(p => p.initiative);
|
||||||
|
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: 'Reroll All Initiative' }));
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /^Cancel$/ }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Reroll initiative for all/i)).not.toBeInTheDocument());
|
||||||
|
expect(partDoc(cid, eid).participants.map(p => p.initiative)).toEqual(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hidden during active combat; toggle button still present', async () => {
|
||||||
|
await setupTwoMonsters('RerollCombatCamp', 'RerollCombatEnc');
|
||||||
|
await startCombatViaUI();
|
||||||
|
|
||||||
|
expect(screen.queryByRole('button', { name: 'Reroll All Initiative' })).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /Add Participants/i })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Add Participants toggle button persists when section collapsed', async () => {
|
||||||
|
await setupTwoMonsters('RerollToggleCamp', 'RerollToggleEnc');
|
||||||
|
const toggle = await screen.findByRole('button', { name: /Add Participants/i });
|
||||||
|
expect(toggle).toHaveAttribute('aria-expanded', 'true');
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
// form furled, toggle + Add All still visible
|
||||||
|
expect(screen.queryByPlaceholderText('e.g., Dire Wolf')).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /Add Participants/i })).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /Add All/i })).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Add Participants/i }));
|
||||||
|
expect(screen.getByPlaceholderText('e.g., Dire Wolf')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// End Encounter modal offers one-time character writeback choice.
|
||||||
|
// Choice defaults from campaign preference but never changes that preference.
|
||||||
|
|
||||||
|
import { screen, fireEvent, waitFor, within } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import {
|
||||||
|
renderApp, createCampaignViaUI, selectCampaignByName,
|
||||||
|
createEncounterViaUI, selectEncounterByName, startCombatViaUI, MOCK_DB,
|
||||||
|
} from './testHelpers';
|
||||||
|
|
||||||
|
const campPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`;
|
||||||
|
const encPath = (cid, eid) => `${campPath(cid)}/encounters/${eid}`;
|
||||||
|
const syncLabel = /Update campaign characters with encounter HP, Max HP, and AC/i;
|
||||||
|
|
||||||
|
async function setup(name, persistentSync) {
|
||||||
|
await renderApp();
|
||||||
|
const cid = await createCampaignViaUI(`${name} Camp`);
|
||||||
|
await selectCampaignByName(`${name} Camp`);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Hero' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('HP', { selector: '#defaultMaxHp' }), { target: { value: '30' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('AC', { selector: '#defaultAc' }), { target: { value: '17' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText('Hero');
|
||||||
|
|
||||||
|
if (persistentSync) {
|
||||||
|
fireEvent.click(screen.getByLabelText(/Sync character changes on encounter end/i));
|
||||||
|
await waitFor(() => expect(MOCK_DB.get(campPath(cid)).syncCharacters).toBe(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
const eid = await createEncounterViaUI(`${name} Encounter`);
|
||||||
|
await selectEncounterByName(`${name} Encounter`);
|
||||||
|
fireEvent.click(await screen.findByRole('button', { name: /Add All \(Roll Init\)/i }));
|
||||||
|
await waitFor(() => expect(MOCK_DB.get(encPath(cid, eid)).participants).toHaveLength(1));
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Edit participant' }));
|
||||||
|
const editModal = (await screen.findByRole('heading', { name: 'Edit Hero' })).closest('.fixed');
|
||||||
|
const currentHp = within(editModal).getByText('Current HP', { selector: 'label' }).parentElement.querySelector('input');
|
||||||
|
const ac = within(editModal).getByText('AC', { selector: 'label' }).parentElement.querySelector('input');
|
||||||
|
fireEvent.change(currentHp, { target: { value: '11' } });
|
||||||
|
fireEvent.change(ac, { target: { value: '19' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
|
||||||
|
await waitFor(() => {
|
||||||
|
const hero = MOCK_DB.get(encPath(cid, eid)).participants[0];
|
||||||
|
expect(hero.currentHp).toBe(11);
|
||||||
|
expect(hero.ac).toBe(19);
|
||||||
|
});
|
||||||
|
|
||||||
|
await startCombatViaUI();
|
||||||
|
return { cid, eid };
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEndModal() {
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /End Combat/i }));
|
||||||
|
return screen.getByLabelText(syncLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('End Encounter one-time character sync choice', () => {
|
||||||
|
test('defaults off, resets after cancel, can sync once without persisting preference', async () => {
|
||||||
|
const { cid } = await setup('One Time Sync', false);
|
||||||
|
|
||||||
|
let checkbox = openEndModal();
|
||||||
|
expect(checkbox).not.toBeChecked();
|
||||||
|
fireEvent.click(checkbox);
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Cancel$/ }));
|
||||||
|
expect(MOCK_DB.get(campPath(cid)).syncCharacters).not.toBe(true);
|
||||||
|
|
||||||
|
checkbox = openEndModal();
|
||||||
|
expect(checkbox).not.toBeChecked();
|
||||||
|
fireEvent.click(checkbox);
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Confirm$/ }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const campaign = MOCK_DB.get(campPath(cid));
|
||||||
|
const hero = campaign.players.find(p => p.name === 'Hero');
|
||||||
|
expect(hero.defaultCurrentHp).toBe(11);
|
||||||
|
expect(hero.defaultAc).toBe(19);
|
||||||
|
expect(campaign.syncCharacters).not.toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('defaults on from preference; unchecking skips once without changing preference', async () => {
|
||||||
|
const { cid } = await setup('Skip Once Sync', true);
|
||||||
|
|
||||||
|
const checkbox = openEndModal();
|
||||||
|
expect(checkbox).toBeChecked();
|
||||||
|
fireEvent.click(checkbox);
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Confirm$/ }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const campaign = MOCK_DB.get(campPath(cid));
|
||||||
|
const hero = campaign.players.find(p => p.name === 'Hero');
|
||||||
|
expect(hero.defaultCurrentHp).not.toBe(11);
|
||||||
|
expect(hero.defaultAc).toBe(17);
|
||||||
|
expect(campaign.syncCharacters).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -26,7 +26,7 @@ describe('FEAT-3 reslot: inline init change reorders list', () => {
|
|||||||
const addOne = async (name, hp, mod, init) => {
|
const addOne = async (name, hp, mod, init) => {
|
||||||
fireEvent.change(form.getByPlaceholderText('e.g., Dire Wolf'), { target: { value: name } });
|
fireEvent.change(form.getByPlaceholderText('e.g., Dire Wolf'), { target: { value: name } });
|
||||||
fireEvent.change(form.getByLabelText(/Init Mod/i), { target: { value: String(mod) } });
|
fireEvent.change(form.getByLabelText(/Init Mod/i), { target: { value: String(mod) } });
|
||||||
fireEvent.change(form.getByLabelText(/Max HP/i), { target: { value: String(hp) } });
|
fireEvent.change(document.getElementById('monsterMaxHp'), { target: { value: String(hp) } });
|
||||||
fireEvent.change(form.getByPlaceholderText('auto'), { target: { value: String(init) } });
|
fireEvent.change(form.getByPlaceholderText('auto'), { target: { value: String(init) } });
|
||||||
fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
|
fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// localStorage scoping: selectedEncounter + scrollY keyed per campaign.
|
||||||
|
// Two tabs on different campaigns don't fight over selection/scroll.
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { setupReady, addMonsterViaUI } from './testHelpers';
|
||||||
|
|
||||||
|
describe('localStorage campaign scoping', () => {
|
||||||
|
test('selectedEncounter key is scoped (not bare)', async () => {
|
||||||
|
await setupReady('ScopeCamp1', 'ScopeEnc1');
|
||||||
|
// bare key should not exist
|
||||||
|
expect(localStorage.getItem('ttrpg.selectedEncounter')).toBeNull();
|
||||||
|
// scoped key with suffix should exist
|
||||||
|
const scoped = Object.keys(localStorage).find(
|
||||||
|
k => k.startsWith('ttrpg.selectedEncounter.') && k !== 'ttrpg.selectedEncounter'
|
||||||
|
);
|
||||||
|
expect(scoped).toBeTruthy();
|
||||||
|
expect(localStorage.getItem(scoped)).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('scrollY key is scoped (not bare)', async () => {
|
||||||
|
await setupReady('ScopeCamp2', 'ScopeEnc2');
|
||||||
|
await addMonsterViaUI('Goblin', 10, 5);
|
||||||
|
expect(localStorage.getItem('ttrpg.scrollY')).toBeNull();
|
||||||
|
const scoped = Object.keys(localStorage).find(
|
||||||
|
k => k.startsWith('ttrpg.scrollY.') && k !== 'ttrpg.scrollY'
|
||||||
|
);
|
||||||
|
// key may not exist until save fires — trigger by checking bare is null
|
||||||
|
// and at least scoped format is used if any scrollY key present
|
||||||
|
const scrollKeys = Object.keys(localStorage).filter(k => k.startsWith('ttrpg.scrollY'));
|
||||||
|
scrollKeys.forEach(k => expect(k).not.toBe('ttrpg.scrollY'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('global keys still exist (campaign selection, wake lock)', async () => {
|
||||||
|
await setupReady('ScopeCamp3', 'ScopeEnc3');
|
||||||
|
expect(localStorage.getItem('ttrpg.selectedCampaign')).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -20,7 +20,7 @@ async function addCharacterToEncounter(name = 'Hero', hp = 10) {
|
|||||||
await selectCampaignByName(`DS-${name}`);
|
await selectCampaignByName(`DS-${name}`);
|
||||||
|
|
||||||
fireEvent.change(screen.getByPlaceholderText('Character name'), { target: { value: name } });
|
fireEvent.change(screen.getByPlaceholderText('Character name'), { target: { value: name } });
|
||||||
fireEvent.change(screen.getByLabelText(/Default HP/i), { target: { value: String(hp) } });
|
fireEvent.change(screen.getByLabelText(/^HP$/i), { target: { value: String(hp) } });
|
||||||
fireEvent.click(screen.getByRole('button', { name: /Add Character/i }));
|
fireEvent.click(screen.getByRole('button', { name: /Add Character/i }));
|
||||||
await waitFor(() => findCalls('updateDoc', '/campaigns/').find(c => c.data.players?.length === 1));
|
await waitFor(() => findCalls('updateDoc', '/campaigns/').find(c => c.data.players?.length === 1));
|
||||||
const charId = findCalls('updateDoc', '/campaigns/').find(c => c.data.players?.length === 1).data.players[0].id;
|
const charId = findCalls('updateDoc', '/campaigns/').find(c => c.data.players?.length === 1).data.players[0].id;
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ describe('Participant -> Firebase', () => {
|
|||||||
test('toggleActive: updateDoc flips isActive', async () => {
|
test('toggleActive: updateDoc flips isActive', async () => {
|
||||||
await setupReady();
|
await setupReady();
|
||||||
await addMonsterViaUI('Toggle', 10, 0);
|
await addMonsterViaUI('Toggle', 10, 0);
|
||||||
fireEvent.click(screen.getByTitle('Mark Inactive'));
|
fireEvent.click(screen.getByRole('button', { name: 'Disable participant' }));
|
||||||
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.isActive === false);
|
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.isActive === false);
|
||||||
expect(lastEncCall().data.participants[0].isActive).toBe(false);
|
expect(lastEncCall().data.participants[0].isActive).toBe(false);
|
||||||
});
|
});
|
||||||
@@ -116,7 +116,7 @@ describe('Participant -> Firebase', () => {
|
|||||||
test('toggleCondition: updateDoc adds condition to array', async () => {
|
test('toggleCondition: updateDoc adds condition to array', async () => {
|
||||||
await setupReady();
|
await setupReady();
|
||||||
await addMonsterViaUI('Cond', 10, 0);
|
await addMonsterViaUI('Cond', 10, 0);
|
||||||
fireEvent.click(screen.getByTitle('Conditions'));
|
fireEvent.click(screen.getByRole('button', { name: 'Open conditions' }));
|
||||||
await waitFor(() => screen.getByRole('button', { name: /Blinded/i }));
|
await waitFor(() => screen.getByRole('button', { name: /Blinded/i }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: /Blinded/i }));
|
fireEvent.click(screen.getByRole('button', { name: /Blinded/i }));
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { screen, fireEvent } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { setupReady, addMonsterViaUI } from './testHelpers';
|
||||||
|
|
||||||
|
describe('participant action selected states', () => {
|
||||||
|
test('active toggle clearly changes to selected inactive state', async () => {
|
||||||
|
await setupReady('ActionCamp1', 'ActionEnc1');
|
||||||
|
await addMonsterViaUI('Toggle Orc', 15, 3);
|
||||||
|
|
||||||
|
const disable = screen.getByRole('button', { name: 'Disable participant' });
|
||||||
|
expect(disable).toHaveAttribute('aria-pressed', 'true');
|
||||||
|
expect(disable).toHaveClass('bg-emerald-700');
|
||||||
|
fireEvent.click(disable);
|
||||||
|
|
||||||
|
const enable = await screen.findByRole('button', { name: 'Enable participant' });
|
||||||
|
expect(enable).toHaveAttribute('aria-pressed', 'false');
|
||||||
|
expect(enable).toHaveClass('bg-red-900', 'ring-red-500');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('conditions toggle highlights open state and gives close action', async () => {
|
||||||
|
await setupReady('ActionCamp2', 'ActionEnc2');
|
||||||
|
await addMonsterViaUI('Condition Orc', 15, 3);
|
||||||
|
|
||||||
|
const open = screen.getByRole('button', { name: 'Open conditions' });
|
||||||
|
expect(open).toHaveAttribute('aria-expanded', 'false');
|
||||||
|
fireEvent.click(open);
|
||||||
|
|
||||||
|
const close = screen.getByRole('button', { name: 'Close conditions' });
|
||||||
|
expect(close).toHaveAttribute('aria-expanded', 'true');
|
||||||
|
expect(close).toHaveClass('bg-purple-700', 'ring-purple-300');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('edit toggle exposes selected state while editor is open', async () => {
|
||||||
|
await setupReady('ActionCamp3', 'ActionEnc3');
|
||||||
|
await addMonsterViaUI('Edit Orc', 15, 3);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Edit participant' }));
|
||||||
|
const closeEditor = screen.getByRole('button', { name: 'Close participant editor' });
|
||||||
|
expect(closeEditor).toHaveAttribute('aria-pressed', 'true');
|
||||||
|
expect(closeEditor).toHaveClass('bg-amber-500', 'ring-amber-200');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
// Reroll initiative: per-participant dice button for non-player (monster/npc).
|
||||||
|
// Player characters keep manual initiative only.
|
||||||
|
|
||||||
|
import { screen, fireEvent, waitFor, within, act } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { getCalls } from '../__mocks__/firebase/_mock-db';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName, createEncounterViaUI, addMonsterViaUI, setupReady, getParticipantForm } from './testHelpers';
|
||||||
|
|
||||||
|
function lastParticipantWrite(name) {
|
||||||
|
const calls = getCalls().filter(c => c.path.includes('/encounters/'));
|
||||||
|
const withFn = getCalls().filter(c => (c.fn === 'setDoc' || c.fn === 'updateDoc' || c.fn === 'batchWrite') && c.path.includes('/encounters/'));
|
||||||
|
const latest = withFn[withFn.length - 1];
|
||||||
|
const parts = latest?.data?.participants || [];
|
||||||
|
return parts.find(p => p.name === name);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addCharacterViaUI(name = 'Hero', initMod = 2) {
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: name } });
|
||||||
|
fireEvent.change(screen.getByLabelText(/Init Mod/i, { selector: '#defaultInitMod' }), { target: { value: String(initMod) } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('reroll initiative button', () => {
|
||||||
|
test('monster card has reroll; character card does not; reroll writes d20+mod', async () => {
|
||||||
|
await setupReady('RerollCamp', 'RerollEnc');
|
||||||
|
await addMonsterViaUI('Dire Wolf', 30, 5);
|
||||||
|
await addCharacterViaUI('Hero', 2);
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Add All \(Roll Init\)/i }));
|
||||||
|
|
||||||
|
// NO reroll button on card
|
||||||
|
expect(screen.queryByTitle('Reroll initiative for Dire Wolf')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('editor reroll rolls d20+mod, saves on Save; card stays clean', async () => {
|
||||||
|
await setupReady('RerollCamp2', 'RerollEnc2');
|
||||||
|
await addMonsterViaUI('Goblin', 7, 2);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Edit participant' }));
|
||||||
|
const modInput = await screen.findByLabelText('Init Mod', { selector: '#edit-initmod' });
|
||||||
|
const initInput = screen.getByLabelText('Initiative', { selector: '#edit-initiative' });
|
||||||
|
const before = parseInt(initInput.value, 10);
|
||||||
|
|
||||||
|
const rerollBtn = screen.getByRole('button', { name: 'Reroll initiative' });
|
||||||
|
for (let i = 0; i < 10 && parseInt(initInput.value, 10) === before; i++) {
|
||||||
|
fireEvent.click(rerollBtn);
|
||||||
|
}
|
||||||
|
const rolled = parseInt(initInput.value, 10);
|
||||||
|
const mod = parseInt(modInput.value || '0', 10);
|
||||||
|
expect(rolled).not.toBe(before);
|
||||||
|
expect(rolled).toBeGreaterThanOrEqual(mod + 1);
|
||||||
|
expect(rolled).toBeLessThanOrEqual(mod + 20);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
|
||||||
|
await waitFor(() => {
|
||||||
|
const p = lastParticipantWrite('Goblin');
|
||||||
|
expect(p.initiative).toBe(rolled);
|
||||||
|
});
|
||||||
|
// still nothing on card after save
|
||||||
|
expect(screen.queryByTitle(/Reroll initiative for Goblin/)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('npc from roster keeps default init mod for reroll', async () => {
|
||||||
|
await renderApp();
|
||||||
|
await createCampaignViaUI('NpcCamp');
|
||||||
|
await selectCampaignByName('NpcCamp');
|
||||||
|
await createEncounterViaUI('NpcEnc');
|
||||||
|
|
||||||
|
// roster NPC: name + init mod + isNpc checkbox
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Bartender' } });
|
||||||
|
fireEvent.change(screen.getByLabelText(/Init Mod/i, { selector: '#defaultInitMod' }), { target: { value: '1' } });
|
||||||
|
fireEvent.click(screen.getByLabelText(/Long-lived NPC/i));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText('Bartender');
|
||||||
|
// Add All skips roster NPCs — add via character dropdown instead.
|
||||||
|
// Background rerenders replace form nodes mid-test; settle, then re-query fresh.
|
||||||
|
await act(async () => { await new Promise(r => setTimeout(r, 250)); });
|
||||||
|
const selects = within(getParticipantForm()).getAllByRole('combobox');
|
||||||
|
const typeSel = selects.find(s => [...s.options].some(o => o.value === 'character'));
|
||||||
|
fireEvent.change(typeSel, { target: { value: 'character' } });
|
||||||
|
await act(async () => { await new Promise(r => setTimeout(r, 50)); });
|
||||||
|
const charSel = within(getParticipantForm()).getAllByRole('combobox').find(s => [...s.options].some(o => o.textContent.includes('Bartender')));
|
||||||
|
fireEvent.change(charSel, { target: { value: [...charSel.options].find(o => o.textContent.includes('Bartender')).value } });
|
||||||
|
await act(async () => { await new Promise(r => setTimeout(r, 300)); });
|
||||||
|
const addBtn = within(getParticipantForm()).getByRole('button', { name: /Add to Encounter \(Roll Init\)/i });
|
||||||
|
await act(async () => { fireEvent.click(addBtn); });
|
||||||
|
|
||||||
|
// no reroll button on card for NPC either
|
||||||
|
expect(screen.queryByTitle(/Reroll initiative for Bartender/)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
@@ -16,7 +16,7 @@ function lastParticipantsUpdate() {
|
|||||||
async function addOne(form, name, hp, mod, init) {
|
async function addOne(form, name, hp, mod, init) {
|
||||||
fireEvent.change(form.getByPlaceholderText('e.g., Dire Wolf'), { target: { value: name } });
|
fireEvent.change(form.getByPlaceholderText('e.g., Dire Wolf'), { target: { value: name } });
|
||||||
fireEvent.change(form.getByLabelText(/Init Mod/i), { target: { value: String(mod) } });
|
fireEvent.change(form.getByLabelText(/Init Mod/i), { target: { value: String(mod) } });
|
||||||
fireEvent.change(form.getByLabelText(/Max HP/i), { target: { value: String(hp) } });
|
fireEvent.change(document.getElementById('monsterMaxHp'), { target: { value: String(hp) } });
|
||||||
fireEvent.change(form.getByPlaceholderText('auto'), { target: { value: String(init) } });
|
fireEvent.change(form.getByPlaceholderText('auto'), { target: { value: String(init) } });
|
||||||
fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
|
fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
@@ -57,7 +57,7 @@ describe('reslot on all mutation paths', () => {
|
|||||||
expect(lastParticipantsUpdate().map(p => p.name)).toEqual(['Orc', 'Goblin']);
|
expect(lastParticipantsUpdate().map(p => p.name)).toEqual(['Orc', 'Goblin']);
|
||||||
|
|
||||||
// open edit modal for Goblin, bump init to 8
|
// open edit modal for Goblin, bump init to 8
|
||||||
const editBtns = screen.getAllByTitle('Edit');
|
const editBtns = screen.getAllByRole('button', { name: 'Edit participant' });
|
||||||
const goblinEdit = editBtns.find(b => b.closest('li')?.textContent.includes('Goblin'));
|
const goblinEdit = editBtns.find(b => b.closest('li')?.textContent.includes('Goblin'));
|
||||||
fireEvent.click(goblinEdit);
|
fireEvent.click(goblinEdit);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// Roster stable state: badge on character card, cleared when Current HP raised.
|
||||||
|
|
||||||
|
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { renderApp, createCampaignViaUI, selectCampaignByName, MOCK_DB } from './testHelpers';
|
||||||
|
|
||||||
|
const campPath = id => `artifacts/ttrpg-initiative-tracker-default/public/data/campaigns/${id}`;
|
||||||
|
|
||||||
|
async function setupWithStableChar() {
|
||||||
|
await renderApp();
|
||||||
|
const id = await createCampaignViaUI('StableCamp');
|
||||||
|
await selectCampaignByName('StableCamp');
|
||||||
|
|
||||||
|
// character form
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Fallen Hero' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText('Fallen Hero');
|
||||||
|
|
||||||
|
// writeback would have set these; seed directly
|
||||||
|
const doc = MOCK_DB.get(campPath(id));
|
||||||
|
doc.players = doc.players.map(p => p.name === 'Fallen Hero'
|
||||||
|
? { ...p, defaultCurrentHp: 0, stableRegainHours: 3 }
|
||||||
|
: p);
|
||||||
|
MOCK_DB.set(campPath(id), doc);
|
||||||
|
await screen.findByText(/Stable — regains 1 HP after 3 hours/);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('roster stable state', () => {
|
||||||
|
test('character card shows stable badge with hours', async () => {
|
||||||
|
await setupWithStableChar();
|
||||||
|
expect(screen.getByText(/Stable — regains 1 HP after 3 hours/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('raising Current HP in editor clears stable state', async () => {
|
||||||
|
const id = await setupWithStableChar();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Edit character' }));
|
||||||
|
const curHpInput = await screen.findByTitle('Default Current HP');
|
||||||
|
expect(curHpInput).toHaveValue(0);
|
||||||
|
fireEvent.change(curHpInput, { target: { value: '10' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save character' }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const doc = MOCK_DB.get(campPath(id));
|
||||||
|
const hero = doc.players.find(p => p.name === 'Fallen Hero');
|
||||||
|
expect(hero.defaultCurrentHp).toBe(10);
|
||||||
|
expect(hero.stableRegainHours).toBeNull();
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Stable — regains/)).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import { setupReady } from './testHelpers';
|
||||||
|
|
||||||
|
describe('screen controls', () => {
|
||||||
|
let originalRequestFullscreen;
|
||||||
|
let originalExitFullscreen;
|
||||||
|
let originalFullscreenElement;
|
||||||
|
let originalVisibilityState;
|
||||||
|
let originalWakeLock;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
originalRequestFullscreen = document.documentElement.requestFullscreen;
|
||||||
|
originalExitFullscreen = document.exitFullscreen;
|
||||||
|
originalFullscreenElement = Object.getOwnPropertyDescriptor(document, 'fullscreenElement');
|
||||||
|
originalVisibilityState = Object.getOwnPropertyDescriptor(document, 'visibilityState');
|
||||||
|
originalWakeLock = Object.getOwnPropertyDescriptor(navigator, 'wakeLock');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
document.documentElement.requestFullscreen = originalRequestFullscreen;
|
||||||
|
document.exitFullscreen = originalExitFullscreen;
|
||||||
|
if (originalFullscreenElement) Object.defineProperty(document, 'fullscreenElement', originalFullscreenElement);
|
||||||
|
else Object.defineProperty(document, 'fullscreenElement', { configurable: true, value: null });
|
||||||
|
if (originalVisibilityState) Object.defineProperty(document, 'visibilityState', originalVisibilityState);
|
||||||
|
if (originalWakeLock) Object.defineProperty(navigator, 'wakeLock', originalWakeLock);
|
||||||
|
else Object.defineProperty(navigator, 'wakeLock', { configurable: true, value: undefined });
|
||||||
|
localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('encounter header exposes prevent-sleep, browser-fullscreen, and popout controls', async () => {
|
||||||
|
await setupReady('ScreenCamp', 'ScreenEnc');
|
||||||
|
|
||||||
|
expect(screen.getAllByRole('button', { name: 'Caffeine OFF' }).length).toBeGreaterThanOrEqual(2);
|
||||||
|
expect(screen.getAllByRole('button', { name: 'Enter browser fullscreen' })).toHaveLength(1);
|
||||||
|
expect(screen.getByRole('button', { name: 'Expand encounter to full page' })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('re-acquires wake lock when tablet becomes visible after browser release', async () => {
|
||||||
|
let releaseListener;
|
||||||
|
const sentinel = {
|
||||||
|
released: false,
|
||||||
|
release: jest.fn().mockResolvedValue(undefined),
|
||||||
|
addEventListener: jest.fn((event, callback) => { if (event === 'release') releaseListener = callback; }),
|
||||||
|
};
|
||||||
|
const request = jest.fn().mockResolvedValue(sentinel);
|
||||||
|
Object.defineProperty(navigator, 'wakeLock', { configurable: true, value: { request } });
|
||||||
|
let visibility = 'visible';
|
||||||
|
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
|
||||||
|
|
||||||
|
await setupReady('WakeCamp', 'WakeEnc');
|
||||||
|
fireEvent.click(screen.getAllByRole('button', { name: 'Caffeine OFF' })[0]);
|
||||||
|
await waitFor(() => expect(request).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
visibility = 'hidden';
|
||||||
|
releaseListener();
|
||||||
|
visibility = 'visible';
|
||||||
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
|
||||||
|
await waitFor(() => expect(request).toHaveBeenCalledTimes(2));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('character editor has labeled tablet-sized save button', async () => {
|
||||||
|
await setupReady('SaveCamp', 'SaveEnc');
|
||||||
|
fireEvent.change(screen.getByLabelText('Name', { selector: '#characterName' }), { target: { value: 'Tablet Hero' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Character' }));
|
||||||
|
await screen.findByText('Tablet Hero');
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Edit character' }));
|
||||||
|
const save = screen.getByRole('button', { name: 'Save character' });
|
||||||
|
expect(save).toHaveTextContent('Save');
|
||||||
|
expect(save).toHaveClass('min-h-[40px]');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('attempts to restore fullscreen when tablet becomes visible after lock', async () => {
|
||||||
|
const requestFullscreen = jest.fn().mockResolvedValue(undefined);
|
||||||
|
document.documentElement.requestFullscreen = requestFullscreen;
|
||||||
|
document.exitFullscreen = jest.fn().mockResolvedValue(undefined);
|
||||||
|
Object.defineProperty(document, 'fullscreenElement', { configurable: true, get: () => null });
|
||||||
|
let visibility = 'visible';
|
||||||
|
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
|
||||||
|
|
||||||
|
await setupReady('RestoreCamp', 'RestoreEnc');
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Enter browser fullscreen' }));
|
||||||
|
await waitFor(() => expect(requestFullscreen).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
visibility = 'hidden';
|
||||||
|
document.dispatchEvent(new Event('fullscreenchange'));
|
||||||
|
visibility = 'visible';
|
||||||
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
|
||||||
|
await waitFor(() => expect(requestFullscreen).toHaveBeenCalledTimes(2));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { screen, fireEvent, waitFor, within } from '@testing-library/react';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import {
|
||||||
|
setupReady, addMonsterViaUI, renderApp, createCampaignViaUI,
|
||||||
|
selectCampaignByName, selectEncounterByName, startCombatViaUI, MOCK_DB,
|
||||||
|
} from './testHelpers';
|
||||||
|
|
||||||
|
function latestEncounter() {
|
||||||
|
const row = [...MOCK_DB._state.docs.entries()]
|
||||||
|
.filter(([path]) => path.includes('/encounters/'))
|
||||||
|
.pop();
|
||||||
|
return row ? MOCK_DB.get(row[0]) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('tracked effects DM UI', () => {
|
||||||
|
test('5e Turned preset creates prominent 10-round damage-expiring participant effect', async () => {
|
||||||
|
await setupReady('Turned Camp', 'Turned Encounter');
|
||||||
|
await addMonsterViaUI('Zombie', 22, -2);
|
||||||
|
|
||||||
|
expect(screen.queryByRole('button', { name: 'Add effect to Zombie' })).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Open conditions' }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Turned' }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const fx = latestEncounter().effects[0];
|
||||||
|
expect(fx).toMatchObject({
|
||||||
|
presetId: 'turned', name: 'Turned', scope: 'participant',
|
||||||
|
remainingRounds: 10, expiresOnDamage: true, playerDisplay: 'prominent',
|
||||||
|
});
|
||||||
|
expect(fx.targetParticipantId).toBe(latestEncounter().participants.find(p => p.name === 'Zombie').id);
|
||||||
|
});
|
||||||
|
expect(await screen.findByText('TURNED')).toBeInTheDocument();
|
||||||
|
expect(screen.getByLabelText('Turns left for Turned')).toHaveValue(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('custom encounter effect converts 5e minutes to rounds and supports prominent display', async () => {
|
||||||
|
await setupReady('Effect Camp', 'Effect Encounter');
|
||||||
|
await addMonsterViaUI('Cleric', 30, 2);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Open conditions' }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Custom tracked effect' }));
|
||||||
|
fireEvent.change(screen.getByLabelText('Effect scope'), { target: { value: 'encounter' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Effect name'), { target: { value: 'Spirit Guardians' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Duration'), { target: { value: '2' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Duration unit'), { target: { value: 'minutes' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Player display'), { target: { value: 'prominent' } });
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add Effect' }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(latestEncounter().effects[0]).toMatchObject({
|
||||||
|
name: 'Spirit Guardians', scope: 'encounter', remainingRounds: 20,
|
||||||
|
playerDisplay: 'prominent',
|
||||||
|
}));
|
||||||
|
expect(screen.getByText('SPIRIT GUARDIANS')).toBeInTheDocument();
|
||||||
|
expect(screen.getByLabelText('Turns left for Spirit Guardians')).toHaveValue(20);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Spiritual Weapon preset creates 10-round encounter effect', async () => {
|
||||||
|
await setupReady('Weapon Camp', 'Weapon Encounter');
|
||||||
|
await addMonsterViaUI('Cleric', 30, 2);
|
||||||
|
await addMonsterViaUI('Wizard', 24, 3);
|
||||||
|
|
||||||
|
await startCombatViaUI();
|
||||||
|
const activeId = latestEncounter().currentTurnParticipantId;
|
||||||
|
const otherId = latestEncounter().participants.find(p => p.id !== activeId).id;
|
||||||
|
fireEvent.click(within(screen.getByTestId(`admin-participant-card-${otherId}`)).getByRole('button', { name: 'Open conditions' }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Spiritual Weapon' }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(latestEncounter().effects[0]).toMatchObject({
|
||||||
|
presetId: 'spiritual_weapon', name: 'Spiritual Weapon', scope: 'encounter',
|
||||||
|
ownerParticipantId: activeId, remainingRounds: 10,
|
||||||
|
expiresOnDamage: false, playerDisplay: 'prominent',
|
||||||
|
}));
|
||||||
|
expect(within(screen.getByTestId(`admin-participant-card-${activeId}`)).getByText('SPIRITUAL WEAPON')).toBeInTheDocument();
|
||||||
|
|
||||||
|
const ownerSelect = screen.getByLabelText('Owner for Spiritual Weapon');
|
||||||
|
expect(ownerSelect).toHaveValue(activeId);
|
||||||
|
fireEvent.change(ownerSelect, { target: { value: otherId } });
|
||||||
|
await waitFor(() => expect(latestEncounter().effects[0].ownerParticipantId).toBe(otherId));
|
||||||
|
expect(within(screen.getByTestId(`admin-participant-card-${otherId}`)).getByText('SPIRITUAL WEAPON')).toBeInTheDocument();
|
||||||
|
expect(within(screen.getByTestId(`admin-participant-card-${activeId}`)).queryByText('SPIRITUAL WEAPON')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('generic ruleset offers custom effects only and rounds only', async () => {
|
||||||
|
await renderApp();
|
||||||
|
await createCampaignViaUI('Generic Effect Camp');
|
||||||
|
await selectCampaignByName('Generic Effect Camp');
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /Create Encounter/i }));
|
||||||
|
fireEvent.change(await screen.findByLabelText(/Encounter Name/i), { target: { value: 'Generic Effect Encounter' } });
|
||||||
|
fireEvent.click(screen.getByRole('radio', { name: /Generic/i }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Create$/i }));
|
||||||
|
await selectEncounterByName('Generic Effect Encounter');
|
||||||
|
await addMonsterViaUI('Generic Mob', 10, 0);
|
||||||
|
|
||||||
|
expect(screen.queryByRole('button', { name: 'Add encounter effect' })).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Open conditions' }));
|
||||||
|
expect(screen.queryByRole('button', { name: 'Turned' })).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('button', { name: 'Spiritual Weapon' })).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Custom tracked effect' }));
|
||||||
|
const durationOptions = [...screen.getByLabelText('Duration unit').options].map(o => o.value);
|
||||||
|
expect(durationOptions).toEqual(['rounds']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('effect duration controls adjust and remove effect', async () => {
|
||||||
|
await setupReady('Control Camp', 'Control Encounter');
|
||||||
|
await addMonsterViaUI('Ghoul', 18, 2);
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Open conditions' }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Turned' }));
|
||||||
|
await screen.findByText('TURNED');
|
||||||
|
|
||||||
|
const turnsInput = screen.getByLabelText('Turns left for Turned');
|
||||||
|
fireEvent.change(turnsInput, { target: { value: '3' } });
|
||||||
|
fireEvent.blur(turnsInput);
|
||||||
|
await waitFor(() => expect(latestEncounter().effects[0].remainingRounds).toBe(3));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Decrease Turned duration' }));
|
||||||
|
await waitFor(() => expect(latestEncounter().effects[0].remainingRounds).toBe(2));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Remove Turned' }));
|
||||||
|
await waitFor(() => expect(latestEncounter().effects).toEqual([]));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -9,7 +9,8 @@ export const fastWaitFor = (cb, opts) => waitFor(cb, { interval: 5, timeout: 100
|
|||||||
|
|
||||||
// Scoped container: the "Add Participants" section (avoids label clashes with CharacterManager).
|
// Scoped container: the "Add Participants" section (avoids label clashes with CharacterManager).
|
||||||
export function getParticipantForm() {
|
export function getParticipantForm() {
|
||||||
const heading = screen.getByText('Add Participants');
|
const heading = screen.getByText((content, element) =>
|
||||||
|
element.tagName === 'BUTTON' && content.trim() === 'Add Participants');
|
||||||
// closest section/div wrapping the form
|
// closest section/div wrapping the form
|
||||||
let node = heading;
|
let node = heading;
|
||||||
for (let i = 0; i < 6; i++) {
|
for (let i = 0; i < 6; i++) {
|
||||||
@@ -74,7 +75,7 @@ export async function addMonsterViaUI(name = 'Goblin', maxHp = 7, initMod = 2) {
|
|||||||
const form = within(getParticipantForm());
|
const form = within(getParticipantForm());
|
||||||
fireEvent.change(form.getByPlaceholderText('e.g., Dire Wolf'), { target: { value: name } });
|
fireEvent.change(form.getByPlaceholderText('e.g., Dire Wolf'), { target: { value: name } });
|
||||||
fireEvent.change(form.getByLabelText(/Init Mod/i), { target: { value: String(initMod) } });
|
fireEvent.change(form.getByLabelText(/Init Mod/i), { target: { value: String(initMod) } });
|
||||||
fireEvent.change(form.getByLabelText(/Max HP/i), { target: { value: String(maxHp) } });
|
fireEvent.change(document.getElementById('monsterMaxHp'), { target: { value: String(maxHp) } });
|
||||||
fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
|
fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
|
||||||
const { getCalls } = require('../__mocks__/firebase/_mock-db');
|
const { getCalls } = require('../__mocks__/firebase/_mock-db');
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|||||||
Reference in new issue
Block a user