# TTRPG Initiative Tracker (v0.4)

![Here it is in use](images/in_use.png)

This application is the result of not having the exact tool I want to use, and after a few sessions of [vibe-coding](https://www.youtube.com/watch?v=Tw18-4U7mts) with [Google Gemini](https://developers.google.com/gemini-code-assist/docs/overview), here it is!.

**Use at your own risk.**

A web-based application designed to help Dungeon Masters (DMs) manage and display combat initiative for tabletop role-playing games (TTRPGs). It features a DM admin interface for controlling encounters and a separate player display view suitable for an external monitor.

![](images/initiative_tracker.png)

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)

* **Campaign Management:**
    * Create campaigns to organize game sessions.
    * Option to set a custom background image URL for the player display on a per-campaign basis.
    * Campaign cards display the number of characters and encounters.
* **Character Management:**
    * Add and manage characters (player characters) within each campaign.
    * Set default Max HP and default Initiative Modifier for each campaign character.
    * The character list is collapsible to save screen space.
* **Encounter Management:**
    * Create multiple encounters per campaign.
    * Add characters from the campaign roster (with auto-rolled initiative based on their modifier and HP pre-filled from campaign defaults) or add custom monsters.
    * Monsters have an editable default initiative modifier (pre-filled at +2) and can be marked as NPCs.
    * "Add All Campaign Characters" button for quickly populating encounters with initiative rolls.
    * DM controls to start, pause/resume, advance turns, and end encounters.
    * Visual feedback for rolled initiative when adding individual participants.
    * Participants can be added mid-combat while the encounter is paused; the turn order recalculates on resume.
* **HP Tracking:**
    * Apply damage or healing to any participant during combat directly from the DM view.
    * When a participant reaches 0 HP they are automatically marked inactive and shown with a skull (☠️) icon.
    * Healing a dead participant above 0 HP revives them and reactivates them in the turn order.
* **Death Save Tracking:**
    * When a player character reaches 0 HP, three death save checkboxes appear in the DM view.
    * Marking the third death save triggers a dissolve animation on the player display, then removes the participant from the encounter.
* **Conditions:**
    * Apply any of 22 conditions to a participant, including all standard D&D conditions plus several extras: Alchemist Fire 🔥, Bardic Inspiration 🎵, Blinded 🙈, Charmed 💘, Deafened 🔇, Exhaustion 😴, Frightened 😱, Grappled 🤜, Grazed 🩹, Incapacitated 💫, Invisible 👻, Paralyzed ⚡, Petrified 🗿, Poisoned 🤢, Prone ⬇️, Restrained 🕸️, Sapped 🔨, Shield 🛡️, Slowed 🐌, Stunned 💥, Unconscious 💤, Vexed 🎯.
    * Active conditions are shown as emoji badges on both the DM view and the player display.
    * Conditions can be toggled directly from the badge or from an expandable condition picker per participant.
