581 lines
37 KiB
Markdown
581 lines
37 KiB
Markdown
# AGENTS.md — Dragonroll
|
||
|
||
Read this file before touching the code. It is a complete map of the project: layout, architecture,
|
||
data model, API, conventions and known landmines. You should not need to explore the rest of the repo
|
||
to make a correct change.
|
||
|
||
## 1. What this is
|
||
|
||
**Dragonroll** is a free/open-source helper for tabletop RPG campaigns (notes, campaigns, folders,
|
||
dice widgets, shared markdown, sounds). It is a two-app monorepo:
|
||
|
||
- `backend/` — Node + **Express 5** + **Mongoose 9** (MongoDB) REST API, JWT auth. CommonJS.
|
||
- `frontend/` — **Nuxt 4 / Vue 3** client (Composition API, `<script setup>`), SCSS, axios, marked, mitt, motion.
|
||
|
||
There is **no** database seeding, no ORM migrations, no linter/formatter config, no Pinia/Vuex, and no
|
||
Vue Router pages (see §5.1 — the UI is a window manager, not routed pages). The only automated tests
|
||
are `tests/*.test.js` (`npm test`, Node's built-in runner), which exercise the Foundry module's sync
|
||
logic against stubbed Foundry globals.
|
||
|
||
Git: default branch `master`, hosted on a self-hosted Gitea (`git.aranroig.com/BinarySandia04/Dragonroll`).
|
||
CI (`.gitea/workflows/deploy.yml`) builds two Docker images on every push to `master`, pushes them to
|
||
`git.aranroig.com/<user>/dragonroll-{frontend,backend}:latest`, copies `docker-compose.yml` +
|
||
`nginx.conf` to the deploy host and runs `docker compose pull && up -d`.
|
||
|
||
## 2. Root layout
|
||
|
||
```
|
||
dragonroll/
|
||
├── backend/ Express API (CommonJS, entry: src/index.js)
|
||
├── frontend/ Nuxt 4 app (entry: app/app.vue)
|
||
├── obsidian-plugin/ Plain JavaScript Obsidian plugin for campaign note import/push
|
||
├── docker-compose.yml nginx :3000 -> frontend :3000, /api -> backend :5000
|
||
├── nginx.conf reverse proxy rules for the compose stack
|
||
├── ecosystem.config.js PM2 config (stale: runs `npm start`, which does not exist — see §9)
|
||
├── .gitea/workflows/deploy.yml
|
||
├── static/media/ README logo images only
|
||
├── tests/ `node --test` tests (Foundry module sync toggle)
|
||
├── package.json root: only `concurrently`, used by `npm run dev`
|
||
└── README.md install/run instructions are STALE (see §9)
|
||
```
|
||
|
||
## 3. Commands
|
||
|
||
```bash
|
||
npm install # root: installs `concurrently` only
|
||
npm install --prefix backend
|
||
npm install --prefix frontend # runs `nuxt prepare` via postinstall
|
||
|
||
npm run dev # both apps: backend (nodemon, :5000) + frontend (nuxt dev, :3000)
|
||
# also runs the Foundry VTT start script from root .env
|
||
# (FOUNDRY_START_SCRIPT, via scripts/run-foundry.js)
|
||
npm --prefix backend run dev # backend only
|
||
npm --prefix frontend run dev # frontend only
|
||
npm --prefix frontend run build # nuxt build --dotenv .env.production
|
||
npm --prefix frontend run preview
|
||
|
||
npm test # node --test tests/ (Foundry module sync logic, no dependencies)
|
||
```
|
||
|
||
There is no `start` script in either package and no lint command.
|
||
Verification = run the dev server and exercise the flow (`/api/test` returns a JSON hello);
|
||
`npm test` covers the Foundry character/item sync toggle and per-actor force sync.
|
||
|
||
### Environment files
|
||
|
||
| File | Contents | Notes |
|
||
|---|---|---|
|
||
| `.env` (root) | `FOUNDRY_START_SCRIPT=<path to Foundry VTT start.sh>` | gitignored; consumed by `scripts/run-foundry.js` during `npm run dev` |
|
||
| `backend/.env` | `PORT=5000`, `DB_URI=mongodb://localhost:27017/dragonroll`, `NODE_ENV=development` | gitignored |
|
||
| `backend/.env.production` | same shape, `DB_URI=mongodb://192.168.1.7:27017/dragonroll` | **committed** |
|
||
| `frontend/.env` | `NUXT_PUBLIC_API_BASE_URL=http://localhost:5000/api` | gitignored |
|
||
| `frontend/.env.production` | `NUXT_PUBLIC_API_BASE_URL=https://dragonroll.aranroig.com/api` | **committed** |
|
||
|
||
`backend/src/index.js` loads `.env.$NODE_ENV` when `NODE_ENV` is set, otherwise plain `.env`.
|
||
`PORT` is read from env but **ignored**: the server always listens on 5000.
|
||
|
||
## 4. Backend
|
||
|
||
```
|
||
backend/src/
|
||
├── index.js app bootstrap: dotenv, static uploads, json limits (50mb),
|
||
│ passport init, CORS, route mounting, listen(5000)
|
||
├── db.js connectDB() -> mongoose.connect(process.env.DB_URI)
|
||
├── models/ User.js Campaign.js Note.js Folder.js Actor.js Item.js Map.js
|
||
│ FoundryLinkRequest.js DiscordLinkRequest.js DiscordGuildLink.js
|
||
├── routes/ user.js campaign.js note.js folder.js actor.js item.js map.js
|
||
│ foundry-link.js (token sync, mounted BEFORE auth) foundry.js (bridge proxy)
|
||
│ discord.js
|
||
├── services/
|
||
│ ├── keys.js { secret: "putyoursecrethere" } <- JWT secret, hardcoded
|
||
│ ├── passport.js JwtStrategy: Bearer token -> User.findById(jwt_payload._id)
|
||
│ ├── middleware.js isAdmin — imported by routes/user.js but applied to no route yet
|
||
│ ├── rate-limiter.js express-rate-limit: 150 req / 60 min, applied to /user/login and /user/setup
|
||
│ ├── storage.js multer diskStorage -> backend/src/uploads/, filename `<field>-<timestamp><ext>`
|
||
│ ├── foundry.js requestFoundry(): reads the optional snapshot bridge
|
||
│ ├── foundry-fields.js shared asText/numberOr/plainText/stringList for the mappers
|
||
│ ├── actor-foundry.js foundryActorToCharacter(): Foundry actor document -> Actor fields
|
||
│ └── item-foundry.js foundryItemToItemData(): Foundry item document -> Item fields
|
||
└── uploads/ created on demand, gitignored, served PUBLICLY at /api/public
|
||
```
|
||
|
||
### Auth chain (order matters, `src/index.js`)
|
||
|
||
1. `/api/public/*` → static file serving of `src/uploads` (no auth).
|
||
2. `app.use('/api/user', routes/user)` → **mounted before the JWT guard**, so the whole user router is
|
||
reachable unauthenticated. Individual handlers that need a user call
|
||
`passport.authenticate('jwt', {session:false})` inline (`/upload-avatar`, `/update-settings`,
|
||
`/get-settings`).
|
||
3. `checkAuth = passport.authenticate('jwt', { session: false })` — note the **missing declaration**
|
||
(implicit global). Everything mounted after this is JWT-protected.
|
||
4. `/api/campaign`, `/api/note`, `/api/folder`, `/api/actor`, `/api/item` and `/api/foundry`
|
||
(the read-only bridge proxy). `routes/foundry-link.js` is deliberately mounted **before** step 3 —
|
||
it authenticates with the per-campaign sync token instead of a Dragonroll login (see §4.1).
|
||
|
||
JWT: signed in `POST /api/user/login` with payload `{ _id, username, name, email, admin, settings }`,
|
||
`expiresIn: 172800` (48h). `req.user` is the Mongoose `User` document, so routes use `req.user.id`.
|
||
|
||
### Response convention
|
||
|
||
Every endpoint returns HTTP 200 with a JSON envelope; there is almost no real status-code usage:
|
||
|
||
```jsonc
|
||
{ "status": "ok", ...payload }
|
||
{ "status": "error", "msg": "errors.internal" } // msg is an i18n KEY, not prose
|
||
```
|
||
|
||
Common `msg` keys: `errors.missing-data`, `errors.notfound`, `errors.internal`, `unauthorized`,
|
||
`login.errors.invalid-credentials`, `register.errors.email-username-exists`. The frontend checks
|
||
`response.data.status !== 'ok'`. `GET /user/has-admin` uses a special `status: "init"` to mean
|
||
"no admin exists yet → show first-run registration".
|
||
|
||
### Authorization model
|
||
|
||
Single-tenant per user: a campaign belongs to `createdBy`, everything else hangs off a campaign.
|
||
`note.js` and `folder.js` define a local helper:
|
||
|
||
```js
|
||
async function userOwnsCampaign(campaignId, userId) { ... } // duplicated in both files
|
||
```
|
||
|
||
Ownership is enforced per handler. `settings`, `color`, `description` and `User.settings` are schemaless
|
||
`Object`/free-form fields.
|
||
|
||
### Data model
|
||
|
||
```
|
||
User ──< Campaign ──< Note ──?> Folder ──?> Folder (parentFolder, self-ref)
|
||
└───────< Folder
|
||
└───────< Actor (Foundry actors, when linked)
|
||
└───────< Item (Foundry gear + hand-made items)
|
||
└───────< Map (uploaded images + their grid settings)
|
||
```
|
||
|
||
| Model | File | Fields |
|
||
|---|---|---|
|
||
| `User` | `models/User.js` | `name*`, `username*` (unique), `email*` (unique), `password` (bcrypt hash, 10 salt rounds), `date`, `admin` (bool, default false), `image`, `setupCode`, `settings` (Object) |
|
||
| `Campaign` | `models/Campaign.js` | `name*`, `description`, `color`, `createdBy*` → User, `date`, `settings` (Object), `foundryWorldId` (unique, sparse), `foundryWorldTitle`, `foundrySystem`, `foundrySyncTokenHash` (`select: false`), `discordGuildId` |
|
||
| `Note` | `models/Note.js` | `title`, `content` (markdown source string), `campaign*` → Campaign, `folder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` |
|
||
| `Folder` | `models/Folder.js` | `name*`, `campaign*` → Campaign, `parentFolder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` |
|
||
| `Actor` | `models/Actor.js` | `name*`, `type` (`character`\|`npc`\|`creature`), `species`, `className`, `subclass`, `level`, `background`, `challengeRating`, `description`, `image`, `abilityScores{str..cha}`, `armorClass`, `speed`, `proficiencies`, `inventory[{name,quantity,weight}]` (flattened Foundry items, embedded — not `Item` docs), `traits`, `spells` (newline text), `campaign*` → Campaign, `foundryActorId` (unique per campaign), `date` |
|
||
| `Item` | `models/Item.js` | `name*`, `category` (`weapon`\|`armor`\|`shield`\|`adventuring-gear`\|`magic-item`\|`consumable`\|`tool`\|`treasure`\|`other`), `rarity` (`common`…`artifact`), `quantity`, `weight`, `properties`, `description`, `campaign*` → Campaign, `foundryItemId` (unique per campaign), `foundryNames` (names Foundry uses for it, keeps dedup stable across a Dragonroll rename), `date` |
|
||
| `Map` | `models/Map.js` | `name*`, `image` (filename in `src/uploads`), `gridSize` (cell size in image px), `offsetX`/`offsetY` (grid origin in image px), `scale` (distance one cell stands for), `campaign*` → Campaign, `date` |
|
||
|
||
`*` = required. Notes and folders are ordered by `date: -1` everywhere.
|
||
|
||
### API reference
|
||
|
||
`POST /api/user/register` — body `{username,email,name,password}`. First registered user becomes
|
||
`admin: true`. (Currently broken: see §9.)
|
||
|
||
`GET /api/user/verify-setup?code=` — `{status:'ok',code}` | `{status:'error',msg:'not-exists'}`
|
||
|
||
`POST /api/user/setup?code=` — rate limited. Body `{name,username,email,password}` completes an
|
||
invited account (`setupCode` is cleared).
|
||
|
||
`POST /api/user/login` — rate limited. Body `{usermail,password}` (accepts username **or** email) →
|
||
`{status:'ok', token, msg:'success'}`.
|
||
|
||
`POST /api/user/upload-avatar` — multipart field `image`, JWT required → stores filename on `User.image`.
|
||
Fetch the file from `/api/public/<filename>`.
|
||
|
||
`GET /api/user/retrieve-avatar?username=` → `{status:'ok', image}`
|
||
|
||
`GET /api/user/has-admin` → `status: 'ok' | 'init' | 'error'`
|
||
|
||
`POST /api/user/update-settings` — JWT inline. Body `{ settings: {...} }` (whole object replaced).
|
||
`GET /api/user/get-settings` — JWT inline → `{status:'ok', settings}`
|
||
|
||
`POST /api/campaign/create` — `{name,description,color,settings}` → `{status:'ok',campaign}`
|
||
`GET /api/campaign/list` → `{status:'ok',campaigns}`
|
||
`GET /api/campaign/retrieve/:id` → `{status:'ok',campaign}` (401 when no `req.user.id`)
|
||
|
||
`GET /api/note/list?campaign=` → `{status:'ok', folders, notes}` — notes with `folder: null` (roots);
|
||
folder entries include `parentFolder` so clients can rebuild nested folder paths
|
||
`GET /api/note/subfolder/list?campaign=&folder=` → `{status:'ok', subfolders, notes}`
|
||
`POST /api/note/create` — `{title*,content,campaign*,folder?}` (folder validated against campaign)
|
||
`POST /api/note/update` — `{id*, title?, content?, folder?, color?}` — partial, ownership checked
|
||
`POST /api/note/delete` — `{id}` — **no ownership check** (§9)
|
||
|
||
`GET /api/folder/list?campaign=` → `{status:'ok',folders}`
|
||
`POST /api/folder/create` — `{name*,campaign*}`
|
||
`POST /api/folder/rename` — `{id*,name*}`
|
||
`POST /api/folder/update` — `{id*, name?, color?}` — partial, ownership checked
|
||
`POST /api/folder/delete` — `{id}` — recursive: notes inside are moved to root (`folder: null`),
|
||
subfolders re-parented to null then deleted.
|
||
|
||
`GET /api/test` — health check.
|
||
|
||
`GET /api/actor/list?campaign=` → `{status:'ok',actors}`
|
||
`POST /api/actor/create` — `{name*,campaign*,type?,species?,className?,subclass?,level?,background?,challengeRating?,description?}`
|
||
`POST /api/actor/update` — `{id*, name?, species?, className?, subclass?, level?, abilityScores?, armorClass?, speed?, proficiencies?, inventory?, traits?, spells?, image?}` — partial, ownership checked
|
||
`POST /api/actor/upload-image?actor=` — multipart field `image`
|
||
`POST /api/actor/delete` — `{id}`
|
||
|
||
`GET /api/item/list?campaign=` → `{status:'ok',items}`
|
||
`POST /api/item/create` — `{name*,campaign*,category?,rarity?,quantity?,weight?,properties?,description?}`
|
||
`POST /api/item/update` — `{id*, name?, category?, rarity?, quantity?, weight?, properties?, description?}` — partial, ownership checked. `''` for `quantity`/`weight` is ignored, like `/item/create`.
|
||
`POST /api/item/delete` — `{id}`
|
||
|
||
`GET /api/map/list?campaign=` → `{status:'ok',maps}`
|
||
`POST /api/map/create` — multipart (`image`) or JSON `{name*,campaign*,gridSize?,offsetX?,offsetY?,scale?}` → `{status:'ok',map}`
|
||
`POST /api/map/update` — `{id*, name?, gridSize?, offsetX?, offsetY?, scale?}`, partial, ownership checked. Send it as
|
||
multipart with an `image` field to replace the photo (multer reads the other fields from the form; JSON works too).
|
||
`POST /api/map/delete` — `{id}`
|
||
|
||
### 4.1 Foundry integration (actors, items)
|
||
|
||
`dragonroll-foundry/` holds the Foundry VTT module (`scripts/api.js`, loaded by `module.json`) and an
|
||
optional read-only snapshot bridge (`bridge/server.js`). The module talks to Dragonroll with a
|
||
per-campaign bearer token, **not** a Dragonroll login: `POST /api/foundry/link/complete` redeems a
|
||
pairing code, stores its hash on `Campaign.foundrySyncTokenHash` and hands the plain token to Foundry
|
||
once. Every sync route re-reads the campaign from that hash and rejects payloads whose `worldId` is
|
||
not `Campaign.foundryWorldId` (`syncCampaign` / `requestMatchesWorld`). CORS is opened for
|
||
`/api/foundry/sync*` and `/foundry/link/complete` in `src/index.js`, before the app-wide CORS.
|
||
`dragonroll-foundry/README.md` documents pairing, the bridge and its environment variables.
|
||
|
||
| Sync route (token) | Meaning |
|
||
|---|---|
|
||
| `POST /sync/snapshot` | `{worldId, actors[], items[], fullSync}` — upserts actors, world items and every item embedded in those actors; a `fullSync` also deletes actors/items that are gone |
|
||
| `POST /sync/item-snapshot` | `{worldId, items[]}` — live world-item edits, upsert only (never prunes) |
|
||
| `POST /sync/item-delete` | `{worldId, foundryItemId}` — a world item was deleted |
|
||
| `GET /sync/characters` | Actors the module applies back into Foundry |
|
||
| `GET /sync/items` | Items the module applies back into Foundry (creates world items for Dragonroll-authored ones) |
|
||
| `GET /sync/status` | The campaign a sync token belongs to; the module shows it in its **Dragonroll Pairing Status** setting and treats `unauthorized` as the campaign having unlinked the world |
|
||
| `POST /sync/map` / `POST /sync/map-item` | Store the id mapping after the module creates a document |
|
||
| `POST /sync/delete` | `{worldId, foundryActorId}` |
|
||
|
||
Rules worth knowing before editing this:
|
||
|
||
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index so local
|
||
documents can leave it unset). A document carrying the `dragonroll-foundry.actorId` /
|
||
`dragonroll-foundry.itemId` flag adopts the matching Dragonroll row.
|
||
- **Items are deduplicated by name.** Foundry keeps the same gear once per carrier, so one Dragonroll
|
||
`Item` per name: the first document to claim it keeps the mapping, later copies just return it.
|
||
`foundryNames` remembers Foundry's names so a Dragonroll rename does not resurrect a duplicate.
|
||
`services/item-foundry.js` returns `null` for non-gear types (spells, classes, feats, species…),
|
||
which the sync skips.
|
||
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events
|
||
overwrite. Item pruning requires the full snapshot, since only it sees world items and actor copies.
|
||
- **Autosync is a Foundry-side switch** (`autoSync` client setting, on by default): when off, the
|
||
module queues no CRUD push, runs no periodic reconcile and sends no startup snapshot; the actor
|
||
directory's `Dragonroll: Force Sync` entry still pushes the selected actors as an upsert
|
||
(`fullSync:false`, so it never prunes). The read-only bridge snapshot is not gated by it.
|
||
- **`pairingStatus` is a setting the module writes, not the GM**: the module settings sentence about
|
||
whether this world is connected comes from the stored sync token plus the answer from
|
||
`/sync/status` (checked at world start and every minute), and anything typed into it is replaced.
|
||
- `Actor.inventory` stays a flattened copy of the actor's embedded items; it is not linked to `Item`.
|
||
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only
|
||
bridge, only useful when `FOUNDRY_API_URL` is configured.
|
||
|
||
## 5. Frontend
|
||
|
||
```
|
||
frontend/
|
||
├── nuxt.config.ts css order (colors, fonts, main, callouts), runtimeConfig.public
|
||
│ {apiBaseUrl, gitCommit, gitTag, gitBranch, buildDate}, @nuxtjs/i18n module,
|
||
│ vite.optimizeDeps; git info harvested at build time via execSync
|
||
├── 18n.config.ts vue-i18n fallbackLocale 'en'
|
||
├── i18n/locales/ en/ es/ ca/ (+ empty en.json, es.json, ca.json for the nuxt module)
|
||
├── public/ img/ icons/{iconoir/{regular,solid},Pixelarticons,ui} sounds/ fonts/{5e,amiri,...}
|
||
│ → served at /img, /icons, /sounds, /fonts
|
||
└── app/ Nuxt 4 source root (`~/` and `@/` both alias here)
|
||
├── app.vue real entry: theme setup + start() boot logic + 5 managers
|
||
├── assets/css/ colors.scss (theme maps → CSS vars), fonts.scss (5e-style font families),
|
||
│ main.scss (globals, scrollbars, .icon), callouts.scss (Obsidian-like callouts)
|
||
├── components/
|
||
│ ├── managers/ WindowManager, ContentManager, ToastManager, TooltipManager, ContextMenuManager
|
||
│ ├── windows/ ExampleWindow (template to copy), Login, Register, MainMenu, Settings,
|
||
│ │ CreateCampaign, RenameNote, NewFolder + partials/{WindowHandle,
|
||
│ │ FixedBottomButtons, BigIconTemplate}
|
||
│ ├── partials/ ContentSidebar, NestedNoteList, CampaignEntry, EditUserPartial, Spinner,
|
||
│ │ VersionRender
|
||
│ ├── layouts/ IconButton, Dropdown, Tabs, ColorPicker (reusable UI atoms)
|
||
│ └── viewer/ TopBar, statusbar/{StatusBar,FetchStatus}, topbar/{TopSearchBar,SearchResult},
|
||
│ content/{Content,NoteContainer,Note}, map/MapViewerPane, widgets/{TableWidget,TestWidget,
|
||
│ inline/RollWidgetInline,display/RollWidgetDisplay}
|
||
├── composables/ useTheme.ts (theme+accent singletons, localStorage, data-* attrs),
|
||
│ useEmitter.ts (BROKEN, see §9)
|
||
├── plugins/ api.ts (inject runtimeConfig apiBaseUrl into the axios instance), i18n.ts
|
||
└── services/ plain ES modules holding reactive module state (the app has no store)
|
||
```
|
||
|
||
### 5.1 It is not a routed app
|
||
|
||
There is no `app/pages/`. `app/app.vue` renders a fixed shell of managers. "Screens" are either:
|
||
|
||
- **Windows** — floating, draggable/resizable overlays (login, main menu, settings…), or
|
||
- **Content** — the campaign workspace (`TopBar` + `ContentSidebar` + note column + `StatusBar`),
|
||
shown when `Campaign` state is non-null. The note column shows the open notes, or the map anchored
|
||
on it (`AnchorMap` / `ActivePane` in `services/Content.js`); the sidebar's notes and maps buttons
|
||
switch between the two while both keep their state, and `viewer/map/MapViewerPane.vue` renders the
|
||
map there and inside the `map_viewer` window (a detached anchored map).
|
||
|
||
Boot sequence (`app.vue` → `start()`):
|
||
|
||
```
|
||
GetUser() (JWT in localStorage, un-expired)?
|
||
├─ yes → RestoreCampaign() (localStorage.selectedCampaignId) → on failure open 'main_menu'
|
||
└─ no → HasAdmin() ? open 'login' : open 'register' {firstTime:true}
|
||
```
|
||
|
||
### 5.2 The window system (most important thing to understand)
|
||
|
||
`app/services/WindowDefinitions.js` is the **registry**: key = window type, value =
|
||
`{ title: 'i18n.key', component: () => import('~/components/windows/X.vue'), movable, close?, back?, ... }`.
|
||
Adding a window = add an entry here **and** a component in `app/components/windows/`.
|
||
|
||
`app/services/Windows.js` is the runtime. Module-level state: `windows = ref([])`, auto-incrementing
|
||
`currentId`, `currentIndex` z-index counter. Key exports:
|
||
|
||
`CreateWindow(type, data)` (one instance per type — duplicates are ignored),
|
||
`CreateChildWindow(parentId, type, data)` (child dies with parent), `ClearWindow({type}|{id})`
|
||
(recursive over `children`), `ClearAll()`, `GetWindowWithId(id)`, `GetFirstWindowId(type)`,
|
||
`CallWindow(id, callableName, arg)`, `SetSize/SetPosition/SetMinSize/SetMaxSize/SetResizable/
|
||
SetMovable/ResetPosition(id,'center')/SetOnTop/Top`, `getComponent(type)` (cached `defineAsyncComponent`),
|
||
and `SetupHandle(id, handleRef)` which wires raw DOM mouse listeners for drag/resize.
|
||
|
||
Contract a window component must fulfil (copy `ExampleWindow.vue`):
|
||
|
||
```vue
|
||
<script setup>
|
||
import { SetupHandle, SetSize, ResetPosition, Top } from '@/services/Windows';
|
||
import WindowHandle from './partials/WindowHandle.vue';
|
||
const handle = ref(null), wrapper = ref(null);
|
||
const props = defineProps(['data']); // 'data' = merged {type,id,...WindowDefinitions entry,...CreateWindow data}
|
||
const id = props.data.id;
|
||
onMounted(() => {
|
||
Top(wrapper); SetupHandle(id, handle);
|
||
SetSize(id, { width: 500, height: 380 }); ResetPosition(id, 'center');
|
||
});
|
||
</script>
|
||
<template>
|
||
<div class="window-wrapper" :id="'window-wrapper-' + id" ref="wrapper">
|
||
<WindowHandle :window="id" ref="handle"></WindowHandle>
|
||
<!-- body -->
|
||
</div>
|
||
</template>
|
||
```
|
||
|
||
DOM id conventions that `Windows.js`, `WindowHandle.vue` and drag/resize depend on — do not rename:
|
||
`window-wrapper-{id}`, `window-handle-{id}`, `window-resize-handle-{id}`, `context-menu`, `mouse-tooltip`.
|
||
|
||
`WindowHandle.vue` reads `title` (translated at mount via `$t`), `close` and `back` off the window
|
||
object, exposes `setupHandle()`, and plays `/sounds/close.wav` when closed.
|
||
|
||
### 5.3 Services (`app/services/`) — the state layer
|
||
|
||
Plain modules with module-scope `ref()`s imported directly. No DI, no Pinia. Singleton by import.
|
||
|
||
| Service | Provides |
|
||
|---|---|
|
||
| `Server.js` | axios instance (fallback baseURL `http://localhost:5000/api`), `initApi(baseURL)` called by `plugins/api.ts`, request interceptor adding `Authorization: Bearer <localStorage.token>`, `getBaseUrl()`. Default export is a factory: call `Server()` then `.get/.post`. |
|
||
| `User.js` | `UserStatus` ref, `GetUser()` (decodes JWT, auto-logout on `exp`), `SetUser(token)`, `LoadUser`, `LogoutUser`, `IsAdmin`, `HasAdmin()`, `GetUserSetting(key)` / `SetUserSetting(key,value)` (server-backed, in `User.settings`) |
|
||
| `Campaign.js` | `useCampaignService()` → `Campaign` (`useState('campaign')`), `SetCampaign(data)` (also writes `localStorage.selectedCampaignId`), `RestoreCampaign()` |
|
||
| `Content.js` | `ShowContent` ref (drives the campaign workspace: `ContentManager.vue` turns it on from a `watch(Campaign)`, `TopBar` off when leaving a campaign) and the anchored map: `ActivePane` (`'notes'`\|`'map'`), `AnchoredMap`, `SetActivePane`, `AnchorMap`, `ClearAnchoredMap` |
|
||
| `Emitter.js` | `export const emitter = mitt()` — the app-wide event bus |
|
||
| `Toaster.js` | `DisplayToast(color, text, duration)` → emits `toast`; `ToastManager.vue` renders it |
|
||
| `Tooltip.js` | `SetupTooltip()`, `AddTooltip(el, text, {max_width})` (stores on `el._dr_tooltip`), polled visibility via `elementsFromPoint` |
|
||
| `ContextMenu.js` | `SetupContextMenu()`, `AddContextMenu(el, items, {dropdown:true})`, `ShowContextMenu(items)`, `HideContextMenu()`. Items: `{name, icon?, action?, divider?}` or `{name, context:[...]}` for a submenu; built imperatively into `#context-menu` with `motion` animations |
|
||
| `Sound.js` | `AddSound(rootEl)` binds `/sounds/snap.wav` to every `.sound-click` inside `rootEl` |
|
||
| `Marker.js` | marked `Marked` instance + custom extensions, `ParseMarkdown(src)`, `GetWidget(kind,name)` (§5.4) |
|
||
| `ActionRegistry.js` | `register({id,label,description,execute,isActive?})`, `unregister`, `search(q)` (diacritic-insensitive, prefix-first sort), `execute(id,params)` — powers the command palette |
|
||
| `Windows.js` / `WindowDefinitions.js` | §5.2 |
|
||
| `widgets/DiceParser.js` | recursive-descent dice evaluator (§5.5) |
|
||
|
||
### 5.4 Markdown → Vue widgets
|
||
|
||
`Marker.js` registers three marked extensions:
|
||
|
||
| Syntax | Level | Output |
|
||
|---|---|---|
|
||
| `@name\n<content>\n@end` | block | `<div class="vue-component-display" data-component data-content>` |
|
||
| `@name[text]` | inline | `<span class="vue-component-inline" data-component data-content>` |
|
||
| `[[target]]` | inline | `<span class="vue-link" data-href>` (renders the literal text `Link`) |
|
||
|
||
`Note.vue` renders the HTML with `v-html`, then in a `setTimeout(...,0)` calls `mountComponents()`,
|
||
which `querySelectorAll('.vue-component-display'|'.vue-component-inline')` and mounts each node with a
|
||
**separate** `createApp(GetWidget(kind, el.dataset.component), { content: el.dataset.content })`.
|
||
Widgets are therefore isolated mini-apps: they receive only `content` (a string) and must not rely on
|
||
the parent app's provides/injection.
|
||
|
||
Registering a widget = add an entry to `widget_map` in `Marker.js`:
|
||
|
||
```js
|
||
const widget_map = {
|
||
inline: { roll: () => import("~/components/viewer/widgets/inline/RollWidgetInline.vue") },
|
||
display: { roll: () => import("~/components/viewer/widgets/display/RollWidgetDisplay.vue") },
|
||
};
|
||
```
|
||
|
||
`Note.vue` also: handles `Ctrl/Cmd+E` (toggle edit/preview, saves on exit) and `Ctrl/Cmd+S` (save via
|
||
`POST /note/update`), tracks dirty state (white dot in the vertical title strip), and wires
|
||
Obsidian-style collapsible callouts (`setupCallout()`/`toggleCallout()` + `callouts.scss`).
|
||
|
||
### 5.5 Dice grammar (`DiceParser.js`)
|
||
|
||
`parse(expr) -> { total, steps[] }`. Tokens: `\d*d\d+` with optional `adv|dis|kh<N>|kl<N>`, integers,
|
||
`+ - * / ( )`, unary minus. `adv`/`dis` roll 2dN and keep max/min; `kh`/`kl` keep highest/lowest N.
|
||
Division is `Math.floor`. Guards: count 1–1000, sides 2–10000. `steps` are `{type:'op'|'const'|'dice'}`
|
||
and `RollWidgetDisplay.vue` turns them into the visual breakdown (kept/dropped/max/min classes).
|
||
|
||
### 5.6 Event bus contract
|
||
|
||
Every listener in the app (there are only these six `emitter.on` call sites):
|
||
|
||
| Event | Payload | Listened by |
|
||
|---|---|---|
|
||
| `toast` | `{color,text,duration}` | `ToastManager.vue` |
|
||
| `push-note` | `{key,title,text,date}` | `NoteContainer.vue` |
|
||
| `close-note` | note key (string) | `NoteContainer.vue` (removes the note from the open column only) |
|
||
| `delete-note` | note key (string) | `NoteContainer.vue`, `ContentSidebar.vue`, `NestedNoteList.vue` (real deletion: closes the note **and** removes it from the sidebar) |
|
||
| `title-updated` | `{key,title}` | `Note.vue`, `NoteContainer.vue` |
|
||
| `status-bar-update` | `{text,icon}` | `FetchStatus.vue` |
|
||
|
||
Emitters: `Toaster.js` (`toast`), `ContentSidebar` / `TopSearchBar` (`push-note`), `Note.vue`
|
||
(`close-note` — the close button must not use `delete-note` or the sidebar entry disappears),
|
||
`NestedNoteList.vue` (`delete-note`, after `POST /note/delete`), `ContentSidebar` (`title-updated`),
|
||
`FetchStatus` (self-test emit).
|
||
|
||
**Orphan events** — emitted, never subscribed to anywhere (the matching handlers `handleNoteCreated` /
|
||
`handleNoteRenamed` exist in `ContentSidebar.vue` but were never wired with `emitter.on`; see §9.17):
|
||
|
||
| Event | Emitted by | Intended handler |
|
||
|---|---|---|
|
||
| `note-created` | `ContentSidebar.createNote`, `TopSearchBar` | `ContentSidebar.handleNoteCreated` (dead) |
|
||
| `note-renamed` | `RenameNoteWindow.vue` | `ContentSidebar.handleNoteRenamed` (dead) |
|
||
| `folder-saved` | `NewFolderWindow.vue` | none — sidebar refreshes only via `@reload-notes` from `NestedNoteList` |
|
||
|
||
So "create note" currently works because the sidebar mutates its own list, and folder changes need an
|
||
explicit `fetchCampaignNotes()`. If you rely on an event, check a listener exists.
|
||
|
||
Note object shape in the UI layer is `{ key, title, text, date }` (mapped from the API's
|
||
`{_id,title,content,date}`); convert at the boundary as `ContentSidebar.fetchCampaignNotes` does.
|
||
|
||
### 5.7 Theming, fonts, icons, sounds
|
||
|
||
- `useTheme.ts` owns `theme` (`'light'|'dark'`) and `accent` (`'katlum'`, type currently narrow) as
|
||
module singletons, persists to `localStorage`, and sets `data-theme` / `data-accent` on `<html>`.
|
||
`app.vue` calls `setupTheme()` then forces `setTheme('dark')` on mount.
|
||
- `colors.scss` holds Sass maps `dark`/`light` (and accents `katlum`/`solus`/`silang`) emitted as
|
||
**`--color-*` CSS variables**. Always style with `var(--color-...)` (`background`,
|
||
`window-background`, `button-hover`, `text`, `border`, `icon-invert`, …), never hardcode hex.
|
||
- Icons are inverted via `filter: invert(var(--color-icon-invert))` — white SVGs + `.icon` class.
|
||
Reference either as public assets (`/icons/iconoir/regular/xmark.svg`, `/icons/ui/...`,
|
||
`/icons/Pixelarticons/white/close.svg`) or from the `pixelarticons` npm package
|
||
(`import SearchIcon from 'pixelarticons/svg/search.svg'`).
|
||
- Fonts (`fonts.scss` + `public/fonts/5e`): `BookInsanityRemake` (body default), `MrEavesRemake`
|
||
(headings/window titles), `ScalySansRemake`, `NodestoCapsCondensed`, `SolberaImitationRemake`, etc.
|
||
- Sounds in `public/sounds/`: `snap.wav` (the `.sound-click` default), `close.wav`, `click.wav`,
|
||
`dice.wav`, `roll1.wav`, `roll2.wav`, `notify.wav`, `drums.wav`, `lock.wav`, `doors/`.
|
||
|
||
### 5.8 i18n
|
||
|
||
Locales: `en` (default), `es`, `ca`. Files live at `frontend/i18n/locales/<lang>/<namespace>.json`, and
|
||
`app/plugins/i18n.ts` globs them and nests each under its **filename** — so the key is
|
||
`<file>.<path>`, e.g. `i18n/locales/en/main-menu.json` → `$t('main-menu.create-campaign')`.
|
||
Namespaces in use: `general`, `login`, `register`, `main-menu`, `settings`, `windows`, `campaigns`
|
||
(`campaigns` currently only exists for `en`). Call it as `$t(...)` in templates or via `useI18n()` in
|
||
script; `WindowDefinitions` stores raw keys (`title: 'windows.login'`) and `WindowHandle` translates them.
|
||
|
||
**Adding a string = add it to all three locales** (`en`, `es`, `ca`); the Nuxt i18n module is also
|
||
configured (`nuxt.config.ts`, `langDir: 'locales/'`, `vueI18n: './i18n.config.ts'`) but its locale files
|
||
(`locales/en.json` etc.) are empty `{}` — the custom plugin is what components actually consume.
|
||
|
||
### 5.9 Obsidian plugin
|
||
|
||
`obsidian-plugin/` is a plain JavaScript community plugin; copy `main.js` and `manifest.json` into
|
||
`<vault>/.obsidian/plugins/dragonroll-sync/` (details in its README). It signs in through
|
||
`POST /api/user/login`, saves the 48-hour JWT token in plugin data, and does not save the password.
|
||
The user selects a campaign from `GET /api/campaign/list`.
|
||
|
||
- **Import or refresh campaign notes** reads `/api/note/list` plus `/api/note/subfolder/list` and
|
||
creates/updates Markdown files under `Dragonroll/<Campaign>/`, preserving Dragonroll's folder tree.
|
||
- **Push active note to Dragonroll** creates a root campaign note or updates the note linked in its
|
||
frontmatter.
|
||
- `dragonrollId`, `dragonrollCampaign`, and `dragonrollTitle` frontmatter properties link imported
|
||
notes. They are omitted from content sent to Dragonroll. Per-note signatures detect local edits;
|
||
imports preserve modified local files, and push is explicit.
|
||
|
||
The plugin uses Obsidian's `requestUrl` helper, so the request path does not depend on browser CORS.
|
||
|
||
## 6. Conventions
|
||
|
||
- **Backend**: CommonJS `require`/`module.exports`; files in `services/` are shared infra, `routes/`
|
||
are thin Express routers, `models/` one Mongoose schema per file exporting `mongoose.model(...)`.
|
||
Every handler is `try/catch` → `{status:'error', msg:'errors.internal'}` + `console.error`.
|
||
Route logic helpers (like `userOwnsCampaign`) are duplicated per router file today — match that
|
||
style unless you refactor both at once.
|
||
- **Frontend**: Vue 3 `<script setup>`; PascalCase exported functions in `services/` (`CreateWindow`,
|
||
`GetUser`), camelCase locals; PascalCase component filenames; `kebab-case` DOM ids that services
|
||
depend on. Both `~/` and `@/` aliases appear in imports (both resolve to `app/`) — follow whatever
|
||
the neighbouring file uses.
|
||
- Components talk to the API through `Server()` directly (there is no api-layer abstraction); `await`
|
||
or `.then` both appear.
|
||
- Code comments are mixed English and Catalan ("Moure aixo", "Programar un resizer mitjanament
|
||
competent") — do not "translate" unrelated comments while editing.
|
||
- No formatter: keep diffs minimal and local; the codebase is deliberately rough.
|
||
|
||
## 7. Recipes
|
||
|
||
**New API resource**: add `models/X.js`, `routes/x.js` (with `userOwnsCampaign`-style ownership checks
|
||
and the `{status,msg}` envelope), then `app.use('/api/x', require('./routes/x'))` in `src/index.js`
|
||
**after** the `checkAuth` line if it needs auth.
|
||
|
||
**New window**: entry in `WindowDefinitions.js` → component in `app/components/windows/` following
|
||
§5.2 → open with `CreateWindow('type', data)` or `CreateChildWindow(parentId, 'type', data)` → strings
|
||
in `i18n/locales/*/windows.json`.
|
||
|
||
**New markdown widget**: component in `app/components/viewer/widgets/{inline|display}/`, register in
|
||
`widget_map` in `Marker.js`, consume the `content` prop.
|
||
|
||
**New command-palette action**: `register({id,label,description,execute,isActive?})` from
|
||
`~/services/ActionRegistry` (see `registerCreateNoteAction` in `TopSearchBar.vue`); palette opens with
|
||
`Ctrl/Cmd+K` or `/`.
|
||
|
||
**New theme color**: add the key to *both* `dark` and `light` maps in `colors.scss`, use
|
||
`var(--color-<key>)`.
|
||
|
||
## 8. Port map
|
||
|
||
`frontend dev :3000` · `backend :5000` (hardcoded) · MongoDB `:27017` · nginx `:3000 → 80` inside
|
||
compose, proxying `/` → `frontend:3000`, `/api/` → `backend:5000`.
|
||
|
||
## 9. Known landmines (verified in code — do not "fix" silently, but never make them worse)
|
||
|
||
1. `README.md` tells you to run `./install.sh` and `./start.sh`; **neither script exists** in the repo.
|
||
2. `frontend/README.md` says the frontend is **React**. It is Nuxt/Vue 3.
|
||
3. `services/keys.js` ships a hardcoded JWT secret `"putyoursecrethere"`, used in prod.
|
||
4. `src/index.js` sets CORS `origin: 'http://localhost:3000'` only — the production origin
|
||
(`https://dragonroll.aranroig.com`) is not whitelisted; in production the nginx same-origin proxy
|
||
is what hides this.
|
||
5. `POST /api/user/register` responds `{status:'ok', code: setupCode}` but `setupCode` is not defined
|
||
in that scope → ReferenceError → caught → the first-run registration actually returns
|
||
`errors.internal`. Fix carefully: the register UI (`RegisterWindow.vue`) drives the first-admin flow.
|
||
6. `POST /api/note/delete` has **no ownership check** (any authenticated user can delete any note id).
|
||
`folder.js` and the other `note.js` handlers do check.
|
||
7. `composables/useEmitter.ts` reads `$emitter` from `useNuxtApp()`, but **no plugin provides it** —
|
||
always import `{ emitter }` from `~/services/Emitter` instead.
|
||
8. `ecosystem.config.js` runs `npm start` in both apps; neither package defines a `start` script → PM2
|
||
would fail. Compose/nginx is the real deployment path.
|
||
9. `/api/user/*` is entirely mounted before the JWT guard (see §4); new user routes are public unless
|
||
they call `passport.authenticate('jwt', {session:false})` inline.
|
||
10. `checkAuth` in `src/index.js` is assigned without `const` (implicit global).
|
||
11. `ClearAll()` in `Windows.js` iterates `Object.keys(windows)` (the ref object, not `.value`) — it
|
||
does not behave like the name suggests.
|
||
12. `GetWidget`/`getComponent` caches are process-global and never invalidated; new widget/window types
|
||
need a dev-server restart if HMR misbehaves.
|
||
13. `Windows.js` `SetupHandle` attaches `mousemove`/`mouseup` listeners on `document` for **every**
|
||
window and never removes them; they early-return on `win.movable` but still accumulate.
|
||
14. `Note.vue` mounts widgets with `createApp` and never unmounts them — leaked apps remain when note
|
||
content is re-rendered.
|
||
15. `User.js` (frontend) treats the JWT as the user cache: `settings` changes require
|
||
`SetUserSetting`/`GetUserSetting` round-trips, the token payload goes stale.
|
||
16. `.env.production` files (both apps) are committed and contain internal hosts.
|
||
17. `note-created`, `note-renamed` and `folder-saved` are emitted with **no subscribers**; the sidebar's
|
||
`handleNoteCreated` / `handleNoteRenamed` are unwired dead code (§5.6). The sidebar refreshes its
|
||
tree only on `campaignId` change, on mount, on the manual refresh button, or on `@reload-notes`
|
||
from `NestedNoteList.vue`.
|
||
18. `SetShowContent` (`services/Content.js`) and `services/middleware.js`'s `isAdmin` are exported /
|
||
imported but never used; `ContentManager.vue` never hides the workspace again once shown.
|