Deploy deepseek 2
This commit is contained in:
@@ -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) => `<p>${escapeNoteHtml(block.trim()).replace(/\n/g, "<br />")}</p>`)
|
||||
.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 `<span class="dragonroll-note-link is-unresolved">${escapeNoteHtml(text)}</span>`;
|
||||
}
|
||||
return `@UUID[${target.uuid}]{${escapeNoteHtml(text)}}`;
|
||||
}
|
||||
|
||||
function noteEmbedHtml(label) {
|
||||
const text = String(label ?? "").trim();
|
||||
const target = findNoteTarget(text, { embed: true });
|
||||
if (!target) {
|
||||
return `<span class="dragonroll-note-link is-unresolved">${escapeNoteHtml(text)}</span>`;
|
||||
}
|
||||
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 `<button type="button" class="${classes}" data-dragonroll-roll="${escapeNoteHtml(formula)}"`
|
||||
+ ` title="Roll ${escapeNoteHtml(label)}">`
|
||||
+ '<i class="fa-solid fa-dice-d20" aria-hidden="true"></i>'
|
||||
+ `<span>${escapeNoteHtml(label)}</span></button>`;
|
||||
}
|
||||
|
||||
// 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: <strong>${escapeNoteHtml(formula)}</strong>`,
|
||||
});
|
||||
} 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(`<pre><code${language ? ` class="language-${language}"` : ""}>${escapeNoteHtml(code.join("\n"))}</code></pre>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
|
||||
blocks.push("<hr />");
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const heading = line.match(/^(#{1,6})\s+(.*?)\s*#*\s*$/);
|
||||
if (heading) {
|
||||
blocks.push(`<h${heading[1].length}>${noteInlineHtml(heading[2])}</h${heading[1].length}>`);
|
||||
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(`<h${level}>${noteInlineHtml(line.trim())}</h${level}>`);
|
||||
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(`<blockquote>${markdownBlocks(quote.join("\n"))}</blockquote>`);
|
||||
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(`<li>${noteInlineHtml(continuation.join("\n")).replace(/\n/g, "<br />")}</li>`);
|
||||
}
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
blocks.push(`<${tag}>\n${items.join("\n")}\n</${tag}>`);
|
||||
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(`<p>${noteInlineHtml(paragraph.join("\n")).replace(/\n/g, "<br />")}</p>`);
|
||||
}
|
||||
|
||||
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(`<code>${escapeNoteHtml(code)}</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) =>
|
||||
`<img src="${source}" alt="${alt}" />`);
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (match, label, href) =>
|
||||
`<a href="${href}">${label}</a>`);
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
||||
html = html.replace(/(^|[\s(])__([^_]+)__(?=[\s).,!?:;<]|$)/g, "$1<strong>$2</strong>");
|
||||
html = html.replace(/(^|[^*])\*([^*]+)\*/g, "$1<em>$2</em>");
|
||||
html = html.replace(/(^|[\s(])_([^_]+)_(?=[\s).,!?:;<]|$)/g, "$1<em>$2</em>");
|
||||
html = html.replace(/~~([^~]+)~~/g, "<s>$1</s>");
|
||||
return html.replace(/\u0000(\d+)\u0000/g, (match, position) => atoms[Number(position)]);
|
||||
}
|
||||
|
||||
function escapeNoteHtml(value) {
|
||||
return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
return String(value)
|
||||
.replace(/&/g, "&")
|
||||
.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: '<i class="fa-solid fa-rotate"></i>',
|
||||
// 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));
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user