diff --git a/backend/src/models/Folder.js b/backend/src/models/Folder.js index 533dd613..138f4134 100644 --- a/backend/src/models/Folder.js +++ b/backend/src/models/Folder.js @@ -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); diff --git a/backend/src/models/Item.js b/backend/src/models/Item.js index 4633907e..3a28a1a9 100644 --- a/backend/src/models/Item.js +++ b/backend/src/models/Item.js @@ -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 diff --git a/backend/src/routes/folder.js b/backend/src/routes/folder.js index c0251250..a12ffdf4 100644 --- a/backend/src/routes/folder.js +++ b/backend/src/routes/folder.js @@ -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); diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js index dbfbe532..d76e2ec9 100644 --- a/backend/src/routes/foundry-link.js +++ b/backend/src/routes/foundry-link.js @@ -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' }); diff --git a/backend/src/routes/item.js b/backend/src/routes/item.js index d1460507..c8feb205 100644 --- a/backend/src/routes/item.js +++ b/backend/src/routes/item.js @@ -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' }); diff --git a/backend/src/routes/note.js b/backend/src/routes/note.js index 8773bc47..f9028df5 100644 --- a/backend/src/routes/note.js +++ b/backend/src/routes/note.js @@ -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(); diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js index fb3f5cbb..f1befd00 100644 --- a/dragonroll-foundry/scripts/api.js +++ b/dragonroll-foundry/scripts/api.js @@ -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 diff --git a/frontend/app/components/partials/ContentSidebar.vue b/frontend/app/components/partials/ContentSidebar.vue index e6b5dd10..e6c87212 100644 --- a/frontend/app/components/partials/ContentSidebar.vue +++ b/frontend/app/components/partials/ContentSidebar.vue @@ -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(() => { -
- - {{ item.name }} - {{ t('campaigns.synced') }} - - {{ itemSummary(item) }} -
+