From dd4c9535d3d0f7201f75aa92bbfae4be70ce56e9 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 | 7 +- 20 files changed, 823 insertions(+), 60 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 fa574c7c..e3504573 100644 --- a/frontend/app/components/windows/ItemSheetWindow.vue +++ b/frontend/app/components/windows/ItemSheetWindow.vue @@ -1,9 +1,10 @@ @@ -131,10 +119,12 @@ async function removeIcon() {
-
+
+

{{ form.name }}

@@ -148,16 +138,13 @@ async function removeIcon() {
{{ error }}
- - - - +