* **Player Display:**
    * A clean interface showing the current initiative order, round number, participant HP, and current turn.
    * HP bars use color-coded thresholds: green (above half), yellow (quarter to half), red (below quarter), dark red (dead).
    * Monster and NPC HP totals are hidden; only the color-coded bar is shown.
    * Player character HP can be hidden from the player display via a toggle in the DM's initiative controls ("Hide player HP"). When enabled, only the color-coded bar is shown for characters as well.
    * Active conditions are displayed as emoji badges on each participant's card.
    * Inactive participants (and dead ones) are greyed out with a grayscale filter.
    * Inactive monsters (e.g. pre-staged or summoned reserves) are hidden from the player display entirely; inactive player characters still appear greyed out.
    * The current participant's card auto-scrolls into view when the turn advances.
    * NPCs are visually distinct from hostile monsters, which are distinct from player characters.
    * Displays a custom campaign background image if one is set.
    * Shows a "Game Session Paused" message when no encounter is active, or "(Combat Paused)" when the DM pauses a running encounter.
    * Player display is opened in a separate window via the "Open Player Window" button in the DM's header.
    * 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 (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.

## Tech Stack

* **Frontend:** React
* **Styling:** Tailwind CSS
* **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

![](images/running_combat.png) 

The TTRPG Initiative Tracker is designed for Dungeon Masters to manage combat encounters and display the initiative order to players. Here's a typical workflow:

1.  **Admin Interface (DM's View):**
    * **Create a Campaign:** Start by creating a new campaign. You can optionally provide a URL for a custom background image that will be shown on the Player Display for this campaign. Campaign cards will show a preview of this background.
    * **Add Characters:** Within a campaign, add your player characters. For each, set their name, default maximum HP, and a default initiative modifier. This section is collapsible to save screen space.
    * **Create Encounters:** For each combat scenario, create an encounter within the selected campaign.
    * **Manage Participants:**
        * Add characters from your campaign roster. Their Max HP will pre-fill from their campaign default, and their initiative will be automatically rolled (d20 + their default modifier).
        * Add monsters. Provide a name, Max HP, and an initiative modifier (defaults to +2 but is editable). Mark if the monster is an "NPC" for different styling. Their initiative will be automatically rolled (d20 + specified modifier).
        * Use the "Add All From Campaign (Roll Init)" button to quickly add all campaign characters not yet in the encounter, with their initiative rolled and HP set from defaults.
        * If there are ties in initiative, you can drag and drop participants (before starting the encounter or while it's paused) to set a specific tie-breaker order.
    * **Control Player Display:**
        * Click the "Open Player Window" button in the header to launch a separate, clean window for your players (ideal for an external monitor). This window's content is controlled by the DM.
        * Use the "eyeball" icon next to an encounter to toggle it as "LIVE ON PLAYER DISPLAY". This controls what is shown on the Player Display window. Only one encounter can be live at a time.
    * **Run Combat:**
        * Once participants are added and initiative is set, click "Start Encounter". This also automatically makes the encounter live on the Player Display.
        * Use the "Pause" button to temporarily halt combat. While paused, you can adjust HP and re-order tied initiatives. Click "Resume" to continue.
        * Use the "Next Turn" button (disabled when paused) to advance through the initiative order. The current combatant will be highlighted.
        * Apply damage or healing to participants directly in the Admin View. Participants at 0 HP are automatically deactivated and marked with a skull icon. Healing them above 0 HP revives them.
        * For player characters at 0 HP, track death saving throws using the three checkboxes that appear. Marking the third failure triggers a death animation on the player display and removes the participant.
        * Apply or remove conditions (Blinded, Charmed, Poisoned, etc.) using the ✨ button next to each participant. Active conditions appear as emoji badges on both the DM view and the player display.
        * Mark participants as inactive (e.g., if knocked out) using the toggle next to their name. Inactive monsters are hidden from the player display entirely, making this useful for pre-staging summoned reserves.
        * Toggle **Hide player HP** in the initiative controls to show or hide player character HP values on the player display.
        * Click "End Encounter" (with confirmation) when combat is over. This also deactivates it from the Player Display.

2.  **Player Display Window:**
    * This window (opened by the DM via the "Open Player Window" button, or accessed directly at `/display` or `/?playerView=true`) shows a simplified, header-less view of the active encounter.
    * It displays the initiative order, current turn, round number, and participant HP bars. Monster/NPC HP totals are hidden; only the color-coded bar is shown. Player character HP is shown numerically unless the DM has enabled "Hide player HP".
    * HP bars are color-coded: green (above 50%), yellow (25–50%), red (below 25%), dark red (dead/0 HP).
    * Active conditions are shown as emoji badges on each participant's card.
    * The current participant's card automatically scrolls into view when the turn advances.
    * NPCs are styled with a muted gray background, distinct from hostile monsters (reddish-brown) and player characters (dark blue/indigo).
    * Dead and inactive participants are greyed out with a grayscale filter. Inactive monsters are hidden entirely.
    * When a player character's third death save is marked, a dissolve animation plays on the display before the participant is removed.
    * If a custom background URL was set for the campaign, it will be displayed with a semi-transparent overlay behind the participant cards.
    * If no encounter is active on the Player Display, it shows "Game Session Paused". If the current encounter is paused by the DM, it shows "(Combat Paused)".
    * Use the **fullscreen button** (top-right) to go fullscreen — great for a dedicated second monitor. Press Escape or click again to exit.
    * Use the **prevent sleep toggle** (moon icon, top-right) to keep the screen awake using the browser Wake Lock API. The icon turns amber and switches to a coffee cup when active.

3.  **Combat Log (`/logs`):**
    * A dedicated page that records all significant combat events: encounter starts and ends, turn advances, HP changes, condition changes, participant additions/removals, and activation toggles.
    * Each entry is timestamped and tagged with the encounter name for easy reference.
    * Most entries have an **↩ Undo** button. Clicking it rolls back that specific action in Firestore — restoring HP, conditions, turn order, or participant state to what it was before. The entry is then greyed out and marked "rolled back".
    * The log can be cleared in bulk from the page (with confirmation).
    * Accessible via the "Logs" link in the DM header or directly at `/logs`.

This flow allows the DM to prepare and run encounters efficiently while providing a clear, real-time view for the players.

## Getting Started

### 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** (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:**
    ```bash
    git clone https://code.draft13.com/robert/ttrpg-initiative-tracker
    cd ttrpg-initiative-tracker
    ```

2.  **Create Firebase Configuration File (`.env.local`):**
    * In the root of the project, create a file named `.env.local`.
    * Add your Firebase project configuration details to this file. You can find these in your Firebase project settings (Project settings > General > Your apps > Firebase SDK snippet > Config).
    * **Important:** This `.env.local` file contains sensitive API keys and should **NOT** be committed to Git. Make sure it's listed in your `.gitignore` file.

    Your `.env.local` should look like this:
    ```ini
    REACT_APP_FIREBASE_API_KEY="YOUR_FIREBASE_API_KEY"
    REACT_APP_FIREBASE_AUTH_DOMAIN="YOUR_FIREBASE_AUTH_DOMAIN"
    REACT_APP_FIREBASE_PROJECT_ID="YOUR_FIREBASE_PROJECT_ID"
    REACT_APP_FIREBASE_STORAGE_BUCKET="YOUR_FIREBASE_STORAGE_BUCKET"
    REACT_APP_FIREBASE_MESSAGING_SENDER_ID="YOUR_FIREBASE_MESSAGING_SENDER_ID"
    REACT_APP_FIREBASE_APP_ID="YOUR_FIREBASE_APP_ID"

    # Used for namespacing Firestore paths, can be any unique string for your app instance
    REACT_APP_TRACKER_APP_ID="ttrpg-initiative-tracker-dev"
    ```
    *An `.env.example` file is included in the repository as a template.*

3.  **Install Dependencies:**
    Navigate to the project root in your terminal and run:
    ```bash
    npm install
    ```
    This will install all the necessary packages defined in `package.json` and create a `package-lock.json` file.

4.  **Set up Firestore Security Rules:**
    * Go to your Firebase project console -> Firestore Database -> Rules.
    * Use the following rules for development (allows authenticated users to read/write all data). **For production, you MUST implement more restrictive rules.**
        ```
        rules_version = '2';
        service cloud.firestore {
          match /databases/{database}/documents {
            match /{document=**} {
              allow read, write: if request.auth != null;
            }
          }
        }
        ```
    * Publish these rules.

5.  **Run the Development Server:**
    ```bash
    npm start
    ```
    This will start the React development server, usually on `http://localhost:3000`. The application will open in your default web browser.

### Deployment with Docker

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.

1.  **Prerequisites for Docker:**
    * Ensure Docker Desktop (or Docker Engine on Linux) is installed and running. Download from [docker.com](https://www.docker.com/products/docker-desktop).

2.  **Building the Docker Image (for Local Testing with `.env.local`):**
    * Make sure your `.env.local` file is present in the project root and correctly configured with your Firebase details. The `Dockerfile` is set up to copy this file as `.env` during the build for local testing.
    * **Security Warning:** The image built this way will contain your Firebase API keys from `.env.local`. **Do NOT push this specific image to a public Docker registry.** For production, environment variables should be injected by your hosting platform or CI/CD pipeline at build or runtime.

    To build the image, navigate to the project root and run:
    ```bash
    docker build -t ttrpg-initiative-tracker .
    ```
    *(You can replace `ttrpg-initiative-tracker` with your preferred image name/tag).*

3.  **Running the Docker Container Locally:**
    Once the image is built, run it:
    ```bash
    docker run -p 8080:80 --rm --name ttrpg-tracker-app ttrpg-initiative-tracker
    ```
    * `-p 8080:80`: Maps port 8080 on your host machine to port 80 inside the container (where Nginx is listening).
    * `--rm`: Automatically removes the container when it stops.
    * `--name ttrpg-tracker-app`: Assigns a name to the running container.
    * `ttrpg-initiative-tracker`: The name of the image you built.

    You can then access the application at `http://localhost:8080`.

4.  **Production Deployment Considerations:**
    * When deploying to a production environment (e.g., a cloud provider, your own server), you should **not** copy your `.env.local` file into the Docker image.
    * Instead, configure the `REACT_APP_FIREBASE_...` environment variables directly in your hosting platform's settings or pass them to the Docker container at runtime (if your application is set up to read them at runtime, though Create React App bakes them in at build time).
    * 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 (recommended):**
```bash
npm install                # installs root, server/, and shared/ workspaces
./scripts/dev-start.sh     # backend :4001 + frontend :3999, server mode
./scripts/dev-stop.sh      # stop both
```

**Manual (fallback):**
```bash
npm install
npm run server:dev         # starts backend on :4001 (SQLite at data/tracker.sqlite)

# in another terminal:
REACT_APP_STORAGE=server \
REACT_APP_BACKEND_URL=http://127.0.0.1:4001 \
REACT_APP_BACKEND_REALTIME_URL=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>
ttrpg-initiative-tracker/
├── .dockerignore        # Specifies intentionally untracked files that Docker should ignore
├── .env.example         # Example environment variables
├── .env.local           # Local environment variables (ignored by Git)
├── .gitignore           # Specifies intentionally untracked files that Git should ignore
├── Dockerfile           # Firebase-mode image (frontend-only, served by nginx)
├── package.json         # Workspaces root: frontend + server + shared
├── package-lock.json    # Records exact versions of 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 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.
