Fix issue #49: Unify folder system
Some checks failed
Test / test (push) Failing after 2s

This commit is contained in:
Gitea OpenCode Agent
2026-10-15 12:11:19 +00:00
parent 0106c13835
commit cd92a2d112
19 changed files with 875 additions and 127 deletions

View File

@@ -35,6 +35,13 @@ const ActorSchema = new Schema({
ref: 'Campaign',
required: true
},
// The folder this actor stands in: a Folder of the same campaign whose target is
// 'actor' (null = the root of the actor list).
folder: {
type: Schema.Types.ObjectId,
ref: 'Folder',
default: null
},
foundryActorId: { type: String },
date: { type: Date, default: Date.now }
});

View File

@@ -1,6 +1,12 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Which campaign list a folder belongs to. Every sidebar section files its rows into
// folders of its own, and all of them share this model: note folders are what it has
// always held, and their rows carry no target at all, so anything reading the note tree
// asks with `filterForTarget('note')` and keeps finding them.
const FOLDER_TARGETS = ['note', 'actor', 'item', 'map'];
const FolderSchema = new Schema({
name: { type: String, required: true },
campaign: {
@@ -12,10 +18,7 @@ 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' },
target: { type: String, enum: FOLDER_TARGETS, default: 'note' },
// The Foundry item folder this row mirrors, set by the item sync only
// (see routes/foundry-link.js).
foundryFolderId: { type: String },
@@ -28,4 +31,33 @@ FolderSchema.index(
{ unique: true, partialFilterExpression: { foundryFolderId: { $type: 'string' } } }
);
// The sections a folder can file rows of, and whether a request names one of them.
FolderSchema.statics.isTarget = function isTarget(target) {
return FOLDER_TARGETS.includes(target);
};
// The filter matching one section's folders, to spread into a `find` along with whatever
// else the listing asks for. The notes ask for "none of the other sections" because the
// rows saved before `target` existed carry none at all and are all note folders.
FolderSchema.statics.filterForTarget = function filterForTarget(target) {
if (target === 'note') {
return { target: { $nin: FOLDER_TARGETS.filter((other) => other !== 'note') } };
}
return { target };
};
// The folder an entry of a section may stand in: `null` is the root of that list, and
// anything else has to be a folder of the same campaign *and* the same section, so a
// move never files an entry where its own list would not show it again. Answers whether
// it does — an id that is none of those says `false` rather than throwing.
FolderSchema.statics.belongsToSection = async function belongsToSection(folderId, campaignId, target) {
if (folderId === null || folderId === undefined || folderId === '') return true;
if (!mongoose.isValidObjectId(folderId)) return false;
const folder = await this
.findOne({ _id: folderId, campaign: campaignId, ...this.filterForTarget(target) })
.lean();
return Boolean(folder);
};
module.exports = mongoose.model('Folder', FolderSchema);

View File

@@ -32,6 +32,13 @@ const MapSchema = new Schema({
ref: 'Campaign',
required: true
},
// The folder this map stands in: a Folder of the same campaign whose target is
// 'map' (null = the root of the map list).
folder: {
type: Schema.Types.ObjectId,
ref: 'Folder',
default: null
},
date: { type: Date, default: Date.now }
});

View File

@@ -5,6 +5,7 @@ const upload = require('../services/storage');
const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Folder = require('../models/Folder');
const Map = require('../models/Map');
async function userOwnsCampaign(campaignId, userId) {
@@ -12,6 +13,15 @@ async function userOwnsCampaign(campaignId, userId) {
return Boolean(campaign);
}
// Folders the campaign's actors are grouped into, in the shape the sidebar groups by
// (the notes, items and maps each keep a tree of their own, see models/Folder.js).
async function actorFolders(campaignId) {
return Folder.find({ campaign: campaignId, target: 'actor' })
.select('_id name parentFolder date color')
.sort({ date: -1 })
.lean();
}
router.get('/list', async (req, res) => {
try {
const { campaign } = req.query;
@@ -19,7 +29,7 @@ router.get('/list', async (req, res) => {
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const actors = await Actor.find({ campaign }).sort({ name: 1 }).lean();
res.json({ status: 'ok', actors });
res.json({ status: 'ok', actors, folders: await actorFolders(campaign) });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
@@ -46,13 +56,22 @@ router.post('/create', async (req, res) => {
router.post('/update', async (req, res) => {
try {
const { id, name, species, className, subclass, level, abilityScores, armorClass, speed, proficiencies, inventory, traits, spells, image } = req.body;
const { id, name, species, className, subclass, level, abilityScores, armorClass, speed, proficiencies, inventory, traits, spells, image, folder } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const actor = await Actor.findById(id);
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(actor.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
// `null` moves the actor to the root of the actor list, an id files it in one of
// this campaign's actor folders; anything else is refused.
if (folder !== undefined) {
if (!(await Folder.belongsToSection(folder || null, actor.campaign, 'actor'))) {
return res.json({ status: 'error', msg: 'errors.notfound' });
}
actor.folder = folder || null;
}
if (name !== undefined) actor.name = String(name).trim();
if (species !== undefined) actor.species = species;
if (className !== undefined) actor.className = className;

View File

@@ -2,7 +2,9 @@ const express = require('express');
const router = express.Router();
const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Folder = require('../models/Folder');
const Map = require('../models/Map');
const Note = require('../models/Note');
const Item = require('../models/Item');
@@ -13,14 +15,16 @@ async function userOwnsCampaign(campaignId, userId) {
router.get('/list', async (req, res) => {
try {
const { campaign } = req.query;
if (!campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
// Every sidebar section has its own folders; a request that names none means the
// notes, like every caller of this route has until the other sections got theirs.
const { campaign, target = 'note' } = req.query;
if (!campaign || !Folder.isTarget(target)) return res.json({ status: 'error', msg: 'errors.missing-data' });
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name date color')
const folders = await Folder.find({ campaign, ...Folder.filterForTarget(target) })
.select('_id name parentFolder date color')
.sort({ date: -1 })
.lean();
@@ -33,15 +37,16 @@ router.get('/list', async (req, res) => {
router.post('/create', async (req, res) => {
try {
const { name, campaign } = req.body;
if (!name || !campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
const { name, campaign, target = 'note' } = req.body;
if (!name || !campaign || !Folder.isTarget(target)) return res.json({ status: 'error', msg: 'errors.missing-data' });
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const newFolder = new Folder({
name: name.trim(),
campaign
campaign,
target
});
await newFolder.save();
res.json({ status: 'ok', folder: newFolder });
@@ -51,6 +56,7 @@ router.post('/create', async (req, res) => {
}
});
// Renaming and colouring works the same for the folders of every campaign section.
router.post('/update', async (req, res) => {
try {
const { id, name, color } = req.body;
@@ -86,16 +92,25 @@ router.post('/delete', async (req, res) => {
async function moveRecursive(folderId) {
const subfolders = await Folder.find({ parentFolder: folderId }).select('_id').lean();
// Every section files rows into a folder of its own, so each of them moves what
// stands in this one to the root of its own list instead of leaving it pointing
// at a folder that is gone.
await Note.updateMany(
{ 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 Actor.updateMany(
{ folder: folderId },
{ $set: { folder: null } }
);
await Item.updateMany(
{ folder: folderId },
{ $set: { folder: null } }
);
await Map.updateMany(
{ folder: folderId },
{ $set: { folder: null } }
);
await Folder.deleteOne({ _id: folderId });
for (const sub of subfolders) {
await moveRecursive(sub._id);

View File

@@ -119,8 +119,8 @@ async function saveFoundryItem(campaign, source, fullSync = false, folders = nul
// 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.
// is. The world owns the folder of its own directory, so a move it reports lands on
// a full snapshot too and wins over one a campaign made from its item list.
const folder = resolveFoundryItemFolder(source, folders);
if (folder !== undefined) item.folder = folder;
await item.save();

View File

@@ -16,7 +16,7 @@ async function userOwnsCampaign(campaignId, userId) {
// (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')
.select('_id name parentFolder date color')
.sort({ date: -1 })
.lean();
}
@@ -56,13 +56,23 @@ router.post('/create', async (req, res) => {
router.post('/update', async (req, res) => {
try {
const { id, name, category, rarity, quantity, weight, properties, description, image } = req.body;
const { id, name, category, rarity, quantity, weight, properties, description, image, folder } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const item = await Item.findById(id);
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(item.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
// `null` moves the item to the root of the item list, an id files it in one of
// this campaign's item folders; anything else is refused. The linked world owns
// its own folder tree, so a move it reports later wins over one made here.
if (folder !== undefined) {
if (!(await Folder.belongsToSection(folder || null, item.campaign, 'item'))) {
return res.json({ status: 'error', msg: 'errors.notfound' });
}
item.folder = folder || null;
}
if (name !== undefined) item.name = String(name).trim();
if (category !== undefined) item.category = category;
if (rarity !== undefined) item.rarity = rarity;

View File

@@ -5,6 +5,7 @@ const upload = require('../services/storage');
const Campaign = require('../models/Campaign');
const Map = require('../models/Map');
const Folder = require('../models/Folder');
const Note = require('../models/Note');
const Actor = require('../models/Actor');
@@ -13,6 +14,15 @@ async function userOwnsCampaign(campaignId, userId) {
return Boolean(campaign);
}
// Folders the campaign's maps are grouped into, in the shape the sidebar groups by
// (the notes, actors and items each keep a tree of their own, see models/Folder.js).
async function mapFolders(campaignId) {
return Folder.find({ campaign: campaignId, target: 'map' })
.select('_id name parentFolder date color')
.sort({ date: -1 })
.lean();
}
// Grid values arrive as strings when the request is a multipart form upload.
function toNumber(value, fallback) {
if (value === undefined || value === null || value === '') return fallback;
@@ -27,7 +37,7 @@ router.get('/list', async (req, res) => {
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const maps = await Map.find({ campaign }).sort({ name: 1 }).lean();
res.json({ status: 'ok', maps });
res.json({ status: 'ok', maps, folders: await mapFolders(campaign) });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
@@ -57,13 +67,22 @@ router.post('/create', upload.single('image'), async (req, res) => {
router.post('/update', upload.single('image'), async (req, res) => {
try {
const { id, name, gridSize, offsetX, offsetY, scale } = req.body;
const { id, name, gridSize, offsetX, offsetY, scale, folder } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const map = await Map.findById(id);
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
// `null` moves the map to the root of the map list, an id files it in one of this
// campaign's map folders; anything else is refused.
if (folder !== undefined) {
if (!(await Folder.belongsToSection(folder || null, map.campaign, 'map'))) {
return res.json({ status: 'error', msg: 'errors.notfound' });
}
map.folder = folder || null;
}
if (name !== undefined) map.name = String(name).trim();
if (gridSize !== undefined) map.gridSize = toNumber(gridSize, map.gridSize);
if (offsetX !== undefined) map.offsetX = toNumber(offsetX, map.offsetX);

View File

@@ -19,9 +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' });
// 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' } })
// The note tree only: the folders of the actors, items and maps share this model
// and would otherwise turn up as empty folders between the notes.
const folders = await Folder.find({ campaign, ...Folder.filterForTarget('note') })
.select('_id name parentFolder date color')
.sort({ date: -1 })
.lean();
@@ -50,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, target: { $ne: 'item' } })
const subfolders = await Folder.find({ campaign, parentFolder: folder, ...Folder.filterForTarget('note') })
.select('_id name date color')
.sort({ date: -1 })
.lean();
@@ -82,7 +82,7 @@ router.get('/all', async (req, res) => {
.sort({ title: 1 })
.lean();
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
const folders = await Folder.find({ campaign, ...Folder.filterForTarget('note') })
.select('_id name parentFolder')
.lean();

View File

@@ -5,11 +5,13 @@ 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 { BuildColorMenu } from '~/services/EntryColors';
import { BuildItemRows } from '~/services/ItemFolders';
import Server from '~/services/Server';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
import { ACTOR_DRAG_TYPE } from '~/services/MapTokens';
import EntryFolderRow from './EntryFolderRow.vue';
import NestedNoteList from './NestedNoteList.vue';
const { Campaign } = useCampaignService();
@@ -18,12 +20,13 @@ 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 };
// Every sidebar section files its rows into folders of its own (see models/Folder.js), so
// each entry list keeps the tree `/actor|item|map/list` sends along. Folders are open by
// default: a folder synced from Foundry should show what stands in it, not hide it.
const entryFolders = { actor: ref([]), item: ref([]), map: ref([]) };
const collapsedFolderIds = ref([]);
const loadingNotes = ref(false);
const loadingEntries = ref(false);
const notesError = ref('');
@@ -111,12 +114,27 @@ function handleNoteDeleted(noteKey) {
notes.value = notes.value.filter(n => n.key !== noteKey);
}
function handleFolderSaved() {
function sectionForTarget(target) {
if (target === 'actor') return 'actors';
if (target === 'item') return 'items';
if (target === 'map') return 'maps';
return null;
}
function handleFolderSaved(folder) {
// A folder only shows up once the list it belongs to reads it back: the notes refetch
// their tree, an entry list refetches its own (silently, its rows are already there).
const section = sectionForTarget(folder?.target ?? 'note');
if (!section) {
fetchCampaignNotes();
return;
}
fetchCampaignEntries(section, true);
}
function handleFolderDeleted(folderId) {
expandedFolderIds.value = expandedFolderIds.value.filter((id) => id !== folderId);
collapsedFolderIds.value = collapsedFolderIds.value.filter((id) => id !== folderId);
}
function handleCampaignEntryCreated({ entityType, entry }) {
@@ -207,9 +225,10 @@ 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 ?? [];
// Every entry list comes with the folders its rows stand in, so the sidebar can
// group them the way the note tree does (and the way the Foundry item directory
// arrives for items).
entryFolders[kind].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);
@@ -243,6 +262,14 @@ function createEntry(entityType) {
CreateWindow('create_campaign_entry', { entityType, campaign: campaignId.value });
}
// Every section files its rows into folders of its own: the window passes along which
// list the folder belongs to, so the notes, the actors, the items and the maps each keep
// a tree the others never show.
function createFolder(target = 'note') {
if (!campaignId.value) return;
CreateWindow('new_folder', { campaign: campaignId.value, target });
}
function entrySummary(actor) {
const bits = [t(`campaigns.actor.types.${actor.type}`)];
if (actor.species) bits.push(actor.species);
@@ -289,6 +316,14 @@ function showEntryMenu(entry, entityType) {
});
}
// Rows of every section can be filed into a folder of their own list, like a note
// into a folder of the note tree.
menuItems.push({
name: t('campaigns.folders.move-to'),
icon: '/icons/iconoir/regular/folder.svg',
context: moveToFolderMenu(entityType, entry)
});
menuItems.push({
name: t('campaigns.actions.delete'),
icon: '/icons/iconoir/regular/trash.svg',
@@ -305,6 +340,74 @@ function showEntryMenu(entry, entityType) {
ShowContextMenu(menuItems);
}
// The menu of a folder row: rename it, colour it, delete it. The notes' folders are
// renamed and coloured the same way, through the same `/folder/*` routes.
function folderMenuItems(folder) {
return [
{
name: t('campaigns.folders.rename'), icon: '/icons/iconoir/regular/edit-pencil.svg',
action: () => {
HideContextMenu();
CreateWindow('new_folder', { folderId: folder._id, campaign: campaignId.value, name: folder.name });
}
},
{
name: t('campaigns.folders.color'), icon: '/icons/iconoir/regular/palette.svg',
context: BuildColorMenu((color) => setFolderColor(folder, color), { defaultLabel: t('campaigns.folders.default') })
},
{ divider: true },
{ name: t('campaigns.folders.delete'), icon: '/icons/iconoir/regular/trash.svg', action: () => deleteEntryFolder(folder) }
];
}
async function setFolderColor(folder, color) {
try {
const response = await Server().post('/folder/update', { id: folder._id, color });
if (response.data.status === 'ok') folder.color = color;
} catch (error) {} finally {
HideContextMenu();
}
}
async function deleteEntryFolder(folder) {
try {
const response = await Server().post('/folder/delete', { id: folder._id });
if (response.data.status !== 'ok') return;
collapsedFolderIds.value = collapsedFolderIds.value.filter((id) => id !== folder._id);
// Whatever stood in the folder moved to the root of the list along with it.
await fetchCampaignEntries(activeSection.value, true);
} catch (error) {} finally {
HideContextMenu();
}
}
// The 'move to folder' submenu of an entry: the folders of its own list and its root.
function moveToFolderMenu(entityType, entry) {
const menuItems = entryFolders[entityType].value.map((folder) => ({
name: folder.name, icon: '/icons/iconoir/regular/folder.svg',
action: () => moveEntryToFolder(entityType, entry, folder._id)
}));
if (menuItems.length > 0) menuItems.push({ divider: true });
menuItems.push({
name: t('campaigns.folders.root'), icon: '/icons/iconoir/regular/xmark-circle.svg',
action: () => moveEntryToFolder(entityType, entry, null)
});
return menuItems;
}
async function moveEntryToFolder(entityType, entry, folderId) {
try {
const response = await Server().post(`/${entityType}/update`, { id: entry._id, folder: folderId });
if (response.data.status !== 'ok') return;
// The row walks over to its new folder. This is the event a Foundry sync of the
// entry sends, so the list regroups and a window open on it sees the change.
emitter.emit('campaign-entry-updated', { entityType, entry: response.data[entityType] });
} catch (error) {} finally {
HideContextMenu();
}
}
async function openCharacterSheet(actor) {
const existingWindowId = GetFirstWindowId('character_sheet');
if (existingWindowId !== undefined) {
@@ -343,38 +446,41 @@ function createNote() {
CreateWindow('new_note', { campaign: campaignId.value });
}
function createFolder() {
CreateWindow('new_folder', { campaign: campaignId.value });
}
function toggleSidebar() {
sidebarCollapsed.value = !sidebarCollapsed.value;
}
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));
// The rows of each entry list: every folder followed by what stands in it, deeper and
// deeper, the way the item list has done since its folders arrived from the linked world
// (services/ItemFolders.js builds them from the list and the folders the API sends).
// Without any folder this is the plain list, and `row.item` is the entry of the section
// the row belongs to: its actor, item or map.
const entryRows = {
actor: computed(() => BuildItemRows(actors.value, entryFolders.actor.value, collapsedFolderIds.value)),
item: computed(() => BuildItemRows(items.value, entryFolders.item.value, collapsedFolderIds.value)),
map: computed(() => BuildItemRows(maps.value, entryFolders.map.value, collapsedFolderIds.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];
function toggleFolder(folderId) {
collapsedFolderIds.value = collapsedFolderIds.value.includes(folderId)
? collapsedFolderIds.value.filter((id) => id !== folderId)
: [...collapsedFolderIds.value, folderId];
}
watch(campaignId, (newVal) => {
if (newVal) {
actors.value = [];
items.value = [];
itemFolders.value = [];
collapsedItemFolderIds.value = [];
maps.value = [];
for (const sectionFolders of Object.values(entryFolders)) sectionFolders.value = [];
collapsedFolderIds.value = [];
ClearAnchoredMap();
fetchCampaignNotes();
if (isEntrySection(activeSection.value)) fetchCampaignEntries(activeSection.value);
@@ -383,9 +489,9 @@ watch(campaignId, (newVal) => {
folders.value = [];
actors.value = [];
items.value = [];
itemFolders.value = [];
collapsedItemFolderIds.value = [];
maps.value = [];
for (const sectionFolders of Object.values(entryFolders)) sectionFolders.value = [];
collapsedFolderIds.value = [];
notesError.value = '';
entriesError.value = '';
ClearAnchoredMap();
@@ -496,7 +602,7 @@ onBeforeUnmount(() => {
<button class="sidebar-action" type="button" @click="createNote" :disabled="!Campaign" :title="t('campaigns.actions.new-note')" :aria-label="t('campaigns.actions.new-note')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/plus.svg" alt="" aria-hidden="true">
</button>
<button class="sidebar-action" type="button" @click="createFolder" :disabled="!Campaign" :title="t('campaigns.actions.new-folder')" :aria-label="t('campaigns.actions.new-folder')">
<button class="sidebar-action" type="button" @click="createFolder()" :disabled="!Campaign" :title="t('campaigns.actions.new-folder')" :aria-label="t('campaigns.actions.new-folder')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
</button>
<button class="sidebar-action" type="button" @click="fetchCampaignNotes" :disabled="!Campaign || loadingNotes" :title="t('campaigns.actions.refresh')" :aria-label="t('campaigns.actions.refresh')">
@@ -507,6 +613,9 @@ onBeforeUnmount(() => {
<button class="sidebar-action" type="button" @click="createEntry(entryEntityType(activeSection))" :disabled="!Campaign" :title="t('campaigns.actions.create', { section: t(`campaigns.sections.${activeSection}`).toLowerCase() })" :aria-label="t('campaigns.actions.create', { section: t(`campaigns.sections.${activeSection}`).toLowerCase() })">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/plus.svg" alt="" aria-hidden="true">
</button>
<button class="sidebar-action" type="button" @click="createFolder(entryEntityType(activeSection))" :disabled="!Campaign" :title="t('campaigns.actions.new-folder')" :aria-label="t('campaigns.actions.new-folder')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
</button>
<button class="sidebar-action" type="button" @click="fetchCampaignEntries(activeSection)" :disabled="!Campaign || loadingEntries" :title="t('campaigns.actions.refresh')" :aria-label="t('campaigns.actions.refresh')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/refresh.svg" alt="" aria-hidden="true">
</button>
@@ -528,36 +637,38 @@ onBeforeUnmount(() => {
<template v-else-if="activeSection === 'actors'">
<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="actors.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-actors') }}</div>
<div v-for="actor in actors" :key="actor._id" class="entity-entry" role="button" tabindex="0" draggable="true" :title="t('campaigns.map.tokens.drag')" @click="openCharacterSheet(actor)" @keydown.enter="openCharacterSheet(actor)" @keydown.space.prevent="openCharacterSheet(actor)" @dragstart="startActorDrag($event, actor)" @contextmenu.prevent="showEntryMenu(actor, 'actor')">
<span class="entity-entry-name">{{ actor.name }}</span>
<span class="entity-entry-meta">{{ entrySummary(actor) }}</span>
<div v-else-if="actors.length === 0 && entryFolders.actor.value.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-actors') }}</div>
<template v-for="row in entryRows.actor.value" :key="row.key">
<EntryFolderRow
v-if="row.kind === 'folder'"
:folder="row.folder"
:collapsed="collapsedFolderIds.includes(row.folder._id)"
:indent="rowIndent(row.depth)"
:menu="folderMenuItems(row.folder)"
:toggle-label="t('campaigns.folders.toggle', { name: row.folder.name })"
@toggle="toggleFolder(row.folder._id)"
/>
<div v-else class="entity-entry" :style="rowIndent(row.depth)" role="button" tabindex="0" draggable="true" :title="t('campaigns.map.tokens.drag')" @click="openCharacterSheet(row.item)" @keydown.enter="openCharacterSheet(row.item)" @keydown.space.prevent="openCharacterSheet(row.item)" @dragstart="startActorDrag($event, row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'actor')">
<span class="entity-entry-name">{{ row.item.name }}</span>
<span class="entity-entry-meta">{{ entrySummary(row.item) }}</span>
</div>
</template>
</template>
<template v-else-if="activeSection === 'items'">
<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>
<template v-for="row in itemRows" :key="row.key">
<button
<div v-else-if="items.length === 0 && entryFolders.item.value.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div>
<template v-for="row in entryRows.item.value" :key="row.key">
<EntryFolderRow
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>
:folder="row.folder"
:collapsed="collapsedFolderIds.includes(row.folder._id)"
:indent="rowIndent(row.depth)"
:menu="folderMenuItems(row.folder)"
:toggle-label="t('campaigns.folders.toggle', { name: row.folder.name })"
@toggle="toggleFolder(row.folder._id)"
/>
<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>
@@ -571,16 +682,27 @@ onBeforeUnmount(() => {
<template v-else>
<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="maps.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-maps') }}</div>
<div v-for="map in maps" :key="map._id" class="entity-entry" :class="{ anchored: isAnchoredMap(map) }" role="button" tabindex="0" @click="openMapViewer(map)" @keydown.enter="openMapViewer(map)" @keydown.space.prevent="openMapViewer(map)" @contextmenu.prevent="showEntryMenu(map, 'map')">
<div v-else-if="maps.length === 0 && entryFolders.map.value.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-maps') }}</div>
<template v-for="row in entryRows.map.value" :key="row.key">
<EntryFolderRow
v-if="row.kind === 'folder'"
:folder="row.folder"
:collapsed="collapsedFolderIds.includes(row.folder._id)"
:indent="rowIndent(row.depth)"
:menu="folderMenuItems(row.folder)"
:toggle-label="t('campaigns.folders.toggle', { name: row.folder.name })"
@toggle="toggleFolder(row.folder._id)"
/>
<div v-else class="entity-entry" :style="rowIndent(row.depth)" :class="{ anchored: isAnchoredMap(row.item) }" role="button" tabindex="0" @click="openMapViewer(row.item)" @keydown.enter="openMapViewer(row.item)" @keydown.space.prevent="openMapViewer(row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'map')">
<span class="entity-entry-name-row">
<span class="entity-entry-name">{{ map.name }}</span>
<span v-if="isAnchoredMap(map)" class="entity-entry-sync">{{ t('campaigns.map.anchored') }}</span>
<span class="entity-entry-name">{{ row.item.name }}</span>
<span v-if="isAnchoredMap(row.item)" class="entity-entry-sync">{{ t('campaigns.map.anchored') }}</span>
</span>
<span class="entity-entry-meta">{{ mapSummary(map) }}</span>
<span v-if="!map.image" class="entity-entry-description">{{ t('campaigns.map.no-image') }}</span>
<span class="entity-entry-meta">{{ mapSummary(row.item) }}</span>
<span v-if="!row.item.image" class="entity-entry-description">{{ t('campaigns.map.no-image') }}</span>
</div>
</template>
</template>
</div>
</aside>
</div>
@@ -731,18 +853,6 @@ 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,57 @@
<script setup>
// One folder row of a campaign entry list (actors, items or maps), nested by the depth the
// folder stands at. Toggling it collapses what is inside; its context menu renames the
// folder, colours it, and deletes it. Note folders have their own tree (NestedNoteList),
// which loads its contents one folder at a time.
import { ShowContextMenu } from '~/services/ContextMenu';
const props = defineProps({
folder: { type: Object, required: true },
collapsed: { type: Boolean, default: false },
// The padding of the level this folder stands at, from the sidebar's `rowIndent`.
indent: { type: Object, default: () => ({}) },
menu: { type: Array, default: () => [] },
toggleLabel: { type: String, default: '' }
});
const emit = defineEmits(['toggle']);
</script>
<template>
<button
class="entry-folder-row"
:class="{ 'has-color': !!folder.color }"
:style="[indent, folder.color ? { '--entry-color': folder.color } : null]"
type="button"
:aria-expanded="(!collapsed).toString()"
:aria-label="toggleLabel"
@click="emit('toggle')"
@contextmenu.prevent="ShowContextMenu(menu)"
>
<img
class="entry-folder-arrow"
:src="collapsed ? '/icons/iconoir/regular/nav-arrow-right.svg' : '/icons/iconoir/regular/nav-arrow-down.svg'"
alt=""
aria-hidden="true"
>
<img class="entry-folder-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
<span class="entry-folder-name">{{ folder.name }}</span>
</button>
</template>
<style scoped>
/* The same row box as an entry, since folders and entries share the sidebar list and its
width rules. */
.entry-folder-row {
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;
}
.entry-folder-row:hover { background: var(--color-background-soft); }
.entry-folder-row:focus-visible { outline: 1px solid var(--color-link); }
.entry-folder-row.has-color { background: color-mix(in srgb, var(--entry-color) 32%, transparent); }
.entry-folder-row.has-color:hover { background: color-mix(in srgb, var(--entry-color) 50%, transparent); }
.entry-folder-arrow { width: 12px; height: 12px; flex: 0 0 12px; filter: invert(var(--color-icon-invert)); opacity: 0.6; }
.entry-folder-icon { width: 15px; height: 15px; flex: 0 0 15px; filter: invert(var(--color-icon-invert)); }
.entry-folder-name { min-width: 0; font-weight: bold; word-break: break-word; }
</style>

View File

@@ -1,6 +1,7 @@
<script setup>
import { ref, onBeforeUnmount, onMounted, watch } from 'vue';
import { emitter } from '~/services/Emitter';
import { BuildColorMenu } from '~/services/EntryColors';
import Server from '~/services/Server';
import { CreateWindow } from '~/services/Windows';
import { ShowContextMenu, HideContextMenu } from '~/services/ContextMenu';
@@ -20,18 +21,6 @@ const emit = defineEmits(['open-note', 'reload-notes']);
const loadingFolders = new Set();
const dragHoveredFolderId = ref(null);
// Preset colors for notes and folders (shown as swatches in the context menu)
const entryColors = [
{ name: 'Red', value: '#e74c3c' },
{ name: 'Orange', value: '#e67e22' },
{ name: 'Yellow', value: '#f1c40f' },
{ name: 'Green', value: '#2ecc71' },
{ name: 'Teal', value: '#1abc9c' },
{ name: 'Blue', value: '#3498db' },
{ name: 'Purple', value: '#9b59b6' },
{ name: 'Pink', value: '#fd79a8' }
];
// Cache of loaded folder contents — persists across reloads until cleared
// Each entry: { [folderId]: { notes: [], subfolders: [] } }
const folderContentCache = ref({});
@@ -216,13 +205,7 @@ function buildFolderContextMenu(folder) {
}
function buildColorMenu(kind, item) {
const colorItems = entryColors.map((color) => ({
name: color.name, color: color.value, action: () => setEntryColor(kind, item, color.value)
}));
colorItems.push({ divider: true });
colorItems.push({ name: 'Default', icon: '/icons/iconoir/regular/xmark-circle.svg', action: () => setEntryColor(kind, item, null) });
return colorItems;
return BuildColorMenu((color) => setEntryColor(kind, item, color));
}
async function setEntryColor(kind, item, color) {

View File

@@ -40,6 +40,10 @@ function confirmSave() {
const url = creating ? '/folder/rename' : '/folder/create';
if (creating) {
folderData.id = data.folderId;
} else {
// Which campaign list the folder belongs to: the notes when the caller says
// nothing, one of the entry lists when their sidebar button opens this window.
folderData.target = data.target ?? 'note';
}
Server().post(url, folderData).then((response) => {

View File

@@ -0,0 +1,27 @@
// The colours a note, a folder or an entry row can be given, and shown as swatches in the
// sidebar's colour menus. The list lives here because every campaign section colours its
// rows the same way; nothing in it talks to the API or holds state.
const ENTRY_COLORS = [
{ name: 'Red', value: '#e74c3c' },
{ name: 'Orange', value: '#e67e22' },
{ name: 'Yellow', value: '#f1c40f' },
{ name: 'Green', value: '#2ecc71' },
{ name: 'Teal', value: '#1abc9c' },
{ name: 'Blue', value: '#3498db' },
{ name: 'Purple', value: '#9b59b6' },
{ name: 'Pink', value: '#fd79a8' }
];
// The 'Color' submenu: one swatch per preset colour, and a way back to no colour at all.
// `pick` is called with the colour, or null for the default.
function BuildColorMenu(pick, { defaultLabel = 'Default' } = {}) {
const items = ENTRY_COLORS.map((color) => ({
name: color.name, color: color.value, action: () => pick(color.value)
}));
items.push({ divider: true });
items.push({ name: defaultLabel, icon: '/icons/iconoir/regular/xmark-circle.svg', action: () => pick(null) });
return items;
}
export { ENTRY_COLORS, BuildColorMenu };

View File

@@ -44,6 +44,11 @@
"create": "Crea {section}", "submit": "Crea", "edit": "Edita", "save": "Desa", "delete": "Suprimeix", "saving": "Desant...",
"collapse-sidebar": "Redueix la barra lateral", "expand-sidebar": "Expandeix la barra lateral"
},
"folders": {
"toggle": "Mostra o amaga la carpeta {name}",
"rename": "Canvia el nom", "color": "Color", "default": "Per defecte", "delete": "Suprimeix la carpeta",
"move-to": "Mou a carpeta...", "root": "Arrel"
},
"states": {
"loading": "Carregant...", "loading-notes": "Carregant notes...", "empty-notes": "Encara no hi ha notes en aquesta campanya.",
"empty-actors": "Encara no hi ha actors ni personatges.", "empty-items": "Encara no hi ha objectes en aquesta campanya.",
@@ -62,7 +67,6 @@
"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

@@ -48,6 +48,11 @@
"create": "Create {section}", "submit": "Create", "edit": "Edit", "save": "Save", "delete": "Delete", "saving": "Saving...",
"collapse-sidebar": "Collapse sidebar", "expand-sidebar": "Expand sidebar"
},
"folders": {
"toggle": "Toggle the {name} folder",
"rename": "Rename", "color": "Color", "default": "Default", "delete": "Delete folder",
"move-to": "Move to folder...", "root": "Root"
},
"states": {
"loading": "Loading...", "loading-notes": "Loading notes...", "empty-notes": "No notes in this campaign yet.",
"empty-actors": "No actors or characters yet.", "empty-items": "No items in this campaign yet.",
@@ -66,7 +71,6 @@
"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

@@ -44,6 +44,11 @@
"create": "Crear {section}", "submit": "Crear", "edit": "Editar", "save": "Guardar", "delete": "Eliminar", "saving": "Guardando...",
"collapse-sidebar": "Contraer barra lateral", "expand-sidebar": "Expandir barra lateral"
},
"folders": {
"toggle": "Muestra o oculta la carpeta {name}",
"rename": "Renombrar", "color": "Color", "default": "Por defecto", "delete": "Eliminar carpeta",
"move-to": "Mover a carpeta...", "root": "Raíz"
},
"states": {
"loading": "Cargando...", "loading-notes": "Cargando notas...", "empty-notes": "Aún no hay notas en esta campaña.",
"empty-actors": "Aún no hay actores ni personajes.", "empty-items": "Aún no hay objetos en esta campaña.",
@@ -62,7 +67,6 @@
"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.",

444
tests/entry-folders.test.js Normal file
View File

@@ -0,0 +1,444 @@
// Tests for the folder system shared by every campaign list (Syndria98/dragonroll#49):
// folders are created, renamed, coloured and deleted for the actors, the items and the
// maps as well as for the notes, and each list only ever shows the folders of its own.
//
// The repository root installs no dependencies, so each side is loaded the way the other
// tests do it. The routes run against a stubbed `require` (express and the models answer
// with plain objects and a small filter matcher) — except the Folder model's own logic,
// which is read out of the real model file so its target filter is the one under test. The
// frontend services are plain ES modules and are read as text, and the sidebar is read as
// text too, the way tests/sidebar-entity-entry.test.js reads it.
//
// 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");
// --- Enough of the query language the folder routes use --------------------------
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) && !(expected instanceof Date)) {
return Object.entries(expected).every(([operator, wanted]) => {
// A row without the field at all counts as "not one of these", which is
// how MongoDB's $nin keeps the note folders saved before `target` existed.
if (operator === "$ne") return String(value ?? "") !== String(wanted ?? "");
if (operator === "$in") return wanted.some((entry) => String(value ?? "") === String(entry ?? ""));
if (operator === "$nin") return !wanted.some((entry) => String(value ?? "") === String(entry ?? ""));
if (operator === "$exists") return (value !== undefined && value !== null) === wanted;
throw new Error(`filter operator "${key}.${operator}" is not stubbed`);
});
}
return String(value ?? "") === String(expected ?? "");
});
}
function mongooseQuery(rows) {
const result = {
select: () => result,
sort: () => result,
limit: (count) => mongooseQuery(rows.slice(0, count)),
lean: () => Promise.resolve(rows),
then: (onFulfilled, onRejected) => Promise.resolve(rows).then(onFulfilled, onRejected),
};
return result;
}
function fakeCollection(name, seed = []) {
const rows = [];
let counter = 0;
function Document(data = {}) {
counter += 1;
this._id = `${name}-${counter}`;
this.isNew = true;
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; } });
function seedRow(data) {
const row = new Document(data);
row.isNew = false;
rows.push(row);
return row;
}
for (const data of seed) seedRow(data);
const model = function Model(data) { return new Document(data); };
model.rows = rows;
model.seed = seedRow;
model.find = (filter) => mongooseQuery(rows.filter((row) => matches(row, filter)));
// A row that answers both when awaited and through `.lean()`, because the routes read
// some of their lookups one way and some the other.
const one = (row) => Object.assign(Promise.resolve(row ?? null), { lean: () => Promise.resolve(row ?? null) });
model.findOne = (filter) => one(rows.find((document) => matches(document, filter)));
model.findById = (id) => one(rows.find((document) => String(document._id) === String(id)));
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.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;
}
// --- The real Folder model's own logic, over a stubbed mongoose -------------------
// The model file's statics (`filterForTarget`, `isTarget`, `belongsToSection`) and the
// `target` enum, read out of the file with a mongoose that only builds a schema. What the
// routes ask for is therefore the code under test, not a copy of it.
function realFolderModel(seed = []) {
let definition = null;
function Schema(schemaDefinition) {
definition = schemaDefinition;
this.statics = {};
}
Schema.prototype.index = function index() {};
Schema.Types = { ObjectId: "ObjectId" };
const mongoose = {
Schema,
isValidObjectId: (value) => typeof value === "string" && value.length > 0,
model: (name, schema) => Object.assign(function Model() {}, schema.statics),
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "models", "Folder.js"), ["require", "module"])(
(id) => {
if (id === "mongoose") return mongoose;
throw new Error(`require("${id}") is not stubbed`);
},
moduleStub
);
const collection = fakeCollection("folder", seed);
const model = Object.assign(collection, moduleStub.exports);
model.definition = () => definition;
return model;
}
// --- Routes against stubbed models ----------------------------------------------
function loadRoute(file, models) {
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 };
// The image upload middleware: the folder routes never see a file.
if (id === "../services/storage") return { single: () => (req, res, next) => next() };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", file), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
return async function call(route, { body = {}, query = {} } = {}) {
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, user: { id: "user-1" } }, res);
return res.payload;
};
}
// The routes share one set of tables, the way the API does: a folder deleted through
// `/folder/delete` has to empty the rows pointing at it in each of them.
function campaign({ folders = [], notes = [], actors = [], items = [], maps = [] } = {}) {
const campaignDoc = { _id: "campaign-1", id: "campaign-1", createdBy: "user-1" };
const collections = {
// Folders belong to the campaign the tests run their requests against unless a
// seed says otherwise.
Folder: realFolderModel(folders.map((folder) => ({ campaign: "campaign-1", ...folder }))),
Note: fakeCollection("note", notes),
Actor: fakeCollection("actor", actors),
Item: fakeCollection("item", items),
Map: fakeCollection("map", maps),
};
const models = {
// `userOwnsCampaign` reads the campaign through `findOne(...).lean()`.
"../models/Campaign": { findOne: () => ({ lean: async () => campaignDoc }) },
"../models/Folder": collections.Folder,
"../models/Note": collections.Note,
"../models/Actor": collections.Actor,
"../models/Item": collections.Item,
"../models/Map": collections.Map,
};
return { call: (file) => loadRoute(file, models), collections };
}
// --- Every list gets a folder of its own ----------------------------------------
test("a folder is made for the campaign list the sidebar names", async () => {
const { collections, call } = campaign();
const create = await call("folder.js");
for (const target of ["actor", "item", "map"]) {
const response = await create("POST /create", { body: { name: `${target} folder`, campaign: "campaign-1", target } });
assert.equal(response.status, "ok");
assert.equal(response.folder.target, target, `${target} folders are filed as such`);
}
assert.deepEqual(collections.Folder.rows.map((folder) => folder.target), ["actor", "item", "map"]);
});
test("a folder made without a target belongs to the notes, as it always did", async () => {
const { collections, call } = campaign();
const response = await call("folder.js")("POST /create", { body: { name: "Lore", campaign: "campaign-1" } });
assert.equal(response.status, "ok");
assert.equal(collections.Folder.rows[0].target, "note");
});
test("the notes keep the folders saved before the model knew about targets", async () => {
const legacy = { _id: "folder-legacy", name: "Old lore" };
const { collections, call } = campaign({
folders: [legacy, { _id: "folder-actors", name: "Adventurers", target: "actor" }],
});
const notes = await call("note.js")("GET /list", { query: { campaign: "campaign-1" } });
const listed = await call("folder.js")("GET /list", { query: { campaign: "campaign-1" } });
assert.equal(notes.status, "ok");
assert.deepEqual(notes.folders.map((folder) => folder._id), ["folder-legacy"], "the notes tree shows its own folders only");
assert.deepEqual(listed.folders.map((folder) => folder._id), ["folder-legacy"], "and a request naming no target means the notes");
assert.deepEqual(collections.Folder.rows.length, 2, "the actor folder is left alone, it is another list's");
});
test("a list answers with the folders of its own section", async () => {
const { call } = campaign({
folders: [
{ _id: "folder-note", name: "Lore", target: "note" },
{ _id: "folder-actor", name: "Adventurers", target: "actor" },
{ _id: "folder-item", name: "Gear", target: "item" },
{ _id: "folder-map", name: "Regions", target: "map" },
],
});
for (const [target, ids] of [["note", ["folder-note"]], ["actor", ["folder-actor"]], ["item", ["folder-item"]], ["map", ["folder-map"]]]) {
const response = await call("folder.js")("GET /list", { query: { campaign: "campaign-1", target } });
assert.deepEqual(response.folders.map((folder) => folder._id), ids, `${target} folders only`);
}
});
test("a folder is not made for a list that does not exist", async () => {
const { collections, call } = campaign();
const response = await call("folder.js")("POST /create", { body: { name: "Nowhere", campaign: "campaign-1", target: "spell" } });
assert.equal(response.status, "error");
assert.equal(response.msg, "errors.missing-data");
assert.deepEqual(collections.Folder.rows, []);
});
test("the actor, item and map lists send the tree their rows stand in", async () => {
const { call } = campaign({
folders: [{ _id: "folder-actor", name: "Adventurers", target: "actor", color: "#e74c3c" }],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1" }],
items: [{ _id: "item-1", name: "Longsword", campaign: "campaign-1" }],
maps: [{ _id: "map-1", name: "Crossroads", campaign: "campaign-1" }],
});
for (const [file, key] of [["actor.js", "actors"], ["item.js", "items"], ["map.js", "maps"]]) {
const response = await call(file)("GET /list", { query: { campaign: "campaign-1" } });
assert.equal(response.status, "ok");
assert.equal(response[key].length, 1);
assert.ok(Array.isArray(response.folders), `${file} sends its folders along`);
}
});
// --- Filing rows, and emptying a folder that goes away ---------------------------
test("an actor, an item and a map each move into a folder of their own list", async () => {
const { collections, call } = campaign({
folders: [
{ _id: "folder-actor", name: "Adventurers", target: "actor" },
{ _id: "folder-item", name: "Gear", target: "item" },
{ _id: "folder-map", name: "Regions", target: "map" },
],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1" }],
items: [{ _id: "item-1", name: "Longsword", campaign: "campaign-1" }],
maps: [{ _id: "map-1", name: "Crossroads", campaign: "campaign-1" }],
});
const actor = await call("actor.js")("POST /update", { body: { id: "actor-1", folder: "folder-actor" } });
const item = await call("item.js")("POST /update", { body: { id: "item-1", folder: "folder-item" } });
const map = await call("map.js")("POST /update", { body: { id: "map-1", folder: "folder-map" } });
assert.equal(actor.status, "ok");
assert.equal(String(actor.actor.folder), "folder-actor");
assert.equal(String(collections.Actor.rows[0].folder), "folder-actor");
assert.equal(String(item.item.folder), "folder-item");
assert.equal(String(map.map.folder), "folder-map");
});
test("a move refuses a folder of another list, or of another campaign", async () => {
const { collections, call } = campaign({
folders: [
{ _id: "folder-actor", name: "Adventurers", target: "actor" },
{ _id: "folder-item", name: "Gear", target: "item" },
{ _id: "folder-other", name: "Somebody else's", target: "actor", campaign: "campaign-2" },
],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1" }],
});
const update = await call("actor.js");
const wrongList = await update("POST /update", { body: { id: "actor-1", folder: "folder-item" } });
const wrongCampaign = await update("POST /update", { body: { id: "actor-1", folder: "folder-other" } });
assert.equal(wrongList.status, "error");
assert.equal(wrongList.msg, "errors.notfound");
assert.equal(wrongCampaign.status, "error");
assert.equal(collections.Actor.rows[0].folder, undefined, "the actor stays where it was");
const toRoot = await update("POST /update", { body: { id: "actor-1", folder: null } });
assert.equal(toRoot.status, "ok");
assert.equal(toRoot.actor.folder, null, "and the root of the list is always a valid target");
});
test("updating an entry that says nothing about folders leaves it where it stands", async () => {
const { collections, call } = campaign({
folders: [{ _id: "folder-actor", name: "Adventurers", target: "actor" }],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1", folder: "folder-actor" }],
});
const response = await call("actor.js")("POST /update", { body: { id: "actor-1", level: 3 } });
assert.equal(response.status, "ok");
assert.equal(String(collections.Actor.rows[0].folder), "folder-actor", "a sheet save does not file the actor away");
});
test("deleting a folder moves what stood in it to the root of every list", async () => {
const { collections, call } = campaign({
folders: [
{ _id: "folder-actor", name: "Adventurers", target: "actor" },
{ _id: "folder-actor-sub", name: "Family", target: "actor", parentFolder: "folder-actor" },
],
notes: [{ _id: "note-1", title: "Lore", campaign: "campaign-1", folder: "folder-actor-sub" }],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1", folder: "folder-actor" }],
items: [{ _id: "item-1", name: "Longsword", campaign: "campaign-1", folder: "folder-actor" }],
maps: [{ _id: "map-1", name: "Crossroads", campaign: "campaign-1", folder: "folder-actor-sub" }],
});
const response = await call("folder.js")("POST /delete", { body: { id: "folder-actor" } });
assert.equal(response.status, "ok");
assert.deepEqual(collections.Folder.rows, [], "the folder and the one nested in it are gone");
assert.equal(collections.Actor.rows[0].folder, null);
assert.equal(collections.Item.rows[0].folder, null);
assert.equal(collections.Map.rows[0].folder, null);
assert.equal(collections.Note.rows[0].folder, null);
});
// --- The frontend: one folder row, and a menu that works everywhere --------------
function loadEntryColorsService() {
const source = read("frontend", "app", "services", "EntryColors.js").replace(
"export { ENTRY_COLORS, BuildColorMenu };", "return { ENTRY_COLORS, BuildColorMenu };"
);
return vm.compileFunction(source)();
}
test("the colour menu offers the palette once, to every section", () => {
const { ENTRY_COLORS, BuildColorMenu } = loadEntryColorsService();
const picked = [];
const menu = BuildColorMenu((color) => picked.push(color), { defaultLabel: "No colour" });
assert.equal(menu.filter((item) => item.color).length, ENTRY_COLORS.length, "one swatch per preset colour");
assert.deepEqual(menu.at(-1).name, "No colour");
menu.at(-1).action();
assert.deepEqual(picked, [null], "and the last item takes the colour off");
menu[0].action();
assert.deepEqual(picked, [null, ENTRY_COLORS[0].value]);
// The notes' tree shares the palette instead of keeping its own copy.
const noteTree = read("frontend", "app", "components", "partials", "NestedNoteList.vue");
assert.match(noteTree, /import \{ BuildColorMenu \} from '~\/services\/EntryColors'/);
assert.doesNotMatch(noteTree, /const entryColors = /, "the note tree has no palette of its own");
});
test("every entry section files its rows under folder rows", () => {
const sidebar = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
// The three entry lists are each built from their own folders and rendered with the
// folder row, which is how the item list already did it.
for (const kind of ["actor", "item", "map"]) {
assert.match(sidebar, new RegExp(`${kind}: computed\\(\\(\\) => BuildItemRows\\(${kind}s\\.value, entryFolders\\.${kind}\\.value, collapsedFolderIds\\.value\\)\\)`));
}
assert.equal(sidebar.match(/<EntryFolderRow/g)?.length, 3, "each entry section renders folder rows");
assert.match(sidebar, /entryFolders\[kind\]\.value = response\.data\.folders/, "each list reads the tree it is sent");
});
test("every entry section can create, rename, colour and delete a folder", () => {
const sidebar = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
// The header's folder button names the list the folder belongs to; the notes ask for
// their own, and a click event must not slip in as the target.
assert.match(sidebar, /@click="createFolder\(\)"/);
assert.match(sidebar, /@click="createFolder\(entryEntityType\(activeSection\)\)"/);
assert.match(sidebar, /function createFolder\(target = 'note'\)/);
assert.match(sidebar, /CreateWindow\('new_folder', \{ campaign: campaignId\.value, target \}\)/);
// Rename, colour, delete: the same routes the note tree uses, so the same window and
// the same `/folder/*` calls serve every section.
assert.match(sidebar, /CreateWindow\('new_folder', \{ folderId: folder\._id, campaign: campaignId\.value, name: folder\.name \}\)/);
assert.match(sidebar, /Server\(\)\.post\('\/folder\/update', \{ id: folder\._id, color \}\)/);
assert.match(sidebar, /Server\(\)\.post\('\/folder\/delete', \{ id: folder\._id \}\)/);
// And an entry of any list can be filed into a folder, or back to the root.
assert.match(sidebar, /Server\(\)\.post\(`\/\$\{entityType\}\/update`, \{ id: entry\._id, folder: folderId \}\)/);
// The window hands the target to the API when making a folder.
const window = read("frontend", "app", "components", "windows", "NewFolderWindow.vue");
assert.match(window, /folderData\.target = data\.target \?\? 'note'/);
// A saved folder only appears in the list it belongs to.
assert.match(sidebar, /fetchCampaignEntries\(section, true\)/);
});
test("a folder row says what it is and shows the colour it was given", () => {
const row = read("frontend", "app", "components", "partials", "EntryFolderRow.vue");
assert.match(row, /:aria-expanded="\(!collapsed\)\.toString\(\)"/);
assert.match(row, /@click="emit\('toggle'\)"/);
assert.match(row, /@contextmenu\.prevent="ShowContextMenu\(menu\)"/);
assert.match(row, /folder\.color \? \{ '--entry-color': folder\.color \} : null/);
// The colour tints the row instead of replacing its text colours, the way notes and
// note folders do.
assert.match(row, /\.entry-folder-row\.has-color \{ background: color-mix\(in srgb, var\(--entry-color\)/);
});
test("every locale says what the folder menus do", () => {
const keys = ["toggle", "rename", "color", "default", "delete", "move-to", "root"];
for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
for (const key of keys) {
assert.ok(campaigns.folders?.[key], `${locale} is missing campaigns.folders.${key}`);
}
}
});

View File

@@ -290,16 +290,18 @@ test("an item the world moved out of a folder follows it to the root", async ()
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.
test("every folder listing says which campaign list it belongs to", () => {
// The sidebar's four lists share the Folder model, so a listing that names no target
// would show folders of the other lists between its own rows. The note routes and
// `/folder/list` ask through `Folder.filterForTarget`, which for the notes names every
// other section instead of the notes' own target: note folders made before the target
// field existed carry none at all. tests/entry-folders.test.js runs these routes.
for (const route of ["note.js", "folder.js"]) {
const source = read("backend", "src", "routes", route);
const listings = source.match(/Folder\.find\(\{[^}]*\}\)/g) ?? [];
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}`);
}
const filtered = source.match(/Folder\.find\(\{[^{]*Folder\.filterForTarget\((?:'note'|target)\)/g) ?? [];
assert.equal(filtered.length, listings.length, `${route} has a folder listing that names no campaign list`);
}
});
@@ -582,9 +584,9 @@ test("an item whose folder is gone, or a folder nested in itself, reads as a roo
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", () => {
test("every locale labels the 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`);
assert.ok(campaigns.folders?.["toggle"], `${locale} is missing campaigns.folders.toggle`);
}
});