diff --git a/backend/src/models/Item.js b/backend/src/models/Item.js index bd0b67fb..4633907e 100644 --- a/backend/src/models/Item.js +++ b/backend/src/models/Item.js @@ -17,6 +17,12 @@ const ItemSchema = new Schema({ weight: { type: Number, min: 0 }, properties: { type: String, default: '' }, description: { type: String, default: '' }, + // Item icon: an uploaded filename served from /api/public, or a full URL + // (Foundry sends its own icon as one). + image: { type: String, default: '' }, + // The icon Foundry last sent for this item, kept even after the user picks + // their own so Dragonroll can still offer Foundry's back. + foundryImage: { type: String, default: '' }, campaign: { type: Schema.Types.ObjectId, ref: 'Campaign', diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js index 33062571..dbfbe532 100644 --- a/backend/src/routes/foundry-link.js +++ b/backend/src/routes/foundry-link.js @@ -109,6 +109,9 @@ async function saveFoundryItem(campaign, source, fullSync = false) { item.foundryItemId = foundryItemId; if (!fullSync || item.isNew) Object.assign(item, fields); + // Foundry's own icon is kept on every save, not only when the edits above + // land: the item window offers it back after the user picked their own. + if (fields.image) item.foundryImage = fields.image; if (!item.foundryNames.includes(fields.name)) { item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES); } diff --git a/backend/src/routes/item.js b/backend/src/routes/item.js index 45ff8558..d1460507 100644 --- a/backend/src/routes/item.js +++ b/backend/src/routes/item.js @@ -1,6 +1,8 @@ const express = require('express'); const router = express.Router(); +const upload = require('../services/storage'); + const Campaign = require('../models/Campaign'); const Item = require('../models/Item'); @@ -44,7 +46,7 @@ router.post('/create', async (req, res) => { router.post('/update', async (req, res) => { try { - const { id, name, category, rarity, quantity, weight, properties, description } = req.body; + const { id, name, category, rarity, quantity, weight, properties, description, image } = req.body; if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' }); const item = await Item.findById(id); @@ -58,6 +60,7 @@ router.post('/update', async (req, res) => { if (weight !== undefined && weight !== '') item.weight = Number(weight); if (properties !== undefined) item.properties = properties; if (description !== undefined) item.description = description; + if (image !== undefined) item.image = String(image); await item.save(); res.json({ status: 'ok', item }); @@ -67,6 +70,25 @@ router.post('/update', async (req, res) => { } }); +// Upload item image post +router.post("/upload-image", upload.single("image"), async (req, res) => { + try { + const itemId = req.query.item || req.body.item; + if (!itemId || !req.file) return res.json({ status: 'error', msg: 'errors.missing-data' }); + + const item = await Item.findById(itemId); + 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' }); + + item.image = req.file.filename; + await item.save(); + res.json({ status: "ok", msg: "uploaded", item }); + } catch (err) { + console.error(err); + res.json({ status: "error", msg: "internal" }); + } +}); + router.post('/delete', async (req, res) => { try { const { id } = req.body; diff --git a/backend/src/services/item-foundry.js b/backend/src/services/item-foundry.js index b1c7205f..d570e760 100644 --- a/backend/src/services/item-foundry.js +++ b/backend/src/services/item-foundry.js @@ -101,7 +101,9 @@ function foundryItemToItemData(foundryItem) { quantity: Math.max(1, Math.trunc(numberOr(system.quantity, 1))), weight: Math.max(0, numberOr(system.weight?.value ?? system.weight, 0)), properties: foundryItemProperties(foundryItem), - description: plainText(system.description?.value ?? system.description) + description: plainText(system.description?.value ?? system.description), + // The module sends Foundry's icon as an absolute URL, like actors do. + image: asText(foundryItem.img || foundryItem.image) }; } diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js index a309e2eb..fb3f5cbb 100644 --- a/dragonroll-foundry/scripts/api.js +++ b/dragonroll-foundry/scripts/api.js @@ -461,7 +461,9 @@ function dragonrollActorId(actor) { function serializeFoundryActor(actor) { const data = { ...toPlainData(actor), - items: actor.items?.contents?.map(toPlainData) || [], + // Embedded items go through serializeFoundryItem so their icons become + // absolute URLs too: Dragonroll renders them outside of Foundry. + items: (actor.items?.contents?.map(serializeFoundryItem) || []).filter(Boolean), }; if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) { data.img = new URL(data.img, window.location.origin).toString(); @@ -760,6 +762,7 @@ function makeFoundryItemData(entry) { const data = { name: String(entry.name || "").trim(), type, + img: getDragonrollImageUrl(entry.image) || undefined, system: { quantity: Number(entry.quantity) || 1, weight: Number(entry.weight) || 0, @@ -773,13 +776,18 @@ function makeFoundryItemData(entry) { } function foundryItemUpdateData(entry) { - return { + const updates = { name: String(entry.name || "").trim(), "system.quantity": Number(entry.quantity) || 1, "system.weight": Number(entry.weight) || 0, "system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common", "system.description.value": entry.description || "", }; + // An icon the campaign picked in Dragonroll travels back to Foundry; no icon + // there means leave the world's own choice alone, not erase it. + const image = getDragonrollImageUrl(entry.image); + if (image) updates.img = image; + return updates; } async function applyDragonrollItem(item, entry) { diff --git a/frontend/app/components/partials/ContentSidebar.vue b/frontend/app/components/partials/ContentSidebar.vue index 07315317..94f72b28 100644 --- a/frontend/app/components/partials/ContentSidebar.vue +++ b/frontend/app/components/partials/ContentSidebar.vue @@ -27,7 +27,6 @@ const sidebarCollapsed = ref(false); const activeSection = ref('notes'); const isDragOverSidebar = ref(false); const expandedFolderIds = ref([]); -const expandedEntryIds = ref([]); const nestedNoteListRef = ref(null); let entryRefreshInterval; @@ -296,12 +295,6 @@ function showEntryMenu(entry, entityType) { ShowContextMenu(menuItems); } -function toggleEntryDetails(entryId) { - expandedEntryIds.value = expandedEntryIds.value.includes(entryId) - ? expandedEntryIds.value.filter((id) => id !== entryId) - : [...expandedEntryIds.value, entryId]; -} - async function openCharacterSheet(actor) { const existingWindowId = GetFirstWindowId('character_sheet'); if (existingWindowId !== undefined) { @@ -311,6 +304,16 @@ async function openCharacterSheet(actor) { CreateWindow('character_sheet', { actor }); } +// Clicking an item opens its window, like a character does with its sheet. +async function openItemSheet(item) { + const existingWindowId = GetFirstWindowId('item_sheet'); + if (existingWindowId !== undefined) { + ClearWindow({ id: existingWindowId }); + await nextTick(); + } + CreateWindow('item_sheet', { item }); +} + // Maps are anchored on the note container instead of opening a window: the notes that were open // stay open, and the sidebar's notes/maps buttons switch between the two. function openMapViewer(map) { @@ -507,17 +510,12 @@ onBeforeUnmount(() => { -
+
{{ item.name }} {{ t('campaigns.synced') }} -
diff --git a/frontend/app/components/windows/ItemSheetWindow.vue b/frontend/app/components/windows/ItemSheetWindow.vue new file mode 100644 index 00000000..d6c2e935 --- /dev/null +++ b/frontend/app/components/windows/ItemSheetWindow.vue @@ -0,0 +1,213 @@ + + + + + diff --git a/frontend/app/services/WindowDefinitions.js b/frontend/app/services/WindowDefinitions.js index 4529fba6..5ca163d4 100644 --- a/frontend/app/services/WindowDefinitions.js +++ b/frontend/app/services/WindowDefinitions.js @@ -71,6 +71,12 @@ const defWindows = { close: () => ClearWindow({type: 'character_sheet'}), movable: true }, + item_sheet: { + title: 'windows.item-sheet', + component: () => import('~/components/windows/ItemSheetWindow.vue'), + close: () => ClearWindow({type: 'item_sheet'}), + movable: true + }, create_map: { title: 'windows.create-map', component: () => import('~/components/windows/CreateMapWindow.vue'), diff --git a/frontend/i18n/locales/ca/campaigns.json b/frontend/i18n/locales/ca/campaigns.json index a2974330..bdec7102 100644 --- a/frontend/i18n/locales/ca/campaigns.json +++ b/frontend/i18n/locales/ca/campaigns.json @@ -62,6 +62,12 @@ "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", + "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.", + "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." + }, "categories": { "weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura", "magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre" diff --git a/frontend/i18n/locales/ca/windows.json b/frontend/i18n/locales/ca/windows.json index 1678f8c1..9a28fcd5 100644 --- a/frontend/i18n/locales/ca/windows.json +++ b/frontend/i18n/locales/ca/windows.json @@ -8,5 +8,6 @@ "create-campaign": "Crear campanya", "create-map": "Crear mapa", "map-viewer": "Mapa", - "pinned-note": "Nota fixada" + "pinned-note": "Nota fixada", + "item-sheet": "Objecte" } diff --git a/frontend/i18n/locales/en/campaigns.json b/frontend/i18n/locales/en/campaigns.json index a04baf4f..d98c463b 100644 --- a/frontend/i18n/locales/en/campaigns.json +++ b/frontend/i18n/locales/en/campaigns.json @@ -66,6 +66,12 @@ "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", + "sheet": { + "icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change 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.", + "no-description": "No description added." + }, "categories": { "weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear", "magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other" diff --git a/frontend/i18n/locales/en/windows.json b/frontend/i18n/locales/en/windows.json index 5efefaae..93536f61 100644 --- a/frontend/i18n/locales/en/windows.json +++ b/frontend/i18n/locales/en/windows.json @@ -8,5 +8,6 @@ "create-campaign": "Create Campaign", "create-map": "Create Map", "map-viewer": "Map", - "pinned-note": "Pinned note" + "pinned-note": "Pinned note", + "item-sheet": "Item" } diff --git a/frontend/i18n/locales/es/campaigns.json b/frontend/i18n/locales/es/campaigns.json index 8ed35b74..d63d945d 100644 --- a/frontend/i18n/locales/es/campaigns.json +++ b/frontend/i18n/locales/es/campaigns.json @@ -62,6 +62,12 @@ "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", + "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.", + "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." + }, "categories": { "weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura", "magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro" diff --git a/frontend/i18n/locales/es/windows.json b/frontend/i18n/locales/es/windows.json index c5d46d81..98f34193 100644 --- a/frontend/i18n/locales/es/windows.json +++ b/frontend/i18n/locales/es/windows.json @@ -8,5 +8,6 @@ "create-campaign": "Crear campanya", "create-map": "Crear mapa", "map-viewer": "Mapa", - "pinned-note": "Nota fijada" + "pinned-note": "Nota fijada", + "item-sheet": "Objeto" } diff --git a/tests/item-sheet-window.test.js b/tests/item-sheet-window.test.js new file mode 100644 index 00000000..62d01277 --- /dev/null +++ b/tests/item-sheet-window.test.js @@ -0,0 +1,105 @@ +// Tests for Syndria98/dragonroll#35: clicking an item in the campaign sidebar opens a window with +// the item's info, and that window can pick the item's icon — Foundry's own when the item is synced, +// or an uploaded one. +// +// The mapper from a Foundry item to Dragonroll item fields is a pure CommonJS service, so it is +// required and called directly. The window wiring lives 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 { foundryItemToItemData } = require(path.join(__dirname, "..", "backend", "src", "services", "item-foundry")); + +const sidebarSource = read("frontend", "app", "components", "partials", "ContentSidebar.vue"); +const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js"); +const itemWindowSource = read("frontend", "app", "components", "windows", "ItemSheetWindow.vue"); +const itemRouteSource = read("backend", "src", "routes", "item.js"); +const itemModelSource = read("backend", "src", "models", "Item.js"); +const foundryLinkSource = read("backend", "src", "routes", "foundry-link.js"); +const moduleSource = read("dragonroll-foundry", "scripts", "api.js"); + +test("a synced Foundry item carries its icon over to the Dragonroll item", () => { + const fields = foundryItemToItemData({ + name: "Longsword", + type: "weapon", + img: "http://vtt.test/icons/svg/sword.svg", + system: { quantity: 1, weight: 3, rarity: "common" }, + }); + assert.equal(fields.image, "http://vtt.test/icons/svg/sword.svg"); +}); + +test("a Foundry item without an icon maps to an empty one", () => { + const fields = foundryItemToItemData({ name: "Torch", type: "loot", system: { quantity: 1 } }); + assert.equal(fields.image, ""); +}); + +test("the Item model stores the icon and the icon Foundry last sent", () => { + assert.match(itemModelSource, /image:\s*{\s*type:\s*String/); + assert.match(itemModelSource, /foundryImage:\s*{\s*type:\s*String/); +}); + +test("Foundry sync keeps foundryImage even when the save preserves Dragonroll edits", () => { + // The preserve-edits rule must not cover foundryImage: it is Foundry's state, + // and the item window offers it back after the user picked their own icon. + const keep = /if \(!fullSync \|\| item\.isNew\) Object\.assign\(item, fields\);([\s\S]{0,220}?)if \(!item\.foundryNames/.exec(foundryLinkSource); + assert.ok(keep, "expected the foundryImage keep between the guarded assign and the name bookkeeping"); + assert.match(keep[1], /if \(fields\.image\) item\.foundryImage = fields\.image;/); +}); + +test("the item routes accept the icon and upload one", () => { + assert.match(itemRouteSource, /router\.post\(["']\/upload-image["'], upload\.single\(["']image["']\)/); + assert.match(itemRouteSource, /req\.query\.item \|\| req\.body\.item/); + assert.match(itemRouteSource, /item\.image = req\.file\.filename/); + // the upload checks ownership like every other item handler + const uploadRoute = /router\.post\(["']\/upload-image[\s\S]*?module\.exports/.exec(itemRouteSource)?.[0] ?? itemRouteSource; + assert.match(uploadRoute, /userOwnsCampaign\(item\.campaign, req\.user\.id\)/); + // /update accepts the icon so the window can switch between own and Foundry's + assert.match(itemRouteSource, /if \(image !== undefined\) item\.image = String\(image\);/); +}); + +test("the item info window is registered and opens on a sidebar click", () => { + assert.match(windowDefsSource, /item_sheet:\s*{\s*title:[^}]*ItemSheetWindow\.vue/s); + // clicking (or Enter/Space on) an item row opens the window instead of expanding inline + assert.match(sidebarSource, /v-for="item in items"[^>]*@click="openItemSheet\(item\)"/); + assert.match(sidebarSource, /CreateWindow\(['"]item_sheet['"],\s*\{ item \}\)/); + assert.doesNotMatch(sidebarSource, /toggleEntryDetails/); +}); + +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"]) { + 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 + assert.match(itemWindowSource, /\/item\/upload-image\?item=/); + // Foundry icon: switch the item image back to the one the world sent + assert.match(itemWindowSource, /form\.value\.foundryImage/); + assert.match(itemWindowSource, /updateItem\(\{ image: form\.value\.foundryImage \}\)/); + // uploads resolve as backend /public files, world URLs load as they are + assert.match(itemWindowSource, /\$\{getBaseUrl\(\)\}\/public\//); +}); + +test("the Foundry module sends item icons as URLs Dragonroll can load", () => { + // actor-embedded items go through the same serializer as world items + assert.match(moduleSource, /items:\s*\(actor\.items\?\.contents\?\.map\(serializeFoundryItem\)/); + // the icon chosen in Dragonroll travels back into the linked world + assert.match(moduleSource, /const image = getDragonrollImageUrl\(entry\.image\);\s*if \(image\) updates\.img = image;/); + assert.match(moduleSource, /img: getDragonrollImageUrl\(entry\.image\) \|\| undefined,\s*system:/); +}); + +test("every locale names the item window and its icon controls", () => { + for (const locale of ["en", "es", "ca"]) { + const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json")); + assert.ok(windows["item-sheet"], `${locale} is missing the item window title`); + const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json")); + for (const key of ["choose-icon", "change-icon", "foundry-icon", "remove-icon", "upload-error"]) { + assert.ok(campaigns.item?.sheet?.[key], `${locale} is missing campaigns.item.sheet.${key}`); + } + } +});