// Tests for the walls of maps (Syndria98/dragonroll#100): a wall editor on the map viewer, the // walls kept on the map document, and the sync that lets a paired Foundry scene and a campaign // map trade the same segments. // // Like map-pins.test.js, the express routers run against a stubbed `require` inside `node:vm`, // the `MapWalls.js` service is loaded the way the map tests load the other services, and the // Foundry module is loaded into a stubbed Foundry world whose embedded-document writes are // observable. The last checks read the template of the map viewer, because there the wiring // itself is what has to stay right. // // 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 MODULE_ID = "dragonroll-foundry"; function readRepoFile(...parts) { return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8"); } // A mongoose query answers whatever `await query` and `query.lean()` answer with, and lets // `select()` and `sort()` sit in between. function mongooseQuery(value) { const result = { select: () => result, sort: () => result, lean: () => Promise.resolve(value), then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected), }; return result; } // Loads an express router file with every module it requires stubbed out: `stubs` maps a require // path to the module the route should see. function loadRouter(relativeParts, stubs) { const routes = new Map(); const router = { get: (route, ...handlers) => routes.set(`GET ${route}`, handlers), post: (route, ...handlers) => routes.set(`POST ${route}`, handlers), }; const requireStub = (id) => { if (id === "express") return { Router: () => router }; if (id === "../services/storage") return { single: () => (req, res, next) => next() }; if (!(id in stubs)) throw new Error(`require("${id}") is not stubbed`); return stubs[id]; }; const moduleStub = { exports: {} }; vm.compileFunction(readRepoFile(...relativeParts), ["require", "module", "exports"])( requireStub, moduleStub, moduleStub.exports ); async function call(route, { body = {}, query = {}, params = {}, user = { id: "user-1" }, get = () => "" } = {}) { const handlers = routes.get(route); assert.ok(handlers, `${route} is not mounted`); const res = { payload: null, json(payload) { this.payload = payload; } }; await handlers[handlers.length - 1]({ body, query, params, user, get }, res); return res.payload; } return { routes, call }; } // --- POST /map/walls: the wall editor's save ------------------------------------------------ function makeMapDoc(walls = []) { return { _id: "map-1", campaign: "campaign-1", walls, save: async () => {} }; } function loadMapRoutes({ ownsCampaign = true, maps = [] } = {}) { return loadRouter(["backend", "src", "routes", "map.js"], { "../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) }, "../models/Map": { findById: (id) => mongooseQuery(maps.find((map) => map._id === id) ?? null) }, "../models/Note": { findOne: () => mongooseQuery(null) }, "../models/Actor": { findOne: () => mongooseQuery(null) }, "../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true }, }); } function wallSaveRouteTests() { test("the wall editor saves the whole set, sanitised to whole image pixels", async () => { const map = makeMapDoc(); const api = loadMapRoutes({ maps: [map] }); const response = await api.call("POST /walls", { body: { id: "map-1", walls: [ // Coordinates arrive as strings from a form-ish body and can leave the image. { x1: "10.4", y1: -8, x2: 50, y2: 50.5, move: false }, { _id: "wall-2", x1: 100, y1: 0, x2: 100, y2: 75, door: 2 }, ], }, }); assert.equal(response.status, "ok"); assert.deepEqual(map.walls, [ { x1: 10, y1: 0, x2: 50, y2: 51, move: false, sight: true, door: 0 }, { _id: "wall-2", x1: 100, y1: 0, x2: 100, y2: 75, move: true, sight: true, door: 2 }, ]); }); test("a save replaces the set: walls the editor dropped are gone", async () => { const map = makeMapDoc([ { _id: "wall-1", x1: 0, y1: 0, x2: 50, y2: 0 }, { _id: "wall-2", x1: 0, y1: 0, x2: 0, y2: 50 }, ]); const api = loadMapRoutes({ maps: [map] }); await api.call("POST /walls", { body: { id: "map-1", walls: [{ _id: "wall-2", x1: 5, y1: 5, x2: 0, y2: 60 }] } }); assert.deepEqual(map.walls.map((wall) => String(wall._id)), ["wall-2"]); assert.equal(map.walls[0].y1, 5); }); test("segments without length or with unreadable endpoints are dropped", async () => { const map = makeMapDoc(); const api = loadMapRoutes({ maps: [map] }); await api.call("POST /walls", { body: { id: "map-1", walls: [ { x1: 40, y1: 40, x2: 40, y2: 40 }, { x1: "wide", y1: 0, x2: 50, y2: 50 }, { x1: 0, y1: 0, x2: 50, y2: 50 }, ], }, }); assert.equal(map.walls.length, 1); }); test("an unknown _id does not smuggle an id into the set, and a door outside 1 and 2 is no door", async () => { const map = makeMapDoc([{ _id: "wall-1", x1: 0, y1: 0, x2: 50, y2: 0 }]); const api = loadMapRoutes({ maps: [map] }); await api.call("POST /walls", { body: { id: "map-1", walls: [ { _id: "wall-9", x1: 0, y1: 0, x2: 50, y2: 0, door: 5 }, { _id: "wall-1", x1: 60, y1: 0, x2: 60, y2: 50, door: "1" }, ], }, }); assert.deepEqual(map.walls, [ { x1: 0, y1: 0, x2: 50, y2: 0, move: true, sight: true, door: 0 }, { _id: "wall-1", x1: 60, y1: 0, x2: 60, y2: 50, move: true, sight: true, door: 1 }, ]); }); test("saving walls needs the map and an array, and only of one's own campaign", async () => { const map = makeMapDoc(); const api = loadMapRoutes({ maps: [map] }); const foreign = loadMapRoutes({ ownsCampaign: false, maps: [makeMapDoc()] }); assert.equal((await api.call("POST /walls", { body: { walls: [] } })).msg, "errors.missing-data"); assert.equal((await api.call("POST /walls", { body: { id: "map-1" } })).msg, "errors.missing-data"); assert.equal((await api.call("POST /walls", { body: { id: "map-1", walls: "nope" } })).msg, "errors.missing-data"); assert.equal((await api.call("POST /walls", { body: { id: "map-404", walls: [] } })).msg, "errors.notfound"); assert.equal((await foreign.call("POST /walls", { body: { id: "map-1", walls: [] } })).msg, "unauthorized"); assert.deepEqual(map.walls, []); }); } // --- The module's sync routes: pairing a scene and trading wall sets ------------------------- function loadSyncRoutes({ campaign = { _id: "campaign-1", foundryWorldId: "world-1", settings: {} }, maps = [] } = {}) { const matches = (map, filter) => { if (filter._id !== undefined) { if (typeof filter._id === "object" && filter._id.$ne !== undefined) { if (String(map._id) === String(filter._id.$ne)) return false; } else if (String(map._id) !== String(filter._id)) return false; } if (filter.campaign !== undefined && String(map.campaign) !== String(filter.campaign)) return false; if (filter.foundrySceneId !== undefined && String(map.foundrySceneId ?? "") !== String(filter.foundrySceneId)) return false; return true; }; return loadRouter(["backend", "src", "routes", "foundry-link.js"], { "node:crypto": require("node:crypto"), mongoose: { isValidObjectId: () => false }, "../models/Campaign": { findOne: () => mongooseQuery(campaign) }, "../models/Actor": { find: () => mongooseQuery([]), findOne: () => mongooseQuery(null) }, "../models/Item": { find: () => mongooseQuery([]), findOne: () => mongooseQuery(null) }, "../models/Folder": { find: () => mongooseQuery([]) }, "../models/Map": { find: (filter) => mongooseQuery(maps.filter((map) => matches(map, filter))), findOne: (filter) => mongooseQuery(maps.find((map) => matches(map, filter)) ?? null), }, "../services/actor-foundry": { foundryActorToCharacter: () => ({}) }, "../services/item-foundry": { foundryItemToItemData: () => null }, "../services/foundry-icons": { joinFoundryAssetUrl: () => "" }, }); } // The sync routes authenticate with the token, not a JWT. function asModule(request) { return { ...request, get: (name) => (String(name).toLowerCase() === "authorization" ? "Bearer sync-token-1" : "") }; } function syncRoutesTests() { test("the module reads the campaign's maps with their walls and pairings", async () => { const maps = [ { _id: "map-1", campaign: "campaign-1", name: "Dungeon", image: "d.png", foundrySceneId: "scene-1", walls: [{ x1: 0, y1: 0, x2: 50, y2: 0 }] }, { _id: "map-2", campaign: "campaign-1", name: "Town", image: "", foundrySceneId: null, walls: [] }, ]; const api = loadSyncRoutes({ maps }); const response = await api.call("GET /sync/maps", asModule({})); assert.equal(response.status, "ok"); assert.deepEqual(response.maps.map((map) => map.name), ["Dungeon", "Town"]); assert.deepEqual(response.maps[0].walls, [{ x1: 0, y1: 0, x2: 50, y2: 0 }]); }); test("a paired scene's whole wall set replaces the map's, sanitised", async () => { const map = { _id: "map-1", campaign: "campaign-1", name: "Dungeon", foundrySceneId: "scene-1", walls: [{ x1: 9, y1: 9, x2: 9, y2: 60 }], save: async () => {} }; const api = loadSyncRoutes({ maps: [map] }); const response = await api.call("POST /sync/map-walls", asModule({ body: { worldId: "world-1", foundrySceneId: "scene-1", walls: [ { x1: 10.4, y1: -3, x2: 60, y2: 50.5, move: true, sight: false, door: 0 }, { x1: 0, y1: 0, x2: 0, y2: 0, door: 2 }, { x1: 0, y1: 0, x2: 50, y2: 0, door: 1 }, ], }, })); assert.equal(response.status, "ok"); assert.deepEqual(map.walls, [ { x1: 10, y1: 0, x2: 60, y2: 51, move: true, sight: false, door: 0 }, { x1: 0, y1: 0, x2: 50, y2: 0, move: true, sight: true, door: 1 }, ]); }); test("a scene with no paired map answers notfound and changes no map", async () => { const map = { _id: "map-1", campaign: "campaign-1", name: "Dungeon", foundrySceneId: "scene-1", walls: [{ x1: 0, y1: 0, x2: 50, y2: 50 }], save: async () => {} }; const api = loadSyncRoutes({ maps: [map] }); const response = await api.call("POST /sync/map-walls", asModule({ body: { worldId: "world-1", foundrySceneId: "scene-2", walls: [] }, })); assert.equal(response.msg, "errors.notfound"); assert.equal(map.walls.length, 1); }); test("the wall push needs the paired world, the scene and an array", async () => { const map = { _id: "map-1", campaign: "campaign-1", name: "Dungeon", foundrySceneId: "scene-1", walls: [{ x1: 0, y1: 0, x2: 50, y2: 50 }], save: async () => {} }; const api = loadSyncRoutes({ maps: [map] }); const wrongWorld = await api.call("POST /sync/map-walls", asModule({ body: { worldId: "world-2", foundrySceneId: "scene-1", walls: [] } })); const noScene = await api.call("POST /sync/map-walls", asModule({ body: { worldId: "world-1", walls: [] } })); const noWalls = await api.call("POST /sync/map-walls", asModule({ body: { worldId: "world-1", foundrySceneId: "scene-1" } })); assert.deepEqual([wrongWorld.msg, noScene.msg, noWalls.msg], ["errors.missing-data", "errors.missing-data", "errors.missing-data"]); assert.equal(map.walls.length, 1); }); test("an unauthenticated module hears nothing but unauthorized", async () => { const api = loadSyncRoutes({ maps: [] }); const response = await api.call("GET /sync/maps", { get: () => "" }); assert.equal(response.msg, "unauthorized"); }); test("pairing a map with a scene records it, and one scene walls one map at most", async () => { const maps = [ { _id: "map-1", campaign: "campaign-1", name: "Dungeon", foundrySceneId: null, walls: [], save: async () => {} }, { _id: "map-2", campaign: "campaign-1", name: "Crypt", foundrySceneId: "scene-1", walls: [], save: async () => {} }, ]; const api = loadSyncRoutes({ maps }); const taken = await api.call("POST /sync/map-scene", asModule({ body: { worldId: "world-1", mapId: "map-1", foundrySceneId: "scene-1" } })); assert.equal(taken.msg, "foundry.errors.scene-already-synced"); assert.equal(maps[0].foundrySceneId, null); const paired = await api.call("POST /sync/map-scene", asModule({ body: { worldId: "world-1", mapId: "map-1", foundrySceneId: "scene-7" } })); assert.equal(paired.status, "ok"); assert.equal(maps[0].foundrySceneId, "scene-7"); }); } // --- The MapWalls service: snapping and drawing --------------------------------------------- function loadMapWallsService() { const source = readRepoFile("frontend", "app", "services", "MapWalls.js"); const body = source.replace(/export\s*\{/, "return {").concat("\n;"); return vm.compileFunction(body, [])(); } function mapWallsServiceTests() { const service = loadMapWallsService(); // 800x600 image, shown at 200% and panned so its top left corner sits at (20, 10) of the viewport. const view = { zoom: 2, pan: { x: 20, y: 10 }, width: 800, height: 600 }; const grid = { gridSize: 50, offsetX: 10, offsetY: 0 }; test("a spot of the viewport becomes the image pixel it stands for, clamped but never refused", () => { assert.deepEqual(service.ToDrawPoint({ x: 100, y: 50 }, view), { x: 40, y: 20 }); // A drag over the edge keeps drawing at the edge instead of dropping the wall. assert.deepEqual(service.ToDrawPoint({ x: 0, y: 50 }, view), { x: 0, y: 20 }); assert.equal(service.ToDrawPoint({ x: 100, y: 50 }, { zoom: 0, pan: { x: 0, y: 0 } }), null); }); test("endpoints snap to the nearest grid intersection, offset included", () => { assert.deepEqual(service.SnapToGrid({ x: 112, y: 24 }, grid), { x: 110, y: 0 }); assert.deepEqual(service.SnapToGrid({ x: 112, y: 26 }, grid), { x: 110, y: 50 }); assert.deepEqual(service.SnapToGrid({ x: -8, y: -8 }, grid), { x: 0, y: 0 }); assert.equal(service.SnapToGrid(null, grid), null); }); test("a wall becomes the screen line that draws it", () => { assert.deepEqual(service.ToScreenWall({ x1: 40, y1: 20, x2: 90, y2: 70 }, view), { x1: 100, y1: 50, x2: 200, y2: 150 }); assert.deepEqual(service.ToScreenWall({}, view), { x1: 20, y1: 10, x2: 20, y2: 10 }); }); test("a slid wall keeps its shape and goes nowhere off the image", () => { assert.deepEqual(service.MoveWall({ x1: 10, y1: 10, x2: 60, y2: 10 }, 13.4, -5.6), { x1: 23, y1: 4, x2: 73, y2: 4 }); assert.deepEqual(service.MoveWall({ x1: 5, y1: 5, x2: 5, y2: 55 }, -10, 0), { x1: 0, y1: 0, x2: 0, y2: 50 }); assert.equal(service.MoveWall({ x1: 0, y1: 0, x2: 5, y2: 5 }, "x", 0), null); }); test("a segment with no length is no wall", () => { assert.equal(service.IsWall({ x1: 40, y1: 40, x2: 41, y2: 40 }), true); assert.equal(service.IsWall({ x1: 40, y1: 40, x2: 40, y2: 40 }), false); assert.equal(service.IsWall(null), false); assert.equal(service.IsWall({ x1: 0, y1: 0, x2: 0 }), false); }); } // --- The Foundry module: pairing scenes, trading wall sets ----------------------------------- function makeWallWorld({ autoSync = true, maps = [], scenes = [], pairedSceneIds = null } = {}) { const state = { hooks: new Map(), registered: new Map(), requests: [], notifications: [], timers: new Map(), nextTimerId: 1, maps, embeddedWrites: [], pairedSceneIds, }; const settingsStore = { autoSync, 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: (text) => state.notifications.push(["info", text]), warn: (text) => state.notifications.push(["warn", text]), error: (text) => state.notifications.push(["error", text]), }, }, Hooks: { once(name, fn) { state.hooks.set(name, [fn]); }, on(name, fn) { const handlers = state.hooks.get(name) || []; handlers.push(fn); state.hooks.set(name, handlers); }, }, 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 = {}) => { const href = String(url); const body = options.body ? JSON.parse(options.body) : null; state.requests.push({ href, method: options.method, body }); if (href.includes("foundry/sync/maps")) { return { ok: true, status: 200, json: async () => ({ status: "ok", maps: state.maps }) }; } if (href.includes("foundry/sync/map-walls") && state.pairedSceneIds && !state.pairedSceneIds.includes(body?.foundrySceneId)) { return { ok: true, status: 200, json: async () => ({ status: "error", msg: "errors.notfound" }) }; } return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [], folders: [] }) }; }, 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: [], get: () => null }, items: { contents: [], get: () => null }, folders: { contents: [] }, scenes: { contents: scenes, get: (id) => scenes.find((scene) => scene.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(readRepoFile("dragonroll-foundry", "scripts", "api.js"), sandbox); state.game = sandbox.game; // A scene holding Foundry-shape wall documents. Its embedded writes are recorded, and — // like the real client — each one fires the scene's wall hooks while the write is under way. state.makeScene = (id, name, walls = []) => { const scene = { id, name, documentName: "Scene", wallDocuments: { contents: walls }, async updateEmbeddedDocuments(kind, updates) { state.embeddedWrites.push([kind, "update", updates]); for (const update of updates) { const wall = walls.find((current) => current.id === update._id); const { _id, ...rest } = update; Object.assign(wall, rest); } await state.fireSync("updateWall", walls.map((wall) => ({ documentName: "Wall", id: wall.id, parent: scene }))); }, async createEmbeddedDocuments(kind, creates) { state.embeddedWrites.push([kind, "create", creates]); const created = creates.map((data, index) => ({ id: `${id}-wall-${index}`, ...data })); walls.push(...created); await state.fireSync("createWall", created.map((wall) => ({ documentName: "Wall", id: wall.id, parent: scene }))); }, async deleteEmbeddedDocuments(kind, ids) { state.embeddedWrites.push([kind, "delete", ids]); for (const documentId of ids) { const index = walls.findIndex((wall) => wall.id === documentId); if (index >= 0) walls.splice(index, 1); } await state.fireSync("deleteWall", ids.map((documentId) => ({ documentName: "Wall", id: documentId, parent: scene }))); }, }; return scene; }; // Fire a wall hook through the sandboxed Hooks registry without awaiting each handler: the // real client fires wall hooks synchronously while a write runs. state.fireSync = (name, documents) => { for (const handler of state.hooks.get(name) || []) { for (const document of documents) handler(document); } }; 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 < 8; 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(); } }; async function drain() { await new Promise((resolve) => setImmediate(resolve)); } state.linkedSetup = async () => { await state.fire("init"); await state.fire("ready"); await state.runTimers(); state.requests.length = 0; state.embeddedWrites.length = 0; return state; }; state.wallPushes = () => state.requests.filter((request) => request.href.includes("foundry/sync/map-walls")); state.scenePairings = () => state.requests.filter((request) => request.href.includes("foundry/sync/map-scene")); return state; } function foundryModuleWallTests() { test("a GM's wall edit pushes the scene's whole set, in the campaign's shape", async () => { const scene = makeWallWorld().makeScene("scene-1", "Dungeon", [ { id: "wall-1", c: [10.4, -3, 60, 50.5], light: 2, sense: 2, move: 1, door: 0, ds: 0 }, { id: "wall-2", c: [0, 0, 50, 0], light: 0, sense: 0, move: 0, door: 2, ds: 1 }, ]); const world = await scene.linkedSetup(); await world.fire("updateWall", { documentName: "Wall", id: "wall-2", parent: scene }); await world.runTimers(); const pushes = world.wallPushes(); assert.equal(pushes.length, 1); assert.equal(pushes[0].body.foundrySceneId, "scene-1"); assert.deepEqual(pushes[0].body.walls, [ { x1: 10, y1: 0, x2: 60, y2: 51, move: true, sight: true, door: 0 }, { x1: 0, y1: 0, x2: 50, y2: 0, move: false, sight: false, door: 1 }, ]); assert.deepEqual(world.embeddedWrites, []); }); test("the campaign's set lands on its paired scene: changed walls written, extra ones deleted", async () => { const world = makeWallWorld({ maps: [{ _id: "map-1", name: "Dungeon", foundrySceneId: "scene-1", walls: [ { x1: 0, y1: 0, x2: 50, y2: 0, move: true, sight: true, door: 0 }, { x1: 50, y1: 0, x2: 50, y2: 100, move: false, sight: true, door: 2 }, ], }], scenes: [], }); const scene = world.makeScene("scene-1", "Dungeon", [ { id: "wall-1", c: [0, 0, 50, 0], light: 2, sense: 2, move: 1, door: 0, ds: 0 }, { id: "wall-2", c: [0, 0, 0, 80], light: 2, sense: 2, move: 1, door: 0, ds: 0 }, { id: "wall-3", c: [90, 90, 120, 90], light: 2, sense: 2, move: 1, door: 0, ds: 0 }, ]); world.game.scenes.contents.push(scene); await world.fire("init"); await world.fire("ready"); await world.runTimers(); // wall-1 already stands where the campaign wants it and is left alone; wall-2 is // retyped into the campaign's second segment; wall-3 is beyond the set and goes. const updates = world.embeddedWrites.find(([, kind, payload]) => kind === "update" && payload.length)?.[2]; assert.deepEqual(updates, [{ _id: "wall-2", c: [50, 0, 50, 100], light: 2, sense: 2, move: 0, door: 2, ds: 0, }]); const deletes = world.embeddedWrites.find(([, kind, payload]) => kind === "delete")?.[2]; assert.deepEqual(deletes, ["wall-3"]); // The set landed on the scene is exactly the campaign's: it reads back unchanged, so the // writes are not echoed to the campaign. assert.deepEqual(world.wallPushes(), []); }); test("a map with no walls adopts the walls the scene already has", async () => { const world = makeWallWorld({ maps: [{ _id: "map-1", name: "Crypt", foundrySceneId: "scene-1", walls: [] }], scenes: [], }); const scene = world.makeScene("scene-1", "Crypt", [ { id: "wall-1", c: [0, 0, 100, 0], light: 2, sense: 2, move: 1, door: 0, ds: 0 }, ]); world.game.scenes.contents.push(scene); await world.fire("init"); await world.fire("ready"); await world.runTimers(); const pushes = world.wallPushes(); assert.equal(pushes.length, 1); assert.deepEqual(pushes[0].body.walls, [ { x1: 0, y1: 0, x2: 100, y2: 0, move: true, sight: true, door: 0 }, ]); assert.deepEqual(world.embeddedWrites, []); }); test("a campaign map pairs with the scene of its name, and only when it is the only one", async () => { const paired = makeWallWorld({ maps: [{ _id: "map-1", name: "Dungeon", foundrySceneId: null, walls: [{ x1: 10, y1: 10, x2: 60, y2: 60 }] }], scenes: [], }); const scene = paired.makeScene("scene-1", "Dungeon", []); paired.game.scenes.contents.push(scene); await paired.fire("init"); await paired.fire("ready"); await paired.runTimers(); const pairings = paired.scenePairings(); assert.equal(pairings.length, 1); assert.deepEqual(pairings[0].body, { worldId: "world-1", mapId: "map-1", foundrySceneId: "scene-1" }); // Paired, the campaign's wall lands as a new wall document on the scene. const creates = paired.embeddedWrites.find(([, kind, payload]) => kind === "create")?.[2]; assert.deepEqual(creates, [{ c: [10, 10, 60, 60], light: 2, sense: 2, move: 1, door: 0, ds: 0 }]); // Two scenes share the name: the map is nobody's by name alone, and nothing is paired or written. const twin = makeWallWorld({ maps: [{ _id: "map-1", name: "Dungeon", foundrySceneId: null, walls: [{ x1: 10, y1: 10, x2: 60, y2: 60 }] }], scenes: [], }); twin.game.scenes.contents.push(twin.makeScene("scene-1", "Dungeon", []), twin.makeScene("scene-2", "Dungeon", [])); await twin.fire("init"); await twin.fire("ready"); await twin.runTimers(); assert.deepEqual(twin.scenePairings(), []); assert.deepEqual(twin.embeddedWrites, []); }); test("a scene no campaign map mirrors is let go of, not retried", async () => { const world = makeWallWorld({ pairedSceneIds: [] }); const scene = world.makeScene("scene-9", "Not a map", [ { id: "wall-1", c: [0, 0, 50, 50], light: 2, sense: 2, move: 1, door: 0, ds: 0 }, ]); await world.linkedSetup(); world.game.scenes.contents.push(scene); await world.fire("createWall", { documentName: "Wall", id: "wall-1", parent: scene }); await world.runTimers(); // The push was made once and, hearing the campaign keeps no map for this scene, the // module stops asking about it again. assert.equal(world.wallPushes().length, 1); assert.deepEqual(world.notifications.filter(([kind]) => kind === "error"), []); }); test("autosync off keeps walls at home, and on again reconciles them", async () => { const world = makeWallWorld({ autoSync: false, scenes: [] }); const scene = world.makeScene("scene-1", "Dungeon", [ { id: "wall-1", c: [0, 0, 50, 50], light: 2, sense: 2, move: 1, door: 0, ds: 0 }, ]); world.game.scenes.contents.push(scene); await world.fire("init"); await world.fire("ready"); await world.runTimers(); await world.fire("updateWall", { documentName: "Wall", id: "wall-1", parent: scene }); await world.runTimers(); assert.deepEqual(world.wallPushes(), []); assert.ok(!world.requests.some((request) => request.href.includes("foundry/sync/maps"))); await world.game.settings.set(MODULE_ID, "autoSync", true); await world.runTimers(); assert.ok(world.requests.some((request) => request.href.includes("foundry/sync/maps")), "the campaign's maps are asked for again"); }); } // --- The map viewer: the editor's wiring ------------------------------------------------------- function mapViewerWiringTests() { const pane = readRepoFile("frontend", "app", "components", "viewer", "map", "MapViewerPane.vue"); test("the viewer bar opens the wall editor", () => { assert.match(pane, /:aria-pressed="editingWalls\.toString\(\)" @click="toggleWallEditing"/); assert.match(pane, /\$t\('campaigns\.map\.walls\.edit'\)/); }); test("walls are drawn in screen space and only the editor's hit areas catch the mouse", () => { assert.match(pane, /class="wall-line"[^>]*:class="wallClasses\(wall\)"[^>]*v-bind="wallScreen\(wall\)"/); assert.match(pane, /\.map-walls\s*\{[^}]*pointer-events:\s*none/); assert.match(pane, /\.wall-hit\s*\{[^}]*pointer-events:\s*stroke/); }); test("every wall edit saves the whole set through /map/walls", () => { assert.match(pane, /updateMap\('\/map\/walls'/); // A held drag stays local until the pointer lets go, and a wall keeps its _id through saves. assert.match(pane, /_id: String\(wall\._id\)/); assert.match(pane, /if \(IsWall\(segment\)\) await saveWalls\(\[\.\.\.walls\.value, segment\]\)/); }); test("drawn endpoints snap to the grid, like Foundry's wall tool", () => { assert.match(pane, /import \{ IsWall, MoveWall, SnapToGrid, ToDrawPoint, ToScreenWall \} from '~\/services\/MapWalls'/); assert.match(pane, /SnapToGrid\(spot, grid\.value\)/); }); test("a wall answers the mouse and the keyboard", () => { assert.match(pane, /@contextmenu\.stop\.prevent="onWallContextMenu\(wall\)"/); assert.match(pane, /@keydown="onWallKeydown\(\$event, wall\)"/); assert.match(pane, /Delete.*removeWall|removeWall/); assert.match(pane, /event\.key !== 'Escape'[\s\S]*drawingWall\.value = null/); }); } wallSaveRouteTests(); syncRoutesTests(); mapWallsServiceTests(); foundryModuleWallTests(); mapViewerWiringTests();