Merge branch 'master' into ai/issue-90
All checks were successful
Test / test (push) Successful in 2s
All checks were successful
Test / test (push) Successful in 2s
This commit is contained in:
111
tests/character-sheet-persistent-column.test.js
Normal file
111
tests/character-sheet-persistent-column.test.js
Normal file
@@ -0,0 +1,111 @@
|
||||
// Tests for Syndria98/dragonroll#91: the column that opens the character sheet — the portrait with
|
||||
// the armor class, the speed, the bonuses and both pools under it — stays on screen whoever's tab is
|
||||
// open, instead of being the ability scores tab's own content and disappearing when the sheet moves
|
||||
// to the inventory, the traits or the spells.
|
||||
//
|
||||
// The window is a `.vue` file and the repository root installs no dependencies for the frontend, so
|
||||
// the template and the styles are read out of the source the way tests/character-sheet-tabs.test.js
|
||||
// and tests/character-sheet-portrait-column.test.js read them.
|
||||
//
|
||||
// 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 read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||
|
||||
const sheetSource = read("frontend", "app", "components", "windows", "CharacterSheetWindow.vue");
|
||||
const template = /<template>([\s\S]*)<\/template>/.exec(sheetSource)?.[1] ?? "";
|
||||
const TAB_KEYS = ["abilities", "inventory", "traits", "spells"];
|
||||
|
||||
const COLUMN = '<div class="character-column">';
|
||||
|
||||
function tabBody(key) {
|
||||
const block = new RegExp(`<main v-show="activeTab === '${key}'"[\\s\\S]*?</main>`).exec(template)?.[0];
|
||||
assert.ok(block, `expected a body for the ${key} tab`);
|
||||
return block;
|
||||
}
|
||||
|
||||
// The column, taken whole: it stands ahead of the tab bodies, which are its siblings.
|
||||
function characterColumn() {
|
||||
const start = template.indexOf(COLUMN);
|
||||
const end = template.indexOf('<main v-show="activeTab');
|
||||
assert.ok(start !== -1 && end > start, "expected the character column ahead of the tab bodies");
|
||||
return template.slice(start, end);
|
||||
}
|
||||
|
||||
// The classes wrapping a tag, worked out by walking the blocks of the template in order the way a
|
||||
// browser nests them, so a tab cannot hide the column by wrapping it.
|
||||
function ancestorsOf(needle) {
|
||||
const at = template.indexOf(needle);
|
||||
assert.ok(at !== -1, `expected ${needle} in the template`);
|
||||
const stack = [];
|
||||
for (const match of template.matchAll(/<(\/?)(div|main|section|header|nav)\b([^>]*)>/g)) {
|
||||
if (match.index > at) break;
|
||||
const [, closed, , attrs] = match;
|
||||
if (closed) stack.pop();
|
||||
else if (!attrs.trimEnd().endsWith("/")) {
|
||||
const classes = /\bclass="([^"]*)"/.exec(attrs);
|
||||
stack.push(classes ? classes[1].trim().split(/\s+/) : []);
|
||||
}
|
||||
}
|
||||
return stack.slice(0, -1).map((classes) => classes.join(" "));
|
||||
}
|
||||
|
||||
test("the character column belongs to no tab", () => {
|
||||
const column = characterColumn();
|
||||
assert.ok(column.includes('class="sheet-portrait"'), "the portrait is part of the column");
|
||||
assert.ok(column.includes('class="sheet-panel vitals-panel"'), "and so is the panel of readouts and bars");
|
||||
// Nothing toggles the column: no tab decides whether it shows.
|
||||
assert.doesNotMatch(column, /v-show=/, "the column never hides behind a tab");
|
||||
|
||||
for (const key of TAB_KEYS) {
|
||||
const body = tabBody(key);
|
||||
assert.doesNotMatch(body, /class="character-column"/, `the ${key} tab does not own the column`);
|
||||
assert.doesNotMatch(body, /sheet-portrait|vitals-panel/, `the ${key} tab does not hold the column's contents`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the column and the tab that is open stand beside each other", () => {
|
||||
const columnWrappers = ancestorsOf(COLUMN);
|
||||
assert.equal(columnWrappers.at(-1), "sheet-layout", "the column stands in the sheet's own layout");
|
||||
for (const key of TAB_KEYS) {
|
||||
assert.deepEqual(
|
||||
ancestorsOf(`<main v-show="activeTab === '${key}'"`),
|
||||
columnWrappers,
|
||||
`the ${key} tab is a sibling of the column, so it is never wrapped around it`
|
||||
);
|
||||
}
|
||||
|
||||
const layout = /\.sheet-layout\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
|
||||
assert.match(layout, /display:\s*grid/, "the layout puts the column and the open tab side by side");
|
||||
assert.match(
|
||||
layout,
|
||||
/grid-template-columns:\s*minmax\(200px,\s*34%\)\s+minmax\(0,\s*1fr\)/,
|
||||
"the character keeps its own column and the tab has all the room left"
|
||||
);
|
||||
const columnRule = /\.character-column\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
|
||||
assert.match(columnRule, /grid-column:\s*1/, "the character stands in the first column");
|
||||
const bodyRule = /\.sheet-tab-body\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
|
||||
assert.match(bodyRule, /grid-column:\s*2/, "the open tab takes the space beside it");
|
||||
assert.match(bodyRule, /grid-row:\s*1/, "and on the same row, so switching a tab leaves the column where it was");
|
||||
});
|
||||
|
||||
test("a narrow window stacks the column over the tab instead of hiding it", () => {
|
||||
const narrow = /@media \(max-width: 760px\)\s*\{([\s\S]*?)\n\}/.exec(sheetSource)?.[1] ?? "";
|
||||
assert.match(narrow, /\.sheet-layout\s*\{[^}]*grid-template-columns:\s*1fr/, "the two columns become one");
|
||||
assert.match(
|
||||
narrow,
|
||||
/\.character-column,\s*\.sheet-tab-body\s*\{[^}]*grid-column:\s*1 \/ -1;[^}]*grid-row:\s*auto/,
|
||||
"the column goes over the tab, it does not go away with it"
|
||||
);
|
||||
});
|
||||
|
||||
test("what stays on screen is what the sheet is read for", () => {
|
||||
const column = characterColumn();
|
||||
for (const key of ["armor-class", "speed", "proficiency-bonus", "initiative", "hit-points", "hit-dice"]) {
|
||||
assert.ok(column.includes(`campaigns.character-sheet.${key}`), `the ${key} stays visible from any tab`);
|
||||
}
|
||||
});
|
||||
@@ -43,7 +43,7 @@ const normalizeActor = fromSource(script, /function normalizeActor\(actor\) \{[\
|
||||
const barPercent = fromSource(script, /function barPercent\(current, max\) \{[\s\S]*?\n\}/);
|
||||
const barPool = fromSource(actorRouteSource, /function barPool\(existing, value\) \{[\s\S]*?\n\}/);
|
||||
|
||||
// The column that opens the abilities tab: the portrait with everything under it.
|
||||
// The column that stands beside every tab: the portrait with everything under it.
|
||||
function portraitColumn() {
|
||||
const start = template.indexOf('<div class="character-column">');
|
||||
const end = template.indexOf('<section class="sheet-panel abilities-panel">');
|
||||
|
||||
@@ -53,7 +53,6 @@ function tabBody(key) {
|
||||
|
||||
test("every tab shows only its own content and hides the others", () => {
|
||||
const abilities = tabBody("abilities");
|
||||
assert.match(abilities, /class="sheet-portrait"/, "the portrait stays with ability scores");
|
||||
assert.match(abilities, /class="sheet-panel abilities-panel"/);
|
||||
assert.match(abilities, /class="sheet-panel proficiencies-panel"/, "the proficiencies ride with the ability scores");
|
||||
for (const other of ["inventory-panel", "traits-panel", "spells-panel"]) {
|
||||
@@ -63,7 +62,12 @@ test("every tab shows only its own content and hides the others", () => {
|
||||
for (const [key, panel] of [["inventory", "inventory-panel"], ["traits", "traits-panel"], ["spells", "spells-panel"]]) {
|
||||
const body = tabBody(key);
|
||||
assert.ok(body.includes(panel), `the ${key} tab shows the ${panel}`);
|
||||
assert.doesNotMatch(body, /class="sheet-portrait"/);
|
||||
}
|
||||
|
||||
// #91 took the character column out of the tabs: it stands beside every one of them, so no tab
|
||||
// body holds the portrait (see tests/character-sheet-persistent-column.test.js).
|
||||
for (const key of ["abilities", "inventory", "traits", "spells"]) {
|
||||
assert.doesNotMatch(tabBody(key), /class="sheet-portrait"/, `the portrait is not the ${key} tab's to hide`);
|
||||
}
|
||||
|
||||
// the panels are toggled, not unmounted, so editing on one tab and flipping away keeps the draft
|
||||
|
||||
522
tests/character-sheet-traits-items.test.js
Normal file
522
tests/character-sheet-traits-items.test.js
Normal file
@@ -0,0 +1,522 @@
|
||||
// Tests for Syndria98/dragonroll#89: on the character sheet traits and items were all
|
||||
// displayed together and the icons did not load. The world's mapper put every embedded
|
||||
// document that was not a class, subclass, background or spell into the character's
|
||||
// inventory — so its traits (feat items) and its species (the race item) stood in the
|
||||
// inventory list beside the gear, while the sheet already shows both in fields of their
|
||||
// own. And a world image that arrives as a Foundry path — the bridge's snapshot and older
|
||||
// modules send those, where the module sends absolute URLs — was read against Dragonroll's
|
||||
// uploads folder, where nothing of that name is, so nothing loaded.
|
||||
//
|
||||
// The mapper is plain CommonJS and is required for real. The writers run in a stubbed
|
||||
// `require` against fake models, like tests/foundry-force-import.test.js runs them. And
|
||||
// since the campaign's inventory no longer claims trait and species documents, the module
|
||||
// must stop deleting ones earlier syncs marked as its own: the Foundry module goes into a
|
||||
// `node:vm` context holding stubbed Foundry globals with fake timers, like
|
||||
// tests/foundry-actor-details.test.js, so what writing a character leaves behind is observable.
|
||||
//
|
||||
// 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));
|
||||
const MODULE_ID = "dragonroll-foundry";
|
||||
|
||||
// --- What the world's mapper keeps where -------------------------------------------------
|
||||
|
||||
const { foundryActorToCharacter } = require(path.join(__dirname, "..", "backend", "src", "services", "actor-foundry.js"));
|
||||
|
||||
test("traits and species stand in their own fields, not among the carried items", () => {
|
||||
const character = foundryActorToCharacter({
|
||||
name: "Thalia",
|
||||
system: { details: {} },
|
||||
items: [
|
||||
{ name: "Longsword", type: "weapon", img: "http://vtt.test/icons/sword.svg", system: { quantity: 1, weight: { value: 3 } } },
|
||||
{ name: "Rope", type: "equipment", system: { quantity: 2 } },
|
||||
{ name: "Darkvision", type: "feat", system: { featType: "trs", description: { value: "<p>See in the dark.</p>" } } },
|
||||
{ name: "Human", type: "race" },
|
||||
{ name: "Spellbook", type: "spellbook" },
|
||||
{ name: "Magic Missile", type: "spell" },
|
||||
{ name: "Fighter", type: "class" },
|
||||
{ name: "Oracle", type: "subclass" },
|
||||
{ name: "Soldier", type: "background" },
|
||||
],
|
||||
});
|
||||
|
||||
assert.deepEqual(character.inventory.map((item) => item.name), ["Longsword", "Rope"],
|
||||
"the inventory holds what the character carries, and nothing else");
|
||||
assert.deepEqual(character.inventory[0],
|
||||
{ name: "Longsword", quantity: 1, weight: 3, icon: "http://vtt.test/icons/sword.svg" });
|
||||
assert.equal(character.traits, "Darkvision\nSee in the dark.", "the feat is read as a trait, where the sheet shows it");
|
||||
assert.equal(character.spells, "Magic Missile", "and the spell where its tab shows it");
|
||||
});
|
||||
|
||||
test("gear of a type the mapper has never seen is still carried", () => {
|
||||
const character = foundryActorToCharacter({
|
||||
name: "Thalia",
|
||||
items: [{ name: "Strange Relic", type: "loot", system: { quantity: 1 } }],
|
||||
});
|
||||
|
||||
assert.deepEqual(character.inventory.map((item) => item.name), ["Strange Relic"],
|
||||
"only the listed non-gear types are let out of the inventory");
|
||||
});
|
||||
|
||||
// --- The writers read a world's paths off the world's address ----------------------------
|
||||
|
||||
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 writers use: equality and $or.
|
||||
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;
|
||||
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) {
|
||||
const row = new Document({ campaign: campaignId, ...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)));
|
||||
return model;
|
||||
}
|
||||
|
||||
// The sync writers against fake models. `settings` is what the campaign keeps — the world
|
||||
// address the icons are loaded from stands in it, as it does in the real one.
|
||||
function loadFoundryWriters({ seed = {}, settings } = {}) {
|
||||
const campaign = { _id: "campaign-1", id: "campaign-1", foundryWorldId: "world-1", ...(settings ? { settings } : {}) };
|
||||
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)),
|
||||
};
|
||||
|
||||
const requireStub = (id) => {
|
||||
if (id === "express") return { Router: () => ({ get: () => {}, post: () => {} }) };
|
||||
if (id.startsWith("node:")) return require(id);
|
||||
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 repoRequire(path.join("backend", "src", "services", "actor-foundry.js"));
|
||||
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 (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
|
||||
);
|
||||
return { campaign, models, writers: moduleStub.exports };
|
||||
}
|
||||
|
||||
test("a world image that arrives as a path is stored as the address the sheet can load", async () => {
|
||||
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000/" } } });
|
||||
|
||||
await sync.writers.saveFoundryActor(sync.campaign, {
|
||||
_id: "actor-1",
|
||||
name: "Thalia",
|
||||
type: "character",
|
||||
img: "icons/actors/thalia.svg",
|
||||
items: [
|
||||
{ name: "Torch", type: "loot", img: "icons/tools/torch torch.svg", system: { quantity: 2 } },
|
||||
{ name: "Darkvision", type: "feat", img: "icons/svg/eye.svg" },
|
||||
],
|
||||
});
|
||||
|
||||
const actor = sync.models["../models/Actor"].rows[0];
|
||||
assert.equal(actor.image, "http://vtt.test:30000/icons/actors/thalia.svg", "the portrait is read off the world's address");
|
||||
assert.deepEqual(actor.inventory.map((item) => item.name), ["Torch"], "the feat is not carried into the inventory");
|
||||
assert.equal(actor.inventory[0].icon, "http://vtt.test:30000/icons/tools/torch%20torch.svg", "and the gear's icon is");
|
||||
});
|
||||
|
||||
test("the absolute addresses the module sends travel as they are", async () => {
|
||||
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000" } } });
|
||||
|
||||
await sync.writers.saveFoundryActor(sync.campaign, {
|
||||
_id: "actor-1",
|
||||
name: "Thalia",
|
||||
img: "http://elsewhere.test/portraits/thalia.png",
|
||||
items: [{ name: "Torch", type: "loot", img: "data:image/png;base64,TgA=" }],
|
||||
});
|
||||
|
||||
const actor = sync.models["../models/Actor"].rows[0];
|
||||
assert.equal(actor.image, "http://elsewhere.test/portraits/thalia.png");
|
||||
assert.equal(actor.inventory[0].icon, "data:image/png;base64,TgA=");
|
||||
});
|
||||
|
||||
test("a campaign with no world address keeps the path as it came", async () => {
|
||||
const sync = loadFoundryWriters();
|
||||
|
||||
await sync.writers.saveFoundryActor(sync.campaign, {
|
||||
_id: "actor-1", name: "Thalia", img: "icons/actors/thalia.svg",
|
||||
});
|
||||
|
||||
assert.equal(sync.models["../models/Actor"].rows[0].image, "icons/actors/thalia.svg",
|
||||
"with no world to read it against, nothing is invented for it");
|
||||
});
|
||||
|
||||
test("a world item's icon is read off the world's address the same way", async () => {
|
||||
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000" } } });
|
||||
|
||||
await sync.writers.saveFoundryItem(sync.campaign, {
|
||||
_id: "item-1", name: "Longsword", type: "weapon", img: "icons/equipment/sword.svg",
|
||||
});
|
||||
|
||||
const item = sync.models["../models/Item"].rows[0];
|
||||
assert.equal(item.image, "http://vtt.test:30000/icons/equipment/sword.svg");
|
||||
assert.equal(item.foundryImage, "http://vtt.test:30000/icons/equipment/sword.svg",
|
||||
"the icon the item window offers back is the loadable one too");
|
||||
});
|
||||
|
||||
// --- The module leaves the world's own documents alone ------------------------------------
|
||||
|
||||
function makeStubItem(id, { name, type, system = {}, flags = {} }) {
|
||||
return {
|
||||
_id: id,
|
||||
id,
|
||||
name,
|
||||
type,
|
||||
system,
|
||||
flags,
|
||||
parent: { documentName: "Actor" },
|
||||
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
||||
toObject() {
|
||||
return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: this.flags };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function writeDotted(target, data) {
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
const parts = key.split(".");
|
||||
const last = parts.pop();
|
||||
let node = target;
|
||||
for (const part of parts) node = node[part] ??= {};
|
||||
node[last] = value;
|
||||
}
|
||||
}
|
||||
|
||||
let stubCounter = 0;
|
||||
|
||||
function makeStubActor(name, { type = "character", system = {}, flags = {}, items = [] } = {}) {
|
||||
stubCounter += 1;
|
||||
const id = `actor-${stubCounter}`;
|
||||
const contents = items.map((item, index) => makeStubItem(item._id || `embedded-${stubCounter}-${index}`, item));
|
||||
const actor = {
|
||||
id,
|
||||
name,
|
||||
type,
|
||||
documentName: "Actor",
|
||||
img: "icons/svg/mystery-man.svg",
|
||||
system,
|
||||
flags,
|
||||
items: { contents },
|
||||
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
||||
async update(data) {
|
||||
writeDotted(this, data);
|
||||
return this;
|
||||
},
|
||||
async updateEmbeddedDocuments(documentName, updates) {
|
||||
for (const update of updates) {
|
||||
const item = contents.find((candidate) => candidate.id === update._id);
|
||||
if (item) writeDotted(item, update);
|
||||
}
|
||||
return updates.map((update) => contents.find((candidate) => candidate.id === update._id));
|
||||
},
|
||||
async createEmbeddedDocuments(documentName, datas) {
|
||||
const created = datas.map((data) => {
|
||||
const item = makeStubItem(`embedded-${stubCounter}-${contents.length}`, data);
|
||||
contents.push(item);
|
||||
return item;
|
||||
});
|
||||
return created;
|
||||
},
|
||||
async deleteEmbeddedDocuments(documentName, ids) {
|
||||
for (const id of ids) {
|
||||
const index = contents.findIndex((item) => item.id === id);
|
||||
if (index >= 0) contents.splice(index, 1);
|
||||
}
|
||||
return ids;
|
||||
},
|
||||
toObject() {
|
||||
return {
|
||||
_id: this.id,
|
||||
name: this.name,
|
||||
type: this.type,
|
||||
img: this.img,
|
||||
flags: this.flags,
|
||||
system: this.system,
|
||||
};
|
||||
},
|
||||
};
|
||||
return actor;
|
||||
}
|
||||
|
||||
function makeWorld({ actors = [], remoteActors = [] } = {}) {
|
||||
const state = {
|
||||
hooks: new Map(),
|
||||
registered: new Map(),
|
||||
requests: [],
|
||||
timers: new Map(),
|
||||
nextTimerId: 1,
|
||||
logs: [],
|
||||
};
|
||||
|
||||
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
|
||||
const sandbox = {
|
||||
console: {
|
||||
log() {},
|
||||
info() {},
|
||||
warn: (...args) => state.logs.push(args.map(String).join(" ")),
|
||||
error: (...args) => state.logs.push(args.map(String).join(" ")),
|
||||
},
|
||||
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 timerId = state.nextTimerId++;
|
||||
state.timers.set(timerId, { fn, delay });
|
||||
return timerId;
|
||||
},
|
||||
clearTimeout: (timerId) => state.timers.delete(timerId),
|
||||
setInterval: () => 0,
|
||||
clearInterval: () => {},
|
||||
fetch: async (url, options = {}) => {
|
||||
const href = String(url);
|
||||
state.requests.push({ href, method: options.method, body: options.body ? JSON.parse(options.body) : null });
|
||||
if (href.includes("foundry/sync/characters")) return { ok: true, status: 200, json: async () => ({ status: "ok", actors: remoteActors }) };
|
||||
if (href.includes("foundry/sync/items")) return { ok: true, status: 200, json: async () => ({ status: "ok", items: [] }) };
|
||||
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
|
||||
},
|
||||
Item: { async create() { return null; } },
|
||||
Actor: {
|
||||
async create(data) {
|
||||
const actor = makeStubActor(data.name, {
|
||||
type: data.type,
|
||||
system: structuredClone(data.system || {}),
|
||||
flags: structuredClone(data.flags || {}),
|
||||
items: (data.items || []).map((item) => ({ name: item.name, type: item.type, system: item.system })),
|
||||
});
|
||||
actors.push(actor);
|
||||
return actor;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
sandbox.game = {
|
||||
user: { isGM: true },
|
||||
world: { id: "world-1", title: "Test World" },
|
||||
system: { id: "dnd5e" },
|
||||
modules: { get: () => ({}) },
|
||||
actors: { contents: actors, get: (actorId) => actors.find((actor) => actor.id === actorId) },
|
||||
items: { contents: [], get: () => null },
|
||||
folders: { contents: [], get: () => null },
|
||||
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;
|
||||
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
|
||||
|
||||
// World start: the actors are pushed, then the campaign's characters are applied.
|
||||
state.start = async () => {
|
||||
await state.fire("init");
|
||||
await state.fire("ready");
|
||||
await state.runTimers();
|
||||
return state;
|
||||
};
|
||||
|
||||
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.itemNames = (actor) => actor.items.contents.map((item) => [item.type, item.name]);
|
||||
state.actorPushes = () => state.requests
|
||||
.filter((request) => request.href.includes("foundry/sync/snapshot"))
|
||||
.map((request) => request.body.actors[0]);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
// The campaign's character for `actor`, holding what Dragonroll keeps for it.
|
||||
function campaignCharacter(actor, over = {}) {
|
||||
return {
|
||||
_id: "dr-actor-1",
|
||||
name: "Thalia",
|
||||
type: "character",
|
||||
species: "",
|
||||
className: "",
|
||||
subclass: "",
|
||||
level: 1,
|
||||
background: "",
|
||||
challengeRating: "",
|
||||
description: "",
|
||||
image: "",
|
||||
abilityScores: {},
|
||||
armorClass: 10,
|
||||
speed: 30,
|
||||
traits: "",
|
||||
proficiencies: "",
|
||||
spells: "",
|
||||
inventory: [],
|
||||
foundryActorId: actor?.id ?? null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
test("a trait row an older campaign left in the inventory does not become a loot duplicate", async () => {
|
||||
// A campaign that synced before #89 still carries its world's traits as inventory
|
||||
// rows. Writing the character must neither make a piece of loot after a trait's name
|
||||
// nor touch the world's feat it holds that name — the row is the campaign's to write
|
||||
// off, and the document is the world's to keep.
|
||||
const actor = makeStubActor("Thalia", {
|
||||
system: { details: {} },
|
||||
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
|
||||
items: [{ _id: "feat-1", name: "Darkvision", type: "feat", system: { featType: "trs" } }],
|
||||
});
|
||||
const world = await makeWorld({
|
||||
actors: [actor],
|
||||
remoteActors: [campaignCharacter(actor, {
|
||||
traits: "Darkvision\nSee in the dark.",
|
||||
inventory: [{ name: "Darkvision", quantity: 1, weight: 0 }],
|
||||
})],
|
||||
}).start();
|
||||
|
||||
assert.deepEqual(world.itemNames(actor), [["feat", "Darkvision"]],
|
||||
"no gear made after the trait's name, and the feat stands where it was");
|
||||
assert.equal(actor.items.contents[0].system.quantity, undefined, "the world's feat is not written as gear");
|
||||
assert.deepEqual(world.logs, [], "applying the character did not warn");
|
||||
});
|
||||
|
||||
test("writing the character leaves the world's trait and species documents where they stand", async () => {
|
||||
// An earlier sync marked everything in the actor as its own. The campaign no longer
|
||||
// carries traits and species in the inventory, so those marks must not cost the world
|
||||
// its documents — while loot the campaign truly dropped still goes.
|
||||
const actor = makeStubActor("Thalia", {
|
||||
system: { details: {} },
|
||||
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
|
||||
items: [
|
||||
{ _id: "feat-1", name: "Darkvision", type: "feat", flags: { [MODULE_ID]: { syncedItem: true } } },
|
||||
{ _id: "race-1", name: "Human", type: "race", flags: { [MODULE_ID]: { syncedItem: true } } },
|
||||
{ _id: "loot-old", name: "Torch", type: "loot", flags: { [MODULE_ID]: { syncedItem: true } } },
|
||||
],
|
||||
});
|
||||
const world = await makeWorld({
|
||||
actors: [actor],
|
||||
remoteActors: [campaignCharacter(actor, {
|
||||
species: "Human",
|
||||
traits: "Darkvision\nSee in the dark.",
|
||||
inventory: [{ name: "Rations", quantity: 1, weight: 0.5 }],
|
||||
})],
|
||||
}).start();
|
||||
|
||||
assert.deepEqual(world.itemNames(actor), [
|
||||
["feat", "Darkvision"],
|
||||
["race", "Human"],
|
||||
["loot", "Rations"],
|
||||
], "the trait and the species survive, the carried gear follows the campaign");
|
||||
assert.equal(actor.system.details.race, "race-1", "the species reference still resolves to the surviving item");
|
||||
assert.deepEqual(world.logs, [], "applying the character did not warn");
|
||||
});
|
||||
|
||||
test("the snapshot marks the carried gear and no longer the world's own documents", async () => {
|
||||
const actor = makeStubActor("Grimnir", {
|
||||
system: { details: {} },
|
||||
items: [
|
||||
{ name: "Longsword", type: "weapon" },
|
||||
{ name: "Darkvision", type: "feat" },
|
||||
{ name: "Giant", type: "race" },
|
||||
],
|
||||
});
|
||||
await makeWorld({ actors: [actor], remoteActors: [] }).start();
|
||||
|
||||
const [sword, feat, race] = actor.items.contents;
|
||||
assert.equal(sword.getFlag(MODULE_ID, "syncedItem"), true, "the gear the campaign carries is marked as its own");
|
||||
assert.equal(feat.getFlag(MODULE_ID, "syncedItem"), undefined, "a trait is not");
|
||||
assert.equal(race.getFlag(MODULE_ID, "syncedItem"), undefined, "neither is a species");
|
||||
});
|
||||
|
||||
test("an actor snapshot still sends the feats its traits are made of", async () => {
|
||||
// Leaving feats out of the inventory must not leave them out of the snapshot: they are
|
||||
// what the campaign's traits tab reads.
|
||||
const actor = makeStubActor("Thalia", {
|
||||
system: { details: {} },
|
||||
items: [{ name: "Darkvision", type: "feat", system: { featType: "trs" } }],
|
||||
});
|
||||
const world = await makeWorld({ actors: [actor], remoteActors: [] }).start();
|
||||
|
||||
const sent = world.actorPushes().at(-1);
|
||||
assert.deepEqual(sent.items.map((item) => [item.type, item.name]), [["feat", "Darkvision"]],
|
||||
"the feat still travels with its actor, as the traits text is read off it");
|
||||
});
|
||||
@@ -280,6 +280,7 @@ function loadFoundryWriters({ seed = {} } = {}) {
|
||||
if (id === "../models/Campaign") return { findOne: async () => campaign };
|
||||
if (id === "../services/actor-foundry") return repoRequire(path.join("backend", "src", "services", "actor-foundry.js"));
|
||||
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 (models[id]) return models[id];
|
||||
throw new Error(`require("${id}") is not stubbed`);
|
||||
};
|
||||
|
||||
@@ -141,6 +141,7 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
|
||||
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 (models[id]) return models[id];
|
||||
throw new Error(`require("${id}") is not stubbed`);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user