Fix issue #98: Sync notes from dragonroll to foundry
All checks were successful
Test / test (push) Successful in 2s
All checks were successful
Test / test (push) Successful in 2s
This commit is contained in:
@@ -105,6 +105,17 @@ else (Syndria98/dragonroll#67):
|
||||
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.
|
||||
|
||||
### 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 module calls these Dragonroll routes with the campaign sync token (no Dragonroll login):
|
||||
|
||||
| Route | Use |
|
||||
@@ -114,12 +125,16 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon
|
||||
| `POST /api/foundry/sync/item-delete` | A world item 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 |
|
||||
| `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 |
|
||||
| `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 world items are marked with `dragonroll-foundry.syncMutation` while Dragonroll writes them so
|
||||
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.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"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.4.0",
|
||||
"version": "0.5.0",
|
||||
"library": true,
|
||||
"compatibility": {
|
||||
"minimum": "12",
|
||||
|
||||
@@ -450,6 +450,7 @@ function handleAutoSyncChange(value) {
|
||||
initializeCharacterSync();
|
||||
reconcileDragonrollItems();
|
||||
queueFoundryItemFolders(400);
|
||||
reconcileDragonrollNotes();
|
||||
if (queuedActorChanges.size) {
|
||||
clearTimeout(actorSyncTimeout);
|
||||
actorSyncTimeout = setTimeout(flushActorChanges, 400);
|
||||
@@ -1356,6 +1357,157 @@ function queueFoundryActorChange(kind, actor) {
|
||||
queueActorChange(kind, actor);
|
||||
}
|
||||
|
||||
// --- 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.
|
||||
|
||||
const NOTES_JOURNAL_NAME = "Dragonroll";
|
||||
let noteSyncRunning = false;
|
||||
let noteSyncErrorLogged = false;
|
||||
|
||||
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;
|
||||
}
|
||||
return markdown
|
||||
.split(/\n\s*\n/)
|
||||
.map((block) => `<p>${escapeNoteHtml(block.trim()).replace(/\n/g, "<br />")}</p>`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function escapeNoteHtml(value) {
|
||||
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;
|
||||
}
|
||||
|
||||
async function ensureNotesJournal() {
|
||||
const existing = notesJournal();
|
||||
if (existing) {
|
||||
if (!existing.getFlag?.(MODULE_ID, "notesJournal")) {
|
||||
await existing.update({ [`flags.${MODULE_ID}.notesJournal`]: true });
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
const created = await JournalEntry.create(
|
||||
{ name: NOTES_JOURNAL_NAME, flags: { [MODULE_ID]: { 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.title?.text ?? page.title ?? "") !== title) updates["title.text"] = 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", [{
|
||||
title: { text: 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 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;
|
||||
|
||||
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 retainedPageIds = new Set();
|
||||
|
||||
for (const entry of remoteNotes) {
|
||||
let page = entry.foundryPageId ? journal.pages?.get(entry.foundryPageId) : null;
|
||||
if (!page) page = localByRemoteId.get(String(entry._id));
|
||||
if (page) {
|
||||
retainedPageIds.add(page.id);
|
||||
await applyDragonrollNotePage(page, entry);
|
||||
if (!entry.foundryPageId) await mapDragonrollNote(entry._id, page.id);
|
||||
} else {
|
||||
const created = await createDragonrollNotePage(journal, entry);
|
||||
if (created) {
|
||||
retainedPageIds.add(created.id);
|
||||
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();
|
||||
}
|
||||
noteSyncErrorLogged = false;
|
||||
} catch (error) {
|
||||
reportNoteSyncError(error);
|
||||
} finally {
|
||||
noteSyncRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function publishSnapshot() {
|
||||
if (!game.user?.isGM || !game.world) return;
|
||||
if (syncInProgress) {
|
||||
@@ -1448,6 +1600,10 @@ 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.
|
||||
setTimeout(reconcileDragonrollNotes, 3000);
|
||||
setInterval(reconcileDragonrollNotes, 5000);
|
||||
|
||||
for (const event of [
|
||||
"createActor", "updateActor", "deleteActor",
|
||||
|
||||
Reference in New Issue
Block a user