23 Commits

Author SHA1 Message Date
4faa585874 Merge pull request 'Fix #44: Sync item folders' (#46) from ai/issue-44 into master
Some checks failed
Test / test (push) Failing after 2s
Build and Deploy Nuxt / build (push) Successful in 1m6s
Reviewed-on: #46
2026-10-15 10:39:47 +00:00
69e0181b66 Merge branch 'master' into ai/issue-44
Some checks failed
Test / test (push) Failing after 2s
2026-10-15 10:39:41 +00:00
f29bbd45a3 Merge pull request 'Fix #42: Improve search' (#45) from ai/issue-42 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 54s
Reviewed-on: #45
2026-10-15 09:16:57 +00:00
5643031a70 Merge branch 'master' into ai/issue-42
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 09:16:51 +00:00
Gitea OpenCode Agent
1f9ab330b9 Fix issue #44: Sync item folders
Some checks failed
Test / test (push) Failing after 2s
2026-10-14 23:39:26 +00:00
Gitea OpenCode Agent
c6656fad3a Fix issue #42: Improve search
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 22:39:24 +00:00
c7d20dd1f7 Merge pull request 'Fix #41: Clicking button of actors on sidebar not change map or notes' (#43) from ai/issue-41 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 52s
Reviewed-on: #43
2026-10-14 22:33:19 +00:00
Gitea OpenCode Agent
8348936122 Fix issue #41: Clicking button of actors on sidebar not change map or notes
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 22:30:17 +00:00
4d532d10ae Merge pull request 'Fix #38: Implement tokens on maps' (#40) from ai/issue-38 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 1m11s
Reviewed-on: #40
2026-10-14 22:24:00 +00:00
af7bf9fa27 Merge branch 'master' into ai/issue-38
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 22:23:52 +00:00
3b897da390 Merge pull request 'Fix #35: Dragonroll frontend: item modifications' (#39) from ai/issue-35 into master
Some checks failed
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Has been cancelled
Reviewed-on: #39
2026-10-14 22:23:48 +00:00
278d25b294 Merge branch 'master' into ai/issue-35
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 22:23:41 +00:00
Gitea OpenCode Agent
d567b5d171 Fix issue #38: Implement tokens on maps
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 18:41:17 +00:00
Gitea OpenCode Agent
22c6403736 Fix issue #35: Dragonroll frontend: item modifications
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 18:08:19 +00:00
ef343dbdd8 Merge pull request 'Fix #34: Motion error' (#37) from ai/issue-34 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 57s
Reviewed-on: #37
2026-10-14 17:56:20 +00:00
909d403435 Merge branch 'master' into ai/issue-34
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 17:56:13 +00:00
Gitea OpenCode Agent
4505365f21 Fix issue #34: Motion error
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 17:52:37 +00:00
2c78ad039a Merge pull request 'Fix #33: Try to remove ecosystem' (#36) from ai/issue-33 into master
All checks were successful
Test / test (push) Successful in 1s
Build and Deploy Nuxt / build (push) Successful in 1m2s
Reviewed-on: #36
2026-10-14 17:52:18 +00:00
Gitea OpenCode Agent
1d3d978cda Fix issue #33: Try to remove ecosystem
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 17:50:31 +00:00
e11c6fc4f3 jkdsjkdjs
All checks were successful
Test / test (push) Successful in 1s
Build and Deploy Nuxt / build (push) Successful in 51s
2026-10-14 19:13:14 +02:00
8fa852d859 Merge pull request 'Fix #29: Migrate from npm to pnpm workspace' (#31) from ai/issue-29 into master
All checks were successful
Test / test (push) Successful in 1s
Build and Deploy Nuxt / build (push) Successful in 1m37s
Reviewed-on: #31
2026-10-14 17:09:51 +00:00
4e15b28bf6 Merge branch 'master' into ai/issue-29
All checks were successful
Test / test (push) Successful in 1s
2026-10-14 17:09:45 +00:00
Gitea OpenCode Agent
9820a375dc Fix issue #29: Migrate from npm to pnpm workspace
All checks were successful
Test / test (push) Successful in 2s
2026-10-14 17:01:02 +00:00
51 changed files with 12724 additions and 15345 deletions

9
.dockerignore Normal file
View File

@@ -0,0 +1,9 @@
# Images are built from the repository root (see .gitea/workflows/deploy.yml:
# `docker build -f <package>/Dockerfile .`), so this is the ignore file that counts.
.git
**/node_modules
**/*.log
**/.env
frontend/.nuxt
frontend/.output
frontend/dist

View File

@@ -32,24 +32,28 @@ jobs:
run: | run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.aranroig.com -u "${{ secrets.REGISTRY_USER }}" --password-stdin echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.aranroig.com -u "${{ secrets.REGISTRY_USER }}" --password-stdin
# pnpm workspace: every image is built from the repository root so the
# Dockerfiles can read pnpm-workspace.yaml, pnpm-lock.yaml and the other
# package.json files of the workspace.
- name: Build frontend - name: Build frontend
run: | run: |
docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-frontend:latest \ docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-frontend:latest \
--build-arg NUXT_PUBLIC_GIT_COMMIT=$(git rev-parse --short HEAD) \ --build-arg NUXT_PUBLIC_GIT_COMMIT=$(git rev-parse --short HEAD) \
--build-arg NUXT_PUBLIC_GIT_TAG=$(git describe --tags --abbrev=0) \ --build-arg NUXT_PUBLIC_GIT_TAG=$(git describe --tags --abbrev=0) \
--build-arg NUXT_PUBLIC_GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) \ --build-arg NUXT_PUBLIC_GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) \
./frontend -f ./frontend/Dockerfile .
docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-frontend:latest docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-frontend:latest
- name: Build backend - name: Build backend
run: | run: |
docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-backend:latest ./backend docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-backend:latest \
-f ./backend/Dockerfile .
docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-backend:latest docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-backend:latest
- name: Build discord bot - name: Build discord bot
run: | run: |
docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-discord-bot:latest \ docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-discord-bot:latest \
./discord-bot -f ./discord-bot/Dockerfile .
docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-discord-bot:latest docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-discord-bot:latest
- name: Copy files - name: Copy files

View File

@@ -28,4 +28,8 @@ jobs:
fi fi
- name: Run tests - name: Run tests
run: npm test # The repository is a pnpm workspace: run the root script through corepack,
# which picks the pnpm version pinned by "packageManager" in package.json.
run: corepack pnpm test
env:
COREPACK_ENABLE_DOWNLOAD_PROMPT: '0'

View File

@@ -14,7 +14,7 @@ items, maps, dice widgets, sounds).
- `discord-bot/` — Discord bot (slash commands) that talks to the backend with a shared service secret, no login. - `discord-bot/` — Discord bot (slash commands) that talks to the backend with a shared service secret, no login.
- `dragonroll-foundry/` — Foundry VTT module (`scripts/api.js`) + optional read-only snapshot bridge. - `dragonroll-foundry/` — Foundry VTT module (`scripts/api.js`) + optional read-only snapshot bridge.
- `obsidian-plugin/` — plain JavaScript Obsidian plugin that imports/pushes campaign notes. - `obsidian-plugin/` — plain JavaScript Obsidian plugin that imports/pushes campaign notes.
- `tests/` — `npm test` (`node --test`, no dependencies installed): Foundry sync toggle and pairing status, map pins, sidebar entries. - `tests/` — `npm test` (`node --test`, no dependencies installed): Foundry sync toggle and pairing status, map pins and tokens, sidebar entries.
No DB seeding, no migrations, no linter/formatter, no Pinia/Vuex. Git: default branch `master` on a No DB seeding, no migrations, no linter/formatter, no Pinia/Vuex. Git: default branch `master` on a
self-hosted Gitea; `.gitea/workflows/deploy.yml` builds and deploys Docker images on push to `master`, self-hosted Gitea; `.gitea/workflows/deploy.yml` builds and deploys Docker images on push to `master`,
@@ -22,16 +22,24 @@ self-hosted Gitea; `.gitea/workflows/deploy.yml` builds and deploys Docker image
## 2. Commands ## 2. Commands
`pnpm` comes from corepack (`packageManager` in `package.json`); `COREPACK_ENABLE_DOWNLOAD_PROMPT=0`
keeps corepack from asking in non-interactive shells.
```bash ```bash
npm install --prefix backend && npm install --prefix frontend # root `npm install` = concurrently only pnpm install # whole workspace, one lockfile (`-r` / `--filter <pkg>` for a single one)
npm run dev # backend :5000 + frontend :3000 + discord-bot + scripts/run-foundry.js pnpm dev # backend :5000 + frontend :3000 + discord-bot + scripts/run-foundry.js
npm --prefix backend run dev # or --prefix frontend run dev | build | preview pnpm dev:backend # or dev:frontend | dev:discord-bot
npm test pnpm --filter ./frontend run build # or preview
pnpm test
``` ```
No `start` script in backend/frontend and no lint command. Verification = run the dev server and No `start` script in backend/frontend and no lint command. Verification = run the dev server and
exercise the flow (`GET /api/test` returns a JSON hello). exercise the flow (`GET /api/test` returns a JSON hello).
There is no PM2 and no `ecosystem.config.js`: `pnpm dev` starts every dev process at the same time
through the workspace (`concurrently` only labels them and kills them together), and production runs
from the compose images (`CMD` of each `Dockerfile`).
Env: `backend/.env` (`PORT` is read but ignored, `DB_URI`), `frontend/.env` (`NUXT_PUBLIC_API_BASE_URL`), Env: `backend/.env` (`PORT` is read but ignored, `DB_URI`), `frontend/.env` (`NUXT_PUBLIC_API_BASE_URL`),
both gitignored; the `.env.production` files are committed. `backend/src/index.js` loads `.env.$NODE_ENV` both gitignored; the `.env.production` files are committed. `backend/src/index.js` loads `.env.$NODE_ENV`
when `NODE_ENV` is set, otherwise `.env`. The server always listens on **5000**. when `NODE_ENV` is set, otherwise `.env`. The server always listens on **5000**.
@@ -79,7 +87,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user
- `Folder` — `name*`, `campaign*`, `parentFolder` (null = root, self-ref), `color` - `Folder` — `name*`, `campaign*`, `parentFolder` (null = root, self-ref), `color`
- `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), plus free-form sheet fields (`type`, `species`, `className`, `level`, `abilityScores`, `armorClass`, `speed`, `proficiencies`, `traits`, `spells`, `image`) and `inventory[{name,quantity,weight}]` (flattened Foundry items, **not** `Item` docs) - `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), plus free-form sheet fields (`type`, `species`, `className`, `level`, `abilityScores`, `armorClass`, `speed`, `proficiencies`, `traits`, `spells`, `image`) and `inventory[{name,quantity,weight}]` (flattened Foundry items, **not** `Item` docs)
- `Item` — `name*`, `campaign*`, `foundryItemId` (unique per campaign), `foundryNames`, `category`, `rarity`, `quantity`, `weight`, `properties`, `description` - `Item` — `name*`, `campaign*`, `foundryItemId` (unique per campaign), `foundryNames`, `category`, `rarity`, `quantity`, `weight`, `properties`, `description`
- `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`), `gridSize`/`offsetX`/`offsetY`/`scale` (image px), `pins[{note→Note, x, y}]` (addressed by the pin's own `_id`) - `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`), `gridSize`/`offsetX`/`offsetY`/`scale` (image px), `pins[{note→Note, x, y}]` (addressed by the pin's own `_id`), `tokens[{actor→Actor, x, y}]` (the centre of the grid cell the token stands in, also addressed by its own `_id`)
- `ServiceLinkRequest` — the pending/completed service pairings of §4; `DiscordGuildLink` maps a Discord guild to the Dragonroll user who claimed it - `ServiceLinkRequest` — the pending/completed service pairings of §4; `DiscordGuildLink` maps a Discord guild to the Dragonroll user who claimed it
**API surface** (all under `/api`, all `{status,msg}`): **API surface** (all under `/api`, all `{status,msg}`):
@@ -90,7 +98,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user
- `folder` — `list`, `create`, `update`, `rename`, `delete` (recursive: inner notes go to `folder: null`, subfolders re-parent then delete) - `folder` — `list`, `create`, `update`, `rename`, `delete` (recursive: inner notes go to `folder: null`, subfolders re-parent then delete)
- `actor` — `list`, `create`, `update` (partial, ownership checked), `upload-image?actor=` (multipart), `delete` - `actor` — `list`, `create`, `update` (partial, ownership checked), `upload-image?actor=` (multipart), `delete`
- `item` — `list`, `create`, `update` (partial), `delete` - `item` — `list`, `create`, `update` (partial), `delete`
- `map` — `list`, `create` (multipart `image` or JSON), `update` (multipart to replace the photo), `delete`, `pin` (`{id,note,x,y}`, re-pinning moves the marker), `unpin` (`{id,pin}`) - `map` — `list`, `create` (multipart `image` or JSON), `update` (multipart to replace the photo), `delete`, `pin` (`{id,note,x,y}`, re-pinning moves the marker), `unpin` (`{id,pin}`), `place-token` (`{id,actor,x,y}`, snapped to a cell centre, re-placing moves the token), `remove-token` (`{id,token}`)
- `foundry` — read-only proxy over the bridge (`/world`, `/actors`, `/characters`, `/items`, `/actors/:id`, `/items/:id`, `/actors/:id/items`), needs `FOUNDRY_API_URL` - `foundry` — read-only proxy over the bridge (`/world`, `/actors`, `/characters`, `/items`, `/actors/:id`, `/items/:id`, `/actors/:id/items`), needs `FOUNDRY_API_URL`
## 4. Service integrations (Foundry, Discord, Obsidian) ## 4. Service integrations (Foundry, Discord, Obsidian)
@@ -130,7 +138,9 @@ campaign workspace (`TopBar` + `ContentSidebar` + note column + `StatusBar`), tu
(`ActivePane` / `AnchoredMap` / `AnchorMap` in `services/Content.js`); `viewer/map/MapViewerPane.vue` (`ActivePane` / `AnchoredMap` / `AnchorMap` in `services/Content.js`); `viewer/map/MapViewerPane.vue`
renders it both there and in the detached `map_viewer` window. Right-clicking that map pins a campaign renders it both there and in the detached `map_viewer` window. Right-clicking that map pins a campaign
note at the spot (`services/MapPins.js` translates image px ↔ screen), clicking the marker opens note at the spot (`services/MapPins.js` translates image px ↔ screen), clicking the marker opens
`pinned_note`. `pinned_note`. Dragging an actor row out of the sidebar onto the map makes it stand on that grid cell
as a token (`services/MapTokens.js` snaps to cell centres and sizes the token by its cell); the token
drags on with the pointer, steps over the grid with the arrow keys, and Delete takes it off.
### 5.2 The window system ### 5.2 The window system
@@ -154,7 +164,7 @@ DOM ids these services depend on — **do not rename**: `window-wrapper-{id}`, `
writes `localStorage.selectedCampaignId`, `RestoreCampaign`), `Content.js` (§5.1), `Emitter.js` writes `localStorage.selectedCampaignId`, `RestoreCampaign`), `Content.js` (§5.1), `Emitter.js`
(`mitt()` bus), `Toaster.js`, `Tooltip.js`, `ContextMenu.js`, `Sound.js` (`AddSound` binds (`mitt()` bus), `Toaster.js`, `Tooltip.js`, `ContextMenu.js`, `Sound.js` (`AddSound` binds
`snap.wav` to `.sound-click`), `Marker.js` (marked + widgets), `ActionRegistry.js` (command palette: `snap.wav` to `.sound-click`), `Marker.js` (marked + widgets), `ActionRegistry.js` (command palette:
`register/unregister/search/execute`), `Windows.js` / `WindowDefinitions.js`, `MapPins.js`, `register/unregister/search/execute`), `Windows.js` / `WindowDefinitions.js`, `MapPins.js`, `MapTokens.js`,
`widgets/DiceParser.js`. `widgets/DiceParser.js`.
### 5.4 Markdown → widgets ### 5.4 Markdown → widgets
@@ -214,7 +224,7 @@ new string to all three locales.** Namespaces in use: `general`, `login`, `regis
4. `POST /api/note/delete` has **no ownership check** (any authenticated user can delete any note id); the other `note.js` handlers and `folder.js` do check. 4. `POST /api/note/delete` has **no ownership check** (any authenticated user can delete any note id); the other `note.js` handlers and `folder.js` do check.
5. `/api/user/*` is mounted before the JWT guard: new routes there are public unless they authenticate inline (`/api/discord` is also before it, but every route there is gated by `requireBot`, the shared bot-secret header). `services/middleware.js`'s `isAdmin` is imported but applied to no route. 5. `/api/user/*` is mounted before the JWT guard: new routes there are public unless they authenticate inline (`/api/discord` is also before it, but every route there is gated by `requireBot`, the shared bot-secret header). `services/middleware.js`'s `isAdmin` is imported but applied to no route.
6. `composables/useEmitter.ts` reads `$emitter` from `useNuxtApp()` and no plugin provides it — use `~/services/Emitter`. 6. `composables/useEmitter.ts` reads `$emitter` from `useNuxtApp()` and no plugin provides it — use `~/services/Emitter`.
7. App-wide CORS only whitelists `http://localhost:3000`; `.env.production` files are committed with internal hosts; `ecosystem.config.js` runs `npm start`, which backend/frontend do not define (PM2 is dead, compose + nginx is the real deploy). 7. App-wide CORS only whitelists `http://localhost:3000`; `.env.production` files are committed with internal hosts.
8. `Windows.js`: `getComponent` caches `defineAsyncComponent` per type for the whole process (restart the dev server if a new window misbehaves), `SetupHandle` attaches `document` mouse listeners per window and never removes them, and `ClearAll()` iterates `Object.keys(windows)` instead of `windows.value`. 8. `Windows.js`: `getComponent` caches `defineAsyncComponent` per type for the whole process (restart the dev server if a new window misbehaves), `SetupHandle` attaches `document` mouse listeners per window and never removes them, and `ClearAll()` iterates `Object.keys(windows)` instead of `windows.value`.
9. The frontend treats the JWT as the user cache: `settings` changes need `GetUserSetting`/`SetUserSetting` round-trips, the token payload goes stale. 9. The frontend treats the JWT as the user cache: `settings` changes need `GetUserSetting`/`SetUserSetting` round-trips, the token payload goes stale.

View File

@@ -1,23 +1,29 @@
# Use official Node.js runtime # Use official Node.js runtime
FROM node:20-alpine FROM node:20-alpine
# pnpm is served by corepack and pinned by "packageManager" in the root package.json
RUN corepack enable
# Create app directory # Create app directory
WORKDIR /usr/src/app WORKDIR /usr/src/app
# Copy package files first (better caching) # Copy the workspace manifests first (better caching)
COPY package*.json ./ COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
COPY backend/package.json ./backend/
COPY frontend/package.json ./frontend/
COPY discord-bot/package.json ./discord-bot/
# Install dependencies # Install the production dependencies of the backend package
RUN npm ci --only=production RUN pnpm install --frozen-lockfile --prod --filter ./backend...
# Copy application source # Copy application source
COPY . . COPY backend ./backend
# Expose the app port
# EXPOSE 3000
# Environment variable # Environment variable
ENV NODE_ENV=production ENV NODE_ENV=production
# The app reads .env.production from its working directory
WORKDIR /usr/src/app/backend
# Start the application # Start the application
CMD ["node", "src/index.js"] CMD ["node", "src/index.js"]

1770
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,8 +12,20 @@ const FolderSchema = new Schema({
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: 'Folder' ref: 'Folder'
}, },
// Which campaign list a folder belongs to. Note folders are what this model has
// always held, and their rows carry no target at all, so everything reading the
// note tree asks for `{ target: { $ne: 'item' } }` and keeps finding them.
target: { type: String, enum: ['note', 'item'], default: 'note' },
// The Foundry item folder this row mirrors, set by the item sync only
// (see routes/foundry-link.js).
foundryFolderId: { type: String },
color: { type: String }, color: { type: String },
date: { type: Date, default: Date.now } date: { type: Date, default: Date.now }
}); });
FolderSchema.index(
{ campaign: 1, foundryFolderId: 1 },
{ unique: true, partialFilterExpression: { foundryFolderId: { $type: 'string' } } }
);
module.exports = mongoose.model('Folder', FolderSchema); module.exports = mongoose.model('Folder', FolderSchema);

View File

