Compare commits
18 Commits
844ed006cc
...
ai/issue-6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b47bbb4cab | ||
| cdafd1f53a | |||
| 2e2fb97e5d | |||
|
|
d03cc1eb59 | ||
| 20128d195b | |||
| d901385900 | |||
|
|
2add9e7cb8 | ||
| fe63bd15f3 | |||
| 733e7ef193 | |||
| d566388fc6 | |||
| 86e1d34beb | |||
| cd741880ac | |||
| 378e28f703 | |||
|
|
7e1ed4475e | ||
|
|
0c6026aea8 | ||
| 4b6200960f | |||
| 1e0d81ecc4 | |||
|
|
cd92a2d112 |
@@ -99,7 +99,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user
|
|||||||
- `actor` — `list`, `create`, `update` (partial, ownership checked), `upload-image?actor=` (multipart), `delete`
|
- `actor` — `list`, `create`, `update` (partial, ownership checked), `upload-image?actor=` (multipart), `delete`
|
||||||
- `item` — `list`, `create`, `update` (partial), `delete`
|
- `item` — `list`, `create`, `update` (partial), `delete`
|
||||||
- `map` — `list`, `create` (multipart `image` or JSON), `update` (multipart to replace the photo), `delete`, `pin` (`{id,note,x,y}`, re-pinning moves the marker), `unpin` (`{id,pin}`), `place-token` (`{id,actor,x,y}`, snapped to a cell centre, re-placing moves the token), `remove-token` (`{id,token}`)
|
- `map` — `list`, `create` (multipart `image` or JSON), `update` (multipart to replace the photo), `delete`, `pin` (`{id,note,x,y}`, re-pinning moves the marker), `unpin` (`{id,pin}`), `place-token` (`{id,actor,x,y}`, snapped to a cell centre, re-placing moves the token), `remove-token` (`{id,token}`)
|
||||||
- `foundry` — read-only proxy over the bridge (`/world`, `/actors`, `/characters`, `/items`, `/actors/:id`, `/items/:id`, `/actors/:id/items`), needs `FOUNDRY_API_URL`
|
- `foundry` — read-only proxy over the bridge (`/world`, `/actors`, `/characters`, `/items`, `/actors/:id`, `/items/:id`, `/actors/:id/items`), needs `FOUNDRY_API_URL`; `/icons?campaign=&dir=&offset=` lists one folder of the world's core `icons/` library (the bridge reads it from `DRAGONROLL_FOUNDRY_DATA_PATH`) and answers `{dir, parent, folders, files[{path,name,url}], next}`, the icons paged so the library stays lazy to load
|
||||||
|
|
||||||
## 4. Service integrations (Foundry, Discord, Obsidian)
|
## 4. Service integrations (Foundry, Discord, Obsidian)
|
||||||
|
|
||||||
@@ -118,6 +118,7 @@ the JWT guard; CORS opened for it): `snapshot` (actors + world items, `fullSync`
|
|||||||
|
|
||||||
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index); a Foundry document carrying the `dragonroll-foundry.actorId` / `.itemId` flag adopts the matching Dragonroll row.
|
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index); a Foundry document carrying the `dragonroll-foundry.actorId` / `.itemId` flag adopts the matching Dragonroll row.
|
||||||
- **Items are deduplicated by name** — Foundry keeps the same gear once per carrier, so one `Item` per name; `foundryNames` keeps Foundry's names so a Dragonroll rename does not resurrect a duplicate. `services/item-foundry.js` returns `null` for non-gear types and those are skipped.
|
- **Items are deduplicated by name** — Foundry keeps the same gear once per carrier, so one `Item` per name; `foundryNames` keeps Foundry's names so a Dragonroll rename does not resurrect a duplicate. `services/item-foundry.js` returns `null` for non-gear types and those are skipped.
|
||||||
|
- **Item folders mirror the world's item directory** (`Folder.foundryFolderId`, target `item`): every push carries the whole tree and the world owns its names and nesting. `color` is the one field the campaign sets too, so it travels back with the folders `GET /foundry/sync/items` answers with (`{items, folders}`) and the module writes it onto the world's folder.
|
||||||
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events overwrite. Only a full snapshot can prune.
|
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events overwrite. Only a full snapshot can prune.
|
||||||
- **Autosync is a Foundry-side setting** (`autoSync`, on by default): off = no CRUD push, no periodic reconcile, no startup snapshot; the actor directory's *Dragonroll: Force Sync* still upserts the selection (`fullSync:false`).
|
- **Autosync is a Foundry-side setting** (`autoSync`, on by default): off = no CRUD push, no periodic reconcile, no startup snapshot; the actor directory's *Dragonroll: Force Sync* still upserts the selection (`fullSync:false`).
|
||||||
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge.
|
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge.
|
||||||
|
|||||||
@@ -35,6 +35,13 @@ const ActorSchema = new Schema({
|
|||||||
ref: 'Campaign',
|
ref: 'Campaign',
|
||||||
required: true
|
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 },
|
foundryActorId: { type: String },
|
||||||
date: { type: Date, default: Date.now }
|
date: { type: Date, default: Date.now }
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
const mongoose = require('mongoose');
|
const mongoose = require('mongoose');
|
||||||
const Schema = mongoose.Schema;
|
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({
|
const FolderSchema = new Schema({
|
||||||
name: { type: String, required: true },
|
name: { type: String, required: true },
|
||||||
campaign: {
|
campaign: {
|
||||||
@@ -12,10 +18,7 @@ const FolderSchema = new Schema({
|
|||||||
type: Schema.Types.ObjectId,
|
type: Schema.Types.ObjectId,
|
||||||
ref: 'Folder'
|
ref: 'Folder'
|
||||||
},
|
},
|
||||||
// Which campaign list a folder belongs to. Note folders are what this model has
|
target: { type: String, enum: FOLDER_TARGETS, default: 'note' },
|
||||||
// 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
|
// The Foundry item folder this row mirrors, set by the item sync only
|
||||||
// (see routes/foundry-link.js).
|
// (see routes/foundry-link.js).
|
||||||
foundryFolderId: { type: String },
|
foundryFolderId: { type: String },
|
||||||
@@ -28,4 +31,33 @@ FolderSchema.index(
|
|||||||
{ unique: true, partialFilterExpression: { foundryFolderId: { $type: 'string' } } }
|
{ 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);
|
module.exports = mongoose.model('Folder', FolderSchema);
|
||||||
|
|||||||
@@ -32,6 +32,13 @@ const MapSchema = new Schema({
|
|||||||
ref: 'Campaign',
|
ref: 'Campaign',
|
||||||
required: true
|
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 }
|
date: { type: Date, default: Date.now }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ const upload = require('../services/storage');
|
|||||||
|
|
||||||
const Campaign = require('../models/Campaign');
|
const Campaign = require('../models/Campaign');
|
||||||
const Actor = require('../models/Actor');
|
const Actor = require('../models/Actor');
|
||||||
|
const Folder = require('../models/Folder');
|
||||||
const Map = require('../models/Map');
|
const Map = require('../models/Map');
|
||||||
|
|
||||||
async function userOwnsCampaign(campaignId, userId) {
|
async function userOwnsCampaign(campaignId, userId) {
|
||||||
@@ -12,6 +13,15 @@ async function userOwnsCampaign(campaignId, userId) {
|
|||||||
return Boolean(campaign);
|
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) => {
|
router.get('/list', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { campaign } = req.query;
|
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' });
|
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||||
|
|
||||||
const actors = await Actor.find({ campaign }).sort({ name: 1 }).lean();
|
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) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
res.json({ status: 'error', msg: 'errors.internal' });
|
res.json({ status: 'error', msg: 'errors.internal' });
|
||||||
@@ -46,13 +56,22 @@ router.post('/create', async (req, res) => {
|
|||||||
|
|
||||||
router.post('/update', async (req, res) => {
|
router.post('/update', async (req, res) => {
|
||||||
try {
|
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' });
|
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||||
|
|
||||||
const actor = await Actor.findById(id);
|
const actor = await Actor.findById(id);
|
||||||
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
|
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' });
|
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 (name !== undefined) actor.name = String(name).trim();
|
||||||
if (species !== undefined) actor.species = species;
|
if (species !== undefined) actor.species = species;
|
||||||
if (className !== undefined) actor.className = className;
|
if (className !== undefined) actor.className = className;
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ const express = require('express');
|
|||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
const Campaign = require('../models/Campaign');
|
const Campaign = require('../models/Campaign');
|
||||||
|
const Actor = require('../models/Actor');
|
||||||
const Folder = require('../models/Folder');
|
const Folder = require('../models/Folder');
|
||||||
|
const Map = require('../models/Map');
|
||||||
const Note = require('../models/Note');
|
const Note = require('../models/Note');
|
||||||
const Item = require('../models/Item');
|
const Item = require('../models/Item');
|
||||||
|
|
||||||
@@ -13,14 +15,16 @@ async function userOwnsCampaign(campaignId, userId) {
|
|||||||
|
|
||||||
router.get('/list', async (req, res) => {
|
router.get('/list', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { campaign } = req.query;
|
// Every sidebar section has its own folders; a request that names none means the
|
||||||
if (!campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
// 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);
|
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
|
||||||
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
|
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||||
|
|
||||||
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
|
const folders = await Folder.find({ campaign, ...Folder.filterForTarget(target) })
|
||||||
.select('_id name date color')
|
.select('_id name parentFolder date color')
|
||||||
.sort({ date: -1 })
|
.sort({ date: -1 })
|
||||||
.lean();
|
.lean();
|
||||||
|
|
||||||
@@ -33,15 +37,16 @@ router.get('/list', async (req, res) => {
|
|||||||
|
|
||||||
router.post('/create', async (req, res) => {
|
router.post('/create', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { name, campaign } = req.body;
|
const { name, campaign, target = 'note' } = req.body;
|
||||||
if (!name || !campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
if (!name || !campaign || !Folder.isTarget(target)) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||||
|
|
||||||
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
|
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
|
||||||
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
|
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||||
|
|
||||||
const newFolder = new Folder({
|
const newFolder = new Folder({
|
||||||
name: name.trim(),
|
name: name.trim(),
|
||||||
campaign
|
campaign,
|
||||||
|
target
|
||||||
});
|
});
|
||||||
await newFolder.save();
|
await newFolder.save();
|
||||||
res.json({ status: 'ok', folder: newFolder });
|
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) => {
|
router.post('/update', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id, name, color } = req.body;
|
const { id, name, color } = req.body;
|
||||||
@@ -86,16 +92,25 @@ router.post('/delete', async (req, res) => {
|
|||||||
|
|
||||||
async function moveRecursive(folderId) {
|
async function moveRecursive(folderId) {
|
||||||
const subfolders = await Folder.find({ parentFolder: folderId }).select('_id').lean();
|
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(
|
await Note.updateMany(
|
||||||
{ folder: folderId },
|
{ folder: folderId },
|
||||||
{ $set: { folder: null, date: Date.now() } }
|
{ $set: { folder: null, date: Date.now() } }
|
||||||
);
|
);
|
||||||
// Item folders share this model: the items inside move to the root of
|
await Actor.updateMany(
|
||||||
// the item list rather than point at a folder that is gone.
|
{ folder: folderId },
|
||||||
|
{ $set: { folder: null } }
|
||||||
|
);
|
||||||
await Item.updateMany(
|
await Item.updateMany(
|
||||||
{ folder: folderId },
|
{ folder: folderId },
|
||||||
{ $set: { folder: null } }
|
{ $set: { folder: null } }
|
||||||
);
|
);
|
||||||
|
await Map.updateMany(
|
||||||
|
{ folder: folderId },
|
||||||
|
{ $set: { folder: null } }
|
||||||
|
);
|
||||||
await Folder.deleteOne({ _id: folderId });
|
await Folder.deleteOne({ _id: folderId });
|
||||||
for (const sub of subfolders) {
|
for (const sub of subfolders) {
|
||||||
await moveRecursive(sub._id);
|
await moveRecursive(sub._id);
|
||||||
|
|||||||
@@ -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.
|
// 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
|
// `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
|
// 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
|
// is. The world owns the folder of its own directory, so a move it reports lands on
|
||||||
// snapshot too: nothing on the Dragonroll side files items by hand.
|
// a full snapshot too and wins over one a campaign made from its item list.
|
||||||
const folder = resolveFoundryItemFolder(source, folders);
|
const folder = resolveFoundryItemFolder(source, folders);
|
||||||
if (folder !== undefined) item.folder = folder;
|
if (folder !== undefined) item.folder = folder;
|
||||||
await item.save();
|
await item.save();
|
||||||
@@ -144,6 +144,16 @@ async function syncFoundryItems(campaign, sources, fullSync = false, folders = n
|
|||||||
// say nothing: the folders they carry belong to that actor's own inventory, and
|
// say nothing: the folders they carry belong to that actor's own inventory, and
|
||||||
// Dragonroll keeps one item per piece of gear anyway.
|
// Dragonroll keeps one item per piece of gear anyway.
|
||||||
|
|
||||||
|
// The colour a pushed folder carries. `undefined` means the push says nothing about
|
||||||
|
// colours — an older module, which knows nothing about them — and the colour the
|
||||||
|
// campaign has stays; `null` is the world leaving a folder uncoloured, which takes
|
||||||
|
// the campaign's colour off along with it. Anything else is the colour to show.
|
||||||
|
function foundryFolderColor(source) {
|
||||||
|
if (source?.color === undefined) return undefined;
|
||||||
|
const color = typeof source.color === 'string' ? source.color.trim() : '';
|
||||||
|
return color || null;
|
||||||
|
}
|
||||||
|
|
||||||
// Parents before children, so a folder is mapped before the one nested in it.
|
// 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.
|
// A folder whose parent is missing, or caught in a cycle, becomes a root.
|
||||||
function orderFoundryFolderSources(sources) {
|
function orderFoundryFolderSources(sources) {
|
||||||
@@ -152,7 +162,12 @@ function orderFoundryFolderSources(sources) {
|
|||||||
const id = String(source?.id || '').trim().slice(0, 120);
|
const id = String(source?.id || '').trim().slice(0, 120);
|
||||||
const name = String(source?.name || '').trim();
|
const name = String(source?.name || '').trim();
|
||||||
if (!id || !name) continue;
|
if (!id || !name) continue;
|
||||||
byId.set(id, { id, name, parent: String(source?.parent || '').trim().slice(0, 120) });
|
byId.set(id, {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
parent: String(source?.parent || '').trim().slice(0, 120),
|
||||||
|
color: foundryFolderColor(source)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const ordered = [];
|
const ordered = [];
|
||||||
@@ -195,6 +210,10 @@ async function syncFoundryItemFolders(campaign, folderSources) {
|
|||||||
// The world owns this tree, so unlike an item's fields a rename or a move
|
// 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.
|
// lands whatever kind of push carried it: the whole tree arrives with each.
|
||||||
folder.name = source.name;
|
folder.name = source.name;
|
||||||
|
// Its colour is the one part of the tree the campaign colours too: what the
|
||||||
|
// world shows arrives here, and what the campaign picks travels back to the
|
||||||
|
// world with the folder list `/sync/items` answers with.
|
||||||
|
if (source.color !== undefined) folder.color = source.color;
|
||||||
const parent = inTree.has(source.parent) ? folders.get(source.parent) : null;
|
const parent = inTree.has(source.parent) ? folders.get(source.parent) : null;
|
||||||
folder.parentFolder = parent ? parent._id : null;
|
folder.parentFolder = parent ? parent._id : null;
|
||||||
await folder.save();
|
await folder.save();
|
||||||
@@ -388,12 +407,20 @@ router.post('/sync/item-delete', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The item list the world reconciles against, together with the folders its rows are
|
||||||
|
// grouped into — the same shape the campaign's own `/item/list` answers with. The folders
|
||||||
|
// travel back for their colour: the world owns the tree's name and nesting, while whoever
|
||||||
|
// colours a folder on either side expects to see it coloured on the other.
|
||||||
router.get('/sync/items', async (req, res) => {
|
router.get('/sync/items', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const campaign = await syncCampaign(req, res);
|
const campaign = await syncCampaign(req, res);
|
||||||
if (!campaign) return;
|
if (!campaign) return;
|
||||||
const items = await Item.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
|
const items = await Item.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
|
||||||
res.json({ status: 'ok', items });
|
const folders = await Folder.find({ campaign: campaign._id, target: 'item' })
|
||||||
|
.select('_id name color foundryFolderId')
|
||||||
|
.sort({ name: 1 })
|
||||||
|
.lean();
|
||||||
|
res.json({ status: 'ok', items, folders });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
res.json({ status: 'error', msg: 'errors.internal' });
|
res.json({ status: 'error', msg: 'errors.internal' });
|
||||||
|
|||||||
@@ -1,6 +1,16 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const { requestFoundry } = require('../services/foundry');
|
const { requestFoundry } = require('../services/foundry');
|
||||||
|
const { normalizeIconDirectory, readIconListingPage, shapeIconListing } = require('../services/foundry-icons');
|
||||||
|
|
||||||
|
const Campaign = require('../models/Campaign');
|
||||||
|
|
||||||
|
// The world address the icons are loaded from is kept on the campaign, so an icon
|
||||||
|
// listing is always asked for one of the caller's own campaigns.
|
||||||
|
async function findOwnedCampaign(campaignId, userId) {
|
||||||
|
if (!campaignId) return null;
|
||||||
|
return Campaign.findOne({ _id: campaignId, createdBy: userId }).select('settings').lean();
|
||||||
|
}
|
||||||
|
|
||||||
async function proxy(path, res) {
|
async function proxy(path, res) {
|
||||||
try {
|
try {
|
||||||
@@ -24,4 +34,38 @@ router.get('/actors/:id/items', (req, res) => proxy(`api/actors/${encodeURICompo
|
|||||||
router.get('/actors/:id', (req, res) => proxy(`api/actors/${encodeURIComponent(req.params.id)}`, res));
|
router.get('/actors/:id', (req, res) => proxy(`api/actors/${encodeURIComponent(req.params.id)}`, res));
|
||||||
router.get('/items/:id', (req, res) => proxy(`api/items/${encodeURIComponent(req.params.id)}`, res));
|
router.get('/items/:id', (req, res) => proxy(`api/items/${encodeURIComponent(req.params.id)}`, res));
|
||||||
|
|
||||||
|
// Foundry's core icon library: the `icons/` folder of the world's data directory.
|
||||||
|
// One folder per request, and the icons inside it paged, because that library runs
|
||||||
|
// into the thousands and the window only ever shows where the user is standing.
|
||||||
|
// The bridge reads it on the Foundry host; the images themselves are loaded by the
|
||||||
|
// browser from the campaign's world address, the same way a synced item's icon is.
|
||||||
|
router.get('/icons', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const campaign = await findOwnedCampaign(req.query.campaign, req.user.id);
|
||||||
|
if (!campaign) return res.status(404).json({ status: 'error', msg: 'errors.notfound' });
|
||||||
|
|
||||||
|
const base = campaign.settings?.integrations?.foundryUrl || '';
|
||||||
|
if (!base) return res.status(400).json({ status: 'error', msg: 'foundry.errors.icons-no-world-url' });
|
||||||
|
|
||||||
|
const dir = normalizeIconDirectory(req.query.dir);
|
||||||
|
if (!dir) return res.status(400).json({ status: 'error', msg: 'errors.missing-data' });
|
||||||
|
|
||||||
|
const { limit, offset } = readIconListingPage(req.query);
|
||||||
|
const query = new URLSearchParams({ dir, offset: String(offset), limit: String(limit) });
|
||||||
|
const result = await requestFoundry(`api/icons?${query}`);
|
||||||
|
if (result.status !== 200 || result.data?.status !== 'ok') {
|
||||||
|
return res.status(502).json({ status: 'error', msg: 'foundry.errors.icons-unavailable' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ status: 'ok', ...shapeIconListing({ base, dir, listing: result.data }) });
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === 'FOUNDRY_NOT_CONFIGURED') {
|
||||||
|
return res.status(503).json({ status: 'error', msg: 'foundry.errors.icons-unavailable' });
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error(err);
|
||||||
|
res.status(502).json({ status: 'error', msg: 'foundry.errors.icons-unavailable' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ async function userOwnsCampaign(campaignId, userId) {
|
|||||||
// (the world's own item folders arrive through the sync, see routes/foundry-link.js).
|
// (the world's own item folders arrive through the sync, see routes/foundry-link.js).
|
||||||
async function itemFolders(campaignId) {
|
async function itemFolders(campaignId) {
|
||||||
return Folder.find({ campaign: campaignId, target: 'item' })
|
return Folder.find({ campaign: campaignId, target: 'item' })
|
||||||
.select('_id name parentFolder date')
|
.select('_id name parentFolder date color')
|
||||||
.sort({ date: -1 })
|
.sort({ date: -1 })
|
||||||
.lean();
|
.lean();
|
||||||
}
|
}
|
||||||
@@ -56,13 +56,23 @@ router.post('/create', async (req, res) => {
|
|||||||
|
|
||||||
router.post('/update', async (req, res) => {
|
router.post('/update', async (req, res) => {
|
||||||
try {
|
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' });
|
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||||
|
|
||||||
const item = await Item.findById(id);
|
const item = await Item.findById(id);
|
||||||
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
|
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' });
|
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 (name !== undefined) item.name = String(name).trim();
|
||||||
if (category !== undefined) item.category = category;
|
if (category !== undefined) item.category = category;
|
||||||
if (rarity !== undefined) item.rarity = rarity;
|
if (rarity !== undefined) item.rarity = rarity;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ const upload = require('../services/storage');
|
|||||||
|
|
||||||
const Campaign = require('../models/Campaign');
|
const Campaign = require('../models/Campaign');
|
||||||
const Map = require('../models/Map');
|
const Map = require('../models/Map');
|
||||||
|
const Folder = require('../models/Folder');
|
||||||
const Note = require('../models/Note');
|
const Note = require('../models/Note');
|
||||||
const Actor = require('../models/Actor');
|
const Actor = require('../models/Actor');
|
||||||
|
|
||||||
@@ -13,6 +14,15 @@ async function userOwnsCampaign(campaignId, userId) {
|
|||||||
return Boolean(campaign);
|
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.
|
// Grid values arrive as strings when the request is a multipart form upload.
|
||||||
function toNumber(value, fallback) {
|
function toNumber(value, fallback) {
|
||||||
if (value === undefined || value === null || value === '') return 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' });
|
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||||
|
|
||||||
const maps = await Map.find({ campaign }).sort({ name: 1 }).lean();
|
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) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
res.json({ status: 'error', msg: 'errors.internal' });
|
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) => {
|
router.post('/update', upload.single('image'), async (req, res) => {
|
||||||
try {
|
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' });
|
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||||
|
|
||||||
const map = await Map.findById(id);
|
const map = await Map.findById(id);
|
||||||
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
|
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' });
|
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 (name !== undefined) map.name = String(name).trim();
|
||||||
if (gridSize !== undefined) map.gridSize = toNumber(gridSize, map.gridSize);
|
if (gridSize !== undefined) map.gridSize = toNumber(gridSize, map.gridSize);
|
||||||
if (offsetX !== undefined) map.offsetX = toNumber(offsetX, map.offsetX);
|
if (offsetX !== undefined) map.offsetX = toNumber(offsetX, map.offsetX);
|
||||||
|
|||||||
@@ -19,9 +19,9 @@ router.get('/list', async (req, res) => {
|
|||||||
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
|
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
|
||||||
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
|
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||||
|
|
||||||
// The note tree only: item folders share this model and would otherwise
|
// The note tree only: the folders of the actors, items and maps share this model
|
||||||
// turn up as empty folders between the notes.
|
// and would otherwise turn up as empty folders between the notes.
|
||||||
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
|
const folders = await Folder.find({ campaign, ...Folder.filterForTarget('note') })
|
||||||
.select('_id name parentFolder date color')
|
.select('_id name parentFolder date color')
|
||||||
.sort({ date: -1 })
|
.sort({ date: -1 })
|
||||||
.lean();
|
.lean();
|
||||||
@@ -50,7 +50,7 @@ router.get('/subfolder/list', async (req, res) => {
|
|||||||
const folderDoc = await Folder.findOne({ _id: folder, campaign }).lean();
|
const folderDoc = await Folder.findOne({ _id: folder, campaign }).lean();
|
||||||
if (!folderDoc) return res.json({ status: 'error', msg: 'errors.notfound' });
|
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')
|
.select('_id name date color')
|
||||||
.sort({ date: -1 })
|
.sort({ date: -1 })
|
||||||
.lean();
|
.lean();
|
||||||
@@ -82,7 +82,7 @@ router.get('/all', async (req, res) => {
|
|||||||
.sort({ title: 1 })
|
.sort({ title: 1 })
|
||||||
.lean();
|
.lean();
|
||||||
|
|
||||||
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
|
const folders = await Folder.find({ campaign, ...Folder.filterForTarget('note') })
|
||||||
.select('_id name parentFolder')
|
.select('_id name parentFolder')
|
||||||
.lean();
|
.lean();
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,28 @@
|
|||||||
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
|
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
|
||||||
|
|
||||||
|
// D&D 5e keeps an actor's background, species, class and subclass as a reference to an
|
||||||
|
// embedded item: `system.details.background` and friends hold that item's id, and the
|
||||||
|
// field's `fallback` option hands back the bare id when the item is gone. Dragonroll
|
||||||
|
// holds names, so a reference is read through the actor's items and an id that resolves
|
||||||
|
// to nothing is dropped. An id travelling back as a name is how Foundry ends up with a
|
||||||
|
// background item — and a details reference — that does not exist (Syndria98/dragonroll#54).
|
||||||
|
const FOUNDRY_DOCUMENT_ID = /^[A-Za-z0-9_-]{16}$/;
|
||||||
|
|
||||||
|
function looksLikeFoundryId(value) {
|
||||||
|
// Sixteen plain letters is a name; the ids Foundry generates carry a digit.
|
||||||
|
return FOUNDRY_DOCUMENT_ID.test(value) && /[0-9]/.test(value) && /[A-Za-z]/.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The name a `system.details` entry stands for: an embedded item's id resolves to that
|
||||||
|
// item's name, and plain text (older system releases store the name here) is the name.
|
||||||
|
function detailsName(value, items) {
|
||||||
|
const text = asText(value).trim();
|
||||||
|
if (!text) return '';
|
||||||
|
const referenced = items.find((item) => asText(item?._id ?? item?.id).trim() === text);
|
||||||
|
if (referenced) return asText(referenced.name).trim();
|
||||||
|
return looksLikeFoundryId(text) ? '' : text;
|
||||||
|
}
|
||||||
|
|
||||||
function foundryActorToCharacter(foundryActor) {
|
function foundryActorToCharacter(foundryActor) {
|
||||||
const system = foundryActor.system || {};
|
const system = foundryActor.system || {};
|
||||||
const details = system.details || {};
|
const details = system.details || {};
|
||||||
@@ -25,11 +48,11 @@ function foundryActorToCharacter(foundryActor) {
|
|||||||
type: ['character', 'npc', 'creature'].includes(savedDragonrollType)
|
type: ['character', 'npc', 'creature'].includes(savedDragonrollType)
|
||||||
? savedDragonrollType
|
? savedDragonrollType
|
||||||
: (['character', 'npc', 'creature'].includes(foundryActor.type) ? foundryActor.type : 'character'),
|
: (['character', 'npc', 'creature'].includes(foundryActor.type) ? foundryActor.type : 'character'),
|
||||||
species: asText(details.race || details.species),
|
species: detailsName(details.race || details.species, items),
|
||||||
className: asText(details.class || classItem?.name),
|
className: detailsName(details.class, items) || asText(classItem?.name),
|
||||||
subclass: asText(details.subclass || subclassItem?.name),
|
subclass: detailsName(details.subclass, items) || asText(subclassItem?.name),
|
||||||
level: numberOr(details.level ?? classItem?.system?.levels, 1),
|
level: numberOr(details.level ?? classItem?.system?.levels, 1),
|
||||||
background: asText(details.background || backgroundItem?.name),
|
background: detailsName(details.background, items) || asText(backgroundItem?.name),
|
||||||
challengeRating: String(details.cr ?? ''),
|
challengeRating: String(details.cr ?? ''),
|
||||||
description: plainText(details.biography?.value || details.biography),
|
description: plainText(details.biography?.value || details.biography),
|
||||||
image: asText(foundryActor.img || foundryActor.image),
|
image: asText(foundryActor.img || foundryActor.image),
|
||||||
|
|||||||
110
backend/src/services/foundry-icons.js
Normal file
110
backend/src/services/foundry-icons.js
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
// Foundry's core icon library is the `icons/` folder of its data directory: a few
|
||||||
|
// thousand images spread over its own folder tree. Dragonroll never reads that
|
||||||
|
// tree itself — the bridge on the Foundry host lists one folder per request (see
|
||||||
|
// dragonroll-foundry/bridge/server.js) — but everything that goes over the wire is
|
||||||
|
// normalised here first, so a caller cannot ask for a folder outside the icon root.
|
||||||
|
|
||||||
|
const ICON_ROOT = 'icons';
|
||||||
|
|
||||||
|
// Image formats Foundry's own file picker offers.
|
||||||
|
const ICON_EXTENSIONS = ['.svg', '.png', '.webp', '.jpg', '.jpeg', '.gif', '.avif'];
|
||||||
|
|
||||||
|
// How many icons one request lists. The window asks again for the next page, so a
|
||||||
|
// folder with hundreds of them is never sent or rendered all at once.
|
||||||
|
const DEFAULT_ICON_PAGE_SIZE = 120;
|
||||||
|
const MAX_ICON_PAGE_SIZE = 500;
|
||||||
|
|
||||||
|
// The folder a listing request asks for, inside the icon root: `icons`, `icons/svg`,
|
||||||
|
// ... Empty asks for the root. Anything that tries to leave the root is invalid.
|
||||||
|
function normalizeIconDirectory(input) {
|
||||||
|
const raw = String(input ?? '').trim().replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
|
||||||
|
if (!raw || raw === '.') return ICON_ROOT;
|
||||||
|
|
||||||
|
const segments = raw.split('/').filter((segment) => segment && segment !== '.');
|
||||||
|
if (!segments.length || segments.includes('..')) return null;
|
||||||
|
if (segments[0] !== ICON_ROOT) return null;
|
||||||
|
return segments.join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
// The folder above an icon folder, or null at the root.
|
||||||
|
function parentIconDirectory(dir) {
|
||||||
|
const normalized = normalizeIconDirectory(dir);
|
||||||
|
if (!normalized || normalized === ICON_ROOT) return null;
|
||||||
|
return normalized.slice(0, normalized.lastIndexOf('/'));
|
||||||
|
}
|
||||||
|
function iconName(filePath) {
|
||||||
|
const path = String(filePath ?? '');
|
||||||
|
return path.slice(path.lastIndexOf('/') + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isIconFile(filePath) {
|
||||||
|
const lower = String(filePath ?? '').toLowerCase();
|
||||||
|
return ICON_EXTENSIONS.some((extension) => lower.endsWith(extension));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Where the browser loads a Foundry data file from: Foundry serves its data
|
||||||
|
// directory over the world's own address, which is the one the campaign keeps
|
||||||
|
// (settings.integrations.foundryUrl). Items store icons as these absolute URLs,
|
||||||
|
// the same way a synced Foundry item's icon arrives as one.
|
||||||
|
function joinFoundryAssetUrl(baseUrl, filePath) {
|
||||||
|
const base = String(baseUrl ?? '').trim();
|
||||||
|
const file = String(filePath ?? '').trim().replace(/^\/+/, '');
|
||||||
|
if (!base || !file) return '';
|
||||||
|
return `${base.replace(/\/+$/, '')}/${encodeURI(file)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The page a request asks for. Directories are always listed whole — the window
|
||||||
|
// needs every subfolder to navigate — so paging only ever covers the icons.
|
||||||
|
function readIconListingPage(query) {
|
||||||
|
const requestedLimit = Number(query?.limit);
|
||||||
|
const limit = Number.isFinite(requestedLimit)
|
||||||
|
? Math.min(MAX_ICON_PAGE_SIZE, Math.max(1, Math.trunc(requestedLimit)))
|
||||||
|
: DEFAULT_ICON_PAGE_SIZE;
|
||||||
|
const requestedOffset = Number(query?.offset);
|
||||||
|
const offset = Number.isFinite(requestedOffset) ? Math.max(0, Math.trunc(requestedOffset)) : 0;
|
||||||
|
|
||||||
|
return { limit, offset };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The bridge answers with plain relative paths; this is the shape the icon window
|
||||||
|
// works with: the folder it shows, the one above it, its subfolders, and its icons
|
||||||
|
// with a url to load. `next` is the offset of the next page, null once it is all
|
||||||
|
// listed, which is what keeps a big library lazy to load.
|
||||||
|
function shapeIconListing({ base = '', dir, listing = {} } = {}) {
|
||||||
|
const current = normalizeIconDirectory(dir ?? listing.dir) || ICON_ROOT;
|
||||||
|
|
||||||
|
const folders = [];
|
||||||
|
const seenFolders = new Set();
|
||||||
|
for (const entry of Array.isArray(listing.directories) ? listing.directories : []) {
|
||||||
|
const path = normalizeIconDirectory(typeof entry === 'string' ? entry : entry?.path);
|
||||||
|
if (!path || path === current || seenFolders.has(path)) continue;
|
||||||
|
seenFolders.add(path);
|
||||||
|
folders.push({ path, name: iconName(path) });
|
||||||
|
}
|
||||||
|
|
||||||
|
const files = (Array.isArray(listing.files) ? listing.files : [])
|
||||||
|
.map((entry) => String(typeof entry === 'string' ? entry : entry?.path ?? '').trim().replace(/^\/+/, ''))
|
||||||
|
.filter((entry) => entry.startsWith(`${ICON_ROOT}/`) && isIconFile(entry))
|
||||||
|
.map((entry) => ({ path: entry, name: iconName(entry), url: joinFoundryAssetUrl(base, entry) }));
|
||||||
|
|
||||||
|
const offset = Number.isFinite(Number(listing.offset)) ? Math.max(0, Math.trunc(Number(listing.offset))) : 0;
|
||||||
|
const next = Number.isFinite(Number(listing.next)) && Number(listing.next) > offset
|
||||||
|
? Math.trunc(Number(listing.next))
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return { dir: current, parent: parentIconDirectory(current), folders, files, offset, next };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
ICON_ROOT,
|
||||||
|
ICON_EXTENSIONS,
|
||||||
|
DEFAULT_ICON_PAGE_SIZE,
|
||||||
|
MAX_ICON_PAGE_SIZE,
|
||||||
|
normalizeIconDirectory,
|
||||||
|
parentIconDirectory,
|
||||||
|
iconName,
|
||||||
|
isIconFile,
|
||||||
|
joinFoundryAssetUrl,
|
||||||
|
readIconListingPage,
|
||||||
|
shapeIconListing
|
||||||
|
};
|
||||||
@@ -96,6 +96,10 @@ The campaign's Item list is synchronized with the world's gear, both ways:
|
|||||||
properties, description). An item made by hand in Dragonroll is created in the world's item
|
properties, description). An item made by hand in Dragonroll is created in the world's item
|
||||||
directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry
|
directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry
|
||||||
document.
|
document.
|
||||||
|
- The folders grouping the world's item directory arrive in the campaign as its own item folders, tree
|
||||||
|
and nesting included, and the items are filed in them. A folder's **colour** goes the other way too:
|
||||||
|
what the GM colours in Foundry shows on the campaign's folder, and what the campaign colours lands on
|
||||||
|
the world's folder on the next reconcile (the world's document keeps its name and nesting either way).
|
||||||
- A full snapshot keeps Dragonroll edits on reconnect; live Foundry edits overwrite. Item removal is
|
- A full snapshot keeps Dragonroll edits on reconnect; live Foundry edits overwrite. Item removal is
|
||||||
pruned only by a full snapshot, so a live item push never deletes anything. Deleting a synced item in
|
pruned only by a full snapshot, so a live item push never deletes anything. Deleting a synced item in
|
||||||
Dragonroll removes its Foundry world copy on the next reconcile. Items that live only in an actor's
|
Dragonroll removes its Foundry world copy on the next reconcile. Items that live only in an actor's
|
||||||
@@ -110,14 +114,15 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon
|
|||||||
| `POST /api/foundry/sync/item-snapshot` | Live world item edits, upsert only |
|
| `POST /api/foundry/sync/item-snapshot` | Live world item edits, upsert only |
|
||||||
| `POST /api/foundry/sync/item-delete` | A world item was deleted |
|
| `POST /api/foundry/sync/item-delete` | A world item was deleted |
|
||||||
| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry |
|
| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry |
|
||||||
| `GET /api/foundry/sync/items` | Items to apply back in Foundry |
|
| `GET /api/foundry/sync/items` | Items, and the item folders with their Dragonroll colours, to apply back in Foundry |
|
||||||
| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status |
|
| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status |
|
||||||
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
|
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
|
||||||
| `POST /api/foundry/sync/delete` | An actor was deleted |
|
| `POST /api/foundry/sync/delete` | An actor was deleted |
|
||||||
|
|
||||||
Foundry documents keep the Dragonroll id in the `dragonroll-foundry.actorId` / `dragonroll-foundry.itemId`
|
Foundry documents keep the Dragonroll id in the `dragonroll-foundry.actorId` / `dragonroll-foundry.itemId`
|
||||||
flag, and world items are marked with `dragonroll-foundry.syncMutation` while Dragonroll writes them so
|
flag, and world items are marked with `dragonroll-foundry.syncMutation` while Dragonroll writes them so
|
||||||
the write is not echoed back.
|
the write is not echoed back. A folder colour is written with that folder held in the client's set of
|
||||||
|
folders being synced, for the same reason.
|
||||||
|
|
||||||
## 2. Run the bridge on the Foundry host
|
## 2. Run the bridge on the Foundry host
|
||||||
|
|
||||||
@@ -130,6 +135,9 @@ export DRAGONROLL_FOUNDRY_PUSH_TOKEN='replace-with-a-different-long-random-publi
|
|||||||
export DRAGONROLL_FOUNDRY_ALLOWED_ORIGINS='https://vtt.example.com'
|
export DRAGONROLL_FOUNDRY_ALLOWED_ORIGINS='https://vtt.example.com'
|
||||||
export DRAGONROLL_FOUNDRY_HOST='0.0.0.0'
|
export DRAGONROLL_FOUNDRY_HOST='0.0.0.0'
|
||||||
export DRAGONROLL_FOUNDRY_PORT='8787'
|
export DRAGONROLL_FOUNDRY_PORT='8787'
|
||||||
|
# Optional: the Foundry Data directory. With it the bridge can list the core
|
||||||
|
# `icons/` library Dragonroll's item icon browser shows.
|
||||||
|
export DRAGONROLL_FOUNDRY_DATA_PATH='/home/foundry/Foundry Data'
|
||||||
npm start --prefix foundry/bridge
|
npm start --prefix foundry/bridge
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -165,6 +173,7 @@ The backend exposes these JWT-protected routes when the optional snapshot bridge
|
|||||||
| `GET /api/foundry/actors/:id/items` | Items embedded in an actor |
|
| `GET /api/foundry/actors/:id/items` | Items embedded in an actor |
|
||||||
| `GET /api/foundry/items` | World-level items |
|
| `GET /api/foundry/items` | World-level items |
|
||||||
| `GET /api/foundry/items/:id` | One world-level item |
|
| `GET /api/foundry/items/:id` | One world-level item |
|
||||||
|
| `GET /api/foundry/icons?campaign=&dir=&offset=` | One folder of Foundry's core icon library |
|
||||||
|
|
||||||
The bridge exposes the matching routes under `/api/*`, plus `GET /health`. Data routes require
|
The bridge exposes the matching routes under `/api/*`, plus `GET /health`. Data routes require
|
||||||
`Authorization: Bearer <read-token>`. Responses contain `{ status: "ok", data, world, syncedAt,
|
`Authorization: Bearer <read-token>`. Responses contain `{ status: "ok", data, world, syncedAt,
|
||||||
@@ -172,6 +181,13 @@ ageSeconds, stale }`. The snapshot stays in memory; `stale` becomes true when th
|
|||||||
received a GM heartbeat for more than two minutes. The bridge returns `503 foundry.not-ready` until a
|
received a GM heartbeat for more than two minutes. The bridge returns `503 foundry.not-ready` until a
|
||||||
configured GM client has published its first snapshot.
|
configured GM client has published its first snapshot.
|
||||||
|
|
||||||
|
The icon library is the one route that reads the disk instead of the snapshot: with
|
||||||
|
`DRAGONROLL_FOUNDRY_DATA_PATH` set, `GET /api/icons?dir=icons/svg&offset=120&limit=120` answers one
|
||||||
|
folder at a time — `{ status: "ok", dir, directories, files, offset, next }` of paths relative to the
|
||||||
|
data directory — and never reads outside `icons/`. `next` is the offset of the next page of icons, or
|
||||||
|
null once the folder is listed, which is how the campaign's icon browser keeps a library of thousands
|
||||||
|
lazy to load. Without that variable the route answers `503 foundry.errors.icons-unavailable`.
|
||||||
|
|
||||||
World-level items come from Foundry's `game.items`; actor inventories come from each actor's embedded
|
World-level items come from Foundry's `game.items`; actor inventories come from each actor's embedded
|
||||||
items collection. The API returns plain document data snapshots. This is a read-only integration: it
|
items collection. The API returns plain document data snapshots. This is a read-only integration: it
|
||||||
does not create or update Foundry documents, and it does not persist the bridge cache across restarts.
|
does not create or update Foundry documents, and it does not persist the bridge cache across restarts.
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
const http = require("node:http");
|
const http = require("node:http");
|
||||||
|
const fs = require("node:fs");
|
||||||
|
const path = require("node:path");
|
||||||
const { timingSafeEqual } = require("node:crypto");
|
const { timingSafeEqual } = require("node:crypto");
|
||||||
|
|
||||||
const host = process.env.DRAGONROLL_FOUNDRY_HOST || "0.0.0.0";
|
const host = process.env.DRAGONROLL_FOUNDRY_HOST || "0.0.0.0";
|
||||||
@@ -12,6 +14,9 @@ const allowedOrigins = new Set(
|
|||||||
.filter(Boolean),
|
.filter(Boolean),
|
||||||
);
|
);
|
||||||
const maxBodySize = 50 * 1024 * 1024;
|
const maxBodySize = 50 * 1024 * 1024;
|
||||||
|
// The Foundry Data directory, for listing the core `icons/` library. Optional:
|
||||||
|
// without it the bridge simply cannot answer icon listing requests.
|
||||||
|
const dataPath = (process.env.DRAGONROLL_FOUNDRY_DATA_PATH || "").trim();
|
||||||
|
|
||||||
if (!readToken || !pushToken) {
|
if (!readToken || !pushToken) {
|
||||||
throw new Error("Set DRAGONROLL_FOUNDRY_READ_TOKEN and DRAGONROLL_FOUNDRY_PUSH_TOKEN before starting the bridge.");
|
throw new Error("Set DRAGONROLL_FOUNDRY_READ_TOKEN and DRAGONROLL_FOUNDRY_PUSH_TOKEN before starting the bridge.");
|
||||||
@@ -106,6 +111,80 @@ function decodePathSegment(segment) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Core icon library -----------------------------------------------------
|
||||||
|
// Foundry keeps the icons it ships in the `icons/` folder of its data directory:
|
||||||
|
// thousands of images over a folder tree of their own. The campaign's icon window
|
||||||
|
// browses that tree, so the bridge lists one folder per request and pages the
|
||||||
|
// icons inside it. It never reads outside `icons/`.
|
||||||
|
|
||||||
|
const iconRoot = "icons";
|
||||||
|
const iconExtensions = new Set([".svg", ".png", ".webp", ".jpg", ".jpeg", ".gif", ".avif"]);
|
||||||
|
const defaultIconPageSize = 120;
|
||||||
|
const maxIconPageSize = 500;
|
||||||
|
|
||||||
|
function normalizeIconDirectory(input) {
|
||||||
|
const raw = String(input ?? "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
||||||
|
if (!raw || raw === ".") return iconRoot;
|
||||||
|
|
||||||
|
const segments = raw.split("/").filter((segment) => segment && segment !== ".");
|
||||||
|
if (!segments.length || segments.includes("..") || segments[0] !== iconRoot) return null;
|
||||||
|
return segments.join("/");
|
||||||
|
}
|
||||||
|
|
||||||
|
function readIconDirectory(dir, offset, limit) {
|
||||||
|
const root = path.resolve(dataPath, iconRoot);
|
||||||
|
const target = path.resolve(dataPath, dir);
|
||||||
|
if (target !== root && !target.startsWith(root + path.sep)) return null;
|
||||||
|
|
||||||
|
const directories = [];
|
||||||
|
const files = [];
|
||||||
|
for (const entry of fs.readdirSync(target, { withFileTypes: true })) {
|
||||||
|
const entryPath = path.posix.join(dir, entry.name);
|
||||||
|
if (entry.isDirectory()) directories.push(entryPath);
|
||||||
|
else if (entry.isFile() && iconExtensions.has(path.extname(entry.name).toLowerCase())) files.push(entryPath);
|
||||||
|
}
|
||||||
|
directories.sort((a, b) => a.localeCompare(b));
|
||||||
|
files.sort((a, b) => a.localeCompare(b));
|
||||||
|
|
||||||
|
const page = files.slice(offset, offset + limit);
|
||||||
|
return {
|
||||||
|
// Subfolders always come back whole: the window needs every one of them to
|
||||||
|
// navigate, and there are never many. Paging covers the icons.
|
||||||
|
directories,
|
||||||
|
files: page,
|
||||||
|
offset,
|
||||||
|
next: offset + page.length < files.length ? offset + page.length : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendIconListing(request, response) {
|
||||||
|
if (!dataPath) return sendJson(response, 503, { status: "error", msg: "foundry.errors.icons-unavailable" });
|
||||||
|
|
||||||
|
const params = new URL(request.url, "http://localhost").searchParams;
|
||||||
|
const dir = normalizeIconDirectory(params.get("dir"));
|
||||||
|
if (!dir) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
|
||||||
|
|
||||||
|
const requestedLimit = Number(params.get("limit"));
|
||||||
|
const limit = Number.isFinite(requestedLimit)
|
||||||
|
? Math.min(maxIconPageSize, Math.max(1, Math.trunc(requestedLimit)))
|
||||||
|
: defaultIconPageSize;
|
||||||
|
const requestedOffset = Number(params.get("offset"));
|
||||||
|
const offset = Number.isFinite(requestedOffset) ? Math.max(0, Math.trunc(requestedOffset)) : 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const listing = readIconDirectory(dir, offset, limit);
|
||||||
|
if (!listing) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
|
||||||
|
sendJson(response, 200, { status: "ok", dir, ...listing });
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === "ENOENT" || error.code === "ENOTDIR") {
|
||||||
|
sendJson(response, 404, { status: "error", msg: "errors.notfound" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error(`Could not list the Foundry icon folder ${dir}.`, error);
|
||||||
|
sendJson(response, 500, { status: "error", msg: "foundry.errors.icons-unavailable" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const server = http.createServer(async (request, response) => {
|
const server = http.createServer(async (request, response) => {
|
||||||
if (!setCorsHeaders(request, response)) {
|
if (!setCorsHeaders(request, response)) {
|
||||||
sendJson(response, 403, { status: "error", msg: "foundry.origin-not-allowed" });
|
sendJson(response, 403, { status: "error", msg: "foundry.origin-not-allowed" });
|
||||||
@@ -188,6 +267,10 @@ const server = http.createServer(async (request, response) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The icon library is on disk, not in the world snapshot, so it answers whether
|
||||||
|
// or not a GM client has published one yet.
|
||||||
|
if (pathname === "/api/icons") return sendIconListing(request, response);
|
||||||
|
|
||||||
const current = currentSnapshot(response);
|
const current = currentSnapshot(response);
|
||||||
if (!current) return;
|
if (!current) return;
|
||||||
|
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ let itemSyncErrorLogged = false;
|
|||||||
let folderSyncTimeout;
|
let folderSyncTimeout;
|
||||||
let folderSyncRunning = false;
|
let folderSyncRunning = false;
|
||||||
const syncingItemIds = new Set();
|
const syncingItemIds = new Set();
|
||||||
|
const syncingFolderIds = new Set();
|
||||||
const queuedItemChanges = new Map();
|
const queuedItemChanges = new Map();
|
||||||
|
|
||||||
function getCollectionContents(collection, collectionName) {
|
function getCollectionContents(collection, collectionName) {
|
||||||
@@ -675,10 +676,23 @@ function isWorldItemFolder(folder, seen = new Set()) {
|
|||||||
return isWorldItemFolder(parent, seen);
|
return isWorldItemFolder(parent, seen);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A Foundry folder's colour, or null for one the GM left uncoloured. Null travels as null:
|
||||||
|
// it tells Dragonroll to take a colour off the folder it was given before, whereas a module
|
||||||
|
// that says nothing about colours at all leaves the campaign's own choice alone.
|
||||||
|
function itemFolderColor(folder) {
|
||||||
|
const color = typeof folder?.color === "string" ? folder.color.trim() : "";
|
||||||
|
return color || null;
|
||||||
|
}
|
||||||
|
|
||||||
function worldItemFolderSnapshots() {
|
function worldItemFolderSnapshots() {
|
||||||
return (game.folders?.contents || [])
|
return (game.folders?.contents || [])
|
||||||
.filter((folder) => isWorldItemFolder(folder))
|
.filter((folder) => isWorldItemFolder(folder))
|
||||||
.map((folder) => ({ id: folder.id, name: folder.name, parent: itemFolderParent(folder)?.id || null }));
|
.map((folder) => ({
|
||||||
|
id: folder.id,
|
||||||
|
name: folder.name,
|
||||||
|
parent: itemFolderParent(folder)?.id || null,
|
||||||
|
color: itemFolderColor(folder),
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// A world item travels with the folder it stands in, so Dragonroll can file it the
|
// A world item travels with the folder it stands in, so Dragonroll can file it the
|
||||||
@@ -706,6 +720,35 @@ function getWorldItemSnapshots() {
|
|||||||
return (game.items?.contents || []).map(serializeFoundryWorldItem).filter(Boolean);
|
return (game.items?.contents || []).map(serializeFoundryWorldItem).filter(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Folder colours ----------------------------------------------------------
|
||||||
|
// Colouring a folder is the one thing about the tree the campaign gets to do on its
|
||||||
|
// own: the world owns what the folders are called and how they nest, and Dragonroll
|
||||||
|
// owns the colour its user picks for one. So the colour travels back with the folder
|
||||||
|
// list the item reconcile reads, and lands on the world's folder — marked, like every
|
||||||
|
// Dragonroll write, so the world does not echo it straight back to the campaign.
|
||||||
|
|
||||||
|
async function withFolderSyncSuppressed(folder, callback) {
|
||||||
|
if (!folder?.id) return callback();
|
||||||
|
syncingFolderIds.add(folder.id);
|
||||||
|
try {
|
||||||
|
return await callback();
|
||||||
|
} finally {
|
||||||
|
syncingFolderIds.delete(folder.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyDragonrollFolderColors(entries) {
|
||||||
|
for (const entry of entries || []) {
|
||||||
|
const folder = entry?.foundryFolderId ? game.folders?.get(entry.foundryFolderId) : null;
|
||||||
|
// Only the world's item directories: a Dragonroll folder the world has no document
|
||||||
|
// for is the campaign's business alone, and making one there is not ours to do.
|
||||||
|
if (!folder || folder.documentName !== "Folder" || !isWorldItemFolder(folder)) continue;
|
||||||
|
const color = entry.color || null;
|
||||||
|
if (itemFolderColor(folder) === color) continue;
|
||||||
|
await withFolderSyncSuppressed(folder, () => folder.update({ color }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function dragonrollItemIdOf(item) {
|
function dragonrollItemIdOf(item) {
|
||||||
return item.getFlag?.(MODULE_ID, "itemId") || item.flags?.[MODULE_ID]?.itemId || "";
|
return item.getFlag?.(MODULE_ID, "itemId") || item.flags?.[MODULE_ID]?.itemId || "";
|
||||||
}
|
}
|
||||||
@@ -916,10 +959,13 @@ async function reconcileDragonrollItems() {
|
|||||||
if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return;
|
if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return;
|
||||||
itemSyncRunning = true;
|
itemSyncRunning = true;
|
||||||
try {
|
try {
|
||||||
|
const result = await getDragonroll("foundry/sync/items", token);
|
||||||
|
// The folder colours are applied first, and whatever system this world runs: a
|
||||||
|
// colour is the same on every one of them, while writing an item is what needs D&D 5e.
|
||||||
|
await applyDragonrollFolderColors(result.folders);
|
||||||
if (game.system.id !== "dnd5e") {
|
if (game.system.id !== "dnd5e") {
|
||||||
throw new Error("Item sync currently requires the D&D 5e Foundry system.");
|
throw new Error("Item sync currently requires the D&D 5e Foundry system.");
|
||||||
}
|
}
|
||||||
const result = await getDragonroll("foundry/sync/items", token);
|
|
||||||
const remoteItems = result.items || [];
|
const remoteItems = result.items || [];
|
||||||
const remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry]));
|
const remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry]));
|
||||||
const localByRemoteId = new Map(game.items.contents
|
const localByRemoteId = new Map(game.items.contents
|
||||||
@@ -1000,10 +1046,10 @@ function makeFoundryCharacterData(entry) {
|
|||||||
type: entry.type === "character" ? "character" : "npc",
|
type: entry.type === "character" ? "character" : "npc",
|
||||||
img: getDragonrollImageUrl(entry.image) || undefined,
|
img: getDragonrollImageUrl(entry.image) || undefined,
|
||||||
system: {
|
system: {
|
||||||
|
// `details.race` and `details.background` are left out on purpose: they reference
|
||||||
|
// embedded items and are linked once the actor stands with its items made.
|
||||||
details: {
|
details: {
|
||||||
race: entry.species || "",
|
|
||||||
level: Number(entry.level) || 1,
|
level: Number(entry.level) || 1,
|
||||||
background: entry.background || "",
|
|
||||||
biography: { value: entry.description || "" },
|
biography: { value: entry.description || "" },
|
||||||
cr: entry.challengeRating || "",
|
cr: entry.challengeRating || "",
|
||||||
},
|
},
|
||||||
@@ -1036,9 +1082,7 @@ function characterUpdateData(entry) {
|
|||||||
const updates = {
|
const updates = {
|
||||||
name: entry.name,
|
name: entry.name,
|
||||||
img: getDragonrollImageUrl(entry.image) || "icons/svg/mystery-man.svg",
|
img: getDragonrollImageUrl(entry.image) || "icons/svg/mystery-man.svg",
|
||||||
"system.details.race": entry.species || "",
|
|
||||||
"system.details.level": Number(entry.level) || 1,
|
"system.details.level": Number(entry.level) || 1,
|
||||||
"system.details.background": entry.background || "",
|
|
||||||
"system.details.biography.value": entry.description || "",
|
"system.details.biography.value": entry.description || "",
|
||||||
"system.details.cr": entry.challengeRating || "",
|
"system.details.cr": entry.challengeRating || "",
|
||||||
[`flags.${MODULE_ID}.traits`]: entry.traits || "",
|
[`flags.${MODULE_ID}.traits`]: entry.traits || "",
|
||||||
@@ -1052,6 +1096,40 @@ function characterUpdateData(entry) {
|
|||||||
return updates;
|
return updates;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `system.details.background` and `system.details.race` are LocalDocumentFields in
|
||||||
|
// D&D 5e: they hold the id of an item embedded in the actor, never its name. A name
|
||||||
|
// written into one is a reference that resolves to nothing, and adding that item in
|
||||||
|
// Foundry then fails, so each of these follows the actor's own item for it instead.
|
||||||
|
const EMBEDDED_DETAILS = [
|
||||||
|
// Dragonroll owns the background item it lists, so its reference follows it always and
|
||||||
|
// a background taken off in the campaign leaves no reference behind.
|
||||||
|
{ field: "background", path: "system.details.background", types: ["background"], clearWhenMissing: true },
|
||||||
|
// The species item belongs to the world: point at it when it carries the name, and
|
||||||
|
// leave the reference to the GM when it does not.
|
||||||
|
{ field: "species", path: "system.details.race", types: ["race", "species"] },
|
||||||
|
];
|
||||||
|
|
||||||
|
function localDocumentId(value) {
|
||||||
|
// The field resolves to the referenced document when it can and to the stored id
|
||||||
|
// when the document is gone (its `fallback` option).
|
||||||
|
if (typeof value === "string") return value;
|
||||||
|
return value?._id || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function embeddedDetailReferenceData(actor, entry) {
|
||||||
|
const updates = {};
|
||||||
|
for (const detail of EMBEDDED_DETAILS) {
|
||||||
|
const wanted = String(entry[detail.field] || "").trim();
|
||||||
|
const item = wanted
|
||||||
|
? actor.items?.contents?.find((candidate) => detail.types.includes(candidate.type) && candidate.name === wanted)
|
||||||
|
: null;
|
||||||
|
const reference = item?.id || "";
|
||||||
|
if (!reference && !detail.clearWhenMissing) continue;
|
||||||
|
if (localDocumentId(documentValue(actor, detail.path)) !== reference) updates[detail.path] = reference;
|
||||||
|
}
|
||||||
|
return updates;
|
||||||
|
}
|
||||||
|
|
||||||
async function reconcileEmbeddedItems(actor, entry) {
|
async function reconcileEmbeddedItems(actor, entry) {
|
||||||
const desired = [];
|
const desired = [];
|
||||||
if (entry.className) desired.push({ type: "class", name: entry.className, system: { levels: Number(entry.level) || 1 } });
|
if (entry.className) desired.push({ type: "class", name: entry.className, system: { levels: Number(entry.level) || 1 } });
|
||||||
@@ -1110,6 +1188,9 @@ async function applyDragonrollCharacter(actor, entry) {
|
|||||||
await withActorSyncSuppressed(actor, async () => {
|
await withActorSyncSuppressed(actor, async () => {
|
||||||
if (changed) await actor.update(updates);
|
if (changed) await actor.update(updates);
|
||||||
await reconcileEmbeddedItems(actor, entry);
|
await reconcileEmbeddedItems(actor, entry);
|
||||||
|
// The item references are written after the reconcile that makes the items they point at.
|
||||||
|
const references = embeddedDetailReferenceData(actor, entry);
|
||||||
|
if (Object.keys(references).length) await actor.update(references);
|
||||||
if (dragonrollActorId(actor) !== String(entry._id)
|
if (dragonrollActorId(actor) !== String(entry._id)
|
||||||
|| actor.getFlag?.(MODULE_ID, "actorType") !== entry.type) {
|
|| actor.getFlag?.(MODULE_ID, "actorType") !== entry.type) {
|
||||||
await actor.update({
|
await actor.update({
|
||||||
@@ -1137,7 +1218,12 @@ async function createFoundryCharacter(entry) {
|
|||||||
if (!actor) return;
|
if (!actor) return;
|
||||||
|
|
||||||
await withActorSyncSuppressed(actor, async () => {
|
await withActorSyncSuppressed(actor, async () => {
|
||||||
await actor.update({ [`flags.${MODULE_ID}.syncMutation`]: false });
|
await actor.update({
|
||||||
|
// The actor was made with its items, so its background and species references
|
||||||
|
// can point at them right away.
|
||||||
|
...embeddedDetailReferenceData(actor, entry),
|
||||||
|
[`flags.${MODULE_ID}.syncMutation`]: false,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
await mapDragonrollActor(entry._id, actor.id);
|
await mapDragonrollActor(entry._id, actor.id);
|
||||||
}
|
}
|
||||||
@@ -1307,7 +1393,9 @@ Hooks.once("ready", () => {
|
|||||||
}
|
}
|
||||||
// An item folder the GM made, renamed or nested changes the tree the campaign
|
// 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.
|
// mirrors; nothing about the items themselves changed, so only the tree goes.
|
||||||
|
// A colour Dragonroll has just written into the folder is not the GM changing it.
|
||||||
if (document.documentName === "Folder") {
|
if (document.documentName === "Folder") {
|
||||||
|
if (syncingFolderIds.has(document.id)) return;
|
||||||
if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders();
|
if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ import { useI18n } from 'vue-i18n';
|
|||||||
import { useCampaignService } from '~/services/Campaign.js';
|
import { useCampaignService } from '~/services/Campaign.js';
|
||||||
import { AnchorMap, AnchoredMap, ClearAnchoredMap, SetActivePane } from '~/services/Content.js';
|
import { AnchorMap, AnchoredMap, ClearAnchoredMap, SetActivePane } from '~/services/Content.js';
|
||||||
import { emitter } from '~/services/Emitter';
|
import { emitter } from '~/services/Emitter';
|
||||||
|
import { BuildColorMenu } from '~/services/EntryColors';
|
||||||
import { BuildItemRows } from '~/services/ItemFolders';
|
import { BuildItemRows } from '~/services/ItemFolders';
|
||||||
import Server from '~/services/Server';
|
import Server, { getBaseUrl } from '~/services/Server';
|
||||||
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
|
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
|
||||||
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
|
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
|
||||||
import { ACTOR_DRAG_TYPE } from '~/services/MapTokens';
|
import { ACTOR_DRAG_TYPE } from '~/services/MapTokens';
|
||||||
|
import EntryFolderRow from './EntryFolderRow.vue';
|
||||||
import NestedNoteList from './NestedNoteList.vue';
|
import NestedNoteList from './NestedNoteList.vue';
|
||||||
|
|
||||||
const { Campaign } = useCampaignService();
|
const { Campaign } = useCampaignService();
|
||||||
@@ -18,12 +20,13 @@ const notes = ref([]);
|
|||||||
const folders = ref([]);
|
const folders = ref([]);
|
||||||
const actors = ref([]);
|
const actors = ref([]);
|
||||||
const items = 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 maps = ref([]);
|
||||||
const entryLists = { actor: actors, item: items, map: maps };
|
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 loadingNotes = ref(false);
|
||||||
const loadingEntries = ref(false);
|
const loadingEntries = ref(false);
|
||||||
const notesError = ref('');
|
const notesError = ref('');
|
||||||
@@ -111,12 +114,27 @@ function handleNoteDeleted(noteKey) {
|
|||||||
notes.value = notes.value.filter(n => n.key !== 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();
|
fetchCampaignNotes();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fetchCampaignEntries(section, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFolderDeleted(folderId) {
|
function handleFolderDeleted(folderId) {
|
||||||
expandedFolderIds.value = expandedFolderIds.value.filter((id) => id !== folderId);
|
expandedFolderIds.value = expandedFolderIds.value.filter((id) => id !== folderId);
|
||||||
|
collapsedFolderIds.value = collapsedFolderIds.value.filter((id) => id !== folderId);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleCampaignEntryCreated({ entityType, entry }) {
|
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]));
|
const previousById = new Map(list.value.map((entry) => [entry._id, entry]));
|
||||||
list.value = response.data[entityType] ?? [];
|
list.value = response.data[entityType] ?? [];
|
||||||
// Items come with the folder tree their world synced over, so the list can
|
// Every entry list comes with the folders its rows stand in, so the sidebar can
|
||||||
// group them the way the Foundry item directory does.
|
// group them the way the note tree does (and the way the Foundry item directory
|
||||||
if (kind === 'item') itemFolders.value = response.data.folders ?? [];
|
// arrives for items).
|
||||||
|
entryFolders[kind].value = response.data.folders ?? [];
|
||||||
// Tell open windows about Foundry changes landing behind them.
|
// Tell open windows about Foundry changes landing behind them.
|
||||||
for (const entry of list.value) {
|
for (const entry of list.value) {
|
||||||
const previous = previousById.get(entry._id);
|
const previous = previousById.get(entry._id);
|
||||||
@@ -243,6 +262,14 @@ function createEntry(entityType) {
|
|||||||
CreateWindow('create_campaign_entry', { entityType, campaign: campaignId.value });
|
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) {
|
function entrySummary(actor) {
|
||||||
const bits = [t(`campaigns.actor.types.${actor.type}`)];
|
const bits = [t(`campaigns.actor.types.${actor.type}`)];
|
||||||
if (actor.species) bits.push(actor.species);
|
if (actor.species) bits.push(actor.species);
|
||||||
@@ -256,6 +283,13 @@ function itemSummary(item) {
|
|||||||
return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`;
|
return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// An item's icon in the sidebar: an uploaded filename served from /api/public, or a full URL
|
||||||
|
// (Foundry sends its own icon as one) — the same rule the item window uses.
|
||||||
|
function itemImageUrl(image) {
|
||||||
|
if (!image) return '';
|
||||||
|
return /^(https?:|data:|\/\/)/i.test(image) ? image : `${getBaseUrl()}/public/${image}`;
|
||||||
|
}
|
||||||
|
|
||||||
function mapSummary(map) {
|
function mapSummary(map) {
|
||||||
return t('campaigns.map.summary', { size: map.gridSize, scale: map.scale });
|
return t('campaigns.map.summary', { size: map.gridSize, scale: map.scale });
|
||||||
}
|
}
|
||||||
@@ -289,6 +323,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({
|
menuItems.push({
|
||||||
name: t('campaigns.actions.delete'),
|
name: t('campaigns.actions.delete'),
|
||||||
icon: '/icons/iconoir/regular/trash.svg',
|
icon: '/icons/iconoir/regular/trash.svg',
|
||||||
@@ -305,6 +347,74 @@ function showEntryMenu(entry, entityType) {
|
|||||||
ShowContextMenu(menuItems);
|
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) {
|
async function openCharacterSheet(actor) {
|
||||||
const existingWindowId = GetFirstWindowId('character_sheet');
|
const existingWindowId = GetFirstWindowId('character_sheet');
|
||||||
if (existingWindowId !== undefined) {
|
if (existingWindowId !== undefined) {
|
||||||
@@ -343,38 +453,41 @@ function createNote() {
|
|||||||
CreateWindow('new_note', { campaign: campaignId.value });
|
CreateWindow('new_note', { campaign: campaignId.value });
|
||||||
}
|
}
|
||||||
|
|
||||||
function createFolder() {
|
|
||||||
CreateWindow('new_folder', { campaign: campaignId.value });
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleSidebar() {
|
function toggleSidebar() {
|
||||||
sidebarCollapsed.value = !sidebarCollapsed.value;
|
sidebarCollapsed.value = !sidebarCollapsed.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
const rootNotes = computed(() => notes.value.filter(n => !n._folder));
|
const rootNotes = computed(() => notes.value.filter(n => !n._folder));
|
||||||
|
|
||||||
// The items of the campaign, each under the folder it stands in (see
|
// The rows of each entry list: every folder followed by what stands in it, deeper and
|
||||||
// services/ItemFolders.js). Without any folder this is the plain item list.
|
// deeper, the way the item list has done since its folders arrived from the linked world
|
||||||
const itemRows = computed(() => BuildItemRows(items.value, itemFolders.value, collapsedItemFolderIds.value));
|
// (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.
|
// Rows one step deeper per folder level; the sidebar list's own padding is the base.
|
||||||
function rowIndent(depth) {
|
function rowIndent(depth) {
|
||||||
return { paddingLeft: `${10 + depth * 14}px` };
|
return { paddingLeft: `${10 + depth * 14}px` };
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleItemFolder(folderId) {
|
function toggleFolder(folderId) {
|
||||||
collapsedItemFolderIds.value = collapsedItemFolderIds.value.includes(folderId)
|
collapsedFolderIds.value = collapsedFolderIds.value.includes(folderId)
|
||||||
? collapsedItemFolderIds.value.filter((id) => id !== folderId)
|
? collapsedFolderIds.value.filter((id) => id !== folderId)
|
||||||
: [...collapsedItemFolderIds.value, folderId];
|
: [...collapsedFolderIds.value, folderId];
|
||||||
}
|
}
|
||||||
|
|
||||||
watch(campaignId, (newVal) => {
|
watch(campaignId, (newVal) => {
|
||||||
if (newVal) {
|
if (newVal) {
|
||||||
actors.value = [];
|
actors.value = [];
|
||||||
items.value = [];
|
items.value = [];
|
||||||
itemFolders.value = [];
|
|
||||||
collapsedItemFolderIds.value = [];
|
|
||||||
maps.value = [];
|
maps.value = [];
|
||||||
|
for (const sectionFolders of Object.values(entryFolders)) sectionFolders.value = [];
|
||||||
|
collapsedFolderIds.value = [];
|
||||||
ClearAnchoredMap();
|
ClearAnchoredMap();
|
||||||
fetchCampaignNotes();
|
fetchCampaignNotes();
|
||||||
if (isEntrySection(activeSection.value)) fetchCampaignEntries(activeSection.value);
|
if (isEntrySection(activeSection.value)) fetchCampaignEntries(activeSection.value);
|
||||||
@@ -383,9 +496,9 @@ watch(campaignId, (newVal) => {
|
|||||||
folders.value = [];
|
folders.value = [];
|
||||||
actors.value = [];
|
actors.value = [];
|
||||||
items.value = [];
|
items.value = [];
|
||||||
itemFolders.value = [];
|
|
||||||
collapsedItemFolderIds.value = [];
|
|
||||||
maps.value = [];
|
maps.value = [];
|
||||||
|
for (const sectionFolders of Object.values(entryFolders)) sectionFolders.value = [];
|
||||||
|
collapsedFolderIds.value = [];
|
||||||
notesError.value = '';
|
notesError.value = '';
|
||||||
entriesError.value = '';
|
entriesError.value = '';
|
||||||
ClearAnchoredMap();
|
ClearAnchoredMap();
|
||||||
@@ -496,7 +609,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')">
|
<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">
|
<img class="sidebar-action-icon" src="/icons/iconoir/regular/plus.svg" alt="" aria-hidden="true">
|
||||||
</button>
|
</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">
|
<img class="sidebar-action-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
|
||||||
</button>
|
</button>
|
||||||
<button class="sidebar-action" type="button" @click="fetchCampaignNotes" :disabled="!Campaign || loadingNotes" :title="t('campaigns.actions.refresh')" :aria-label="t('campaigns.actions.refresh')">
|
<button class="sidebar-action" type="button" @click="fetchCampaignNotes" :disabled="!Campaign || loadingNotes" :title="t('campaigns.actions.refresh')" :aria-label="t('campaigns.actions.refresh')">
|
||||||
@@ -507,6 +620,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() })">
|
<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">
|
<img class="sidebar-action-icon" src="/icons/iconoir/regular/plus.svg" alt="" aria-hidden="true">
|
||||||
</button>
|
</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')">
|
<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">
|
<img class="sidebar-action-icon" src="/icons/iconoir/regular/refresh.svg" alt="" aria-hidden="true">
|
||||||
</button>
|
</button>
|
||||||
@@ -528,40 +644,44 @@ onBeforeUnmount(() => {
|
|||||||
<template v-else-if="activeSection === 'actors'">
|
<template v-else-if="activeSection === 'actors'">
|
||||||
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
|
<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="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-else-if="actors.length === 0 && entryFolders.actor.value.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')">
|
<template v-for="row in entryRows.actor.value" :key="row.key">
|
||||||
<span class="entity-entry-name">{{ actor.name }}</span>
|
<EntryFolderRow
|
||||||
<span class="entity-entry-meta">{{ entrySummary(actor) }}</span>
|
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>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
</template>
|
||||||
|
|
||||||
<template v-else-if="activeSection === 'items'">
|
<template v-else-if="activeSection === 'items'">
|
||||||
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
|
<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="entriesError" class="sidebar-state error">{{ entriesError }}</div>
|
||||||
<div v-else-if="items.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div>
|
<div v-else-if="items.length === 0 && entryFolders.item.value.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div>
|
||||||
<template v-for="row in itemRows" :key="row.key">
|
<template v-for="row in entryRows.item.value" :key="row.key">
|
||||||
<button
|
<EntryFolderRow
|
||||||
v-if="row.kind === 'folder'"
|
v-if="row.kind === 'folder'"
|
||||||
class="item-folder-entry"
|
:folder="row.folder"
|
||||||
type="button"
|
:collapsed="collapsedFolderIds.includes(row.folder._id)"
|
||||||
:style="rowIndent(row.depth)"
|
:indent="rowIndent(row.depth)"
|
||||||
:aria-expanded="(!collapsedItemFolderIds.includes(row.folder._id)).toString()"
|
:menu="folderMenuItems(row.folder)"
|
||||||
:aria-label="t('campaigns.item.folder-toggle', { name: row.folder.name })"
|
:toggle-label="t('campaigns.folders.toggle', { name: row.folder.name })"
|
||||||
@click="toggleItemFolder(row.folder._id)"
|
@toggle="toggleFolder(row.folder._id)"
|
||||||
>
|
/>
|
||||||
<img
|
|
||||||
class="item-folder-arrow"
|
|
||||||
:src="collapsedItemFolderIds.includes(row.folder._id) ? '/icons/iconoir/regular/nav-arrow-right.svg' : '/icons/iconoir/regular/nav-arrow-down.svg'"
|
|
||||||
alt=""
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<img class="item-folder-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
|
|
||||||
<span class="item-folder-name">{{ row.folder.name }}</span>
|
|
||||||
</button>
|
|
||||||
<div v-else class="entity-entry" :style="rowIndent(row.depth)" role="button" tabindex="0" @click="openItemSheet(row.item)" @keydown.enter="openItemSheet(row.item)" @keydown.space.prevent="openItemSheet(row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'item')">
|
<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-title">
|
||||||
|
<span v-if="row.item.image" class="entity-entry-image" aria-hidden="true">
|
||||||
|
<img :src="itemImageUrl(row.item.image)" alt="">
|
||||||
|
</span>
|
||||||
<span class="entity-entry-name">{{ row.item.name }}</span>
|
<span class="entity-entry-name">{{ row.item.name }}</span>
|
||||||
<span v-if="row.item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span>
|
|
||||||
</span>
|
</span>
|
||||||
<span class="entity-entry-meta">{{ itemSummary(row.item) }}</span>
|
<span class="entity-entry-meta">{{ itemSummary(row.item) }}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -571,16 +691,27 @@ onBeforeUnmount(() => {
|
|||||||
<template v-else>
|
<template v-else>
|
||||||
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
|
<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="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-else-if="maps.length === 0 && entryFolders.map.value.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')">
|
<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-row">
|
||||||
<span class="entity-entry-name">{{ map.name }}</span>
|
<span class="entity-entry-name">{{ row.item.name }}</span>
|
||||||
<span v-if="isAnchoredMap(map)" class="entity-entry-sync">{{ t('campaigns.map.anchored') }}</span>
|
<span v-if="isAnchoredMap(row.item)" class="entity-entry-sync">{{ t('campaigns.map.anchored') }}</span>
|
||||||
</span>
|
</span>
|
||||||
<span class="entity-entry-meta">{{ mapSummary(map) }}</span>
|
<span class="entity-entry-meta">{{ mapSummary(row.item) }}</span>
|
||||||
<span v-if="!map.image" class="entity-entry-description">{{ t('campaigns.map.no-image') }}</span>
|
<span v-if="!row.item.image" class="entity-entry-description">{{ t('campaigns.map.no-image') }}</span>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
@@ -731,18 +862,6 @@ onBeforeUnmount(() => {
|
|||||||
}
|
}
|
||||||
.entity-entry:hover { border-color: var(--color-border); background: var(--color-background-soft); }
|
.entity-entry:hover { border-color: var(--color-border); background: var(--color-background-soft); }
|
||||||
.entity-entry:focus-visible { outline: 1px solid var(--color-link); }
|
.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. */
|
/* The map currently anchored on the note container. */
|
||||||
.entity-entry.anchored { border-color: var(--color-link); background: var(--color-background-soft); }
|
.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; }
|
.entity-entry-name-row { display: flex; align-items: baseline; gap: 6px; min-width: 0; }
|
||||||
@@ -755,6 +874,15 @@ onBeforeUnmount(() => {
|
|||||||
}
|
}
|
||||||
.entity-entry-meta, .entity-entry-description { font-size: 12px; opacity: 0.72; }
|
.entity-entry-meta, .entity-entry-description { font-size: 12px; opacity: 0.72; }
|
||||||
.entity-entry-description { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
|
.entity-entry-description { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
|
||||||
|
/* An item row leads with the item's own icon on the left of its name, standing in for the
|
||||||
|
"SYNCED" text it used to show (Syndria98/dragonroll#53). */
|
||||||
|
.entity-entry-title { display: flex; align-items: center; gap: 9px; min-width: 0; }
|
||||||
|
.entity-entry-image {
|
||||||
|
flex: 0 0 30px; width: 30px; height: 30px; box-sizing: border-box;
|
||||||
|
display: grid; place-items: center; overflow: hidden;
|
||||||
|
border: 1px solid var(--color-border); border-radius: 6px; background: var(--color-background-soft);
|
||||||
|
}
|
||||||
|
.entity-entry-image img { width: 100%; height: 100%; object-fit: contain; }
|
||||||
|
|
||||||
@media (max-width: 900px) {
|
@media (max-width: 900px) {
|
||||||
.notes-sidebar {
|
.notes-sidebar {
|
||||||
|
|||||||
57
frontend/app/components/partials/EntryFolderRow.vue
Normal file
57
frontend/app/components/partials/EntryFolderRow.vue
Normal 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>
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onBeforeUnmount, onMounted, watch } from 'vue';
|
import { ref, onBeforeUnmount, onMounted, watch } from 'vue';
|
||||||
import { emitter } from '~/services/Emitter';
|
import { emitter } from '~/services/Emitter';
|
||||||
|
import { BuildColorMenu } from '~/services/EntryColors';
|
||||||
import Server from '~/services/Server';
|
import Server from '~/services/Server';
|
||||||
import { CreateWindow } from '~/services/Windows';
|
import { CreateWindow } from '~/services/Windows';
|
||||||
import { ShowContextMenu, HideContextMenu } from '~/services/ContextMenu';
|
import { ShowContextMenu, HideContextMenu } from '~/services/ContextMenu';
|
||||||
@@ -20,18 +21,6 @@ const emit = defineEmits(['open-note', 'reload-notes']);
|
|||||||
const loadingFolders = new Set();
|
const loadingFolders = new Set();
|
||||||
const dragHoveredFolderId = ref(null);
|
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
|
// Cache of loaded folder contents — persists across reloads until cleared
|
||||||
// Each entry: { [folderId]: { notes: [], subfolders: [] } }
|
// Each entry: { [folderId]: { notes: [], subfolders: [] } }
|
||||||
const folderContentCache = ref({});
|
const folderContentCache = ref({});
|
||||||
@@ -216,13 +205,7 @@ function buildFolderContextMenu(folder) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildColorMenu(kind, item) {
|
function buildColorMenu(kind, item) {
|
||||||
const colorItems = entryColors.map((color) => ({
|
return BuildColorMenu((color) => setEntryColor(kind, item, 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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setEntryColor(kind, item, color) {
|
async function setEntryColor(kind, item, color) {
|
||||||
|
|||||||
@@ -24,6 +24,16 @@ const abilityStats = [
|
|||||||
{ key: 'int', label: 'INT' }, { key: 'wis', label: 'WIS' }, { key: 'cha', label: 'CHA' }
|
{ key: 'int', label: 'INT' }, { key: 'wis', label: 'WIS' }, { key: 'cha', label: 'CHA' }
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Les pestanyes del lateral dret reparteixen la fitxa: característiques i combat,
|
||||||
|
// inventari, trets i conjurs. Són pestanyes de marcadors, no una pàgina nova.
|
||||||
|
const tabs = [
|
||||||
|
{ key: 'abilities', label: 'campaigns.character-sheet.tabs.abilities' },
|
||||||
|
{ key: 'inventory', label: 'campaigns.character-sheet.tabs.inventory' },
|
||||||
|
{ key: 'traits', label: 'campaigns.character-sheet.tabs.traits' },
|
||||||
|
{ key: 'spells', label: 'campaigns.character-sheet.tabs.spells' }
|
||||||
|
];
|
||||||
|
const activeTab = ref('abilities');
|
||||||
|
|
||||||
function normalizeActor(actor) {
|
function normalizeActor(actor) {
|
||||||
return {
|
return {
|
||||||
name: actor?.name ?? '',
|
name: actor?.name ?? '',
|
||||||
@@ -207,7 +217,9 @@ async function saveSheet() {
|
|||||||
|
|
||||||
<div v-if="error" class="sheet-error">{{ error }}</div>
|
<div v-if="error" class="sheet-error">{{ error }}</div>
|
||||||
|
|
||||||
<main class="sheet-grid">
|
<div class="sheet-layout">
|
||||||
|
<div class="sheet-content">
|
||||||
|
<main v-show="activeTab === 'abilities'" class="sheet-grid">
|
||||||
<div v-if="form.image || editing" class="sheet-portrait" :class="{ empty: !form.image }">
|
<div v-if="form.image || editing" class="sheet-portrait" :class="{ empty: !form.image }">
|
||||||
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.character-sheet.photo')">
|
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.character-sheet.photo')">
|
||||||
<button v-if="editing && !form.image" class="portrait-upload" type="button" :disabled="uploadingPhoto" @click="pickPhoto">
|
<button v-if="editing && !form.image" class="portrait-upload" type="button" :disabled="uploadingPhoto" @click="pickPhoto">
|
||||||
@@ -256,19 +268,9 @@ async function saveSheet() {
|
|||||||
<textarea v-if="editing" v-model="form.proficiencies" rows="5" :placeholder="$t('campaigns.character-sheet.proficiencies-placeholder')" />
|
<textarea v-if="editing" v-model="form.proficiencies" rows="5" :placeholder="$t('campaigns.character-sheet.proficiencies-placeholder')" />
|
||||||
<p v-else class="sheet-copy">{{ form.proficiencies || $t('campaigns.character-sheet.empty-proficiencies') }}</p>
|
<p v-else class="sheet-copy">{{ form.proficiencies || $t('campaigns.character-sheet.empty-proficiencies') }}</p>
|
||||||
</section>
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
<section class="sheet-panel traits-panel">
|
<main v-show="activeTab === 'inventory'" class="sheet-tab-body">
|
||||||
<h2>{{ $t('campaigns.character-sheet.traits') }}</h2>
|
|
||||||
<textarea v-if="editing" v-model="form.traits" rows="5" :placeholder="$t('campaigns.character-sheet.traits-placeholder')" />
|
|
||||||
<p v-else class="sheet-copy">{{ form.traits || $t('campaigns.character-sheet.empty-traits') }}</p>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="sheet-panel spells-panel">
|
|
||||||
<h2>{{ $t('campaigns.character-sheet.spells') }}</h2>
|
|
||||||
<textarea v-if="editing" v-model="form.spells" rows="5" :placeholder="$t('campaigns.character-sheet.spells-placeholder')" />
|
|
||||||
<p v-else class="sheet-copy">{{ form.spells || $t('campaigns.character-sheet.empty-spells') }}</p>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="sheet-panel inventory-panel">
|
<section class="sheet-panel inventory-panel">
|
||||||
<div class="panel-title-row">
|
<div class="panel-title-row">
|
||||||
<h2>{{ $t('campaigns.character-sheet.inventory') }}</h2>
|
<h2>{{ $t('campaigns.character-sheet.inventory') }}</h2>
|
||||||
@@ -302,6 +304,37 @@ async function saveSheet() {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<main v-show="activeTab === 'traits'" class="sheet-tab-body">
|
||||||
|
<section class="sheet-panel traits-panel">
|
||||||
|
<h2>{{ $t('campaigns.character-sheet.traits') }}</h2>
|
||||||
|
<textarea v-if="editing" v-model="form.traits" rows="12" :placeholder="$t('campaigns.character-sheet.traits-placeholder')" />
|
||||||
|
<p v-else class="sheet-copy">{{ form.traits || $t('campaigns.character-sheet.empty-traits') }}</p>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<main v-show="activeTab === 'spells'" class="sheet-tab-body">
|
||||||
|
<section class="sheet-panel spells-panel">
|
||||||
|
<h2>{{ $t('campaigns.character-sheet.spells') }}</h2>
|
||||||
|
<textarea v-if="editing" v-model="form.spells" rows="12" :placeholder="$t('campaigns.character-sheet.spells-placeholder')" />
|
||||||
|
<p v-else class="sheet-copy">{{ form.spells || $t('campaigns.character-sheet.empty-spells') }}</p>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav class="sheet-tabs" role="tablist" aria-orientation="vertical">
|
||||||
|
<button
|
||||||
|
v-for="tab in tabs"
|
||||||
|
:key="tab.key"
|
||||||
|
class="sheet-tab"
|
||||||
|
:class="{ active: activeTab === tab.key }"
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
:aria-selected="activeTab === tab.key"
|
||||||
|
@click="activeTab = tab.key"
|
||||||
|
>{{ $t(tab.label) }}</button>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -325,7 +358,27 @@ async function saveSheet() {
|
|||||||
.sheet-button.primary { background: var(--color-link); color: var(--color-background); border-color: var(--color-link); }
|
.sheet-button.primary { background: var(--color-link); color: var(--color-background); border-color: var(--color-link); }
|
||||||
.sheet-button:disabled { opacity: .55; cursor: wait; }
|
.sheet-button:disabled { opacity: .55; cursor: wait; }
|
||||||
.sheet-button.compact { padding: 5px 9px; font-size: 12px; }
|
.sheet-button.compact { padding: 5px 9px; font-size: 12px; }
|
||||||
.sheet-grid { display: grid; grid-template-columns: minmax(200px, 34%) minmax(0, 1fr) minmax(0, 1fr); grid-template-rows: auto auto auto auto; gap: 11px; align-items: start; }
|
.sheet-grid { display: grid; grid-template-columns: minmax(200px, 34%) minmax(0, 1fr) minmax(0, 1fr); grid-template-rows: auto auto; gap: 11px; align-items: start; }
|
||||||
|
.sheet-layout { display: flex; align-items: flex-start; gap: 10px; }
|
||||||
|
.sheet-content { flex: 1 1 auto; min-width: 0; }
|
||||||
|
.sheet-tab-body { display: block; }
|
||||||
|
.sheet-tabs { flex: 0 0 auto; display: flex; flex-direction: column; gap: 6px; position: sticky; top: 0; align-self: flex-start; }
|
||||||
|
.sheet-tab {
|
||||||
|
text-align: left;
|
||||||
|
padding: 9px 14px 9px 11px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-left-width: 3px;
|
||||||
|
border-radius: 0 9px 9px 0;
|
||||||
|
background: var(--color-background-soft);
|
||||||
|
color: var(--color-text);
|
||||||
|
font: 13px MrEavesRemake;
|
||||||
|
letter-spacing: .02em;
|
||||||
|
white-space: nowrap;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background .15s ease, border-color .15s ease, color .15s ease;
|
||||||
|
}
|
||||||
|
.sheet-tab:hover { background: var(--color-button-hover); }
|
||||||
|
.sheet-tab.active { background: var(--color-background-light); color: var(--color-link); border-left-color: var(--color-link); box-shadow: 0 3px 12px var(--color-window-shadow); }
|
||||||
.sheet-panel { min-width: 0; padding: 13px; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-light); box-shadow: 0 3px 12px var(--color-window-shadow); }
|
.sheet-panel { min-width: 0; padding: 13px; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-light); box-shadow: 0 3px 12px var(--color-window-shadow); }
|
||||||
.sheet-panel h2 { margin: 0 0 12px; padding-bottom: 7px; border-bottom: 1px solid var(--color-border); font: 17px MrEavesRemake; letter-spacing: .03em; }
|
.sheet-panel h2 { margin: 0 0 12px; padding-bottom: 7px; border-bottom: 1px solid var(--color-border); font: 17px MrEavesRemake; letter-spacing: .03em; }
|
||||||
.sheet-panel h3 { margin: 13px 0 7px; font: 14px MrEavesRemake; }
|
.sheet-panel h3 { margin: 13px 0 7px; font: 14px MrEavesRemake; }
|
||||||
@@ -340,9 +393,7 @@ async function saveSheet() {
|
|||||||
.portrait-controls button:disabled { opacity: .55; cursor: wait; }
|
.portrait-controls button:disabled { opacity: .55; cursor: wait; }
|
||||||
.photo-input { display: none; }
|
.photo-input { display: none; }
|
||||||
.abilities-panel { grid-column: 2 / -1; grid-row: 1; }
|
.abilities-panel { grid-column: 2 / -1; grid-row: 1; }
|
||||||
.combat-panel { grid-column: 2; grid-row: 2; }
|
.combat-panel { grid-column: 2 / -1; grid-row: 2; }
|
||||||
.traits-panel { grid-column: 3; grid-row: 2; }
|
|
||||||
.spells-panel { grid-column: 2 / -1; grid-row: 3; }
|
|
||||||
.ability-grid { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 7px; }
|
.ability-grid { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 7px; }
|
||||||
.ability-card { min-height: 83px; padding: 8px 5px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); }
|
.ability-card { min-height: 83px; padding: 8px 5px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); }
|
||||||
.ability-label { font-size: 11px; font-weight: 700; letter-spacing: .08em; opacity: .75; }
|
.ability-label { font-size: 11px; font-weight: 700; letter-spacing: .08em; opacity: .75; }
|
||||||
@@ -369,7 +420,6 @@ textarea { resize: vertical; width: 100%; min-height: 88px; font-size: 12px; }
|
|||||||
.weight-summary strong { white-space: nowrap; }
|
.weight-summary strong { white-space: nowrap; }
|
||||||
.weight-track { height: 5px; margin-bottom: 10px; overflow: hidden; border-radius: 999px; background: var(--color-background-soft); }
|
.weight-track { height: 5px; margin-bottom: 10px; overflow: hidden; border-radius: 999px; background: var(--color-background-soft); }
|
||||||
.weight-fill { height: 100%; border-radius: inherit; background: var(--color-link); transition: width .2s ease; }
|
.weight-fill { height: 100%; border-radius: inherit; background: var(--color-link); transition: width .2s ease; }
|
||||||
.inventory-panel { grid-column: 2 / -1; grid-row: 4; }
|
|
||||||
.inventory-table-wrap { overflow-x: auto; }
|
.inventory-table-wrap { overflow-x: auto; }
|
||||||
.inventory-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
.inventory-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
||||||
.inventory-table th { padding: 6px 7px; text-align: left; font-weight: 600; opacity: .7; }
|
.inventory-table th { padding: 6px 7px; text-align: left; font-weight: 600; opacity: .7; }
|
||||||
@@ -383,17 +433,17 @@ textarea { resize: vertical; width: 100%; min-height: 88px; font-size: 12px; }
|
|||||||
.sheet-error { padding: 7px 10px; margin-bottom: 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
|
.sheet-error { padding: 7px 10px; margin-bottom: 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
|
||||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||||
@media (max-width: 760px) {
|
@media (max-width: 760px) {
|
||||||
.sheet-grid { grid-template-columns: 1fr 1fr; grid-template-rows: none; }
|
.sheet-grid { grid-template-columns: 1fr; grid-template-rows: none; }
|
||||||
.sheet-portrait { grid-column: 1 / -1; grid-row: auto; }
|
.sheet-portrait, .abilities-panel, .combat-panel { grid-column: 1 / -1; grid-row: auto; }
|
||||||
.abilities-panel { grid-column: 1 / -1; grid-row: auto; }
|
|
||||||
.combat-panel, .traits-panel { grid-column: auto; grid-row: auto; }
|
|
||||||
.spells-panel, .inventory-panel { grid-column: 1 / -1; grid-row: auto; }
|
|
||||||
}
|
}
|
||||||
@media (max-width: 520px) {
|
@media (max-width: 520px) {
|
||||||
.sheet-body { padding: 10px; }
|
.sheet-body { padding: 10px; }
|
||||||
.sheet-hero { align-items: flex-start; flex-wrap: wrap; }
|
.sheet-hero { align-items: flex-start; flex-wrap: wrap; }
|
||||||
.sheet-actions { margin-left: auto; }
|
.sheet-actions { margin-left: auto; }
|
||||||
.sheet-grid { grid-template-columns: 1fr; }
|
|
||||||
.ability-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
.ability-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||||
|
.sheet-layout { flex-direction: column; }
|
||||||
|
.sheet-tabs { flex-direction: row; flex-wrap: wrap; order: -1; }
|
||||||
|
.sheet-tab { flex: 1 1 auto; text-align: center; border-radius: 7px; border-left-width: 1px; border-top-width: 3px; }
|
||||||
|
.sheet-tab.active { border-left-color: var(--color-border); border-top-color: var(--color-link); }
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
166
frontend/app/components/windows/FoundryIconPickerWindow.vue
Normal file
166
frontend/app/components/windows/FoundryIconPickerWindow.vue
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top, SetResizable, SetMinSize } from '@/services/Windows';
|
||||||
|
import WindowHandle from './partials/WindowHandle.vue';
|
||||||
|
import Server from '~/services/Server';
|
||||||
|
import { emitter } from '~/services/Emitter';
|
||||||
|
|
||||||
|
const props = defineProps(['data']);
|
||||||
|
const id = props.data.id;
|
||||||
|
const itemId = props.data.item?._id;
|
||||||
|
const campaign = props.data.campaign || '';
|
||||||
|
const ICON_ROOT = 'icons';
|
||||||
|
|
||||||
|
const handle = ref(null);
|
||||||
|
const wrapper = ref(null);
|
||||||
|
const loading = ref(false);
|
||||||
|
const error = ref('');
|
||||||
|
const applying = ref('');
|
||||||
|
// What the window is standing on: one folder of Foundry's icon library at a time.
|
||||||
|
const listing = ref({ dir: ICON_ROOT, parent: null, folders: [], files: [], next: null });
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
Top(wrapper);
|
||||||
|
SetupHandle(id, handle);
|
||||||
|
SetSize(id, { width: 560, height: 540 });
|
||||||
|
ResetPosition(id, 'center');
|
||||||
|
SetResizable(id, true);
|
||||||
|
SetMinSize(id, { width: 420, height: 340 });
|
||||||
|
Load(ICON_ROOT);
|
||||||
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => ClearWindow({ type: 'foundry_icons' }));
|
||||||
|
|
||||||
|
// One request per folder, and the icons inside it a page at a time: that library
|
||||||
|
// runs into the thousands, so the window only ever asks for what it shows.
|
||||||
|
async function Load(dir, offset = 0) {
|
||||||
|
if (loading.value) return;
|
||||||
|
if (!campaign) {
|
||||||
|
error.value = t('foundry.errors.icons-no-world-url');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
loading.value = true;
|
||||||
|
error.value = '';
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({ campaign, dir });
|
||||||
|
if (offset) params.set('offset', String(offset));
|
||||||
|
const response = await Server().get(`/foundry/icons?${params.toString()}`);
|
||||||
|
if (response.data.status !== 'ok') {
|
||||||
|
error.value = t(response.data.msg || 'foundry.errors.icons-unavailable');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const page = {
|
||||||
|
dir: response.data.dir || dir,
|
||||||
|
parent: response.data.parent ?? null,
|
||||||
|
folders: response.data.folders || [],
|
||||||
|
files: response.data.files || [],
|
||||||
|
next: response.data.next ?? null,
|
||||||
|
};
|
||||||
|
listing.value = offset
|
||||||
|
? { ...page, files: [...listing.value.files, ...page.files] }
|
||||||
|
: page;
|
||||||
|
} catch (requestError) {
|
||||||
|
error.value = t('foundry.errors.icons-unavailable');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const trail = computed(() => {
|
||||||
|
const parts = String(listing.value.dir || ICON_ROOT).split('/').filter(Boolean);
|
||||||
|
return parts.map((name, index) => ({ name, path: parts.slice(0, index + 1).join('/') }));
|
||||||
|
});
|
||||||
|
|
||||||
|
const empty = computed(() => !loading.value && !listing.value.folders.length && !listing.value.files.length);
|
||||||
|
|
||||||
|
function GoUp() {
|
||||||
|
Load(listing.value.parent || ICON_ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The icon is stored as the url the browser loads it from, the same shape a synced
|
||||||
|
// Foundry item's icon has; the item window follows the event this leaves behind.
|
||||||
|
async function Choose(icon) {
|
||||||
|
if (applying.value) return;
|
||||||
|
applying.value = icon.path;
|
||||||
|
error.value = '';
|
||||||
|
try {
|
||||||
|
const response = await Server().post('/item/update', { id: itemId, image: icon.url });
|
||||||
|
if (response.data.status !== 'ok') {
|
||||||
|
error.value = t('campaigns.item.sheet.save-error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
|
||||||
|
ClearWindow({ type: 'foundry_icons' });
|
||||||
|
ClearWindow({ type: 'item_icon_source' });
|
||||||
|
} catch (requestError) {
|
||||||
|
error.value = t('campaigns.item.sheet.save-error');
|
||||||
|
} finally {
|
||||||
|
applying.value = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="window-wrapper foundry-icons-window" :id="'window-wrapper-' + id" ref="wrapper">
|
||||||
|
<WindowHandle :window="id" ref="handle" />
|
||||||
|
<div class="icons-body">
|
||||||
|
<nav class="icons-trail" :aria-label="$t('foundry.icons.path')">
|
||||||
|
<button class="trail-up" type="button" :disabled="loading || !listing.parent" :aria-label="$t('foundry.icons.up')" @click="GoUp">
|
||||||
|
<img class="icon" src="/icons/iconoir/regular/arrow-up.svg" alt="" aria-hidden="true">
|
||||||
|
</button>
|
||||||
|
<template v-for="crumb in trail" :key="crumb.path">
|
||||||
|
<span class="trail-separator" aria-hidden="true">/</span>
|
||||||
|
<button class="trail-crumb" type="button" :disabled="loading" @click="Load(crumb.path)">{{ crumb.name }}</button>
|
||||||
|
</template>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div v-if="error" class="icons-error">{{ error }}</div>
|
||||||
|
<p v-if="loading" class="icons-state">{{ $t('foundry.icons.loading') }}</p>
|
||||||
|
<p v-else-if="empty" class="icons-state">{{ $t('foundry.icons.empty') }}</p>
|
||||||
|
|
||||||
|
<div v-if="listing.folders.length" class="icon-tiles">
|
||||||
|
<button v-for="folder in listing.folders" :key="folder.path" class="icon-tile folder" type="button" :disabled="loading" @click="Load(folder.path)">
|
||||||
|
<img class="icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
|
||||||
|
<span class="tile-name">{{ folder.name }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="listing.files.length" class="icon-tiles">
|
||||||
|
<button v-for="icon in listing.files" :key="icon.path" class="icon-tile" type="button"
|
||||||
|
:disabled="applying !== ''" :title="icon.name" @click="Choose(icon)">
|
||||||
|
<img class="tile-image" :src="icon.url" :alt="icon.name" loading="lazy">
|
||||||
|
<span class="tile-name">{{ icon.name }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button v-if="listing.next" class="icons-more sheet-button" type="button" :disabled="loading" @click="Load(listing.dir, listing.next)">
|
||||||
|
{{ $t('foundry.icons.load-more') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.foundry-icons-window { min-width: 0; min-height: 0; }
|
||||||
|
.icons-body { width: 100%; min-height: 0; flex: 1; overflow: auto; padding: 12px 14px 16px; box-sizing: border-box; display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.icons-trail { display: flex; align-items: center; flex-wrap: wrap; gap: 4px; position: sticky; top: 0; padding-bottom: 8px; background: var(--color-window-background); font-size: 12px; }
|
||||||
|
.trail-up, .trail-crumb { display: inline-flex; align-items: center; padding: 4px 7px; border: 1px solid var(--color-border); border-radius: 6px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; font-size: 12px; }
|
||||||
|
.trail-up:hover, .trail-crumb:hover { background: var(--color-button-hover); }
|
||||||
|
.trail-up:disabled, .trail-crumb:disabled { opacity: .5; cursor: wait; }
|
||||||
|
.trail-separator { opacity: .45; }
|
||||||
|
.icons-error { padding: 7px 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
|
||||||
|
.icons-state { margin: 0; font-size: 12px; opacity: .7; }
|
||||||
|
.icon-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(78px, 1fr)); gap: 8px; }
|
||||||
|
.icon-tile { display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 8px 6px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; }
|
||||||
|
.icon-tile:hover { background: var(--color-button-hover); border-color: var(--color-link); }
|
||||||
|
.icon-tile:disabled { opacity: .55; cursor: wait; }
|
||||||
|
.icon-tile.folder { justify-content: center; }
|
||||||
|
.icon-tile .icon { width: 22px; height: 22px; }
|
||||||
|
.tile-image { width: 40px; height: 40px; object-fit: contain; }
|
||||||
|
.tile-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 10px; opacity: .75; }
|
||||||
|
.icons-more { align-self: center; border: 1px solid var(--color-border); border-radius: 7px; padding: 7px 12px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; white-space: nowrap; font-size: 13px; }
|
||||||
|
.icons-more:hover { background: var(--color-button-hover); }
|
||||||
|
.icons-more:disabled { opacity: .55; cursor: wait; }
|
||||||
|
</style>
|
||||||
128
frontend/app/components/windows/ItemIconSourceWindow.vue
Normal file
128
frontend/app/components/windows/ItemIconSourceWindow.vue
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top, CreateChildWindow } from '@/services/Windows';
|
||||||
|
import WindowHandle from './partials/WindowHandle.vue';
|
||||||
|
import Server, { getBaseUrl } from '~/services/Server';
|
||||||
|
import { emitter } from '~/services/Emitter';
|
||||||
|
|
||||||
|
const props = defineProps(['data']);
|
||||||
|
const id = props.data.id;
|
||||||
|
const item = props.data.item || {};
|
||||||
|
const itemId = item._id;
|
||||||
|
const campaign = props.data.campaign || '';
|
||||||
|
const handle = ref(null);
|
||||||
|
const wrapper = ref(null);
|
||||||
|
const error = ref('');
|
||||||
|
const uploading = ref(false);
|
||||||
|
const photoInput = ref(null);
|
||||||
|
const image = ref(item.image || '');
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
Top(wrapper);
|
||||||
|
SetupHandle(id, handle);
|
||||||
|
SetSize(id, { width: 430, height: 320 });
|
||||||
|
ResetPosition(id, 'center');
|
||||||
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => ClearWindow({ type: 'item_icon_source' }));
|
||||||
|
|
||||||
|
// An uploaded icon is a file of the backend's uploads folder and a Foundry one an
|
||||||
|
// absolute url of the world; both are drawn the way the item window draws them.
|
||||||
|
const imageUrl = computed(() => {
|
||||||
|
if (!image.value) return '';
|
||||||
|
return /^(https?:|data:|\/\/)/i.test(image.value)
|
||||||
|
? image.value
|
||||||
|
: `${getBaseUrl()}/public/${image.value}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
function pickLocalIcon() {
|
||||||
|
photoInput.value?.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The icon browser opens on top of this window, as its child: closing the chooser
|
||||||
|
// takes the browser with it, like every other child window here.
|
||||||
|
function openFoundryIcons() {
|
||||||
|
CreateChildWindow(id, 'foundry_icons', { item: { _id: itemId, name: item.name }, campaign });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onIconSelected(event) {
|
||||||
|
const file = event.target.files?.[0];
|
||||||
|
event.target.value = '';
|
||||||
|
if (!file || uploading.value) return;
|
||||||
|
uploading.value = true;
|
||||||
|
error.value = '';
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('image', file);
|
||||||
|
const response = await Server().post(`/item/upload-image?item=${itemId}`, formData, {
|
||||||
|
headers: { "Content-Type": "multipart/form-data" }
|
||||||
|
});
|
||||||
|
if (response.data.status !== 'ok') {
|
||||||
|
error.value = t('campaigns.item.sheet.upload-error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The item window follows this event and shows the new icon.
|
||||||
|
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
|
||||||
|
ClearWindow({ id });
|
||||||
|
} catch (requestError) {
|
||||||
|
error.value = t('campaigns.item.sheet.upload-error');
|
||||||
|
} finally {
|
||||||
|
uploading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="window-wrapper icon-source-window" :id="'window-wrapper-' + id" ref="wrapper">
|
||||||
|
<WindowHandle :window="id" ref="handle" />
|
||||||
|
<div class="source-body">
|
||||||
|
<header class="source-hero">
|
||||||
|
<div class="source-icon" :class="{ empty: !image }">
|
||||||
|
<img v-if="imageUrl" :src="imageUrl" :alt="$t('campaigns.item.sheet.icon')">
|
||||||
|
<span v-else aria-hidden="true">{{ (item.name || '?').slice(0, 1).toUpperCase() }}</span>
|
||||||
|
</div>
|
||||||
|
<p class="source-intro">{{ $t('campaigns.item.icon-picker.intro') }}</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div v-if="error" class="source-error">{{ error }}</div>
|
||||||
|
|
||||||
|
<div class="source-options">
|
||||||
|
<button class="source-option" type="button" :disabled="uploading" @click="pickLocalIcon">
|
||||||
|
<img class="icon" src="/icons/iconoir/regular/cloud-upload.svg" alt="" aria-hidden="true">
|
||||||
|
<span class="source-option-title">{{ uploading
|
||||||
|
? $t('campaigns.item.sheet.uploading')
|
||||||
|
: $t('campaigns.item.icon-picker.upload') }}</span>
|
||||||
|
<span class="source-option-hint">{{ $t('campaigns.item.icon-picker.upload-hint') }}</span>
|
||||||
|
</button>
|
||||||
|
<button class="source-option" type="button" @click="openFoundryIcons">
|
||||||
|
<img class="icon" src="/icons/iconoir/regular/media-image.svg" alt="" aria-hidden="true">
|
||||||
|
<span class="source-option-title">{{ $t('campaigns.item.icon-picker.foundry') }}</span>
|
||||||
|
<span class="source-option-hint">{{ $t('campaigns.item.icon-picker.foundry-hint') }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onIconSelected">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.icon-source-window { min-width: 0; min-height: 0; }
|
||||||
|
.source-body { width: 100%; min-height: 0; flex: 1; overflow: auto; padding: 14px 16px 16px; box-sizing: border-box; display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.source-hero { display: flex; align-items: center; gap: 13px; padding-bottom: 12px; border-bottom: 1px solid var(--color-border); }
|
||||||
|
.source-icon { width: 56px; height: 56px; flex: 0 0 56px; display: grid; place-items: center; overflow: hidden; border-radius: 10px; border: 1px solid var(--color-border); background: var(--color-background-soft); color: var(--color-link); font: 26px MrEavesRemake; }
|
||||||
|
.source-icon.empty { border-style: dashed; }
|
||||||
|
.source-icon img { width: 100%; height: 100%; object-fit: contain; }
|
||||||
|
.source-intro { margin: 0; font-size: 13px; opacity: .85; }
|
||||||
|
.source-error { padding: 7px 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
|
||||||
|
.source-options { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.source-option { display: grid; grid-template-columns: 26px 1fr; align-items: center; gap: 4px 10px; padding: 12px 14px; text-align: left; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; }
|
||||||
|
.source-option:hover { background: var(--color-button-hover); }
|
||||||
|
.source-option:disabled { opacity: .55; cursor: wait; }
|
||||||
|
.source-option .icon { width: 20px; height: 20px; grid-row: span 2; }
|
||||||
|
.source-option-title { font: 15px MrEavesRemake; }
|
||||||
|
.source-option-hint { font-size: 12px; opacity: .7; }
|
||||||
|
.photo-input { display: none; }
|
||||||
|
</style>
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
|
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top, CreateChildWindow } from '@/services/Windows';
|
||||||
import WindowHandle from './partials/WindowHandle.vue';
|
import WindowHandle from './partials/WindowHandle.vue';
|
||||||
import Server, { getBaseUrl } from '~/services/Server';
|
import Server, { getBaseUrl } from '~/services/Server';
|
||||||
|
import { useCampaignService } from '~/services/Campaign.js';
|
||||||
import { emitter } from '~/services/Emitter';
|
import { emitter } from '~/services/Emitter';
|
||||||
|
|
||||||
const props = defineProps(['data']);
|
const props = defineProps(['data']);
|
||||||
@@ -12,9 +13,10 @@ const itemId = props.data.item?._id;
|
|||||||
const handle = ref(null);
|
const handle = ref(null);
|
||||||
const wrapper = ref(null);
|
const wrapper = ref(null);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
const uploadingIcon = ref(false);
|
// Set while this window writes the item's icon, so a Foundry sync landing behind
|
||||||
const applyingFoundryIcon = ref(false);
|
// the window does not rewrite the form under the change being made.
|
||||||
const photoInput = ref(null);
|
const applyingIcon = ref(false);
|
||||||
|
const { Campaign } = useCampaignService();
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
function normalizeItem(item) {
|
function normalizeItem(item) {
|
||||||
@@ -44,9 +46,10 @@ onMounted(() => {
|
|||||||
onBeforeUnmount(() => ClearWindow({ type: 'item_sheet' }));
|
onBeforeUnmount(() => ClearWindow({ type: 'item_sheet' }));
|
||||||
|
|
||||||
// The sidebar keeps this entry fresh (Foundry sync lands in the background);
|
// The sidebar keeps this entry fresh (Foundry sync lands in the background);
|
||||||
// follow along unless the window is mid-icon-upload.
|
// follow along unless this window is mid-icon-change. The icon windows leave
|
||||||
|
// their result here, on the same event.
|
||||||
function handleItemSync({ entityType, entry }) {
|
function handleItemSync({ entityType, entry }) {
|
||||||
if (entityType !== 'item' || entry?._id !== itemId || uploadingIcon.value) return;
|
if (entityType !== 'item' || entry?._id !== itemId || applyingIcon.value) return;
|
||||||
form.value = normalizeItem(entry);
|
form.value = normalizeItem(entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,40 +73,22 @@ async function updateItem(payload) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickIcon() {
|
// Choosing an icon is a window of its own: upload one from this device, or browse
|
||||||
photoInput.value?.click();
|
// the icon library of the linked Foundry world. Both leave their result on the
|
||||||
}
|
// `campaign-entry-updated` event, which this window follows.
|
||||||
|
function chooseIcon() {
|
||||||
async function onIconSelected(event) {
|
CreateChildWindow(id, 'item_icon_source', {
|
||||||
const file = event.target.files?.[0];
|
item: { _id: itemId, name: form.value.name, image: form.value.image },
|
||||||
event.target.value = '';
|
campaign: Campaign.value?._id || ''
|
||||||
if (!file || uploadingIcon.value) return;
|
|
||||||
uploadingIcon.value = true;
|
|
||||||
error.value = '';
|
|
||||||
try {
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('image', file);
|
|
||||||
const response = await Server().post(`/item/upload-image?item=${itemId}`, formData, {
|
|
||||||
headers: { "Content-Type": "multipart/form-data" }
|
|
||||||
});
|
});
|
||||||
if (response.data.status !== 'ok') {
|
|
||||||
error.value = t('campaigns.item.sheet.upload-error');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
form.value = normalizeItem(response.data.item);
|
|
||||||
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
|
|
||||||
} catch (requestError) {
|
|
||||||
error.value = t('campaigns.item.sheet.upload-error');
|
|
||||||
} finally {
|
|
||||||
uploadingIcon.value = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// "Fetch from Foundry's icons": the module keeps the world's own icon on the
|
// The world's own icon for this item: the module keeps it on the item, so this
|
||||||
// item, so this just switches back to it.
|
// just switches back to it. Picking one of the world's other icons is what the
|
||||||
|
// icon browser is for.
|
||||||
async function useFoundryIcon() {
|
async function useFoundryIcon() {
|
||||||
if (!canUseFoundryIcon.value || applyingFoundryIcon.value) return;
|
if (!canUseFoundryIcon.value || applyingIcon.value) return;
|
||||||
applyingFoundryIcon.value = true;
|
applyingIcon.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
try {
|
try {
|
||||||
const done = await updateItem({ image: form.value.foundryImage });
|
const done = await updateItem({ image: form.value.foundryImage });
|
||||||
@@ -111,18 +96,21 @@ async function useFoundryIcon() {
|
|||||||
} catch (requestError) {
|
} catch (requestError) {
|
||||||
error.value = t('campaigns.item.sheet.save-error');
|
error.value = t('campaigns.item.sheet.save-error');
|
||||||
} finally {
|
} finally {
|
||||||
applyingFoundryIcon.value = false;
|
applyingIcon.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function removeIcon() {
|
async function removeIcon() {
|
||||||
if (!form.value.image) return;
|
if (!form.value.image || applyingIcon.value) return;
|
||||||
|
applyingIcon.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
try {
|
try {
|
||||||
const done = await updateItem({ image: '' });
|
const done = await updateItem({ image: '' });
|
||||||
if (!done) error.value = t('campaigns.item.sheet.save-error');
|
if (!done) error.value = t('campaigns.item.sheet.save-error');
|
||||||
} catch (requestError) {
|
} catch (requestError) {
|
||||||
error.value = t('campaigns.item.sheet.save-error');
|
error.value = t('campaigns.item.sheet.save-error');
|
||||||
|
} finally {
|
||||||
|
applyingIcon.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -132,10 +120,12 @@ async function removeIcon() {
|
|||||||
<WindowHandle :window="id" ref="handle" />
|
<WindowHandle :window="id" ref="handle" />
|
||||||
<div class="item-body">
|
<div class="item-body">
|
||||||
<header class="item-hero">
|
<header class="item-hero">
|
||||||
<div class="item-icon" :class="{ empty: !form.image }">
|
<button class="item-icon" :class="{ empty: !form.image }" type="button"
|
||||||
|
:aria-label="$t(form.image ? 'campaigns.item.sheet.change-icon' : 'campaigns.item.sheet.choose-icon')"
|
||||||
|
@click="chooseIcon">
|
||||||
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.item.sheet.icon')">
|
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.item.sheet.icon')">
|
||||||
<span v-else aria-hidden="true">{{ form.name.slice(0, 1).toUpperCase() }}</span>
|
<span v-else aria-hidden="true">{{ form.name.slice(0, 1).toUpperCase() }}</span>
|
||||||
</div>
|
</button>
|
||||||
<div class="item-identity">
|
<div class="item-identity">
|
||||||
<h1>{{ form.name }}</h1>
|
<h1>{{ form.name }}</h1>
|
||||||
<div class="item-tags">
|
<div class="item-tags">
|
||||||
@@ -149,16 +139,13 @@ async function removeIcon() {
|
|||||||
<div v-if="error" class="item-error">{{ error }}</div>
|
<div v-if="error" class="item-error">{{ error }}</div>
|
||||||
|
|
||||||
<div class="icon-controls">
|
<div class="icon-controls">
|
||||||
<button class="sheet-button" type="button" :disabled="uploadingIcon" @click="pickIcon">
|
<button class="sheet-button" type="button" @click="chooseIcon">
|
||||||
{{ uploadingIcon
|
{{ form.image ? $t('campaigns.item.sheet.change-icon') : $t('campaigns.item.sheet.choose-icon') }}
|
||||||
? $t('campaigns.item.sheet.uploading')
|
|
||||||
: (form.image ? $t('campaigns.item.sheet.change-icon') : $t('campaigns.item.sheet.choose-icon')) }}
|
|
||||||
</button>
|
</button>
|
||||||
<button v-if="canUseFoundryIcon" class="sheet-button secondary" type="button" :disabled="applyingFoundryIcon" @click="useFoundryIcon">
|
<button v-if="canUseFoundryIcon" class="sheet-button secondary" type="button" :disabled="applyingIcon" @click="useFoundryIcon">
|
||||||
{{ $t('campaigns.item.sheet.foundry-icon') }}
|
{{ $t('campaigns.item.sheet.foundry-icon') }}
|
||||||
</button>
|
</button>
|
||||||
<button v-if="form.image" class="sheet-button secondary" type="button" :disabled="uploadingIcon" :aria-label="$t('campaigns.item.sheet.remove-icon')" @click="removeIcon">×</button>
|
<button v-if="form.image" class="sheet-button secondary" type="button" :disabled="applyingIcon" :aria-label="$t('campaigns.item.sheet.remove-icon')" @click="removeIcon">×</button>
|
||||||
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onIconSelected">
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<dl class="item-facts">
|
<dl class="item-facts">
|
||||||
@@ -189,7 +176,8 @@ async function removeIcon() {
|
|||||||
.item-window { min-width: 0; min-height: 0; }
|
.item-window { min-width: 0; min-height: 0; }
|
||||||
.item-body { width: 100%; min-height: 0; flex: 1; overflow: auto; padding: 14px 16px 16px; box-sizing: border-box; }
|
.item-body { width: 100%; min-height: 0; flex: 1; overflow: auto; padding: 14px 16px 16px; box-sizing: border-box; }
|
||||||
.item-hero { display: flex; align-items: center; gap: 13px; padding: 2px 2px 13px; margin-bottom: 11px; border-bottom: 1px solid var(--color-border); }
|
.item-hero { display: flex; align-items: center; gap: 13px; padding: 2px 2px 13px; margin-bottom: 11px; border-bottom: 1px solid var(--color-border); }
|
||||||
.item-icon { width: 64px; height: 64px; flex: 0 0 64px; display: grid; place-items: center; overflow: hidden; border-radius: 10px; border: 1px solid var(--color-border); background: var(--color-background-soft); color: var(--color-link); font: 30px MrEavesRemake; }
|
.item-icon { width: 64px; height: 64px; flex: 0 0 64px; display: grid; place-items: center; overflow: hidden; border-radius: 10px; border: 1px solid var(--color-border); background: var(--color-background-soft); color: var(--color-link); font: 30px MrEavesRemake; padding: 0; cursor: pointer; }
|
||||||
|
.item-icon:hover { border-color: var(--color-link); }
|
||||||
.item-icon.empty { border-style: dashed; }
|
.item-icon.empty { border-style: dashed; }
|
||||||
.item-icon img { width: 100%; height: 100%; object-fit: contain; }
|
.item-icon img { width: 100%; height: 100%; object-fit: contain; }
|
||||||
.item-identity { min-width: 0; }
|
.item-identity { min-width: 0; }
|
||||||
@@ -202,7 +190,6 @@ async function removeIcon() {
|
|||||||
.sheet-button { border: 1px solid var(--color-border); border-radius: 7px; padding: 7px 12px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; white-space: nowrap; font-size: 13px; }
|
.sheet-button { border: 1px solid var(--color-border); border-radius: 7px; padding: 7px 12px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; white-space: nowrap; font-size: 13px; }
|
||||||
.sheet-button:hover { background: var(--color-button-hover); }
|
.sheet-button:hover { background: var(--color-button-hover); }
|
||||||
.sheet-button:disabled { opacity: .55; cursor: wait; }
|
.sheet-button:disabled { opacity: .55; cursor: wait; }
|
||||||
.photo-input { display: none; }
|
|
||||||
.item-facts { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 13px; }
|
.item-facts { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 13px; }
|
||||||
.item-fact { flex: 1 1 120px; min-width: 0; padding: 9px 11px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); }
|
.item-fact { flex: 1 1 120px; min-width: 0; padding: 9px 11px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); }
|
||||||
.item-fact dt { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; opacity: .72; }
|
.item-fact dt { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; opacity: .72; }
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ function confirmSave() {
|
|||||||
const url = creating ? '/folder/rename' : '/folder/create';
|
const url = creating ? '/folder/rename' : '/folder/create';
|
||||||
if (creating) {
|
if (creating) {
|
||||||
folderData.id = data.folderId;
|
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) => {
|
Server().post(url, folderData).then((response) => {
|
||||||
|
|||||||
27
frontend/app/services/EntryColors.js
Normal file
27
frontend/app/services/EntryColors.js
Normal 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 };
|
||||||
@@ -88,6 +88,21 @@ const defWindows = {
|
|||||||
close: () => ClearWindow({type: 'item_sheet'}),
|
close: () => ClearWindow({type: 'item_sheet'}),
|
||||||
movable: true
|
movable: true
|
||||||
},
|
},
|
||||||
|
item_icon_source: {
|
||||||
|
title: 'windows.icon-source',
|
||||||
|
component: () => import('~/components/windows/ItemIconSourceWindow.vue'),
|
||||||
|
close: () => ClearWindow({ type: 'item_icon_source' }),
|
||||||
|
movable: true
|
||||||
|
},
|
||||||
|
foundry_icons: {
|
||||||
|
title: 'windows.foundry-icons',
|
||||||
|
component: () => import('~/components/windows/FoundryIconPickerWindow.vue'),
|
||||||
|
// Back closes the icon browser and leaves the chooser it was opened from,
|
||||||
|
// which is still open behind it.
|
||||||
|
back: () => ClearWindow({ type: 'foundry_icons' }),
|
||||||
|
close: () => ClearWindow({ type: 'foundry_icons' }),
|
||||||
|
movable: true
|
||||||
|
},
|
||||||
create_map: {
|
create_map: {
|
||||||
title: 'windows.create-map',
|
title: 'windows.create-map',
|
||||||
component: () => import('~/components/windows/CreateMapWindow.vue'),
|
component: () => import('~/components/windows/CreateMapWindow.vue'),
|
||||||
|
|||||||
@@ -44,6 +44,11 @@
|
|||||||
"create": "Crea {section}", "submit": "Crea", "edit": "Edita", "save": "Desa", "delete": "Suprimeix", "saving": "Desant...",
|
"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"
|
"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": {
|
"states": {
|
||||||
"loading": "Carregant...", "loading-notes": "Carregant notes...", "empty-notes": "Encara no hi ha notes en aquesta campanya.",
|
"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.",
|
"empty-actors": "Encara no hi ha actors ni personatges.", "empty-items": "Encara no hi ha objectes en aquesta campanya.",
|
||||||
@@ -62,13 +67,17 @@
|
|||||||
"new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.",
|
"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",
|
"category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat",
|
||||||
"quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
|
"quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
|
||||||
"folder-toggle": "Mostra o amaga la carpeta {name}",
|
|
||||||
"sheet": {
|
"sheet": {
|
||||||
"icon": "Icona de l'objecte", "choose-icon": "Tria la teva pròpia icona", "change-icon": "Canvia la icona",
|
"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.",
|
"uploading": "Pujant...", "upload-error": "No s'ha pogut pujar aquesta icona.",
|
||||||
"foundry-icon": "Fes servir la icona del Foundry", "remove-icon": "Treu la icona", "save-error": "No s'ha pogut desar aquest objecte.",
|
"foundry-icon": "Fes servir la icona del Foundry", "remove-icon": "Treu la icona", "save-error": "No s'ha pogut desar aquest objecte.",
|
||||||
"no-description": "Sense descripció afegida."
|
"no-description": "Sense descripció afegida."
|
||||||
},
|
},
|
||||||
|
"icon-picker": {
|
||||||
|
"intro": "D'on ha de sortir la icona d'aquest objecte?",
|
||||||
|
"upload": "Pujar una icona", "upload-hint": "Tria una imatge d'aquest dispositiu.",
|
||||||
|
"foundry": "Carregar del Foundry", "foundry-hint": "Recorre les icones que inclou el teu món del Foundry."
|
||||||
|
},
|
||||||
"categories": {
|
"categories": {
|
||||||
"weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura",
|
"weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura",
|
||||||
"magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre"
|
"magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre"
|
||||||
@@ -101,6 +110,7 @@
|
|||||||
},
|
},
|
||||||
"character-sheet": {
|
"character-sheet": {
|
||||||
"title": "Fitxa de personatge", "name": "Nom del personatge", "class": "Classe", "subclass": "Subclasse", "unset-class": "Classe sense definir",
|
"title": "Fitxa de personatge", "name": "Nom del personatge", "class": "Classe", "subclass": "Subclasse", "unset-class": "Classe sense definir",
|
||||||
|
"tabs": { "abilities": "Característiques", "inventory": "Inventari", "traits": "Trets", "spells": "Conjurs" },
|
||||||
"level": "Nivell", "species": "Espècie", "unset-species": "Espècie sense definir", "edit": "Edita la fitxa", "cancel": "Cancel·la",
|
"level": "Nivell", "species": "Espècie", "unset-species": "Espècie sense definir", "edit": "Edita la fitxa", "cancel": "Cancel·la",
|
||||||
"saving": "Desant...", "save": "Desa la fitxa", "save-error": "No s'ha pogut desar aquesta fitxa de personatge.", "photo": "Foto", "upload-photo": "Pujar foto", "change-photo": "Canviar foto", "remove-photo": "Treure foto", "uploading-photo": "Pujant...", "photo-error": "No s'ha pogut pujar aquesta foto.", "ability-scores": "Característiques", "proficiency-bonus": "Bonificador de competència",
|
"saving": "Desant...", "save": "Desa la fitxa", "save-error": "No s'ha pogut desar aquesta fitxa de personatge.", "photo": "Foto", "upload-photo": "Pujar foto", "change-photo": "Canviar foto", "remove-photo": "Treure foto", "uploading-photo": "Pujant...", "photo-error": "No s'ha pogut pujar aquesta foto.", "ability-scores": "Característiques", "proficiency-bonus": "Bonificador de competència",
|
||||||
"combat": "Combat", "armor-class": "Classe d'armadura", "speed": "Velocitat", "proficiencies": "Competències",
|
"combat": "Combat", "armor-class": "Classe d'armadura", "speed": "Velocitat", "proficiencies": "Competències",
|
||||||
|
|||||||
@@ -3,6 +3,15 @@
|
|||||||
"link-expired": "El codi d'enllaç de Foundry no és vàlid, ha caducat o ja s'ha utilitzat.",
|
"link-expired": "El codi d'enllaç de Foundry no és vàlid, ha caducat o ja s'ha utilitzat.",
|
||||||
"world-already-linked": "Aquest món de Foundry ja està enllaçat amb una altra campanya.",
|
"world-already-linked": "Aquest món de Foundry ja està enllaçat amb una altra campanya.",
|
||||||
"actor-already-synced": "Un altre actor d'aquesta campanya ja està sincronitzat amb aquell actor del Foundry.",
|
"actor-already-synced": "Un altre actor d'aquesta campanya ja està sincronitzat amb aquell actor del Foundry.",
|
||||||
"item-already-synced": "Un altre objecte d'aquesta campanya ja està sincronitzat amb aquell objecte del Foundry."
|
"item-already-synced": "Un altre objecte d'aquesta campanya ja està sincronitzat amb aquell objecte del Foundry.",
|
||||||
|
"icons-unavailable": "Les icones del Foundry no són disponibles: el seu bridge no està configurat o ara mateix no hi arriba.",
|
||||||
|
"icons-no-world-url": "Aquesta campanya no té adreça del món del Foundry. Definiu-la als ajustos de la campanya, a la pestanya d'integracions."
|
||||||
|
},
|
||||||
|
"icons": {
|
||||||
|
"path": "Carpeta d'icones",
|
||||||
|
"up": "Una carpeta amunt",
|
||||||
|
"loading": "Carregant icones...",
|
||||||
|
"empty": "No hi ha icones per triar en aquesta carpeta.",
|
||||||
|
"load-more": "Carregar més icones"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,5 +10,7 @@
|
|||||||
"create-map": "Crear mapa",
|
"create-map": "Crear mapa",
|
||||||
"map-viewer": "Mapa",
|
"map-viewer": "Mapa",
|
||||||
"pinned-note": "Nota fixada",
|
"pinned-note": "Nota fixada",
|
||||||
"item-sheet": "Objecte"
|
"item-sheet": "Objecte",
|
||||||
|
"icon-source": "Tria una icona",
|
||||||
|
"foundry-icons": "Icones del Foundry"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,11 @@
|
|||||||
"create": "Create {section}", "submit": "Create", "edit": "Edit", "save": "Save", "delete": "Delete", "saving": "Saving...",
|
"create": "Create {section}", "submit": "Create", "edit": "Edit", "save": "Save", "delete": "Delete", "saving": "Saving...",
|
||||||
"collapse-sidebar": "Collapse sidebar", "expand-sidebar": "Expand sidebar"
|
"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": {
|
"states": {
|
||||||
"loading": "Loading...", "loading-notes": "Loading notes...", "empty-notes": "No notes in this campaign yet.",
|
"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.",
|
"empty-actors": "No actors or characters yet.", "empty-items": "No items in this campaign yet.",
|
||||||
@@ -66,13 +71,17 @@
|
|||||||
"new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.",
|
"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",
|
"category": "Category", "rarity": "Rarity", "quantity": "Quantity",
|
||||||
"quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
|
"quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
|
||||||
"folder-toggle": "Toggle the {name} folder",
|
|
||||||
"sheet": {
|
"sheet": {
|
||||||
"icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change icon",
|
"icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change icon",
|
||||||
"uploading": "Uploading...", "upload-error": "Unable to upload this icon.",
|
"uploading": "Uploading...", "upload-error": "Unable to upload this icon.",
|
||||||
"foundry-icon": "Use Foundry icon", "remove-icon": "Remove icon", "save-error": "Unable to save this item.",
|
"foundry-icon": "Use Foundry icon", "remove-icon": "Remove icon", "save-error": "Unable to save this item.",
|
||||||
"no-description": "No description added."
|
"no-description": "No description added."
|
||||||
},
|
},
|
||||||
|
"icon-picker": {
|
||||||
|
"intro": "Where should this item's icon come from?",
|
||||||
|
"upload": "Upload icon", "upload-hint": "Choose an image from this device.",
|
||||||
|
"foundry": "Load from Foundry", "foundry-hint": "Browse the icons your Foundry world ships with."
|
||||||
|
},
|
||||||
"categories": {
|
"categories": {
|
||||||
"weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear",
|
"weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear",
|
||||||
"magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other"
|
"magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other"
|
||||||
@@ -105,6 +114,7 @@
|
|||||||
},
|
},
|
||||||
"character-sheet": {
|
"character-sheet": {
|
||||||
"title": "Character Sheet", "name": "Character name", "class": "Class", "subclass": "Subclass", "unset-class": "Class not set",
|
"title": "Character Sheet", "name": "Character name", "class": "Class", "subclass": "Subclass", "unset-class": "Class not set",
|
||||||
|
"tabs": { "abilities": "Ability Scores", "inventory": "Inventory", "traits": "Traits", "spells": "Spells" },
|
||||||
"level": "Level", "species": "Species", "unset-species": "Species not set", "edit": "Edit sheet", "cancel": "Cancel",
|
"level": "Level", "species": "Species", "unset-species": "Species not set", "edit": "Edit sheet", "cancel": "Cancel",
|
||||||
"saving": "Saving...", "save": "Save sheet", "save-error": "Unable to save this character sheet.",
|
"saving": "Saving...", "save": "Save sheet", "save-error": "Unable to save this character sheet.",
|
||||||
"photo": "Photo", "upload-photo": "Upload photo", "change-photo": "Change photo", "remove-photo": "Remove photo",
|
"photo": "Photo", "upload-photo": "Upload photo", "change-photo": "Change photo", "remove-photo": "Remove photo",
|
||||||
|
|||||||
@@ -3,6 +3,15 @@
|
|||||||
"link-expired": "This Foundry pairing code is invalid, expired, or already used.",
|
"link-expired": "This Foundry pairing code is invalid, expired, or already used.",
|
||||||
"world-already-linked": "This Foundry world is already linked to another campaign.",
|
"world-already-linked": "This Foundry world is already linked to another campaign.",
|
||||||
"actor-already-synced": "Another actor in this campaign is already synced with that Foundry actor.",
|
"actor-already-synced": "Another actor in this campaign is already synced with that Foundry actor.",
|
||||||
"item-already-synced": "Another item in this campaign is already synced with that Foundry item."
|
"item-already-synced": "Another item in this campaign is already synced with that Foundry item.",
|
||||||
|
"icons-unavailable": "Foundry's icons are not available: its bridge is not set up, or it cannot be reached right now.",
|
||||||
|
"icons-no-world-url": "This campaign has no Foundry world address. Set it under campaign settings, in the Integrations tab."
|
||||||
|
},
|
||||||
|
"icons": {
|
||||||
|
"path": "Icon folder",
|
||||||
|
"up": "One folder up",
|
||||||
|
"loading": "Loading icons...",
|
||||||
|
"empty": "No icons to pick in this folder.",
|
||||||
|
"load-more": "Load more icons"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,5 +10,7 @@
|
|||||||
"create-map": "Create Map",
|
"create-map": "Create Map",
|
||||||
"map-viewer": "Map",
|
"map-viewer": "Map",
|
||||||
"pinned-note": "Pinned note",
|
"pinned-note": "Pinned note",
|
||||||
"item-sheet": "Item"
|
"item-sheet": "Item",
|
||||||
|
"icon-source": "Choose an icon",
|
||||||
|
"foundry-icons": "Foundry icons"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,6 +44,11 @@
|
|||||||
"create": "Crear {section}", "submit": "Crear", "edit": "Editar", "save": "Guardar", "delete": "Eliminar", "saving": "Guardando...",
|
"create": "Crear {section}", "submit": "Crear", "edit": "Editar", "save": "Guardar", "delete": "Eliminar", "saving": "Guardando...",
|
||||||
"collapse-sidebar": "Contraer barra lateral", "expand-sidebar": "Expandir barra lateral"
|
"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": {
|
"states": {
|
||||||
"loading": "Cargando...", "loading-notes": "Cargando notas...", "empty-notes": "Aún no hay notas en esta campaña.",
|
"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.",
|
"empty-actors": "Aún no hay actores ni personajes.", "empty-items": "Aún no hay objetos en esta campaña.",
|
||||||
@@ -62,13 +67,17 @@
|
|||||||
"new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.",
|
"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",
|
"category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad",
|
||||||
"quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
|
"quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
|
||||||
"folder-toggle": "Muestra o oculta la carpeta {name}",
|
|
||||||
"sheet": {
|
"sheet": {
|
||||||
"icon": "Icono del objeto", "choose-icon": "Elegir tu propio icono", "change-icon": "Cambiar icono",
|
"icon": "Icono del objeto", "choose-icon": "Elegir tu propio icono", "change-icon": "Cambiar icono",
|
||||||
"uploading": "Subiendo...", "upload-error": "No se pudo subir este icono.",
|
"uploading": "Subiendo...", "upload-error": "No se pudo subir este icono.",
|
||||||
"foundry-icon": "Usar el icono de Foundry", "remove-icon": "Quitar el icono", "save-error": "No se pudo guardar este objeto.",
|
"foundry-icon": "Usar el icono de Foundry", "remove-icon": "Quitar el icono", "save-error": "No se pudo guardar este objeto.",
|
||||||
"no-description": "Sin descripción añadida."
|
"no-description": "Sin descripción añadida."
|
||||||
},
|
},
|
||||||
|
"icon-picker": {
|
||||||
|
"intro": "¿De dónde debe salir el icono de este objeto?",
|
||||||
|
"upload": "Subir icono", "upload-hint": "Elige una imagen de este dispositivo.",
|
||||||
|
"foundry": "Cargar desde Foundry", "foundry-hint": "Recorre los iconos que incluye tu mundo de Foundry."
|
||||||
|
},
|
||||||
"categories": {
|
"categories": {
|
||||||
"weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura",
|
"weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura",
|
||||||
"magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro"
|
"magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro"
|
||||||
@@ -101,6 +110,7 @@
|
|||||||
},
|
},
|
||||||
"character-sheet": {
|
"character-sheet": {
|
||||||
"title": "Hoja de personaje", "name": "Nombre del personaje", "class": "Clase", "subclass": "Subclase", "unset-class": "Clase sin definir",
|
"title": "Hoja de personaje", "name": "Nombre del personaje", "class": "Clase", "subclass": "Subclase", "unset-class": "Clase sin definir",
|
||||||
|
"tabs": { "abilities": "Características", "inventory": "Inventario", "traits": "Rasgos", "spells": "Conjuros" },
|
||||||
"level": "Nivel", "species": "Especie", "unset-species": "Especie sin definir", "edit": "Editar hoja", "cancel": "Cancelar",
|
"level": "Nivel", "species": "Especie", "unset-species": "Especie sin definir", "edit": "Editar hoja", "cancel": "Cancelar",
|
||||||
"saving": "Guardando...", "save": "Guardar hoja", "save-error": "No se pudo guardar esta hoja de personaje.", "photo": "Foto", "upload-photo": "Subir foto", "change-photo": "Cambiar foto", "remove-photo": "Quitar foto", "uploading-photo": "Subiendo...", "photo-error": "No se pudo subir esta foto.", "ability-scores": "Características", "proficiency-bonus": "Bonificador por competencia",
|
"saving": "Guardando...", "save": "Guardar hoja", "save-error": "No se pudo guardar esta hoja de personaje.", "photo": "Foto", "upload-photo": "Subir foto", "change-photo": "Cambiar foto", "remove-photo": "Quitar foto", "uploading-photo": "Subiendo...", "photo-error": "No se pudo subir esta foto.", "ability-scores": "Características", "proficiency-bonus": "Bonificador por competencia",
|
||||||
"combat": "Combate", "armor-class": "Clase de armadura", "speed": "Velocidad", "proficiencies": "Competencias",
|
"combat": "Combate", "armor-class": "Clase de armadura", "speed": "Velocidad", "proficiencies": "Competencias",
|
||||||
|
|||||||
@@ -3,6 +3,15 @@
|
|||||||
"link-expired": "El código de vinculación de Foundry no es válido, ha caducado o ya se ha usado.",
|
"link-expired": "El código de vinculación de Foundry no es válido, ha caducado o ya se ha usado.",
|
||||||
"world-already-linked": "Este mundo de Foundry ya está vinculado a otra campaña.",
|
"world-already-linked": "Este mundo de Foundry ya está vinculado a otra campaña.",
|
||||||
"actor-already-synced": "Otro actor de esta campaña ya está sincronizado con ese actor de Foundry.",
|
"actor-already-synced": "Otro actor de esta campaña ya está sincronizado con ese actor de Foundry.",
|
||||||
"item-already-synced": "Otro objeto de esta campaña ya está sincronizado con ese objeto de Foundry."
|
"item-already-synced": "Otro objeto de esta campaña ya está sincronizado con ese objeto de Foundry.",
|
||||||
|
"icons-unavailable": "Los iconos de Foundry no están disponibles: su bridge no está configurado o no es accesible ahora.",
|
||||||
|
"icons-no-world-url": "Esta campaña no tiene dirección del mundo de Foundry. Defínala en los ajustes de la campaña, en la pestaña de integraciones."
|
||||||
|
},
|
||||||
|
"icons": {
|
||||||
|
"path": "Carpeta de iconos",
|
||||||
|
"up": "Una carpeta arriba",
|
||||||
|
"loading": "Cargando iconos...",
|
||||||
|
"empty": "No hay iconos para elegir en esta carpeta.",
|
||||||
|
"load-more": "Cargar más iconos"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,5 +10,7 @@
|
|||||||
"create-map": "Crear mapa",
|
"create-map": "Crear mapa",
|
||||||
"map-viewer": "Mapa",
|
"map-viewer": "Mapa",
|
||||||
"pinned-note": "Nota fijada",
|
"pinned-note": "Nota fijada",
|
||||||
"item-sheet": "Objeto"
|
"item-sheet": "Objeto",
|
||||||
|
"icon-source": "Elegir icono",
|
||||||
|
"foundry-icons": "Iconos de Foundry"
|
||||||
}
|
}
|
||||||
|
|||||||
89
tests/character-sheet-tabs.test.js
Normal file
89
tests/character-sheet-tabs.test.js
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
// Tests for Syndria98/dragonroll#55: the character sheet splits its contents across bookmarks down
|
||||||
|
// the right edge (ability scores, inventory, traits, spells) instead of stacking every panel on one
|
||||||
|
// long page.
|
||||||
|
//
|
||||||
|
// The repository root installs no dependencies, so the window wiring is read from the sources the way
|
||||||
|
// tests/item-sheet-window.test.js and tests/settings-window.test.js do 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 read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||||
|
|
||||||
|
const sheetSource = read("frontend", "app", "components", "windows", "CharacterSheetWindow.vue");
|
||||||
|
const script = /<script setup>([\s\S]*?)<\/script>/.exec(sheetSource)?.[1] ?? "";
|
||||||
|
const template = /<template>([\s\S]*)<\/template>/.exec(sheetSource)?.[1] ?? "";
|
||||||
|
|
||||||
|
// The four bookmarks the issue asks for, in order.
|
||||||
|
test("the sheet declares the four tabs the issue splits the contents into", () => {
|
||||||
|
const array = /const tabs = \[([\s\S]*?)\];/.exec(script)?.[1] ?? "";
|
||||||
|
const keys = [...array.matchAll(/key:\s*['"](\w+)['"]/g)].map((m) => m[1]);
|
||||||
|
assert.deepEqual(keys, ["abilities", "inventory", "traits", "spells"]);
|
||||||
|
for (const key of keys) {
|
||||||
|
assert.ok(
|
||||||
|
new RegExp(`label:\\s*['"]campaigns\\.character-sheet\\.tabs\\.${key}['"]`).test(array),
|
||||||
|
`the ${key} tab must point at its own i18n key`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert.match(script, /const activeTab = ref\(['"]abilities['"]\)/, "the sheet opens on the ability scores tab");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the tabs sit on the right as a vertical bookmark rail", () => {
|
||||||
|
assert.match(template, /<nav class="sheet-tabs"[^>]*role="tablist"[^>]*aria-orientation="vertical"/);
|
||||||
|
assert.match(template, /v-for="tab in tabs"[\s\S]*?:aria-selected="activeTab === tab\.key"/);
|
||||||
|
const rail = /\.sheet-tabs\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
|
||||||
|
assert.match(rail, /flex-direction:\s*column/, "the bookmarks stack down the right edge");
|
||||||
|
// content column and rail sit side by side, the rail hugging the right
|
||||||
|
assert.match(sheetSource, /\.sheet-layout\s*\{[^}]*display:\s*flex[^}]*\}/, "content and rail share a row");
|
||||||
|
assert.match(sheetSource, /\.sheet-content\s*\{[^}]*flex:\s*1[^}]*\}/, "the content takes the room, the rail stays slim");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Each tab shows only its own panels; the rest are hidden with v-show so an in-progress edit is
|
||||||
|
// not thrown away when hopping between tabs.
|
||||||
|
function tabBody(key) {
|
||||||
|
const block = new RegExp(`<main v-show="activeTab === '${key}'"[\\s\\S]*?</main>`).exec(template)?.[0];
|
||||||
|
assert.ok(block, `expected a body for the ${key} tab`);
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
|
||||||
|
test("every tab shows only its own content and hides the others", () => {
|
||||||
|
const abilities = tabBody("abilities");
|
||||||
|
assert.match(abilities, /class="sheet-portrait"/, "the portrait stays with ability scores");
|
||||||
|
assert.match(abilities, /class="sheet-panel abilities-panel"/);
|
||||||
|
assert.match(abilities, /class="sheet-panel combat-panel"/, "combat rides with the ability scores");
|
||||||
|
for (const other of ["inventory-panel", "traits-panel", "spells-panel"]) {
|
||||||
|
assert.doesNotMatch(abilities, new RegExp(other));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [key, panel] of [["inventory", "inventory-panel"], ["traits", "traits-panel"], ["spells", "spells-panel"]]) {
|
||||||
|
const body = tabBody(key);
|
||||||
|
assert.ok(body.includes(panel), `the ${key} tab shows the ${panel}`);
|
||||||
|
assert.doesNotMatch(body, /class="sheet-portrait"/);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the panels are toggled, not unmounted, so editing on one tab and flipping away keeps the draft
|
||||||
|
assert.match(template, /v-show="activeTab === 'inventory'"/);
|
||||||
|
assert.match(template, /v-show="activeTab === 'traits'"/);
|
||||||
|
assert.match(template, /v-show="activeTab === 'spells'"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the tabs still edit and save through the existing sheet form", () => {
|
||||||
|
assert.match(tabBody("inventory"), /@click="addInventoryItem"/);
|
||||||
|
assert.match(tabBody("inventory"), /removeInventoryItem\(index\)/);
|
||||||
|
assert.match(tabBody("traits"), /v-model="form\.traits"/);
|
||||||
|
assert.match(tabBody("spells"), /v-model="form\.spells"/);
|
||||||
|
assert.match(tabBody("abilities"), /v-model\.number="form\.abilityScores\[stat\.key\]"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("every locale names the four tabs", () => {
|
||||||
|
for (const locale of ["en", "es", "ca"]) {
|
||||||
|
const sheet = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"))["character-sheet"];
|
||||||
|
for (const key of ["abilities", "inventory", "traits", "spells"]) {
|
||||||
|
assert.ok(sheet.tabs?.[key], `${locale} is missing campaigns.character-sheet.tabs.${key}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
444
tests/entry-folders.test.js
Normal file
444
tests/entry-folders.test.js
Normal 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}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
417
tests/foundry-actor-details.test.js
Normal file
417
tests/foundry-actor-details.test.js
Normal file
@@ -0,0 +1,417 @@
|
|||||||
|
// Tests for the D&D 5e details the system keeps as a reference to an embedded item
|
||||||
|
// (Syndria98/dragonroll#54). `system.details.background` and `system.details.race` are
|
||||||
|
// LocalDocumentFields: they hold the id of the actor's background / race item and never
|
||||||
|
// its name, and their `fallback` option hands the bare id back when that item is gone.
|
||||||
|
// Dragonroll holds names, so reading the id as a name and writing it back gave Foundry a
|
||||||
|
// background item that does not exist and a details reference resolving to nothing —
|
||||||
|
// adding a background in Foundry then failed.
|
||||||
|
//
|
||||||
|
// The backend mapper is plain CommonJS and is required directly. The Foundry module is
|
||||||
|
// loaded into a `node:vm` context holding stubbed Foundry globals with fake timers, like
|
||||||
|
// tests/foundry-sync-toggle.test.js: the characters Dragonroll answers with are applied
|
||||||
|
// to a stubbed actor, so the references it writes are observable.
|
||||||
|
//
|
||||||
|
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||||
|
|
||||||
|
const { test } = require("node:test");
|
||||||
|
const assert = require("node:assert/strict");
|
||||||
|
const fs = require("node:fs");
|
||||||
|
const path = require("node:path");
|
||||||
|
const vm = require("node:vm");
|
||||||
|
|
||||||
|
const MODULE_ID = "dragonroll-foundry";
|
||||||
|
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||||
|
|
||||||
|
const { foundryActorToCharacter } = require(path.join(__dirname, "..", "backend", "src", "services", "actor-foundry.js"));
|
||||||
|
|
||||||
|
// Foundry generates document ids as sixteen characters of its alphabet, digits included.
|
||||||
|
const ID_GONE = "aB3cD9eF1gH2iJ4k";
|
||||||
|
const ID_SOLDIER = "Kx7pQ2mR9vT4wZ8n";
|
||||||
|
const ID_HUMAN = "7QcL2fYh5Bd0Mn3s";
|
||||||
|
|
||||||
|
function foundryActor(details = {}, items = []) {
|
||||||
|
return { _id: "actor-1", name: "Thalia", type: "character", system: { details }, items };
|
||||||
|
}
|
||||||
|
|
||||||
|
test("a background carried as an item arrives by its name, not its id", () => {
|
||||||
|
const character = foundryActor(
|
||||||
|
{ background: ID_SOLDIER },
|
||||||
|
[{ _id: ID_SOLDIER, name: "Soldier", type: "background" }],
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(foundryActorToCharacter(character).background, "Soldier");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a background reference whose item is gone does not become a background", () => {
|
||||||
|
// The item was deleted, and `fallback: true` gives the id back instead.
|
||||||
|
const character = foundryActor({ background: ID_GONE }, []);
|
||||||
|
|
||||||
|
assert.equal(foundryActorToCharacter(character).background, "");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a background item takes the place of a reference that resolves to nothing", () => {
|
||||||
|
const character = foundryActor(
|
||||||
|
{ background: ID_GONE },
|
||||||
|
[{ _id: ID_SOLDIER, name: "Soldier", type: "background" }],
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(foundryActorToCharacter(character).background, "Soldier");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a plain-text background from an older system release is still a name", () => {
|
||||||
|
const character = foundryActor({ background: "Sailor" }, []);
|
||||||
|
|
||||||
|
assert.equal(foundryActorToCharacter(character).background, "Sailor");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the class, subclass and species references resolve the same way", () => {
|
||||||
|
const items = [
|
||||||
|
{ _id: ID_HUMAN, name: "Human", type: "race" },
|
||||||
|
{ _id: "cls1Id00000000", name: "Fighter", type: "class" },
|
||||||
|
{ _id: "sub1Id00000000", name: "Oracle", type: "subclass" },
|
||||||
|
];
|
||||||
|
const character = foundryActor(
|
||||||
|
{ race: ID_HUMAN, class: "cls1Id00000000", subclass: "sub1Id00000000" },
|
||||||
|
items,
|
||||||
|
);
|
||||||
|
|
||||||
|
const fields = foundryActorToCharacter(character);
|
||||||
|
assert.equal(fields.species, "Human");
|
||||||
|
assert.equal(fields.className, "Fighter");
|
||||||
|
assert.equal(fields.subclass, "Oracle");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a class reference that resolves to nothing falls back to the class item", () => {
|
||||||
|
const character = foundryActor(
|
||||||
|
{ class: ID_GONE, race: ID_GONE },
|
||||||
|
[{ _id: "cls1Id00000000", name: "Fighter", type: "class" }],
|
||||||
|
);
|
||||||
|
|
||||||
|
const fields = foundryActorToCharacter(character);
|
||||||
|
assert.equal(fields.className, "Fighter", "the class the actor carries, not the id");
|
||||||
|
assert.equal(fields.species, "", "and nothing to name the species from");
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- The Foundry module applies Dragonroll's character --------------------------
|
||||||
|
|
||||||
|
// A reference is either the id this sync wrote or the document the field resolves to.
|
||||||
|
function referenceId(actor, field) {
|
||||||
|
const value = actor.system.details?.[field];
|
||||||
|
return typeof value === "string" ? value : value?._id || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeStubItem(id, { name, type, system = {}, flags = {} }) {
|
||||||
|
return {
|
||||||
|
_id: id,
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
type,
|
||||||
|
system,
|
||||||
|
flags,
|
||||||
|
parent: { documentName: "Actor" },
|
||||||
|
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
||||||
|
toObject() {
|
||||||
|
return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: this.flags };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeDotted(target, data) {
|
||||||
|
for (const [key, value] of Object.entries(data)) {
|
||||||
|
const parts = key.split(".");
|
||||||
|
const last = parts.pop();
|
||||||
|
let node = target;
|
||||||
|
for (const part of parts) node = node[part] ??= {};
|
||||||
|
node[last] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let stubCounter = 0;
|
||||||
|
|
||||||
|
function makeStubActor(name, { type = "character", system = {}, flags = {}, items = [] } = {}) {
|
||||||
|
stubCounter += 1;
|
||||||
|
const id = `actor-${stubCounter}`;
|
||||||
|
const contents = items.map((item, index) => makeStubItem(item._id || `embedded-${stubCounter}-${index}`, item));
|
||||||
|
const actor = {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
type,
|
||||||
|
documentName: "Actor",
|
||||||
|
img: "icons/svg/mystery-man.svg",
|
||||||
|
system,
|
||||||
|
flags,
|
||||||
|
items: { contents },
|
||||||
|
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
||||||
|
async update(data) {
|
||||||
|
writeDotted(this, data);
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
async updateEmbeddedDocuments(documentName, updates) {
|
||||||
|
for (const update of updates) {
|
||||||
|
const item = contents.find((candidate) => candidate.id === update._id);
|
||||||
|
if (item) writeDotted(item, update);
|
||||||
|
}
|
||||||
|
return updates.map((update) => contents.find((candidate) => candidate.id === update._id));
|
||||||
|
},
|
||||||
|
async createEmbeddedDocuments(documentName, datas) {
|
||||||
|
const created = datas.map((data) => {
|
||||||
|
const item = makeStubItem(`embedded-${stubCounter}-${contents.length}`, data);
|
||||||
|
item.name = data.name;
|
||||||
|
item.type = data.type;
|
||||||
|
contents.push(item);
|
||||||
|
return item;
|
||||||
|
});
|
||||||
|
return created;
|
||||||
|
},
|
||||||
|
async deleteEmbeddedDocuments(documentName, ids) {
|
||||||
|
for (const id of ids) {
|
||||||
|
const index = contents.findIndex((item) => item.id === id);
|
||||||
|
if (index >= 0) contents.splice(index, 1);
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
},
|
||||||
|
toObject() {
|
||||||
|
return {
|
||||||
|
_id: this.id,
|
||||||
|
name: this.name,
|
||||||
|
type: this.type,
|
||||||
|
img: this.img,
|
||||||
|
flags: this.flags,
|
||||||
|
system: this.system,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A linked world with the actors it holds, answering `foundry/sync/characters` with the
|
||||||
|
// campaign's characters. Each one is applied to its Foundry actor on the next reconcile.
|
||||||
|
function makeWorld({ actors = [], remoteActors = [] } = {}) {
|
||||||
|
const state = {
|
||||||
|
hooks: new Map(),
|
||||||
|
registered: new Map(),
|
||||||
|
requests: [],
|
||||||
|
timers: new Map(),
|
||||||
|
nextTimerId: 1,
|
||||||
|
logs: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
|
||||||
|
const sandbox = {
|
||||||
|
console: {
|
||||||
|
log() {},
|
||||||
|
info() {},
|
||||||
|
warn: (...args) => state.logs.push(args.map(String).join(" ")),
|
||||||
|
error: (...args) => state.logs.push(args.map(String).join(" ")),
|
||||||
|
},
|
||||||
|
URL,
|
||||||
|
CONFIG: {},
|
||||||
|
window: { location: { origin: "http://vtt.test" } },
|
||||||
|
ui: { notifications: { info() {}, warn() {}, error() {} } },
|
||||||
|
Hooks: {
|
||||||
|
once(name, fn) { state.hooks.set(name, [fn]); },
|
||||||
|
on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); },
|
||||||
|
},
|
||||||
|
setTimeout: (fn, delay = 0) => {
|
||||||
|
const timerId = state.nextTimerId++;
|
||||||
|
state.timers.set(timerId, { fn, delay });
|
||||||
|
return timerId;
|
||||||
|
},
|
||||||
|
clearTimeout: (timerId) => state.timers.delete(timerId),
|
||||||
|
setInterval: () => 0,
|
||||||
|
clearInterval: () => {},
|
||||||
|
fetch: async (url, options = {}) => {
|
||||||
|
const href = String(url);
|
||||||
|
state.requests.push({ href, method: options.method, body: options.body ? JSON.parse(options.body) : null });
|
||||||
|
if (href.includes("foundry/sync/characters")) return { ok: true, status: 200, json: async () => ({ status: "ok", actors: remoteActors }) };
|
||||||
|
if (href.includes("foundry/sync/items")) return { ok: true, status: 200, json: async () => ({ status: "ok", items: [] }) };
|
||||||
|
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
|
||||||
|
},
|
||||||
|
Item: { async create() { return null; } },
|
||||||
|
Actor: {
|
||||||
|
async create(data) {
|
||||||
|
const actor = makeStubActor(data.name, {
|
||||||
|
type: data.type,
|
||||||
|
system: structuredClone(data.system || {}),
|
||||||
|
flags: structuredClone(data.flags || {}),
|
||||||
|
items: (data.items || []).map((item) => ({ name: item.name, type: item.type, system: item.system })),
|
||||||
|
});
|
||||||
|
actors.push(actor);
|
||||||
|
return actor;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
sandbox.game = {
|
||||||
|
user: { isGM: true },
|
||||||
|
world: { id: "world-1", title: "Test World" },
|
||||||
|
system: { id: "dnd5e" },
|
||||||
|
modules: { get: () => ({}) },
|
||||||
|
actors: { contents: actors, get: (actorId) => actors.find((actor) => actor.id === actorId) },
|
||||||
|
items: { contents: [], get: () => null },
|
||||||
|
folders: { contents: [], get: () => null },
|
||||||
|
settings: {
|
||||||
|
register(module, key, definition) {
|
||||||
|
state.registered.set(key, definition);
|
||||||
|
if (!(key in settingsStore)) settingsStore[key] = definition.default;
|
||||||
|
},
|
||||||
|
get(module, key) { return settingsStore[key]; },
|
||||||
|
async set(module, key, value) {
|
||||||
|
settingsStore[key] = value;
|
||||||
|
await state.registered.get(key)?.onChange?.(value);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
vm.createContext(sandbox);
|
||||||
|
vm.runInContext(read("dragonroll-foundry", "scripts", "api.js"), sandbox);
|
||||||
|
|
||||||
|
state.game = sandbox.game;
|
||||||
|
state.actor = (actorId) => actors.find((actor) => actor.id === actorId);
|
||||||
|
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
|
||||||
|
|
||||||
|
// World start: the actors are pushed, then the campaign's characters are applied.
|
||||||
|
state.start = async () => {
|
||||||
|
await state.fire("init");
|
||||||
|
await state.fire("ready");
|
||||||
|
await state.runTimers();
|
||||||
|
return state;
|
||||||
|
};
|
||||||
|
|
||||||
|
state.fire = async (name, ...args) => {
|
||||||
|
for (const handler of state.hooks.get(name) || []) await handler(...args);
|
||||||
|
await drain();
|
||||||
|
};
|
||||||
|
state.runTimers = async () => {
|
||||||
|
for (let round = 0; round < 6; round += 1) {
|
||||||
|
if (!state.timers.size && round > 2) break;
|
||||||
|
const due = [...state.timers.values()];
|
||||||
|
state.timers.clear();
|
||||||
|
for (const timer of due) await timer.fn();
|
||||||
|
await drain();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
state.itemNames = (actor) => actor.items.contents.map((item) => [item.type, item.name]);
|
||||||
|
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The campaign's character for `actor`, holding what Dragonroll keeps for it.
|
||||||
|
function campaignCharacter(actor, over = {}) {
|
||||||
|
return {
|
||||||
|
_id: "dr-actor-1",
|
||||||
|
name: "Thalia",
|
||||||
|
type: "character",
|
||||||
|
species: "",
|
||||||
|
className: "",
|
||||||
|
subclass: "",
|
||||||
|
level: 1,
|
||||||
|
background: "",
|
||||||
|
challengeRating: "",
|
||||||
|
description: "",
|
||||||
|
image: "",
|
||||||
|
abilityScores: {},
|
||||||
|
armorClass: 10,
|
||||||
|
speed: 30,
|
||||||
|
traits: "",
|
||||||
|
proficiencies: "",
|
||||||
|
spells: "",
|
||||||
|
inventory: [],
|
||||||
|
foundryActorId: actor?.id ?? null,
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test("Dragonroll's background becomes the actor's background item, referenced by id", async () => {
|
||||||
|
const actor = makeStubActor("Thalia", {
|
||||||
|
system: { details: { background: "" } },
|
||||||
|
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
|
||||||
|
});
|
||||||
|
const world = await makeWorld({
|
||||||
|
actors: [actor],
|
||||||
|
remoteActors: [campaignCharacter(actor, { background: "Soldier" })],
|
||||||
|
}).start();
|
||||||
|
|
||||||
|
const background = actor.items.contents.find((item) => item.type === "background");
|
||||||
|
assert.ok(background, "the character's background stands in Foundry as an item");
|
||||||
|
assert.equal(background.name, "Soldier");
|
||||||
|
assert.equal(referenceId(actor, "background"), background.id, "its details reference points at the item");
|
||||||
|
assert.equal(actor.system.details.background, background.id);
|
||||||
|
assert.deepEqual(world.logs, [], "applying the character did not warn");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the background an earlier sync invented is taken back out", async () => {
|
||||||
|
// What the bug left behind: an item named after the id the details field held, next to
|
||||||
|
// the real background, and a reference the old sync overwrote with that id.
|
||||||
|
const actor = makeStubActor("Thalia", {
|
||||||
|
system: { details: { background: ID_GONE } },
|
||||||
|
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
|
||||||
|
items: [
|
||||||
|
{ _id: ID_SOLDIER, name: "Soldier", type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
|
||||||
|
{ _id: "item-bogus", name: ID_GONE, type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const world = await makeWorld({
|
||||||
|
actors: [actor],
|
||||||
|
remoteActors: [campaignCharacter(actor, { background: "Soldier" })],
|
||||||
|
}).start();
|
||||||
|
|
||||||
|
assert.deepEqual(world.itemNames(actor), [["background", "Soldier"]], "only the real background is left");
|
||||||
|
assert.equal(referenceId(actor, "background"), ID_SOLDIER, "and the reference resolves to it");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a background taken off in Dragonroll clears the reference", async () => {
|
||||||
|
const actor = makeStubActor("Thalia", {
|
||||||
|
system: { details: { background: ID_SOLDIER } },
|
||||||
|
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
|
||||||
|
items: [
|
||||||
|
{ _id: ID_SOLDIER, name: "Soldier", type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const world = await makeWorld({ actors: [actor], remoteActors: [campaignCharacter(actor)] }).start();
|
||||||
|
|
||||||
|
assert.deepEqual(world.itemNames(actor), [], "the background item went with it");
|
||||||
|
assert.equal(referenceId(actor, "background"), "", "and no reference is left pointing at nothing");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a species never lands in the details reference as a name", async () => {
|
||||||
|
const actor = makeStubActor("Thalia", {
|
||||||
|
// A species picked in the sheet: dnd5e made the race item and referenced it by id.
|
||||||
|
system: { details: { race: ID_HUMAN } },
|
||||||
|
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
|
||||||
|
items: [{ _id: ID_HUMAN, name: "Human", type: "race", flags: { [MODULE_ID]: { syncedItem: true } } }],
|
||||||
|
});
|
||||||
|
await makeWorld({
|
||||||
|
actors: [actor],
|
||||||
|
remoteActors: [campaignCharacter(actor, { species: "Human", background: "Soldier" })],
|
||||||
|
}).start();
|
||||||
|
|
||||||
|
assert.equal(referenceId(actor, "race"), ID_HUMAN, "the species reference still points at the race item");
|
||||||
|
assert.notEqual(actor.system.details.race, "Human", "a name in it would resolve to nothing");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a species the world keeps as plain text is left to the world", async () => {
|
||||||
|
// An actor migrated from an older system release: no race item, the name is what the
|
||||||
|
// field holds, and Dragonroll has nothing to reference.
|
||||||
|
const actor = makeStubActor("Thalia", {
|
||||||
|
system: { details: { race: "Human" } },
|
||||||
|
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
|
||||||
|
});
|
||||||
|
await makeWorld({
|
||||||
|
actors: [actor],
|
||||||
|
remoteActors: [campaignCharacter(actor, { species: "Human" })],
|
||||||
|
}).start();
|
||||||
|
|
||||||
|
assert.equal(actor.system.details.race, "Human", "the text the sheet reads is kept as it was");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a character made in Dragonroll references the background it is created with", async () => {
|
||||||
|
const world = await makeWorld({ actors: [], remoteActors: [campaignCharacter(null, { background: "Soldier" })] }).start();
|
||||||
|
|
||||||
|
const [actor] = world.game.actors.contents;
|
||||||
|
assert.ok(actor, "the campaign's character was made in this world");
|
||||||
|
const background = actor.items.contents.find((item) => item.type === "background");
|
||||||
|
assert.ok(background, "created together with its background item");
|
||||||
|
assert.equal(background.name, "Soldier");
|
||||||
|
assert.equal(referenceId(actor, "background"), background.id, "referenced by that item's id, never its name");
|
||||||
|
});
|
||||||
170
tests/foundry-icon-picker.test.js
Normal file
170
tests/foundry-icon-picker.test.js
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
// Tests for Syndria98/dragonroll#65: picking an item's icon opens a window that asks
|
||||||
|
// where the icon comes from — upload one from this device, or load one from the icon
|
||||||
|
// library the linked Foundry world ships in its data directory's `icons/` folder.
|
||||||
|
// That library runs into the thousands, so it is listed one folder per request, with
|
||||||
|
// its icons paged and its thumbnails lazy to load.
|
||||||
|
//
|
||||||
|
// The icon listing helpers are a pure CommonJS service, so they are required and called
|
||||||
|
// directly. The windows and the bridge live in files this repository installs no
|
||||||
|
// dependencies for, so those checks read the sources, like tests/map-viewer.test.js does.
|
||||||
|
//
|
||||||
|
// 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 read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||||
|
const iconService = require(path.join(__dirname, "..", "backend", "src", "services", "foundry-icons"));
|
||||||
|
|
||||||
|
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
|
||||||
|
const itemWindowSource = read("frontend", "app", "components", "windows", "ItemSheetWindow.vue");
|
||||||
|
const sourceWindowSource = read("frontend", "app", "components", "windows", "ItemIconSourceWindow.vue");
|
||||||
|
const foundryIconsSource = read("frontend", "app", "components", "windows", "FoundryIconPickerWindow.vue");
|
||||||
|
const foundryRouteSource = read("backend", "src", "routes", "foundry.js");
|
||||||
|
const bridgeSource = read("dragonroll-foundry", "bridge", "server.js");
|
||||||
|
|
||||||
|
// --- The listing service: what the browser may ask for, and what it gets back ------
|
||||||
|
|
||||||
|
test("icon listings always stay inside Foundry's icon root", () => {
|
||||||
|
assert.equal(iconService.ICON_ROOT, "icons");
|
||||||
|
assert.equal(iconService.normalizeIconDirectory(""), "icons");
|
||||||
|
assert.equal(iconService.normalizeIconDirectory(undefined), "icons");
|
||||||
|
assert.equal(iconService.normalizeIconDirectory("/icons/svg/"), "icons/svg");
|
||||||
|
assert.equal(iconService.normalizeIconDirectory("icons/sfdcc/axes"), "icons/sfdcc/axes");
|
||||||
|
assert.equal(iconService.normalizeIconDirectory("icons/./svg"), "icons/svg");
|
||||||
|
// nothing that leaves `icons/` is a folder this route will list
|
||||||
|
assert.equal(iconService.normalizeIconDirectory("icons/../secret"), null);
|
||||||
|
assert.equal(iconService.normalizeIconDirectory("../etc"), null);
|
||||||
|
assert.equal(iconService.normalizeIconDirectory("systems/dnd5e/icons"), null);
|
||||||
|
assert.equal(iconService.parentIconDirectory("icons/svg/axes"), "icons/svg");
|
||||||
|
assert.equal(iconService.parentIconDirectory("icons"), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("icons are listed a page at a time, bounded", () => {
|
||||||
|
assert.deepEqual(iconService.readIconListingPage({}), { limit: iconService.DEFAULT_ICON_PAGE_SIZE, offset: 0 });
|
||||||
|
assert.deepEqual(iconService.readIconListingPage({ limit: "20", offset: "240" }), { limit: 20, offset: 240 });
|
||||||
|
// a caller cannot ask for the whole library at once, or for a page before the first
|
||||||
|
assert.equal(iconService.readIconListingPage({ limit: "99999" }).limit, iconService.MAX_ICON_PAGE_SIZE);
|
||||||
|
assert.equal(iconService.readIconListingPage({ offset: "-10" }).offset, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("only image files become icons, and they load from the world's own address", () => {
|
||||||
|
const listing = iconService.shapeIconListing({
|
||||||
|
base: "https://vtt.example.com/",
|
||||||
|
dir: "icons/svg",
|
||||||
|
listing: {
|
||||||
|
directories: ["icons/svg/creature", "icons/svg/creature", "icons/svg"],
|
||||||
|
files: ["icons/svg/dice.svg", "icons/svg/sword.png", "icons/svg/readme.txt", "stray.md"],
|
||||||
|
offset: 0,
|
||||||
|
next: 120,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(listing.dir, "icons/svg");
|
||||||
|
assert.equal(listing.parent, "icons");
|
||||||
|
assert.deepEqual(listing.folders.map((folder) => folder.path), ["icons/svg/creature"]);
|
||||||
|
assert.deepEqual(listing.folders.map((folder) => folder.name), ["creature"]);
|
||||||
|
assert.deepEqual(listing.files.map((icon) => icon.path), ["icons/svg/dice.svg", "icons/svg/sword.png"]);
|
||||||
|
assert.equal(listing.files[0].name, "dice.svg");
|
||||||
|
assert.equal(listing.files[0].url, "https://vtt.example.com/icons/svg/dice.svg");
|
||||||
|
assert.equal(listing.next, 120);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an icon path with spaces still gives the browser a loadable url", () => {
|
||||||
|
assert.equal(
|
||||||
|
iconService.joinFoundryAssetUrl("http://vtt.test:30000", "icons/sfdcc/axes/halberd sword.svg"),
|
||||||
|
"http://vtt.test:30000/icons/sfdcc/axes/halberd%20sword.svg"
|
||||||
|
);
|
||||||
|
assert.equal(iconService.joinFoundryAssetUrl("", "icons/svg/dice.svg"), "");
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- The backend route ------------------------------------------------------------
|
||||||
|
|
||||||
|
test("the foundry proxy lists one icon folder for one of the caller's campaigns", () => {
|
||||||
|
assert.match(foundryRouteSource, /router\.get\(["']\/icons["'], async \(req, res\)/);
|
||||||
|
const route = /router\.get\(["']\/icons[\s\S]*?module\.exports/.exec(foundryRouteSource)?.[0] ?? foundryRouteSource;
|
||||||
|
// the campaign is where the world address is kept, so it has to be the caller's own
|
||||||
|
assert.match(route, /findOwnedCampaign\(req\.query\.campaign, req\.user\.id\)/);
|
||||||
|
assert.match(foundryRouteSource, /Campaign\.findOne\(\{\s*_id:\s*campaignId,\s*createdBy:\s*userId\s*\}\)/);
|
||||||
|
assert.match(route, /campaign\.settings\?\.integrations\?\.foundryUrl/);
|
||||||
|
assert.match(route, /requestFoundry\(`api\/icons\?\$\{query\}`\)/);
|
||||||
|
// a folder outside the icon root is refused before it reaches the Foundry host
|
||||||
|
assert.match(route, /const dir = normalizeIconDirectory\(req\.query\.dir\);/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- The bridge on the Foundry host ------------------------------------------------
|
||||||
|
|
||||||
|
test("the bridge lists a core icon folder and never leaves the icon root", () => {
|
||||||
|
assert.match(bridgeSource, /const dataPath = \(process\.env\.DRAGONROLL_FOUNDRY_DATA_PATH \|\| ""\)\.trim\(\);/);
|
||||||
|
assert.match(bridgeSource, /if \(pathname === "\/api\/icons"\) return sendIconListing\(request, response\);/);
|
||||||
|
assert.match(bridgeSource, /if \(!dataPath\) return sendJson\(response, 503, \{ status: "error", msg: "foundry\.errors\.icons-unavailable" \}\);/);
|
||||||
|
const normalize = /function normalizeIconDirectory\(input\) \{[\s\S]*?\n\}/.exec(bridgeSource)?.[0] ?? "";
|
||||||
|
assert.match(normalize, /segments\.includes\("\.\."\) \|\| segments\[0\] !== iconRoot/);
|
||||||
|
// the answer is one folder plus the offset of the next page of its icons
|
||||||
|
assert.match(bridgeSource, /directories\.sort\(\(a, b\) => a\.localeCompare\(b\)\);/);
|
||||||
|
assert.match(bridgeSource, /const page = files\.slice\(offset, offset \+ limit\);/);
|
||||||
|
assert.match(bridgeSource, /next: offset \+ page\.length < files\.length \? offset \+ page\.length : null,/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- The windows -------------------------------------------------------------------
|
||||||
|
|
||||||
|
test("choosing an icon opens its own window from the item sheet", () => {
|
||||||
|
assert.match(windowDefsSource, /item_icon_source:\s*{\s*title:[^}]*ItemIconSourceWindow\.vue/s);
|
||||||
|
assert.match(windowDefsSource, /foundry_icons:\s*{\s*title:[^}]*FoundryIconPickerWindow\.vue/s);
|
||||||
|
// the item window asks where the icon comes from instead of opening a file dialog
|
||||||
|
assert.match(itemWindowSource, /CreateChildWindow\(id, ['"]item_icon_source['"]/);
|
||||||
|
assert.doesNotMatch(itemWindowSource, /type="file"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the icon source window offers uploading and Foundry, and uploads the local file", () => {
|
||||||
|
assert.match(sourceWindowSource, /\$t\(['"]campaigns\.item\.icon-picker\.upload['"]\)/);
|
||||||
|
assert.match(sourceWindowSource, /\$t\(['"]campaigns\.item\.icon-picker\.foundry['"]\)/);
|
||||||
|
// upload: a local file, sent through the item route like the character sheet does its photo
|
||||||
|
assert.match(sourceWindowSource, /type="file" accept="image\/\*"/);
|
||||||
|
assert.match(sourceWindowSource, /\/item\/upload-image\?item=\$\{itemId\}/);
|
||||||
|
assert.match(sourceWindowSource, /formData\.append\(['"]image['"], file\)/);
|
||||||
|
// and it hands the item over to the icon browser, as its child window
|
||||||
|
assert.match(sourceWindowSource, /CreateChildWindow\(id, ['"]foundry_icons['"]/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the icon browser browses the world's icons folder by folder", () => {
|
||||||
|
assert.match(foundryIconsSource, /\/foundry\/icons\?\$\{params\.toString\(\)\}/);
|
||||||
|
// one folder per request: navigating a folder asks for it, and going up asks for its parent
|
||||||
|
assert.match(foundryIconsSource, /Load\(ICON_ROOT\)/);
|
||||||
|
assert.match(foundryIconsSource, /@click="Load\(folder\.path\)"/);
|
||||||
|
assert.match(foundryIconsSource, /Load\(listing\.value\.parent \|\| ICON_ROOT\)/);
|
||||||
|
// lazy in every way that matters: a page of icons at a time, thumbnails fetched when seen
|
||||||
|
assert.match(foundryIconsSource, /if \(offset\) params\.set\(['"]offset['"], String\(offset\)\)/);
|
||||||
|
assert.match(foundryIconsSource, /@click="Load\(listing\.dir, listing\.next\)"/);
|
||||||
|
assert.match(foundryIconsSource, /loading="lazy"/);
|
||||||
|
// picking an icon stores the world's url and tells the item window about it
|
||||||
|
assert.match(foundryIconsSource, /Server\(\)\.post\(['"]\/item\/update['"], \{ id: itemId, image: icon\.url \}\)/);
|
||||||
|
assert.match(foundryIconsSource, /emitter\.emit\(['"]campaign-entry-updated['"], \{ entityType: ['"]item['"], entry: response\.data\.item \}\)/);
|
||||||
|
assert.match(foundryIconsSource, /ClearWindow\(\{ type: ['"]item_icon_source['"] \}\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Strings -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
test("every locale names the icon windows and their controls", () => {
|
||||||
|
for (const locale of ["en", "es", "ca"]) {
|
||||||
|
const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json"));
|
||||||
|
for (const key of ["icon-source", "foundry-icons"]) {
|
||||||
|
assert.ok(windows[key], `${locale} is missing the ${key} window title`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
|
||||||
|
for (const key of ["intro", "upload", "upload-hint", "foundry", "foundry-hint"]) {
|
||||||
|
assert.ok(campaigns.item?.["icon-picker"]?.[key], `${locale} is missing campaigns.item.icon-picker.${key}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const foundry = JSON.parse(read("frontend", "i18n", "locales", locale, "foundry.json"));
|
||||||
|
for (const key of ["loading", "empty", "load-more", "up"]) {
|
||||||
|
assert.ok(foundry.icons?.[key], `${locale} is missing foundry.icons.${key}`);
|
||||||
|
}
|
||||||
|
for (const key of ["icons-unavailable", "icons-no-world-url"]) {
|
||||||
|
assert.ok(foundry.errors?.[key], `${locale} is missing foundry.errors.${key}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
69
tests/item-entry-display.test.js
Normal file
69
tests/item-entry-display.test.js
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
// Tests for Syndria98/dragonroll#53: the item row in the campaign sidebar dropped its "SYNCED"
|
||||||
|
// text badge and now leads with the item's own icon on the left of the entry.
|
||||||
|
//
|
||||||
|
// The repository root installs no dependencies, so these read the sidebar component the way
|
||||||
|
// tests/sidebar-entity-entry.test.js does — the checks are about the markup and style of the row.
|
||||||
|
//
|
||||||
|
// 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 source = fs.readFileSync(
|
||||||
|
path.join(__dirname, "..", "frontend", "app", "components", "partials", "ContentSidebar.vue"),
|
||||||
|
"utf8"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The block that renders the item rows, from the items section down to its closing template. The
|
||||||
|
// items section is followed by the maps section (`v-else`), so the first `</template>` that leads
|
||||||
|
// there ends it; the inner `v-for` close is followed by another close, not by `v-else`.
|
||||||
|
const itemSection =
|
||||||
|
/<template v-else-if="activeSection === 'items'">([\s\S]*?)<\/template>\s*\n\s*<template v-else>/.exec(source)?.[1] ?? "";
|
||||||
|
|
||||||
|
// `selector` is inserted verbatim, so escape the `.` of a class combination. Comments are dropped:
|
||||||
|
// they explain a rule, they are not part of it.
|
||||||
|
function ruleFor(selector) {
|
||||||
|
const rule = new RegExp(`\\.${selector}\\s*\\{([^}]*)\\}`).exec(source)?.[0];
|
||||||
|
return rule?.replace(/\/\*[\s\S]*?\*\//g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
test("the item entry no longer shows the SYNCED text", () => {
|
||||||
|
assert.ok(itemSection, "expected to find the items section of the sidebar");
|
||||||
|
assert.doesNotMatch(itemSection, /campaigns\.synced/, "the item row must not render the synced text");
|
||||||
|
assert.doesNotMatch(itemSection, /entity-entry-sync/, "the item row must not render the synced badge");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the item entry shows the item's image on the left when it has one", () => {
|
||||||
|
// the icon renders only for an item that carries an image, resolved through the helper...
|
||||||
|
assert.match(
|
||||||
|
itemSection,
|
||||||
|
/<span v-if="row\.item\.image" class="entity-entry-image"[\s\S]*?<img :src="itemImageUrl\(row\.item\.image\)"/
|
||||||
|
);
|
||||||
|
// ...and on the left: it stands before the name in the row markup.
|
||||||
|
assert.ok(
|
||||||
|
itemSection.indexOf("entity-entry-image") < itemSection.indexOf("entity-entry-name"),
|
||||||
|
"the item image must stand to the left of the name"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the item entry lays the icon out beside the name", () => {
|
||||||
|
const title = ruleFor("entity-entry-title");
|
||||||
|
assert.ok(title, "expected a .entity-entry-title style rule");
|
||||||
|
assert.match(title, /display:\s*flex/, "the icon and the name sit side by side");
|
||||||
|
|
||||||
|
const image = ruleFor("entity-entry-image");
|
||||||
|
assert.ok(image, "expected a .entity-entry-image style rule");
|
||||||
|
assert.match(image, /overflow:\s*hidden/, "the icon is clipped to its box");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an item image resolves like the item window: uploads from /public, full URLs as they are", () => {
|
||||||
|
assert.match(source, /import Server, \{ getBaseUrl \} from ['"]~\/services\/Server['"]/);
|
||||||
|
|
||||||
|
const resolver = /function itemImageUrl\(image\)\s*\{[\s\S]*?\n\}/.exec(source)?.[0] ?? "";
|
||||||
|
assert.ok(resolver, "expected an itemImageUrl helper");
|
||||||
|
assert.match(resolver, /https\?:/, "a full http(s) URL loads as it is");
|
||||||
|
assert.match(resolver, /data:/, "a data URI loads as it is");
|
||||||
|
assert.match(resolver, /\$\{getBaseUrl\(\)\}\/public\//, "an uploaded filename resolves as a /public file");
|
||||||
|
});
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
// Tests for item folders following the Foundry world into the campaign
|
// Tests for item folders following the Foundry world into the campaign
|
||||||
// (Syndria98/dragonroll#44): the world's item directory is grouped into folders, and
|
// (Syndria98/dragonroll#44): the world's item directory is grouped into folders, and
|
||||||
// Dragonroll mirrors that tree as Folders of target 'item' and files the synced items
|
// Dragonroll mirrors that tree as Folders of target 'item' and files the synced items
|
||||||
// in them, so its item list reads like the world's.
|
// in them, so its item list reads like the world's. And for those folders' colours
|
||||||
|
// going both ways (Syndria98/dragonroll#57): the world's colour arrives with its tree,
|
||||||
|
// and the one the campaign picks travels back on the folder list the module reads.
|
||||||
//
|
//
|
||||||
// The repository root installs no dependencies, so each side is loaded the way the
|
// The repository root installs no dependencies, so each side is loaded the way the
|
||||||
// other tests do it. The sync route runs against a stubbed `require` (express,
|
// other tests do it. The sync route runs against a stubbed `require` (express,
|
||||||
@@ -120,14 +122,19 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
|
|||||||
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
|
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
|
||||||
};
|
};
|
||||||
const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId };
|
const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId };
|
||||||
|
// Every row belongs to the campaign the sync token belongs to, like every real row
|
||||||
|
// does: the sync looks its rows up by campaign, so a seeded row without one would be
|
||||||
|
// invisible to it and a test would pass without touching what it means to check.
|
||||||
|
const seeded = (rows = []) => rows.map((row) => ({ campaign: campaign._id, ...row }));
|
||||||
const models = {
|
const models = {
|
||||||
"../models/Actor": fakeModel("actor", seed.actors),
|
"../models/Actor": fakeModel("actor", seeded(seed.actors)),
|
||||||
"../models/Item": fakeModel("item", seed.items),
|
"../models/Item": fakeModel("item", seeded(seed.items)),
|
||||||
"../models/Folder": fakeModel("folder", seed.folders),
|
"../models/Folder": fakeModel("folder", seeded(seed.folders)),
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireStub = (id) => {
|
const requireStub = (id) => {
|
||||||
if (id === "express") return { Router: () => router };
|
if (id === "express") return { Router: () => router };
|
||||||
|
if (id.startsWith("node:")) return require(id); // crypto: the sync token is hashed, not stubbed
|
||||||
if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 };
|
if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 };
|
||||||
if (id === "../models/Campaign") return { findOne: async () => campaign };
|
if (id === "../models/Campaign") return { findOne: async () => campaign };
|
||||||
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
|
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
|
||||||
@@ -290,16 +297,86 @@ 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);
|
assert.equal(sync.models["../models/Item"].rows[0].folder, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("item folders stay out of the note tree", () => {
|
test("a folder coloured in the world is coloured in the campaign", async () => {
|
||||||
// The note routes share the Folder model, so each of them asks for "anything but
|
const sync = loadSyncRoute();
|
||||||
// item": note folders made before the target field existed keep matching that.
|
|
||||||
|
await sync.call("POST /sync/item-snapshot", {
|
||||||
|
worldId: "world-1",
|
||||||
|
items: [],
|
||||||
|
folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null, color: "#7f00ff" }],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(sync.models["../models/Folder"].rows[0].color, "#7f00ff");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a folder the world leaves uncoloured takes the campaign's colour off", async () => {
|
||||||
|
const sync = loadSyncRoute({
|
||||||
|
seed: {
|
||||||
|
folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons", color: "#7f00ff" }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await sync.call("POST /sync/item-snapshot", {
|
||||||
|
worldId: "world-1",
|
||||||
|
items: [],
|
||||||
|
folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null, color: null }],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(sync.models["../models/Folder"].rows[0].color, null, "the world has no colour to show, so neither does the campaign");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a module that says nothing about colours leaves the campaign's colour alone", async () => {
|
||||||
|
const sync = loadSyncRoute({
|
||||||
|
seed: {
|
||||||
|
folders: [{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons", color: "#7f00ff" }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// A tree pushed by a module that knows folders but not their colours: no colour at all.
|
||||||
|
await sync.call("POST /sync/snapshot", {
|
||||||
|
worldId: "world-1",
|
||||||
|
actors: [],
|
||||||
|
items: [],
|
||||||
|
folders: [{ id: "folder-melee", name: "Melee Weapons", parent: null }],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(sync.models["../models/Folder"].rows[0].color, "#7f00ff");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the folder list the world reads back carries the colours the campaign picked", async () => {
|
||||||
|
const sync = loadSyncRoute({
|
||||||
|
seed: {
|
||||||
|
folders: [
|
||||||
|
{ _id: "folder-1", target: "item", foundryFolderId: "folder-melee", name: "Melee Weapons", color: "#0080ff" },
|
||||||
|
{ _id: "folder-2", target: "item", name: "Homebrew" },
|
||||||
|
{ _id: "folder-3", name: "Chapter 1" },
|
||||||
|
],
|
||||||
|
items: [{ _id: "item-1", name: "Longsword", foundryItemId: "item-1", folder: "folder-1" }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await sync.call("GET /sync/items");
|
||||||
|
|
||||||
|
assert.equal(response.status, "ok");
|
||||||
|
assert.equal(response.items.length, 1);
|
||||||
|
const coloured = response.folders.find((folder) => folder._id === "folder-1");
|
||||||
|
assert.equal(coloured.foundryFolderId, "folder-melee", "the world's folder to write the colour back to");
|
||||||
|
assert.equal(coloured.color, "#0080ff");
|
||||||
|
assert.ok(!response.folders.some((folder) => folder._id === "folder-3"), "only the item list's folders travel back");
|
||||||
|
});
|
||||||
|
|
||||||
|
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"]) {
|
for (const route of ["note.js", "folder.js"]) {
|
||||||
const source = read("backend", "src", "routes", route);
|
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`);
|
assert.ok(listings.length, `${route} lists folders`);
|
||||||
for (const listing of listings) {
|
const filtered = source.match(/Folder\.find\(\{[^{]*Folder\.filterForTarget\((?:'note'|target)\)/g) ?? [];
|
||||||
assert.match(listing, /target:\s*\{\s*\$ne:\s*['"]item['"]\s*\}/, `${route} leaks item folders: ${listing}`);
|
assert.equal(filtered.length, listings.length, `${route} has a folder listing that names no campaign list`);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -318,15 +395,40 @@ function makeWorld() {
|
|||||||
registered: new Map(),
|
registered: new Map(),
|
||||||
requests: [],
|
requests: [],
|
||||||
timers: new Map(),
|
timers: new Map(),
|
||||||
|
intervals: new Map(),
|
||||||
|
// What Dragonroll answers a folder reconcile with: the campaign's folders and the
|
||||||
|
// colours its user gave them.
|
||||||
|
remoteFolders: [],
|
||||||
nextTimerId: 1,
|
nextTimerId: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Foundry's `update` takes dotted paths ("flags.dragonroll-foundry.itemId"); an
|
||||||
|
// embedded update names the row to write them on, so `_id` is not a path to set.
|
||||||
|
function writeFoundryPaths(target, data) {
|
||||||
|
for (const [key, value] of Object.entries(data)) {
|
||||||
|
if (key === "_id") continue;
|
||||||
|
const parts = key.split(".");
|
||||||
|
const last = parts.pop();
|
||||||
|
let node = target;
|
||||||
|
for (const part of parts) node = node[part] ??= {};
|
||||||
|
node[last] = value;
|
||||||
|
}
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A Folder document, plain data and the `update` both the GM and Dragonroll write with.
|
||||||
|
const makeFolder = (id, name, over = {}) => ({
|
||||||
|
id, name, type: "Item", parent: null, color: null, documentName: "Folder",
|
||||||
|
async update(data) { return writeFoundryPaths(this, data); },
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
const folders = [
|
const folders = [
|
||||||
{ id: "folder-melee", name: "Melee Weapons", type: "Item", parent: null, documentName: "Folder" },
|
makeFolder("folder-melee", "Melee Weapons", { color: "#8b0000" }),
|
||||||
{ id: "folder-ranged", name: "Ranged Weapons", type: "Item", parent: "folder-melee", documentName: "Folder" },
|
makeFolder("folder-ranged", "Ranged Weapons", { parent: "folder-melee" }),
|
||||||
// An actor's own inventory folder: it hangs off the actor, not the world.
|
// An actor's own inventory folder: it hangs off the actor, not the world.
|
||||||
{ id: "folder-carried", name: "Carried", type: "Item", parent: { id: "actor-1", documentName: "Actor" }, documentName: "Folder" },
|
makeFolder("folder-carried", "Carried", { parent: { id: "actor-1", documentName: "Actor" } }),
|
||||||
{ id: "folder-journal", name: "Lore", type: "JournalEntry", parent: null, documentName: "Folder" },
|
makeFolder("folder-journal", "Lore", { type: "JournalEntry" }),
|
||||||
];
|
];
|
||||||
const items = [
|
const items = [
|
||||||
{
|
{
|
||||||
@@ -352,6 +454,15 @@ function makeWorld() {
|
|||||||
id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {},
|
id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {},
|
||||||
items: { contents: [carriedItem] },
|
items: { contents: [carriedItem] },
|
||||||
getFlag() { return undefined; },
|
getFlag() { return undefined; },
|
||||||
|
async update(data) { return writeFoundryPaths(this, data); },
|
||||||
|
// Embedded documents are written through the document holding them, and each
|
||||||
|
// update names the row it belongs to.
|
||||||
|
async updateEmbeddedDocuments(_kind, updates) {
|
||||||
|
for (const update of updates) {
|
||||||
|
if (carriedItem.id === update._id) writeFoundryPaths(carriedItem, update);
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
},
|
||||||
toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags }; },
|
toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags }; },
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -373,15 +484,24 @@ function makeWorld() {
|
|||||||
return id;
|
return id;
|
||||||
},
|
},
|
||||||
clearTimeout: (id) => state.timers.delete(id),
|
clearTimeout: (id) => state.timers.delete(id),
|
||||||
setInterval: () => 0,
|
setInterval: (fn, delay = 0) => {
|
||||||
clearInterval: () => {},
|
// Recorded, never run by itself: tests ask for a periodic reconcile with
|
||||||
|
// `runIntervals`, so the ones watching single pushes stay on their own.
|
||||||
|
const id = state.nextTimerId++;
|
||||||
|
state.intervals.set(id, { fn, delay });
|
||||||
|
return id;
|
||||||
|
},
|
||||||
|
clearInterval: (id) => state.intervals.delete(id),
|
||||||
fetch: async (url, options = {}) => {
|
fetch: async (url, options = {}) => {
|
||||||
|
const href = String(url);
|
||||||
state.requests.push({
|
state.requests.push({
|
||||||
href: String(url),
|
href,
|
||||||
method: options.method,
|
method: options.method,
|
||||||
body: options.body ? JSON.parse(options.body) : null,
|
body: options.body ? JSON.parse(options.body) : null,
|
||||||
});
|
});
|
||||||
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
|
const payload = { status: "ok", actors: [], items: [] };
|
||||||
|
if (href.includes("foundry/sync/items")) payload.folders = state.remoteFolders;
|
||||||
|
return { ok: true, status: 200, json: async () => payload };
|
||||||
},
|
},
|
||||||
Actor: { async create() { return null; } },
|
Actor: { async create() { return null; } },
|
||||||
Item: { async create() { return null; } },
|
Item: { async create() { return null; } },
|
||||||
@@ -432,6 +552,12 @@ function makeWorld() {
|
|||||||
await drain();
|
await drain();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
// The reconciles `setInterval` registered: what runs every few seconds on a world
|
||||||
|
// that is linked, and so what carries Dragonroll's folder colours back into the world.
|
||||||
|
state.runIntervals = async () => {
|
||||||
|
for (const interval of [...state.intervals.values()]) await interval.fn();
|
||||||
|
await drain();
|
||||||
|
};
|
||||||
state.linkedSetup = async () => {
|
state.linkedSetup = async () => {
|
||||||
await state.fire("init");
|
await state.fire("init");
|
||||||
await state.fire("ready");
|
await state.fire("ready");
|
||||||
@@ -452,9 +578,9 @@ test("the world sends its item folder tree with a snapshot", async () => {
|
|||||||
const [push] = world.pushes("foundry/sync/snapshot");
|
const [push] = world.pushes("foundry/sync/snapshot");
|
||||||
assert.ok(push, "the actor change pushed a snapshot");
|
assert.ok(push, "the actor change pushed a snapshot");
|
||||||
assert.deepEqual(push.body.folders, [
|
assert.deepEqual(push.body.folders, [
|
||||||
{ id: "folder-melee", name: "Melee Weapons", parent: null },
|
{ id: "folder-melee", name: "Melee Weapons", parent: null, color: "#8b0000" },
|
||||||
{ id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee" },
|
{ id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee", color: null },
|
||||||
], "the item directory tree, nested, without the actor's own or another type's folders");
|
], "the item directory tree, nested and coloured, without the actor's own or another type's folders");
|
||||||
const longsword = push.body.items.find((item) => item._id === "item-1");
|
const longsword = push.body.items.find((item) => item._id === "item-1");
|
||||||
assert.equal(longsword.dragonroll.folder, "folder-melee", "a world item says which folder it stands in");
|
assert.equal(longsword.dragonroll.folder, "folder-melee", "a world item says which folder it stands in");
|
||||||
const torch = push.body.items.find((item) => item._id === "item-2");
|
const torch = push.body.items.find((item) => item._id === "item-2");
|
||||||
@@ -499,6 +625,21 @@ test("a folder change reaches Dragonroll without pushing the items in it", async
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a folder the GM colours sends its colour with the tree", async () => {
|
||||||
|
const world = await makeWorld().linkedSetup();
|
||||||
|
|
||||||
|
const ranged = world.folder("folder-ranged");
|
||||||
|
ranged.color = "#123456";
|
||||||
|
await world.fire("updateFolder", ranged);
|
||||||
|
await world.runTimers();
|
||||||
|
|
||||||
|
const [push] = world.pushes("foundry/sync/item-snapshot");
|
||||||
|
assert.deepEqual(push.body.folders.map((folder) => [folder.id, folder.color]), [
|
||||||
|
["folder-melee", "#8b0000"],
|
||||||
|
["folder-ranged", "#123456"],
|
||||||
|
], "every folder reports the colour the world shows for it, `null` for one it left uncoloured");
|
||||||
|
});
|
||||||
|
|
||||||
test("a folder of another document type does not touch the item list", async () => {
|
test("a folder of another document type does not touch the item list", async () => {
|
||||||
const world = await makeWorld().linkedSetup();
|
const world = await makeWorld().linkedSetup();
|
||||||
|
|
||||||
@@ -519,14 +660,54 @@ test("autosync off: folder changes stop syncing", async () => {
|
|||||||
assert.deepEqual(world.syncRequests(), []);
|
assert.deepEqual(world.syncRequests(), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- The colours the campaign gives those folders travel back to the world ---------
|
||||||
|
|
||||||
|
test("a folder coloured in the Dragonroll campaign is coloured in the world", async () => {
|
||||||
|
const world = await makeWorld().linkedSetup();
|
||||||
|
|
||||||
|
world.remoteFolders = [
|
||||||
|
{ _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: "#0080ff" },
|
||||||
|
// A folder the campaign made for its own items: there is no world document to colour.
|
||||||
|
{ _id: "db-homebrew", name: "Homebrew", color: "#00ff00" },
|
||||||
|
];
|
||||||
|
await world.runIntervals();
|
||||||
|
|
||||||
|
assert.equal(world.folder("folder-melee").color, "#0080ff");
|
||||||
|
assert.equal(world.folder("folder-ranged").color, null, "a folder the campaign says nothing about keeps what the world shows");
|
||||||
|
assert.deepEqual(world.requests.filter((request) => request.method === "POST"), [],
|
||||||
|
"Dragonroll's own write is not pushed back to the campaign as a world change");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a colour taken off in the campaign comes off the world's folder", async () => {
|
||||||
|
const world = await makeWorld().linkedSetup();
|
||||||
|
|
||||||
|
world.remoteFolders = [{ _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: null }];
|
||||||
|
await world.runIntervals();
|
||||||
|
|
||||||
|
assert.equal(world.folder("folder-melee").color, null, "uncoloured in the campaign is uncoloured in the world");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("autosync off: the campaign's folder colours are not written into the world", async () => {
|
||||||
|
const world = await makeWorld().linkedSetup();
|
||||||
|
await world.game.settings.set("dragonroll-foundry", "autoSync", false);
|
||||||
|
|
||||||
|
world.remoteFolders = [{ _id: "db-melee", name: "Melee Weapons", foundryFolderId: "folder-melee", color: "#0080ff" }];
|
||||||
|
await world.runIntervals();
|
||||||
|
|
||||||
|
assert.equal(world.folder("folder-melee").color, "#8b0000", "the world keeps what it shows while autosync is off");
|
||||||
|
});
|
||||||
|
|
||||||
// --- The sidebar groups its items under those folders ----------------------------
|
// --- The sidebar groups its items under those folders ----------------------------
|
||||||
|
|
||||||
async function loadItemFoldersService() {
|
// `vm.compileFunction` is synchronous, so the service is ready right away. Loading it with
|
||||||
|
// a top-level `await` instead makes Node read this whole file as an ES module, where
|
||||||
|
// `require` is not defined and none of these tests run at all.
|
||||||
|
function loadItemFoldersService() {
|
||||||
const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };");
|
const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };");
|
||||||
return vm.compileFunction(source)();
|
return vm.compileFunction(source)();
|
||||||
}
|
}
|
||||||
|
|
||||||
const { BuildItemRows } = await loadItemFoldersService();
|
const { BuildItemRows } = loadItemFoldersService();
|
||||||
|
|
||||||
const SIDEBAR_FOLDERS = [
|
const SIDEBAR_FOLDERS = [
|
||||||
{ _id: "f-melee", name: "Melee Weapons" },
|
{ _id: "f-melee", name: "Melee Weapons" },
|
||||||
@@ -582,9 +763,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");
|
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"]) {
|
for (const locale of ["en", "es", "ca"]) {
|
||||||
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
|
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`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -77,8 +77,10 @@ test("the item window shows the info and offers both icon sources", () => {
|
|||||||
for (const key of ["form.name", "form.category", "form.rarity", "form.quantity", "form.weight", "form.properties", "form.description"]) {
|
for (const key of ["form.name", "form.category", "form.rarity", "form.quantity", "form.weight", "form.properties", "form.description"]) {
|
||||||
assert.ok(itemWindowSource.includes(key), `expected the window to render ${key}`);
|
assert.ok(itemWindowSource.includes(key), `expected the window to render ${key}`);
|
||||||
}
|
}
|
||||||
// own icon: upload through the item route like the character sheet does its photo
|
// own icon: #65 moved picking one into a window of its own, which uploads through
|
||||||
assert.match(itemWindowSource, /\/item\/upload-image\?item=/);
|
// the item route (see tests/foundry-icon-picker.test.js); the sheet opens it and
|
||||||
|
// follows whatever the choice leaves behind.
|
||||||
|
assert.match(itemWindowSource, /CreateChildWindow\(id, ['"]item_icon_source['"]/);
|
||||||
// Foundry icon: switch the item image back to the one the world sent
|
// Foundry icon: switch the item image back to the one the world sent
|
||||||
assert.match(itemWindowSource, /form\.value\.foundryImage/);
|
assert.match(itemWindowSource, /form\.value\.foundryImage/);
|
||||||
assert.match(itemWindowSource, /updateItem\(\{ image: form\.value\.foundryImage \}\)/);
|
assert.match(itemWindowSource, /updateItem\(\{ image: form\.value\.foundryImage \}\)/);
|
||||||
|
|||||||
Reference in New Issue
Block a user