Merge branch 'master' into ai/issue-47
Some checks failed
Test / test (push) Failing after 2s

This commit is contained in:
2026-10-15 11:08:48 +00:00
14 changed files with 981 additions and 23 deletions

View File

@@ -12,8 +12,20 @@ const FolderSchema = new Schema({
type: Schema.Types.ObjectId,
ref: 'Folder'
},
// Which campaign list a folder belongs to. Note folders are what this model has
// always held, and their rows carry no target at all, so everything reading the
// note tree asks for `{ target: { $ne: 'item' } }` and keeps finding them.
target: { type: String, enum: ['note', 'item'], default: 'note' },
// The Foundry item folder this row mirrors, set by the item sync only
// (see routes/foundry-link.js).
foundryFolderId: { type: String },
color: { type: String },
date: { type: Date, default: Date.now }
});
FolderSchema.index(
{ campaign: 1, foundryFolderId: 1 },
{ unique: true, partialFilterExpression: { foundryFolderId: { $type: 'string' } } }
);
module.exports = mongoose.model('Folder', FolderSchema);

View File

@@ -28,6 +28,13 @@ const ItemSchema = new Schema({
ref: 'Campaign',
required: true
},
// The folder this item stands in: a Folder of the same campaign whose target is
// 'item' (null = the root of the item list).
folder: {
type: Schema.Types.ObjectId,
ref: 'Folder',
default: null
},
foundryItemId: { type: String },
// Names Foundry uses for this item. Dragonroll may rename it, and the copies
// Foundry keeps sending still have to fold into this row instead of

View File

@@ -4,6 +4,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Folder = require('../models/Folder');
const Note = require('../models/Note');
const Item = require('../models/Item');
async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
@@ -18,7 +19,7 @@ router.get('/list', async (req, res) => {
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const folders = await Folder.find({ campaign })
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name date color')
.sort({ date: -1 })
.lean();
@@ -89,6 +90,12 @@ router.post('/delete', async (req, res) => {
{ folder: folderId },
{ $set: { folder: null, date: Date.now() } }
);
// Item folders share this model: the items inside move to the root of
// the item list rather than point at a folder that is gone.
await Item.updateMany(
{ folder: folderId },
{ $set: { folder: null } }
);
await Folder.deleteOne({ _id: folderId });
for (const sub of subfolders) {
await moveRecursive(sub._id);

View File

@@ -6,6 +6,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Item = require('../models/Item');
const Folder = require('../models/Folder');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
@@ -81,7 +82,7 @@ function snapshotItemSources(body) {
return sources;
}
async function saveFoundryItem(campaign, source, fullSync = false) {
async function saveFoundryItem(campaign, source, fullSync = false, folders = null) {
const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryItemToItemData(source || {});
if (!foundryItemId || !fields) return null;
@@ -115,19 +116,113 @@ async function saveFoundryItem(campaign, source, fullSync = false) {
if (!item.foundryNames.includes(fields.name)) {
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
}
// Which folder of the campaign's item tree the world says this item stands in.
// `undefined` means the push says nothing about folders — an item embedded in an
// actor, or a module that knows nothing about them — and the item stays where it
// is. The world owns the folder of its own directory, so a move lands on a full
// snapshot too: nothing on the Dragonroll side files items by hand.
const folder = resolveFoundryItemFolder(source, folders);
if (folder !== undefined) item.folder = folder;
await item.save();
return { foundryItemId, itemId: item.id };
}
async function syncFoundryItems(campaign, sources, fullSync = false) {
async function syncFoundryItems(campaign, sources, fullSync = false, folders = null) {
const items = [];
for (const source of sources) {
const mapping = await saveFoundryItem(campaign, source, fullSync);
const mapping = await saveFoundryItem(campaign, source, fullSync, folders);
if (mapping) items.push(mapping);
}
return items;
}
// --- Item folders ------------------------------------------------------------
// A Foundry world groups its item directory into folders; the campaign mirrors that
// tree as Folders of target 'item' so its item list reads like the world's. Every
// push from a module that knows about folders carries the whole world tree, and
// names the folder each world item it sends stands in. Items embedded in an actor
// say nothing: the folders they carry belong to that actor's own inventory, and
// Dragonroll keeps one item per piece of gear anyway.
// 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.
function orderFoundryFolderSources(sources) {
const byId = new Map();
for (const source of sources) {
const id = String(source?.id || '').trim().slice(0, 120);
const name = String(source?.name || '').trim();
if (!id || !name) continue;
byId.set(id, { id, name, parent: String(source?.parent || '').trim().slice(0, 120) });
}
const ordered = [];
const placed = new Set();
const visiting = new Set();
function place(id) {
if (!byId.has(id) || placed.has(id) || visiting.has(id)) return;
visiting.add(id);
place(byId.get(id).parent);
visiting.delete(id);
placed.add(id);
ordered.push(byId.get(id));
}
for (const id of byId.keys()) place(id);
return ordered;
}
// The campaign folders mirroring the world's item folder tree, keyed by the Foundry
// folder id so pushing the same tree again neither doubles a folder nor loses the
// items filed in it. Rows the campaign made for its own items (no foundryFolderId)
// are left alone: the world does not know them.
async function syncFoundryItemFolders(campaign, folderSources) {
const folders = new Map();
for (const folder of await Folder.find({ campaign: campaign._id, target: 'item' })) {
if (folder.foundryFolderId) folders.set(String(folder.foundryFolderId), folder);
}
const ordered = orderFoundryFolderSources(folderSources);
const inTree = new Set(ordered.map((source) => source.id));
for (const source of ordered) {
let folder = folders.get(source.id);
if (!folder) {
folder = new Folder({
campaign: campaign._id,
target: 'item',
foundryFolderId: source.id,
name: source.name
});
}
// 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.
folder.name = source.name;
const parent = inTree.has(source.parent) ? folders.get(source.parent) : null;
folder.parentFolder = parent ? parent._id : null;
await folder.save();
folders.set(source.id, folder);
}
// Folders the world no longer has go with it, and the items standing in them
// move to the root instead of pointing at a folder that is not there.
const staleIds = [...folders.values()]
.filter((folder) => folder.foundryFolderId && !inTree.has(String(folder.foundryFolderId)))
.map((folder) => folder._id);
if (staleIds.length) {
await Item.updateMany({ campaign: campaign._id, folder: { $in: staleIds } }, { $set: { folder: null } });
await Folder.deleteMany({ campaign: campaign._id, _id: { $in: staleIds } });
}
return folders;
}
// The folder of a pushed item: undefined when the push says nothing about folders,
// null for the root of the item directory, and the campaign folder otherwise. An
// id the tree does not know puts the item at the root rather than nowhere.
function resolveFoundryItemFolder(source, folders) {
const foundryFolderId = source?.dragonroll?.folder;
if (!folders || typeof foundryFolderId !== 'string') return undefined;
return folders.get(foundryFolderId.trim())?._id || null;
}
// Linking a world to a campaign happens through the sign-up link every service
// uses (routes/service-link.js); what stays here is the sync that world keeps up
// with the campaign once that link has handed it its token.
@@ -163,12 +258,16 @@ router.post('/sync/snapshot', async (req, res) => {
}
const fullSync = req.body.fullSync === true;
// A module that knows nothing about item folders sends neither the tree
// nor the folder of an item, and then nothing here touches the folders.
const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null;
const actors = [];
for (const source of actorSources || []) {
const mapping = await saveFoundryActor(campaign, source, fullSync);
if (mapping) actors.push(mapping);
}
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync);
const itemFolders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null;
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync, itemFolders);
if (fullSync && actorSources) {
const currentIds = actorSources
@@ -197,17 +296,21 @@ router.post('/sync/snapshot', async (req, res) => {
}
});
// Live Foundry item edits: upserts only, never prunes. Removing items that no
// longer exist is left to the full snapshot sent with the actors.
// Live Foundry item edits: upserts only, never prunes items. Removing items that no
// longer exist is left to the full snapshot sent with the actors. Item folders are
// the exception: every request carries the world's whole folder tree, so a folder
// the world dropped is dropped here too, and a push may carry folders only.
router.post('/sync/item-snapshot', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items) });
const folders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null;
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items, false, folders) });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });

