From b47bbb4cabe15389a5e2022acdf8c670138b68b5 Mon Sep 17 00:00:00 2001 From: Gitea OpenCode Agent Date: Thu, 15 Oct 2026 16:01:36 +0000 Subject: [PATCH] Fix issue #65: Item selecting icon --- AGENTS.md | 2 +- backend/src/routes/foundry.js | 44 +++++ backend/src/services/foundry-icons.js | 110 ++++++++++++ dragonroll-foundry/README.md | 11 ++ dragonroll-foundry/bridge/server.js | 83 +++++++++ .../windows/FoundryIconPickerWindow.vue | 166 +++++++++++++++++ .../windows/ItemIconSourceWindow.vue | 128 +++++++++++++ .../components/windows/ItemSheetWindow.vue | 87 ++++----- frontend/app/services/WindowDefinitions.js | 15 ++ frontend/i18n/locales/ca/campaigns.json | 5 + frontend/i18n/locales/ca/foundry.json | 11 +- frontend/i18n/locales/ca/windows.json | 4 +- frontend/i18n/locales/en/campaigns.json | 5 + frontend/i18n/locales/en/foundry.json | 11 +- frontend/i18n/locales/en/windows.json | 4 +- frontend/i18n/locales/es/campaigns.json | 5 + frontend/i18n/locales/es/foundry.json | 11 +- frontend/i18n/locales/es/windows.json | 4 +- tests/foundry-icon-picker.test.js | 170 ++++++++++++++++++ tests/item-sheet-window.test.js | 6 +- 20 files changed, 823 insertions(+), 59 deletions(-) create mode 100644 backend/src/services/foundry-icons.js create mode 100644 frontend/app/components/windows/FoundryIconPickerWindow.vue create mode 100644 frontend/app/components/windows/ItemIconSourceWindow.vue create mode 100644 tests/foundry-icon-picker.test.js diff --git a/AGENTS.md b/AGENTS.md index 5155922e..3a13b5bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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` - `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}`) -- `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) diff --git a/backend/src/routes/foundry.js b/backend/src/routes/foundry.js index 84aa0af8..ef669552 100644 --- a/backend/src/routes/foundry.js +++ b/backend/src/routes/foundry.js @@ -1,6 +1,16 @@ const express = require('express'); const router = express.Router(); 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) { 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('/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; diff --git a/backend/src/services/foundry-icons.js b/backend/src/services/foundry-icons.js new file mode 100644 index 00000000..5e612abb --- /dev/null +++ b/backend/src/services/foundry-icons.js @@ -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 +}; diff --git a/dragonroll-foundry/README.md b/dragonroll-foundry/README.md index 034fdaef..f877f128 100644 --- a/dragonroll-foundry/README.md +++ b/dragonroll-foundry/README.md @@ -135,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_HOST='0.0.0.0' 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 ``` @@ -170,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/items` | World-level items | | `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 `Authorization: Bearer `. Responses contain `{ status: "ok", data, world, syncedAt, @@ -177,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 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 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. diff --git a/dragonroll-foundry/bridge/server.js b/dragonroll-foundry/bridge/server.js index 6943db32..c70f499d 100644 --- a/dragonroll-foundry/bridge/server.js +++ b/dragonroll-foundry/bridge/server.js @@ -1,4 +1,6 @@ const http = require("node:http"); +const fs = require("node:fs"); +const path = require("node:path"); const { timingSafeEqual } = require("node:crypto"); const host = process.env.DRAGONROLL_FOUNDRY_HOST || "0.0.0.0"; @@ -12,6 +14,9 @@ const allowedOrigins = new Set( .filter(Boolean), ); 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) { 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) => { if (!setCorsHeaders(request, response)) { sendJson(response, 403, { status: "error", msg: "foundry.origin-not-allowed" }); @@ -188,6 +267,10 @@ const server = http.createServer(async (request, response) => { 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); if (!current) return; diff --git a/frontend/app/components/windows/FoundryIconPickerWindow.vue b/frontend/app/components/windows/FoundryIconPickerWindow.vue new file mode 100644 index 00000000..cf873ad2 --- /dev/null +++ b/frontend/app/components/windows/FoundryIconPickerWindow.vue @@ -0,0 +1,166 @@ + + + + + diff --git a/frontend/app/components/windows/ItemIconSourceWindow.vue b/frontend/app/components/windows/ItemIconSourceWindow.vue new file mode 100644 index 00000000..6c8c487c --- /dev/null +++ b/frontend/app/components/windows/ItemIconSourceWindow.vue @@ -0,0 +1,128 @@ + + + + + diff --git a/frontend/app/components/windows/ItemSheetWindow.vue b/frontend/app/components/windows/ItemSheetWindow.vue index d6c2e935..4adfb180 100644 --- a/frontend/app/components/windows/ItemSheetWindow.vue +++ b/frontend/app/components/windows/ItemSheetWindow.vue @@ -1,9 +1,10 @@ @@ -132,10 +120,12 @@ async function removeIcon() {
-
+
+

{{ form.name }}

