From 1ec29121e123edf265999b1f04ef134e897c1e3a Mon Sep 17 00:00:00 2001 From: Aran Roig Date: Mon, 19 Oct 2026 19:04:28 +0200 Subject: [PATCH] Deploy deepseek 2 --- AGENTS.md | 2 +- backend/src/models/Actor.js | 8 + backend/src/models/Note.js | 7 +- backend/src/routes/actor.js | 3 +- backend/src/routes/foundry-link.js | 86 ++- backend/src/services/actor-foundry.js | 47 +- dragonroll-foundry/README.md | 47 +- dragonroll-foundry/module.json | 7 +- dragonroll-foundry/scripts/api.js | 604 ++++++++++++++++-- dragonroll-foundry/styles/dragonroll.css | 27 + frontend/Dockerfile | 3 + .../viewer/content/EmbeddedEntry.vue | 302 +++++++++ .../components/viewer/content/LinkPreview.vue | 227 +++++++ .../app/components/viewer/content/Note.vue | 490 +++++++++++++- .../viewer/content/SuggestionMenu.vue | 73 +++ .../viewer/statusbar/FetchStatus.vue | 15 +- .../windows/CharacterSheetWindow.vue | 39 +- .../app/components/windows/TraitWindow.vue | 57 ++ .../01-notes-and-markdown.md | 37 ++ .../docs/03-integrations/03-foundry.md | 33 +- frontend/app/services/LinkAutocomplete.js | 109 ++++ frontend/app/services/LinkTargets.js | 71 ++ frontend/app/services/Marker.js | 48 +- frontend/app/services/WidgetAutocomplete.js | 78 +++ frontend/app/services/WindowDefinitions.js | 6 + frontend/i18n/locales/ca/campaigns.json | 7 + frontend/i18n/locales/ca/general.json | 4 + frontend/i18n/locales/ca/windows.json | 1 + frontend/i18n/locales/en/campaigns.json | 7 + frontend/i18n/locales/en/general.json | 4 + frontend/i18n/locales/en/windows.json | 1 + frontend/i18n/locales/es/campaigns.json | 7 + frontend/i18n/locales/es/general.json | 4 + frontend/i18n/locales/es/windows.json | 1 + .../routes/foundry/dragonroll-foundry.zip.js | 7 + frontend/server/routes/foundry/module.json.js | 14 + frontend/server/utils/foundry-module.js | 110 ++++ tests/character-sheet-details.test.js | 29 +- tests/character-sheet-traits-items.test.js | 4 +- tests/foundry-manifest.test.js | 87 +++ tests/foundry-note-journal.test.js | 422 +++++++++++- tests/foundry-sync-toggle.test.js | 11 +- tests/link-autocomplete.test.js | 153 +++++ tests/note-links.test.js | 157 +++++ tests/widget-autocomplete.test.js | 148 +++++ 45 files changed, 3438 insertions(+), 166 deletions(-) create mode 100644 dragonroll-foundry/styles/dragonroll.css create mode 100644 frontend/app/components/viewer/content/EmbeddedEntry.vue create mode 100644 frontend/app/components/viewer/content/LinkPreview.vue create mode 100644 frontend/app/components/viewer/content/SuggestionMenu.vue create mode 100644 frontend/app/components/windows/TraitWindow.vue create mode 100644 frontend/app/services/LinkAutocomplete.js create mode 100644 frontend/app/services/LinkTargets.js create mode 100644 frontend/app/services/WidgetAutocomplete.js create mode 100644 frontend/server/routes/foundry/dragonroll-foundry.zip.js create mode 100644 frontend/server/routes/foundry/module.json.js create mode 100644 frontend/server/utils/foundry-module.js create mode 100644 tests/foundry-manifest.test.js create mode 100644 tests/link-autocomplete.test.js create mode 100644 tests/note-links.test.js create mode 100644 tests/widget-autocomplete.test.js diff --git a/AGENTS.md b/AGENTS.md index 60af12ab..a7ae6c2d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,7 +123,7 @@ prunes), `scene-delete`, `characters`, `items`, `notes` / `map-note`, `status`, - **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 every campaign note as a page of one world `JournalEntry` named Dragonroll — 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 reconcile rewrites pages from the notes and drops the page of a deleted note; journal edits never travel back. +- **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`). - **`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`). - `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. diff --git a/backend/src/models/Actor.js b/backend/src/models/Actor.js index 19010dce..77054951 100644 --- a/backend/src/models/Actor.js +++ b/backend/src/models/Actor.js @@ -86,6 +86,14 @@ const ActorSchema = new Schema({ // for, shown on the left of the inventory row. icon: { type: String, default: '' } }], + // The character's features as the world writes them (Syndria98/dragonroll#89): one row + // per Foundry `feat` item, with the item's own picture and text. The free-form `traits` + // above keeps the details a world has no item for. + features: [{ + name: { type: String, trim: true, default: '' }, + description: { type: String, default: '' }, + icon: { type: String, default: '' } + }], traits: { type: String, default: '' }, spells: { type: String, default: '' }, campaign: { diff --git a/backend/src/models/Note.js b/backend/src/models/Note.js index 74eb754d..12a5fc42 100644 --- a/backend/src/models/Note.js +++ b/backend/src/models/Note.js @@ -14,9 +14,10 @@ const NoteSchema = new Schema({ ref: 'Folder' }, color: { type: String }, - // The journal page this note is written as in the linked Foundry world: the - // page of the one "Dragonroll" journal whose rows carry this note's id in - // their `dragonroll-foundry.noteId` flag (see the module's notes sync). + // 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 } }); diff --git a/backend/src/routes/actor.js b/backend/src/routes/actor.js index 3958bd54..65a69d1c 100644 --- a/backend/src/routes/actor.js +++ b/backend/src/routes/actor.js @@ -74,7 +74,7 @@ router.post('/update', async (req, res) => { try { const { id, name, species, className, subclass, level, abilityScores, armorClass, speed, hitPoints, hitDice, - proficiencies, skills, savingThrows, tools, languages, currency, inventory, traits, spells, image, folder + proficiencies, skills, savingThrows, tools, languages, currency, inventory, features, traits, spells, image, folder } = req.body; if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' }); @@ -111,6 +111,7 @@ router.post('/update', async (req, res) => { if (languages !== undefined) actor.languages = textList(languages); if (currency !== undefined) actor.currency = currency; if (inventory !== undefined) actor.inventory = inventory; + if (features !== undefined) actor.features = features; if (traits !== undefined) actor.traits = traits; if (spells !== undefined) actor.spells = spells; if (image !== undefined) actor.image = String(image); diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js index ec7470e1..580944d1 100644 --- a/backend/src/routes/foundry-link.js +++ b/backend/src/routes/foundry-link.js @@ -66,6 +66,9 @@ function resolveWorldAssets(fields, campaign) { if (Array.isArray(fields.inventory)) { for (const entry of fields.inventory) entry.icon = worldAssetUrl(entry.icon, worldUrl); } + if (Array.isArray(fields.features)) { + for (const entry of fields.features) entry.icon = worldAssetUrl(entry.icon, worldUrl); + } } async function saveFoundryActor(campaign, source, fullSync = false, replace = false) { @@ -580,24 +583,89 @@ router.post('/sync/map-item', async (req, res) => { }); // --- Note pages ------------------------------------------------------------ -// The campaign's notes are read where their authors' table sits: every note -// stands as a page of the one 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. +// 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. Folders of the notes do not travel — the journal is flat. +// 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') + .select('_id title content foundryPageId date folder') .sort({ date: -1 }) .lean(); - res.json({ status: 'ok', notes }); + 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' }); diff --git a/backend/src/services/actor-foundry.js b/backend/src/services/actor-foundry.js index 3d411899..666a12ef 100644 --- a/backend/src/services/actor-foundry.js +++ b/backend/src/services/actor-foundry.js @@ -111,23 +111,27 @@ function foundryCurrency(system) { return Object.fromEntries(CURRENCIES.map((key) => [key, Math.max(0, numberOr(coins[key], 0))])); } -// The character's traits as the world writes them: the free-text details field some -// system releases keep, or its trait items, which are how a monster's traits and a -// character's racial and class features are written. `undefined` says the world holds -// no traits to show. -function foundryTraits(source, items) { +// The character's features: D&D 5e files species, background, class and monster features +// under the `feat` item type, each with its text and picture on the item. They are what +// the sheet's traits tab lists, one row per feature. +function foundryFeatures(items) { + return items + .filter((item) => item.type === 'feat') + .map((item) => ({ + name: asText(item.name).trim(), + description: plainText(item.system?.description?.value ?? item.system?.description), + icon: asText(item.img).trim() + })) + .filter((feature) => feature.name); +} + +// The free-form traits text: the details field some system releases keep, or what the +// campaign wrote and the module carries back on its flag. `undefined` says the world +// holds no text of its own, which keeps a live edit from clearing the campaign's. +function foundryTraits(source, savedDragonrollFields, replace) { const text = plainText(source.system?.details?.trait); - if (text) return text; - const features = items - .filter((item) => item.type === 'feat' && stringList(item.system?.featType?.value ?? item.system?.featType) - .some((type) => asText(type).toLowerCase().startsWith('tr'))) - .map((item) => { - const name = asText(item.name).trim(); - const description = plainText(item.system?.description?.value ?? item.system?.description); - return name ? `${name}\n${description}`.trim() : ''; - }) - .filter(Boolean); - return features.length ? features.join('\n\n') : undefined; + const campaignTraits = replace ? '' : asText(savedDragonrollFields.traits); + return text || campaignTraits || undefined; } // `replace` is a forced actor sync from the module's context menu (Syndria98/dragonroll#96): @@ -188,7 +192,11 @@ function foundryActorToCharacter(foundryActor, replace = false) { icon: asText(item.img).trim() })) .filter((item) => item.name), - spells: items.filter((item) => item.type === 'spell').map((item) => asText(item.name)).filter(Boolean).join('\n') + spells: items.filter((item) => item.type === 'spell').map((item) => asText(item.name)).filter(Boolean).join('\n'), + // The features themselves, icons and all: the traits tab draws them like the + // inventory, and a live edit sends the world's whole item list, so a feature the + // GM removed in Foundry goes here too. + features: foundryFeatures(items) }; // What the world says about each of these, when it says anything: leaving a field @@ -206,9 +214,8 @@ function foundryActorToCharacter(foundryActor, replace = false) { if (languages) fields.languages = languages; const currency = foundryCurrency(system); if (currency) fields.currency = currency; - const worldTraits = foundryTraits(foundryActor, items); - const campaignTraits = replace ? '' : asText(savedDragonrollFields.traits); - if (worldTraits || campaignTraits) fields.traits = worldTraits || campaignTraits; + const worldTraits = foundryTraits(foundryActor, savedDragonrollFields, replace); + if (worldTraits) fields.traits = worldTraits; // A replace writes the fields a live edit would leave out when the world says // nothing, so the campaign's toggles, lists and text for this actor go with it and diff --git a/dragonroll-foundry/README.md b/dragonroll-foundry/README.md index 5351cee6..9feb9ea9 100644 --- a/dragonroll-foundry/README.md +++ b/dragonroll-foundry/README.md @@ -11,7 +11,13 @@ The Foundry module uses the client-side package API and hooks documented by Foun ## 1. Install the Foundry module -Copy the contents of this directory into +In Foundry's **Setup → Add-on Modules → Install Module**, paste the manifest URL +`https://dragonroll.aranroig.com/foundry/module.json`. The frontend serves that manifest and the +zip it points to (`/foundry/dragonroll-foundry.zip`), both built from this directory, and the same +manifest URL is what Foundry checks for updates. A self-hosted Dragonroll serves it at +`https:///foundry/module.json`. + +Alternatively, copy the contents of this directory into `{Foundry user data}/Data/modules/dragonroll-foundry/`. Restart Foundry, then enable **Dragonroll Foundry API** in the world's module settings. @@ -133,14 +139,34 @@ about it cross over: the scene's **background picture** and the **grid** laid ov ### Notes -The campaign's notes read like the campaign's journal in the world (Syndria98/dragonroll#98): every -note stands as a page of one JournalEntry named **Dragonroll**. The module creates that journal — or -adopts one the GM already made under that name, marking it as the notes' journal — and renders each -note's markdown into page HTML with Foundry's own renderer. Notes are written in Dragonroll, so this -copy runs one way: a note made or edited in the campaign rewrites its page on the next reconcile, and -a note deleted there takes its page with it. Pages the campaign does not own — the GM's own pages in -that journal — are left alone, and nothing written in the journal travels back. Autosync off stops it -too, like the rest of the sync. +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 module calls these Dragonroll routes with the campaign sync token (no Dragonroll login): @@ -153,7 +179,8 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon | `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, and the journal page each stands as | +| `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/map` / `map-item` | Store an id mapping after creating a document | diff --git a/dragonroll-foundry/module.json b/dragonroll-foundry/module.json index 1a81c4db..7f60902a 100644 --- a/dragonroll-foundry/module.json +++ b/dragonroll-foundry/module.json @@ -2,13 +2,16 @@ "id": "dragonroll-foundry", "title": "Dragonroll Foundry API", "description": "Links a Foundry world to a Dragonroll campaign and exposes a client-side API for world data.", - "version": "0.6.0", + "version": "0.7.0", "library": true, "compatibility": { - "minimum": "12", + "minimum": "14", "verified": "14" }, "esmodules": [ "scripts/api.js" + ], + "styles": [ + "styles/dragonroll.css" ] } diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js index a75553e4..14eed3fc 100644 --- a/dragonroll-foundry/scripts/api.js +++ b/dragonroll-foundry/scripts/api.js @@ -305,6 +305,9 @@ async function applyDragonrollLink(result) { 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"; @@ -1470,67 +1473,455 @@ async function initializeSceneSync() { } // --- Note pages ------------------------------------------------------------ -// The campaign's notes read like the campaign's journal in the world: every note -// stands as a page of one JournalEntry named "Dragonroll". 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 in that journal are left alone: only the -// ones this module made carry the `dragonroll-foundry.noteId` flag. +// 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 || ""; } -// A note is markdown, a journal page is HTML. Foundry's own renderer keeps the -// page readable in the journal and in its styles; where this Foundry does not -// offer one, escaped paragraphs keep the text legible until it does. -function notePageHtml(content) { - const markdown = String(content ?? ""); - if (!markdown.trim()) return ""; - if (typeof TextEditor !== "undefined" && typeof TextEditor._getMarkdown === "function") { - const html = TextEditor._getMarkdown(markdown); - if (html) return html; +// --- 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 markdown - .split(/\n\s*\n/) - .map((block) => `

${escapeNoteHtml(block.trim()).replace(/\n/g, "
")}

`) - .join("\n"); + 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, ">"); + return String(value) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); } function notePageTitle(entry) { return String(entry.title || "").trim() || "Untitled note"; } -// The journal this module writes the campaign's notes into: the one it flagged as -// its own, or one the GM already made under that name. An unflagged one is -// flagged on use, so renaming it afterwards still leaves the notes' home findable. -function notesJournal() { - const journals = game.journals?.contents || []; - return journals.find((journal) => journal.getFlag?.(MODULE_ID, "notesJournal")) - || journals.find((journal) => journal.name === NOTES_JOURNAL_NAME) - || null; +// 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) : ""; } -async function ensureNotesJournal() { - const existing = notesJournal(); - if (existing) { - if (!existing.getFlag?.(MODULE_ID, "notesJournal")) { - await existing.update({ [`flags.${MODULE_ID}.notesJournal`]: true }); +// 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: NOTES_JOURNAL_NAME, flags: { [MODULE_ID]: { notesJournal: true } } }, - { renderSheet: false }, - ); + + const created = await JournalEntry.create({ + name, + flags: { [MODULE_ID]: folderKey ? { notesFolder: folderKey } : { notesJournal: true } }, + }, { renderSheet: false }); return Array.isArray(created) ? created[0] : created; } @@ -1577,43 +1968,102 @@ async function reconcileDragonrollNotes() { 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 one it once had - // stays, so the pages of notes it deleted can go with them. - if (!remoteNotes.length && !notesJournal()) return; - const journal = await ensureNotesJournal(); - if (!journal) return; + // 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 remoteById = new Map(remoteNotes.map((entry) => [String(entry._id), entry])); - const localByRemoteId = new Map((journal.pages?.contents || []) - .map((page) => [String(dragonrollNoteId(page)), page]) - .filter(([noteId]) => noteId)); + 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) { - let page = entry.foundryPageId ? journal.pages?.get(entry.foundryPageId) : null; - if (!page) page = localByRemoteId.get(String(entry._id)); + 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); - if (!entry.foundryPageId) await mapDragonrollNote(entry._id, page.id); + 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); } } } - // Pages whose note the campaign deleted go with it. Only pages this module - // made are its business: an unflagged page is the GM's own. - for (const page of journal.pages?.contents || []) { - const noteId = dragonrollNoteId(page); - if (!noteId || retainedPageIds.has(page.id) || remoteById.has(String(noteId))) continue; - await page.delete(); + // 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); @@ -1698,6 +2148,7 @@ 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. @@ -1714,10 +2165,12 @@ Hooks.once("ready", () => { // 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 on - // the same rhythm: a note written in the app is on the journal within seconds. + // 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, 5000); + 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. @@ -1767,18 +2220,27 @@ Hooks.once("ready", () => { // A GM sends selected actors to Dragonroll from the actor directory's context // menu, replacing whatever the campaign holds for them. This works with autosync on // and off: it is the one push done on purpose. -Hooks.on("getActorDirectoryEntryContext", (html, options) => { - if (!game.user?.isGM || !getSyncToken()) return; - - options.push({ - name: "Dragonroll: Force Sync", - icon: '', - // Array.from: the selected entries are jQuery in Foundry 12 and a plain - // array afterwards, and both are array-like. - callback: (entries) => forceSyncActorsToDragonroll( - Array.from(entries || []) - .map((entry) => game.actors?.get(entry.dataset?.actorId)) - .filter(Boolean), - ), +// +// Foundry 13 replaced getActorDirectoryEntryContext with getActorContextOptions, +// which fires when the directory first renders, so the hook is registered here at +// load time rather than inside "ready". The entry is always offered and hidden with +// "visible" when it cannot apply, because the hook may only run once. +Hooks.on("getActorContextOptions", (application, menuItems) => { + menuItems.push({ + label: "Dragonroll: Force Sync", + icon: "fa-solid fa-rotate", + visible: () => Boolean(game.user?.isGM && getSyncToken()), + onClick: (event, target) => { + // One entry is clicked at a time, but several can be selected: take every + // selected actor directory entry, falling back to the one the menu was + // opened for. + const clicked = target?.closest?.("[data-entry-id]") ?? target; + const ids = new Set( + [...(application?.element?.querySelectorAll?.("[data-entry-id].selected") ?? [])] + .map((entry) => entry.dataset?.entryId), + ); + if (clicked?.dataset?.entryId) ids.add(clicked.dataset.entryId); + forceSyncActorsToDragonroll([...ids].map((id) => game.actors?.get(id)).filter(Boolean)); + }, }); }); diff --git a/dragonroll-foundry/styles/dragonroll.css b/dragonroll-foundry/styles/dragonroll.css new file mode 100644 index 00000000..4589eaa7 --- /dev/null +++ b/dragonroll-foundry/styles/dragonroll.css @@ -0,0 +1,27 @@ +/* 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; +} diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 4cad3421..8336817a 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -38,6 +38,9 @@ WORKDIR /app # Copy built output COPY --from=builder /app/frontend/.output ./.output +# Source of the Foundry module, zipped on demand by /foundry/dragonroll-foundry.zip +COPY dragonroll-foundry ./dragonroll-foundry + # Expose Nuxt port EXPOSE 3000 diff --git a/frontend/app/components/viewer/content/EmbeddedEntry.vue b/frontend/app/components/viewer/content/EmbeddedEntry.vue new file mode 100644 index 00000000..d431974d --- /dev/null +++ b/frontend/app/components/viewer/content/EmbeddedEntry.vue @@ -0,0 +1,302 @@ + + + + + \ No newline at end of file diff --git a/frontend/app/components/viewer/content/LinkPreview.vue b/frontend/app/components/viewer/content/LinkPreview.vue new file mode 100644 index 00000000..c7fc8306 --- /dev/null +++ b/frontend/app/components/viewer/content/LinkPreview.vue @@ -0,0 +1,227 @@ + + + + + \ No newline at end of file diff --git a/frontend/app/components/viewer/content/Note.vue b/frontend/app/components/viewer/content/Note.vue index 314fb748..9da8ac55 100644 --- a/frontend/app/components/viewer/content/Note.vue +++ b/frontend/app/components/viewer/content/Note.vue @@ -1,12 +1,21 @@ + + + + diff --git a/frontend/app/components/viewer/statusbar/FetchStatus.vue b/frontend/app/components/viewer/statusbar/FetchStatus.vue index 3c960a9f..aae8cb04 100644 --- a/frontend/app/components/viewer/statusbar/FetchStatus.vue +++ b/frontend/app/components/viewer/statusbar/FetchStatus.vue @@ -1,23 +1,28 @@