Deploy deepseek 2
This commit is contained in:
@@ -368,7 +368,7 @@ test("a carried item brings its own icon", () => {
|
||||
|
||||
// --- The traits tab syncs --------------------------------------------------------
|
||||
|
||||
test("the world's own traits reach the campaign", () => {
|
||||
test("the world's own traits and features reach the campaign", () => {
|
||||
const fromText = foundryActorToCharacter({ name: "Thalia", system: { details: { trait: "Spellcaster.<br>Light sleeper." } } });
|
||||
assert.equal(fromText.traits, "Spellcaster.\nLight sleeper.");
|
||||
|
||||
@@ -376,12 +376,17 @@ test("the world's own traits reach the campaign", () => {
|
||||
name: "Thalia",
|
||||
system: {},
|
||||
items: [
|
||||
{ name: "Darkvision", type: "feat", system: { featType: "trs", description: { value: "<p>See in the dark.</p>" } } },
|
||||
{ name: "Brave", type: "feat", system: { featType: ["tr"], description: { value: "Advantage on saves." } } },
|
||||
{ name: "Alert", type: "feat", system: { featType: "feat", description: { value: "Never surprised." } } },
|
||||
{ name: "Darkvision", type: "feat", img: "http://vtt.test/icons/eye.svg", system: { type: { value: "race" }, description: { value: "<p>See in the dark.</p>" } } },
|
||||
{ name: "Second Wind", type: "feat", system: { type: { value: "class" }, description: { value: "Regain hit points." } } },
|
||||
{ name: "Alert", type: "feat", system: { type: { value: "feat" }, description: { value: "Never surprised." } } },
|
||||
],
|
||||
});
|
||||
assert.equal(fromFeatures.traits, "Darkvision\nSee in the dark.\n\nBrave\nAdvantage on saves.");
|
||||
assert.deepEqual(fromFeatures.features, [
|
||||
{ name: "Darkvision", description: "See in the dark.", icon: "http://vtt.test/icons/eye.svg" },
|
||||
{ name: "Second Wind", description: "Regain hit points.", icon: "" },
|
||||
{ name: "Alert", description: "Never surprised.", icon: "" },
|
||||
], "each feature is a row of its own, with the world's icon and text");
|
||||
assert.ok(!("traits" in fromFeatures), "the feature items are not repeated as free text");
|
||||
});
|
||||
|
||||
test("the world leads the traits tab, and what the campaign wrote fills in when it has none", () => {
|
||||
@@ -410,6 +415,20 @@ test("an actor that holds no traits does not clear what the campaign has", () =>
|
||||
assert.ok(!("traits" in character), "a live edit that knows nothing about traits leaves the tab as it is");
|
||||
});
|
||||
|
||||
test("features stand like inventory rows and open their description", () => {
|
||||
const panel = /<section class="sheet-panel traits-panel">([\s\S]*?)<\/section>/.exec(template)?.[1] ?? "";
|
||||
assert.match(panel, /v-for="\(trait, index\) in form\.features"/, "one row per feature");
|
||||
assert.match(panel, /resolveImage\(trait\.icon\)/, "the world's icon sits on the left");
|
||||
assert.match(panel, /@click="openTrait\(trait\)"/, "clicking a row opens its description");
|
||||
assert.match(read("frontend", "app", "services", "WindowDefinitions.js"), /trait_sheet: \{/);
|
||||
|
||||
assert.deepEqual(
|
||||
normalizeActor({ features: [{ name: "Darkvision", description: "See in the dark.", icon: "eye.svg" }] }).features,
|
||||
[{ name: "Darkvision", description: "See in the dark.", icon: "eye.svg" }]
|
||||
);
|
||||
assert.deepEqual(normalizeActor({}).features, []);
|
||||
});
|
||||
|
||||
// A forced actor sync from the module's context menu replaces everything the campaign
|
||||
// holds for that actor (Syndria98/dragonroll#96): the fields a live edit leaves out when
|
||||
// the world says nothing are written empty instead of kept, and the campaign's own text
|
||||
|
||||
@@ -51,7 +51,9 @@ test("traits and species stand in their own fields, not among the carried items"
|
||||
"the inventory holds what the character carries, and nothing else");
|
||||
assert.deepEqual(character.inventory[0],
|
||||
{ name: "Longsword", quantity: 1, weight: 3, icon: "http://vtt.test/icons/sword.svg" });
|
||||
assert.equal(character.traits, "Darkvision\nSee in the dark.", "the feat is read as a trait, where the sheet shows it");
|
||||
assert.deepEqual(character.features,
|
||||
[{ name: "Darkvision", description: "See in the dark.", icon: "" }],
|
||||
"the feat stands as a feature row, where the sheet shows it");
|
||||
assert.equal(character.spells, "Magic Missile", "and the spell where its tab shows it");
|
||||
});
|
||||
|
||||
|
||||
87
tests/foundry-manifest.test.js
Normal file
87
tests/foundry-manifest.test.js
Normal file
@@ -0,0 +1,87 @@
|
||||
// Tests for the Foundry manifest the frontend serves (Syndria98/dragonroll#111): Foundry installs a
|
||||
// module from a manifest URL and then downloads a zip, so the zip has to hold `module.json` and every
|
||||
// module file at its root, and the manifest has to be the source module.json with absolute URLs.
|
||||
//
|
||||
// `frontend/server/utils/foundry-module.js` builds both. It is loaded straight from source, with its
|
||||
// `node:` imports, the way the other tests load frontend code; the routes on top of it only add the
|
||||
// request origin.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { pathToFileURL } = require("node:url");
|
||||
|
||||
const moduleDir = path.join(__dirname, "..", "dragonroll-foundry");
|
||||
const moduleUtil = pathToFileURL(
|
||||
path.join(__dirname, "..", "frontend", "server", "utils", "foundry-module.js"),
|
||||
).href;
|
||||
|
||||
function readSourceFiles(dir, base = dir) {
|
||||
return fs.readdirSync(dir, { withFileTypes: true })
|
||||
.flatMap((entry) => {
|
||||
const full = path.join(dir, entry.name);
|
||||
return entry.isDirectory()
|
||||
? readSourceFiles(full, base)
|
||||
: [path.relative(base, full).split(path.sep).join("/")];
|
||||
})
|
||||
.sort();
|
||||
}
|
||||
|
||||
// Reads a stored (uncompressed) zip through its central directory, checking each local header.
|
||||
function readZipEntries(zip) {
|
||||
const eocd = zip.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
|
||||
assert.ok(eocd >= 0, "the zip has an end of central directory record");
|
||||
|
||||
const count = zip.readUInt16LE(eocd + 10);
|
||||
let offset = zip.readUInt32LE(eocd + 16);
|
||||
const entries = [];
|
||||
|
||||
for (let index = 0; index < count; index++) {
|
||||
assert.equal(zip.readUInt32LE(offset), 0x02014b50, "central directory header");
|
||||
assert.equal(zip.readUInt16LE(offset + 10), 0, "stored, not deflated");
|
||||
|
||||
const nameLength = zip.readUInt16LE(offset + 28);
|
||||
const extraLength = zip.readUInt16LE(offset + 30);
|
||||
const commentLength = zip.readUInt16LE(offset + 32);
|
||||
const localOffset = zip.readUInt32LE(offset + 42);
|
||||
const name = zip.toString("utf8", offset + 46, offset + 46 + nameLength);
|
||||
|
||||
assert.equal(zip.readUInt32LE(localOffset), 0x04034b50, "local file header");
|
||||
const dataStart = localOffset + 30
|
||||
+ zip.readUInt16LE(localOffset + 26)
|
||||
+ zip.readUInt16LE(localOffset + 28);
|
||||
const size = zip.readUInt32LE(localOffset + 18);
|
||||
|
||||
entries.push({ name, data: zip.subarray(dataStart, dataStart + size) });
|
||||
offset += 46 + nameLength + extraLength + commentLength;
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
test("the manifest is the module's module.json", async () => {
|
||||
const { readModuleManifest } = await import(moduleUtil);
|
||||
const manifest = readModuleManifest();
|
||||
const source = JSON.parse(fs.readFileSync(path.join(moduleDir, "module.json"), "utf8"));
|
||||
|
||||
assert.deepEqual(manifest, source);
|
||||
assert.equal(manifest.id, "dragonroll-foundry");
|
||||
assert.ok(manifest.version);
|
||||
});
|
||||
|
||||
test("the zip installs every module file at its root, byte for byte", async () => {
|
||||
const { buildFoundryModuleZip } = await import(moduleUtil);
|
||||
const entries = readZipEntries(buildFoundryModuleZip());
|
||||
|
||||
assert.deepEqual(entries.map((entry) => entry.name), readSourceFiles(moduleDir));
|
||||
assert.ok(entries.some((entry) => entry.name === "module.json"));
|
||||
assert.ok(entries.some((entry) => entry.name === "scripts/api.js"));
|
||||
assert.ok(entries.some((entry) => entry.name === "styles/dragonroll.css"));
|
||||
|
||||
for (const entry of entries) {
|
||||
assert.deepEqual(entry.data, fs.readFileSync(path.join(moduleDir, entry.name)), entry.name);
|
||||
}
|
||||
});
|
||||
@@ -1,14 +1,15 @@
|
||||
// Tests for the campaign's notes reaching the Foundry world as journal pages
|
||||
// (Syndria98/dragonroll#98): every Dragonroll note stands as a page of the one
|
||||
// journal the world calls "Dragonroll", written by the module and kept in step with
|
||||
// the campaign. The copy runs one way — notes are written in Dragonroll — so the
|
||||
// backend answers with the notes and remembers each note's page; the module reads
|
||||
// them, renders the markdown, and prunes the page of a note the campaign deleted.
|
||||
// (Syndria98/dragonroll#98): each Dragonroll folder stands as a journal named after
|
||||
// its path (root notes share "Dragonroll"), written by the module and kept in step
|
||||
// with the campaign. The copy runs one way — notes are written in Dragonroll — so
|
||||
// the backend answers with the notes and their folder paths and remembers each
|
||||
// note's page; the module reads them, renders the markdown, moves a page when its
|
||||
// note changes folder, and prunes the page of a note the campaign deleted.
|
||||
//
|
||||
// Both sides are loaded the way the other Foundry tests do it: the sync route runs
|
||||
// against a stubbed `require` (models answer with plain objects and a small filter
|
||||
// matcher), and the Foundry module is loaded into a `node:vm` context holding
|
||||
// stubbed Foundry globals (`game.journals` and `JournalEntry` included) with fake
|
||||
// stubbed Foundry globals (`game.journal` and `JournalEntry` included) with fake
|
||||
// timers, like tests/item-folder-sync.test.js.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
@@ -155,6 +156,30 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
|
||||
|
||||
// --- The sync route: the notes it answers and the page ids it keeps ---------------
|
||||
|
||||
test("the notes revision folds the campaign's notes into one hash", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: {
|
||||
notes: [
|
||||
{ _id: "note-1", title: "Session 1", content: "hi" },
|
||||
{ _id: "note-2", title: "Tavern Brawl", content: "ho" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const first = await sync.call("GET /sync/notes/revision");
|
||||
assert.equal(first.status, "ok");
|
||||
assert.match(first.revision, /^[0-9a-f]{64}$/, "a sha-256 of the notes, not their content");
|
||||
|
||||
sync.models["../models/Note"].rows[0].content = "hi there";
|
||||
const edited = await sync.call("GET /sync/notes/revision");
|
||||
assert.notEqual(edited.revision, first.revision, "editing a note moves the revision");
|
||||
|
||||
sync.models["../models/Note"].rows[0].content = "hi";
|
||||
sync.models["../models/Note"].rows[0].foundryPageId = "page-9";
|
||||
const mapped = await sync.call("GET /sync/notes/revision");
|
||||
assert.equal(mapped.revision, first.revision, "mapping a note to its page is not an edit");
|
||||
});
|
||||
|
||||
test("the world reads the campaign's notes with their content and page mapping", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: {
|
||||
@@ -173,6 +198,47 @@ test("the world reads the campaign's notes with their content and page mapping",
|
||||
assert.equal(response.notes[0].foundryPageId, "page-9", "and the note says which page it already stands as");
|
||||
});
|
||||
|
||||
test("the world reads each note with the path of the folder it lives in", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: {
|
||||
folders: [
|
||||
{ _id: "folder-1", name: "Sessions", parentFolder: null },
|
||||
{ _id: "folder-2", name: "Arc 1", parentFolder: "folder-1" },
|
||||
],
|
||||
notes: [
|
||||
{ _id: "note-1", title: "Root", content: "root" },
|
||||
{ _id: "note-2", title: "In folder", content: "folder", folder: "folder-1" },
|
||||
{ _id: "note-3", title: "Deep", content: "deep", folder: "folder-2" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const response = await sync.call("GET /sync/notes");
|
||||
const pathByTitle = Object.fromEntries(response.notes.map((note) => [note.title, note.folderPath]));
|
||||
|
||||
assert.deepEqual(pathByTitle, {
|
||||
Root: "",
|
||||
"In folder": "Sessions",
|
||||
Deep: "Sessions / Arc 1",
|
||||
}, "the module names the journal of a note after its whole folder path");
|
||||
});
|
||||
|
||||
test("renaming a folder moves the notes revision", async () => {
|
||||
const sync = loadSyncRoute({
|
||||
seed: {
|
||||
folders: [{ _id: "folder-1", name: "Sessions", parentFolder: null }],
|
||||
notes: [{ _id: "note-1", title: "Session 1", content: "hi", folder: "folder-1" }],
|
||||
},
|
||||
});
|
||||
|
||||
const before = await sync.call("GET /sync/notes/revision");
|
||||
sync.models["../models/Folder"].rows[0].name = "Chapters";
|
||||
const after = await sync.call("GET /sync/notes/revision");
|
||||
|
||||
assert.notEqual(after.revision, before.revision,
|
||||
"a folder rename has to reach the world as another journal name");
|
||||
});
|
||||
|
||||
test("mapping a note to the page the module made keeps them paired", async () => {
|
||||
const sync = loadSyncRoute({ seed: { notes: [{ _id: "note-1", title: "Session 1", content: "hi" }] } });
|
||||
|
||||
@@ -238,7 +304,7 @@ function writeFoundryPaths(target, data) {
|
||||
return target;
|
||||
}
|
||||
|
||||
function makeWorld({ markdown = true } = {}) {
|
||||
function makeWorld() {
|
||||
const state = {
|
||||
hooks: new Map(),
|
||||
registered: new Map(),
|
||||
@@ -248,6 +314,8 @@ function makeWorld({ markdown = true } = {}) {
|
||||
// What Dragonroll answers the notes reconcile with. Mapping a page answers
|
||||
// like the real backend: the note keeps the page id, so later reads carry it.
|
||||
remoteNotes: [],
|
||||
rollMessages: [],
|
||||
clickListeners: [],
|
||||
nextId: 1,
|
||||
};
|
||||
|
||||
@@ -261,6 +329,7 @@ function makeWorld({ markdown = true } = {}) {
|
||||
text: { content: data.text?.content ?? "" },
|
||||
flags: data.flags ?? {},
|
||||
writes: 0,
|
||||
get uuid() { return `JournalEntry.${journal.id}.JournalEntryPage.${this.id}`; },
|
||||
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
||||
async update(update) {
|
||||
page.writes += 1;
|
||||
@@ -282,9 +351,14 @@ function makeWorld({ markdown = true } = {}) {
|
||||
name: data.name,
|
||||
documentName: "JournalEntry",
|
||||
flags: data.flags ?? {},
|
||||
get uuid() { return `JournalEntry.${this.id}`; },
|
||||
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
||||
pages: { contents: pages, get: (id) => pages.find((page) => page.id === id) },
|
||||
async update(update) { return writeFoundryPaths(this, update); },
|
||||
async delete() {
|
||||
const index = journals.indexOf(this);
|
||||
if (index >= 0) journals.splice(index, 1);
|
||||
},
|
||||
async createEmbeddedDocuments(documentName, docs) {
|
||||
assert.equal(documentName, "JournalEntryPage", "the notes' pages are journal pages");
|
||||
// Foundry's own page validation refuses a page without a name.
|
||||
@@ -302,6 +376,26 @@ function makeWorld({ markdown = true } = {}) {
|
||||
URL,
|
||||
CONFIG: {},
|
||||
window: { location: { origin: "http://vtt.test" } },
|
||||
document: {
|
||||
addEventListener(name, fn) {
|
||||
if (name === "click") state.clickListeners.push(fn);
|
||||
},
|
||||
},
|
||||
Roll: class FakeRoll {
|
||||
constructor(formula) {
|
||||
this.formula = formula;
|
||||
this.evaluated = false;
|
||||
}
|
||||
async evaluate() {
|
||||
this.evaluated = true;
|
||||
return this;
|
||||
}
|
||||
async toMessage(data) {
|
||||
assert.equal(this.evaluated, true, "the roll is evaluated before it reaches chat");
|
||||
state.rollMessages.push({ formula: this.formula, ...data });
|
||||
}
|
||||
},
|
||||
ChatMessage: { getSpeaker: () => ({ alias: "GM" }) },
|
||||
ui: { notifications: { info() {}, warn() {}, error() {} } },
|
||||
Hooks: {
|
||||
once(name, fn) { state.hooks.set(name, [fn]); },
|
||||
@@ -330,6 +424,19 @@ function makeWorld({ markdown = true } = {}) {
|
||||
if (note) note.foundryPageId = body.foundryPageId;
|
||||
return { ok: true, status: 200, json: async () => ({ status: "ok", note }) };
|
||||
}
|
||||
// The cheap change check: a hash of the notes' content, so changing
|
||||
// `remoteNotes` (and nothing else) is what makes the module pull them over,
|
||||
// like the backend hashing the campaign's notes does.
|
||||
if (href.includes("foundry/sync/notes/revision")) {
|
||||
const revision = state.remoteNotes
|
||||
.map((note) => [
|
||||
note._id, note.title ?? "", note.content ?? "",
|
||||
note.folder ?? "", note.folderPath ?? "",
|
||||
].join("\u0000"))
|
||||
.sort()
|
||||
.join("\u0001");
|
||||
return { ok: true, status: 200, json: async () => ({ status: "ok", revision }) };
|
||||
}
|
||||
if (href.includes("foundry/sync/notes")) {
|
||||
return { ok: true, status: 200, json: async () => ({ status: "ok", notes: state.remoteNotes }) };
|
||||
}
|
||||
@@ -345,8 +452,6 @@ function makeWorld({ markdown = true } = {}) {
|
||||
},
|
||||
},
|
||||
};
|
||||
if (markdown) sandbox.TextEditor = { _getMarkdown: (md) => `<marked>${md}</marked>` };
|
||||
|
||||
sandbox.game = {
|
||||
user: { isGM: true },
|
||||
world: { id: "world-1", title: "Test World" },
|
||||
@@ -355,7 +460,7 @@ function makeWorld({ markdown = true } = {}) {
|
||||
actors: { contents: [], get: () => null },
|
||||
items: { contents: [], get: () => null },
|
||||
folders: { contents: [], get: () => null },
|
||||
journals: { contents: journals, get: (id) => journals.find((journal) => journal.id === id) },
|
||||
journal: { contents: journals, get: (id) => journals.find((journal) => journal.id === id) },
|
||||
settings: {
|
||||
register(module, key, definition) {
|
||||
state.registered.set(key, definition);
|
||||
@@ -386,6 +491,9 @@ function makeWorld({ markdown = true } = {}) {
|
||||
};
|
||||
state.mapNoteRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/map-note"));
|
||||
state.notesReads = () => state.requests.filter((request) => request.href.includes("foundry/sync/notes"));
|
||||
// The full note pulls, not the cheap revision pings the change check makes.
|
||||
state.notesPulls = () => state.requests.filter((request) =>
|
||||
request.href.includes("foundry/sync/notes") && !request.href.includes("/revision"));
|
||||
|
||||
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
|
||||
state.fire = async (name, ...args) => {
|
||||
@@ -407,6 +515,19 @@ function makeWorld({ markdown = true } = {}) {
|
||||
for (const interval of [...state.intervals.values()]) await interval.fn();
|
||||
await drain();
|
||||
};
|
||||
// Press a dice button the journal drew: the module listens on the document and
|
||||
// finds the button through `closest`, like a click inside a journal page.
|
||||
state.clickRoll = async (formula) => {
|
||||
const button = { dataset: { dragonrollRoll: formula } };
|
||||
const event = {
|
||||
target: { closest: (selector) => (selector === "[data-dragonroll-roll]" ? button : null) },
|
||||
defaultPrevented: false,
|
||||
preventDefault() { this.defaultPrevented = true; },
|
||||
};
|
||||
for (const listener of state.clickListeners) await listener(event);
|
||||
await drain();
|
||||
return event;
|
||||
};
|
||||
state.linkedSetup = async () => {
|
||||
await state.fire("init");
|
||||
await state.fire("ready");
|
||||
@@ -433,9 +554,9 @@ test("the campaign's notes become pages of one Dragonroll journal", async () =>
|
||||
const journal = world.journals()[0];
|
||||
assert.equal(journal.name, "Dragonroll");
|
||||
assert.deepEqual(journal.pages.contents.map((page) => [page.name, page.text.content]), [
|
||||
["Session 1", "<marked>**The start**</marked>"],
|
||||
["Tavern Brawl", "<marked>A rope, a chandelier.</marked>"],
|
||||
], "each note is a page, its markdown rendered by Foundry's own renderer");
|
||||
["Session 1", "<p><strong>The start</strong></p>"],
|
||||
["Tavern Brawl", "<p>A rope, a chandelier.</p>"],
|
||||
], "each note is a page, its markdown drawn into the page's HTML");
|
||||
assert.deepEqual(journal.pages.contents.map((page) => page.getFlag(MODULE_ID, "noteId")), ["note-1", "note-2"],
|
||||
"each page keeps the note it stands for");
|
||||
assert.deepEqual(world.mapNoteRequests().map((request) => [request.body.noteId, request.body.foundryPageId]), [
|
||||
@@ -444,6 +565,66 @@ test("the campaign's notes become pages of one Dragonroll journal", async () =>
|
||||
], "and the campaign remembers each note's page");
|
||||
});
|
||||
|
||||
test("notes in a folder share the journal named after its path", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [
|
||||
sessionNote(),
|
||||
{ _id: "note-2", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
|
||||
{ _id: "note-3", title: "The cave", content: "dark", folder: "folder-2", folderPath: "Sessions / Arc 1" },
|
||||
];
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
const byName = new Map(world.journals().map((journal) => [journal.name, journal]));
|
||||
assert.deepEqual([...byName.keys()].sort(), ["Dragonroll", "Sessions", "Sessions / Arc 1"],
|
||||
"the root notes and each folder path get a journal of their own");
|
||||
assert.deepEqual(byName.get("Dragonroll").pages.contents.map((page) => page.name), ["Session 1"]);
|
||||
assert.deepEqual(byName.get("Sessions").pages.contents.map((page) => page.name), ["The road"]);
|
||||
assert.deepEqual(byName.get("Sessions / Arc 1").pages.contents.map((page) => page.name), ["The cave"],
|
||||
"a subfolder's notes stand in a journal named after the whole path");
|
||||
assert.equal(byName.get("Sessions").getFlag(MODULE_ID, "notesFolder"), "folder-1",
|
||||
"each folder journal keeps the folder it belongs to");
|
||||
assert.equal(byName.get("Sessions / Arc 1").getFlag(MODULE_ID, "notesFolder"), "folder-2");
|
||||
});
|
||||
|
||||
test("renaming a folder renames its journal", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [
|
||||
{ _id: "note-1", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
|
||||
];
|
||||
await world.runIntervals();
|
||||
|
||||
world.remoteNotes = [{ ...world.remoteNotes[0], folderPath: "Chapters" }];
|
||||
await world.runIntervals();
|
||||
|
||||
assert.deepEqual(world.journals().map((journal) => journal.name), ["Chapters"],
|
||||
"the journal follows the folder's path without being made again");
|
||||
assert.equal(world.journals()[0].pages.contents.length, 1, "and its page stays where it was");
|
||||
});
|
||||
|
||||
test("a note moved to another folder takes its page to that folder's journal", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [
|
||||
{ _id: "note-1", title: "The road", content: "east", folder: "folder-1", folderPath: "Sessions" },
|
||||
];
|
||||
await world.runIntervals();
|
||||
|
||||
const firstPage = world.journals()[0].pages.contents[0];
|
||||
world.remoteNotes = [{
|
||||
...world.remoteNotes[0],
|
||||
folder: "folder-2",
|
||||
folderPath: "Sessions / Arc 1",
|
||||
}];
|
||||
await world.runIntervals();
|
||||
|
||||
assert.deepEqual(world.journals().map((journal) => journal.name), ["Sessions / Arc 1"],
|
||||
"the journal the note left goes when it has nothing else in it");
|
||||
const moved = world.journals()[0].pages.contents[0];
|
||||
assert.equal(moved.name, "The road");
|
||||
assert.notEqual(moved.id, firstPage.id, "the page is made in the journal the note moved to");
|
||||
assert.equal(world.remoteNotes[0].foundryPageId, moved.id, "and the campaign maps the note to its new page");
|
||||
});
|
||||
|
||||
test("reconciling again does not double the journal or its pages", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [sessionNote(), tavernNote()];
|
||||
@@ -469,6 +650,38 @@ test("an existing journal named Dragonroll is used, not doubled", async () => {
|
||||
assert.equal(gmsOwn.getFlag(MODULE_ID, "notesJournal"), true, "and it is marked, so renaming it keeps the notes' home findable");
|
||||
});
|
||||
|
||||
test("extra journals named Dragonroll are removed before the notes are written", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
const kept = world.addJournal("Dragonroll", { [MODULE_ID]: { notesJournal: true } });
|
||||
const gmDuplicate = world.addJournal("Dragonroll");
|
||||
const flaggedDuplicate = world.addJournal("Dragonroll", { [MODULE_ID]: { notesJournal: true } });
|
||||
const unrelated = world.addJournal("Session Log");
|
||||
|
||||
world.remoteNotes = [sessionNote()];
|
||||
await world.runIntervals();
|
||||
|
||||
assert.deepEqual(world.journals(), [kept, unrelated],
|
||||
"only the journal the reconcile writes into survives, beside the GM's other journals");
|
||||
assert.deepEqual(kept.pages.contents.map((page) => page.name), ["Session 1"]);
|
||||
assert.equal(gmDuplicate.pages.contents.length, 0);
|
||||
assert.equal(flaggedDuplicate.pages.contents.length, 0);
|
||||
assert.ok(unrelated, "a journal of another name is left alone");
|
||||
});
|
||||
|
||||
test("several journals named Dragonroll collapse into the first one", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
const first = world.addJournal("Dragonroll");
|
||||
world.addJournal("Dragonroll");
|
||||
world.addJournal("Dragonroll");
|
||||
|
||||
world.remoteNotes = [sessionNote()];
|
||||
await world.runIntervals();
|
||||
|
||||
assert.deepEqual(world.journals(), [first], "the duplicates go, the first one stays the notes' home");
|
||||
assert.deepEqual(first.pages.contents.map((page) => page.name), ["Session 1"]);
|
||||
assert.equal(first.getFlag(MODULE_ID, "notesJournal"), true);
|
||||
});
|
||||
|
||||
test("a note edited in Dragonroll rewrites its page", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [sessionNote()];
|
||||
@@ -481,7 +694,7 @@ test("a note edited in Dragonroll rewrites its page", async () => {
|
||||
const journal = world.journals()[0];
|
||||
assert.equal(journal.pages.contents.length, 1, "the note still stands as the same single page");
|
||||
assert.deepEqual(journal.pages.contents[0].name, "Session 1 — revisited");
|
||||
assert.equal(journal.pages.contents[0].text.content, "<marked>**A different start**</marked>");
|
||||
assert.equal(journal.pages.contents[0].text.content, "<p><strong>A different start</strong></p>");
|
||||
assert.equal(world.mapNoteRequests().length, 1, "the pairing the world reads back needs no remapping");
|
||||
});
|
||||
|
||||
@@ -511,6 +724,43 @@ test("pages already in step with the campaign are not rewritten", async () => {
|
||||
assert.equal(page.writes, 0, "a reconcile that changes nothing leaves the page alone");
|
||||
});
|
||||
|
||||
test("an unchanged campaign is not pulled over again", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [sessionNote()];
|
||||
await world.runIntervals();
|
||||
assert.equal(world.notesPulls().length, 1, "the first reconcile pulls the notes");
|
||||
|
||||
await world.runIntervals();
|
||||
assert.equal(world.notesPulls().length, 1,
|
||||
"with the revision and the journal unchanged, only the cheap revision is asked for");
|
||||
});
|
||||
|
||||
test("a page a GM edited is written back from the campaign's note", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [sessionNote()];
|
||||
await world.runIntervals();
|
||||
|
||||
const page = world.journals()[0].pages.contents[0];
|
||||
page.name = "GM renamed it";
|
||||
page.text.content = "GM wrote this";
|
||||
await world.runIntervals();
|
||||
|
||||
assert.equal(page.name, "Session 1", "the campaign's title is written back over the GM's");
|
||||
assert.equal(page.text.content, "<p><strong>The start</strong></p>", "and so is its content");
|
||||
});
|
||||
|
||||
test("a journal page a GM removed is built again from the campaign's note", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [sessionNote()];
|
||||
await world.runIntervals();
|
||||
world.journals()[0].pages.contents.length = 0;
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
assert.deepEqual(world.journals()[0].pages.contents.map((entry) => entry.name), ["Session 1"],
|
||||
"the journal holds the note's page again");
|
||||
});
|
||||
|
||||
test("the campaign's page mapping claims a page whose flag was lost", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
const journal = world.addJournal("Dragonroll");
|
||||
@@ -524,8 +774,8 @@ test("the campaign's page mapping claims a page whose flag was lost", async () =
|
||||
assert.equal(orphan.getFlag(MODULE_ID, "noteId"), "note-1", "and the page is marked again");
|
||||
});
|
||||
|
||||
test("without Foundry's markdown renderer the fallback keeps the text legible", async () => {
|
||||
const world = await makeWorld({ markdown: false }).linkedSetup();
|
||||
test("text that is not markdown is escaped, not injected", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [{ _id: "note-1", title: "Session 1", content: "a & b < c\nline two\n\nsecond para" }];
|
||||
|
||||
await world.runIntervals();
|
||||
@@ -533,7 +783,145 @@ test("without Foundry's markdown renderer the fallback keeps the text legible",
|
||||
assert.equal(
|
||||
world.journals()[0].pages.contents[0].text.content,
|
||||
"<p>a & b < c<br />line two</p>\n<p>second para</p>",
|
||||
"escaped paragraphs instead of nothing, until this Foundry offers a renderer",
|
||||
"the raw text is escaped and stays legible",
|
||||
);
|
||||
});
|
||||
|
||||
test("a note's markdown is drawn into the page: headings, lists and marks", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [{
|
||||
_id: "note-1",
|
||||
title: "Session 1",
|
||||
content: "# Session One\n\n## The Tavern\n\n- rope\n- **torch**\n\n> danger\n\n---\n\n`code` and [a link](https://dragonroll.test)",
|
||||
}];
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
assert.equal(
|
||||
world.journals()[0].pages.contents[0].text.content,
|
||||
"<h1>Session One</h1>\n"
|
||||
+ "<h2>The Tavern</h2>\n"
|
||||
+ "<ul>\n<li>rope</li>\n<li><strong>torch</strong></li>\n</ul>\n"
|
||||
+ "<blockquote><p>danger</p></blockquote>\n"
|
||||
+ "<hr />\n"
|
||||
+ "<p><code>code</code> and <a href=\"https://dragonroll.test\">a link</a></p>",
|
||||
"the note is drawn as the elements Foundry's journal styles know",
|
||||
);
|
||||
});
|
||||
|
||||
test("a note's dice widgets become buttons that roll in Foundry", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [{
|
||||
_id: "note-1",
|
||||
title: "Goblin",
|
||||
content: "The goblin attacks with @roll[1d20+4].\n\n@roll\n8d6\n@end",
|
||||
}];
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
const html = world.journals()[0].pages.contents[0].text.content;
|
||||
assert.match(html,
|
||||
/<p>The goblin attacks with <button type="button" class="dragonroll-note-roll" data-dragonroll-roll="1d20\+4" title="Roll 1d20\+4"><i class="fa-solid fa-dice-d20" aria-hidden="true"><\/i><span>1d20\+4<\/span><\/button>\.<\/p>/,
|
||||
"the inline widget is a button showing the expression the note wrote");
|
||||
assert.match(html,
|
||||
/<button type="button" class="dragonroll-note-roll dragonroll-note-roll-block" data-dragonroll-roll="8d6" title="Roll 8d6">/,
|
||||
"the block widget is a button of its own, drawn full width");
|
||||
|
||||
const event = await world.clickRoll("1d20+4");
|
||||
assert.equal(event.defaultPrevented, true, "the click does not navigate the journal");
|
||||
assert.deepEqual(world.rollMessages.map((message) => message.formula), ["1d20+4"],
|
||||
"pressing the button evaluates that expression in Foundry");
|
||||
assert.equal(world.rollMessages[0].speaker.alias, "GM");
|
||||
assert.match(world.rollMessages[0].flavor, /1d20\+4/,
|
||||
"the chat card says the roll came from Dragonroll");
|
||||
});
|
||||
|
||||
test("advantage and disadvantage become Foundry's keep-highest and keep-lowest", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [{
|
||||
_id: "note-1",
|
||||
title: "Rolls",
|
||||
content: "@roll[d20adv] @roll[2d20dis] @roll[4d6kh1]",
|
||||
}];
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
const html = world.journals()[0].pages.contents[0].text.content;
|
||||
assert.match(html, /data-dragonroll-roll="2d20kh1"/, "advantage rolls twice and keeps the higher die");
|
||||
assert.match(html, /data-dragonroll-roll="2d20kl1"/, "disadvantage rolls twice and keeps the lower die");
|
||||
assert.match(html, /data-dragonroll-roll="4d6kh1"/, "a keep-highest expression already reads as Foundry does");
|
||||
});
|
||||
|
||||
test("a dice widget inside a code span stays text", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [{ _id: "note-1", title: "Syntax", content: "`@roll[1d6]`" }];
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
assert.equal(world.journals()[0].pages.contents[0].text.content,
|
||||
"<p><code>@roll[1d6]</code></p>",
|
||||
"code that shows the widget syntax is not turned into a button");
|
||||
});
|
||||
|
||||
// --- Wiki links and embeds in the journal page -----------------------------------
|
||||
|
||||
test("a note's [[links]] and ![[embeds]] become Foundry's own enrichers", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.game.actors.contents.push({ id: "actor-1", name: "Mira", documentName: "Actor" });
|
||||
world.game.items.contents.push({ id: "item-1", name: "Rope of Climbing", documentName: "Item" });
|
||||
world.remoteNotes = [{
|
||||
_id: "note-1",
|
||||
title: "Links",
|
||||
content: "[[Mira]] and ![[Mira]]\n\n[[Rope of Climbing]] and ![[Rope of Climbing]]",
|
||||
}];
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
const html = world.journals()[0].pages.contents[0].text.content;
|
||||
assert.match(html, /@UUID\[Actor\.actor-1\]\{Mira\}/,
|
||||
"a link to a character opens it in Foundry");
|
||||
assert.match(html, /@Embed\[Actor\.actor-1\]\{Mira\}/,
|
||||
"an embedded character is drawn as a sheet preview");
|
||||
assert.match(html, /@UUID\[Item\.item-1\]\{Rope of Climbing\}/,
|
||||
"a link to an item opens it in Foundry");
|
||||
assert.match(html, /@Embed\[Item\.item-1\]\{Rope of Climbing\}/,
|
||||
"an embedded item is drawn as its sheet");
|
||||
});
|
||||
|
||||
test("a name the world does not have is left dimmed, and only sheets can be embedded", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [{
|
||||
_id: "note-1",
|
||||
title: "Missing",
|
||||
content: "[[Nobody]]\n\n![[Nobody]]\n\n![[Tavern Brawl]]",
|
||||
}];
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
const html = world.journals()[0].pages.contents[0].text.content;
|
||||
assert.match(html, /<span class="dragonroll-note-link is-unresolved">Nobody<\/span>/,
|
||||
"an unresolved link still reads, but cannot be opened");
|
||||
assert.match(html, /<span class="dragonroll-note-link is-unresolved">Tavern Brawl<\/span>/,
|
||||
"a note written with the bang is not embedded as a sheet");
|
||||
assert.doesNotMatch(html, /@Embed\[/, "nothing is embedded when there is no character or item");
|
||||
});
|
||||
|
||||
test("a note can link to another note created in the same pull", async () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
world.remoteNotes = [
|
||||
sessionNote({ content: "See [[Tavern Brawl]]." }),
|
||||
tavernNote(),
|
||||
];
|
||||
|
||||
await world.runIntervals();
|
||||
|
||||
const journal = world.journals()[0];
|
||||
const sessionPage = journal.pages.contents.find((page) => page.name === "Session 1");
|
||||
const tavernPage = journal.pages.contents.find((page) => page.name === "Tavern Brawl");
|
||||
assert.match(
|
||||
sessionPage.text.content,
|
||||
new RegExp(`@UUID\\[JournalEntry\\.${journal.id}\\.JournalEntryPage\\.${tavernPage.id}\\]\\{Tavern Brawl\\}`),
|
||||
"the page of the note it points at opens from the link"
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -180,11 +180,16 @@ function makeStubWorld({ autoSync = true } = {}) {
|
||||
}
|
||||
|
||||
async function forceSyncActors(world, ...actorIds) {
|
||||
// Foundry 13+ hands the context menu hook the directory application and the
|
||||
// menu items to mutate; selected entries carry their id on data-entry-id.
|
||||
const entries = actorIds.map((actorId) => ({ dataset: { entryId: actorId } }));
|
||||
const application = { element: { querySelectorAll: () => entries } };
|
||||
const options = [];
|
||||
await world.fire("getActorDirectoryEntryContext", null, options);
|
||||
const entry = options.find((option) => option.name === "Dragonroll: Force Sync");
|
||||
await world.fire("getActorContextOptions", application, options);
|
||||
const entry = options.find((option) => option.label === "Dragonroll: Force Sync");
|
||||
assert.ok(entry, "Dragonroll: Force Sync is offered in the actor directory context menu");
|
||||
await entry.callback(actorIds.map((actorId) => ({ dataset: { actorId } })));
|
||||
assert.ok(!entry.visible || entry.visible(), "the entry is visible for a linked GM world");
|
||||
await entry.onClick(null, entries[0] ?? null);
|
||||
await world.runTimers();
|
||||
}
|
||||
|
||||
|
||||
153
tests/link-autocomplete.test.js
Normal file
153
tests/link-autocomplete.test.js
Normal file
@@ -0,0 +1,153 @@
|
||||
// Tests for the note editor's wiki-link autocomplete (type `[[` while editing a note and the
|
||||
// campaign's notes, actors, items and maps are offered to link to). The rules live in
|
||||
// `frontend/app/services/LinkAutocomplete.js`, which imports nothing, so it is loaded straight from
|
||||
// source; the fetching side, `LinkTargets.js`, is checked by reading it, because it talks to the API
|
||||
// the repository root does not stand up.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
function readRepoFile(...parts) {
|
||||
return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||
}
|
||||
|
||||
function loadLinkAutocomplete() {
|
||||
const source = readRepoFile("frontend", "app", "services", "LinkAutocomplete.js");
|
||||
return new Function(source.replace("export {", "return {"))();
|
||||
}
|
||||
|
||||
const autocomplete = loadLinkAutocomplete();
|
||||
|
||||
// --- Finding the `[[target` the caret is in ---
|
||||
|
||||
test("typing after a [[ opens a trigger with what has been typed so far", () => {
|
||||
assert.deepEqual(autocomplete.FindLinkTrigger("see [[The Wr", 12), { start: 4, query: "The Wr" });
|
||||
assert.deepEqual(autocomplete.FindLinkTrigger("[[", 2), { start: 0, query: "" });
|
||||
assert.deepEqual(autocomplete.FindLinkTrigger("a\n[[Mi", 6), { start: 2, query: "Mi" });
|
||||
});
|
||||
|
||||
test("the trigger starts at the last [[ before the caret", () => {
|
||||
assert.deepEqual(autocomplete.FindLinkTrigger("[[a [[b", 8), { start: 4, query: "b" });
|
||||
});
|
||||
|
||||
test("a link is a single line, so a closed or newlined [[ opens nothing", () => {
|
||||
// Caret after the closing brackets: the link is finished, not being typed.
|
||||
assert.equal(autocomplete.FindLinkTrigger("[[The Inn]] ", 12), null);
|
||||
assert.equal(autocomplete.FindLinkTrigger("[[The\nInn", 9), null);
|
||||
assert.equal(autocomplete.FindLinkTrigger("no brackets here", 15), null);
|
||||
assert.equal(autocomplete.FindLinkTrigger("", 0), null);
|
||||
});
|
||||
|
||||
// --- The entries offered, from the campaign's four lists ---
|
||||
|
||||
test("every named note, actor, item and map becomes a suggestion, sorted by label", () => {
|
||||
const suggestions = autocomplete.BuildLinkSuggestions({
|
||||
notes: [{ _id: "n1", title: "The Wreck" }, { _id: "n2", title: " " }, { _id: "n3", title: "The Inn" }],
|
||||
actors: [{ _id: "a1", name: "Mira" }],
|
||||
items: [{ _id: "i1", name: "Rope" }],
|
||||
maps: [{ _id: "m1", name: "Saltmarsh" }],
|
||||
});
|
||||
|
||||
assert.deepEqual(suggestions, [
|
||||
{ id: "a1", label: "Mira", type: "actor" },
|
||||
{ id: "i1", label: "Rope", type: "item" },
|
||||
{ id: "m1", label: "Saltmarsh", type: "map" },
|
||||
{ id: "n3", label: "The Inn", type: "note" },
|
||||
{ id: "n1", label: "The Wreck", type: "note" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("entries without a name are left out, and a repeated label is offered once", () => {
|
||||
const suggestions = autocomplete.BuildLinkSuggestions({
|
||||
notes: [{ _id: "n1", title: "The Inn" }, { _id: "n2", title: "The Inn" }, { _id: "n3" }],
|
||||
});
|
||||
|
||||
assert.deepEqual(suggestions, [{ id: "n1", label: "The Inn", type: "note" }]);
|
||||
});
|
||||
|
||||
test("a campaign with no lists offers nothing", () => {
|
||||
assert.deepEqual(autocomplete.BuildLinkSuggestions({}), []);
|
||||
assert.deepEqual(autocomplete.BuildLinkSuggestions(undefined), []);
|
||||
});
|
||||
|
||||
// --- Filtering what has been typed ---
|
||||
|
||||
test("the suggestions are filtered accent- and case-insensitively", () => {
|
||||
const suggestions = [{ id: "n1", label: "Café", type: "note" }];
|
||||
assert.equal(autocomplete.FilterLinkSuggestions(suggestions, "cafe").length, 1);
|
||||
assert.equal(autocomplete.FilterLinkSuggestions(suggestions, "CAFÉ").length, 1);
|
||||
assert.equal(autocomplete.FilterLinkSuggestions(suggestions, "tea").length, 0);
|
||||
});
|
||||
|
||||
test("labels that start with what was typed come before the ones that only contain it", () => {
|
||||
const suggestions = [
|
||||
{ id: "n1", label: "The Inn", type: "note" },
|
||||
{ id: "n2", label: "Innkeeper", type: "note" },
|
||||
];
|
||||
|
||||
assert.deepEqual(
|
||||
autocomplete.FilterLinkSuggestions(suggestions, "inn").map((s) => s.label),
|
||||
["Innkeeper", "The Inn"]
|
||||
);
|
||||
});
|
||||
|
||||
test("an empty query offers the entries, capped so the menu stays short", () => {
|
||||
const many = Array.from({ length: 60 }, (_, i) => ({ id: `n${i}`, label: `Note ${i}`, type: "note" }));
|
||||
|
||||
assert.equal(autocomplete.FilterLinkSuggestions(many, "").length, 50);
|
||||
assert.equal(autocomplete.FilterLinkSuggestions([], "").length, 0);
|
||||
});
|
||||
|
||||
// --- What is written when an entry is chosen ---
|
||||
|
||||
test("choosing an entry writes [[label]] and leaves the caret after the closing brackets", () => {
|
||||
const trigger = autocomplete.FindLinkTrigger("see [[The Wr", 12);
|
||||
const result = autocomplete.InsertLinkSuggestion("see [[The Wr", trigger, { label: "The Wreck" });
|
||||
|
||||
assert.equal(result.text, "see [[The Wreck]]");
|
||||
assert.equal(result.caret, 17);
|
||||
});
|
||||
|
||||
test("only the trigger is replaced, the note around it is kept", () => {
|
||||
const trigger = autocomplete.FindLinkTrigger("a [[M b", 5);
|
||||
const result = autocomplete.InsertLinkSuggestion("a [[M b", trigger, { label: "Mira" });
|
||||
|
||||
assert.equal(result.text, "a [[Mira]] b");
|
||||
assert.equal(result.text.slice(0, result.caret) + "|" + result.text.slice(result.caret), "a [[Mira]]| b");
|
||||
});
|
||||
|
||||
// --- The editor, the fetch and the menu are wired together ---
|
||||
|
||||
function wiringTests() {
|
||||
const note = readRepoFile("frontend", "app", "components", "viewer", "content", "Note.vue");
|
||||
const targets = readRepoFile("frontend", "app", "services", "LinkTargets.js");
|
||||
|
||||
test("the editor offers links through the service and the shared menu", () => {
|
||||
assert.match(note, /from '~\/services\/LinkAutocomplete'/, "the editor reads the link autocomplete service");
|
||||
assert.match(note, /from '~\/services\/LinkTargets'/, "…and the one that fetches the entries");
|
||||
assert.match(note, /<SuggestionMenu/, "widgets and links share one menu");
|
||||
assert.match(note, /@select="applySuggestion"/);
|
||||
});
|
||||
|
||||
test("the entries a note can link to are the campaign's four lists", () => {
|
||||
for (const path of ["/note/all", "/actor/list", "/item/list", "/map/list"]) {
|
||||
assert.ok(targets.includes(path), `the link entries do not read ${path}`);
|
||||
}
|
||||
assert.match(targets, /CACHE_TTL/, "the four lists are cached instead of fetched per keystroke");
|
||||
});
|
||||
|
||||
test("the link menu names its section in every locale", () => {
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const sections = JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "campaigns.json")).sections;
|
||||
for (const type of ["note", "actor", "item", "map"]) {
|
||||
assert.ok(sections[`${type}s`], `${locale} has no label for the ${type} section`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
wiringTests();
|
||||
157
tests/note-links.test.js
Normal file
157
tests/note-links.test.js
Normal file
@@ -0,0 +1,157 @@
|
||||
// Tests for the `[[…]]` links a note shows in display mode: the link carries the entry's name, the
|
||||
// note resolves it against the campaign's lists, and a character or item link previews its sheet
|
||||
// before opening it. The label lookup is the pure part of `LinkAutocomplete.js`, loaded straight
|
||||
// from source; the rest is checked by reading the files that wire it together.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
function readRepoFile(...parts) {
|
||||
return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||
}
|
||||
|
||||
function loadLinkAutocomplete() {
|
||||
const source = readRepoFile("frontend", "app", "services", "LinkAutocomplete.js");
|
||||
return new Function(source.replace("export {", "return {"))();
|
||||
}
|
||||
|
||||
const autocomplete = loadLinkAutocomplete();
|
||||
|
||||
// --- Finding the entry a written link points at ---
|
||||
|
||||
test("a link resolves to the entry whose label it carries", () => {
|
||||
const targets = [
|
||||
{ id: "a1", label: "Mira", type: "actor" },
|
||||
{ id: "i1", label: "Rope of Climbing", type: "item" },
|
||||
];
|
||||
|
||||
assert.deepEqual(autocomplete.FindLinkTarget(targets, "Mira"), targets[0]);
|
||||
assert.deepEqual(autocomplete.FindLinkTarget(targets, "Rope of Climbing"), targets[1]);
|
||||
});
|
||||
|
||||
test("the lookup forgives case, accents and surrounding spaces", () => {
|
||||
const targets = [{ id: "a1", label: "Café", type: "actor" }];
|
||||
|
||||
assert.equal(autocomplete.FindLinkTarget(targets, "cafe")?.id, "a1");
|
||||
assert.equal(autocomplete.FindLinkTarget(targets, " CAFÉ ")?.id, "a1");
|
||||
});
|
||||
|
||||
test("a link that no longer matches anything resolves to null", () => {
|
||||
const targets = [{ id: "a1", label: "Mira", type: "actor" }];
|
||||
|
||||
assert.equal(autocomplete.FindLinkTarget(targets, "Mira the Bold"), null);
|
||||
assert.equal(autocomplete.FindLinkTarget(targets, " "), null);
|
||||
assert.equal(autocomplete.FindLinkTarget(undefined, "Mira"), null);
|
||||
});
|
||||
|
||||
// --- The rendered link, the resolver and the preview are wired together ---
|
||||
|
||||
test("the markdown renders the link's label instead of a placeholder", () => {
|
||||
const marker = readRepoFile("frontend", "app", "services", "Marker.js");
|
||||
const link = marker.slice(marker.indexOf("const linkExtension"), marker.indexOf("marker.use"));
|
||||
|
||||
assert.match(link, /class="vue-link"/, "the link keeps the class the note binds to");
|
||||
assert.match(link, /data-href=/, "…and the label it points at");
|
||||
assert.match(link, /token\.link/, "the label is the link's text");
|
||||
assert.doesNotMatch(link, />Link</, "the link does not show a generic placeholder");
|
||||
});
|
||||
|
||||
test("the entry lists are shared by the autocomplete, the resolver and the preview", () => {
|
||||
const targets = readRepoFile("frontend", "app", "services", "LinkTargets.js");
|
||||
|
||||
for (const type of ["note", "actor", "item", "map"]) {
|
||||
assert.ok(targets.includes(`${type}:`), `the link targets do not cover ${type}s`);
|
||||
}
|
||||
assert.match(targets, /LoadLinkEntry/, "the preview needs the entry itself, not only its label");
|
||||
assert.match(targets, /CACHE_TTL/, "the four lists are still cached");
|
||||
});
|
||||
|
||||
test("the note binds its rendered links to the preview and the sheet windows", () => {
|
||||
const note = readRepoFile("frontend", "app", "components", "viewer", "content", "Note.vue");
|
||||
|
||||
assert.match(note, /FindLinkTarget/, "the note resolves the label it renders");
|
||||
assert.match(note, /LoadLinkEntry/, "…and asks for the entry to preview");
|
||||
assert.match(note, /classList\.add\('is-resolved'\)/, "resolved links are marked");
|
||||
assert.match(note, /classList\.add\('is-unresolved'\)/, "a link to a deleted entry is marked too");
|
||||
assert.match(note, /<LinkPreview/, "the preview card is drawn by the note");
|
||||
assert.match(note, /'character_sheet'/, "a character link opens its sheet");
|
||||
assert.match(note, /'item_sheet'/, "an item link opens its sheet");
|
||||
assert.match(note, /CreateWindow\(windowType/, "…through the same window the sidebar opens");
|
||||
assert.match(note, /AnchorMap/, "a map link anchors the map like the sidebar does");
|
||||
});
|
||||
|
||||
test("the preview card tells a character from an item", () => {
|
||||
const preview = readRepoFile("frontend", "app", "components", "viewer", "content", "LinkPreview.vue");
|
||||
|
||||
assert.match(preview, /target\.value\.type === 'actor'/);
|
||||
assert.match(preview, /target\.value\.type === 'item'/);
|
||||
assert.match(preview, /campaigns\.link-preview\.open-character/);
|
||||
assert.match(preview, /campaigns\.link-preview\.open-item/);
|
||||
assert.match(preview, /armorClass/, "the character preview reads the sheet's vitals");
|
||||
});
|
||||
|
||||
// --- `![[…]]`: the entry itself, drawn in the note ---
|
||||
|
||||
test("the editor's link menu also completes an embed", () => {
|
||||
// The trigger starts at the `[[`, so the bang typed before it is kept.
|
||||
const trigger = autocomplete.FindLinkTrigger("see ![[Mir", 10);
|
||||
assert.deepEqual(trigger, { start: 5, query: "Mir" });
|
||||
|
||||
const result = autocomplete.InsertLinkSuggestion("see ![[Mir", trigger, { label: "Mira" });
|
||||
assert.equal(result.text, "see ![[Mira]]");
|
||||
});
|
||||
|
||||
test("the bang writes an embed token, and the embed is tried before the plain link", () => {
|
||||
const marker = readRepoFile("frontend", "app", "services", "Marker.js");
|
||||
const embed = marker.slice(marker.indexOf("const embedExtension"), marker.indexOf("const linkExtension"));
|
||||
|
||||
assert.match(embed, /!\\\[\\\[/, "the token starts with a bang");
|
||||
assert.match(embed, /class="vue-embed"/, "the note mounts something other than a link");
|
||||
assert.match(embed, /data-href=/, "…for the label that was written");
|
||||
assert.doesNotMatch(embed, /class="vue-link"/);
|
||||
|
||||
const registration = marker.slice(marker.indexOf("marker.use"));
|
||||
assert.ok(
|
||||
registration.indexOf("embedExtension") < registration.indexOf("linkExtension"),
|
||||
"the embed tokenizer has to run before the link one"
|
||||
);
|
||||
});
|
||||
|
||||
test("the note mounts an embedded entry the way it mounts a widget", () => {
|
||||
const note = readRepoFile("frontend", "app", "components", "viewer", "content", "Note.vue");
|
||||
|
||||
assert.match(note, /import EmbeddedEntry from '\.\/EmbeddedEntry\.vue'/);
|
||||
assert.match(note, /querySelectorAll\('\.vue-embed'\)/, "the placeholders Marker left are found");
|
||||
assert.match(note, /createApp\(EmbeddedEntry,\s*\{\s*href:/, "each one becomes a card of its own");
|
||||
assert.match(note, /mountEmbeds\(\)/, "…and is mounted with the note");
|
||||
assert.match(note, /mountedApps\.push\(app\)/, "so it is unmounted when the note re-renders");
|
||||
});
|
||||
|
||||
test("an embed draws the sheet inline and opens the full one", () => {
|
||||
const embed = readRepoFile("frontend", "app", "components", "viewer", "content", "EmbeddedEntry.vue");
|
||||
|
||||
assert.match(embed, /FindLinkTarget/, "the label is resolved exactly like a link");
|
||||
assert.match(embed, /LoadLinkEntry/, "…and its entry read from the campaign lists");
|
||||
assert.match(embed, /target\.value\?\.type === 'actor'/, "a character gets its sheet");
|
||||
assert.match(embed, /target\.value\?\.type === 'item'/, "an item gets its description");
|
||||
assert.match(embed, /armorClass/, "the character card carries the sheet's vitals");
|
||||
assert.match(embed, /abilityScores/, "…and the ability scores");
|
||||
assert.match(embed, /entry\.description/, "the item card carries the description");
|
||||
assert.match(embed, /CreateWindow\(windowType/, "the full sheet opens from the card");
|
||||
});
|
||||
|
||||
test("the preview strings exist in every locale", () => {
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const strings = JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "campaigns.json"));
|
||||
const preview = strings["link-preview"];
|
||||
assert.ok(preview, `${locale} has no link preview strings`);
|
||||
|
||||
for (const key of ["open-character", "open-item", "no-description", "not-found", "close"]) {
|
||||
assert.ok(preview[key], `${locale} has no link-preview.${key}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
148
tests/widget-autocomplete.test.js
Normal file
148
tests/widget-autocomplete.test.js
Normal file
@@ -0,0 +1,148 @@
|
||||
// Tests for the note editor's widget autocomplete (type `@` while editing a note and the widgets of
|
||||
// Marker.js are offered to insert). The rules live in `frontend/app/services/WidgetAutocomplete.js`,
|
||||
// which imports nothing, so it is loaded straight from source the way the other tests load the
|
||||
// frontend services; the repository root installs no dependencies, so `new Function` is enough.
|
||||
//
|
||||
// The last checks read the editor and the dropdown, because there the wiring itself is what has to
|
||||
// stay right: the textarea asks the service, the registry comes from Marker.js, and the two strings
|
||||
// the dropdown shows exist in every locale.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
function readRepoFile(...parts) {
|
||||
return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||
}
|
||||
|
||||
function loadWidgetAutocomplete() {
|
||||
const source = readRepoFile("frontend", "app", "services", "WidgetAutocomplete.js");
|
||||
return new Function(source.replace("export {", "return {"))();
|
||||
}
|
||||
|
||||
const autocomplete = loadWidgetAutocomplete();
|
||||
|
||||
// --- Finding the `@name` the caret is in ---
|
||||
|
||||
test("typing after an @ opens a trigger with what has been typed so far", () => {
|
||||
assert.deepEqual(autocomplete.FindWidgetTrigger("hello @ro", 9), { start: 6, query: "ro" });
|
||||
assert.deepEqual(autocomplete.FindWidgetTrigger("@", 1), { start: 0, query: "" });
|
||||
assert.deepEqual(autocomplete.FindWidgetTrigger("@roll", 5), { start: 0, query: "roll" });
|
||||
assert.deepEqual(autocomplete.FindWidgetTrigger("a\n@r", 4), { start: 2, query: "r" });
|
||||
});
|
||||
|
||||
test("the trigger is the token under the caret, not the rest of the note", () => {
|
||||
// Caret sits after `@ro`, with more text after it: only the token is replaced later.
|
||||
assert.deepEqual(autocomplete.FindWidgetTrigger("@ro b", 3), { start: 0, query: "ro" });
|
||||
});
|
||||
|
||||
test("an @ inside a word does not open the menu", () => {
|
||||
// An email address should never pop the widget list open.
|
||||
assert.equal(autocomplete.FindWidgetTrigger("user@example", 12), null);
|
||||
assert.equal(autocomplete.FindWidgetTrigger("x@ro", 4), null);
|
||||
});
|
||||
|
||||
test("a caret away from any @ finds no trigger", () => {
|
||||
assert.equal(autocomplete.FindWidgetTrigger("just some text", 5), null);
|
||||
assert.equal(autocomplete.FindWidgetTrigger("", 0), null);
|
||||
});
|
||||
|
||||
// --- The widgets offered, from Marker's registry ---
|
||||
|
||||
test("every registered widget is offered, once per way of writing it", () => {
|
||||
const registry = { inline: ["roll"], display: ["roll"] };
|
||||
assert.deepEqual(autocomplete.BuildWidgetSuggestions(registry), [
|
||||
{ name: "roll", type: "inline" },
|
||||
{ name: "roll", type: "display" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("a registry with no widgets offers nothing", () => {
|
||||
assert.deepEqual(autocomplete.BuildWidgetSuggestions({}), []);
|
||||
assert.deepEqual(autocomplete.BuildWidgetSuggestions(undefined), []);
|
||||
});
|
||||
|
||||
test("the suggestions are filtered by the prefix that has been typed", () => {
|
||||
const suggestions = [
|
||||
{ name: "roll", type: "inline" },
|
||||
{ name: "roll", type: "display" },
|
||||
{ name: "table", type: "display" },
|
||||
];
|
||||
|
||||
assert.equal(autocomplete.FilterWidgetSuggestions(suggestions, "").length, 3);
|
||||
assert.deepEqual(autocomplete.FilterWidgetSuggestions(suggestions, "ro"), [
|
||||
{ name: "roll", type: "inline" },
|
||||
{ name: "roll", type: "display" },
|
||||
]);
|
||||
assert.deepEqual(autocomplete.FilterWidgetSuggestions(suggestions, "zz"), []);
|
||||
});
|
||||
|
||||
// --- What is written when a widget is chosen ---
|
||||
|
||||
test("choosing an inline widget writes it with the caret between the brackets", () => {
|
||||
// "hit @ro" (caret at the end) becomes "hit @roll[]" with the caret before "]".
|
||||
const trigger = autocomplete.FindWidgetTrigger("hit @ro", 7);
|
||||
const result = autocomplete.InsertWidgetSuggestion("hit @ro", trigger, { name: "roll", type: "inline" });
|
||||
|
||||
assert.equal(result.text, "hit @roll[]");
|
||||
assert.equal(result.caret, 10);
|
||||
assert.equal(result.text.slice(0, result.caret) + "|" + result.text.slice(result.caret), "hit @roll[|]");
|
||||
});
|
||||
|
||||
test("choosing a block widget writes it with the caret on the blank line", () => {
|
||||
const trigger = autocomplete.FindWidgetTrigger("@ro", 3);
|
||||
const result = autocomplete.InsertWidgetSuggestion("@ro", trigger, { name: "roll", type: "display" });
|
||||
|
||||
assert.equal(result.text, "@roll\n\n@end");
|
||||
assert.equal(result.caret, 6);
|
||||
assert.equal(result.text.slice(0, result.caret) + "|" + result.text.slice(result.caret), "@roll\n|\n@end");
|
||||
});
|
||||
|
||||
test("only the trigger is replaced, the note around it is kept", () => {
|
||||
const trigger = autocomplete.FindWidgetTrigger("a @ro b", 5);
|
||||
const result = autocomplete.InsertWidgetSuggestion("a @ro b", trigger, { name: "roll", type: "inline" });
|
||||
|
||||
assert.equal(result.text, "a @roll[] b");
|
||||
});
|
||||
|
||||
// --- The editor and the dropdown are wired together ---
|
||||
|
||||
function wiringTests() {
|
||||
const note = readRepoFile("frontend", "app", "components", "viewer", "content", "Note.vue");
|
||||
const menu = readRepoFile("frontend", "app", "components", "viewer", "content", "SuggestionMenu.vue");
|
||||
const marker = readRepoFile("frontend", "app", "services", "Marker.js");
|
||||
const textarea = /<textarea[^>]*class="full-editor"[^>]*>/.exec(note)?.[0];
|
||||
|
||||
test("the editing textarea drives the suggestions from its own text and caret", () => {
|
||||
assert.ok(textarea, "expected the note editor's textarea");
|
||||
assert.match(textarea, /@input="onEditorInput"/);
|
||||
assert.match(textarea, /@keydown="onEditorKeydown"/);
|
||||
assert.match(note, /from '~\/services\/WidgetAutocomplete'/, "the editor reads the autocomplete service");
|
||||
});
|
||||
|
||||
test("the suggestion menu is drawn while editing", () => {
|
||||
assert.match(note, /<SuggestionMenu[\s\S]*v-if="suggestions\.length"/, "the menu is shown only when there is something to offer");
|
||||
assert.match(note, /@select="applySuggestion"/, "choosing an entry inserts it");
|
||||
assert.match(menu, /@mousedown\.prevent="emit\('select', suggestion\)"/, "a click does not blur the textarea before it lands");
|
||||
});
|
||||
|
||||
test("the widgets shown come from Marker's registry, not a second hand-kept list", () => {
|
||||
assert.match(marker, /const GetWidgetRegistry/, "Marker exposes the widget registry");
|
||||
assert.match(marker, /export \{ ParseMarkdown, GetWidget, GetWidgetRegistry \}/);
|
||||
assert.match(note, /BuildWidgetSuggestions\(GetWidgetRegistry\(\)\)/, "the editor builds its menu from the registry");
|
||||
});
|
||||
|
||||
test("the dropdown's two labels exist in every locale", () => {
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const strings = JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "general.json"));
|
||||
for (const type of ["inline", "display"]) {
|
||||
assert.ok(strings.widgets?.[type], `${locale} has no label for a ${type} widget`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
wiringTests();
|
||||
Reference in New Issue
Block a user