20 Commits
Author SHA1 Message Date
david raistrick 4da5ed9bcc Merge remote-tracking branch 'upstream/main' into single-source
# Conflicts:
#	src/App.js
2026-07-04 16:43:14 -04:00
david raistrick c556860e49 refactor(App): remove dead SDK imports (BUG-17)
App.js imported 9 Firestore SDK functions it never called standalone:
doc, setDoc, addDoc, collection, onSnapshot, updateDoc, deleteDoc, query,
writeBatch. All writes go through storage adapter (storage.*). Auth pieces
(initializeApp, getAuth, signInAnonymously, onAuthStateChanged,
signInWithCustomToken, getFirestore) stay — real SDK init in firebase mode.

orderBy/limit stay — now neutral builders from index.js (prev commit).
2026-07-04 16:07:21 -04:00
david raistrick 27b2272ced fix(storage): neutral queryConstraints honored by both adapters
Bug: server adapter accepted queryConstraints (orderBy/limit) but ignored them.
Combat log [orderBy('timestamp','desc'), limit(500)] returned ALL logs unordered
in server mode — unbounded growth. No test caught it: shared contract tested
subscribeCollection with 0 constraints; the firebase-only queryConstraint test
never touched the server adapter. Parity gap.

Fix (Plan A — neutral shape):
- index.js: orderBy()/limit() now NEUTRAL builders returning {__type}. Removed
  SDK orderBy/limit re-export.
- firebase.js: subscribeCollection translates neutral -> SDK query constraints.
- server.js: applyConstraints() helper sorts/limits client-side (backend returns
  all). Constraints stored per collection, applied on initial fetch + WS change.
- contract.js: added 3 queryConstraint tests (orderBy desc, limit, no-constraints)
  to SHARED contract — both adapters now run identical assertions.
- firebase.contract.test.js: removed now-redundant firebase-only constraint
  block (covered by shared contract).

Data impact: ZERO. Constraints are query-time only, never stored. Combat log
docs keep timestamp field. No Firebase data migration needed.

208 tests green.
2026-07-04 16:06:28 -04:00
david raistrick e94e1959ff refactor: rename ws adapter to server across codebase
'ws' conflated storage mode with transport protocol (WebSocket). Renamed for
clarity: the adapter talks the self-hosted server (src/storage/server.js), which
happens to use WebSocket for realtime — but the name should describe what it
connects to, not how.

Renames:
- src/storage/ws.js -> server.js
- createWsStorage() -> createServerStorage()
- storage mode 'ws' -> 'server'
- REACT_APP_BACKEND_WS -> REACT_APP_BACKEND_REALTIME_URL
- factory param wsUrl -> realtimeUrl
- server/tests/ws-*.test.js -> server-*.test.js

Kept literal: 'ws' npm package, ws:// protocol URLs, /ws WebSocket endpoint.
Transport is accurate there; only storage-naming changed.

