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:
@@ -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