// Tests for item folders following the Foundry world into the campaign // (Syndria98/dragonroll#44): the world's item directory is grouped into folders, and // Dragonroll mirrors that tree as Folders of target 'item' and files the synced items // in them, so its item list reads like the world's. And for those folders' colours // going both ways (Syndria98/dragonroll#57): the world's colour arrives with its tree, // and the one the campaign picks travels back on the folder list the module reads. // // The repository root installs no dependencies, so each side is loaded the way the // other tests do it. The sync route runs against a stubbed `require` (express, // mongoose and the models answer with plain objects and a small filter matcher): // that keeps the tree, the filing and the pruning observable without a database. The // Foundry module is loaded into a `node:vm` context holding stubbed Foundry globals // (`game.folders` included) with fake timers, like tests/foundry-sync-toggle.test.js. // The grouping of the sidebar list lives in a plain ES module and is read as text. // // 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 vm = require("node:vm"); const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8"); const repoRequire = (relative) => require(path.join(__dirname, "..", relative)); // --- The sync route against stubbed models ------------------------------------- // A mongoose query answers whatever `await query` and `query.lean()` answer with, and // lets `select()`, `sort()` and `limit()` sit in between. function mongooseQuery(value) { const result = { select: () => result, sort: () => result, limit: (count) => mongooseQuery(value.slice(0, count)), lean: () => Promise.resolve(value), then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected), }; return result; } // Enough of the query language the item folder sync uses: equality, $or, $in, $nin, // $exists. Anything else is a filter this test did not expect and says so. function matches(document, filter = {}) { return Object.entries(filter).every(([key, expected]) => { if (key === "$or") return expected.some((part) => matches(document, part)); const value = document?.[key]; if (expected && typeof expected === "object" && !Array.isArray(expected)) { return Object.entries(expected).every(([operator, wanted]) => { if (operator === "$exists") return (value !== undefined && value !== null) === wanted; if (operator === "$in") return wanted.some((entry) => String(value) === String(entry)); if (operator === "$nin") return !wanted.some((entry) => String(value) === String(entry)); throw new Error(`filter operator "${key}.${operator}" is not stubbed`); }); } return String(value ?? "") === String(expected ?? ""); }); } function fakeModel(table, seed = [], campaignId) { const rows = []; let counter = 0; function Document(data = {}) { counter += 1; this._id = `${table}-${counter}`; this.isNew = true; this.foundryNames = []; Object.assign(this, data); } Document.prototype.save = async function save() { if (this.isNew) rows.push(this); this.isNew = false; return this; }; Object.defineProperty(Document.prototype, "id", { get() { return this._id; } }); for (const data of seed) { // A seeded row belongs to the campaign the requests are made against unless the // seed says otherwise: the routes scope every lookup by campaign. const row = new Document({ campaign: campaignId, [table === "folder" ? "target" : "name"]: undefined, ...data }); row.isNew = false; rows.push(row); } const model = function Model(data) { return new Document(data); }; model.rows = rows; model.findOne = async (filter) => rows.find((row) => matches(row, filter)) ?? null; model.find = (filter) => mongooseQuery(rows.filter((row) => matches(row, filter))); model.deleteOne = async (filter) => { const hit = rows.filter((row) => matches(row, filter)); for (const row of hit) rows.splice(rows.indexOf(row), 1); return { deletedCount: hit.length }; }; model.deleteMany = async (filter) => { const hit = rows.filter((row) => matches(row, filter)); for (const row of hit) rows.splice(rows.indexOf(row), 1); return { deletedCount: hit.length }; }; model.updateMany = async (filter, update) => { const hit = rows.filter((row) => matches(row, filter)); for (const row of hit) Object.assign(row, update.$set ?? {}); return { modifiedCount: hit.length }; }; return model; } function worldItem(over = {}) { return { _id: "item-1", name: "Longsword", type: "weapon", system: { quantity: 1, weight: 3, rarity: "common" }, ...over, }; } // The Foundry sync route with every model it requires stubbed. `seed` pre-fills the // tables with documents the campaign already holds. function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) { const routes = new Map(); const router = { get: (route, ...handlers) => routes.set(`GET ${route}`, handlers), post: (route, ...handlers) => routes.set(`POST ${route}`, handlers), }; const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId }; // Every row belongs to the campaign the sync token belongs to, like every real row // does: the sync looks its rows up by campaign, so a seeded row without one would be // invisible to it and a test would pass without touching what it means to check. const seeded = (rows = []) => rows.map((row) => ({ campaign: campaign._id, ...row })); const models = { "../models/Actor": fakeModel("actor", seeded(seed.actors)), "../models/Item": fakeModel("item", seeded(seed.items)), "../models/Folder": fakeModel("folder", seeded(seed.folders)), "../models/Map": fakeModel("map", seeded(seed.maps)), }; const requireStub = (id) => { if (id === "express") return { Router: () => router }; if (id.startsWith("node:")) return require(id); // crypto: the sync token is hashed, not stubbed if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 }; if (id === "../models/Campaign") return { findOne: async () => campaign }; if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) }; if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js")); if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js")); if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js")); if (models[id]) return models[id]; throw new Error(`require("${id}") is not stubbed`); }; const moduleStub = { exports: {} }; vm.compileFunction(read("backend", "src", "routes", "foundry-link.js"), ["require", "module", "exports"])( requireStub, moduleStub, moduleStub.exports ); async function call(route, body = {}) { const handlers = routes.get(route); assert.ok(handlers, `${route} is not mounted`); const res = { payload: null, json(payload) { this.payload = payload; }, set: () => {} }; const req = { body, get: (name) => (String(name).toLowerCase() === "authorization" ? "Bearer sync-token" : "") }; await handlers[handlers.length - 1](req, res); return res.payload; } return { call, models, campaign }; } const FOLDER_TREE = [ { id: "folder-melee", name: "Melee Weapons", parent: null }, { id: "folder-ranged", name: "Ranged Weapons", parent: null }, { id: "folder-powder", name: "Powder Weapons", parent: "folder-ranged" }, ]; test("a synced world item arrives in the folder the world keeps it in", async () => { const sync = loadSyncRoute(); const response = await sync.call("POST /sync/snapshot", { worldId: "world-1", actors: [], folders: FOLDER_TREE, items: [worldItem({ dragonroll: { folder: "folder-melee" } })], }); assert.equal(response.status, "ok"); const [folder] = sync.models["../models/Folder"].rows; assert.equal(folder.name, "Melee Weapons"); assert.equal(folder.target, "item", "a synced folder belongs to the item list, not the notes"); assert.equal(folder.foundryFolderId, "folder-melee"); assert.equal(sync.models["../models/Item"].rows[0].folder, folder._id); }); test("a nested Foundry folder becomes a nested campaign folder", async () => { const sync = loadSyncRoute(); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: FOLDER_TREE }); const folders = sync.models["../models/Folder"].rows; const ranged = folders.find((folder) => folder.name === "Ranged Weapons"); const powder = folders.find((folder) => folder.name === "Powder Weapons"); assert.equal(powder.parentFolder, ranged._id, "the subfolder hangs under the folder nesting it"); assert.equal(folders.find((folder) => folder.name === "Melee Weapons").parentFolder, null); }); test("the same world folder is never made twice, and keeps its items", async () => { const sync = loadSyncRoute(); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [worldItem({ dragonroll: { folder: "folder-melee" } })], folders: FOLDER_TREE, }); const filed = sync.models["../models/Item"].rows[0].folder; await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [worldItem({ dragonroll: { folder: "folder-melee" } })], folders: FOLDER_TREE, }); assert.equal(sync.models["../models/Folder"].rows.length, FOLDER_TREE.length, "the tree was mirrored once"); assert.equal(sync.models["../models/Item"].rows[0].folder, filed, "the item stays in the folder it was filed in"); }); test("a folder renamed in the world is renamed in the campaign", async () => { const sync = loadSyncRoute({ seed: { folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Old name", parentFolder: null }] }, }); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null }], }); assert.equal(sync.models["../models/Folder"].rows.length, 1); assert.equal(sync.models["../models/Folder"].rows[0].name, "Melee Weapons"); }); test("a folder the world dropped goes, and its items move to the root", async () => { const sync = loadSyncRoute({ seed: { folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }], items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }], }, }); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [] }); assert.deepEqual(sync.models["../models/Folder"].rows, [], "the empty folder row is gone with the world's folder"); assert.equal(sync.models["../models/Item"].rows[0].folder, null, "the item moves to the root instead of nowhere"); }); test("a campaign folder the world does not know is left alone", async () => { const sync = loadSyncRoute({ seed: { folders: [{ _id: "folder-1", target: "item", name: "Homebrew", parentFolder: null }] }, }); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [] }); assert.equal(sync.models["../models/Folder"].rows.length, 1, "only folders mirrored from the world are pruned"); }); test("an item embedded in an actor leaves the folder of its world copy alone", async () => { const sync = loadSyncRoute({ seed: { items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }] }, }); // The actor's copy carries no folder of its own: the inventory folders an actor // keeps say nothing about the campaign's item list. await sync.call("POST /sync/snapshot", { worldId: "world-1", actors: [{ _id: "actor-1", name: "Thalia", items: [worldItem({ _id: "item-1" })] }], items: [], folders: FOLDER_TREE, }); assert.equal(sync.models["../models/Item"].rows[0].folder, "folder-1"); }); test("a module that knows nothing about folders leaves them untouched", async () => { const sync = loadSyncRoute({ seed: { folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }], items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }], }, }); await sync.call("POST /sync/snapshot", { worldId: "world-1", actors: [], items: [worldItem()] }); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [worldItem()] }); assert.equal(sync.models["../models/Folder"].rows.length, 1, "no tree was sent, so nothing was pruned"); assert.equal(sync.models["../models/Item"].rows[0].folder, "folder-1", "and the item stays filed where it was"); }); test("an item the world moved out of a folder follows it to the root", async () => { const sync = loadSyncRoute({ seed: { folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }], items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }], }, }); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [worldItem({ dragonroll: { folder: "" } })], folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null }], }); assert.equal(sync.models["../models/Item"].rows[0].folder, null); }); // --- Only the world's item directory is listed (Syndria98/dragonroll#67) -------------- // The campaign's item list equals the world's items tab: gear that only an actor // carries is its inventory (kept on the actor document), not a Dragonroll item. test("an actor's gear is kept off the campaign's item list", async () => { const sync = loadSyncRoute(); await sync.call("POST /sync/snapshot", { worldId: "world-1", items: [worldItem()], // Thalia carries a potion the world's item directory does not hold. actors: [{ _id: "actor-1", name: "Thalia", items: [{ _id: "potion-1", name: "Potion of Healing", type: "consumable", system: { quantity: 2 } }], }], }); const names = sync.models["../models/Item"].rows.map((row) => row.name); assert.deepEqual(names, ["Longsword"], "only the world's item reaches the list, not the actor's potion"); }); test("the campaign's item list is the world's whole item directory", async () => { const sync = loadSyncRoute(); await sync.call("POST /sync/snapshot", { worldId: "world-1", items: [worldItem(), worldItem({ _id: "item-2", name: "Torch", type: "loot", system: { quantity: 1 } })], actors: [], }); assert.deepEqual( sync.models["../models/Item"].rows.map((row) => row.name).sort(), ["Longsword", "Torch"], ); }); test("an item carried by a character is listed once, as its world entry", async () => { const sync = loadSyncRoute(); await sync.call("POST /sync/snapshot", { worldId: "world-1", items: [worldItem()], // The same sword, a second copy embedded in an actor under another id. actors: [{ _id: "actor-1", name: "Thalia", items: [worldItem({ _id: "sword-copy" })] }], }); assert.deepEqual(sync.models["../models/Item"].rows.map((row) => row.name), ["Longsword"]); }); test("a full snapshot prunes gear that only an actor carried", async () => { const sync = loadSyncRoute({ seed: { items: [{ _id: "potion-1", name: "Potion of Healing", foundryItemId: "embedded-1" }] }, }); // The world's item directory is now empty: nothing but a character holds the potion. await sync.call("POST /sync/snapshot", { worldId: "world-1", items: [], actors: [{ _id: "actor-1", name: "Thalia", items: [{ _id: "embedded-1", name: "Potion of Healing", type: "consumable", system: { quantity: 2 } }], }], fullSync: true, }); assert.deepEqual(sync.models["../models/Item"].rows, [], "the actor's own gear no longer stands in the item list"); }); test("a folder coloured in the world is coloured in the campaign", async () => { const sync = loadSyncRoute(); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null, color: "#7f00ff" }], }); assert.equal(sync.models["../models/Folder"].rows[0].color, "#7f00ff"); }); test("a folder the world leaves uncoloured takes the campaign's colour off", async () => { const sync = loadSyncRoute({ seed: { folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons", color: "#7f00ff" }], }, }); await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null, color: null }], }); assert.equal(sync.models["../models/Folder"].rows[0].color, null, "the world has no colour to show, so neither does the campaign"); }); test("a module that says nothing about colours leaves the campaign's colour alone", async () => { const sync = loadSyncRoute({ seed: { folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons", color: "#7f00ff" }], }, }); // A tree pushed by a module that knows folders but not their colours: no colour at all. await sync.call("POST /sync/snapshot", { worldId: "world-1", actors: [], items: [], folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null }], }); assert.equal(sync.models["../models/Folder"].rows[0].color, "#7f00ff"); }); test("the folder list the world reads back carries the colours the campaign picked", async () => { const sync = loadSyncRoute({ seed: { folders: [ { _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons", color: "#0080ff" }, { _id: "folder-2", target: "item", name: "Homebrew" }, { _id: "folder-3", name: "Chapter 1" }, ], items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }], }, }); const response = await sync.call("GET /sync/items"); assert.equal(response.status, "ok"); assert.equal(response.items.length, 1); const coloured = response.folders.find((folder) => folder._id === "folder-1"); assert.equal(coloured.foundryFolderId, "folder-melee", "the world's folder to write the colour back to"); assert.equal(coloured.color, "#0080ff"); assert.ok(!response.folders.some((folder) => folder._id === "folder-3"), "only the item list's folders travel back"); }); test("every folder listing says which campaign list it belongs to", () => { // The sidebar's four lists share the Folder model, so a listing that names no target // would show folders of the other lists between its own rows. The note routes and // `/folder/list` ask through `Folder.filterForTarget`, which for the notes names every // other section instead of the notes' own target: note folders made before the target // field existed carry none at all. tests/entry-folders.test.js runs these routes. for (const route of ["note.js", "folder.js"]) { const source = read("backend", "src", "routes", route); // The listings that gather a campaign's folders are the ones shown as a section's // tree. A walk of one folder's own children (`parentFolder`) is inside a single // list already: folders are only ever nested within their own section. const listings = source.match(/Folder\.find\(\{\s*campaign/g) ?? []; assert.ok(listings.length, `${route} lists folders`); const filtered = source.match(/Folder\.find\(\{\s*campaign[^{]*Folder\.filterForTarget\((?:'note'|target)\)/g) ?? []; assert.equal(filtered.length, listings.length, `${route} has a folder listing that names no campaign list`); } }); test("the item list comes with the folders it groups into, and items carry theirs", () => { assert.match(read("backend", "src", "models", "Item.js"), /folder:\s*{\s*type:\s*Schema\.Types\.ObjectId,\s*ref:\s*'Folder'/); const itemRoute = read("backend", "src", "routes", "item.js"); assert.match(itemRoute, /res\.json\(\{\s*status:\s*'ok',\s*items,\s*folders:/); assert.match(itemRoute, /Folder\.find\(\{\s*campaign:\s*campaignId,\s*target:\s*'item'\s*\}/); }); // --- The Foundry module sends its folder tree ------------------------------------ function makeWorld() { const state = { hooks: new Map(), registered: new Map(), requests: [], timers: new Map(), intervals: new Map(), // What Dragonroll answers a folder reconcile with: the campaign's folders and the // colours its user gave them. remoteFolders: [], nextTimerId: 1, }; // Foundry's `update` takes dotted paths ("flags.dragonroll-foundry.itemId"); an // embedded update names the row to write them on, so `_id` is not a path to set. function writeFoundryPaths(target, data) { for (const [key, value] of Object.entries(data)) { if (key === "_id") continue; const parts = key.split("."); const last = parts.pop(); let node = target; for (const part of parts) node = node[part] ??= {}; node[last] = value; } return target; } // A Folder document, plain data and the `update` both the GM and Dragonroll write with. const makeFolder = (id, name, over = {}) => ({ id, name, type: "Item", parent: null, color: null, documentName: "Folder", async update(data) { return writeFoundryPaths(this, data); }, ...over, }); const folders = [ makeFolder("folder-melee", "Melee Weapons", { color: "#8b0000" }), makeFolder("folder-ranged", "Ranged Weapons", { parent: "folder-melee" }), // An actor's own inventory folder: it hangs off the actor, not the world. makeFolder("folder-carried", "Carried", { parent: { id: "actor-1", documentName: "Actor" } }), makeFolder("folder-journal", "Lore", { type: "JournalEntry" }), ]; const items = [ { id: "item-1", name: "Longsword", type: "weapon", documentName: "Item", parent: null, folder: "folder-melee", system: { properties: { value: [] }, quantity: 1, weight: 3, rarity: "common" }, toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; }, }, { id: "item-2", name: "Torch", type: "loot", documentName: "Item", parent: null, folder: "", system: { properties: { value: [] }, quantity: 1, weight: 1, rarity: "common" }, toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; }, }, ]; const carriedItem = { id: "item-3", name: "Caltrops", type: "loot", documentName: "Item", parent: { documentName: "Actor" }, folder: "folder-carried", system: { properties: { value: [] }, quantity: 4, weight: 0, rarity: "common" }, toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; }, }; const actors = [ { id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {}, items: { contents: [carriedItem] }, getFlag() { return undefined; }, async update(data) { return writeFoundryPaths(this, data); }, // Embedded documents are written through the document holding them, and each // update names the row it belongs to. async updateEmbeddedDocuments(_kind, updates) { for (const update of updates) { if (carriedItem.id === update._id) writeFoundryPaths(carriedItem, update); } return []; }, toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags }; }, }, ]; const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" }; const sandbox = { console: { log() {}, info() {}, warn() {}, error() {} }, URL, CONFIG: {}, window: { location: { origin: "http://vtt.test" } }, ui: { notifications: { info() {}, warn() {}, error() {} } }, Hooks: { once(name, fn) { state.hooks.set(name, [fn]); }, on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); }, }, setTimeout: (fn, delay = 0) => { const id = state.nextTimerId++; state.timers.set(id, { fn, delay }); return id; }, clearTimeout: (id) => state.timers.delete(id), setInterval: (fn, delay = 0) => { // Recorded, never run by itself: tests ask for a periodic reconcile with // `runIntervals`, so the ones watching single pushes stay on their own. const id = state.nextTimerId++; state.intervals.set(id, { fn, delay }); return id; }, clearInterval: (id) => state.intervals.delete(id), fetch: async (url, options = {}) => { const href = String(url); state.requests.push({ href, method: options.method, body: options.body ? JSON.parse(options.body) : null, }); const payload = { status: "ok", actors: [], items: [] }; if (href.includes("foundry/sync/items")) payload.folders = state.remoteFolders; return { ok: true, status: 200, json: async () => payload }; }, Actor: { async create() { return null; } }, Item: { async create() { return null; } }, }; sandbox.game = { user: { isGM: true }, world: { id: "world-1", title: "Test World" }, system: { id: "dnd5e" }, modules: { get: () => ({}) }, actors: { contents: actors, get: (id) => actors.find((actor) => actor.id === id) }, items: { contents: items, get: (id) => items.find((item) => item.id === id) }, folders: { contents: folders, get: (id) => folders.find((folder) => folder.id === id) }, settings: { register(module, key, definition) { state.registered.set(key, definition); if (!(key in settingsStore)) settingsStore[key] = definition.default; }, get(module, key) { return settingsStore[key]; }, async set(module, key, value) { settingsStore[key] = value; await state.registered.get(key)?.onChange?.(value); }, }, }; vm.createContext(sandbox); vm.runInContext(read("dragonroll-foundry", "scripts", "api.js"), sandbox); state.game = sandbox.game; state.folder = (id) => folders.find((folder) => folder.id === id); state.item = (id) => items.find((item) => item.id === id); state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync") && !request.href.includes("foundry/sync/status")); state.pushes = (route) => state.syncRequests().filter((request) => request.href.includes(route)); const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); }; state.fire = async (name, ...args) => { for (const handler of state.hooks.get(name) || []) await handler(...args); await drain(); }; state.runTimers = async () => { for (let round = 0; round < 6; round += 1) { if (!state.timers.size && round > 2) break; const due = [...state.timers.values()]; state.timers.clear(); for (const timer of due) await timer.fn(); await drain(); } }; // The reconciles `setInterval` registered: what runs every few seconds on a world // that is linked, and so what carries Dragonroll's folder colours back into the world. state.runIntervals = async () => { for (const interval of [...state.intervals.values()]) await interval.fn(); await drain(); }; state.linkedSetup = async () => { await state.fire("init"); await state.fire("ready"); await state.runTimers(); state.requests.length = 0; return state; }; return state; } test("the world sends its item folder tree with a snapshot", async () => { const world = await makeWorld().linkedSetup(); await world.fire("updateActor", world.game.actors.contents[0]); await world.runTimers(); const [push] = world.pushes("foundry/sync/snapshot"); assert.ok(push, "the actor change pushed a snapshot"); assert.deepEqual(push.body.folders, [ { id: "folder-melee", name: "Melee Weapons", parent: null, color: "#8b0000" }, { id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee", color: null }, ], "the item directory tree, nested and coloured, without the actor's own or another type's folders"); const longsword = push.body.items.find((item) => item._id === "item-1"); assert.equal(longsword.dragonroll.folder, "folder-melee", "a world item says which folder it stands in"); const torch = push.body.items.find((item) => item._id === "item-2"); assert.equal(torch.dragonroll.folder, "", "and which one stands at the root"); }); test("an item embedded in an actor does not report the actor's inventory folders", async () => { const world = await makeWorld().linkedSetup(); await world.fire("updateActor", world.game.actors.contents[0]); await world.runTimers(); const [push] = world.pushes("foundry/sync/snapshot"); const carried = push.body.actors[0].items.find((item) => item._id === "item-3"); assert.equal(carried.dragonroll?.folder, undefined, "the actor copy carries no folder for the campaign"); }); test("a live item edit carries the folder tree too", async () => { const world = await makeWorld().linkedSetup(); await world.fire("updateItem", world.item("item-1")); await world.runTimers(); const [push] = world.pushes("foundry/sync/item-snapshot"); assert.deepEqual(push.body.folders.map((folder) => folder.id), ["folder-melee", "folder-ranged"]); assert.equal(push.body.items[0].dragonroll.folder, "folder-melee"); }); test("a folder change reaches Dragonroll without pushing the items in it", async () => { const world = await makeWorld().linkedSetup(); const melee = world.folder("folder-melee"); melee.name = "Close Weapons"; await world.fire("updateFolder", melee); await world.runTimers(); const [push] = world.pushes("foundry/sync/item-snapshot"); assert.deepEqual(push.body.items, [], "the items themselves are left alone"); assert.deepEqual(push.body.folders.map((folder) => [folder.id, folder.name]), [ ["folder-melee", "Close Weapons"], ["folder-ranged", "Ranged Weapons"], ]); }); test("a folder the GM colours sends its colour with the tree", async () => { const world = await makeWorld().linkedSetup(); const ranged = world.folder("folder-ranged"); ranged.color = "#123456"; await world.fire("updateFolder", ranged); await world.runTimers(); const [push] = world.pushes("foundry/sync/item-snapshot"); assert.deepEqual(push.body.folders.map((folder) => [folder.id, folder.color]), [ ["folder-melee", "#8b0000"], ["folder-ranged", "#123456"], ], "every folder reports the colour the world shows for it, `null` for one it left uncoloured"); }); test("a folder of another document type does not touch the item list", async () => { const world = await makeWorld().linkedSetup(); await world.fire("updateFolder", world.folder("folder-journal")); await world.runTimers(); assert.deepEqual(world.syncRequests(), []); }); test("autosync off: folder changes stop syncing", async () => { const world = await makeWorld().linkedSetup(); await world.game.settings.set("dragonroll-foundry", "autoSync", false); await world.fire("updateFolder", world.folder("folder-melee")); await world.fire("updateItem", world.item("item-1")); await world.runTimers(); assert.deepEqual(world.syncRequests(), []); }); // --- The colours the campaign gives those folders travel back to the world --------- test("a folder coloured in the Dragonroll campaign is coloured in the world", async () => { const world = await makeWorld().linkedSetup(); world.remoteFolders = [ { _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: "#0080ff" }, // A folder the campaign made for its own items: there is no world document to colour. { _id: "db-homebrew", name: "Homebrew", color: "#00ff00" }, ]; await world.runIntervals(); assert.equal(world.folder("folder-melee").color, "#0080ff"); assert.equal(world.folder("folder-ranged").color, null, "a folder the campaign says nothing about keeps what the world shows"); assert.deepEqual(world.requests.filter((request) => request.method === "POST"), [], "Dragonroll's own write is not pushed back to the campaign as a world change"); }); test("a colour taken off in the campaign comes off the world's folder", async () => { const world = await makeWorld().linkedSetup(); world.remoteFolders = [{ _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: null }]; await world.runIntervals(); assert.equal(world.folder("folder-melee").color, null, "uncoloured in the campaign is uncoloured in the world"); }); test("autosync off: the campaign's folder colours are not written into the world", async () => { const world = await makeWorld().linkedSetup(); await world.game.settings.set("dragonroll-foundry", "autoSync", false); world.remoteFolders = [{ _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: "#0080ff" }]; await world.runIntervals(); assert.equal(world.folder("folder-melee").color, "#8b0000", "the world keeps what it shows while autosync is off"); }); // --- The sidebar groups its items under those folders ---------------------------- // `vm.compileFunction` is synchronous, so the service is ready right away. Loading it with // a top-level `await` instead makes Node read this whole file as an ES module, where // `require` is not defined and none of these tests run at all. function loadItemFoldersService() { const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };"); return vm.compileFunction(source)(); } const { BuildItemRows } = loadItemFoldersService(); const SIDEBAR_FOLDERS = [ { _id: "f-melee", name: "Melee Weapons" }, { _id: "f-ranged", name: "Ranged Weapons" }, { _id: "f-powder", name: "Powder Weapons", parentFolder: "f-ranged" }, ]; const SIDEBAR_ITEMS = [ { _id: "i-sword", name: "Longsword", folder: "f-melee" }, { _id: "i-pistol", name: "Pistol", folder: "f-powder" }, { _id: "i-torch", name: "Torch" }, ]; test("items are grouped under the folder they stand in, nested", () => { const shape = BuildItemRows(SIDEBAR_ITEMS, SIDEBAR_FOLDERS).map((row) => [ row.kind, row.kind === "folder" ? row.folder.name : row.item.name, row.depth, ]); // Every folder is followed by what stands in it, one step deeper, and the items that // stand at the root come last (see BuildItemRows). assert.deepEqual(shape, [ ["folder", "Melee Weapons", 0], ["item", "Longsword", 1], ["folder", "Ranged Weapons", 0], ["folder", "Powder Weapons", 1], ["item", "Pistol", 2], ["item", "Torch", 0], ]); }); test("a collapsed folder hides its whole subtree", () => { const rows = BuildItemRows(SIDEBAR_ITEMS, SIDEBAR_FOLDERS, ["f-ranged"]); assert.ok(rows.some((row) => row.kind === "folder" && row.folder.name === "Ranged Weapons")); assert.ok(!rows.some((row) => row.kind === "item" && row.item.name === "Pistol"), "the nested item is hidden too"); }); test("without any folder the list is the plain item list", () => { const rows = BuildItemRows([{ _id: "i-1", name: "Torch" }, { _id: "i-2", name: "Longsword" }], []); assert.deepEqual(rows.map((row) => [row.kind, row.item.name, row.depth]), [ ["item", "Longsword", 0], ["item", "Torch", 0], ]); }); test("an item whose folder is gone, or a folder nested in itself, reads as a root item", () => { const rows = BuildItemRows( [{ _id: "i-1", name: "Torch", folder: "f-gone" }], [{ _id: "f-a", name: "A", parentFolder: "f-b" }, { _id: "f-b", name: "B", parentFolder: "f-a" }], ); const shape = rows.map((row) => [row.kind, row.kind === "folder" ? row.folder.name : row.item.name]); assert.ok(shape.some(([kind, name]) => kind === "item" && name === "Torch"), "the item is not lost with the folder that was removed"); assert.deepEqual(new Set(shape.filter(([kind]) => kind === "folder").map(([, name]) => name)), new Set(["A", "B"])); assert.equal(shape.filter(([kind]) => kind === "folder").length, 2, "a broken tree is walked once, not forever"); }); test("every locale labels the folder row", () => { for (const locale of ["en", "es", "ca"]) { const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json")); assert.ok(campaigns.folders?.["toggle"], `${locale} is missing campaigns.folders.toggle`); } });