diff --git a/AGENTS.md b/AGENTS.md index dbaf0321..3666e10b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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/`. - `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 diff --git a/backend/src/index.js b/backend/src/index.js index d04b1e3e..9f0dac3a 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -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')); diff --git a/backend/src/models/Map.js b/backend/src/models/Map.js index 1055fc1e..c3545d21 100644 --- a/backend/src/models/Map.js +++ b/backend/src/models/Map.js @@ -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); diff --git a/backend/src/models/Media.js b/backend/src/models/Media.js new file mode 100644 index 00000000..dd092d5c --- /dev/null +++ b/backend/src/models/Media.js @@ -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); diff --git a/backend/src/models/Note.js b/backend/src/models/Note.js index 12a5fc42..ae357062 100644 --- a/backend/src/models/Note.js +++ b/backend/src/models/Note.js @@ -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); \ No newline at end of file diff --git a/backend/src/routes/folder.js b/backend/src/routes/folder.js index b71ce337..1d99729b 100644 --- a/backend/src/routes/folder.js +++ b/backend/src/routes/folder.js @@ -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 } } diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js index f6e90eef..e90eb130 100644 --- a/backend/src/routes/foundry-link.js +++ b/backend/src/routes/foundry-link.js @@ -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. diff --git a/backend/src/routes/media.js b/backend/src/routes/media.js new file mode 100644 index 00000000..015cb79d --- /dev/null +++ b/backend/src/routes/media.js @@ -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; diff --git a/backend/src/routes/note.js b/backend/src/routes/note.js index 61aeb265..24515a7f 100644 --- a/backend/src/routes/note.js +++ b/backend/src/routes/note.js @@ -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' }); diff --git a/backend/src/services/map-foundry.js b/backend/src/services/map-foundry.js deleted file mode 100644 index 6449231c..00000000 --- a/backend/src/services/map-foundry.js +++ /dev/null @@ -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 }; diff --git a/dragonroll-foundry/README.md b/dragonroll-foundry/README.md index 4de55b0f..70818344 100644 --- a/dragonroll-foundry/README.md +++ b/dragonroll-foundry/README.md @@ -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 diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js index 457d205a..612d36f1 100644 --- a/dragonroll-foundry/scripts/api.js +++ b/dragonroll-foundry/scripts/api.js @@ -33,13 +33,8 @@ let itemSyncRunning = false; let itemSyncErrorLogged = false; let folderSyncTimeout; let folderSyncRunning = false; -let sceneSyncTimeout; -let sceneSyncRetryTimeout; -let sceneSyncErrorLogged = false; const syncingItemIds = new Set(); -const syncingFolderIds = new Set(); const queuedItemChanges = new Map(); -const queuedSceneChanges = new Map(); function getCollectionContents(collection, collectionName) { if (!collection) { @@ -315,11 +310,6 @@ async function applyDragonrollLink(result) { ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign."); scheduleSnapshotSync(0); setTimeout(initializeCharacterSync, 0); - setTimeout(reconcileDragonrollItems, 2000); - setTimeout(initializeSceneSync, 1000); - // The notes are pulled over on their own change check; get the first one in - // as soon as the world has a token instead of waiting for the next poll. - setTimeout(reconcileDragonrollNotes, 3000); } else { // Without a token this client cannot sync, and only a fresh link gives one. linkProblem = "this client could not save the token it was given"; @@ -579,8 +569,8 @@ function getSyncToken() { } // Autosync is what the module has always done: every Foundry create, update and -// delete pushes to Dragonroll, and both sides reconcile on a timer. When it is -// off, nothing syncs on its own and only a forced actor sync reaches Dragonroll. +// delete pushes to Dragonroll. When it is off, nothing syncs on its own and only a +// forced actor sync reaches Dragonroll. function isAutoSyncEnabled() { return game.settings.get(MODULE_ID, SETTING_AUTO_SYNC) !== false; } @@ -590,19 +580,14 @@ function handleAutoSyncChange(value) { clearTimeout(actorSyncTimeout); clearTimeout(itemSyncTimeout); clearTimeout(folderSyncTimeout); - clearTimeout(sceneSyncTimeout); - clearTimeout(sceneSyncRetryTimeout); return; } if (!game.user?.isGM || !getSyncToken()) return; - // Switching it back on converges both sides again, then the changes queued - // while autosync was off are pushed so this world's state wins over them. + // Switching it back on sends everything this world holds, then the changes + // queued while autosync was off. initializeCharacterSync(); - reconcileDragonrollItems(); queueFoundryItemFolders(400); - reconcileDragonrollNotes(); - initializeSceneSync(); if (queuedActorChanges.size) { clearTimeout(actorSyncTimeout); actorSyncTimeout = setTimeout(flushActorChanges, 400); @@ -611,10 +596,6 @@ function handleAutoSyncChange(value) { clearTimeout(itemSyncTimeout); itemSyncTimeout = setTimeout(flushItemChanges, 400); } - if (queuedSceneChanges.size) { - clearTimeout(sceneSyncTimeout); - sceneSyncTimeout = setTimeout(flushSceneChanges, 400); - } } function dragonrollActorId(actor) { @@ -825,7 +806,7 @@ async function flushActorChanges() { // --- World item sync ------------------------------------------------------- // Items embedded in an actor travel with that actor's snapshot; the items below -// handle the world-level item directory (game.items) in both directions. +// send the world-level item directory (game.items) to the campaign. function itemPropertyLabels(item) { const values = item.system?.properties?.value; @@ -931,34 +912,7 @@ function getWorldItemSnapshots() { return (game.items?.contents || []).map(serializeFoundryWorldItem).filter(Boolean); } -// --- Folder colours ---------------------------------------------------------- -// Colouring a folder is the one thing about the tree the campaign gets to do on its -// own: the world owns what the folders are called and how they nest, and Dragonroll -// owns the colour its user picks for one. So the colour travels back with the folder -// list the item reconcile reads, and lands on the world's folder — marked, like every -// Dragonroll write, so the world does not echo it straight back to the campaign. - -async function withFolderSyncSuppressed(folder, callback) { - if (!folder?.id) return callback(); - syncingFolderIds.add(folder.id); - try { - return await callback(); - } finally { - syncingFolderIds.delete(folder.id); - } -} - -async function applyDragonrollFolderColors(entries) { - for (const entry of entries || []) { - const folder = entry?.foundryFolderId ? game.folders?.get(entry.foundryFolderId) : null; - // Only the world's item directories: a Dragonroll folder the world has no document - // for is the campaign's business alone, and making one there is not ours to do. - if (!folder || folder.documentName !== "Folder" || !isWorldItemFolder(folder)) continue; - const color = entry.color || null; - if (itemFolderColor(folder) === color) continue; - await withFolderSyncSuppressed(folder, () => folder.update({ color })); - } -} +// --- Item identities --------------------------------------------------------- function dragonrollItemIdOf(item) { return item.getFlag?.(MODULE_ID, "itemId") || item.flags?.[MODULE_ID]?.itemId || ""; @@ -1079,436 +1033,14 @@ async function flushItemChanges() { } } -const CATEGORY_TO_FOUNDRY_ITEM_TYPE = { - weapon: "weapon", - armor: "equipment", - shield: "equipment", - consumable: "consumable", - tool: "tool", - "adventuring-gear": "loot", - "magic-item": "loot", - treasure: "loot", - other: "loot", -}; - -const RARITY_TO_FOUNDRY_VALUE = { - common: "common", - uncommon: "uncommon", - rare: "rare", - "very-rare": "veryRare", - legendary: "legendary", - artifact: "artifact", -}; - -function makeFoundryItemData(entry) { - const type = CATEGORY_TO_FOUNDRY_ITEM_TYPE[entry.category] || "loot"; - const data = { - name: String(entry.name || "").trim(), - type, - img: getDragonrollImageUrl(entry.image) || undefined, - system: { - quantity: Number(entry.quantity) || 1, - weight: Number(entry.weight) || 0, - rarity: RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common", - description: { value: entry.description || "" }, - }, - flags: { [MODULE_ID]: { itemId: String(entry._id), syncMutation: true } }, - }; - if (type === "equipment") data.system.armor = { type: entry.category === "shield" ? "shield" : "medium" }; - return data; -} - -function foundryItemUpdateData(entry) { - const updates = { - name: String(entry.name || "").trim(), - "system.quantity": Number(entry.quantity) || 1, - "system.weight": Number(entry.weight) || 0, - "system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common", - "system.description.value": entry.description || "", - }; - // An icon the campaign picked in Dragonroll travels back to Foundry; no icon - // there means leave the world's own choice alone, not erase it. - const image = getDragonrollImageUrl(entry.image); - if (image) updates.img = image; - return updates; -} - -async function applyDragonrollItem(item, entry) { - const updates = foundryItemUpdateData(entry); - const changed = Object.entries(updates).some(([key, value]) => documentValue(item, key) !== value); - await withItemSyncSuppressed(item, async () => { - if (changed) await item.update(updates); - if (dragonrollItemIdOf(item) !== String(entry._id)) { - await item.update({ [`flags.${MODULE_ID}.itemId`]: String(entry._id) }); - } - }); -} - -async function mapDragonrollItem(itemId, foundryItemId) { - const token = getSyncToken(); - return postDragonroll("foundry/sync/map-item", { - worldId: game.world.id, - itemId: String(itemId), - foundryItemId: String(foundryItemId), - }, token); -} - -async function createFoundryWorldItem(entry) { - const data = makeFoundryItemData(entry); - if (!data.name) return; - const item = await Item.create(data); - if (!item) return; - - await withItemSyncSuppressed(item, async () => { - await item.update({ [`flags.${MODULE_ID}.syncMutation`]: false }); - }); - await mapDragonrollItem(entry._id, item.id); -} - -async function reconcileDragonrollItems() { - const token = getSyncToken(); - if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return; - itemSyncRunning = true; - try { - const result = await getDragonroll("foundry/sync/items", token); - // The folder colours are applied first, and whatever system this world runs: a - // colour is the same on every one of them, while writing an item is what needs D&D 5e. - await applyDragonrollFolderColors(result.folders); - if (game.system.id !== "dnd5e") { - throw new Error("Item sync currently requires the D&D 5e Foundry system."); - } - const remoteItems = result.items || []; - const remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry])); - const localByRemoteId = new Map(game.items.contents - .map((item) => [String(dragonrollItemIdOf(item)), item]) - .filter(([itemId]) => itemId)); - const retainedFoundryIds = new Set(); - - for (const entry of remoteItems) { - let item = entry.foundryItemId ? game.items.get(entry.foundryItemId) : null; - if (!item) item = localByRemoteId.get(String(entry._id)); - if (item) { - retainedFoundryIds.add(item.id); - await applyDragonrollItem(item, entry); - if (!entry.foundryItemId) await mapDragonrollItem(entry._id, item.id); - } else if (entry.foundryItemId) { - // Imported gear that only exists inside an actor's inventory: its actor - // snapshot owns it, so cloning it into the world would duplicate it. - continue; - } else { - // A Dragonroll item named like an unmapped Foundry item maps to that - // document instead of adding a second copy of the same gear. - const sameName = game.items.contents.find((candidate) => candidate.name === String(entry.name).trim() - && !dragonrollItemIdOf(candidate)); - if (sameName) { - retainedFoundryIds.add(sameName.id); - await mapDragonrollItem(entry._id, sameName.id); - } else { - await createFoundryWorldItem(entry); - } - } - } - - for (const item of game.items.contents) { - const itemId = dragonrollItemIdOf(item); - if (!itemId || retainedFoundryIds.has(item.id) || remoteById.has(String(itemId))) continue; - await withItemSyncSuppressed(item, () => item.delete()); - } - itemSyncErrorLogged = false; - } catch (error) { - reportItemSyncError(error); - } finally { - itemSyncRunning = false; - } -} - -function getDragonrollImageUrl(image) { - if (!image) return ""; - if (/^(https?:|data:|\/\/)/i.test(image)) return image; - - const endpoint = new URL(game.settings.get(MODULE_ID, SETTING_DRAGONROLL_API_URL)); - const basePath = endpoint.pathname.replace(/\/+$/, ""); - endpoint.pathname = `${basePath.endsWith("/api") ? basePath : `${basePath}/api`}/public/${encodeURIComponent(image)}`; - endpoint.search = ""; - endpoint.hash = ""; - return endpoint.toString(); -} - -function makeFoundryCharacterData(entry) { - const stats = entry.abilityScores || {}; - const items = []; - if (entry.className) items.push({ name: entry.className, type: "class", system: { levels: Number(entry.level) || 1 } }); - if (entry.subclass) items.push({ name: entry.subclass, type: "subclass" }); - if (entry.background) items.push({ name: entry.background, type: "background" }); - for (const name of String(entry.spells || "").split("\n").map((value) => value.trim()).filter(Boolean)) { - items.push({ name, type: "spell" }); - } - for (const item of entry.inventory || []) { - if (!item.name?.trim()) continue; - items.push({ - name: item.name.trim(), - type: "loot", - system: { quantity: Number(item.quantity) || 1, weight: { value: Number(item.weight) || 0 } }, - }); - } - - return { - name: entry.name, - type: entry.type === "character" ? "character" : "npc", - img: getDragonrollImageUrl(entry.image) || undefined, - system: { - // `details.race` and `details.background` are left out on purpose: they reference - // embedded items and are linked once the actor stands with its items made. - details: { - level: Number(entry.level) || 1, - biography: { value: entry.description || "" }, - cr: entry.challengeRating || "", - }, - abilities: Object.fromEntries(["str", "dex", "con", "int", "wis", "cha"].map((key) => [ - key, - { value: Number(stats[key]) || 10 }, - ])), - attributes: { - ac: { value: Number(entry.armorClass) || 10 }, - movement: { walk: Number(entry.speed) || 30 }, - }, - }, - items, - flags: { [MODULE_ID]: { - actorId: String(entry._id), - actorType: entry.type, - traits: entry.traits || "", - proficiencies: entry.proficiencies || "", - syncMutation: true, - } }, - }; -} - -function documentValue(document, path) { - return path.split(".").reduce((value, key) => value?.[key], document); -} - -function characterUpdateData(entry) { - const stats = entry.abilityScores || {}; - const updates = { - name: entry.name, - img: getDragonrollImageUrl(entry.image) || "icons/svg/mystery-man.svg", - "system.details.level": Number(entry.level) || 1, - "system.details.biography.value": entry.description || "", - "system.details.cr": entry.challengeRating || "", - [`flags.${MODULE_ID}.traits`]: entry.traits || "", - [`flags.${MODULE_ID}.proficiencies`]: entry.proficiencies || "", - "system.attributes.ac.value": Number(entry.armorClass) || 10, - "system.attributes.movement.walk": Number(entry.speed) || 30, - }; - for (const key of ["str", "dex", "con", "int", "wis", "cha"]) { - updates[`system.abilities.${key}.value`] = Number(stats[key]) || 10; - } - return updates; -} - -// `system.details.background` and `system.details.race` are LocalDocumentFields in -// D&D 5e: they hold the id of an item embedded in the actor, never its name. A name -// written into one is a reference that resolves to nothing, and adding that item in -// Foundry then fails, so each of these follows the actor's own item for it instead. -const EMBEDDED_DETAILS = [ - // Dragonroll owns the background item it lists, so its reference follows it always and - // a background taken off in the campaign leaves no reference behind. - { field: "background", path: "system.details.background", types: ["background"], clearWhenMissing: true }, - // The species item belongs to the world: point at it when it carries the name, and - // leave the reference to the GM when it does not. - { field: "species", path: "system.details.race", types: ["race", "species"] }, -]; - -function localDocumentId(value) { - // The field resolves to the referenced document when it can and to the stored id - // when the document is gone (its `fallback` option). - if (typeof value === "string") return value; - return value?._id || ""; -} - -function embeddedDetailReferenceData(actor, entry) { - const updates = {}; - for (const detail of EMBEDDED_DETAILS) { - const wanted = String(entry[detail.field] || "").trim(); - const item = wanted - ? actor.items?.contents?.find((candidate) => detail.types.includes(candidate.type) && candidate.name === wanted) - : null; - const reference = item?.id || ""; - if (!reference && !detail.clearWhenMissing) continue; - if (localDocumentId(documentValue(actor, detail.path)) !== reference) updates[detail.path] = reference; - } - return updates; -} - -async function reconcileEmbeddedItems(actor, entry) { - const desired = []; - if (entry.className) desired.push({ type: "class", name: entry.className, system: { levels: Number(entry.level) || 1 } }); - if (entry.subclass) desired.push({ type: "subclass", name: entry.subclass }); - if (entry.background) desired.push({ type: "background", name: entry.background }); - for (const name of String(entry.spells || "").split("\n").map((value) => value.trim()).filter(Boolean)) { - desired.push({ type: "spell", name }); - } - for (const item of entry.inventory || []) { - if (item.name?.trim()) desired.push({ - type: "loot", - name: item.name.trim(), - system: { quantity: Number(item.quantity) || 1, weight: { value: Number(item.weight) || 0 } }, - }); - } - - const retainedIds = new Set(); - for (const wanted of desired) { - const existing = actor.items.contents.find((item) => item.name === wanted.name - && item.type === wanted.type && item.getFlag?.(MODULE_ID, "syncedItem")) - || actor.items.contents.find((item) => item.name === wanted.name - && item.getFlag?.(MODULE_ID, "syncedItem") && !WORLD_OWNED_EMBEDDED_TYPES.has(item.type)); - // A carried row holding the name of one of the world's own trait or species documents - // — a trait a campaign that synced before #89 still has in its inventory — stands in - // the world as that document: no loot is made after its name, and the document itself - // is let be. Writing it out of the campaign is the campaign's to do, keeping it is the world's. - if (!existing && wanted.type === "loot") { - const worldOwned = actor.items.contents.find((item) => item.name === wanted.name - && WORLD_OWNED_EMBEDDED_TYPES.has(item.type)); - if (worldOwned) { - retainedIds.add(worldOwned.id); - continue; - } - } - if (existing) { - retainedIds.add(existing.id); - const update = { _id: existing.id }; - const expected = { name: wanted.name }; - if (wanted.system?.levels !== undefined) expected["system.levels"] = wanted.system.levels; - if (wanted.system?.quantity !== undefined) expected["system.quantity"] = wanted.system.quantity; - if (wanted.system?.weight?.value !== undefined) expected["system.weight.value"] = wanted.system.weight.value; - let changed = false; - for (const [key, value] of Object.entries(expected)) { - if (documentValue(existing, key) !== value) { - update[key] = value; - changed = true; - } - } - if (changed) await actor.updateEmbeddedDocuments("Item", [update]); - } else { - const created = await actor.createEmbeddedDocuments("Item", [{ - ...wanted, - flags: { [MODULE_ID]: { syncedItem: true } }, - }]); - for (const item of created) retainedIds.add(item.id); - } - } - - const staleItemIds = actor.items.contents - .filter((item) => item.getFlag?.(MODULE_ID, "syncedItem") && !retainedIds.has(item.id) - && !WORLD_OWNED_EMBEDDED_TYPES.has(item.type)) - .map((item) => item.id); - if (staleItemIds.length) await actor.deleteEmbeddedDocuments("Item", staleItemIds); -} - -async function applyDragonrollCharacter(actor, entry) { - const updates = characterUpdateData(entry); - const changed = Object.entries(updates).some(([key, value]) => documentValue(actor, key) !== value); - await withActorSyncSuppressed(actor, async () => { - if (changed) await actor.update(updates); - await reconcileEmbeddedItems(actor, entry); - // The item references are written after the reconcile that makes the items they point at. - const references = embeddedDetailReferenceData(actor, entry); - if (Object.keys(references).length) await actor.update(references); - if (dragonrollActorId(actor) !== String(entry._id) - || actor.getFlag?.(MODULE_ID, "actorType") !== entry.type) { - await actor.update({ - [`flags.${MODULE_ID}.actorId`]: String(entry._id), - [`flags.${MODULE_ID}.actorType`]: entry.type, - }); - } - }); -} - -async function mapDragonrollActor(actorId, foundryActorId) { - const token = getSyncToken(); - return postDragonroll("foundry/sync/map", { - worldId: game.world.id, - actorId: String(actorId), - foundryActorId: String(foundryActorId), - }, token); -} - -async function createFoundryCharacter(entry) { - if (game.system.id !== "dnd5e") { - throw new Error("Character sync currently requires the D&D 5e Foundry system."); - } - const actor = await Actor.create(makeFoundryCharacterData(entry), { renderSheet: false }); - if (!actor) return; - - await withActorSyncSuppressed(actor, async () => { - await actor.update({ - // The actor was made with its items, so its background and species references - // can point at them right away. - ...embeddedDetailReferenceData(actor, entry), - [`flags.${MODULE_ID}.syncMutation`]: false, - }); - }); - await mapDragonrollActor(entry._id, actor.id); -} - -async function reconcileDragonrollCharacters() { - const token = getSyncToken(); - if (!token || !game.user?.isGM || !game.world || characterSyncRunning || !isAutoSyncEnabled()) return; - characterSyncRunning = true; - try { - if (game.system.id !== "dnd5e") { - throw new Error("Character sync currently requires the D&D 5e Foundry system."); - } - const result = await getDragonroll("foundry/sync/characters", token); - const remoteActors = result.actors || []; - const remoteById = new Map(remoteActors.map((actor) => [String(actor._id), actor])); - const localByRemoteId = new Map(game.actors.contents - .map((actor) => [String(dragonrollActorId(actor)), actor]) - .filter(([actorId]) => actorId)); - const retainedFoundryIds = new Set(); - - for (const entry of remoteActors) { - let actor = entry.foundryActorId ? game.actors.get(entry.foundryActorId) : null; - if (!actor) actor = localByRemoteId.get(String(entry._id)); - if (actor) { - retainedFoundryIds.add(actor.id); - await applyDragonrollCharacter(actor, entry); - if (!entry.foundryActorId) await mapDragonrollActor(entry._id, actor.id); - } else { - await createFoundryCharacter(entry); - } - } - - for (const actor of game.actors.contents) { - const actorId = dragonrollActorId(actor); - if (!actorId || retainedFoundryIds.has(actor.id) || remoteById.has(String(actorId))) continue; - await withActorSyncSuppressed(actor, () => actor.delete()); - } - actorSyncErrorLogged = false; - } catch (error) { - reportActorSyncError(error); - } finally { - characterSyncRunning = false; - } -} - -// Both sides converge on a timer that only runs while the world is open, so a -// round that could not reach Dragonroll is asked for again in a while instead of -// leaving the campaign with whatever it happened to receive. -function scheduleDragonrollCharacterSync(delay = 15000) { - clearTimeout(characterSyncRetryTimeout); - characterSyncRetryTimeout = setTimeout(reconcileDragonrollCharacters, delay); -} - async function initializeCharacterSync() { if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return; try { await pushFoundryActors(game.actors.contents, true); - await reconcileDragonrollCharacters(); } catch (error) { reportActorSyncError(error); - scheduleDragonrollCharacterSync(15000); + clearTimeout(characterSyncRetryTimeout); + characterSyncRetryTimeout = setTimeout(initializeCharacterSync, 15000); } } @@ -1517,702 +1049,6 @@ function queueFoundryActorChange(kind, actor) { queueActorChange(kind, actor); } -// --- Scene sync --------------------------------------------------------------- -// A scene of this world is one of the campaign's maps (Syndria98/dragonroll#99): its -// background picture and the grid laid over it travel to Dragonroll, which keeps a map per -// scene. That is all of a scene that crosses over — pinning notes on a map, standing tokens -// on it and saying how far one of its cells goes are the campaign's own business, so none -// of it comes back to the world. - -// A scene travels as plain document data with its picture read from this world: Dragonroll -// draws it outside Foundry, so the path becomes an absolute URL the way a portrait does. -// Since V13 the picture sits under `background.src`, and under plain `img` before that. -function serializeFoundryScene(scene) { - const data = toPlainData(scene); - if (!data) return null; - - const absolute = (path) => new URL(path, window.location.origin).toString(); - if (data.background?.src && !/^(https?:|data:|\/\/)/i.test(data.background.src)) { - data.background = { ...data.background, src: absolute(data.background.src) }; - } else if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) { - data.img = absolute(data.img); - } - return data; -} - -// The scenes the campaign mirrors as its maps. Every scene goes, including one with no -// picture: Dragonroll decides what of a scene is a map and, since such a scene's id is -// still listed, no map of the campaign is pruned because of it. -async function pushFoundryScenes(scenes, fullSync = false) { - const token = getSyncToken(); - // A full push travels even with no scenes left: it is the one that tells the campaign - // which of the maps it mirrors from this world the world has let go of. - if (!token || !game.user?.isGM || !game.world || (!scenes.length && !fullSync)) return; - - await postDragonroll("foundry/sync/scenes", { - worldId: game.world.id, - scenes: scenes.map(serializeFoundryScene).filter(Boolean), - fullSync, - }, token); - sceneSyncErrorLogged = false; -} - -async function deleteDragonrollScene(foundrySceneId) { - const token = getSyncToken(); - if (!token || !game.world || !foundrySceneId) return; - await postDragonroll("foundry/sync/scene-delete", { - worldId: game.world.id, - foundrySceneId, - }, token); -} - -function reportSceneSyncError(error) { - if (sceneSyncErrorLogged) return; - sceneSyncErrorLogged = true; - console.warn(`${MODULE_ID} | Map sync failed and will retry.`, error); -} - -function queueFoundrySceneChange(kind, scene) { - if (!scene || !game.user?.isGM || !getSyncToken()) return; - - queuedSceneChanges.set(scene.id, { kind, scene }); - clearTimeout(sceneSyncTimeout); - sceneSyncTimeout = setTimeout(flushSceneChanges, 400); -} - -async function flushSceneChanges() { - // Autosync off: the scene edits wait here, like the actor and item changes do. - if (!isAutoSyncEnabled()) return; - const changes = [...queuedSceneChanges.values()]; - queuedSceneChanges.clear(); - const deleted = changes.filter((change) => change.kind === "delete"); - const changed = changes.filter((change) => change.kind !== "delete"); - - try { - for (const change of deleted) await deleteDragonrollScene(change.scene.id); - if (changed.length) await pushFoundryScenes(changed.map((change) => change.scene)); - } catch (error) { - reportSceneSyncError(error); - for (const change of changes) queuedSceneChanges.set(change.scene.id, change); - clearTimeout(sceneSyncTimeout); - sceneSyncTimeout = setTimeout(flushSceneChanges, 5000); - } -} - -// The whole scene list travels when the world links and when it loads: the campaign's map -// list mirrors this world's scenes, and only a push holding every scene can say which of -// those maps the world has let go of. -async function initializeSceneSync() { - if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return; - try { - await pushFoundryScenes(game.scenes?.contents || [], true); - } catch (error) { - reportSceneSyncError(error); - clearTimeout(sceneSyncRetryTimeout); - sceneSyncRetryTimeout = setTimeout(initializeSceneSync, 15000); - } -} - -// --- Note pages ------------------------------------------------------------ -// The campaign's notes read like the campaign's journal in the world: each folder -// stands as a JournalEntry named after its path, and every note inside it is one -// of that journal's pages. Notes in the root of the campaign share the journal -// named "Dragonroll", and a note in "Sessions / Arc 1" belongs to the journal -// named after that path. Notes are written in Dragonroll, so this copy runs one way — the -// reconcile writes each note into its page and drops the page of a note the -// campaign deleted. Nothing of the journal is read back, and the GM's own pages -// are left alone: only the ones this module made carry the -// `dragonroll-foundry.noteId` flag. Moving a note to another folder moves its page -// to that folder's journal; the journal of a folder whose notes all left goes with -// them when the GM has no pages of their own in it. -// -// The poll asks Dragonroll for a cheap revision first: the notes are only pulled -// over — and the journals only rewritten — when that revision or the pages this -// module wrote have changed since the last reconcile, so an untouched campaign -// costs one hash comparison instead of a page rewrite every few seconds. - -const NOTES_JOURNAL_NAME = "Dragonroll"; -let noteSyncRunning = false; -let noteSyncErrorLogged = false; -// What the last reconcile was based on: the campaign's notes revision, and a summary -// of the pages this module put in the world. Both unchanged means there is nothing to -// do, which is how an idle campaign skips the whole pull-and-render. -let lastNoteRevision = null; -let lastNoteJournalSignature = null; - -function dragonrollNoteId(page) { - return page.getFlag?.(MODULE_ID, "noteId") || page.flags?.[MODULE_ID]?.noteId || ""; -} - -// --- Links and embeds in a note ------------------------------------------- -// Dragonroll writes `[[Name]]` for a link and `![[Name]]` for an embed. Foundry has its own -// enrichers for both: `@UUID[…]` becomes a content link that opens the document, and `@Embed[…]` -// draws that document's sheet in the page. The note only carries names, so the target is looked up -// in the world the same way the campaign lists it: notes first, then characters, items and maps. -function normalizeNoteLabel(value) { - return String(value ?? "") - .normalize("NFD") - .replace(/[\u0300-\u036f]/g, "") - .toLowerCase() - .trim(); -} - -function noteDocumentUuid(document, documentName) { - return document?.uuid || `${document?.documentName || documentName}.${document?.id}`; -} - -// A journal page's uuid is the pair of its journal and its own id; tests and older -// Foundry versions do not always carry the getter, so it is rebuilt when missing. -function notePageUuid(journal, page) { - return page?.uuid || `JournalEntry.${journal.id}.JournalEntryPage.${page.id}`; -} - -function noteJournalPages() { - const pages = []; - for (const journal of notesJournals()) { - for (const page of journal.pages?.contents || []) pages.push({ journal, page }); - } - return pages; -} - -function findNoteJournalPage(needle) { - const pages = noteJournalPages(); - // Prefer the page the module itself made for a note: a GM page with the same - // name is not the note the campaign is pointing at. - return pages.find(({ page }) => dragonrollNoteId(page) && normalizeNoteLabel(page.name) === needle) - || pages.find(({ page }) => normalizeNoteLabel(page.name) === needle) - || null; -} - -// The document a written label points at. An embed only makes sense for a character or -// an item, which are the documents Foundry knows how to show inline. -function findNoteTarget(label, { embed = false } = {}) { - const needle = normalizeNoteLabel(label); - if (!needle) return null; - - if (!embed) { - const note = findNoteJournalPage(needle); - if (note) return { uuid: notePageUuid(note.journal, note.page), type: "note" }; - } - - const actor = (game.actors?.contents || []).find((candidate) => normalizeNoteLabel(candidate.name) === needle); - if (actor) return { uuid: noteDocumentUuid(actor, "Actor"), type: "actor" }; - - const item = (game.items?.contents || []).find((candidate) => normalizeNoteLabel(candidate.name) === needle); - if (item) return { uuid: noteDocumentUuid(item, "Item"), type: "item" }; - - if (embed) return null; - - const scene = (game.scenes?.contents || []).find((candidate) => normalizeNoteLabel(candidate.name) === needle); - if (scene) return { uuid: noteDocumentUuid(scene, "Scene"), type: "map" }; - - return null; -} - -function noteWikiLinkHtml(label) { - const text = String(label ?? "").trim(); - const target = findNoteTarget(text); - if (!target) { - return `${escapeNoteHtml(text)}`; - } - return `@UUID[${target.uuid}]{${escapeNoteHtml(text)}}`; -} - -function noteEmbedHtml(label) { - const text = String(label ?? "").trim(); - const target = findNoteTarget(text, { embed: true }); - if (!target) { - return `${escapeNoteHtml(text)}`; - } - return `@Embed[${target.uuid}]{${escapeNoteHtml(text)}}`; -} - -// A note is markdown, a journal page is HTML. Foundry keeps no markdown renderer -// the module can call — the `TextEditor._getMarkdown` this once probed for was -// never real, so every note fell through to escaped paragraphs and a `#` heading -// stayed a `#` heading — so the note's markdown is drawn here and the journal -// styles the page like any other. -function notePageHtml(content) { - const markdown = String(content ?? "").replace(/\r\n?/g, "\n"); - if (!markdown.trim()) return ""; - return markdownBlocks(markdown); -} - -// Dragonroll's dice widget is a button in the journal too: pressing it rolls the -// expression in Foundry and posts the result to chat. `adv`/`dis` are Dragonroll's -// names for rolling twice and keeping the better/worse die, which Foundry writes as -// `kh1`/`kl1`; everything else in the expression is already Foundry's syntax. -function dragonrollRollFormula(expression) { - return String(expression ?? "") - .trim() - .replace(/(\d*)d(\d+)\s*adv\b/gi, (match, count, sides) => `2d${sides}kh1`) - .replace(/(\d*)d(\d+)\s*dis\b/gi, (match, count, sides) => `2d${sides}kl1`); -} - -function noteRollButtonHtml(expression, block = false) { - const label = String(expression ?? "").trim(); - const formula = dragonrollRollFormula(label); - const classes = block ? "dragonroll-note-roll dragonroll-note-roll-block" : "dragonroll-note-roll"; - return ``; -} - -// Every dice button the module draws listens through one delegated handler: the -// journal re-renders its pages, so binding each button would go stale. -function onDragonrollNoteRollClick(event) { - const button = event.target?.closest?.("[data-dragonroll-roll]"); - if (!button) return; - event.preventDefault(); - return rollDragonrollNote(button); -} - -async function rollDragonrollNote(button) { - const formula = button?.dataset?.dragonrollRoll; - if (!formula) return; - try { - const roll = new Roll(formula); - await roll.evaluate(); - await roll.toMessage({ - speaker: ChatMessage.getSpeaker(), - flavor: `Dragonroll: ${escapeNoteHtml(formula)}`, - }); - } catch (error) { - console.warn(`${MODULE_ID} | Could not roll "${formula}".`, error); - ui.notifications?.warn?.(`Dragonroll: could not roll ${formula}.`); - } -} - -function bindDragonrollNoteRolls() { - if (typeof document === "undefined") return; - document.addEventListener("click", onDragonrollNoteRollClick); -} - -// The block-level elements a note is written with, line by line. A blank line -// ends a block, anything no block rule claims is a paragraph, and the single -// newlines inside a paragraph become line breaks. -function markdownBlocks(markdown) { - const lines = markdown.split("\n"); - const blocks = []; - let index = 0; - - while (index < lines.length) { - const line = lines[index]; - if (!line.trim()) { - index += 1; - continue; - } - - // A dice widget on its own line: `@roll`, the expression, then `@end`. A - // block without its closing marker is left to the paragraph rules below. - if (/^@roll\s*$/.test(line)) { - let closing = index + 1; - while (closing < lines.length && !/^@end\s*$/.test(lines[closing])) closing += 1; - if (closing < lines.length) { - blocks.push(noteRollButtonHtml(lines.slice(index + 1, closing).join("\n"), true)); - index = closing + 1; - continue; - } - } - - // A fenced code block: everything up to the line that closes the fence is - // kept as written, escaped rather than read as markdown. - const fence = line.match(/^\s*(`{3,}|~{3,})(.*)$/); - if (fence) { - const marker = fence[1][0]; - const isClosingFence = (candidate) => { - const trimmed = candidate.trim(); - return trimmed.length >= 3 && [...trimmed].every((character) => character === marker); - }; - index += 1; - const code = []; - while (index < lines.length && !isClosingFence(lines[index])) { - code.push(lines[index]); - index += 1; - } - index += 1; - const language = fence[2].trim().split(/\s+/)[0].replace(/[^\w+#-]/g, ""); - blocks.push(`
${escapeNoteHtml(code.join("\n"))}
`); - continue; - } - - if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { - blocks.push("
"); - index += 1; - continue; - } - - const heading = line.match(/^(#{1,6})\s+(.*?)\s*#*\s*$/); - if (heading) { - blocks.push(`${noteInlineHtml(heading[2])}`); - index += 1; - continue; - } - - // A line underlined with `=` or `-` is a heading of its own. - const underline = lines[index + 1]?.match(/^\s*(=+|-+)\s*$/); - if (underline) { - const level = underline[1][0] === "=" ? 1 : 2; - blocks.push(`${noteInlineHtml(line.trim())}`); - index += 2; - continue; - } - - if (/^\s*>/.test(line)) { - const quote = []; - while (index < lines.length && /^\s*>/.test(lines[index])) { - quote.push(lines[index].replace(/^\s*>\s?/, "")); - index += 1; - } - blocks.push(`
${markdownBlocks(quote.join("\n"))}
`); - continue; - } - - const listItem = line.match(/^\s*([-*+]|\d+[.)])\s+/); - if (listItem) { - const ordered = /^\d/.test(listItem[1]); - const items = []; - while (index < lines.length) { - const item = lines[index].match(/^\s*(?:[-*+]|\d+[.)])\s+(.*)$/); - if (!item) break; - const continuation = [item[1]]; - index += 1; - while (index < lines.length && lines[index].trim() - && !/^\s*(?:[-*+]|\d+[.)])\s+/.test(lines[index])) { - continuation.push(lines[index].trim()); - index += 1; - } - items.push(`
  • ${noteInlineHtml(continuation.join("\n")).replace(/\n/g, "
    ")}
  • `); - } - const tag = ordered ? "ol" : "ul"; - blocks.push(`<${tag}>\n${items.join("\n")}\n`); - continue; - } - - const paragraph = [line.trim()]; - index += 1; - while (index < lines.length && lines[index].trim() - && !/^\s*(`{3,}|~{3,})/.test(lines[index]) - && !/^#{1,6}\s+/.test(lines[index]) - && !/^\s*>/.test(lines[index]) - && !/^\s*(?:[-*+]|\d+[.)])\s+/.test(lines[index]) - && !/^\s*([-*_])(\s*\1){2,}\s*$/.test(lines[index]) - && !/^\s*[=-]+\s*$/.test(lines[index])) { - paragraph.push(lines[index].trim()); - index += 1; - } - blocks.push(`

    ${noteInlineHtml(paragraph.join("\n")).replace(/\n/g, "
    ")}

    `); - } - - return blocks.join("\n"); -} - -// The inline marks inside a block: code spans and dice widgets are lifted out -// first so nothing in them is read as a mark, and the rest — images, links, -// strong, emphasis and strikethrough — are plain, non-nesting replacements over -// escaped text. -function noteInlineHtml(text) { - const atoms = []; - const hold = (html) => { - atoms.push(html); - return `\u0000${atoms.length - 1}\u0000`; - }; - let html = String(text) - .replace(/`([^`]+)`/g, (match, code) => hold(`${escapeNoteHtml(code)}`)) - .replace(/@roll\s*\[([^\]]*)\]/g, (match, expression) => hold(noteRollButtonHtml(expression))) - // The bang has to be read first: `![[Name]]` would otherwise be caught by the - // link rule and drawn as a plain link. - .replace(/!\[\[([^\n]*?)\]\]/g, (match, label) => hold(noteEmbedHtml(label))) - .replace(/\[\[([^\n]*?)\]\]/g, (match, label) => hold(noteWikiLinkHtml(label))); - html = escapeNoteHtml(html); - html = html.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (match, alt, source) => - `${alt}`); - html = html.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (match, label, href) => - `${label}`); - html = html.replace(/\*\*([^*]+)\*\*/g, "$1"); - html = html.replace(/(^|[\s(])__([^_]+)__(?=[\s).,!?:;<]|$)/g, "$1$2"); - html = html.replace(/(^|[^*])\*([^*]+)\*/g, "$1$2"); - html = html.replace(/(^|[\s(])_([^_]+)_(?=[\s).,!?:;<]|$)/g, "$1$2"); - html = html.replace(/~~([^~]+)~~/g, "$1"); - return html.replace(/\u0000(\d+)\u0000/g, (match, position) => atoms[Number(position)]); -} - -function escapeNoteHtml(value) { - return String(value) - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """); -} - -function notePageTitle(entry) { - return String(entry.title || "").trim() || "Untitled note"; -} - -// Which folder's journal a note belongs to: the note's folder id, or the empty -// string for the root notes the "Dragonroll" journal holds. -function noteFolderKey(entry) { - return entry?.folder ? String(entry.folder) : ""; -} - -// The journal a note belongs to is named after the folder path Dragonroll sends; -// root notes keep the journal the world calls "Dragonroll". -function noteJournalName(entry) { - const path = String(entry?.folderPath ?? "").trim(); - return path || NOTES_JOURNAL_NAME; -} - -function journalFolderKey(journal) { - const folder = journal.getFlag?.(MODULE_ID, "notesFolder"); - return folder === undefined || folder === null ? "" : String(folder); -} - -function isNotesJournal(journal) { - return Boolean(journal.getFlag?.(MODULE_ID, "notesJournal") - || journal.getFlag?.(MODULE_ID, "notesFolder")); -} - -// Every journal this module writes the campaign's notes into: the ones it flagged -// for a folder or for the root notes, plus any journal holding a page it made (a -// flag can be lost to a hand edit). The world's journals live in `game.journal` -// (singular) — there is no `game.journals`. -function notesJournals() { - return (game.journal?.contents || []).filter((journal) => - isNotesJournal(journal) - || journal.name === NOTES_JOURNAL_NAME - || (journal.pages?.contents || []).some((page) => dragonrollNoteId(page))); -} - -// What the module's journals and pages look like right now: the journals' names -// and each module page's id, title and text. A change here means a GM edited or -// removed something, so the reconcile has to run again even though the campaign's -// notes have not moved. -function notesJournalSignature() { - return notesJournals().map((journal) => { - const pages = (journal.pages?.contents || []) - .filter((page) => dragonrollNoteId(page)) - .map((page) => `${page.id}\u0000${page.name ?? ""}\u0000${page.text?.content ?? ""}`) - .sort() - .join("\u0001"); - return `${journal.id}\u0000${journal.name ?? ""}\u0000${pages}`; - }).sort().join("\u0002"); -} - -// The page each module page id stands as, across every journal, so a note that -// moved folders can be found in the journal it is leaving before it is written -// into the one it now belongs to. -function notePageLocations() { - const locations = new Map(); - for (const journal of notesJournals()) { - for (const page of journal.pages?.contents || []) { - locations.set(String(page.id), { journal, page }); - } - } - return locations; -} - -// Foundry lets several journals share a name, so a world can end up holding more -// than one journal for the same folder — a GM-made one beside the module's own, or -// two the module made before this check. The reconcile writes into one of them; -// every other one it made for that folder is a duplicate and goes, so the notes -// never split across journals. -async function removeDuplicateNotesJournals(keep, folderKey) { - for (const journal of [...(game.journal?.contents || [])]) { - if (journal === keep) continue; - if (folderKey) { - if (journalFolderKey(journal) === folderKey && isNotesJournal(journal)) await journal.delete(); - } else if (!journalFolderKey(journal) - && (journal.getFlag?.(MODULE_ID, "notesJournal") || journal.name === NOTES_JOURNAL_NAME)) { - await journal.delete(); - } - } -} - -// The journal a note is written into, made on first use. A journal the GM already -// made under the folder's name is adopted (and flagged), and a folder journal is -// renamed with its folder so the world keeps reading the same path. -async function ensureNotesJournal(entry) { - const folderKey = noteFolderKey(entry); - const name = noteJournalName(entry); - const journals = notesJournals(); - const existing = folderKey - ? journals.find((journal) => journalFolderKey(journal) === folderKey) - || journals.find((journal) => !journalFolderKey(journal) - && !journal.getFlag?.(MODULE_ID, "notesJournal") - && journal.name === name) - : journals.find((journal) => journal.getFlag?.(MODULE_ID, "notesJournal")) - || journals.find((journal) => !journalFolderKey(journal) && journal.name === NOTES_JOURNAL_NAME); - - if (existing) { - const updates = {}; - if (String(existing.name ?? "") !== name) updates.name = name; - if (folderKey) { - if (journalFolderKey(existing) !== folderKey) { - updates[`flags.${MODULE_ID}.notesFolder`] = folderKey; - } - } else if (!existing.getFlag?.(MODULE_ID, "notesJournal")) { - updates[`flags.${MODULE_ID}.notesJournal`] = true; - } - if (Object.keys(updates).length) await existing.update(updates); - await removeDuplicateNotesJournals(existing, folderKey); - return existing; - } - - const created = await JournalEntry.create({ - name, - flags: { [MODULE_ID]: folderKey ? { notesFolder: folderKey } : { notesJournal: true } }, - }, { renderSheet: false }); - return Array.isArray(created) ? created[0] : created; -} - -// The page a note stands as: rewrite what the campaign changed, and claim a page -// the campaign mapped by id but whose flag was lost. -async function applyDragonrollNotePage(page, entry) { - const title = notePageTitle(entry); - const html = notePageHtml(entry.content); - const updates = {}; - if (String(page.name ?? "") !== title) updates.name = title; - if (String(page.text?.content ?? "") !== html) updates["text.content"] = html; - if (!dragonrollNoteId(page)) updates[`flags.${MODULE_ID}.noteId`] = String(entry._id); - if (Object.keys(updates).length) await page.update(updates); -} - -async function createDragonrollNotePage(journal, entry) { - const pages = await journal.createEmbeddedDocuments("JournalEntryPage", [{ - // A page's display title is its `name`; `title` only holds the table-of-contents - // flags (`show`/`level`). Missing `name` fails the document's validation. - name: notePageTitle(entry), - text: { content: notePageHtml(entry.content) }, - flags: { [MODULE_ID]: { noteId: String(entry._id) } }, - }], { renderSheet: false }); - return Array.isArray(pages) ? pages[0] : pages; -} - -async function mapDragonrollNote(noteId, foundryPageId) { - const token = getSyncToken(); - return postDragonroll("foundry/sync/map-note", { - worldId: game.world.id, - noteId: String(noteId), - foundryPageId: String(foundryPageId), - }, token); -} - -function reportNoteSyncError(error) { - if (noteSyncErrorLogged) return; - noteSyncErrorLogged = true; - console.warn(`${MODULE_ID} | Note journal sync failed and will retry.`, error); -} - -async function reconcileDragonrollNotes() { - const token = getSyncToken(); - if (!token || !game.user?.isGM || !game.world || noteSyncRunning || !isAutoSyncEnabled()) return; - noteSyncRunning = true; - try { - const { revision } = await getDragonroll("foundry/sync/notes/revision", token); - const remoteRevision = String(revision ?? ""); - // Both sides are unchanged since the last reconcile: the campaign's notes hash - // the same and the journal still holds what was written to it. Stop before - // pulling every note over and rendering it again. - if (remoteRevision === lastNoteRevision && notesJournalSignature() === lastNoteJournalSignature) return; - - const result = await getDragonroll("foundry/sync/notes", token); - const remoteNotes = result.notes || []; - // A campaign without notes gets no journal of its own — but ones it once had - // stay, so the pages of notes it deleted can go with them. - if (!remoteNotes.length && !notesJournals().length) { - lastNoteRevision = remoteRevision; - lastNoteJournalSignature = ""; - return; - } - - const pageLocations = notePageLocations(); - const journalsByFolder = new Map(); - const retainedPageIds = new Set(); - // Every page that now holds a note, so the notes can be drawn a second time once - // they all exist: a note that links to another note needs that note's page uuid, - // and the page it points at may have been created after it in this loop. - const renderedPages = []; - - for (const entry of remoteNotes) { - const folderKey = noteFolderKey(entry); - let journal = journalsByFolder.get(folderKey); - if (!journal) { - journal = await ensureNotesJournal(entry); - if (!journal) continue; - journalsByFolder.set(folderKey, journal); - } - - // The note's page can be in the journal it now belongs to, or in the one of - // the folder it left: a note moved in Dragonroll takes its page along. - let location = entry.foundryPageId ? pageLocations.get(String(entry.foundryPageId)) : null; - if (!location) { - const page = (journal.pages?.contents || []).find((candidate) => - String(dragonrollNoteId(candidate)) === String(entry._id)); - if (page) location = { journal, page }; - } - - let page = location?.page ?? null; - if (page && location.journal !== journal) { - await page.delete(); - pageLocations.delete(String(page.id)); - page = null; - } - - if (page) { - retainedPageIds.add(page.id); - await applyDragonrollNotePage(page, entry); - renderedPages.push({ journal, page, entry }); - if (String(entry.foundryPageId ?? "") !== String(page.id)) { - await mapDragonrollNote(entry._id, page.id); - } - } else { - const created = await createDragonrollNotePage(journal, entry); - if (created) { - retainedPageIds.add(created.id); - pageLocations.set(String(created.id), { journal, page: created }); - renderedPages.push({ journal, page: created, entry }); - await mapDragonrollNote(entry._id, created.id); - } - } - } - - // Now that every page of this pull exists, draw the notes again: only the pages - // whose wiki links just found their target are written a second time. - for (const { page, entry } of renderedPages) { - await applyDragonrollNotePage(page, entry); - } - - // Pages whose note the campaign deleted go with it, and so does a page left in - // a journal the note no longer belongs to. Only pages this module made are its - // business: an unflagged page is the GM's own. - for (const journal of notesJournals()) { - for (const page of [...(journal.pages?.contents || [])]) { - const noteId = dragonrollNoteId(page); - if (!noteId || retainedPageIds.has(page.id)) continue; - await page.delete(); - } - } - - // A folder journal whose notes have all moved or gone goes with them, unless - // the GM keeps pages of their own in it. - for (const journal of notesJournals()) { - const folderKey = journalFolderKey(journal); - if (!folderKey || (journal.pages?.contents || []).length) continue; - if (remoteNotes.some((entry) => noteFolderKey(entry) === folderKey)) continue; - await journal.delete(); - } - - lastNoteRevision = remoteRevision; - lastNoteJournalSignature = notesJournalSignature(); - noteSyncErrorLogged = false; - } catch (error) { - reportNoteSyncError(error); - } finally { - noteSyncRunning = false; - } -} - async function publishSnapshot() { if (!game.user?.isGM || !game.world) return; if (syncInProgress) { @@ -2289,7 +1125,6 @@ async function publishHeartbeat() { } Hooks.once("ready", () => { - bindDragonrollNoteRolls(); advanceDragonrollLink().then(refreshPairingStatus); // While this world has no campaign, its sign-up link is what the GM has to // work with: keep showing it and keep asking whether it has been answered. @@ -2301,21 +1136,6 @@ Hooks.once("ready", () => { scheduleSnapshotSync(0); setInterval(publishHeartbeat, 60000); setTimeout(initializeCharacterSync, 1000); - setInterval(reconcileDragonrollCharacters, 5000); - // Items reconcile after the character snapshot has landed so Dragonroll has - // already seen the world directory when it starts sending its own items back. - setTimeout(reconcileDragonrollItems, 2000); - setInterval(reconcileDragonrollItems, 5000); - // The campaign's notes arrive as pages of the world's Dragonroll journal. The - // recurring check only asks for a cheap revision, so a note written in the app — - // or a journal page a GM changed — is still picked up shortly, but nothing is - // pulled over or rewritten while both sides stay as the last reconcile left them. - setTimeout(reconcileDragonrollNotes, 3000); - setInterval(reconcileDragonrollNotes, 15000); - // The campaign's maps mirror this world's scenes: the whole list goes once the world is - // loaded, and that push alone tells the campaign which of its synced maps this world has - // let go of. - setTimeout(initializeSceneSync, 3000); for (const event of [ "createActor", "updateActor", "deleteActor", @@ -2332,9 +1152,7 @@ Hooks.once("ready", () => { } // An item folder the GM made, renamed or nested changes the tree the campaign // mirrors; nothing about the items themselves changed, so only the tree goes. - // A colour Dragonroll has just written into the folder is not the GM changing it. if (document.documentName === "Folder") { - if (syncingFolderIds.has(document.id)) return; if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders(); return; } @@ -2349,13 +1167,6 @@ Hooks.once("ready", () => { queueFoundryItemChange(isDelete ? "delete" : "upsert", document); }); } - - // A scene the GM makes, renames or throws away is one of the campaign's maps being drawn - // or let go of (Syndria98/dragonroll#99). Only its picture and grid cross over, so this - // goes one way and needs no snapshot of the world behind it. - for (const event of ["createScene", "updateScene", "deleteScene"]) { - Hooks.on(event, (document) => queueFoundrySceneChange(event.startsWith("delete") ? "delete" : "upsert", document)); - } }); // A GM sends selected actors to Dragonroll from the actor directory's context diff --git a/dragonroll-foundry/styles/dragonroll.css b/dragonroll-foundry/styles/dragonroll.css index 44712d87..4078bf67 100644 --- a/dragonroll-foundry/styles/dragonroll.css +++ b/dragonroll-foundry/styles/dragonroll.css @@ -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; diff --git a/frontend/app/components/partials/ContentSidebar.vue b/frontend/app/components/partials/ContentSidebar.vue index c056b69b..24b2cd6b 100644 --- a/frontend/app/components/partials/ContentSidebar.vue +++ b/frontend/app/components/partials/ContentSidebar.vue @@ -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(() => { + + @@ -684,9 +732,9 @@ onBeforeUnmount(() => { @@ -706,7 +754,10 @@ onBeforeUnmount(() => { @toggle="toggleFolder(row.folder._id)" />
    - {{ row.item.name }} + + + {{ row.item.name }} +
    @@ -731,6 +782,7 @@ onBeforeUnmount(() => { + {{ row.item.name }} @@ -752,9 +804,12 @@ onBeforeUnmount(() => { @toggle="toggleFolder(row.folder._id)" />
    - - {{ row.item.name }} - {{ t('campaigns.map.anchored') }} + + + + {{ row.item.name }} + {{ t('campaigns.map.anchored') }} + {{ t('campaigns.map.no-image') }} @@ -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; } diff --git a/frontend/app/components/partials/NestedNoteList.vue b/frontend/app/components/partials/NestedNoteList.vue index 4e4e1d63..06633ed1 100644 --- a/frontend/app/components/partials/NestedNoteList.vue +++ b/frontend/app/components/partials/NestedNoteList.vue @@ -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:"). +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) { + + +
    - +
    @@ -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; } diff --git a/frontend/app/components/windows/CreateCampaignEntryWindow.vue b/frontend/app/components/windows/CreateCampaignEntryWindow.vue index ba5a3e0f..48755a4f 100644 --- a/frontend/app/components/windows/CreateCampaignEntryWindow.vue +++ b/frontend/app/components/windows/CreateCampaignEntryWindow.vue @@ -1,6 +1,6 @@ + + + + diff --git a/frontend/app/components/windows/NewFolderWindow.vue b/frontend/app/components/windows/NewFolderWindow.vue index 3a23d063..79edb347 100644 --- a/frontend/app/components/windows/NewFolderWindow.vue +++ b/frontend/app/components/windows/NewFolderWindow.vue @@ -1,6 +1,6 @@