Updated all docs (DEVELOPMENT, TESTING, REWORK_PLAN, GLOSSARY, TODO), scripts
(dev-start.sh, replay-combat.js), factory + ESM tests. 204 tests green.
2026-07-04 15:47:13 -04:00
david raistrick cb41d9ec8f fix(turn): slot-not-sort in add/update; static guard against stray .sort()
addParticipant + updateParticipant used sortParticipantsByInitiative (stable
sort, tie-break = original array index). That destroyed manually-dragged tie
order when a drag moved a same-init pair — violated the slot-not-sort design
(docs/INITIATIVE_ORDERING.md: 'Re-slotting on add/edit must preserve
drag-established tie order').

Fix: new slotIndexForInit(list, init) returns splice index into the CURRENT
list (initiative-descending). addParticipant inserts there; updateParticipant
re-inserts only when initiative changed (unrelated edits keep slot — avoids
mid-round rotation dupes surfaced by the 100-round combat test).

Tests:
- turn.slot-not-sort.test.js: drag tie order survives add/edit (4 cases).
- static.no-sort.test.js: errs if .sort( added outside allowlist
  (sortParticipantsByInitiative only). Verified by injecting a stray sort —
  guard caught it.
2026-07-04 15:40:39 -04:00
david raistrick 6baecd374e ws adapter: match main truth (id injection + setDoc merge)
- getDoc/getCollection/subscribe inject {id,...data} (main firebase shape)
- getCollection normalizes backend {id,data}[] OR bare data[] → {id,...data}
- setDoc(opts.merge) → PATCH (create-on-miss); else PUT (replace)
- ws-reconnect test asserts id now present

24/24 server green. All suites green: App 83, shared 91, server 24.
2026-07-04 12:35:28 -04:00
david raistrick 79af61cb8b match main firebase behavior; fix contract + mismatches
Contract rewritten to match main prod truth:
- require id injection in all doc/collection results
- honor setDoc({merge:true}) (main L1624 + 4 activeDisplay sites)
- drop invented bare<->prefixed cross-lookup tests (main never does this)
- add setDoc{merge}, batch set-only/update-only contract coverage

Fix mismatches vs main:
- subscribeCollection hook now forwards queryConstraints (was dropped;
  LOG_QUERY sort+limit honored again). Mock onSnapshot honors orderBy+limit.
  2 new contract tests prove the chain.
- subscribeDoc/subscribeCollection adapters now forward errCb. App hooks +
  DisplayView propagate subscribe errors to UI (match main onSnapshot 3rd arg).
- ws adapter signatures accept queryConstraints + errCb (interface match).

activeDisplay writes match main:
- 5 unguarded sites -> setDoc({merge:true}) (create-if-missing, not updateDoc)
- 3 guarded sites stay updateDoc

Delete memory adapter: third storage system added complexity, zero value.
firebase-mock covers fast tests, ws covers server path. Factory throws on
unknown mode now.

Delete phantom 'Phase A/B' comment in firebase.js header.

Tests updated to assert setDoc{merge} (not updateDoc) for activeDisplay writes.
83/83 green.
2026-07-04 12:22:19 -04:00
david raistrick b12ac904a6 test: add storage coverage (firebase contract, factory), silence scenario log
- firebase.contract.test.js: run storage contract against createFirebaseStorage
  via SDK mock. Currently 12 fail (firebase diverges from contract: no norm(),
  injects id). Failures real — firebase copied from main, memory/ws invented
  new requirements. Contract under review vs main prod truth.
- storage.factory.test.js: getStorage() routing per REACT_APP_STORAGE env,
  singleton cache, getStorageMode() reporting.
- Combat.scenario.test.js: remove console.log (test noise).
- package.json: test:all now runs App + shared + server suites (was missing App).
2026-07-03 18:53:58 -04:00
david raistrick 7f60ec140e fix(scenario): run 100 rounds not turns, exercise all combat paths
Previous test lied: called nextTurn 100x = ~100 turns = ~12 rounds (see
docs/GLOSSARY.md turn vs round). Now loops by actual round-wrap count.

100 rounds = 975 turns verified via console log + expect(roundsDone).toBe(100).

Exercises ALL shared combat paths deterministically (vs replay random):
startEncounter, nextTurn, togglePause, addParticipant, addParticipants,
updateParticipant, removeParticipant, toggleParticipantActive, applyHpChange
(damage+heal), deathSave (1/2/3-success → isDying path), toggleCondition,
reorderParticipants (drag same-init tie), endEncounter, activateDisplay,
clearDisplay, toggleHidePlayerHp.

Rotation integrity checked every 10 rounds: no dup turnOrderIds, currentTurn
in order, turnOrderIds === participants.map(id).

Run time: 19ms (was 72s React, lieing).
2026-07-03 18:29:35 -04:00
david raistrick e650cd2710 refactor: single-source display lifecycle + scenario test no React
Move activeDisplay lifecycle to shared (one path, not duplicated in App):
- activateDisplay({campaignId, encounterId})
- clearDisplay()
- toggleHidePlayerHp(current)
All 6 App sites wired (start/end/2×delete-encounter/delete-campaign/hp-toggle).
Existing {patch,log} return shape preserved. No interface changes.

Combat.scenario.test.js rewritten to call shared directly, no React:
- Same actions as old UI version (roster chars, monsters, addAll, hp-toggle×2,
  start, 100 rounds of damage/heal/conditions/toggle/edit/deathsave/pause/
  resume/add/remove, end). Same funcs, same order, same data.
- Models two firestore docs (encounter + activeDisplay) via shared patches.
- Run time: 72s -> 4ms.

Both suites green: shared 91/91, App 77/77.
2026-07-03 18:26:02 -04:00
david raistrick d83d1383c0 refactor: single-source combat logic (App handlers call shared, slot model)
App.js no longer inlines combat logic. All handlers delegate to @ttrpg/shared:
startEncounter, nextTurn, togglePause, endEncounter, addParticipant(s),
updateParticipant, removeParticipant, toggleParticipantActive, applyHpChange,
deathSave, toggleCondition, reorderParticipants. ONE code path for UI.

shared/turn.js aligned to slot model (docs/INITIATIVE_ORDERING.md):
- addParticipant: splice into slot by initiative (no sort)
- updateParticipant: re-slot on initiative change (no sort)
- reorderParticipants: same-init drag only (cross-init blocked)
- applyHpChange: death flips isActive=false (matches App), revive reactivates

No renames, no API changes. Shared func signatures unchanged.

Tests updated to match unified behavior:
- dead-skip: death deactivates (was FEAT-1 stays active)
- characterization: death deactivates + revive reactivates
- reorder/invariant: cross-init drag blocked, same-init allowed

Both suites green: shared 91/91, App 77/77, 0 warnings.
2026-07-03 17:59:41 -04:00
david raistrick c3d89554e8 docs: initiative ordering design (slot, never sort)
Single list = display = turn order. Slot by initiative, tie-break = add
order. Drag = same-init only (DM tie override). No re-sort on mutation.
Round wrap no rebuild. No cross-init drag.
2026-07-03 17:18:00 -04:00
david raistrick d1cc3a8b9a test: warning=failure guard + fix ambiguous switch selector
- setupTests.js: console.error/warn now throw. Warning = failure.
- Combat.characterization: two role=switch (player HP + NPC HP), scope
  to player-HP label. getByRole('switch') was ambiguous.

Full suite: 77/77 pass, 0 warnings.
2026-07-03 16:05:04 -04:00
david raistrick 31d19c5912 test: kill act env warnings + remove debug console noise
Root cause: mock _notify cb fires during waitFor poll, but testing-library
asyncWrapper flips IS_REACT_ACT_ENVIRONMENT=false. Raw react act() then
warns 'not configured to support act' (146 warnings).

Fix: _notify sets globalThis.IS_REACT_ACT_ENVIRONMENT=true around act(),
restores after. setupTests sets flag globally. Both together = 0 warnings.

Also:
- Remove 4 debug console.log from App.js (encounter start/end, drag, add chars)
- Remove always-fires scenario summary console.log
- Add fastWaitFor helper (5ms poll) to testHelpers
- Swap scenario waitFor -> fastWaitFor

Tests: 77 pass / 0 fail / 0 warnings / 0 console noise.
2026-07-03 15:59:14 -04:00
david raistrick 530aaadf90 test: kill act env warnings (globalThis flag + _notify act wrapper)
- setupTests.js: set globalThis.IS_REACT_ACT_ENVIRONMENT = true (RTL reads
  getGlobalThis, not global). Kills 'environment not configured for act'.
- _mock-db.js _notify: set flag true around subscriber cb, restore prev
  after. RTL waitFor flips flag false mid-poll -> act() warned. Now clean.
- 146 act warnings -> 0.
2026-07-03 15:58:50 -04:00
david raistrick 1a744e511a test: upgrade @testing-library/react v14, kill act warnings
@testing-library/react v13 -> v14. v13 used deprecated
ReactDOMTestUtils.act on every render -> 708 deprecation warnings.
v14 imports act from react directly. Drops to 0.

Mock _notify (src/__mocks__/firebase/_mock-db.js): wrap subscriber
callbacks in act(() => cb()). Sync setState from subscribe callbacks
fired outside test act boundary -> 14 warnings. Now 0. try/catch
fallback if react/act unavailable (defensive).

Full suite: 166 pass / 1 fail (Combat.scenario BUG-11 pre-existing
crash). Warnings: 1416 -> 0.

Note: NOT complete kill-shared. App.js still inlines 8 logic fns
(startEncounter, nextTurn, togglePause, endEncounter, addParticipant,
updateParticipant, reorder/drag). turn.js versions dead in app, used
by replay + turn tests only. Next: make handlers call turn.js.
2026-07-03 15:46:27 -04:00
robert 8cf3dad5b6 Merge pull request 'Rework backend' (#2) from rework-backend into main
Reviewed-on: #2
2026-07-03 08:35:32 -04:00
robertandClaude Sonnet 5 ec578eeef5 Bump to v0.4, document self-hosted backend in README
The rework-backend merge added an optional self-hosted Express/ws/SQLite
backend (npm workspaces, single-container Docker deployment) alongside
the existing Firebase default. Bump APP_VERSION and refresh README to
cover both storage modes and the new repo layout.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-01 19:59:46 -04:00
robertandClaude Sonnet 5 c54fd88c32 fix(docker): copy workspace package.json files before npm install
npm workspaces needs shared/package.json and server/package.json present
at install time to link @ttrpg/shared, otherwise the build stage fails
with "Module not found: Error: Can't resolve '@ttrpg/shared'".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-01 19:40:23 -04:00
robert e31fe15382 Merge pull request 'Rework backend' (#1) from rework-backend into main
Reviewed-on: #1
2026-07-01 19:29:33 -04:00
44 changed files with 1292 additions and 1037 deletions
+1
View File
@@ -13,3 +13,4 @@ server/data/*.sqlite
server/data/*.sqlite-*
/data
/scratch
tmp/
+4 -1
View File
@@ -7,8 +7,11 @@ LABEL stage="build-local-testing"
WORKDIR /app
# Copy package.json and package-lock.json (or yarn.lock)
# Copy root package.json/lockfile plus workspace manifests so npm can
# resolve the @ttrpg/shared and server workspace links during install.
COPY package*.json ./
COPY shared/package.json ./shared/
COPY server/package.json ./server/
# Install dependencies using the lock file for consistency
RUN npm install
+64 -12
View File
@@ -1,4 +1,4 @@
# TTRPG Initiative Tracker (v0.2.5)
# TTRPG Initiative Tracker (v0.4)
![Here it is in use](images/in_use.png)
@@ -12,6 +12,8 @@ A web-based application designed to help Dungeon Masters (DMs) manage and displa
Have you tried it? Got feedback or questions? Discuss here: [https://discourse.draft13.com/c/ttrpg-initiative-tracker/16](https://discourse.draft13.com/c/ttrpg-initiative-tracker/16)
As of v0.4, the app can optionally run against a self-hosted backend (Node/Express/ws/SQLite, shipped as a single Docker container) instead of Firebase — useful if you'd rather not depend on a Google account. Firebase remains the default; see [Self-Hosted Backend (Optional)](#self-hosted-backend-optional) below.
## Features
![DM View.](images/dm_view.png)
@@ -59,7 +61,7 @@ Have you tried it? Got feedback or questions? Discuss here: [https://discourse.d
* A **fullscreen button** (top-right corner) toggles the browser into fullscreen mode — ideal for a dedicated second monitor.
* A **prevent sleep toggle** (moon/coffee icon, top-right corner) uses the browser Wake Lock API to keep the screen on while active.
* **Combat Action Log:** A running log of combat events (HP changes, condition changes, turn advances, participant additions/removals, encounter starts/ends, etc.) is available at `/logs`. Entries are timestamped and tagged with the encounter name. Most entries include an **↩ Undo** button that rolls back the action in Firestore (restoring HP, conditions, turn order, etc.). Rolled-back entries are greyed out with a strikethrough. The log can be cleared in bulk from that page.
* **Real-time Updates:** Uses Firebase Firestore for real-time synchronization between DM actions and the player display.
* **Real-time Updates:** Uses Firebase Firestore for real-time synchronization between DM actions and the player display (or a self-hosted WebSocket backend, see below).
* **Initiative Tie-Breaking:** DMs can drag-and-drop participants with tied initiative scores (before an encounter starts or while paused) to set a manual order.
* **Responsive Design:** Styled with Tailwind CSS.
* **Confirmation Modals:** Used for destructive actions like deleting campaigns, characters, encounters, or ending combat.
@@ -68,8 +70,9 @@ Have you tried it? Got feedback or questions? Discuss here: [https://discourse.d
* **Frontend:** React
* **Styling:** Tailwind CSS
* **Backend/Database:** Firebase Firestore (for real-time data)
* **Authentication:** Firebase Anonymous Authentication
* **Backend/Database:** Firebase Firestore (default), or a self-hosted Node/Express + `ws` + SQLite (`better-sqlite3`) backend behind Caddy (optional, see [Self-Hosted Backend](#self-hosted-backend-optional))
* **Authentication:** Firebase Anonymous Authentication (Firebase mode only; the self-hosted backend has no auth layer — intended for trusted/local networks)
* **Shared logic:** Turn-order state machine (`shared/`) is framework-agnostic and used by both the frontend and the self-hosted backend, covered by a Jest test suite
## App Usage Overview
@@ -128,11 +131,13 @@ This flow allows the DM to prepare and run encounters efficiently while providin
### Prerequisites
* **Node.js and npm:** Ensure you have Node.js (which includes npm) installed. You can download it from [nodejs.org](https://nodejs.org/).
* **Firebase Project:** You'll need a Firebase project with:
* **Firebase Project** (only if using the default Firebase storage mode): You'll need a Firebase project with:
* Firestore Database created and initialized.
* Anonymous Authentication enabled in the "Authentication" > "Sign-in method" tab.
* **Git:** For cloning the repository.
The project is an npm workspaces monorepo (`server/`, `shared/`, plus the CRA frontend at the root) — a single `npm install` at the repo root installs everything.
### Local Development Setup (using npm)
1. **Clone the Repository:**
@@ -190,7 +195,14 @@ This flow allows the DM to prepare and run encounters efficiently while providin
### Deployment with Docker
This project includes a `Dockerfile` to containerize the application for deployment. It uses a multi-stage build:
There are two Docker paths, depending on which storage mode you want:
* **Firebase mode (default):** the root `Dockerfile` builds a static frontend-only image, described below.
* **Self-hosted mode:** the `docker/` directory builds a single container running the Node backend + SQLite + the frontend behind Caddy, with no Firebase dependency. See [Self-Hosted Backend (Optional)](#self-hosted-backend-optional).
#### Firebase-mode image (root `Dockerfile`)
This project includes a `Dockerfile` to containerize the Firebase-backed application for deployment. It uses a multi-stage build:
* **Stage 1 (build):** Installs dependencies, copies your `.env.local` (for local testing builds), and builds the static React application using `npm run build`.
* **Stage 2 (nginx):** Uses an Nginx server to serve the static files produced in the build stage.
@@ -225,6 +237,30 @@ This project includes a `Dockerfile` to containerize the application for deploym
* If your CI/CD pipeline builds the Docker image, ensure these environment variables are securely provided to the build environment.
* **Implement strict Firebase Security Rules** appropriate for a production application to protect your data.
### Self-Hosted Backend (Optional)
If you'd rather not depend on Firebase/Google, the app can run entirely self-hosted: a Node/Express + `ws` backend backed by SQLite, with the frontend talking to it instead of Firestore. Intended for trusted/local networks (no auth layer yet).
**Quickest path — Docker Compose (single container: Caddy + Node + SQLite):**
```bash
docker compose -f docker/docker-compose.yml up --build
```
This serves the app at `http://localhost:8080` (override with `PORT`), proxies `/api` and `/ws` to the backend, and persists the SQLite database in a named Docker volume. Override the Firestore-style app-id namespace with `TRACKER_APP_ID` if needed.
**Local dev (backend + frontend separately):**
```bash
npm install # installs root, server/, and shared/ workspaces
npm run server:dev # starts backend on :4001 (SQLite at server/data/tracker.sqlite)
# in another terminal:
REACT_APP_STORAGE=ws \
REACT_APP_BACKEND_URL=http://127.0.0.1:4001 \
REACT_APP_BACKEND_WS=ws://127.0.0.1:4001/ws \
npm start
```
See `docs/DEVELOPMENT.md` for the full architecture (generic KV doc store, storage adapter interface, test layers) and `docs/REWORK_PLAN.md` for the design rationale.
## Project Structure
<pre>
@@ -233,21 +269,37 @@ ttrpg-initiative-tracker/
├── .env.example # Example environment variables
├── .env.local # Local environment variables (ignored by Git)
├── .gitignore # Specifies intentionally untracked files that Git should ignore
├── Dockerfile # Instructions to build the Docker image
├── Dockerfile # Firebase-mode image (frontend-only, served by nginx)
├── package.json # Workspaces root: frontend + server + shared
├── package-lock.json # Records exact versions of dependencies
├── package.json # Project metadata and dependencies
├── postcss.config.js # PostCSS configuration (for Tailwind CSS)
├── tailwind.config.js # Tailwind CSS configuration
├── docker/ # Self-hosted deployment: Dockerfile, docker-compose.yml, Caddyfile
├── docs/ # Rework plan, dev setup, testing, encounter-builder guide, glossary
├── scripts/ # Manual demo/ops tooling (e.g. replay-combat.js)
├── tests/ # Exploratory audit tooling (not part of the automated suite)
├── public/ # Static assets
│ ├── favicon.ico
│ ├── index.html # Main HTML template
│ └── manifest.json
── src/ # React application source code
├── App.js # Main application component
├── index.css # Global styles (including Tailwind directives)
── index.js # React entry point
── src/ # React frontend (Create React App)
├── App.js # Main application component
│ ├── storage/ # Storage adapter layer: firebase / ws / memory
│ ├── index.css # Global styles (including Tailwind directives)
│ └── index.js # React entry point
├── server/ # Self-hosted backend: Express + ws + SQLite (better-sqlite3)
└── shared/ # Framework-agnostic turn-order logic, used by frontend + server
</pre>
## Further Reading
* `docs/DEVELOPMENT.md` — setup, running the backend, test suites
* `docs/REWORK_PLAN.md` — why/how the self-hosted backend was added
* `docs/TESTING.md` — test layers and how to run them
* `docs/ENCOUNTER_BUILDER.md` — entity model and storage paths behind the DM interface
* `docs/GLOSSARY.md` — domain terms (turn vs. round, etc.)
* `TODO.md` — known bugs and backlog
## 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.
+55 -7
View File
@@ -5,10 +5,33 @@ REWORK_PLAN.md.
## Feature backlog
### CRITICAL BUG - storage
- docker for sql is not using persistant storage...
TODO: FIX: test for warnings. any warnings in tests, or compile or runtime == failure. like perl and php used to ahve. warning == error. we should lways solve them
TODO: make tests have integrated timeout - even 60s is probabvly too long, should not take long.
TODO: combat.scenario doesnt do 100 rounds it does 100 turns. recover from kill-shared stash
TODO: death saves wrong
TODO: custom condition field
server = YOUR SQLite server. server/db.js = better-sqlite3. src/storage/server.js = client that talks to it (REST +
websocket). Name bad. Should be "sqlite-adapter" or "server". You right.
memory = in-process JS Map. Useless? Mostly yes for prod. Value: fast contract tests, no server spinup. If
contract test runs vs firebase-mock + live server backend.
Memory = optional convenience. === extra complication.
### feat - campaign section rollup
### feat - add all characters to participants list
@@ -113,7 +136,7 @@ REWORK_PLAN.md.
`src/__mocks__/firebase/firestore.js` setDoc records call, IGNORES opts
(no actual merge). Mock must simulate firebase merge semantics for test
to pass. Fix = mock setDoc: if opts.merge, MOCK_DB.merge(path,data) else
replace. OR change App.js setDoc(merge) → updateDoc (cleaner, ws adapter
replace. OR change App.js setDoc(merge) → updateDoc (cleaner, server adapter
uses PATCH). Decide which.
- Test: render App + DisplayView, toggle hide-HP, assert display still shows
encounter (not paused).
@@ -143,8 +166,8 @@ REWORK_PLAN.md.
- `reorderParticipants` returns `log: null`. Other ops return `log.undo`.
- Cannot undo drag-drop. Candidate for undo system (M6).
### BUG-8: ws adapter has no reconnect
- Test: `server/tests/ws-reconnect.test.js` (RED).
### BUG-8: server adapter has no reconnect
- Test: `server/tests/server-reconnect.test.js` (RED).
- WS dies (idle/error/close) → `wsReady=null`, subscribers dead forever.
- Display frozen until full reload.
- Fix: `onclose` → reconnect + re-subscribe existing paths.
@@ -192,12 +215,37 @@ REWORK_PLAN.md.
- Related: FEAT-3 (initiative first-class field).
## Pipeline (bugs only --- milestones live in REWORK_PLAN.md)
### BUG-16: subscribeCollection hook drops queryConstraints
- SS `useFirestoreCollection` (App.js ~L233) calls
`storage.subscribeCollection(collectionPath, cb)` --- NO constraints passed.
- main (L251-253): `const q = query(collection(db,collectionPath), ...queryConstraints); onSnapshot(q, ...)`.
- Effect: `LOG_QUERY = [orderBy('timestamp','desc'), limit(500)]` IGNORED. Logs
unsorted + unbounded. Other collections unaffected (no constraints passed
elsewhere) but interface broken.
- firebase adapter `subscribeCollection(path, cb, queryConstraints=[])` HAS the
param, hook just doesn't forward it.
- Fix: hook pass `queryConstraints` as 3rd arg. RED first.
### BUG-17: dead SDK imports in App.js
- L5 imports `doc,setDoc,collection,onSnapshot,writeBatch,query,getDocs` from
`./storage` but App never calls them raw (all via `storage.*`). Only used as
re-export passthrough. `getFirestore`,`initializeApp` still used in init flow.
- Noise, not behavioral. Cleanup: trim dead imports OR keep for adapter test
instrumentation. Decide after audit.
### BUG-18: stale comments reference deleted memory adapter + phantom Phase B
- `src/storage/firebase.js` header had Phase A/B comment (DELETED this session).
- `src/storage/index.js` L3: "per-group refactor pending" --- stale.
- `src/tests/StorageEsm.test.js`, `storage.factory.test.js` referenced memory
(FIXED this session). Re-audit for stragglers.
- [ ] BUG-4: fix setDoc→updateDoc for all 5 activeDisplay sites
- [x] BUG-5: fixed (1-list model, 500 rounds clean)
- [x] BUG-6: fixed structurally (1-list model)
- [x] BUG-12: fixed --- campaign selection follows activeDisplay
- [x] BUG-15: fixed --- DisplayView no longer re-sorts (drag order preserved)
- [x] BUG-8: ws adapter reconnect (implemented + GREEN)
- [x] BUG-8: server adapter reconnect (implemented + GREEN)
- [ ] BUG-10: deact+reactivate double-act
- [ ] BUG-11: FE Combat.scenario crash
- [ ] BUG-13: reorder cross-pointer semantics (RED + decide block/allow)
+6 -6
View File
@@ -65,12 +65,12 @@ curl http://127.0.0.1:4001/health # -> {"ok":true}
Never put db in `/tmp` (wipe risk). Use `./data/` (gitignored) or docker volume.
### Frontend (dev server, ws mode)
### Frontend (dev server, server mode)
```bash
REACT_APP_STORAGE=ws \
REACT_APP_STORAGE=server \
REACT_APP_BACKEND_URL=http://127.0.0.1:4001 \
REACT_APP_BACKEND_WS=ws://127.0.0.1:4001/ws \
REACT_APP_BACKEND_REALTIME_URL=ws://127.0.0.1:4001/ws \
BROWSER=none PORT=3999 \
npm start
```
@@ -225,12 +225,12 @@ App passes firebase-prefixed paths (`artifacts/{APP_ID}/public/data/campaigns/..
`getStorageMode()` reads `REACT_APP_STORAGE` env (default `firebase`).
- `firebase` → real SDK init
- `ws`/`memory` → stub auth + db sentinel, route via `storage.*` adapter
- `server` → stub auth + db sentinel, route via `storage.*` adapter
## Test layers
- **Layer 1**: App vs firebase mock. Proves adapter call shape. Never exercises ws adapter.
- **Layer 2**: ws adapter vs live backend. Proves translation + path identity.
- **Layer 1**: App vs firebase mock. Proves adapter call shape. Never exercises server adapter.
- **Layer 2**: server adapter vs live backend. Proves translation + path identity.
Both required — Layer 1 alone misses adapter bugs (path mismatch, no-op players, ws.on EventEmitter vs browser handlers).
+2 -2
View File
@@ -52,8 +52,8 @@ Round 2: turn 1 (Fighter) → ... → turn 8 (Merchant) [round counter +=1 at
| Term | Meaning |
|------|---------|
| **Adapter** | `src/storage/{firebase,ws,memory}.js`. Contract boundary between App and backend. App only calls `storage.*`, never raw SDK/fetch. |
| **Adapter** | `src/storage/{firebase,server}.js`. Contract boundary between App and backend. App only calls `storage.*`, never raw SDK/fetch. |
| **Path normalization** (`norm()`) | Strip firebase prefix (`artifacts/{APP_ID}/public/data/`) → bare canonical path (`campaigns/X`). Runs inside every adapter method. |
| **Generic KV doc store** | Backend stores opaque JSON at arbitrary path strings. No shape-specific endpoints. Backend = firebase mirror, not REST API for app entities. |
| **Layer 1 test** | App vs firebase mock. Proves adapter call shape. |
| **Layer 2 test** | ws adapter vs live backend. Proves translation + path identity. |
| **Layer 2 test** | server adapter vs live backend. Proves translation + path identity. |
+59
View File
@@ -0,0 +1,59 @@
# Initiative Ordering — Design
## Core Principle
**Slot, never sort.**
Initiative order = a single list. Participants occupy slots determined by
initiative value. The list is mutated by insert/move operations — never
re-sorted wholesale.
## Single Source of Truth
One list: `participants[]`.
- Display order = `participants[]` order (both Player view + DM view).
- Turn order = `participants[]` order.
- No derived/re-sorted copy. `turnOrderIds`, if present, is always an exact
mirror (`participants.map(p => p.id)`) — never an independent ordering.
## When Ordering Changes
| Action | Effect on order |
|--------|-----------------|
| **Add** (roll or manual) | Insert participant into slot by initiative |
| **Edit initiative** | Move participant to new slot |
| **Drag** | Reorder within a tie (same initiative) only |
| **Remove** | Splice out; others keep position |
| **Start encounter** | Freeze current list. No re-sort. |
| **Round wrap** | No rebuild. Continue rotation through existing list. |
| **Damage/heal/death/save** | No order change. |
| **Toggle active** | No position change. Skip in rotation only. |
## Slotting Rules
- Insert/move positions participants so the list stays initiative-descending.
- **Tie-break = original add order.** Later additions slot *after* existing
same-init participants. Stable insertion.
- Tie order is only changed by explicit DM drag. Never auto-changed.
## Drag (DM Tie-Break Override)
- Only participants with the **same initiative** are draggable onto each other.
- Cross-initiative drag is **not allowed**. (Use edit-initiative field instead.)
- Drag persists in `participants[]`. Survives all subsequent operations.
- **Re-slotting on add/edit must preserve drag-established tie order.**
## Explicitly Forbidden
- `sort()` on every mutation. Overwrites drag order. Root cause of past drift.
- Separate display order vs turn order. Causes player/DM divergence.
- Re-sort on round wrap. Replays rounds, introduces skips.
- Cross-initiative drag. Contradicts initiative as the primary key.
- Auto-changing tie order on add/edit. Silently loses DM intent.
## Why
Sorting is destructive to manual ordering. A stable slot list with drag for
ties gives deterministic, DM-controllable order that never drifts between
display surfaces or combat rounds.
+10 -10
View File
@@ -61,7 +61,7 @@ The storage interface is the test seam and the upstream-compat layer.
| Impl | When used | Automated-tested? |
|---|---|---|
| `firebase.js` | default (`STORAGE=firebase`) — upstream path | No — requires live Firebase project |
| `ws.js` | `STORAGE=ws` — our fork, talks to backend | Yes — against running backend |
| `server.js` | `STORAGE=server` — our fork, talks to backend | Yes — against running backend |
| `memory.js` | test-only, in-process | Yes — fast, deterministic |
**Frontend interface contract** (all three implement):
@@ -82,7 +82,7 @@ Memory impl: in-memory Map + EventEmitter, for tests (M3).
storage/
index.js # factory: pick impl from STORAGE env
firebase.js # extracted from current App.js (verbatim)
ws.js # NEW — talks to backend
server.js # talks to backend (was ws.js)
memory.js # NEW — test only
contract.js # interface spec (runStorageContract)
tests/ # frontend tests
@@ -116,7 +116,7 @@ Each milestone = independently mergeable PR upstream (unless marked ❌).
| M | Does | Tests? |
|---|---|---|
| 0 | repo, branch, remotes | no |
| 1 | build backend (Node+Express+ws+better-sqlite3) | unit tests as built |
| 1 | build backend (Node+Express+WebSocket+better-sqlite3) | unit tests as built |
| 2 | frontend WS adapter — app runs vs backend, cross-device works | yes |
| 3 | characterization tests lock current behavior | yes |
| 4 | resolve initiative rotation corruption (BUG-5) | yes |
@@ -135,7 +135,7 @@ Each milestone = independently mergeable PR upstream (unless marked ❌).
- **Upstream-PRable:** n/a (fork infra)
### Milestone 1 — Build backend ✅
- `server/`: Express + ws + better-sqlite3.
- `server/`: Express + WebSocket + better-sqlite3.
- Generic KV doc store (firebase mirror): `docs` table (path PK, parent, data JSON, updated_at). REST: GET/PUT/PATCH/DELETE `/api/doc?path=`, GET `/api/collection?path=`, POST `/api/collection`, POST `/api/batch`. WS: subscribe by path.
- Server holds authoritative state. No turn logic server-side (logic stays client-side in `shared/turn.js`).
- **Exit criteria:** backend boots, serves state over WS, persists to SQLite, unit tests green. ✅ DONE.
@@ -144,10 +144,10 @@ Each milestone = independently mergeable PR upstream (unless marked ❌).
### Milestone 2 — Frontend WS adapter ✅
- Define `storage/contract.js` interface spec.
- Move all Firestore call sites from `App.js` into `storage/firebase.js` behind interface (verbatim).
- Implement `storage/ws.js` per interface, talking to backend. Generic KV ops, subscribes to WS.
- Implement `storage/server.js` per interface, talking to backend. Generic KV ops, subscribes via WebSocket.
- Implement `storage/memory.js` for frontend unit tests.
- `storage/index.js` factory: `STORAGE` env → pick impl. Default `firebase` (upstream unchanged).
- App runs against backend with `STORAGE=ws`.
- App runs against backend with `STORAGE=server`.
- Cross-device verified manually: DM view + player display + tablet.
- **Exit criteria:** app runs fully against local backend, no Firebase. Multi-device sync works. ✅ DONE.
- **Upstream-PRable:** ⚠️ partial. Storage interface + firebase extract = ✅. WS impl = ❌.
@@ -155,7 +155,7 @@ Each milestone = independently mergeable PR upstream (unless marked ❌).
### Milestone 3 — Characterization tests lock current behavior ✅
- Lock current behavior via tests.
- Cover: START, NEXT_TURN, PAUSE, RESUME, ADD_PARTICIPANT, REMOVE_PARTICIPANT, TOGGLE_ACTIVE, REORDER, APPLY_DAMAGE/HEAL, DEATH_SAVE, END.
- Two layers: Layer 1 (App + firebase mock, proves call shape), Layer 2 (ws adapter vs live backend, proves translation).
- Two layers: Layer 1 (App + firebase mock, proves call shape), Layer 2 (server adapter vs live backend, proves translation).
- Iterate until confident: baseline solid, regressions impossible to silently slip.
- **Exit criteria:** characterization suite green. Baseline locked. ✅ DONE.
- **Upstream-PRable:** ✅ if kept storage-agnostic (tests target turn logic shape).
@@ -173,7 +173,7 @@ Each milestone = independently mergeable PR upstream (unless marked ❌).
- Single container: caddy (front, static + proxy) + node backend (internal :4001).
- Files in `docker/` tree (kept separate from upstream root Dockerfile):
- `docker/Dockerfile` — build FE + BE, runtime caddy+node
- `docker/Caddyfile` — proxy /api + /ws to node, static SPA fallback
- `docker/Caddyfile` — proxy /api + /ws (WebSocket path) to node, static SPA fallback
- `docker/entrypoint.sh` — node bg + caddy fg
- `docker/docker-compose.yml` — one `app` service, volume for sqlite
- Run: `docker compose -f docker/docker-compose.yml up --build` (or `cd docker && docker compose up --build`). Port 8080.
@@ -214,7 +214,7 @@ Each milestone = independently mergeable PR upstream (unless marked ❌).
### Manual smoke via config flags
- `STORAGE=firebase` → current behavior (friend's path, upstream default).
- `STORAGE=ws` → our path, local backend.
- `STORAGE=server` → our path, local backend.
- docker-compose profiles mirror the above.
### Accepted test gap
@@ -261,6 +261,6 @@ Default `STORAGE=firebase` + `AUTH_MODE=none` (unset) = upstream sees literally
- M0 ✅, M1 ✅, M2 ✅, M3 ✅, M4 ✅, M5 ✅
- Backend live: port 4001, db `./data/tracker.sqlite`
- Frontend: port 3999 with `REACT_APP_STORAGE=ws`
- Frontend: port 3999 with `REACT_APP_STORAGE=server`
- Test suite: ~160 tests (shared + server + FE). Bugs tracked in `TODO.md`.
- Next milestones: M5 docker-compose. Undo moved to TODO backlog.
+5 -6
View File
@@ -194,11 +194,11 @@ curl http://127.0.0.1:4001/health # → {"ok":true}
Never db in `/tmp` (wipe risk). Use `./data/` (gitignored) or docker volume.
### Frontend (ws mode)
### Frontend (server mode)
```bash
REACT_APP_STORAGE=ws \
REACT_APP_STORAGE=server \
REACT_APP_BACKEND_URL=http://127.0.0.1:4001 \
REACT_APP_BACKEND_WS=ws://127.0.0.1:4001/ws \
REACT_APP_BACKEND_REALTIME_URL=ws://127.0.0.1:4001/ws \
BROWSER=none PORT=3999 \
npm start
```
@@ -210,10 +210,9 @@ Firebase mode (default): set `REACT_APP_FIREBASE_*` in `.env.local` (copy `env.e
`STORAGE_MODE = getStorageMode()` reads `REACT_APP_STORAGE`:
- `firebase` (default) → real SDK
- `ws` → backend (docker/prod)
- `memory` → in-process (test seed)
- `server` → backend (docker/prod)
All adapters ESM. Adapter contract: `src/storage/contract.js` — same spec vs memory/ws/firebase.
All adapters ESM. Adapter contract: `src/storage/contract.js` — same spec vs server/firebase.
## Known RED / backlog
+24 -10
View File
@@ -13,7 +13,6 @@
],
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"autoprefixer": "^10.4.19",
"firebase": "^10.12.2",
@@ -24,6 +23,9 @@
"react-scripts": "5.0.1",
"tailwindcss": "^3.4.3",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"@testing-library/react": "^14.3.1"
}
},
"node_modules/@adobe/css-tools": {
@@ -5237,17 +5239,18 @@
}
},
"node_modules/@testing-library/react": {
"version": "13.4.0",
"resolved": "https://registry.npmjs.org/@testing-library/react/-/react-13.4.0.tgz",
"integrity": "sha512-sXOGON+WNTh3MLE9rve97ftaZukN3oNf2KjDy7YTx6hcTO2uuLHuCGynMDhFwGw/jYf4OJ2Qk0i4i79qMNNkyw==",
"version": "14.3.1",
"resolved": "https://registry.npmjs.org/@testing-library/react/-/react-14.3.1.tgz",
"integrity": "sha512-H99XjUhWQw0lTgyMN05W3xQG1Nh4lq574D8keFf1dDoNTJgp66VbJozRaczoF+wsiaPJNt/TcnfpLGufGxSrZQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@testing-library/dom": "^8.5.0",
"@testing-library/dom": "^9.0.0",
"@types/react-dom": "^18.0.0"
},
"engines": {
"node": ">=12"
"node": ">=14"
},
"peerDependencies": {
"react": "^18.0.0",
@@ -5255,9 +5258,10 @@
}
},
"node_modules/@testing-library/react/node_modules/@testing-library/dom": {
"version": "8.20.1",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-8.20.1.tgz",
"integrity": "sha512-/DiOQ5xBxgdYRC8LNk7U+RWat0S3qRLeIw3ZIkMQ9kkVlRmwD/Eg8k8CqIpD6GW7u20JIUOfMKbxtiLutpjQ4g==",
"version": "9.3.4",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-9.3.4.tgz",
"integrity": "sha512-FlS4ZWlp97iiNWig0Muq8p+3rVDjRiYE+YKGbAqXOu9nwJFFOdL00kFpz42M+4huzYi86vAK1sOOfyOG45muIQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.10.4",
@@ -5270,13 +5274,14 @@
"pretty-format": "^27.0.2"
},
"engines": {
"node": ">=12"
"node": ">=14"
}
},
"node_modules/@testing-library/react/node_modules/aria-query": {
"version": "5.1.3",
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz",
"integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"deep-equal": "^2.0.5"
@@ -5286,6 +5291,7 @@
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -5635,6 +5641,7 @@
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"dev": true,
"license": "MIT",
"peer": true
},
@@ -5660,6 +5667,7 @@
"version": "18.3.27",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz",
"integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
@@ -5671,6 +5679,7 @@
"version": "18.3.7",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
@@ -9383,6 +9392,7 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT",
"peer": true
},
@@ -9505,6 +9515,7 @@
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.3.tgz",
"integrity": "sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==",
"dev": true,
"license": "MIT",
"dependencies": {
"array-buffer-byte-length": "^1.0.0",
@@ -10118,6 +10129,7 @@
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.3.tgz",
"integrity": "sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.2",
@@ -12560,6 +12572,7 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.2.0.tgz",
"integrity": "sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
@@ -16816,6 +16829,7 @@
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.6.tgz",
"integrity": "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.7",
+4 -2
View File
@@ -8,7 +8,6 @@
],
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"autoprefixer": "^10.4.19",
"firebase": "^10.12.2",
@@ -28,7 +27,7 @@
"server:dev": "npm run dev --workspace server",
"server:test": "npm test --workspace server",
"shared:test": "npm test --workspace shared",
"test:all": "npm run shared:test && npm run server:test"
"test:all": "CI=true react-scripts test --watchAll=false && npm run shared:test && npm run server:test"
},
"eslintConfig": {
"extends": [
@@ -47,5 +46,8 @@
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@testing-library/react": "^14.3.1"
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ Manual demo tool. NOT test.
## replay-combat.js
Live backend demo. Drives full combat via ws adapter (same contract as App).
Live backend demo. Drives full combat via server adapter (same contract as App).
Player display live-updates. Watch UI react to state changes.
```bash
+4 -4
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Start local dev stack: node backend (sqlite) + react frontend, ws storage mode.
# Start local dev stack: node backend (sqlite) + react frontend, server storage mode.
# Usage: ./scripts/dev-start.sh
# Stop: ./scripts/dev-stop.sh
set -euo pipefail
@@ -25,12 +25,12 @@ else
echo "backend already on :4001"
fi
# frontend: ws storage, :3999
# frontend: server storage, :3999
if ! lsof -ti :3999 >/dev/null 2>&1; then
echo "starting frontend :3999..."
REACT_APP_STORAGE=ws \
REACT_APP_STORAGE=server \
REACT_APP_BACKEND_URL=http://127.0.0.1:4001 \
REACT_APP_BACKEND_WS=ws://127.0.0.1:4001/ws \
REACT_APP_BACKEND_REALTIME_URL=ws://127.0.0.1:4001/ws \
BROWSER=none PORT=3999 \
nohup npm start > tmp/fe.log 2>&1 &
echo $! > tmp/fe.pid
+3 -3
View File
@@ -30,10 +30,10 @@ const {
toggleParticipantActive, applyHpChange, deathSave,
toggleCondition, reorderParticipants, endEncounter,
} = shared;
const { createWsStorage } = require('../src/storage/ws');
const { createServerStorage } = require('../src/storage/server');
const BACKEND = process.env.BACKEND_URL || 'http://127.0.0.1:4001';
const WS_URL = process.env.BACKEND_WS || BACKEND.replace(/^http/, 'ws') + '/ws';
const WS_URL = process.env.BACKEND_REALTIME_URL || BACKEND.replace(/^http/, 'ws') + '/ws';
const ROUNDS = parseInt(process.argv[2], 10) || 100;
const DELAY = parseInt(process.argv[3], 10) || 200;
@@ -51,7 +51,7 @@ const getPath = {
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
// Use the ADAPTER as the contract boundary (same as App). No raw REST.
const storage = createWsStorage({ baseUrl: BACKEND, wsUrl: WS_URL });
const storage = createServerStorage({ baseUrl: BACKEND, realtimeUrl: WS_URL });
// Mirror App.js CONDITIONS so we exercise all of them.
const CONDITIONS = [
+1 -1
View File
@@ -10,7 +10,7 @@
// logs/{id} doc
//
// No shape-specific tables. Data is opaque JSON. This is the firebase mirror:
// the adapter (src/storage/ws.js) is a thin passthrough, app logic unchanged.
// the adapter (src/storage/server.js) is a thin passthrough, app logic unchanged.
'use strict';
+1 -1
View File
@@ -1,6 +1,6 @@
// server/index.js — generic KV document store over HTTP + WebSocket.
// firebase mirror: doc-tree model. Thin REST, path-based WS push.
// Adapter (src/storage/ws.js) = passthrough, no shape translation.
// Adapter (src/storage/server.js) = passthrough, no shape translation.
'use strict';
@@ -1,9 +1,9 @@
// Layer 2 test: exercise ws.js storage adapter against a LIVE backend.
// Layer 2 test: exercise server.js storage adapter against a LIVE backend.
// Complements Layer 1 (App + firebase mock) which proves App call shape but
// never touches ws.js. This catches translation bugs in the adapter.
//
// Runs the shared storage contract (same spec memory/firebase satisfy) against
// createWsStorage pointed at an ephemeral backend instance. A FRESH backend is
// createServerStorage pointed at an ephemeral backend instance. A FRESH backend is
// spun up per test to guarantee isolation (backend has no reset endpoint yet).
'use strict';
@@ -11,7 +11,7 @@
const path = require('path');
const os = require('os');
const { createServer } = require('../index');
const { createWsStorage } = require('../../src/storage/ws');
const { createServerStorage } = require('../../src/storage/server');
const { runStorageContract } = require('../../src/storage/contract');
// Factory: fresh backend (unique sqlite file) + storage pointed at it.
@@ -26,9 +26,9 @@ async function makeStorage() {
const port = handle.server.address().port;
const baseUrl = `http://127.0.0.1:${port}`;
const wsUrl = `ws://127.0.0.1:${port}/ws`;
const storage = createWsStorage({ baseUrl, wsUrl });
const storage = createServerStorage({ baseUrl, realtimeUrl: wsUrl });
storage.dispose = (done) => handle.close(done);
return storage;
}
runStorageContract('ws (live backend)', makeStorage);
runStorageContract('server (live backend)', makeStorage);
@@ -8,7 +8,7 @@
const path = require('path');
const os = require('os');
const { createServer } = require('../index');
const { createWsStorage } = require('../../src/storage/ws');
const { createServerStorage } = require('../../src/storage/server');
const flush = (ms = 150) => new Promise(r => setTimeout(r, ms));
@@ -22,7 +22,7 @@ async function makeStorage() {
const port = handle.server.address().port;
const baseUrl = `http://127.0.0.1:${port}`;
const wsUrl = `ws://127.0.0.1:${port}/ws`;
const storage = createWsStorage({ baseUrl, wsUrl });
const storage = createServerStorage({ baseUrl, realtimeUrl: wsUrl });
storage.dispose = (done) => handle.close(done);
return storage;
}
@@ -48,7 +48,7 @@ describe('BUG-8: ws adapter reconnect after drop', () => {
await flush(1000);
const last = calls[calls.length - 1];
expect(last).toEqual({ name: 'V2' });
expect(last).toEqual({ id: 'a', name: 'V2' });
} finally {
await new Promise(r => storage.dispose(r));
}
+70
View File
@@ -0,0 +1,70 @@
// STATIC GUARD: no `.sort(` introduced in shared/turn.js outside the ONE
// allowed function (sortParticipantsByInitiative, used by startEncounter to
// freeze the list once). Slot-not-sort design (docs/INITIATIVE_ORDERING.md):
// mutations = insert/move, never wholesale re-sort. A stray `.sort(` after
// start destroys drag tie-break order.
//
// This test errs the moment someone adds `.sort(` anywhere but the allowlist.
// Maintenance: add a function to ALLOWED only if it runs at startEncounter
// (one-time freeze), NOT in add/update/reorder/nextTurn paths.
'use strict';
const fs = require('fs');
const path = require('path');
const SRC = fs.readFileSync(path.join(__dirname, '..', 'turn.js'), 'utf8');
// Functions permitted to call .sort(. Listed so intent is explicit + reviewed.
const ALLOWED_SORT_FUNCTIONS = new Set([
'sortParticipantsByInitiative',
]);
// Collect top-level function bodies by brace counting.
// Matches `function NAME(` decls AND `const NAME = ... =>` arrow fns.
// Returns [{ name, body }].
function collectBody(src, fromIdx) {
let i = fromIdx;
while (i < src.length && src[i] !== '{') i++;
let depth = 0;
const start = i;
for (; i < src.length; i++) {
if (src[i] === '{') depth++;
else if (src[i] === '}') { depth--; if (depth === 0) break; }
}
return src.slice(start, i + 1);
}
function extractFunctions(src) {
const out = [];
const fnRe = /\bfunction\s+([A-Za-z0-9_$]+)\s*\(/g;
const arrowRe = /(?:const|let|var)\s+([A-Za-z0-9_$]+)\s*=\s*[^=;]*?=>/g;
let m;
while ((m = fnRe.exec(src)) !== null) {
out.push({ name: m[1], body: collectBody(src, m.index + m[0].length) });
}
while ((m = arrowRe.exec(src)) !== null) {
out.push({ name: m[1], body: collectBody(src, m.index + m[0].length) });
}
return out;
}
describe('STATIC: no .sort( outside allowlist (slot-not-sort design)', () => {
test('every .sort( call lives in an allowed function', () => {
const fns = extractFunctions(SRC);
const offenders = [];
for (const { name, body } of fns) {
if (!ALLOWED_SORT_FUNCTIONS.has(name) && /\.sort\(/.test(body)) {
offenders.push(name);
}
}
expect(offenders).toEqual([]);
});
test('allowed sort function is declared (no silent allowlist drift)', () => {
const declared = new Set(extractFunctions(SRC).map(f => f.name));
for (const name of ALLOWED_SORT_FUNCTIONS) {
expect(declared.has(name)).toBe(true);
}
});
});
+10 -11
View File
@@ -213,22 +213,21 @@ describe('applyHpChange', () => {
expect(patch.participants[0].currentHp).toBe(10);
});
test('damage to 0 keeps active + stays in turn order (FEAT-1)', () => {
// FEAT-1: death no longer deactivates or removes from turn order.
// Dead stay in rotation, nextTurn still visits them, PCs get death-save turn.
test('damage to 0 deactivates + keeps turn order (unified)', () => {
// Unified: death flips isActive=false (removed from active rotation).
// turnOrderIds unchanged (no turn-order patch on death).
const ps = [p('a', 10, { currentHp: 3 }), p('b', 5)];
const e = enc(ps, { isStarted: true, turnOrderIds: ['a', 'b'], currentTurnParticipantId: 'a' });
const { patch } = applyHpChange(e, 'a', 'damage', 5);
expect(patch.participants[0].currentHp).toBe(0);
expect(patch.participants[0].isActive).toBe(true);
expect(patch.participants[0].isActive).toBe(false);
expect(patch.turnOrderIds).toBeUndefined();
expect(patch.currentTurnParticipantId).toBeUndefined();
});
test('heal above 0 resets death saves, keeps active (FEAT-1)', () => {
// FEAT-1: revive no longer flips isActive (was already active — death
// doesn't deactivate). deathSaves still reset.
const ps = [p('a', 10, { currentHp: 0, deathSaves: 2 })];
test('heal above 0 reactivates + resets death saves (unified)', () => {
// Unified: revive from 0 flips isActive=true, deathSaves reset.
const ps = [p('a', 10, { currentHp: 0, isActive: false, deathSaves: 2 })];
const { patch } = applyHpChange(enc(ps), 'a', 'heal', 5);
expect(patch.participants[0].currentHp).toBe(5);
expect(patch.participants[0].isActive).toBe(true);
@@ -285,17 +284,17 @@ describe('toggleCondition', () => {
});
describe('reorderParticipants', () => {
test('drag before target (1-list, cross-init allowed)', () => {
test('drag before target (same-init tie)', () => {
const ps = [p('a', 10), p('b', 10), p('c', 10)];
const { patch } = reorderParticipants(enc(ps), 'a', 'c');
// drag a before c: remove a → [b,c], insert before c → [b,a,c]
expect(patch.participants.map(x => x.id)).toEqual(['b', 'a', 'c']);
});
test('cross-init drag allowed (1-list, DM override)', () => {
test('cross-init drag blocked (no-op)', () => {
const ps = [p('a', 10), p('b', 5)];
const { patch } = reorderParticipants(enc(ps), 'a', 'b');
expect(patch.participants.map(x => x.id)).toEqual(['a', 'b']);
expect(patch).toBeNull();
});
});
+32 -15
View File
@@ -1,6 +1,9 @@
// M4 desired behavior: dead PC stays in turn order, turn still comes up,
// deathSave fires. Current code filters isActive (set false on death) so
// dead participants are SKIPPED. Test asserts desired state = RED on current.
// Unified behavior (App main): death flips isActive=false, dead participant
// removed from active rotation, skipped by nextTurn. deathSave is a manual
// DM action (button), not tied to rotation. turnOrderIds unchanged on death
// (only isActive flag flips). Revive (heal from 0) reactivates.
//
// Previous "M4: dead stays in rotation" concept reversed by unification.
const shared = require('@ttrpg/shared');
const { makeParticipant, startEncounter, nextTurn, applyHpChange, deathSave } = shared;
@@ -24,8 +27,8 @@ function enc(ps) {
round:0, currentTurnParticipantId:null, turnOrderIds:[] };
}
describe('M4: dead participants stay in turn order', () => {
test('dead PC not removed from turnOrderIds', () => {
describe('unified: death deactivates, dead skipped in rotation', () => {
test('dead PC not removed from turnOrderIds (stays in list, inactive)', () => {
const ps = [pc('a', 20), pc('b', 15), pc('c', 10)];
let e = enc(ps);
e = { ...e, ...startEncounter(e).patch };
@@ -35,39 +38,53 @@ describe('M4: dead participants stay in turn order', () => {
expect(e.turnOrderIds).toEqual(orderBefore);
});
test('dead PC turn still comes up (nextTurn visits them)', () => {
test('dead PC skipped by nextTurn (isActive=false)', () => {
const ps = [pc('a', 20), pc('b', 15), pc('c', 10)];
let e = enc(ps);
e = { ...e, ...startEncounter(e).patch };
// kill b
e = { ...e, ...applyHpChange(e, 'b', 'damage', 100).patch };
// advance: a→b→c. b's turn should come up.
// advance: a→c (b skipped, inactive)
e = { ...e, ...nextTurn(e).patch };
expect(e.currentTurnParticipantId).toBe('b');
expect(e.currentTurnParticipantId).toBe('c');
});
test('dead PC on their turn can deathSave', () => {
test('dead PC deathSave fires on manual call (not via rotation)', () => {
const ps = [pc('a', 20), pc('b', 15)];
let e = enc(ps);
e = { ...e, ...startEncounter(e).patch };
// kill b (current = a)
e = { ...e, ...applyHpChange(e, 'b', 'damage', 100).patch };
// advance to b's turn
e = { ...e, ...nextTurn(e).patch };
expect(e.currentTurnParticipantId).toBe('b');
// b is dead, on their turn: deathSave should not throw
// b is dead: DM can still fire deathSave (manual action)
const r = deathSave(e, 'b', 1);
expect(r.patch).toBeTruthy();
const b = r.patch.participants.find(x => x.id === 'b');
expect(b.deathSaves).toBe(1);
});
test('dead PC not auto-set isActive=false by applyHpChange', () => {
// D1 unification: shared now matches App main — death flips isActive=false.
// Dead participant removed from active rotation (skipped by nextTurn).
test('dead PC auto-set isActive=false by applyHpChange', () => {
const ps = [pc('a', 20), pc('b', 15)];
let e = enc(ps);
e = { ...e, ...startEncounter(e).patch };
e = { ...e, ...applyHpChange(e, 'b', 'damage', 100).patch };
const b = e.participants.find(x => x.id === 'b');
expect(b.isActive).toBe(true);
expect(b.isActive).toBe(false);
});
test('revive (heal from 0) reactivates participant', () => {
const ps = [pc('a', 20), pc('b', 15)];
let e = enc(ps);
e = { ...e, ...startEncounter(e).patch };
e = { ...e, ...applyHpChange(e, 'b', 'damage', 100).patch };
const dead = e.participants.find(x => x.id === 'b');
expect(dead.isActive).toBe(false);
// heal b back up
e = { ...e, ...applyHpChange(e, 'b', 'heal', 50).patch };
const revived = e.participants.find(x => x.id === 'b');
expect(revived.isActive).toBe(true);
expect(revived.currentHp).toBe(50);
expect(revived.deathSaves).toBe(0);
});
});
+6 -6
View File
@@ -82,16 +82,16 @@ describe('1-list model: turnOrderIds === participants.map(id), no re-sort', () =
expect(e.turnOrderIds).toEqual(e.participants.map(x => x.id));
});
test('reorder cross-init: allowed, list + rotation reflect new order', () => {
test('reorder cross-init: blocked (no-op)', () => {
let e = enc([p('a',10),p('b',7),p('c',3)]);
e = apply(e, startEncounter(e)); // [a,b,c]
e = apply(e, reorderParticipants(e, 'c', 'a')); // drag c before a
expect(e.turnOrderIds).toEqual(['c','a','b']);
expect(e.turnOrderIds).toEqual(e.participants.map(x => x.id));
const r = reorderParticipants(e, 'c', 'a'); // cross-init
expect(r.patch).toBeNull();
expect(e.turnOrderIds).toEqual(['a','b','c']); // unchanged
});
test('reorder: rotation follows new list order', () => {
let e = enc([p('a',10),p('b',7),p('c',3)]);
test('reorder same-init: rotation follows new list order', () => {
let e = enc([p('a',10),p('b',10),p('c',3)]); // a,b tie
e = apply(e, startEncounter(e)); // [a,b,c], cur=a
e = apply(e, reorderParticipants(e, 'b', 'a')); // [b,a,c], cur still a
const rot = walkRotation(e); // start a, next c (wrap), next b, back a
+2 -2
View File
@@ -29,12 +29,12 @@ describe('reorderParticipants', () => {
expect(r.patch.participants.map(p => p.id)).toEqual(['c', 'b', 'a']);
});
test('cross-init drag allowed (1-list, DM override)', () => {
test('cross-init drag blocked (no-op)', () => {
const ps = [p('a', 10), p('b', 20)];
let e = enc(ps);
e = { ...e, ...startEncounter(e).patch }; // [b,a]
const r = reorderParticipants(e, 'a', 'b');
expect(r.patch.participants.map(p => p.id)).toEqual(['a', 'b']);
expect(r.patch).toBeNull();
});
test('throws if id not found', () => {
+77
View File
@@ -0,0 +1,77 @@
// SLOT-NOT-SORT invariant: addParticipant + updateParticipant must PRESERVE
// manually-dragged tie order (same-initiative participants).
//
// Design doc (docs/INITIATIVE_ORDERING.md):
// "Re-slotting on add/edit must preserve drag-established tie order."
// "Tie-break = original add order. Later additions slot AFTER existing
// same-init participants. Stable insertion."
//
// Current code uses sortParticipantsByInitiative (stable sort, tie-break =
// original array index). That is NOT stable insertion: it re-sorts the whole
// list, destroying drag order when a drag moved a same-init pair.
//
// RED now: drag tie order survives neither add nor edit.
'use strict';
const shared = require('@ttrpg/shared');
const {
makeParticipant,
startEncounter, addParticipant, updateParticipant, reorderParticipants,
} = shared;
function p(id, init, extra = {}) {
return makeParticipant({ id, name: id, type: 'monster',
initiative: init, maxHp: 100, currentHp: 100, ...extra });
}
function enc(ps, extra = {}) {
return { name:'t', participants:ps, isStarted:false, isPaused:false,
round:0, currentTurnParticipantId:null, turnOrderIds:[], ...extra };
}
const apply = (e, r) => r && r.patch ? { ...e, ...r.patch } : e;
describe('SLOT-NOT-SORT: drag tie order survives add/edit', () => {
test('addParticipant preserves existing drag tie order', () => {
// Two same-init participants. DM drags b BEFORE a (tie override).
let e = enc([p('a', 10), p('b', 10)]);
e = apply(e, reorderParticipants(e, 'b', 'a')); // drag b ahead of a → [b,a]
expect(e.participants.map(x => x.id)).toEqual(['b', 'a']);
// Add unrelated participant (different init). Tie order [b,a] MUST survive.
e = apply(e, addParticipant(e, p('c', 5)));
const ids = e.participants.map(x => x.id);
// c slots last (init 5 < 10). b,a tie order preserved.
expect(ids).toEqual(['b', 'a', 'c']);
});
test('addParticipant with same init as dragged pair slots AFTER tie group', () => {
// DM drags b before a (both init 10). Then add d also init 10.
// d must slot AFTER existing same-init pair (stable insertion), not re-sort.
let e = enc([p('a', 10), p('b', 10)]);
e = apply(e, reorderParticipants(e, 'b', 'a')); // [b,a]
e = apply(e, addParticipant(e, p('d', 10))); // init 10, after tie group
const ids = e.participants.map(x => x.id);
expect(ids).toEqual(['b', 'a', 'd']);
});
test('updateParticipant preserves drag tie order on unrelated field edit', () => {
let e = enc([p('a', 10), p('b', 10)]);
e = apply(e, reorderParticipants(e, 'b', 'a')); // [b,a]
// Edit a's name (not initiative). Tie order MUST survive.
e = apply(e, updateParticipant(e, 'a', { name: 'A2' }));
expect(e.participants.map(x => x.id)).toEqual(['b', 'a']);
});
test('updateParticipant init change slots, preserves OTHER tie group order', () => {
// Two tie groups: [a,b] init 10, [c,d] init 5. DM drags b before a.
let e = enc([p('a', 10), p('b', 10), p('c', 5), p('d', 5)]);
e = apply(e, reorderParticipants(e, 'b', 'a')); // [b,a,c,d]
// Edit c's initiative to 10 — slots into top group. [c] order within its
// own old group irrelevant (it leaves that group). But [b,a] tie MUST stay.
e = apply(e, updateParticipant(e, 'c', { initiative: 10 }));
const topTwo = e.participants.filter(x => x.initiative === 10).map(x => x.id);
// b before a preserved. c joins the 10-group (exact slot less critical
// than b,a order surviving).
expect(topTwo.indexOf('b')).toBeLessThan(topTwo.indexOf('a'));
});
});
+82 -35
View File
@@ -31,9 +31,18 @@ const formatInitMod = (mod) => {
return mod >= 0 ? `+${mod}` : `${mod}`;
};
// Sort used ONLY at insert points (startEncounter, addParticipant) to position
// participants by initiative. Once positioned, turnOrderIds = participants.map(id)
// (1-list model). No re-sort after start — drag/edit are manual overrides.
// SLOT, NEVER SORT. 1-list model (docs/INITIATIVE_ORDERING.md).
//
// `sortParticipantsByInitiative` exists for ONE call site: startEncounter
// (freeze list once by init). After that, mutations = insert/move ops that
// PRESERVE existing array order. No wholesale re-sort ever — destroys drag
// tie-break order.
//
// slotIndexForInit: pure insert position. Scans existing list, returns index
// of first participant with init STRICTLY LESS than target. New participant
// splices there. Same-init participants stay ahead (stable). Existing tie
// order (incl. drag-established) untouched because scan reads current array,
// not original add-order.
const sortParticipantsByInitiative = (participants, originalOrder) => {
return [...participants].sort((a, b) => {
if (a.initiative === b.initiative) {
@@ -45,6 +54,17 @@ const sortParticipantsByInitiative = (participants, originalOrder) => {
});
};
// Find splice index for a single participant by initiative. List assumed
// already initiative-descending (startEncounter freezes it; add/edit maintain).
// Returns position to insert so list stays descending, ties go AFTER existing
// same-init (stable insertion). Current array order = source of truth.
function slotIndexForInit(list, init) {
for (let i = 0; i < list.length; i++) {
if (init > list[i].initiative) return i;
}
return list.length;
}
// 1-LIST SYNC: turnOrderIds always mirrors participants[].map(id).
// Call after any participants[] mutation. Returns turnOrderIds patch.
const syncTurnOrder = (participants) => ({
@@ -311,26 +331,14 @@ function addParticipant(encounter, participant) {
if ((encounter.participants || []).some(p => p.id === participant.id)) {
throw new Error(`Participant with id "${participant.id}" already exists in encounter.`);
}
// 1-list: splice participant into participants[] by initiative position,
// then sync turnOrderIds = participants.map(id).
let updatedParticipants;
let insertAt;
if (!encounter.isStarted) {
updatedParticipants = [...(encounter.participants || []), participant];
} else {
const { insertAt: at } = computeTurnOrderAfterAddition(
{ ...encounter, participants: [...(encounter.participants || []), participant] },
participant.id);
insertAt = at !== undefined ? at : (encounter.participants || []).length;
updatedParticipants = [
...(encounter.participants || []).slice(0, insertAt),
participant,
...(encounter.participants || []).slice(insertAt),
];
}
const turnUpdates = encounter.isStarted ? syncTurnOrder(updatedParticipants) : {};
// SLOT (not sort): insert by initiative into current list. Preserves
// existing array order incl. drag-established tie order.
const base = [...(encounter.participants || [])];
const idx = slotIndexForInit(base, participant.initiative);
base.splice(idx, 0, participant);
const updatedParticipants = base;
return {
patch: { participants: updatedParticipants, ...turnUpdates },
patch: { participants: updatedParticipants, ...syncTurnOrder(updatedParticipants) },
log: {
message: `${participant.name} added to encounter (Initiative: ${participant.initiative})`,
undo: {
@@ -351,10 +359,21 @@ function addParticipants(encounter, newParticipants) {
// UPDATE_PARTICIPANT — edit modal save (name/initiative/hp/isNpc).
function updateParticipant(encounter, participantId, updatedData) {
const updatedParticipants = (encounter.participants || []).map(p =>
p.id === participantId ? { ...p, ...updatedData } : p
);
return { patch: { participants: updatedParticipants }, log: null };
const existing = encounter.participants || [];
const target = existing.find(p => p.id === participantId);
if (!target) throw new Error(`Participant "${participantId}" not found.`);
const merged = { ...target, ...updatedData };
// SLOT only if initiative changed. Other edits (name/hp/notes/isNpc) = no
// position change (design doc). Re-slots on unrelated edits shuffle the
// list mid-round → rotation dupes.
if (!('initiative' in updatedData) || updatedData.initiative === target.initiative) {
const sameSlot = existing.map(p => p.id === participantId ? merged : p);
return { patch: { participants: sameSlot, ...syncTurnOrder(sameSlot) }, log: null };
}
const without = existing.filter(p => p.id !== participantId);
const idx = slotIndexForInit(without, merged.initiative);
without.splice(idx, 0, merged);
return { patch: { participants: without, ...syncTurnOrder(without) }, log: null };
}
// REMOVE_PARTICIPANT — verbatim from ParticipantManager.confirmDeleteParticipant
@@ -427,24 +446,24 @@ function applyHpChange(encounter, participantId, changeType, amount) {
const isDead = newHp === 0;
const wasResurrected = wasDead && newHp > 0;
// FEAT-1: death no longer flips isActive or touches turnOrderIds.
// Dead participants stay in turn order, nextTurn still visits them, PCs
// get their death-save turn. isActive = DM-controlled combatant toggle only.
// Unified (App main): death flips isActive=false (removed from active
// rotation, skipped by nextTurn). Revive flips true. No turnOrderIds change.
const updatedParticipants = (encounter.participants || []).map(p => {
if (p.id !== participantId) return p;
const updates = { ...p, currentHp: newHp };
if (isDead && !wasDead) {
updates.isActive = false;
updates.deathSaves = p.deathSaves || 0;
updates.isDying = false;
}
if (wasResurrected) {
updates.isActive = true;
updates.deathSaves = 0;
updates.isDying = false;
}
return updates;
});
// No turn-order updates on death/revive (FEAT-1).
const turnUpdates = {};
const hpLine = `${participant.currentHp}${newHp} HP`;
@@ -519,15 +538,19 @@ function toggleCondition(encounter, participantId, conditionId) {
// REORDER_PARTICIPANTS — drag-drop. 1-list model: drag overrides initiative
// (DM choice). Cross-init drag allowed. Splices participants[], syncs turnOrderIds.
// REORDER_PARTICIPANTS — drag. Same-initiative ONLY (tie-break override).
// Cross-init drag = no-op (use edit-initiative field instead). Splice move.
function reorderParticipants(encounter, draggedId, targetId) {
const participants = [...(encounter.participants || [])];
const draggedIndex = participants.findIndex(p => p.id === draggedId);
const targetIndex = participants.findIndex(p => p.id === targetId);
if (draggedIndex === -1 || targetIndex === -1) {
throw new Error('Dragged or target item not found.');
const dragged = participants.find(p => p.id === draggedId);
const target = participants.find(p => p.id === targetId);
if (!dragged || !target) throw new Error('Dragged or target item not found.');
if (draggedId === targetId) return { patch: null, log: null };
if (dragged.initiative !== target.initiative) {
return { patch: null, log: null }; // cross-init blocked
}
const draggedIndex = participants.findIndex(p => p.id === draggedId);
const [removedItem] = participants.splice(draggedIndex, 1);
// recompute targetIndex after removal (shift if dragged was before target)
const newTargetIndex = participants.findIndex(p => p.id === targetId);
participants.splice(newTargetIndex, 0, removedItem);
const turnUpdates = encounter.isStarted ? syncTurnOrder(participants) : {};
@@ -557,6 +580,27 @@ function endEncounter(encounter) {
};
}
// ----------------------------------------------------------------------------
// Display lifecycle (activeDisplay/status doc). Pure patches, same shape as
// App's inline storage.updateDoc(getPath.activeDisplay(), ...). Single source.
// Callers persist patch to the activeDisplay/status doc.
// ----------------------------------------------------------------------------
// ACTIVATE_DISPLAY — start combat: point player display at this encounter.
function activateDisplay({ campaignId, encounterId }) {
return { patch: { activeCampaignId: campaignId, activeEncounterId: encounterId } };
}
// CLEAR_DISPLAY — end combat: player display shows nothing.
function clearDisplay() {
return { patch: { activeCampaignId: null, activeEncounterId: null } };
}
// TOGGLE_HIDE_PLAYER_HP — flip player-HP visibility on display.
function toggleHidePlayerHp(currentValue) {
return { patch: { hidePlayerHp: !currentValue } };
}
module.exports = {
DEFAULT_MAX_HP,
DEFAULT_INIT_MOD,
@@ -584,4 +628,7 @@ module.exports = {
toggleCondition,
reorderParticipants,
endEncounter,
activateDisplay,
clearDisplay,
toggleHidePlayerHp,
};
+116 -385
View File
@@ -1,8 +1,6 @@
import React, { useState, useEffect, useRef, useMemo } from 'react';
import * as shared from '@ttrpg/shared';
import { initializeApp } from './storage';
import { getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken } from './storage';
import { getFirestore, doc, setDoc, addDoc, collection, onSnapshot, updateDoc, deleteDoc, query, orderBy, limit, writeBatch, getStorage, getStorageMode } from './storage';
import { initializeApp, getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken, getFirestore, orderBy, limit, getStorage, getStorageMode } from './storage';
import {
PlusCircle, Users, Swords, Trash2, Eye, Edit3, Save, XCircle, ChevronsUpDown,
UserCheck, UserX, HeartCrack, HeartPulse, Zap, EyeOff, ExternalLink, AlertTriangle,
@@ -46,8 +44,21 @@ if (typeof document !== 'undefined') {
// CONSTANTS
// ============================================================================
const APP_VERSION = 'v0.3';
const { DEFAULT_MAX_HP, DEFAULT_INIT_MOD, MONSTER_DEFAULT_INIT_MOD, generateId, rollD20, formatInitMod, sortParticipantsByInitiative, syncTurnOrder, computeTurnOrderAfterRemoval } = shared;
const APP_VERSION = 'v0.4';
const {
DEFAULT_MAX_HP, DEFAULT_INIT_MOD, MONSTER_DEFAULT_INIT_MOD,
generateId, rollD20, formatInitMod,
sortParticipantsByInitiative, syncTurnOrder,
computeTurnOrderAfterRemoval,
startEncounter, nextTurn, togglePause, endEncounter,
addParticipant, addParticipants, updateParticipant, removeParticipant,
toggleParticipantActive: combatToggleActive,
applyHpChange: combatApplyHpChange,
deathSave: combatDeathSave,
toggleCondition: combatToggleCondition,
reorderParticipants,
activateDisplay, clearDisplay, toggleHidePlayerHp: combatToggleHidePlayerHp,
} = shared;
const ROLL_DISPLAY_DURATION = 5000;
const CONDITIONS = [
@@ -192,6 +203,11 @@ function useFirestoreDocument(docPath) {
const unsubscribe = storage.subscribeDoc(docPath, (doc) => {
setData(doc);
setIsLoading(false);
}, (err) => {
console.error(`Error fetching document ${docPath}:`, err);
setError(err.message || "Failed to fetch document.");
setIsLoading(false);
setData(null);
});
return () => { if (typeof unsubscribe === 'function') unsubscribe(); };
}, [docPath]);
@@ -220,6 +236,11 @@ function useFirestoreCollection(collectionPath, queryConstraints = []) {
const unsubscribe = storage.subscribeCollection(collectionPath, (items) => {
setData(items);
setIsLoading(false);
}, queryConstraints, (err) => {
console.error(`Error fetching collection ${collectionPath}:`, err);
setError(err.message || "Failed to fetch collection.");
setIsLoading(false);
setData([]);
});
return () => { if (typeof unsubscribe === 'function') unsubscribe(); };
// queryString, not array ref
@@ -825,7 +846,6 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
if (participantType === 'character') {
const character = campaignCharacters.find(c => c.id === selectedCharacterId);
if (!character) {
console.error("Selected character not found");
return;
}
if (participants.some(p => p.type === 'character' && p.originalCharacterId === selectedCharacterId)) {
@@ -852,18 +872,16 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
isNpc: participantType === 'monster' ? participantIsNpc : false,
conditions: [],
isActive: true,
deathSaves: 0, // Track failed death saves (0-3)
isDying: false, // For death animation on player display
deathSaves: 0,
isDying: false,
};
try {
await storage.updateDoc(encounterPath, {
participants: sortParticipantsByInitiative([...participants, newParticipant], participants),
...syncTurnOrder([...participants, newParticipant]),
});
logAction(`${nameToAdd} added to encounter (Initiative: ${computedInitiative})`, { encounterName: encounter.name }, {
const { patch, log } = addParticipant(encounter, newParticipant);
await storage.updateDoc(encounterPath, patch);
logAction(log.message, { encounterName: encounter.name }, {
encounterPath,
updates: { participants: [...participants] },
updates: log.undo,
});
setLastRollDetails({
@@ -876,7 +894,6 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
});
setTimeout(() => setLastRollDetails(null), ROLL_DISPLAY_DURATION);
// Reset form
setParticipantName('');
setMaxHp(DEFAULT_MAX_HP);
setSelectedCharacterId('');
@@ -884,7 +901,6 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
setIsNpc(false);
setManualInitiative('');
} catch (err) {
console.error("Error adding participant:", err);
alert("Failed to add participant. Please try again.");
}
};
@@ -902,7 +918,6 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
const initiativeRoll = rollD20();
const modifier = char.defaultInitMod || 0;
const finalInitiative = initiativeRoll + modifier;
return {
id: generateId(),
name: char.name,
@@ -925,32 +940,20 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
}
try {
await storage.updateDoc(encounterPath, {
participants: [...participants, ...newParticipants]
});
console.log(`Added ${newParticipants.length} characters to the encounter.`);
const { patch } = addParticipants(encounter, newParticipants);
await storage.updateDoc(encounterPath, patch);
} catch (err) {
console.error("Error adding all campaign characters:", err);
alert("Failed to add all characters. Please try again.");
}
};
const handleUpdateParticipant = async (updatedData) => {
if (!db || !editingParticipant) return;
const updatedParticipants = participants.map(p =>
p.id === editingParticipant.id ? { ...p, ...updatedData } : p
);
const reslotted = sortParticipantsByInitiative(updatedParticipants, participants);
try {
await storage.updateDoc(encounterPath, {
participants: reslotted,
...syncTurnOrder(reslotted),
});
const { patch } = updateParticipant(encounter, editingParticipant.id, updatedData);
await storage.updateDoc(encounterPath, patch);
setEditingParticipant(null);
} catch (err) {
console.error("Error updating participant:", err);
alert("Failed to update participant. Please try again.");
}
};
@@ -963,17 +966,11 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
if (!db) return;
const n = parseInt(value, 10);
if (isNaN(n)) return;
const updatedParticipants = participants.map(p =>
p.id === participantId ? { ...p, initiative: n } : p
);
const reslotted = sortParticipantsByInitiative(updatedParticipants, participants);
try {
await storage.updateDoc(encounterPath, {
participants: reslotted,
...syncTurnOrder(reslotted),
});
const { patch } = updateParticipant(encounter, participantId, { initiative: n });
await storage.updateDoc(encounterPath, patch);
} catch (err) {
console.error("Error updating initiative:", err);
// fall through silently
}
};
@@ -984,221 +981,89 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
const confirmDeleteParticipant = async () => {
if (!db || !itemToDelete) return;
const updatedParticipants = participants.filter(p => p.id !== itemToDelete.id);
const deleteUndoData = {
encounterPath,
updates: {
participants: [...participants],
...(encounter.isStarted ? {
currentTurnParticipantId: encounter.currentTurnParticipantId,
turnOrderIds: [...(encounter.turnOrderIds || [])],
} : {}),
},
};
try {
await storage.updateDoc(encounterPath, {
participants: updatedParticipants,
...(encounter.isStarted ? {
...syncTurnOrder(updatedParticipants),
...computeTurnOrderAfterRemoval(encounter, itemToDelete.id, updatedParticipants),
} : {}),
const { patch, log } = removeParticipant(encounter, itemToDelete.id);
await storage.updateDoc(encounterPath, patch);
logAction(log.message, { encounterName: encounter.name }, {
encounterPath,
updates: log.undo,
});
logAction(`${itemToDelete.name} removed from encounter`, { encounterName: encounter.name }, deleteUndoData);
} catch (err) {
console.error("Error deleting participant:", err);
alert("Failed to delete participant. Please try again.");
}
setShowDeleteConfirm(false);
setItemToDelete(null);
};
const toggleParticipantActive = async (participantId) => {
if (!db) return;
const participant = participants.find(p => p.id === participantId);
if (!participant) return;
const newIsActive = !participant.isActive;
const updatedParticipants = participants.map(p =>
p.id === participantId ? { ...p, isActive: newIsActive } : p
);
// 1-list: stay in slot, flip isActive only. Sync turnOrderIds. Advance
// current only if deact hits current.
let turnUpdates = {};
if (encounter.isStarted) {
turnUpdates = syncTurnOrder(updatedParticipants);
if (!newIsActive && encounter.currentTurnParticipantId === participantId) {
turnUpdates = { ...turnUpdates, ...computeTurnOrderAfterRemoval(encounter, participantId, updatedParticipants) };
}
}
try {
await storage.updateDoc(encounterPath, { participants: updatedParticipants, ...turnUpdates });
logAction(`${participant.name} ${newIsActive ? 'reactivated' : 'deactivated'}`, { encounterName: encounter.name }, {
const { patch, log } = combatToggleActive(encounter, participantId);
await storage.updateDoc(encounterPath, patch);
logAction(log.message, { encounterName: encounter.name }, {
encounterPath,
updates: {
participants: [...participants],
...(encounter.isStarted ? {
currentTurnParticipantId: encounter.currentTurnParticipantId,
turnOrderIds: [...(encounter.turnOrderIds || [])],
} : {}),
},
updates: log.undo,
});
} catch (err) {
console.error("Error toggling active state:", err);
// fall through silently
}
};
const applyHpChange = async (participantId, changeType) => {
if (!db) return;
const amountStr = hpChangeValues[participantId];
if (!amountStr || amountStr.trim() === '') return;
const amount = parseInt(amountStr, 10);
if (isNaN(amount) || amount === 0) {
setHpChangeValues(prev => ({ ...prev, [participantId]: '' }));
return;
}
const participant = participants.find(p => p.id === participantId);
if (!participant) return;
let newHp = participant.currentHp;
if (changeType === 'damage') {
newHp = Math.max(0, participant.currentHp - amount);
} else if (changeType === 'heal') {
newHp = Math.min(participant.maxHp, participant.currentHp + amount);
}
// Determine if participant died or was resurrected
const wasDead = participant.currentHp === 0;
const isDead = newHp === 0;
const wasResurrected = wasDead && newHp > 0;
const updatedParticipants = participants.map(p => {
if (p.id === participantId) {
const updates = { ...p, currentHp: newHp };
// Handle death - deactivate and start death saves
if (isDead && !wasDead) {
updates.isActive = false;
updates.deathSaves = p.deathSaves || 0;
updates.isDying = false;
}
// Handle resurrection - reactivate and reset death saves
if (wasResurrected) {
updates.isActive = true;
updates.deathSaves = 0;
updates.isDying = false;
}
return updates;
}
return p;
});
const turnUpdates = {};
const hpUndoData = {
encounterPath,
updates: {
participants: [...participants],
...((isDead && !wasDead) || wasResurrected ? {
currentTurnParticipantId: encounter.currentTurnParticipantId,
turnOrderIds: [...(encounter.turnOrderIds || [])],
} : {}),
},
};
try {
await storage.updateDoc(encounterPath, { participants: updatedParticipants, ...turnUpdates });
setHpChangeValues(prev => ({ ...prev, [participantId]: '' }));
const hpLine = `${participant.currentHp}${newHp} HP`;
const deathSuffix = (isDead && !wasDead) ? (participant.type === 'character' ? ' — Unconscious' : ' — Defeated') : '';
const resurSuffix = wasResurrected ? ' — Revived' : '';
if (changeType === 'damage') {
logAction(`${participant.name} took ${amount} damage (${hpLine})${deathSuffix}`, { encounterName: encounter.name }, hpUndoData);
} else {
logAction(`${participant.name} healed for ${amount} (${hpLine})${resurSuffix}`, { encounterName: encounter.name }, hpUndoData);
const { patch, log } = combatApplyHpChange(encounter, participantId, changeType, amount);
if (patch) {
await storage.updateDoc(encounterPath, patch);
if (log) {
logAction(log.message, { encounterName: encounter.name }, {
encounterPath,
updates: log.undo,
});
}
}
setHpChangeValues(prev => ({ ...prev, [participantId]: '' }));
} catch (err) {
console.error("Error applying HP change:", err);
// fall through silently
}
};
const handleDeathSaveChange = async (participantId, saveNumber) => {
if (!db) return;
const participant = participants.find(p => p.id === participantId);
if (!participant) return;
const currentSaves = participant.deathSaves || 0;
const newSaves = currentSaves === saveNumber ? saveNumber - 1 : saveNumber;
// If clicking the third death save, mark as dying (for player view animation)
if (newSaves === 3) {
const updatedParticipants = participants.map(p =>
p.id === participantId ? { ...p, deathSaves: newSaves, isDying: true } : p
);
try {
await storage.updateDoc(encounterPath, { participants: updatedParticipants });
// Wait for animation to complete on player display (2 seconds) then remove participant
try {
const { patch, isDying } = combatDeathSave(encounter, participantId, saveNumber);
await storage.updateDoc(encounterPath, patch);
if (isDying) {
setTimeout(async () => {
const finalParticipants = participants.filter(p => p.id !== participantId);
try {
await storage.updateDoc(encounterPath, { participants: finalParticipants });
} catch (err) {
console.error("Error removing dead participant:", err);
}
const finalParticipants = encounter.participants.filter(p => p.id !== participantId);
await storage.updateDoc(encounterPath, { participants: finalParticipants });
}, 2000);
} catch (err) {
console.error("Error marking participant as dying:", err);
}
} else {
// Normal death save update
const updatedParticipants = participants.map(p =>
p.id === participantId ? { ...p, deathSaves: newSaves } : p
);
try {
await storage.updateDoc(encounterPath, { participants: updatedParticipants });
} catch (err) {
console.error("Error updating death saves:", err);
}
} catch (err) {
// fall through silently
}
};
const toggleCondition = async (participantId, conditionId) => {
if (!db) return;
const participant = participants.find(p => p.id === participantId);
if (!participant) return;
const wasActive = (participant.conditions || []).includes(conditionId);
const updatedParticipants = participants.map(p => {
if (p.id !== participantId) return p;
const current = p.conditions || [];
const next = wasActive
? current.filter(c => c !== conditionId)
: [...current, conditionId];
return { ...p, conditions: next };
});
try {
await storage.updateDoc(encounterPath, { participants: updatedParticipants });
const { patch, log } = combatToggleCondition(encounter, participantId, conditionId);
await storage.updateDoc(encounterPath, patch);
const cond = CONDITIONS.find(c => c.id === conditionId);
const condLabel = cond ? `${cond.label} ${cond.emoji}` : conditionId;
logAction(`${participant.name} ${wasActive ? 'lost' : 'gained'} ${condLabel}`, { encounterName: encounter.name }, {
logAction(log.message.replace(conditionId, condLabel), { encounterName: encounter.name }, {
encounterPath,
updates: { participants: [...participants] },
updates: log.undo,
});
} catch (err) {
console.error("Error updating conditions:", err);
// fall through silently
}
};
@@ -1214,40 +1079,16 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
const handleDrop = async (e, targetId) => {
e.preventDefault();
if (!db || draggedItemId === null || draggedItemId === targetId) {
setDraggedItemId(null);
return;
}
const currentParticipants = [...participants];
const draggedIndex = currentParticipants.findIndex(p => p.id === draggedItemId);
const targetIndex = currentParticipants.findIndex(p => p.id === targetId);
if (draggedIndex === -1 || targetIndex === -1) {
console.error("Dragged or target item not found.");
setDraggedItemId(null);
return;
}
const draggedItem = currentParticipants[draggedIndex];
const targetItem = currentParticipants[targetIndex];
if (draggedItem.initiative !== targetItem.initiative) {
console.log("Drag-drop only allowed for participants with same initiative.");
setDraggedItemId(null);
return;
}
const [removedItem] = currentParticipants.splice(draggedIndex, 1);
currentParticipants.splice(targetIndex, 0, removedItem);
try {
await storage.updateDoc(encounterPath, { participants: currentParticipants });
const { patch } = reorderParticipants(encounter, draggedItemId, targetId);
await storage.updateDoc(encounterPath, patch);
} catch (err) {
console.error("Error reordering participants:", err);
// drag invalid (id not found) — ignore
}
setDraggedItemId(null);
};
@@ -1663,7 +1504,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
const handleToggleHidePlayerHp = async () => {
if (!db) return;
try {
await storage.updateDoc(getPath.activeDisplay(), { hidePlayerHp: !hidePlayerHp });
await storage.setDoc(getPath.activeDisplay(), combatToggleHidePlayerHp(hidePlayerHp).patch, { merge: true });
} catch (err) {
console.error("Error toggling hidePlayerHp:", err);
}
@@ -1672,7 +1513,7 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
const handleToggleHideNpcHp = async () => {
if (!db) return;
try {
await storage.updateDoc(getPath.activeDisplay(), { hideNpcHp: !hideNpcHp });
await storage.setDoc(getPath.activeDisplay(), { hideNpcHp: !hideNpcHp }, { merge: true });
} catch (err) {
console.error("Error toggling hideNpcHp:", err);
}
@@ -1684,75 +1525,30 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
return;
}
const activeParticipants = encounter.participants.filter(p => p.isActive);
if (activeParticipants.length === 0) {
alert("No active participants.");
return;
}
// 1-list model: sort ALL participants by init (active+inactive),
// first active = current. Matches shared.startEncounter.
const sortedParticipants = sortParticipantsByInitiative(encounter.participants, encounter.participants);
const firstActive = sortedParticipants.find(p => p.isActive);
try {
await storage.updateDoc(encounterPath, {
isStarted: true,
isPaused: false,
round: 1,
participants: sortedParticipants,
currentTurnParticipantId: firstActive.id,
turnOrderIds: sortedParticipants.map(p => p.id)
});
await storage.updateDoc(getPath.activeDisplay(), {
activeCampaignId: campaignId,
activeEncounterId: encounter.id
});
logAction(`Combat started: "${encounter.name}" — ${sortedParticipants[0].name}'s turn (Round 1)`, { encounterName: encounter.name }, {
const { patch, log } = startEncounter(encounter);
await storage.updateDoc(encounterPath, patch);
await storage.setDoc(getPath.activeDisplay(), activateDisplay({ campaignId, encounterId: encounter.id }).patch, { merge: true });
logAction(log.message, { encounterName: encounter.name }, {
encounterPath,
updates: {
isStarted: encounter.isStarted ?? false,
isPaused: encounter.isPaused ?? false,
round: encounter.round ?? 0,
currentTurnParticipantId: encounter.currentTurnParticipantId ?? null,
turnOrderIds: [...(encounter.turnOrderIds || [])],
},
updates: log.undo,
});
console.log("Encounter started and set as active display.");
} catch (err) {
console.error("Error starting encounter:", err);
alert("Failed to start encounter. Please try again.");
alert(err.message || "Failed to start encounter. Please try again.");
}
};
const handleTogglePause = async () => {
if (!db || !encounter || !encounter.isStarted) return;
const newPausedState = !encounter.isPaused;
let newTurnOrderIds = encounter.turnOrderIds;
if (!newPausedState && encounter.isPaused) {
// 1-list model: no re-sort on resume. turnOrderIds already mirrors
// participants[] (set at start/add/reorder). Resume = unpause only.
newTurnOrderIds = encounter.turnOrderIds;
}
try {
await storage.updateDoc(encounterPath, {
isPaused: newPausedState,
turnOrderIds: newTurnOrderIds
});
logAction(`Combat ${newPausedState ? 'paused' : 'resumed'}: "${encounter.name}"`, { encounterName: encounter.name }, {
const { patch, log } = togglePause(encounter);
await storage.updateDoc(encounterPath, patch);
logAction(log.message, { encounterName: encounter.name }, {
encounterPath,
updates: {
isPaused: encounter.isPaused ?? false,
turnOrderIds: [...(encounter.turnOrderIds || [])],
},
updates: log.undo,
});
} catch (err) {
console.error("Error toggling pause state:", err);
// fall through silently
}
};
@@ -1760,11 +1556,16 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
if (!db || !encounter.isStarted || encounter.isPaused) return;
if (!encounter.currentTurnParticipantId || !encounter.turnOrderIds || encounter.turnOrderIds.length === 0) return;
const activePsInOrder = encounter.turnOrderIds
.map(id => encounter.participants.find(p => p.id === id && p.isActive))
.filter(Boolean);
if (activePsInOrder.length === 0) {
try {
const { patch, log } = nextTurn(encounter);
await storage.updateDoc(encounterPath, patch);
logAction(log.message, { encounterName: encounter.name }, {
encounterPath,
updates: log.undo,
});
} catch (err) {
// nextTurn throws if no active participants — auto-end combat
if (err.message === 'Encounter not running.' || err.message === 'No active turn.') return;
alert("No active participants left.");
await storage.updateDoc(encounterPath, {
isStarted: false,
@@ -1772,88 +1573,21 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) {
currentTurnParticipantId: null,
round: encounter.round
});
return;
}
let currentIndex = activePsInOrder.findIndex(p => p.id === encounter.currentTurnParticipantId);
let nextRound = encounter.round;
// Current participant was removed; find the next one after their old position in turnOrderIds
if (currentIndex === -1) {
const rawPos = (encounter.turnOrderIds || []).indexOf(encounter.currentTurnParticipantId);
const candidateIds = [...(encounter.turnOrderIds || []).slice(rawPos + 1), ...(encounter.turnOrderIds || []).slice(0, rawPos)];
const nextP = candidateIds.map(id => activePsInOrder.find(p => p.id === id)).find(Boolean);
currentIndex = nextP ? activePsInOrder.findIndex(p => p.id === nextP.id) - 1 : -1;
}
let nextIndex = (currentIndex + 1) % activePsInOrder.length;
let newTurnOrderIds = encounter.turnOrderIds;
if (nextIndex === 0 && currentIndex !== -1) {
nextRound += 1;
// Rebuild turn order by initiative at the start of each new round so that participants
// activated mid-round (appended to the end) slot into proper initiative position next round.
const activePs = encounter.participants.filter(p => p.isActive);
const sorted = sortParticipantsByInitiative(activePs, encounter.participants);
newTurnOrderIds = sorted.map(p => p.id);
}
// When wrapping to a new round the next participant is first in the rebuilt order
const nextParticipant = (nextIndex === 0 && currentIndex !== -1)
? encounter.participants.find(p => p.id === newTurnOrderIds[0])
: activePsInOrder[nextIndex];
if (!nextParticipant) return;
try {
await storage.updateDoc(encounterPath, {
currentTurnParticipantId: nextParticipant.id,
round: nextRound,
turnOrderIds: newTurnOrderIds,
});
logAction(`${nextParticipant.name}'s turn (Round ${nextRound})`, { encounterName: encounter.name }, {
encounterPath,
updates: {
currentTurnParticipantId: encounter.currentTurnParticipantId,
round: encounter.round,
turnOrderIds: [...encounter.turnOrderIds],
},
});
} catch (err) {
console.error("Error advancing turn:", err);
}
};
const confirmEndEncounter = async () => {
if (!db) return;
try {
await storage.updateDoc(encounterPath, {
isStarted: false,
isPaused: false,
currentTurnParticipantId: null,
round: 0,
turnOrderIds: []
});
await storage.updateDoc(getPath.activeDisplay(), {
activeCampaignId: null,
activeEncounterId: null
});
logAction(`Combat ended: "${encounter.name}"`, { encounterName: encounter.name }, {
const { patch, log } = endEncounter(encounter);
await storage.updateDoc(encounterPath, patch);
await storage.setDoc(getPath.activeDisplay(), clearDisplay().patch, { merge: true });
logAction(log.message, { encounterName: encounter.name }, {
encounterPath,
updates: {
isStarted: encounter.isStarted ?? false,
isPaused: encounter.isPaused ?? false,
round: encounter.round ?? 0,
currentTurnParticipantId: encounter.currentTurnParticipantId ?? null,
turnOrderIds: [...(encounter.turnOrderIds || [])],
},
updates: log.undo,
});
console.log("Encounter ended and deactivated from Player Display.");
} catch (err) {
console.error("Error ending encounter:", err);
alert("Failed to end encounter. Please try again.");
}
setShowEndConfirm(false);
@@ -2043,10 +1777,7 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
}
if (activeDisplayInfo && activeDisplayInfo.activeEncounterId === encounterId) {
await storage.updateDoc(getPath.activeDisplay(), {
activeCampaignId: null,
activeEncounterId: null
});
await storage.updateDoc(getPath.activeDisplay(), clearDisplay().patch);
}
} catch (err) {
console.error("Error deleting encounter:", err);
@@ -2065,12 +1796,9 @@ function EncounterManager({ campaignId, initialActiveEncounterId, campaignCharac
const currentActiveEncounter = activeDisplayInfo?.activeEncounterId;
if (currentActiveCampaign === campaignId && currentActiveEncounter === encounterId) {
await storage.updateDoc(getPath.activeDisplay(), {
activeCampaignId: null,
activeEncounterId: null,
});
await storage.setDoc(getPath.activeDisplay(), clearDisplay().patch, { merge: true });
} else {
await storage.updateDoc(getPath.activeDisplay(), {
await storage.setDoc(getPath.activeDisplay(), {
activeCampaignId: campaignId,
activeEncounterId: encounterId,
});
@@ -2311,10 +2039,7 @@ function AdminView({ userId }) {
const activeDisplay = await storage.getDoc(getPath.activeDisplay());
if (activeDisplay && activeDisplay.activeCampaignId === campaignId) {
await storage.updateDoc(getPath.activeDisplay(), {
activeCampaignId: null,
activeEncounterId: null
});
await storage.updateDoc(getPath.activeDisplay(), clearDisplay().patch);
}
} catch (err) {
console.error("Error deleting campaign:", err);
@@ -2548,7 +2273,8 @@ function DisplayView() {
getPath.campaign(activeCampaignId),
(camp) => {
setCampaignBackgroundUrl((camp && camp.playerDisplayBackgroundUrl) || '');
}
},
(err) => console.error("Error fetching campaign background:", err)
);
unsubscribeEncounter = storage.subscribeDoc(
@@ -2561,6 +2287,11 @@ function DisplayView() {
setEncounterError("Active encounter data not found.");
}
setIsLoadingEncounter(false);
},
(err) => {
console.error("Error fetching active encounter details:", err);
setEncounterError("Error loading active encounter data.");
setIsLoadingEncounter(false);
}
);
} else {
+25 -3
View File
@@ -38,11 +38,33 @@ export const MOCK_DB = {
return () => state.subscribers.get(path)?.delete(cb);
},
_notify(path) {
// notify exact doc path subscribers
if (state.subscribers.has(path)) state.subscribers.get(path).forEach(cb => cb());
// notify exact doc path subscribers (wrapped in act for test isolation).
// Set flag true around cb: testing-library asyncWrapper (waitFor) flips it
// false during poll, which makes raw react act() warn 'not configured'.
if (state.subscribers.has(path)) state.subscribers.get(path).forEach(cb => {
try {
const { act } = require('react');
const prev = globalThis.IS_REACT_ACT_ENVIRONMENT;
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
act(() => cb());
globalThis.IS_REACT_ACT_ENVIRONMENT = prev;
} catch {
cb();
}
});
// notify parent collection subscribers
const parent = path.split('/').slice(0, -1).join('/');
if (parent && state.subscribers.has(parent)) state.subscribers.get(parent).forEach(cb => cb());
if (parent && state.subscribers.has(parent)) state.subscribers.get(parent).forEach(cb => {
try {
const { act } = require('react');
const prev = globalThis.IS_REACT_ACT_ENVIRONMENT;
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
act(() => cb());
globalThis.IS_REACT_ACT_ENVIRONMENT = prev;
} catch {
cb();
}
});
},
nextId() { state.counter += 1; return String(state.counter).padStart(3, '0'); },
_state: state,
+29 -2
View File
@@ -19,7 +19,11 @@ export function limit(n) { return { __type: 'limit', n }; }
// writes
export async function setDoc(docRef, data, opts) {
recordCall({ fn: 'setDoc', path: docRef.path, data: clone(data), opts: opts || null });
MOCK_DB.set(docRef.path, clone(data));
if (opts && opts.merge) {
MOCK_DB.merge(docRef.path, clone(data));
} else {
MOCK_DB.set(docRef.path, clone(data));
}
return undefined;
}
export async function updateDoc(docRef, patch) {
@@ -70,6 +74,7 @@ export async function getDocs(collRefOrQuery) {
// realtime — emit from mock DB, capture unsub
export function onSnapshot(refOrQuery, onSuccess, onError) {
const path = refOrQuery.path || (refOrQuery.ref && refOrQuery.ref.path);
const constraints = refOrQuery.constraints || [];
// fire immediately with current state
const emit = () => {
if (refOrQuery.__ref && refOrQuery.path && path.split('/').length % 2 === 0) {
@@ -80,7 +85,8 @@ export function onSnapshot(refOrQuery, onSuccess, onError) {
data: () => data,
});
} else {
const docs = MOCK_DB.collection(path);
let docs = MOCK_DB.collection(path);
docs = applyConstraints(docs, constraints);
onSuccess({ docs: docs.map(d => ({ id: d.id, data: () => d.data })) });
}
};
@@ -90,6 +96,27 @@ export function onSnapshot(refOrQuery, onSuccess, onError) {
return unsub;
}
// Apply Firestore-style query constraints (orderBy desc/asc, limit) to mock docs.
// Mirrors real SDK semantics enough for contract tests. Only orderBy + limit
// supported (App's LOG_QUERY uses exactly these).
function applyConstraints(docs, constraints) {
let out = [...docs];
for (const c of constraints) {
if (c.__type === 'orderBy') {
out.sort((a, b) => {
const av = a.data[c.field];
const bv = b.data[c.field];
if (av === bv) return 0;
const cmp = av > bv ? 1 : -1;
return c.dir === 'desc' ? -cmp : cmp;
});
} else if (c.__type === 'limit') {
out = out.slice(0, c.n);
}
}
return out;
}
function clone(v) {
if (v === null || v === undefined) return v;
return JSON.parse(JSON.stringify(v));
+21
View File
@@ -2,6 +2,27 @@
import '@testing-library/jest-dom';
import { resetMockDb } from './__mocks__/firebase/_mock-db';
// RTL v14: tell React this is an act environment. Without it every
// async update warns "current testing environment is not configured to
// support act(...)". RTL reads getGlobalThis(), so set on globalThis.
// Must be set before any component renders.
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
// WARNING = FAILURE. Fail test on any console.error/warn (React act warnings,
// deprecations, prop errors). App code's own error logs allowed only inside
// try/catch failure paths — those tests should assert the error was handled,
// not silently log it. Override the spies to throw.
const originalError = console.error;
const originalWarn = console.warn;
console.error = (...args) => {
originalError(...args);
throw new Error(`console.error in test: ${args.map(String).join(' ').slice(0, 500)}`);
};
console.warn = (...args) => {
originalWarn(...args);
throw new Error(`console.warn in test: ${args.map(String).join(' ').slice(0, 500)}`);
};
// polyfill crypto.randomUUID for jsdom (used by generateId in App.js).
if (!global.crypto) global.crypto = {};
if (!global.crypto.randomUUID) {
+83 -32
View File
@@ -27,10 +27,10 @@ function runStorageContract(name, factory) {
afterEach(async () => { if (storage && storage.dispose) await storage.dispose(); });
describe('getDoc / setDoc', () => {
test('setDoc then getDoc returns the doc', async () => {
test('setDoc then getDoc returns the doc (with id)', async () => {
await storage.setDoc('campaigns/a', { name: 'Alpha' });
const doc = await storage.getDoc('campaigns/a');
expect(doc).toEqual({ name: 'Alpha' });
expect(doc).toEqual({ id: 'a', name: 'Alpha' });
});
test('getDoc on missing path returns null', async () => {
@@ -42,7 +42,15 @@ function runStorageContract(name, factory) {
await storage.setDoc('campaigns/a', { name: 'Alpha', players: [] });
await storage.setDoc('campaigns/a', { name: 'Beta' });
const doc = await storage.getDoc('campaigns/a');
expect(doc).toEqual({ name: 'Beta' });
expect(doc).toEqual({ id: 'a', name: 'Beta' });
});
// main L1624: setDoc(path, data, {merge:true}) — merge flag.
test('setDoc with {merge:true} merges into existing doc', async () => {
await storage.setDoc('campaigns/a', { name: 'Alpha', players: [] });
await storage.setDoc('campaigns/a', { players: [1] }, { merge: true });
const doc = await storage.getDoc('campaigns/a');
expect(doc).toEqual({ id: 'a', name: 'Alpha', players: [1] });
});
});
@@ -51,13 +59,13 @@ function runStorageContract(name, factory) {
await storage.setDoc('campaigns/a', { name: 'Alpha', players: [1] });
await storage.updateDoc('campaigns/a', { players: [1, 2] });
const doc = await storage.getDoc('campaigns/a');
expect(doc).toEqual({ name: 'Alpha', players: [1, 2] });
expect(doc).toEqual({ id: 'a', name: 'Alpha', players: [1, 2] });
});
test('updateDoc on missing doc creates it', async () => {
await storage.updateDoc('campaigns/a', { name: 'Alpha' });
const doc = await storage.getDoc('campaigns/a');
expect(doc).toEqual({ name: 'Alpha' });
expect(doc).toEqual({ id: 'a', name: 'Alpha' });
});
});
@@ -79,7 +87,7 @@ function runStorageContract(name, factory) {
expect(id).toBeTruthy();
expect(path).toBe(`campaigns/a/encounters/${id}`);
const doc = await storage.getDoc(path);
expect(doc).toEqual({ name: 'E1' });
expect(doc).toEqual({ id, name: 'E1' });
});
test('two addDocs produce distinct ids', async () => {
@@ -91,33 +99,15 @@ function runStorageContract(name, factory) {
describe('firebase-prefixed path identity', () => {
// App passes firebase-prefixed paths (artifacts/{APP_ID}/public/data/...).
// Adapter must normalize internally so write+read at prefixed path round-trips
// AND collection queries at bare canonical path find prefixed-written docs.
// Catches replay-script bug (wrote prefixed, adapter reads bare, missed).
// main prod truth: ALWAYS prefixed. Write+read same prefixed round-trips.
// Cross bare<->prefixed lookup is NOT required by main (App never does it).
// Kept as same-prefix roundtrip only — matches prod.
const PREFIX = 'artifacts/test-app/public/data';
test('setDoc prefixed then getCollection bare finds it', async () => {
await storage.setDoc(`${PREFIX}/campaigns/c1`, { name: 'P1' });
const docs = await storage.getCollection('campaigns');
expect(docs.some(d => d.name === 'P1')).toBe(true);
});
test('setDoc prefixed then getDoc same prefixed path returns it', async () => {
test('setDoc prefixed then getDoc same prefixed path returns it (id)', async () => {
await storage.setDoc(`${PREFIX}/campaigns/c2`, { name: 'P2' });
const doc = await storage.getDoc(`${PREFIX}/campaigns/c2`);
expect(doc).toEqual({ name: 'P2' });
});
test('setDoc prefixed then getDoc bare path returns it', async () => {
await storage.setDoc(`${PREFIX}/campaigns/c3`, { name: 'P3' });
const doc = await storage.getDoc('campaigns/c3');
expect(doc).toEqual({ name: 'P3' });
});
test('setDoc bare then getCollection prefixed finds it', async () => {
await storage.setDoc('campaigns/c4', { name: 'P4' });
const docs = await storage.getCollection(`${PREFIX}/campaigns`);
expect(docs.some(d => d.name === 'P4')).toBe(true);
expect(doc).toEqual({ id: 'c2', name: 'P2' });
});
});
@@ -165,7 +155,29 @@ function runStorageContract(name, factory) {
{ type: 'delete', path: 'campaigns/a' },
]);
expect(await storage.getDoc('campaigns/a')).toBeNull();
expect(await storage.getDoc('campaigns/b')).toEqual({ name: 'B' });
expect(await storage.getDoc('campaigns/b')).toEqual({ id: 'b', name: 'B' });
});
// set-only batch (not used in main currently, but interface allows).
test('applies set-only batch', async () => {
await storage.batchWrite([
{ type: 'set', path: 'campaigns/a', data: { name: 'A' } },
{ type: 'set', path: 'campaigns/b', data: { name: 'B' } },
]);
expect(await storage.getDoc('campaigns/a')).toEqual({ id: 'a', name: 'A' });
expect(await storage.getDoc('campaigns/b')).toEqual({ id: 'b', name: 'B' });
});
// update-only batch (interface allows).
test('applies update-only batch', async () => {
await storage.setDoc('campaigns/a', { name: 'A', hp: 10 });
await storage.setDoc('campaigns/b', { name: 'B', hp: 5 });
await storage.batchWrite([
{ type: 'update', path: 'campaigns/a', data: { hp: 8 } },
{ type: 'update', path: 'campaigns/b', data: { hp: 2 } },
]);
expect(await storage.getDoc('campaigns/a')).toEqual({ id: 'a', name: 'A', hp: 8 });
expect(await storage.getDoc('campaigns/b')).toEqual({ id: 'b', name: 'B', hp: 2 });
});
});
@@ -176,7 +188,7 @@ function runStorageContract(name, factory) {
storage.subscribeDoc('campaigns/a', (doc) => calls.push(doc));
await flush();
expect(calls).toHaveLength(1);
expect(calls[0]).toEqual({ name: 'Alpha' });
expect(calls[0]).toEqual({ id: 'a', name: 'Alpha' });
});
test('fires cb on subsequent change', async () => {
@@ -186,7 +198,7 @@ function runStorageContract(name, factory) {
await storage.setDoc('campaigns/a', { name: 'Alpha' });
await flush();
const last = calls[calls.length - 1];
expect(last).toEqual({ name: 'Alpha' });
expect(last).toEqual({ id: 'a', name: 'Alpha' });
});
test('unsubscribe stops callbacks', async () => {
@@ -220,6 +232,45 @@ function runStorageContract(name, factory) {
expect(last).toHaveLength(1);
});
});
// queryConstraints: orderBy + limit. App's combat log uses
// [orderBy('timestamp','desc'), limit(500)] — newest 500 entries.
// Adapter MUST honor these. Constraint shape = neutral {__type} objects
// (what firebase mock produces; what App passes via shared builders).
describe('subscribeCollection queryConstraints', () => {
const orderByC = (field, dir) => ({ __type: 'orderBy', field, dir });
const limitC = (n) => ({ __type: 'limit', n });
beforeEach(async () => {
// seed 5 log docs, timestamps out of order
await storage.setDoc('logs/l1', { msg: 'one', timestamp: 1 });
await storage.setDoc('logs/l2', { msg: 'two', timestamp: 3 });
await storage.setDoc('logs/l3', { msg: 'three', timestamp: 5 });
await storage.setDoc('logs/l4', { msg: 'four', timestamp: 2 });
await storage.setDoc('logs/l5', { msg: 'five', timestamp: 4 });
});
test('orderBy desc sorts newest-first', async () => {
const result = await new Promise((resolve) => {
storage.subscribeCollection('logs', resolve, [orderByC('timestamp', 'desc')]);
});
expect(result.map(d => d.msg)).toEqual(['three', 'five', 'two', 'four', 'one']);
});
test('limit returns only first N after ordering', async () => {
const result = await new Promise((resolve) => {
storage.subscribeCollection('logs', resolve, [orderByC('timestamp', 'desc'), limitC(2)]);
});
expect(result.map(d => d.msg)).toEqual(['three', 'five']);
});
test('no constraints returns all (insertion/id order)', async () => {
const result = await new Promise((resolve) => {
storage.subscribeCollection('logs', resolve, []);
});
expect(result).toHaveLength(5);
});
});
});
}
+23 -11
View File
@@ -1,10 +1,8 @@
// firebase.js — storage adapter wrapping Firebase SDK. Default impl (upstream-unchanged).
// Matches interface of memory.js / ws.js so App.js calls stay identical.
//
// NOTE: App.js currently imports SDK directly. This adapter extracted verbatim.
// Two-phase refactor:
// Phase A (now): adapter exists, wraps SDK. Hooks/writes can switch incrementally.
// Phase B (later): App.js imports storage factory, drops direct SDK imports.
// App.js imports SDK via this module (doc, setDoc, etc re-exported) for both
// the adapter (createFirebaseStorage) and direct SDK calls. ONE import path.
'use strict';
@@ -120,21 +118,34 @@ export function createFirebaseStorage() {
},
// Subscribe = onSnapshot. cb fires immediately + on change. Returns unsubscribe.
subscribeDoc(path, cb) {
subscribeDoc(path, cb, errCb) {
recordAdapterCall({ fn: 'subscribeDoc', path });
return onSnapshot(doc(db, path), (snap) => {
cb(snap.exists() ? { id: snap.id, ...snap.data() } : null);
}, (err) => console.error(`subscribeDoc ${path}:`, err));
}, (err) => {
console.error(`subscribeDoc ${path}:`, err);
if (typeof errCb === 'function') errCb(err);
});
},
subscribeCollection(collectionPath, cb, queryConstraints = []) {
subscribeCollection(collectionPath, cb, queryConstraints = [], errCb) {
recordAdapterCall({ fn: 'subscribeCollection', path: collectionPath });
const q = queryConstraints.length > 0
? query(collection(db, collectionPath), ...queryConstraints)
// queryConstraints = neutral {__type} builders (from index.js).
// Translate to SDK orderBy/limit.
const sdkConstraints = queryConstraints.map(c => {
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);
return onSnapshot(q, (snap) => {
cb(snap.docs.map(d => ({ id: d.id, ...d.data() })));
}, (err) => console.error(`subscribeCollection ${collectionPath}:`, err));
}, (err) => {
console.error(`subscribeCollection ${collectionPath}:`, err);
if (typeof errCb === 'function') errCb(err);
});
},
dispose() { /* SDK managed; no-op */ },
@@ -142,7 +153,8 @@ export function createFirebaseStorage() {
}
// Re-export SDK pieces App.js uses directly (until full refactor).
// orderBy/limit NOT re-exported: App uses neutral builders from index.js.
export {
doc, setDoc, updateDoc, deleteDoc, addDoc, collection, onSnapshot,
query, orderBy, limit, writeBatch,
query, writeBatch,
};
+16 -9
View File
@@ -1,5 +1,6 @@
// src/storage/index.js — storage factory + SDK re-exports.
// STORAGE=firebase (default): adapter wraps SDK. STORAGE=ws: backend.
// STORAGE=firebase (default): adapter wraps SDK. STORAGE=server: backend.
// orderBy/limit below = NEUTRAL builders (not SDK passthrough).
// App.js imports getStorage() for subscribe; still imports SDK pieces for writes (per-group refactor pending).
import { initializeApp } from 'firebase/app';
@@ -8,11 +9,10 @@ import {
} from 'firebase/auth';
import {
getFirestore, doc, setDoc, getDoc, getDocs, addDoc, collection,
onSnapshot, updateDoc, deleteDoc, query, orderBy, limit, writeBatch,
onSnapshot, updateDoc, deleteDoc, query, writeBatch,
} from 'firebase/firestore';
import { initFirebase, createFirebaseStorage } from './firebase';
import { createWsStorage } from './ws';
import { createMemoryStorage } from './memory';
import { createServerStorage } from './server';
let storageInstance = null;
@@ -24,13 +24,13 @@ export function getStorage() {
const ok = initFirebase();
if (!ok) throw new Error('Firebase config missing. Check REACT_APP_FIREBASE_* env.');
storageInstance = createFirebaseStorage();
} else if (mode === 'ws') {
storageInstance = createWsStorage({
} else if (mode === 'server') {
storageInstance = createServerStorage({
baseUrl: process.env.REACT_APP_BACKEND_URL || '',
wsUrl: process.env.REACT_APP_BACKEND_WS || '',
realtimeUrl: process.env.REACT_APP_BACKEND_REALTIME_URL || '',
});
} else {
storageInstance = createMemoryStorage();
throw new Error(`Unknown REACT_APP_STORAGE mode: ${mode}. Use 'firebase' or 'server'.`);
}
return storageInstance;
}
@@ -39,9 +39,16 @@ export function getStorageMode() {
return process.env.REACT_APP_STORAGE || 'firebase';
}
// Neutral query-constraint builders. App builds constraints with these (not
// raw SDK), so both adapters read the same shape. firebase adapter translates
// neutral -> SDK; server adapter applies client-side. Combat log uses these:
// [orderBy('timestamp','desc'), limit(500)]
export function orderBy(field, dir) { return { __type: 'orderBy', field, dir }; }
export function limit(n) { return { __type: 'limit', n }; }
export {
initializeApp,
getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken,
getFirestore, doc, setDoc, getDoc, getDocs, addDoc, collection,
onSnapshot, updateDoc, deleteDoc, query, orderBy, limit, writeBatch,
onSnapshot, updateDoc, deleteDoc, query, writeBatch,
};
-140
View File
@@ -1,140 +0,0 @@
// memory.js — in-process storage impl. Test seed.
// Map<docPath, data>. EventEmitter for subscribe.
// Mirrors firebase semantics: setDoc=replace, updateDoc=shallow merge, addDoc=auto-id.
'use strict';
import { EventEmitter } from 'events';
function createMemoryStorage() {
const docs = new Map(); // path -> data obj
const bus = new EventEmitter();
bus.setMaxListeners(1000);
// Firebase-prefixed paths (artifacts/{APP_ID}/public/data/...) normalized to
// bare canonical. Matches ws.js norm() so all impls share path identity.
function norm(p) {
if (!p) return p;
return p.replace(/^[\s\S]*\/public\/data\//, '');
}
// ---- path helpers ----
// collection path = path with even number of segments OR known collection.
// doc path = odd segments (coll/doc, coll/doc/subcoll/subdoc).
// getCollection(path) returns all docs whose path === path/id for any single id segment.
function isCollectionPath(p) {
return p.split('/').length % 2 === 1;
}
function emitDoc(path, data) { bus.emit('doc:' + path, data); }
function emitCollection(collPath) {
const children = collectionDocs(collPath);
bus.emit('coll:' + collPath, children);
}
function collectionDocs(collPath) {
const out = [];
const segLen = collPath.split('/').length + 1;
for (const [p, data] of docs) {
const segs = p.split('/');
if (segs.length !== segLen) continue;
const parent = segs.slice(0, -1).join('/');
if (parent === collPath) out.push(data);
}
return out;
}
function genId() {
return (typeof crypto !== 'undefined' && crypto.randomUUID)
? crypto.randomUUID()
: `id_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
}
const storage = {
async getDoc(rawPath) {
const path = norm(rawPath);
return docs.has(path) ? deepClone(docs.get(path)) : null;
},
async setDoc(rawPath, data) {
const path = norm(rawPath);
docs.set(path, deepClone(data));
emitDoc(path, deepClone(data));
const segs = path.split('/');
if (segs.length >= 2) emitCollection(segs.slice(0, -1).join('/'));
},
async updateDoc(rawPath, patch) {
const path = norm(rawPath);
const existing = docs.has(path) ? docs.get(path) : {};
const merged = { ...existing, ...patch };
docs.set(path, merged);
emitDoc(path, deepClone(merged));
const segs = path.split('/');
if (segs.length >= 2) emitCollection(segs.slice(0, -1).join('/'));
},
async deleteDoc(rawPath) {
const path = norm(rawPath);
docs.delete(path);
emitDoc(path, null);
const segs = path.split('/');
if (segs.length >= 2) emitCollection(segs.slice(0, -1).join('/'));
},
async addDoc(rawCollectionPath, data) {
const collectionPath = norm(rawCollectionPath);
const id = genId();
const path = `${collectionPath}/${id}`;
docs.set(path, deepClone(data));
emitDoc(path, deepClone(data));
emitCollection(collectionPath);
return { id, path };
},
async getCollection(rawCollPath) {
const collPath = norm(rawCollPath);
return collectionDocs(collPath).map(deepClone);
},
async batchWrite(ops) {
for (const op of ops) {
const mop = { ...op, path: norm(op.path) };
if (mop.type === 'set') await storage.setDoc(mop.path, mop.data);
else if (mop.type === 'delete') await storage.deleteDoc(mop.path);
else if (mop.type === 'update') await storage.updateDoc(mop.path, mop.data);
}
},
subscribeDoc(rawPath, cb) {
const path = norm(rawPath);
const cur = docs.has(path) ? deepClone(docs.get(path)) : null;
Promise.resolve().then(() => cb(cur));
const handler = (data) => cb(data);
bus.on('doc:' + path, handler);
return () => bus.off('doc:' + path, handler);
},
subscribeCollection(rawCollPath, cb) {
const collPath = norm(rawCollPath);
Promise.resolve().then(() => cb(collectionDocs(collPath).map(deepClone)));
const handler = (docs) => cb(docs);
bus.on('coll:' + collPath, handler);
return () => bus.off('coll:' + collPath, handler);
},
dispose() { bus.removeAllListeners(); docs.clear(); },
// test/debug
_docs: docs,
};
return storage;
}
function deepClone(v) {
if (v === null || v === undefined) return v;
return JSON.parse(JSON.stringify(v));
}
export { createMemoryStorage };
+68 -16
View File
@@ -11,13 +11,13 @@ if (typeof WebSocket !== 'undefined') {
WebSocketImpl = WebSocket;
}
function createWsStorage({ baseUrl, wsUrl } = {}) {
function createServerStorage({ baseUrl, realtimeUrl } = {}) {
// Same-origin by default: empty baseUrl = relative fetch (Caddy/proxy).
// Fallback to localhost for bare `npm start` dev without proxy.
const API = (baseUrl || (typeof window !== 'undefined' && window.location ? '' : 'http://127.0.0.1:4001')).replace(/\/$/, '');
let WS;
if (wsUrl) {
WS = wsUrl;
if (realtimeUrl) {
WS = realtimeUrl;
} else if (typeof window !== 'undefined' && window.location) {
// derive from current origin (http→ws, https→wss), same host/port.
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
@@ -33,8 +33,39 @@ function createWsStorage({ baseUrl, wsUrl } = {}) {
return p.replace(/^[\s\S]*\/public\/data\//, '');
}
// Inject id (last path segment) into doc — matches main firebase truth:
// { id: docSnap.id, ...snap.data() }
// Backend stores docs WITHOUT id; client adds it so all adapters share shape.
function withId(rawPath, data) {
if (data === null || data === undefined) return data;
const id = norm(rawPath).split('/').pop();
return { id, ...data };
}
// Apply neutral {__type} query constraints client-side. Backend returns all
// docs; adapter sorts/limits. Mirrors firebase mock applyConstraints.
function applyConstraints(docs, constraints) {
let out = [...docs];
for (const c of constraints || []) {
if (!c || !c.__type) continue;
if (c.__type === 'orderBy') {
out.sort((a, b) => {
const av = a[c.field];
const bv = b[c.field];
if (av === bv) return 0;
const cmp = av > bv ? 1 : -1;
return c.dir === 'desc' ? -cmp : cmp;
});
} else if (c.__type === 'limit') {
out = out.slice(0, c.n);
}
}
return out;
}
const docSubs = new Map(); // path -> Set<cb>
const collSubs = new Map(); // collPath -> Set<cb>
const collConstraints = new Map(); // collPath -> constraints[] (per collection)
let ws = null;
let wsReady = null;
@@ -121,11 +152,12 @@ function createWsStorage({ baseUrl, wsUrl } = {}) {
const doc = await storage.getDoc(c.path);
docCbs.forEach(cb => cb(doc));
}
// collection subscribers at parent path (doc belongs to this collection)
// collection subscribers at parent path (apply their stored constraints)
if (c.parent) {
const collCbs = collSubs.get(c.parent);
if (collCbs) {
const docs = await storage.getCollection(c.parent);
const constraints = collConstraints.get(c.parent) || [];
const docs = applyConstraints(await storage.getCollection(c.parent), constraints);
collCbs.forEach(cb => cb(docs));
}
}
@@ -154,12 +186,19 @@ function createWsStorage({ baseUrl, wsUrl } = {}) {
async getDoc(rawPath) {
const p = norm(rawPath);
const res = await api('GET', '/api/doc', { path: p });
return res && res.data !== undefined ? res.data : null;
const data = res && res.data !== undefined ? res.data : null;
return withId(rawPath, data);
},
async setDoc(rawPath, data) {
async setDoc(rawPath, data, opts = {}) {
const p = norm(rawPath);
await api('PUT', '/api/doc', null, { path: p, data });
// merge flag -> PATCH (shallow merge, create-on-miss). Matches firebase
// setDoc(path, data, {merge:true}) semantics.
if (opts.merge) {
await api('PATCH', '/api/doc', null, { path: p, patch: data });
} else {
await api('PUT', '/api/doc', null, { path: p, data });
}
},
async updateDoc(rawPath, patch) {
@@ -180,7 +219,16 @@ function createWsStorage({ baseUrl, wsUrl } = {}) {
async getCollection(rawCollPath) {
const p = norm(rawCollPath);
return await api('GET', '/api/collection', { path: p });
const docs = await api('GET', '/api/collection', { path: p });
// Backend returns array of { id, data } OR bare data[]; normalize to
// { id, ...data } (firebase truth).
if (!Array.isArray(docs)) return [];
return docs.map(d => {
if (d && typeof d === 'object' && 'id' in d && 'data' in d) {
return { id: d.id, ...d.data };
}
return { ...d };
});
},
async batchWrite(ops) {
@@ -188,9 +236,9 @@ function createWsStorage({ baseUrl, wsUrl } = {}) {
await api('POST', '/api/batch', null, { ops: normOps });
},
subscribeDoc(rawPath, cb) {
subscribeDoc(rawPath, cb, errCb) {
const p = norm(rawPath);
// Initial value via REST (independent of WS connect).
// Initial value via REST (independent of WS connect). getDoc injects id.
storage.getDoc(p).then(cb).catch(() => {});
// WS only for subsequent change notifications.
ensureWs().then(() => {
@@ -201,10 +249,14 @@ function createWsStorage({ baseUrl, wsUrl } = {}) {
return () => { docSubs.get(p)?.delete(cb); };
},
subscribeCollection(rawCollPath, cb) {
subscribeCollection(rawCollPath, cb, queryConstraints = [], errCb) {
const p = norm(rawCollPath);
// Initial value via REST (independent of WS connect).
storage.getCollection(p).then(cb).catch(() => {});
collConstraints.set(p, queryConstraints || []);
// Initial value via REST (independent of WS connect). Apply constraints
// client-side — backend returns all docs, adapter sorts/limits.
storage.getCollection(p)
.then(docs => cb(applyConstraints(docs, queryConstraints || [])))
.catch(() => {});
// WS only for subsequent change notifications.
ensureWs().then(() => {
ws.send(JSON.stringify({ type: 'subscribe', kind: 'collection', path: p }));
@@ -218,7 +270,7 @@ function createWsStorage({ baseUrl, wsUrl } = {}) {
disposed = true;
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
if (ws) ws.close();
docSubs.clear(); collSubs.clear();
docSubs.clear(); collSubs.clear(); collConstraints.clear();
if (typeof cb === 'function') cb();
},
@@ -234,4 +286,4 @@ function createWsStorage({ baseUrl, wsUrl } = {}) {
return storage;
}
export { createWsStorage };
export { createServerStorage };
+9 -7
View File
@@ -41,7 +41,7 @@ describe('Combat -> Firebase', () => {
test('startEncounter: also sets activeDisplay to this encounter', async () => {
await setupWithMonsters();
await startCombatViaUI();
const adCalls = findCallActiveDisplay('updateDoc');
const adCalls = findCallActiveDisplay('setDoc');
const last = adCalls[adCalls.length - 1];
expect(last.data.activeCampaignId).toBeTruthy();
expect(last.data.activeEncounterId).toBeTruthy();
@@ -111,26 +111,28 @@ describe('Combat -> Firebase', () => {
fireEvent.click(screen.getByRole('button', { name: /End Combat/i }));
fireEvent.click(await screen.findByRole('button', { name: /Confirm/i }));
await waitFor(() => {
const adCalls = findCallActiveDisplay('updateDoc');
const adCalls = findCallActiveDisplay('setDoc');
const last = adCalls[adCalls.length - 1];
return last && last.data.activeCampaignId === null;
});
const adCalls = findCallActiveDisplay('updateDoc');
const adCalls = findCallActiveDisplay('setDoc');
const last = adCalls[adCalls.length - 1];
expect(last.data).toMatchObject({ activeCampaignId: null, activeEncounterId: null });
});
test('toggleHidePlayerHp: updateDoc patch on activeDisplay/status', async () => {
test('toggleHidePlayerHp: setDoc{merge} patch on activeDisplay/status', async () => {
await setupWithMonsters();
await startCombatViaUI();
const switchBtn = screen.getByRole('switch');
// Two switches now (Hide player HP + Hide NPC/monster HP). Scope to player one.
const playerHpLabel = screen.getByText('Hide player HP');
const switchBtn = playerHpLabel.parentElement.querySelector('[role="switch"]');
fireEvent.click(switchBtn);
await waitFor(() => {
const adCalls = findCallActiveDisplay('updateDoc');
const adCalls = findCallActiveDisplay('setDoc');
const last = adCalls[adCalls.length - 1];
return last && 'hidePlayerHp' in last.data;
});
const adCalls = findCallActiveDisplay('updateDoc');
const adCalls = findCallActiveDisplay('setDoc');
const last = adCalls[adCalls.length - 1];
expect(last.data).toHaveProperty('hidePlayerHp');
});
+256 -262
View File
@@ -1,23 +1,84 @@
// Combat.scenario.test.js
// Full combat scenario: campaign -> encounter -> participants -> 100 rounds of
// damage/heal/conditions/toggle-active/edit/death-save/pause/resume/add/remove.
// Drives the SAME UI buttons a DM clicks. Failing assertions do NOT abort the run:
// each phase wraps in try/catch, failures collected, final expect reports all.
// Full combat scenario driven through shared/turn.js directly --- NO React.
//
// Purpose: exercise as much of the supported feature surface as possible in one
// long combat, surfacing behavioral bugs characterization tests miss.
// Does 100 ROUNDS (not turns). A round = one full pass through initiative
// (every active participant acts once); round counter increments at wrap.
// See docs/GLOSSARY.md. Previous version lied: called nextTurn 100× (~100
// turns, ~12 rounds). Now loops by actual round-wrap count.
//
// Exercises ALL combat paths deterministically (less random than replay):
// startEncounter, nextTurn, togglePause, addParticipant, addParticipants,
// updateParticipant, removeParticipant, toggleParticipantActive,
// applyHpChange (damage/heal), deathSave (incl. 3-success → isDying),
// toggleCondition, reorderParticipants (drag same-init tie), endEncounter,
// activateDisplay, clearDisplay, toggleHidePlayerHp.
//
// Failing assertions do NOT abort the run: each phase wrapped in try/catch,
// failures collected, final expect reports all.
import React from 'react';
import { screen, fireEvent, waitFor, within } from '@testing-library/react';
import '@testing-library/jest-dom';
import App from '../App';
import {
renderApp, createCampaignViaUI, selectCampaignByName,
createEncounterViaUI, selectEncounterByName, addMonsterViaUI, setupReady,
} from './testHelpers';
import { getCalls, MOCK_DB } from '../__mocks__/firebase/_mock-db';
const {
makeParticipant,
buildCharacterParticipant,
buildMonsterParticipant,
startEncounter,
nextTurn,
togglePause,
addParticipant,
addParticipants,
updateParticipant,
removeParticipant,
toggleParticipantActive,
applyHpChange,
deathSave,
toggleCondition,
reorderParticipants,
endEncounter,
activateDisplay,
clearDisplay,
toggleHidePlayerHp,
} = require('../../shared');
// ---------- scenario helpers (UI only, same buttons as human) ----------
// aliases for combat funcs that clash with local helper names
const {
applyHpChange: combatApplyHpChange,
toggleParticipantActive: combatToggleActive,
toggleCondition: combatToggleCondition,
deathSave: combatDeathSave,
} = require('../../shared');
// ---------- scenario state (mirrors two firestore docs) ----------
const ROUNDS = 100;
// encounter doc
let enc = {
name: 'BigBoss',
participants: [],
isStarted: false,
isPaused: false,
round: 0,
currentTurnParticipantId: null,
turnOrderIds: [],
};
// activeDisplay/status doc
let display = {
activeCampaignId: null,
activeEncounterId: null,
hidePlayerHp: true,
hideNpcHp: false,
};
const CAMPAIGN_ID = 'camp-1';
const ENCOUNTER_ID = 'enc-1';
const roster = [];
function applyEnc(patch) {
if (!patch) return;
for (const [k, v] of Object.entries(patch)) enc[k] = v;
}
function applyDisplay(patch) {
if (!patch) return;
for (const [k, v] of Object.entries(patch)) display[k] = v;
}
const RESULTS = [];
function record(phase, fn) {
@@ -29,205 +90,93 @@ async function recordAsync(phase, fn) {
catch (err) { RESULTS.push({ phase, ok: false, err: err.message }); }
}
function getParticipantForm() {
const heading = screen.getByText('Add Participants');
let node = heading;
for (let i = 0; i < 6; i++) {
node = node.parentElement;
if (!node) break;
if (node.querySelector('form')) return within(node);
// ---------- helpers (shared, no React) ----------
const alive = (name) => enc.participants.find(p => p.name === name && p.currentHp > 0);
const any = (name) => enc.participants.find(p => p.name === name);
const idOf = (name) => { const p = any(name); return p ? p.id : null; };
function addCharacterViaUI(name, maxHp, initMod) {
roster.push({ id: `char-${name}`, name, defaultMaxHp: maxHp, defaultInitMod: initMod });
}
function addMonsterParticipant(name, maxHp, initMod, isNpc = false) {
const { participant } = buildMonsterParticipant({ name, maxHp, initMod, isNpc });
applyEnc(addParticipant(enc, participant).patch);
}
function addCharacterParticipant(charName) {
const character = roster.find(c => c.name === charName);
if (!character) throw new Error(`char not found: ${charName}`);
if (enc.participants.some(p => p.type === 'character' && p.originalCharacterId === character.id)) {
throw new Error(`${charName} already in encounter`);
}
return within(heading.parentElement);
const { participant } = buildCharacterParticipant(character);
applyEnc(addParticipant(enc, participant).patch);
}
// Find a participant's encounter <li> row by name. Scoped to the encounter
// participant list (NOT the CharacterManager roster, which also shows names).
// Encounter participant rows render an 'Init:' label; roster rows do not.
function getParticipantRow(name) {
const lis = document.querySelectorAll('li');
for (const li of lis) {
const txt = li.textContent || '';
if (txt.includes('Init:') && txt.includes(name)) {
return within(li);
}
}
throw new Error(`encounter participant row not found: ${name}`);
function addAllCharacters() {
const toAdd = roster
.filter(c => !enc.participants.some(p => p.type === 'character' && p.originalCharacterId === c.id))
.map(c => buildCharacterParticipant(c).participant);
applyEnc(addParticipants(enc, toAdd).patch);
}
// Character roster (CharacterManager). Assumes campaign selected.
async function addCharacterViaUI(name, maxHp, initMod) {
fireEvent.change(document.getElementById('characterName'), { target: { value: name } });
fireEvent.change(document.getElementById('defaultMaxHp'), { target: { value: String(maxHp) } });
fireEvent.change(document.getElementById('defaultInitMod'), { target: { value: String(initMod) } });
fireEvent.click(screen.getByRole('button', { name: /^Add Character$/i }));
await waitFor(() => {
const call = getCalls().find(c => c.fn === 'updateDoc' && c.path.includes('/campaigns/') &&
Array.isArray(c.data.players) && c.data.players.some(p => p.name === name));
if (!call) throw new Error('char not persisted');
});
function startCombat() {
applyEnc(startEncounter(enc).patch);
applyDisplay(activateDisplay({ campaignId: CAMPAIGN_ID, encounterId: ENCOUNTER_ID }).patch);
}
function setParticipantType(type) {
// The Type select is inside the Add Participants form.
const form = getParticipantForm();
const selects = form.getAllByRole('combobox');
// first combobox in the participant form is Type
fireEvent.change(selects[0], { target: { value: type } });
}
async function addMonsterParticipant(name, maxHp, initMod, isNpc = false) {
const form = getParticipantForm();
setParticipantType('monster');
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(/Max HP/i), { target: { value: String(maxHp) } });
if (isNpc) {
const npcCheck = form.getByRole('checkbox', { name: /NPC/i });
if (!npcCheck.checked) fireEvent.click(npcCheck);
}
fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
await waitFor(() => {
const last = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/')).slice(-1)[0];
if (!last || !last.data.participants?.some(p => p.name === name)) throw new Error('monster not added');
});
}
async function addCharacterParticipant(charName) {
const form = getParticipantForm();
setParticipantType('character');
// character select is the 2nd combobox in the form after Type
const charSelect = form.getAllByRole('combobox')[1];
// find option whose text includes the char name
const opt = [...charSelect.querySelectorAll('option')].find(o => o.textContent.includes(charName));
if (!opt) throw new Error(`char option not found: ${charName}`);
fireEvent.change(charSelect, { target: { value: opt.value } });
fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
await waitFor(() => {
const last = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/')).slice(-1)[0];
if (!last || !last.data.participants?.some(p => p.name === charName)) throw new Error('char not added');
});
}
async function addAllCharacters() {
fireEvent.click(screen.getByRole('button', { name: /Add All/i }));
await waitFor(() => {
const last = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/')).slice(-1)[0];
if (!last) throw new Error('add all no-op');
});
function endCombat() {
applyEnc(endEncounter(enc).patch);
applyDisplay(clearDisplay().patch);
}
function nextTurnAction() { applyEnc(nextTurn(enc).patch); }
function pauseCombat() { applyEnc(togglePause(enc).patch); if (!enc.isPaused) throw new Error('not paused'); }
function resumeCombat() { applyEnc(togglePause(enc).patch); if (enc.isPaused) throw new Error('not resumed'); }
function applyDamage(name, amount) {
const row = getParticipantRow(name);
const dmgBtn = row.queryByTitle('Damage');
if (!dmgBtn) {
// participant dead (Damage button hidden when currentHp===0). Expected game
// state over a long fight; not a bug. Skip silently.
return;
}
fireEvent.change(row.getByLabelText(`HP change for ${name}`), { target: { value: String(amount) } });
fireEvent.click(dmgBtn);
const p = any(name);
if (!p || p.currentHp <= 0) return; // dead = skip (button hidden in UI)
applyEnc(combatApplyHpChange(enc, p.id, 'damage', amount).patch);
}
function applyHeal(name, amount) {
const row = getParticipantRow(name);
const healBtn = row.queryByTitle('Heal / Revive') || row.queryByTitle('Heal');
if (!healBtn) throw new Error(`${name} has no Heal button`);
fireEvent.change(row.getByLabelText(`HP change for ${name}`), { target: { value: String(amount) } });
fireEvent.click(healBtn);
const p = any(name);
if (!p) return; // removed (death) = skip (no button in UI)
applyEnc(combatApplyHpChange(enc, p.id, 'heal', amount).patch);
}
function toggleActive(name) {
const row = getParticipantRow(name);
const btn = row.queryByTitle('Mark Active') || row.queryByTitle('Mark Inactive');
if (!btn) throw new Error(`${name} has no active toggle`);
fireEvent.click(btn);
const p = any(name);
if (!p) throw new Error(`no active target: ${name}`);
applyEnc(combatToggleActive(enc, p.id).patch);
}
function openConditions(name) {
const row = getParticipantRow(name);
const btn = row.getByTitle('Conditions');
// idempotent: ensure panel open. Click toggles; if another participant's panel
// was open it's already closed by this participant's row focus, so just click.
fireEvent.click(btn);
}
function toggleCondition(name, label) {
openConditions(name);
// panel render is async (React state). Wait for button by title.
return waitFor(() => {
const condButtons = document.querySelectorAll('button[title]');
const target = [...condButtons].find(b => b.getAttribute('title') === label);
if (!target) throw new Error(`condition button not found: ${label}`);
fireEvent.click(target);
});
function toggleConditionAction(name, label) {
const p = any(name);
if (!p) throw new Error(`no condition target: ${name}`);
applyEnc(combatToggleCondition(enc, p.id, label).patch);
}
function editParticipant(name, patch) {
const row = getParticipantRow(name);
fireEvent.click(row.getByTitle('Edit'));
// EditParticipantModal. Scope to the modal via its form inputs.
const modal = document.querySelector('.fixed.inset-0') || document.body;
const inputs = modal.querySelectorAll('input');
if (patch.name !== undefined) {
fireEvent.change(inputs[0], { target: { value: patch.name } });
}
if (patch.initiative !== undefined && inputs[1]) {
fireEvent.change(inputs[1], { target: { value: String(patch.initiative) } });
}
const saveBtn = modal.querySelector('button[type="submit"]') ||
[...modal.querySelectorAll('button')].find(b => /^Save$/i.test(b.textContent.trim()));
fireEvent.click(saveBtn);
const p = any(name);
if (!p) throw new Error(`no edit target: ${name}`);
applyEnc(updateParticipant(enc, p.id, patch).patch);
}
function removeParticipant(name) {
fireEvent.click(getParticipantRow(name).getByTitle('Remove'));
function removeParticipantByName(name) {
const p = any(name);
if (!p) throw new Error(`no remove target: ${name}`);
applyEnc(removeParticipant(enc, p.id).patch);
}
async function deathSave(name, saveNum) {
const row = getParticipantRow(name);
const btn = row.getByTitle(`Death save ${saveNum}`);
fireEvent.click(btn);
await waitFor(() => {
const last = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/')).slice(-1)[0];
if (!last) throw new Error('deathSave no write');
});
function deathSaveAction(name, saveNum) {
const p = any(name);
if (!p) throw new Error(`no deathsave target: ${name}`);
applyEnc(combatDeathSave(enc, p.id, saveNum).patch);
}
async function nextTurn() {
fireEvent.click(screen.getByRole('button', { name: /Next Turn/i }));
await waitFor(() => {
const last = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/')).slice(-1)[0];
if (!last) throw new Error('nextTurn no write');
});
function dragTie(draggedName, targetName) {
const d = any(draggedName), t = any(targetName);
if (!d || !t) throw new Error('drag target missing');
applyEnc(reorderParticipants(enc, d.id, t.id).patch);
}
async function pauseCombat() {
fireEvent.click(screen.getByRole('button', { name: /Pause Combat/i }));
await waitFor(() => {
const last = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/')).slice(-1)[0];
if (!last?.data?.isPaused) throw new Error('not paused');
});
}
async function resumeCombat() {
fireEvent.click(screen.getByRole('button', { name: /Resume Combat/i }));
await waitFor(() => {
const last = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/')).slice(-1)[0];
if (last?.data?.isPaused) throw new Error('not resumed');
});
}
async function startCombat() {
fireEvent.click(screen.getByRole('button', { name: /Start Combat/i }));
await waitFor(() => {
const last = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/')).slice(-1)[0];
if (!last?.data?.isStarted) throw new Error('not started');
});
}
function toggleHidePlayerHp() {
fireEvent.click(screen.getByRole('switch'));
}
function currentEncDoc() {
const calls = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/'));
return calls[calls.length - 1]?.data;
function toggleHidePlayerHpAction() {
applyDisplay(toggleHidePlayerHp(display.hidePlayerHp).patch);
}
// ---------- scenario ----------
const ROUNDS = 100;
test('full 100-round combat scenario', async () => {
await setupReady('ScenarioCamp', 'BigBoss');
test('full 100-round combat scenario (shared, no React)', async () => {
// roster
await recordAsync('addChar Fighter', () => addCharacterViaUI('Fighter', 30, 2));
await recordAsync('addChar Cleric', () => addCharacterViaUI('Cleric', 24, 1));
@@ -244,97 +193,142 @@ test('full 100-round combat scenario', async () => {
await recordAsync('addCharParticipant Fighter', () => addCharacterParticipant('Fighter'));
await recordAsync('addCharParticipant Cleric', () => addCharacterParticipant('Cleric'));
await recordAsync('addCharParticipant Rogue', () => addCharacterParticipant('Rogue'));
await recordAsync('addAllChars', () => addAllCharacters());
await recordAsync('addAllChars', () => addAllCharacters()); // bulk add path
// hidden hp toggle
record('toggleHidePlayerHp', () => toggleHidePlayerHp());
record('toggleHidePlayerHp back', () => toggleHidePlayerHp());
// hidden hp toggle x2 (back to default)
record('toggleHidePlayerHp', () => toggleHidePlayerHpAction());
record('toggleHidePlayerHp back', () => toggleHidePlayerHpAction());
await recordAsync('startCombat', () => startCombat());
// 100 rounds of mixed actions
for (let r = 1; r <= ROUNDS; r++) {
await recordAsync(`round ${r} nextTurn`, () => nextTurn());
// ---------- 100 ROUNDS (loop by actual round-wrap count) ----------
let roundsDone = 0;
let prevRound = enc.round;
let turnInRound = 0;
let turnTotal = 0;
// rotation integrity: turnOrderIds no dup, currentTurn valid
if (r % 10 === 0) {
record(`round ${r} rotation-check`, () => {
const enc = currentEncDoc();
if (!enc) throw new Error('no encounter doc');
while (roundsDone < ROUNDS) {
turnTotal++;
const actor = anyById(enc.currentTurnParticipantId);
const r = enc.round;
// per-turn deterministic actions keyed by round + actor type
// damage OrcBoss every even round
if (r % 2 === 0 && turnInRound === 0) {
await recordAsync(`r${r} damage OrcBoss`, () => applyDamage('OrcBoss', 3));
}
// heal Cleric every 3 rounds
if (r % 3 === 0 && turnInRound === 1) {
record(`r${r} heal Cleric`, () => applyHeal('Cleric', 2));
}
// condition on Fighter every 5 rounds
if (r % 5 === 0 && turnInRound === 2) {
record(`r${r} condition Fighter stunned`, () => toggleConditionAction('Fighter', 'Stunned'));
}
// toggleActive Goblin2 every 7 rounds (toggle off, next 7 toggle on)
if (r % 7 === 0 && turnInRound === 3) {
record(`r${r} toggleActive Goblin2`, () => toggleActive('Goblin2'));
}
// edit Wolf initiative every 13 rounds
if (r % 13 === 0 && turnInRound === 4) {
record(`r${r} edit Wolf init`, () => editParticipant('Wolf', { initiative: 15 }));
}
// pause/resume + add reinforcement + edit every 10 rounds
if (r % 10 === 0 && turnInRound === 0) {
await recordAsync(`r${r} pause`, () => pauseCombat());
await recordAsync(`r${r} addReinforcement`, () => addMonsterParticipant(`Reinforce${r}`, 10, 1));
await recordAsync(`r${r} edit Rogue initiative`, () => editParticipant('Rogue', { initiative: 20 }));
await recordAsync(`r${r} resume`, () => resumeCombat());
}
// create a same-init tie + drag every 15 rounds (exercises reorderParticipants)
if (r % 15 === 0 && turnInRound === 5) {
const g1 = any('Goblin1');
if (g1 && alive('Goblin2')) {
record(`r${r} tie Goblin2->Goblin1 init`, () => editParticipant('Goblin2', { initiative: g1.initiative }));
record(`r${r} drag Goblin2 before Goblin1`, () => dragTie('Goblin2', 'Goblin1'));
}
}
// death scenarios: drop a PC to 0, death saves, revive
if (r === 25 && turnInRound === 0) {
await recordAsync(`r${r} drop Rogue`, () => applyDamage('Rogue', 99));
record(`r${r} deathSave1 Rogue`, () => deathSaveAction('Rogue', 1));
record(`r${r} revive Rogue`, () => applyHeal('Rogue', 22));
}
// round 50: full 3-success death-save path (isDying) on Cleric, then remove
if (r === 50 && turnInRound === 0) {
await recordAsync(`r${r} drop Cleric`, () => applyDamage('Cleric', 99));
await recordAsync(`r${r} deathSave Cleric x3 (isDying)`, async () => {
deathSaveAction('Cleric', 1);
deathSaveAction('Cleric', 2);
deathSaveAction('Cleric', 3); // → isDying true
});
const cl = any('Cleric');
if (cl && cl.isDying) record(`r${r} remove dying Cleric`, () => removeParticipantByName('Cleric'));
}
// remove a reinforcement every 30 rounds
if (r % 30 === 0 && turnInRound === 1) {
const rein = any(`Reinforce${r - 10}`);
if (rein) record(`r${r} remove Reinforce${r - 10}`, () => removeParticipantByName(`Reinforce${r - 10}`));
}
// toggle hide hp every 20 rounds
if (r % 20 === 0 && turnInRound === 0) {
record(`r${r} toggleHidePlayerHp`, () => toggleHidePlayerHpAction());
record(`r${r} toggleHidePlayerHp back`, () => toggleHidePlayerHpAction());
}
// rotation integrity check every 10 rounds at round start
if (turnInRound === 0 && r % 10 === 0) {
record(`r${r} rotation-check`, () => {
const order = enc.turnOrderIds || [];
const uniq = new Set(order);
if (uniq.size !== order.length) {
throw new Error(`turnOrderIds dup: ${JSON.stringify(order)}`);
}
if (uniq.size !== order.length) throw new Error(`turnOrderIds dup: ${JSON.stringify(order)}`);
if (enc.currentTurnParticipantId && !order.includes(enc.currentTurnParticipantId)) {
throw new Error(`currentTurn ${enc.currentTurnParticipantId} not in turnOrderIds`);
}
const ids = enc.participants.map(p => p.id);
if (JSON.stringify(order) !== JSON.stringify(ids)) {
throw new Error(`turnOrderIds drift: order=${JSON.stringify(order)} ids=${JSON.stringify(ids)}`);
}
});
}
// damage front monster every other round
if (r % 2 === 0) record(`round ${r} damage OrcBoss`, () => applyDamage('OrcBoss', 3));
if (r % 3 === 0) record(`round ${r} heal Cleric`, () => applyHeal('Cleric', 2));
if (r % 5 === 0) record(`round ${r} condition Fighter stunned`, () => toggleCondition('Fighter', 'Stunned'));
if (r % 7 === 0) record(`round ${r} toggleActive Goblin2`, () => toggleActive('Goblin2'));
// advance turn
await recordAsync(`r${r} turn${turnInRound} nextTurn`, () => nextTurnAction());
turnInRound++;
// pause/resume every 10 rounds, add a participant, resume
if (r % 10 === 0) {
await recordAsync(`round ${r} pause`, () => pauseCombat());
await recordAsync(`round ${r} addReinforcement`, () =>
addMonsterParticipant(`Reinforce${r}`, 10, 1));
await recordAsync(`round ${r} edit Rogue initiative`, () => editParticipant('Rogue', { initiative: 20 }));
await recordAsync(`round ${r} resume`, () => resumeCombat());
}
// edit initiative on Wolf every 13
if (r % 13 === 0) record(`round ${r} edit Wolf init`, () => editParticipant('Wolf', { initiative: 15 }));
// damage-to-0 + death save on Rogue around round 25 and 50
if (r === 25) {
record(`round ${r} drop Rogue`, () => applyDamage('Rogue', 99));
record(`round ${r} deathSave1 Rogue`, () => deathSave('Rogue', 1));
record(`round ${r} revive Rogue`, () => applyHeal('Rogue', 22));
}
if (r === 50) {
record(`round ${r} drop Cleric`, () => applyDamage('Cleric', 99));
record(`round ${r} deathSave Cleric x3`, async () => {
await deathSave('Cleric', 1);
await deathSave('Cleric', 2);
await deathSave('Cleric', 3);
});
record(`round ${r} revive Cleric`, () => applyHeal('Cleric', 24));
}
// remove a reinforcement late
if (r === 30) {
await recordAsync(`round ${r} pause`, () => pauseCombat());
record(`round ${r} remove Reinforce20`, () => removeParticipant('Reinforce20'));
await recordAsync(`round ${r} resume`, () => resumeCombat());
// round wrap detected
if (enc.round > prevRound) {
roundsDone++;
prevRound = enc.round;
turnInRound = 0;
}
}
await recordAsync('endCombat', async () => {
fireEvent.click(screen.getByRole('button', { name: /End Combat/i }));
// End-combat ConfirmationModal has title 'End Encounter?'. Scope Confirm to it.
const endConfirm = await screen.findByRole('heading', { name: /End Encounter/i });
const modal = endConfirm.closest('.fixed.inset-0') || document.body;
const confirmBtn = [...modal.querySelectorAll('button')].find(b => /Confirm/i.test(b.textContent.trim()));
fireEvent.click(confirmBtn);
await waitFor(() => {
const last = currentEncDoc();
if (last?.isStarted !== false) throw new Error('not ended');
});
});
await recordAsync('endCombat', () => endCombat());
// ---------- report ----------
const failed = RESULTS.filter(r => !r.ok);
const failed = RESULTS.filter(x => !x.ok);
if (failed.length > 0) {
const msg = failed.map(f => `FAIL [${f.phase}]: ${f.err}`).join('\n');
// eslint-disable-next-line no-console
console.error(`\n=== SCENARIO FAILURES (${failed.length}/${RESULTS.length}) ===\n${msg}\n`);
}
// eslint-disable-next-line no-console
console.log(`\n=== SCENARIO: ${RESULTS.length - failed.length}/${RESULTS.length} phases ok ===\n`);
expect(failed).toEqual([]);
}, 240000); // long timeout: 100 rounds
expect(roundsDone).toBe(ROUNDS);
// lifecycle assertions (activeDisplay mirrors combat state)
expect(enc.isStarted).toBe(false);
expect(enc.round).toBe(0);
expect(enc.currentTurnParticipantId).toBeNull();
expect(display.activeCampaignId).toBeNull();
expect(display.activeEncounterId).toBeNull();
});
function anyById(id) {
return enc.participants.find(p => p.id === id);
}
+8 -8
View File
@@ -42,7 +42,7 @@ describe('Encounter -> Firebase', () => {
expect(call.path).toMatch(/campaigns\/[^/]+\/encounters\//);
});
test('togglePlayerDisplay: updateDoc patch on activeDisplay/status', async () => {
test('togglePlayerDisplay: setDoc{merge} patch on activeDisplay/status', async () => {
await setupCampaignAndEncounter('Camp D', 'Enc D');
await selectEncounterByName('Enc D');
@@ -50,33 +50,33 @@ describe('Encounter -> Firebase', () => {
const eyeBtn = await screen.findByTitle('Activate for Player Display');
fireEvent.click(eyeBtn);
await waitFor(() => findCall('updateDoc', 'activeDisplay/status'));
const call = findCall('updateDoc', 'activeDisplay/status');
// BUG-4 fix: updateDoc patch, not setDoc replace (was clobbering fields)
await waitFor(() => findCall('setDoc', 'activeDisplay/status'));
const call = findCall('setDoc', 'activeDisplay/status');
// main truth: setDoc{merge} patch, not replace (would clobber fields)
expect(call.data).toMatchObject({
activeCampaignId: expect.any(String),
activeEncounterId: expect.any(String),
});
});
test('togglePlayerDisplay off: updateDoc nulls active ids', async () => {
test('togglePlayerDisplay off: setDoc{merge} nulls active ids', async () => {
await setupCampaignAndEncounter('Camp O', 'Enc O');
await selectEncounterByName('Enc O');
// turn ON
const onBtn = await screen.findByTitle('Activate for Player Display');
fireEvent.click(onBtn);
await waitFor(() => findCall('updateDoc', 'activeDisplay/status'));
await waitFor(() => findCall('setDoc', 'activeDisplay/status'));
// turn OFF
const offBtn = await screen.findByTitle('Deactivate for Player Display');
fireEvent.click(offBtn);
await waitFor(() => {
const calls = findCalls('updateDoc', 'activeDisplay/status');
const calls = findCalls('setDoc', 'activeDisplay/status');
const last = calls[calls.length - 1];
return last.data.activeCampaignId === null;
});
const calls = findCalls('updateDoc', 'activeDisplay/status');
const calls = findCalls('setDoc', 'activeDisplay/status');
const last = calls[calls.length - 1];
expect(last.data).toMatchObject({ activeCampaignId: null, activeEncounterId: null });
});
+9 -7
View File
@@ -1,8 +1,8 @@
// BUG-4 repro: toggling hidePlayerHp must not clobber activeDisplay doc.
// setDoc = replace (contract). {merge:true} arg ignored.
// Toggling hide-HP writes {hidePlayerHp:X} alone → activeCampaignId + activeEncounterId → null.
// Display reads null → "Game Session Paused". Recover requires re-activating encounter.
// Fix: use updateDoc (patch), not setDoc.
// setDoc = replace would clobber. setDoc({merge:true}) patches only — matches main.
// Toggling hide-HP writes {hidePlayerHp:X} via setDoc{merge} → activeCampaignId + activeEncounterId preserved.
// Display keeps reading them → stays active.
// Regression: if caller swaps to plain setDoc (no merge) or updateDoc-throws-on-missing, re-breaks.
import React from 'react';
import { render, waitFor, screen, fireEvent } from '@testing-library/react';
@@ -50,14 +50,16 @@ describe('BUG-4: hide-player-HP toggle preserves activeDisplay', () => {
await waitFor(() => {
const writes = getAdapterCalls().filter(
c => c.fn === 'updateDoc' && c.path.includes('activeDisplay/status')
c => c.fn === 'setDoc' && c.path.includes('activeDisplay/status')
);
expect(writes.length).toBeGreaterThan(0);
const last = writes[writes.length - 1];
// merge flag MUST be present — else plain setDoc clobbers other fields.
expect(last.opts && last.opts.merge).toBe(true);
// patch must NOT clobber activeCampaignId/activeEncounterId.
// BUG: setDoc replace writes only {hidePlayerHp:true} → clobbers.
// Fix: updateDoc patch — other fields untouched.
expect(last.patch.hidePlayerHp).toBe(true);
// Fix: setDoc{merge} patch — other fields untouched.
expect(last.data.hidePlayerHp).toBe(true);
}, { timeout: 3000 });
});
});
+2 -2
View File
@@ -82,10 +82,10 @@ describe('Logs -> Firebase', () => {
fireEvent.click(undoBtns[0]);
await waitFor(() => {
const und = getCalls().find(c => c.fn === 'updateDoc' && c.path.endsWith(`/logs/${logId}`) && c.data.undone === true);
const und = getCalls().find(c => c.fn === 'updateDoc' && c.path.includes('/logs/') && c.data.undone === true);
return und;
});
const markUndone = getCalls().find(c => c.fn === 'updateDoc' && c.path.endsWith(`/logs/${logId}`));
const markUndone = getCalls().find(c => c.fn === 'updateDoc' && c.path.includes('/logs/') && c.data.undone === true);
expect(markUndone.data.undone).toBe(true);
// encounter path updated with undo payload (any encounter update after undo click)
const encUndo = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/'));
+2 -2
View File
@@ -1,6 +1,6 @@
// Lock: storage adapters must use ESM exports (no module.exports).
// Regression guard: CJS in src/ crashes CRA prod build (ESM strict).
// Bug history: ws.js + memory.js used module.exports. Dev lenient (masked),
// Bug history: server.js + firebase.js used module.exports. Dev lenient (masked),
// prod bundle crashed blank page. firebase.js always ESM.
import fs from 'fs';
import path from 'path';
@@ -8,7 +8,7 @@ import path from 'path';
const ADAPTER_DIR = path.join(__dirname, '..', 'storage');
describe('storage adapters use ESM (no CJS)', () => {
const adapters = ['ws.js', 'memory.js', 'firebase.js', 'index.js'];
const adapters = ['server.js', 'firebase.js', 'index.js'];
test.each(adapters)('%s has no module.exports', (file) => {
const full = fs.readFileSync(path.join(ADAPTER_DIR, file), 'utf8');
// strip line comments so words like 'require' in explanatory comments don't trip the guard
+21
View File
@@ -0,0 +1,21 @@
// Firebase adapter contract test.
// Runs the SAME storage contract as server (src/storage/contract.js)
// against createFirebaseStorage. The SDK is mocked via src/__mocks__/firebase/*,
// so this proves the adapter translates contract calls -> SDK calls correctly
// (path handling, merge semantics, subscribe, queryConstraints) without network.
//
// queryConstraints (orderBy + limit) now tested in shared contract for BOTH
// adapters — no separate firebase-only block needed here.
import { initFirebase, createFirebaseStorage } from '../storage/firebase';
import { runStorageContract } from '../storage/contract';
import { resetMockDb } from '../__mocks__/firebase/_mock-db';
// Firebase mock DB is shared global state. Reset before each factory so
// contract tests are isolated.
runStorageContract('firebase', () => {
resetMockDb();
const ok = initFirebase();
if (!ok) throw new Error('initFirebase failed under mocked env');
return createFirebaseStorage();
});
+70
View File
@@ -0,0 +1,70 @@
// Storage factory (index.js) test.
// Verifies getStorage() returns the right adapter per REACT_APP_STORAGE env,
// caches as singleton, and getStorageMode() reports the active mode.
// Adapters are mocked (no network/init) — factory routing is the unit.
import { getStorage, getStorageMode } from '../storage/index';
// reset module-level singleton between tests
let originalStorage;
beforeEach(() => {
originalStorage = process.env.REACT_APP_STORAGE;
// bust the module singleton by re-importing fresh
jest.resetModules();
});
afterEach(() => {
if (originalStorage === undefined) delete process.env.REACT_APP_STORAGE;
else process.env.REACT_APP_STORAGE = originalStorage;
jest.resetModules();
});
describe('getStorageMode', () => {
test('defaults to firebase when env unset', () => {
delete process.env.REACT_APP_STORAGE;
const { getStorageMode } = require('../storage/index');
expect(getStorageMode()).toBe('firebase');
});
test('returns server when REACT_APP_STORAGE=server', () => {
process.env.REACT_APP_STORAGE = 'server';
const { getStorageMode } = require('../storage/index');
expect(getStorageMode()).toBe('server');
});
test('throws on unknown mode', () => {
process.env.REACT_APP_STORAGE = 'garbage';
const { getStorage } = require('../storage/index');
expect(() => getStorage()).toThrow(/Unknown REACT_APP_STORAGE/);
});
});
describe('getStorage factory routing', () => {
test('server mode returns server adapter (init may fail without backend — catch)', () => {
process.env.REACT_APP_STORAGE = 'server';
const { getStorage } = require('../storage/index');
try {
const s = getStorage();
expect(s).toBeTruthy();
expect(typeof s.getDoc).toBe('function');
} catch (e) {
// ws adapter without backend URL/config is allowed to throw at factory;
// routing reached ws branch (not firebase) which is the contract.
expect(e).toBeTruthy();
}
});
test('returns singleton on repeat call (same instance)', () => {
process.env.REACT_APP_STORAGE = 'server';
const { getStorage } = require('../storage/index');
let a;
try { a = getStorage(); } catch (e) { return; } // no backend ok
if (a) {
const b = getStorage();
expect(a).toBe(b);
}
});
});
-8
View File
@@ -1,8 +0,0 @@
// Runner: executes storage contract against each impl.
// TDD: contract = spec. Run against memory first. RED until memory.js built.
'use strict';
const { runStorageContract } = require('../storage/contract');
const { createMemoryStorage } = require('../storage/memory');
runStorageContract('memory', () => createMemoryStorage());
+3
View File
@@ -4,6 +4,9 @@ import { render, screen, fireEvent, waitFor, within } from '@testing-library/rea
import App from '../App';
import { MOCK_DB } from '../__mocks__/firebase/_mock-db';
// fast waitFor: 5ms poll vs default 50ms. Cuts scenario ~8x.
export const fastWaitFor = (cb, opts) => waitFor(cb, { interval: 5, timeout: 1000, ...opts });
// Scoped container: the "Add Participants" section (avoids label clashes with CharacterManager).
export function getParticipantForm() {
const heading = screen.getByText('Add Participants');