// 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 };