Fix issue #57: Sync foundry folder colors
Some checks failed
Test / test (push) Failing after 2s

This commit is contained in:
Gitea OpenCode Agent
2026-10-15 13:58:42 +00:00
parent fe63bd15f3
commit d03cc1eb59
5 changed files with 283 additions and 23 deletions

View File

@@ -1,7 +1,9 @@
// 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.
// 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,
@@ -120,14 +122,19 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
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", seed.actors),
"../models/Item": fakeModel("item", seed.items),
"../models/Folder": fakeModel("folder", seed.folders),
"../models/Actor": fakeModel("actor", seeded(seed.actors)),
"../models/Item": fakeModel("item", seeded(seed.items)),
"../models/Folder": fakeModel("folder", seeded(seed.folders)),
};
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 ?? "" }) };
@@ -290,6 +297,74 @@ test("an item the world moved out of a folder follows it to the root", async ()
assert.equal(sync.models["../models/Item"].rows[0].folder, null);
});
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
@@ -320,15 +395,40 @@ function makeWorld() {
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 = [
{ 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" },
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.
{ 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" },
makeFolder("folder-carried", "Carried", { parent: { id: "actor-1", documentName: "Actor" } }),
makeFolder("folder-journal", "Lore", { type: "JournalEntry" }),
];
const items = [
{
@@ -354,6 +454,15 @@ function makeWorld() {
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 }; },
},
];
@@ -375,15 +484,24 @@ function makeWorld() {
return id;
},
clearTimeout: (id) => state.timers.delete(id),
setInterval: () => 0,
clearInterval: () => {},
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: String(url),
href,
method: options.method,
body: options.body ? JSON.parse(options.body) : null,
});
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
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; } },
@@ -434,6 +552,12 @@ function makeWorld() {
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");
@@ -454,9 +578,9 @@ test("the world sends its item folder tree with a snapshot", async () => {
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");
{ 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");
@@ -501,6 +625,21 @@ test("a folder change reaches Dragonroll without pushing the items in it", async
]);
});
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();
@@ -521,14 +660,54 @@ test("autosync off: folder changes stop syncing", async () => {
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 ----------------------------
async function loadItemFoldersService() {
// `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 } = await loadItemFoldersService();
const { BuildItemRows } = loadItemFoldersService();
const SIDEBAR_FOLDERS = [
{ _id: "f-melee", name: "Melee Weapons" },