@@ -17,11 +17,24 @@ const ItemSchema = new Schema({
weight: { type: Number, min: 0 }, weight: { type: Number, min: 0 },
properties: { type: String, default: '' }, properties: { type: String, default: '' },
description: { type: String, default: '' }, description: { type: String, default: '' },
// Item icon: an uploaded filename served from /api/public, or a full URL
// (Foundry sends its own icon as one).
image: { type: String, default: '' },
// The icon Foundry last sent for this item, kept even after the user picks
// their own so Dragonroll can still offer Foundry's back.
foundryImage: { type: String, default: '' },
campaign: { campaign: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: 'Campaign', ref: 'Campaign',
required: true required: true
}, },
// The folder this item stands in: a Folder of the same campaign whose target is
// 'item' (null = the root of the item list).
folder: {
type: Schema.Types.ObjectId,
ref: 'Folder',
default: null
},
foundryItemId: { type: String }, foundryItemId: { type: String },
// Names Foundry uses for this item. Dragonroll may rename it, and the copies // Names Foundry uses for this item. Dragonroll may rename it, and the copies
// Foundry keeps sending still have to fold into this row instead of // Foundry keeps sending still have to fold into this row instead of

View File

@@ -19,6 +19,14 @@ const MapSchema = new Schema({
x: { type: Number, default: 0 }, x: { type: Number, default: 0 },
y: { type: Number, default: 0 } y: { type: Number, default: 0 }
}], }],
// Actors dragged onto the map to stand on it as tokens. x/y are image pixels of the centre of the
// token, like a pin, and the viewer keeps them snapped onto a grid cell so a token sits where the
// square it stands in is.
tokens: [{
actor: { type: Schema.Types.ObjectId, ref: 'Actor', required: true },
x: { type: Number, default: 0 },
y: { type: Number, default: 0 }
}],
campaign: { campaign: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: 'Campaign', ref: 'Campaign',

View File

@@ -5,6 +5,7 @@ const upload = require('../services/storage');
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor'); const Actor = require('../models/Actor');
const Map = require('../models/Map');
async function userOwnsCampaign(campaignId, userId) { async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
@@ -101,6 +102,11 @@ router.post('/delete', async (req, res) => {
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' }); if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(actor.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' }); if (!(await userOwnsCampaign(actor.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
await actor.deleteOne(); await actor.deleteOne();
// A token pointing at an actor that is gone would stand on the maps for nothing: drop those
// along with the actor, like the pins of a deleted note.
await Map.updateMany({ 'tokens.actor': id }, { $pull: { tokens: { actor: id } } });
res.json({ status: 'ok' }); res.json({ status: 'ok' });
} catch (err) { } catch (err) {
console.error(err); console.error(err);

View File

@@ -4,6 +4,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Folder = require('../models/Folder'); const Folder = require('../models/Folder');
const Note = require('../models/Note'); const Note = require('../models/Note');
const Item = require('../models/Item');
async function userOwnsCampaign(campaignId, userId) { async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
@@ -18,7 +19,7 @@ router.get('/list', async (req, res) => {
const hasAccess = await userOwnsCampaign(campaign, req.user.id); const hasAccess = await userOwnsCampaign(campaign, req.user.id);
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' }); if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const folders = await Folder.find({ campaign }) const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name date color') .select('_id name date color')
.sort({ date: -1 }) .sort({ date: -1 })
.lean(); .lean();
@@ -89,6 +90,12 @@ router.post('/delete', async (req, res) => {
{ folder: folderId }, { folder: folderId },
{ $set: { folder: null, date: Date.now() } } { $set: { folder: null, date: Date.now() } }
); );
// Item folders share this model: the items inside move to the root of
// the item list rather than point at a folder that is gone.
await Item.updateMany(
{ folder: folderId },
{ $set: { folder: null } }
);
await Folder.deleteOne({ _id: folderId }); await Folder.deleteOne({ _id: folderId });
for (const sub of subfolders) { for (const sub of subfolders) {
await moveRecursive(sub._id); await moveRecursive(sub._id);

View File

@@ -6,6 +6,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor'); const Actor = require('../models/Actor');
const Item = require('../models/Item'); const Item = require('../models/Item');
const Folder = require('../models/Folder');
const { foundryActorToCharacter } = require('../services/actor-foundry'); const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry'); const { foundryItemToItemData } = require('../services/item-foundry');
@@ -81,7 +82,7 @@ function snapshotItemSources(body) {
return sources; return sources;
} }
async function saveFoundryItem(campaign, source, fullSync = false) { async function saveFoundryItem(campaign, source, fullSync = false, folders = null) {
const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120); const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryItemToItemData(source || {}); const fields = foundryItemToItemData(source || {});
if (!foundryItemId || !fields) return null; if (!foundryItemId || !fields) return null;
@@ -109,22 +110,119 @@ async function saveFoundryItem(campaign, source, fullSync = false) {
item.foundryItemId = foundryItemId; item.foundryItemId = foundryItemId;
if (!fullSync || item.isNew) Object.assign(item, fields); if (!fullSync || item.isNew) Object.assign(item, fields);
// Foundry's own icon is kept on every save, not only when the edits above
// land: the item window offers it back after the user picked their own.
if (fields.image) item.foundryImage = fields.image;
if (!item.foundryNames.includes(fields.name)) { if (!item.foundryNames.includes(fields.name)) {
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES); item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
} }
// Which folder of the campaign's item tree the world says this item stands in.
// `undefined` means the push says nothing about folders — an item embedded in an
// actor, or a module that knows nothing about them — and the item stays where it
// is. The world owns the folder of its own directory, so a move lands on a full
// snapshot too: nothing on the Dragonroll side files items by hand.
const folder = resolveFoundryItemFolder(source, folders);
if (folder !== undefined) item.folder = folder;
await item.save(); await item.save();
return { foundryItemId, itemId: item.id }; return { foundryItemId, itemId: item.id };
} }
async function syncFoundryItems(campaign, sources, fullSync = false) { async function syncFoundryItems(campaign, sources, fullSync = false, folders = null) {
const items = []; const items = [];
for (const source of sources) { for (const source of sources) {
const mapping = await saveFoundryItem(campaign, source, fullSync); const mapping = await saveFoundryItem(campaign, source, fullSync, folders);
if (mapping) items.push(mapping); if (mapping) items.push(mapping);
} }
return items; return items;
} }
// --- Item folders ------------------------------------------------------------
// A Foundry world groups its item directory into folders; the campaign mirrors that
// tree as Folders of target 'item' so its item list reads like the world's. Every
// push from a module that knows about folders carries the whole world tree, and
// names the folder each world item it sends stands in. Items embedded in an actor
// say nothing: the folders they carry belong to that actor's own inventory, and
// Dragonroll keeps one item per piece of gear anyway.
// Parents before children, so a folder is mapped before the one nested in it.
// A folder whose parent is missing, or caught in a cycle, becomes a root.
function orderFoundryFolderSources(sources) {
const byId = new Map();
for (const source of sources) {
const id = String(source?.id || '').trim().slice(0, 120);
const name = String(source?.name || '').trim();
if (!id || !name) continue;
byId.set(id, { id, name, parent: String(source?.parent || '').trim().slice(0, 120) });
}
const ordered = [];
const placed = new Set();
const visiting = new Set();
function place(id) {
if (!byId.has(id) || placed.has(id) || visiting.has(id)) return;
visiting.add(id);
place(byId.get(id).parent);
visiting.delete(id);
placed.add(id);
ordered.push(byId.get(id));
}
for (const id of byId.keys()) place(id);
return ordered;
}
// The campaign folders mirroring the world's item folder tree, keyed by the Foundry
// folder id so pushing the same tree again neither doubles a folder nor loses the
// items filed in it. Rows the campaign made for its own items (no foundryFolderId)
// are left alone: the world does not know them.
async function syncFoundryItemFolders(campaign, folderSources) {
const folders = new Map();
for (const folder of await Folder.find({ campaign: campaign._id, target: 'item' })) {
if (folder.foundryFolderId) folders.set(String(folder.foundryFolderId), folder);
}
const ordered = orderFoundryFolderSources(folderSources);
const inTree = new Set(ordered.map((source) => source.id));
for (const source of ordered) {
let folder = folders.get(source.id);
if (!folder) {
folder = new Folder({
campaign: campaign._id,
target: 'item',
foundryFolderId: source.id,
name: source.name
});
}
// The world owns this tree, so unlike an item's fields a rename or a move
// lands whatever kind of push carried it: the whole tree arrives with each.
folder.name = source.name;
const parent = inTree.has(source.parent) ? folders.get(source.parent) : null;
folder.parentFolder = parent ? parent._id : null;
await folder.save();
folders.set(source.id, folder);
}
// Folders the world no longer has go with it, and the items standing in them
// move to the root instead of pointing at a folder that is not there.
const staleIds = [...folders.values()]
.filter((folder) => folder.foundryFolderId && !inTree.has(String(folder.foundryFolderId)))
.map((folder) => folder._id);
if (staleIds.length) {
await Item.updateMany({ campaign: campaign._id, folder: { $in: staleIds } }, { $set: { folder: null } });
await Folder.deleteMany({ campaign: campaign._id, _id: { $in: staleIds } });
}
return folders;
}
// The folder of a pushed item: undefined when the push says nothing about folders,
// null for the root of the item directory, and the campaign folder otherwise. An
// id the tree does not know puts the item at the root rather than nowhere.
function resolveFoundryItemFolder(source, folders) {
const foundryFolderId = source?.dragonroll?.folder;
if (!folders || typeof foundryFolderId !== 'string') return undefined;
return folders.get(foundryFolderId.trim())?._id || null;
}
// Linking a world to a campaign happens through the sign-up link every service // Linking a world to a campaign happens through the sign-up link every service
// uses (routes/service-link.js); what stays here is the sync that world keeps up // uses (routes/service-link.js); what stays here is the sync that world keeps up
// with the campaign once that link has handed it its token. // with the campaign once that link has handed it its token.
@@ -160,12 +258,16 @@ router.post('/sync/snapshot', async (req, res) => {
} }
const fullSync = req.body.fullSync === true; const fullSync = req.body.fullSync === true;
// A module that knows nothing about item folders sends neither the tree
// nor the folder of an item, and then nothing here touches the folders.
const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null;
const actors = []; const actors = [];
for (const source of actorSources || []) { for (const source of actorSources || []) {
const mapping = await saveFoundryActor(campaign, source, fullSync); const mapping = await saveFoundryActor(campaign, source, fullSync);
if (mapping) actors.push(mapping); if (mapping) actors.push(mapping);
} }
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync); const itemFolders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null;
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync, itemFolders);
if (fullSync && actorSources) { if (fullSync && actorSources) {
const currentIds = actorSources const currentIds = actorSources
@@ -194,17 +296,21 @@ router.post('/sync/snapshot', async (req, res) => {
} }
}); });
// Live Foundry item edits: upserts only, never prunes. Removing items that no // Live Foundry item edits: upserts only, never prunes items. Removing items that no
// longer exist is left to the full snapshot sent with the actors. // longer exist is left to the full snapshot sent with the actors. Item folders are
// the exception: every request carries the world's whole folder tree, so a folder
// the world dropped is dropped here too, and a push may carry folders only.
router.post('/sync/item-snapshot', async (req, res) => { router.post('/sync/item-snapshot', async (req, res) => {
try { try {
const campaign = await syncCampaign(req, res); const campaign = await syncCampaign(req, res);
if (!campaign) return; if (!campaign) return;
const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) { if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) {
return res.json({ status: 'error', msg: 'errors.missing-data' }); return res.json({ status: 'error', msg: 'errors.missing-data' });
} }
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items) }); const folders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null;
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items, false, folders) });
} catch (err) { } catch (err) {
console.error(err); console.error(err);
res.json({ status: 'error', msg: 'errors.internal' }); res.json({ status: 'error', msg: 'errors.internal' });

View File

@@ -1,14 +1,26 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const upload = require('../services/storage');
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Item = require('../models/Item'); const Item = require('../models/Item');
const Folder = require('../models/Folder');
async function userOwnsCampaign(campaignId, userId) { async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
return Boolean(campaign); return Boolean(campaign);
} }
// Folders the campaign's items are grouped into, in the shape the sidebar groups by
// (the world's own item folders arrive through the sync, see routes/foundry-link.js).
async function itemFolders(campaignId) {
return Folder.find({ campaign: campaignId, target: 'item' })
.select('_id name parentFolder date')
.sort({ date: -1 })
.lean();
}
router.get('/list', async (req, res) => { router.get('/list', async (req, res) => {
try { try {
const { campaign } = req.query; const { campaign } = req.query;
@@ -16,7 +28,7 @@ router.get('/list', async (req, res) => {
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' }); if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const items = await Item.find({ campaign }).sort({ name: 1 }).lean(); const items = await Item.find({ campaign }).sort({ name: 1 }).lean();
res.json({ status: 'ok', items }); res.json({ status: 'ok', items, folders: await itemFolders(campaign) });
} catch (err) { } catch (err) {
console.error(err); console.error(err);
res.json({ status: 'error', msg: 'errors.internal' }); res.json({ status: 'error', msg: 'errors.internal' });
@@ -44,7 +56,7 @@ router.post('/create', async (req, res) => {
router.post('/update', async (req, res) => { router.post('/update', async (req, res) => {
try { try {
const { id, name, category, rarity, quantity, weight, properties, description } = req.body; const { id, name, category, rarity, quantity, weight, properties, description, image } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' }); if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const item = await Item.findById(id); const item = await Item.findById(id);
@@ -58,6 +70,7 @@ router.post('/update', async (req, res) => {
if (weight !== undefined && weight !== '') item.weight = Number(weight); if (weight !== undefined && weight !== '') item.weight = Number(weight);
if (properties !== undefined) item.properties = properties; if (properties !== undefined) item.properties = properties;
if (description !== undefined) item.description = description; if (description !== undefined) item.description = description;
if (image !== undefined) item.image = String(image);
await item.save(); await item.save();
res.json({ status: 'ok', item }); res.json({ status: 'ok', item });
@@ -67,6 +80,25 @@ router.post('/update', async (req, res) => {
} }
}); });
// Upload item image post
router.post("/upload-image", upload.single("image"), async (req, res) => {
try {
const itemId = req.query.item || req.body.item;
if (!itemId || !req.file) return res.json({ status: 'error', msg: 'errors.missing-data' });
const item = await Item.findById(itemId);
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(item.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
item.image = req.file.filename;
await item.save();
res.json({ status: "ok", msg: "uploaded", item });
} catch (err) {
console.error(err);
res.json({ status: "error", msg: "internal" });
}
});
router.post('/delete', async (req, res) => { router.post('/delete', async (req, res) => {
try { try {
const { id } = req.body; const { id } = req.body;

View File

@@ -6,6 +6,7 @@ const upload = require('../services/storage');
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Map = require('../models/Map'); const Map = require('../models/Map');
const Note = require('../models/Note'); const Note = require('../models/Note');
const Actor = require('../models/Actor');
async function userOwnsCampaign(campaignId, userId) { async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
@@ -93,8 +94,9 @@ router.post('/delete', async (req, res) => {
} }
}); });
// A pin is a note placed at a spot of the map, in image pixels. Coordinates arrive as strings with // A pin is a note placed at a spot of the map, in image pixels, and so is the centre of a token.
// multipart requests and are never negative: the viewer clamps them to the image already. // Coordinates arrive as strings with multipart requests and are never negative: the viewer clamps
// them to the image already.
function toCoordinate(value) { function toCoordinate(value) {
const number = Number(value); const number = Number(value);
if (!Number.isFinite(number)) return 0; if (!Number.isFinite(number)) return 0;
@@ -152,4 +154,69 @@ router.post('/unpin', async (req, res) => {
} }
}); });
// A token is an actor standing on the map, at the middle of a grid cell. Anywhere it is dropped in a
// cell lands it in that cell, whatever the grid is drawn from: same rounding as the viewer does while
// it drags, so the token does not jump when the move is saved.
function toCellCoordinate(value, size, offset) {
const grid = Math.max(1, Number(size) || 50);
const origin = Number(offset) || 0;
const cell = Math.floor((toCoordinate(value) - origin) / grid);
return Math.max(0, Math.round(origin + (cell + 0.5) * grid));
}
router.post('/place-token', async (req, res) => {
try {
const { id, actor, x, y } = req.body;
if (!id || !actor) return res.json({ status: 'error', msg: 'errors.missing-data' });
const map = await Map.findById(id);
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
// Only an actor of the same campaign can stand on one of its maps.
const actorDoc = await Actor.findOne({ _id: actor, campaign: map.campaign }).select('_id').lean();
if (!actorDoc) return res.json({ status: 'error', msg: 'errors.notfound' });
// An actor stands on a map once: placing it again moves its token instead of adding a twin.
const token = map.tokens.find((current) => String(current.actor) === String(actor));
const spot = {
x: toCellCoordinate(x, map.gridSize, map.offsetX),
y: toCellCoordinate(y, map.gridSize, map.offsetY)
};
if (token) {
token.x = spot.x;
token.y = spot.y;
} else {
map.tokens.push({ actor, ...spot });
}
await map.save();
res.json({ status: 'ok', map });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/remove-token', async (req, res) => {
try {
const { id, token } = req.body;
if (!id || !token) return res.json({ status: 'error', msg: 'errors.missing-data' });
const map = await Map.findById(id);
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
// `_id` stays with the tokens that remain, the same way the pins are removed.
map.tokens = map.tokens
.filter((current) => String(current._id) !== String(token))
.map((current) => ({ _id: current._id, actor: current.actor, x: current.x, y: current.y }));
await map.save();
res.json({ status: 'ok', map });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
module.exports = router; module.exports = router;

View File

@@ -19,7 +19,9 @@ router.get('/list', async (req, res) => {
const hasAccess = await userOwnsCampaign(campaign, req.user.id); const hasAccess = await userOwnsCampaign(campaign, req.user.id);
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' }); if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const folders = await Folder.find({ campaign }) // The note tree only: item folders share this model and would otherwise
// turn up as empty folders between the notes.
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name parentFolder date color') .select('_id name parentFolder date color')
.sort({ date: -1 }) .sort({ date: -1 })
.lean(); .lean();
@@ -48,7 +50,7 @@ router.get('/subfolder/list', async (req, res) => {
const folderDoc = await Folder.findOne({ _id: folder, campaign }).lean(); const folderDoc = await Folder.findOne({ _id: folder, campaign }).lean();
if (!folderDoc) return res.json({ status: 'error', msg: 'errors.notfound' }); if (!folderDoc) return res.json({ status: 'error', msg: 'errors.notfound' });
const subfolders = await Folder.find({ campaign, parentFolder: folder }) const subfolders = await Folder.find({ campaign, parentFolder: folder, target: { $ne: 'item' } })
.select('_id name date color') .select('_id name date color')
.sort({ date: -1 }) .sort({ date: -1 })
.lean(); .lean();
@@ -80,7 +82,7 @@ router.get('/all', async (req, res) => {
.sort({ title: 1 }) .sort({ title: 1 })
.lean(); .lean();
const folders = await Folder.find({ campaign }) const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name parentFolder') .select('_id name parentFolder')
.lean(); .lean();

View File

@@ -101,7 +101,9 @@ function foundryItemToItemData(foundryItem) {
quantity: Math.max(1, Math.trunc(numberOr(system.quantity, 1))), quantity: Math.max(1, Math.trunc(numberOr(system.quantity, 1))),
weight: Math.max(0, numberOr(system.weight?.value ?? system.weight, 0)), weight: Math.max(0, numberOr(system.weight?.value ?? system.weight, 0)),
properties: foundryItemProperties(foundryItem), properties: foundryItemProperties(foundryItem),
description: plainText(system.description?.value ?? system.description) description: plainText(system.description?.value ?? system.description),
// The module sends Foundry's icon as an absolute URL, like actors do.
image: asText(foundryItem.img || foundryItem.image)
}; };
} }

View File

@@ -1,21 +1,30 @@
# Use official Node.js runtime # Use official Node.js runtime
FROM node:20-alpine FROM node:20-alpine
# pnpm is served by corepack and pinned by "packageManager" in the root package.json
RUN corepack enable
# Create app directory # Create app directory
WORKDIR /usr/src/app WORKDIR /usr/src/app
# Copy package files first (better caching) # Copy the workspace manifests first (better caching)
COPY package*.json ./ COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
COPY backend/package.json ./backend/
COPY frontend/package.json ./frontend/
COPY discord-bot/package.json ./discord-bot/
# Install dependencies # Install the production dependencies of the bot package
RUN npm ci --only=production RUN pnpm install --frozen-lockfile --prod --filter ./discord-bot...
# Copy application source # Copy application source
COPY . . COPY discord-bot ./discord-bot
# Environment variable # Environment variable
ENV NODE_ENV=production ENV NODE_ENV=production
# The bot reads .env from its working directory
WORKDIR /usr/src/app/discord-bot
# The bot only makes outbound connections (Discord gateway + Dragonroll API), # The bot only makes outbound connections (Discord gateway + Dragonroll API),
# it does not listen on a port. # it does not listen on a port.
# Start the application # Start the application

View File

@@ -1,327 +0,0 @@
{
"name": "dragonroll-discord-bot",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dragonroll-discord-bot",
"version": "1.0.0",
"dependencies": {
"discord.js": "^14.27.0",
"dotenv": "^17.2.3"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@discordjs/builders": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",
"integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/formatters": "^0.6.2",
"@discordjs/util": "^1.2.0",
"@sapphire/shapeshift": "^4.0.0",
"discord-api-types": "^0.38.40",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.4",
"tslib": "^2.6.3"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/collection": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",
"integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==",
"license": "Apache-2.0",
"engines": {
"node": ">=16.11.0"
}
},
"node_modules/@discordjs/formatters": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz",
"integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",
"license": "Apache-2.0",
"dependencies": {
"discord-api-types": "^0.38.33"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/rest": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz",
"integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/collection": "^2.1.1",
"@discordjs/util": "^1.2.0",
"@sapphire/async-queue": "^1.5.3",
"@sapphire/snowflake": "^3.5.5",
"@vladfrangu/async_event_emitter": "^2.4.6",
"discord-api-types": "^0.38.50",
"magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3",
"undici": "^6.27.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/rest/node_modules/@discordjs/collection": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/util": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",
"integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",
"license": "Apache-2.0",
"dependencies": {
"discord-api-types": "^0.38.33"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/ws": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz",
"integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/collection": "^2.1.0",
"@discordjs/rest": "^2.5.1",
"@discordjs/util": "^1.1.0",
"@sapphire/async-queue": "^1.5.2",
"@types/ws": "^8.5.10",
"@vladfrangu/async_event_emitter": "^2.2.4",
"discord-api-types": "^0.38.1",
"tslib": "^2.6.2",
"ws": "^8.17.0"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/ws/node_modules/@discordjs/collection": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@sapphire/async-queue": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",
"integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@sapphire/shapeshift": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",
"integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"lodash": "^4.17.21"
},
"engines": {
"node": ">=v16"
}
},
"node_modules/@sapphire/snowflake": {
"version": "3.5.5",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",
"integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@types/node": {
"version": "26.6.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/ws": {
"version": "8.18.2",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
"integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@vladfrangu/async_event_emitter": {
"version": "2.4.7",
"resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz",
"integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/discord-api-types": {
"version": "0.38.56",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.56.tgz",
"integrity": "sha512-Hti4RZsGvF5C7SM8rF2MDHtIm0Hyfrlk84GpEA29nj91tvVVMvX+oQSCodu10t2ZcjFGofq8TX0YyC04B2E69Q==",
"license": "MIT"
},
"node_modules/discord.js": {
"version": "14.27.0",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz",
"integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/builders": "^1.14.1",
"@discordjs/collection": "1.5.3",
"@discordjs/formatters": "^0.6.2",
"@discordjs/rest": "^2.6.2",
"@discordjs/util": "^1.2.0",
"@discordjs/ws": "^1.2.3",
"@sapphire/snowflake": "3.5.5",
"discord-api-types": "^0.38.49",
"fast-deep-equal": "3.1.3",
"lodash.snakecase": "4.1.1",
"magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3",
"undici": "^6.27.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/dotenv": {
"version": "17.4.2",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
"license": "MIT"
},
"node_modules/lodash.snakecase": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",
"license": "MIT"
},
"node_modules/magic-bytes.js": {
"version": "1.13.1",
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz",
"integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==",
"license": "MIT"
},
"node_modules/ts-mixer": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
"integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==",
"license": "MIT"
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/undici": {
"version": "6.29.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz",
"integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"license": "MIT"
},
"node_modules/ws": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}

View File

@@ -30,6 +30,8 @@ const queuedActorChanges = new Map();
let itemSyncTimeout; let itemSyncTimeout;
let itemSyncRunning = false; let itemSyncRunning = false;
let itemSyncErrorLogged = false; let itemSyncErrorLogged = false;
let folderSyncTimeout;
let folderSyncRunning = false;
const syncingItemIds = new Set(); const syncingItemIds = new Set();
const queuedItemChanges = new Map(); const queuedItemChanges = new Map();
@@ -436,6 +438,7 @@ function handleAutoSyncChange(value) {
if (value === false) { if (value === false) {
clearTimeout(actorSyncTimeout); clearTimeout(actorSyncTimeout);
clearTimeout(itemSyncTimeout); clearTimeout(itemSyncTimeout);
clearTimeout(folderSyncTimeout);
return; return;
} }
if (!game.user?.isGM || !getSyncToken()) return; if (!game.user?.isGM || !getSyncToken()) return;
@@ -444,6 +447,7 @@ function handleAutoSyncChange(value) {
// while autosync was off are pushed so this world's state wins over them. // while autosync was off are pushed so this world's state wins over them.
initializeCharacterSync(); initializeCharacterSync();
reconcileDragonrollItems(); reconcileDragonrollItems();
queueFoundryItemFolders(400);
if (queuedActorChanges.size) { if (queuedActorChanges.size) {
clearTimeout(actorSyncTimeout); clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 400); actorSyncTimeout = setTimeout(flushActorChanges, 400);
@@ -461,7 +465,9 @@ function dragonrollActorId(actor) {
function serializeFoundryActor(actor) { function serializeFoundryActor(actor) {
const data = { const data = {
...toPlainData(actor), ...toPlainData(actor),
items: actor.items?.contents?.map(toPlainData) || [], // Embedded items go through serializeFoundryItem so their icons become
// absolute URLs too: Dragonroll renders them outside of Foundry.
items: (actor.items?.contents?.map(serializeFoundryItem) || []).filter(Boolean),
}; };
if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) { if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) {
data.img = new URL(data.img, window.location.origin).toString(); data.img = new URL(data.img, window.location.origin).toString();
@@ -525,6 +531,8 @@ async function pushFoundryActors(actors, fullSync = false) {
// Dragonroll deduplicates by name, so sending the world directory next to // Dragonroll deduplicates by name, so sending the world directory next to
// the actor copies keeps a single Item per piece of gear. // the actor copies keeps a single Item per piece of gear.
items: getWorldItemSnapshots(), items: getWorldItemSnapshots(),
// The folder tree those world items stand in (see worldItemFolderSnapshots).
folders: worldItemFolderSnapshots(),
fullSync, fullSync,
}, token); }, token);
@@ -642,8 +650,60 @@ function serializeFoundryItem(item) {
return data; return data;
} }
// --- Item folders ------------------------------------------------------------
// Dragonroll mirrors the folders the world's item directory is grouped into, so its
// item list reads like Foundry's. `game.folders` also holds the folders an actor
// keeps for its own inventory: those hang off the actor instead of the world, and
// the campaign has no use for them, so only folders rooted in the world go over.
// The folder a folder is nested in, or null when it is not nested in a folder.
function itemFolderParent(folder) {
const parent = typeof folder.parent === "string" ? game.folders?.get(folder.parent) : folder.parent;
return parent?.documentName === "Folder" ? parent : null;
}
// Whether a folder belongs to the world's item directory: its whole ancestry has
// to be folders, ending in one that nothing is above.
function isWorldItemFolder(folder, seen = new Set()) {
if (folder.type !== "Item" || seen.has(folder.id)) return false;
seen.add(folder.id);
const rawParent = folder.parent;
const rawParentId = typeof rawParent === "string" ? rawParent : rawParent?.id;
if (!rawParentId) return true;
const parent = typeof rawParent === "string" ? game.folders?.get(rawParentId) : rawParent;
if (parent?.documentName !== "Folder") return false;
return isWorldItemFolder(parent, seen);
}
function worldItemFolderSnapshots() {
return (game.folders?.contents || [])
.filter((folder) => isWorldItemFolder(folder))
.map((folder) => ({ id: folder.id, name: folder.name, parent: itemFolderParent(folder)?.id || null }));
}
// A world item travels with the folder it stands in, so Dragonroll can file it the
// same way; `""` says the world keeps it at the root of the item directory. Items
// embedded in an actor use serializeFoundryItem instead: their folders are the
// actor's own, and the campaign's item list is deduplicated by name anyway.
function serializeFoundryWorldItem(item) {
const data = serializeFoundryItem(item);
if (!data) return null;
data.dragonroll = { ...data.dragonroll, folder: worldItemFolderId(item) };
return data;
}
// The folder id an item data carries is either the id or the Folder document
// itself, depending on the Foundry version.
function worldItemFolderId(item) {
const folder = item?.folder;
if (!folder) return "";
if (typeof folder === "string") return game.folders?.get(folder)?.documentName === "Folder" ? folder : "";
return folder.documentName === "Folder" ? String(folder.id || "") : "";
}
function getWorldItemSnapshots() { function getWorldItemSnapshots() {
return (game.items?.contents || []).map(serializeFoundryItem).filter(Boolean); return (game.items?.contents || []).map(serializeFoundryWorldItem).filter(Boolean);
} }
function dragonrollItemIdOf(item) { function dragonrollItemIdOf(item) {
@@ -691,7 +751,10 @@ async function pushFoundryItems(items) {
const result = await postDragonroll("foundry/sync/item-snapshot", { const result = await postDragonroll("foundry/sync/item-snapshot", {
worldId: game.world.id, worldId: game.world.id,
items: items.map(serializeFoundryItem).filter(Boolean), items: items.map(serializeFoundryWorldItem).filter(Boolean),
// The folder tree goes along, so an item that moved into or out of a folder
// arrives with the folder it names.
folders: worldItemFolderSnapshots(),
}, token); }, token);
await rememberItemMappings(result.items); await rememberItemMappings(result.items);
itemSyncErrorLogged = false; itemSyncErrorLogged = false;
@@ -715,6 +778,34 @@ function queueFoundryItemChange(kind, item) {
itemSyncTimeout = setTimeout(flushItemChanges, 400); itemSyncTimeout = setTimeout(flushItemChanges, 400);
} }
// A folder the GM made, renamed or nested has to reach the campaign even though no
// item changed, so the tree goes over on its own without pushing the items in it.
function queueFoundryItemFolders(delay = 400) {
clearTimeout(folderSyncTimeout);
folderSyncTimeout = setTimeout(pushFoundryItemFolders, delay);
}
async function pushFoundryItemFolders() {
// Autosync off: folder changes wait, like the item edits do.
if (!isAutoSyncEnabled()) return;
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || folderSyncRunning) return;
folderSyncRunning = true;
try {
await postDragonroll("foundry/sync/item-snapshot", {
worldId: game.world.id,
items: [],
folders: worldItemFolderSnapshots(),
}, token);
itemSyncErrorLogged = false;
} catch (error) {
reportItemSyncError(error);
queueFoundryItemFolders(5000);
} finally {
folderSyncRunning = false;
}
}
async function flushItemChanges() { async function flushItemChanges() {
// Autosync off: the queued edits wait here, like the actor changes do. // Autosync off: the queued edits wait here, like the actor changes do.
if (!isAutoSyncEnabled()) return; if (!isAutoSyncEnabled()) return;
@@ -760,6 +851,7 @@ function makeFoundryItemData(entry) {
const data = { const data = {
name: String(entry.name || "").trim(), name: String(entry.name || "").trim(),
type, type,
img: getDragonrollImageUrl(entry.image) || undefined,
system: { system: {
quantity: Number(entry.quantity) || 1, quantity: Number(entry.quantity) || 1,
weight: Number(entry.weight) || 0, weight: Number(entry.weight) || 0,
@@ -773,13 +865,18 @@ function makeFoundryItemData(entry) {
} }
function foundryItemUpdateData(entry) { function foundryItemUpdateData(entry) {
return { const updates = {
name: String(entry.name || "").trim(), name: String(entry.name || "").trim(),
"system.quantity": Number(entry.quantity) || 1, "system.quantity": Number(entry.quantity) || 1,
"system.weight": Number(entry.weight) || 0, "system.weight": Number(entry.weight) || 0,
"system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common", "system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common",
"system.description.value": entry.description || "", "system.description.value": entry.description || "",
}; };
// An icon the campaign picked in Dragonroll travels back to Foundry; no icon
// there means leave the world's own choice alone, not erase it.
const image = getDragonrollImageUrl(entry.image);
if (image) updates.img = image;
return updates;
} }
async function applyDragonrollItem(item, entry) { async function applyDragonrollItem(item, entry) {
@@ -1198,6 +1295,7 @@ Hooks.once("ready", () => {
for (const event of [ for (const event of [
"createActor", "updateActor", "deleteActor", "createActor", "updateActor", "deleteActor",
"createItem", "updateItem", "deleteItem", "createItem", "updateItem", "deleteItem",
"createFolder", "updateFolder", "deleteFolder",
]) { ]) {
Hooks.on(event, (document) => { Hooks.on(event, (document) => {
scheduleSnapshotSync(); scheduleSnapshotSync();
@@ -1207,6 +1305,12 @@ Hooks.once("ready", () => {
queueFoundryActorChange(isDelete ? "delete" : "upsert", document); queueFoundryActorChange(isDelete ? "delete" : "upsert", document);
return; return;
} }
// An item folder the GM made, renamed or nested changes the tree the campaign
// mirrors; nothing about the items themselves changed, so only the tree goes.
if (document.documentName === "Folder") {
if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders();
return;
}
if (document.documentName !== "Item") return; if (document.documentName !== "Item") return;
// Items embedded in an actor travel with that actor's snapshot: adding or // Items embedded in an actor travel with that actor's snapshot: adding or

View File

@@ -1,22 +0,0 @@
module.exports = {
apps: [
{
name: "backend",
cwd: "./backend",
script: "npm",
args: "start",
env: {
NODE_ENV: "production"
}
},
{
name: "frontend",
cwd: "./frontend",
script: "npm",
args: "start",
env: {
NODE_ENV: "production"
}
}
]
};

View File

@@ -1,6 +1,9 @@
# ---------- Build Stage ---------- # ---------- Build Stage ----------
FROM node:20-alpine AS builder FROM node:20-alpine AS builder
# pnpm is served by corepack and pinned by "packageManager" in the root package.json
RUN corepack enable
ARG NUXT_PUBLIC_GIT_COMMIT ARG NUXT_PUBLIC_GIT_COMMIT
ARG NUXT_PUBLIC_GIT_TAG ARG NUXT_PUBLIC_GIT_TAG
ARG NUXT_PUBLIC_GIT_BRANCH ARG NUXT_PUBLIC_GIT_BRANCH
@@ -11,18 +14,21 @@ ENV NUXT_PUBLIC_GIT_BRANCH=$NUXT_PUBLIC_GIT_BRANCH
WORKDIR /app WORKDIR /app
# Copy package files # Copy the workspace manifests (pnpm needs every package.json of the workspace)
COPY package*.json ./ COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
COPY backend/package.json ./backend/
COPY frontend/package.json ./frontend/
COPY discord-bot/package.json ./discord-bot/
# Install dependencies # Install the dependencies of the frontend package
RUN npm install RUN pnpm install --frozen-lockfile --filter ./frontend...
# Copy project files # Copy project files
ARG CACHEBUST=1 ARG CACHEBUST=1
COPY . . COPY frontend ./frontend
# Build the Nuxt app # Build the Nuxt app
RUN npm run build RUN pnpm --filter ./frontend run build
# ---------- Production Stage ---------- # ---------- Production Stage ----------
FROM node:20-alpine FROM node:20-alpine
@@ -30,7 +36,7 @@ FROM node:20-alpine
WORKDIR /app WORKDIR /app
# Copy built output # Copy built output
COPY --from=builder /app/.output ./.output COPY --from=builder /app/frontend/.output ./.output
# Expose Nuxt port # Expose Nuxt port
EXPOSE 3000 EXPOSE 3000

View File

@@ -5,9 +5,11 @@ import { useI18n } from 'vue-i18n';
import { useCampaignService } from '~/services/Campaign.js'; import { useCampaignService } from '~/services/Campaign.js';
import { AnchorMap, AnchoredMap, ClearAnchoredMap, SetActivePane } from '~/services/Content.js'; import { AnchorMap, AnchoredMap, ClearAnchoredMap, SetActivePane } from '~/services/Content.js';
import { emitter } from '~/services/Emitter'; import { emitter } from '~/services/Emitter';
import { BuildItemRows } from '~/services/ItemFolders';
import Server from '~/services/Server'; import Server from '~/services/Server';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows'; import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu'; import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
import { ACTOR_DRAG_TYPE } from '~/services/MapTokens';
import NestedNoteList from './NestedNoteList.vue'; import NestedNoteList from './NestedNoteList.vue';
const { Campaign } = useCampaignService(); const { Campaign } = useCampaignService();
@@ -16,6 +18,10 @@ const notes = ref([]);
const folders = ref([]); const folders = ref([]);
const actors = ref([]); const actors = ref([]);
const items = ref([]); const items = ref([]);
// The folders items stand in, and which of them the list has collapsed. Folders are
// open by default: a folder synced from Foundry should show its items, not hide them.
const itemFolders = ref([]);
const collapsedItemFolderIds = ref([]);
const maps = ref([]); const maps = ref([]);
const entryLists = { actor: actors, item: items, map: maps }; const entryLists = { actor: actors, item: items, map: maps };
const loadingNotes = ref(false); const loadingNotes = ref(false);
@@ -26,7 +32,6 @@ const sidebarCollapsed = ref(false);
const activeSection = ref('notes'); const activeSection = ref('notes');
const isDragOverSidebar = ref(false); const isDragOverSidebar = ref(false);
const expandedFolderIds = ref([]); const expandedFolderIds = ref([]);
const expandedEntryIds = ref([]);
const nestedNoteListRef = ref(null); const nestedNoteListRef = ref(null);
let entryRefreshInterval; let entryRefreshInterval;
@@ -44,6 +49,14 @@ async function handleSidebarDrop(event) {
} catch (e) {} } catch (e) {}
} }
// An actor row is dragged out of the sidebar onto a map, where it stands as a token. The map viewer
// reads that type back on its drop (see MapViewerPane.vue); a note drag carries 'text/plain'
// instead, so the two never land where the other belongs.
function startActorDrag(event, actor) {
event.dataTransfer.setData(ACTOR_DRAG_TYPE, String(actor._id));
event.dataTransfer.effectAllowed = 'copyMove';
}
function toggleExpandedFolder(folderId) { function toggleExpandedFolder(folderId) {
const arr = expandedFolderIds.value; const arr = expandedFolderIds.value;
const idx = arr.indexOf(folderId); const idx = arr.indexOf(folderId);
@@ -194,6 +207,9 @@ async function fetchCampaignEntries(entityType = activeSection.value, silent = f
const previousById = new Map(list.value.map((entry) => [entry._id, entry])); const previousById = new Map(list.value.map((entry) => [entry._id, entry]));
list.value = response.data[entityType] ?? []; list.value = response.data[entityType] ?? [];
// Items come with the folder tree their world synced over, so the list can
// group them the way the Foundry item directory does.
if (kind === 'item') itemFolders.value = response.data.folders ?? [];
// Tell open windows about Foundry changes landing behind them. // Tell open windows about Foundry changes landing behind them.
for (const entry of list.value) { for (const entry of list.value) {
const previous = previousById.get(entry._id); const previous = previousById.get(entry._id);
@@ -211,9 +227,11 @@ async function fetchCampaignEntries(entityType = activeSection.value, silent = f
function selectSection(section) { function selectSection(section) {
activeSection.value = section; activeSection.value = section;
if (isEntrySection(section)) fetchCampaignEntries(section); if (isEntrySection(section)) fetchCampaignEntries(section);
// The content area follows the sidebar: maps shows the anchored map, everything else the // Only the notes and maps buttons say something about the note container: they switch it between
// notes that are currently open. // the notes that are open and the anchored map. Actors and items open windows of their own, so
SetActivePane(section === 'maps' && AnchoredMap.value ? 'map' : 'notes'); // their buttons leave whatever the note container was showing untouched.
if (section === 'notes') SetActivePane('notes');
else if (section === 'maps' && AnchoredMap.value) SetActivePane('map');
} }
function createEntry(entityType) { function createEntry(entityType) {
@@ -287,12 +305,6 @@ function showEntryMenu(entry, entityType) {
ShowContextMenu(menuItems); ShowContextMenu(menuItems);
} }
function toggleEntryDetails(entryId) {
expandedEntryIds.value = expandedEntryIds.value.includes(entryId)
? expandedEntryIds.value.filter((id) => id !== entryId)
: [...expandedEntryIds.value, entryId];
}
async function openCharacterSheet(actor) { async function openCharacterSheet(actor) {
const existingWindowId = GetFirstWindowId('character_sheet'); const existingWindowId = GetFirstWindowId('character_sheet');
if (existingWindowId !== undefined) { if (existingWindowId !== undefined) {
@@ -302,6 +314,16 @@ async function openCharacterSheet(actor) {
CreateWindow('character_sheet', { actor }); CreateWindow('character_sheet', { actor });
} }
// Clicking an item opens its window, like a character does with its sheet.
async function openItemSheet(item) {
const existingWindowId = GetFirstWindowId('item_sheet');
if (existingWindowId !== undefined) {
ClearWindow({ id: existingWindowId });
await nextTick();
}
CreateWindow('item_sheet', { item });
}
// Maps are anchored on the note container instead of opening a window: the notes that were open // Maps are anchored on the note container instead of opening a window: the notes that were open
// stay open, and the sidebar's notes/maps buttons switch between the two. // stay open, and the sidebar's notes/maps buttons switch between the two.
function openMapViewer(map) { function openMapViewer(map) {
@@ -331,10 +353,27 @@ function toggleSidebar() {
const rootNotes = computed(() => notes.value.filter(n => !n._folder)); const rootNotes = computed(() => notes.value.filter(n => !n._folder));
// The items of the campaign, each under the folder it stands in (see
// services/ItemFolders.js). Without any folder this is the plain item list.
const itemRows = computed(() => BuildItemRows(items.value, itemFolders.value, collapsedItemFolderIds.value));
// Rows one step deeper per folder level; the sidebar list's own padding is the base.
function rowIndent(depth) {
return { paddingLeft: `${10 + depth * 14}px` };
}
function toggleItemFolder(folderId) {
collapsedItemFolderIds.value = collapsedItemFolderIds.value.includes(folderId)
? collapsedItemFolderIds.value.filter((id) => id !== folderId)
: [...collapsedItemFolderIds.value, folderId];
}
watch(campaignId, (newVal) => { watch(campaignId, (newVal) => {
if (newVal) { if (newVal) {
actors.value = []; actors.value = [];
items.value = []; items.value = [];
itemFolders.value = [];
collapsedItemFolderIds.value = [];
maps.value = []; maps.value = [];
ClearAnchoredMap(); ClearAnchoredMap();
fetchCampaignNotes(); fetchCampaignNotes();
@@ -344,6 +383,8 @@ watch(campaignId, (newVal) => {
folders.value = []; folders.value = [];
actors.value = []; actors.value = [];
items.value = []; items.value = [];
itemFolders.value = [];
collapsedItemFolderIds.value = [];
maps.value = []; maps.value = [];
notesError.value = ''; notesError.value = '';
entriesError.value = ''; entriesError.value = '';
@@ -488,7 +529,7 @@ onBeforeUnmount(() => {
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div> <div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
<div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div> <div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div>
<div v-else-if="actors.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-actors') }}</div> <div v-else-if="actors.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-actors') }}</div>
<div v-for="actor in actors" :key="actor._id" class="entity-entry" role="button" tabindex="0" @click="openCharacterSheet(actor)" @keydown.enter="openCharacterSheet(actor)" @keydown.space.prevent="openCharacterSheet(actor)" @contextmenu.prevent="showEntryMenu(actor, 'actor')"> <div v-for="actor in actors" :key="actor._id" class="entity-entry" role="button" tabindex="0" draggable="true" :title="t('campaigns.map.tokens.drag')" @click="openCharacterSheet(actor)" @keydown.enter="openCharacterSheet(actor)" @keydown.space.prevent="openCharacterSheet(actor)" @dragstart="startActorDrag($event, actor)" @contextmenu.prevent="showEntryMenu(actor, 'actor')">
<span class="entity-entry-name">{{ actor.name }}</span> <span class="entity-entry-name">{{ actor.name }}</span>
<span class="entity-entry-meta">{{ entrySummary(actor) }}</span> <span class="entity-entry-meta">{{ entrySummary(actor) }}</span>
</div> </div>
@@ -498,18 +539,33 @@ onBeforeUnmount(() => {
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div> <div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
<div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div> <div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div>
<div v-else-if="items.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div> <div v-else-if="items.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div>
<div v-for="item in items" :key="item._id" class="entity-entry" role="button" tabindex="0" :aria-expanded="expandedEntryIds.includes(item._id)" @click="toggleEntryDetails(item._id)" @keydown.enter="toggleEntryDetails(item._id)" @keydown.space.prevent="toggleEntryDetails(item._id)" @contextmenu.prevent="showEntryMenu(item, 'item')"> <template v-for="row in itemRows" :key="row.key">
<span class="entity-entry-name-row"> <button
<span class="entity-entry-name">{{ item.name }}</span> v-if="row.kind === 'folder'"
<span v-if="item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span> class="item-folder-entry"
</span> type="button"
<span class="entity-entry-meta">{{ itemSummary(item) }}</span> :style="rowIndent(row.depth)"
<template v-if="expandedEntryIds.includes(item._id)"> :aria-expanded="(!collapsedItemFolderIds.includes(row.folder._id)).toString()"
<span v-if="item.weight !== undefined" class="entity-entry-description">{{ item.weight }} lb</span> :aria-label="t('campaigns.item.folder-toggle', { name: row.folder.name })"
<span v-if="item.properties" class="entity-entry-description">{{ item.properties }}</span> @click="toggleItemFolder(row.folder._id)"
<span v-if="item.description" class="entity-entry-description">{{ item.description }}</span> >
</template> <img
</div> class="item-folder-arrow"
:src="collapsedItemFolderIds.includes(row.folder._id) ? '/icons/iconoir/regular/nav-arrow-right.svg' : '/icons/iconoir/regular/nav-arrow-down.svg'"
alt=""
aria-hidden="true"
>
<img class="item-folder-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
<span class="item-folder-name">{{ row.folder.name }}</span>
</button>
<div v-else class="entity-entry" :style="rowIndent(row.depth)" role="button" tabindex="0" @click="openItemSheet(row.item)" @keydown.enter="openItemSheet(row.item)" @keydown.space.prevent="openItemSheet(row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'item')">
<span class="entity-entry-name-row">
<span class="entity-entry-name">{{ row.item.name }}</span>
<span v-if="row.item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span>
</span>
<span class="entity-entry-meta">{{ itemSummary(row.item) }}</span>
</div>
</template>
</template> </template>
<template v-else> <template v-else>
@@ -675,6 +731,18 @@ onBeforeUnmount(() => {
} }
.entity-entry:hover { border-color: var(--color-border); background: var(--color-background-soft); } .entity-entry:hover { border-color: var(--color-border); background: var(--color-background-soft); }
.entity-entry:focus-visible { outline: 1px solid var(--color-link); } .entity-entry:focus-visible { outline: 1px solid var(--color-link); }
/* Item folders, synced from the linked world's item directory: the same row box as
an entry, since they share the sidebar list and its width rules. */
.item-folder-entry {
width: 100%; min-width: 0; box-sizing: border-box; margin: 0; padding: 8px 10px; border: 1px solid transparent;
border-radius: 8px; background: transparent; color: var(--color-text); text-align: left; display: flex;
align-items: center; gap: 6px; cursor: pointer; font: inherit;
}
.item-folder-entry:hover { background: var(--color-background-soft); }
.item-folder-entry:focus-visible { outline: 1px solid var(--color-link); }
.item-folder-arrow { width: 12px; height: 12px; flex: 0 0 12px; filter: invert(var(--color-icon-invert)); opacity: 0.6; }
.item-folder-icon { width: 15px; height: 15px; flex: 0 0 15px; filter: invert(var(--color-icon-invert)); }
.item-folder-name { min-width: 0; font-weight: bold; word-break: break-word; }
/* The map currently anchored on the note container. */ /* The map currently anchored on the note container. */
.entity-entry.anchored { border-color: var(--color-link); background: var(--color-background-soft); } .entity-entry.anchored { border-color: var(--color-link); background: var(--color-background-soft); }
.entity-entry-name-row { display: flex; align-items: baseline; gap: 6px; min-width: 0; } .entity-entry-name-row { display: flex; align-items: baseline; gap: 6px; min-width: 0; }

View File

@@ -4,6 +4,7 @@ import { useI18n } from 'vue-i18n';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '@/services/Windows'; import { ClearWindow, CreateWindow, GetFirstWindowId } from '@/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu'; import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
import { BuildNoteOptions, OptionLabel, ToImagePoint, ToScreenPoint } from '~/services/MapPins'; import { BuildNoteOptions, OptionLabel, ToImagePoint, ToScreenPoint } from '~/services/MapPins';
import { ActorDragId, CellCentre, IsActorDrag, MoveByCells, TokenSize } from '~/services/MapTokens';
import { DisplayToast } from '~/services/Toaster'; import { DisplayToast } from '~/services/Toaster';
import Server, { getBaseUrl } from '~/services/Server'; import Server, { getBaseUrl } from '~/services/Server';
import { emitter } from '~/services/Emitter'; import { emitter } from '~/services/Emitter';
@@ -227,27 +228,29 @@ function onPinContextMenu(pin) {
} }
async function savePin(noteId, spot) { async function savePin(noteId, spot) {
await updatePins('/map/pin', { id: map.value?._id, note: noteId, x: spot.x, y: spot.y }); await updateMap('/map/pin', { id: map.value?._id, note: noteId, x: spot.x, y: spot.y }, t('campaigns.map.pins.error'));
} }
async function removePin(pin) { async function removePin(pin) {
await updatePins('/map/unpin', { id: map.value?._id, pin: pin?._id }); await updateMap('/map/unpin', { id: map.value?._id, pin: pin?._id }, t('campaigns.map.pins.error'));
} }
// Both pin changes answer with the whole map, which keeps the sidebar entry and the anchored map in // Every pin and token change answers with the whole map, which keeps the sidebar entry and the
// step with what is on screen. // anchored map in step with what is on screen.
async function updatePins(route, body) { async function updateMap(route, body, failure) {
if (!body.id) return; if (!body.id) return false;
try { try {
const response = await Server().post(route, body); const response = await Server().post(route, body);
if (response.data.status !== 'ok') { if (response.data.status !== 'ok') {
DisplayToast('red', t('campaigns.map.pins.error'), 3000); DisplayToast('red', failure, 3000);
return; return false;
} }
map.value = { ...response.data.map }; map.value = { ...response.data.map };
emitter.emit('campaign-entry-updated', { entityType: 'map', entry: response.data.map }); emitter.emit('campaign-entry-updated', { entityType: 'map', entry: response.data.map });
return true;
} catch (error) { } catch (error) {
DisplayToast('red', t('campaigns.map.pins.error'), 3000); DisplayToast('red', failure, 3000);
return false;
} }
} }
@@ -274,27 +277,252 @@ function handlePinnedNoteRenamed({ key, title }) {
option.label = OptionLabel(option); option.label = OptionLabel(option);
} }
// --- Actors standing on the map as tokens ---
// An actor dragged out of the sidebar lands on the cell it is dropped on, and its token can then be
// dragged (or nudged with the arrow keys) from cell to cell. Tokens are kept in image pixels like the
// pins, so moving one only writes the middle of the cell it moved to.
const actors = ref([]);
const actorsById = computed(() => new Map(actors.value.map((actor) => [String(actor._id), actor])));
// Actor portraits that will not load (a Foundry path, say) fall back to the initials of the actor.
const brokenImages = ref(new Set());
const draggingActor = ref(false);
// The token a pointer is holding, and the cell centre it is held at: the move stays local until the
// pointer lets go, so a drag across the map is one save and not one per mouse move.
const movingToken = ref(null);
const grid = computed(() => ({
gridSize: map.value?.gridSize,
offsetX: map.value?.offsetX,
offsetY: map.value?.offsetY
}));
const tokens = computed(() => map.value?.tokens ?? []);
// The actor names and portraits the tokens are drawn from. An actor that is not (or no longer) in the
// campaign is not dropped from the map here: the backend does that, and the next read of the map is
// the one that shows it gone.
async function fetchTokenActors() {
if (!campaignId.value) {
actors.value = [];
return;
}
try {
const response = await Server().get('/actor/list', { params: { campaign: campaignId.value } });
actors.value = response.data.status === 'ok' ? (response.data.actors ?? []) : [];
} catch (error) {
actors.value = [];
}
}
function tokenActor(token) {
return actorsById.value.get(String(token?.actor)) ?? null;
}
function tokenLabel(token) {
return tokenActor(token)?.name ?? '';
}
function tokenInitials(token) {
const name = String(tokenLabel(token) ?? '').trim();
if (!name) return '?';
return name.split(/\s+/).slice(0, 2).map((part) => part.charAt(0).toUpperCase()).join('');
}
function tokenImage(token) {
const image = tokenActor(token)?.image;
if (!image || brokenImages.value.has(String(token?.actor))) return '';
return /^(https?:|data:|\/\/)/i.test(image) ? image : `${getBaseUrl()}/public/${image}`;
}
function onTokenImageError(token) {
brokenImages.value = new Set(brokenImages.value).add(String(token?.actor));
}
// Tokens are drawn in screen space too, but they are sized by the cell they stand on: unlike a pin, a
// token covers ground, so it grows and shrinks with the map.
function tokenStyle(token) {
const held = movingToken.value && String(movingToken.value.token?._id) === String(token?._id)
? movingToken.value
: token;
const point = ToScreenPoint(held, viewState());
const size = TokenSize(grid.value, zoom.value);
return {
left: `${point.x}px`,
top: `${point.y}px`,
width: `${size}px`,
height: `${size}px`,
// The initials of an actor with no portrait are read at the size of its token.
fontSize: `${Math.min(18, Math.max(9, Math.round(size * 0.36)))}px`
};
}
// The spot of the viewport a drop or a drag is over, in image pixels, or null outside of the image.
function imagePointOf(event) {
const bounds = viewport.value?.getBoundingClientRect();
if (!bounds) return null;
return ToImagePoint({ x: event.clientX - bounds.left, y: event.clientY - bounds.top }, viewState());
}
function onMapDragOver(event) {
if (!imageUrl.value || !IsActorDrag(event)) return;
// Saying so is what lets the browser deliver the drop at all.
event.preventDefault();
draggingActor.value = true;
}
function onMapDragLeave(event) {
// Crossing into a child of the viewport is not leaving it.
if (event.relatedTarget && viewport.value?.contains(event.relatedTarget)) return;
draggingActor.value = false;
}
async function onMapDrop(event) {
draggingActor.value = false;
const actorId = ActorDragId(event);
if (!actorId || !imageUrl.value || !map.value?._id) return;
const spot = imagePointOf(event);
if (!spot) return;
await placeToken(actorId, spot);
}
// An actor stands on the map once: dropping it again on a map it already occupies moves it there, the
// same way re-pinning a note moves its marker.
async function placeToken(actorId, spot) {
const centre = CellCentre(spot, grid.value);
if (!centre) return false;
return updateMap('/map/place-token', {
id: map.value?._id, actor: actorId, x: centre.x, y: centre.y
}, t('campaigns.map.tokens.error'));
}
async function removeToken(token) {
await updateMap('/map/remove-token', { id: map.value?._id, token: token?._id }, t('campaigns.map.tokens.error'));
}
let tokenPointerId = null;
function onTokenPointerDown(event, token) {
// The token is what is being held here: the map must not start panning under the pointer.
event.stopPropagation();
if (event.button !== 0) return;
tokenPointerId = event.pointerId;
event.currentTarget.setPointerCapture?.(event.pointerId);
movingToken.value = { token: { ...token }, x: Number(token.x) || 0, y: Number(token.y) || 0 };
}
function onTokenPointerMove(event) {
if (!movingToken.value || event.pointerId !== tokenPointerId) return;
const spot = imagePointOf(event);
// Dragged off the image, the token keeps the cell it had: an actor is never lost over the edge.
if (!spot) return;
const centre = CellCentre(spot, grid.value);
if (!centre) return;
movingToken.value = { ...movingToken.value, x: centre.x, y: centre.y };
}
async function onTokenPointerUp(event) {
if (!movingToken.value || event.pointerId !== tokenPointerId) return;
const { token, x, y } = movingToken.value;
tokenPointerId = null;
movingToken.value = null;
event.currentTarget?.releasePointerCapture?.(event.pointerId);
if (x === Number(token.x) && y === Number(token.y)) return;
await placeToken(token.actor, { x, y });
}
const CELL_STEPS = {
ArrowLeft: [-1, 0],
ArrowRight: [1, 0],
ArrowUp: [0, -1],
ArrowDown: [0, 1]
};
// A focused token answers to the keyboard too: arrows walk it over the grid, Delete takes it off.
async function onTokenKeydown(event, token) {
const step = CELL_STEPS[event.key];
if (step) {
event.preventDefault();
const centre = MoveByCells(token, grid.value, step[0], step[1]);
if (centre) await placeToken(token.actor, centre);
return;
}
if (event.key === 'Delete' || event.key === 'Backspace') {
event.preventDefault();
await removeToken(token);
}
}
function onTokenContextMenu(token) {
const actor = tokenActor(token);
const menuItems = [];
if (actor) {
menuItems.push({
name: t('campaigns.map.tokens.open'),
icon: '/icons/iconoir/regular/user.svg',
action: () => { HideContextMenu(); openActorSheet(actor); }
});
menuItems.push({ divider: true });
}
menuItems.push({
name: t('campaigns.map.tokens.remove'),
icon: '/icons/iconoir/regular/xmark-circle.svg',
action: () => { HideContextMenu(); removeToken(token); }
});
ShowContextMenu(menuItems);
}
async function openActorSheet(actor) {
// One sheet at a time, like the sidebar opens it.
const existingWindowId = GetFirstWindowId('character_sheet');
if (existingWindowId !== undefined) ClearWindow({ id: existingWindowId });
await nextTick();
CreateWindow('character_sheet', { actor });
}
function handleActorEntry({ entityType, entry }) {
if (entityType !== 'actor' || !entry?._id) return;
if (entry.campaign && String(entry.campaign) !== String(campaignId.value)) return;
actors.value = [entry, ...actors.value.filter((current) => String(current._id) !== String(entry._id))];
}
// A different map was anchored while this pane was already mounted. // A different map was anchored while this pane was already mounted.
watch(() => props.map, (incoming, previous) => { watch(() => props.map, (incoming, previous) => {
if (incoming === previous) return; if (incoming === previous) return;
map.value = incoming ? { ...incoming } : null; map.value = incoming ? { ...incoming } : null;
imageSize.value = { width: 0, height: 0 }; imageSize.value = { width: 0, height: 0 };
movingToken.value = null;
draggingActor.value = false;
}); });
watch(campaignId, () => { watch(campaignId, () => {
noteOptions.value = []; noteOptions.value = [];
fetchPinnableNotes(); fetchPinnableNotes();
actors.value = [];
fetchTokenActors();
}); });
onMounted(() => { onMounted(() => {
emitter.on('campaign-entry-updated', handleMapUpdated); emitter.on('campaign-entry-updated', handleMapUpdated);
emitter.on('campaign-entry-created', handleActorEntry);
emitter.on('campaign-entry-updated', handleActorEntry);
emitter.on('delete-note', handlePinnedNoteDeleted); emitter.on('delete-note', handlePinnedNoteDeleted);
emitter.on('title-updated', handlePinnedNoteRenamed); emitter.on('title-updated', handlePinnedNoteRenamed);
fetchPinnableNotes(); fetchPinnableNotes();
fetchTokenActors();
}); });
onBeforeUnmount(() => { onBeforeUnmount(() => {
emitter.off('campaign-entry-updated', handleMapUpdated); emitter.off('campaign-entry-updated', handleMapUpdated);
emitter.off('campaign-entry-created', handleActorEntry);
emitter.off('campaign-entry-updated', handleActorEntry);
emitter.off('delete-note', handlePinnedNoteDeleted); emitter.off('delete-note', handlePinnedNoteDeleted);
emitter.off('title-updated', handlePinnedNoteRenamed); emitter.off('title-updated', handlePinnedNoteRenamed);
}); });
@@ -342,6 +570,9 @@ onBeforeUnmount(() => {
@pointerup="onPointerUp" @pointerup="onPointerUp"
@pointercancel="onPointerUp" @pointercancel="onPointerUp"
@contextmenu.prevent="onMapContextMenu" @contextmenu.prevent="onMapContextMenu"
@dragover="onMapDragOver"
@dragleave="onMapDragLeave"
@drop.prevent="onMapDrop"
> >
<template v-if="imageUrl"> <template v-if="imageUrl">
<img class="map-image" :src="imageUrl" :style="stageStyle" :alt="map?.name" draggable="false" @load="onImageLoaded"> <img class="map-image" :src="imageUrl" :style="stageStyle" :alt="map?.name" draggable="false" @load="onImageLoaded">
@@ -363,6 +594,30 @@ onBeforeUnmount(() => {
<span class="pin-label">{{ pinLabel(pin) }}</span> <span class="pin-label">{{ pinLabel(pin) }}</span>
</button> </button>
</div> </div>
<div class="map-tokens">
<button
v-for="token in tokens"
:key="token._id"
class="map-token"
:class="{ moving: movingToken && String(movingToken.token?._id) === String(token._id) }"
type="button"
:style="tokenStyle(token)"
:title="tokenLabel(token) || $t('campaigns.map.tokens.token')"
:aria-label="tokenLabel(token) || $t('campaigns.map.tokens.token')"
draggable="false"
@pointerdown="onTokenPointerDown($event, token)"
@pointermove="onTokenPointerMove"
@pointerup="onTokenPointerUp"
@pointercancel="onTokenPointerUp"
@contextmenu.stop.prevent="onTokenContextMenu(token)"
@keydown="onTokenKeydown($event, token)"
>
<span class="token-initials" aria-hidden="true">{{ tokenInitials(token) }}</span>
<img v-if="tokenImage(token)" class="token-image" :src="tokenImage(token)" alt="" draggable="false" @error="onTokenImageError(token)">
<span class="token-label">{{ tokenLabel(token) }}</span>
</button>
</div>
<div v-if="draggingActor" class="map-drop-hint">{{ $t('campaigns.map.tokens.drop-hint') }}</div>
</template> </template>
<div v-else class="map-empty"> <div v-else class="map-empty">
{{ $t('campaigns.map.no-image') }} {{ $t('campaigns.map.no-image') }}
@@ -404,6 +659,35 @@ onBeforeUnmount(() => {
/* The note's name only when it is asked for: a map full of labels is a map nobody can read. */ /* The note's name only when it is asked for: a map full of labels is a map nobody can read. */
.pin-label { display: none; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .pin-label { display: none; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.map-pin:hover .pin-label, .map-pin:focus-visible .pin-label { display: inline; } .map-pin:hover .pin-label, .map-pin:focus-visible .pin-label { display: inline; }
/* Tokens are the actors standing on the map: drawn in screen space like the pins, but sized by the
grid cell they occupy, so a token covers its square whatever the zoom is (see TokenSize). */
.map-tokens { position: absolute; inset: 0; pointer-events: none; }
.map-token {
position: absolute; transform: translate(-50%, -50%); pointer-events: auto;
display: flex; align-items: center; justify-content: center; margin: 0; padding: 0;
border: 2px solid var(--color-link); border-radius: 50%;
background: var(--color-background-soft); color: var(--color-text);
cursor: grab; user-select: none; box-shadow: 0px 0px 6px -1px rgba(0,0,0,0.55);
}
.map-token:hover { border-color: var(--color-text); }
.map-token:focus-visible { outline: 1px solid var(--color-link); outline-offset: 2px; }
.map-token.moving { cursor: grabbing; }
.token-image { position: absolute; inset: 0; box-sizing: border-box; width: 100%; height: 100%; object-fit: cover; border-radius: 50%; }
/* No portrait (or one that will not load): the token shows the initials of its actor instead. */
.token-initials { opacity: .8; white-space: nowrap; }
.token-label {
display: none; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); margin-top: 3px;
max-width: 160px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-size: 11px; text-shadow: 0px 0px 4px rgba(0,0,0,0.8);
}
.map-token:hover .token-label, .map-token:focus-visible .token-label { display: block; }
/* Shown while an actor is carried over the map from the sidebar, so the spot to let go of it has. */
.map-drop-hint {
position: absolute; top: 10px; left: 50%; transform: translateX(-50%);
padding: 5px 10px; border: 1px dashed var(--color-link); border-radius: 7px;
background: var(--color-background-soft); color: var(--color-text); font-size: 12px;
pointer-events: none; box-shadow: 0px 0px 6px -1px rgba(0,0,0,0.55);
}
.map-empty { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; font-size: 13px; opacity: .8; } .map-empty { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; font-size: 13px; opacity: .8; }
.map-edit { border: 1px solid var(--color-border); border-radius: 7px; padding: 6px 11px; background: var(--color-background-soft); color: var(--color-text); font-size: 12px; cursor: pointer; } .map-edit { border: 1px solid var(--color-border); border-radius: 7px; padding: 6px 11px; background: var(--color-background-soft); color: var(--color-text); font-size: 12px; cursor: pointer; }
.map-edit:hover { background: var(--color-button-hover); } .map-edit:hover { background: var(--color-button-hover); }

View File

@@ -1,5 +1,5 @@
<script setup> <script setup>
defineProps({ const props = defineProps({
title: { type: String, default: '' }, title: { type: String, default: '' },
subtitle: { type: String, default: '' }, subtitle: { type: String, default: '' },
link: { type: String, default: '' }, link: { type: String, default: '' },

View File

@@ -1,24 +1,42 @@
<script setup> <script setup>
import { ref, onMounted, onUnmounted } from 'vue'; import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import SearchIcon from 'pixelarticons/svg/search.svg' import SearchIcon from 'pixelarticons/svg/search.svg'
import PlusIcon from 'pixelarticons/svg/plus.svg' import PlusIcon from 'pixelarticons/svg/plus.svg'
import NoteSearchResult from './SearchResult.vue'; import NoteSearchResult from './SearchResult.vue';
import Server from '~/services/Server'; import Server from '~/services/Server';
import { emitter } from '~/services/Emitter'; import { emitter } from '~/services/Emitter';
import { CreateWindow } from '~/services/Windows'; import { AnchorMap } from '~/services/Content.js';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { register, search as searchActions, execute as executeAction } from '~/services/ActionRegistry'; import { register, search as searchActions, execute as executeAction } from '~/services/ActionRegistry';
import { useCampaignService } from '~/services/Campaign.js'; import { useCampaignService } from '~/services/Campaign.js';
const { Campaign } = useCampaignService(); const { Campaign } = useCampaignService();
const { t } = useI18n();
const inputText = ref(''); const inputText = ref('');
// Everything the palette searches: the campaign's notes, actors, items and maps.
const notes = ref([]); const notes = ref([]);
const actors = ref([]);
const items = ref([]);
const maps = ref([]);
const showResults = ref(false); const showResults = ref(false);
const selectedIndex = ref(-1); const selectedIndex = ref(-1);
const focusInput = ref(null); const focusInput = ref(null);
const campaignId = computed(() => Campaign.value?._id ?? Campaign.value?.id ?? null);
// The lists belong to one campaign; when another one opens they are dropped and refetched.
watch(campaignId, () => {
notes.value = [];
actors.value = [];
items.value = [];
maps.value = [];
});
// ---- Keyboard shortcut to open search ---- // ---- Keyboard shortcut to open search ----
function globalKeydown(e) { function globalKeydown(e) {
const modKey = e.metaKey || e.ctrlKey; const modKey = e.metaKey || e.ctrlKey;
@@ -51,100 +69,166 @@ function registerCreateNoteAction() {
register(action); register(action);
} }
// ---- Note search ---- // ---- Campaign entries to search ----
async function fetchNotes() { // The same accent- and case-insensitive normalisation the action filter uses, so a match is
if (!Campaign.value) return; // never hidden by how the name was written.
function normalize(text) {
return (text || '').normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
}
const campaignId = Campaign.value?._id ?? Campaign.value?.id; async function fetchList(path, key) {
try { try {
const response = await Server().get('/note/list', { params: { campaign: campaignId } }); const response = await Server().get(path, { params: { campaign: campaignId.value } });
if (response.data.status !== 'ok') { if (response.data.status !== 'ok') return [];
notes.value = []; return response.data[key] ?? [];
return;
}
notes.value = response.data.notes.map(n => ({
key: n._id,
title: n.title || 'Untitled',
date: n.date
}));
} catch (err) { } catch (err) {
notes.value = []; return [];
} }
} }
function openNote(note) { async function fetchSearchEntries() {
emitter.emit('push-note', note); if (!campaignId.value) return;
closeResults(); // /note/all covers notes nested in folders too, unlike the sidebar's /note/list.
const [allNotes, fetchedActors, fetchedItems, fetchedMaps] = await Promise.all([
fetchList('/note/all', 'notes'),
fetchList('/actor/list', 'actors'),
fetchList('/item/list', 'items'),
fetchList('/map/list', 'maps')
]);
notes.value = allNotes.map(n => ({
key: n._id,
title: n.title || 'Untitled',
date: n.date
}));
actors.value = fetchedActors;
items.value = fetchedItems;
maps.value = fetchedMaps;
} }
// ---- Unified results: notes + command actions ---- // ---- Unified results: notes, actors, items, maps + command actions ----
function getCombinedResults(query) { function getCombinedResults(query) {
const combined = []; const combined = [];
const q = normalize(query);
if (query && query.trim().length > 0) { function pushMatches(list, type, getName) {
const q = query.normalize("NFD").replace(/[\u036f]/g, "").toLowerCase().trim(); for (const data of list) {
if (q && !normalize(getName(data)).includes(q)) continue;
combined.push({ type, data });
}
}
// Filter notes that match the query text pushMatches(notes.value, 'note', n => n.title);
const matchingNotes = notes.value.filter(note => { pushMatches(actors.value, 'actor', a => a.name);
const title = (note.title || '').normalize("NFD").replace(/[\u036f]/g, "").toLowerCase(); pushMatches(items.value, 'item', i => i.name);
return title.includes(q); pushMatches(maps.value, 'map', m => m.name);
});
for (const note of matchingNotes) { // Command actions match on their label and description themselves.
combined.push({ type: 'note', data: note }); for (const action of searchActions(query ?? '')) {
} combined.push({ type: 'action', data: action });
// Search command actions
const matchedActions = searchActions(query);
for (const action of matchedActions) {
combined.push({ type: 'action', data: action });
}
} else if (query === '' || query === null) {
// Empty query - show all notes + all actions
for (const note of notes.value) {
combined.push({ type: 'note', data: note });
}
const allActions = searchActions('');
for (const action of allActions) {
combined.push({ type: 'action', data: action });
}
} }
return combined; return combined;
} }
// Each result type renders like the sidebar row of that entry: the section's icon and name.
const resultIcons = {
note: '/icons/iconoir/regular/book.svg',
actor: '/icons/iconoir/regular/user.svg',
item: '/icons/iconoir/regular/box.svg',
map: '/icons/iconoir/regular/map.svg'
};
function resultTitle(item) {
if (item.type === 'action') return item.data.label;
return item.data.title || item.data.name || 'Untitled';
}
function resultSubtitle(item) {
if (item.type === 'action') return item.data.description;
return t(`campaigns.sections.${item.type}s`);
}
function resultIcon(item) {
return item.type === 'action' ? PlusIcon : resultIcons[item.type];
}
// ---- Opening a result, the way the sidebar opens that kind of entry ----
async function openNote(note) {
closeResults();
// /note/all never carries content; retrieve the note to open it with its text.
try {
const response = await Server().get(`/note/retrieve/${note.key}`);
if (response.data.status !== 'ok' || !response.data.note) return;
const full = response.data.note;
emitter.emit('push-note', { key: full._id, title: full.title, text: full.content ?? '', date: full.date });
} catch (err) {}
}
// A character or an item replaces the sheet window that is already open.
async function openActor(actor) {
closeResults();
const existingWindowId = GetFirstWindowId('character_sheet');
if (existingWindowId !== undefined) {
ClearWindow({ id: existingWindowId });
await nextTick();
}
CreateWindow('character_sheet', { actor });
}
async function openItem(item) {
closeResults();
const existingWindowId = GetFirstWindowId('item_sheet');
if (existingWindowId !== undefined) {
ClearWindow({ id: existingWindowId });
await nextTick();
}
CreateWindow('item_sheet', { item });
}
// Maps anchor on the note container instead of opening a window, like from the sidebar.
function openMap(map) {
closeResults();
const floatingViewer = GetFirstWindowId('map_viewer');
if (floatingViewer !== undefined) ClearWindow({ id: floatingViewer });
AnchorMap(map);
}
function openResult(item) {
if (!item) return;
if (item.type === 'note') openNote(item.data);
else if (item.type === 'actor') openActor(item.data);
else if (item.type === 'item') openItem(item.data);
else if (item.type === 'map') openMap(item.data);
else {
executeAction(item.data.id);
closeResults();
}
}
// ---- Input handling ---- // ---- Input handling ----
function onInput(event) { function onInput(event) {
const query = event.target.value; inputText.value = event.target.value;
inputText.value = query;
selectedIndex.value = -1; selectedIndex.value = -1;
if (!query || query.trim() === '') {
showResults.value = false;
return;
}
showResults.value = true; showResults.value = true;
} }
function onFocus() { function onFocus() {
if (notes.value.length === 0) { showResults.value = true;
fetchNotes().then(() => { // Foundry keeps syncing entries into the campaign in the background: refresh every time the
showResults.value = true; // palette is opened so it never offers stale results.
}); if (campaignId.value) fetchSearchEntries();
} else {
showResults.value = true;
}
} }
function onBlur(event) { function onBlur() {
// Delay closing to allow click on results // Delay closing to allow click on results
setTimeout(() => { setTimeout(() => {
closeResults(); closeResults();
}, 150); }, 150);
} }
async function onKeydown(event) { function onKeydown(event) {
const combined = getCombinedResults(inputText.value); const combined = getCombinedResults(inputText.value);
if (event.key === 'ArrowDown') { if (event.key === 'ArrowDown') {
@@ -162,16 +246,9 @@ async function onKeydown(event) {
if (event.key === 'Enter') { if (event.key === 'Enter') {
event.preventDefault(); event.preventDefault();
if (selectedIndex.value >= 0) { if (selectedIndex.value >= 0) {
const item = combined[selectedIndex.value]; openResult(combined[selectedIndex.value]);
if (!item) return;
if (item.type === 'note') {
openNote(item.data);
} else if (item.type === 'action') {
executeAction(item.data.id);
closeResults();
}
} }
return;
} }
if (event.key === 'Escape') { if (event.key === 'Escape') {
@@ -179,21 +256,6 @@ async function onKeydown(event) {
} }
} }
function onSelect(result) {
if (!result) return;
if (result.link) {
const note = notes.value.find(n => n.key === result.link);
if (note) openNote(note);
}
closeResults();
}
function handleActionSelect(actionData) {
executeAction(actionData.id);
closeResults();
}
function closeResults() { function closeResults() {
showResults.value = false; showResults.value = false;
selectedIndex.value = -1; selectedIndex.value = -1;
@@ -231,21 +293,19 @@ onUnmounted(() => {
</div> </div>
<div class="search-container" v-if="showResults"> <div class="search-container" v-if="showResults">
<template v-if="getCombinedResults(inputText).length === 0 && inputText.trim()"> <template v-if="getCombinedResults(inputText).length === 0">
<div class="search-empty">No results found</div> <div class="search-empty">No results found</div>
</template> </template>
<div class="search-container-list"> <div class="search-container-list">
<NoteSearchResult <NoteSearchResult
v-for="(item, index) in getCombinedResults(inputText)" v-for="(item, index) in getCombinedResults(inputText)"
:key="(item.data.key || item.data.id) + '-' + index" :key="item.type + '-' + (item.data.key || item.data._id || item.data.id) + '-' + index"
:title="item.type === 'note' ? item.data.title : item.data.label" :title="resultTitle(item)"
:subtitle="item.type === 'action' ? item.data.description : ''" :subtitle="resultSubtitle(item)"
:link="item.type === 'note' ? item.data.key : null" :icon="resultIcon(item)"
:icon="item.type === 'action' ? PlusIcon : ''"
:class="{ selected: index === selectedIndex }" :class="{ selected: index === selectedIndex }"
@select="onSelect" @click.stop.prevent="openResult(item)"
@click.stop.prevent="() => { if (item.type === 'note') openNote(item.data); else handleActionSelect(item.data); }"
/> />
</div> </div>
</div> </div>

View File

@@ -89,9 +89,11 @@ onMounted(() => {
.steps { .steps {
margin-left: 8px; margin-left: 8px;
height: 22px; height: 22px;
> { }
font-size: 12px; /* No nested `> {}` here: the scoped style transform turns it into a dangling
} combinator, which the current CSS minifier rejects. */
.steps > * {
font-size: 12px;
} }
.steps :deep(.roll-val){ .steps :deep(.roll-val){
display: inline-flex; display: inline-flex;

View File

@@ -0,0 +1,213 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
import WindowHandle from './partials/WindowHandle.vue';
import Server, { getBaseUrl } from '~/services/Server';
import { emitter } from '~/services/Emitter';
const props = defineProps(['data']);
const id = props.data.id;
const itemId = props.data.item?._id;
const handle = ref(null);
const wrapper = ref(null);
const error = ref('');
const uploadingIcon = ref(false);
const applyingFoundryIcon = ref(false);
const photoInput = ref(null);
const { t } = useI18n();
function normalizeItem(item) {
return {
name: item?.name ?? '',
category: item?.category ?? 'adventuring-gear',
rarity: item?.rarity ?? 'common',
quantity: Number(item?.quantity ?? 1),
weight: item?.weight ?? '',
properties: item?.properties ?? '',
description: item?.description ?? '',
image: item?.image ?? '',
foundryItemId: item?.foundryItemId ?? '',
foundryImage: item?.foundryImage ?? ''
};
}
const form = ref(normalizeItem(props.data.item));
onMounted(() => {
Top(wrapper);
SetupHandle(id, handle);
SetSize(id, { width: 460, height: 560 });
ResetPosition(id, 'center');
});
onBeforeUnmount(() => ClearWindow({ type: 'item_sheet' }));
// The sidebar keeps this entry fresh (Foundry sync lands in the background);
// follow along unless the window is mid-icon-upload.
function handleItemSync({ entityType, entry }) {
if (entityType !== 'item' || entry?._id !== itemId || uploadingIcon.value) return;
form.value = normalizeItem(entry);
}
onMounted(() => emitter.on('campaign-entry-updated', handleItemSync));
onBeforeUnmount(() => emitter.off('campaign-entry-updated', handleItemSync));
const imageUrl = computed(() => {
if (!form.value.image) return '';
return /^(https?:|data:|\/\/)/i.test(form.value.image)
? form.value.image
: `${getBaseUrl()}/public/${form.value.image}`;
});
const canUseFoundryIcon = computed(() => Boolean(form.value.foundryImage) && form.value.foundryImage !== form.value.image);
async function updateItem(payload) {
const response = await Server().post('/item/update', { id: itemId, ...payload });
if (response.data.status !== 'ok') return false;
form.value = normalizeItem(response.data.item);
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
return true;
}
function pickIcon() {
photoInput.value?.click();
}
async function onIconSelected(event) {
const file = event.target.files?.[0];
event.target.value = '';
if (!file || uploadingIcon.value) return;
uploadingIcon.value = true;
error.value = '';
try {
const formData = new FormData();
formData.append('image', file);
const response = await Server().post(`/item/upload-image?item=${itemId}`, formData, {
headers: { "Content-Type": "multipart/form-data" }
});
if (response.data.status !== 'ok') {
error.value = t('campaigns.item.sheet.upload-error');
return;
}
form.value = normalizeItem(response.data.item);
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
} catch (requestError) {
error.value = t('campaigns.item.sheet.upload-error');
} finally {
uploadingIcon.value = false;
}
}
// "Fetch from Foundry's icons": the module keeps the world's own icon on the
// item, so this just switches back to it.
async function useFoundryIcon() {
if (!canUseFoundryIcon.value || applyingFoundryIcon.value) return;
applyingFoundryIcon.value = true;
error.value = '';
try {
const done = await updateItem({ image: form.value.foundryImage });
if (!done) error.value = t('campaigns.item.sheet.save-error');
} catch (requestError) {
error.value = t('campaigns.item.sheet.save-error');
} finally {
applyingFoundryIcon.value = false;
}
}
async function removeIcon() {
if (!form.value.image) return;
error.value = '';
try {
const done = await updateItem({ image: '' });
if (!done) error.value = t('campaigns.item.sheet.save-error');
} catch (requestError) {
error.value = t('campaigns.item.sheet.save-error');
}
}
</script>
<template>
<div class="window-wrapper item-window" :id="'window-wrapper-' + id" ref="wrapper">
<WindowHandle :window="id" ref="handle" />
<div class="item-body">
<header class="item-hero">
<div class="item-icon" :class="{ empty: !form.image }">
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.item.sheet.icon')">
<span v-else aria-hidden="true">{{ form.name.slice(0, 1).toUpperCase() }}</span>
</div>
<div class="item-identity">
<h1>{{ form.name }}</h1>
<div class="item-tags">
<span class="item-tag">{{ $t(`campaigns.item.categories.${form.category}`) }}</span>
<span class="item-tag">{{ $t(`campaigns.item.rarities.${form.rarity}`) }}</span>
<span v-if="form.foundryItemId" class="item-tag synced">{{ $t('campaigns.synced') }}</span>
</div>
</div>
</header>
<div v-if="error" class="item-error">{{ error }}</div>
<div class="icon-controls">
<button class="sheet-button" type="button" :disabled="uploadingIcon" @click="pickIcon">
{{ uploadingIcon
? $t('campaigns.item.sheet.uploading')
: (form.image ? $t('campaigns.item.sheet.change-icon') : $t('campaigns.item.sheet.choose-icon')) }}
</button>
<button v-if="canUseFoundryIcon" class="sheet-button secondary" type="button" :disabled="applyingFoundryIcon" @click="useFoundryIcon">
{{ $t('campaigns.item.sheet.foundry-icon') }}
</button>
<button v-if="form.image" class="sheet-button secondary" type="button" :disabled="uploadingIcon" :aria-label="$t('campaigns.item.sheet.remove-icon')" @click="removeIcon">×</button>
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onIconSelected">
</div>
<dl class="item-facts">
<div class="item-fact">
<dt>{{ $t('campaigns.item.quantity') }}</dt>
<dd>{{ form.quantity }}</dd>
</div>
<div v-if="form.weight !== '' && form.weight !== undefined" class="item-fact">
<dt>{{ $t('campaigns.item.weight') }}</dt>
<dd>{{ Number(form.weight).toFixed(1) }} lb</dd>
</div>
</dl>
<section v-if="form.properties" class="item-section">
<h2>{{ $t('campaigns.item.properties') }}</h2>
<p class="item-copy">{{ form.properties }}</p>
</section>
<section class="item-section">
<h2>{{ $t('campaigns.fields.description') }}</h2>
<p class="item-copy">{{ form.description || $t('campaigns.item.sheet.no-description') }}</p>
</section>
</div>
</div>
</template>
<style scoped>
.item-window { min-width: 0; min-height: 0; }
.item-body { width: 100%; min-height: 0; flex: 1; overflow: auto; padding: 14px 16px 16px; box-sizing: border-box; }
.item-hero { display: flex; align-items: center; gap: 13px; padding: 2px 2px 13px; margin-bottom: 11px; border-bottom: 1px solid var(--color-border); }
.item-icon { width: 64px; height: 64px; flex: 0 0 64px; display: grid; place-items: center; overflow: hidden; border-radius: 10px; border: 1px solid var(--color-border); background: var(--color-background-soft); color: var(--color-link); font: 30px MrEavesRemake; }
.item-icon.empty { border-style: dashed; }
.item-icon img { width: 100%; height: 100%; object-fit: contain; }
.item-identity { min-width: 0; }
.item-identity h1 { margin: 0 0 6px; font: 24px MrEavesRemake; overflow-wrap: anywhere; }
.item-tags { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
.item-tag { padding: 3px 9px; border: 1px solid var(--color-border); border-radius: 999px; background: var(--color-background-soft); font-size: 12px; opacity: .9; }
.item-tag.synced { font-size: 10px; letter-spacing: .04em; text-transform: uppercase; opacity: .6; }
.item-error { padding: 7px 10px; margin-bottom: 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
.icon-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; margin-bottom: 13px; }
.sheet-button { border: 1px solid var(--color-border); border-radius: 7px; padding: 7px 12px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; white-space: nowrap; font-size: 13px; }
.sheet-button:hover { background: var(--color-button-hover); }
.sheet-button:disabled { opacity: .55; cursor: wait; }
.photo-input { display: none; }
.item-facts { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 13px; }
.item-fact { flex: 1 1 120px; min-width: 0; padding: 9px 11px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); }
.item-fact dt { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; opacity: .72; }
.item-fact dd { margin: 3px 0 0; font: 17px MrEavesRemake; }
.item-section { padding: 11px 13px; margin: 0 0 10px; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-light); }
.item-section h2 { margin: 0 0 8px; padding-bottom: 6px; border-bottom: 1px solid var(--color-border); font: 15px MrEavesRemake; letter-spacing: .03em; }
.item-copy { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; line-height: 1.45; opacity: .85; }
</style>

View File

@@ -0,0 +1,68 @@
// The rules behind grouping the campaign's items under the folders they stand in.
// Item folders arrive from the linked Foundry world (routes/foundry-link.js mirrors
// its item directory), so the campaign only reads this tree: the helper holds no
// state, talks to no API and builds rows from what `/item/list` already returns.
function ByName(a, b) {
return String(a?.name ?? '').localeCompare(String(b?.name ?? ''));
}
// The folder a folder hangs under. A parent the campaign does not know puts it at
// the root, and so does a parent chain that leads back to the folder itself: a
// broken tree must not hide everything below it.
function ParentKey(folder, knownFolders) {
let parentKey = String(folder.parentFolder ?? '');
if (!parentKey || !knownFolders.has(parentKey)) return '';
const seen = new Set([String(folder._id)]);
while (parentKey) {
if (seen.has(parentKey)) return '';
seen.add(parentKey);
const parent = knownFolders.get(parentKey);
parentKey = knownFolders.has(String(parent?.parentFolder ?? '')) ? String(parent.parentFolder) : '';
}
return String(folder.parentFolder);
}
// The rows of the item list in the order they are shown: every folder followed by
// what stands in it, deeper and deeper, with the items standing at that level last.
// `collapsedFolderIds` hides a folder's whole subtree; folders start open so a
// synced item is never hidden behind a click. Rows are `{ kind: 'folder', key,
// depth, folder }` or `{ kind: 'item', key, depth, item }`. An item whose folder the
// campaign does not know reads as a root item instead of vanishing from the list.
function BuildItemRows(items, folders, collapsedFolderIds = []) {
const knownFolders = new Map((folders ?? []).map((folder) => [String(folder._id), folder]));
const collapsed = new Set((collapsedFolderIds ?? []).map(String));
const childFolders = new Map([['', []]]);
const itemsByFolder = new Map([['', []]]);
for (const folder of knownFolders.values()) {
const parentKey = ParentKey(folder, knownFolders);
if (!childFolders.has(parentKey)) childFolders.set(parentKey, []);
childFolders.get(parentKey).push(folder);
}
for (const item of items ?? []) {
const folderKey = item?.folder && knownFolders.has(String(item.folder)) ? String(item.folder) : '';
if (!itemsByFolder.has(folderKey)) itemsByFolder.set(folderKey, []);
itemsByFolder.get(folderKey).push(item);
}
const rows = [];
const visitedFolders = new Set();
function walk(folderKey, depth) {
for (const folder of (childFolders.get(folderKey) ?? []).slice().sort(ByName)) {
if (visitedFolders.has(String(folder._id))) continue;
visitedFolders.add(String(folder._id));
rows.push({ kind: 'folder', key: `folder-${folder._id}`, depth, folder });
if (!collapsed.has(String(folder._id))) walk(String(folder._id), depth + 1);
}
for (const item of (itemsByFolder.get(folderKey) ?? []).slice().sort(ByName)) {
rows.push({ kind: 'item', key: `item-${item._id}`, depth, item });
}
}
walk('', 0);
return rows;
}
export { BuildItemRows };

View File

@@ -0,0 +1,69 @@
// The rules behind the actor tokens of a map (drag an actor from the sidebar onto a map, move the
// token from cell to cell). Like the pins, a token is stored in image pixels, so these helpers only
// translate and snap: they hold no state and talk to no API.
// What the sidebar puts into a drag when an actor row is pulled out of it, so the map knows an actor
// is on its way and nothing else dropped on it (a note, a file) is taken for one.
const ACTOR_DRAG_TYPE = 'application/x-dragonroll-actor';
// The actor id carried by a drag event, or null when the drag carries no actor. `types` is what a
// dragover can see: the data itself is protected until the drop.
function IsActorDrag(event) {
return Array.from(event?.dataTransfer?.types ?? []).includes(ACTOR_DRAG_TYPE);
}
function ActorDragId(event) {
return String(event?.dataTransfer?.getData?.(ACTOR_DRAG_TYPE) ?? '').trim() || null;
}
// The middle of the grid cell a point of the image stands in, in image pixels: this is what a token
// is stored at, so it always stands in a square of the grid. The backend snaps the same way, so a
// token does not move when a drag lands.
function CellCentre(point, grid) {
const size = Math.max(1, Number(grid?.gridSize) || 50);
const offsetX = Number(grid?.offsetX) || 0;
const offsetY = Number(grid?.offsetY) || 0;
const x = Number(point?.x);
const y = Number(point?.y);
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
// Spots off the top left corner count from the corner itself, and only whole pixels count: both
// the way the route reads a coordinate, so the token a drag shows is the token that gets saved.
const column = Math.floor((Math.max(0, Math.round(x)) - offsetX) / size);
const row = Math.floor((Math.max(0, Math.round(y)) - offsetY) / size);
return {
x: Math.max(0, Math.round(offsetX + (column + 0.5) * size)),
y: Math.max(0, Math.round(offsetY + (row + 0.5) * size))
};
}
// A token moved by whole cells (the arrow keys of a focused token): the same cell width the grid is
// drawn with, so a token steps from one square to the next and never in between.
function MoveByCells(centre, grid, columns, rows) {
const size = Math.max(1, Number(grid?.gridSize) || 50);
const x = Number(centre?.x);
const y = Number(centre?.y);
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
return {
x: Math.max(0, Math.round(x + Number(columns) * size)),
y: Math.max(0, Math.round(y + Number(rows) * size))
};
}
// The side of a token in screen pixels: one grid cell, so a token covers the square it stands in at
// every zoom. Never smaller than an icon, or a zoomed-out map would hide its actors.
function TokenSize(grid, zoom) {
const cell = Math.max(1, Number(grid?.gridSize) || 50) * (Number(zoom) || 1);
return Math.round(Math.max(18, cell));
}
export {
ACTOR_DRAG_TYPE,
ActorDragId,
CellCentre,
IsActorDrag,
MoveByCells,
TokenSize
};

View File

@@ -19,7 +19,7 @@ function ShowTooltip(){
animate(tooltip, { animate(tooltip, {
opacity: [0, 1], opacity: [0, 1],
translateY: [20, 0] translateY: [20, 0]
}, {duration: 0.1, ease: 'ease-out'}); }, {duration: 0.1, ease: 'easeOut'});
showed = true; showed = true;
hided = false; hided = false;
} }
@@ -33,7 +33,7 @@ function HideTooltip(){
animate(tooltip, { animate(tooltip, {
opacity: [1, 0], opacity: [1, 0],
translateY: [0, 20] translateY: [0, 20]
}, {duration: 0.1, ease: 'ease-in'}).finished.then(() => tooltip.style.display = "none") }, {duration: 0.1, ease: 'easeIn'}).finished.then(() => tooltip.style.display = "none")
hided = true; hided = true;
showed = false; showed = false;
} }

View File

@@ -71,6 +71,12 @@ const defWindows = {
close: () => ClearWindow({type: 'character_sheet'}), close: () => ClearWindow({type: 'character_sheet'}),
movable: true movable: true
}, },
item_sheet: {
title: 'windows.item-sheet',
component: () => import('~/components/windows/ItemSheetWindow.vue'),
close: () => ClearWindow({type: 'item_sheet'}),
movable: true
},
create_map: { create_map: {
title: 'windows.create-map', title: 'windows.create-map',
component: () => import('~/components/windows/CreateMapWindow.vue'), component: () => import('~/components/windows/CreateMapWindow.vue'),

View File

@@ -62,6 +62,13 @@
"new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.", "new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.",
"category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat", "category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat",
"quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil", "quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
"folder-toggle": "Mostra o amaga la carpeta {name}",
"sheet": {
"icon": "Icona de l'objecte", "choose-icon": "Tria la teva pròpia icona", "change-icon": "Canvia la icona",
"uploading": "Pujant...", "upload-error": "No s'ha pogut pujar aquesta icona.",
"foundry-icon": "Fes servir la icona del Foundry", "remove-icon": "Treu la icona", "save-error": "No s'ha pogut desar aquest objecte.",
"no-description": "Sense descripció afegida."
},
"categories": { "categories": {
"weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura", "weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura",
"magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre" "magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre"
@@ -84,6 +91,12 @@
"open": "Obre la nota", "remove": "Treu el marcador", "open": "Obre la nota", "remove": "Treu el marcador",
"error": "No s'han pogut canviar els marcadors d'aquest mapa.", "error": "No s'han pogut canviar els marcadors d'aquest mapa.",
"note-error": "No s'ha pogut llegir aquesta nota. Potser s'ha suprimit." "note-error": "No s'ha pogut llegir aquesta nota. Potser s'ha suprimit."
},
"tokens": {
"token": "Fitxa", "drag": "Arrossega aquest actor sobre un mapa per posar-lo",
"drop-hint": "Deixa anar per posar l'actor en aquest mapa",
"open": "Obre la fitxa de personatge", "remove": "Treu la fitxa",
"error": "No s'han pogut canviar les fitxes d'aquest mapa."
} }
}, },
"character-sheet": { "character-sheet": {

View File

@@ -8,5 +8,6 @@
"create-campaign": "Crear campanya", "create-campaign": "Crear campanya",
"create-map": "Crear mapa", "create-map": "Crear mapa",
"map-viewer": "Mapa", "map-viewer": "Mapa",
"pinned-note": "Nota fixada" "pinned-note": "Nota fixada",
"item-sheet": "Objecte"
} }

View File

@@ -66,6 +66,13 @@
"new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.", "new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.",
"category": "Category", "rarity": "Rarity", "quantity": "Quantity", "category": "Category", "rarity": "Rarity", "quantity": "Quantity",
"quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse", "quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
"folder-toggle": "Toggle the {name} folder",
"sheet": {
"icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change icon",
"uploading": "Uploading...", "upload-error": "Unable to upload this icon.",
"foundry-icon": "Use Foundry icon", "remove-icon": "Remove icon", "save-error": "Unable to save this item.",
"no-description": "No description added."
},
"categories": { "categories": {
"weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear", "weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear",
"magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other" "magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other"
@@ -88,6 +95,12 @@
"open": "Open note", "remove": "Remove pin", "open": "Open note", "remove": "Remove pin",
"error": "Unable to change the pins of this map.", "error": "Unable to change the pins of this map.",
"note-error": "This note could not be read. It may have been deleted." "note-error": "This note could not be read. It may have been deleted."
},
"tokens": {
"token": "Token", "drag": "Drag this actor onto a map to place it there",
"drop-hint": "Drop to place the actor on this map",
"open": "Open character sheet", "remove": "Remove token",
"error": "Unable to change the tokens of this map."
} }
}, },
"character-sheet": { "character-sheet": {

View File

@@ -8,5 +8,6 @@
"create-campaign": "Create Campaign", "create-campaign": "Create Campaign",
"create-map": "Create Map", "create-map": "Create Map",
"map-viewer": "Map", "map-viewer": "Map",
"pinned-note": "Pinned note" "pinned-note": "Pinned note",
"item-sheet": "Item"
} }

View File

@@ -62,6 +62,13 @@
"new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.", "new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.",
"category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad", "category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad",
"quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil", "quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
"folder-toggle": "Muestra o oculta la carpeta {name}",
"sheet": {
"icon": "Icono del objeto", "choose-icon": "Elegir tu propio icono", "change-icon": "Cambiar icono",
"uploading": "Subiendo...", "upload-error": "No se pudo subir este icono.",
"foundry-icon": "Usar el icono de Foundry", "remove-icon": "Quitar el icono", "save-error": "No se pudo guardar este objeto.",
"no-description": "Sin descripción añadida."
},
"categories": { "categories": {
"weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura", "weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura",
"magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro" "magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro"
@@ -84,6 +91,12 @@
"open": "Abrir nota", "remove": "Quitar el marcador", "open": "Abrir nota", "remove": "Quitar el marcador",
"error": "No se pudieron cambiar los marcadores de este mapa.", "error": "No se pudieron cambiar los marcadores de este mapa.",
"note-error": "No se pudo leer esta nota. Puede que se haya eliminado." "note-error": "No se pudo leer esta nota. Puede que se haya eliminado."
},
"tokens": {
"token": "Ficha", "drag": "Arrastra este actor sobre un mapa para colocarlo",
"drop-hint": "Suelta para colocar al actor en este mapa",
"open": "Abrir hoja de personaje", "remove": "Quitar la ficha",
"error": "No se pudieron cambiar las fichas de este mapa."
} }
}, },
"character-sheet": { "character-sheet": {

View File

@@ -8,5 +8,6 @@
"create-campaign": "Crear campanya", "create-campaign": "Crear campanya",
"create-map": "Crear mapa", "create-map": "Crear mapa",
"map-viewer": "Mapa", "map-viewer": "Mapa",
"pinned-note": "Nota fijada" "pinned-note": "Nota fijada",
"item-sheet": "Objeto"
} }

12707
frontend/package-lock.json generated

File diff suppressed because it is too large Load Diff

326
package-lock.json generated
View File

@@ -1,326 +0,0 @@
{
"name": "dragonroll",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"devDependencies": {
"concurrently": "^9.2.1"
}
},
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/chalk": {
"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",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chalk/node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
"dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.1",
"wrap-ansi": "^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true,
"license": "MIT"
},
"node_modules/concurrently": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
"integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==",
"dev": true,
"license": "MIT",
"dependencies": {
"chalk": "4.1.2",
"rxjs": "7.8.2",
"shell-quote": "1.8.3",
"supports-color": "8.1.1",
"tree-kill": "1.2.2",
"yargs": "17.7.2"
},
"bin": {
"conc": "dist/bin/concurrently.js",
"concurrently": "dist/bin/concurrently.js"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/open-cli-tools/concurrently?sponsor=1"
}
},
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"dev": true,
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/rxjs": {
"version": "7.8.2",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.1.0"
}
},
"node_modules/shell-quote": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
"dev": true,
"license": "MIT",
"bin": {
"tree-kill": "cli.js"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD"
},
"node_modules/wrap-ansi": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=10"
}
},
"node_modules/yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
"integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
"dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^8.0.1",
"escalade": "^3.1.1",
"get-caller-file": "^2.0.5",
"require-directory": "^2.1.1",
"string-width": "^4.2.3",
"y18n": "^5.0.5",
"yargs-parser": "^21.1.1"
},
"engines": {
"node": ">=12"
}
},
"node_modules/yargs-parser": {
"version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=12"
}
}
}
}

View File

@@ -1,9 +1,15 @@
{ {
"name": "dragonroll-workspace",
"private": true,
"packageManager": "pnpm@10.28.2",
"devDependencies": { "devDependencies": {
"concurrently": "^9.2.1" "concurrently": "^9.2.1"
}, },
"scripts": { "scripts": {
"dev": "concurrently -k -n BACKEND,FRONTEND,DISCORD-BOT,FOUNDRY -c blue,green,yellow,magenta \"DEBUG=* npm --prefix backend run dev\" \"npm --prefix frontend run dev\" \"npm --prefix discord-bot start\" \"node scripts/run-foundry.js\"", "dev": "concurrently -k -n BACKEND,FRONTEND,DISCORD-BOT,FOUNDRY -c blue,green,yellow,magenta \"DEBUG=* pnpm --filter ./backend run dev\" \"pnpm --filter ./frontend run dev\" \"pnpm --filter ./discord-bot run start\" \"node scripts/run-foundry.js\"",
"dev:backend": "DEBUG=* pnpm --filter ./backend run dev",
"dev:frontend": "pnpm --filter ./frontend run dev",
"dev:discord-bot": "pnpm --filter ./discord-bot run start",
"test": "node --test tests/" "test": "node --test tests/"
} }
} }

9814
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

10
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,10 @@
packages:
- backend
- frontend
- discord-bot
# pnpm blocks install scripts of dependencies by default; these two place their
# native binaries through theirs and have to be allowed to run them.
onlyBuiltDependencies:
- '@parcel/watcher'
- esbuild

View File

@@ -1,5 +1,5 @@
// Runs the Foundry Virtual Tabletop start script defined by FOUNDRY_START_SCRIPT // Runs the Foundry Virtual Tabletop start script defined by FOUNDRY_START_SCRIPT
// in the root .env file. Used by `npm run dev` via concurrently. // in the root .env file. Used by `pnpm dev` via concurrently.
const { spawn } = require('node:child_process'); const { spawn } = require('node:child_process');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');

View File

@@ -0,0 +1,590 @@
// Tests for item folders following the Foundry world into the campaign
// (Syndria98/dragonroll#44): the world's item directory is grouped into folders, and
// Dragonroll mirrors that tree as Folders of target 'item' and files the synced items
// in them, so its item list reads like the world's.
//
// The repository root installs no dependencies, so each side is loaded the way the
// other tests do it. The sync route runs against a stubbed `require` (express,
// mongoose and the models answer with plain objects and a small filter matcher):
// that keeps the tree, the filing and the pruning observable without a database. The
// Foundry module is loaded into a `node:vm` context holding stubbed Foundry globals
// (`game.folders` included) with fake timers, like tests/foundry-sync-toggle.test.js.
// The grouping of the sidebar list lives in a plain ES module and is read as text.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const repoRequire = (relative) => require(path.join(__dirname, "..", relative));
// --- The sync route against stubbed models -------------------------------------
// A mongoose query answers whatever `await query` and `query.lean()` answer with, and
// lets `select()`, `sort()` and `limit()` sit in between.
function mongooseQuery(value) {
const result = {
select: () => result,
sort: () => result,
limit: (count) => mongooseQuery(value.slice(0, count)),
lean: () => Promise.resolve(value),
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
};
return result;
}
// Enough of the query language the item folder sync uses: equality, $or, $in, $nin,
// $exists. Anything else is a filter this test did not expect and says so.
function matches(document, filter = {}) {
return Object.entries(filter).every(([key, expected]) => {
if (key === "$or") return expected.some((part) => matches(document, part));
const value = document?.[key];
if (expected && typeof expected === "object" && !Array.isArray(expected)) {
return Object.entries(expected).every(([operator, wanted]) => {
if (operator === "$exists") return (value !== undefined && value !== null) === wanted;
if (operator === "$in") return wanted.some((entry) => String(value) === String(entry));
if (operator === "$nin") return !wanted.some((entry) => String(value) === String(entry));
throw new Error(`filter operator "${key}.${operator}" is not stubbed`);
});
}
return String(value ?? "") === String(expected ?? "");
});
}
function fakeModel(table, seed = []) {
const rows = [];
let counter = 0;
function Document(data = {}) {
counter += 1;
this._id = `${table}-${counter}`;
this.isNew = true;
this.foundryNames = [];
Object.assign(this, data);
}
Document.prototype.save = async function save() {
if (this.isNew) rows.push(this);
this.isNew = false;
return this;
};
Object.defineProperty(Document.prototype, "id", { get() { return this._id; } });
for (const data of seed) {
const row = new Document({ [table === "folder" ? "target" : "name"]: undefined, ...data });
row.isNew = false;
rows.push(row);
}
const model = function Model(data) { return new Document(data); };
model.rows = rows;
model.findOne = async (filter) => rows.find((row) => matches(row, filter)) ?? null;
model.find = (filter) => mongooseQuery(rows.filter((row) => matches(row, filter)));
model.deleteOne = async (filter) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) rows.splice(rows.indexOf(row), 1);
return { deletedCount: hit.length };
};
model.deleteMany = async (filter) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) rows.splice(rows.indexOf(row), 1);
return { deletedCount: hit.length };
};
model.updateMany = async (filter, update) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) Object.assign(row, update.$set ?? {});
return { modifiedCount: hit.length };
};
return model;
}
function worldItem(over = {}) {
return {
_id: "item-1",
name: "Longsword",
type: "weapon",
system: { quantity: 1, weight: 3, rarity: "common" },
...over,
};
}
// The Foundry sync route with every model it requires stubbed. `seed` pre-fills the
// tables with documents the campaign already holds.
function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
const routes = new Map();
const router = {
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
};
const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId };
const models = {
"../models/Actor": fakeModel("actor", seed.actors),
"../models/Item": fakeModel("item", seed.items),
"../models/Folder": fakeModel("folder", seed.folders),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 };
if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", "foundry-link.js"), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
async function call(route, body = {}) {
const handlers = routes.get(route);
assert.ok(handlers, `${route} is not mounted`);
const res = { payload: null, json(payload) { this.payload = payload; }, set: () => {} };
const req = { body, get: (name) => (String(name).toLowerCase() === "authorization" ? "Bearer sync-token" : "") };
await handlers[handlers.length - 1](req, res);
return res.payload;
}
return { call, models, campaign };
}
const FOLDER_TREE = [
{ id: "folder-melee", name: "Melee Weapons", parent: null },
{ id: "folder-ranged", name: "Ranged Weapons", parent: null },
{ id: "folder-powder", name: "Powder Weapons", parent: "folder-ranged" },
];
test("a synced world item arrives in the folder the world keeps it in", async () => {
const sync = loadSyncRoute();
const response = await sync.call("POST /sync/snapshot", {
worldId: "world-1",
actors: [],
folders: FOLDER_TREE,
items: [worldItem({ dragonroll: { folder: "folder-melee" } })],
});
assert.equal(response.status, "ok");
const [folder] = sync.models["../models/Folder"].rows;
assert.equal(folder.name, "Melee Weapons");
assert.equal(folder.target, "item", "a synced folder belongs to the item list, not the notes");
assert.equal(folder.foundryFolderId, "folder-melee");
assert.equal(sync.models["../models/Item"].rows[0].folder, folder._id);
});
test("a nested Foundry folder becomes a nested campaign folder", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: FOLDER_TREE });
const folders = sync.models["../models/Folder"].rows;
const ranged = folders.find((folder) => folder.name === "Ranged Weapons");
const powder = folders.find((folder) => folder.name === "Powder Weapons");
assert.equal(powder.parentFolder, ranged._id, "the subfolder hangs under the folder nesting it");
assert.equal(folders.find((folder) => folder.name === "Melee Weapons").parentFolder, null);
});
test("the same world folder is never made twice, and keeps its items", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/item-snapshot", {
worldId: "world-1", items: [worldItem({ dragonroll: { folder: "folder-melee" } })], folders: FOLDER_TREE,
});
const filed = sync.models["../models/Item"].rows[0].folder;
await sync.call("POST /sync/item-snapshot", {
worldId: "world-1", items: [worldItem({ dragonroll: { folder: "folder-melee" } })], folders: FOLDER_TREE,
});
assert.equal(sync.models["../models/Folder"].rows.length, FOLDER_TREE.length, "the tree was mirrored once");
assert.equal(sync.models["../models/Item"].rows[0].folder, filed, "the item stays in the folder it was filed in");
});
test("a folder renamed in the world is renamed in the campaign", async () => {
const sync = loadSyncRoute({
seed: { folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Old name", parentFolder: null }] },
});
await sync.call("POST /sync/item-snapshot", {
worldId: "world-1", items: [], folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null }],
});
assert.equal(sync.models["../models/Folder"].rows.length, 1);
assert.equal(sync.models["../models/Folder"].rows[0].name, "Melee Weapons");
});
test("a folder the world dropped goes, and its items move to the root", async () => {
const sync = loadSyncRoute({
seed: {
folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }],
items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }],
},
});
await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [] });
assert.deepEqual(sync.models["../models/Folder"].rows, [], "the empty folder row is gone with the world's folder");
assert.equal(sync.models["../models/Item"].rows[0].folder, null, "the item moves to the root instead of nowhere");
});
test("a campaign folder the world does not know is left alone", async () => {
const sync = loadSyncRoute({
seed: { folders: [{ _id: "folder-1", target: "item", name: "Homebrew", parentFolder: null }] },
});
await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [] });
assert.equal(sync.models["../models/Folder"].rows.length, 1, "only folders mirrored from the world are pruned");
});
test("an item embedded in an actor leaves the folder of its world copy alone", async () => {
const sync = loadSyncRoute({
seed: { items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }] },
});
// The actor's copy carries no folder of its own: the inventory folders an actor
// keeps say nothing about the campaign's item list.
await sync.call("POST /sync/snapshot", {
worldId: "world-1",
actors: [{ _id: "actor-1", name: "Thalia", items: [worldItem({ _id: "item-1" })] }],
items: [],
folders: FOLDER_TREE,
});
assert.equal(sync.models["../models/Item"].rows[0].folder, "folder-1");
});
test("a module that knows nothing about folders leaves them untouched", async () => {
const sync = loadSyncRoute({
seed: {
folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }],
items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }],
},
});
await sync.call("POST /sync/snapshot", { worldId: "world-1", actors: [], items: [worldItem()] });
await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [worldItem()] });
assert.equal(sync.models["../models/Folder"].rows.length, 1, "no tree was sent, so nothing was pruned");
assert.equal(sync.models["../models/Item"].rows[0].folder, "folder-1", "and the item stays filed where it was");
});
test("an item the world moved out of a folder follows it to the root", async () => {
const sync = loadSyncRoute({
seed: {
folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }],
items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }],
},
});
await sync.call("POST /sync/item-snapshot", {
worldId: "world-1",
items: [worldItem({ dragonroll: { folder: "" } })],
folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null }],
});
assert.equal(sync.models["../models/Item"].rows[0].folder, null);
});
test("item folders stay out of the note tree", () => {
// The note routes share the Folder model, so each of them asks for "anything but
// item": note folders made before the target field existed keep matching that.
for (const route of ["note.js", "folder.js"]) {
const source = read("backend", "src", "routes", route);
const listings = source.match(/Folder\.find\(\{[^}]*\}\)/g) ?? [];
assert.ok(listings.length, `${route} lists folders`);
for (const listing of listings) {
assert.match(listing, /target:\s*\{\s*\$ne:\s*['"]item['"]\s*\}/, `${route} leaks item folders: ${listing}`);
}
}
});
test("the item list comes with the folders it groups into, and items carry theirs", () => {
assert.match(read("backend", "src", "models", "Item.js"), /folder:\s*{\s*type:\s*Schema\.Types\.ObjectId,\s*ref:\s*'Folder'/);
const itemRoute = read("backend", "src", "routes", "item.js");
assert.match(itemRoute, /res\.json\(\{\s*status:\s*'ok',\s*items,\s*folders:/);
assert.match(itemRoute, /Folder\.find\(\{\s*campaign:\s*campaignId,\s*target:\s*'item'\s*\}/);
});
// --- The Foundry module sends its folder tree ------------------------------------
function makeWorld() {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
nextTimerId: 1,
};
const folders = [
{ id: "folder-melee", name: "Melee Weapons", type: "Item", parent: null, documentName: "Folder" },
{ id: "folder-ranged", name: "Ranged Weapons", type: "Item", parent: "folder-melee", documentName: "Folder" },
// An actor's own inventory folder: it hangs off the actor, not the world.
{ id: "folder-carried", name: "Carried", type: "Item", parent: { id: "actor-1", documentName: "Actor" }, documentName: "Folder" },
{ id: "folder-journal", name: "Lore", type: "JournalEntry", parent: null, documentName: "Folder" },
];
const items = [
{
id: "item-1", name: "Longsword", type: "weapon", documentName: "Item", parent: null,
folder: "folder-melee",
system: { properties: { value: [] }, quantity: 1, weight: 3, rarity: "common" },
toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; },
},
{
id: "item-2", name: "Torch", type: "loot", documentName: "Item", parent: null, folder: "",
system: { properties: { value: [] }, quantity: 1, weight: 1, rarity: "common" },
toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; },
},
];
const carriedItem = {
id: "item-3", name: "Caltrops", type: "loot", documentName: "Item", parent: { documentName: "Actor" },
folder: "folder-carried",
system: { properties: { value: [] }, quantity: 4, weight: 0, rarity: "common" },
toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; },
};
const actors = [
{
id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {},
items: { contents: [carriedItem] },
getFlag() { return undefined; },
toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags }; },
},
];
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
const sandbox = {
console: { log() {}, info() {}, warn() {}, error() {} },
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: { notifications: { info() {}, warn() {}, error() {} } },
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); },
},
setTimeout: (fn, delay = 0) => {
const id = state.nextTimerId++;
state.timers.set(id, { fn, delay });
return id;
},
clearTimeout: (id) => state.timers.delete(id),
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
state.requests.push({
href: String(url),
method: options.method,
body: options.body ? JSON.parse(options.body) : null,
});
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: actors, get: (id) => actors.find((actor) => actor.id === id) },
items: { contents: items, get: (id) => items.find((item) => item.id === id) },
folders: { contents: folders, get: (id) => folders.find((folder) => folder.id === id) },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(read("dragonroll-foundry", "scripts", "api.js"), sandbox);
state.game = sandbox.game;
state.folder = (id) => folders.find((folder) => folder.id === id);
state.item = (id) => items.find((item) => item.id === id);
state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync")
&& !request.href.includes("foundry/sync/status"));
state.pushes = (route) => state.syncRequests().filter((request) => request.href.includes(route));
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await drain();
};
state.runTimers = async () => {
for (let round = 0; round < 6; round += 1) {
if (!state.timers.size && round > 2) break;
const due = [...state.timers.values()];
state.timers.clear();
for (const timer of due) await timer.fn();
await drain();
}
};
state.linkedSetup = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
state.requests.length = 0;
return state;
};
return state;
}
test("the world sends its item folder tree with a snapshot", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("updateActor", world.game.actors.contents[0]);
await world.runTimers();
const [push] = world.pushes("foundry/sync/snapshot");
assert.ok(push, "the actor change pushed a snapshot");
assert.deepEqual(push.body.folders, [
{ id: "folder-melee", name: "Melee Weapons", parent: null },
{ id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee" },
], "the item directory tree, nested, without the actor's own or another type's folders");
const longsword = push.body.items.find((item) => item._id === "item-1");
assert.equal(longsword.dragonroll.folder, "folder-melee", "a world item says which folder it stands in");
const torch = push.body.items.find((item) => item._id === "item-2");
assert.equal(torch.dragonroll.folder, "", "and which one stands at the root");
});
test("an item embedded in an actor does not report the actor's inventory folders", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("updateActor", world.game.actors.contents[0]);
await world.runTimers();
const [push] = world.pushes("foundry/sync/snapshot");
const carried = push.body.actors[0].items.find((item) => item._id === "item-3");
assert.equal(carried.dragonroll?.folder, undefined, "the actor copy carries no folder for the campaign");
});
test("a live item edit carries the folder tree too", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("updateItem", world.item("item-1"));
await world.runTimers();
const [push] = world.pushes("foundry/sync/item-snapshot");
assert.deepEqual(push.body.folders.map((folder) => folder.id), ["folder-melee", "folder-ranged"]);
assert.equal(push.body.items[0].dragonroll.folder, "folder-melee");
});
test("a folder change reaches Dragonroll without pushing the items in it", async () => {
const world = await makeWorld().linkedSetup();
const melee = world.folder("folder-melee");
melee.name = "Close Weapons";
await world.fire("updateFolder", melee);
await world.runTimers();
const [push] = world.pushes("foundry/sync/item-snapshot");
assert.deepEqual(push.body.items, [], "the items themselves are left alone");
assert.deepEqual(push.body.folders.map((folder) => [folder.id, folder.name]), [
["folder-melee", "Close Weapons"],
["folder-ranged", "Ranged Weapons"],
]);
});
test("a folder of another document type does not touch the item list", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("updateFolder", world.folder("folder-journal"));
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
});
test("autosync off: folder changes stop syncing", async () => {
const world = await makeWorld().linkedSetup();
await world.game.settings.set("dragonroll-foundry", "autoSync", false);
await world.fire("updateFolder", world.folder("folder-melee"));
await world.fire("updateItem", world.item("item-1"));
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
});
// --- The sidebar groups its items under those folders ----------------------------
async function loadItemFoldersService() {
const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };");
return vm.compileFunction(source)();
}
const { BuildItemRows } = await loadItemFoldersService();
const SIDEBAR_FOLDERS = [
{ _id: "f-melee", name: "Melee Weapons" },
{ _id: "f-ranged", name: "Ranged Weapons" },
{ _id: "f-powder", name: "Powder Weapons", parentFolder: "f-ranged" },
];
const SIDEBAR_ITEMS = [
{ _id: "i-sword", name: "Longsword", folder: "f-melee" },
{ _id: "i-pistol", name: "Pistol", folder: "f-powder" },
{ _id: "i-torch", name: "Torch" },
];
test("items are grouped under the folder they stand in, nested", () => {
const shape = BuildItemRows(SIDEBAR_ITEMS, SIDEBAR_FOLDERS).map((row) => [
row.kind, row.kind === "folder" ? row.folder.name : row.item.name, row.depth,
]);
assert.deepEqual(shape, [
["folder", "Melee Weapons", 0],
["folder", "Ranged Weapons", 0],
["folder", "Powder Weapons", 1],
["item", "Pistol", 1],
["item", "Torch", 0],
["item", "Longsword", 1],
]);
});
test("a collapsed folder hides its whole subtree", () => {
const rows = BuildItemRows(SIDEBAR_ITEMS, SIDEBAR_FOLDERS, ["f-ranged"]);
assert.ok(rows.some((row) => row.kind === "folder" && row.folder.name === "Ranged Weapons"));
assert.ok(!rows.some((row) => row.kind === "item" && row.item.name === "Pistol"), "the nested item is hidden too");
});
test("without any folder the list is the plain item list", () => {
const rows = BuildItemRows([{ _id: "i-1", name: "Torch" }, { _id: "i-2", name: "Longsword" }], []);
assert.deepEqual(rows.map((row) => [row.kind, row.item.name, row.depth]), [
["item", "Longsword", 0],
["item", "Torch", 0],
]);
});
test("an item whose folder is gone, or a folder nested in itself, reads as a root item", () => {
const rows = BuildItemRows(
[{ _id: "i-1", name: "Torch", folder: "f-gone" }],
[{ _id: "f-a", name: "A", parentFolder: "f-b" }, { _id: "f-b", name: "B", parentFolder: "f-a" }],
);
const shape = rows.map((row) => [row.kind, row.kind === "folder" ? row.folder.name : row.item.name]);
assert.ok(shape.includes(["item", "Torch"]), "the item is not lost with the folder that was removed");
assert.deepEqual(new Set(shape.filter(([kind]) => kind === "folder").map(([, name]) => name)), new Set(["A", "B"]));
assert.equal(rows.filter(([kind]) => kind === "folder").length, 2, "a broken tree is walked once, not forever");
});
test("every locale labels the item folder row", () => {
for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
assert.ok(campaigns.item?.["folder-toggle"], `${locale} is missing campaigns.item.folder-toggle`);
}
});

View File

@@ -0,0 +1,106 @@
// Tests for Syndria98/dragonroll#35: clicking an item in the campaign sidebar opens a window with
// the item's info, and that window can pick the item's icon — Foundry's own when the item is synced,
// or an uploaded one.
//
// The mapper from a Foundry item to Dragonroll item fields is a pure CommonJS service, so it is
// required and called directly. The window wiring lives in files this repository installs no
// dependencies for, so those checks read the sources, like tests/map-viewer.test.js does.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const { foundryItemToItemData } = require(path.join(__dirname, "..", "backend", "src", "services", "item-foundry"));
const sidebarSource = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
const itemWindowSource = read("frontend", "app", "components", "windows", "ItemSheetWindow.vue");
const itemRouteSource = read("backend", "src", "routes", "item.js");
const itemModelSource = read("backend", "src", "models", "Item.js");
const foundryLinkSource = read("backend", "src", "routes", "foundry-link.js");
const moduleSource = read("dragonroll-foundry", "scripts", "api.js");
test("a synced Foundry item carries its icon over to the Dragonroll item", () => {
const fields = foundryItemToItemData({
name: "Longsword",
type: "weapon",
img: "http://vtt.test/icons/svg/sword.svg",
system: { quantity: 1, weight: 3, rarity: "common" },
});
assert.equal(fields.image, "http://vtt.test/icons/svg/sword.svg");
});
test("a Foundry item without an icon maps to an empty one", () => {
const fields = foundryItemToItemData({ name: "Torch", type: "loot", system: { quantity: 1 } });
assert.equal(fields.image, "");
});
test("the Item model stores the icon and the icon Foundry last sent", () => {
assert.match(itemModelSource, /image:\s*{\s*type:\s*String/);
assert.match(itemModelSource, /foundryImage:\s*{\s*type:\s*String/);
});
test("Foundry sync keeps foundryImage even when the save preserves Dragonroll edits", () => {
// The preserve-edits rule must not cover foundryImage: it is Foundry's state,
// and the item window offers it back after the user picked their own icon.
const keep = /if \(!fullSync \|\| item\.isNew\) Object\.assign\(item, fields\);([\s\S]{0,220}?)if \(!item\.foundryNames/.exec(foundryLinkSource);
assert.ok(keep, "expected the foundryImage keep between the guarded assign and the name bookkeeping");
assert.match(keep[1], /if \(fields\.image\) item\.foundryImage = fields\.image;/);
});
test("the item routes accept the icon and upload one", () => {
assert.match(itemRouteSource, /router\.post\(["']\/upload-image["'], upload\.single\(["']image["']\)/);
assert.match(itemRouteSource, /req\.query\.item \|\| req\.body\.item/);
assert.match(itemRouteSource, /item\.image = req\.file\.filename/);
// the upload checks ownership like every other item handler
const uploadRoute = /router\.post\(["']\/upload-image[\s\S]*?module\.exports/.exec(itemRouteSource)?.[0] ?? itemRouteSource;
assert.match(uploadRoute, /userOwnsCampaign\(item\.campaign, req\.user\.id\)/);
// /update accepts the icon so the window can switch between own and Foundry's
assert.match(itemRouteSource, /if \(image !== undefined\) item\.image = String\(image\);/);
});
test("the item info window is registered and opens on a sidebar click", () => {
assert.match(windowDefsSource, /item_sheet:\s*{\s*title:[^}]*ItemSheetWindow\.vue/s);
// clicking (or Enter/Space on) an item row opens the window instead of expanding inline.
// Since #44 the rows come from the folder tree the world synced, so the row holds the item.
assert.match(sidebarSource, /v-for="row in itemRows"[\s\S]*?@click="openItemSheet\(row\.item\)"/);
assert.match(sidebarSource, /CreateWindow\(['"]item_sheet['"],\s*\{ item \}\)/);
assert.doesNotMatch(sidebarSource, /toggleEntryDetails/);
});
test("the item window shows the info and offers both icon sources", () => {
// info: name, category, rarity, quantity, weight, properties, description
for (const key of ["form.name", "form.category", "form.rarity", "form.quantity", "form.weight", "form.properties", "form.description"]) {
assert.ok(itemWindowSource.includes(key), `expected the window to render ${key}`);
}
// own icon: upload through the item route like the character sheet does its photo
assert.match(itemWindowSource, /\/item\/upload-image\?item=/);
// Foundry icon: switch the item image back to the one the world sent
assert.match(itemWindowSource, /form\.value\.foundryImage/);
assert.match(itemWindowSource, /updateItem\(\{ image: form\.value\.foundryImage \}\)/);
// uploads resolve as backend /public files, world URLs load as they are
assert.match(itemWindowSource, /\$\{getBaseUrl\(\)\}\/public\//);
});
test("the Foundry module sends item icons as URLs Dragonroll can load", () => {
// actor-embedded items go through the same serializer as world items
assert.match(moduleSource, /items:\s*\(actor\.items\?\.contents\?\.map\(serializeFoundryItem\)/);
// the icon chosen in Dragonroll travels back into the linked world
assert.match(moduleSource, /const image = getDragonrollImageUrl\(entry\.image\);\s*if \(image\) updates\.img = image;/);
assert.match(moduleSource, /img: getDragonrollImageUrl\(entry\.image\) \|\| undefined,\s*system:/);
});
test("every locale names the item window and its icon controls", () => {
for (const locale of ["en", "es", "ca"]) {
const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json"));
assert.ok(windows["item-sheet"], `${locale} is missing the item window title`);
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
for (const key of ["choose-icon", "change-icon", "foundry-icon", "remove-icon", "upload-error"]) {
assert.ok(campaigns.item?.sheet?.[key], `${locale} is missing campaigns.item.sheet.${key}`);
}
}
});

View File

@@ -83,6 +83,8 @@ function loadMapRoutes({ ownsCampaign = true, maps = [], notes = [] } = {}) {
: null : null
), ),
}, },
// The pins do not ask after actors, only the token routes below do.
"../models/Actor": { findOne: () => mongooseQuery(null) },
}); });
} }

344
tests/map-tokens.test.js Normal file
View File

@@ -0,0 +1,344 @@
// Tests for the actor tokens of a map (Syndria98/dragonroll#38): an actor dragged out of the campaign
// sidebar lands on the map as a token, and that token is then moved from cell to cell of the grid.
//
// Same set-up as tests/map-pins.test.js, which the repository root runs without installing anything:
// the express routers are loaded into `node:vm` with their models stubbed, `MapTokens.js` is loaded as
// a plain function, and the last checks read the templates, where the drag and drop wiring itself is
// what has to stay right.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
function readRepoFile(...parts) {
return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
}
// A mongoose query answers whatever `await query` and `query.lean()` answer with, and lets `select()`
// and `sort()` sit in between.
function mongooseQuery(value) {
const result = {
select: () => result,
sort: () => result,
lean: () => Promise.resolve(value),
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
};
return result;
}
// Loads an express router file with every module it requires stubbed out.
function loadRouter(relativeParts, stubs) {
const routes = new Map();
const router = {
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id === "../services/storage") return { single: () => (req, res, next) => next() };
if (!(id in stubs)) throw new Error(`require("${id}") is not stubbed`);
return stubs[id];
};
const moduleStub = { exports: {} };
vm.compileFunction(readRepoFile(...relativeParts), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
async function call(route, { body = {}, query = {}, params = {}, user = { id: "user-1" } } = {}) {
const handlers = routes.get(route);
assert.ok(handlers, `${route} is not mounted`);
const res = { payload: null, json(payload) { this.payload = payload; } };
await handlers[handlers.length - 1]({ body, query, params, user }, res);
return res.payload;
}
return { routes, call };
}
function makeMap(tokens = [], grid = {}) {
return {
_id: "map-1", campaign: "campaign-1", tokens,
gridSize: 50, offsetX: 0, offsetY: 0,
...grid,
save: async () => {}
};
}
function loadMapRoutes({ ownsCampaign = true, maps = [], actors = [] } = {}) {
return loadRouter(["backend", "src", "routes", "map.js"], {
"../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) },
"../models/Map": { findById: (id) => mongooseQuery(maps.find((map) => map._id === id) ?? null) },
"../models/Note": { findOne: () => mongooseQuery(null) },
"../models/Actor": {
findOne: (filter) => mongooseQuery(
actors.some((actor) => actor._id === String(filter._id) && String(actor.campaign) === String(filter.campaign))
? { _id: String(filter._id) }
: null
),
},
});
}
function placeTokenRouteTests() {
test("an actor dropped on the map stands in the middle of the cell it landed on", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 124, y: 76 } });
assert.equal(response.status, "ok");
// 50 px cells: 124 falls in the column centred on 125, 76 in the row centred on 75.
assert.deepEqual(map.tokens, [{ actor: "actor-1", x: 125, y: 75 }]);
});
test("a token lands in the cell of a grid that does not start at the corner of the image", async () => {
const map = makeMap([], { gridSize: 40, offsetX: 10, offsetY: 4 });
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 55, y: 20 } });
assert.deepEqual(map.tokens, [{ actor: "actor-1", x: 70, y: 24 }]);
});
test("an actor of another campaign cannot be made to stand on a map", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-2", campaign: "campaign-2" }] });
const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-2", x: 10, y: 10 } });
assert.equal(response.msg, "errors.notfound");
assert.deepEqual(map.tokens, []);
});
test("a map of somebody else's campaign answers unauthorized", async () => {
const map = makeMap();
const api = loadMapRoutes({ ownsCampaign: false, maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 10, y: 10 } });
assert.equal(response.msg, "unauthorized");
assert.deepEqual(map.tokens, []);
});
test("placing an actor again moves its token instead of adding a twin", async () => {
const map = makeMap([{ _id: "token-1", actor: "actor-1", x: 25, y: 25 }]);
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 300, y: 224 } });
assert.equal(map.tokens.length, 1);
assert.deepEqual({ ...map.tokens[0] }, { _id: "token-1", actor: "actor-1", x: 325, y: 225 });
});
test("placing a token needs both a map and an actor", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
assert.equal((await api.call("POST /place-token", { body: { actor: "actor-1", x: 1, y: 1 } })).msg, "errors.missing-data");
assert.equal((await api.call("POST /place-token", { body: { id: "map-1", x: 1, y: 1 } })).msg, "errors.missing-data");
assert.deepEqual(map.tokens, []);
});
test("removing a token takes the one it is given and keeps the others", async () => {
const map = makeMap([
{ _id: "token-1", actor: "actor-1", x: 25, y: 25 },
{ _id: "token-2", actor: "actor-2", x: 75, y: 25 },
]);
const api = loadMapRoutes({ maps: [map] });
const response = await api.call("POST /remove-token", { body: { id: "map-1", token: "token-1" } });
assert.equal(response.status, "ok");
assert.deepEqual(map.tokens.map((token) => token._id), ["token-2"]);
});
test("removing a token of a map of somebody else keeps its tokens", async () => {
const map = makeMap([{ _id: "token-1", actor: "actor-1", x: 25, y: 25 }]);
const api = loadMapRoutes({ ownsCampaign: false, maps: [map] });
const response = await api.call("POST /remove-token", { body: { id: "map-1", token: "token-1" } });
assert.equal(response.msg, "unauthorized");
assert.equal(map.tokens.length, 1);
});
}
function loadActorRoutes({ ownsCampaign = true, actors = [], deletedCount = 1 } = {}) {
const tokensPulled = [];
const api = loadRouter(["backend", "src", "routes", "actor.js"], {
"../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) },
"../models/Actor": {
findById: (id) => mongooseQuery(
actors.find((actor) => actor._id === id)
? { ...actors.find((actor) => actor._id === id), deleteOne: async () => ({ deletedCount }) }
: null
),
},
"../models/Map": {
// The driver drops the tokens of the actor from every map holding one; what is worth
// keeping here is the filter it is asked to do that with.
updateMany: async (filter, update) => {
tokensPulled.push({ filter, update });
return { modifiedCount: 1 };
},
},
});
return { api, tokensPulled };
}
function actorDeletionTests() {
test("deleting an actor takes its tokens off the maps", async () => {
const { api, tokensPulled } = loadActorRoutes({ actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const response = await api.call("POST /delete", { body: { id: "actor-1" } });
assert.equal(response.status, "ok");
assert.deepEqual(tokensPulled, [{ filter: { "tokens.actor": "actor-1" }, update: { $pull: { tokens: { actor: "actor-1" } } } }]);
});
test("a token is not left behind by an actor that could not be deleted", async () => {
const { api, tokensPulled } = loadActorRoutes({ ownsCampaign: false, actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const response = await api.call("POST /delete", { body: { id: "actor-1" } });
assert.equal(response.msg, "unauthorized");
assert.deepEqual(tokensPulled, []);
});
}
function loadMapTokensService() {
const source = readRepoFile("frontend", "app", "services", "MapTokens.js");
const body = source
.replace(/import\s*\{[^}]*\}\s*from\s*['"]vue['"];?/, "")
.replace(/export\s*\{/, "return {")
.concat("\n;");
return vm.compileFunction(body, [])();
}
function mapTokensServiceTests() {
const service = loadMapTokensService();
const grid = { gridSize: 50, offsetX: 0, offsetY: 0 };
test("a spot of the image becomes the middle of the cell it stands in", () => {
assert.deepEqual(service.CellCentre({ x: 124, y: 76 }, grid), { x: 125, y: 75 });
assert.deepEqual(service.CellCentre({ x: 125, y: 75 }, grid), { x: 125, y: 75 });
});
test("cells are counted from the grid origin, not from the corner of the image", () => {
const shifted = { gridSize: 40, offsetX: 10, offsetY: 4 };
assert.deepEqual(service.CellCentre({ x: 55, y: 20 }, shifted), { x: 70, y: 24 });
});
test("a token never stands off the top left corner of the map", () => {
assert.deepEqual(service.CellCentre({ x: -8, y: -1 }, grid), { x: 25, y: 25 });
// A grid starting off the image still cannot put a token at a negative pixel.
assert.deepEqual(service.CellCentre({ x: -8, y: -1 }, { gridSize: 40, offsetX: -30, offsetY: 0 }), { x: 0, y: 20 });
});
test("a grid with nothing set is the 50 px grid the backend defaults to", () => {
assert.deepEqual(service.CellCentre({ x: 10, y: 10 }, {}), { x: 25, y: 25 });
assert.deepEqual(service.CellCentre({ x: 10, y: 10 }, undefined), { x: 25, y: 25 });
});
test("a spot that is not a spot centres on nothing", () => {
assert.equal(service.CellCentre({ x: NaN, y: 10 }, grid), null);
assert.equal(service.CellCentre({}, grid), null);
assert.equal(service.CellCentre(undefined, grid), null);
});
test("the arrow keys walk a token over whole cells", () => {
assert.deepEqual(service.MoveByCells({ x: 125, y: 75 }, grid, -1, 2), { x: 75, y: 175 });
assert.deepEqual(service.MoveByCells({ x: 25, y: 25 }, grid, -3, -1), { x: 0, y: 0 });
assert.equal(service.MoveByCells({ x: 25 }, grid, 1, 0), null);
});
test("a token covers the cell it stands on and never shrinks below an icon", () => {
assert.equal(service.TokenSize(grid, 1), 50);
assert.equal(service.TokenSize(grid, 0.2), 18);
assert.equal(service.TokenSize({ gridSize: 80 }, 2), 160);
});
test("the map tells an actor drag from any other drag dropped on it", () => {
const actorDrag = {
dataTransfer: {
types: [service.ACTOR_DRAG_TYPE],
getData: (type) => (type === service.ACTOR_DRAG_TYPE ? "actor-1" : "")
}
};
const noteDrag = { dataTransfer: { types: ["text/plain"], getData: (type) => (type === "text/plain" ? "note-1" : "") } };
assert.equal(service.IsActorDrag(actorDrag), true);
assert.equal(service.ActorDragId(actorDrag), "actor-1");
assert.equal(service.IsActorDrag(noteDrag), false);
assert.equal(service.ActorDragId(noteDrag), null);
assert.equal(service.IsActorDrag(undefined), false);
assert.equal(service.ActorDragId(undefined), null);
});
test("the viewer and the route agree on where a token stands", async () => {
// A drop is snapped while it is dragged and again when it is saved: the token must not jump.
const map = makeMap([], { gridSize: 40, offsetX: 10, offsetY: 4 });
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const spot = { x: 300, y: 220 };
await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", ...spot } });
assert.deepEqual({ x: map.tokens[0].x, y: map.tokens[0].y }, service.CellCentre(spot, map));
});
}
function mapViewerTokenWiringTests() {
const pane = readRepoFile("frontend", "app", "components", "viewer", "map", "MapViewerPane.vue");
const sidebar = readRepoFile("frontend", "app", "components", "partials", "ContentSidebar.vue");
test("an actor row of the sidebar can be dragged out of it", () => {
const actorRow = /<div v-for="actor in actors"[^>]*>/.exec(sidebar)?.[0];
assert.ok(actorRow, "expected the actor rows of the sidebar");
assert.match(actorRow, /draggable="true"/);
assert.match(actorRow, /@dragstart="startActorDrag\(\$event, actor\)"/);
assert.match(sidebar, /setData\(ACTOR_DRAG_TYPE, String\(actor\._id\)\)/);
});
test("the map viewport takes the actor drag and places it", () => {
const viewport = /<div[^>]*ref="viewport"[\s\S]*?>/.exec(pane)?.[0];
assert.ok(viewport, "expected the map viewport element");
assert.match(viewport, /@dragover="onMapDragOver"/);
assert.match(viewport, /@drop\.prevent="onMapDrop"/);
});
test("tokens are drawn in screen space, sized by their cell, and only they catch the mouse", () => {
assert.match(pane, /class="map-token"[^>]*:style="tokenStyle\(token\)"/);
assert.match(pane, /\.map-tokens\s*\{[^}]*pointer-events:\s*none/);
assert.match(pane, /\.map-token\s*\{[^}]*pointer-events:\s*auto/);
});
test("dragging a token moves it and does not pan the map", () => {
assert.match(pane, /@pointerdown="onTokenPointerDown\(\$event, token\)"/);
assert.match(pane, /@pointermove="onTokenPointerMove"/);
assert.match(pane, /@pointerup="onTokenPointerUp"/);
// The pane stops the pointer before the viewport ever sees it, so holding a token never pans.
assert.match(pane, /function onTokenPointerDown\(event, token\) \{[^}]*?event\.stopPropagation\(\)/);
});
test("a token answers to the keyboard and its own menu", () => {
assert.match(pane, /@keydown="onTokenKeydown\(\$event, token\)"/);
assert.match(pane, /@contextmenu\.stop\.prevent="onTokenContextMenu\(token\)"/);
});
test("tokens are saved and taken off through the map routes", () => {
assert.match(pane, /['"]\/map\/place-token['"]/);
assert.match(pane, /['"]\/map\/remove-token['"]/);
});
}
placeTokenRouteTests();
actorDeletionTests();
mapTokensServiceTests();
mapViewerTokenWiringTests();

View File

@@ -0,0 +1,75 @@
// Tests for the motion error of Syndria98/dragonroll#34: the tooltip animated itself with
// `ease: 'ease-in'`, and motion throws `Invalid easing type 'ease-in'` on that. Motion's easing
// options are its own names (`easeIn`, `easeOut`, ...), not the CSS keywords, so every string ease
// option in the frontend has to be one of the names motion accepts.
//
// `frontend/app/services/Tooltip.js` imports `vue` and `motion` and the repository root installs no
// dependencies, so the checks read the sources the way `tests/map-viewer.test.js` reads them.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
// The strings motion accepts for `ease` (https://motion.dev/troubleshooting/invalid-easing-type).
const VALID_EASINGS = [
"linear",
"easeIn",
"easeInOut",
"easeOut",
"circIn",
"circInOut",
"circOut",
"backIn",
"backInOut",
"backOut",
"anticipate",
];
function frontendSources(dir = path.join(__dirname, "..", "frontend", "app")) {
const found = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) found.push(...frontendSources(full));
else if (/\.(js|ts|vue)$/.test(entry.name)) found.push({ file: full, source: fs.readFileSync(full, "utf8") });
}
return found;
}
// An ease option is the `ease` key of a JS object (motion's options), so it is always quoted. CSS
// `transition: ... ease` declarations have no colon after `ease` and never match.
function easeOptions(source) {
return [...source.matchAll(/\bease:\s*(['"])([^'"]*)\1/g)].map((match) => match[2]);
}
function readTooltip() {
return fs.readFileSync(
path.join(__dirname, "..", "frontend", "app", "services", "Tooltip.js"),
"utf8"
);
}
test("the tooltip keeps animating itself in and out", () => {
const ease = easeOptions(readTooltip());
// Guards the checks below against silently matching nothing.
assert.equal(ease.length, 2, `expected the show and the hide ease option, found ${ease.length}`);
});
test("the tooltip options use easing names motion accepts", () => {
for (const value of easeOptions(readTooltip())) {
assert.ok(VALID_EASINGS.includes(value), `invalid easing type '${value}'`);
}
});
test("no frontend animation uses a CSS keyword as motion easing", () => {
for (const { file, source } of frontendSources()) {
for (const value of easeOptions(source)) {
assert.ok(
VALID_EASINGS.includes(value),
`${path.relative(path.join(__dirname, ".."), file)} uses invalid easing type '${value}'`
);
}
}
});

View File

@@ -0,0 +1,154 @@
// Tests for Syndria98/dragonroll#29: the monorepo is a pnpm workspace, so running or installing it
// goes through pnpm (`pnpm install`, `pnpm dev`, `pnpm test`) and the images are built with the
// workspace manifests instead of one npm lockfile per package.
//
// These checks only read the manifests, the Dockerfiles and the workflows, so they need no installed
// dependencies. They fail when a package is added to the repository without joining the workspace, or
// when a build step slips back to npm and its deleted `package-lock.json`.
//
// Run with `pnpm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const root = path.join(__dirname, "..");
const read = (...parts) => fs.readFileSync(path.join(root, ...parts), "utf8");
const workspace = read("pnpm-workspace.yaml");
const rootManifest = JSON.parse(read("package.json"));
// `dragonroll-foundry/bridge` is deliberately left out: it depends on nothing but Node built-ins, it
// is not part of `pnpm dev`, and its README runs it with `npm start --prefix foundry/bridge`.
const apps = ["backend", "frontend", "discord-bot"];
function packageJsonOf(pkg) {
return JSON.parse(read(pkg, "package.json"));
}
// The items of a top-level `key:` list of pnpm-workspace.yaml, quotes dropped.
function yamlList(key) {
const block = new RegExp(`${key}\\n((?:\\s+-.*\\n?)+)`).exec(workspace)?.[1] ?? "";
return [...block.matchAll(/^\s+-\s+'?([^'\s]+)'?\s*$/gm)].map((match) => match[1]);
}
test("every app package of the monorepo belongs to the pnpm workspace", () => {
const listed = yamlList("packages:");
for (const pkg of apps) {
assert.ok(listed.includes(pkg), `${pkg} must be listed in pnpm-workspace.yaml`);
assert.ok(fs.existsSync(path.join(root, pkg, "package.json")), `${pkg} must have a package.json`);
}
});
test("the workspace root is private and pins one pnpm version for corepack", () => {
assert.equal(rootManifest.private, true, "the workspace root must not be publishable");
assert.match(rootManifest.packageManager, /^pnpm@\d+\.\d+\.\d+$/, "packageManager must pin pnpm");
});
test("npm lockfiles stay gone and pnpm-lock.yaml is the only lockfile", () => {
const lockfiles = ["", ...apps].flatMap((pkg) => [
path.join(root, pkg, "package-lock.json"),
path.join(root, pkg, "yarn.lock"),
]);
const present = lockfiles.filter((lockfile) => fs.existsSync(lockfile));
assert.deepEqual(present, [], `only pnpm-lock.yaml may exist, found ${present.join(", ")}`);
assert.ok(fs.existsSync(path.join(root, "pnpm-lock.yaml")), "pnpm-lock.yaml must be committed");
});
test("`pnpm dev` runs the whole monorepo through the workspace instead of npm --prefix", () => {
const dev = rootManifest.scripts.dev;
assert.match(dev, /^concurrently -k/, "the dev script keeps running every app together");
assert.ok(!/\bnpm\b/.test(dev), "the dev script must not call npm");
for (const pkg of apps) {
assert.ok(
dev.includes(`pnpm --filter ./${pkg}`),
`the dev script must run ${pkg} through the workspace: ${dev}`
);
}
// The Foundry launcher is not a package, so concurrently keeps driving it.
assert.match(dev, /node scripts\/run-foundry\.js/);
});
test("every app package can be started on its own", () => {
// `pnpm dev:<package>`; building stays `pnpm --filter ./frontend run build`.
for (const pkg of apps) {
const script = rootManifest.scripts[`dev:${pkg}`];
assert.ok(script, `the root needs a dev:${pkg} script`);
assert.match(script, new RegExp(`pnpm --filter ./${pkg} run \\w+`));
const packageScript = packageJsonOf(pkg).scripts[/run (\w+)$/.exec(script)[1]];
assert.ok(packageScript, `${pkg} must define the script dev:${pkg} runs`);
}
});
test("the Dockerfiles install with pnpm from the workspace root", () => {
for (const pkg of apps) {
const dockerfile = read(pkg, "Dockerfile");
assert.match(dockerfile, /corepack enable/, `${pkg}: pnpm must come from corepack`);
assert.match(
dockerfile,
/COPY pnpm-workspace\.yaml pnpm-lock\.yaml package.json/,
`${pkg}: the workspace manifests must be copied before installing`
);
assert.match(
dockerfile,
new RegExp(`pnpm install --frozen-lockfile[^\\n]*--filter \\./${pkg}`),
`${pkg}: dependencies must be installed from the lockfile, filtered to this package`
);
assert.ok(!/\bnpm (ci|install)\b/.test(dockerfile), `${pkg}: must not fall back to npm install`);
}
// The images are built from the repository root, so the manifests are in the context.
const deploy = read(".gitea", "workflows", "deploy.yml");
for (const pkg of apps) {
assert.ok(
deploy.includes(`-f ./${pkg}/Dockerfile .`),
`${pkg} must be built with the repository root as build context`
);
}
});
test("the test workflow runs the suite through pnpm", () => {
assert.match(read(".gitea", "workflows", "test.yml"), /corepack pnpm test/);
});
// Syndria98/dragonroll#33: PM2 and its `ecosystem.config.js` are gone. It started backend and frontend
// with `npm start`, a script neither package defines; production runs from the compose images (the `CMD`
// of each Dockerfile) and every dev process is started together by `pnpm dev`, checked above. These
// checks keep the PM2 ecosystem from creeping back in.
test("PM2 plays no part in running the monorepo", () => {
const ecosystems = [
"ecosystem.config.js",
"ecosystem.config.cjs",
"ecosystem.config.json",
"ecosystem.json",
].filter((file) => fs.existsSync(path.join(root, file)));
assert.deepEqual(ecosystems, [], `no PM2 ecosystem file may exist, found ${ecosystems.join(", ")}`);
const manifests = [[null, rootManifest], ...apps.map((pkg) => [pkg, packageJsonOf(pkg)])];
for (const [pkg, manifest] of manifests) {
const dependencies = { ...manifest.dependencies, ...manifest.devDependencies, ...manifest.optionalDependencies };
assert.ok(!dependencies.pm2, `${pkg ?? "the workspace root"} must not depend on pm2`);
}
// Neither the images nor the workflows nor compose may fall back to PM2.
const runbooks = [
".gitea/workflows/deploy.yml",
".gitea/workflows/test.yml",
"docker-compose.yml",
...apps.map((pkg) => `${pkg}/Dockerfile`),
];
for (const file of runbooks) {
const text = read(...file.split("/"));
assert.ok(!/\bpm2\b|ecosystem\.config/i.test(text), `${file} must not mention PM2`);
}
});
test("the workspace allows the dependencies that build native binaries to run their scripts", () => {
// pnpm skips install scripts of dependencies by default; the frontend build needs these two to
// place their native binary.
const allowed = yamlList("onlyBuiltDependencies:");
for (const dependency of ["esbuild", "@parcel/watcher"]) {
assert.ok(allowed.includes(dependency), `${dependency} must be listed in onlyBuiltDependencies`);
}
});

View File

@@ -0,0 +1,97 @@
// Tests for Syndria98/dragonroll#42: the Ctrl+K search only looked at notes; it now searches the
// whole campaign — notes (nested in folders included), actors, items and maps — and selecting a
// result opens that entry the same way the campaign sidebar opens it.
//
// The repository root installs no dependencies, so these checks read the search component's
// source, like tests/map-viewer.test.js reads its window.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const searchSource = read("frontend", "app", "components", "viewer", "topbar", "TopSearchBar.vue");
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
test("the search fetches notes, actors, items and maps of the campaign", () => {
for (const [route, key] of [
["/note/all", "notes"],
["/actor/list", "actors"],
["/item/list", "items"],
["/map/list", "maps"],
]) {
assert.ok(searchSource.includes(`'${route}'`), `expected the search to fetch ${route}`);
assert.ok(searchSource.includes(`'${key}'`), `expected the ${route} response key '${key}' to be read`);
}
// every list is fetched scoped to the current campaign
assert.match(searchSource, /params:\s*\{\s*campaign:\s*campaignId\.value\s*\}/);
});
test("every entry list is matched against the query, accent- and case-insensitively", () => {
// one shared normalisation like the action registry's own filter uses
assert.match(searchSource, /normalize\("NFD"\)\.replace\(\/\[\\u0300-\\u036f\]\/g,\s*""\)\.toLowerCase\(\)/);
// notes by title, actors / items / maps by name
for (const call of [
String.raw`pushMatches\(notes\.value,\s*'note',\s*n => n\.title\)`,
String.raw`pushMatches\(actors\.value,\s*'actor',\s*a => a\.name\)`,
String.raw`pushMatches\(items\.value,\s*'item',\s*i => i\.name\)`,
String.raw`pushMatches\(maps\.value,\s*'map',\s*m => m\.name\)`,
]) {
assert.match(searchSource, new RegExp(call));
}
// command actions keep matching through the registry
assert.match(searchSource, /searchActions\(query \?\? ''\)/);
});
test("selecting a result opens each entry type the way the sidebar opens it", () => {
// a note opens in the note column, with its content retrieved (/note/all never carries it)
assert.match(searchSource, /get\(`\/note\/retrieve\/\$\{note\.key\}`\)/);
assert.match(searchSource, /emitter\.emit\('push-note',\s*\{ key: full\._id, title: full\.title, text: full\.content \?\? ''/);
// a character replaces the open sheet window
assert.match(searchSource, /GetFirstWindowId\('character_sheet'\)/);
assert.match(searchSource, /CreateWindow\('character_sheet',\s*\{ actor \}\)/);
// an item replaces the open item window
assert.match(searchSource, /GetFirstWindowId\('item_sheet'\)/);
assert.match(searchSource, /CreateWindow\('item_sheet',\s*\{ item \}\)/);
// a map anchors on the note container, clearing a floating viewer first
assert.match(searchSource, /GetFirstWindowId\('map_viewer'\)/);
assert.match(searchSource, /AnchorMap\(map\)/);
// a command action still executes
assert.match(searchSource, /executeAction\(item\.data\.id\)/);
// the windows these opens use are all registered
for (const type of ["character_sheet", "item_sheet"]) {
assert.match(windowDefsSource, new RegExp(`${type}:\\s*\\{`));
}
});
test("keyboard Enter and clicking share one dispatcher over the combined results", () => {
// a single openResult handles every type, keyed off the result's type tag
assert.match(searchSource, /function openResult\(item\)[\s\S]*item\.type === 'note'[\s\S]*item\.type === 'actor'[\s\S]*item\.type === 'item'[\s\S]*item\.type === 'map'/);
// Enter on the selected row and a click on a row both go through it
assert.match(searchSource, /if \(event\.key === 'Enter'\)[\s\S]*?openResult\(combined\[selectedIndex\.value\]\)/);
assert.match(searchSource, /@click\.stop\.prevent="openResult\(item\)"/);
});
test("the palette shows what each result is and stays fresh", () => {
// every result carries its section's icon and label
for (const icon of ["book.svg", "user.svg", "box.svg", "map.svg"]) {
assert.ok(searchSource.includes(`/icons/iconoir/regular/${icon}`), `expected an icon per entry type (${icon})`);
}
assert.match(searchSource, /t\(`campaigns\.sections\.\$\{item\.type\}s`\)/);
// the section labels come from i18n: they exist in every locale
for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
for (const key of ["notes", "actors", "items", "maps"]) {
assert.ok(campaigns.sections?.[key], `${locale} is missing campaigns.sections.${key}`);
}
}
// refetched when the palette opens (Foundry syncs entries in the background)...
assert.match(searchSource, /function onFocus\(\)[\s\S]*?fetchSearchEntries\(\)/);
// ...and dropped when another campaign becomes the current one
assert.match(searchSource, /watch\(campaignId,\s*\(\)\s*=>\s*\{[^}]*notes\.value = \[\][^}]*actors\.value = \[\][^}]*items\.value = \[\][^}]*maps\.value = \[\]/);
});

View File

@@ -0,0 +1,114 @@
// Tests for the sidebar section buttons of Syndria98/dragonroll#41: clicking the actors or the items
// button must not change what the note container shows — an anchored map stays on the screen and the
// notes that were open stay open — while the notes and maps buttons keep switching the note container
// between those two, the way they have since #15.
//
// The repository root installs no dependencies, so `selectSection` is lifted out of the sidebar's
// `<script setup>` block and run in a `node:vm` context with its collaborators stubbed, the way
// tests/map-viewer.test.js loads Content.js. `ActivePane` is modelled as a plain value written by the
// `SetActivePane` stub, so a test asks the same question the user does: what is the note container
// showing after the click.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const source = fs.readFileSync(
path.join(__dirname, "..", "frontend", "app", "components", "partials", "ContentSidebar.vue"),
"utf8"
);
const script = /<script setup>([\s\S]*?)<\/script>/.exec(source)?.[1];
// Top-level functions of the script block: their bodies are indented, so the first `}` in column 0
// closes the function.
function functionSource(name) {
assert.ok(script, "expected the sidebar to have a <script setup> block");
const fn = new RegExp(`function ${name}\\s*\\([^)]*\\)\\s*\\{[\\s\\S]*?\\n\\}`).exec(script)?.[0];
assert.ok(fn, `expected a top-level ${name}() function in the sidebar script`);
return fn;
}
// The sidebar's section buttons with the pane they act on: `pane` is what the note container shows
// when the button is clicked and `anchoredMap` the map anchored on it.
function sidebar({ pane = "notes", anchoredMap = null } = {}) {
const body = [
functionSource("entryEntityType"),
functionSource("isEntrySection"),
functionSource("selectSection"),
"return selectSection;",
].join("\n\n");
const state = { activeSection: { value: "notes" }, pane, entriesFetched: [], anchoredMap: { value: anchoredMap } };
state.selectSection = vm.compileFunction(body, ["activeSection", "fetchCampaignEntries", "AnchoredMap", "SetActivePane"], {
parsingContext: vm.createContext({}),
})(
state.activeSection,
(section) => state.entriesFetched.push(section),
state.anchoredMap,
(value) => {
state.pane = value;
}
);
return state;
}
test("the actors button keeps an anchored map on the note container", () => {
const bar = sidebar({ pane: "map", anchoredMap: { _id: "map-1" } });
bar.selectSection("actors");
assert.equal(bar.pane, "map", "the anchored map must not be swapped for the notes");
assert.equal(bar.anchoredMap.value?._id, "map-1", "the map must stay anchored");
});
test("the items button keeps an anchored map on the note container", () => {
const bar = sidebar({ pane: "map", anchoredMap: { _id: "map-1" } });
bar.selectSection("items");
assert.equal(bar.pane, "map", "the anchored map must not be swapped for the notes");
assert.equal(bar.anchoredMap.value?._id, "map-1", "the map must stay anchored");
});
test("the actors button keeps the notes that are open showing", () => {
const bar = sidebar({ pane: "notes", anchoredMap: { _id: "map-1" } });
bar.selectSection("actors");
assert.equal(bar.pane, "notes", "the open notes must not be swapped for the anchored map");
});
test("the buttons still select the section they were clicked for", () => {
for (const section of ["notes", "actors", "items", "maps"]) {
const bar = sidebar({ pane: "map", anchoredMap: { _id: "map-1" } });
bar.selectSection(section);
assert.equal(bar.activeSection.value, section, `${section} must be the selected section`);
}
});
test("the actor and item buttons still load their own list", () => {
const bar = sidebar({ pane: "map", anchoredMap: { _id: "map-1" } });
bar.selectSection("actors");
bar.selectSection("items");
assert.deepEqual(bar.entriesFetched, ["actors", "items"]);
});
test("the notes button switches the note container back to the open notes", () => {
const bar = sidebar({ pane: "map", anchoredMap: { _id: "map-1" } });
bar.selectSection("notes");
assert.equal(bar.pane, "notes");
assert.equal(bar.anchoredMap.value?._id, "map-1", "switching to the notes keeps the map anchored");
});
test("the maps button shows the anchored map again", () => {
const bar = sidebar({ pane: "notes", anchoredMap: { _id: "map-1" } });
bar.selectSection("maps");
assert.equal(bar.pane, "map");
});
test("the maps button has nothing to show without an anchored map", () => {
const bar = sidebar({ pane: "notes" });
bar.selectSection("maps");
assert.equal(bar.pane, "notes");
});