View File

@@ -5,12 +5,22 @@ const upload = require('../services/storage');
const Campaign = require('../models/Campaign');
const Item = require('../models/Item');
const Folder = require('../models/Folder');
async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
return Boolean(campaign);
}
// Folders the campaign's items are grouped into, in the shape the sidebar groups by
// (the world's own item folders arrive through the sync, see routes/foundry-link.js).
async function itemFolders(campaignId) {
return Folder.find({ campaign: campaignId, target: 'item' })
.select('_id name parentFolder date')
.sort({ date: -1 })
.lean();
}
router.get('/list', async (req, res) => {
try {
const { campaign } = req.query;
@@ -18,7 +28,7 @@ router.get('/list', async (req, res) => {
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const items = await Item.find({ campaign }).sort({ name: 1 }).lean();
res.json({ status: 'ok', items });
res.json({ status: 'ok', items, folders: await itemFolders(campaign) });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });

View File

@@ -19,7 +19,9 @@ router.get('/list', async (req, res) => {
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const folders = await Folder.find({ campaign })
// The note tree only: item folders share this model and would otherwise
// turn up as empty folders between the notes.
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name parentFolder date color')
.sort({ date: -1 })
.lean();
@@ -48,7 +50,7 @@ router.get('/subfolder/list', async (req, res) => {
const folderDoc = await Folder.findOne({ _id: folder, campaign }).lean();
if (!folderDoc) return res.json({ status: 'error', msg: 'errors.notfound' });
const subfolders = await Folder.find({ campaign, parentFolder: folder })
const subfolders = await Folder.find({ campaign, parentFolder: folder, target: { $ne: 'item' } })
.select('_id name date color')
.sort({ date: -1 })
.lean();
@@ -80,7 +82,7 @@ router.get('/all', async (req, res) => {
.sort({ title: 1 })
.lean();
const folders = await Folder.find({ campaign })
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name parentFolder')
.lean();

View File

@@ -30,6 +30,8 @@ const queuedActorChanges = new Map();
let itemSyncTimeout;
let itemSyncRunning = false;
let itemSyncErrorLogged = false;
let folderSyncTimeout;
let folderSyncRunning = false;
const syncingItemIds = new Set();
const queuedItemChanges = new Map();
@@ -436,6 +438,7 @@ function handleAutoSyncChange(value) {
if (value === false) {
clearTimeout(actorSyncTimeout);
clearTimeout(itemSyncTimeout);
clearTimeout(folderSyncTimeout);
return;
}
if (!game.user?.isGM || !getSyncToken()) return;
@@ -444,6 +447,7 @@ function handleAutoSyncChange(value) {
// while autosync was off are pushed so this world's state wins over them.
initializeCharacterSync();
reconcileDragonrollItems();
queueFoundryItemFolders(400);
if (queuedActorChanges.size) {
clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 400);
@@ -527,6 +531,8 @@ async function pushFoundryActors(actors, fullSync = false) {
// Dragonroll deduplicates by name, so sending the world directory next to
// the actor copies keeps a single Item per piece of gear.
items: getWorldItemSnapshots(),
// The folder tree those world items stand in (see worldItemFolderSnapshots).
folders: worldItemFolderSnapshots(),
fullSync,
}, token);
@@ -644,8 +650,60 @@ function serializeFoundryItem(item) {
return data;
}
// --- Item folders ------------------------------------------------------------
// Dragonroll mirrors the folders the world's item directory is grouped into, so its
// item list reads like Foundry's. `game.folders` also holds the folders an actor
// keeps for its own inventory: those hang off the actor instead of the world, and
// the campaign has no use for them, so only folders rooted in the world go over.
// The folder a folder is nested in, or null when it is not nested in a folder.
function itemFolderParent(folder) {
const parent = typeof folder.parent === "string" ? game.folders?.get(folder.parent) : folder.parent;
return parent?.documentName === "Folder" ? parent : null;
}
// Whether a folder belongs to the world's item directory: its whole ancestry has
// to be folders, ending in one that nothing is above.
function isWorldItemFolder(folder, seen = new Set()) {
if (folder.type !== "Item" || seen.has(folder.id)) return false;
seen.add(folder.id);
const rawParent = folder.parent;
const rawParentId = typeof rawParent === "string" ? rawParent : rawParent?.id;
if (!rawParentId) return true;
const parent = typeof rawParent === "string" ? game.folders?.get(rawParentId) : rawParent;
if (parent?.documentName !== "Folder") return false;
return isWorldItemFolder(parent, seen);
}
function worldItemFolderSnapshots() {
return (game.folders?.contents || [])
.filter((folder) => isWorldItemFolder(folder))
.map((folder) => ({ id: folder.id, name: folder.name, parent: itemFolderParent(folder)?.id || null }));
}
// A world item travels with the folder it stands in, so Dragonroll can file it the
// same way; `""` says the world keeps it at the root of the item directory. Items
// embedded in an actor use serializeFoundryItem instead: their folders are the
// actor's own, and the campaign's item list is deduplicated by name anyway.
function serializeFoundryWorldItem(item) {
const data = serializeFoundryItem(item);
if (!data) return null;
data.dragonroll = { ...data.dragonroll, folder: worldItemFolderId(item) };
return data;
}
// The folder id an item data carries is either the id or the Folder document
// itself, depending on the Foundry version.
function worldItemFolderId(item) {
const folder = item?.folder;
if (!folder) return "";
if (typeof folder === "string") return game.folders?.get(folder)?.documentName === "Folder" ? folder : "";
return folder.documentName === "Folder" ? String(folder.id || "") : "";
}
function getWorldItemSnapshots() {
return (game.items?.contents || []).map(serializeFoundryItem).filter(Boolean);
return (game.items?.contents || []).map(serializeFoundryWorldItem).filter(Boolean);
}
function dragonrollItemIdOf(item) {
@@ -693,7 +751,10 @@ async function pushFoundryItems(items) {
const result = await postDragonroll("foundry/sync/item-snapshot", {
worldId: game.world.id,
items: items.map(serializeFoundryItem).filter(Boolean),
items: items.map(serializeFoundryWorldItem).filter(Boolean),
// The folder tree goes along, so an item that moved into or out of a folder
// arrives with the folder it names.
folders: worldItemFolderSnapshots(),
}, token);
await rememberItemMappings(result.items);
itemSyncErrorLogged = false;
@@ -717,6 +778,34 @@ function queueFoundryItemChange(kind, item) {
itemSyncTimeout = setTimeout(flushItemChanges, 400);
}
// A folder the GM made, renamed or nested has to reach the campaign even though no
// item changed, so the tree goes over on its own without pushing the items in it.
function queueFoundryItemFolders(delay = 400) {
clearTimeout(folderSyncTimeout);
folderSyncTimeout = setTimeout(pushFoundryItemFolders, delay);
}
async function pushFoundryItemFolders() {
// Autosync off: folder changes wait, like the item edits do.
if (!isAutoSyncEnabled()) return;
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || folderSyncRunning) return;
folderSyncRunning = true;
try {
await postDragonroll("foundry/sync/item-snapshot", {
worldId: game.world.id,
items: [],
folders: worldItemFolderSnapshots(),
}, token);
itemSyncErrorLogged = false;
} catch (error) {
reportItemSyncError(error);
queueFoundryItemFolders(5000);
} finally {
folderSyncRunning = false;
}
}
async function flushItemChanges() {
// Autosync off: the queued edits wait here, like the actor changes do.
if (!isAutoSyncEnabled()) return;
@@ -1206,6 +1295,7 @@ Hooks.once("ready", () => {
for (const event of [
"createActor", "updateActor", "deleteActor",
"createItem", "updateItem", "deleteItem",
"createFolder", "updateFolder", "deleteFolder",
]) {
Hooks.on(event, (document) => {
scheduleSnapshotSync();
@@ -1215,6 +1305,12 @@ Hooks.once("ready", () => {
queueFoundryActorChange(isDelete ? "delete" : "upsert", document);
return;
}
// 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.
if (document.documentName === "Folder") {
if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders();
return;
}
if (document.documentName !== "Item") return;
// Items embedded in an actor travel with that actor's snapshot: adding or

View File

@@ -5,6 +5,7 @@ import { useI18n } from 'vue-i18n';
import { useCampaignService } from '~/services/Campaign.js';
import { AnchorMap, AnchoredMap, ClearAnchoredMap, SetActivePane } from '~/services/Content.js';
import { emitter } from '~/services/Emitter';
import { BuildItemRows } from '~/services/ItemFolders';
import Server from '~/services/Server';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
@@ -17,6 +18,10 @@ const notes = ref([]);
const folders = ref([]);
const actors = ref([]);
const items = ref([]);
// The folders items stand in, and which of them the list has collapsed. Folders are
// open by default: a folder synced from Foundry should show its items, not hide them.
const itemFolders = ref([]);
const collapsedItemFolderIds = ref([]);
const maps = ref([]);
const entryLists = { actor: actors, item: items, map: maps };
const loadingNotes = ref(false);
@@ -202,6 +207,9 @@ async function fetchCampaignEntries(entityType = activeSection.value, silent = f
const previousById = new Map(list.value.map((entry) => [entry._id, entry]));
list.value = response.data[entityType] ?? [];
// Items come with the folder tree their world synced over, so the list can
// group them the way the Foundry item directory does.
if (kind === 'item') itemFolders.value = response.data.folders ?? [];
// Tell open windows about Foundry changes landing behind them.
for (const entry of list.value) {
const previous = previousById.get(entry._id);
@@ -345,10 +353,27 @@ function toggleSidebar() {
const rootNotes = computed(() => notes.value.filter(n => !n._folder));
// The items of the campaign, each under the folder it stands in (see
// services/ItemFolders.js). Without any folder this is the plain item list.
const itemRows = computed(() => BuildItemRows(items.value, itemFolders.value, collapsedItemFolderIds.value));
// Rows one step deeper per folder level; the sidebar list's own padding is the base.
function rowIndent(depth) {
return { paddingLeft: `${10 + depth * 14}px` };
}
function toggleItemFolder(folderId) {
collapsedItemFolderIds.value = collapsedItemFolderIds.value.includes(folderId)
? collapsedItemFolderIds.value.filter((id) => id !== folderId)
: [...collapsedItemFolderIds.value, folderId];
}
watch(campaignId, (newVal) => {
if (newVal) {
actors.value = [];
items.value = [];
itemFolders.value = [];
collapsedItemFolderIds.value = [];
maps.value = [];
ClearAnchoredMap();
fetchCampaignNotes();
@@ -358,6 +383,8 @@ watch(campaignId, (newVal) => {
folders.value = [];
actors.value = [];
items.value = [];
itemFolders.value = [];
collapsedItemFolderIds.value = [];
maps.value = [];
notesError.value = '';
entriesError.value = '';
@@ -512,13 +539,33 @@ onBeforeUnmount(() => {
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
<div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div>
<div v-else-if="items.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div>
<div v-for="item in items" :key="item._id" class="entity-entry" role="button" tabindex="0" @click="openItemSheet(item)" @keydown.enter="openItemSheet(item)" @keydown.space.prevent="openItemSheet(item)" @contextmenu.prevent="showEntryMenu(item, 'item')">
<span class="entity-entry-name-row">
<span class="entity-entry-name">{{ item.name }}</span>
<span v-if="item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span>
</span>
<span class="entity-entry-meta">{{ itemSummary(item) }}</span>
</div>
<template v-for="row in itemRows" :key="row.key">
<button
v-if="row.kind === 'folder'"
class="item-folder-entry"
type="button"
:style="rowIndent(row.depth)"
:aria-expanded="(!collapsedItemFolderIds.includes(row.folder._id)).toString()"
:aria-label="t('campaigns.item.folder-toggle', { name: row.folder.name })"
@click="toggleItemFolder(row.folder._id)"
>
<img
class="item-folder-arrow"
:src="collapsedItemFolderIds.includes(row.folder._id) ? '/icons/iconoir/regular/nav-arrow-right.svg' : '/icons/iconoir/regular/nav-arrow-down.svg'"
alt=""
aria-hidden="true"
>
<img class="item-folder-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
<span class="item-folder-name">{{ row.folder.name }}</span>
</button>
<div v-else class="entity-entry" :style="rowIndent(row.depth)" role="button" tabindex="0" @click="openItemSheet(row.item)" @keydown.enter="openItemSheet(row.item)" @keydown.space.prevent="openItemSheet(row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'item')">
<span class="entity-entry-name-row">
<span class="entity-entry-name">{{ row.item.name }}</span>
<span v-if="row.item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span>
</span>
<span class="entity-entry-meta">{{ itemSummary(row.item) }}</span>
</div>
</template>
</template>
<template v-else>
@@ -684,6 +731,18 @@ onBeforeUnmount(() => {
}
.entity-entry:hover { border-color: var(--color-border); background: var(--color-background-soft); }
.entity-entry:focus-visible { outline: 1px solid var(--color-link); }
/* Item folders, synced from the linked world's item directory: the same row box as
an entry, since they share the sidebar list and its width rules. */
.item-folder-entry {
width: 100%; min-width: 0; box-sizing: border-box; margin: 0; padding: 8px 10px; border: 1px solid transparent;
border-radius: 8px; background: transparent; color: var(--color-text); text-align: left; display: flex;
align-items: center; gap: 6px; cursor: pointer; font: inherit;
}
.item-folder-entry:hover { background: var(--color-background-soft); }
.item-folder-entry:focus-visible { outline: 1px solid var(--color-link); }
.item-folder-arrow { width: 12px; height: 12px; flex: 0 0 12px; filter: invert(var(--color-icon-invert)); opacity: 0.6; }
.item-folder-icon { width: 15px; height: 15px; flex: 0 0 15px; filter: invert(var(--color-icon-invert)); }
.item-folder-name { min-width: 0; font-weight: bold; word-break: break-word; }
/* The map currently anchored on the note container. */
.entity-entry.anchored { border-color: var(--color-link); background: var(--color-background-soft); }
.entity-entry-name-row { display: flex; align-items: baseline; gap: 6px; min-width: 0; }

View File

@@ -0,0 +1,68 @@
// The rules behind grouping the campaign's items under the folders they stand in.
// Item folders arrive from the linked Foundry world (routes/foundry-link.js mirrors
// its item directory), so the campaign only reads this tree: the helper holds no
// state, talks to no API and builds rows from what `/item/list` already returns.
function ByName(a, b) {
return String(a?.name ?? '').localeCompare(String(b?.name ?? ''));
}
// The folder a folder hangs under. A parent the campaign does not know puts it at
// the root, and so does a parent chain that leads back to the folder itself: a
// broken tree must not hide everything below it.
function ParentKey(folder, knownFolders) {
let parentKey = String(folder.parentFolder ?? '');
if (!parentKey || !knownFolders.has(parentKey)) return '';
const seen = new Set([String(folder._id)]);
while (parentKey) {
if (seen.has(parentKey)) return '';
seen.add(parentKey);
const parent = knownFolders.get(parentKey);
parentKey = knownFolders.has(String(parent?.parentFolder ?? '')) ? String(parent.parentFolder) : '';
}
return String(folder.parentFolder);
}
// The rows of the item list in the order they are shown: every folder followed by
// what stands in it, deeper and deeper, with the items standing at that level last.
// `collapsedFolderIds` hides a folder's whole subtree; folders start open so a
// synced item is never hidden behind a click. Rows are `{ kind: 'folder', key,
// depth, folder }` or `{ kind: 'item', key, depth, item }`. An item whose folder the
// campaign does not know reads as a root item instead of vanishing from the list.
function BuildItemRows(items, folders, collapsedFolderIds = []) {
const knownFolders = new Map((folders ?? []).map((folder) => [String(folder._id), folder]));
const collapsed = new Set((collapsedFolderIds ?? []).map(String));
const childFolders = new Map([['', []]]);
const itemsByFolder = new Map([['', []]]);
for (const folder of knownFolders.values()) {
const parentKey = ParentKey(folder, knownFolders);
if (!childFolders.has(parentKey)) childFolders.set(parentKey, []);
childFolders.get(parentKey).push(folder);
}
for (const item of items ?? []) {
const folderKey = item?.folder && knownFolders.has(String(item.folder)) ? String(item.folder) : '';
if (!itemsByFolder.has(folderKey)) itemsByFolder.set(folderKey, []);
itemsByFolder.get(folderKey).push(item);
}
const rows = [];
const visitedFolders = new Set();
function walk(folderKey, depth) {
for (const folder of (childFolders.get(folderKey) ?? []).slice().sort(ByName)) {
if (visitedFolders.has(String(folder._id))) continue;
visitedFolders.add(String(folder._id));
rows.push({ kind: 'folder', key: `folder-${folder._id}`, depth, folder });
if (!collapsed.has(String(folder._id))) walk(String(folder._id), depth + 1);
}
for (const item of (itemsByFolder.get(folderKey) ?? []).slice().sort(ByName)) {
rows.push({ kind: 'item', key: `item-${item._id}`, depth, item });
}
}
walk('', 0);
return rows;
}
export { BuildItemRows };

View File

@@ -62,6 +62,7 @@
"new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.",
"category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat",
"quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
"folder-toggle": "Mostra o amaga la carpeta {name}",
"sheet": {
"icon": "Icona de l'objecte", "choose-icon": "Tria la teva pròpia icona", "change-icon": "Canvia la icona",
"uploading": "Pujant...", "upload-error": "No s'ha pogut pujar aquesta icona.",

View File

@@ -66,6 +66,7 @@
"new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.",
"category": "Category", "rarity": "Rarity", "quantity": "Quantity",
"quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
"folder-toggle": "Toggle the {name} folder",
"sheet": {
"icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change icon",
"uploading": "Uploading...", "upload-error": "Unable to upload this icon.",

View File

@@ -62,6 +62,7 @@
"new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.",
"category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad",
"quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
"folder-toggle": "Muestra o oculta la carpeta {name}",
"sheet": {
"icon": "Icono del objeto", "choose-icon": "Elegir tu propio icono", "change-icon": "Cambiar icono",
"uploading": "Subiendo...", "upload-error": "No se pudo subir este icono.",

View File

@@ -0,0 +1,590 @@
// Tests for item folders following the Foundry world into the campaign
// (Syndria98/dragonroll#44): the world's item directory is grouped into folders, and
// Dragonroll mirrors that tree as Folders of target 'item' and files the synced items
// in them, so its item list reads like the world's.
//
// The repository root installs no dependencies, so each side is loaded the way the
// other tests do it. The sync route runs against a stubbed `require` (express,
// mongoose and the models answer with plain objects and a small filter matcher):
// that keeps the tree, the filing and the pruning observable without a database. The
// Foundry module is loaded into a `node:vm` context holding stubbed Foundry globals
// (`game.folders` included) with fake timers, like tests/foundry-sync-toggle.test.js.
// The grouping of the sidebar list lives in a plain ES module and is read as text.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const repoRequire = (relative) => require(path.join(__dirname, "..", relative));
// --- The sync route against stubbed models -------------------------------------
// A mongoose query answers whatever `await query` and `query.lean()` answer with, and
// lets `select()`, `sort()` and `limit()` sit in between.
function mongooseQuery(value) {
const result = {
select: () => result,
sort: () => result,
limit: (count) => mongooseQuery(value.slice(0, count)),
lean: () => Promise.resolve(value),
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
};
return result;
}
// Enough of the query language the item folder sync uses: equality, $or, $in, $nin,
// $exists. Anything else is a filter this test did not expect and says so.
function matches(document, filter = {}) {
return Object.entries(filter).every(([key, expected]) => {
if (key === "$or") return expected.some((part) => matches(document, part));
const value = document?.[key];
if (expected && typeof expected === "object" && !Array.isArray(expected)) {
return Object.entries(expected).every(([operator, wanted]) => {
if (operator === "$exists") return (value !== undefined && value !== null) === wanted;
if (operator === "$in") return wanted.some((entry) => String(value) === String(entry));
if (operator === "$nin") return !wanted.some((entry) => String(value) === String(entry));
throw new Error(`filter operator "${key}.${operator}" is not stubbed`);
});
}
return String(value ?? "") === String(expected ?? "");
});
}
function fakeModel(table, seed = []) {
const rows = [];
let counter = 0;
function Document(data = {}) {
counter += 1;
this._id = `${table}-${counter}`;
this.isNew = true;
this.foundryNames = [];
Object.assign(this, data);
}
Document.prototype.save = async function save() {
if (this.isNew) rows.push(this);
this.isNew = false;
return this;
};
Object.defineProperty(Document.prototype, "id", { get() { return this._id; } });
for (const data of seed) {
const row = new Document({ [table === "folder" ? "target" : "name"]: undefined, ...data });
row.isNew = false;
rows.push(row);
}
const model = function Model(data) { return new Document(data); };
model.rows = rows;
model.findOne = async (filter) => rows.find((row) => matches(row, filter)) ?? null;
model.find = (filter) => mongooseQuery(rows.filter((row) => matches(row, filter)));
model.deleteOne = async (filter) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) rows.splice(rows.indexOf(row), 1);
return { deletedCount: hit.length };
};
model.deleteMany = async (filter) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) rows.splice(rows.indexOf(row), 1);
return { deletedCount: hit.length };
};
model.updateMany = async (filter, update) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) Object.assign(row, update.$set ?? {});
return { modifiedCount: hit.length };
};
return model;
}
function worldItem(over = {}) {
return {
_id: "item-1",
name: "Longsword",
type: "weapon",
system: { quantity: 1, weight: 3, rarity: "common" },
...over,
};
}
// The Foundry sync route with every model it requires stubbed. `seed` pre-fills the
// tables with documents the campaign already holds.
function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
const routes = new Map();
const router = {
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
};
const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId };
const models = {
"../models/Actor": fakeModel("actor", seed.actors),
"../models/Item": fakeModel("item", seed.items),
"../models/Folder": fakeModel("folder", seed.folders),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 };
if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", "foundry-link.js"), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
async function call(route, body = {}) {
const handlers = routes.get(route);
assert.ok(handlers, `${route} is not mounted`);
const res = { payload: null, json(payload) { this.payload = payload; }, set: () => {} };
const req = { body, get: (name) => (String(name).toLowerCase() === "authorization" ? "Bearer sync-token" : "") };
await handlers[handlers.length - 1](req, res);
return res.payload;
}
return { call, models, campaign };
}
const FOLDER_TREE = [
{ id: "folder-melee", name: "Melee Weapons", parent: null },
{ id: "folder-ranged", name: "Ranged Weapons", parent: null },
{ id: "folder-powder", name: "Powder Weapons", parent: "folder-ranged" },
];
test("a synced world item arrives in the folder the world keeps it in", async () => {
const sync = loadSyncRoute();
const response = await sync.call("POST /sync/snapshot", {
worldId: "world-1",
actors: [],
folders: FOLDER_TREE,
items: [worldItem({ dragonroll: { folder: "folder-melee" } })],
});
assert.equal(response.status, "ok");
const [folder] = sync.models["../models/Folder"].rows;
assert.equal(folder.name, "Melee Weapons");
assert.equal(folder.target, "item", "a synced folder belongs to the item list, not the notes");
assert.equal(folder.foundryFolderId, "folder-melee");
assert.equal(sync.models["../models/Item"].rows[0].folder, folder._id);
});
test("a nested Foundry folder becomes a nested campaign folder", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: FOLDER_TREE });
const folders = sync.models["../models/Folder"].rows;
const ranged = folders.find((folder) => folder.name === "Ranged Weapons");
const powder = folders.find((folder) => folder.name === "Powder Weapons");
assert.equal(powder.parentFolder, ranged._id, "the subfolder hangs under the folder nesting it");
assert.equal(folders.find((folder) => folder.name === "Melee Weapons").parentFolder, null);
});
test("the same world folder is never made twice, and keeps its items", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/item-snapshot", {
worldId: "world-1", items: [worldItem({ dragonroll: { folder: "folder-melee" } })], folders: FOLDER_TREE,
});
const filed = sync.models["../models/Item"].rows[0].folder;
await sync.call("POST /sync/item-snapshot", {
worldId: "world-1", items: [worldItem({ dragonroll: { folder: "folder-melee" } })], folders: FOLDER_TREE,
});
assert.equal(sync.models["../models/Folder"].rows.length, FOLDER_TREE.length, "the tree was mirrored once");
assert.equal(sync.models["../models/Item"].rows[0].folder, filed, "the item stays in the folder it was filed in");
});
test("a folder renamed in the world is renamed in the campaign", async () => {
const sync = loadSyncRoute({
seed: { folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Old name", parentFolder: null }] },
});
await sync.call("POST /sync/item-snapshot", {
worldId: "world-1", items: [], folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null }],
});
assert.equal(sync.models["../models/Folder"].rows.length, 1);
assert.equal(sync.models["../models/Folder"].rows[0].name, "Melee Weapons");
});
test("a folder the world dropped goes, and its items move to the root", async () => {
const sync = loadSyncRoute({
seed: {
folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }],
items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }],
},
});
await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [] });
assert.deepEqual(sync.models["../models/Folder"].rows, [], "the empty folder row is gone with the world's folder");
assert.equal(sync.models["../models/Item"].rows[0].folder, null, "the item moves to the root instead of nowhere");
});
test("a campaign folder the world does not know is left alone", async () => {
const sync = loadSyncRoute({
seed: { folders: [{ _id: "folder-1", target: "item", name: "Homebrew", parentFolder: null }] },
});
await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [], folders: [] });
assert.equal(sync.models["../models/Folder"].rows.length, 1, "only folders mirrored from the world are pruned");
});
test("an item embedded in an actor leaves the folder of its world copy alone", async () => {
const sync = loadSyncRoute({
seed: { items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }] },
});
// The actor's copy carries no folder of its own: the inventory folders an actor
// keeps say nothing about the campaign's item list.
await sync.call("POST /sync/snapshot", {
worldId: "world-1",
actors: [{ _id: "actor-1", name: "Thalia", items: [worldItem({ _id: "item-1" })] }],
items: [],
folders: FOLDER_TREE,
});
assert.equal(sync.models["../models/Item"].rows[0].folder, "folder-1");
});
test("a module that knows nothing about folders leaves them untouched", async () => {
const sync = loadSyncRoute({
seed: {
folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }],
items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }],
},
});
await sync.call("POST /sync/snapshot", { worldId: "world-1", actors: [], items: [worldItem()] });
await sync.call("POST /sync/item-snapshot", { worldId: "world-1", items: [worldItem()] });
assert.equal(sync.models["../models/Folder"].rows.length, 1, "no tree was sent, so nothing was pruned");
assert.equal(sync.models["../models/Item"].rows[0].folder, "folder-1", "and the item stays filed where it was");
});
test("an item the world moved out of a folder follows it to the root", async () => {
const sync = loadSyncRoute({
seed: {
folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons" }],
items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }],
},
});
await sync.call("POST /sync/item-snapshot", {
worldId: "world-1",
items: [worldItem({ dragonroll: { folder: "" } })],
folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null }],
});
assert.equal(sync.models["../models/Item"].rows[0].folder, null);
});
test("item folders stay out of the note tree", () => {
// The note routes share the Folder model, so each of them asks for "anything but
// item": note folders made before the target field existed keep matching that.
for (const route of ["note.js", "folder.js"]) {
const source = read("backend", "src", "routes", route);
const listings = source.match(/Folder\.find\(\{[^}]*\}\)/g) ?? [];
assert.ok(listings.length, `${route} lists folders`);
for (const listing of listings) {
assert.match(listing, /target:\s*\{\s*\$ne:\s*['"]item['"]\s*\}/, `${route} leaks item folders: ${listing}`);
}
}
});
test("the item list comes with the folders it groups into, and items carry theirs", () => {
assert.match(read("backend", "src", "models", "Item.js"), /folder:\s*{\s*type:\s*Schema\.Types\.ObjectId,\s*ref:\s*'Folder'/);
const itemRoute = read("backend", "src", "routes", "item.js");
assert.match(itemRoute, /res\.json\(\{\s*status:\s*'ok',\s*items,\s*folders:/);
assert.match(itemRoute, /Folder\.find\(\{\s*campaign:\s*campaignId,\s*target:\s*'item'\s*\}/);
});
// --- The Foundry module sends its folder tree ------------------------------------
function makeWorld() {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
nextTimerId: 1,
};
const folders = [
{ id: "folder-melee", name: "Melee Weapons", type: "Item", parent: null, documentName: "Folder" },
{ id: "folder-ranged", name: "Ranged Weapons", type: "Item", parent: "folder-melee", documentName: "Folder" },
// An actor's own inventory folder: it hangs off the actor, not the world.
{ id: "folder-carried", name: "Carried", type: "Item", parent: { id: "actor-1", documentName: "Actor" }, documentName: "Folder" },
{ id: "folder-journal", name: "Lore", type: "JournalEntry", parent: null, documentName: "Folder" },
];
const items = [
{
id: "item-1", name: "Longsword", type: "weapon", documentName: "Item", parent: null,
folder: "folder-melee",
system: { properties: { value: [] }, quantity: 1, weight: 3, rarity: "common" },
toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; },
},
{
id: "item-2", name: "Torch", type: "loot", documentName: "Item", parent: null, folder: "",
system: { properties: { value: [] }, quantity: 1, weight: 1, rarity: "common" },
toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; },
},
];
const carriedItem = {
id: "item-3", name: "Caltrops", type: "loot", documentName: "Item", parent: { documentName: "Actor" },
folder: "folder-carried",
system: { properties: { value: [] }, quantity: 4, weight: 0, rarity: "common" },
toObject() { return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: {} }; },
};
const actors = [
{
id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {},
items: { contents: [carriedItem] },
getFlag() { return undefined; },
toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags }; },
},
];
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
const sandbox = {
console: { log() {}, info() {}, warn() {}, error() {} },
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: { notifications: { info() {}, warn() {}, error() {} } },
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); },
},
setTimeout: (fn, delay = 0) => {
const id = state.nextTimerId++;
state.timers.set(id, { fn, delay });
return id;
},
clearTimeout: (id) => state.timers.delete(id),
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
state.requests.push({
href: String(url),
method: options.method,
body: options.body ? JSON.parse(options.body) : null,
});
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: actors, get: (id) => actors.find((actor) => actor.id === id) },
items: { contents: items, get: (id) => items.find((item) => item.id === id) },
folders: { contents: folders, get: (id) => folders.find((folder) => folder.id === id) },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(read("dragonroll-foundry", "scripts", "api.js"), sandbox);
state.game = sandbox.game;
state.folder = (id) => folders.find((folder) => folder.id === id);
state.item = (id) => items.find((item) => item.id === id);
state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync")
&& !request.href.includes("foundry/sync/status"));
state.pushes = (route) => state.syncRequests().filter((request) => request.href.includes(route));
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await drain();
};
state.runTimers = async () => {
for (let round = 0; round < 6; round += 1) {
if (!state.timers.size && round > 2) break;
const due = [...state.timers.values()];
state.timers.clear();
for (const timer of due) await timer.fn();
await drain();
}
};
state.linkedSetup = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
state.requests.length = 0;
return state;
};
return state;
}
test("the world sends its item folder tree with a snapshot", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("updateActor", world.game.actors.contents[0]);
await world.runTimers();
const [push] = world.pushes("foundry/sync/snapshot");
assert.ok(push, "the actor change pushed a snapshot");
assert.deepEqual(push.body.folders, [
{ id: "folder-melee", name: "Melee Weapons", parent: null },
{ id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee" },
], "the item directory tree, nested, without the actor's own or another type's folders");
const longsword = push.body.items.find((item) => item._id === "item-1");
assert.equal(longsword.dragonroll.folder, "folder-melee", "a world item says which folder it stands in");
const torch = push.body.items.find((item) => item._id === "item-2");
assert.equal(torch.dragonroll.folder, "", "and which one stands at the root");
});
test("an item embedded in an actor does not report the actor's inventory folders", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("updateActor", world.game.actors.contents[0]);
await world.runTimers();
const [push] = world.pushes("foundry/sync/snapshot");
const carried = push.body.actors[0].items.find((item) => item._id === "item-3");
assert.equal(carried.dragonroll?.folder, undefined, "the actor copy carries no folder for the campaign");
});
test("a live item edit carries the folder tree too", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("updateItem", world.item("item-1"));
await world.runTimers();
const [push] = world.pushes("foundry/sync/item-snapshot");
assert.deepEqual(push.body.folders.map((folder) => folder.id), ["folder-melee", "folder-ranged"]);
assert.equal(push.body.items[0].dragonroll.folder, "folder-melee");
});
test("a folder change reaches Dragonroll without pushing the items in it", async () => {
const world = await makeWorld().linkedSetup();
const melee = world.folder("folder-melee");
melee.name = "Close Weapons";
await world.fire("updateFolder", melee);
await world.runTimers();
const [push] = world.pushes("foundry/sync/item-snapshot");
assert.deepEqual(push.body.items, [], "the items themselves are left alone");
assert.deepEqual(push.body.folders.map((folder) => [folder.id, folder.name]), [
["folder-melee", "Close Weapons"],
["folder-ranged", "Ranged Weapons"],
]);
});
test("a folder of another document type does not touch the item list", async () => {
const world = await makeWorld().linkedSetup();
await world.fire("updateFolder", world.folder("folder-journal"));
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
});
test("autosync off: folder changes stop syncing", async () => {
const world = await makeWorld().linkedSetup();
await world.game.settings.set("dragonroll-foundry", "autoSync", false);
await world.fire("updateFolder", world.folder("folder-melee"));
await world.fire("updateItem", world.item("item-1"));
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
});
// --- The sidebar groups its items under those folders ----------------------------
async function loadItemFoldersService() {
const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };");
return vm.compileFunction(source)();
}
const { BuildItemRows } = await loadItemFoldersService();
const SIDEBAR_FOLDERS = [
{ _id: "f-melee", name: "Melee Weapons" },
{ _id: "f-ranged", name: "Ranged Weapons" },
{ _id: "f-powder", name: "Powder Weapons", parentFolder: "f-ranged" },
];
const SIDEBAR_ITEMS = [
{ _id: "i-sword", name: "Longsword", folder: "f-melee" },
{ _id: "i-pistol", name: "Pistol", folder: "f-powder" },
{ _id: "i-torch", name: "Torch" },
];
test("items are grouped under the folder they stand in, nested", () => {
const shape = BuildItemRows(SIDEBAR_ITEMS, SIDEBAR_FOLDERS).map((row) => [
row.kind, row.kind === "folder" ? row.folder.name : row.item.name, row.depth,
]);
assert.deepEqual(shape, [
["folder", "Melee Weapons", 0],
["folder", "Ranged Weapons", 0],
["folder", "Powder Weapons", 1],
["item", "Pistol", 1],
["item", "Torch", 0],
["item", "Longsword", 1],
]);
});
test("a collapsed folder hides its whole subtree", () => {
const rows = BuildItemRows(SIDEBAR_ITEMS, SIDEBAR_FOLDERS, ["f-ranged"]);
assert.ok(rows.some((row) => row.kind === "folder" && row.folder.name === "Ranged Weapons"));
assert.ok(!rows.some((row) => row.kind === "item" && row.item.name === "Pistol"), "the nested item is hidden too");
});
test("without any folder the list is the plain item list", () => {
const rows = BuildItemRows([{ _id: "i-1", name: "Torch" }, { _id: "i-2", name: "Longsword" }], []);
assert.deepEqual(rows.map((row) => [row.kind, row.item.name, row.depth]), [
["item", "Longsword", 0],
["item", "Torch", 0],
]);
});
test("an item whose folder is gone, or a folder nested in itself, reads as a root item", () => {
const rows = BuildItemRows(
[{ _id: "i-1", name: "Torch", folder: "f-gone" }],
[{ _id: "f-a", name: "A", parentFolder: "f-b" }, { _id: "f-b", name: "B", parentFolder: "f-a" }],
);
const shape = rows.map((row) => [row.kind, row.kind === "folder" ? row.folder.name : row.item.name]);
assert.ok(shape.includes(["item", "Torch"]), "the item is not lost with the folder that was removed");
assert.deepEqual(new Set(shape.filter(([kind]) => kind === "folder").map(([, name]) => name)), new Set(["A", "B"]));
assert.equal(rows.filter(([kind]) => kind === "folder").length, 2, "a broken tree is walked once, not forever");
});
test("every locale labels the item folder row", () => {
for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
assert.ok(campaigns.item?.["folder-toggle"], `${locale} is missing campaigns.item.folder-toggle`);
}
});

View File

@@ -65,8 +65,9 @@ test("the item routes accept the icon and upload one", () => {
test("the item info window is registered and opens on a sidebar click", () => {
assert.match(windowDefsSource, /item_sheet:\s*{\s*title:[^}]*ItemSheetWindow\.vue/s);
// clicking (or Enter/Space on) an item row opens the window instead of expanding inline
assert.match(sidebarSource, /v-for="item in items"[^>]*@click="openItemSheet\(item\)"/);
// clicking (or Enter/Space on) an item row opens the window instead of expanding inline.
// Since #44 the rows come from the folder tree the world synced, so the row holds the item.
assert.match(sidebarSource, /v-for="row in itemRows"[\s\S]*?@click="openItemSheet\(row\.item\)"/);
assert.match(sidebarSource, /CreateWindow\(['"]item_sheet['"],\s*\{ item \}\)/);
assert.doesNotMatch(sidebarSource, /toggleEntryDetails/);
});