593 lines
26 KiB
JavaScript
593 lines
26 KiB
JavaScript
// 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.
|
|
//
|
|
// 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 = []) {
|
|
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) {
|
|
const row = new Document({ [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 };
|
|
const models = {
|
|
"../models/Actor": fakeModel("actor", seed.actors),
|
|
"../models/Item": fakeModel("item", seed.items),
|
|
"../models/Folder": fakeModel("folder", seed.folders),
|
|
};
|
|
|
|
const requireStub = (id) => {
|
|
if (id === "express") return { Router: () => router };
|
|
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 (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);
|
|
});
|
|
|
|
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);
|
|
const listings = source.match(/Folder\.find\(/g) ?? [];
|
|
assert.ok(listings.length, `${route} lists folders`);
|
|
const filtered = source.match(/Folder\.find\(\{[^{]*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(),
|
|
nextTimerId: 1,
|
|
};
|
|
|
|
const folders = [
|
|
{ id: "folder-melee", name: "Melee Weapons", type: "Item", parent: null, documentName: "Folder" },
|
|
{ id: "folder-ranged", name: "Ranged Weapons", type: "Item", parent: "folder-melee", documentName: "Folder" },
|
|
// An actor's own inventory folder: it hangs off the actor, not the world.
|
|
{ id: "folder-carried", name: "Carried", type: "Item", parent: { id: "actor-1", documentName: "Actor" }, documentName: "Folder" },
|
|
{ id: "folder-journal", name: "Lore", type: "JournalEntry", parent: null, documentName: "Folder" },
|
|
];
|
|
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; },
|
|
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: () => 0,
|
|
clearInterval: () => {},
|
|
fetch: async (url, options = {}) => {
|
|
state.requests.push({
|
|
href: String(url),
|
|
method: options.method,
|
|
body: options.body ? JSON.parse(options.body) : null,
|
|
});
|
|
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
|
|
},
|
|
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();
|
|
}
|
|
};
|
|
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 },
|
|
{ id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee" },
|
|
], "the item directory tree, nested, 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 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 sidebar groups its items under those folders ----------------------------
|
|
|
|
async function loadItemFoldersService() {
|
|
const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };");
|
|
return vm.compileFunction(source)();
|
|
}
|
|
|
|
const { BuildItemRows } = await 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,
|
|
]);
|
|
|
|
assert.deepEqual(shape, [
|
|
["folder", "Melee Weapons", 0],
|
|
["folder", "Ranged Weapons", 0],
|
|
["folder", "Powder Weapons", 1],
|
|
["item", "Pistol", 1],
|
|
["item", "Torch", 0],
|
|
["item", "Longsword", 1],
|
|
]);
|
|
});
|
|
|
|
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.includes(["item", "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(rows.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`);
|
|
}
|
|
});
|