diff --git a/AGENTS.md b/AGENTS.md index 0e779a9a..f9e39339 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,604 +1,227 @@ # 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. +Orientation map, kept short on purpose. Read the file you are about to change: this tells you where to +look and what will bite you, it does not replace the code. Longer docs: `dragonroll-foundry/README.md`, +`discord-bot/README.md`, `obsidian-plugin/README.md`. ## 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: +Free/open-source helper for tabletop RPG campaigns (campaigns, markdown notes, folders, characters, +items, maps, dice widgets, sounds). -- `backend/` — Node + **Express 5** + **Mongoose 9** (MongoDB) REST API, JWT auth. CommonJS. -- `frontend/` — **Nuxt 4 / Vue 3** client (Composition API, ` - -``` +Events in use: `toast`, `push-note`, `close-note` (removes from the open column only), `delete-note` +(closes **and** removes from the sidebar, and drops map pins — the note's close button must not use it), +`title-updated`, `campaign-entry-created` / `campaign-entry-updated`, `note-created`, `note-renamed`, +`folder-saved`, `folder-deleted`, `status-bar-update`. Payloads are API documents; the UI note shape is +`{key, title, text, date}`, mapped at the boundary as `ContentSidebar.fetchCampaignNotes` does. Always +`import { emitter } from '~/services/Emitter'` — `composables/useEmitter.ts` is broken (§8). -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`. +### 5.6 Styling, i18n -`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. +`colors.scss` Sass maps (`dark`/`light`, accents `katlum`/`solus`/`silang`) become `--color-*` CSS +variables: always style with `var(--color-…)`, never hardcode hex, and add a new key to **both** maps. +`useTheme.ts` persists theme/accent and sets `data-theme`/`data-accent` on ``; `app.vue` forces +`setTheme('dark')`. Icons are white SVGs with `.icon` (inverted via `--color-icon-invert`), from +`/icons/...` or the `pixelarticons` package. Fonts (`fonts.scss`, 5e-style families) and sounds +(`/sounds/*.wav`) live in `public/`. -### 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 `, `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\n@end` | block | `
` | -| `@name[text]` | inline | `` | -| `[[target]]` | inline | `` (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|kl`, 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), `MapViewerPane.vue` (drops the markers pinned to that note) | -| `title-updated` | `{key,title}` | `Note.vue`, `NoteContainer.vue`, `MapViewerPane.vue` (relabels the map pins of that note) | -| `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 ``. - `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//.json`, and -`app/plugins/i18n.ts` globs them and nests each under its **filename** — so the key is -`.`, 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 -`/.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//`, 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. +i18n: `frontend/i18n/locales//.json` for `en` (default), `es`, `ca`; `plugins/i18n.ts` +nests each file under its filename, so the key is `.` (`$t('windows.login')`). **Add every +new string to all three locales.** Namespaces in use: `general`, `login`, `register`, `main-menu`, +`settings`, `windows`, `campaigns`, `link`, `foundry`, `discord`. ## 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 `