Compare commits
15 Commits
7e1ed4475e
...
ai/issue-6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b47bbb4cab | ||
| cdafd1f53a | |||
| 2e2fb97e5d | |||
|
|
d03cc1eb59 | ||
| 20128d195b | |||
| d901385900 | |||
|
|
2add9e7cb8 | ||
| fe63bd15f3 | |||
| 733e7ef193 | |||
| d566388fc6 | |||
| 86e1d34beb | |||
| cd741880ac | |||
| 378e28f703 | |||
|
|
0c6026aea8 | ||
|
|
844ed006cc |
@@ -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)
|
||||
|
||||
@@ -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' });
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -193,4 +193,113 @@ router.get('/get-settings', passport.authenticate('jwt', {session: false}), asyn
|
||||
}
|
||||
});
|
||||
|
||||
// -- Account management (the "Manage accounts" window of the site settings) ----
|
||||
// /api/user is mounted before the JWT guard, so every route below authenticates
|
||||
// inline; and only an administrator gets past isAdmin (services/middleware.js).
|
||||
|
||||
router.get('/list', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => {
|
||||
try {
|
||||
// No account gets out with its password or an unfinished setup code.
|
||||
const users = await User.find().select('-password -setupCode').sort({ date: 1 });
|
||||
res.json({ status: "ok", users });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: "error", msg: "errors.internal" });
|
||||
}
|
||||
});
|
||||
|
||||
// The admin creates the account with the password its user logs in with; the
|
||||
// setupCode flow above stays as it is, nothing on the frontend completes it.
|
||||
router.post('/create', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => {
|
||||
try {
|
||||
const { name, username, email, password } = req.body;
|
||||
if (!(name && username && email && password)) {
|
||||
return res.json({ status: "error", msg: "errors.missing-data" });
|
||||
}
|
||||
|
||||
const existingUser = await User.findOne({
|
||||
$or: [
|
||||
{ email: email },
|
||||
{ username: username }
|
||||
]
|
||||
});
|
||||
if (existingUser) {
|
||||
return res.json({
|
||||
status: "error",
|
||||
msg: "register.errors.email-username-exists"
|
||||
});
|
||||
}
|
||||
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
let user = new User({
|
||||
name: name,
|
||||
username: username,
|
||||
email: email,
|
||||
password: await bcrypt.hash(password, salt)
|
||||
});
|
||||
await user.save();
|
||||
res.json({
|
||||
status: "ok",
|
||||
user: {
|
||||
_id: user._id,
|
||||
name: user.name,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
admin: user.admin,
|
||||
date: user.date
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: "error", msg: "errors.internal" });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/set-admin', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => {
|
||||
try {
|
||||
const { id, admin } = req.body;
|
||||
if (!id || typeof admin !== 'boolean') {
|
||||
return res.json({ status: "error", msg: "errors.missing-data" });
|
||||
}
|
||||
|
||||
// Switching one's own rights off could leave an instance with nobody who
|
||||
// can manage accounts at all, so the row for yourself stays closed.
|
||||
if (String(req.user._id) === String(id)) {
|
||||
return res.json({ status: "error", msg: "settings.site-administration.accounts.errors.self-admin" });
|
||||
}
|
||||
|
||||
const user = await User.findOne({ _id: id });
|
||||
if (!user) return res.json({ status: "error", msg: "errors.notfound" });
|
||||
|
||||
user.admin = admin;
|
||||
await user.save();
|
||||
res.json({ status: "ok", user: { _id: user._id, admin: user.admin } });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: "error", msg: "errors.internal" });
|
||||
}
|
||||
});
|
||||
|
||||
// Only the account itself goes; what it created stays as it is.
|
||||
router.post('/delete', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => {
|
||||
try {
|
||||
const { id } = req.body;
|
||||
if (!id) return res.json({ status: "error", msg: "errors.missing-data" });
|
||||
|
||||
// Same guard as the admin switch: nobody locks themselves out on the way out.
|
||||
if (String(req.user._id) === String(id)) {
|
||||
return res.json({ status: "error", msg: "settings.site-administration.accounts.errors.self-delete" });
|
||||
}
|
||||
|
||||
const user = await User.findOne({ _id: id });
|
||||
if (!user) return res.json({ status: "error", msg: "errors.notfound" });
|
||||
|
||||
await user.deleteOne();
|
||||
res.json({ status: "ok" });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: "error", msg: "errors.internal" });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
110
backend/src/services/foundry-icons.js
Normal file
110
backend/src/services/foundry-icons.js
Normal file
@@ -0,0 +1,110 @@
|
||||
// Foundry's core icon library is the `icons/` folder of its data directory: a few
|
||||
// thousand images spread over its own folder tree. Dragonroll never reads that
|
||||
// tree itself — the bridge on the Foundry host lists one folder per request (see
|
||||
// dragonroll-foundry/bridge/server.js) — but everything that goes over the wire is
|
||||
// normalised here first, so a caller cannot ask for a folder outside the icon root.
|
||||
|
||||
const ICON_ROOT = 'icons';
|
||||
|
||||
// Image formats Foundry's own file picker offers.
|
||||
const ICON_EXTENSIONS = ['.svg', '.png', '.webp', '.jpg', '.jpeg', '.gif', '.avif'];
|
||||
|
||||
// How many icons one request lists. The window asks again for the next page, so a
|
||||
// folder with hundreds of them is never sent or rendered all at once.
|
||||
const DEFAULT_ICON_PAGE_SIZE = 120;
|
||||
const MAX_ICON_PAGE_SIZE = 500;
|
||||
|
||||
// The folder a listing request asks for, inside the icon root: `icons`, `icons/svg`,
|
||||
// ... Empty asks for the root. Anything that tries to leave the root is invalid.
|
||||
function normalizeIconDirectory(input) {
|
||||
const raw = String(input ?? '').trim().replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
|
||||
if (!raw || raw === '.') return ICON_ROOT;
|
||||
|
||||
const segments = raw.split('/').filter((segment) => segment && segment !== '.');
|
||||
if (!segments.length || segments.includes('..')) return null;
|
||||
if (segments[0] !== ICON_ROOT) return null;
|
||||
return segments.join('/');
|
||||
}
|
||||
|
||||
// The folder above an icon folder, or null at the root.
|
||||
function parentIconDirectory(dir) {
|
||||
const normalized = normalizeIconDirectory(dir);
|
||||
if (!normalized || normalized === ICON_ROOT) return null;
|
||||
return normalized.slice(0, normalized.lastIndexOf('/'));
|
||||
}
|
||||
function iconName(filePath) {
|
||||
const path = String(filePath ?? '');
|
||||
return path.slice(path.lastIndexOf('/') + 1);
|
||||
}
|
||||
|
||||
function isIconFile(filePath) {
|
||||
const lower = String(filePath ?? '').toLowerCase();
|
||||
return ICON_EXTENSIONS.some((extension) => lower.endsWith(extension));
|
||||
}
|
||||
|
||||
// Where the browser loads a Foundry data file from: Foundry serves its data
|
||||
// directory over the world's own address, which is the one the campaign keeps
|
||||
// (settings.integrations.foundryUrl). Items store icons as these absolute URLs,
|
||||
// the same way a synced Foundry item's icon arrives as one.
|
||||
function joinFoundryAssetUrl(baseUrl, filePath) {
|
||||
const base = String(baseUrl ?? '').trim();
|
||||
const file = String(filePath ?? '').trim().replace(/^\/+/, '');
|
||||
if (!base || !file) return '';
|
||||
return `${base.replace(/\/+$/, '')}/${encodeURI(file)}`;
|
||||
}
|
||||
|
||||
// The page a request asks for. Directories are always listed whole — the window
|
||||
// needs every subfolder to navigate — so paging only ever covers the icons.
|
||||
function readIconListingPage(query) {
|
||||
const requestedLimit = Number(query?.limit);
|
||||
const limit = Number.isFinite(requestedLimit)
|
||||
? Math.min(MAX_ICON_PAGE_SIZE, Math.max(1, Math.trunc(requestedLimit)))
|
||||
: DEFAULT_ICON_PAGE_SIZE;
|
||||
const requestedOffset = Number(query?.offset);
|
||||
const offset = Number.isFinite(requestedOffset) ? Math.max(0, Math.trunc(requestedOffset)) : 0;
|
||||
|
||||
return { limit, offset };
|
||||
}
|
||||
|
||||
// The bridge answers with plain relative paths; this is the shape the icon window
|
||||
// works with: the folder it shows, the one above it, its subfolders, and its icons
|
||||
// with a url to load. `next` is the offset of the next page, null once it is all
|
||||
// listed, which is what keeps a big library lazy to load.
|
||||
function shapeIconListing({ base = '', dir, listing = {} } = {}) {
|
||||
const current = normalizeIconDirectory(dir ?? listing.dir) || ICON_ROOT;
|
||||
|
||||
const folders = [];
|
||||
const seenFolders = new Set();
|
||||
for (const entry of Array.isArray(listing.directories) ? listing.directories : []) {
|
||||
const path = normalizeIconDirectory(typeof entry === 'string' ? entry : entry?.path);
|
||||
if (!path || path === current || seenFolders.has(path)) continue;
|
||||
seenFolders.add(path);
|
||||
folders.push({ path, name: iconName(path) });
|
||||
}
|
||||
|
||||
const files = (Array.isArray(listing.files) ? listing.files : [])
|
||||
.map((entry) => String(typeof entry === 'string' ? entry : entry?.path ?? '').trim().replace(/^\/+/, ''))
|
||||
.filter((entry) => entry.startsWith(`${ICON_ROOT}/`) && isIconFile(entry))
|
||||
.map((entry) => ({ path: entry, name: iconName(entry), url: joinFoundryAssetUrl(base, entry) }));
|
||||
|
||||
const offset = Number.isFinite(Number(listing.offset)) ? Math.max(0, Math.trunc(Number(listing.offset))) : 0;
|
||||
const next = Number.isFinite(Number(listing.next)) && Number(listing.next) > offset
|
||||
? Math.trunc(Number(listing.next))
|
||||
: null;
|
||||
|
||||
return { dir: current, parent: parentIconDirectory(current), folders, files, offset, next };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ICON_ROOT,
|
||||
ICON_EXTENSIONS,
|
||||
DEFAULT_ICON_PAGE_SIZE,
|
||||
MAX_ICON_PAGE_SIZE,
|
||||
normalizeIconDirectory,
|
||||
parentIconDirectory,
|
||||
iconName,
|
||||
isIconFile,
|
||||
joinFoundryAssetUrl,
|
||||
readIconListingPage,
|
||||
shapeIconListing
|
||||
};
|
||||
@@ -96,6 +96,10 @@ The campaign's Item list is synchronized with the world's gear, both ways:
|
||||
properties, description). An item made by hand in Dragonroll is created in the world's item
|
||||
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
|
||||
|
||||
@@ -130,6 +135,9 @@ export DRAGONROLL_FOUNDRY_PUSH_TOKEN='replace-with-a-different-long-random-publi
|
||||
export DRAGONROLL_FOUNDRY_ALLOWED_ORIGINS='https://vtt.example.com'
|
||||
export DRAGONROLL_FOUNDRY_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
|
||||
```
|
||||
|
||||
@@ -165,6 +173,7 @@ The backend exposes these JWT-protected routes when the optional snapshot bridge
|
||||
| `GET /api/foundry/actors/:id/items` | Items embedded in an actor |
|
||||
| `GET /api/foundry/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 <read-token>`. Responses contain `{ status: "ok", data, world, syncedAt,
|
||||
@@ -172,6 +181,13 @@ ageSeconds, stale }`. The snapshot stays in memory; `stale` becomes true when th
|
||||
received a GM heartbeat for more than two minutes. The bridge returns `503 foundry.not-ready` until a
|
||||
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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { AnchorMap, AnchoredMap, ClearAnchoredMap, SetActivePane } from '~/servi
|
||||
import { emitter } from '~/services/Emitter';
|
||||
import { BuildColorMenu } from '~/services/EntryColors';
|
||||
import { BuildItemRows } from '~/services/ItemFolders';
|
||||
import Server from '~/services/Server';
|
||||
import Server, { getBaseUrl } from '~/services/Server';
|
||||
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
|
||||
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
|
||||
import { ACTOR_DRAG_TYPE } from '~/services/MapTokens';
|
||||
@@ -283,6 +283,13 @@ function itemSummary(item) {
|
||||
return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`;
|
||||
}
|
||||
|
||||
// An item's icon in the sidebar: an uploaded filename served from /api/public, or a full URL
|
||||
// (Foundry sends its own icon as one) — the same rule the item window uses.
|
||||
function itemImageUrl(image) {
|
||||
if (!image) return '';
|
||||
return /^(https?:|data:|\/\/)/i.test(image) ? image : `${getBaseUrl()}/public/${image}`;
|
||||
}
|
||||
|
||||
function mapSummary(map) {
|
||||
return t('campaigns.map.summary', { size: map.gridSize, scale: map.scale });
|
||||
}
|
||||
@@ -670,9 +677,11 @@ onBeforeUnmount(() => {
|
||||
@toggle="toggleFolder(row.folder._id)"
|
||||
/>
|
||||
<div v-else class="entity-entry" :style="rowIndent(row.depth)" role="button" tabindex="0" @click="openItemSheet(row.item)" @keydown.enter="openItemSheet(row.item)" @keydown.space.prevent="openItemSheet(row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'item')">
|
||||
<span class="entity-entry-name-row">
|
||||
<span class="entity-entry-title">
|
||||
<span v-if="row.item.image" class="entity-entry-image" aria-hidden="true">
|
||||
<img :src="itemImageUrl(row.item.image)" alt="">
|
||||
</span>
|
||||
<span class="entity-entry-name">{{ row.item.name }}</span>
|
||||
<span v-if="row.item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span>
|
||||
</span>
|
||||
<span class="entity-entry-meta">{{ itemSummary(row.item) }}</span>
|
||||
</div>
|
||||
@@ -865,6 +874,15 @@ onBeforeUnmount(() => {
|
||||
}
|
||||
.entity-entry-meta, .entity-entry-description { font-size: 12px; opacity: 0.72; }
|
||||
.entity-entry-description { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
|
||||
/* An item row leads with the item's own icon on the left of its name, standing in for the
|
||||
"SYNCED" text it used to show (Syndria98/dragonroll#53). */
|
||||
.entity-entry-title { display: flex; align-items: center; gap: 9px; min-width: 0; }
|
||||
.entity-entry-image {
|
||||
flex: 0 0 30px; width: 30px; height: 30px; box-sizing: border-box;
|
||||
display: grid; place-items: center; overflow: hidden;
|
||||
border: 1px solid var(--color-border); border-radius: 6px; background: var(--color-background-soft);
|
||||
}
|
||||
.entity-entry-image img { width: 100%; height: 100%; object-fit: contain; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.notes-sidebar {
|
||||
|
||||
289
frontend/app/components/windows/AccountManagementWindow.vue
Normal file
289
frontend/app/components/windows/AccountManagementWindow.vue
Normal file
@@ -0,0 +1,289 @@
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
import WindowHandle from './partials/WindowHandle.vue';
|
||||
import Server from '~/services/Server';
|
||||
import { DisplayToast } from '~/services/Toaster';
|
||||
import { GetUser } from '@/services/User';
|
||||
import { SetupHandle, SetSize, ResetPosition, Top, SetResizable, SetMinSize } from '@/services/Windows';
|
||||
|
||||
const handle = ref(null);
|
||||
const wrapper = ref(null);
|
||||
|
||||
const props = defineProps(['data']);
|
||||
const data = props.data;
|
||||
|
||||
const id = data.id;
|
||||
|
||||
// The admin standing in front of the window: their own row keeps the switches closed,
|
||||
// the server answers the same to anybody who still tries (routes/user.js).
|
||||
const currentUserId = GetUser()?._id;
|
||||
|
||||
const users = ref([]);
|
||||
const busy = ref("");
|
||||
|
||||
const creating = ref(false);
|
||||
const name = ref("");
|
||||
const username = ref("");
|
||||
const email = ref("");
|
||||
const password = ref("");
|
||||
|
||||
onMounted(() => {
|
||||
Top(wrapper);
|
||||
SetupHandle(id, handle);
|
||||
SetSize(id, {width: 620, height: 520});
|
||||
ResetPosition(id, "center");
|
||||
SetResizable(id, true);
|
||||
SetMinSize(id, {width: 460, height: 360});
|
||||
|
||||
LoadUsers();
|
||||
});
|
||||
|
||||
async function LoadUsers(){
|
||||
try {
|
||||
const response = await Server().get('/user/list');
|
||||
if(response.data.status !== 'ok') return;
|
||||
users.value = response.data.users || [];
|
||||
} catch {
|
||||
DisplayToast('red', $t('errors.internal'), 3000);
|
||||
}
|
||||
}
|
||||
|
||||
function ClearForm(){
|
||||
name.value = "";
|
||||
username.value = "";
|
||||
email.value = "";
|
||||
password.value = "";
|
||||
}
|
||||
|
||||
async function CreateAccount(){
|
||||
// The checks the register window makes before it asks the server for an account
|
||||
if(username.value.length < 3){
|
||||
DisplayToast('red', $t('settings.site-administration.accounts.errors.username-empty'), 3000);
|
||||
return;
|
||||
}
|
||||
if(email.value.length < 5 || !email.value.includes('@')){
|
||||
DisplayToast('red', $t('settings.site-administration.accounts.errors.email-empty'), 3000);
|
||||
return;
|
||||
}
|
||||
if(name.value.length == 0){
|
||||
DisplayToast('red', $t('settings.site-administration.accounts.errors.name-empty'), 3000);
|
||||
return;
|
||||
}
|
||||
if(password.value.length == 0){
|
||||
DisplayToast('red', $t('settings.site-administration.accounts.errors.password-empty'), 3000);
|
||||
return;
|
||||
}
|
||||
|
||||
creating.value = true;
|
||||
try {
|
||||
const response = await Server().post('/user/create', {
|
||||
name: name.value,
|
||||
username: username.value,
|
||||
email: email.value,
|
||||
password: password.value
|
||||
});
|
||||
if(response.data.status !== 'ok'){
|
||||
DisplayToast('red', $t(response.data.msg || 'errors.internal'), 3000);
|
||||
return;
|
||||
}
|
||||
users.value.push(response.data.user);
|
||||
ClearForm();
|
||||
DisplayToast('green', $t('settings.site-administration.accounts.created'), 3000);
|
||||
} catch {
|
||||
DisplayToast('red', $t('errors.internal'), 3000);
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function ToggleAdmin(user){
|
||||
busy.value = user._id;
|
||||
try {
|
||||
const response = await Server().post('/user/set-admin', { id: user._id, admin: !user.admin });
|
||||
if(response.data.status !== 'ok'){
|
||||
DisplayToast('red', $t(response.data.msg || 'errors.internal'), 3000);
|
||||
return;
|
||||
}
|
||||
user.admin = response.data.user.admin;
|
||||
DisplayToast('green', $t('settings.site-administration.accounts.updated'), 3000);
|
||||
} catch {
|
||||
DisplayToast('red', $t('errors.internal'), 3000);
|
||||
} finally {
|
||||
busy.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function DeleteAccount(user){
|
||||
busy.value = user._id;
|
||||
try {
|
||||
const response = await Server().post('/user/delete', { id: user._id });
|
||||
if(response.data.status !== 'ok'){
|
||||
DisplayToast('red', $t(response.data.msg || 'errors.internal'), 3000);
|
||||
return;
|
||||
}
|
||||
users.value = users.value.filter((account) => account._id !== user._id);
|
||||
DisplayToast('green', $t('settings.site-administration.accounts.deleted'), 3000);
|
||||
} catch {
|
||||
DisplayToast('red', $t('errors.internal'), 3000);
|
||||
} finally {
|
||||
busy.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
function IsSelf(user){
|
||||
return user._id === currentUserId;
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<template>
|
||||
<div class="window-wrapper" :id="'window-wrapper-' + id" ref="wrapper">
|
||||
<WindowHandle :window="id" ref="handle"></WindowHandle>
|
||||
|
||||
<!-- Body -->
|
||||
<div class="accounts-body">
|
||||
<div class="accounts-list">
|
||||
<div v-for="user in users" :key="user._id" class="account-row">
|
||||
<div class="account-info">
|
||||
<span class="account-name">{{ user.name }} <span v-if="IsSelf(user)" class="account-self">({{ $t('settings.site-administration.accounts.you') }})</span></span>
|
||||
<span class="account-line">@{{ user.username }}</span>
|
||||
<span class="account-line">{{ user.email }}</span>
|
||||
<span v-if="user.admin" class="account-admin">{{ $t('settings.site-administration.accounts.admin') }}</span>
|
||||
</div>
|
||||
<div class="account-actions" v-if="!IsSelf(user)">
|
||||
<button class="btn-primary button-small sound-click" type="button" :disabled="busy !== ''" v-on:click.prevent="ToggleAdmin(user)">
|
||||
{{ user.admin ? $t('settings.site-administration.accounts.remove-admin') : $t('settings.site-administration.accounts.make-admin') }}
|
||||
</button>
|
||||
<button class="btn-primary button-small danger sound-click" type="button" :disabled="busy !== ''" v-on:click.prevent="DeleteAccount(user)">
|
||||
{{ $t('settings.site-administration.accounts.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form class="new-account" v-on:submit.prevent="CreateAccount">
|
||||
<h3>{{ $t('settings.site-administration.accounts.new-account') }}</h3>
|
||||
<div class="form-field">
|
||||
<label for="account-name-field">{{$t('settings.site-administration.accounts.name')}}</label>
|
||||
<input id="account-name-field" type="text" name="name" v-model="name" autocomplete="off">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label for="account-username-field">{{$t('settings.site-administration.accounts.username')}}</label>
|
||||
<input id="account-username-field" type="text" name="username" v-model="username" autocomplete="off">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label for="account-email-field">{{$t('settings.site-administration.accounts.email')}}</label>
|
||||
<input id="account-email-field" type="email" name="email" v-model="email" autocomplete="off">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label for="account-password-field">{{$t('settings.site-administration.accounts.password')}}</label>
|
||||
<input id="account-password-field" type="password" name="password" v-model="password" autocomplete="off">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<button class="btn-primary sound-click" type="submit" :disabled="creating">
|
||||
{{ $t('settings.site-administration.accounts.create') }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
<style scoped>
|
||||
.window-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.accounts-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.accounts-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.account-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
background-color: var(--color-background-soft);
|
||||
}
|
||||
|
||||
.account-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.account-name {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.account-line {
|
||||
font-size: 13px;
|
||||
opacity: 0.75;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.account-self {
|
||||
font-weight: normal;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.account-admin {
|
||||
color: var(--color-green);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.account-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.danger {
|
||||
color: var(--color-red);
|
||||
}
|
||||
|
||||
.new-account {
|
||||
padding: 0 16px 16px 16px;
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.new-account h3 {
|
||||
font-family: MrEavesRemake;
|
||||
}
|
||||
|
||||
.form-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.form-field input {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
label {
|
||||
text-align: left;
|
||||
}
|
||||
</style>
|
||||
@@ -24,6 +24,16 @@ const abilityStats = [
|
||||
{ key: 'int', label: 'INT' }, { key: 'wis', label: 'WIS' }, { key: 'cha', label: 'CHA' }
|
||||
];
|
||||
|
||||
// Les pestanyes del lateral dret reparteixen la fitxa: característiques i combat,
|
||||
// inventari, trets i conjurs. Són pestanyes de marcadors, no una pàgina nova.
|
||||
const tabs = [
|
||||
{ key: 'abilities', label: 'campaigns.character-sheet.tabs.abilities' },
|
||||
{ key: 'inventory', label: 'campaigns.character-sheet.tabs.inventory' },
|
||||
{ key: 'traits', label: 'campaigns.character-sheet.tabs.traits' },
|
||||
{ key: 'spells', label: 'campaigns.character-sheet.tabs.spells' }
|
||||
];
|
||||
const activeTab = ref('abilities');
|
||||
|
||||
function normalizeActor(actor) {
|
||||
return {
|
||||
name: actor?.name ?? '',
|
||||
@@ -207,101 +217,124 @@ async function saveSheet() {
|
||||
|
||||
<div v-if="error" class="sheet-error">{{ error }}</div>
|
||||
|
||||
<main class="sheet-grid">
|
||||
<div v-if="form.image || editing" class="sheet-portrait" :class="{ empty: !form.image }">
|
||||
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.character-sheet.photo')">
|
||||
<button v-if="editing && !form.image" class="portrait-upload" type="button" :disabled="uploadingPhoto" @click="pickPhoto">
|
||||
{{ uploadingPhoto ? $t('campaigns.character-sheet.uploading-photo') : $t('campaigns.character-sheet.upload-photo') }}
|
||||
</button>
|
||||
<div v-if="editing && form.image" class="portrait-controls">
|
||||
<button type="button" :disabled="uploadingPhoto" @click="pickPhoto">
|
||||
{{ uploadingPhoto ? $t('campaigns.character-sheet.uploading-photo') : $t('campaigns.character-sheet.change-photo') }}
|
||||
</button>
|
||||
<button type="button" :disabled="uploadingPhoto" :aria-label="$t('campaigns.character-sheet.remove-photo')" @click="removePhoto">×</button>
|
||||
</div>
|
||||
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onPhotoSelected">
|
||||
<div class="sheet-layout">
|
||||
<div class="sheet-content">
|
||||
<main v-show="activeTab === 'abilities'" class="sheet-grid">
|
||||
<div v-if="form.image || editing" class="sheet-portrait" :class="{ empty: !form.image }">
|
||||
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.character-sheet.photo')">
|
||||
<button v-if="editing && !form.image" class="portrait-upload" type="button" :disabled="uploadingPhoto" @click="pickPhoto">
|
||||
{{ uploadingPhoto ? $t('campaigns.character-sheet.uploading-photo') : $t('campaigns.character-sheet.upload-photo') }}
|
||||
</button>
|
||||
<div v-if="editing && form.image" class="portrait-controls">
|
||||
<button type="button" :disabled="uploadingPhoto" @click="pickPhoto">
|
||||
{{ uploadingPhoto ? $t('campaigns.character-sheet.uploading-photo') : $t('campaigns.character-sheet.change-photo') }}
|
||||
</button>
|
||||
<button type="button" :disabled="uploadingPhoto" :aria-label="$t('campaigns.character-sheet.remove-photo')" @click="removePhoto">×</button>
|
||||
</div>
|
||||
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onPhotoSelected">
|
||||
</div>
|
||||
|
||||
<section class="sheet-panel abilities-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.ability-scores') }}</h2>
|
||||
<div class="ability-grid">
|
||||
<div v-for="stat in abilityStats" :key="stat.key" class="ability-card">
|
||||
<span class="ability-label">{{ stat.label }}</span>
|
||||
<input v-if="editing" v-model.number="form.abilityScores[stat.key]" type="number" min="1" max="30" :aria-label="stat.label">
|
||||
<strong v-else class="ability-score">{{ form.abilityScores[stat.key] }}</strong>
|
||||
<span class="ability-modifier">{{ abilityModifier(form.abilityScores[stat.key]) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="proficiency-badge">
|
||||
<span>{{ $t('campaigns.character-sheet.proficiency-bonus') }}</span>
|
||||
<strong>+{{ proficiencyBonus }}</strong>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="sheet-panel combat-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.combat') }}</h2>
|
||||
<div class="combat-stats">
|
||||
<div class="combat-stat">
|
||||
<span>{{ $t('campaigns.character-sheet.armor-class') }}</span>
|
||||
<input v-if="editing" v-model.number="form.armorClass" type="number" min="0">
|
||||
<strong v-else>{{ form.armorClass }}</strong>
|
||||
</div>
|
||||
<div class="combat-stat">
|
||||
<span>{{ $t('campaigns.character-sheet.speed') }}</span>
|
||||
<label v-if="editing" class="number-with-unit"><input v-model.number="form.speed" type="number" min="0"><small>ft</small></label>
|
||||
<strong v-else>{{ form.speed }} <small>ft</small></strong>
|
||||
</div>
|
||||
</div>
|
||||
<h3>{{ $t('campaigns.character-sheet.proficiencies') }}</h3>
|
||||
<textarea v-if="editing" v-model="form.proficiencies" rows="5" :placeholder="$t('campaigns.character-sheet.proficiencies-placeholder')" />
|
||||
<p v-else class="sheet-copy">{{ form.proficiencies || $t('campaigns.character-sheet.empty-proficiencies') }}</p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<main v-show="activeTab === 'inventory'" class="sheet-tab-body">
|
||||
<section class="sheet-panel inventory-panel">
|
||||
<div class="panel-title-row">
|
||||
<h2>{{ $t('campaigns.character-sheet.inventory') }}</h2>
|
||||
<button v-if="editing" class="sheet-button secondary compact" type="button" @click="addInventoryItem">{{ $t('campaigns.character-sheet.add-item') }}</button>
|
||||
</div>
|
||||
<div class="weight-summary">
|
||||
<span>{{ $t('campaigns.character-sheet.carried-weight') }}</span>
|
||||
<strong>{{ carriedWeight.toFixed(1) }} / {{ carryingCapacity }} lb</strong>
|
||||
</div>
|
||||
<div class="weight-track"><div class="weight-fill" :style="{ width: `${carryPercent}%` }" /></div>
|
||||
<div class="inventory-table-wrap">
|
||||
<table class="inventory-table">
|
||||
<thead><tr>
|
||||
<th>{{ $t('campaigns.character-sheet.item-name') }}</th>
|
||||
<th>{{ $t('campaigns.character-sheet.quantity') }}</th>
|
||||
<th>{{ $t('campaigns.character-sheet.weight-each') }}</th>
|
||||
<th>{{ $t('campaigns.character-sheet.total-weight') }}</th>
|
||||
<th v-if="editing"><span class="sr-only">{{ $t('campaigns.character-sheet.actions') }}</span></th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="(item, index) in form.inventory" :key="index">
|
||||
<td><input v-if="editing" v-model="item.name" :aria-label="$t('campaigns.character-sheet.item-name')"><span v-else>{{ item.name }}</span></td>
|
||||
<td><input v-if="editing" v-model.number="item.quantity" type="number" min="1" :aria-label="$t('campaigns.character-sheet.quantity')"><span v-else>{{ item.quantity }}</span></td>
|
||||
<td><input v-if="editing" v-model.number="item.weight" type="number" min="0" step="0.1" :aria-label="$t('campaigns.character-sheet.weight-each')"><span v-else>{{ Number(item.weight).toFixed(1) }} lb</span></td>
|
||||
<td>{{ ((Number(item.quantity) || 0) * (Number(item.weight) || 0)).toFixed(1) }} lb</td>
|
||||
<td v-if="editing"><button class="remove-item" type="button" @click="removeInventoryItem(index)">×</button></td>
|
||||
</tr>
|
||||
<tr v-if="form.inventory.length === 0"><td :colspan="editing ? 5 : 4" class="empty-inventory">{{ $t('campaigns.character-sheet.empty-inventory') }}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<main v-show="activeTab === 'traits'" class="sheet-tab-body">
|
||||
<section class="sheet-panel traits-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.traits') }}</h2>
|
||||
<textarea v-if="editing" v-model="form.traits" rows="12" :placeholder="$t('campaigns.character-sheet.traits-placeholder')" />
|
||||
<p v-else class="sheet-copy">{{ form.traits || $t('campaigns.character-sheet.empty-traits') }}</p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<main v-show="activeTab === 'spells'" class="sheet-tab-body">
|
||||
<section class="sheet-panel spells-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.spells') }}</h2>
|
||||
<textarea v-if="editing" v-model="form.spells" rows="12" :placeholder="$t('campaigns.character-sheet.spells-placeholder')" />
|
||||
<p v-else class="sheet-copy">{{ form.spells || $t('campaigns.character-sheet.empty-spells') }}</p>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<section class="sheet-panel abilities-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.ability-scores') }}</h2>
|
||||
<div class="ability-grid">
|
||||
<div v-for="stat in abilityStats" :key="stat.key" class="ability-card">
|
||||
<span class="ability-label">{{ stat.label }}</span>
|
||||
<input v-if="editing" v-model.number="form.abilityScores[stat.key]" type="number" min="1" max="30" :aria-label="stat.label">
|
||||
<strong v-else class="ability-score">{{ form.abilityScores[stat.key] }}</strong>
|
||||
<span class="ability-modifier">{{ abilityModifier(form.abilityScores[stat.key]) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="proficiency-badge">
|
||||
<span>{{ $t('campaigns.character-sheet.proficiency-bonus') }}</span>
|
||||
<strong>+{{ proficiencyBonus }}</strong>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="sheet-panel combat-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.combat') }}</h2>
|
||||
<div class="combat-stats">
|
||||
<div class="combat-stat">
|
||||
<span>{{ $t('campaigns.character-sheet.armor-class') }}</span>
|
||||
<input v-if="editing" v-model.number="form.armorClass" type="number" min="0">
|
||||
<strong v-else>{{ form.armorClass }}</strong>
|
||||
</div>
|
||||
<div class="combat-stat">
|
||||
<span>{{ $t('campaigns.character-sheet.speed') }}</span>
|
||||
<label v-if="editing" class="number-with-unit"><input v-model.number="form.speed" type="number" min="0"><small>ft</small></label>
|
||||
<strong v-else>{{ form.speed }} <small>ft</small></strong>
|
||||
</div>
|
||||
</div>
|
||||
<h3>{{ $t('campaigns.character-sheet.proficiencies') }}</h3>
|
||||
<textarea v-if="editing" v-model="form.proficiencies" rows="5" :placeholder="$t('campaigns.character-sheet.proficiencies-placeholder')" />
|
||||
<p v-else class="sheet-copy">{{ form.proficiencies || $t('campaigns.character-sheet.empty-proficiencies') }}</p>
|
||||
</section>
|
||||
|
||||
<section class="sheet-panel traits-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.traits') }}</h2>
|
||||
<textarea v-if="editing" v-model="form.traits" rows="5" :placeholder="$t('campaigns.character-sheet.traits-placeholder')" />
|
||||
<p v-else class="sheet-copy">{{ form.traits || $t('campaigns.character-sheet.empty-traits') }}</p>
|
||||
</section>
|
||||
|
||||
<section class="sheet-panel spells-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.spells') }}</h2>
|
||||
<textarea v-if="editing" v-model="form.spells" rows="5" :placeholder="$t('campaigns.character-sheet.spells-placeholder')" />
|
||||
<p v-else class="sheet-copy">{{ form.spells || $t('campaigns.character-sheet.empty-spells') }}</p>
|
||||
</section>
|
||||
|
||||
<section class="sheet-panel inventory-panel">
|
||||
<div class="panel-title-row">
|
||||
<h2>{{ $t('campaigns.character-sheet.inventory') }}</h2>
|
||||
<button v-if="editing" class="sheet-button secondary compact" type="button" @click="addInventoryItem">{{ $t('campaigns.character-sheet.add-item') }}</button>
|
||||
</div>
|
||||
<div class="weight-summary">
|
||||
<span>{{ $t('campaigns.character-sheet.carried-weight') }}</span>
|
||||
<strong>{{ carriedWeight.toFixed(1) }} / {{ carryingCapacity }} lb</strong>
|
||||
</div>
|
||||
<div class="weight-track"><div class="weight-fill" :style="{ width: `${carryPercent}%` }" /></div>
|
||||
<div class="inventory-table-wrap">
|
||||
<table class="inventory-table">
|
||||
<thead><tr>
|
||||
<th>{{ $t('campaigns.character-sheet.item-name') }}</th>
|
||||
<th>{{ $t('campaigns.character-sheet.quantity') }}</th>
|
||||
<th>{{ $t('campaigns.character-sheet.weight-each') }}</th>
|
||||
<th>{{ $t('campaigns.character-sheet.total-weight') }}</th>
|
||||
<th v-if="editing"><span class="sr-only">{{ $t('campaigns.character-sheet.actions') }}</span></th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="(item, index) in form.inventory" :key="index">
|
||||
<td><input v-if="editing" v-model="item.name" :aria-label="$t('campaigns.character-sheet.item-name')"><span v-else>{{ item.name }}</span></td>
|
||||
<td><input v-if="editing" v-model.number="item.quantity" type="number" min="1" :aria-label="$t('campaigns.character-sheet.quantity')"><span v-else>{{ item.quantity }}</span></td>
|
||||
<td><input v-if="editing" v-model.number="item.weight" type="number" min="0" step="0.1" :aria-label="$t('campaigns.character-sheet.weight-each')"><span v-else>{{ Number(item.weight).toFixed(1) }} lb</span></td>
|
||||
<td>{{ ((Number(item.quantity) || 0) * (Number(item.weight) || 0)).toFixed(1) }} lb</td>
|
||||
<td v-if="editing"><button class="remove-item" type="button" @click="removeInventoryItem(index)">×</button></td>
|
||||
</tr>
|
||||
<tr v-if="form.inventory.length === 0"><td :colspan="editing ? 5 : 4" class="empty-inventory">{{ $t('campaigns.character-sheet.empty-inventory') }}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<nav class="sheet-tabs" role="tablist" aria-orientation="vertical">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.key"
|
||||
class="sheet-tab"
|
||||
:class="{ active: activeTab === tab.key }"
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="activeTab === tab.key"
|
||||
@click="activeTab = tab.key"
|
||||
>{{ $t(tab.label) }}</button>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -325,7 +358,27 @@ async function saveSheet() {
|
||||
.sheet-button.primary { background: var(--color-link); color: var(--color-background); border-color: var(--color-link); }
|
||||
.sheet-button:disabled { opacity: .55; cursor: wait; }
|
||||
.sheet-button.compact { padding: 5px 9px; font-size: 12px; }
|
||||
.sheet-grid { display: grid; grid-template-columns: minmax(200px, 34%) minmax(0, 1fr) minmax(0, 1fr); grid-template-rows: auto auto auto auto; gap: 11px; align-items: start; }
|
||||
.sheet-grid { display: grid; grid-template-columns: minmax(200px, 34%) minmax(0, 1fr) minmax(0, 1fr); grid-template-rows: auto auto; gap: 11px; align-items: start; }
|
||||
.sheet-layout { display: flex; align-items: flex-start; gap: 10px; }
|
||||
.sheet-content { flex: 1 1 auto; min-width: 0; }
|
||||
.sheet-tab-body { display: block; }
|
||||
.sheet-tabs { flex: 0 0 auto; display: flex; flex-direction: column; gap: 6px; position: sticky; top: 0; align-self: flex-start; }
|
||||
.sheet-tab {
|
||||
text-align: left;
|
||||
padding: 9px 14px 9px 11px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-left-width: 3px;
|
||||
border-radius: 0 9px 9px 0;
|
||||
background: var(--color-background-soft);
|
||||
color: var(--color-text);
|
||||
font: 13px MrEavesRemake;
|
||||
letter-spacing: .02em;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: background .15s ease, border-color .15s ease, color .15s ease;
|
||||
}
|
||||
.sheet-tab:hover { background: var(--color-button-hover); }
|
||||
.sheet-tab.active { background: var(--color-background-light); color: var(--color-link); border-left-color: var(--color-link); box-shadow: 0 3px 12px var(--color-window-shadow); }
|
||||
.sheet-panel { min-width: 0; padding: 13px; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-light); box-shadow: 0 3px 12px var(--color-window-shadow); }
|
||||
.sheet-panel h2 { margin: 0 0 12px; padding-bottom: 7px; border-bottom: 1px solid var(--color-border); font: 17px MrEavesRemake; letter-spacing: .03em; }
|
||||
.sheet-panel h3 { margin: 13px 0 7px; font: 14px MrEavesRemake; }
|
||||
@@ -340,9 +393,7 @@ async function saveSheet() {
|
||||
.portrait-controls button:disabled { opacity: .55; cursor: wait; }
|
||||
.photo-input { display: none; }
|
||||
.abilities-panel { grid-column: 2 / -1; grid-row: 1; }
|
||||
.combat-panel { grid-column: 2; grid-row: 2; }
|
||||
.traits-panel { grid-column: 3; grid-row: 2; }
|
||||
.spells-panel { grid-column: 2 / -1; grid-row: 3; }
|
||||
.combat-panel { grid-column: 2 / -1; grid-row: 2; }
|
||||
.ability-grid { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 7px; }
|
||||
.ability-card { min-height: 83px; padding: 8px 5px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); }
|
||||
.ability-label { font-size: 11px; font-weight: 700; letter-spacing: .08em; opacity: .75; }
|
||||
@@ -369,7 +420,6 @@ textarea { resize: vertical; width: 100%; min-height: 88px; font-size: 12px; }
|
||||
.weight-summary strong { white-space: nowrap; }
|
||||
.weight-track { height: 5px; margin-bottom: 10px; overflow: hidden; border-radius: 999px; background: var(--color-background-soft); }
|
||||
.weight-fill { height: 100%; border-radius: inherit; background: var(--color-link); transition: width .2s ease; }
|
||||
.inventory-panel { grid-column: 2 / -1; grid-row: 4; }
|
||||
.inventory-table-wrap { overflow-x: auto; }
|
||||
.inventory-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
||||
.inventory-table th { padding: 6px 7px; text-align: left; font-weight: 600; opacity: .7; }
|
||||
@@ -383,17 +433,17 @@ textarea { resize: vertical; width: 100%; min-height: 88px; font-size: 12px; }
|
||||
.sheet-error { padding: 7px 10px; margin-bottom: 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
@media (max-width: 760px) {
|
||||
.sheet-grid { grid-template-columns: 1fr 1fr; grid-template-rows: none; }
|
||||
.sheet-portrait { grid-column: 1 / -1; grid-row: auto; }
|
||||
.abilities-panel { grid-column: 1 / -1; grid-row: auto; }
|
||||
.combat-panel, .traits-panel { grid-column: auto; grid-row: auto; }
|
||||
.spells-panel, .inventory-panel { grid-column: 1 / -1; grid-row: auto; }
|
||||
.sheet-grid { grid-template-columns: 1fr; grid-template-rows: none; }
|
||||
.sheet-portrait, .abilities-panel, .combat-panel { grid-column: 1 / -1; grid-row: auto; }
|
||||
}
|
||||
@media (max-width: 520px) {
|
||||
.sheet-body { padding: 10px; }
|
||||
.sheet-hero { align-items: flex-start; flex-wrap: wrap; }
|
||||
.sheet-actions { margin-left: auto; }
|
||||
.sheet-grid { grid-template-columns: 1fr; }
|
||||
.ability-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.sheet-layout { flex-direction: column; }
|
||||
.sheet-tabs { flex-direction: row; flex-wrap: wrap; order: -1; }
|
||||
.sheet-tab { flex: 1 1 auto; text-align: center; border-radius: 7px; border-left-width: 1px; border-top-width: 3px; }
|
||||
.sheet-tab.active { border-left-color: var(--color-border); border-top-color: var(--color-link); }
|
||||
}
|
||||
</style>
|
||||
|
||||
166
frontend/app/components/windows/FoundryIconPickerWindow.vue
Normal file
166
frontend/app/components/windows/FoundryIconPickerWindow.vue
Normal file
@@ -0,0 +1,166 @@
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top, SetResizable, SetMinSize } from '@/services/Windows';
|
||||
import WindowHandle from './partials/WindowHandle.vue';
|
||||
import Server from '~/services/Server';
|
||||
import { emitter } from '~/services/Emitter';
|
||||
|
||||
const props = defineProps(['data']);
|
||||
const id = props.data.id;
|
||||
const itemId = props.data.item?._id;
|
||||
const campaign = props.data.campaign || '';
|
||||
const ICON_ROOT = 'icons';
|
||||
|
||||
const handle = ref(null);
|
||||
const wrapper = ref(null);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const applying = ref('');
|
||||
// What the window is standing on: one folder of Foundry's icon library at a time.
|
||||
const listing = ref({ dir: ICON_ROOT, parent: null, folders: [], files: [], next: null });
|
||||
const { t } = useI18n();
|
||||
|
||||
onMounted(() => {
|
||||
Top(wrapper);
|
||||
SetupHandle(id, handle);
|
||||
SetSize(id, { width: 560, height: 540 });
|
||||
ResetPosition(id, 'center');
|
||||
SetResizable(id, true);
|
||||
SetMinSize(id, { width: 420, height: 340 });
|
||||
Load(ICON_ROOT);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => ClearWindow({ type: 'foundry_icons' }));
|
||||
|
||||
// One request per folder, and the icons inside it a page at a time: that library
|
||||
// runs into the thousands, so the window only ever asks for what it shows.
|
||||
async function Load(dir, offset = 0) {
|
||||
if (loading.value) return;
|
||||
if (!campaign) {
|
||||
error.value = t('foundry.errors.icons-no-world-url');
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const params = new URLSearchParams({ campaign, dir });
|
||||
if (offset) params.set('offset', String(offset));
|
||||
const response = await Server().get(`/foundry/icons?${params.toString()}`);
|
||||
if (response.data.status !== 'ok') {
|
||||
error.value = t(response.data.msg || 'foundry.errors.icons-unavailable');
|
||||
return;
|
||||
}
|
||||
const page = {
|
||||
dir: response.data.dir || dir,
|
||||
parent: response.data.parent ?? null,
|
||||
folders: response.data.folders || [],
|
||||
files: response.data.files || [],
|
||||
next: response.data.next ?? null,
|
||||
};
|
||||
listing.value = offset
|
||||
? { ...page, files: [...listing.value.files, ...page.files] }
|
||||
: page;
|
||||
} catch (requestError) {
|
||||
error.value = t('foundry.errors.icons-unavailable');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const trail = computed(() => {
|
||||
const parts = String(listing.value.dir || ICON_ROOT).split('/').filter(Boolean);
|
||||
return parts.map((name, index) => ({ name, path: parts.slice(0, index + 1).join('/') }));
|
||||
});
|
||||
|
||||
const empty = computed(() => !loading.value && !listing.value.folders.length && !listing.value.files.length);
|
||||
|
||||
function GoUp() {
|
||||
Load(listing.value.parent || ICON_ROOT);
|
||||
}
|
||||
|
||||
// The icon is stored as the url the browser loads it from, the same shape a synced
|
||||
// Foundry item's icon has; the item window follows the event this leaves behind.
|
||||
async function Choose(icon) {
|
||||
if (applying.value) return;
|
||||
applying.value = icon.path;
|
||||
error.value = '';
|
||||
try {
|
||||
const response = await Server().post('/item/update', { id: itemId, image: icon.url });
|
||||
if (response.data.status !== 'ok') {
|
||||
error.value = t('campaigns.item.sheet.save-error');
|
||||
return;
|
||||
}
|
||||
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
|
||||
ClearWindow({ type: 'foundry_icons' });
|
||||
ClearWindow({ type: 'item_icon_source' });
|
||||
} catch (requestError) {
|
||||
error.value = t('campaigns.item.sheet.save-error');
|
||||
} finally {
|
||||
applying.value = '';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="window-wrapper foundry-icons-window" :id="'window-wrapper-' + id" ref="wrapper">
|
||||
<WindowHandle :window="id" ref="handle" />
|
||||
<div class="icons-body">
|
||||
<nav class="icons-trail" :aria-label="$t('foundry.icons.path')">
|
||||
<button class="trail-up" type="button" :disabled="loading || !listing.parent" :aria-label="$t('foundry.icons.up')" @click="GoUp">
|
||||
<img class="icon" src="/icons/iconoir/regular/arrow-up.svg" alt="" aria-hidden="true">
|
||||
</button>
|
||||
<template v-for="crumb in trail" :key="crumb.path">
|
||||
<span class="trail-separator" aria-hidden="true">/</span>
|
||||
<button class="trail-crumb" type="button" :disabled="loading" @click="Load(crumb.path)">{{ crumb.name }}</button>
|
||||
</template>
|
||||
</nav>
|
||||
|
||||
<div v-if="error" class="icons-error">{{ error }}</div>
|
||||
<p v-if="loading" class="icons-state">{{ $t('foundry.icons.loading') }}</p>
|
||||
<p v-else-if="empty" class="icons-state">{{ $t('foundry.icons.empty') }}</p>
|
||||
|
||||
<div v-if="listing.folders.length" class="icon-tiles">
|
||||
<button v-for="folder in listing.folders" :key="folder.path" class="icon-tile folder" type="button" :disabled="loading" @click="Load(folder.path)">
|
||||
<img class="icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
|
||||
<span class="tile-name">{{ folder.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="listing.files.length" class="icon-tiles">
|
||||
<button v-for="icon in listing.files" :key="icon.path" class="icon-tile" type="button"
|
||||
:disabled="applying !== ''" :title="icon.name" @click="Choose(icon)">
|
||||
<img class="tile-image" :src="icon.url" :alt="icon.name" loading="lazy">
|
||||
<span class="tile-name">{{ icon.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button v-if="listing.next" class="icons-more sheet-button" type="button" :disabled="loading" @click="Load(listing.dir, listing.next)">
|
||||
{{ $t('foundry.icons.load-more') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.foundry-icons-window { min-width: 0; min-height: 0; }
|
||||
.icons-body { width: 100%; min-height: 0; flex: 1; overflow: auto; padding: 12px 14px 16px; box-sizing: border-box; display: flex; flex-direction: column; gap: 10px; }
|
||||
.icons-trail { display: flex; align-items: center; flex-wrap: wrap; gap: 4px; position: sticky; top: 0; padding-bottom: 8px; background: var(--color-window-background); font-size: 12px; }
|
||||
.trail-up, .trail-crumb { display: inline-flex; align-items: center; padding: 4px 7px; border: 1px solid var(--color-border); border-radius: 6px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; font-size: 12px; }
|
||||
.trail-up:hover, .trail-crumb:hover { background: var(--color-button-hover); }
|
||||
.trail-up:disabled, .trail-crumb:disabled { opacity: .5; cursor: wait; }
|
||||
.trail-separator { opacity: .45; }
|
||||
.icons-error { padding: 7px 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
|
||||
.icons-state { margin: 0; font-size: 12px; opacity: .7; }
|
||||
.icon-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(78px, 1fr)); gap: 8px; }
|
||||
.icon-tile { display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 8px 6px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; }
|
||||
.icon-tile:hover { background: var(--color-button-hover); border-color: var(--color-link); }
|
||||
.icon-tile:disabled { opacity: .55; cursor: wait; }
|
||||
.icon-tile.folder { justify-content: center; }
|
||||
.icon-tile .icon { width: 22px; height: 22px; }
|
||||
.tile-image { width: 40px; height: 40px; object-fit: contain; }
|
||||
.tile-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 10px; opacity: .75; }
|
||||
.icons-more { align-self: center; border: 1px solid var(--color-border); border-radius: 7px; padding: 7px 12px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; white-space: nowrap; font-size: 13px; }
|
||||
.icons-more:hover { background: var(--color-button-hover); }
|
||||
.icons-more:disabled { opacity: .55; cursor: wait; }
|
||||
</style>
|
||||
128
frontend/app/components/windows/ItemIconSourceWindow.vue
Normal file
128
frontend/app/components/windows/ItemIconSourceWindow.vue
Normal file
@@ -0,0 +1,128 @@
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top, CreateChildWindow } from '@/services/Windows';
|
||||
import WindowHandle from './partials/WindowHandle.vue';
|
||||
import Server, { getBaseUrl } from '~/services/Server';
|
||||
import { emitter } from '~/services/Emitter';
|
||||
|
||||
const props = defineProps(['data']);
|
||||
const id = props.data.id;
|
||||
const item = props.data.item || {};
|
||||
const itemId = item._id;
|
||||
const campaign = props.data.campaign || '';
|
||||
const handle = ref(null);
|
||||
const wrapper = ref(null);
|
||||
const error = ref('');
|
||||
const uploading = ref(false);
|
||||
const photoInput = ref(null);
|
||||
const image = ref(item.image || '');
|
||||
const { t } = useI18n();
|
||||
|
||||
onMounted(() => {
|
||||
Top(wrapper);
|
||||
SetupHandle(id, handle);
|
||||
SetSize(id, { width: 430, height: 320 });
|
||||
ResetPosition(id, 'center');
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => ClearWindow({ type: 'item_icon_source' }));
|
||||
|
||||
// An uploaded icon is a file of the backend's uploads folder and a Foundry one an
|
||||
// absolute url of the world; both are drawn the way the item window draws them.
|
||||
const imageUrl = computed(() => {
|
||||
if (!image.value) return '';
|
||||
return /^(https?:|data:|\/\/)/i.test(image.value)
|
||||
? image.value
|
||||
: `${getBaseUrl()}/public/${image.value}`;
|
||||
});
|
||||
|
||||
function pickLocalIcon() {
|
||||
photoInput.value?.click();
|
||||
}
|
||||
|
||||
// The icon browser opens on top of this window, as its child: closing the chooser
|
||||
// takes the browser with it, like every other child window here.
|
||||
function openFoundryIcons() {
|
||||
CreateChildWindow(id, 'foundry_icons', { item: { _id: itemId, name: item.name }, campaign });
|
||||
}
|
||||
|
||||
async function onIconSelected(event) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
if (!file || uploading.value) return;
|
||||
uploading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('image', file);
|
||||
const response = await Server().post(`/item/upload-image?item=${itemId}`, formData, {
|
||||
headers: { "Content-Type": "multipart/form-data" }
|
||||
});
|
||||
if (response.data.status !== 'ok') {
|
||||
error.value = t('campaigns.item.sheet.upload-error');
|
||||
return;
|
||||
}
|
||||
// The item window follows this event and shows the new icon.
|
||||
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
|
||||
ClearWindow({ id });
|
||||
} catch (requestError) {
|
||||
error.value = t('campaigns.item.sheet.upload-error');
|
||||
} finally {
|
||||
uploading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="window-wrapper icon-source-window" :id="'window-wrapper-' + id" ref="wrapper">
|
||||
<WindowHandle :window="id" ref="handle" />
|
||||
<div class="source-body">
|
||||
<header class="source-hero">
|
||||
<div class="source-icon" :class="{ empty: !image }">
|
||||
<img v-if="imageUrl" :src="imageUrl" :alt="$t('campaigns.item.sheet.icon')">
|
||||
<span v-else aria-hidden="true">{{ (item.name || '?').slice(0, 1).toUpperCase() }}</span>
|
||||
</div>
|
||||
<p class="source-intro">{{ $t('campaigns.item.icon-picker.intro') }}</p>
|
||||
</header>
|
||||
|
||||
<div v-if="error" class="source-error">{{ error }}</div>
|
||||
|
||||
<div class="source-options">
|
||||
<button class="source-option" type="button" :disabled="uploading" @click="pickLocalIcon">
|
||||
<img class="icon" src="/icons/iconoir/regular/cloud-upload.svg" alt="" aria-hidden="true">
|
||||
<span class="source-option-title">{{ uploading
|
||||
? $t('campaigns.item.sheet.uploading')
|
||||
: $t('campaigns.item.icon-picker.upload') }}</span>
|
||||
<span class="source-option-hint">{{ $t('campaigns.item.icon-picker.upload-hint') }}</span>
|
||||
</button>
|
||||
<button class="source-option" type="button" @click="openFoundryIcons">
|
||||
<img class="icon" src="/icons/iconoir/regular/media-image.svg" alt="" aria-hidden="true">
|
||||
<span class="source-option-title">{{ $t('campaigns.item.icon-picker.foundry') }}</span>
|
||||
<span class="source-option-hint">{{ $t('campaigns.item.icon-picker.foundry-hint') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onIconSelected">
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.icon-source-window { min-width: 0; min-height: 0; }
|
||||
.source-body { width: 100%; min-height: 0; flex: 1; overflow: auto; padding: 14px 16px 16px; box-sizing: border-box; display: flex; flex-direction: column; gap: 12px; }
|
||||
.source-hero { display: flex; align-items: center; gap: 13px; padding-bottom: 12px; border-bottom: 1px solid var(--color-border); }
|
||||
.source-icon { width: 56px; height: 56px; flex: 0 0 56px; display: grid; place-items: center; overflow: hidden; border-radius: 10px; border: 1px solid var(--color-border); background: var(--color-background-soft); color: var(--color-link); font: 26px MrEavesRemake; }
|
||||
.source-icon.empty { border-style: dashed; }
|
||||
.source-icon img { width: 100%; height: 100%; object-fit: contain; }
|
||||
.source-intro { margin: 0; font-size: 13px; opacity: .85; }
|
||||
.source-error { padding: 7px 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
|
||||
.source-options { display: flex; flex-direction: column; gap: 10px; }
|
||||
.source-option { display: grid; grid-template-columns: 26px 1fr; align-items: center; gap: 4px 10px; padding: 12px 14px; text-align: left; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; }
|
||||
.source-option:hover { background: var(--color-button-hover); }
|
||||
.source-option:disabled { opacity: .55; cursor: wait; }
|
||||
.source-option .icon { width: 20px; height: 20px; grid-row: span 2; }
|
||||
.source-option-title { font: 15px MrEavesRemake; }
|
||||
.source-option-hint { font-size: 12px; opacity: .7; }
|
||||
.photo-input { display: none; }
|
||||
</style>
|
||||
@@ -1,9 +1,10 @@
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
|
||||
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top, CreateChildWindow } from '@/services/Windows';
|
||||
import WindowHandle from './partials/WindowHandle.vue';
|
||||
import Server, { getBaseUrl } from '~/services/Server';
|
||||
import { useCampaignService } from '~/services/Campaign.js';
|
||||
import { emitter } from '~/services/Emitter';
|
||||
|
||||
const props = defineProps(['data']);
|
||||
@@ -12,9 +13,10 @@ const itemId = props.data.item?._id;
|
||||
const handle = ref(null);
|
||||
const wrapper = ref(null);
|
||||
const error = ref('');
|
||||
const uploadingIcon = ref(false);
|
||||
const applyingFoundryIcon = ref(false);
|
||||
const photoInput = ref(null);
|
||||
// Set while this window writes the item's icon, so a Foundry sync landing behind
|
||||
// the window does not rewrite the form under the change being made.
|
||||
const applyingIcon = ref(false);
|
||||
const { Campaign } = useCampaignService();
|
||||
const { t } = useI18n();
|
||||
|
||||
function normalizeItem(item) {
|
||||
@@ -44,9 +46,10 @@ onMounted(() => {
|
||||
onBeforeUnmount(() => ClearWindow({ type: 'item_sheet' }));
|
||||
|
||||
// The sidebar keeps this entry fresh (Foundry sync lands in the background);
|
||||
// follow along unless the window is mid-icon-upload.
|
||||
// follow along unless this window is mid-icon-change. The icon windows leave
|
||||
// their result here, on the same event.
|
||||
function handleItemSync({ entityType, entry }) {
|
||||
if (entityType !== 'item' || entry?._id !== itemId || uploadingIcon.value) return;
|
||||
if (entityType !== 'item' || entry?._id !== itemId || applyingIcon.value) return;
|
||||
form.value = normalizeItem(entry);
|
||||
}
|
||||
|
||||
@@ -70,40 +73,22 @@ async function updateItem(payload) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function pickIcon() {
|
||||
photoInput.value?.click();
|
||||
// Choosing an icon is a window of its own: upload one from this device, or browse
|
||||
// the icon library of the linked Foundry world. Both leave their result on the
|
||||
// `campaign-entry-updated` event, which this window follows.
|
||||
function chooseIcon() {
|
||||
CreateChildWindow(id, 'item_icon_source', {
|
||||
item: { _id: itemId, name: form.value.name, image: form.value.image },
|
||||
campaign: Campaign.value?._id || ''
|
||||
});
|
||||
}
|
||||
|
||||
async function onIconSelected(event) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
if (!file || uploadingIcon.value) return;
|
||||
uploadingIcon.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('image', file);
|
||||
const response = await Server().post(`/item/upload-image?item=${itemId}`, formData, {
|
||||
headers: { "Content-Type": "multipart/form-data" }
|
||||
});
|
||||
if (response.data.status !== 'ok') {
|
||||
error.value = t('campaigns.item.sheet.upload-error');
|
||||
return;
|
||||
}
|
||||
form.value = normalizeItem(response.data.item);
|
||||
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
|
||||
} catch (requestError) {
|
||||
error.value = t('campaigns.item.sheet.upload-error');
|
||||
} finally {
|
||||
uploadingIcon.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// "Fetch from Foundry's icons": the module keeps the world's own icon on the
|
||||
// item, so this just switches back to it.
|
||||
// The world's own icon for this item: the module keeps it on the item, so this
|
||||
// just switches back to it. Picking one of the world's other icons is what the
|
||||
// icon browser is for.
|
||||
async function useFoundryIcon() {
|
||||
if (!canUseFoundryIcon.value || applyingFoundryIcon.value) return;
|
||||
applyingFoundryIcon.value = true;
|
||||
if (!canUseFoundryIcon.value || applyingIcon.value) return;
|
||||
applyingIcon.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const done = await updateItem({ image: form.value.foundryImage });
|
||||
@@ -111,18 +96,21 @@ async function useFoundryIcon() {
|
||||
} catch (requestError) {
|
||||
error.value = t('campaigns.item.sheet.save-error');
|
||||
} finally {
|
||||
applyingFoundryIcon.value = false;
|
||||
applyingIcon.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeIcon() {
|
||||
if (!form.value.image) return;
|
||||
if (!form.value.image || applyingIcon.value) return;
|
||||
applyingIcon.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const done = await updateItem({ image: '' });
|
||||
if (!done) error.value = t('campaigns.item.sheet.save-error');
|
||||
} catch (requestError) {
|
||||
error.value = t('campaigns.item.sheet.save-error');
|
||||
} finally {
|
||||
applyingIcon.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -132,10 +120,12 @@ async function removeIcon() {
|
||||
<WindowHandle :window="id" ref="handle" />
|
||||
<div class="item-body">
|
||||
<header class="item-hero">
|
||||
<div class="item-icon" :class="{ empty: !form.image }">
|
||||
<button class="item-icon" :class="{ empty: !form.image }" type="button"
|
||||
:aria-label="$t(form.image ? 'campaigns.item.sheet.change-icon' : 'campaigns.item.sheet.choose-icon')"
|
||||
@click="chooseIcon">
|
||||
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.item.sheet.icon')">
|
||||
<span v-else aria-hidden="true">{{ form.name.slice(0, 1).toUpperCase() }}</span>
|
||||
</div>
|
||||
</button>
|
||||
<div class="item-identity">
|
||||
<h1>{{ form.name }}</h1>
|
||||
<div class="item-tags">
|
||||
@@ -149,16 +139,13 @@ async function removeIcon() {
|
||||
<div v-if="error" class="item-error">{{ error }}</div>
|
||||
|
||||
<div class="icon-controls">
|
||||
<button class="sheet-button" type="button" :disabled="uploadingIcon" @click="pickIcon">
|
||||
{{ uploadingIcon
|
||||
? $t('campaigns.item.sheet.uploading')
|
||||
: (form.image ? $t('campaigns.item.sheet.change-icon') : $t('campaigns.item.sheet.choose-icon')) }}
|
||||
<button class="sheet-button" type="button" @click="chooseIcon">
|
||||
{{ form.image ? $t('campaigns.item.sheet.change-icon') : $t('campaigns.item.sheet.choose-icon') }}
|
||||
</button>
|
||||
<button v-if="canUseFoundryIcon" class="sheet-button secondary" type="button" :disabled="applyingFoundryIcon" @click="useFoundryIcon">
|
||||
<button v-if="canUseFoundryIcon" class="sheet-button secondary" type="button" :disabled="applyingIcon" @click="useFoundryIcon">
|
||||
{{ $t('campaigns.item.sheet.foundry-icon') }}
|
||||
</button>
|
||||
<button v-if="form.image" class="sheet-button secondary" type="button" :disabled="uploadingIcon" :aria-label="$t('campaigns.item.sheet.remove-icon')" @click="removeIcon">×</button>
|
||||
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onIconSelected">
|
||||
<button v-if="form.image" class="sheet-button secondary" type="button" :disabled="applyingIcon" :aria-label="$t('campaigns.item.sheet.remove-icon')" @click="removeIcon">×</button>
|
||||
</div>
|
||||
|
||||
<dl class="item-facts">
|
||||
@@ -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; }
|
||||
|
||||
@@ -80,21 +80,15 @@ onMounted(() => {
|
||||
});
|
||||
|
||||
function OpenManageAccounts(){
|
||||
ClearWindow('settings');
|
||||
ClearWindow({ type: 'settings' });
|
||||
CreateWindow('account_management', {
|
||||
type: 'account_management',
|
||||
title: 'settings.site-administration.manage-accounts.title',
|
||||
id: 'account-management',
|
||||
// Back returns to the settings tab this button sits on; CreateWindow leaves
|
||||
// a window that is already open alone.
|
||||
back: () => {
|
||||
ClearWindow('account-management')
|
||||
CreateWindow('settings', {
|
||||
id: 'settings',
|
||||
type: 'settings',
|
||||
title: 'settings.title',
|
||||
back: () => { ClearWindow('settings'); CreateWindow('main_menu'); }
|
||||
});
|
||||
ClearWindow({ type: 'account_management' });
|
||||
CreateWindow('settings');
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
const getLocaleName = (locale) => {
|
||||
|
||||
@@ -34,6 +34,12 @@ const defWindows = {
|
||||
},
|
||||
movable: true
|
||||
},
|
||||
account_management: {
|
||||
title: 'windows.account-management',
|
||||
component: () => import('~/components/windows/AccountManagementWindow.vue'),
|
||||
close: () => ClearWindow({type: 'account_management'}),
|
||||
movable: true
|
||||
},
|
||||
create_campaign: {
|
||||
title: "windows.create-campaign",
|
||||
component: () => import('~/components/windows/CreateCampaignWindow.vue'),
|
||||
@@ -82,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'),
|
||||
|
||||
@@ -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"
|
||||
@@ -105,6 +110,7 @@
|
||||
},
|
||||
"character-sheet": {
|
||||
"title": "Fitxa de personatge", "name": "Nom del personatge", "class": "Classe", "subclass": "Subclasse", "unset-class": "Classe sense definir",
|
||||
"tabs": { "abilities": "Característiques", "inventory": "Inventari", "traits": "Trets", "spells": "Conjurs" },
|
||||
"level": "Nivell", "species": "Espècie", "unset-species": "Espècie sense definir", "edit": "Edita la fitxa", "cancel": "Cancel·la",
|
||||
"saving": "Desant...", "save": "Desa la fitxa", "save-error": "No s'ha pogut desar aquesta fitxa de personatge.", "photo": "Foto", "upload-photo": "Pujar foto", "change-photo": "Canviar foto", "remove-photo": "Treure foto", "uploading-photo": "Pujant...", "photo-error": "No s'ha pogut pujar aquesta foto.", "ability-scores": "Característiques", "proficiency-bonus": "Bonificador de competència",
|
||||
"combat": "Combat", "armor-class": "Classe d'armadura", "speed": "Velocitat", "proficiencies": "Competències",
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,30 @@
|
||||
"language": "Idioma"
|
||||
},
|
||||
"site-administration": {
|
||||
"manage-accounts": "Gestiona els comptes"
|
||||
"manage-accounts": "Gestiona els comptes",
|
||||
"accounts": {
|
||||
"you": "tu",
|
||||
"admin": "Administrador",
|
||||
"make-admin": "Fes-lo administrador",
|
||||
"remove-admin": "Treu-li l'administrador",
|
||||
"delete": "Elimina",
|
||||
"new-account": "Nou compte",
|
||||
"name": "Nom",
|
||||
"username": "Nom d'usuari",
|
||||
"email": "Correu electrònic",
|
||||
"password": "Contrasenya",
|
||||
"create": "Crea el compte",
|
||||
"created": "Compte creat",
|
||||
"updated": "Compte actualitzat",
|
||||
"deleted": "Compte eliminat",
|
||||
"errors": {
|
||||
"name-empty": "Si us plau, introdueix un nom.",
|
||||
"username-empty": "Si us plau, introdueix un nom d'usuari.",
|
||||
"email-empty": "Si us plau, introdueix un correu electrònic vàlid.",
|
||||
"password-empty": "Si us plau, introdueix una contrasenya.",
|
||||
"self-admin": "No pots canviar els teus propis privilegis d'administrador.",
|
||||
"self-delete": "No pots eliminar el teu propi compte."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,12 @@
|
||||
"example": "Finestra d'exemple",
|
||||
"edit-profile": "Editar perfil",
|
||||
"settings": "Configuració",
|
||||
"account-management": "Gestió dels comptes",
|
||||
"create-campaign": "Crear campanya",
|
||||
"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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
@@ -109,6 +114,7 @@
|
||||
},
|
||||
"character-sheet": {
|
||||
"title": "Character Sheet", "name": "Character name", "class": "Class", "subclass": "Subclass", "unset-class": "Class not set",
|
||||
"tabs": { "abilities": "Ability Scores", "inventory": "Inventory", "traits": "Traits", "spells": "Spells" },
|
||||
"level": "Level", "species": "Species", "unset-species": "Species not set", "edit": "Edit sheet", "cancel": "Cancel",
|
||||
"saving": "Saving...", "save": "Save sheet", "save-error": "Unable to save this character sheet.",
|
||||
"photo": "Photo", "upload-photo": "Upload photo", "change-photo": "Change photo", "remove-photo": "Remove photo",
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,30 @@
|
||||
"language": "Language"
|
||||
},
|
||||
"site-administration": {
|
||||
"manage-accounts": "Manage accounts"
|
||||
"manage-accounts": "Manage accounts",
|
||||
"accounts": {
|
||||
"you": "you",
|
||||
"admin": "Administrator",
|
||||
"make-admin": "Make administrator",
|
||||
"remove-admin": "Remove administrator",
|
||||
"delete": "Delete",
|
||||
"new-account": "New account",
|
||||
"name": "Name",
|
||||
"username": "Username",
|
||||
"email": "Email",
|
||||
"password": "Password",
|
||||
"create": "Create account",
|
||||
"created": "Account created",
|
||||
"updated": "Account updated",
|
||||
"deleted": "Account deleted",
|
||||
"errors": {
|
||||
"name-empty": "Please enter a name.",
|
||||
"username-empty": "Please enter a username.",
|
||||
"email-empty": "Please enter a valid email address.",
|
||||
"password-empty": "Please enter a password.",
|
||||
"self-admin": "You cannot change your own administrator rights.",
|
||||
"self-delete": "You cannot delete your own account."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,12 @@
|
||||
"example": "Example Window",
|
||||
"edit-profile": "Edit Profile",
|
||||
"settings": "Settings",
|
||||
"account-management": "Manage accounts",
|
||||
"create-campaign": "Create Campaign",
|
||||
"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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
@@ -105,6 +110,7 @@
|
||||
},
|
||||
"character-sheet": {
|
||||
"title": "Hoja de personaje", "name": "Nombre del personaje", "class": "Clase", "subclass": "Subclase", "unset-class": "Clase sin definir",
|
||||
"tabs": { "abilities": "Características", "inventory": "Inventario", "traits": "Rasgos", "spells": "Conjuros" },
|
||||
"level": "Nivel", "species": "Especie", "unset-species": "Especie sin definir", "edit": "Editar hoja", "cancel": "Cancelar",
|
||||
"saving": "Guardando...", "save": "Guardar hoja", "save-error": "No se pudo guardar esta hoja de personaje.", "photo": "Foto", "upload-photo": "Subir foto", "change-photo": "Cambiar foto", "remove-photo": "Quitar foto", "uploading-photo": "Subiendo...", "photo-error": "No se pudo subir esta foto.", "ability-scores": "Características", "proficiency-bonus": "Bonificador por competencia",
|
||||
"combat": "Combate", "armor-class": "Clase de armadura", "speed": "Velocidad", "proficiencies": "Competencias",
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,30 @@
|
||||
"language": "Idioma"
|
||||
},
|
||||
"site-administration": {
|
||||
"manage-accounts": "Gestionar cuentas"
|
||||
"manage-accounts": "Gestionar cuentas",
|
||||
"accounts": {
|
||||
"you": "tú",
|
||||
"admin": "Administrador",
|
||||
"make-admin": "Nombrar administrador",
|
||||
"remove-admin": "Quitar administrador",
|
||||
"delete": "Eliminar",
|
||||
"new-account": "Nueva cuenta",
|
||||
"name": "Nombre",
|
||||
"username": "Nombre de usuario",
|
||||
"email": "Correo electrónico",
|
||||
"password": "Contraseña",
|
||||
"create": "Crear cuenta",
|
||||
"created": "Cuenta creada",
|
||||
"updated": "Cuenta actualizada",
|
||||
"deleted": "Cuenta eliminada",
|
||||
"errors": {
|
||||
"name-empty": "Por favor, introduce un nombre.",
|
||||
"username-empty": "Por favor, introduce un nombre de usuario.",
|
||||
"email-empty": "Por favor, introduce un correo electrónico válido.",
|
||||
"password-empty": "Por favor, introduce una contraseña.",
|
||||
"self-admin": "No puedes cambiar tus propios privilegios de administrador.",
|
||||
"self-delete": "No puedes eliminar tu propia cuenta."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,12 @@
|
||||
"example": "Ventana de ejemplo",
|
||||
"edit-profile": "Editar perfil",
|
||||
"settings": "Configuración",
|
||||
"account-management": "Gestionar cuentas",
|
||||
"create-campaign": "Crear campanya",
|
||||
"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"
|
||||
}
|
||||
|
||||
89
tests/character-sheet-tabs.test.js
Normal file
89
tests/character-sheet-tabs.test.js
Normal file
@@ -0,0 +1,89 @@
|
||||
// Tests for Syndria98/dragonroll#55: the character sheet splits its contents across bookmarks down
|
||||
// the right edge (ability scores, inventory, traits, spells) instead of stacking every panel on one
|
||||
// long page.
|
||||
//
|
||||
// The repository root installs no dependencies, so the window wiring is read from the sources the way
|
||||
// tests/item-sheet-window.test.js and tests/settings-window.test.js do it.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||
|
||||
const sheetSource = read("frontend", "app", "components", "windows", "CharacterSheetWindow.vue");
|
||||
const script = /<script setup>([\s\S]*?)<\/script>/.exec(sheetSource)?.[1] ?? "";
|
||||
const template = /<template>([\s\S]*)<\/template>/.exec(sheetSource)?.[1] ?? "";
|
||||
|
||||
// The four bookmarks the issue asks for, in order.
|
||||
test("the sheet declares the four tabs the issue splits the contents into", () => {
|
||||
const array = /const tabs = \[([\s\S]*?)\];/.exec(script)?.[1] ?? "";
|
||||
const keys = [...array.matchAll(/key:\s*['"](\w+)['"]/g)].map((m) => m[1]);
|
||||
assert.deepEqual(keys, ["abilities", "inventory", "traits", "spells"]);
|
||||
for (const key of keys) {
|
||||
assert.ok(
|
||||
new RegExp(`label:\\s*['"]campaigns\\.character-sheet\\.tabs\\.${key}['"]`).test(array),
|
||||
`the ${key} tab must point at its own i18n key`
|
||||
);
|
||||
}
|
||||
assert.match(script, /const activeTab = ref\(['"]abilities['"]\)/, "the sheet opens on the ability scores tab");
|
||||
});
|
||||
|
||||
test("the tabs sit on the right as a vertical bookmark rail", () => {
|
||||
assert.match(template, /<nav class="sheet-tabs"[^>]*role="tablist"[^>]*aria-orientation="vertical"/);
|
||||
assert.match(template, /v-for="tab in tabs"[\s\S]*?:aria-selected="activeTab === tab\.key"/);
|
||||
const rail = /\.sheet-tabs\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
|
||||
assert.match(rail, /flex-direction:\s*column/, "the bookmarks stack down the right edge");
|
||||
// content column and rail sit side by side, the rail hugging the right
|
||||
assert.match(sheetSource, /\.sheet-layout\s*\{[^}]*display:\s*flex[^}]*\}/, "content and rail share a row");
|
||||
assert.match(sheetSource, /\.sheet-content\s*\{[^}]*flex:\s*1[^}]*\}/, "the content takes the room, the rail stays slim");
|
||||
});
|
||||
|
||||
// Each tab shows only its own panels; the rest are hidden with v-show so an in-progress edit is
|
||||
// not thrown away when hopping between tabs.
|
||||
function tabBody(key) {
|
||||
const block = new RegExp(`<main v-show="activeTab === '${key}'"[\\s\\S]*?</main>`).exec(template)?.[0];
|
||||
assert.ok(block, `expected a body for the ${key} tab`);
|
||||
return block;
|
||||
}
|
||||
|
||||
test("every tab shows only its own content and hides the others", () => {
|
||||
const abilities = tabBody("abilities");
|
||||
assert.match(abilities, /class="sheet-portrait"/, "the portrait stays with ability scores");
|
||||
assert.match(abilities, /class="sheet-panel abilities-panel"/);
|
||||
assert.match(abilities, /class="sheet-panel combat-panel"/, "combat rides with the ability scores");
|
||||
for (const other of ["inventory-panel", "traits-panel", "spells-panel"]) {
|
||||
assert.doesNotMatch(abilities, new RegExp(other));
|
||||
}
|
||||
|
||||
for (const [key, panel] of [["inventory", "inventory-panel"], ["traits", "traits-panel"], ["spells", "spells-panel"]]) {
|
||||
const body = tabBody(key);
|
||||
assert.ok(body.includes(panel), `the ${key} tab shows the ${panel}`);
|
||||
assert.doesNotMatch(body, /class="sheet-portrait"/);
|
||||
}
|
||||
|
||||
// the panels are toggled, not unmounted, so editing on one tab and flipping away keeps the draft
|
||||
assert.match(template, /v-show="activeTab === 'inventory'"/);
|
||||
assert.match(template, /v-show="activeTab === 'traits'"/);
|
||||
assert.match(template, /v-show="activeTab === 'spells'"/);
|
||||
});
|
||||
|
||||
test("the tabs still edit and save through the existing sheet form", () => {
|
||||
assert.match(tabBody("inventory"), /@click="addInventoryItem"/);
|
||||
assert.match(tabBody("inventory"), /removeInventoryItem\(index\)/);
|
||||
assert.match(tabBody("traits"), /v-model="form\.traits"/);
|
||||
assert.match(tabBody("spells"), /v-model="form\.spells"/);
|
||||
assert.match(tabBody("abilities"), /v-model\.number="form\.abilityScores\[stat\.key\]"/);
|
||||
});
|
||||
|
||||
test("every locale names the four tabs", () => {
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const sheet = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"))["character-sheet"];
|
||||
for (const key of ["abilities", "inventory", "traits", "spells"]) {
|
||||
assert.ok(sheet.tabs?.[key], `${locale} is missing campaigns.character-sheet.tabs.${key}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
170
tests/foundry-icon-picker.test.js
Normal file
170
tests/foundry-icon-picker.test.js
Normal file
@@ -0,0 +1,170 @@
|
||||
// Tests for Syndria98/dragonroll#65: picking an item's icon opens a window that asks
|
||||
// where the icon comes from — upload one from this device, or load one from the icon
|
||||
// library the linked Foundry world ships in its data directory's `icons/` folder.
|
||||
// That library runs into the thousands, so it is listed one folder per request, with
|
||||
// its icons paged and its thumbnails lazy to load.
|
||||
//
|
||||
// The icon listing helpers are a pure CommonJS service, so they are required and called
|
||||
// directly. The windows and the bridge live in files this repository installs no
|
||||
// dependencies for, so those checks read the sources, like tests/map-viewer.test.js does.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||
const iconService = require(path.join(__dirname, "..", "backend", "src", "services", "foundry-icons"));
|
||||
|
||||
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
|
||||
const itemWindowSource = read("frontend", "app", "components", "windows", "ItemSheetWindow.vue");
|
||||
const sourceWindowSource = read("frontend", "app", "components", "windows", "ItemIconSourceWindow.vue");
|
||||
const foundryIconsSource = read("frontend", "app", "components", "windows", "FoundryIconPickerWindow.vue");
|
||||
const foundryRouteSource = read("backend", "src", "routes", "foundry.js");
|
||||
const bridgeSource = read("dragonroll-foundry", "bridge", "server.js");
|
||||
|
||||
// --- The listing service: what the browser may ask for, and what it gets back ------
|
||||
|
||||
test("icon listings always stay inside Foundry's icon root", () => {
|
||||
assert.equal(iconService.ICON_ROOT, "icons");
|
||||
assert.equal(iconService.normalizeIconDirectory(""), "icons");
|
||||
assert.equal(iconService.normalizeIconDirectory(undefined), "icons");
|
||||
assert.equal(iconService.normalizeIconDirectory("/icons/svg/"), "icons/svg");
|
||||
assert.equal(iconService.normalizeIconDirectory("icons/sfdcc/axes"), "icons/sfdcc/axes");
|
||||
assert.equal(iconService.normalizeIconDirectory("icons/./svg"), "icons/svg");
|
||||
// nothing that leaves `icons/` is a folder this route will list
|
||||
assert.equal(iconService.normalizeIconDirectory("icons/../secret"), null);
|
||||
assert.equal(iconService.normalizeIconDirectory("../etc"), null);
|
||||
assert.equal(iconService.normalizeIconDirectory("systems/dnd5e/icons"), null);
|
||||
assert.equal(iconService.parentIconDirectory("icons/svg/axes"), "icons/svg");
|
||||
assert.equal(iconService.parentIconDirectory("icons"), null);
|
||||
});
|
||||
|
||||
test("icons are listed a page at a time, bounded", () => {
|
||||
assert.deepEqual(iconService.readIconListingPage({}), { limit: iconService.DEFAULT_ICON_PAGE_SIZE, offset: 0 });
|
||||
assert.deepEqual(iconService.readIconListingPage({ limit: "20", offset: "240" }), { limit: 20, offset: 240 });
|
||||
// a caller cannot ask for the whole library at once, or for a page before the first
|
||||
assert.equal(iconService.readIconListingPage({ limit: "99999" }).limit, iconService.MAX_ICON_PAGE_SIZE);
|
||||
assert.equal(iconService.readIconListingPage({ offset: "-10" }).offset, 0);
|
||||
});
|
||||
|
||||
test("only image files become icons, and they load from the world's own address", () => {
|
||||
const listing = iconService.shapeIconListing({
|
||||
base: "https://vtt.example.com/",
|
||||
dir: "icons/svg",
|
||||
listing: {
|
||||
directories: ["icons/svg/creature", "icons/svg/creature", "icons/svg"],
|
||||
files: ["icons/svg/dice.svg", "icons/svg/sword.png", "icons/svg/readme.txt", "stray.md"],
|
||||
offset: 0,
|
||||
next: 120,
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(listing.dir, "icons/svg");
|
||||
assert.equal(listing.parent, "icons");
|
||||
assert.deepEqual(listing.folders.map((folder) => folder.path), ["icons/svg/creature"]);
|
||||
assert.deepEqual(listing.folders.map((folder) => folder.name), ["creature"]);
|
||||
assert.deepEqual(listing.files.map((icon) => icon.path), ["icons/svg/dice.svg", "icons/svg/sword.png"]);
|
||||
assert.equal(listing.files[0].name, "dice.svg");
|
||||
assert.equal(listing.files[0].url, "https://vtt.example.com/icons/svg/dice.svg");
|
||||
assert.equal(listing.next, 120);
|
||||
});
|
||||
|
||||
test("an icon path with spaces still gives the browser a loadable url", () => {
|
||||
assert.equal(
|
||||
iconService.joinFoundryAssetUrl("http://vtt.test:30000", "icons/sfdcc/axes/halberd sword.svg"),
|
||||
"http://vtt.test:30000/icons/sfdcc/axes/halberd%20sword.svg"
|
||||
);
|
||||
assert.equal(iconService.joinFoundryAssetUrl("", "icons/svg/dice.svg"), "");
|
||||
});
|
||||
|
||||
// --- The backend route ------------------------------------------------------------
|
||||
|
||||
test("the foundry proxy lists one icon folder for one of the caller's campaigns", () => {
|
||||
assert.match(foundryRouteSource, /router\.get\(["']\/icons["'], async \(req, res\)/);
|
||||
const route = /router\.get\(["']\/icons[\s\S]*?module\.exports/.exec(foundryRouteSource)?.[0] ?? foundryRouteSource;
|
||||
// the campaign is where the world address is kept, so it has to be the caller's own
|
||||
assert.match(route, /findOwnedCampaign\(req\.query\.campaign, req\.user\.id\)/);
|
||||
assert.match(foundryRouteSource, /Campaign\.findOne\(\{\s*_id:\s*campaignId,\s*createdBy:\s*userId\s*\}\)/);
|
||||
assert.match(route, /campaign\.settings\?\.integrations\?\.foundryUrl/);
|
||||
assert.match(route, /requestFoundry\(`api\/icons\?\$\{query\}`\)/);
|
||||
// a folder outside the icon root is refused before it reaches the Foundry host
|
||||
assert.match(route, /const dir = normalizeIconDirectory\(req\.query\.dir\);/);
|
||||
});
|
||||
|
||||
// --- The bridge on the Foundry host ------------------------------------------------
|
||||
|
||||
test("the bridge lists a core icon folder and never leaves the icon root", () => {
|
||||
assert.match(bridgeSource, /const dataPath = \(process\.env\.DRAGONROLL_FOUNDRY_DATA_PATH \|\| ""\)\.trim\(\);/);
|
||||
assert.match(bridgeSource, /if \(pathname === "\/api\/icons"\) return sendIconListing\(request, response\);/);
|
||||
assert.match(bridgeSource, /if \(!dataPath\) return sendJson\(response, 503, \{ status: "error", msg: "foundry\.errors\.icons-unavailable" \}\);/);
|
||||
const normalize = /function normalizeIconDirectory\(input\) \{[\s\S]*?\n\}/.exec(bridgeSource)?.[0] ?? "";
|
||||
assert.match(normalize, /segments\.includes\("\.\."\) \|\| segments\[0\] !== iconRoot/);
|
||||
// the answer is one folder plus the offset of the next page of its icons
|
||||
assert.match(bridgeSource, /directories\.sort\(\(a, b\) => a\.localeCompare\(b\)\);/);
|
||||
assert.match(bridgeSource, /const page = files\.slice\(offset, offset \+ limit\);/);
|
||||
assert.match(bridgeSource, /next: offset \+ page\.length < files\.length \? offset \+ page\.length : null,/);
|
||||
});
|
||||
|
||||
// --- The windows -------------------------------------------------------------------
|
||||
|
||||
test("choosing an icon opens its own window from the item sheet", () => {
|
||||
assert.match(windowDefsSource, /item_icon_source:\s*{\s*title:[^}]*ItemIconSourceWindow\.vue/s);
|
||||
assert.match(windowDefsSource, /foundry_icons:\s*{\s*title:[^}]*FoundryIconPickerWindow\.vue/s);
|
||||
// the item window asks where the icon comes from instead of opening a file dialog
|
||||
assert.match(itemWindowSource, /CreateChildWindow\(id, ['"]item_icon_source['"]/);
|
||||
assert.doesNotMatch(itemWindowSource, /type="file"/);
|
||||
});
|
||||
|
||||
test("the icon source window offers uploading and Foundry, and uploads the local file", () => {
|
||||
assert.match(sourceWindowSource, /\$t\(['"]campaigns\.item\.icon-picker\.upload['"]\)/);
|
||||
assert.match(sourceWindowSource, /\$t\(['"]campaigns\.item\.icon-picker\.foundry['"]\)/);
|
||||
// upload: a local file, sent through the item route like the character sheet does its photo
|
||||
assert.match(sourceWindowSource, /type="file" accept="image\/\*"/);
|
||||
assert.match(sourceWindowSource, /\/item\/upload-image\?item=\$\{itemId\}/);
|
||||
assert.match(sourceWindowSource, /formData\.append\(['"]image['"], file\)/);
|
||||
// and it hands the item over to the icon browser, as its child window
|
||||
assert.match(sourceWindowSource, /CreateChildWindow\(id, ['"]foundry_icons['"]/);
|
||||
});
|
||||
|
||||
test("the icon browser browses the world's icons folder by folder", () => {
|
||||
assert.match(foundryIconsSource, /\/foundry\/icons\?\$\{params\.toString\(\)\}/);
|
||||
// one folder per request: navigating a folder asks for it, and going up asks for its parent
|
||||
assert.match(foundryIconsSource, /Load\(ICON_ROOT\)/);
|
||||
assert.match(foundryIconsSource, /@click="Load\(folder\.path\)"/);
|
||||
assert.match(foundryIconsSource, /Load\(listing\.value\.parent \|\| ICON_ROOT\)/);
|
||||
// lazy in every way that matters: a page of icons at a time, thumbnails fetched when seen
|
||||
assert.match(foundryIconsSource, /if \(offset\) params\.set\(['"]offset['"], String\(offset\)\)/);
|
||||
assert.match(foundryIconsSource, /@click="Load\(listing\.dir, listing\.next\)"/);
|
||||
assert.match(foundryIconsSource, /loading="lazy"/);
|
||||
// picking an icon stores the world's url and tells the item window about it
|
||||
assert.match(foundryIconsSource, /Server\(\)\.post\(['"]\/item\/update['"], \{ id: itemId, image: icon\.url \}\)/);
|
||||
assert.match(foundryIconsSource, /emitter\.emit\(['"]campaign-entry-updated['"], \{ entityType: ['"]item['"], entry: response\.data\.item \}\)/);
|
||||
assert.match(foundryIconsSource, /ClearWindow\(\{ type: ['"]item_icon_source['"] \}\)/);
|
||||
});
|
||||
|
||||
// --- Strings -----------------------------------------------------------------------
|
||||
|
||||
test("every locale names the icon windows and their controls", () => {
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json"));
|
||||
for (const key of ["icon-source", "foundry-icons"]) {
|
||||
assert.ok(windows[key], `${locale} is missing the ${key} window title`);
|
||||
}
|
||||
|
||||
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
|
||||
for (const key of ["intro", "upload", "upload-hint", "foundry", "foundry-hint"]) {
|
||||
assert.ok(campaigns.item?.["icon-picker"]?.[key], `${locale} is missing campaigns.item.icon-picker.${key}`);
|
||||
}
|
||||
|
||||
const foundry = JSON.parse(read("frontend", "i18n", "locales", locale, "foundry.json"));
|
||||
for (const key of ["loading", "empty", "load-more", "up"]) {
|
||||
assert.ok(foundry.icons?.[key], `${locale} is missing foundry.icons.${key}`);
|
||||
}
|
||||
for (const key of ["icons-unavailable", "icons-no-world-url"]) {
|
||||
assert.ok(foundry.errors?.[key], `${locale} is missing foundry.errors.${key}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
69
tests/item-entry-display.test.js
Normal file
69
tests/item-entry-display.test.js
Normal file
@@ -0,0 +1,69 @@
|
||||
// Tests for Syndria98/dragonroll#53: the item row in the campaign sidebar dropped its "SYNCED"
|
||||
// text badge and now leads with the item's own icon on the left of the entry.
|
||||
//
|
||||
// The repository root installs no dependencies, so these read the sidebar component the way
|
||||
// tests/sidebar-entity-entry.test.js does — the checks are about the markup and style of the row.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const source = fs.readFileSync(
|
||||
path.join(__dirname, "..", "frontend", "app", "components", "partials", "ContentSidebar.vue"),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
// The block that renders the item rows, from the items section down to its closing template. The
|
||||
// items section is followed by the maps section (`v-else`), so the first `</template>` that leads
|
||||
// there ends it; the inner `v-for` close is followed by another close, not by `v-else`.
|
||||
const itemSection =
|
||||
/<template v-else-if="activeSection === 'items'">([\s\S]*?)<\/template>\s*\n\s*<template v-else>/.exec(source)?.[1] ?? "";
|
||||
|
||||
// `selector` is inserted verbatim, so escape the `.` of a class combination. Comments are dropped:
|
||||
// they explain a rule, they are not part of it.
|
||||
function ruleFor(selector) {
|
||||
const rule = new RegExp(`\\.${selector}\\s*\\{([^}]*)\\}`).exec(source)?.[0];
|
||||
return rule?.replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
}
|
||||
|
||||
test("the item entry no longer shows the SYNCED text", () => {
|
||||
assert.ok(itemSection, "expected to find the items section of the sidebar");
|
||||
assert.doesNotMatch(itemSection, /campaigns\.synced/, "the item row must not render the synced text");
|
||||
assert.doesNotMatch(itemSection, /entity-entry-sync/, "the item row must not render the synced badge");
|
||||
});
|
||||
|
||||
test("the item entry shows the item's image on the left when it has one", () => {
|
||||
// the icon renders only for an item that carries an image, resolved through the helper...
|
||||
assert.match(
|
||||
itemSection,
|
||||
/<span v-if="row\.item\.image" class="entity-entry-image"[\s\S]*?<img :src="itemImageUrl\(row\.item\.image\)"/
|
||||
);
|
||||
// ...and on the left: it stands before the name in the row markup.
|
||||
assert.ok(
|
||||
itemSection.indexOf("entity-entry-image") < itemSection.indexOf("entity-entry-name"),
|
||||
"the item image must stand to the left of the name"
|
||||
);
|
||||
});
|
||||
|
||||
test("the item entry lays the icon out beside the name", () => {
|
||||
const title = ruleFor("entity-entry-title");
|
||||
assert.ok(title, "expected a .entity-entry-title style rule");
|
||||
assert.match(title, /display:\s*flex/, "the icon and the name sit side by side");
|
||||
|
||||
const image = ruleFor("entity-entry-image");
|
||||
assert.ok(image, "expected a .entity-entry-image style rule");
|
||||
assert.match(image, /overflow:\s*hidden/, "the icon is clipped to its box");
|
||||
});
|
||||
|
||||
test("an item image resolves like the item window: uploads from /public, full URLs as they are", () => {
|
||||
assert.match(source, /import Server, \{ getBaseUrl \} from ['"]~\/services\/Server['"]/);
|
||||
|
||||
const resolver = /function itemImageUrl\(image\)\s*\{[\s\S]*?\n\}/.exec(source)?.[0] ?? "";
|
||||
assert.ok(resolver, "expected an itemImageUrl helper");
|
||||
assert.match(resolver, /https\?:/, "a full http(s) URL loads as it is");
|
||||
assert.match(resolver, /data:/, "a data URI loads as it is");
|
||||
assert.match(resolver, /\$\{getBaseUrl\(\)\}\/public\//, "an uploaded filename resolves as a /public file");
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
// Tests for item folders following the Foundry world into the campaign
|
||||
// (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" },
|
||||
|
||||
@@ -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 \}\)/);
|
||||
|
||||
217
tests/manage-accounts.test.js
Normal file
217
tests/manage-accounts.test.js
Normal file
@@ -0,0 +1,217 @@
|
||||
// Tests for "Manage accounts" of Syndria98/dragonroll#51: the button on the settings window's site
|
||||
// administration tab opened a window type (`account_management`) that was never registered in
|
||||
// `WindowDefinitions.js`, so `getComponent` dereferenced `defWindows[type].component` on `undefined` —
|
||||
// `can't access property "component", (intermediate value)[type] is undefined` — instead of opening
|
||||
// anything. The window is the site administration screen now (list accounts, create one, grant or
|
||||
// take administrator rights, delete one), guarded on the backend by the `isAdmin` middleware.
|
||||
//
|
||||
// Like tests/settings-window.test.js, the window wiring is read from the sources; the window registry
|
||||
// is also checked against every window type the frontend opens, which is what catches this class of
|
||||
// bug before the click 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 frontendApp = path.join(__dirname, "..", "frontend", "app");
|
||||
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
|
||||
const settingsWindowSource = read("frontend", "app", "components", "windows", "SettingsWindow.vue");
|
||||
const accountsWindowSource = read("frontend", "app", "components", "windows", "AccountManagementWindow.vue");
|
||||
const userRouteSource = read("backend", "src", "routes", "user.js");
|
||||
|
||||
// -- the window registry -------------------------------------------------------
|
||||
|
||||
// Top-level entries of `defWindows`: every entry sits at 2 spaces, its contents at 4+.
|
||||
function registryEntries() {
|
||||
const header = /^ {2}([A-Za-z_]\w*):\s*\{/gm;
|
||||
const marks = [];
|
||||
let match;
|
||||
while ((match = header.exec(windowDefsSource))) marks.push({ type: match[1], index: match.index });
|
||||
assert.ok(marks.length > 0, "expected window definitions to register windows");
|
||||
|
||||
const entries = {};
|
||||
marks.forEach((mark, i) => {
|
||||
const end = i + 1 < marks.length ? marks[i + 1].index : windowDefsSource.length;
|
||||
entries[mark.type] = windowDefsSource.slice(mark.index, end);
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
function* sourceFiles(dir) {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) yield* sourceFiles(full);
|
||||
else if (/\.(vue|js|ts)$/.test(entry.name)) yield full;
|
||||
}
|
||||
}
|
||||
|
||||
test("account_management is a registered window with a component on disk", () => {
|
||||
const entries = registryEntries();
|
||||
const definition = entries["account_management"];
|
||||
assert.ok(definition, "account_management must be registered or getComponent opens undefined");
|
||||
assert.match(definition, /AccountManagementWindow\.vue/);
|
||||
const component = path.join(frontendApp, "components", "windows", "AccountManagementWindow.vue");
|
||||
assert.ok(fs.existsSync(component), "the window component file must exist");
|
||||
});
|
||||
|
||||
test("no window is opened with a type that is not registered", () => {
|
||||
const registered = registryEntries();
|
||||
// The type is the first string argument of CreateWindow; CreateChildWindow takes a parent
|
||||
// (GetFirstWindowId('main_menu')-style, a registered type itself) before the type. Data
|
||||
// objects after it hold strings that mean nothing to the registry, so they stay unmatched.
|
||||
const createWindow = /CreateWindow\(\s*['"]([a-z_]+)['"]/g;
|
||||
const createChildWindow = /CreateChildWindow\(\s*(?:GetFirstWindowId\(\s*['"]([a-z_]+)['"]\s*\)|[a-z_]+)\s*,\s*['"]([a-z_]+)['"]/g;
|
||||
|
||||
for (const file of sourceFiles(frontendApp)) {
|
||||
const source = fs.readFileSync(file, "utf8");
|
||||
const found = [...source.matchAll(createWindow), ...source.matchAll(createChildWindow)];
|
||||
for (const match of found) {
|
||||
for (const type of match.slice(1)) {
|
||||
if (!type) continue;
|
||||
assert.ok(
|
||||
registered[type],
|
||||
`${path.relative(frontendApp, file)} opens '${type}', which WindowDefinitions.js does not define`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("every registered window points at a component file that exists", () => {
|
||||
for (const [type, definition] of Object.entries(registryEntries())) {
|
||||
const imported = /import\(['"]([^'"]+)['"]\)/.exec(definition)?.[1];
|
||||
assert.ok(imported, `${type} must import a component`);
|
||||
const file = path.join(frontendApp, imported.replace(/^~\//, ""));
|
||||
assert.ok(fs.existsSync(file), `${type} points at ${imported}, which is not there`);
|
||||
}
|
||||
});
|
||||
|
||||
// -- opening it from the settings window ----------------------------------------
|
||||
|
||||
const openManageAccounts = /function OpenManageAccounts\(\)\s*\{[\s\S]*?\n\}/.exec(settingsWindowSource)?.[0];
|
||||
|
||||
test("the settings tab opens the account window and can come back", () => {
|
||||
assert.ok(openManageAccounts, "expected an OpenManageAccounts in the settings window");
|
||||
assert.match(openManageAccounts, /CreateWindow\(\s*'account_management'/);
|
||||
// ClearWindow takes a selector object; a bare string matched neither `selector.type` nor
|
||||
// `selector.id` and closed nothing, leaving both windows stacked.
|
||||
assert.match(openManageAccounts, /ClearWindow\(\s*\{\s*type:\s*'settings'\s*\}\s*\)/);
|
||||
assert.match(openManageAccounts, /ClearWindow\(\s*\{\s*type:\s*'account_management'\s*\}\s*\)/);
|
||||
assert.match(openManageAccounts, /CreateWindow\(\s*'settings'/, "back returns to the settings window");
|
||||
assert.doesNotMatch(settingsWindowSource, /ClearWindow\(\s*['"]/g, "no ClearWindow call may pass a bare string");
|
||||
});
|
||||
|
||||
// -- the account management window ------------------------------------------------
|
||||
|
||||
test("the account window talks to the account management endpoints", () => {
|
||||
assert.match(accountsWindowSource, /Server\(\)\.get\(['"]\/user\/list['"]/);
|
||||
assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/create['"]/);
|
||||
assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/set-admin['"]/);
|
||||
assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/delete['"]/);
|
||||
});
|
||||
|
||||
test("the window closes the switches on the row of the admin using it", () => {
|
||||
// The server answers the same way to anybody who still posts it (see below); the row just
|
||||
// does not invite the attempt.
|
||||
assert.match(accountsWindowSource, /v-if="!IsSelf\(user\)"/);
|
||||
assert.match(accountsWindowSource, /GetUser\(\)\?\._id/);
|
||||
});
|
||||
|
||||
// -- the backend routes -----------------------------------------------------------
|
||||
|
||||
function routeDeclaration(method, route) {
|
||||
const declaration = new RegExp(`router\\.${method}\\(['"]${route}['"][^\\n]*`).exec(userRouteSource)?.[0];
|
||||
assert.ok(declaration, `expected a ${method.toUpperCase()} ${route} route`);
|
||||
// /api/user is mounted before the JWT guard: without inline authentication the route would
|
||||
// be public to any request (landmine 5 of AGENTS.md), and only an admin may manage accounts.
|
||||
assert.match(declaration, /passport\.authenticate\(['"]jwt['"]/);
|
||||
assert.match(declaration, /isAdmin/, `${route} may only be answered for an administrator`);
|
||||
return declaration;
|
||||
}
|
||||
|
||||
function routeBlock(method, route) {
|
||||
const start = userRouteSource.indexOf(`router.${method}('${route}'`);
|
||||
assert.ok(start !== -1, `expected a ${method.toUpperCase()} ${route} route`);
|
||||
const next = userRouteSource.indexOf(`\nrouter.`, start + 1);
|
||||
return userRouteSource.slice(start, next === -1 ? userRouteSource.length : next);
|
||||
}
|
||||
|
||||
test("GET /user/list answers the accounts without passwords or setup codes", () => {
|
||||
routeDeclaration("get", "/list");
|
||||
assert.match(routeBlock("get", "/list"), /select\(['"]-password -setupCode['"]\)/);
|
||||
});
|
||||
|
||||
test("POST /user/create stores a hashed password and refuses duplicates", () => {
|
||||
const block = routeBlock("post", "/create");
|
||||
assert.match(block, /bcrypt\.hash\(password/, "the password must not go in as it came");
|
||||
assert.match(block, /register\.errors\.email-username-exists/, "duplicates answer with the register message");
|
||||
assert.doesNotMatch(block, /setupCode/, "no half-finished setup account is invented here");
|
||||
});
|
||||
|
||||
for (const route of ["/set-admin", "/delete"]) {
|
||||
test(`POST /user${route} refuses to act on the admin that is asking`, () => {
|
||||
routeDeclaration("post", route);
|
||||
const block = routeBlock("post", route);
|
||||
assert.match(block, /String\(req\.user\._id\) === String\(id\)/, "an admin keeps their own account closed");
|
||||
assert.match(block, /errors\.internal/);
|
||||
});
|
||||
}
|
||||
|
||||
// -- i18n --------------------------------------------------------------------------
|
||||
|
||||
test("every locale titles the account window and names its strings", () => {
|
||||
const required = [
|
||||
"accounts.you",
|
||||
"accounts.admin",
|
||||
"accounts.make-admin",
|
||||
"accounts.remove-admin",
|
||||
"accounts.delete",
|
||||
"accounts.new-account",
|
||||
"accounts.name",
|
||||
"accounts.username",
|
||||
"accounts.email",
|
||||
"accounts.password",
|
||||
"accounts.create",
|
||||
"accounts.created",
|
||||
"accounts.updated",
|
||||
"accounts.deleted",
|
||||
"accounts.errors.self-admin",
|
||||
"accounts.errors.self-delete",
|
||||
];
|
||||
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json"));
|
||||
assert.ok(windows["account-management"]?.trim(), `${locale} is missing the account window title`);
|
||||
|
||||
const settings = JSON.parse(read("frontend", "i18n", "locales", locale, "settings.json"));
|
||||
assert.ok(settings["site-administration"]?.["manage-accounts"]?.trim(), `${locale} is missing manage accounts`);
|
||||
for (const key of required) {
|
||||
const value = key.split(".").reduce((node, part) => node?.[part], settings["site-administration"]);
|
||||
assert.ok(value?.trim(), `${locale} is missing settings.site-administration.${key}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("every accounts string the window translates exists in every locale", () => {
|
||||
// $t keys with nothing to translate fall back to the key itself, so every accounts key the
|
||||
// window uses has to be carried by every locale. (`errors.internal` is the envelope fallback
|
||||
// every window toasts the same way and stays out of it.)
|
||||
const used = [...new Set(
|
||||
[...accountsWindowSource.matchAll(/\$t\(\s*['"](settings\.site-administration\.accounts\.[\w.-]+)['"]/g)]
|
||||
.map((key) => key[1])
|
||||
)];
|
||||
assert.ok(used.length >= 14, `expected the window's translated strings, found ${used.length}`);
|
||||
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const settings = JSON.parse(read("frontend", "i18n", "locales", locale, "settings.json"));
|
||||
for (const key of used) {
|
||||
const value = key.split(".").slice(1).reduce((node, part) => node?.[part], settings);
|
||||
assert.ok(typeof value === "string" && value.trim(), `${locale} is missing ${key}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user