@@ -149,16 +139,13 @@ async function removeIcon() {
{{ error }}
- - - - +
@@ -189,7 +176,8 @@ async function removeIcon() { .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-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 img { width: 100%; height: 100%; object-fit: contain; } .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:hover { background: var(--color-button-hover); } .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-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; } diff --git a/frontend/app/services/WindowDefinitions.js b/frontend/app/services/WindowDefinitions.js index 115cc3aa..5b51fd6a 100644 --- a/frontend/app/services/WindowDefinitions.js +++ b/frontend/app/services/WindowDefinitions.js @@ -88,6 +88,21 @@ const defWindows = { close: () => ClearWindow({type: 'item_sheet'}), 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: { 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 33097529..e1f1cf49 100644 --- a/frontend/i18n/locales/ca/campaigns.json +++ b/frontend/i18n/locales/ca/campaigns.json @@ -73,6 +73,11 @@ "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." }, + "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": { "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/foundry.json b/frontend/i18n/locales/ca/foundry.json index 9d2696c9..e61d3db2 100644 --- a/frontend/i18n/locales/ca/foundry.json +++ b/frontend/i18n/locales/ca/foundry.json @@ -3,6 +3,15 @@ "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.", "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" } } diff --git a/frontend/i18n/locales/ca/windows.json b/frontend/i18n/locales/ca/windows.json index bb86f379..792fb2f4 100644 --- a/frontend/i18n/locales/ca/windows.json +++ b/frontend/i18n/locales/ca/windows.json @@ -10,5 +10,7 @@ "create-map": "Crear mapa", "map-viewer": "Mapa", "pinned-note": "Nota fixada", - "item-sheet": "Objecte" + "item-sheet": "Objecte", + "icon-source": "Tria una icona", + "foundry-icons": "Icones del Foundry" } diff --git a/frontend/i18n/locales/en/campaigns.json b/frontend/i18n/locales/en/campaigns.json index 05c6508c..a01cd827 100644 --- a/frontend/i18n/locales/en/campaigns.json +++ b/frontend/i18n/locales/en/campaigns.json @@ -77,6 +77,11 @@ "foundry-icon": "Use Foundry icon", "remove-icon": "Remove icon", "save-error": "Unable to save this item.", "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": { "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/foundry.json b/frontend/i18n/locales/en/foundry.json index 78e267a9..ad13d5d9 100644 --- a/frontend/i18n/locales/en/foundry.json +++ b/frontend/i18n/locales/en/foundry.json @@ -3,6 +3,15 @@ "link-expired": "This Foundry pairing code is invalid, expired, or already used.", "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.", - "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" } } diff --git a/frontend/i18n/locales/en/windows.json b/frontend/i18n/locales/en/windows.json index e063057f..b1b98510 100644 --- a/frontend/i18n/locales/en/windows.json +++ b/frontend/i18n/locales/en/windows.json @@ -10,5 +10,7 @@ "create-map": "Create Map", "map-viewer": "Map", "pinned-note": "Pinned note", - "item-sheet": "Item" + "item-sheet": "Item", + "icon-source": "Choose an icon", + "foundry-icons": "Foundry icons" } diff --git a/frontend/i18n/locales/es/campaigns.json b/frontend/i18n/locales/es/campaigns.json index e87cf653..23aa0b5c 100644 --- a/frontend/i18n/locales/es/campaigns.json +++ b/frontend/i18n/locales/es/campaigns.json @@ -73,6 +73,11 @@ "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." }, + "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": { "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/foundry.json b/frontend/i18n/locales/es/foundry.json index 8e4a2306..9949d98a 100644 --- a/frontend/i18n/locales/es/foundry.json +++ b/frontend/i18n/locales/es/foundry.json @@ -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.", "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.", - "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" } } diff --git a/frontend/i18n/locales/es/windows.json b/frontend/i18n/locales/es/windows.json index 23e5817e..fb897d13 100644 --- a/frontend/i18n/locales/es/windows.json +++ b/frontend/i18n/locales/es/windows.json @@ -10,5 +10,7 @@ "create-map": "Crear mapa", "map-viewer": "Mapa", "pinned-note": "Nota fijada", - "item-sheet": "Objeto" + "item-sheet": "Objeto", + "icon-source": "Elegir icono", + "foundry-icons": "Iconos de Foundry" } diff --git a/tests/foundry-icon-picker.test.js b/tests/foundry-icon-picker.test.js new file mode 100644 index 00000000..c6fa7e0a --- /dev/null +++ b/tests/foundry-icon-picker.test.js @@ -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}`); + } + } +}); diff --git a/tests/item-sheet-window.test.js b/tests/item-sheet-window.test.js index 07d55c40..e31834e5 100644 --- a/tests/item-sheet-window.test.js +++ b/tests/item-sheet-window.test.js @@ -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"]) { 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=/); + // own icon: #65 moved picking one into a window of its own, which uploads through + // 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 assert.match(itemWindowSource, /form\.value\.foundryImage/); assert.match(itemWindowSource, /updateItem\(\{ image: form\.value\.foundryImage \}\)/);