Compare commits
4 Commits
ai/issue-6
...
09e9010729
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
09e9010729 | ||
| cdafd1f53a | |||
| 2e2fb97e5d | |||
|
|
d03cc1eb59 |
@@ -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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
@@ -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
|
||||
// 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.
|
||||
// A folder whose parent is missing, or caught in a cycle, becomes a root.
|
||||
function orderFoundryFolderSources(sources) {
|
||||
@@ -152,7 +162,12 @@ function orderFoundryFolderSources(sources) {
|
||||
const id = String(source?.id || '').trim().slice(0, 120);
|
||||
const name = String(source?.name || '').trim();
|
||||
if (!id || !name) continue;
|
||||
byId.set(id, { id, name, parent: String(source?.parent || '').trim().slice(0, 120) });
|
||||
byId.set(id, {
|
||||
id,
|
||||
name,
|
||||
parent: String(source?.parent || '').trim().slice(0, 120),
|
||||
color: foundryFolderColor(source)
|
||||
});
|
||||
}
|
||||
|
||||
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
|
||||
// lands whatever kind of push carried it: the whole tree arrives with each.
|
||||
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;
|
||||
folder.parentFolder = parent ? parent._id : null;
|
||||
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) => {
|
||||
try {
|
||||
const campaign = await syncCampaign(req, res);
|
||||
if (!campaign) return;
|
||||
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) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
|
||||
@@ -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
|
||||
directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry
|
||||
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
|
||||
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
|
||||
@@ -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-delete` | A world item was deleted |
|
||||
| `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 |
|
||||
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
|
||||
| `POST /api/foundry/sync/delete` | An actor was deleted |
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ let itemSyncErrorLogged = false;
|
||||
let folderSyncTimeout;
|
||||
let folderSyncRunning = false;
|
||||
const syncingItemIds = new Set();
|
||||
const syncingFolderIds = new Set();
|
||||
const queuedItemChanges = new Map();
|
||||
|
||||
function getCollectionContents(collection, collectionName) {
|
||||
@@ -675,10 +676,23 @@ function isWorldItemFolder(folder, seen = new Set()) {
|
||||
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() {
|
||||
return (game.folders?.contents || [])
|
||||
.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
|
||||
@@ -706,6 +720,35 @@ function getWorldItemSnapshots() {
|
||||
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) {
|
||||
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;
|
||||
itemSyncRunning = true;
|
||||
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") {
|
||||
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 remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry]));
|
||||
const localByRemoteId = new Map(game.items.contents
|
||||
@@ -1347,7 +1393,9 @@ Hooks.once("ready", () => {
|
||||
}
|
||||
// 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.
|
||||
// A colour Dragonroll has just written into the folder is not the GM changing it.
|
||||
if (document.documentName === "Folder") {
|
||||
if (syncingFolderIds.has(document.id)) return;
|
||||
if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,13 @@ $themes: (
|
||||
green: #98c379,
|
||||
gray: #cccccc,
|
||||
|
||||
// The rarity of an item colours its row in the sidebar (Syndria98/dragonroll#63).
|
||||
rarity-common: #ffffff,
|
||||
rarity-uncommon: #1eff00,
|
||||
rarity-rare: #2f81f7,
|
||||
rarity-very-rare: #a855f7,
|
||||
rarity-legendary: #ff8000,
|
||||
|
||||
icon-invert: 100%,
|
||||
|
||||
search-background: #20202077,
|
||||
@@ -72,6 +79,13 @@ $themes: (
|
||||
green: #98c379,
|
||||
gray: #cccccc,
|
||||
|
||||
// Same rarities as the dark map, darkened to stay readable on a light background.
|
||||
rarity-common: #1e1e1e,
|
||||
rarity-uncommon: #157f2b,
|
||||
rarity-rare: #1d4ed8,
|
||||
rarity-very-rare: #7e22ce,
|
||||
rarity-legendary: #c05621,
|
||||
|
||||
icon-invert: 0%,
|
||||
|
||||
search-background: #f0f0f0aa,
|
||||
|
||||
@@ -279,8 +279,13 @@ function entrySummary(actor) {
|
||||
return bits.join(' · ');
|
||||
}
|
||||
|
||||
function itemSummary(item) {
|
||||
return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`;
|
||||
// The rarity of an item colours the text of its row instead of listing category, rarity and
|
||||
// quantity (Syndria98/dragonroll#63): common white, uncommon green, rare blue, very rare purple,
|
||||
// legendary orange. Anything else (artifact) keeps the default text colour.
|
||||
function rarityClass(item) {
|
||||
return ['common', 'uncommon', 'rare', 'very-rare', 'legendary'].includes(item.rarity)
|
||||
? `rarity-${item.rarity}`
|
||||
: '';
|
||||
}
|
||||
|
||||
// An item's icon in the sidebar: an uploaded filename served from /api/public, or a full URL
|
||||
@@ -681,9 +686,8 @@ onBeforeUnmount(() => {
|
||||
<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" :class="rarityClass(row.item)">{{ row.item.name }}</span>
|
||||
</span>
|
||||
<span class="entity-entry-meta">{{ itemSummary(row.item) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
@@ -877,6 +881,13 @@ onBeforeUnmount(() => {
|
||||
/* 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; }
|
||||
/* The rarity of an item colours the text of its row (Syndria98/dragonroll#63): common white,
|
||||
uncommon green, rare blue, very rare purple, legendary orange. */
|
||||
.entity-entry-name.rarity-common { color: var(--color-rarity-common); }
|
||||
.entity-entry-name.rarity-uncommon { color: var(--color-rarity-uncommon); }
|
||||
.entity-entry-name.rarity-rare { color: var(--color-rarity-rare); }
|
||||
.entity-entry-name.rarity-very-rare { color: var(--color-rarity-very-rare); }
|
||||
.entity-entry-name.rarity-legendary { color: var(--color-rarity-legendary); }
|
||||
.entity-entry-image {
|
||||
flex: 0 0 30px; width: 30px; height: 30px; box-sizing: border-box;
|
||||
display: grid; place-items: center; overflow: hidden;
|
||||
|
||||
@@ -20,13 +20,13 @@ function initialForm() {
|
||||
if (!editing) {
|
||||
return {
|
||||
name: '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '',
|
||||
category: 'adventuring-gear', rarity: 'common', quantity: 1, weight: '', properties: '', description: ''
|
||||
category: 'adventuring-gear', rarity: 'common', weight: '', properties: '', description: ''
|
||||
};
|
||||
}
|
||||
return {
|
||||
name: editing.name ?? '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '',
|
||||
category: editing.category ?? 'adventuring-gear', rarity: editing.rarity ?? 'common',
|
||||
quantity: editing.quantity ?? 1, weight: editing.weight ?? '', properties: editing.properties ?? '',
|
||||
weight: editing.weight ?? '', properties: editing.properties ?? '',
|
||||
description: editing.description ?? ''
|
||||
};
|
||||
}
|
||||
@@ -49,7 +49,7 @@ async function saveEntry() {
|
||||
? { name: form.value.name.trim(), campaign: data.campaign }
|
||||
: { name: form.value.name.trim(), ...(editing ? { id: editing._id } : { campaign: data.campaign }) };
|
||||
if (!isActor) {
|
||||
for (const field of ['category', 'rarity', 'quantity', 'weight', 'properties', 'description']) {
|
||||
for (const field of ['category', 'rarity', 'weight', 'properties', 'description']) {
|
||||
payload[field] = form.value[field];
|
||||
}
|
||||
}
|
||||
@@ -105,10 +105,6 @@ async function saveEntry() {
|
||||
<option value="artifact">{{ $t('campaigns.item.rarities.artifact') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>{{ $t('campaigns.item.quantity') }}</span>
|
||||
<input v-model.number="form.quantity" type="number" min="1" required>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>{{ $t('campaigns.item.weight') }}</span>
|
||||
<input v-model="form.weight" type="number" min="0" step="0.1">
|
||||
|
||||
@@ -22,7 +22,6 @@ function normalizeItem(item) {
|
||||
name: item?.name ?? '',
|
||||
category: item?.category ?? 'adventuring-gear',
|
||||
rarity: item?.rarity ?? 'common',
|
||||
quantity: Number(item?.quantity ?? 1),
|
||||
weight: item?.weight ?? '',
|
||||
properties: item?.properties ?? '',
|
||||
description: item?.description ?? '',
|
||||
@@ -161,11 +160,9 @@ async function removeIcon() {
|
||||
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onIconSelected">
|
||||
</div>
|
||||
|
||||
<!-- Quantity is the actor inventory's business (Syndria98/dragonroll#63); the item
|
||||
sheet only states what the item itself is. -->
|
||||
<dl class="item-facts">
|
||||
<div class="item-fact">
|
||||
<dt>{{ $t('campaigns.item.quantity') }}</dt>
|
||||
<dd>{{ form.quantity }}</dd>
|
||||
</div>
|
||||
<div v-if="form.weight !== '' && form.weight !== undefined" class="item-fact">
|
||||
<dt>{{ $t('campaigns.item.weight') }}</dt>
|
||||
<dd>{{ Number(form.weight).toFixed(1) }} lb</dd>
|
||||
|
||||
@@ -65,8 +65,8 @@
|
||||
},
|
||||
"item": {
|
||||
"new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.",
|
||||
"category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat",
|
||||
"quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
|
||||
"category": "Categoria", "rarity": "Raresa",
|
||||
"weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
|
||||
"sheet": {
|
||||
"icon": "Icona de l'objecte", "choose-icon": "Tria la teva pròpia icona", "change-icon": "Canvia la icona",
|
||||
"uploading": "Pujant...", "upload-error": "No s'ha pogut pujar aquesta icona.",
|
||||
|
||||
@@ -69,8 +69,8 @@
|
||||
},
|
||||
"item": {
|
||||
"new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.",
|
||||
"category": "Category", "rarity": "Rarity", "quantity": "Quantity",
|
||||
"quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
|
||||
"category": "Category", "rarity": "Rarity",
|
||||
"weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
|
||||
"sheet": {
|
||||
"icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change icon",
|
||||
"uploading": "Uploading...", "upload-error": "Unable to upload this icon.",
|
||||
|
||||
@@ -65,8 +65,8 @@
|
||||
},
|
||||
"item": {
|
||||
"new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.",
|
||||
"category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad",
|
||||
"quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
|
||||
"category": "Categoría", "rarity": "Rareza",
|
||||
"weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
|
||||
"sheet": {
|
||||
"icon": "Icono del objeto", "choose-icon": "Elegir tu propio icono", "change-icon": "Cambiar icono",
|
||||
"uploading": "Subiendo...", "upload-error": "No se pudo subir este icono.",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// Tests for item folders following the Foundry world into the campaign
|
||||
// (Syndria98/dragonroll#44): the world's item directory is grouped into folders, and
|
||||
// Dragonroll mirrors that tree as Folders of target 'item' and files the synced items
|
||||
// in them, so its item list reads like the world's.
|
||||
// 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
|
||||
// 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),
|
||||
};
|
||||
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 = {
|
||||
"../models/Actor": fakeModel("actor", seed.actors),
|
||||
"../models/Item": fakeModel("item", seed.items),
|
||||
"../models/Folder": fakeModel("folder", seed.folders),
|
||||
"../models/Actor": fakeModel("actor", seeded(seed.actors)),
|
||||
"../models/Item": fakeModel("item", seeded(seed.items)),
|
||||
"../models/Folder": fakeModel("folder", seeded(seed.folders)),
|
||||
};
|
||||
|
||||
const requireStub = (id) => {
|
||||
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 === "../models/Campaign") return { findOne: async () => campaign };
|
||||
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
|
||||
@@ -290,6 +297,74 @@ test("an item the world moved out of a folder follows it to the root", async ()
|
||||
assert.equal(sync.models["../models/Item"].rows[0].folder, null);
|
||||
});
|
||||
|
||||
test("a folder coloured in the world is coloured in the campaign", async () => {
|
||||
const sync = loadSyncRoute();
|
||||
|
||||
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
|
||||
@@ -320,15 +395,40 @@ function makeWorld() {
|
||||
registered: new Map(),
|
||||
requests: [],
|
||||
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,
|
||||
};
|
||||
|
||||
// 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 = [
|
||||
{ id: "folder-melee", name: "Melee Weapons", type: "Item", parent: null, documentName: "Folder" },
|
||||
{ id: "folder-ranged", name: "Ranged Weapons", type: "Item", parent: "folder-melee", documentName: "Folder" },
|
||||
makeFolder("folder-melee", "Melee Weapons", { color: "#8b0000" }),
|
||||
makeFolder("folder-ranged", "Ranged Weapons", { parent: "folder-melee" }),
|
||||
// An actor's own inventory folder: it hangs off the actor, not the world.
|
||||
{ id: "folder-carried", name: "Carried", type: "Item", parent: { id: "actor-1", documentName: "Actor" }, documentName: "Folder" },
|
||||
{ id: "folder-journal", name: "Lore", type: "JournalEntry", parent: null, documentName: "Folder" },
|
||||
makeFolder("folder-carried", "Carried", { parent: { id: "actor-1", documentName: "Actor" } }),
|
||||
makeFolder("folder-journal", "Lore", { type: "JournalEntry" }),
|
||||
];
|
||||
const items = [
|
||||
{
|
||||
@@ -354,6 +454,15 @@ function makeWorld() {
|
||||
id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {},
|
||||
items: { contents: [carriedItem] },
|
||||
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 }; },
|
||||
},
|
||||
];
|
||||
@@ -375,15 +484,24 @@ function makeWorld() {
|
||||
return id;
|
||||
},
|
||||
clearTimeout: (id) => state.timers.delete(id),
|
||||
setInterval: () => 0,
|
||||
clearInterval: () => {},
|
||||
setInterval: (fn, delay = 0) => {
|
||||
// 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 = {}) => {
|
||||
const href = String(url);
|
||||
state.requests.push({
|
||||
href: String(url),
|
||||
href,
|
||||
method: options.method,
|
||||
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; } },
|
||||
Item: { async create() { return null; } },
|
||||
@@ -434,6 +552,12 @@ function makeWorld() {
|
||||
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 () => {
|
||||
await state.fire("init");
|
||||
await state.fire("ready");
|
||||
@@ -454,9 +578,9 @@ test("the world sends its item folder tree with a snapshot", async () => {
|
||||
const [push] = world.pushes("foundry/sync/snapshot");
|
||||
assert.ok(push, "the actor change pushed a snapshot");
|
||||
assert.deepEqual(push.body.folders, [
|
||||
{ id: "folder-melee", name: "Melee Weapons", parent: null },
|
||||
{ id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee" },
|
||||
], "the item directory tree, nested, without the actor's own or another type's folders");
|
||||
{ id: "folder-melee", name: "Melee Weapons", parent: null, color: "#8b0000" },
|
||||
{ id: "folder-ranged", name: "Ranged Weapons", parent: "folder-melee", color: null },
|
||||
], "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");
|
||||
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");
|
||||
@@ -501,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 () => {
|
||||
const world = await makeWorld().linkedSetup();
|
||||
|
||||
@@ -521,14 +660,54 @@ test("autosync off: folder changes stop syncing", async () => {
|
||||
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 ----------------------------
|
||||
|
||||
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 };");
|
||||
return vm.compileFunction(source)();
|
||||
}
|
||||
|
||||
const { BuildItemRows } = await loadItemFoldersService();
|
||||
const { BuildItemRows } = loadItemFoldersService();
|
||||
|
||||
const SIDEBAR_FOLDERS = [
|
||||
{ _id: "f-melee", name: "Melee Weapons" },
|
||||
|
||||
89
tests/item-rarity-entry.test.js
Normal file
89
tests/item-rarity-entry.test.js
Normal file
@@ -0,0 +1,89 @@
|
||||
// Tests for Syndria98/dragonroll#63: the item rows in the campaign sidebar dropped the text
|
||||
// listing category, rarity and quantity — the rarity colours the text of the entry instead
|
||||
// (common white, uncommon green, rare blue, very rare purple, legendary orange) — and the
|
||||
// quantity left the item surfaces altogether, since it only belongs to an actor's inventory.
|
||||
//
|
||||
// The repository root installs no dependencies, so these read the sources the way
|
||||
// tests/item-entry-display.test.js does — the checks are about the markup and style.
|
||||
//
|
||||
// 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 sidebarSource = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
|
||||
const itemWindowSource = read("frontend", "app", "components", "windows", "ItemSheetWindow.vue");
|
||||
const entryFormSource = read("frontend", "app", "components", "windows", "CreateCampaignEntryWindow.vue");
|
||||
const sheetSource = read("frontend", "app", "components", "windows", "CharacterSheetWindow.vue");
|
||||
const colorsSource = read("frontend", "app", "assets", "css", "colors.scss");
|
||||
|
||||
// The block that renders the item rows, as in tests/item-entry-display.test.js.
|
||||
const itemSection =
|
||||
/<template v-else-if="activeSection === 'items'">([\s\S]*?)<\/template>\s*\n\s*<template v-else>/.exec(sidebarSource)?.[1] ?? "";
|
||||
|
||||
const rarities = ["common", "uncommon", "rare", "very-rare", "legendary"];
|
||||
|
||||
// `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(sidebarSource)?.[0];
|
||||
return rule?.replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
}
|
||||
|
||||
test("the item entry no longer lists the category, rarity and quantity as text", () => {
|
||||
assert.ok(itemSection, "expected to find the items section of the sidebar");
|
||||
assert.doesNotMatch(itemSection, /entity-entry-meta/, "the item row must not render a meta line");
|
||||
assert.doesNotMatch(itemSection, /campaigns\.item\.(categories|rarities|quantity)/, "the item row must not render item meta text");
|
||||
assert.doesNotMatch(sidebarSource, /itemSummary/, "the removed summary helper must not be kept around");
|
||||
});
|
||||
|
||||
test("the rarity of an item picks a class for the text of its entry", () => {
|
||||
assert.match(
|
||||
itemSection,
|
||||
/<span class="entity-entry-name" :class="rarityClass\(row\.item\)"/,
|
||||
"the item name must carry the class picked from its rarity"
|
||||
);
|
||||
const helper = /function rarityClass\(item\)\s*\{[\s\S]*?\n\}/.exec(sidebarSource)?.[0] ?? "";
|
||||
assert.ok(helper, "expected a rarityClass helper");
|
||||
for (const rarity of rarities) {
|
||||
assert.ok(helper.includes(`'${rarity}'`), `rarityClass must know about '${rarity}'`);
|
||||
}
|
||||
});
|
||||
|
||||
test("each rarity colours the entry text with its own theme colour", () => {
|
||||
for (const rarity of rarities) {
|
||||
const rule = ruleFor(`entity-entry-name\\.rarity-${rarity}`);
|
||||
assert.ok(rule, `expected a colour rule for .entity-entry-name.rarity-${rarity}`);
|
||||
assert.match(rule, new RegExp(`color:\\s*var\\(--color-rarity-${rarity}\\)`));
|
||||
}
|
||||
});
|
||||
|
||||
test("both theme maps carry the rarity colours", () => {
|
||||
for (const rarity of rarities) {
|
||||
const declarations = colorsSource.match(new RegExp(`rarity-${rarity}:\\s*#[0-9a-fA-F]{6}`, "g")) || [];
|
||||
assert.equal(declarations.length, 2, `expected rarity-${rarity} in both the dark and the light map`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the quantity only shows in an actor's inventory", () => {
|
||||
assert.doesNotMatch(itemWindowSource, /quantity/, "the item window must not list the quantity");
|
||||
assert.doesNotMatch(entryFormSource, /quantity/, "the item create/edit form must not offer the quantity");
|
||||
// the character sheet's inventory table keeps it.
|
||||
assert.match(sheetSource, /campaigns\.character-sheet\.quantity/);
|
||||
assert.match(sheetSource, /\{\{ item\.quantity \}\}/);
|
||||
});
|
||||
|
||||
test("no locale keeps the removed item quantity strings", () => {
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
|
||||
assert.ok(campaigns.item, `${locale} is missing the campaigns.item block`);
|
||||
assert.equal(campaigns.item.quantity, undefined, `${locale} still has campaigns.item.quantity`);
|
||||
assert.equal(campaigns.item["quantity-short"], undefined, `${locale} still has campaigns.item.quantity-short`);
|
||||
// the character sheet's inventory keeps its own quantity column label
|
||||
assert.ok(campaigns["character-sheet"]?.quantity, `${locale} is missing campaigns.character-sheet.quantity`);
|
||||
}
|
||||
});
|
||||
@@ -73,10 +73,12 @@ test("the item info window is registered and opens on a sidebar click", () => {
|
||||
});
|
||||
|
||||
test("the item window shows the info and offers both icon sources", () => {
|
||||
// info: name, category, rarity, quantity, weight, properties, description
|
||||
for (const key of ["form.name", "form.category", "form.rarity", "form.quantity", "form.weight", "form.properties", "form.description"]) {
|
||||
// info: name, category, rarity, weight, properties, description — quantity is gone
|
||||
// (#63 keeps it for the actors' inventories).
|
||||
for (const key of ["form.name", "form.category", "form.rarity", "form.weight", "form.properties", "form.description"]) {
|
||||
assert.ok(itemWindowSource.includes(key), `expected the window to render ${key}`);
|
||||
}
|
||||
assert.doesNotMatch(itemWindowSource, /quantity/, "the item window must not list the quantity");
|
||||
// own icon: upload through the item route like the character sheet does its photo
|
||||
assert.match(itemWindowSource, /\/item\/upload-image\?item=/);
|
||||
// Foundry icon: switch the item image back to the one the world sent
|
||||
|
||||
Reference in New Issue
Block a user