Fix #57: Sync foundry folder colors #66

Merged
Syndria98 merged 2 commits from ai/issue-57 into master 2026-10-15 14:00:08 +00:00
5 changed files with 283 additions and 23 deletions

View File

@@ -118,6 +118,7 @@ the JWT guard; CORS opened for it): `snapshot` (actors + world items, `fullSync`
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index); a Foundry document carrying the `dragonroll-foundry.actorId` / `.itemId` flag adopts the matching Dragonroll row. - **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index); a Foundry document carrying the `dragonroll-foundry.actorId` / `.itemId` flag adopts the matching Dragonroll row.
- **Items are deduplicated by name** — Foundry keeps the same gear once per carrier, so one `Item` per name; `foundryNames` keeps Foundry's names so a Dragonroll rename does not resurrect a duplicate. `services/item-foundry.js` returns `null` for non-gear types and those are skipped. - **Items are deduplicated by name** — Foundry keeps the same gear once per carrier, so one `Item` per name; `foundryNames` keeps Foundry's names so a Dragonroll rename does not resurrect a duplicate. `services/item-foundry.js` returns `null` for non-gear types and those are skipped.
- **Item folders mirror the world's item directory** (`Folder.foundryFolderId`, target `item`): every push carries the whole tree and the world owns its names and nesting. `color` is the one field the campaign sets too, so it travels back with the folders `GET /foundry/sync/items` answers with (`{items, folders}`) and the module writes it onto the world's folder.
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events overwrite. Only a full snapshot can prune. - **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events overwrite. Only a full snapshot can prune.
- **Autosync is a Foundry-side setting** (`autoSync`, on by default): off = no CRUD push, no periodic reconcile, no startup snapshot; the actor directory's *Dragonroll: Force Sync* still upserts the selection (`fullSync:false`). - **Autosync is a Foundry-side setting** (`autoSync`, on by default): off = no CRUD push, no periodic reconcile, no startup snapshot; the actor directory's *Dragonroll: Force Sync* still upserts the selection (`fullSync:false`).
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge. - `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge.

View File

@@ -144,6 +144,16 @@ async function syncFoundryItems(campaign, sources, fullSync = false, folders = n
// say nothing: the folders they carry belong to that actor's own inventory, and // say nothing: the folders they carry belong to that actor's own inventory, and
// Dragonroll keeps one item per piece of gear anyway. // Dragonroll keeps one item per piece of gear anyway.
// The colour a pushed folder carries. `undefined` means the push says nothing about
// colours — an older module, which knows nothing about them — and the colour the
// campaign has stays; `null` is the world leaving a folder uncoloured, which takes
// the campaign's colour off along with it. Anything else is the colour to show.
function foundryFolderColor(source) {
if (source?.color === undefined) return undefined;
const color = typeof source.color === 'string' ? source.color.trim() : '';
return color || null;
}
// Parents before children, so a folder is mapped before the one nested in it. // Parents before children, so a folder is mapped before the one nested in it.
// A folder whose parent is missing, or caught in a cycle, becomes a root. // A folder whose parent is missing, or caught in a cycle, becomes a root.
function orderFoundryFolderSources(sources) { function orderFoundryFolderSources(sources) {
@@ -152,7 +162,12 @@ function orderFoundryFolderSources(sources) {
const id = String(source?.id || '').trim().slice(0, 120); const id = String(source?.id || '').trim().slice(0, 120);
const name = String(source?.name || '').trim(); const name = String(source?.name || '').trim();
if (!id || !name) continue; if (!id || !name) continue;
byId.set(id, { id, name, parent: String(source?.parent || '').trim().slice(0, 120) }); byId.set(id, {
id,
name,
parent: String(source?.parent || '').trim().slice(0, 120),
color: foundryFolderColor(source)
});
} }
const ordered = []; const ordered = [];
@@ -195,6 +210,10 @@ async function syncFoundryItemFolders(campaign, folderSources) {
// The world owns this tree, so unlike an item's fields a rename or a move // The world owns this tree, so unlike an item's fields a rename or a move
// lands whatever kind of push carried it: the whole tree arrives with each. // lands whatever kind of push carried it: the whole tree arrives with each.
folder.name = source.name; folder.name = source.name;
// Its colour is the one part of the tree the campaign colours too: what the
// world shows arrives here, and what the campaign picks travels back to the
// world with the folder list `/sync/items` answers with.
if (source.color !== undefined) folder.color = source.color;
const parent = inTree.has(source.parent) ? folders.get(source.parent) : null; const parent = inTree.has(source.parent) ? folders.get(source.parent) : null;
folder.parentFolder = parent ? parent._id : null; folder.parentFolder = parent ? parent._id : null;
await folder.save(); await folder.save();
@@ -388,12 +407,20 @@ router.post('/sync/item-delete', async (req, res) => {
} }
}); });
// The item list the world reconciles against, together with the folders its rows are
// grouped into — the same shape the campaign's own `/item/list` answers with. The folders
// travel back for their colour: the world owns the tree's name and nesting, while whoever
// colours a folder on either side expects to see it coloured on the other.
router.get('/sync/items', async (req, res) => { router.get('/sync/items', async (req, res) => {
try { try {
const campaign = await syncCampaign(req, res); const campaign = await syncCampaign(req, res);
if (!campaign) return; if (!campaign) return;
const items = await Item.find({ campaign: campaign._id }).sort({ name: 1 }).lean(); const items = await Item.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
res.json({ status: 'ok', items }); const folders = await Folder.find({ campaign: campaign._id, target: 'item' })
.select('_id name color foundryFolderId')
.sort({ name: 1 })
.lean();
res.json({ status: 'ok', items, folders });
} catch (err) { } catch (err) {
console.error(err); console.error(err);
res.json({ status: 'error', msg: 'errors.internal' }); res.json({ status: 'error', msg: 'errors.internal' });

View File

@@ -96,6 +96,10 @@ The campaign's Item list is synchronized with the world's gear, both ways:
properties, description). An item made by hand in Dragonroll is created in the world's item properties, description). An item made by hand in Dragonroll is created in the world's item
directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry
document. document.
- The folders grouping the world's item directory arrive in the campaign as its own item folders, tree
and nesting included, and the items are filed in them. A folder's **colour** goes the other way too:
what the GM colours in Foundry shows on the campaign's folder, and what the campaign colours lands on
the world's folder on the next reconcile (the world's document keeps its name and nesting either way).
- A full snapshot keeps Dragonroll edits on reconnect; live Foundry edits overwrite. Item removal is - A full snapshot keeps Dragonroll edits on reconnect; live Foundry edits overwrite. Item removal is
pruned only by a full snapshot, so a live item push never deletes anything. Deleting a synced item in pruned only by a full snapshot, so a live item push never deletes anything. Deleting a synced item in
Dragonroll removes its Foundry world copy on the next reconcile. Items that live only in an actor's Dragonroll removes its Foundry world copy on the next reconcile. Items that live only in an actor's
@@ -110,14 +114,15 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon
| `POST /api/foundry/sync/item-snapshot` | Live world item edits, upsert only | | `POST /api/foundry/sync/item-snapshot` | Live world item edits, upsert only |
| `POST /api/foundry/sync/item-delete` | A world item was deleted | | `POST /api/foundry/sync/item-delete` | A world item was deleted |
| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry | | `GET /api/foundry/sync/characters` | Characters to apply back in Foundry |
| `GET /api/foundry/sync/items` | Items to apply back in Foundry | | `GET /api/foundry/sync/items` | Items, and the item folders with their Dragonroll colours, to apply back in Foundry |
| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status | | `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status |
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document | | `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
| `POST /api/foundry/sync/delete` | An actor was deleted | | `POST /api/foundry/sync/delete` | An actor was deleted |
Foundry documents keep the Dragonroll id in the `dragonroll-foundry.actorId` / `dragonroll-foundry.itemId` Foundry documents keep the Dragonroll id in the `dragonroll-foundry.actorId` / `dragonroll-foundry.itemId`
flag, and world items are marked with `dragonroll-foundry.syncMutation` while Dragonroll writes them so flag, and world items are marked with `dragonroll-foundry.syncMutation` while Dragonroll writes them so
the write is not echoed back. the write is not echoed back. A folder colour is written with that folder held in the client's set of
folders being synced, for the same reason.
## 2. Run the bridge on the Foundry host ## 2. Run the bridge on the Foundry host

View File

@@ -33,6 +33,7 @@ let itemSyncErrorLogged = false;
let folderSyncTimeout; let folderSyncTimeout;
let folderSyncRunning = false; let folderSyncRunning = false;
const syncingItemIds = new Set(); const syncingItemIds = new Set();
const syncingFolderIds = new Set();
const queuedItemChanges = new Map(); const queuedItemChanges = new Map();
function getCollectionContents(collection, collectionName) { function getCollectionContents(collection, collectionName) {
@@ -675,10 +676,23 @@ function isWorldItemFolder(folder, seen = new Set()) {
return isWorldItemFolder(parent, seen); return isWorldItemFolder(parent, seen);
} }
// A Foundry folder's colour, or null for one the GM left uncoloured. Null travels as null:
// it tells Dragonroll to take a colour off the folder it was given before, whereas a module
// that says nothing about colours at all leaves the campaign's own choice alone.
function itemFolderColor(folder) {
const color = typeof folder?.color === "string" ? folder.color.trim() : "";
return color || null;
}
function worldItemFolderSnapshots() { function worldItemFolderSnapshots() {
return (game.folders?.contents || []) return (game.folders?.contents || [])
.filter((folder) => isWorldItemFolder(folder)) .filter((folder) => isWorldItemFolder(folder))
.map((folder) => ({ id: folder.id, name: folder.name, parent: itemFolderParent(folder)?.id || null })); .map((folder) => ({
id: folder.id,
name: folder.name,
parent: itemFolderParent(folder)?.id || null,
color: itemFolderColor(folder),
}));
} }
// A world item travels with the folder it stands in, so Dragonroll can file it the // A world item travels with the folder it stands in, so Dragonroll can file it the
@@ -706,6 +720,35 @@ function getWorldItemSnapshots() {
return (game.items?.contents || []).map(serializeFoundryWorldItem).filter(Boolean); return (game.items?.contents || []).map(serializeFoundryWorldItem).filter(Boolean);
} }
// --- Folder colours ----------------------------------------------------------
// Colouring a folder is the one thing about the tree the campaign gets to do on its
// own: the world owns what the folders are called and how they nest, and Dragonroll
// owns the colour its user picks for one. So the colour travels back with the folder
// list the item reconcile reads, and lands on the world's folder — marked, like every
// Dragonroll write, so the world does not echo it straight back to the campaign.
async function withFolderSyncSuppressed(folder, callback) {
if (!folder?.id) return callback();
syncingFolderIds.add(folder.id);
try {
return await callback();
} finally {
syncingFolderIds.delete(folder.id);
}
}
async function applyDragonrollFolderColors(entries) {
for (const entry of entries || []) {
const folder = entry?.foundryFolderId ? game.folders?.get(entry.foundryFolderId) : null;
// Only the world's item directories: a Dragonroll folder the world has no document
// for is the campaign's business alone, and making one there is not ours to do.
if (!folder || folder.documentName !== "Folder" || !isWorldItemFolder(folder)) continue;
const color = entry.color || null;
if (itemFolderColor(folder) === color) continue;
await withFolderSyncSuppressed(folder, () => folder.update({ color }));
}
}
function dragonrollItemIdOf(item) { function dragonrollItemIdOf(item) {
return item.getFlag?.(MODULE_ID, "itemId") || item.flags?.[MODULE_ID]?.itemId || ""; return item.getFlag?.(MODULE_ID, "itemId") || item.flags?.[MODULE_ID]?.itemId || "";
} }
@@ -916,10 +959,13 @@ async function reconcileDragonrollItems() {
if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return; if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return;
itemSyncRunning = true; itemSyncRunning = true;
try { try {
const result = await getDragonroll("foundry/sync/items", token);
// The folder colours are applied first, and whatever system this world runs: a
// colour is the same on every one of them, while writing an item is what needs D&D 5e.
await applyDragonrollFolderColors(result.folders);
if (game.system.id !== "dnd5e") { if (game.system.id !== "dnd5e") {
throw new Error("Item sync currently requires the D&D 5e Foundry system."); throw new Error("Item sync currently requires the D&D 5e Foundry system.");
} }
const result = await getDragonroll("foundry/sync/items", token);
const remoteItems = result.items || []; const remoteItems = result.items || [];
const remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry])); const remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry]));
const localByRemoteId = new Map(game.items.contents const localByRemoteId = new Map(game.items.contents
@@ -1347,7 +1393,9 @@ Hooks.once("ready", () => {
} }
// An item folder the GM made, renamed or nested changes the tree the campaign // An item folder the GM made, renamed or nested changes the tree the campaign
// mirrors; nothing about the items themselves changed, so only the tree goes. // mirrors; nothing about the items themselves changed, so only the tree goes.
// A colour Dragonroll has just written into the folder is not the GM changing it.
if (document.documentName === "Folder") { if (document.documentName === "Folder") {
if (syncingFolderIds.has(document.id)) return;
if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders(); if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders();
return; return;
} }

View File

@@ -1,7 +1,9 @@
// Tests for item folders following the Foundry world into the campaign // Tests for item folders following the Foundry world into the campaign
// (Syndria98/dragonroll#44): the world's item directory is grouped into folders, and // (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 // 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 // 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, // 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), post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
}; };
const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId }; 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 = { const models = {
"../models/Actor": fakeModel("actor", seed.actors), "../models/Actor": fakeModel("actor", seeded(seed.actors)),
"../models/Item": fakeModel("item", seed.items), "../models/Item": fakeModel("item", seeded(seed.items)),
"../models/Folder": fakeModel("folder", seed.folders), "../models/Folder": fakeModel("folder", seeded(seed.folders)),
}; };
const requireStub = (id) => { const requireStub = (id) => {
if (id === "express") return { Router: () => router }; 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 === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 };
if (id === "../models/Campaign") return { findOne: async () => campaign }; if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) }; 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); 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", () => { 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 // 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 // would show folders of the other lists between its own rows. The note routes and
@@ -320,15 +395,40 @@ function makeWorld() {
registered: new Map(), registered: new Map(),
requests: [], requests: [],
timers: new Map(), 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, 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 = [ const folders = [
{ id: "folder-melee", name: "Melee Weapons", type: "Item", parent: null, documentName: "Folder" }, makeFolder("folder-melee", "Melee Weapons", { color: "#8b0000" }),
{ id: "folder-ranged", name: "Ranged Weapons", type: "Item", parent: "folder-melee", documentName: "Folder" }, makeFolder("folder-ranged", "Ranged Weapons", { parent: "folder-melee" }),
// An actor's own inventory folder: it hangs off the actor, not the world. // 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" }, makeFolder("folder-carried", "Carried", { parent: { id: "actor-1", documentName: "Actor" } }),
{ id: "folder-journal", name: "Lore", type: "JournalEntry", parent: null, documentName: "Folder" }, makeFolder("folder-journal", "Lore", { type: "JournalEntry" }),
]; ];
const items = [ const items = [
{ {
@@ -354,6 +454,15 @@ function makeWorld() {
id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {}, id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {},
items: { contents: [carriedItem] }, items: { contents: [carriedItem] },
getFlag() { return undefined; }, 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 }; }, toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags }; },
}, },
]; ];
@@ -375,15 +484,24 @@ function makeWorld() {
return id; return id;
}, },
clearTimeout: (id) => state.timers.delete(id), clearTimeout: (id) => state.timers.delete(id),
setInterval: () => 0, setInterval: (fn, delay = 0) => {
clearInterval: () => {}, // 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 = {}) => { fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({ state.requests.push({
href: String(url), href,
method: options.method, method: options.method,
body: options.body ? JSON.parse(options.body) : null, 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; } }, Actor: { async create() { return null; } },
Item: { async create() { return null; } }, Item: { async create() { return null; } },
@@ -434,6 +552,12 @@ function makeWorld() {
await drain(); 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 () => { state.linkedSetup = async () => {
await state.fire("init"); await state.fire("init");
await state.fire("ready"); 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"); const [push] = world.pushes("foundry/sync/snapshot");
assert.ok(push, "the actor change pushed a snapshot"); assert.ok(push, "the actor change pushed a snapshot");
assert.deepEqual(push.body.folders, [ assert.deepEqual(push.body.folders, [
{ id: "folder-melee", name: "Melee Weapons", parent: null }, { id: "folder-melee", name: "Melee Weapons", parent: null, color: "#8b0000" },
{ id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee" }, { id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee", color: null },
], "the item directory tree, nested, without the actor's own or another type's folders"); ], "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"); 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"); 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"); 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 () => { test("a folder of another document type does not touch the item list", async () => {
const world = await makeWorld().linkedSetup(); const world = await makeWorld().linkedSetup();
@@ -521,14 +660,54 @@ test("autosync off: folder changes stop syncing", async () => {
assert.deepEqual(world.syncRequests(), []); 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 ---------------------------- // --- 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 };"); const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };");
return vm.compileFunction(source)(); return vm.compileFunction(source)();
} }
const { BuildItemRows } = await loadItemFoldersService(); const { BuildItemRows } = loadItemFoldersService();
const SIDEBAR_FOLDERS = [ const SIDEBAR_FOLDERS = [
{ _id: "f-melee", name: "Melee Weapons" }, { _id: "f-melee", name: "Melee Weapons" },