More things
Some checks failed
Test / test (push) Failing after 5s
Build and Deploy Nuxt / build (push) Successful in 2m3s

This commit is contained in:
2026-11-20 18:59:01 +01:00
parent b83f64ff9e
commit d61659cfdd
51 changed files with 1777 additions and 3817 deletions

View File

@@ -83,19 +83,20 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user
- `User` — `name*`, `username*`, `email*` (both unique), `password` (bcrypt, 10 rounds), `admin`, `image`, `setupCode`, `settings`
- `Campaign` — `name*`, `createdBy*`→User, `description`, `color`, `settings`, `foundryWorldId`/`foundryWorldTitle`/`foundrySystem`, `foundrySyncTokenHash` (`select: false`), `discordGuildId`
- `Note` — `title`, `content` (markdown source), `campaign*`, `folder` (null = root), `color`, `foundryPageId`
- `Note` — `title`, `content` (markdown source), `campaign*`, `folder` (null = root), `color`
- `Media` — `name*`, `file*` (filename in `src/uploads`), `mimeType*`, `campaign*`, `folder` (a note folder; null = root), listed in the notes sidebar beside the notes
- `Folder` — `name*`, `campaign*`, `parentFolder` (null = root, self-ref), `color`
- `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), `discordUserId` (the Discord player holding the character, unique per campaign — set only by `routes/discord.js`), 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`
- `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`, or a full URL a synced scene's
picture arrives as), `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`), `foundrySceneId` (the Foundry scene this map mirrors, unique per campaign)
- `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`, or a full URL), `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
**API surface** (all under `/api`, all `{status,msg}`):
- `user` — `register`, `verify-setup?code=`, `setup?code=`, `login` (`{usermail,password}`, accepts username or email → `{token}`), `upload-avatar` (multipart `image`, JWT) / `retrieve-avatar?username=`, `has-admin`, `update-settings` / `get-settings`. Files fetched from `/api/public/<filename>`.
- `campaign` — `create`, `update`, `list`, `retrieve/:id`, `services` + `service-unlink` (what is linked to a campaign)
- `note` — `list?campaign=` (root notes + folders with `parentFolder`), `subfolder/list?campaign=&folder=`, `all?campaign=` (titles only, for the map pin picker), `retrieve/:id`, `create`, `update` (partial), `delete`
- `note` — `list?campaign=` (root notes + folders with `parentFolder`), `subfolder/list?campaign=&folder=`, `all?campaign=` (titles only, for the map pin picker), `retrieve/:id`, `create`, `update` (partial), `delete` (both list routes also answer with the `media` standing at that level)
- `media` — `upload` (multipart `file`, plus `campaign` and optional `folder`), `update` (`{id, folder}`, moves a row in the note tree), `delete` (drops the row and its uploaded file)
- `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`
- `item` — `list`, `create`, `update` (partial), `delete`
@@ -115,17 +116,14 @@ rest, expire after 10 min, and Obsidian gets a long-lived (365 d) token back.
Foundry then syncs with that token on `/api/foundry/sync/*` (`routes/foundry-link.js`, mounted before
the JWT guard; CORS opened for it): `snapshot` (actors + world items, `fullSync` also prunes),
`item-snapshot`, `item-delete`, `scenes` (the world's scenes as the campaign's maps, `fullSync` also
prunes), `scene-delete`, `characters`, `items`, `notes` / `map-note`, `status`, `unlink`,
`map` / `map-item`, `delete`. Rules:
`item-snapshot`, `item-delete`, `status`, `unlink`, `delete`. Sync runs **one way — Foundry to
Dragonroll — and only characters and items**; nothing is written back into the world. Rules:
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index); a Foundry document carrying the `dragonroll-foundry.actorId` / `.itemId` flag adopts the matching Dragonroll row.
- **Only the world's item directory reaches the item list** (Syndria98/dragonroll#67) — `snapshotItemSources` reads `body.items` (`game.items`) alone; gear embedded in a character is that actor's `inventory` (see the `Actor` model), not an `Item`. A world item still folds into a hand-made or renamed row it matches by name (`foundryNames`), so a rename does not resurrect a duplicate. `services/item-foundry.js` returns `null` for non-gear types and those are skipped.
- **Item folders mirror the world's item directory** (`Folder.foundryFolderId`, target `item`): every push carries the whole tree and the world owns its names and nesting. `color` is the one field the campaign sets too, so it travels back with the folders `GET /foundry/sync/items` answers with (`{items, folders}`) and the module writes it onto the world's folder.
- **A world's scenes arrive as its campaign's maps** (Syndria98/dragonroll#99): `POST /foundry/sync/scenes` writes one `Map` per scene through `saveFoundryScene`, and only the scene's background picture and grid cross over (`services/map-foundry.js`: `gridSize` from `grid`/`grid.size`, the offsets from `flags.core.shiftX`/`.shiftY`) — `scale`, the folder, the pins and the tokens stay with the campaign and nothing of a map goes back to the world. Identity is `Map.foundrySceneId` (unique per campaign), a `dragonroll-foundry.mapId` flag or a hand-made unmapped map of the same name; a scene with no picture makes no map. `POST /foundry/sync/scene-delete` drops the map of a deleted scene, and only the full list the module sends when the world links or loads prunes.
- **Notes reach the world as journal pages, one way** (Syndria98/dragonroll#98): the module reads `GET /sync/notes` and stands each campaign folder as a world `JournalEntry` named after its path (root notes share `Dragonroll`, a note in `Sessions/Arc 1` gets `Sessions / Arc 1`) — the page carries the note's id in a `dragonroll-foundry.noteId` flag, the note keeps the page's id in `foundryPageId` (`POST /sync/map-note`). The backend computes the path (`folderPath`) and includes it in the revision hash, so a rename or move reaches the world. The reconcile rewrites pages from the notes, moves a note's page when it changes folder, renames a folder journal with its folder and drops the page of a deleted note; journal edits never travel back. A folder journal with no notes left goes unless the GM keeps pages of their own in it, and a world holding several journals for root notes keeps only the one the notes live in. The poll asks `GET /sync/notes/revision` (a hash of the notes and folder paths) every 15 s and only pulls the notes over when that hash or the pages it last wrote have changed, so an untouched campaign is not re-read and rewritten every few seconds. A note's `@roll` widgets are drawn as buttons in the page: a delegated click handler evaluates the expression with Foundry's `Roll` and posts it to chat (`adv`/`dis` become `kh1`/`kl1`).
- **Item folders mirror the world's item directory** (`Folder.foundryFolderId`, target `item`): every push carries the whole tree, and the world owns its names, nesting and colours.
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events overwrite. Only a full snapshot can prune.
- **Autosync is a Foundry-side setting** (`autoSync`, on by default): off = no CRUD push, no periodic reconcile, no startup snapshot; the actor directory's *Dragonroll: Force Sync* still upserts the selection (`fullSync:false`).
- **Autosync is a Foundry-side setting** (`autoSync`, on by default): off = no CRUD push and no startup snapshot; the actor directory's *Dragonroll: Force Sync* still upserts the selection (`fullSync:false`).
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge. Its one write, `POST /import`, pulls the bridge's actors or world items into the campaign through the same writers as a sync push.
## 5. Frontend

View File

@@ -84,6 +84,7 @@ app.use(checkAuth);
// ROUTES WITH AUTH
app.use('/api/campaign', require('./routes/campaign'));
app.use('/api/note', require('./routes/note'));
app.use('/api/media', require('./routes/media'));
app.use('/api/folder', require('./routes/folder'));
app.use('/api/actor', require('./routes/actor'));
app.use('/api/item', require('./routes/item'));

View File

@@ -39,15 +39,7 @@ const MapSchema = new Schema({
ref: 'Folder',
default: null
},
// The Foundry scene this map mirrors, set by the scene sync only
// (see routes/foundry-link.js). Only the picture and the grid follow the world.
foundrySceneId: { type: String },
date: { type: Date, default: Date.now }
});
MapSchema.index(
{ campaign: 1, foundrySceneId: 1 },
{ unique: true, partialFilterExpression: { foundrySceneId: { $type: 'string' } } }
);
module.exports = mongoose.model('Map', MapSchema);

View File

@@ -0,0 +1,23 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// A media file of a campaign's note tree: an image, a sound, a video or a document uploaded to
// src/uploads and listed in the sidebar beside the notes. It holds no content of its own, only the
// name it shows under, the file it points at and the note folder it stands in.
const MediaSchema = new Schema({
name: { type: String, required: true },
file: { type: String, required: true },
mimeType: { type: String, required: true },
campaign: {
type: Schema.Types.ObjectId,
ref: 'Campaign',
required: true
},
folder: {
type: Schema.Types.ObjectId,
ref: 'Folder'
},
date: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Media', MediaSchema);

View File

@@ -14,17 +14,7 @@ const NoteSchema = new Schema({
ref: 'Folder'
},
color: { type: String },
// The journal page this note is written as in the linked Foundry world: a page
// of the journal of this note's folder (root notes: "Dragonroll") whose rows
// carry this note's id in their `dragonroll-foundry.noteId` flag (see the
// module's notes sync).
foundryPageId: { type: String },
date: { type: Date, default: Date.now }
});
NoteSchema.index(
{ campaign: 1, foundryPageId: 1 },
{ unique: true, partialFilterExpression: { foundryPageId: { $type: 'string' } } }
);
module.exports = mongoose.model('Note', NoteSchema);

View File

@@ -6,6 +6,7 @@ const Actor = require('../models/Actor');
const Folder = require('../models/Folder');
const Map = require('../models/Map');
const Note = require('../models/Note');
const Media = require('../models/Media');
const Item = require('../models/Item');
async function userOwnsCampaign(campaignId, userId) {
@@ -99,6 +100,10 @@ router.post('/delete', async (req, res) => {
{ folder: folderId },
{ $set: { folder: null, date: Date.now() } }
);
await Media.updateMany(
{ folder: folderId },
{ $set: { folder: null, date: Date.now() } }
);
await Actor.updateMany(
{ folder: folderId },
{ $set: { folder: null } }

View File

@@ -6,13 +6,9 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Item = require('../models/Item');
// Not `Map`: this route builds plain `Map`s of its own to mirror the world's folder tree.
const MapModel = require('../models/Map');
const Folder = require('../models/Folder');
const Note = require('../models/Note');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
const { foundrySceneToMapData } = require('../services/map-foundry');
const { joinFoundryAssetUrl } = require('../services/foundry-icons');
const serviceLinks = require('../services/service-links');
@@ -245,9 +241,7 @@ async function syncFoundryItemFolders(campaign, folderSources) {
// 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;
// Its colour is the one part of the tree the campaign colours too: what the
// world shows arrives here, and what the campaign picks travels back to the
// world with the folder list `/sync/items` answers with.
// The colour the world shows for the folder arrives here with the tree.
if (source.color !== undefined) folder.color = source.color;
const parent = inTree.has(source.parent) ? folders.get(source.parent) : null;
folder.parentFolder = parent ? parent._id : null;
@@ -276,48 +270,6 @@ function resolveFoundryItemFolder(source, folders) {
return folders.get(foundryFolderId.trim())?._id || null;
}
// --- Maps -------------------------------------------------------------------
// A scene of the world becomes one of the campaign's maps (Syndria98/dragonroll#99):
// services/map-foundry.js says what of a scene travels — its background picture and the
// grid laid over it, and nothing else, so the map's pins, its tokens, the folder it
// stands in and what one of its cells means stay the campaign's own.
async function saveFoundryScene(campaign, source, fullSync = false) {
const foundrySceneId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundrySceneToMapData(source || {});
if (!foundrySceneId || !fields) return null;
resolveWorldAssets(fields, campaign);
let map = await MapModel.findOne({ campaign: campaign._id, foundrySceneId });
const dragonrollMapId = source?.flags?.['dragonroll-foundry']?.mapId;
if (!map && mongoose.isValidObjectId(dragonrollMapId)) {
const flagged = await MapModel.findOne({ _id: dragonrollMapId, campaign: campaign._id });
// Only adopt a flagged map while no other scene owns its mapping.
if (flagged && (!flagged.foundrySceneId || flagged.foundrySceneId === foundrySceneId)) map = flagged;
}
if (!map) {
// The campaign drew this place by hand before the scene of it ever arrived: a scene
// naming the one unmapped map the campaign holds folds into that row instead of
// adding a second copy of the same room.
const sameName = await MapModel.find({
campaign: campaign._id,
name: fields.name,
foundrySceneId: { $exists: false }
}).limit(2);
map = sameName.length === 1 ? sameName[0] : new MapModel({ campaign: campaign._id });
}
map.foundrySceneId = foundrySceneId;
// `created` says whether this row is new, like the actor and item writers answer it.
const created = map.isNew;
// A full snapshot runs when a GM reconnects: the grid the campaign lined up for a map
// it already has survives that. Live scene edits continue to overwrite normally.
if (!fullSync || map.isNew) Object.assign(map, fields);
await map.save();
return { foundrySceneId, mapId: map.id, created };
}
// 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
// with the campaign once that link has handed it its token.
@@ -433,41 +385,6 @@ router.post('/sync/delete', async (req, res) => {
}
});
router.get('/sync/characters', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const actors = await Actor.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
res.json({ status: 'ok', actors });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/sync/map', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const { actorId, foundryActorId, worldId } = req.body;
if (!requestMatchesWorld(campaign, worldId) || !actorId || !foundryActorId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const actor = await Actor.findOne({ _id: actorId, campaign: campaign._id });
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
const existing = await Actor.findOne({ campaign: campaign._id, foundryActorId, _id: { $ne: actor._id } });
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.actor-already-synced' });
actor.foundryActorId = String(foundryActorId).trim().slice(0, 120);
await actor.save();
res.json({ status: 'ok', actor });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Only world-level Foundry items reach this route: an item dropped by an actor
// still exists in the world, and its actor snapshot overwrites the inventory.
router.post('/sync/item-delete', async (req, res) => {
@@ -487,218 +404,6 @@ router.post('/sync/item-delete', async (req, res) => {
}
});
// The world's scenes, upserted as the campaign's maps (Syndria98/dragonroll#99). Like a
// world item push, this one prunes only when it is told it carries every scene: that push
// alone sees the whole scene list, so it alone knows which synced maps the world has let go
// of. A map the campaign made by hand has no scene of its own and is never pruned.
router.post('/sync/scenes', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.scenes)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const fullSync = req.body.fullSync === true;
const maps = [];
for (const source of req.body.scenes) {
const mapping = await saveFoundryScene(campaign, source, fullSync);
if (mapping) maps.push(mapping);
}
if (fullSync) {
const currentIds = req.body.scenes
.map((source) => String(source?._id || source?.id || '').trim())
.filter(Boolean);
await MapModel.deleteMany({
campaign: campaign._id,
foundrySceneId: { $exists: true, $nin: currentIds }
});
}
res.json({ status: 'ok', maps });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// A scene the world deleted takes its map with it. Only the world says so; deleting a map
// in the campaign leaves the world's scene alone, which is the campaign's own to do.
router.post('/sync/scene-delete', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const foundrySceneId = String(req.body.foundrySceneId || '').trim();
if (!requestMatchesWorld(campaign, req.body.worldId) || !foundrySceneId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
await MapModel.deleteOne({ campaign: campaign._id, foundrySceneId });
res.json({ status: 'ok' });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// The item list the world reconciles against, together with the folders its rows are
// grouped into — the same shape the campaign's own `/item/list` answers with. The folders
// travel back for their colour: the world owns the tree's name and nesting, while whoever
// colours a folder on either side expects to see it coloured on the other.
router.get('/sync/items', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const items = await Item.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
const folders = await Folder.find({ campaign: campaign._id, target: 'item' })
.select('_id name color foundryFolderId')
.sort({ name: 1 })
.lean();
res.json({ status: 'ok', items, folders });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/sync/map-item', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const { itemId, foundryItemId, worldId } = req.body;
if (!requestMatchesWorld(campaign, worldId) || !itemId || !foundryItemId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const item = await Item.findOne({ _id: itemId, campaign: campaign._id });
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
const existing = await Item.findOne({ campaign: campaign._id, foundryItemId, _id: { $ne: item._id } });
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.item-already-synced' });
item.foundryItemId = String(foundryItemId).trim().slice(0, 120);
await item.save();
res.json({ status: 'ok', item });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// --- Note pages ------------------------------------------------------------
// The campaign's notes are read where their authors' table sits: each note
// stands as a page of the journal of the folder it lives in, and root notes share
// the journal the world calls "Dragonroll". Notes are written in Dragonroll, so
// this copy runs one way — the module reads the notes and rewrites their pages;
// nothing of the journal travels back. Its pages keep the note's id in a
// `dragonroll-foundry.noteId` flag, and the note keeps the page's id here, so
// either side recognises the pairing again after a restart.
const NOTE_FOLDER_SEPARATOR = ' / ';
// The path of the folder a note lives in, from the root down: the module names a
// journal after it, so a note in "Sessions / Arc 1" is written into that journal.
// A broken parent chain stops at the first folder seen twice instead of looping.
function noteFolderPath(folderId, foldersById) {
const names = [];
const seen = new Set();
let folder = folderId ? foldersById.get(String(folderId)) : null;
while (folder && !seen.has(String(folder._id))) {
seen.add(String(folder._id));
if (folder.name) names.unshift(String(folder.name));
folder = folder.parentFolder ? foldersById.get(String(folder.parentFolder)) : null;
}
return names.join(NOTE_FOLDER_SEPARATOR);
}
// The note folders of a campaign, keyed by id, for the path of each note.
async function campaignNoteFolders(campaignId) {
const folders = await Folder.find({ campaign: campaignId })
.select('_id name parentFolder')
.lean();
return new Map(folders.map((folder) => [String(folder._id), folder]));
}
// A cheap summary of the campaign's notes for the module's change check: the same
// notes `/sync/notes` would send, folded into one hash, so a world can tell whether
// anything changed without pulling every note's markdown over on every poll. The
// folder path travels in the hash too: renaming or moving a folder moves a note to
// another journal. The page a note is already mapped to is left out — mapping is
// not an edit.
router.get('/sync/notes/revision', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const notes = await Note.find({ campaign: campaign._id })
.select('_id title content folder')
.sort({ _id: 1 })
.lean();
const foldersById = await campaignNoteFolders(campaign._id);
const revision = crypto.createHash('sha256')
.update(notes.map((note) => [
note._id,
note.title ?? '',
note.content ?? '',
note.folder ?? '',
noteFolderPath(note.folder, foldersById),
].join('\u0000')).join('\u0001'))
.digest('hex');
res.json({ status: 'ok', revision });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Every note of the campaign, content included: enough for the module to write
// each one as a page. A note also carries the path of its folder, which names the
// journal the page belongs to; root notes carry an empty path.
router.get('/sync/notes', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const notes = await Note.find({ campaign: campaign._id })
.select('_id title content foundryPageId date folder')
.sort({ date: -1 })
.lean();
const foldersById = await campaignNoteFolders(campaign._id);
res.json({
status: 'ok',
notes: notes.map((note) => ({
...note,
folderPath: noteFolderPath(note.folder, foldersById),
})),
});
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// The page the module made for a note, kept on the note so the next reconcile —
// or a world whose page flags were lost — writes that page instead of a second
// one under the same title.
router.post('/sync/map-note', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const { noteId, foundryPageId, worldId } = req.body;
if (!requestMatchesWorld(campaign, worldId) || !noteId || !foundryPageId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const note = await Note.findOne({ _id: noteId, campaign: campaign._id });
if (!note) return res.json({ status: 'error', msg: 'errors.notfound' });
const existing = await Note.findOne({ campaign: campaign._id, foundryPageId, _id: { $ne: note._id } });
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.note-already-synced' });
note.foundryPageId = String(foundryPageId).trim().slice(0, 120);
await note.save();
res.json({ status: 'ok', note });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// A world letting its campaign go from the module settings: the campaign forgets
// the world and the token this request used stops working, so the world is free
// to pair again — and the campaign's settings stop listing it as connected.

View File

@@ -0,0 +1,88 @@
const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();
const Campaign = require('../models/Campaign');
const Folder = require('../models/Folder');
const Media = require('../models/Media');
const upload = require('../services/storage');
const uploadDir = path.join(__dirname, '..', 'uploads');
async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
return Boolean(campaign);
}
// Media stands in the note tree, so its folders are the note folders and nothing else.
async function noteFolderFor(folderId, campaignId) {
if (folderId === null || folderId === undefined || folderId === '') return true;
return Folder.belongsToSection(folderId, campaignId, 'note');
}
router.post('/upload', upload.single('file'), async (req, res) => {
try {
const { campaign, folder } = req.body;
if (!campaign || !req.file) return res.json({ status: 'error', msg: 'errors.missing-data' });
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
if (!(await noteFolderFor(folder, campaign))) return res.json({ status: 'error', msg: 'errors.notfound' });
const media = new Media({
name: (req.body.name || req.file.originalname).trim(),
file: req.file.filename,
mimeType: req.file.mimetype,
campaign,
folder: folder || null
});
await media.save();
res.json({ status: 'ok', media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Moving a media row to another folder of the note tree, the way a note is moved.
router.post('/update', async (req, res) => {
try {
const { id, folder } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const media = await Media.findById(id);
if (!media) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(media.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
if (!(await noteFolderFor(folder, media.campaign))) return res.json({ status: 'error', msg: 'errors.notfound' });
media.folder = folder || null;
await media.save();
res.json({ status: 'ok', media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/delete', async (req, res) => {
try {
const { id } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const media = await Media.findById(id);
if (!media) return res.json({ status: 'error', msg: 'errors.notfound' });
// Unlike a note, a media row can be checked before it is deleted: the file belongs to the
// campaign it is asked from, so this route never drops another campaign's upload.
if (!(await userOwnsCampaign(media.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
await Media.deleteOne({ _id: media._id });
fs.unlink(path.join(uploadDir, media.file), () => {});
res.json({ status: 'ok' });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
module.exports = router;

View File

@@ -3,6 +3,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Note = require('../models/Note');
const Media = require('../models/Media');
const Folder = require('../models/Folder');
const Map = require('../models/Map');
@@ -31,7 +32,13 @@ router.get('/list', async (req, res) => {
.sort({ date: -1 })
.lean();
res.json({ status: 'ok', folders, notes: rootNotes });
// The media files standing beside the notes at the root of the tree.
const media = await Media.find({ campaign, folder: null })
.select('_id name file mimeType date')
.sort({ date: -1 })
.lean();
res.json({ status: 'ok', folders, notes: rootNotes, media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
@@ -60,7 +67,12 @@ router.get('/subfolder/list', async (req, res) => {
.sort({ date: -1 })
.lean();
res.json({ status: 'ok', subfolders, notes });
const media = await Media.find({ campaign, folder })
.select('_id name file mimeType date')
.sort({ date: -1 })
.lean();
res.json({ status: 'ok', subfolders, notes, media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });

View File

@@ -1,49 +0,0 @@
const { numberOr, asText } = require('./foundry-fields');
// A Foundry scene is one of the campaign's maps (Syndria98/dragonroll#99): its background
// picture and the grid laid over it travel to Dragonroll. Everything else a scene holds —
// its padding, its lighting, the tokens standing on it — belongs to the world's table, and
// so does what one of its cells stands for (`gridDistance` with its units): the campaign
// sets its own scale and keeps it.
// The scene's background picture: `background.src` since Foundry V13, plain `img` before.
function sceneImage(scene) {
return asText(scene?.background?.src).trim() || asText(scene?.img).trim();
}
// How many pixels of the picture one grid cell covers. Foundry keeps it under `grid.size`
// since V13 and under plain `grid` before; 50 px is its own default cell size, and
// Dragonroll's is the same, so a scene that says nothing gets the grid it draws.
function sceneGridSize(scene) {
const size = numberOr(scene?.grid?.size ?? scene?.grid, 0);
return size >= 1 ? Math.round(size) : 50;
}
// Where that grid starts on the picture. A world shifts it with the core flags of its own
// (`flags.core.shiftX` / `.shiftY`, what it uses to line a hexagonal grid up); one that says
// nothing has its grid at the corner of the picture. The scene's padding is blank canvas
// *outside* the picture, so it is no part of the grid the campaign lays on the picture itself.
function sceneGridOffset(scene, axis) {
return Math.round(numberOr(scene?.flags?.core?.[`shift${axis}`], 0));
}
// Returns null for a scene that is not a map: one with no name, or with no background
// picture. A Dragonroll map without a picture is an empty viewer, so those scenes stay in
// the world — their id is still listed by the snapshot that carries them, so nothing of the
// campaign is pruned because of one.
function foundrySceneToMapData(scene) {
const name = asText(scene?.name).trim();
const image = sceneImage(scene);
if (!name || !image) return null;
return {
name,
// The module sends Foundry's picture as an absolute URL, like actors do.
image,
gridSize: sceneGridSize(scene),
offsetX: sceneGridOffset(scene, 'X'),
offsetY: sceneGridOffset(scene, 'Y')
};
}
module.exports = { foundrySceneToMapData };

View File

@@ -3,7 +3,7 @@
Foundry modules run in the game client, so the module cannot bind an HTTP port on the Foundry host.
This integration uses a small companion bridge process on that host:
1. A linked GM client syncs character Actors, world Items and Scenes directly with the Dragonroll campaign.
1. A linked GM client syncs character Actors and world Items into the Dragonroll campaign.
2. The module publishes the active world's actor and item snapshot to the optional bridge.
3. The bridge serves authenticated HTTP read endpoints that Dragonroll proxies under `/api/foundry/*`.
@@ -68,19 +68,18 @@ client and uses the one-time code instead of a Dragonroll login token.
## Character and item synchronization
After linking, the GM client imports Foundry character, NPC, and creature Actors into the campaign.
Creates, updates, and deletes sync in either direction; Dragonroll changes are applied in Foundry
within about five seconds. The module currently creates Dragonroll characters in D&D 5e Foundry
worlds. After updating an already-linked world to a version with character sync, create a fresh
pairing code and enter it in Foundry once to issue the sync token.
Sync runs one way only — from Foundry to Dragonroll: creates, updates and deletes in the world reach
the campaign, and nothing changed in Dragonroll is written back into Foundry. Character sync requires
the D&D 5e Foundry system. After updating an already-linked world to a version with character sync,
create a fresh pairing code and enter it in Foundry once to issue the sync token.
### Auto-sync, and sending one actor on purpose
**Dragonroll Auto-sync** in the module settings (on by default) is what keeps the campaign and this
world in step: actors and world items the GM creates, updates or deletes are sent to Dragonroll, and
both sides reconcile every few seconds. Turn it off to stop synchronizing altogether — nothing is
sent to the campaign, and Dragonroll stops rewriting those documents in Foundry, so the campaign
keeps whatever it already holds. Turn it back on to reconcile both sides again; the Foundry edits
queued while it was off are sent as the world catches up.
world in step: actors and world items the GM creates, updates or deletes are sent to Dragonroll.
Turn it off to stop synchronizing altogether — nothing is sent to the campaign, so it keeps whatever
it already holds. Turn it back on to send the world's current state again; the Foundry edits queued
while it was off are sent as the world catches up.
With autosync off — or any time a single character needs to cross over right now — right-click an
actor (or several selected ones) in the Foundry actor directory and pick **Dragonroll: Force Sync**.
@@ -107,72 +106,13 @@ else (Syndria98/dragonroll#67):
or one it renamed away from and remembers (`foundryNames`) — instead of doubling it. Spells, classes,
subclasses, backgrounds, feats and species are not gear and are not imported.
- Foundry owns the fields it sends (category from the item type, rarity, quantity, weight, weapon
properties, description). An item made by hand in Dragonroll is created in the world's item
directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry
document.
properties, description). Nothing is written from Dragonroll into the world's item directory.
- The folders grouping the world's item directory arrive in the campaign as its own item folders, tree
and nesting included, and the items are filed in them. A folder's **colour** goes the other way too:
what the GM colours in Foundry shows on the campaign's folder, and what the campaign colours lands on
the world's folder on the next reconcile (the world's document keeps its name and nesting either way).
and nesting included, and the items are filed in them. What the GM colours in Foundry shows on the
campaign's folder.
- A full snapshot keeps Dragonroll edits on reconnect; live Foundry edits overwrite. Item removal is
pruned only by a full snapshot, so a live item push never deletes anything: only a full snapshot sees
the whole world directory and can tell which synced rows it has let go of. Deleting a synced item in
Dragonroll removes its Foundry world copy on the next reconcile.
### Maps
A scene of the world is one of the campaign's maps (Syndria98/dragonroll#99), and only two things
about it cross over: the scene's **background picture** and the **grid** laid over it.
- The picture is sent as an absolute URL of this world, the way an actor's portrait is, so the
campaign draws the same battle map the table is looking at. Its cell size is the scene's own
(`grid`, and `grid.size` since Foundry V13), and the grid starts where the world shifts it
(`flags.core.shiftX` / `.shiftY`). A scene with no background picture makes no map.
- Everything else a scene holds stays in the world, and everything else a map holds stays in the
campaign: what one of its cells stands for, the folder it stands in, the notes pinned onto it and
the actors standing on it as tokens are the campaign's own. Nothing of a map is written back into
the world — scene sync runs one way, so a map deleted in the campaign comes back with its scene on
the next full list, and taking the scene off is what ends the map.
- A scene is matched to a map by its Foundry id, kept on the map as `foundrySceneId` (unique within
the campaign). A campaign that drew the same place by hand before its scene arrived is adopted
instead of doubled: the scene takes over the unmapped map holding its name.
- Live scene edits overwrite the map, including a picture and grid the campaign had set itself; a
full snapshot (the world linking or loading) leaves a map it already has alone. The maps of scenes
the world let go of are pruned by a full snapshot only, and a scene deleted in the world is
reported on `foundry/sync/scene-delete`.
- Autosync covers maps like everything else: turned off, no scene crosses over at all, and the ones
queued while it was off go over when it is turned back on.
### Notes
The campaign's notes read like the campaign's journal in the world (Syndria98/dragonroll#98): each
folder stands as a JournalEntry named after its path. Notes in the root of the campaign share the
journal called **Dragonroll**, and notes in a folder called *Sessions* with a subfolder *Arc 1* share
the journal **Sessions / Arc 1**; a note is always a page of the journal of its folder. The module
creates those journals — or adopts ones the GM already made under the same name, marking them as the
notes' journals — and renders each note's markdown into the page's HTML (headings, lists, quotes,
code and the inline marks), so the page reads in the journal the way the note reads in Dragonroll. A
note's dice widgets become buttons in the page too: pressing one rolls the expression with Foundry's
own dice and posts the result to chat (`adv`/`dis` are sent as `kh1`/`kl1`), so the note rolls at the
table without going back to the app. Its `[[Name]]` links become Foundry content links that open the
note page, character, item or scene they name, and `![[Name]]` embeds a character or an item as a
sheet preview right in the page (Foundry's `@UUID` and `@Embed` enrichers). A name the world has no
document for is shown dimmed, the way Dragonroll dims a link to an entry it cannot find. If a folder
is renamed, its journal is renamed with it, and
moving a note to another folder moves its page to that folder's journal. Notes are written in
Dragonroll, so this copy runs one way: a note made or edited in the campaign rewrites its page, and a
note deleted there takes its page with it. Pages the campaign does not own — the GM's own pages in
those journals — are left alone, and nothing written in a journal travels back. A folder journal whose
notes have all moved or gone is removed too, unless the GM keeps pages of their own in it. Autosync
off stops it too, like the rest of the sync.
Unlike the actor and item reconciles, the notes are only pulled over when something moved. Every
fifteen seconds the module asks for `GET /api/foundry/sync/notes/revision` — a hash of the campaign's
notes and their folder paths — and compares it with the pages it last wrote into the journals. While
both are unchanged the check stops there, so an idle campaign costs one hash comparison instead of a
pull of every note and a journal rewrite. A note made, edited, moved or deleted in Dragonroll, a
folder renamed, or a page of a notes' journal the GM changed or removed, moves one of the two and the
next check writes the pages in step again.
the whole world directory and can tell which synced rows it has let go of.
The module calls these Dragonroll routes with the campaign sync token (no Dragonroll login):
@@ -181,24 +121,12 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon
| `POST /api/foundry/sync/snapshot` | Actors and world items upsert; `fullSync` also prunes |
| `POST /api/foundry/sync/item-snapshot` | Live world item edits, upsert only |
| `POST /api/foundry/sync/item-delete` | A world item was deleted |
| `POST /api/foundry/sync/scenes` | The world's scenes upsert as the campaign's maps; `fullSync` also prunes |
| `POST /api/foundry/sync/scene-delete` | A scene was deleted |
| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry |
| `GET /api/foundry/sync/items` | Items, and the item folders with their Dragonroll colours, to apply back in Foundry |
| `GET /api/foundry/sync/notes` | The campaign's notes, markdown and all, their folder path, and the journal page each stands as |
| `GET /api/foundry/sync/notes/revision` | A hash of the campaign's notes and folder paths, for the module's change check |
| `POST /api/foundry/sync/map-note` | Store a note's journal page id after creating that page |
| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status |
| `POST /api/foundry/sync/unlink` | The module unlinks the world; the campaign forgets it and the token is revoked |
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
| `POST /api/foundry/sync/delete` | An actor was deleted |
Foundry documents keep the Dragonroll id in the `dragonroll-foundry.actorId` / `dragonroll-foundry.itemId`
flag, and a journal page the module made for a note keeps its note's id in the `dragonroll-foundry.noteId`
flag, so the notes reconcile recognises its own pages. World items are marked with
`dragonroll-foundry.syncMutation` while Dragonroll writes them so
the write is not echoed back. A folder colour is written with that folder held in the client's set of
folders being synced, for the same reason.
flag, so the two sides recognise each other on the next push.
## 2. Run the bridge on the Foundry host

File diff suppressed because it is too large Load Diff

View File

@@ -1,31 +1,3 @@
/* Dice widgets in the journal pages the module writes from the campaign's notes. */
.dragonroll-note-roll {
display: inline-flex;
align-items: center;
gap: 0.35em;
vertical-align: middle;
cursor: pointer;
}
.dragonroll-note-roll > i {
pointer-events: none;
}
.dragonroll-note-roll-block {
display: flex;
width: 100%;
justify-content: center;
margin: 0.25em 0;
}
/* A `[[Name]]` the world has no document for: the note still reads, but the name
cannot be opened. Resolved links and embeds are Foundry content links/embeds. */
.dragonroll-note-link.is-unresolved {
opacity: 0.65;
text-decoration: underline dashed;
cursor: help;
}
/* The connection window the module settings open: the sign-up link and its actions. */
.dragonroll-pairing-menu {
display: flex;

View File

@@ -18,6 +18,7 @@ import NestedNoteList from './NestedNoteList.vue';
const { Campaign } = useCampaignService();
const { t } = useI18n();
const notes = ref([]);
const media = ref([]);
const folders = ref([]);
const actors = ref([]);
const items = ref([]);
@@ -40,14 +41,16 @@ const activeSection = ref('notes');
const isDragOverSidebar = ref(false);
const expandedFolderIds = ref([]);
const nestedNoteListRef = ref(null);
const mediaInput = ref(null);
let entryRefreshInterval;
async function handleSidebarDrop(event) {
if (activeSection.value !== 'notes') return;
const noteKey = event.dataTransfer.getData('text/plain');
if (!noteKey) return;
const row = event.dataTransfer.getData('text/plain');
if (!row) return;
const mediaId = row.startsWith('media:') ? row.slice(6) : null;
try {
await Server().post('/note/update', { id: noteKey, folder: null });
await Server().post(mediaId ? '/media/update' : '/note/update', { id: mediaId ?? row, folder: null });
if (nestedNoteListRef.value) {
nestedNoteListRef.value.clearCacheAndReloadExpanded();
} else {
@@ -118,6 +121,11 @@ function handleNoteDeleted(noteKey) {
notes.value = notes.value.filter(n => n.key !== noteKey);
}
// A media row deleted from the tree anywhere under the sidebar.
function handleMediaDeleted(mediaId) {
media.value = media.value.filter((item) => item._id !== mediaId);
}
function sectionForTarget(target) {
if (target === 'actor') return 'actors';
if (target === 'item') return 'items';
@@ -167,6 +175,7 @@ const campaignId = computed(() => {
async function fetchCampaignNotes() {
if (!campaignId.value) {
notes.value = [];
media.value = [];
folders.value = [];
notesError.value = '';
return;
@@ -180,6 +189,7 @@ async function fetchCampaignNotes() {
if (response.data.status !== 'ok') {
notes.value = [];
media.value = [];
folders.value = [];
notesError.value = response.data.msg ?? 'Unable to load notes.';
return;
@@ -192,8 +202,10 @@ async function fetchCampaignNotes() {
notes.value = response.data.notes.map((note) => {
return { key: note._id, title: note.title, text: note.content ?? '', date: note.date, color: note.color };
});
media.value = response.data.media ?? [];
} catch (error) {
notes.value = [];
media.value = [];
folders.value = [];
notesError.value = 'Unable to load notes.';
} finally {
@@ -503,6 +515,34 @@ function createNote() {
CreateWindow('new_note', { campaign: campaignId.value });
}
function chooseMedia() {
mediaInput.value?.click();
}
// The picked files are uploaded to the root of the note tree, one request per file, and their
// rows join the list as each lands.
async function uploadMedia(event) {
const files = Array.from(event.target.files ?? []);
event.target.value = '';
if (!campaignId.value) return;
for (const file of files) {
const body = new FormData();
body.append('file', file);
body.append('campaign', campaignId.value);
try {
const response = await Server().post('/media/upload', body);
if (response.data.status !== 'ok') {
DisplayToast('red', t(response.data.msg || 'campaigns.media.upload-error'), 3000);
continue;
}
media.value = [response.data.media, ...media.value];
} catch (error) {
DisplayToast('red', t('campaigns.media.upload-error'), 3000);
}
}
}
function toggleSidebar() {
sidebarCollapsed.value = !sidebarCollapsed.value;
}
@@ -536,6 +576,7 @@ watch(campaignId, (newVal) => {
actors.value = [];
items.value = [];
maps.value = [];
media.value = [];
for (const sectionFolders of Object.values(entryFolders)) sectionFolders.value = [];
collapsedFolderIds.value = [];
ClearAnchoredMap();
@@ -543,6 +584,7 @@ watch(campaignId, (newVal) => {
if (isEntrySection(activeSection.value)) fetchCampaignEntries(activeSection.value);
} else {
notes.value = [];
media.value = [];
folders.value = [];
actors.value = [];
items.value = [];
@@ -559,6 +601,7 @@ onMounted(() => {
emitter.on('note-created', handleNoteCreated);
emitter.on('note-renamed', handleNoteRenamed);
emitter.on('delete-note', handleNoteDeleted);
emitter.on('media-deleted', handleMediaDeleted);
emitter.on('folder-saved', handleFolderSaved);
emitter.on('folder-deleted', handleFolderDeleted);
emitter.on('campaign-entry-created', handleCampaignEntryCreated);
@@ -580,6 +623,7 @@ onBeforeUnmount(() => {
emitter.off('note-created', handleNoteCreated);
emitter.off('note-renamed', handleNoteRenamed);
emitter.off('delete-note', handleNoteDeleted);
emitter.off('media-deleted', handleMediaDeleted);
emitter.off('folder-saved', handleFolderSaved);
emitter.off('folder-deleted', handleFolderDeleted);
emitter.off('campaign-entry-created', handleCampaignEntryCreated);
@@ -659,6 +703,10 @@ onBeforeUnmount(() => {
<button class="sidebar-action" type="button" @click="createNote" :disabled="!Campaign" :title="t('campaigns.actions.new-note')" :aria-label="t('campaigns.actions.new-note')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/plus.svg" alt="" aria-hidden="true">
</button>
<button class="sidebar-action" type="button" @click="chooseMedia" :disabled="!Campaign" :title="t('campaigns.media.upload')" :aria-label="t('campaigns.media.upload')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/media-image-plus.svg" alt="" aria-hidden="true">
</button>
<input ref="mediaInput" class="media-input" type="file" multiple @change="uploadMedia">
<button class="sidebar-action" type="button" @click="createFolder()" :disabled="!Campaign" :title="t('campaigns.actions.new-folder')" :aria-label="t('campaigns.actions.new-folder')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
</button>
@@ -684,9 +732,9 @@ onBeforeUnmount(() => {
<template v-if="activeSection === 'notes'">
<div v-if="loadingNotes" class="sidebar-state">{{ t('campaigns.states.loading-notes') }}</div>
<div v-else-if="notesError" class="sidebar-state error">{{ notesError }}</div>
<div v-else-if="folders.length === 0 && notes.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-notes') }}</div>
<div v-else-if="folders.length === 0 && notes.length === 0 && media.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-notes') }}</div>
<NestedNoteList v-else ref="nestedNoteListRef"
:parent-folder-id="null" :folders="folders" :notes="rootNotes" :campaign-id="campaignId"
:parent-folder-id="null" :folders="folders" :notes="rootNotes" :media="media" :campaign-id="campaignId"
:expanded-folder-ids="expandedFolderIds" @open-note="openNote"
@reload-notes="fetchCampaignNotes" @toggle-expanded-folder="toggleExpandedFolder" />
</template>
@@ -706,7 +754,10 @@ onBeforeUnmount(() => {
@toggle="toggleFolder(row.folder._id)"
/>
<div v-else class="entity-entry" :style="rowIndent(row.depth)" role="button" tabindex="0" draggable="true" :title="t('campaigns.map.tokens.drag')" @click="openCharacterSheet(row.item)" @keydown.enter="openCharacterSheet(row.item)" @keydown.space.prevent="openCharacterSheet(row.item)" @dragstart="startActorDrag($event, row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'actor')">
<span class="entity-entry-name">{{ row.item.name }}</span>
<span class="entity-entry-title">
<img class="entity-entry-icon" src="/icons/iconoir/regular/user.svg" alt="" aria-hidden="true">
<span class="entity-entry-name">{{ row.item.name }}</span>
</span>
<span class="entity-entry-meta">{{ entrySummary(row.item) }}</span>
</div>
</template>
@@ -731,6 +782,7 @@ onBeforeUnmount(() => {
<span v-if="row.item.image" class="entity-entry-image" aria-hidden="true">
<img :src="itemImageUrl(row.item.image)" alt="">
</span>
<img v-else class="entity-entry-icon" src="/icons/iconoir/regular/box.svg" alt="" aria-hidden="true">
<span class="entity-entry-name" :class="rarityClass(row.item)">{{ row.item.name }}</span>
</span>
</div>
@@ -752,9 +804,12 @@ onBeforeUnmount(() => {
@toggle="toggleFolder(row.folder._id)"
/>
<div v-else class="entity-entry" :style="rowIndent(row.depth)" :class="{ anchored: isAnchoredMap(row.item) }" role="button" tabindex="0" @click="openMapViewer(row.item)" @keydown.enter="openMapViewer(row.item)" @keydown.space.prevent="openMapViewer(row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'map')">
<span class="entity-entry-name-row">
<span class="entity-entry-name">{{ row.item.name }}</span>
<span v-if="isAnchoredMap(row.item)" class="entity-entry-sync">{{ t('campaigns.map.anchored') }}</span>
<span class="entity-entry-title">
<img class="entity-entry-icon" src="/icons/iconoir/regular/map.svg" alt="" aria-hidden="true">
<span class="entity-entry-name-row">
<span class="entity-entry-name">{{ row.item.name }}</span>
<span v-if="isAnchoredMap(row.item)" class="entity-entry-sync">{{ t('campaigns.map.anchored') }}</span>
</span>
</span>
<span class="entity-entry-meta">{{ mapSummary(row.item) }}</span>
<span v-if="!row.item.image" class="entity-entry-description">{{ t('campaigns.map.no-image') }}</span>
@@ -850,6 +905,7 @@ onBeforeUnmount(() => {
}
.sidebar-header-actions { display: flex; align-items: center; gap: 4px; }
.media-input { display: none; }
.sidebar-header-actions .sidebar-action { width: 30px; height: 30px; }
.sidebar-header-actions .sidebar-action-icon { width: 16px; height: 16px; }
@@ -923,6 +979,8 @@ onBeforeUnmount(() => {
}
.entity-entry-meta, .entity-entry-description { font-size: 12px; opacity: 0.72; }
.entity-entry-description { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
/* Every entry row leads with an icon of what it is: an actor, an item, a map. */
.entity-entry-icon { width: 16px; height: 16px; flex: 0 0 16px; filter: invert(var(--color-icon-invert)); }
/* An item row leads with the item's own icon on the left of its name, standing in for the
"SYNCED" text it used to show (Syndria98/dragonroll#53). */
.entity-entry-title { display: flex; align-items: center; gap: 9px; min-width: 0; }

View File

@@ -2,13 +2,15 @@
import { ref, onBeforeUnmount, onMounted, watch } from 'vue';
import { emitter } from '~/services/Emitter';
import { BuildColorMenu } from '~/services/EntryColors';
import Server from '~/services/Server';
import Server, { getBaseUrl } from '~/services/Server';
import { CreateWindow } from '~/services/Windows';
import { ShowContextMenu, HideContextMenu } from '~/services/ContextMenu';
const props = defineProps({
folders: Array,
notes: Array,
// Media files standing beside the notes at this level of the tree.
media: { type: Array, default: () => [] },
campaignId: String,
level: { type: Number, default: 0 },
parentFolderId: String,
@@ -44,6 +46,7 @@ onMounted(() => {
emitter.on('note-created', handleNoteCreated);
emitter.on('note-renamed', handleNoteRenamed);
emitter.on('delete-note', handleNoteDeleted);
emitter.on('media-deleted', handleMediaDeleted);
emitter.on('folder-saved', handleFolderSaved);
});
@@ -51,6 +54,7 @@ onBeforeUnmount(() => {
emitter.off('note-created', handleNoteCreated);
emitter.off('note-renamed', handleNoteRenamed);
emitter.off('delete-note', handleNoteDeleted);
emitter.off('media-deleted', handleMediaDeleted);
emitter.off('folder-saved', handleFolderSaved);
});
@@ -80,6 +84,12 @@ function handleNoteDeleted(noteKey) {
}
}
function handleMediaDeleted(mediaId) {
for (const entry of Object.values(folderContentCache.value)) {
entry.media = entry.media.filter((m) => m._id !== mediaId);
}
}
function handleFolderSaved(folder) {
const folderId = folder?._id ?? folder?.id;
if (!folderId) return;
@@ -98,6 +108,7 @@ function loadFolderContents(folderId) {
if (res.data.status !== 'ok') return;
folderContentCache.value[folderId] = {
notes: res.data.notes.map(n => ({ key: n._id, title: n.title, text: n.content || '', color: n.color })),
media: res.data.media || [],
subfolders: res.data.subfolders || []
};
}).catch(() => {}).finally(() => {
@@ -113,6 +124,10 @@ function getFolderSubfolders(folderId) {
return folderContentCache.value[folderId]?.subfolders || [];
}
function getFolderMedia(folderId) {
return folderContentCache.value[folderId]?.media || [];
}
// Load contents for all currently-expanded folders
function loadExpandedFolders() {
const idsToLoad = props.level === 0
@@ -125,26 +140,32 @@ function loadExpandedFolders() {
}
}
// A row dragged into a folder is either a note (its key) or a media file ("media:<id>").
async function moveDraggedRow(payload, folderId) {
const mediaId = payload.startsWith('media:') ? payload.slice(6) : null;
await Server().post(mediaId ? '/media/update' : '/note/update', { id: mediaId ?? payload, folder: folderId });
}
async function handleDropNoteOnFolder(folderId, event) {
const noteKey = event.dataTransfer.getData('text/plain');
if (!noteKey || !folderId) return;
const row = event.dataTransfer.getData('text/plain');
if (!row || !folderId) return;
dragHoveredFolderId.value = null;
try {
await Server().post('/note/update', { id: noteKey, folder: folderId });
await moveDraggedRow(row, folderId);
clearCacheAndReloadExpanded();
} catch (e) {}
}
async function handleDropNoteOnRoot(event) {
const noteKey = event.dataTransfer.getData('text/plain');
if (!noteKey) return;
const row = event.dataTransfer.getData('text/plain');
if (!row) return;
dragHoveredFolderId.value = null;
try {
await Server().post('/note/update', { id: noteKey, folder: null });
await moveDraggedRow(row, null);
clearCacheAndReloadExpanded();
} catch (e) {}
}
@@ -172,6 +193,31 @@ function startDragNote(event, note) {
event.dataTransfer.effectAllowed = 'move';
}
// A media row drags into a folder like a note does, under a prefixed key so the drop knows
// which of the two lists it is moving.
function startDragMedia(event, media) {
event.dataTransfer.setData('text/plain', `media:${media._id}`);
event.dataTransfer.effectAllowed = 'move';
}
// The icon a media row leads with, the way the sidebar tells a picture from a sound at a glance.
function mediaIcon(media) {
const type = media?.mimeType ?? '';
if (type.startsWith('image/')) return '/icons/iconoir/regular/media-image.svg';
if (type.startsWith('audio/')) return '/icons/iconoir/regular/music-note.svg';
if (type.startsWith('video/')) return '/icons/iconoir/regular/media-video.svg';
if (type === 'application/pdf') return '/icons/iconoir/regular/page.svg';
return '/icons/iconoir/regular/attachment.svg';
}
function mediaUrl(media) {
return media?.file ? `${getBaseUrl()}/public/${media.file}` : '';
}
function openMedia(media) {
CreateWindow('media_viewer', { media });
}
function setDragHover(id) {
dragHoveredFolderId.value = id;
}
@@ -194,6 +240,18 @@ function buildNoteContextMenu(note) {
];
}
function buildMediaContextMenu(media) {
return [
{ name: 'Open', icon: '/icons/iconoir/regular/attachment.svg', action: () => openMedia(media) },
{
name: 'Move to Folder...', icon: '/icons/iconoir/regular/folder.svg',
context: buildMediaMoveToMenu(media)
},
{ divider: true },
{ name: 'Delete', icon: '/icons/iconoir/regular/trash.svg', action: () => deleteMedia(media) }
];
}
function buildFolderContextMenu(folder) {
if (!folder || !folder._id) return [];
return [
@@ -262,6 +320,35 @@ async function deleteFolder(folderId) {
HideContextMenu();
}
function buildMediaMoveToMenu(media) {
const moveItems = (props.folders || []).map(folder => ({
name: folder.name, icon: '/icons/iconoir/regular/folder.svg', action: () => moveMediaToFolder(media, folder._id)
}));
if (moveItems.length > 0) moveItems.push({ divider: true });
moveItems.push({ name: '(Root)', icon: '/icons/iconoir/regular/attachment.svg', action: () => moveMediaToFolder(media, null) });
return moveItems;
}
async function moveMediaToFolder(media, folderId) {
try {
const response = await Server().post('/media/update', { id: media._id, folder: folderId || null });
if (response.data.status !== 'ok') return;
clearCacheAndReloadExpanded();
} catch (e) {}
HideContextMenu();
}
async function deleteMedia(media) {
try {
const response = await Server().post('/media/delete', { id: media._id });
if (response.data.status === 'ok') emitter.emit('media-deleted', media._id);
} catch (error) {} finally {
HideContextMenu();
}
}
async function moveNoteToFolder(note, folderId) {
try {
const response = await Server().post('/note/update', { id: note.key, folder: folderId || null });
@@ -308,6 +395,7 @@ function createNoteInFolder(folderId) {
v-if="expandedFolderIds.includes(folder._id)"
:folders="getFolderSubfolders(folder._id)"
:notes="getFolderNotes(folder._id)"
:media="getFolderMedia(folder._id)"
:campaign-id="campaignId"
:level="level + 1"
:parent-folder-id="folder._id"
@@ -323,15 +411,24 @@ function createNoteInFolder(folderId) {
<!-- Notes at this level -->
<template v-for="note in notes" :key="note.key">
<button type="button" class="note-link" :class="{ 'has-color': !!note.color }" :style="entryColorStyle(note)" draggable="true" @dragstart="startDragNote($event, note)" @click.stop="$emit('open-note', note)" @contextmenu.prevent="ShowContextMenu(buildNoteContextMenu(note))">
<img class="note-link-icon" src="/icons/iconoir/regular/journal-page.svg" alt="" aria-hidden="true">
<span class="note-link-title">{{ note.title }}</span>
</button>
</template>
<!-- Media files at this level, VSCode-explorer style: the type's icon, then the file name -->
<template v-for="item in media" :key="item._id">
<button type="button" class="note-link media-link" draggable="true" :title="item.name" @dragstart="startDragMedia($event, item)" @click.stop="openMedia(item)" @contextmenu.prevent="ShowContextMenu(buildMediaContextMenu(item))">
<img class="media-link-icon" :src="mediaIcon(item)" alt="" aria-hidden="true">
<span class="media-link-name">{{ item.name }}</span>
</button>
</template>
<!-- Drop zone for root-level notes -->
<div v-if="level === 0" class="root-drop-zone" :class="{ 'drag-over': dragHoveredFolderId === 'root' }" @drop.stop="handleDropNoteOnRoot($event)">
</div>
<div v-if="folders.length === 0 && (!notes || notes.length === 0) && level === 0" class="sidebar-state">Empty</div>
<div v-if="folders.length === 0 && (!notes || notes.length === 0) && (!media || media.length === 0) && level === 0" class="sidebar-state">Empty</div>
</div>
</template>
@@ -353,10 +450,17 @@ function createNoteInFolder(folderId) {
.folder-children { padding-left: 20px; margin-top: 2px; cursor: default; }
.folder-children.drag-over { background: #ffffff22; border-radius: 10px; }
.note-link { width: 100%; padding: 6px; margin: 0; box-shadow: none; border: none; display: flex; flex-direction: column; align-items: flex-start; text-align: left; cursor: grab; border-radius: 8px; }
.note-link { width: 100%; padding: 6px; margin: 0; box-shadow: none; border: none; display: flex; flex-direction: row; align-items: center; gap: 8px; text-align: left; cursor: grab; border-radius: 8px; }
.note-link.has-color { background: color-mix(in srgb, var(--entry-color) 32%, transparent); }
.note-link.has-color:hover { background: color-mix(in srgb, var(--entry-color) 50%, transparent); }
.note-link-title { font-weight: 600; word-break: break-word; }
/* Every note row leads with the page icon, like a media row with the icon of its type. */
.note-link-icon { width: 15px; height: 15px; flex: 0 0 15px; filter: invert(var(--color-icon-invert)); }
.note-link-title { flex: 1; min-width: 0; font-weight: 600; word-break: break-word; }
/* Media rows share the note row's box, with the file type's icon where a note has none. */
.media-link { flex-direction: row; align-items: center; gap: 8px; }
.media-link-icon { width: 15px; height: 15px; flex: 0 0 15px; filter: invert(var(--color-icon-invert)); }
.media-link-name { min-width: 0; font-weight: 500; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sidebar-state { padding: 12px; border-radius: 10px; background: var(--color-background-soft); font-size: 14px; }

View File

@@ -1,6 +1,6 @@
<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { SetupHandle, SetSize, ResetPosition, ClearWindow } from '@/services/Windows';
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
import WindowHandle from './partials/WindowHandle.vue';
import Server from '~/services/Server';
import { emitter } from '~/services/Emitter';
@@ -34,6 +34,7 @@ function initialForm() {
const form = ref(initialForm());
onMounted(() => {
Top(wrapper);
SetupHandle(id, handle);
SetSize(id, isActor ? { width: 420, height: 220 } : { width: 500, height: 560 });
ResetPosition(id, 'center');
@@ -71,7 +72,6 @@ async function saveEntry() {
<WindowHandle :window="id" ref="handle" />
<div class="body">
<h3>{{ $t(editing ? 'campaigns.item.edit' : (isActor ? 'campaigns.actor.new' : 'campaigns.item.new')) }}</h3>
<p v-if="!isActor && editing?.foundryItemId" class="sync-note">{{ $t('campaigns.item.foundry-sync-note') }}</p>
<form @submit.prevent="saveEntry">
<label class="form-field">
<span>{{ $t('campaigns.fields.name') }}</span>
@@ -134,7 +134,6 @@ async function saveEntry() {
.window-wrapper { display: flex; align-items: center; flex-direction: column; }
.body { width: 100%; padding: 10px 18px 16px; overflow-y: auto; }
h3 { margin: 0 0 12px; font-family: MrEavesRemake; }
.sync-note { margin: -8px 0 12px; font-size: 12px; opacity: 0.72; }
form { display: flex; flex-direction: column; gap: 10px; }
.form-field { min-width: 0; display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }

View File

@@ -0,0 +1,57 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { SetupHandle, SetSize, ResetPosition, Top } from '@/services/Windows';
import { getBaseUrl } from '~/services/Server';
import WindowHandle from './partials/WindowHandle.vue';
// One media file of the note tree, shown in a window of its own: an image fills it, a sound and a
// video play in it, and anything else (a PDF, a document) is offered as a link to open.
const props = defineProps(['data']);
const id = props.data.id;
const media = props.data.media;
const handle = ref(null);
const wrapper = ref(null);
const url = computed(() => media?.file ? `${getBaseUrl()}/public/${media.file}` : '');
const kind = computed(() => {
const type = media?.mimeType ?? '';
if (type.startsWith('image/')) return 'image';
if (type.startsWith('audio/')) return 'audio';
if (type.startsWith('video/')) return 'video';
return 'file';
});
onMounted(() => {
Top(wrapper);
SetupHandle(id, handle);
SetSize(id, {
width: Math.max(420, Math.min(900, window.innerWidth - 24)),
height: Math.max(320, Math.min(700, window.innerHeight - 32))
});
ResetPosition(id, 'center');
});
</script>
<template>
<div class="window-wrapper media-window" :id="'window-wrapper-' + id" ref="wrapper">
<WindowHandle :window="id" ref="handle" />
<div class="media-body">
<img v-if="kind === 'image'" class="media-image" :src="url" :alt="media?.name">
<audio v-else-if="kind === 'audio'" :src="url" controls></audio>
<video v-else-if="kind === 'video'" :src="url" controls></video>
<a v-else class="media-file" :href="url" target="_blank" rel="noopener">{{ media?.name }}</a>
</div>
</div>
</template>
<style scoped>
.media-window { min-width: 320px; min-height: 0; }
.media-body {
flex: 1; min-height: 0; box-sizing: border-box; padding: 10px;
display: flex; align-items: center; justify-content: center; overflow: auto;
}
.media-image { max-width: 100%; max-height: 100%; object-fit: contain; }
audio, video { max-width: 100%; }
.media-file { color: var(--color-link); word-break: break-word; }
</style>

View File

@@ -1,6 +1,6 @@
<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { SetupHandle, SetSize, ResetPosition, ClearWindow } from '@/services/Windows';
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
import WindowHandle from './partials/WindowHandle.vue';
import Server from '~/services/Server';
import { emitter } from '~/services/Emitter';
@@ -18,6 +18,7 @@ const creating = !!data.name;
onMounted(() => {
newName.value = data.name || '';
Top(wrapper);
SetupHandle(id, handle);
SetSize(id, { width: 420, height: 200 });
ResetPosition(id, 'center');

View File

@@ -1,6 +1,6 @@
<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { SetupHandle, SetSize, ResetPosition, ClearWindow } from '@/services/Windows';
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
import WindowHandle from './partials/WindowHandle.vue';
import Server from '~/services/Server';
import { emitter } from '~/services/Emitter';
@@ -17,6 +17,7 @@ const newName = ref('');
onMounted(() => {
newName.value = data.title || '';
Top(wrapper);
SetupHandle(id, handle);
SetSize(id, { width: 420, height: 200 });
ResetPosition(id, 'center');

View File

@@ -28,6 +28,14 @@ what matters.
Deleting a folder does not delete your notes: the notes it held move up to its parent folder, its
sub-folders move up with them, and only the empty folders go away.
## Images and media
The notes sidebar lists media files as well as notes. Upload them with the picture button in the
notes header: images, sounds, videos and PDFs all work, and each row leads with an icon of its type,
the way a file explorer does. Clicking a row opens the file in a window of its own, and a media row
moves into a folder like a note — drag it there, or use **Move to Folder…** in its right-click menu.
Right-clicking a media row also deletes it, file included.
## Markdown
Headings, **bold**, *italic*, lists, quotes, tables, code and links all work:
@@ -102,10 +110,6 @@ Either way the widget shows the expression as a button: press it and the dice la
the total spelled out. Press it again to roll again. Only the expression itself goes between `@roll`
and `@end` — write the note about the roll next to the widget, not inside it.
When the note reaches a linked [Foundry world](/docs/foundry), its dice widgets are buttons on the
journal page too: pressing one rolls the expression with Foundry's dice and posts the result to chat,
where the whole table sees it.
The expression understands:
| Written | Meaning |

View File

@@ -1,8 +1,8 @@
# Characters and items
The **Actors & Characters** and **Items** sections of the sidebar hold the people and things of a
campaign as entries of their own, with a sheet each. They can be written by hand, and they are also
what a linked [Foundry VTT](/docs/foundry) world keeps itself in step with.
campaign as entries of their own, with a sheet each. They can be written by hand, and the actors and
items of a linked [Foundry VTT](/docs/foundry) world are sent into them.
## Actors

View File

@@ -49,18 +49,3 @@ the actor it stands for, and **Enter** does the same on a token focused with the
Tokens belong to the map, not to the actor: the same character can stand on several maps, and taking a
token off does not remove the character from the campaign.
## Maps from a linked Foundry world
With a Foundry world linked to the campaign, its scenes arrive as maps of their own: each one with the
scene's background picture and the grid laid over it, in the scene's own cell size and where the world
shifts that grid onto the picture. That is all a scene lends a map — what one of your cells stands
for, the folder a map stands in, and whatever you pin or stand on it stay yours, and nothing about a
map goes back to the world.
A scene renamed in Foundry, or its grid moved, updates its map. Take the background picture off a
scene and its map keeps the one it has; delete the scene and its map goes with it the next time the
world sends its whole scene list, which is when the world loads. For the same reason a map you delete
in the campaign comes back on the next world load while its scene is still there — take the scene off
in Foundry to be rid of the map. A map you made yourself is never doubled by the scene of it: a scene
arriving with the name of an unmapped map adopts that one. See [Foundry VTT](/docs/foundry).

View File

@@ -27,8 +27,7 @@ What a service may do is decided by the campaign you pick, so check the name bef
screen tells you which service is asking, and what it wants:
- a **Discord server** reads the campaign's characters, so whoever is in that server can read them,
- a **Foundry world** keeps its actors and items in step with the campaign, which means it writes into
it, and Dragonroll writes into it,
- a **Foundry world** sends its actors and items into the campaign,
- **Obsidian** reads the campaign's notes and pushes the ones you tell it to.
A campaign holds one link per service: linking a second Foundry world, or a second Discord server,

View File

@@ -1,8 +1,8 @@
# Foundry VTT
The Foundry integration keeps a Dragonroll campaign and a Foundry world in step: the world's
characters, item directory and scenes arrive in the campaign, and what you change in Dragonroll of
those characters and items goes back to the world.
characters and item directory arrive in the campaign. Sync runs one way only — from Foundry to
Dragonroll — so nothing you change in the campaign is written back into the world.
There are two separate parts, and you only need the first of them:
@@ -56,56 +56,30 @@ Worth knowing:
| Character, NPC and creature actors | Actors with the same sheet: abilities, saving throws, skills, combat stats, proficiencies, tools, languages, traits, spells, carried gear with its icons, coins, portrait |
| The world's **item directory** (the items tab) | The campaign's item list, with category, rarity, quantity, weight, properties and description |
| The folders grouping that item directory | Item folders with the same names and nesting |
| A folder's colour | The campaign's folder colour — and the other way round, what you colour in Dragonroll lands on the world's folder |
| The world's **scenes** | The campaign's maps: the scene's background picture and the grid laid over it, in the scene's own cell size |
| A journal per note folder, named after its path — one page per note | Your campaign's notes. They arrive **from** Dragonroll: what you write in a journal does not go back |
| A folder's colour | The campaign's folder colour |
The item list is the world's item directory and nothing else. The gear a character carries is that
character's inventory: it travels with the character and stays on its sheet, so a sword a fighter owns
does not turn up in the campaign's item list. Spells, classes, subclasses, backgrounds, feats and
species are not gear and are not imported.
The world's scenes are the campaign's maps, and only their **background picture** and their **grid**
cross over: a map arrives with the scene's picture and its cell size, and with the grid where the
world shifts it. That is where the two stop — what one of your cells stands for, the folder a map
stands in, the notes pinned onto it and the characters standing on it as tokens stay in the campaign,
and nothing about a map is written back into the world. The scene list goes over when the world links
and when it loads, which is also when the map of a scene the GM deleted goes with it; scenes changed
afterwards arrive as they happen. A scene with no background picture makes no map, and the full list
leaves a map the campaign already had alone, so a grid you lined up yourself survives a reload.
An actor or item keeps the Dragonroll id it was given in a `dragonroll-foundry.actorId` /
`dragonroll-foundry.itemId` flag, and that is what makes the two sides recognise each other. A world
item that carries no flag is matched by name, so a hand-written item in Dragonroll is adopted instead of
doubled, and renaming it in either place does not resurrect a duplicate.
Changes flow both ways as they happen, and Dragonroll's own edits are applied back in Foundry within a
few seconds. A **full** snapshot — the one taken when the world links, or forced from the actor
directory — is the only thing that prunes: it is the only moment either side can see the whole list and
notice what is gone. Live edits never delete anything.
Notes are the exception that runs one way, because notes are written in Dragonroll: each folder
stands as a journal named after its path. Notes in the root of the campaign share the journal called
**Dragonroll**, while notes in a folder called *Sessions* with a subfolder *Arc 1* share the journal
**Sessions / Arc 1**; every note is a page of the journal of its folder. A note's dice widgets are
buttons there as well: press one in the journal and Foundry rolls it and posts the result to chat, so
advantage and disadvantage roll the way the campaign's notes describe them. The note's `[[links]]`
work in the page too: a link to a note page, a character, an item or a scene opens it in Foundry, and
`![[a character or item]]` is drawn as a sheet preview inside the page. Renaming a folder renames
its journal, and moving a note to another folder moves its page along. The module only pulls the notes
over when something has changed, checking every fifteen seconds, so a note you make, edit or move in
the app appears in its journal within that time, and deleting one takes its page with it. Pages the
campaign does not own — ones the GM made in those journals themselves — are left alone, and nothing
written in a journal travels back to the campaign. A folder journal whose notes have all left is
removed too, unless the GM keeps pages of their own in it.
Changes flow one way: as you create, change or delete actors and world items in Foundry, they reach
the campaign. Nothing is written back, so editing a character, an item, a map or a note in Dragonroll
leaves the world alone. A **full** snapshot — the one taken when the world links, or forced from the
actor directory — is the only thing that prunes: it is the only moment the campaign can see the whole
list and notice what is gone. Live edits never delete anything.
## Auto-sync, and sending one actor on purpose
**Dragonroll Auto-sync** is what keeps the two in step: actors and world items you create, change or
delete are sent to the campaign, and both sides reconcile every few seconds. Turning it off stops all
of it — nothing is sent, and Dragonroll stops rewriting your Foundry documents, so the campaign keeps
whatever it already holds. Turn it back on and both sides reconcile again, including the edits queued
while it was off.
delete are sent to the campaign. Turning it off stops all of it — nothing is sent, and the campaign
keeps whatever it already holds. Turn it back on and the world's current state is sent again, including
the edits queued while it was off.
To send one character across right now, or to cross over while autosync is off, right-click the actor
(or several) in the Foundry actor directory and pick **Dragonroll: Force Sync**. Those actors, with the

View File

@@ -127,6 +127,12 @@ const defWindows = {
close: () => ClearWindow({type: 'pinned_note'}),
movable: true
},
media_viewer: {
title: 'windows.media-viewer',
component: () => import('~/components/windows/MediaViewerWindow.vue'),
close: () => ClearWindow({type: 'media_viewer'}),
movable: true
},
documentation: {
title: 'windows.documentation',
component: () => import('~/components/windows/DocumentationWindow.vue'),

View File

@@ -58,6 +58,7 @@
"empty-actors": "Encara no hi ha actors ni personatges.", "empty-items": "Encara no hi ha objectes en aquesta campanya.",
"empty-maps": "Encara no hi ha mapes en aquesta campanya."
},
"media": { "upload": "Puja un fitxer multimèdia", "upload-error": "No s'ha pogut pujar aquest fitxer." },
"errors": { "load": "No s'han pogut carregar les entrades de la campanya." },
"create-entry": "Crea una entrada de campanya",
"fields": { "name": "Nom", "description": "Descripció" },
@@ -68,7 +69,7 @@
"types": { "character": "Personatge", "npc": "PNJ", "creature": "Criatura" }
},
"item": {
"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",
"category": "Categoria", "rarity": "Raresa",
"weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
"sheet": {

View File

@@ -2,8 +2,6 @@
"errors": {
"link-expired": "El codi d'enllaç de Foundry no és vàlid, ha caducat o ja s'ha utilitzat.",
"world-already-linked": "Aquest món de Foundry ja està enllaçat amb una altra campanya.",
"actor-already-synced": "Un altre actor d'aquesta campanya ja està sincronitzat amb aquell actor del Foundry.",
"item-already-synced": "Un altre objecte d'aquesta campanya ja està sincronitzat amb aquell objecte del Foundry.",
"icons-unavailable": "Les icones del Foundry no són disponibles: el seu bridge no està configurat o ara mateix no hi arriba.",
"icons-no-world-url": "Aquesta campanya no té adreça del món del Foundry. Definiu-la als ajustos de la campanya, a la pestanya d'integracions.",
"import-not-linked": "Aquesta campanya no té cap món del Foundry vinculat. Connecteu-ne un als ajustos de la campanya, a la pestanya d'integracions.",

View File

@@ -14,5 +14,6 @@
"item-sheet": "Objecte",
"trait-sheet": "Tret",
"icon-source": "Tria una icona",
"foundry-icons": "Icones del Foundry"
"foundry-icons": "Icones del Foundry",
"media-viewer": "Multimèdia"
}

View File

@@ -62,6 +62,7 @@
"empty-actors": "No actors or characters yet.", "empty-items": "No items in this campaign yet.",
"empty-maps": "No maps in this campaign yet."
},
"media": { "upload": "Upload media", "upload-error": "Unable to upload this file." },
"errors": { "load": "Unable to load campaign entries." },
"create-entry": "Create campaign entry",
"fields": { "name": "Name", "description": "Description" },
@@ -72,7 +73,7 @@
"types": { "character": "Character", "npc": "NPC", "creature": "Creature" }
},
"item": {
"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",
"category": "Category", "rarity": "Rarity",
"weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
"sheet": {

View File

@@ -2,8 +2,6 @@
"errors": {
"link-expired": "This Foundry pairing code is invalid, expired, or already used.",
"world-already-linked": "This Foundry world is already linked to another campaign.",
"actor-already-synced": "Another actor in this campaign is already synced with that Foundry actor.",
"item-already-synced": "Another item in this campaign is already synced with that Foundry item.",
"icons-unavailable": "Foundry's icons are not available: its bridge is not set up, or it cannot be reached right now.",
"icons-no-world-url": "This campaign has no Foundry world address. Set it under campaign settings, in the Integrations tab.",
"import-not-linked": "This campaign has no Foundry world linked to it. Connect one under campaign settings, in the Integrations tab.",

View File

@@ -14,5 +14,6 @@
"item-sheet": "Item",
"trait-sheet": "Trait",
"icon-source": "Choose an icon",
"foundry-icons": "Foundry icons"
"foundry-icons": "Foundry icons",
"media-viewer": "Media"
}

View File

@@ -58,6 +58,7 @@
"empty-actors": "Aún no hay actores ni personajes.", "empty-items": "Aún no hay objetos en esta campaña.",
"empty-maps": "Aún no hay mapas en esta campaña."
},
"media": { "upload": "Subir archivo multimedia", "upload-error": "No se ha podido subir este archivo." },
"errors": { "load": "No se pudieron cargar las entradas de la campaña." },
"create-entry": "Crear entrada de campaña",
"fields": { "name": "Nombre", "description": "Descripción" },
@@ -68,7 +69,7 @@
"types": { "character": "Personaje", "npc": "PNJ", "creature": "Criatura" }
},
"item": {
"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",
"category": "Categoría", "rarity": "Rareza",
"weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
"sheet": {

View File

@@ -2,8 +2,6 @@
"errors": {
"link-expired": "El código de vinculación de Foundry no es válido, ha caducado o ya se ha usado.",
"world-already-linked": "Este mundo de Foundry ya está vinculado a otra campaña.",
"actor-already-synced": "Otro actor de esta campaña ya está sincronizado con ese actor de Foundry.",
"item-already-synced": "Otro objeto de esta campaña ya está sincronizado con ese objeto de Foundry.",
"icons-unavailable": "Los iconos de Foundry no están disponibles: su bridge no está configurado o no es accesible ahora.",
"icons-no-world-url": "Esta campaña no tiene dirección del mundo de Foundry. Defínala en los ajustes de la campaña, en la pestaña de integraciones.",
"import-not-linked": "Esta campaña no tiene ningún mundo de Foundry vinculado. Conecte uno en los ajustes de la campaña, en la pestaña de integraciones.",

View File

@@ -14,5 +14,6 @@
"item-sheet": "Objeto",
"trait-sheet": "Rasgo",
"icon-source": "Elegir icono",
"foundry-icons": "Iconos de Foundry"
"foundry-icons": "Iconos de Foundry",
"media-viewer": "Multimedia"
}

View File

@@ -0,0 +1,51 @@
# Dragonroll Sync for Obsidian
An Obsidian community plugin that imports notes from a Dragonroll campaign and pushes the active
Markdown note back to Dragonroll.
## Install from this repository
Copy `main.js` and `manifest.json` into:
```text
<vault>/.obsidian/plugins/dragonroll-sync/
```
Then enable **Dragonroll Sync** in Obsidian's Community Plugins settings. The plugin is plain
JavaScript and does not need a build step.
## Connect your account
Open **Settings → Community plugins → Dragonroll Sync**, enter the Dragonroll API URL and sign in
with your Dragonroll username/email and password. The default API URL is
`https://dragonroll.aranroig.com/api`; a local server can use `http://localhost:5000/api`.
Choose a campaign after signing in. The plugin saves the Dragonroll session token in this vault;
Dragonroll sessions expire after 48 hours. The password is not saved.
## Commands
- **Import or refresh campaign notes** fetches all campaign notes, including notes inside nested
Dragonroll folders, into `Dragonroll/<Campaign>/`. Imported notes keep their folder hierarchy.
- **Push active note to Dragonroll** creates the active Markdown note as a root campaign note, or
updates its linked Dragonroll note. A note linked to a different campaign cannot be pushed while
another campaign is selected.
The import command adds `dragonrollId`, `dragonrollCampaign`, and `dragonrollTitle` properties to
each imported note's frontmatter. These properties link the local file to its remote record and are
omitted from the Markdown content sent back to Dragonroll. Pushing a new local note adds those
properties as well.
## Automatic sync
Turn on **Auto-sync changes** in the plugin settings and the plugin follows the vault instead of
waiting for the commands: saving an edited note updates its Dragonroll note, a new note created
inside `Dragonroll/<Campaign>/` becomes a campaign note, and deleting a linked file deletes its
Dragonroll note (deleting a folder takes the notes under it along). Notes that are not linked to the
selected campaign are never touched, and the toggle is off by default.
Import protects local edits. It updates a linked note only when the local copy still matches the
last imported/pushed version. If the local copy changed, or both copies changed since the last sync,
the plugin keeps the local file and reports it for review. Push is explicit and updates Dragonroll
with the active note's current title and content.
Without automatic sync this is an explicit import/push workflow; it does not delete notes.

View File

@@ -0,0 +1,647 @@
const {
Notice,
Plugin,
PluginSettingTab,
Setting,
normalizePath,
requestUrl,
} = require('obsidian');
const DEFAULT_SETTINGS = {
apiBaseUrl: 'https://dragonroll.aranroig.com/api',
token: '',
campaignId: '',
autoSync: false,
snapshots: {},
};
const NOTE_ID_PROPERTY = 'dragonrollId';
const CAMPAIGN_PROPERTY = 'dragonrollCampaign';
const REMOTE_TITLE_PROPERTY = 'dragonrollTitle';
module.exports = class DragonrollSyncPlugin extends Plugin {
async onload() {
await this.loadSettings();
this.status = this.addStatusBarItem();
this.updateStatus();
this.addRibbonIcon('refresh-cw', 'Import Dragonroll campaign notes', () => this.importCampaignNotes());
this.addCommand({
id: 'import-campaign-notes',
name: 'Import or refresh campaign notes',
callback: () => this.importCampaignNotes(),
});
this.addCommand({
id: 'push-active-note',
name: 'Push active note to Dragonroll',
checkCallback: (checking) => {
const file = this.app.workspace.getActiveFile();
if (!file || file.extension !== 'md') return false;
if (!checking) void this.pushActiveNote();
return true;
},
});
this.addSettingTab(new DragonrollSettingTab(this.app, this));
this.suspended = false;
this.internalWrites = new Set();
this.linkedNotes = new Map();
this.syncChain = Promise.resolve();
this.app.workspace.onLayoutReady(() => this.refreshLinkedNotes());
this.registerEvent(this.app.vault.on('modify', (file) => this.onVaultChange(file)));
this.registerEvent(this.app.vault.on('create', (file) => this.onVaultChange(file)));
this.registerEvent(this.app.vault.on('rename', (file, oldPath) => this.onVaultChange(file, oldPath)));
this.registerEvent(this.app.vault.on('delete', (file) => this.onVaultDelete(file)));
if (this.settings.token && this.settings.campaignId) {
this.status.setText('Dragonroll: ready');
}
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
if (!this.settings.snapshots || typeof this.settings.snapshots !== 'object') {
this.settings.snapshots = {};
}
}
async saveSettings() {
await this.saveData(this.settings);
this.updateStatus();
}
updateStatus() {
if (!this.status) return;
if (!this.settings.token) this.status.setText('Dragonroll: signed out');
else if (!this.settings.campaignId) this.status.setText('Dragonroll: choose campaign');
else this.status.setText('Dragonroll: ready');
}
apiBaseUrl() {
let url = String(this.settings.apiBaseUrl || '').trim().replace(/\/+$/, '');
if (!url) throw new Error('Enter the Dragonroll API URL in settings.');
if (!/\/api$/i.test(url)) url += '/api';
return url;
}
async request(path, { method = 'GET', body, authenticated = true } = {}) {
const headers = { Accept: 'application/json' };
if (authenticated && this.settings.token) {
headers.Authorization = `Bearer ${this.settings.token}`;
}
if (body !== undefined) headers['Content-Type'] = 'application/json';
let response;
try {
response = await requestUrl({
url: `${this.apiBaseUrl()}${path}`,
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
throw: false,
});
} catch (error) {
throw new Error(`Could not reach Dragonroll: ${error.message || error}`);
}
let data;
try {
data = response.json;
} catch {
throw new Error(`Dragonroll returned an unreadable response (HTTP ${response.status}).`);
}
if (response.status < 200 || response.status >= 300 || data?.status !== 'ok') {
const message = data?.msg || `HTTP ${response.status}`;
if (response.status === 401 || message === 'unauthorized') {
throw new Error('Dragonroll rejected this session. Sign in again in plugin settings.');
}
throw new Error(`Dragonroll: ${message}`);
}
return data;
}
async login(usermail, password) {
const data = await this.request('/user/login', {
method: 'POST',
body: { usermail, password },
authenticated: false,
});
this.settings.token = data.token;
this.settings.campaignId = '';
await this.saveSettings();
return this.getCampaigns();
}
async getCampaigns() {
const data = await this.request('/campaign/list');
return data.campaigns || [];
}
async selectedCampaign() {
if (!this.settings.token) throw new Error('Sign in to Dragonroll in plugin settings first.');
if (!this.settings.campaignId) throw new Error('Choose a campaign in plugin settings first.');
const campaigns = await this.getCampaigns();
const campaign = campaigns.find((item) => String(item._id) === String(this.settings.campaignId));
if (!campaign) throw new Error('The selected campaign is unavailable. Choose a campaign in settings.');
return campaign;
}
async fetchCampaignNotes(campaignId) {
const root = await this.request(`/note/list?campaign=${encodeURIComponent(campaignId)}`);
const folders = root.folders || [];
const folderById = new Map(folders.map((folder) => [String(folder._id), folder]));
const pathCache = new Map();
const folderPath = (folderId, visiting = new Set()) => {
const id = String(folderId || '');
if (!id || !folderById.has(id)) return [];
if (pathCache.has(id)) return pathCache.get(id);
if (visiting.has(id)) return [];
const folder = folderById.get(id);
const nextVisiting = new Set(visiting);
nextVisiting.add(id);
const parent = folder.parentFolder ? String(folder.parentFolder) : '';
const path = [...folderPath(parent, nextVisiting), safeSegment(folder.name, 'Folder')];
pathCache.set(id, path);
return path;
};
const nestedResults = await Promise.all(folders.map(async (folder) => {
const data = await this.request(
`/note/subfolder/list?campaign=${encodeURIComponent(campaignId)}&folder=${encodeURIComponent(folder._id)}`
);
return (data.notes || []).map((note) => ({ note, folders: folderPath(folder._id) }));
}));
const notes = (root.notes || []).map((note) => ({ note, folders: [] }));
for (const result of nestedResults) notes.push(...result);
return notes;
}
async importCampaignNotes() {
this.suspended = true;
try {
const campaign = await this.selectedCampaign();
const notes = await this.fetchCampaignNotes(campaign._id);
const existingById = await this.findFilesByDragonrollId();
const baseFolder = normalizePath(`Dragonroll/${safeSegment(campaign.name, 'Campaign')}`);
let created = 0;
let updated = 0;
let unchanged = 0;
let protectedNotes = 0;
for (const entry of notes) {
const remote = entry.note;
const id = String(remote._id);
const title = String(remote.title || 'Untitled');
const content = String(remote.content || '');
const remoteSignature = await signature(title, content);
const file = existingById.get(id);
if (!file) {
const targetFolder = normalizePath([baseFolder, ...entry.folders].join('/'));
await this.ensureFolder(targetFolder);
const path = await this.availableMarkdownPath(targetFolder, title, id);
const newFile = await this.app.vault.create(path, content);
await this.setNoteIdentity(newFile, id, campaign._id, title);
this.settings.snapshots[id] = remoteSignature;
this.linkedNotes.set(newFile.path, { noteId: id, campaignId: String(campaign._id) });
created += 1;
continue;
}
const localContent = await this.app.vault.read(file);
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter || {};
const storedTitle = frontmatter[REMOTE_TITLE_PROPERTY];
const localTitle = storedTitle && safeSegment(storedTitle, 'Untitled') === file.basename
? String(storedTitle)
: file.basename;
const localSignature = await signature(localTitle, stripPluginMetadata(localContent));
const baseline = this.settings.snapshots[id];
if (!baseline) {
if (localSignature === remoteSignature) {
this.settings.snapshots[id] = remoteSignature;
unchanged += 1;
} else {
protectedNotes += 1;
}
continue;
}
const localChanged = localSignature !== baseline;
const remoteChanged = remoteSignature !== baseline;
if (localChanged && remoteChanged) {
protectedNotes += 1;
continue;
}
if (localChanged) {
protectedNotes += 1;
continue;
}
if (!remoteChanged) {
unchanged += 1;
continue;
}
await this.app.vault.modify(file, content);
await this.setNoteIdentity(file, id, campaign._id, title);
const renamed = await this.renameImportedFile(file, title, id);
this.settings.snapshots[id] = remoteSignature;
updated += 1;
if (renamed) existingById.set(id, renamed);
this.linkedNotes.set((renamed || file).path, { noteId: id, campaignId: String(campaign._id) });
}
await this.saveSettings();
const details = protectedNotes ? `; ${protectedNotes} local edit(s) kept for review` : '';
new Notice(`Dragonroll import: ${created} added, ${updated} updated, ${unchanged} unchanged${details}.`);
} catch (error) {
new Notice(error.message || 'Could not import Dragonroll notes.');
} finally {
this.suspended = false;
}
}
async pushActiveNote() {
try {
const campaign = await this.selectedCampaign();
const file = this.app.workspace.getActiveFile();
if (!file || file.extension !== 'md') throw new Error('Open a Markdown note to push it.');
const cache = this.app.metadataCache.getFileCache(file);
const frontmatter = cache?.frontmatter || {};
const linkedCampaign = frontmatter[CAMPAIGN_PROPERTY];
const noteId = frontmatter[NOTE_ID_PROPERTY];
if (noteId && String(linkedCampaign || '') !== String(campaign._id)) {
throw new Error('This note is linked to another Dragonroll campaign. Select that campaign to push it.');
}
const markdown = stripPluginMetadata(await this.app.vault.read(file));
let remote;
if (noteId) {
const data = await this.request('/note/update', {
method: 'POST',
body: { id: String(noteId), title: file.basename, content: markdown },
});
remote = data.note;
} else {
const data = await this.request('/note/create', {
method: 'POST',
body: { title: file.basename, content: markdown, campaign: campaign._id },
});
remote = data.note;
}
const id = String(remote._id || noteId);
this.internalWrites.add(file.path);
try {
await this.setNoteIdentity(file, id, campaign._id, file.basename);
} finally {
this.internalWrites.delete(file.path);
}
this.settings.snapshots[id] = await signature(file.basename, markdown);
await this.saveSettings();
this.linkedNotes.set(file.path, { noteId: id, campaignId: String(campaign._id) });
new Notice(`Pushed “${file.basename}” to Dragonroll.`);
} catch (error) {
new Notice(error.message || 'Could not push this note to Dragonroll.');
}
}
onVaultChange(file, oldPath) {
if (!this.settings.autoSync) return;
if (this.suspended || this.internalWrites.has(file.path)) return;
if (file.extension !== 'md') return;
if (oldPath) this.linkedNotes.delete(oldPath);
this.queue(() => this.syncFile(file));
}
onVaultDelete(file) {
if (!this.settings.autoSync || this.suspended) return;
const ids = [];
for (const [path, linked] of this.linkedNotes) {
if (path !== file.path && !path.startsWith(`${file.path}/`)) continue;
this.linkedNotes.delete(path);
if (linked.campaignId === String(this.settings.campaignId)) ids.push(linked.noteId);
}
if (!ids.length) return;
this.queue(async () => {
for (const id of ids) delete this.settings.snapshots[id];
await this.saveSettings();
// Keep going past a note the campaign already dropped.
let failure;
for (const id of ids) {
try {
await this.request('/note/delete', { method: 'POST', body: { id } });
} catch (error) {
failure = failure || error;
}
}
if (failure) throw failure;
this.flashSynced();
});
}
queue(task) {
this.syncChain = this.syncChain
.then(task)
.then(() => { this.syncError = ''; })
.catch((error) => {
// An offline vault autosaves often: report a repeated failure once.
if (this.syncError === error.message) return;
this.syncError = error.message;
new Notice(error.message || 'Could not sync with Dragonroll.');
});
}
async syncFile(file) {
if (!this.settings.token || !this.settings.campaignId) return;
if (!this.app.vault.getAbstractFileByPath(file.path)) return;
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter || {};
const noteId = frontmatter[NOTE_ID_PROPERTY] ? String(frontmatter[NOTE_ID_PROPERTY]) : '';
const campaignId = String(frontmatter[CAMPAIGN_PROPERTY] || '');
if (noteId) {
this.linkedNotes.set(file.path, { noteId, campaignId });
if (campaignId && campaignId !== String(this.settings.campaignId)) return;
} else if (!file.path.startsWith('Dragonroll/')) {
return;
}
const markdown = stripPluginMetadata(await this.app.vault.read(file));
const title = file.basename;
const current = await signature(title, markdown);
if (noteId) {
if (this.settings.snapshots[noteId] === current) return;
await this.request('/note/update', {
method: 'POST',
body: { id: noteId, title, content: markdown },
});
this.settings.snapshots[noteId] = current;
await this.saveSettings();
this.flashSynced();
return;
}
// A new local file only becomes a campaign note inside the campaign's import folder.
const campaign = await this.selectedCampaign();
const folder = normalizePath(`Dragonroll/${safeSegment(campaign.name, 'Campaign')}`);
if (!file.path.startsWith(`${folder}/`)) return;
const data = await this.request('/note/create', {
method: 'POST',
body: { title, content: markdown, campaign: campaign._id },
});
const id = String(data.note._id);
this.settings.snapshots[id] = current;
await this.saveSettings();
this.internalWrites.add(file.path);
try {
await this.setNoteIdentity(file, id, campaign._id, title);
} finally {
this.internalWrites.delete(file.path);
}
this.linkedNotes.set(file.path, { noteId: id, campaignId: String(campaign._id) });
this.flashSynced();
}
refreshLinkedNotes() {
this.linkedNotes.clear();
for (const file of this.app.vault.getMarkdownFiles()) {
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter || {};
const noteId = frontmatter[NOTE_ID_PROPERTY];
if (!noteId) continue;
this.linkedNotes.set(file.path, {
noteId: String(noteId),
campaignId: String(frontmatter[CAMPAIGN_PROPERTY] || ''),
});
}
}
flashSynced() {
if (!this.status) return;
this.status.setText('Dragonroll: synced');
setTimeout(() => this.updateStatus(), 2000);
}
async findFilesByDragonrollId() {
const result = new Map();
for (const file of this.app.vault.getMarkdownFiles()) {
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
const id = frontmatter?.[NOTE_ID_PROPERTY];
if (id && !result.has(String(id))) result.set(String(id), file);
}
return result;
}
async setNoteIdentity(file, noteId, campaignId, title) {
await this.app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter[NOTE_ID_PROPERTY] = String(noteId);
frontmatter[CAMPAIGN_PROPERTY] = String(campaignId);
frontmatter[REMOTE_TITLE_PROPERTY] = String(title || file.basename);
});
}
async ensureFolder(path) {
const normalized = normalizePath(path);
if (!normalized || normalized === '.') return;
const parts = normalized.split('/');
let current = '';
for (const part of parts) {
current = current ? `${current}/${part}` : part;
if (!this.app.vault.getAbstractFileByPath(current)) {
await this.app.vault.createFolder(current);
}
}
}
async availableMarkdownPath(folder, title, noteId) {
const base = safeSegment(title, 'Untitled');
let path = normalizePath(`${folder}/${base}.md`);
if (!this.app.vault.getAbstractFileByPath(path)) return path;
const suffix = String(noteId).slice(-6);
path = normalizePath(`${folder}/${base} (${suffix}).md`);
let counter = 2;
while (this.app.vault.getAbstractFileByPath(path)) {
path = normalizePath(`${folder}/${base} (${suffix}-${counter}).md`);
counter += 1;
}
return path;
}
async renameImportedFile(file, title, noteId) {
const parent = file.parent?.path || '';
const base = safeSegment(title, 'Untitled');
let targetPath = normalizePath(parent ? `${parent}/${base}.md` : `${base}.md`);
if (targetPath === file.path) return file;
if (this.app.vault.getAbstractFileByPath(targetPath)) {
targetPath = await this.availableMarkdownPath(parent || '.', title, noteId);
}
await this.app.fileManager.renameFile(file, targetPath);
return this.app.vault.getAbstractFileByPath(targetPath);
}
};
class DragonrollSettingTab extends PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
this.campaigns = [];
this.loginName = '';
this.password = '';
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Dragonroll Sync' });
containerEl.createEl('p', {
text: 'Sign in with your Dragonroll account, choose a campaign, then use the import and push commands. Your password is used only to sign in; the 48-hour session token is stored in this vault.',
});
new Setting(containerEl)
.setName('Dragonroll API URL')
.setDesc('Use the server address, with or without /api.')
.addText((text) => text
.setPlaceholder('https://dragonroll.aranroig.com/api')
.setValue(this.plugin.settings.apiBaseUrl)
.onChange(async (value) => {
const previous = this.plugin.settings.apiBaseUrl.trim().replace(/\/+$/, '');
const next = value.trim().replace(/\/+$/, '');
if (previous !== next) {
this.plugin.settings.token = '';
this.plugin.settings.campaignId = '';
this.campaigns = [];
}
this.plugin.settings.apiBaseUrl = value.trim();
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Username or email')
.addText((text) => text
.setPlaceholder('Dragonroll username or email')
.onChange((value) => { this.loginName = value.trim(); }));
new Setting(containerEl)
.setName('Password')
.addText((text) => {
text.inputEl.type = 'password';
text.inputEl.autocomplete = 'off';
text.onChange((value) => { this.password = value; });
});
new Setting(containerEl)
.setName(this.plugin.settings.token ? 'Session' : 'Sign in')
.setDesc(this.plugin.settings.token ? 'The stored session expires after 48 hours.' : 'Password is not saved by this plugin.')
.addButton((button) => button
.setButtonText('Sign in')
.setCta()
.onClick(async () => {
if (!this.loginName || !this.password) {
new Notice('Enter your Dragonroll username/email and password.');
return;
}
button.setDisabled(true);
try {
this.campaigns = await this.plugin.login(this.loginName, this.password);
this.password = '';
this.display();
new Notice(`Signed in. Found ${this.campaigns.length} campaign(s).`);
} catch (error) {
new Notice(error.message || 'Could not sign in to Dragonroll.');
} finally {
button.setDisabled(false);
}
}));
if (this.plugin.settings.token) {
new Setting(containerEl)
.setName('Campaign')
.setDesc('The campaign used by import and push commands.')
.addDropdown((dropdown) => {
dropdown.addOption('', 'Choose a campaign');
for (const campaign of this.campaigns) {
dropdown.addOption(String(campaign._id), campaign.name);
}
dropdown.setValue(this.plugin.settings.campaignId || '');
dropdown.onChange(async (value) => {
this.plugin.settings.campaignId = value;
await this.plugin.saveSettings();
});
})
.addButton((button) => button
.setButtonText('Load campaigns')
.onClick(async () => {
button.setDisabled(true);
try {
this.campaigns = await this.plugin.getCampaigns();
this.display();
new Notice(`Loaded ${this.campaigns.length} campaign(s).`);
} catch (error) {
new Notice(error.message || 'Could not load campaigns.');
} finally {
button.setDisabled(false);
}
}));
new Setting(containerEl)
.setName('Auto-sync changes')
.setDesc('Every time Obsidian saves a linked note, its title and content are sent to Dragonroll. A new note inside the campaign folder becomes a campaign note, and deleting a linked file deletes its campaign note. Off means only the import and push commands touch Dragonroll.')
.addToggle((toggle) => toggle
.setValue(!!this.plugin.settings.autoSync)
.onChange(async (value) => {
this.plugin.settings.autoSync = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Sign out')
.setDesc('Remove the saved Dragonroll session from this vault.')
.addButton((button) => button
.setButtonText('Sign out')
.onClick(async () => {
this.plugin.settings.token = '';
this.plugin.settings.campaignId = '';
await this.plugin.saveSettings();
this.display();
}));
}
}
}
function safeSegment(value, fallback) {
const safe = String(value || '')
.replace(/[\\\/:*?"<>|#^\[\]]/g, '-')
.replace(/[. ]+$/g, '')
.trim();
return safe || fallback;
}
function stripPluginMetadata(markdown) {
const text = String(markdown || '');
const match = text.match(/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/);
if (!match) return text;
const keptLines = match[2].split(/\r?\n/).filter((line) =>
!/^(dragonrollId|dragonrollCampaign|dragonrollTitle):\s*/.test(line)
);
const frontmatter = keptLines.join('\n').trim();
const body = text.slice(match[0].length);
return frontmatter ? `---\n${frontmatter}\n---\n${body}` : body;
}
async function signature(title, content) {
const value = `${title}\u0000${String(content).replace(/\r\n/g, '\n')}`;
if (globalThis.crypto?.subtle) {
const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
}
let hash = 2166136261;
for (let index = 0; index < value.length; index += 1) {
hash = Math.imul(hash ^ value.charCodeAt(index), 16777619);
}
return (hash >>> 0).toString(16);
}

View File

@@ -0,0 +1,9 @@
{
"id": "dragonroll-sync",
"name": "Dragonroll Sync",
"version": "1.0.0",
"minAppVersion": "1.5.0",
"description": "Import Dragonroll campaign notes into Obsidian and push edits back.",
"author": "Dragonroll",
"isDesktopOnly": false
}

View File

@@ -147,7 +147,6 @@ function loadFoundryWriters({ seed = {}, settings } = {}) {
if (id === "../services/actor-foundry") return repoRequire(path.join("backend", "src", "services", "actor-foundry.js"));
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
@@ -340,8 +339,6 @@ function makeWorld({ actors = [], remoteActors = [] } = {}) {
fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({ href, method: options.method, body: options.body ? JSON.parse(options.body) : null });
if (href.includes("foundry/sync/characters")) return { ok: true, status: 200, json: async () => ({ status: "ok", actors: remoteActors }) };
if (href.includes("foundry/sync/items")) return { ok: true, status: 200, json: async () => ({ status: "ok", items: [] }) };
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Item: { async create() { return null; } },
@@ -415,87 +412,6 @@ function makeWorld({ actors = [], remoteActors = [] } = {}) {
return state;
}
// The campaign's character for `actor`, holding what Dragonroll keeps for it.
function campaignCharacter(actor, over = {}) {
return {
_id: "dr-actor-1",
name: "Thalia",
type: "character",
species: "",
className: "",
subclass: "",
level: 1,
background: "",
challengeRating: "",
description: "",
image: "",
abilityScores: {},
armorClass: 10,
speed: 30,
traits: "",
proficiencies: "",
spells: "",
inventory: [],
foundryActorId: actor?.id ?? null,
...over,
};
}
test("a trait row an older campaign left in the inventory does not become a loot duplicate", async () => {
// A campaign that synced before #89 still carries its world's traits as inventory
// rows. Writing the character must neither make a piece of loot after a trait's name
// nor touch the world's feat it holds that name — the row is the campaign's to write
// off, and the document is the world's to keep.
const actor = makeStubActor("Thalia", {
system: { details: {} },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [{ _id: "feat-1", name: "Darkvision", type: "feat", system: { featType: "trs" } }],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, {
traits: "Darkvision\nSee in the dark.",
inventory: [{ name: "Darkvision", quantity: 1, weight: 0 }],
})],
}).start();
assert.deepEqual(world.itemNames(actor), [["feat", "Darkvision"]],
"no gear made after the trait's name, and the feat stands where it was");
assert.equal(actor.items.contents[0].system.quantity, undefined, "the world's feat is not written as gear");
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("writing the character leaves the world's trait and species documents where they stand", async () => {
// An earlier sync marked everything in the actor as its own. The campaign no longer
// carries traits and species in the inventory, so those marks must not cost the world
// its documents — while loot the campaign truly dropped still goes.
const actor = makeStubActor("Thalia", {
system: { details: {} },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: "feat-1", name: "Darkvision", type: "feat", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "race-1", name: "Human", type: "race", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "loot-old", name: "Torch", type: "loot", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, {
species: "Human",
traits: "Darkvision\nSee in the dark.",
inventory: [{ name: "Rations", quantity: 1, weight: 0.5 }],
})],
}).start();
assert.deepEqual(world.itemNames(actor), [
["feat", "Darkvision"],
["race", "Human"],
["loot", "Rations"],
], "the trait and the species survive, the carried gear follows the campaign");
assert.equal(actor.system.details.race, "race-1", "the species reference still resolves to the surviving item");
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("the snapshot marks the carried gear and no longer the world's own documents", async () => {
const actor = makeStubActor("Grimnir", {
system: { details: {} },

View File

@@ -173,6 +173,7 @@ function campaign({ folders = [], notes = [], actors = [], items = [], maps = []
// seed says otherwise.
Folder: realFolderModel(folders.map((folder) => ({ campaign: "campaign-1", ...folder }))),
Note: fakeCollection("note", notes),
Media: fakeCollection("media", []),
Actor: fakeCollection("actor", actors),
Item: fakeCollection("item", items),
Map: fakeCollection("map", maps),
@@ -182,6 +183,7 @@ function campaign({ folders = [], notes = [], actors = [], items = [], maps = []
"../models/Campaign": { findOne: () => ({ lean: async () => campaignDoc }) },
"../models/Folder": collections.Folder,
"../models/Note": collections.Note,
"../models/Media": collections.Media,
"../models/Actor": collections.Actor,
"../models/Item": collections.Item,
"../models/Map": collections.Map,

View File

@@ -6,21 +6,14 @@
// background item that does not exist and a details reference resolving to nothing —
// adding a background in Foundry then failed.
//
// The backend mapper is plain CommonJS and is required directly. The Foundry module is
// loaded into a `node:vm` context holding stubbed Foundry globals with fake timers, like
// tests/foundry-sync-toggle.test.js: the characters Dragonroll answers with are applied
// to a stubbed actor, so the references it writes are observable.
// The backend mapper is plain CommonJS and is required directly: it reads the
// Foundry document and resolves those references to the names Dragonroll holds.
//
// 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 MODULE_ID = "dragonroll-foundry";
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const { foundryActorToCharacter } = require(path.join(__dirname, "..", "backend", "src", "services", "actor-foundry.js"));
@@ -91,327 +84,3 @@ test("a class reference that resolves to nothing falls back to the class item",
assert.equal(fields.className, "Fighter", "the class the actor carries, not the id");
assert.equal(fields.species, "", "and nothing to name the species from");
});
// --- The Foundry module applies Dragonroll's character --------------------------
// A reference is either the id this sync wrote or the document the field resolves to.
function referenceId(actor, field) {
const value = actor.system.details?.[field];
return typeof value === "string" ? value : value?._id || "";
}
function makeStubItem(id, { name, type, system = {}, flags = {} }) {
return {
_id: id,
id,
name,
type,
system,
flags,
parent: { documentName: "Actor" },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
toObject() {
return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: this.flags };
},
};
}
function writeDotted(target, data) {
for (const [key, value] of Object.entries(data)) {
const parts = key.split(".");
const last = parts.pop();
let node = target;
for (const part of parts) node = node[part] ??= {};
node[last] = value;
}
}
let stubCounter = 0;
function makeStubActor(name, { type = "character", system = {}, flags = {}, items = [] } = {}) {
stubCounter += 1;
const id = `actor-${stubCounter}`;
const contents = items.map((item, index) => makeStubItem(item._id || `embedded-${stubCounter}-${index}`, item));
const actor = {
id,
name,
type,
documentName: "Actor",
img: "icons/svg/mystery-man.svg",
system,
flags,
items: { contents },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
async update(data) {
writeDotted(this, data);
return this;
},
async updateEmbeddedDocuments(documentName, updates) {
for (const update of updates) {
const item = contents.find((candidate) => candidate.id === update._id);
if (item) writeDotted(item, update);
}
return updates.map((update) => contents.find((candidate) => candidate.id === update._id));
},
async createEmbeddedDocuments(documentName, datas) {
const created = datas.map((data) => {
const item = makeStubItem(`embedded-${stubCounter}-${contents.length}`, data);
item.name = data.name;
item.type = data.type;
contents.push(item);
return item;
});
return created;
},
async deleteEmbeddedDocuments(documentName, ids) {
for (const id of ids) {
const index = contents.findIndex((item) => item.id === id);
if (index >= 0) contents.splice(index, 1);
}
return ids;
},
toObject() {
return {
_id: this.id,
name: this.name,
type: this.type,
img: this.img,
flags: this.flags,
system: this.system,
};
},
};
return actor;
}
// A linked world with the actors it holds, answering `foundry/sync/characters` with the
// campaign's characters. Each one is applied to its Foundry actor on the next reconcile.
function makeWorld({ actors = [], remoteActors = [] } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
nextTimerId: 1,
logs: [],
};
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
const sandbox = {
console: {
log() {},
info() {},
warn: (...args) => state.logs.push(args.map(String).join(" ")),
error: (...args) => state.logs.push(args.map(String).join(" ")),
},
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 timerId = state.nextTimerId++;
state.timers.set(timerId, { fn, delay });
return timerId;
},
clearTimeout: (timerId) => state.timers.delete(timerId),
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({ href, method: options.method, body: options.body ? JSON.parse(options.body) : null });
if (href.includes("foundry/sync/characters")) return { ok: true, status: 200, json: async () => ({ status: "ok", actors: remoteActors }) };
if (href.includes("foundry/sync/items")) return { ok: true, status: 200, json: async () => ({ status: "ok", items: [] }) };
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Item: { async create() { return null; } },
Actor: {
async create(data) {
const actor = makeStubActor(data.name, {
type: data.type,
system: structuredClone(data.system || {}),
flags: structuredClone(data.flags || {}),
items: (data.items || []).map((item) => ({ name: item.name, type: item.type, system: item.system })),
});
actors.push(actor);
return actor;
},
},
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: actors, get: (actorId) => actors.find((actor) => actor.id === actorId) },
items: { contents: [], get: () => null },
folders: { contents: [], get: () => null },
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.actor = (actorId) => actors.find((actor) => actor.id === actorId);
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
// World start: the actors are pushed, then the campaign's characters are applied.
state.start = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
return state;
};
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.itemNames = (actor) => actor.items.contents.map((item) => [item.type, item.name]);
return state;
}
// The campaign's character for `actor`, holding what Dragonroll keeps for it.
function campaignCharacter(actor, over = {}) {
return {
_id: "dr-actor-1",
name: "Thalia",
type: "character",
species: "",
className: "",
subclass: "",
level: 1,
background: "",
challengeRating: "",
description: "",
image: "",
abilityScores: {},
armorClass: 10,
speed: 30,
traits: "",
proficiencies: "",
spells: "",
inventory: [],
foundryActorId: actor?.id ?? null,
...over,
};
}
test("Dragonroll's background becomes the actor's background item, referenced by id", async () => {
const actor = makeStubActor("Thalia", {
system: { details: { background: "" } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { background: "Soldier" })],
}).start();
const background = actor.items.contents.find((item) => item.type === "background");
assert.ok(background, "the character's background stands in Foundry as an item");
assert.equal(background.name, "Soldier");
assert.equal(referenceId(actor, "background"), background.id, "its details reference points at the item");
assert.equal(actor.system.details.background, background.id);
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("the background an earlier sync invented is taken back out", async () => {
// What the bug left behind: an item named after the id the details field held, next to
// the real background, and a reference the old sync overwrote with that id.
const actor = makeStubActor("Thalia", {
system: { details: { background: ID_GONE } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: ID_SOLDIER, name: "Soldier", type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "item-bogus", name: ID_GONE, type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { background: "Soldier" })],
}).start();
assert.deepEqual(world.itemNames(actor), [["background", "Soldier"]], "only the real background is left");
assert.equal(referenceId(actor, "background"), ID_SOLDIER, "and the reference resolves to it");
});
test("a background taken off in Dragonroll clears the reference", async () => {
const actor = makeStubActor("Thalia", {
system: { details: { background: ID_SOLDIER } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: ID_SOLDIER, name: "Soldier", type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({ actors: [actor], remoteActors: [campaignCharacter(actor)] }).start();
assert.deepEqual(world.itemNames(actor), [], "the background item went with it");
assert.equal(referenceId(actor, "background"), "", "and no reference is left pointing at nothing");
});
test("a species never lands in the details reference as a name", async () => {
const actor = makeStubActor("Thalia", {
// A species picked in the sheet: dnd5e made the race item and referenced it by id.
system: { details: { race: ID_HUMAN } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [{ _id: ID_HUMAN, name: "Human", type: "race", flags: { [MODULE_ID]: { syncedItem: true } } }],
});
await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { species: "Human", background: "Soldier" })],
}).start();
assert.equal(referenceId(actor, "race"), ID_HUMAN, "the species reference still points at the race item");
assert.notEqual(actor.system.details.race, "Human", "a name in it would resolve to nothing");
});
test("a species the world keeps as plain text is left to the world", async () => {
// An actor migrated from an older system release: no race item, the name is what the
// field holds, and Dragonroll has nothing to reference.
const actor = makeStubActor("Thalia", {
system: { details: { race: "Human" } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
});
await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { species: "Human" })],
}).start();
assert.equal(actor.system.details.race, "Human", "the text the sheet reads is kept as it was");
});
test("a character made in Dragonroll references the background it is created with", async () => {
const world = await makeWorld({ actors: [], remoteActors: [campaignCharacter(null, { background: "Soldier" })] }).start();
const [actor] = world.game.actors.contents;
assert.ok(actor, "the campaign's character was made in this world");
const background = actor.items.contents.find((item) => item.type === "background");
assert.ok(background, "created together with its background item");
assert.equal(background.name, "Soldier");
assert.equal(referenceId(actor, "background"), background.id, "referenced by that item's id, never its name");
});

View File

@@ -283,7 +283,6 @@ function loadFoundryWriters({ seed = {} } = {}) {
if (id === "../services/actor-foundry") return repoRequire(path.join("backend", "src", "services", "actor-foundry.js"));
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);

View File

@@ -1,938 +0,0 @@
// Tests for the campaign's notes reaching the Foundry world as journal pages
// (Syndria98/dragonroll#98): each Dragonroll folder stands as a journal named after
// its path (root notes share "Dragonroll"), written by the module and kept in step
// with the campaign. The copy runs one way — notes are written in Dragonroll — so
// the backend answers with the notes and their folder paths and remembers each
// note's page; the module reads them, renders the markdown, moves a page when its
// note changes folder, and prunes the page of a note the campaign deleted.
//
// Both sides are loaded the way the other Foundry tests do it: the sync route runs
// against a stubbed `require` (models answer with plain objects and a small filter
// matcher), and the Foundry module is loaded into a `node:vm` context holding
// stubbed Foundry globals (`game.journal` and `JournalEntry` included) with fake
// timers, like tests/item-folder-sync.test.js.
//
// 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 MODULE_ID = "dragonroll-foundry";
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 note routes use: equality, $or, $in, $nin,
// $exists, $ne. 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));
if (operator === "$ne") return String(value ?? "") !== String(wanted ?? "");
throw new Error(`filter operator "${key}.${operator}" is not stubbed`);
});
}
return String(value ?? "") === String(expected ?? "");
});
}
function fakeModel(table, seed = [], campaignId) {
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) {
// A seeded row belongs to the campaign the requests are made against unless the
// seed says otherwise: the routes scope every lookup by campaign.
const row = new Document({ campaign: campaignId, ...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;
}
// 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 seeded = (rows = []) => rows.map((row) => ({ campaign: campaign._id, ...row }));
const models = {
"../models/Actor": fakeModel("actor", seeded(seed.actors)),
"../models/Item": fakeModel("item", seeded(seed.items)),
"../models/Folder": fakeModel("folder", seeded(seed.folders)),
"../models/Note": fakeModel("note", seeded(seed.notes)),
"../models/Map": fakeModel("map", seeded(seed.maps)),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id.startsWith("node:")) return require(id); // crypto: the sync token is hashed, not stubbed
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 (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
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 };
}
// --- The sync route: the notes it answers and the page ids it keeps ---------------
test("the notes revision folds the campaign's notes into one hash", async () => {
const sync = loadSyncRoute({
seed: {
notes: [
{ _id: "note-1", title: "Session 1", content: "hi" },
{ _id: "note-2", title: "Tavern Brawl", content: "ho" },
],
},
});
const first = await sync.call("GET /sync/notes/revision");
assert.equal(first.status, "ok");
assert.match(first.revision, /^[0-9a-f]{64}$/, "a sha-256 of the notes, not their content");
sync.models["../models/Note"].rows[0].content = "hi there";
const edited = await sync.call("GET /sync/notes/revision");
assert.notEqual(edited.revision, first.revision, "editing a note moves the revision");
sync.models["../models/Note"].rows[0].content = "hi";
sync.models["../models/Note"].rows[0].foundryPageId = "page-9";
const mapped = await sync.call("GET /sync/notes/revision");
assert.equal(mapped.revision, first.revision, "mapping a note to its page is not an edit");
});
test("the world reads the campaign's notes with their content and page mapping", async () => {
const sync = loadSyncRoute({
seed: {
notes: [
{ _id: "note-1", title: "Session 1", content: "**The start**", foundryPageId: "page-9" },
{ _id: "note-2", title: "Tavern Brawl", content: "- rope" },
],
},
});
const response = await sync.call("GET /sync/notes");
assert.equal(response.status, "ok");
assert.deepEqual(response.notes.map((note) => note.title), ["Session 1", "Tavern Brawl"]);
assert.equal(response.notes[0].content, "**The start**", "the markdown source travels: the module renders it");
assert.equal(response.notes[0].foundryPageId, "page-9", "and the note says which page it already stands as");
});
test("the world reads each note with the path of the folder it lives in", async () => {
const sync = loadSyncRoute({
seed: {
folders: [
{ _id: "folder-1", name: "Sessions", parentFolder: null },
{ _id: "folder-2", name: "Arc 1", parentFolder: "folder-1" },
],
notes: [
{ _id: "note-1", title: "Root", content: "root" },
{ _id: "note-2", title: "In folder", content: "folder", folder: "folder-1" },
{ _id: "note-3", title: "Deep", content: "deep", folder: "folder-2" },
],
},
});
const response = await sync.call("GET /sync/notes");
const pathByTitle = Object.fromEntries(response.notes.map((note) => [note.title, note.folderPath]));
assert.deepEqual(pathByTitle, {
Root: "",
"In folder": "Sessions",
Deep: "Sessions / Arc 1",
}, "the module names the journal of a note after its whole folder path");
});
test("renaming a folder moves the notes revision", async () => {
const sync = loadSyncRoute({
seed: {
folders: [{ _id: "folder-1", name: "Sessions", parentFolder: null }],
notes: [{ _id: "note-1", title: "Session 1", content: "hi", folder: "folder-1" }],
},
});
const before = await sync.call("GET /sync/notes/revision");
sync.models["../models/Folder"].rows[0].name = "Chapters";
const after = await sync.call("GET /sync/notes/revision");
assert.notEqual(after.revision, before.revision,
"a folder rename has to reach the world as another journal name");
});
test("mapping a note to the page the module made keeps them paired", async () => {
const sync = loadSyncRoute({ seed: { notes: [{ _id: "note-1", title: "Session 1", content: "hi" }] } });
const response = await sync.call("POST /sync/map-note", {
worldId: "world-1", noteId: "note-1", foundryPageId: "page-9",
});
assert.equal(response.status, "ok");
assert.equal(sync.models["../models/Note"].rows[0].foundryPageId, "page-9");
// Mapping the same pair again is the module checking, not a conflict.
const again = await sync.call("POST /sync/map-note", {
worldId: "world-1", noteId: "note-1", foundryPageId: "page-9",
});
assert.equal(again.status, "ok");
});
test("a page already mapped to another note is refused", async () => {
const sync = loadSyncRoute({
seed: {
notes: [
{ _id: "note-1", title: "Session 1", content: "hi", foundryPageId: "page-9" },
{ _id: "note-2", title: "Tavern Brawl", content: "ho" },
],
},
});
const response = await sync.call("POST /sync/map-note", {
worldId: "world-1", noteId: "note-2", foundryPageId: "page-9",
});
assert.equal(response.status, "error");
assert.equal(response.msg, "foundry.errors.note-already-synced");
assert.equal(sync.models["../models/Note"].rows.find((row) => row._id === "note-2").foundryPageId, undefined,
"the first note keeps its page");
});
test("map-note wants this world's note and a page for it", async () => {
const sync = loadSyncRoute({ seed: { notes: [{ _id: "note-1", title: "Session 1", content: "hi" }] } });
assert.equal((await sync.call("POST /sync/map-note", { worldId: "world-1" })).msg, "errors.missing-data");
assert.equal((await sync.call("POST /sync/map-note", { noteId: "note-1", foundryPageId: "page-9" })).msg, "errors.missing-data",
"another world cannot map this campaign's note");
const gone = await sync.call("POST /sync/map-note", {
worldId: "world-1", noteId: "note-gone", foundryPageId: "page-9",
});
assert.equal(gone.msg, "errors.notfound");
});
// --- The Foundry module writes the journal ---------------------------------------
// Foundry's `update` takes dotted paths ("flags.dragonroll-foundry.noteId"); an
// embedded document's own id is not a path to set.
function writeFoundryPaths(target, data) {
for (const [key, value] of Object.entries(data)) {
if (key === "_id") continue;
const parts = key.split(".");
const last = parts.pop();
let node = target;
for (const part of parts) node = node[part] ??= {};
node[last] = value;
}
return target;
}
function makeWorld() {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
intervals: new Map(),
// What Dragonroll answers the notes reconcile with. Mapping a page answers
// like the real backend: the note keeps the page id, so later reads carry it.
remoteNotes: [],
rollMessages: [],
clickListeners: [],
nextId: 1,
};
const journals = [];
const makePage = (journal, data = {}) => {
const page = {
id: `page-${state.nextId++}`,
documentName: "JournalEntryPage",
name: data.name,
text: { content: data.text?.content ?? "" },
flags: data.flags ?? {},
writes: 0,
get uuid() { return `JournalEntry.${journal.id}.JournalEntryPage.${this.id}`; },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
async update(update) {
page.writes += 1;
writeFoundryPaths(page, update);
return page;
},
async delete() {
const index = journal.pages.contents.indexOf(page);
if (index >= 0) journal.pages.contents.splice(index, 1);
},
};
return page;
};
const makeJournal = (data = {}) => {
const pages = [];
return {
id: `journal-${state.nextId++}`,
name: data.name,
documentName: "JournalEntry",
flags: data.flags ?? {},
get uuid() { return `JournalEntry.${this.id}`; },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
pages: { contents: pages, get: (id) => pages.find((page) => page.id === id) },
async update(update) { return writeFoundryPaths(this, update); },
async delete() {
const index = journals.indexOf(this);
if (index >= 0) journals.splice(index, 1);
},
async createEmbeddedDocuments(documentName, docs) {
assert.equal(documentName, "JournalEntryPage", "the notes' pages are journal pages");
// Foundry's own page validation refuses a page without a name.
for (const doc of docs) assert.ok(doc.name, "a journal page needs a non-empty name");
const created = docs.map((doc) => makePage(this, doc));
pages.push(...created);
return created;
},
};
};
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" } },
document: {
addEventListener(name, fn) {
if (name === "click") state.clickListeners.push(fn);
},
},
Roll: class FakeRoll {
constructor(formula) {
this.formula = formula;
this.evaluated = false;
}
async evaluate() {
this.evaluated = true;
return this;
}
async toMessage(data) {
assert.equal(this.evaluated, true, "the roll is evaluated before it reaches chat");
state.rollMessages.push({ formula: this.formula, ...data });
}
},
ChatMessage: { getSpeaker: () => ({ alias: "GM" }) },
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.nextId++;
state.timers.set(id, { fn, delay });
return id;
},
clearTimeout: (id) => state.timers.delete(id),
setInterval: (fn, delay = 0) => {
// Recorded, never run by itself: tests ask for a periodic reconcile with
// `runIntervals`, so the ones watching single pushes stay on their own.
const id = state.nextId++;
state.intervals.set(id, { fn, delay });
return id;
},
clearInterval: (id) => state.intervals.delete(id),
fetch: async (url, options = {}) => {
const href = String(url);
const body = options.body ? JSON.parse(options.body) : null;
state.requests.push({ href, method: options.method, body });
if (href.includes("foundry/sync/map-note")) {
const note = state.remoteNotes.find((entry) => String(entry._id) === String(body.noteId));
if (note) note.foundryPageId = body.foundryPageId;
return { ok: true, status: 200, json: async () => ({ status: "ok", note }) };
}
// The cheap change check: a hash of the notes' content, so changing
// `remoteNotes` (and nothing else) is what makes the module pull them over,
// like the backend hashing the campaign's notes does.
if (href.includes("foundry/sync/notes/revision")) {
const revision = state.remoteNotes
.map((note) => [
note._id, note.title ?? "", note.content ?? "",
note.folder ?? "", note.folderPath ?? "",
].join("\u0000"))
.sort()
.join("\u0001");
return { ok: true, status: 200, json: async () => ({ status: "ok", revision }) };
}
if (href.includes("foundry/sync/notes")) {
return { ok: true, status: 200, json: async () => ({ status: "ok", notes: state.remoteNotes }) };
}
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
JournalEntry: {
async create(data) {
const journal = makeJournal(data);
journals.push(journal);
return [journal];
},
},
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: [], get: () => null },
items: { contents: [], get: () => null },
folders: { contents: [], get: () => null },
journal: { contents: journals, get: (id) => journals.find((journal) => journal.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.journals = () => journals;
state.addJournal = (name, flags = {}) => {
const journal = makeJournal({ name, flags });
journals.push(journal);
return journal;
};
state.addPage = (journal, data) => {
const page = makePage(journal, data);
journal.pages.contents.push(page);
return page;
};
state.mapNoteRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/map-note"));
state.notesReads = () => state.requests.filter((request) => request.href.includes("foundry/sync/notes"));
// The full note pulls, not the cheap revision pings the change check makes.
state.notesPulls = () => state.requests.filter((request) =>
request.href.includes("foundry/sync/notes") && !request.href.includes("/revision"));
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();
}
};
// The reconciles `setInterval` registered: what runs every few seconds on a
// linked world, and so what carries each note into its journal page.
state.runIntervals = async () => {
for (const interval of [...state.intervals.values()]) await interval.fn();
await drain();
};
// Press a dice button the journal drew: the module listens on the document and
// finds the button through `closest`, like a click inside a journal page.
state.clickRoll = async (formula) => {
const button = { dataset: { dragonrollRoll: formula } };
const event = {
target: { closest: (selector) => (selector === "[data-dragonroll-roll]" ? button : null) },
defaultPrevented: false,
preventDefault() { this.defaultPrevented = true; },
};
for (const listener of state.clickListeners) await listener(event);
await drain();
return event;
};
state.linkedSetup = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
state.requests.length = 0;
return state;
};
return state;
}
// The fetch stub updates a note with the page it maps, like the real backend
// does, so every test works on notes of its own.
const sessionNote = (over = {}) => ({ _id: "note-1", title: "Session 1", content: "**The start**", ...over });
const tavernNote = (over = {}) => ({ _id: "note-2", title: "Tavern Brawl", content: "A rope, a chandelier.", ...over });
test("the campaign's notes become pages of one Dragonroll journal", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [sessionNote(), tavernNote()];
await world.runIntervals();
assert.equal(world.journals().length, 1, "one journal carries the campaign's notes");
const journal = world.journals()[0];
assert.equal(journal.name, "Dragonroll");
assert.deepEqual(journal.pages.contents.map((page) => [page.name, page.text.content]), [
["Session 1", "<p><strong>The start</strong></p>"],
["Tavern Brawl", "<p>A rope, a chandelier.</p>"],
], "each note is a page, its markdown drawn into the page's HTML");
assert.deepEqual(journal.pages.contents.map((page) => page.getFlag(MODULE_ID, "noteId")), ["note-1", "note-2"],
"each page keeps the note it stands for");
assert.deepEqual(world.mapNoteRequests().map((request) => [request.body.noteId, request.body.foundryPageId]), [
["note-1", journal.pages.contents[0].id],
["note-2", journal.pages.contents[1].id],
], "and the campaign remembers each note's page");
});
test("notes in a folder share the journal named after its path", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [
sessionNote(),
{ _id: "note-2", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
{ _id: "note-3", title: "The cave", content: "dark", folder: "folder-2", folderPath: "Sessions / Arc 1" },
];
await world.runIntervals();
const byName = new Map(world.journals().map((journal) => [journal.name, journal]));
assert.deepEqual([...byName.keys()].sort(), ["Dragonroll", "Sessions", "Sessions / Arc 1"],
"the root notes and each folder path get a journal of their own");
assert.deepEqual(byName.get("Dragonroll").pages.contents.map((page) => page.name), ["Session 1"]);
assert.deepEqual(byName.get("Sessions").pages.contents.map((page) => page.name), ["The road"]);
assert.deepEqual(byName.get("Sessions / Arc 1").pages.contents.map((page) => page.name), ["The cave"],
"a subfolder's notes stand in a journal named after the whole path");
assert.equal(byName.get("Sessions").getFlag(MODULE_ID, "notesFolder"), "folder-1",
"each folder journal keeps the folder it belongs to");
assert.equal(byName.get("Sessions / Arc 1").getFlag(MODULE_ID, "notesFolder"), "folder-2");
});
test("renaming a folder renames its journal", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [
{ _id: "note-1", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
];
await world.runIntervals();
world.remoteNotes = [{ ...world.remoteNotes[0], folderPath: "Chapters" }];
await world.runIntervals();
assert.deepEqual(world.journals().map((journal) => journal.name), ["Chapters"],
"the journal follows the folder's path without being made again");
assert.equal(world.journals()[0].pages.contents.length, 1, "and its page stays where it was");
});
test("a note moved to another folder takes its page to that folder's journal", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [
{ _id: "note-1", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
];
await world.runIntervals();
const firstPage = world.journals()[0].pages.contents[0];
world.remoteNotes = [{
...world.remoteNotes[0],
folder: "folder-2",
folderPath: "Sessions / Arc 1",
}];
await world.runIntervals();
assert.deepEqual(world.journals().map((journal) => journal.name), ["Sessions / Arc 1"],
"the journal the note left goes when it has nothing else in it");
const moved = world.journals()[0].pages.contents[0];
assert.equal(moved.name, "The road");
assert.notEqual(moved.id, firstPage.id, "the page is made in the journal the note moved to");
assert.equal(world.remoteNotes[0].foundryPageId, moved.id, "and the campaign maps the note to its new page");
});
test("reconciling again does not double the journal or its pages", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [sessionNote(), tavernNote()];
await world.runIntervals();
await world.runIntervals();
await world.runIntervals();
assert.equal(world.journals().length, 1, "the journal is made once, not per reconcile");
assert.equal(world.journals()[0].pages.contents.length, 2, "and each note stands as the one page it was given");
assert.equal(world.mapNoteRequests().length, 2, "an already-mapped note is not mapped again");
});
test("an existing journal named Dragonroll is used, not doubled", async () => {
const world = await makeWorld().linkedSetup();
const gmsOwn = world.addJournal("Dragonroll");
world.remoteNotes = [sessionNote()];
await world.runIntervals();
assert.equal(world.journals().length, 1, "the journal the world already had is the notes' one");
assert.deepEqual(gmsOwn.pages.contents.map((page) => page.name), ["Session 1"]);
assert.equal(gmsOwn.getFlag(MODULE_ID, "notesJournal"), true, "and it is marked, so renaming it keeps the notes' home findable");
});
test("extra journals named Dragonroll are removed before the notes are written", async () => {
const world = await makeWorld().linkedSetup();
const kept = world.addJournal("Dragonroll", { [MODULE_ID]: { notesJournal: true } });
const gmDuplicate = world.addJournal("Dragonroll");
const flaggedDuplicate = world.addJournal("Dragonroll", { [MODULE_ID]: { notesJournal: true } });
const unrelated = world.addJournal("Session Log");
world.remoteNotes = [sessionNote()];
await world.runIntervals();
assert.deepEqual(world.journals(), [kept, unrelated],
"only the journal the reconcile writes into survives, beside the GM's other journals");
assert.deepEqual(kept.pages.contents.map((page) => page.name), ["Session 1"]);
assert.equal(gmDuplicate.pages.contents.length, 0);
assert.equal(flaggedDuplicate.pages.contents.length, 0);
assert.ok(unrelated, "a journal of another name is left alone");
});
test("several journals named Dragonroll collapse into the first one", async () => {
const world = await makeWorld().linkedSetup();
const first = world.addJournal("Dragonroll");
world.addJournal("Dragonroll");
world.addJournal("Dragonroll");
world.remoteNotes = [sessionNote()];
await world.runIntervals();
assert.deepEqual(world.journals(), [first], "the duplicates go, the first one stays the notes' home");
assert.deepEqual(first.pages.contents.map((page) => page.name), ["Session 1"]);
assert.equal(first.getFlag(MODULE_ID, "notesJournal"), true);
});
test("a note edited in Dragonroll rewrites its page", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [sessionNote()];
await world.runIntervals();
const first = world.remoteNotes[0];
world.remoteNotes = [{ ...first, title: "Session 1 — revisited", content: "**A different start**" }];
await world.runIntervals();
const journal = world.journals()[0];
assert.equal(journal.pages.contents.length, 1, "the note still stands as the same single page");
assert.deepEqual(journal.pages.contents[0].name, "Session 1 — revisited");
assert.equal(journal.pages.contents[0].text.content, "<p><strong>A different start</strong></p>");
assert.equal(world.mapNoteRequests().length, 1, "the pairing the world reads back needs no remapping");
});
test("a note deleted in Dragonroll takes its page with it", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [sessionNote(), tavernNote()];
await world.runIntervals();
const journal = world.journals()[0];
const gmsPage = world.addPage(journal, { name: "My own notes", text: { content: "not from Dragonroll" } });
world.remoteNotes = world.remoteNotes.filter((note) => note._id !== "note-2");
await world.runIntervals();
assert.deepEqual(journal.pages.contents.map((page) => page.name), ["Session 1", "My own notes"],
"the deleted note's page goes; the GM's own page stays");
assert.ok(journal.pages.contents.includes(gmsPage));
});
test("pages already in step with the campaign are not rewritten", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [sessionNote()];
await world.runIntervals();
const [page] = world.journals()[0].pages.contents;
assert.equal(page.writes, 0, "the page was created whole, not patched");
await world.runIntervals();
assert.equal(page.writes, 0, "a reconcile that changes nothing leaves the page alone");
});
test("an unchanged campaign is not pulled over again", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [sessionNote()];
await world.runIntervals();
assert.equal(world.notesPulls().length, 1, "the first reconcile pulls the notes");
await world.runIntervals();
assert.equal(world.notesPulls().length, 1,
"with the revision and the journal unchanged, only the cheap revision is asked for");
});
test("a page a GM edited is written back from the campaign's note", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [sessionNote()];
await world.runIntervals();
const page = world.journals()[0].pages.contents[0];
page.name = "GM renamed it";
page.text.content = "GM wrote this";
await world.runIntervals();
assert.equal(page.name, "Session 1", "the campaign's title is written back over the GM's");
assert.equal(page.text.content, "<p><strong>The start</strong></p>", "and so is its content");
});
test("a journal page a GM removed is built again from the campaign's note", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [sessionNote()];
await world.runIntervals();
world.journals()[0].pages.contents.length = 0;
await world.runIntervals();
assert.deepEqual(world.journals()[0].pages.contents.map((entry) => entry.name), ["Session 1"],
"the journal holds the note's page again");
});
test("the campaign's page mapping claims a page whose flag was lost", async () => {
const world = await makeWorld().linkedSetup();
const journal = world.addJournal("Dragonroll");
const orphan = world.addPage(journal, { name: "Old name", text: { content: "old" } });
world.remoteNotes = [{ _id: "note-1", title: "Session 1", content: "**The start**", foundryPageId: orphan.id }];
await world.runIntervals();
assert.equal(journal.pages.contents.length, 1, "no second page under the same title");
assert.equal(orphan.name, "Session 1");
assert.equal(orphan.getFlag(MODULE_ID, "noteId"), "note-1", "and the page is marked again");
});
test("text that is not markdown is escaped, not injected", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [{ _id: "note-1", title: "Session 1", content: "a & b < c\nline two\n\nsecond para" }];
await world.runIntervals();
assert.equal(
world.journals()[0].pages.contents[0].text.content,
"<p>a &amp; b &lt; c<br />line two</p>\n<p>second para</p>",
"the raw text is escaped and stays legible",
);
});
test("a note's markdown is drawn into the page: headings, lists and marks", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [{
_id: "note-1",
title: "Session 1",
content: "# Session One\n\n## The Tavern\n\n- rope\n- **torch**\n\n> danger\n\n---\n\n`code` and [a link](https://dragonroll.test)",
}];
await world.runIntervals();
assert.equal(
world.journals()[0].pages.contents[0].text.content,
"<h1>Session One</h1>\n"
+ "<h2>The Tavern</h2>\n"
+ "<ul>\n<li>rope</li>\n<li><strong>torch</strong></li>\n</ul>\n"
+ "<blockquote><p>danger</p></blockquote>\n"
+ "<hr />\n"
+ "<p><code>code</code> and <a href=\"https://dragonroll.test\">a link</a></p>",
"the note is drawn as the elements Foundry's journal styles know",
);
});
test("a note's dice widgets become buttons that roll in Foundry", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [{
_id: "note-1",
title: "Goblin",
content: "The goblin attacks with @roll[1d20+4].\n\n@roll\n8d6\n@end",
}];
await world.runIntervals();
const html = world.journals()[0].pages.contents[0].text.content;
assert.match(html,
/<p>The goblin attacks with <button type="button" class="dragonroll-note-roll" data-dragonroll-roll="1d20\+4" title="Roll 1d20\+4"><i class="fa-solid fa-dice-d20" aria-hidden="true"><\/i><span>1d20\+4<\/span><\/button>\.<\/p>/,
"the inline widget is a button showing the expression the note wrote");
assert.match(html,
/<button type="button" class="dragonroll-note-roll dragonroll-note-roll-block" data-dragonroll-roll="8d6" title="Roll 8d6">/,
"the block widget is a button of its own, drawn full width");
const event = await world.clickRoll("1d20+4");
assert.equal(event.defaultPrevented, true, "the click does not navigate the journal");
assert.deepEqual(world.rollMessages.map((message) => message.formula), ["1d20+4"],
"pressing the button evaluates that expression in Foundry");
assert.equal(world.rollMessages[0].speaker.alias, "GM");
assert.match(world.rollMessages[0].flavor, /1d20\+4/,
"the chat card says the roll came from Dragonroll");
});
test("advantage and disadvantage become Foundry's keep-highest and keep-lowest", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [{
_id: "note-1",
title: "Rolls",
content: "@roll[d20adv] @roll[2d20dis] @roll[4d6kh1]",
}];
await world.runIntervals();
const html = world.journals()[0].pages.contents[0].text.content;
assert.match(html, /data-dragonroll-roll="2d20kh1"/, "advantage rolls twice and keeps the higher die");
assert.match(html, /data-dragonroll-roll="2d20kl1"/, "disadvantage rolls twice and keeps the lower die");
assert.match(html, /data-dragonroll-roll="4d6kh1"/, "a keep-highest expression already reads as Foundry does");
});
test("a dice widget inside a code span stays text", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [{ _id: "note-1", title: "Syntax", content: "`@roll[1d6]`" }];
await world.runIntervals();
assert.equal(world.journals()[0].pages.contents[0].text.content,
"<p><code>@roll[1d6]</code></p>",
"code that shows the widget syntax is not turned into a button");
});
// --- Wiki links and embeds in the journal page -----------------------------------
test("a note's [[links]] and ![[embeds]] become Foundry's own enrichers", async () => {
const world = await makeWorld().linkedSetup();
world.game.actors.contents.push({ id: "actor-1", name: "Mira", documentName: "Actor" });
world.game.items.contents.push({ id: "item-1", name: "Rope of Climbing", documentName: "Item" });
world.remoteNotes = [{
_id: "note-1",
title: "Links",
content: "[[Mira]] and ![[Mira]]\n\n[[Rope of Climbing]] and ![[Rope of Climbing]]",
}];
await world.runIntervals();
const html = world.journals()[0].pages.contents[0].text.content;
assert.match(html, /@UUID\[Actor\.actor-1\]\{Mira\}/,
"a link to a character opens it in Foundry");
assert.match(html, /@Embed\[Actor\.actor-1\]\{Mira\}/,
"an embedded character is drawn as a sheet preview");
assert.match(html, /@UUID\[Item\.item-1\]\{Rope of Climbing\}/,
"a link to an item opens it in Foundry");
assert.match(html, /@Embed\[Item\.item-1\]\{Rope of Climbing\}/,
"an embedded item is drawn as its sheet");
});
test("a name the world does not have is left dimmed, and only sheets can be embedded", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [{
_id: "note-1",
title: "Missing",
content: "[[Nobody]]\n\n![[Nobody]]\n\n![[Tavern Brawl]]",
}];
await world.runIntervals();
const html = world.journals()[0].pages.contents[0].text.content;
assert.match(html, /<span class="dragonroll-note-link is-unresolved">Nobody<\/span>/,
"an unresolved link still reads, but cannot be opened");
assert.match(html, /<span class="dragonroll-note-link is-unresolved">Tavern Brawl<\/span>/,
"a note written with the bang is not embedded as a sheet");
assert.doesNotMatch(html, /@Embed\[/, "nothing is embedded when there is no character or item");
});
test("a note can link to another note created in the same pull", async () => {
const world = await makeWorld().linkedSetup();
world.remoteNotes = [
sessionNote({ content: "See [[Tavern Brawl]]." }),
tavernNote(),
];
await world.runIntervals();
const journal = world.journals()[0];
const sessionPage = journal.pages.contents.find((page) => page.name === "Session 1");
const tavernPage = journal.pages.contents.find((page) => page.name === "Tavern Brawl");
assert.match(
sessionPage.text.content,
new RegExp(`@UUID\\[JournalEntry\\.${journal.id}\\.JournalEntryPage\\.${tavernPage.id}\\]\\{Tavern Brawl\\}`),
"the page of the note it points at opens from the link"
);
});
test("autosync off: the campaign's notes are not written into the world", async () => {
const world = await makeWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
world.remoteNotes = [sessionNote()];
await world.runIntervals();
assert.deepEqual(world.journals(), [], "no journal is made");
assert.deepEqual(world.notesReads(), [], "and the campaign is not even asked");
});

View File

@@ -302,7 +302,7 @@ test("force sync refuses an actor Dragonroll does not import", async () => {
assert.ok(world.notifications.some(([kind, text]) => kind === "warn" && text.includes("Cart")));
});
test("turning autosync back on reconciles both sides again", async () => {
test("turning autosync back on sends the world's snapshot again", async () => {
const world = makeStubWorld({ autoSync: false });
await world.fire("init");
await world.fire("ready");
@@ -314,6 +314,4 @@ test("turning autosync back on reconciles both sides again", async () => {
assert.ok(world.syncRequests().some((request) => request.body?.fullSync === true),
"the world sends its full snapshot again");
assert.ok(world.requests.some((request) => request.href.includes("foundry/sync/characters")),
"Dragonroll documents are applied back into the world");
});

View File

@@ -144,7 +144,6 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
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 (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
@@ -420,28 +419,6 @@ test("a module that says nothing about colours leaves the campaign's colour alon
assert.equal(sync.models["../models/Folder"].rows[0].color, "#7f00ff");
});
test("the folder list the world reads back carries the colours the campaign picked", async () => {
const sync = loadSyncRoute({
seed: {
folders: [
{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons", color: "#0080ff" },
{ _id: "folder-2", target: "item", name: "Homebrew" },
{ _id: "folder-3", name: "Chapter 1" },
],
items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }],
},
});
const response = await sync.call("GET /sync/items");
assert.equal(response.status, "ok");
assert.equal(response.items.length, 1);
const coloured = response.folders.find((folder) => folder._id === "folder-1");
assert.equal(coloured.foundryFolderId, "folder-melee", "the world's folder to write the colour back to");
assert.equal(coloured.color, "#0080ff");
assert.ok(!response.folders.some((folder) => folder._id === "folder-3"), "only the item list's folders travel back");
});
test("every folder listing says which campaign list it belongs to", () => {
// The sidebar's four lists share the Folder model, so a listing that names no target
// would show folders of the other lists between its own rows. The note routes and
@@ -476,9 +453,6 @@ function makeWorld() {
requests: [],
timers: new Map(),
intervals: new Map(),
// What Dragonroll answers a folder reconcile with: the campaign's folders and the
// colours its user gave them.
remoteFolders: [],
nextTimerId: 1,
};
@@ -579,9 +553,7 @@ function makeWorld() {
method: options.method,
body: options.body ? JSON.parse(options.body) : null,
});
const payload = { status: "ok", actors: [], items: [] };
if (href.includes("foundry/sync/items")) payload.folders = state.remoteFolders;
return { ok: true, status: 200, json: async () => payload };
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
@@ -632,12 +604,6 @@ function makeWorld() {
await drain();
}
};
// The reconciles `setInterval` registered: what runs every few seconds on a world
// that is linked, and so what carries Dragonroll's folder colours back into the world.
state.runIntervals = async () => {
for (const interval of [...state.intervals.values()]) await interval.fn();
await drain();
};
state.linkedSetup = async () => {
await state.fire("init");
await state.fire("ready");
@@ -740,43 +706,6 @@ test("autosync off: folder changes stop syncing", async () => {
assert.deepEqual(world.syncRequests(), []);
});
// --- The colours the campaign gives those folders travel back to the world ---------
test("a folder coloured in the Dragonroll campaign is coloured in the world", async () => {
const world = await makeWorld().linkedSetup();
world.remoteFolders = [
{ _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: "#0080ff" },
// A folder the campaign made for its own items: there is no world document to colour.
{ _id: "db-homebrew", name: "Homebrew", color: "#00ff00" },
];
await world.runIntervals();
assert.equal(world.folder("folder-melee").color, "#0080ff");
assert.equal(world.folder("folder-ranged").color, null, "a folder the campaign says nothing about keeps what the world shows");
assert.deepEqual(world.requests.filter((request) => request.method === "POST"), [],
"Dragonroll's own write is not pushed back to the campaign as a world change");
});
test("a colour taken off in the campaign comes off the world's folder", async () => {
const world = await makeWorld().linkedSetup();
world.remoteFolders = [{ _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: null }];
await world.runIntervals();
assert.equal(world.folder("folder-melee").color, null, "uncoloured in the campaign is uncoloured in the world");
});
test("autosync off: the campaign's folder colours are not written into the world", async () => {
const world = await makeWorld().linkedSetup();
await world.game.settings.set("dragonroll-foundry", "autoSync", false);
world.remoteFolders = [{ _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: "#0080ff" }];
await world.runIntervals();
assert.equal(world.folder("folder-melee").color, "#8b0000", "the world keeps what it shows while autosync is off");
});
// --- The sidebar groups its items under those folders ----------------------------
// `vm.compileFunction` is synchronous, so the service is ready right away. Loading it with

View File

@@ -92,9 +92,6 @@ test("the item window shows the info and offers both icon sources", () => {
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", () => {

View File

@@ -1,600 +0,0 @@
// Tests for the world's scenes arriving as the campaign's maps (Syndria98/dragonroll#99).
// Only a scene's background picture and the grid laid over it travel: the campaign keeps its
// own scale, its folders, its pinned notes and the tokens standing on the map, and none of it
// goes back to the world.
//
// Same set-up as tests/item-folder-sync.test.js, which the repository root runs without
// installing anything: the sync route is loaded into `node:vm` with express, mongoose and its
// models stubbed (plain rows and a small filter matcher), so creating, adopting and pruning
// maps is observable without a database. The Foundry module is loaded into a `node:vm` context
// holding stubbed Foundry globals (`game.scenes` included) with fake timers, like
// tests/foundry-sync-toggle.test.js.
//
// 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 scene sync uses: equality, $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]) => {
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 = [], campaignId) {
const rows = [];
let counter = 0;
function Document(data = {}) {
counter += 1;
this._id = `${table}-${counter}`;
this.isNew = true;
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) {
// A seeded row belongs to the campaign the requests are made against unless the seed
// says otherwise: the sync scopes every lookup by campaign.
const row = new Document({ campaign: campaignId, 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 };
};
return model;
}
// 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", settings } = {}) {
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,
...(settings ? { settings } : {}),
};
const seeded = (rows = []) => rows.map((row) => ({ campaign: campaign._id, ...row }));
const models = {
"../models/Actor": fakeModel("actor", seeded(seed.actors)),
"../models/Item": fakeModel("item", seeded(seed.items)),
"../models/Folder": fakeModel("folder", seeded(seed.folders)),
"../models/Note": fakeModel("note", seeded(seed.notes)),
"../models/Map": fakeModel("map", seeded(seed.maps)),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id.startsWith("node:")) return require(id); // crypto: the sync token is hashed, not stubbed
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 { foundryItemToItemData: () => null };
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
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 };
}
// A scene of the world, as the module sends it: plain document data with its picture read
// from the world. This one is 70 px cells and the picture of the ruined keep.
function worldScene(over = {}) {
return {
_id: "scene-1",
name: "The Ruined Keep",
img: "http://vtt.test/images/keep.webp",
grid: 70,
flags: {},
...over,
};
}
const maps = (sync) => sync.models["../models/Map"].rows;
// --- A scene arrives as a map -------------------------------------------------------
test("a world scene arrives as a map of the campaign", async () => {
const sync = loadSyncRoute();
const response = await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
assert.equal(response.status, "ok");
const [map] = maps(sync);
assert.equal(map.name, "The Ruined Keep");
assert.equal(map.image, "http://vtt.test/images/keep.webp", "the scene's background picture is the map's");
assert.equal(map.gridSize, 70, "the scene's own cell size is the grid the campaign draws");
assert.equal(map.offsetX, 0);
assert.equal(map.offsetY, 0, "a scene that shifts nothing has its grid at the corner of the picture");
assert.equal(map.foundrySceneId, "scene-1");
assert.equal(map.campaign, sync.campaign._id, "the map belongs to the campaign the world is linked to");
assert.deepEqual(response.maps, [{ foundrySceneId: "scene-1", mapId: map._id, created: true }]);
});
test("a scene keeps the grid its world shifted onto the picture", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/scenes", {
worldId: "world-1",
scenes: [worldScene({ grid: 64, flags: { core: { shiftX: 12, shiftY: -8 } } })],
});
const [map] = maps(sync);
assert.equal(map.gridSize, 64);
assert.equal(map.offsetX, 12);
assert.equal(map.offsetY, -8, "a grid that starts off the corner of the picture arrives where the world puts it");
});
test("a scene of a newer Foundry still arrives", async () => {
const sync = loadSyncRoute();
// Since Foundry V13 the picture sits under `background.src` and the cell size under
// `grid.size`.
await sync.call("POST /sync/scenes", {
worldId: "world-1",
scenes: [worldScene({ img: undefined, background: { src: "http://vtt.test/images/keep.webp" }, grid: { size: 128 } })],
});
const [map] = maps(sync);
assert.equal(map.image, "http://vtt.test/images/keep.webp");
assert.equal(map.gridSize, 128);
});
test("a scene's picture is read against the world the campaign knows", async () => {
// An older module sends Foundry's own relative path; it is read against the world's
// address, the way an actor's portrait is (Syndria98/dragonroll#89).
const sync = loadSyncRoute({ settings: { integrations: { foundryUrl: "http://vtt.test:30000" } } });
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene({ img: "images/keep.webp" })] });
assert.equal(maps(sync)[0].image, "http://vtt.test:30000/images/keep.webp");
});
test("a scene with no picture is not a map", async () => {
const sync = loadSyncRoute({
seed: { maps: [{ _id: "map-1", name: "The Ruined Keep", foundrySceneId: "scene-1", image: "http://vtt.test/images/keep.webp" }] },
});
// The GM took the picture off the scene: its id still travels with the snapshot, so its
// map is neither made blank nor dropped, and no new row is made for it either.
const response = await sync.call("POST /sync/scenes", {
worldId: "world-1",
scenes: [worldScene({ img: "" })],
fullSync: true,
});
assert.deepEqual(response.maps, []);
assert.equal(maps(sync).length, 1);
assert.equal(maps(sync)[0].image, "http://vtt.test/images/keep.webp");
});
test("what one of the map's cells stands for stays the campaign's", async () => {
const sync = loadSyncRoute({
seed: { maps: [{ _id: "map-1", name: "The Ruined Keep", foundrySceneId: "scene-1", gridSize: 50, scale: 1.5 }] },
});
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene({ gridDistance: 1500, gridUnits: "m" })] });
assert.equal(maps(sync)[0].gridSize, 70, "the world's cell size arrives");
assert.equal(maps(sync)[0].scale, 1.5, "and the distance the campaign says a cell covers is left alone");
});
// --- One map per scene ---------------------------------------------------------------
test("the same scene is never made into two maps", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
const response = await sync.call("POST /sync/scenes", {
worldId: "world-1",
scenes: [worldScene({ name: "The Ruined Keep, II", grid: 80 })],
});
assert.equal(maps(sync).length, 1, "the scene was written over, not doubled");
assert.equal(maps(sync)[0].name, "The Ruined Keep, II");
assert.equal(maps(sync)[0].gridSize, 80);
assert.equal(response.maps[0].created, false, "the push says it wrote a map it already had");
});
test("a live scene edit lands on the map, however the campaign had it", async () => {
const sync = loadSyncRoute({
seed: { maps: [{ _id: "map-1", name: "Old name", foundrySceneId: "scene-1", image: "old.png", gridSize: 40 }] },
});
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
const [map] = maps(sync);
assert.equal(map.image, "http://vtt.test/images/keep.webp");
assert.equal(map.gridSize, 70);
assert.equal(map.name, "The Ruined Keep");
});
test("a full snapshot leaves the picture and grid the campaign lined up alone", async () => {
const sync = loadSyncRoute({
seed: { maps: [{ _id: "map-1", name: "My keep", foundrySceneId: "scene-1", image: "my-keep.png", gridSize: 40 }] },
});
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()], fullSync: true });
const [map] = maps(sync);
assert.equal(map.image, "my-keep.png", "a GM reconnecting does not write over a map the campaign already had");
assert.equal(map.gridSize, 40);
assert.equal(map.name, "My keep");
});
test("a scene takes over the map the campaign drew by hand", async () => {
const sync = loadSyncRoute({
seed: { maps: [{ _id: "map-1", name: "The Ruined Keep", image: "hand-made.png", gridSize: 50 }] },
});
const response = await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
assert.equal(maps(sync).length, 1, "the room the campaign drew first is not doubled by its scene");
assert.equal(maps(sync)[0]._id, "map-1");
assert.equal(maps(sync)[0].foundrySceneId, "scene-1", "and it is the scene's map from then on");
assert.equal(response.maps[0].mapId, "map-1");
});
test("a scene carrying the campaign's map id adopts that row", async () => {
const sync = loadSyncRoute({
seed: { maps: [{ _id: "map-0123456789abcdef0123456789", name: "Keep under way", image: "hand-made.png" }] },
});
const response = await sync.call("POST /sync/scenes", {
worldId: "world-1",
scenes: [worldScene({ name: "Somewhere else", flags: { "dragonroll-foundry": { mapId: "map-0123456789abcdef0123456789" } } })],
});
assert.equal(maps(sync).length, 1);
assert.equal(response.maps[0].mapId, "map-0123456789abcdef0123456789", "the flag says which map the scene is");
});
// --- Pruning --------------------------------------------------------------------------
test("a full snapshot prunes the maps whose scene this world let go of", async () => {
const sync = loadSyncRoute({
seed: {
maps: [
{ _id: "map-1", name: "Cellar", foundrySceneId: "scene-gone" },
{ _id: "map-2", name: "Homebrew ford" },
{ _id: "map-3", name: "The Ruined Keep", foundrySceneId: "scene-1" },
],
},
});
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()], fullSync: true });
assert.deepEqual(maps(sync).map((map) => map._id).sort(), ["map-2", "map-3"],
"the scene that is gone takes its map with it, and the campaign's own maps stay");
});
test("a live scene push never prunes", async () => {
const sync = loadSyncRoute({
seed: { maps: [{ _id: "map-1", name: "Cellar", foundrySceneId: "scene-gone" }] },
});
await sync.call("POST /sync/scenes", { worldId: "world-1", scenes: [worldScene()] });
assert.equal(maps(sync).length, 2, "a push of one scene says nothing about the world's other scenes");
});
test("a scene the world deleted takes its map with it", async () => {
const sync = loadSyncRoute({
seed: {
maps: [
{ _id: "map-1", name: "The Ruined Keep", foundrySceneId: "scene-1" },
{ _id: "map-2", name: "Homebrew ford" },
],
},
});
const response = await sync.call("POST /sync/scene-delete", { worldId: "world-1", foundrySceneId: "scene-1" });
assert.equal(response.status, "ok");
assert.deepEqual(maps(sync).map((map) => map._id), ["map-2"], "only the map of that scene goes");
});
// --- What the route refuses -----------------------------------------------------------
test("a push that is not the campaign's world, or names no scenes, is refused", async () => {
const sync = loadSyncRoute();
assert.equal((await sync.call("POST /sync/scenes", { worldId: "another-world", scenes: [worldScene()] })).msg, "errors.missing-data");
assert.equal((await sync.call("POST /sync/scenes", { worldId: "world-1" })).msg, "errors.missing-data");
assert.deepEqual(maps(sync), [], "nothing was written");
});
test("a delete from another world, or naming no scene, is refused", async () => {
const sync = loadSyncRoute({ seed: { maps: [{ _id: "map-1", name: "Keep", foundrySceneId: "scene-1" }] } });
assert.equal((await sync.call("POST /sync/scene-delete", { worldId: "another-world", foundrySceneId: "scene-1" })).msg, "errors.missing-data");
assert.equal((await sync.call("POST /sync/scene-delete", { worldId: "world-1" })).msg, "errors.missing-data");
assert.equal(maps(sync).length, 1, "and the map is still there");
});
test("a map remembers which scene of the world it mirrors", () => {
const model = read("backend", "src", "models", "Map.js");
assert.match(model, /foundrySceneId:\s*{\s*type:\s*String\s*}/, "the scene a map mirrors is kept on the map");
assert.match(model, /\{\s*campaign:\s*1,\s*foundrySceneId:\s*1\s*\}/, "and is unique within the campaign");
});
// --- The Foundry module sends its scenes ---------------------------------------------
const MODULE_ID = "dragonroll-foundry";
function makeWorld({ autoSync = true } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
intervals: new Map(),
nextTimerId: 1,
};
// A Scene document: the plain data `toObject()` answers with, which since V13 carries
// the picture under `background` rather than `img`.
const makeScene = (id, name, over = {}) => ({
id, name, documentName: "Scene", img: "", grid: 50, flags: {},
toObject() {
return {
_id: this.id, name: this.name, img: this.img, grid: this.grid, flags: this.flags,
...(this.background ? { background: this.background } : {}),
};
},
...over,
});
const scenes = [
makeScene("scene-keep", "The Ruined Keep", { img: "images/keep.webp", grid: 70 }),
// A newer Foundry keeps its picture under `background`, and this one is already an
// absolute URL, which travels as it is.
makeScene("scene-tavern", "Tavern", { img: undefined, background: { src: "http://other.test/tavern.jpg" }, grid: 50 }),
];
const settingsStore = { autoSync, 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: (fn, delay = 0) => {
const id = state.nextTimerId++;
state.intervals.set(id, { fn, delay });
return id;
},
clearInterval: (id) => state.intervals.delete(id),
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" }) };
},
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: [], get: () => null },
items: { contents: [], get: () => null },
scenes: { contents: scenes, get: (id) => scenes.find((scene) => scene.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.scene = (id) => scenes.find((scene) => scene.id === id);
// The two routes the maps travel on: the campaign's reads live under the same prefix and
// tell nothing about what the world sent.
state.sceneRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/scenes")
|| request.href.includes("foundry/sync/scene-delete"));
state.pushes = (route) => state.requests.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();
}
};
// A world that is already linked: init, ready, and the pushes the world makes as it loads.
state.setup = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
return state;
};
// The same, with the world's own pushes out of the way, so a test only sees what it causes.
state.linkedSetup = async () => {
await state.setup();
state.requests.length = 0;
return state;
};
return state;
}
test("the world sends its whole scene list as the campaign's maps when it loads", async () => {
const world = await makeWorld().setup();
const [push] = world.pushes("foundry/sync/scenes");
assert.ok(push, "a linked world pushes its scenes as it loads");
assert.equal(push.body.fullSync, true, "the whole list travels, which is the push that lets the campaign prune");
assert.deepEqual(push.body.worldId, "world-1");
assert.deepEqual(push.body.scenes.map((scene) => [scene._id, scene.name]), [
["scene-keep", "The Ruined Keep"],
["scene-tavern", "Tavern"],
]);
assert.equal(push.body.scenes[0].img, "http://vtt.test/images/keep.webp",
"the picture is read from this world, so it travels as an absolute URL");
assert.equal(push.body.scenes[0].grid, 70, "the scene's own cell size travels with it");
assert.equal(push.body.scenes[1].background.src, "http://other.test/tavern.jpg",
"a picture that is already absolute is left as it is");
});
test("a scene the GM changes reaches the campaign as that map", async () => {
const world = await makeWorld().linkedSetup();
const keep = world.scene("scene-keep");
keep.name = "The Sunken Keep";
keep.grid = 100;
await world.fire("updateScene", keep);
await world.runTimers();
const [push] = world.pushes("foundry/sync/scenes");
assert.equal(push.body.fullSync, false, "a live scene edit never prunes the campaign's other maps");
assert.deepEqual(push.body.scenes.map((scene) => [scene._id, scene.name, scene.grid]), [
["scene-keep", "The Sunken Keep", 100],
]);
});
test("a scene the GM deletes takes its map off the campaign", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("deleteScene", world.scene("scene-tavern"));
await world.runTimers();
const [push] = world.pushes("foundry/sync/scene-delete");
assert.equal(push.body.foundrySceneId, "scene-tavern");
assert.deepEqual(world.pushes("foundry/sync/scenes"), [], "a deleted scene is not sent as a map to keep");
});
test("autosync off: the world's scenes stop syncing, at world start and afterwards", async () => {
const world = makeWorld({ autoSync: false });
await world.fire("init");
await world.fire("ready");
await world.runTimers();
assert.deepEqual(world.sceneRequests(), [], "a world with autosync off sends no scene list");
await world.fire("updateScene", world.scene("scene-keep"));
await world.fire("deleteScene", world.scene("scene-tavern"));
await world.runTimers();
assert.deepEqual(world.sceneRequests(), []);
});
test("the scene edits queued while autosync was off are sent when it is turned back on", async () => {
const world = await makeWorld({ autoSync: false });
await world.fire("init");
await world.fire("ready");
await world.runTimers();
await world.fire("updateScene", world.scene("scene-keep"));
await world.runTimers();
assert.deepEqual(world.sceneRequests(), []);
await world.game.settings.set(MODULE_ID, "autoSync", true);
await world.runTimers();
assert.ok(world.pushes("foundry/sync/scenes").some((push) => push.body.fullSync === true
&& push.body.scenes.length === 2),
"turning autosync back on sends this world's whole scene list again");
assert.ok(world.pushes("foundry/sync/scenes").some((push) => push.body.fullSync === false
&& push.body.scenes.map((scene) => scene._id).includes("scene-keep")),
"and the scene edit queued while it was off is sent");
});

View File

@@ -184,6 +184,8 @@ function loadNoteRoutes({ ownsCampaign = true, notes = [], folders = [], deleted
findById: (id) => mongooseQuery(notes.find((note) => note._id === id) ?? null),
deleteOne: () => mongooseQuery({ deletedCount }),
},
// The note lists also carry the media files standing beside the notes.
"../models/Media": { find: () => mongooseQuery([]) },
"../models/Folder": {
find: () => mongooseQuery(folders),
// models/Folder.js: the note tree is every folder that is not one of the other

196
tests/map-walls.test.js Normal file
View File

@@ -0,0 +1,196 @@
// Tests for the walls of a map: straight segments drawn with the wall tool, stored with the map in
// image pixels, in three kinds (normal, terrain, invisible).
//
// Same set-up as tests/map-tokens.test.js, which the repository root runs without installing
// anything: the express router is loaded into `node:vm` with its models stubbed, and the last checks
// read the viewer template, where the drawing 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(walls = []) {
return { _id: "map-1", campaign: "campaign-1", walls, save: async () => {} };
}
function loadMapRoutes({ ownsCampaign = true, maps = [] } = {}) {
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: () => mongooseQuery(null) },
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
});
}
function wallRouteTests() {
test("a wall is saved with its type and both of its spots in image pixels", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map] });
const response = await api.call("POST /wall", {
body: { id: "map-1", type: "terrain", x1: "10.4", y1: "-3", x2: "70.6", y2: "40" },
});
assert.equal(response.status, "ok");
assert.deepEqual(map.walls, [{ type: "terrain", x1: 10, y1: 0, x2: 71, y2: 40 }]);
});
test("a wall without a known type is a normal wall", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map] });
await api.call("POST /wall", { body: { id: "map-1", x1: 0, y1: 0, x2: 50, y2: 0 } });
await api.call("POST /wall", { body: { id: "map-1", type: "door", x1: 0, y1: 50, x2: 50, y2: 50 } });
assert.deepEqual(map.walls.map((wall) => wall.type), ["normal", "normal"]);
});
test("the three kinds of wall are kept apart", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map] });
for (const type of ["normal", "terrain", "invisible"]) {
await api.call("POST /wall", { body: { id: "map-1", type, x1: 0, y1: 0, x2: 10, y2: 10 } });
}
assert.deepEqual(map.walls.map((wall) => wall.type), ["normal", "terrain", "invisible"]);
});
test("a wall needs its map and both of its ends", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map] });
assert.equal((await api.call("POST /wall", { body: { x1: 0, y1: 0, x2: 10, y2: 10 } })).msg, "errors.missing-data");
assert.equal((await api.call("POST /wall", { body: { id: "map-1", x1: 0, y1: 0, y2: 10 } })).msg, "errors.missing-data");
assert.deepEqual(map.walls, []);
});
test("a map of somebody else's campaign takes no wall", async () => {
const map = makeMap();
const api = loadMapRoutes({ ownsCampaign: false, maps: [map] });
const response = await api.call("POST /wall", { body: { id: "map-1", type: "terrain", x1: 0, y1: 0, x2: 10, y2: 10 } });
assert.equal(response.msg, "unauthorized");
assert.deepEqual(map.walls, []);
});
test("removing a wall takes the one it is given and keeps the others", async () => {
const map = makeMap([
{ _id: "wall-1", type: "normal", x1: 0, y1: 0, x2: 50, y2: 0 },
{ _id: "wall-2", type: "invisible", x1: 50, y1: 0, x2: 50, y2: 50 },
]);
const api = loadMapRoutes({ maps: [map] });
const response = await api.call("POST /unwall", { body: { id: "map-1", wall: "wall-1" } });
assert.equal(response.status, "ok");
assert.deepEqual(map.walls, [{ _id: "wall-2", type: "invisible", x1: 50, y1: 0, x2: 50, y2: 50 }]);
});
test("removing a wall of a map of somebody else keeps it", async () => {
const map = makeMap([{ _id: "wall-1", type: "normal", x1: 0, y1: 0, x2: 50, y2: 0 }]);
const api = loadMapRoutes({ ownsCampaign: false, maps: [map] });
const response = await api.call("POST /unwall", { body: { id: "map-1", wall: "wall-1" } });
assert.equal(response.msg, "unauthorized");
assert.equal(map.walls.length, 1);
});
test("the map schema stores walls of the three kinds", () => {
const model = readRepoFile("backend", "src", "models", "Map.js");
assert.match(model, /walls:\s*\[/);
for (const type of ["normal", "terrain", "invisible"]) {
assert.match(model, new RegExp(`['"]${type}['"]`), `the ${type} wall is missing from the schema`);
}
});
}
function mapViewerWallWiringTests() {
const pane = readRepoFile("frontend", "app", "components", "viewer", "map", "MapViewerPane.vue");
test("the wall tool is a toggle of the map toolbar", () => {
assert.match(pane, /:class="\{ selected: wallMode \}"/);
assert.match(pane, /@click="toggleWalls"/);
assert.match(pane, /const WALL_TYPES = \['normal', 'terrain', 'invisible'\]/);
assert.match(pane, /v-for="type in WALL_TYPES"/);
});
test("a drag with the wall tool on draws a wall instead of panning the map", () => {
assert.match(pane, /if \(wallMode\.value\) \{[^}]*imagePointOf\(event\)/);
assert.match(pane, /drawingWall\.value = \{ x1: spot\.x, y1: spot\.y, x2: spot\.x, y2: spot\.y \}/);
assert.match(pane, /['"]\/map\/wall['"]/);
assert.match(pane, /['"]\/map\/unwall['"]/);
});
test("a click that did not drag leaves no wall behind", () => {
assert.match(pane, /Math\.hypot\(wall\.x2 - wall\.x1, wall\.y2 - wall\.y1\) >= 2\) await saveWall\(wall\)/);
});
test("walls are drawn over the image and only catch the mouse with the tool on", () => {
assert.match(pane, /class="map-walls"/);
assert.match(pane, /\.map-walls\s*\{[^}]*pointer-events:\s*none/);
assert.match(pane, /\.map-walls\.editing \.map-wall-hit\s*\{[^}]*pointer-events:\s*stroke/);
assert.match(pane, /@contextmenu\.stop\.prevent="onWallContextMenu\(wall\)"/);
});
test("invisible walls are hidden until the wall tool is on", () => {
assert.match(pane, /function wallVisible\(wall\) \{\s*return wall\.type !== 'invisible' \|\| wallMode\.value;/);
});
}
wallRouteTests();
mapViewerWallWiringTests();

198
tests/note-media.test.js Normal file
View File

@@ -0,0 +1,198 @@
// Tests for the media files that stand in the note tree beside the notes (the sidebar lists
// images, sounds, videos and documents with an icon of their type, the way a file explorer does).
//
// The repository root installs no dependencies, so the media routes run against a stubbed
// `require`, the note lists are read out of the real route file the same way, and the sidebar and
// nested list are read as text like tests/sidebar-entity-entry.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");
const vm = require("node:vm");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
function loadRoutes(file, models) {
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 === "path") return path;
// The upload folder and the file it drops are not what these checks are about.
if (id === "fs") return { unlink: (file, done) => done() };
if (id === "../services/storage") return { single: () => (req, res, next) => next() };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", file), ["require", "module", "exports", "__dirname"])(
requireStub, moduleStub, moduleStub.exports, path.join(__dirname, "..", "backend", "src", "routes")
);
return async function call(route, { body = {}, query = {}, file = null } = {}) {
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, file, user: { id: "user-1" } }, res);
return res.payload;
};
}
function loadMediaRoutes({ ownsCampaign = true, media = null, folderOk = true } = {}) {
const deleted = [];
const api = loadRoutes("media.js", {
"../models/Campaign": { findOne: () => ({ lean: async () => (ownsCampaign ? { _id: "campaign-1" } : null) }) },
"../models/Folder": { belongsToSection: async () => folderOk },
"../models/Media": Object.assign(
function Media(data) { Object.assign(this, { _id: "media-new", save: async () => {} }, data); },
{
findById: async () => media,
deleteOne: async (filter) => { deleted.push(filter); return { deletedCount: 1 }; },
}
),
});
return { api, deleted };
}
function seededMedia() {
return {
_id: "media-1", campaign: "campaign-1", file: "file-1.png", mimeType: "image/png",
save: async () => {},
};
}
// --- Routes ---------------------------------------------------------------------
test("an uploaded file becomes a media row of the campaign", async () => {
const { api } = loadMediaRoutes();
const response = await api("POST /upload", {
body: { campaign: "campaign-1" },
file: { filename: "file-1.png", mimetype: "image/png", originalname: "harbour.png" },
});
assert.equal(response.status, "ok");
assert.equal(response.media.name, "harbour.png");
assert.equal(response.media.file, "file-1.png");
assert.equal(response.media.mimeType, "image/png");
assert.equal(response.media.folder, null);
});
test("an upload into another campaign is refused", async () => {
const { api } = loadMediaRoutes({ ownsCampaign: false });
const response = await api("POST /upload", {
body: { campaign: "campaign-1" },
file: { filename: "file-1.png", mimetype: "image/png", originalname: "harbour.png" },
});
assert.equal(response.msg, "unauthorized");
});
test("a media file only stands in a note folder", async () => {
const { api } = loadMediaRoutes({ folderOk: false });
const response = await api("POST /upload", {
body: { campaign: "campaign-1", folder: "actor-folder-1" },
file: { filename: "file-1.png", mimetype: "image/png", originalname: "harbour.png" },
});
assert.equal(response.msg, "errors.notfound");
});
test("a media row moves into a folder and back to the root", async () => {
const media = seededMedia();
const { api } = loadMediaRoutes({ media });
const moved = await api("POST /update", { body: { id: "media-1", folder: "folder-1" } });
assert.equal(moved.status, "ok");
assert.equal(media.folder, "folder-1");
await api("POST /update", { body: { id: "media-1", folder: null } });
assert.equal(media.folder, null);
});
test("deleting a media file of somebody else's campaign leaves it where it is", async () => {
const { api, deleted } = loadMediaRoutes({ media: seededMedia(), ownsCampaign: false });
const response = await api("POST /delete", { body: { id: "media-1" } });
assert.equal(response.msg, "unauthorized");
assert.equal(deleted.length, 0, "the row must not be dropped");
});
test("deleting a media file drops its row", async () => {
const { api, deleted } = loadMediaRoutes({ media: seededMedia() });
const response = await api("POST /delete", { body: { id: "media-1" } });
assert.equal(response.status, "ok");
assert.equal(deleted.length, 1);
});
test("a deleted note folder takes its media rows to the root with it", () => {
const folderRoute = read("backend", "src", "routes", "folder.js");
assert.match(folderRoute, /Media\.updateMany\(\s*\{ folder: folderId \}/);
});
// --- Both note lists carry the media standing at their level ---------------------
test("the note tree's root list carries the media at the root", () => {
const noteRoute = read("backend", "src", "routes", "note.js");
assert.match(noteRoute, /Media\.find\(\{ campaign, folder: null \}\)/);
const list = /router\.get\('\/list'[\s\S]*?res\.json\(\{ status: 'ok', folders, notes: rootNotes, media \}\)/.exec(noteRoute);
assert.ok(list, "expected /note/list to answer with media");
});
test("a folder's list carries the media standing in that folder", () => {
const noteRoute = read("backend", "src", "routes", "note.js");
assert.match(noteRoute, /Media\.find\(\{ campaign, folder \}\)/);
assert.match(noteRoute, /res\.json\(\{ status: 'ok', subfolders, notes, media \}\)/);
});
// --- The sidebar -----------------------------------------------------------------
test("the notes section offers a media upload", () => {
const sidebar = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
assert.match(sidebar, /chooseMedia/);
assert.match(sidebar, /type="file" multiple @change="uploadMedia"/);
assert.match(sidebar, /Server\(\)\.post\('\/media\/upload'/);
});
test("the note tree passes each level's media down to its rows", () => {
const sidebar = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
assert.match(sidebar, /:media="media"/);
const nested = read("frontend", "app", "components", "partials", "NestedNoteList.vue");
assert.match(nested, /:media="getFolderMedia\(folder\._id\)"/);
assert.match(nested, /v-for="item in media"/);
});
test("every media row leads with the icon of its type", () => {
const nested = read("frontend", "app", "components", "partials", "NestedNoteList.vue");
assert.match(nested, /type\.startsWith\('image\/'\)[\s\S]*media-image\.svg/);
assert.match(nested, /type\.startsWith\('audio\/'\)[\s\S]*music-note\.svg/);
assert.match(nested, /type\.startsWith\('video\/'\)[\s\S]*media-video\.svg/);
assert.match(nested, /application\/pdf[\s\S]*page\.svg/);
});
test("a media window is registered and reads the file from /api/public", () => {
const definitions = read("frontend", "app", "services", "WindowDefinitions.js");
assert.match(definitions, /media_viewer: \{[\s\S]*MediaViewerWindow\.vue/);
const viewer = read("frontend", "app", "components", "windows", "MediaViewerWindow.vue");
assert.match(viewer, /getBaseUrl\(\)\}\/public\/\$\{media\.file\}/);
});
test("every locale names the upload and the media window", () => {
for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json"));
assert.ok(campaigns.media?.upload, `${locale} must name the media upload`);
assert.ok(campaigns.media?.["upload-error"], `${locale} must say an upload failed`);
assert.ok(windows["media-viewer"], `${locale} must name the media window`);
}
});

View File

@@ -0,0 +1,198 @@
// Tests for the Obsidian plugin's automatic sync: vault events push edits, create notes for files
// added to the campaign folder, and delete the note of a deleted file. The plugin is loaded from
// source with a stubbed `obsidian` module so the real class runs under node:test.
//
// 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 SOURCE = fs.readFileSync(
path.join(__dirname, "..", "obsidian-plugin", "obsidian-dragonroll", "main.js"),
"utf8",
);
function loadPluginClass() {
const module = { exports: {} };
const requireStub = (name) => {
if (name !== "obsidian") throw new Error(`unexpected require: ${name}`);
return {
Notice: class { constructor(message) { this.message = message; } },
Plugin: class {},
PluginSettingTab: class {},
Setting: class {},
normalizePath: (value) => value,
requestUrl: async () => { throw new Error("network is not stubbed"); },
};
};
new Function("module", "exports", "require", SOURCE)(module, module.exports, requireStub);
return module.exports;
}
const DragonrollPlugin = loadPluginClass();
const FILE = {
path: "Dragonroll/Campaign/Session 1.md",
basename: "Session 1",
extension: "md",
};
const BUFFER = [
"---",
"dragonrollId: n1",
"dragonrollCampaign: c1",
"tags: [session]",
"---",
"# Hello",
"",
].join("\n");
function makePlugin({ file = FILE, frontmatter = {}, settings = {}, buffer = BUFFER } = {}) {
const plugin = new DragonrollPlugin();
plugin.settings = { token: "t", campaignId: "c1", autoSync: true, snapshots: {}, ...settings };
plugin.status = { setText() {} };
plugin.suspended = false;
plugin.internalWrites = new Set();
plugin.linkedNotes = new Map();
plugin.syncChain = Promise.resolve();
plugin.saveSettings = async () => {};
plugin.requests = [];
plugin.request = async (url, options = {}) => {
plugin.requests.push({ url, options });
if (url === "/campaign/list") return { status: "ok", campaigns: [{ _id: "c1", name: "Campaign" }] };
if (url === "/note/create") return { status: "ok", note: { _id: "n2" } };
if (url === "/note/update") return { status: "ok", note: { _id: "n1" } };
return { status: "ok" };
};
plugin.app = {
vault: {
getAbstractFileByPath: () => file,
read: async () => buffer,
getMarkdownFiles: () => [file],
},
metadataCache: {
getFileCache: () => ({ frontmatter: { dragonrollId: "n1", dragonrollCampaign: "c1", ...frontmatter } }),
},
fileManager: {
processFrontMatter: async (target, apply) => {
const written = {};
apply(written);
plugin.writtenFrontmatter = written;
},
},
};
return plugin;
}
async function settle(plugin) {
await plugin.syncChain;
}
test("vault events are ignored when auto-sync is off, the file is not markdown, or the plugin wrote it", async () => {
const off = makePlugin({ settings: { autoSync: false } });
off.onVaultChange(FILE);
await settle(off);
assert.equal(off.requests.length, 0);
const notMarkdown = makePlugin();
notMarkdown.onVaultChange({ ...FILE, extension: "pdf" });
await settle(notMarkdown);
assert.equal(notMarkdown.requests.length, 0);
const importing = makePlugin();
importing.suspended = true;
importing.onVaultChange(FILE);
await settle(importing);
assert.equal(importing.requests.length, 0);
const ownWrite = makePlugin();
ownWrite.internalWrites.add(FILE.path);
ownWrite.onVaultChange(FILE);
await settle(ownWrite);
assert.equal(ownWrite.requests.length, 0);
});
test("saving a linked note updates it with the file content, frontmatter stripped", async () => {
const plugin = makePlugin();
plugin.onVaultChange(FILE);
await settle(plugin);
assert.equal(plugin.requests.length, 1);
const [request] = plugin.requests;
assert.equal(request.url, "/note/update");
assert.deepEqual(request.options.body, {
id: "n1",
title: "Session 1",
content: "---\ntags: [session]\n---\n# Hello\n",
});
assert.ok(plugin.settings.snapshots.n1, "the pushed version becomes the import baseline");
plugin.onVaultChange(FILE);
await settle(plugin);
assert.equal(plugin.requests.length, 1, "an unchanged save is not pushed again");
});
test("a new note inside the campaign folder becomes a campaign note", async () => {
const plugin = makePlugin({
file: { path: "Dragonroll/Campaign/New Note.md", basename: "New Note", extension: "md" },
frontmatter: { dragonrollId: undefined },
buffer: "Body",
});
plugin.onVaultChange(plugin.app.vault.getMarkdownFiles()[0]);
await settle(plugin);
const create = plugin.requests.find((request) => request.url === "/note/create");
assert.ok(create, "the new file was not created in the campaign");
assert.deepEqual(create.options.body, { title: "New Note", content: "Body", campaign: "c1" });
assert.deepEqual(plugin.writtenFrontmatter, {
dragonrollId: "n2",
dragonrollCampaign: "c1",
dragonrollTitle: "New Note",
});
assert.deepEqual(plugin.linkedNotes.get("Dragonroll/Campaign/New Note.md"), { noteId: "n2", campaignId: "c1" });
});
test("a new note outside the campaign folder stays local", async () => {
const plugin = makePlugin({
file: { path: "Notes/Idea.md", basename: "Idea", extension: "md" },
frontmatter: { dragonrollId: undefined },
buffer: "Body",
});
plugin.onVaultChange(plugin.app.vault.getMarkdownFiles()[0]);
await settle(plugin);
assert.equal(plugin.requests.length, 0);
});
test("deleting a linked file, or a folder holding linked files, deletes the campaign notes", async () => {
const plugin = makePlugin();
plugin.settings.snapshots.n1 = "sig";
plugin.linkedNotes.set(FILE.path, { noteId: "n1", campaignId: "c1" });
plugin.linkedNotes.set("Dragonroll/Campaign/Other.md", { noteId: "n3", campaignId: "c1" });
plugin.onVaultDelete(FILE);
await settle(plugin);
assert.deepEqual(plugin.requests.map((request) => request.url), ["/note/delete"]);
assert.deepEqual(plugin.requests[0].options.body, { id: "n1" });
assert.equal(plugin.settings.snapshots.n1, undefined);
plugin.onVaultDelete({ path: "Dragonroll/Campaign" });
await settle(plugin);
assert.deepEqual(plugin.requests[1].options.body, { id: "n3" });
assert.equal(plugin.linkedNotes.size, 0);
});
test("deleting a file linked to another campaign leaves that campaign alone", async () => {
const plugin = makePlugin();
plugin.linkedNotes.set(FILE.path, { noteId: "n9", campaignId: "c2" });
plugin.onVaultDelete(FILE);
await settle(plugin);
assert.equal(plugin.requests.length, 0);
});

View File

@@ -16,6 +16,10 @@ const source = fs.readFileSync(
path.join(__dirname, "..", "frontend", "app", "components", "partials", "ContentSidebar.vue"),
"utf8"
);
const noteListSource = fs.readFileSync(
path.join(__dirname, "..", "frontend", "app", "components", "partials", "NestedNoteList.vue"),
"utf8"
);
// `selector` is inserted verbatim, so escape the `.` of a class combination (`entity-entry\\.anchored`).
// A trailing `\.entity-entry\s*\{` cannot match `.entity-entry:hover` or `.entity-entry-name`, so the
@@ -86,3 +90,22 @@ test("a long entry name wraps instead of pushing the entry out of the sidebar",
assert.ok(name, "expected a .entity-entry-name style rule");
assert.match(name, /(word-break|overflow-wrap):/, "an unbreakable name has to wrap inside the entry");
});
test("every entity entry leads with the icon of what it is", () => {
for (const icon of ["user.svg", "box.svg", "map.svg"]) {
assert.match(source, new RegExp(`class="entity-entry-icon"[^>]*${icon.replace('.', '\\.')}`),
`expected the ${icon} icon on an entry row`);
}
// An item that brings its own picture still has the type icon when it carries none.
assert.match(source, /v-else class="entity-entry-icon"[^>]*box\.svg/);
const icon = ruleFor("entity-entry-icon");
assert.ok(icon, "expected a .entity-entry-icon style rule");
assert.match(declaration(icon, "width"), /^\d+px$/);
});
test("note rows lead with the page icon and media rows with the icon of their type", () => {
assert.match(noteListSource, /class="note-link-icon"[^>]*journal-page\.svg/);
assert.match(noteListSource, /v-for="item in media"[\s\S]*media-link-icon/);
});